diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 82c89bb5..00000000 --- a/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -Backup/ -bin/ -obj/ -shadowsocks-csharp/shadowsocks-csharp.csproj.user -TestResults -*.suo - diff --git a/CHANGES b/CHANGES deleted file mode 100644 index 6e8b7840..00000000 --- a/CHANGES +++ /dev/null @@ -1,89 +0,0 @@ -2.3 2015-01-25 -- Use the same port for every profile -- Use the same port for HTTP/Socks5/PAC -- Fix GFWList PAC compatibility issue with IE11 -- Encourage users to report to GFWList when no update found -- Minor UI improvements - -2.2.1 2015-01-18 -- Fix QR Code compatibility - -2.2 2015-01-14 -- Support updating PAC from GFWList -- Support adding server by scanning QR Code -- Output timestamp in logs -- Minor fixes - -2.1.6 2015-01-02 -- Fix OPTIONS requests -- Improve logs - -2.1.5 2014-12-25 -- Fix QR Code compatibility with iOS -- Only left button will trigger double click on tray icon - -2.1.4 2014-12-20 -- Fix crash when remarks are too long - -2.1.3 2014-12-20 -- Add Chinese Language -- Fix some UI issues on Windows 8 -- Fix some UI issues on high DPI screens -- Log bind error more friendly -- Stability issues - -2.1.2 2014-12-14 -- Fix sometimes Shadowsocks doesn't respond to requests - -2.1.1 2014-12-14 -- Add global proxy option - -2.1 2014-12-12 -- Add salsa20 and chacha20 support - -2.0.11 2014-11-23 -- Fix a crash -- Only switch the system proxy off if we have switched it on - -2.0.10 2014-11-18 -- Minor fixes -- Optimize code - -2.0.9 2014-11-13 -- Fix startup path -- Fix allowed port range for polipo - -2.0.8 2014-11-12 -- Fix data corruption -- Set proxy for PPPoE -- Auto Startup Option -- Support high DPI screens - -2.0.7 2014-11-11 -- Use OpenSSL for now - -2.0.6 2014-11-10 -- Minor bug fixes - -2.0.5 2014-11-09 -- Fix QRCode size -- Share over LAN option -- Log to temp path instead - -2.0.4 2014-11-09 -- Try to fix data corruption -- Remove all configuration except x86 - -2.0.3 2014-11-08 -- Support QRCode generation -- Fix compatibility issues with some Chrome version - -2.0.2 2014-11-08 -- Add remarks -- Fix error when polipo is killed - -2.0.1 2014-11-08 -- Check already running - -2.0 2014-11-08 -- Initial release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index c88855b2..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,28 +0,0 @@ -How to Contribute -================= - -Pull Requests -------------- - -1. Pull requests are welcome. If you would like to add a large feature -or make a significant change, make sure to open an issue to discuss with -people first. -2. Make sure to pass the unit tests. Write unit tests for new modules if -needed. - -Issues ------- - -1. Only bugs and feature requests are accepted here. -2. We'll only work on important features. If the feature you're asking only -benefits a few people, you'd better implement the feature yourself and send us -a pull request, or ask some of your friends to do so. -3. We don't answer questions of any other types here. Since very few people -are watching the issue tracker here, you'll probably get no help from here. -Read [Troubleshooting] and get help from forums or [mailing lists]. -4. Issues in languages other than English will be Google translated into English -later. - - -[Troubleshooting]: https://github.com/clowwindy/shadowsocks/wiki/Troubleshooting -[mailing lists]: https://groups.google.com/forum/#!forum/shadowsocks diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index c09e49f7..00000000 --- a/LICENSE.txt +++ /dev/null @@ -1,118 +0,0 @@ -shadowsocks-csharp -================== - -Copyright (C) 2015 clowwindy - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . - - -3rd party projects -================== - -polipo ------------------- - -https://github.com/jech/polipo - -Copyright (c) 2003-2008 by Juliusz Chroboczek - -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 substantial 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. - - -PolarSSL --------- - -https://polarssl.org/ - -License: https://raw.githubusercontent.com/polarssl/polarssl/development/LICENSE - - -SimpleJson ----------- - -https://github.com/facebook-csharp-sdk/simple-json - -Copyright (c) 2011, The Outercurve Foundation - -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 substantial 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. - - -ZXing ------ - -Copyright 2007 ZXing authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - - -libsodium ---------- - -Copyright (c) 2013-2015 -Frank Denis - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 9edd2298..00000000 --- a/README.md +++ /dev/null @@ -1,45 +0,0 @@ -Shadowsocks for Windows -======================= - -[![Build Status]][Appveyor] - -#### Features - -1. System proxy configuration -2. Fast profile switching -3. PAC mode and global mode -4. Compatible with IE -5. Only a single exe file of 200KB size - -#### Download - -Download [latest release]. - -For <= Windows 7, download Shadowsocks-win-x.x.x.zip. - -For >= Windows 8, download Shadowsocks-win-dotnet4.0-x.x.x.zip, unless you have .Net 2.0 installed. - -#### Usage - -1. Find Shadowsocks icon in notification tray -2. You can add multiple servers in servers menu -3. Select Enable System Proxy menu to enable system proxy. Please disable other -proxy addons in your browser, or set them to use system proxy -4. You can also configure your browser proxy manually if you don't want to enable -system proxy. Set Socks5 or HTTP proxy to 127.0.0.1:1080. You can change this -port in Server -> Edit Servers -5. You can change PAC rules by editing the PAC file. When you save the PAC file -with any editor, Shadowsocks will notify browsers about the change automatically - -### Develop - -Visual Studio Express 2012 is recommended. - -#### License - -GPLv3 - - -[Appveyor]: https://ci.appveyor.com/project/clowwindy/shadowsocks-csharp -[Build Status]: https://ci.appveyor.com/api/projects/status/gknc8l1lxy423ehv/branch/master -[latest release]: https://sourceforge.net/projects/shadowsocksgui/files/dist/ diff --git a/packaging/upload.sh b/packaging/upload.sh deleted file mode 100755 index 82f48b06..00000000 --- a/packaging/upload.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -version=$1 - -rsync --progress -e ssh shadowsocks-csharp/bin/x86/Release/Shadowsocks-win-dotnet4.0-$1.zip frs.sourceforge.net:/home/frs/project/shadowsocksgui/dist/ -rsync --progress -e ssh shadowsocks-csharp/bin/x86/Release/Shadowsocks-win-$1.zip frs.sourceforge.net:/home/frs/project/shadowsocksgui/dist/ diff --git a/shadowsocks-csharp.sln b/shadowsocks-csharp.sln deleted file mode 100755 index 83869ae2..00000000 --- a/shadowsocks-csharp.sln +++ /dev/null @@ -1,30 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Express 2012 for Windows Desktop -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "shadowsocks-csharp", "shadowsocks-csharp\shadowsocks-csharp.csproj", "{8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{45913187-0685-4903-B250-DCEF0479CD86}" - ProjectSection(ProjectDependencies) = postProject - {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062} = {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x86 = Debug|x86 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Debug|x86.ActiveCfg = Debug|x86 - {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Debug|x86.Build.0 = Debug|x86 - {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Debug|x86.Deploy.0 = Debug|x86 - {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Release|x86.ActiveCfg = Release|x86 - {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062}.Release|x86.Build.0 = Release|x86 - {45913187-0685-4903-B250-DCEF0479CD86}.Debug|x86.ActiveCfg = Debug|x86 - {45913187-0685-4903-B250-DCEF0479CD86}.Debug|x86.Build.0 = Debug|x86 - {45913187-0685-4903-B250-DCEF0479CD86}.Release|x86.ActiveCfg = Release|x86 - {45913187-0685-4903-B250-DCEF0479CD86}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/shadowsocks-csharp/3rd/SimpleJson.cs b/shadowsocks-csharp/3rd/SimpleJson.cs deleted file mode 100644 index 6581e84b..00000000 --- a/shadowsocks-csharp/3rd/SimpleJson.cs +++ /dev/null @@ -1,1883 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (c) 2011, The Outercurve Foundation. -// -// Licensed under the MIT License (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.opensource.org/licenses/mit-license.php -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me) -// https://github.com/facebook-csharp-sdk/simple-json -//----------------------------------------------------------------------- - -// VERSION: - -// NOTE: uncomment the following line to make SimpleJson class internal. -//#define SIMPLE_JSON_INTERNAL - -// NOTE: uncomment the following line to make JsonArray and JsonObject class internal. -//#define SIMPLE_JSON_OBJARRAYINTERNAL - -// NOTE: uncomment the following line to enable dynamic support. -//#define SIMPLE_JSON_DYNAMIC - -// NOTE: uncomment the following line to enable DataContract support. -//#define SIMPLE_JSON_DATACONTRACT - -// NOTE: uncomment the following line to use Reflection.Emit (better performance) instead of method.invoke(). -// don't enable ReflectionEmit for WinRT, Silverlight and WP7. -//#define SIMPLE_JSON_REFLECTIONEMIT - -// NOTE: uncomment the following line if you are compiling under Window Metro style application/library. -// usually already defined in properties -//#define NETFX_CORE; - -// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html - -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -#if SIMPLE_JSON_DYNAMIC -using System.Dynamic; -#endif -using System.Globalization; -using System.Reflection; -#if SIMPLE_JSON_REFLECTIONEMIT -using System.Reflection.Emit; -#endif -#if SIMPLE_JSON_DATACONTRACT -using System.Runtime.Serialization; -#endif -using System.Text; -using SimpleJson.Reflection; - -namespace SimpleJson -{ - #region JsonArray - - /// - /// Represents the json array. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] -#if SIMPLE_JSON_OBJARRAYINTERNAL - internal -#else - public -#endif - class JsonArray : List - { - /// - /// Initializes a new instance of the class. - /// - public JsonArray() { } - - /// - /// Initializes a new instance of the class. - /// - /// The capacity of the json array. - public JsonArray(int capacity) : base(capacity) { } - - /// - /// The json representation of the array. - /// - /// The json representation of the array. - public override string ToString() - { - return SimpleJson.SerializeObject(this) ?? string.Empty; - } - } - - #endregion - - #region JsonObject - - /// - /// Represents the json object. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] -#if SIMPLE_JSON_OBJARRAYINTERNAL - internal -#else - public -#endif - class JsonObject : -#if SIMPLE_JSON_DYNAMIC - DynamicObject, -#endif - IDictionary - { - /// - /// The internal member dictionary. - /// - private readonly Dictionary _members = new Dictionary(); - - /// - /// Gets the at the specified index. - /// - /// - public object this[int index] - { - get { return GetAtIndex(_members, index); } - } - - internal static object GetAtIndex(IDictionary obj, int index) - { - if (obj == null) - throw new ArgumentNullException("obj"); - - if (index >= obj.Count) - throw new ArgumentOutOfRangeException("index"); - - int i = 0; - foreach (KeyValuePair o in obj) - if (i++ == index) return o.Value; - - return null; - } - - /// - /// Adds the specified key. - /// - /// The key. - /// The value. - public void Add(string key, object value) - { - _members.Add(key, value); - } - - /// - /// Determines whether the specified key contains key. - /// - /// The key. - /// - /// true if the specified key contains key; otherwise, false. - /// - public bool ContainsKey(string key) - { - return _members.ContainsKey(key); - } - - /// - /// Gets the keys. - /// - /// The keys. - public ICollection Keys - { - get { return _members.Keys; } - } - - /// - /// Removes the specified key. - /// - /// The key. - /// - public bool Remove(string key) - { - return _members.Remove(key); - } - - /// - /// Tries the get value. - /// - /// The key. - /// The value. - /// - public bool TryGetValue(string key, out object value) - { - return _members.TryGetValue(key, out value); - } - - /// - /// Gets the values. - /// - /// The values. - public ICollection Values - { - get { return _members.Values; } - } - - /// - /// Gets or sets the with the specified key. - /// - /// - public object this[string key] - { - get { return _members[key]; } - set { _members[key] = value; } - } - - /// - /// Adds the specified item. - /// - /// The item. - public void Add(KeyValuePair item) - { - _members.Add(item.Key, item.Value); - } - - /// - /// Clears this instance. - /// - public void Clear() - { - _members.Clear(); - } - - /// - /// Determines whether [contains] [the specified item]. - /// - /// The item. - /// - /// true if [contains] [the specified item]; otherwise, false. - /// - public bool Contains(KeyValuePair item) - { - return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value; - } - - /// - /// Copies to. - /// - /// The array. - /// Index of the array. - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - int num = Count; - foreach (KeyValuePair kvp in this) - { - array[arrayIndex++] = kvp; - - if (--num <= 0) - return; - } - } - - /// - /// Gets the count. - /// - /// The count. - public int Count - { - get { return _members.Count; } - } - - /// - /// Gets a value indicating whether this instance is read only. - /// - /// - /// true if this instance is read only; otherwise, false. - /// - public bool IsReadOnly - { - get { return false; } - } - - /// - /// Removes the specified item. - /// - /// The item. - /// - public bool Remove(KeyValuePair item) - { - return _members.Remove(item.Key); - } - - /// - /// Gets the enumerator. - /// - /// - public IEnumerator> GetEnumerator() - { - return _members.GetEnumerator(); - } - - /// - /// Returns an enumerator that iterates through a collection. - /// - /// - /// An object that can be used to iterate through the collection. - /// - IEnumerator IEnumerable.GetEnumerator() - { - return _members.GetEnumerator(); - } - - /// - /// Returns a json that represents the current . - /// - /// - /// A json that represents the current . - /// - public override string ToString() - { - return SimpleJson.SerializeObject(this); - } - -#if SIMPLE_JSON_DYNAMIC - /// - /// Provides implementation for type conversion operations. Classes derived from the class can override this method to specify dynamic behavior for operations that convert an object from one type to another. - /// - /// Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the class, binder.Type returns the type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion. - /// The result of the type conversion operation. - /// - /// Alwasy returns true. - /// - public override bool TryConvert(ConvertBinder binder, out object result) - { - // - if (binder == (ConvertBinder)null) - throw new ArgumentNullException("binder"); - // - Type targetType = binder.Type; - - if ((targetType == typeof(IEnumerable)) || - (targetType == typeof(IEnumerable>)) || - (targetType == typeof(IDictionary)) || -#if NETFX_CORE - (targetType == typeof(IDictionary<,>)) -#else - (targetType == typeof(IDictionary)) -#endif -) - { - result = this; - return true; - } - - return base.TryConvert(binder, out result); - } - - /// - /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic. - /// - /// Provides information about the deletion. - /// - /// Alwasy returns true. - /// - public override bool TryDeleteMember(DeleteMemberBinder binder) - { - // - if (binder == (DeleteMemberBinder)null) - throw new ArgumentNullException("binder"); - // - return _members.Remove(binder.Name); - } - - /// - /// Provides the implementation for operations that get a value by index. Classes derived from the class can override this method to specify dynamic behavior for indexing operations. - /// - /// Provides information about the operation. - /// The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, is equal to 3. - /// The result of the index operation. - /// - /// Alwasy returns true. - /// - public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) - { - if (indexes.Length == 1) - { - result = ((IDictionary)this)[(string)indexes[0]]; - return true; - } - result = (object)null; - return true; - } - - /// - /// Provides the implementation for operations that get member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as getting a value for a property. - /// - /// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. - /// The result of the get operation. For example, if the method is called for a property, you can assign the property value to . - /// - /// Alwasy returns true. - /// - public override bool TryGetMember(GetMemberBinder binder, out object result) - { - object value; - if (_members.TryGetValue(binder.Name, out value)) - { - result = value; - return true; - } - result = (object)null; - return true; - } - - /// - /// Provides the implementation for operations that set a value by index. Classes derived from the class can override this method to specify dynamic behavior for operations that access objects by a specified index. - /// - /// Provides information about the operation. - /// The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the class, is equal to 3. - /// The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the class, is equal to 10. - /// - /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown. - /// - public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) - { - if (indexes.Length == 1) - { - ((IDictionary)this)[(string)indexes[0]] = value; - return true; - } - - return base.TrySetIndex(binder, indexes, value); - } - - /// - /// Provides the implementation for operations that set member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as setting a value for a property. - /// - /// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. - /// The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the class, the is "Test". - /// - /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) - /// - public override bool TrySetMember(SetMemberBinder binder, object value) - { - // - if (binder == (SetMemberBinder)null) - throw new ArgumentNullException("binder"); - // - _members[binder.Name] = value; - return true; - } - - /// - /// Returns the enumeration of all dynamic member names. - /// - /// - /// A sequence that contains dynamic member names. - /// - public override IEnumerable GetDynamicMemberNames() - { - foreach (var key in Keys) - yield return key; - } -#endif - } - - #endregion -} - -namespace SimpleJson -{ - #region JsonParser - - /// - /// This class encodes and decodes JSON strings. - /// Spec. details, see http://www.json.org/ - /// - /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList<object>) and JsonObject(IDictionary<string,object>). - /// All numbers are parsed to doubles. - /// -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - class SimpleJson - { - private const int TOKEN_NONE = 0; - private const int TOKEN_CURLY_OPEN = 1; - private const int TOKEN_CURLY_CLOSE = 2; - private const int TOKEN_SQUARED_OPEN = 3; - private const int TOKEN_SQUARED_CLOSE = 4; - private const int TOKEN_COLON = 5; - private const int TOKEN_COMMA = 6; - private const int TOKEN_STRING = 7; - private const int TOKEN_NUMBER = 8; - private const int TOKEN_TRUE = 9; - private const int TOKEN_FALSE = 10; - private const int TOKEN_NULL = 11; - - private const int BUILDER_CAPACITY = 2000; - - /// - /// Parses the string json into a value - /// - /// A JSON string. - /// An IList<object>, a IDictionary<string,object>, a double, a string, null, true, or false - public static object DeserializeObject(string json) - { - object @object; - if (TryDeserializeObject(json, out @object)) - return @object; - throw new System.Runtime.Serialization.SerializationException("Invalid JSON string"); - } - - /// - /// Try parsing the json string into a value. - /// - /// - /// A JSON string. - /// - /// - /// The object. - /// - /// - /// Returns true if successfull otherwise false. - /// - public static bool TryDeserializeObject(string json, out object @object) - { - bool success = true; - if (json != null) - { - char[] charArray = json.ToCharArray(); - int index = 0; - @object = ParseValue(charArray, ref index, ref success); - } - else - @object = null; - - return success; - } - - public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy) - { - object jsonObject = DeserializeObject(json); - - return type == null || jsonObject != null && -#if NETFX_CORE - jsonObject.GetType().GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) -#else - jsonObject.GetType().IsAssignableFrom(type) -#endif - ? jsonObject - : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type); - } - - public static object DeserializeObject(string json, Type type) - { - return DeserializeObject(json, type, null); - } - - public static T DeserializeObject(string json, IJsonSerializerStrategy jsonSerializerStrategy) - { - return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy); - } - - public static T DeserializeObject(string json) - { - return (T)DeserializeObject(json, typeof(T), null); - } - - /// - /// Converts a IDictionary<string,object> / IList<object> object into a JSON string - /// - /// A IDictionary<string,object> / IList<object> - /// Serializer strategy to use - /// A JSON encoded string, or null if object 'json' is not serializable - public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy) - { - StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); - bool success = SerializeValue(jsonSerializerStrategy, json, builder); - return (success ? builder.ToString() : null); - } - - public static string SerializeObject(object json) - { - return SerializeObject(json, CurrentJsonSerializerStrategy); - } - - protected static IDictionary ParseObject(char[] json, ref int index, ref bool success) - { - IDictionary table = new JsonObject(); - int token; - - // { - NextToken(json, ref index); - - bool done = false; - while (!done) - { - token = LookAhead(json, index); - if (token == TOKEN_NONE) - { - success = false; - return null; - } - else if (token == TOKEN_COMMA) - NextToken(json, ref index); - else if (token == TOKEN_CURLY_CLOSE) - { - NextToken(json, ref index); - return table; - } - else - { - // name - string name = ParseString(json, ref index, ref success); - if (!success) - { - success = false; - return null; - } - - // : - token = NextToken(json, ref index); - if (token != TOKEN_COLON) - { - success = false; - return null; - } - - // value - object value = ParseValue(json, ref index, ref success); - if (!success) - { - success = false; - return null; - } - - table[name] = value; - } - } - - return table; - } - - protected static JsonArray ParseArray(char[] json, ref int index, ref bool success) - { - JsonArray array = new JsonArray(); - - // [ - NextToken(json, ref index); - - bool done = false; - while (!done) - { - int token = LookAhead(json, index); - if (token == TOKEN_NONE) - { - success = false; - return null; - } - else if (token == TOKEN_COMMA) - NextToken(json, ref index); - else if (token == TOKEN_SQUARED_CLOSE) - { - NextToken(json, ref index); - break; - } - else - { - object value = ParseValue(json, ref index, ref success); - if (!success) - return null; - array.Add(value); - } - } - - return array; - } - - protected static object ParseValue(char[] json, ref int index, ref bool success) - { - switch (LookAhead(json, index)) - { - case TOKEN_STRING: - return ParseString(json, ref index, ref success); - case TOKEN_NUMBER: - return ParseNumber(json, ref index, ref success); - case TOKEN_CURLY_OPEN: - return ParseObject(json, ref index, ref success); - case TOKEN_SQUARED_OPEN: - return ParseArray(json, ref index, ref success); - case TOKEN_TRUE: - NextToken(json, ref index); - return true; - case TOKEN_FALSE: - NextToken(json, ref index); - return false; - case TOKEN_NULL: - NextToken(json, ref index); - return null; - case TOKEN_NONE: - break; - } - - success = false; - return null; - } - - protected static string ParseString(char[] json, ref int index, ref bool success) - { - StringBuilder s = new StringBuilder(BUILDER_CAPACITY); - char c; - - EatWhitespace(json, ref index); - - // " - c = json[index++]; - - bool complete = false; - while (!complete) - { - if (index == json.Length) - { - break; - } - - c = json[index++]; - if (c == '"') - { - complete = true; - break; - } - else if (c == '\\') - { - if (index == json.Length) - break; - c = json[index++]; - if (c == '"') - s.Append('"'); - else if (c == '\\') - s.Append('\\'); - else if (c == '/') - s.Append('/'); - else if (c == 'b') - s.Append('\b'); - else if (c == 'f') - s.Append('\f'); - else if (c == 'n') - s.Append('\n'); - else if (c == 'r') - s.Append('\r'); - else if (c == 't') - s.Append('\t'); - else if (c == 'u') - { - int remainingLength = json.Length - index; - if (remainingLength >= 4) - { - // parse the 32 bit hex into an integer codepoint - uint codePoint; - if ( - !(success = - UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, - CultureInfo.InvariantCulture, out codePoint))) - return ""; - - // convert the integer codepoint to a unicode char and add to string - - if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate - { - index += 4; // skip 4 chars - remainingLength = json.Length - index; - if (remainingLength >= 6) - { - uint lowCodePoint; - if (new string(json, index, 2) == "\\u" && - UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, - CultureInfo.InvariantCulture, out lowCodePoint)) - { - if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate - { - s.Append((char)codePoint); - s.Append((char)lowCodePoint); - index += 6; // skip 6 chars - continue; - } - } - } - success = false; // invalid surrogate pair - return ""; - } -#if SILVERLIGHT - s.Append(ConvertFromUtf32((int)codePoint)); -#else - s.Append(Char.ConvertFromUtf32((int)codePoint)); -#endif - // skip 4 chars - index += 4; - } - else - break; - } - } - else - s.Append(c); - } - - if (!complete) - { - success = false; - return null; - } - - return s.ToString(); - } - -#if SILVERLIGHT - private static string ConvertFromUtf32(int utf32) - { - // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm - if (utf32 < 0 || utf32 > 0x10FFFF) - throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF."); - if (0xD800 <= utf32 && utf32 <= 0xDFFF) - throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range."); - if (utf32 < 0x10000) - return new string((char)utf32, 1); - utf32 -= 0x10000; - return new string(new char[] {(char) ((utf32 >> 10) + 0xD800),(char) (utf32 % 0x0400 + 0xDC00)}); - } -#endif - - protected static object ParseNumber(char[] json, ref int index, ref bool success) - { - EatWhitespace(json, ref index); - - int lastIndex = GetLastIndexOfNumber(json, index); - int charLength = (lastIndex - index) + 1; - - object returnNumber; - string str = new string(json, index, charLength); - if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) - { - double number; - success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); - returnNumber = number; - } - else - { - long number; - success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); - returnNumber = number; - } - - index = lastIndex + 1; - return returnNumber; - } - - protected static int GetLastIndexOfNumber(char[] json, int index) - { - int lastIndex; - - for (lastIndex = index; lastIndex < json.Length; lastIndex++) - if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break; - return lastIndex - 1; - } - - protected static void EatWhitespace(char[] json, ref int index) - { - for (; index < json.Length; index++) - if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break; - } - - protected static int LookAhead(char[] json, int index) - { - int saveIndex = index; - return NextToken(json, ref saveIndex); - } - - [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - protected static int NextToken(char[] json, ref int index) - { - EatWhitespace(json, ref index); - - if (index == json.Length) - return TOKEN_NONE; - - char c = json[index]; - index++; - switch (c) - { - case '{': - return TOKEN_CURLY_OPEN; - case '}': - return TOKEN_CURLY_CLOSE; - case '[': - return TOKEN_SQUARED_OPEN; - case ']': - return TOKEN_SQUARED_CLOSE; - case ',': - return TOKEN_COMMA; - case '"': - return TOKEN_STRING; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - return TOKEN_NUMBER; - case ':': - return TOKEN_COLON; - } - index--; - - int remainingLength = json.Length - index; - - // false - if (remainingLength >= 5) - { - if (json[index] == 'f' && - json[index + 1] == 'a' && - json[index + 2] == 'l' && - json[index + 3] == 's' && - json[index + 4] == 'e') - { - index += 5; - return TOKEN_FALSE; - } - } - - // true - if (remainingLength >= 4) - { - if (json[index] == 't' && - json[index + 1] == 'r' && - json[index + 2] == 'u' && - json[index + 3] == 'e') - { - index += 4; - return TOKEN_TRUE; - } - } - - // null - if (remainingLength >= 4) - { - if (json[index] == 'n' && - json[index + 1] == 'u' && - json[index + 2] == 'l' && - json[index + 3] == 'l') - { - index += 4; - return TOKEN_NULL; - } - } - - return TOKEN_NONE; - } - - protected static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder) - { - bool success = true; - - if (value is string) - success = SerializeString((string)value, builder); - else if (value is IDictionary) - { - IDictionary dict = (IDictionary)value; - success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); - } - else if (value is IDictionary) - { - IDictionary dict = (IDictionary)value; - success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); - } - else if (value is IEnumerable) - success = SerializeArray(jsonSerializerStrategy, (IEnumerable)value, builder); - else if (IsNumeric(value)) - success = SerializeNumber(value, builder); - else if (value is Boolean) - builder.Append((bool)value ? "true" : "false"); - else if (value == null) - builder.Append("null"); - else - { - object serializedObject; - success = jsonSerializerStrategy.SerializeNonPrimitiveObject(value, out serializedObject); - if (success) - SerializeValue(jsonSerializerStrategy, serializedObject, builder); - } - - return success; - } - - protected static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder) - { - builder.Append("{\r\n"); - - IEnumerator ke = keys.GetEnumerator(); - IEnumerator ve = values.GetEnumerator(); - - bool first = true; - while (ke.MoveNext() && ve.MoveNext()) - { - object key = ke.Current; - object value = ve.Current; - - if (!first) - builder.Append(",\r\n"); - - if (key is string) - SerializeString((string)key, builder); - else - if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; - - builder.Append(" : "); - if (!SerializeValue(jsonSerializerStrategy, value, builder)) - return false; - - first = false; - } - - builder.Append("}\r\n"); - return true; - } - - protected static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder) - { - builder.Append("[\r\n "); - - bool first = true; - foreach (object value in anArray) - { - if (!first) - builder.Append(",\r\n "); - - if (!SerializeValue(jsonSerializerStrategy, value, builder)) - return false; - - first = false; - } - - builder.Append("\r\n]"); - return true; - } - - protected static bool SerializeString(string aString, StringBuilder builder) - { - builder.Append("\""); - - char[] charArray = aString.ToCharArray(); - for (int i = 0; i < charArray.Length; i++) - { - char c = charArray[i]; - if (c == '"') - builder.Append("\\\""); - else if (c == '\\') - builder.Append("\\\\"); - else if (c == '\b') - builder.Append("\\b"); - else if (c == '\f') - builder.Append("\\f"); - else if (c == '\n') - builder.Append("\\n"); - else if (c == '\r') - builder.Append("\\r"); - else if (c == '\t') - builder.Append("\\t"); - else - builder.Append(c); - } - - builder.Append("\""); - return true; - } - - protected static bool SerializeNumber(object number, StringBuilder builder) - { - if (number is long) - { - builder.Append(((long)number).ToString(CultureInfo.InvariantCulture)); - } - else if (number is ulong) - { - builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture)); - } - else if (number is int) - { - builder.Append(((int)number).ToString(CultureInfo.InvariantCulture)); - } - else if (number is uint) - { - builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture)); - } - else if (number is decimal) - { - builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture)); - } - else if (number is float) - { - builder.Append(((float)number).ToString(CultureInfo.InvariantCulture)); - } - else - { - builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture)); - } - - return true; - } - - /// - /// Determines if a given object is numeric in any way - /// (can be integer, double, null, etc). - /// - protected static bool IsNumeric(object value) - { - if (value is sbyte) return true; - if (value is byte) return true; - if (value is short) return true; - if (value is ushort) return true; - if (value is int) return true; - if (value is uint) return true; - if (value is long) return true; - if (value is ulong) return true; - if (value is float) return true; - if (value is double) return true; - if (value is decimal) return true; - return false; - } - - private static IJsonSerializerStrategy currentJsonSerializerStrategy; - public static IJsonSerializerStrategy CurrentJsonSerializerStrategy - { - get - { - // todo: implement locking mechanism. - return currentJsonSerializerStrategy ?? - (currentJsonSerializerStrategy = -#if SIMPLE_JSON_DATACONTRACT - DataContractJsonSerializerStrategy -#else - PocoJsonSerializerStrategy -#endif -); - } - - set - { - currentJsonSerializerStrategy = value; - } - } - - private static PocoJsonSerializerStrategy pocoJsonSerializerStrategy; - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] - public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy - { - get - { - // todo: implement locking mechanism. - return pocoJsonSerializerStrategy ?? (pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy()); - } - } - -#if SIMPLE_JSON_DATACONTRACT - - private static DataContractJsonSerializerStrategy dataContractJsonSerializerStrategy; - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] - public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy - { - get - { - // todo: implement locking mechanism. - return dataContractJsonSerializerStrategy ?? (dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy()); - } - } - -#endif - } - - #endregion - - #region Simple Json Serializer Strategies - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - interface IJsonSerializerStrategy - { - bool SerializeNonPrimitiveObject(object input, out object output); - - object DeserializeObject(object value, Type type); - } - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - class PocoJsonSerializerStrategy : IJsonSerializerStrategy - { - internal CacheResolver CacheResolver; - - private static readonly string[] Iso8601Format = new string[] - { - @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z", - @"yyyy-MM-dd\THH:mm:ss\Z", - @"yyyy-MM-dd\THH:mm:ssK" - }; - - public PocoJsonSerializerStrategy() - { - CacheResolver = new CacheResolver(BuildMap); - } - - protected virtual void BuildMap(Type type, SafeDictionary memberMaps) - { -#if NETFX_CORE - foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) { - var getMethod = info.GetMethod; - if(getMethod==null || !getMethod.IsPublic || getMethod.IsStatic) continue; -#else - foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) - { -#endif - memberMaps.Add(info.Name, new CacheResolver.MemberMap(info)); - } -#if NETFX_CORE - foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) { - if(!info.IsPublic || info.IsStatic) continue; -#else - foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) - { -#endif - memberMaps.Add(info.Name, new CacheResolver.MemberMap(info)); - } - } - - public virtual bool SerializeNonPrimitiveObject(object input, out object output) - { - return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output); - } - - [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - public virtual object DeserializeObject(object value, Type type) - { - object obj = null; - if (value is string) - { - string str = value as string; - - if (!string.IsNullOrEmpty(str)) - { - if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime))) - obj = DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); - else if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))) - obj = new Guid(str); - else - obj = str; - } - else - { - if (type == typeof(Guid)) - obj= default(Guid); - else if(ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)) - obj = null; - else - obj = str; - } - } - else if (value is bool) - obj = value; - else if (value == null) - obj = null; - else if ((value is long && type == typeof(long)) || (value is double && type == typeof(double))) - obj = value; - else if ((value is double && type != typeof(double)) || (value is long && type != typeof(long))) - { - obj = -#if NETFX_CORE - type == typeof(int) || type == typeof(long) || type == typeof(double) ||type == typeof(float) || type == typeof(bool) || type == typeof(decimal) ||type == typeof(byte) || type == typeof(short) -#else - typeof(IConvertible).IsAssignableFrom(type) -#endif - ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture) : value; - } - else - { - if (value is IDictionary) - { - IDictionary jsonObject = (IDictionary)value; - - if (ReflectionUtils.IsTypeDictionary(type)) - { - // if dictionary then -#if NETFX_CORE - Type keyType = type.GetTypeInfo().GenericTypeArguments[0]; - Type valueType = type.GetTypeInfo().GenericTypeArguments[1]; -#else - Type keyType = type.GetGenericArguments()[0]; - Type valueType = type.GetGenericArguments()[1]; -#endif - - Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); - -#if NETFX_CORE - dynamic dict = CacheResolver.GetNewInstance(genericType); -#else - IDictionary dict = (IDictionary)CacheResolver.GetNewInstance(genericType); -#endif - foreach (KeyValuePair kvp in jsonObject) - { - dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType)); - } - - obj = dict; - } - else - { - obj = CacheResolver.GetNewInstance(type); - SafeDictionary maps = CacheResolver.LoadMaps(type); - - if (maps == null) - { - obj = value; - } - else - { - foreach (KeyValuePair keyValuePair in maps) - { - CacheResolver.MemberMap v = keyValuePair.Value; - if (v.Setter == null) - continue; - - string jsonKey = keyValuePair.Key; - if (jsonObject.ContainsKey(jsonKey)) - { - object jsonValue = DeserializeObject(jsonObject[jsonKey], v.Type); - v.Setter(obj, jsonValue); - } - } - } - } - } - else if (value is IList) - { - IList jsonObject = (IList)value; - IList list = null; - - if (type.IsArray) - { - list = (IList)Activator.CreateInstance(type, jsonObject.Count); - int i = 0; - foreach (object o in jsonObject) - list[i++] = DeserializeObject(o, type.GetElementType()); - } - else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || -#if NETFX_CORE - typeof(IList).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) -#else - typeof(IList).IsAssignableFrom(type) -#endif -) - { -#if NETFX_CORE - Type innerType = type.GetTypeInfo().GenericTypeArguments[0]; -#else - Type innerType = type.GetGenericArguments()[0]; -#endif - Type genericType = typeof(List<>).MakeGenericType(innerType); - list = (IList)CacheResolver.GetNewInstance(genericType); - foreach (object o in jsonObject) - list.Add(DeserializeObject(o, innerType)); - } - - obj = list; - } - - return obj; - } - - if (ReflectionUtils.IsNullableType(type)) - return ReflectionUtils.ToNullableType(obj, type); - - if (obj == null) - { - if (type == typeof(Guid)) - return default(Guid); - } - - return obj; - } - - protected virtual object SerializeEnum(Enum p) - { - return Convert.ToDouble(p, CultureInfo.InvariantCulture); - } - - protected virtual bool TrySerializeKnownTypes(object input, out object output) - { - bool returnValue = true; - if (input is DateTime) - output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); - else if (input is Guid) - output = ((Guid)input).ToString("D"); - else if (input is Uri) - output = input.ToString(); - else if (input is Enum) - output = SerializeEnum((Enum)input); - else - { - returnValue = false; - output = null; - } - - return returnValue; - } - - protected virtual bool TrySerializeUnknownTypes(object input, out object output) - { - output = null; - - // todo: implement caching for types - Type type = input.GetType(); - - if (type.FullName == null) - return false; - - IDictionary obj = new JsonObject(); - - SafeDictionary maps = CacheResolver.LoadMaps(type); - - foreach (KeyValuePair keyValuePair in maps) - { - if (keyValuePair.Value.Getter != null) - obj.Add(keyValuePair.Key, keyValuePair.Value.Getter(input)); - } - - output = obj; - return true; - } - } - -#if SIMPLE_JSON_DATACONTRACT -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy - { - public DataContractJsonSerializerStrategy() - { - CacheResolver = new CacheResolver(BuildMap); - } - - protected override void BuildMap(Type type, SafeDictionary map) - { - bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null; - if (!hasDataContract) - { - base.BuildMap(type, map); - return; - } - - string jsonKey; -#if NETFX_CORE - foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) -#else - foreach (PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) -#endif - { - if (CanAdd(info, out jsonKey)) - map.Add(jsonKey, new CacheResolver.MemberMap(info)); - } - -#if NETFX_CORE - foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) -#else - foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) -#endif - { - if (CanAdd(info, out jsonKey)) - map.Add(jsonKey, new CacheResolver.MemberMap(info)); - } - - // todo implement sorting for DATACONTRACT. - } - - private static bool CanAdd(MemberInfo info, out string jsonKey) - { - jsonKey = null; - - if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null) - return false; - - DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute)); - - if (dataMemberAttribute == null) - return false; - - jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name; - return true; - } - } -#endif - - #endregion - - #region Reflection helpers - - namespace Reflection - { -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - class ReflectionUtils - { - public static Attribute GetAttribute(MemberInfo info, Type type) - { -#if NETFX_CORE - if (info == null || type == null || !info.IsDefined(type)) - return null; - return info.GetCustomAttribute(type); -#else - if (info == null || type == null || !Attribute.IsDefined(info, type)) - return null; - return Attribute.GetCustomAttribute(info, type); -#endif - } - - public static Attribute GetAttribute(Type objectType, Type attributeType) - { - -#if NETFX_CORE - if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType)) - return null; - return objectType.GetTypeInfo().GetCustomAttribute(attributeType); -#else - if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType)) - return null; - return Attribute.GetCustomAttribute(objectType, attributeType); -#endif - } - - public static bool IsTypeGenericeCollectionInterface(Type type) - { -#if NETFX_CORE - if (!type.GetTypeInfo().IsGenericType) -#else - if (!type.IsGenericType) -#endif - return false; - - Type genericDefinition = type.GetGenericTypeDefinition(); - - return (genericDefinition == typeof(IList<>) || genericDefinition == typeof(ICollection<>) || genericDefinition == typeof(IEnumerable<>)); - } - - public static bool IsTypeDictionary(Type type) - { -#if NETFX_CORE - if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) - return true; - - if (!type.GetTypeInfo().IsGenericType) - return false; -#else - if (typeof(IDictionary).IsAssignableFrom(type)) - return true; - - if (!type.IsGenericType) - return false; -#endif - Type genericDefinition = type.GetGenericTypeDefinition(); - return genericDefinition == typeof(IDictionary<,>); - } - - public static bool IsNullableType(Type type) - { - return -#if NETFX_CORE - type.GetTypeInfo().IsGenericType -#else - type.IsGenericType -#endif - && type.GetGenericTypeDefinition() == typeof(Nullable<>); - } - - public static object ToNullableType(object obj, Type nullableType) - { - return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture); - } - } - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - delegate object GetHandler(object source); - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - delegate void SetHandler(object source, object value); - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - delegate void MemberMapLoader(Type type, SafeDictionary memberMaps); - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - class CacheResolver - { - private readonly MemberMapLoader _memberMapLoader; - private readonly SafeDictionary> _memberMapsCache = new SafeDictionary>(); - - delegate object CtorDelegate(); - readonly static SafeDictionary ConstructorCache = new SafeDictionary(); - - public CacheResolver(MemberMapLoader memberMapLoader) - { - _memberMapLoader = memberMapLoader; - } - - [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] - public static object GetNewInstance(Type type) - { - CtorDelegate c; - if (ConstructorCache.TryGetValue(type, out c)) - return c(); -#if SIMPLE_JSON_REFLECTIONEMIT - DynamicMethod dynamicMethod = new DynamicMethod("Create" + type.FullName, typeof(object), Type.EmptyTypes, type, true); - dynamicMethod.InitLocals = true; - ILGenerator generator = dynamicMethod.GetILGenerator(); - if (type.IsValueType) - { - generator.DeclareLocal(type); - generator.Emit(OpCodes.Ldloc_0); - generator.Emit(OpCodes.Box, type); - } - else - { - ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); - if (constructorInfo == null) - throw new Exception(string.Format(CultureInfo.InvariantCulture, "Could not get constructor for {0}.", type)); - generator.Emit(OpCodes.Newobj, constructorInfo); - } - generator.Emit(OpCodes.Ret); - c = (CtorDelegate)dynamicMethod.CreateDelegate(typeof(CtorDelegate)); - ConstructorCache.Add(type, c); - return c(); -#else -#if NETFX_CORE - IEnumerable constructorInfos = type.GetTypeInfo().DeclaredConstructors; - ConstructorInfo constructorInfo = null; - foreach (ConstructorInfo item in constructorInfos) // FirstOrDefault() - { - if (item.GetParameters().Length == 0) // Default ctor - make sure it doesn't contain any parameters - { - constructorInfo = item; - break; - } - } -#else - ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); -#endif - c = delegate { return constructorInfo.Invoke(null); }; - ConstructorCache.Add(type, c); - return c(); -#endif - } - - public SafeDictionary LoadMaps(Type type) - { - if (type == null || type == typeof(object)) - return null; - SafeDictionary maps; - if (_memberMapsCache.TryGetValue(type, out maps)) - return maps; - maps = new SafeDictionary(); - _memberMapLoader(type, maps); - _memberMapsCache.Add(type, maps); - return maps; - } - -#if SIMPLE_JSON_REFLECTIONEMIT - static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) - { - DynamicMethod dynamicMethod = !owner.IsInterface - ? new DynamicMethod(name, returnType, parameterTypes, owner, true) - : new DynamicMethod(name, returnType, parameterTypes, (Module)null, true); - - return dynamicMethod; - } -#endif - - static GetHandler CreateGetHandler(FieldInfo fieldInfo) - { -#if SIMPLE_JSON_REFLECTIONEMIT - Type type = fieldInfo.FieldType; - DynamicMethod dynamicGet = CreateDynamicMethod("Get" + fieldInfo.Name, fieldInfo.DeclaringType, new Type[] { typeof(object) }, fieldInfo.DeclaringType); - ILGenerator getGenerator = dynamicGet.GetILGenerator(); - - getGenerator.Emit(OpCodes.Ldarg_0); - getGenerator.Emit(OpCodes.Ldfld, fieldInfo); - if (type.IsValueType) - getGenerator.Emit(OpCodes.Box, type); - getGenerator.Emit(OpCodes.Ret); - - return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler)); -#else - return delegate(object instance) { return fieldInfo.GetValue(instance); }; -#endif - } - - static SetHandler CreateSetHandler(FieldInfo fieldInfo) - { - if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) - return null; -#if SIMPLE_JSON_REFLECTIONEMIT - Type type = fieldInfo.FieldType; - DynamicMethod dynamicSet = CreateDynamicMethod("Set" + fieldInfo.Name, null, new Type[] { typeof(object), typeof(object) }, fieldInfo.DeclaringType); - ILGenerator setGenerator = dynamicSet.GetILGenerator(); - - setGenerator.Emit(OpCodes.Ldarg_0); - setGenerator.Emit(OpCodes.Ldarg_1); - if (type.IsValueType) - setGenerator.Emit(OpCodes.Unbox_Any, type); - setGenerator.Emit(OpCodes.Stfld, fieldInfo); - setGenerator.Emit(OpCodes.Ret); - - return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler)); -#else - return delegate(object instance, object value) { fieldInfo.SetValue(instance, value); }; -#endif - } - - static GetHandler CreateGetHandler(PropertyInfo propertyInfo) - { -#if NETFX_CORE - MethodInfo getMethodInfo = propertyInfo.GetMethod; -#else - MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true); -#endif - if (getMethodInfo == null) - return null; -#if SIMPLE_JSON_REFLECTIONEMIT - Type type = propertyInfo.PropertyType; - DynamicMethod dynamicGet = CreateDynamicMethod("Get" + propertyInfo.Name, propertyInfo.DeclaringType, new Type[] { typeof(object) }, propertyInfo.DeclaringType); - ILGenerator getGenerator = dynamicGet.GetILGenerator(); - - getGenerator.Emit(OpCodes.Ldarg_0); - getGenerator.Emit(OpCodes.Call, getMethodInfo); - if (type.IsValueType) - getGenerator.Emit(OpCodes.Box, type); - getGenerator.Emit(OpCodes.Ret); - - return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler)); -#else -#if NETFX_CORE - return delegate(object instance) { return getMethodInfo.Invoke(instance, new Type[] { }); }; -#else - return delegate(object instance) { return getMethodInfo.Invoke(instance, Type.EmptyTypes); }; -#endif -#endif - } - - static SetHandler CreateSetHandler(PropertyInfo propertyInfo) - { -#if NETFX_CORE - MethodInfo setMethodInfo = propertyInfo.SetMethod; -#else - MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true); -#endif - if (setMethodInfo == null) - return null; -#if SIMPLE_JSON_REFLECTIONEMIT - Type type = propertyInfo.PropertyType; - DynamicMethod dynamicSet = CreateDynamicMethod("Set" + propertyInfo.Name, null, new Type[] { typeof(object), typeof(object) }, propertyInfo.DeclaringType); - ILGenerator setGenerator = dynamicSet.GetILGenerator(); - - setGenerator.Emit(OpCodes.Ldarg_0); - setGenerator.Emit(OpCodes.Ldarg_1); - if (type.IsValueType) - setGenerator.Emit(OpCodes.Unbox_Any, type); - setGenerator.Emit(OpCodes.Call, setMethodInfo); - setGenerator.Emit(OpCodes.Ret); - return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler)); -#else - return delegate(object instance, object value) { setMethodInfo.Invoke(instance, new[] { value }); }; -#endif - } - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - sealed class MemberMap - { - public readonly MemberInfo MemberInfo; - public readonly Type Type; - public readonly GetHandler Getter; - public readonly SetHandler Setter; - - public MemberMap(PropertyInfo propertyInfo) - { - MemberInfo = propertyInfo; - Type = propertyInfo.PropertyType; - Getter = CreateGetHandler(propertyInfo); - Setter = CreateSetHandler(propertyInfo); - } - - public MemberMap(FieldInfo fieldInfo) - { - MemberInfo = fieldInfo; - Type = fieldInfo.FieldType; - Getter = CreateGetHandler(fieldInfo); - Setter = CreateSetHandler(fieldInfo); - } - } - } - -#if SIMPLE_JSON_INTERNAL - internal -#else - public -#endif - class SafeDictionary - { - private readonly object _padlock = new object(); - private readonly Dictionary _dictionary = new Dictionary(); - - public bool TryGetValue(TKey key, out TValue value) - { - return _dictionary.TryGetValue(key, out value); - } - - public TValue this[TKey key] - { - get { return _dictionary[key]; } - } - - public IEnumerator> GetEnumerator() - { - return ((ICollection>)_dictionary).GetEnumerator(); - } - - public void Add(TKey key, TValue value) - { - lock (_padlock) - { - if (_dictionary.ContainsKey(key) == false) - _dictionary.Add(key, value); - } - } - } - } - - #endregion -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/BarcodeFormat.cs b/shadowsocks-csharp/3rd/zxing/BarcodeFormat.cs deleted file mode 100755 index e20f6535..00000000 --- a/shadowsocks-csharp/3rd/zxing/BarcodeFormat.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing -{ - /// - /// Enumerates barcode formats known to this package. - /// - /// Sean Owen - [System.Flags] - public enum BarcodeFormat - { - /// Aztec 2D barcode format. - AZTEC = 1, - - /// CODABAR 1D format. - CODABAR = 2, - - /// Code 39 1D format. - CODE_39 = 4, - - /// Code 93 1D format. - CODE_93 = 8, - - /// Code 128 1D format. - CODE_128 = 16, - - /// Data Matrix 2D barcode format. - DATA_MATRIX = 32, - - /// EAN-8 1D format. - EAN_8 = 64, - - /// EAN-13 1D format. - EAN_13 = 128, - - /// ITF (Interleaved Two of Five) 1D format. - ITF = 256, - - /// MaxiCode 2D barcode format. - MAXICODE = 512, - - /// PDF417 format. - PDF_417 = 1024, - - /// QR Code 2D barcode format. - QR_CODE = 2048, - - /// RSS 14 - RSS_14 = 4096, - - /// RSS EXPANDED - RSS_EXPANDED = 8192, - - /// UPC-A 1D format. - UPC_A = 16384, - - /// UPC-E 1D format. - UPC_E = 32768, - - /// UPC/EAN extension format. Not a stand-alone format. - UPC_EAN_EXTENSION = 65536, - - /// MSI - MSI = 131072, - - /// Plessey - PLESSEY = 262144, - - /// - /// UPC_A | UPC_E | EAN_13 | EAN_8 | CODABAR | CODE_39 | CODE_93 | CODE_128 | ITF | RSS_14 | RSS_EXPANDED - /// without MSI (to many false-positives) - /// - All_1D = UPC_A | UPC_E | EAN_13 | EAN_8 | CODABAR | CODE_39 | CODE_93 | CODE_128 | ITF | RSS_14 | RSS_EXPANDED - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/BaseLuminanceSource.cs b/shadowsocks-csharp/3rd/zxing/BaseLuminanceSource.cs deleted file mode 100755 index c91d81db..00000000 --- a/shadowsocks-csharp/3rd/zxing/BaseLuminanceSource.cs +++ /dev/null @@ -1,206 +0,0 @@ -/* -* Copyright 2012 ZXing.Net authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing -{ - /// - /// The base class for luminance sources which supports - /// cropping and rotating based upon the luminance values. - /// - public abstract class BaseLuminanceSource : LuminanceSource - { - // the following channel weights give nearly the same - // gray scale picture as the java version with BufferedImage.TYPE_BYTE_GRAY - // they are used in sub classes for luminance / gray scale calculation - protected const int RChannelWeight = 19562; - protected const int GChannelWeight = 38550; - protected const int BChannelWeight = 7424; - protected const int ChannelWeight = 16; - - /// - /// - /// - protected byte[] luminances; - - /// - /// Initializes a new instance of the class. - /// - /// The width. - /// The height. - protected BaseLuminanceSource(int width, int height) - : base(width, height) - { - luminances = new byte[width * height]; - } - - /// - /// Initializes a new instance of the class. - /// - /// The luminance array. - /// The width. - /// The height. - protected BaseLuminanceSource(byte[] luminanceArray, int width, int height) - : base(width, height) - { - luminances = new byte[width * height]; - Buffer.BlockCopy(luminanceArray, 0, luminances, 0, width * height); - } - - /// - /// Fetches one row of luminance data from the underlying platform's bitmap. Values range from - /// 0 (black) to 255 (white). It is preferable for implementations of this method - /// to only fetch this row rather than the whole image, since no 2D Readers may be installed and - /// getMatrix() may never be called. - /// - /// The row to fetch, 0 <= y < Height. - /// An optional preallocated array. If null or too small, it will be ignored. - /// Always use the returned object, and ignore the .length of the array. - /// - /// An array containing the luminance data. - /// - override public byte[] getRow(int y, byte[] row) - { - int width = Width; - if (row == null || row.Length < width) - { - row = new byte[width]; - } - for (int i = 0; i < width; i++) - row[i] = luminances[y * width + i]; - return row; - } - - public override byte[] Matrix - { - get { return luminances; } - } - - /// - /// Returns a new object with rotated image data by 90 degrees counterclockwise. - /// Only callable if {@link #isRotateSupported()} is true. - /// - /// - /// A rotated version of this object. - /// - public override LuminanceSource rotateCounterClockwise() - { - var rotatedLuminances = new byte[Width * Height]; - var newWidth = Height; - var newHeight = Width; - var localLuminances = Matrix; - for (var yold = 0; yold < Height; yold++) - { - for (var xold = 0; xold < Width; xold++) - { - var ynew = newHeight - xold - 1; - var xnew = yold; - rotatedLuminances[ynew * newWidth + xnew] = localLuminances[yold * Width + xold]; - } - } - return CreateLuminanceSource(rotatedLuminances, newWidth, newHeight); - } - - /// - /// TODO: not implemented yet - /// - /// - /// A rotated version of this object. - /// - public override LuminanceSource rotateCounterClockwise45() - { - // TODO: implement a good 45 degrees rotation without lost of information - return base.rotateCounterClockwise45(); - } - - /// - /// - /// Whether this subclass supports counter-clockwise rotation. - public override bool RotateSupported - { - get - { - return true; - } - } - - /// - /// Returns a new object with cropped image data. Implementations may keep a reference to the - /// original data rather than a copy. Only callable if CropSupported is true. - /// - /// The left coordinate, 0 <= left < Width. - /// The top coordinate, 0 <= top <= Height. - /// The width of the rectangle to crop. - /// The height of the rectangle to crop. - /// - /// A cropped version of this object. - /// - public override LuminanceSource crop(int left, int top, int width, int height) - { - if (left + width > Width || top + height > Height) - { - throw new ArgumentException("Crop rectangle does not fit within image data."); - } - var croppedLuminances = new byte[width * height]; - var oldLuminances = Matrix; - var oldWidth = Width; - var oldRightBound = left + width; - var oldBottomBound = top + height; - for (int yold = top, ynew = 0; yold < oldBottomBound; yold++, ynew++) - { - for (int xold = left, xnew = 0; xold < oldRightBound; xold++, xnew++) - { - croppedLuminances[ynew * width + xnew] = oldLuminances[yold * oldWidth + xold]; - } - } - return CreateLuminanceSource(croppedLuminances, width, height); - } - - /// - /// - /// Whether this subclass supports cropping. - public override bool CropSupported - { - get - { - return true; - } - } - - /// - /// - /// Whether this subclass supports invertion. - public override bool InversionSupported - { - get - { - return true; - } - } - - - /// - /// Should create a new luminance source with the right class type. - /// The method is used in methods crop and rotate. - /// - /// The new luminances. - /// The width. - /// The height. - /// - protected abstract LuminanceSource CreateLuminanceSource(byte[] newLuminances, int width, int height); - } -} diff --git a/shadowsocks-csharp/3rd/zxing/Binarizer.cs b/shadowsocks-csharp/3rd/zxing/Binarizer.cs deleted file mode 100755 index 213ec66a..00000000 --- a/shadowsocks-csharp/3rd/zxing/Binarizer.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -using ZXing.Common; - -namespace ZXing -{ - /// This class hierarchy provides a set of methods to convert luminance data to 1 bit data. - /// It allows the algorithm to vary polymorphically, for example allowing a very expensive - /// thresholding technique for servers and a fast one for mobile. It also permits the implementation - /// to vary, e.g. a JNI version for Android and a Java fallback version for other platforms. - /// - /// dswitkin@google.com (Daniel Switkin) - /// - public abstract class Binarizer - { - private readonly LuminanceSource source; - - /// - /// Initializes a new instance of the class. - /// - /// The source. - protected internal Binarizer(LuminanceSource source) - { - if (source == null) - { - throw new ArgumentException("Source must be non-null."); - } - this.source = source; - } - - /// - /// Gets the luminance source object. - /// - virtual public LuminanceSource LuminanceSource - { - get - { - return source; - } - } - - /// Converts one row of luminance data to 1 bit data. May actually do the conversion, or return - /// cached data. Callers should assume this method is expensive and call it as seldom as possible. - /// This method is intended for decoding 1D barcodes and may choose to apply sharpening. - /// For callers which only examine one row of pixels at a time, the same BitArray should be reused - /// and passed in with each call for performance. However it is legal to keep more than one row - /// at a time if needed. - /// - /// The row to fetch, 0 <= y < bitmap height. - /// An optional preallocated array. If null or too small, it will be ignored. - /// If used, the Binarizer will call BitArray.clear(). Always use the returned object. - /// - /// The array of bits for this row (true means black). - public abstract BitArray getBlackRow(int y, BitArray row); - - /// Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive - /// and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or - /// may not apply sharpening. Therefore, a row from this matrix may not be identical to one - /// fetched using getBlackRow(), so don't mix and match between them. - /// - /// The 2D array of bits for the image (true means black). - public abstract BitMatrix BlackMatrix { get; } - - /// Creates a new object with the same type as this Binarizer implementation, but with pristine - /// state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache - /// of 1 bit data. See Effective Java for why we can't use Java's clone() method. - /// - /// The LuminanceSource this Binarizer will operate on. - /// A new concrete Binarizer implementation object. - public abstract Binarizer createBinarizer(LuminanceSource source); - - /// - /// Gets the width of the luminance source object. - /// - public int Width - { - get { return source.Width; } - } - - /// - /// Gets the height of the luminance source object. - /// - public int Height - { - get { return source.Height; } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/BinaryBitmap.cs b/shadowsocks-csharp/3rd/zxing/BinaryBitmap.cs deleted file mode 100755 index fea1b266..00000000 --- a/shadowsocks-csharp/3rd/zxing/BinaryBitmap.cs +++ /dev/null @@ -1,186 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using ZXing.Common; - -namespace ZXing -{ - - /// This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects - /// accept a BinaryBitmap and attempt to decode it. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class BinaryBitmap - { - private Binarizer binarizer; - private BitMatrix matrix; - - public BinaryBitmap(Binarizer binarizer) - { - if (binarizer == null) - { - throw new ArgumentException("Binarizer must be non-null."); - } - this.binarizer = binarizer; - } - - /// The width of the bitmap. - /// - public int Width - { - get - { - return binarizer.Width; - } - - } - /// The height of the bitmap. - /// - public int Height - { - get - { - return binarizer.Height; - } - - } - - /// Converts one row of luminance data to 1 bit data. May actually do the conversion, or return - /// cached data. Callers should assume this method is expensive and call it as seldom as possible. - /// This method is intended for decoding 1D barcodes and may choose to apply sharpening. - /// - /// - /// The row to fetch, 0 <= y < bitmap height. - /// - /// An optional preallocated array. If null or too small, it will be ignored. - /// If used, the Binarizer will call BitArray.clear(). Always use the returned object. - /// - /// The array of bits for this row (true means black). - /// - public BitArray getBlackRow(int y, BitArray row) - { - return binarizer.getBlackRow(y, row); - } - - /// Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive - /// and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or - /// may not apply sharpening. Therefore, a row from this matrix may not be identical to one - /// fetched using getBlackRow(), so don't mix and match between them. - /// - /// - /// The 2D array of bits for the image (true means black). - /// - public BitMatrix BlackMatrix - { - get - { - // The matrix is created on demand the first time it is requested, then cached. There are two - // reasons for this: - // 1. This work will never be done if the caller only installs 1D Reader objects, or if a - // 1D Reader finds a barcode before the 2D Readers run. - // 2. This work will only be done once even if the caller installs multiple 2D Readers. - if (matrix == null) - { - matrix = binarizer.BlackMatrix; - } - return matrix; - } - } - - /// Whether this bitmap can be cropped. - /// - public bool CropSupported - { - get - { - return binarizer.LuminanceSource.CropSupported; - } - - } - - /// Returns a new object with cropped image data. Implementations may keep a reference to the - /// original data rather than a copy. Only callable if isCropSupported() is true. - /// - /// - /// The left coordinate, 0 <= left < getWidth(). - /// - /// The top coordinate, 0 <= top <= getHeight(). - /// - /// The width of the rectangle to crop. - /// - /// The height of the rectangle to crop. - /// - /// A cropped version of this object. - /// - public BinaryBitmap crop(int left, int top, int width, int height) - { - var newSource = binarizer.LuminanceSource.crop(left, top, width, height); - return new BinaryBitmap(binarizer.createBinarizer(newSource)); - } - - /// Whether this bitmap supports counter-clockwise rotation. - /// - public bool RotateSupported - { - get - { - return binarizer.LuminanceSource.RotateSupported; - } - - } - - /// - /// Returns a new object with rotated image data by 90 degrees counterclockwise. - /// Only callable if {@link #isRotateSupported()} is true. - /// - /// A rotated version of this object. - /// - public BinaryBitmap rotateCounterClockwise() - { - var newSource = binarizer.LuminanceSource.rotateCounterClockwise(); - return new BinaryBitmap(binarizer.createBinarizer(newSource)); - } - - /// - /// Returns a new object with rotated image data by 45 degrees counterclockwise. - /// Only callable if {@link #isRotateSupported()} is true. - /// - /// A rotated version of this object. - public BinaryBitmap rotateCounterClockwise45() - { - LuminanceSource newSource = binarizer.LuminanceSource.rotateCounterClockwise45(); - return new BinaryBitmap(binarizer.createBinarizer(newSource)); - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - var blackMatrix = BlackMatrix; - return blackMatrix != null ? blackMatrix.ToString() : String.Empty; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/BitmapLuminanceSource.cs b/shadowsocks-csharp/3rd/zxing/BitmapLuminanceSource.cs deleted file mode 100755 index 8c61f531..00000000 --- a/shadowsocks-csharp/3rd/zxing/BitmapLuminanceSource.cs +++ /dev/null @@ -1,242 +0,0 @@ -/* -* Copyright 2012 ZXing.Net authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Drawing.Imaging; -using System.Drawing; -using System.Runtime.InteropServices; - -namespace ZXing -{ - public partial class BitmapLuminanceSource : BaseLuminanceSource - { - /// - /// Initializes a new instance of the class. - /// - /// The width. - /// The height. - protected BitmapLuminanceSource(int width, int height) - : base(width, height) - { - } - - /// - /// Initializes a new instance of the class - /// with the image of a Bitmap instance - /// - /// The bitmap. - public BitmapLuminanceSource(Bitmap bitmap) - : base(bitmap.Width, bitmap.Height) - { - var height = bitmap.Height; - var width = bitmap.Width; - - // In order to measure pure decoding speed, we convert the entire image to a greyscale array - // The underlying raster of image consists of bytes with the luminance values -#if WindowsCE - var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); -#else - var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat); -#endif - try - { - var stride = Math.Abs(data.Stride); - var pixelWidth = stride/width; - - if (pixelWidth > 4) - { - // old slow way for unsupported bit depth - Color c; - for (int y = 0; y < height; y++) - { - int offset = y*width; - for (int x = 0; x < width; x++) - { - c = bitmap.GetPixel(x, y); - luminances[offset + x] = (byte)((RChannelWeight * c.R + GChannelWeight * c.G + BChannelWeight * c.B) >> ChannelWeight); - } - } - } - else - { - var strideStep = data.Stride; - var buffer = new byte[stride]; - var ptrInBitmap = data.Scan0; - -#if !WindowsCE - // prepare palette for 1 and 8 bit indexed bitmaps - var luminancePalette = new byte[bitmap.Palette.Entries.Length]; - for (var index = 0; index < bitmap.Palette.Entries.Length; index++) - { - var color = bitmap.Palette.Entries[index]; - luminancePalette[index] = (byte) ((RChannelWeight*color.R + - GChannelWeight*color.G + - BChannelWeight*color.B) >> ChannelWeight); - } - if (bitmap.PixelFormat == PixelFormat.Format32bppArgb || - bitmap.PixelFormat == PixelFormat.Format32bppPArgb) - { - pixelWidth = 40; - } - if ((int)bitmap.PixelFormat == 8207 || - (bitmap.Flags & (int)ImageFlags.ColorSpaceCmyk) == (int)ImageFlags.ColorSpaceCmyk) - { - pixelWidth = 41; - } -#endif - - for (int y = 0; y < height; y++) - { - // copy a scanline not the whole bitmap because of memory usage - Marshal.Copy(ptrInBitmap, buffer, 0, stride); -#if NET40 - ptrInBitmap = IntPtr.Add(ptrInBitmap, strideStep); -#else - ptrInBitmap = new IntPtr(ptrInBitmap.ToInt64() + strideStep); -#endif - var offset = y*width; - switch (pixelWidth) - { -#if !WindowsCE - case 0: - for (int x = 0; x*8 < width; x++) - { - for (int subX = 0; subX < 8 && 8*x + subX < width; subX++) - { - var index = (buffer[x] >> (7 - subX)) & 1; - luminances[offset + 8*x + subX] = luminancePalette[index]; - } - } - break; - case 1: - for (int x = 0; x < width; x++) - { - luminances[offset + x] = luminancePalette[buffer[x]]; - } - break; -#endif - case 2: - // should be RGB565 or RGB555, assume RGB565 - { - var maxIndex = 2*width; - for (int index = 0; index < maxIndex; index += 2) - { - var byte1 = buffer[index]; - var byte2 = buffer[index + 1]; - - var b5 = byte1 & 0x1F; - var g5 = (((byte1 & 0xE0) >> 5) | ((byte2 & 0x03) << 3)) & 0x1F; - var r5 = (byte2 >> 2) & 0x1F; - var r8 = (r5*527 + 23) >> 6; - var g8 = (g5*527 + 23) >> 6; - var b8 = (b5*527 + 23) >> 6; - - luminances[offset] = (byte)((RChannelWeight * r8 + GChannelWeight * g8 + BChannelWeight * b8) >> ChannelWeight); - offset++; - } - } - break; - case 3: - { - var maxIndex = width*3; - for (int x = 0; x < maxIndex; x += 3) - { - var luminance = (byte) ((BChannelWeight*buffer[x] + - GChannelWeight*buffer[x + 1] + - RChannelWeight*buffer[x + 2]) >> ChannelWeight); - luminances[offset] = luminance; - offset++; - } - } - break; - case 4: - // 4 bytes without alpha channel value - { - var maxIndex = 4*width; - for (int x = 0; x < maxIndex; x += 4) - { - var luminance = (byte) ((BChannelWeight*buffer[x] + - GChannelWeight*buffer[x + 1] + - RChannelWeight*buffer[x + 2]) >> ChannelWeight); - - luminances[offset] = luminance; - offset++; - } - } - break; - case 40: - // with alpha channel; some barcodes are completely black if you - // only look at the r, g and b channel but the alpha channel controls - // the view - { - var maxIndex = 4*width; - for (int x = 0; x < maxIndex; x += 4) - { - var luminance = (byte) ((BChannelWeight*buffer[x] + - GChannelWeight*buffer[x + 1] + - RChannelWeight*buffer[x + 2]) >> ChannelWeight); - - // calculating the resulting luminance based upon a white background - // var alpha = buffer[x * pixelWidth + 3] / 255.0; - // luminance = (byte)(luminance * alpha + 255 * (1 - alpha)); - var alpha = buffer[x + 3]; - luminance = (byte) (((luminance*alpha) >> 8) + (255*(255 - alpha) >> 8) + 1); - luminances[offset] = luminance; - offset++; - } - } - break; - case 41: - // CMYK color space - { - var maxIndex = 4 * width; - for (int x = 0; x < maxIndex; x += 4) - { - var luminance = (byte) (255 - ((BChannelWeight*buffer[x] + - GChannelWeight*buffer[x + 1] + - RChannelWeight*buffer[x + 2]) >> ChannelWeight)); - // Ignore value of k at the moment - luminances[offset] = luminance; - offset++; - } - } - break; - default: - throw new NotSupportedException(); - } - } - } - } - finally - { - bitmap.UnlockBits(data); - } - } - - /// - /// Should create a new luminance source with the right class type. - /// The method is used in methods crop and rotate. - /// - /// The new luminances. - /// The width. - /// The height. - /// - protected override LuminanceSource CreateLuminanceSource(byte[] newLuminances, int width, int height) - { - return new BitmapLuminanceSource(width, height) { luminances = newLuminances }; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/DecodeHintType.cs b/shadowsocks-csharp/3rd/zxing/DecodeHintType.cs deleted file mode 100755 index 8ba21bbb..00000000 --- a/shadowsocks-csharp/3rd/zxing/DecodeHintType.cs +++ /dev/null @@ -1,125 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; - -namespace ZXing -{ - /// - /// Encapsulates a type of hint that a caller may pass to a barcode reader to help it - /// more quickly or accurately decode it. It is up to implementations to decide what, - /// if anything, to do with the information that is supplied. - /// - /// - /// Sean Owen - /// dswitkin@google.com (Daniel Switkin) - public enum DecodeHintType - { - /// - /// Unspecified, application-specific hint. Maps to an unspecified . - /// - OTHER, - - /// - /// Image is a pure monochrome image of a barcode. Doesn't matter what it maps to; - /// use = true. - /// - PURE_BARCODE, - - /// - /// Image is known to be of one of a few possible formats. - /// Maps to a of s. - /// - POSSIBLE_FORMATS, - - /// - /// Spend more time to try to find a barcode; optimize for accuracy, not speed. - /// Doesn't matter what it maps to; use = true. - /// - TRY_HARDER, - - /// - /// Specifies what character encoding to use when decoding, where applicable (type String) - /// - CHARACTER_SET, - - /// - /// Allowed lengths of encoded data -- reject anything else. Maps to an int[]. - /// - ALLOWED_LENGTHS, - - /// - /// Assume Code 39 codes employ a check digit. Maps to . - /// - ASSUME_CODE_39_CHECK_DIGIT, - - /// - /// The caller needs to be notified via callback when a possible - /// is found. Maps to a . - /// - NEED_RESULT_POINT_CALLBACK, - - /// - /// Assume MSI codes employ a check digit. Maps to . - /// - ASSUME_MSI_CHECK_DIGIT, - - /// - /// if Code39 could be detected try to use extended mode for full ASCII character set - /// Maps to . - /// - USE_CODE_39_EXTENDED_MODE, - - /// - /// Don't fail if a Code39 is detected but can't be decoded in extended mode. - /// Return the raw Code39 result instead. Maps to . - /// - RELAXED_CODE_39_EXTENDED_MODE, - - /// - /// 1D readers supporting rotation with TRY_HARDER enabled. - /// But BarcodeReader class can do auto-rotating for 1D and 2D codes. - /// Enabling that option prevents 1D readers doing double rotation. - /// BarcodeReader enables that option automatically if "global" auto-rotation is enabled. - /// Maps to . - /// - TRY_HARDER_WITHOUT_ROTATION, - - /// - /// Assume the barcode is being processed as a GS1 barcode, and modify behavior as needed. - /// For example this affects FNC1 handling for Code 128 (aka GS1-128). Doesn't matter what it maps to; - /// use . - /// - ASSUME_GS1, - - /// - /// If true, return the start and end digits in a Codabar barcode instead of stripping them. They - /// are alpha, whereas the rest are numeric. By default, they are stripped, but this causes them - /// to not be. Doesn't matter what it maps to; use . - /// - RETURN_CODABAR_START_END, - - /// - /// Allowed extension lengths for EAN or UPC barcodes. Other formats will ignore this. - /// Maps to an of the allowed extension lengths, for example [2], [5], or [2, 5]. - /// If it is optional to have an extension, do not set this hint. If this is set, - /// and a UPC or EAN barcode is found but an extension is not, then no result will be returned - /// at all. - /// - ALLOWED_EAN_EXTENSIONS - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/EncodeHintType.cs b/shadowsocks-csharp/3rd/zxing/EncodeHintType.cs deleted file mode 100755 index 01b17f8c..00000000 --- a/shadowsocks-csharp/3rd/zxing/EncodeHintType.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing -{ - /// - /// These are a set of hints that you may pass to Writers to specify their behavior. - /// - /// dswitkin@google.com (Daniel Switkin) - public enum EncodeHintType - { - /// - /// Specifies the width of the barcode image - /// type: - /// - WIDTH, - - /// - /// Specifies the height of the barcode image - /// type: - /// - HEIGHT, - - /// - /// Don't put the content string into the output image. - /// type: - /// - PURE_BARCODE, - - /// - /// Specifies what degree of error correction to use, for example in QR Codes. - /// Type depends on the encoder. For example for QR codes it's type - /// - /// For Aztec it is of type , representing the minimal percentage of error correction words. - /// Note: an Aztec symbol should have a minimum of 25% EC words. - /// For PDF417 it is of type or (between 0 and 8), - /// - ERROR_CORRECTION, - - /// - /// Specifies what character encoding to use where applicable. - /// type: - /// - CHARACTER_SET, - - /// - /// Specifies margin, in pixels, to use when generating the barcode. The meaning can vary - /// by format; for example it controls margin before and after the barcode horizontally for - /// most 1D formats. - /// type: - /// - MARGIN, - - /// - /// Specifies whether to use compact mode for PDF417. - /// type: - /// - PDF417_COMPACT, - - /// - /// Specifies what compaction mode to use for PDF417. - /// type: - /// - PDF417_COMPACTION, - - /// - /// Specifies the minimum and maximum number of rows and columns for PDF417. - /// type: - /// - PDF417_DIMENSIONS, - - /// - /// Don't append ECI segment. - /// That is against the specification of QR Code but some - /// readers have problems if the charset is switched from - /// ISO-8859-1 (default) to UTF-8 with the necessary ECI segment. - /// If you set the property to true you can use UTF-8 encoding - /// and the ECI segment is omitted. - /// type: - /// - DISABLE_ECI, - - /// - /// Specifies the matrix shape for Data Matrix (type ) - /// - DATA_MATRIX_SHAPE, - - /// - /// Specifies a minimum barcode size (type ). Only applicable to Data Matrix now. - /// - MIN_SIZE, - - /// - /// Specifies a maximum barcode size (type ). Only applicable to Data Matrix now. - /// - MAX_SIZE, - - /// - /// if true, don't switch to codeset C for numbers - /// - CODE128_FORCE_CODESET_B, - - /// - /// Specifies the default encodation for Data Matrix (type ) - /// Make sure that the content fits into the encodation value, otherwise there will be an exception thrown. - /// standard value: Encodation.ASCII - /// - DATA_MATRIX_DEFAULT_ENCODATION, - - /// - /// Specifies the required number of layers for an Aztec code: - /// a negative number (-1, -2, -3, -4) specifies a compact Aztec code - /// 0 indicates to use the minimum number of layers (the default) - /// a positive number (1, 2, .. 32) specifies a normal (non-compact) Aztec code - /// - AZTEC_LAYERS, - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/LuminanceSource.cs b/shadowsocks-csharp/3rd/zxing/LuminanceSource.cs deleted file mode 100755 index 371a27c7..00000000 --- a/shadowsocks-csharp/3rd/zxing/LuminanceSource.cs +++ /dev/null @@ -1,198 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Text; - -namespace ZXing -{ - /// The purpose of this class hierarchy is to abstract different bitmap implementations across - /// platforms into a standard interface for requesting greyscale luminance values. The interface - /// only provides immutable methods; therefore crop and rotation create copies. This is to ensure - /// that one Reader does not modify the original luminance source and leave it in an unknown state - /// for other Readers in the chain. - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class LuminanceSource - { - private int width; - private int height; - - protected LuminanceSource(int width, int height) - { - this.width = width; - this.height = height; - } - - /// Fetches one row of luminance data from the underlying platform's bitmap. Values range from - /// 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have - /// to bitwise and with 0xff for each value. It is preferable for implementations of this method - /// to only fetch this row rather than the whole image, since no 2D Readers may be installed and - /// getMatrix() may never be called. - /// - /// - /// The row to fetch, 0 <= y < Height. - /// - /// An optional preallocated array. If null or too small, it will be ignored. - /// Always use the returned object, and ignore the .length of the array. - /// - /// An array containing the luminance data. - /// - public abstract byte[] getRow(int y, byte[] row); - - /// Fetches luminance data for the underlying bitmap. Values should be fetched using: - /// int luminance = array[y * width + x] & 0xff; - /// - /// - /// A row-major 2D array of luminance values. Do not use result.length as it may be - /// larger than width * height bytes on some platforms. Do not modify the contents - /// of the result. - /// - public abstract byte[] Matrix { get; } - - /// The width of the bitmap. - virtual public int Width - { - get - { - return width; - } - protected set - { - width = value; - } - } - - /// The height of the bitmap. - virtual public int Height - { - get - { - return height; - } - protected set - { - height = value; - } - } - - /// Whether this subclass supports cropping. - virtual public bool CropSupported - { - get - { - return false; - } - } - - /// Returns a new object with cropped image data. Implementations may keep a reference to the - /// original data rather than a copy. Only callable if CropSupported is true. - /// - /// - /// The left coordinate, 0 <= left < Width. - /// - /// The top coordinate, 0 <= top <= Height. - /// - /// The width of the rectangle to crop. - /// - /// The height of the rectangle to crop. - /// - /// A cropped version of this object. - /// - public virtual LuminanceSource crop(int left, int top, int width, int height) - { - throw new NotSupportedException("This luminance source does not support cropping."); - } - - /// Whether this subclass supports counter-clockwise rotation. - virtual public bool RotateSupported - { - get - { - return false; - } - } - - /// - /// Returns a new object with rotated image data by 90 degrees counterclockwise. - /// Only callable if {@link #isRotateSupported()} is true. - /// - /// A rotated version of this object. - /// - public virtual LuminanceSource rotateCounterClockwise() - { - throw new NotSupportedException("This luminance source does not support rotation."); - } - - /// - /// Returns a new object with rotated image data by 45 degrees counterclockwise. - /// Only callable if {@link #isRotateSupported()} is true. - /// - /// A rotated version of this object. - public virtual LuminanceSource rotateCounterClockwise45() - { - throw new NotSupportedException("This luminance source does not support rotation by 45 degrees."); - } - - /// - /// - /// Whether this subclass supports invertion. - virtual public bool InversionSupported - { - get - { - return false; - } - } - - override public String ToString() - { - var row = new byte[width]; - var result = new StringBuilder(height * (width + 1)); - for (int y = 0; y < height; y++) - { - row = getRow(y, row); - for (int x = 0; x < width; x++) - { - int luminance = row[x] & 0xFF; - char c; - if (luminance < 0x40) - { - c = '#'; - } - else if (luminance < 0x80) - { - c = '+'; - } - else if (luminance < 0xC0) - { - c = '.'; - } - else - { - c = ' '; - } - result.Append(c); - } - result.Append('\n'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/Result.cs b/shadowsocks-csharp/3rd/zxing/Result.cs deleted file mode 100755 index 3aa6f5b8..00000000 --- a/shadowsocks-csharp/3rd/zxing/Result.cs +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; - -namespace ZXing -{ - /// - /// Encapsulates the result of decoding a barcode within an image. - /// - public sealed class Result - { - /// raw text encoded by the barcode, if applicable, otherwise null - public String Text { get; private set; } - - /// raw bytes encoded by the barcode, if applicable, otherwise null - public byte[] RawBytes { get; private set; } - - /// - /// points related to the barcode in the image. These are typically points - /// identifying finder patterns or the corners of the barcode. The exact meaning is - /// specific to the type of barcode that was decoded. - /// - public ResultPoint[] ResultPoints { get; private set; } - - /// {@link BarcodeFormat} representing the format of the barcode that was decoded - public BarcodeFormat BarcodeFormat { get; private set; } - - /// - /// {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be - /// null. This contains optional metadata about what was detected about the barcode, - /// like orientation. - /// - public IDictionary ResultMetadata { get; private set; } - - /// - /// Gets the timestamp. - /// - public long Timestamp { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - /// The text. - /// The raw bytes. - /// The result points. - /// The format. - public Result(String text, - byte[] rawBytes, - ResultPoint[] resultPoints, - BarcodeFormat format) - : this(text, rawBytes, resultPoints, format, DateTime.Now.Ticks) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The text. - /// The raw bytes. - /// The result points. - /// The format. - /// The timestamp. - public Result(String text, byte[] rawBytes, ResultPoint[] resultPoints, BarcodeFormat format, long timestamp) - { - if (text == null && rawBytes == null) - { - throw new ArgumentException("Text and bytes are null"); - } - Text = text; - RawBytes = rawBytes; - ResultPoints = resultPoints; - BarcodeFormat = format; - ResultMetadata = null; - Timestamp = timestamp; - } - - /// - /// Adds one metadata to the result - /// - /// The type. - /// The value. - public void putMetadata(ResultMetadataType type, Object value) - { - if (ResultMetadata == null) - { - ResultMetadata = new Dictionary(); - } - ResultMetadata[type] = value; - } - - /// - /// Adds a list of metadata to the result - /// - /// The metadata. - public void putAllMetadata(IDictionary metadata) - { - if (metadata != null) - { - if (ResultMetadata == null) - { - ResultMetadata = metadata; - } - else - { - foreach (var entry in metadata) - ResultMetadata[entry.Key] = entry.Value; - } - } - } - - /// - /// Adds the result points. - /// - /// The new points. - public void addResultPoints(ResultPoint[] newPoints) - { - var oldPoints = ResultPoints; - if (oldPoints == null) - { - ResultPoints = newPoints; - } - else if (newPoints != null && newPoints.Length > 0) - { - var allPoints = new ResultPoint[oldPoints.Length + newPoints.Length]; - Array.Copy(oldPoints, 0, allPoints, 0, oldPoints.Length); - Array.Copy(newPoints, 0, allPoints, oldPoints.Length, newPoints.Length); - ResultPoints = allPoints; - } - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override String ToString() - { - if (Text == null) - { - return "[" + RawBytes.Length + " bytes]"; - } - return Text; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/ResultMetadataType.cs b/shadowsocks-csharp/3rd/zxing/ResultMetadataType.cs deleted file mode 100755 index 360357c8..00000000 --- a/shadowsocks-csharp/3rd/zxing/ResultMetadataType.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace ZXing -{ - /// - /// Represents some type of metadata about the result of the decoding that the decoder - /// wishes to communicate back to the caller. - /// - /// Sean Owen - public enum ResultMetadataType - { - /// - /// Unspecified, application-specific metadata. Maps to an unspecified {@link Object}. - /// - OTHER, - - /// - /// Denotes the likely approximate orientation of the barcode in the image. This value - /// is given as degrees rotated clockwise from the normal, upright orientation. - /// For example a 1D barcode which was found by reading top-to-bottom would be - /// said to have orientation "90". This key maps to an {@link Integer} whose - /// value is in the range [0,360). - /// - ORIENTATION, - - /// - ///

2D barcode formats typically encode text, but allow for a sort of 'byte mode' - /// which is sometimes used to encode binary data. While {@link Result} makes available - /// the complete raw bytes in the barcode for these formats, it does not offer the bytes - /// from the byte segments alone.

- ///

This maps to a {@link java.util.List} of byte arrays corresponding to the - /// raw bytes in the byte segments in the barcode, in order.

- ///
- BYTE_SEGMENTS, - - /// - /// Error correction level used, if applicable. The value type depends on the - /// format, but is typically a String. - /// - ERROR_CORRECTION_LEVEL, - - /// - /// For some periodicals, indicates the issue number as an {@link Integer}. - /// - ISSUE_NUMBER, - - /// - /// For some products, indicates the suggested retail price in the barcode as a - /// formatted {@link String}. - /// - SUGGESTED_PRICE, - - /// - /// For some products, the possible country of manufacture as a {@link String} denoting the - /// ISO country code. Some map to multiple possible countries, like "US/CA". - /// - POSSIBLE_COUNTRY, - - /// - /// For some products, the extension text - /// - UPC_EAN_EXTENSION, - - /// - /// If the code format supports structured append and - /// the current scanned code is part of one then the - /// sequence number is given with it. - /// - STRUCTURED_APPEND_SEQUENCE, - - /// - /// If the code format supports structured append and - /// the current scanned code is part of one then the - /// parity is given with it. - /// - STRUCTURED_APPEND_PARITY, - - /// - /// PDF417-specific metadata - /// - PDF417_EXTRA_METADATA, - - /// - /// Aztec-specific metadata - /// - AZTEC_EXTRA_METADATA - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/ResultPoint.cs b/shadowsocks-csharp/3rd/zxing/ResultPoint.cs deleted file mode 100755 index d3f39f2d..00000000 --- a/shadowsocks-csharp/3rd/zxing/ResultPoint.cs +++ /dev/null @@ -1,191 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -using ZXing.Common.Detector; - -namespace ZXing -{ - /// - /// Encapsulates a point of interest in an image containing a barcode. Typically, this - /// would be the location of a finder pattern or the corner of the barcode, for example. - /// - /// Sean Owen - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - public class ResultPoint - { - private readonly float x; - private readonly float y; - private readonly byte[] bytesX; - private readonly byte[] bytesY; - private String toString; - - /// - /// Initializes a new instance of the class. - /// - public ResultPoint() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The x. - /// The y. - public ResultPoint(float x, float y) - { - this.x = x; - this.y = y; - // calculate only once for GetHashCode - bytesX = BitConverter.GetBytes(x); - bytesY = BitConverter.GetBytes(y); - } - - /// - /// Gets the X. - /// - virtual public float X - { - get - { - return x; - } - } - - /// - /// Gets the Y. - /// - virtual public float Y - { - get - { - return y; - } - } - - /// - /// Determines whether the specified is equal to this instance. - /// - /// The to compare with this instance. - /// - /// true if the specified is equal to this instance; otherwise, false. - /// - public override bool Equals(Object other) - { - var otherPoint = other as ResultPoint; - if (otherPoint == null) - return false; - return x == otherPoint.x && y == otherPoint.y; - } - - /// - /// Returns a hash code for this instance. - /// - /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - /// - public override int GetHashCode() - { - return 31 * ((bytesX[0] << 24) + (bytesX[1] << 16) + (bytesX[2] << 8) + bytesX[3]) + - (bytesY[0] << 24) + (bytesY[1] << 16) + (bytesY[2] << 8) + bytesY[3]; - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override String ToString() - { - if (toString == null) - { - var result = new System.Text.StringBuilder(25); - result.AppendFormat(System.Globalization.CultureInfo.CurrentUICulture, "({0}, {1})", x, y); - toString = result.ToString(); - } - return toString; - } - - /// - /// Orders an array of three ResultPoints in an order [A,B,C] such that AB < AC and - /// BC < AC and the angle between BC and BA is less than 180 degrees. - /// - public static void orderBestPatterns(ResultPoint[] patterns) - { - // Find distances between pattern centers - float zeroOneDistance = distance(patterns[0], patterns[1]); - float oneTwoDistance = distance(patterns[1], patterns[2]); - float zeroTwoDistance = distance(patterns[0], patterns[2]); - - ResultPoint pointA, pointB, pointC; - // Assume one closest to other two is B; A and C will just be guesses at first - if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) - { - pointB = patterns[0]; - pointA = patterns[1]; - pointC = patterns[2]; - } - else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) - { - pointB = patterns[1]; - pointA = patterns[0]; - pointC = patterns[2]; - } - else - { - pointB = patterns[2]; - pointA = patterns[0]; - pointC = patterns[1]; - } - - // Use cross product to figure out whether A and C are correct or flipped. - // This asks whether BC x BA has a positive z component, which is the arrangement - // we want for A, B, C. If it's negative, then we've got it flipped around and - // should swap A and C. - if (crossProductZ(pointA, pointB, pointC) < 0.0f) - { - ResultPoint temp = pointA; - pointA = pointC; - pointC = temp; - } - - patterns[0] = pointA; - patterns[1] = pointB; - patterns[2] = pointC; - } - - - /// - /// distance between two points - /// - public static float distance(ResultPoint pattern1, ResultPoint pattern2) - { - return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y); - } - - /// - /// Returns the z component of the cross product between vectors BC and BA. - /// - private static float crossProductZ(ResultPoint pointA, ResultPoint pointB, ResultPoint pointC) - { - float bX = pointB.x; - float bY = pointB.y; - return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/ResultPointCallback.cs b/shadowsocks-csharp/3rd/zxing/ResultPointCallback.cs deleted file mode 100755 index 19c6f23a..00000000 --- a/shadowsocks-csharp/3rd/zxing/ResultPointCallback.cs +++ /dev/null @@ -1,26 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing -{ - /// Callback which is invoked when a possible result point (significant - /// point in the barcode image such as a corner) is found. - /// - /// - /// - /// - public delegate void ResultPointCallback(ResultPoint point); -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/WriterException.cs b/shadowsocks-csharp/3rd/zxing/WriterException.cs deleted file mode 100755 index f6cd3395..00000000 --- a/shadowsocks-csharp/3rd/zxing/WriterException.cs +++ /dev/null @@ -1,55 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing -{ - /// - /// A base class which covers the range of exceptions which may occur when encoding a barcode using - /// the Writer framework. - /// - /// dswitkin@google.com (Daniel Switkin) - [Serializable] - public sealed class WriterException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public WriterException() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The message. - public WriterException(String message) - :base(message) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The message. - /// The inner exc. - public WriterException(String message, Exception innerExc) - : base(message, innerExc) - { - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/BitArray.cs b/shadowsocks-csharp/3rd/zxing/common/BitArray.cs deleted file mode 100755 index 994d5ef5..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/BitArray.cs +++ /dev/null @@ -1,278 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.Common -{ - /// - /// A simple, fast array of bits, represented compactly by an array of ints internally. - /// - /// Sean Owen - public sealed class BitArray - { - private int[] bits; - private int size; - - public int Size - { - get - { - return size; - } - } - - public int SizeInBytes - { - get - { - return (size + 7) >> 3; - } - } - - public bool this[int i] - { - get - { - return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; - } - set - { - if (value) - bits[i >> 5] |= 1 << (i & 0x1F); - } - } - - public BitArray() - { - this.size = 0; - this.bits = new int[1]; - } - - public BitArray(int size) - { - if (size < 1) - { - throw new ArgumentException("size must be at least 1"); - } - this.size = size; - this.bits = makeArray(size); - } - - // For testing only - private BitArray(int[] bits, int size) - { - this.bits = bits; - this.size = size; - } - - private void ensureCapacity(int size) - { - if (size > bits.Length << 5) - { - int[] newBits = makeArray(size); - System.Array.Copy(bits, 0, newBits, 0, bits.Length); - bits = newBits; - } - } - - - private static int numberOfTrailingZeros(int num) - { - var index = (-num & num)%37; - if (index < 0) - index *= -1; - return _lookup[index]; - } - - private static readonly int[] _lookup = - { - 32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17, - 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18 - }; - - - /// Sets a block of 32 bits, starting at bit i. - /// - /// - /// first bit to set - /// - /// the new value of the next 32 bits. Note again that the least-significant bit - /// corresponds to bit i, the next-least-significant to i+1, and so on. - /// - public void setBulk(int i, int newBits) - { - bits[i >> 5] = newBits; - } - - - /// Clears all bits (sets to false). - public void clear() - { - int max = bits.Length; - for (int i = 0; i < max; i++) - { - bits[i] = 0; - } - } - - /// - /// Appends the bit. - /// - /// The bit. - public void appendBit(bool bit) - { - ensureCapacity(size + 1); - if (bit) - { - bits[size >> 5] |= 1 << (size & 0x1F); - } - size++; - } - - /// underlying array of ints. The first element holds the first 32 bits, and the least - /// significant bit is bit 0. - /// - public int[] Array - { - get { return bits; } - } - - /// - /// Appends the least-significant bits, from value, in order from most-significant to - /// least-significant. For example, appending 6 bits from 0x000001E will append the bits - /// 0, 1, 1, 1, 1, 0 in that order. - /// - /// The value. - /// The num bits. - public void appendBits(int value, int numBits) - { - if (numBits < 0 || numBits > 32) - { - throw new ArgumentException("Num bits must be between 0 and 32"); - } - ensureCapacity(size + numBits); - for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) - { - appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1); - } - } - - public void appendBitArray(BitArray other) - { - int otherSize = other.size; - ensureCapacity(size + otherSize); - for (int i = 0; i < otherSize; i++) - { - appendBit(other[i]); - } - } - - public void xor(BitArray other) - { - if (bits.Length != other.bits.Length) - { - throw new ArgumentException("Sizes don't match"); - } - for (int i = 0; i < bits.Length; i++) - { - // The last byte could be incomplete (i.e. not have 8 bits in - // it) but there is no problem since 0 XOR 0 == 0. - bits[i] ^= other.bits[i]; - } - } - - /// - /// Toes the bytes. - /// - /// first bit to start writing - /// array to write into. Bytes are written most-significant byte first. This is the opposite - /// of the internal representation, which is exposed by BitArray - /// position in array to start writing - /// how many bytes to write - public void toBytes(int bitOffset, byte[] array, int offset, int numBytes) - { - for (int i = 0; i < numBytes; i++) - { - int theByte = 0; - for (int j = 0; j < 8; j++) - { - if (this[bitOffset]) - { - theByte |= 1 << (7 - j); - } - bitOffset++; - } - array[offset + i] = (byte)theByte; - } - } - - private static int[] makeArray(int size) - { - return new int[(size + 31) >> 5]; - } - - /// - /// Determines whether the specified is equal to this instance. - /// - /// The to compare with this instance. - /// - /// true if the specified is equal to this instance; otherwise, false. - /// - public override bool Equals(Object o) - { - var other = o as BitArray; - if (other == null) - return false; - if (size != other.size) - return false; - for (var index = 0; index < size; index++) - { - if (bits[index] != other.bits[index]) - return false; - } - return true; - } - - /// - /// Returns a hash code for this instance. - /// - /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - /// - public override int GetHashCode() - { - var hash = size; - foreach (var bit in bits) - { - hash = 31 * hash + bit.GetHashCode(); - } - return hash; - } - - - /// - /// Erstellt ein neues Objekt, das eine Kopie der aktuellen Instanz darstellt. - /// - /// - /// Ein neues Objekt, das eine Kopie dieser Instanz darstellt. - /// - public object Clone() - { - return new BitArray((int[])bits.Clone(), size); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/BitMatrix.cs b/shadowsocks-csharp/3rd/zxing/common/BitMatrix.cs deleted file mode 100755 index 9b250548..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/BitMatrix.cs +++ /dev/null @@ -1,259 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.Common -{ - /// - ///

Represents a 2D matrix of bits. In function arguments below, and throughout the common - /// module, x is the column position, and y is the row position. The ordering is always x, y. - /// The origin is at the top-left.

- ///

Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins - /// with a new int. This is done intentionally so that we can copy out a row into a BitArray very - /// efficiently.

- ///

The ordering of bits is row-major. Within each int, the least significant bits are used first, - /// meaning they represent lower x values. This is compatible with BitArray's implementation.

- ///
- /// Sean Owen - /// dswitkin@google.com (Daniel Switkin) - public sealed partial class BitMatrix - { - private readonly int width; - private readonly int height; - private readonly int rowSize; - private readonly int[] bits; - - /// The width of the matrix - /// - public int Width - { - get - { - return width; - } - - } - /// The height of the matrix - /// - public int Height - { - get - { - return height; - } - - } - - // A helper to construct a square matrix. - public BitMatrix(int dimension) - : this(dimension, dimension) - { - } - - public BitMatrix(int width, int height) - { - if (width < 1 || height < 1) - { - throw new System.ArgumentException("Both dimensions must be greater than 0"); - } - this.width = width; - this.height = height; - this.rowSize = (width + 31) >> 5; - bits = new int[rowSize * height]; - } - - private BitMatrix(int width, int height, int rowSize, int[] bits) - { - this.width = width; - this.height = height; - this.rowSize = rowSize; - this.bits = bits; - } - - ///

Gets the requested bit, where true means black.

- /// - ///
- /// The horizontal component (i.e. which column) - /// - /// The vertical component (i.e. which row) - /// - /// value of given bit in matrix - /// - public bool this[int x, int y] - { - get - { - int offset = y * rowSize + (x >> 5); - return (((int)((uint)(bits[offset]) >> (x & 0x1f))) & 1) != 0; - } - set - { - if (value) - { - int offset = y * rowSize + (x >> 5); - bits[offset] |= 1 << (x & 0x1f); - } - } - } - - ///

Flips the given bit.

- /// - ///
- /// The horizontal component (i.e. which column) - /// - /// The vertical component (i.e. which row) - /// - public void flip(int x, int y) - { - int offset = y * rowSize + (x >> 5); - bits[offset] ^= 1 << (x & 0x1f); - } - - - ///

Sets a square region of the bit matrix to true.

- /// - ///
- /// The horizontal position to begin at (inclusive) - /// - /// The vertical position to begin at (inclusive) - /// - /// The width of the region - /// - /// The height of the region - /// - public void setRegion(int left, int top, int width, int height) - { - if (top < 0 || left < 0) - { - throw new System.ArgumentException("Left and top must be nonnegative"); - } - if (height < 1 || width < 1) - { - throw new System.ArgumentException("Height and width must be at least 1"); - } - int right = left + width; - int bottom = top + height; - if (bottom > this.height || right > this.width) - { - throw new System.ArgumentException("The region must fit inside the matrix"); - } - for (int y = top; y < bottom; y++) - { - int offset = y * rowSize; - for (int x = left; x < right; x++) - { - bits[offset + (x >> 5)] |= 1 << (x & 0x1f); - } - } - } - - /// A fast method to retrieve one row of data from the matrix as a BitArray. - /// - /// - /// The row to retrieve - /// - /// An optional caller-allocated BitArray, will be allocated if null or too small - /// - /// The resulting BitArray - this reference should always be used even when passing - /// your own row - /// - public BitArray getRow(int y, BitArray row) - { - if (row == null || row.Size < width) - { - row = new BitArray(width); - } - else - { - row.clear(); - } - int offset = y * rowSize; - for (int x = 0; x < rowSize; x++) - { - row.setBulk(x << 5, bits[offset + x]); - } - return row; - } - - /// - /// Sets the row. - /// - /// row to set - /// {@link BitArray} to copy from - public void setRow(int y, BitArray row) - { - Array.Copy(row.Array, 0, bits, y * rowSize, rowSize); - } - - - /// - /// This is useful in detecting a corner of a 'pure' barcode. - /// - /// {x,y} coordinate of top-left-most 1 bit, or null if it is all white - public int[] getTopLeftOnBit() - { - int bitsOffset = 0; - while (bitsOffset < bits.Length && bits[bitsOffset] == 0) - { - bitsOffset++; - } - if (bitsOffset == bits.Length) - { - return null; - } - int y = bitsOffset / rowSize; - int x = (bitsOffset % rowSize) << 5; - - int theBits = bits[bitsOffset]; - int bit = 0; - while ((theBits << (31 - bit)) == 0) - { - bit++; - } - x += bit; - return new[] { x, y }; - } - - public int[] getBottomRightOnBit() - { - int bitsOffset = bits.Length - 1; - while (bitsOffset >= 0 && bits[bitsOffset] == 0) - { - bitsOffset--; - } - if (bitsOffset < 0) - { - return null; - } - - int y = bitsOffset / rowSize; - int x = (bitsOffset % rowSize) << 5; - - int theBits = bits[bitsOffset]; - int bit = 31; - - while (((int)((uint)theBits >> bit)) == 0) // (theBits >>> bit) - { - bit--; - } - x += bit; - - return new int[] { x, y }; - } - - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/BitSource.cs b/shadowsocks-csharp/3rd/zxing/common/BitSource.cs deleted file mode 100755 index ba9156d2..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/BitSource.cs +++ /dev/null @@ -1,124 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.Common -{ - ///

This provides an easy abstraction to read bits at a time from a sequence of bytes, where the - /// number of bits read is not often a multiple of 8.

- /// - ///

This class is thread-safe but not reentrant. Unless the caller modifies the bytes array - /// it passed in, in which case all bets are off.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class BitSource - { - private readonly byte[] bytes; - private int byteOffset; - private int bitOffset; - - /// bytes from which this will read bits. Bits will be read from the first byte first. - /// Bits are read within a byte from most-significant to least-significant bit. - /// - public BitSource(byte[] bytes) - { - this.bytes = bytes; - } - - /// - /// index of next bit in current byte which would be read by the next call to {@link #readBits(int)}. - /// - public int BitOffset - { - get { return bitOffset; } - } - - /// - /// index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}. - /// - public int ByteOffset - { - get { return byteOffset; } - } - - /// number of bits to read - /// - /// int representing the bits read. The bits will appear as the least-significant - /// bits of the int - /// - /// if numBits isn't in [1,32] or more than is available - public int readBits(int numBits) - { - if (numBits < 1 || numBits > 32 || numBits > available()) - { - throw new ArgumentException(numBits.ToString(), "numBits"); - } - - int result = 0; - - // First, read remainder from current byte - if (bitOffset > 0) - { - int bitsLeft = 8 - bitOffset; - int toRead = numBits < bitsLeft ? numBits : bitsLeft; - int bitsToNotRead = bitsLeft - toRead; - int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; - result = (bytes[byteOffset] & mask) >> bitsToNotRead; - numBits -= toRead; - bitOffset += toRead; - if (bitOffset == 8) - { - bitOffset = 0; - byteOffset++; - } - } - - // Next read whole bytes - if (numBits > 0) - { - while (numBits >= 8) - { - result = (result << 8) | (bytes[byteOffset] & 0xFF); - byteOffset++; - numBits -= 8; - } - - // Finally read a partial byte - if (numBits > 0) - { - int bitsToNotRead = 8 - numBits; - int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; - result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); - bitOffset += numBits; - } - } - - return result; - } - - /// number of bits that can be read successfully - /// - public int available() - { - return 8 * (bytes.Length - byteOffset) - bitOffset; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/DecoderResult.cs b/shadowsocks-csharp/3rd/zxing/common/DecoderResult.cs deleted file mode 100755 index 024930f2..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/DecoderResult.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; - -namespace ZXing.Common -{ - /// - /// Encapsulates the result of decoding a matrix of bits. This typically - /// applies to 2D barcode formats. For now it contains the raw bytes obtained, - /// as well as a String interpretation of those bytes, if applicable. - /// Sean Owen - /// - public sealed class DecoderResult - { - public byte[] RawBytes { get; private set; } - - public String Text { get; private set; } - - public IList ByteSegments { get; private set; } - - public String ECLevel { get; private set; } - - public bool StructuredAppend - { - get { return StructuredAppendParity >= 0 && StructuredAppendSequenceNumber >= 0; } - } - - public int ErrorsCorrected { get; set; } - - public int StructuredAppendSequenceNumber { get; private set; } - - public int Erasures { get; set; } - - public int StructuredAppendParity { get; private set; } - - /// - /// Miscellanseous data value for the various decoders - /// - /// The other. - public object Other { get; set; } - - public DecoderResult(byte[] rawBytes, String text, IList byteSegments, String ecLevel) - : this(rawBytes, text, byteSegments, ecLevel, -1, -1) - { - } - - public DecoderResult(byte[] rawBytes, String text, IList byteSegments, String ecLevel, int saSequence, int saParity) - { - if (rawBytes == null && text == null) - { - throw new ArgumentException(); - } - RawBytes = rawBytes; - Text = text; - ByteSegments = byteSegments; - ECLevel = ecLevel; - StructuredAppendParity = saParity; - StructuredAppendSequenceNumber = saSequence; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/DefaultGridSampler.cs b/shadowsocks-csharp/3rd/zxing/common/DefaultGridSampler.cs deleted file mode 100755 index b3afaf8e..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/DefaultGridSampler.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; - -namespace ZXing.Common -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class DefaultGridSampler : GridSampler - { - public override BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) - { - PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral( - p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, - p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); - return sampleGrid(image, dimensionX, dimensionY, transform); - } - - public override BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) - { - if (dimensionX <= 0 || dimensionY <= 0) - { - return null; - } - BitMatrix bits = new BitMatrix(dimensionX, dimensionY); - float[] points = new float[dimensionX << 1]; - for (int y = 0; y < dimensionY; y++) - { - int max = points.Length; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float iValue = (float)y + 0.5f; - for (int x = 0; x < max; x += 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - points[x] = (float)(x >> 1) + 0.5f; - points[x + 1] = iValue; - } - transform.transformPoints(points); - // Quick check to see if points transformed to something inside the image; - // sufficient to check the endpoints - if (!checkAndNudgePoints(image, points)) - return null; - try - { - for (int x = 0; x < max; x += 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - bits[x >> 1, y] = image[(int)points[x], (int)points[x + 1]]; - } - } - catch (System.IndexOutOfRangeException) - { - // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting - // transform gets "twisted" such that it maps a straight line of points to a set of points - // whose endpoints are in bounds, but others are not. There is probably some mathematical - // way to detect this about the transformation that I don't know yet. - // This results in an ugly runtime exception despite our clever checks above -- can't have - // that. We could check each point's coordinates but that feels duplicative. We settle for - // catching and wrapping ArrayIndexOutOfBoundsException. - return null; - } - } - return bits; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/DetectorResult.cs b/shadowsocks-csharp/3rd/zxing/common/DetectorResult.cs deleted file mode 100755 index 0f99b9ba..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/DetectorResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.Common -{ - ///

Encapsulates the result of detecting a barcode in an image. This includes the raw - /// matrix of black/white pixels corresponding to the barcode, and possibly points of interest - /// in the image, like the location of finder patterns or corners of the barcode in the image.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public class DetectorResult - { - public BitMatrix Bits { get; private set; } - public ResultPoint[] Points { get; private set; } - - public DetectorResult(BitMatrix bits, ResultPoint[] points) - { - Bits = bits; - Points = points; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/GlobalHistogramBinarizer.cs b/shadowsocks-csharp/3rd/zxing/common/GlobalHistogramBinarizer.cs deleted file mode 100755 index 91f20d55..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/GlobalHistogramBinarizer.cs +++ /dev/null @@ -1,243 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.Common -{ - /// This Binarizer implementation uses the old ZXing global histogram approach. It is suitable - /// for low-end mobile devices which don't have enough CPU or memory to use a local thresholding - /// algorithm. However, because it picks a global black point, it cannot handle difficult shadows - /// and gradients. - /// - /// Faster mobile devices and all desktop applications should probably use HybridBinarizer instead. - /// - /// dswitkin@google.com (Daniel Switkin) - /// Sean Owen - /// - public class GlobalHistogramBinarizer : Binarizer - { - private const int LUMINANCE_BITS = 5; - private const int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; - private const int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; - private static readonly byte[] EMPTY = new byte[0]; - - private byte[] luminances; - private readonly int[] buckets; - - /// - /// Initializes a new instance of the class. - /// - /// The source. - public GlobalHistogramBinarizer(LuminanceSource source) - : base(source) - { - luminances = EMPTY; - buckets = new int[LUMINANCE_BUCKETS]; - } - - /// - /// Applies simple sharpening to the row data to improve performance of the 1D Readers. - /// - /// - /// - /// - public override BitArray getBlackRow(int y, BitArray row) - { - LuminanceSource source = LuminanceSource; - int width = source.Width; - if (row == null || row.Size < width) - { - row = new BitArray(width); - } - else - { - row.clear(); - } - - initArrays(width); - byte[] localLuminances = source.getRow(y, luminances); - int[] localBuckets = buckets; - for (int x = 0; x < width; x++) - { - int pixel = localLuminances[x] & 0xff; - localBuckets[pixel >> LUMINANCE_SHIFT]++; - } - int blackPoint; - if (!estimateBlackPoint(localBuckets, out blackPoint)) - return null; - - int left = localLuminances[0] & 0xff; - int center = localLuminances[1] & 0xff; - for (int x = 1; x < width - 1; x++) - { - int right = localLuminances[x + 1] & 0xff; - // A simple -1 4 -1 box filter with a weight of 2. - int luminance = ((center << 2) - left - right) >> 1; - row[x] = (luminance < blackPoint); - left = center; - center = right; - } - return row; - } - - /// - /// Does not sharpen the data, as this call is intended to only be used by 2D Readers. - /// - override public BitMatrix BlackMatrix - { - get - { - LuminanceSource source = LuminanceSource; - byte[] localLuminances; - - int width = source.Width; - int height = source.Height; - BitMatrix matrix = new BitMatrix(width, height); - - // Quickly calculates the histogram by sampling four rows from the image. This proved to be - // more robust on the blackbox tests than sampling a diagonal as we used to do. - initArrays(width); - int[] localBuckets = buckets; - for (int y = 1; y < 5; y++) - { - int row = height * y / 5; - localLuminances = source.getRow(row, luminances); - int right = (width << 2) / 5; - for (int x = width / 5; x < right; x++) - { - int pixel = localLuminances[x] & 0xff; - localBuckets[pixel >> LUMINANCE_SHIFT]++; - } - } - int blackPoint; - if (!estimateBlackPoint(localBuckets, out blackPoint)) - return null; - - // We delay reading the entire image luminance until the black point estimation succeeds. - // Although we end up reading four rows twice, it is consistent with our motto of - // "fail quickly" which is necessary for continuous scanning. - localLuminances = source.Matrix; - for (int y = 0; y < height; y++) - { - int offset = y * width; - for (int x = 0; x < width; x++) - { - int pixel = localLuminances[offset + x] & 0xff; - matrix[x, y] = (pixel < blackPoint); - } - } - - return matrix; - } - } - - /// - /// Creates a new object with the same type as this Binarizer implementation, but with pristine - /// state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache - /// of 1 bit data. See Effective Java for why we can't use Java's clone() method. - /// - /// The LuminanceSource this Binarizer will operate on. - /// - /// A new concrete Binarizer implementation object. - /// - public override Binarizer createBinarizer(LuminanceSource source) - { - return new GlobalHistogramBinarizer(source); - } - - private void initArrays(int luminanceSize) - { - if (luminances.Length < luminanceSize) - { - luminances = new byte[luminanceSize]; - } - for (int x = 0; x < LUMINANCE_BUCKETS; x++) - { - buckets[x] = 0; - } - } - - private static bool estimateBlackPoint(int[] buckets, out int blackPoint) - { - blackPoint = 0; - // Find the tallest peak in the histogram. - int numBuckets = buckets.Length; - int maxBucketCount = 0; - int firstPeak = 0; - int firstPeakSize = 0; - for (int x = 0; x < numBuckets; x++) - { - if (buckets[x] > firstPeakSize) - { - firstPeak = x; - firstPeakSize = buckets[x]; - } - if (buckets[x] > maxBucketCount) - { - maxBucketCount = buckets[x]; - } - } - - // Find the second-tallest peak which is somewhat far from the tallest peak. - int secondPeak = 0; - int secondPeakScore = 0; - for (int x = 0; x < numBuckets; x++) - { - int distanceToBiggest = x - firstPeak; - // Encourage more distant second peaks by multiplying by square of distance. - int score = buckets[x] * distanceToBiggest * distanceToBiggest; - if (score > secondPeakScore) - { - secondPeak = x; - secondPeakScore = score; - } - } - - // Make sure firstPeak corresponds to the black peak. - if (firstPeak > secondPeak) - { - int temp = firstPeak; - firstPeak = secondPeak; - secondPeak = temp; - } - - // If there is too little contrast in the image to pick a meaningful black point, throw rather - // than waste time trying to decode the image, and risk false positives. - // TODO: It might be worth comparing the brightest and darkest pixels seen, rather than the - // two peaks, to determine the contrast. - if (secondPeak - firstPeak <= numBuckets >> 4) - { - return false; - } - - // Find a valley between them that is low and closer to the white peak. - int bestValley = secondPeak - 1; - int bestValleyScore = -1; - for (int x = secondPeak - 1; x > firstPeak; x--) - { - int fromFirst = x - firstPeak; - int score = fromFirst*fromFirst*(secondPeak - x)*(maxBucketCount - buckets[x]); - if (score > bestValleyScore) - { - bestValley = x; - bestValleyScore = score; - } - } - - blackPoint = bestValley << LUMINANCE_SHIFT; - return true; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/GridSampler.cs b/shadowsocks-csharp/3rd/zxing/common/GridSampler.cs deleted file mode 100755 index a1bffa99..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/GridSampler.cs +++ /dev/null @@ -1,192 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.Common -{ - /// Implementations of this class can, given locations of finder patterns for a QR code in an - /// image, sample the right points in the image to reconstruct the QR code, accounting for - /// perspective distortion. It is abstracted since it is relatively expensive and should be allowed - /// to take advantage of platform-specific optimized implementations, like Sun's Java Advanced - /// Imaging library, but which may not be available in other environments such as J2ME, and vice - /// versa. - /// - /// The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)} - /// with an instance of a class which implements this interface. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class GridSampler - { - /// the current implementation of {@link GridSampler} - /// - public static GridSampler Instance - { - get - { - return gridSampler; - } - - } - - private static GridSampler gridSampler = new DefaultGridSampler(); - - /// Sets the implementation of {@link GridSampler} used by the library. One global - /// instance is stored, which may sound problematic. But, the implementation provided - /// ought to be appropriate for the entire platform, and all uses of this library - /// in the whole lifetime of the JVM. For instance, an Android activity can swap in - /// an implementation that takes advantage of native platform libraries. - /// - /// - /// The platform-specific object to install. - /// - public static void setGridSampler(GridSampler newGridSampler) - { - if (newGridSampler == null) - { - throw new System.ArgumentException(); - } - gridSampler = newGridSampler; - } - - ///

Samples an image for a square matrix of bits of the given dimension. This is used to extract - /// the black/white modules of a 2D barcode like a QR Code found in an image. Because this barcode - /// may be rotated or perspective-distorted, the caller supplies four points in the source image - /// that define known points in the barcode, so that the image may be sampled appropriately.

- /// - ///

The last eight "from" parameters are four X/Y coordinate pairs of locations of points in - /// the image that define some significant points in the image to be sample. For example, - /// these may be the location of finder pattern in a QR Code.

- /// - ///

The first eight "to" parameters are four X/Y coordinate pairs measured in the destination - /// {@link BitMatrix}, from the top left, where the known points in the image given by the "from" - /// parameters map to.

- /// - ///

These 16 parameters define the transformation needed to sample the image.

- /// - ///
- /// image to sample - /// - /// width/height of {@link BitMatrix} to sample from image - /// - /// {@link BitMatrix} representing a grid of points sampled from the image within a region - /// defined by the "from" parameters - /// - /// ReaderException if image can't be sampled, for example, if the transformation defined - /// by the given points is invalid or results in sampling outside the image boundaries - /// - public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY); - - public virtual BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) - { - throw new System.NotSupportedException(); - } - - - ///

Checks a set of points that have been transformed to sample points on an image against - /// the image's dimensions to see if the point are even within the image.

- /// - ///

This method will actually "nudge" the endpoints back onto the image if they are found to be - /// barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder - /// patterns in an image where the QR Code runs all the way to the image border.

- /// - ///

For efficiency, the method will check points from either end of the line until one is found - /// to be within the image. Because the set of points are assumed to be linear, this is valid.

- /// - ///
- /// image into which the points should map - /// - /// actual points in x1,y1,...,xn,yn form - /// - protected internal static bool checkAndNudgePoints(BitMatrix image, float[] points) - { - int width = image.Width; - int height = image.Height; - // Check and nudge points from start until we see some that are OK: - bool nudged = true; - for (int offset = 0; offset < points.Length && nudged; offset += 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int x = (int)points[offset]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int y = (int)points[offset + 1]; - if (x < -1 || x > width || y < -1 || y > height) - { - return false; - } - nudged = false; - if (x == -1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == -1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - // Check and nudge points from end: - nudged = true; - for (int offset = points.Length - 2; offset >= 0 && nudged; offset -= 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int x = (int)points[offset]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int y = (int)points[offset + 1]; - if (x < -1 || x > width || y < -1 || y > height) - { - return false; - } - nudged = false; - if (x == -1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == -1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - - return true; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/HybridBinarizer.cs b/shadowsocks-csharp/3rd/zxing/common/HybridBinarizer.cs deleted file mode 100755 index d8185505..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/HybridBinarizer.cs +++ /dev/null @@ -1,288 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.Common -{ - /// This class implements a local thresholding algorithm, which while slower than the - /// GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for - /// high frequency images of barcodes with black data on white backgrounds. For this application, - /// it does a much better job than a global blackpoint with severe shadows and gradients. - /// However it tends to produce artifacts on lower frequency images and is therefore not - /// a good general purpose binarizer for uses outside ZXing. - /// - /// This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers, - /// and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already - /// inherently local, and only fails for horizontal gradients. We can revisit that problem later, - /// but for now it was not a win to use local blocks for 1D. - /// - /// This Binarizer is the default for the unit tests and the recommended class for library users. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class HybridBinarizer : GlobalHistogramBinarizer - { - override public BitMatrix BlackMatrix - { - get - { - binarizeEntireImage(); - return matrix; - } - } - - // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels. - // So this is the smallest dimension in each axis we can accept. - private const int BLOCK_SIZE_POWER = 3; - private const int BLOCK_SIZE = 1 << BLOCK_SIZE_POWER; // ...0100...00 - private const int BLOCK_SIZE_MASK = BLOCK_SIZE - 1; // ...0011...11 - private const int MINIMUM_DIMENSION = 40; - private const int MIN_DYNAMIC_RANGE = 24; - - private BitMatrix matrix = null; - - public HybridBinarizer(LuminanceSource source) - : base(source) - { - } - - public override Binarizer createBinarizer(LuminanceSource source) - { - return new HybridBinarizer(source); - } - - /// - /// Calculates the final BitMatrix once for all requests. This could be called once from the - /// constructor instead, but there are some advantages to doing it lazily, such as making - /// profiling easier, and not doing heavy lifting when callers don't expect it. - /// - private void binarizeEntireImage() - { - if (matrix == null) - { - LuminanceSource source = LuminanceSource; - int width = source.Width; - int height = source.Height; - if (width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION) - { - byte[] luminances = source.Matrix; - - int subWidth = width >> BLOCK_SIZE_POWER; - if ((width & BLOCK_SIZE_MASK) != 0) - { - subWidth++; - } - int subHeight = height >> BLOCK_SIZE_POWER; - if ((height & BLOCK_SIZE_MASK) != 0) - { - subHeight++; - } - int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height); - - var newMatrix = new BitMatrix(width, height); - calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix); - matrix = newMatrix; - } - else - { - // If the image is too small, fall back to the global histogram approach. - matrix = base.BlackMatrix; - } - } - } - - /// - /// For each 8x8 block in the image, calculate the average black point using a 5x5 grid - /// of the blocks around it. Also handles the corner cases (fractional blocks are computed based - /// on the last 8 pixels in the row/column which are also used in the previous block). - /// - /// The luminances. - /// Width of the sub. - /// Height of the sub. - /// The width. - /// The height. - /// The black points. - /// The matrix. - private static void calculateThresholdForBlock(byte[] luminances, int subWidth, int subHeight, int width, int height, int[][] blackPoints, BitMatrix matrix) - { - for (int y = 0; y < subHeight; y++) - { - int yoffset = y << BLOCK_SIZE_POWER; - int maxYOffset = height - BLOCK_SIZE; - if (yoffset > maxYOffset) - { - yoffset = maxYOffset; - } - for (int x = 0; x < subWidth; x++) - { - int xoffset = x << BLOCK_SIZE_POWER; - int maxXOffset = width - BLOCK_SIZE; - if (xoffset > maxXOffset) - { - xoffset = maxXOffset; - } - int left = cap(x, 2, subWidth - 3); - int top = cap(y, 2, subHeight - 3); - int sum = 0; - for (int z = -2; z <= 2; z++) - { - int[] blackRow = blackPoints[top + z]; - sum += blackRow[left - 2]; - sum += blackRow[left - 1]; - sum += blackRow[left]; - sum += blackRow[left + 1]; - sum += blackRow[left + 2]; - } - int average = sum / 25; - thresholdBlock(luminances, xoffset, yoffset, average, width, matrix); - } - } - } - - private static int cap(int value, int min, int max) - { - return value < min ? min : value > max ? max : value; - } - - /// - /// Applies a single threshold to an 8x8 block of pixels. - /// - /// The luminances. - /// The xoffset. - /// The yoffset. - /// The threshold. - /// The stride. - /// The matrix. - private static void thresholdBlock(byte[] luminances, int xoffset, int yoffset, int threshold, int stride, BitMatrix matrix) - { - int offset = (yoffset * stride) + xoffset; - for (int y = 0; y < BLOCK_SIZE; y++, offset += stride) - { - for (int x = 0; x < BLOCK_SIZE; x++) - { - int pixel = luminances[offset + x] & 0xff; - // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0. - matrix[xoffset + x, yoffset + y] = (pixel <= threshold); - } - } - } - - /// - /// Calculates a single black point for each 8x8 block of pixels and saves it away. - /// See the following thread for a discussion of this algorithm: - /// http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0 - /// - /// The luminances. - /// Width of the sub. - /// Height of the sub. - /// The width. - /// The height. - /// - private static int[][] calculateBlackPoints(byte[] luminances, int subWidth, int subHeight, int width, int height) - { - int[][] blackPoints = new int[subHeight][]; - for (int i = 0; i < subHeight; i++) - { - blackPoints[i] = new int[subWidth]; - } - - for (int y = 0; y < subHeight; y++) - { - int yoffset = y << BLOCK_SIZE_POWER; - int maxYOffset = height - BLOCK_SIZE; - if (yoffset > maxYOffset) - { - yoffset = maxYOffset; - } - for (int x = 0; x < subWidth; x++) - { - int xoffset = x << BLOCK_SIZE_POWER; - int maxXOffset = width - BLOCK_SIZE; - if (xoffset > maxXOffset) - { - xoffset = maxXOffset; - } - int sum = 0; - int min = 0xFF; - int max = 0; - for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width) - { - for (int xx = 0; xx < BLOCK_SIZE; xx++) - { - int pixel = luminances[offset + xx] & 0xFF; - // still looking for good contrast - sum += pixel; - if (pixel < min) - { - min = pixel; - } - if (pixel > max) - { - max = pixel; - } - } - // short-circuit min/max tests once dynamic range is met - if (max - min > MIN_DYNAMIC_RANGE) - { - // finish the rest of the rows quickly - for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width) - { - for (int xx = 0; xx < BLOCK_SIZE; xx++) - { - sum += luminances[offset + xx] & 0xFF; - } - } - } - } - - // The default estimate is the average of the values in the block. - int average = sum >> (BLOCK_SIZE_POWER * 2); - if (max - min <= MIN_DYNAMIC_RANGE) - { - // If variation within the block is low, assume this is a block with only light or only - // dark pixels. In that case we do not want to use the average, as it would divide this - // low contrast area into black and white pixels, essentially creating data out of noise. - // - // The default assumption is that the block is light/background. Since no estimate for - // the level of dark pixels exists locally, use half the min for the block. - average = min >> 1; - - if (y > 0 && x > 0) - { - // Correct the "white background" assumption for blocks that have neighbors by comparing - // the pixels in this block to the previously calculated black points. This is based on - // the fact that dark barcode symbology is always surrounded by some amount of light - // background for which reasonable black point estimates were made. The bp estimated at - // the boundaries is used for the interior. - - // The (min < bp) is arbitrary but works better than other heuristics that were tried. - int averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + - blackPoints[y - 1][x - 1]) >> 2; - if (min < averageNeighborBlackPoint) - { - average = averageNeighborBlackPoint; - } - } - } - blackPoints[y][x] = average; - } - } - return blackPoints; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/PerspectiveTransform.cs b/shadowsocks-csharp/3rd/zxing/common/PerspectiveTransform.cs deleted file mode 100755 index 3515ddd8..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/PerspectiveTransform.cs +++ /dev/null @@ -1,159 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.Common -{ - ///

This class implements a perspective transform in two dimensions. Given four source and four - /// destination points, it will compute the transformation implied between them. The code is based - /// directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class PerspectiveTransform - { - private float a11; - private float a12; - private float a13; - private float a21; - private float a22; - private float a23; - private float a31; - private float a32; - private float a33; - - private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33) - { - this.a11 = a11; - this.a12 = a12; - this.a13 = a13; - this.a21 = a21; - this.a22 = a22; - this.a23 = a23; - this.a31 = a31; - this.a32 = a32; - this.a33 = a33; - } - - public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p) - { - - PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); - PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); - return sToQ.times(qToS); - } - - public void transformPoints(float[] points) - { - int max = points.Length; - float a11 = this.a11; - float a12 = this.a12; - float a13 = this.a13; - float a21 = this.a21; - float a22 = this.a22; - float a23 = this.a23; - float a31 = this.a31; - float a32 = this.a32; - float a33 = this.a33; - for (int i = 0; i < max; i += 2) - { - float x = points[i]; - float y = points[i + 1]; - float denominator = a13 * x + a23 * y + a33; - points[i] = (a11 * x + a21 * y + a31) / denominator; - points[i + 1] = (a12 * x + a22 * y + a32) / denominator; - } - } - - /// Convenience method, not optimized for performance. - public void transformPoints(float[] xValues, float[] yValues) - { - int n = xValues.Length; - for (int i = 0; i < n; i++) - { - float x = xValues[i]; - float y = yValues[i]; - float denominator = a13 * x + a23 * y + a33; - xValues[i] = (a11 * x + a21 * y + a31) / denominator; - yValues[i] = (a12 * x + a22 * y + a32) / denominator; - } - } - - public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, - float x1, float y1, - float x2, float y2, - float x3, float y3) - { - float dx3 = x0 - x1 + x2 - x3; - float dy3 = y0 - y1 + y2 - y3; - if (dx3 == 0.0f && dy3 == 0.0f) - { - // Affine - return new PerspectiveTransform(x1 - x0, x2 - x1, x0, - y1 - y0, y2 - y1, y0, - 0.0f, 0.0f, 1.0f); - } - else - { - float dx1 = x1 - x2; - float dx2 = x3 - x2; - float dy1 = y1 - y2; - float dy2 = y3 - y2; - float denominator = dx1*dy2 - dx2*dy1; - float a13 = (dx3*dy2 - dx2*dy3)/denominator; - float a23 = (dx1*dy3 - dx3*dy1)/denominator; - return new PerspectiveTransform(x1 - x0 + a13*x1, x3 - x0 + a23*x3, x0, - y1 - y0 + a13*y1, y3 - y0 + a23*y3, y0, - a13, a23, 1.0f); - } - } - - public static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - { - // Here, the adjoint serves as the inverse: - return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); - } - - internal PerspectiveTransform buildAdjoint() - { - // Adjoint is the transpose of the cofactor matrix: - return new PerspectiveTransform(a22 * a33 - a23 * a32, - a23 * a31 - a21 * a33, - a21 * a32 - a22 * a31, - a13 * a32 - a12 * a33, - a11 * a33 - a13 * a31, - a12 * a31 - a11 * a32, - a12 * a23 - a13 * a22, - a13 * a21 - a11 * a23, - a11 * a22 - a12 * a21); - } - - internal PerspectiveTransform times(PerspectiveTransform other) - { - return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, - a11 * other.a21 + a21 * other.a22 + a31 * other.a23, - a11 * other.a31 + a21 * other.a32 + a31 * other.a33, - a12 * other.a11 + a22 * other.a12 + a32 * other.a13, - a12 * other.a21 + a22 * other.a22 + a32 * other.a23, - a12 * other.a31 + a22 * other.a32 + a32 * other.a33, - a13 * other.a11 + a23 * other.a12 + a33 * other.a13, - a13 * other.a21 + a23 * other.a22 + a33 * other.a23, - a13 * other.a31 + a23 * other.a32 + a33 * other.a33); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/StringUtils.cs b/shadowsocks-csharp/3rd/zxing/common/StringUtils.cs deleted file mode 100755 index 55b5ec91..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/StringUtils.cs +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Text; - -namespace ZXing.Common -{ - /// - /// Common string-related functions. - /// - /// Sean Owen - /// Alex Dupre - public static class StringUtils - { -#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || WINDOWS_PHONE80 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE) - private const String PLATFORM_DEFAULT_ENCODING = "UTF-8"; -#else - private static String PLATFORM_DEFAULT_ENCODING = Encoding.Default.WebName; -#endif - public static String SHIFT_JIS = "SJIS"; - public static String GB2312 = "GB2312"; - private const String EUC_JP = "EUC-JP"; - private const String UTF8 = "UTF-8"; - private const String ISO88591 = "ISO-8859-1"; - private static readonly bool ASSUME_SHIFT_JIS = - String.Compare(SHIFT_JIS, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0 || - String.Compare(EUC_JP, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0; - - /// - /// Guesses the encoding. - /// - /// bytes encoding a string, whose encoding should be guessed - /// decode hints if applicable - /// name of guessed encoding; at the moment will only guess one of: - /// {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform - /// default encoding if none of these can possibly be correct - public static String guessEncoding(byte[] bytes, IDictionary hints) - { - if (hints != null && hints.ContainsKey(DecodeHintType.CHARACTER_SET)) - { - String characterSet = (String)hints[DecodeHintType.CHARACTER_SET]; - if (characterSet != null) - { - return characterSet; - } - } - - // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, - // which should be by far the most common encodings. - int length = bytes.Length; - bool canBeISO88591 = true; - bool canBeShiftJIS = true; - bool canBeUTF8 = true; - int utf8BytesLeft = 0; - //int utf8LowChars = 0; - int utf2BytesChars = 0; - int utf3BytesChars = 0; - int utf4BytesChars = 0; - int sjisBytesLeft = 0; - //int sjisLowChars = 0; - int sjisKatakanaChars = 0; - //int sjisDoubleBytesChars = 0; - int sjisCurKatakanaWordLength = 0; - int sjisCurDoubleBytesWordLength = 0; - int sjisMaxKatakanaWordLength = 0; - int sjisMaxDoubleBytesWordLength = 0; - //int isoLowChars = 0; - //int isoHighChars = 0; - int isoHighOther = 0; - - bool utf8bom = bytes.Length > 3 && - bytes[0] == 0xEF && - bytes[1] == 0xBB && - bytes[2] == 0xBF; - - for (int i = 0; - i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); - i++) - { - - int value = bytes[i] & 0xFF; - - // UTF-8 stuff - if (canBeUTF8) - { - if (utf8BytesLeft > 0) - { - if ((value & 0x80) == 0) - { - canBeUTF8 = false; - } - else - { - utf8BytesLeft--; - } - } - else if ((value & 0x80) != 0) - { - if ((value & 0x40) == 0) - { - canBeUTF8 = false; - } - else - { - utf8BytesLeft++; - if ((value & 0x20) == 0) - { - utf2BytesChars++; - } - else - { - utf8BytesLeft++; - if ((value & 0x10) == 0) - { - utf3BytesChars++; - } - else - { - utf8BytesLeft++; - if ((value & 0x08) == 0) - { - utf4BytesChars++; - } - else - { - canBeUTF8 = false; - } - } - } - } - } //else { - //utf8LowChars++; - //} - } - - // ISO-8859-1 stuff - if (canBeISO88591) - { - if (value > 0x7F && value < 0xA0) - { - canBeISO88591 = false; - } - else if (value > 0x9F) - { - if (value < 0xC0 || value == 0xD7 || value == 0xF7) - { - isoHighOther++; - } //else { - //isoHighChars++; - //} - } //else { - //isoLowChars++; - //} - } - - // Shift_JIS stuff - if (canBeShiftJIS) - { - if (sjisBytesLeft > 0) - { - if (value < 0x40 || value == 0x7F || value > 0xFC) - { - canBeShiftJIS = false; - } - else - { - sjisBytesLeft--; - } - } - else if (value == 0x80 || value == 0xA0 || value > 0xEF) - { - canBeShiftJIS = false; - } - else if (value > 0xA0 && value < 0xE0) - { - sjisKatakanaChars++; - sjisCurDoubleBytesWordLength = 0; - sjisCurKatakanaWordLength++; - if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) - { - sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength; - } - } - else if (value > 0x7F) - { - sjisBytesLeft++; - //sjisDoubleBytesChars++; - sjisCurKatakanaWordLength = 0; - sjisCurDoubleBytesWordLength++; - if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) - { - sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength; - } - } - else - { - //sjisLowChars++; - sjisCurKatakanaWordLength = 0; - sjisCurDoubleBytesWordLength = 0; - } - } - } - - if (canBeUTF8 && utf8BytesLeft > 0) - { - canBeUTF8 = false; - } - if (canBeShiftJIS && sjisBytesLeft > 0) - { - canBeShiftJIS = false; - } - - // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done - if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) - { - return UTF8; - } - // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done - if (canBeShiftJIS && (ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) - { - return SHIFT_JIS; - } - // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is: - // - If we saw - // - only two consecutive katakana chars in the whole text, or - // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1, - // - then we conclude Shift_JIS, else ISO-8859-1 - if (canBeISO88591 && canBeShiftJIS) - { - return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= length - ? SHIFT_JIS : ISO88591; - } - - // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding - if (canBeISO88591) - { - return ISO88591; - } - if (canBeShiftJIS) - { - return SHIFT_JIS; - } - if (canBeUTF8) - { - return UTF8; - } - // Otherwise, we take a wild guess with platform encoding - return PLATFORM_DEFAULT_ENCODING; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/detector/MathUtils.cs b/shadowsocks-csharp/3rd/zxing/common/detector/MathUtils.cs deleted file mode 100755 index 8782202f..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/detector/MathUtils.cs +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2012 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; - -namespace ZXing.Common.Detector -{ - public static class MathUtils - { - /// - /// Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its - /// argument to the nearest int, where x.5 rounds up to x+1. - /// - /// The d. - /// - public static int round(float d) - { - return (int)(d + 0.5f); - } - - public static float distance(float aX, float aY, float bX, float bY) - { - float xDiff = aX - bX; - float yDiff = aY - bY; - return (float)Math.Sqrt(xDiff * xDiff + yDiff * yDiff); - } - - public static float distance(int aX, int aY, int bX, int bY) - { - int xDiff = aX - bX; - int yDiff = aY - bY; - return (float)Math.Sqrt(xDiff * xDiff + yDiff * yDiff); - } - } -} diff --git a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGF.cs b/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGF.cs deleted file mode 100755 index 276dc999..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGF.cs +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; - -namespace ZXing.Common.ReedSolomon -{ - /// - ///

This class contains utility methods for performing mathematical operations over - /// the Galois Fields. Operations use a given primitive polynomial in calculations.

- ///

Throughout this package, elements of the GF are represented as an {@code int} - /// for convenience and speed (but at the cost of memory). - ///

- ///
- /// Sean Owen - public sealed class GenericGF - { - public static GenericGF AZTEC_DATA_12 = new GenericGF(0x1069, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1 - public static GenericGF AZTEC_DATA_10 = new GenericGF(0x409, 1024, 1); // x^10 + x^3 + 1 - public static GenericGF AZTEC_DATA_6 = new GenericGF(0x43, 64, 1); // x^6 + x + 1 - public static GenericGF AZTEC_PARAM = new GenericGF(0x13, 16, 1); // x^4 + x + 1 - public static GenericGF QR_CODE_FIELD_256 = new GenericGF(0x011D, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1 - public static GenericGF DATA_MATRIX_FIELD_256 = new GenericGF(0x012D, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1 - public static GenericGF AZTEC_DATA_8 = DATA_MATRIX_FIELD_256; - public static GenericGF MAXICODE_FIELD_64 = AZTEC_DATA_6; - - private const int INITIALIZATION_THRESHOLD = 0; - - private int[] expTable; - private int[] logTable; - private GenericGFPoly zero; - private GenericGFPoly one; - private readonly int size; - private readonly int primitive; - private readonly int generatorBase; - private bool initialized = false; - - /// - /// Create a representation of GF(size) using the given primitive polynomial. - /// - /// irreducible polynomial whose coefficients are represented by - /// * the bits of an int, where the least-significant bit represents the constant - /// * coefficient - /// the size of the field - /// the factor b in the generator polynomial can be 0- or 1-based - /// * (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))). - /// * In most cases it should be 1, but for QR code it is 0. - public GenericGF(int primitive, int size, int genBase) - { - this.primitive = primitive; - this.size = size; - this.generatorBase = genBase; - - if (size <= INITIALIZATION_THRESHOLD) - { - initialize(); - } - } - - private void initialize() - { - expTable = new int[size]; - logTable = new int[size]; - int x = 1; - for (int i = 0; i < size; i++) - { - expTable[i] = x; - x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 - if (x >= size) - { - x ^= primitive; - x &= size - 1; - } - } - for (int i = 0; i < size - 1; i++) - { - logTable[expTable[i]] = i; - } - // logTable[0] == 0 but this should never be used - zero = new GenericGFPoly(this, new int[] { 0 }); - one = new GenericGFPoly(this, new int[] { 1 }); - initialized = true; - } - - private void checkInit() - { - if (!initialized) - { - initialize(); - } - } - - internal GenericGFPoly Zero - { - get - { - checkInit(); - return zero; - } - } - - internal GenericGFPoly One - { - get - { - checkInit(); - return one; - } - } - - /// - /// Builds the monomial. - /// - /// The degree. - /// The coefficient. - /// the monomial representing coefficient * x^degree - internal GenericGFPoly buildMonomial(int degree, int coefficient) - { - checkInit(); - - if (degree < 0) - { - throw new ArgumentException(); - } - if (coefficient == 0) - { - return zero; - } - int[] coefficients = new int[degree + 1]; - coefficients[0] = coefficient; - return new GenericGFPoly(this, coefficients); - } - - /// - /// Implements both addition and subtraction -- they are the same in GF(size). - /// - /// sum/difference of a and b - static internal int addOrSubtract(int a, int b) - { - return a ^ b; - } - - /// - /// Exps the specified a. - /// - /// 2 to the power of a in GF(size) - internal int exp(int a) - { - checkInit(); - - return expTable[a]; - } - - /// - /// Logs the specified a. - /// - /// A. - /// base 2 log of a in GF(size) - internal int log(int a) - { - checkInit(); - - if (a == 0) - { - throw new ArgumentException(); - } - return logTable[a]; - } - - /// - /// Inverses the specified a. - /// - /// multiplicative inverse of a - internal int inverse(int a) - { - checkInit(); - - if (a == 0) - { - throw new ArithmeticException(); - } - return expTable[size - logTable[a] - 1]; - } - - /// - /// Multiplies the specified a with b. - /// - /// A. - /// The b. - /// product of a and b in GF(size) - internal int multiply(int a, int b) - { - checkInit(); - - if (a == 0 || b == 0) - { - return 0; - } - return expTable[(logTable[a] + logTable[b]) % (size - 1)]; - } - - /// - /// Gets the size. - /// - public int Size - { - get { return size; } - } - - /// - /// Gets the generator base. - /// - public int GeneratorBase - { - get { return generatorBase; } - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - override public String ToString() - { - return "GF(0x" + primitive.ToString("X") + ',' + size + ')'; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs b/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs deleted file mode 100755 index 427fe11d..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Text; - -namespace ZXing.Common.ReedSolomon -{ - /// - ///

Represents a polynomial whose coefficients are elements of a GF. - /// Instances of this class are immutable.

- ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- ///
- /// Sean Owen - internal sealed class GenericGFPoly - { - private readonly GenericGF field; - private readonly int[] coefficients; - - /// - /// Initializes a new instance of the class. - /// - /// the {@link GenericGF} instance representing the field to use - /// to perform computations - /// coefficients as ints representing elements of GF(size), arranged - /// from most significant (highest-power term) coefficient to least significant - /// if argument is null or empty, - /// or if leading coefficient is 0 and this is not a - /// constant polynomial (that is, it is not the monomial "0") - internal GenericGFPoly(GenericGF field, int[] coefficients) - { - if (coefficients.Length == 0) - { - throw new ArgumentException(); - } - this.field = field; - int coefficientsLength = coefficients.Length; - if (coefficientsLength > 1 && coefficients[0] == 0) - { - // Leading term must be non-zero for anything except the constant polynomial "0" - int firstNonZero = 1; - while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) - { - firstNonZero++; - } - if (firstNonZero == coefficientsLength) - { - this.coefficients = field.Zero.coefficients; - } - else - { - this.coefficients = new int[coefficientsLength - firstNonZero]; - Array.Copy(coefficients, - firstNonZero, - this.coefficients, - 0, - this.coefficients.Length); - } - } - else - { - this.coefficients = coefficients; - } - } - - internal int[] Coefficients - { - get { return coefficients; } - } - - /// - /// degree of this polynomial - /// - internal int Degree - { - get - { - return coefficients.Length - 1; - } - } - - /// - /// Gets a value indicating whether this is zero. - /// - /// true iff this polynomial is the monomial "0" - internal bool isZero - { - get { return coefficients[0] == 0; } - } - - /// - /// coefficient of x^degree term in this polynomial - /// - /// The degree. - /// coefficient of x^degree term in this polynomial - internal int getCoefficient(int degree) - { - return coefficients[coefficients.Length - 1 - degree]; - } - - /// - /// evaluation of this polynomial at a given point - /// - /// A. - /// evaluation of this polynomial at a given point - internal int evaluateAt(int a) - { - int result = 0; - if (a == 0) - { - // Just return the x^0 coefficient - return getCoefficient(0); - } - int size = coefficients.Length; - if (a == 1) - { - // Just the sum of the coefficients - foreach (var coefficient in coefficients) - { - result = GenericGF.addOrSubtract(result, coefficient); - } - return result; - } - result = coefficients[0]; - for (int i = 1; i < size; i++) - { - result = GenericGF.addOrSubtract(field.multiply(a, result), coefficients[i]); - } - return result; - } - - internal GenericGFPoly addOrSubtract(GenericGFPoly other) - { - if (!field.Equals(other.field)) - { - throw new ArgumentException("GenericGFPolys do not have same GenericGF field"); - } - if (isZero) - { - return other; - } - if (other.isZero) - { - return this; - } - - int[] smallerCoefficients = this.coefficients; - int[] largerCoefficients = other.coefficients; - if (smallerCoefficients.Length > largerCoefficients.Length) - { - int[] temp = smallerCoefficients; - smallerCoefficients = largerCoefficients; - largerCoefficients = temp; - } - int[] sumDiff = new int[largerCoefficients.Length]; - int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length; - // Copy high-order terms only found in higher-degree polynomial's coefficients - Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); - - for (int i = lengthDiff; i < largerCoefficients.Length; i++) - { - sumDiff[i] = GenericGF.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); - } - - return new GenericGFPoly(field, sumDiff); - } - - internal GenericGFPoly multiply(GenericGFPoly other) - { - if (!field.Equals(other.field)) - { - throw new ArgumentException("GenericGFPolys do not have same GenericGF field"); - } - if (isZero || other.isZero) - { - return field.Zero; - } - int[] aCoefficients = this.coefficients; - int aLength = aCoefficients.Length; - int[] bCoefficients = other.coefficients; - int bLength = bCoefficients.Length; - int[] product = new int[aLength + bLength - 1]; - for (int i = 0; i < aLength; i++) - { - int aCoeff = aCoefficients[i]; - for (int j = 0; j < bLength; j++) - { - product[i + j] = GenericGF.addOrSubtract(product[i + j], - field.multiply(aCoeff, bCoefficients[j])); - } - } - return new GenericGFPoly(field, product); - } - - internal GenericGFPoly multiply(int scalar) - { - if (scalar == 0) - { - return field.Zero; - } - if (scalar == 1) - { - return this; - } - int size = coefficients.Length; - int[] product = new int[size]; - for (int i = 0; i < size; i++) - { - product[i] = field.multiply(coefficients[i], scalar); - } - return new GenericGFPoly(field, product); - } - - internal GenericGFPoly multiplyByMonomial(int degree, int coefficient) - { - if (degree < 0) - { - throw new ArgumentException(); - } - if (coefficient == 0) - { - return field.Zero; - } - int size = coefficients.Length; - int[] product = new int[size + degree]; - for (int i = 0; i < size; i++) - { - product[i] = field.multiply(coefficients[i], coefficient); - } - return new GenericGFPoly(field, product); - } - - internal GenericGFPoly[] divide(GenericGFPoly other) - { - if (!field.Equals(other.field)) - { - throw new ArgumentException("GenericGFPolys do not have same GenericGF field"); - } - if (other.isZero) - { - throw new ArgumentException("Divide by 0"); - } - - GenericGFPoly quotient = field.Zero; - GenericGFPoly remainder = this; - - int denominatorLeadingTerm = other.getCoefficient(other.Degree); - int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); - - while (remainder.Degree >= other.Degree && !remainder.isZero) - { - int degreeDifference = remainder.Degree - other.Degree; - int scale = field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); - GenericGFPoly term = other.multiplyByMonomial(degreeDifference, scale); - GenericGFPoly iterationQuotient = field.buildMonomial(degreeDifference, scale); - quotient = quotient.addOrSubtract(iterationQuotient); - remainder = remainder.addOrSubtract(term); - } - - return new GenericGFPoly[] { quotient, remainder }; - } - - public override String ToString() - { - StringBuilder result = new StringBuilder(8 * Degree); - for (int degree = Degree; degree >= 0; degree--) - { - int coefficient = getCoefficient(degree); - if (coefficient != 0) - { - if (coefficient < 0) - { - result.Append(" - "); - coefficient = -coefficient; - } - else - { - if (result.Length > 0) - { - result.Append(" + "); - } - } - if (degree == 0 || coefficient != 1) - { - int alphaPower = field.log(coefficient); - if (alphaPower == 0) - { - result.Append('1'); - } - else if (alphaPower == 1) - { - result.Append('a'); - } - else - { - result.Append("a^"); - result.Append(alphaPower); - } - } - if (degree != 0) - { - if (degree == 1) - { - result.Append('x'); - } - else - { - result.Append("x^"); - result.Append(degree); - } - } - } - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonDecoder.cs b/shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonDecoder.cs deleted file mode 100755 index 1030a56d..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonDecoder.cs +++ /dev/null @@ -1,227 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.Common.ReedSolomon -{ - ///

Implements Reed-Solomon decoding, as the name implies.

- /// - ///

The algorithm will not be explained here, but the following references were helpful - /// in creating this implementation:

- /// - /// - /// - ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- /// - ///
- /// Sean Owen - /// William Rucklidge - /// sanfordsquires - public sealed class ReedSolomonDecoder - { - private readonly GenericGF field; - - public ReedSolomonDecoder(GenericGF field) - { - this.field = field; - } - - /// - ///

Decodes given set of received codewords, which include both data and error-correction - /// codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, - /// in the input.

- ///
- /// data and error-correction codewords - /// number of error-correction codewords available - /// false: decoding fails - public bool decode(int[] received, int twoS) - { - var poly = new GenericGFPoly(field, received); - var syndromeCoefficients = new int[twoS]; - var noError = true; - for (var i = 0; i < twoS; i++) - { - var eval = poly.evaluateAt(field.exp(i + field.GeneratorBase)); - syndromeCoefficients[syndromeCoefficients.Length - 1 - i] = eval; - if (eval != 0) - { - noError = false; - } - } - if (noError) - { - return true; - } - var syndrome = new GenericGFPoly(field, syndromeCoefficients); - - var sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS); - if (sigmaOmega == null) - return false; - - var sigma = sigmaOmega[0]; - var errorLocations = findErrorLocations(sigma); - if (errorLocations == null) - return false; - - var omega = sigmaOmega[1]; - var errorMagnitudes = findErrorMagnitudes(omega, errorLocations); - for (var i = 0; i < errorLocations.Length; i++) - { - var position = received.Length - 1 - field.log(errorLocations[i]); - if (position < 0) - { - // throw new ReedSolomonException("Bad error location"); - return false; - } - received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]); - } - - return true; - } - - internal GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R) - { - // Assume a's degree is >= b's - if (a.Degree < b.Degree) - { - GenericGFPoly temp = a; - a = b; - b = temp; - } - - GenericGFPoly rLast = a; - GenericGFPoly r = b; - GenericGFPoly tLast = field.Zero; - GenericGFPoly t = field.One; - - // Run Euclidean algorithm until r's degree is less than R/2 - while (r.Degree >= R / 2) - { - GenericGFPoly rLastLast = rLast; - GenericGFPoly tLastLast = tLast; - rLast = r; - tLast = t; - - // Divide rLastLast by rLast, with quotient in q and remainder in r - if (rLast.isZero) - { - // Oops, Euclidean algorithm already terminated? - // throw new ReedSolomonException("r_{i-1} was zero"); - return null; - } - r = rLastLast; - GenericGFPoly q = field.Zero; - int denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); - int dltInverse = field.inverse(denominatorLeadingTerm); - while (r.Degree >= rLast.Degree && !r.isZero) - { - int degreeDiff = r.Degree - rLast.Degree; - int scale = field.multiply(r.getCoefficient(r.Degree), dltInverse); - q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale)); - r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); - } - - t = q.multiply(tLast).addOrSubtract(tLastLast); - - if (r.Degree >= rLast.Degree) - { - // throw new IllegalStateException("Division algorithm failed to reduce polynomial?"); - return null; - } - } - - int sigmaTildeAtZero = t.getCoefficient(0); - if (sigmaTildeAtZero == 0) - { - // throw new ReedSolomonException("sigmaTilde(0) was zero"); - return null; - } - - int inverse = field.inverse(sigmaTildeAtZero); - GenericGFPoly sigma = t.multiply(inverse); - GenericGFPoly omega = r.multiply(inverse); - return new GenericGFPoly[] { sigma, omega }; - } - - private int[] findErrorLocations(GenericGFPoly errorLocator) - { - // This is a direct application of Chien's search - int numErrors = errorLocator.Degree; - if (numErrors == 1) - { - // shortcut - return new int[] { errorLocator.getCoefficient(1) }; - } - int[] result = new int[numErrors]; - int e = 0; - for (int i = 1; i < field.Size && e < numErrors; i++) - { - if (errorLocator.evaluateAt(i) == 0) - { - result[e] = field.inverse(i); - e++; - } - } - if (e != numErrors) - { - // throw new ReedSolomonException("Error locator degree does not match number of roots"); - return null; - } - return result; - } - - private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations) - { - // This is directly applying Forney's Formula - int s = errorLocations.Length; - int[] result = new int[s]; - for (int i = 0; i < s; i++) - { - int xiInverse = field.inverse(errorLocations[i]); - int denominator = 1; - for (int j = 0; j < s; j++) - { - if (i != j) - { - //denominator = field.multiply(denominator, - // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); - // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug. - // Below is a funny-looking workaround from Steven Parkes - int term = field.multiply(errorLocations[j], xiInverse); - int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1; - denominator = field.multiply(denominator, termPlus1); - - // removed in java version, not sure if this is right - // denominator = field.multiply(denominator, GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); - } - } - result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator)); - if (field.GeneratorBase != 0) - { - result[i] = field.multiply(result[i], xiInverse); - } - } - return result; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonEncoder.cs b/shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonEncoder.cs deleted file mode 100755 index 78aca71d..00000000 --- a/shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonEncoder.cs +++ /dev/null @@ -1,84 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; - -namespace ZXing.Common.ReedSolomon -{ - /// - /// Implements Reed-Solomon encoding, as the name implies. - /// - /// Sean Owen - /// William Rucklidge - public sealed class ReedSolomonEncoder - { - private readonly GenericGF field; - private readonly IList cachedGenerators; - - public ReedSolomonEncoder(GenericGF field) - { - this.field = field; - this.cachedGenerators = new List(); - cachedGenerators.Add(new GenericGFPoly(field, new int[] { 1 })); - } - - private GenericGFPoly buildGenerator(int degree) - { - if (degree >= cachedGenerators.Count) - { - var lastGenerator = cachedGenerators[cachedGenerators.Count - 1]; - for (int d = cachedGenerators.Count; d <= degree; d++) - { - var nextGenerator = lastGenerator.multiply(new GenericGFPoly(field, new int[] { 1, field.exp(d - 1 + field.GeneratorBase) })); - cachedGenerators.Add(nextGenerator); - lastGenerator = nextGenerator; - } - } - return cachedGenerators[degree]; - } - - public void encode(int[] toEncode, int ecBytes) - { - if (ecBytes == 0) - { - throw new ArgumentException("No error correction bytes"); - } - var dataBytes = toEncode.Length - ecBytes; - if (dataBytes <= 0) - { - throw new ArgumentException("No data bytes provided"); - } - - var generator = buildGenerator(ecBytes); - var infoCoefficients = new int[dataBytes]; - Array.Copy(toEncode, 0, infoCoefficients, 0, dataBytes); - - var info = new GenericGFPoly(field, infoCoefficients); - info = info.multiplyByMonomial(ecBytes, 1); - - var remainder = info.divide(generator)[1]; - var coefficients = remainder.Coefficients; - var numZeroCoefficients = ecBytes - coefficients.Length; - for (var i = 0; i < numZeroCoefficients; i++) - { - toEncode[dataBytes + i] = 0; - } - - Array.Copy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.Length); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/QRCodeReader.cs b/shadowsocks-csharp/3rd/zxing/qrcode/QRCodeReader.cs deleted file mode 100755 index 597797bc..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/QRCodeReader.cs +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; - -using ZXing.Common; -using ZXing.QrCode.Internal; - -namespace ZXing.QrCode -{ - /// - /// This implementation can detect and decode QR Codes in an image. - /// Sean Owen - /// - public class QRCodeReader - { - private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; - - private readonly Decoder decoder = new Decoder(); - - /// - /// Gets the decoder. - /// - /// - protected Decoder getDecoder() - { - return decoder; - } - - /// - /// Locates and decodes a QR code in an image. - /// - /// a String representing the content encoded by the QR code - /// - public Result decode(BinaryBitmap image) - { - return decode(image, null); - } - - /// - /// Locates and decodes a barcode in some format within an image. This method also accepts - /// hints, each possibly associated to some data, which may help the implementation decode. - /// - /// image of barcode to decode - /// passed as a from - /// to arbitrary data. The - /// meaning of the data depends upon the hint type. The implementation may or may not do - /// anything with these hints. - /// - /// String which the barcode encodes - /// - public Result decode(BinaryBitmap image, IDictionary hints) - { - DecoderResult decoderResult; - ResultPoint[] points; - if (image == null || image.BlackMatrix == null) - { - // something is wrong with the image - return null; - } - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) - { - var bits = extractPureBits(image.BlackMatrix); - if (bits == null) - return null; - decoderResult = decoder.decode(bits, hints); - points = NO_POINTS; - } - else - { - var detectorResult = new Detector(image.BlackMatrix).detect(hints); - if (detectorResult == null) - return null; - decoderResult = decoder.decode(detectorResult.Bits, hints); - points = detectorResult.Points; - } - if (decoderResult == null) - return null; - - // If the code was mirrored: swap the bottom-left and the top-right points. - var data = decoderResult.Other as QRCodeDecoderMetaData; - if (data != null) - { - data.applyMirroredCorrection(points); - } - - var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE); - var byteSegments = decoderResult.ByteSegments; - if (byteSegments != null) - { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); - } - var ecLevel = decoderResult.ECLevel; - if (ecLevel != null) - { - result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); - } - if (decoderResult.StructuredAppend) - { - result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber); - result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity); - } - return result; - } - - /// - /// Resets any internal state the implementation has after a decode, to prepare it - /// for reuse. - /// - public void reset() - { - // do nothing - } - - /// - /// This method detects a code in a "pure" image -- that is, pure monochrome image - /// which contains only an unrotated, unskewed, image of a code, with some white border - /// around it. This is a specialized method that works exceptionally fast in this special - /// case. - /// - /// - /// - private static BitMatrix extractPureBits(BitMatrix image) - { - int[] leftTopBlack = image.getTopLeftOnBit(); - int[] rightBottomBlack = image.getBottomRightOnBit(); - if (leftTopBlack == null || rightBottomBlack == null) - { - return null; - } - - float moduleSize; - if (!QRCodeReader.moduleSize(leftTopBlack, image, out moduleSize)) - return null; - - int top = leftTopBlack[1]; - int bottom = rightBottomBlack[1]; - int left = leftTopBlack[0]; - int right = rightBottomBlack[0]; - - // Sanity check! - if (left >= right || top >= bottom) - { - return null; - } - - if (bottom - top != right - left) - { - // Special case, where bottom-right module wasn't black so we found something else in the last row - // Assume it's a square, so use height as the width - right = left + (bottom - top); - } - - int matrixWidth = (int)Math.Round((right - left + 1) / moduleSize); - int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize); - if (matrixWidth <= 0 || matrixHeight <= 0) - { - return null; - } - if (matrixHeight != matrixWidth) - { - // Only possibly decode square regions - return null; - } - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - int nudge = (int)(moduleSize / 2.0f); - top += nudge; - left += nudge; - - // But careful that this does not sample off the edge - int nudgedTooFarRight = left + (int)((matrixWidth - 1) * moduleSize) - (right - 1); - if (nudgedTooFarRight > 0) - { - if (nudgedTooFarRight > nudge) - { - // Neither way fits; abort - return null; - } - left -= nudgedTooFarRight; - } - int nudgedTooFarDown = top + (int)((matrixHeight - 1) * moduleSize) - (bottom - 1); - if (nudgedTooFarDown > 0) - { - if (nudgedTooFarDown > nudge) - { - // Neither way fits; abort - return null; - } - top -= nudgedTooFarDown; - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); - for (int y = 0; y < matrixHeight; y++) - { - int iOffset = top + (int)(y * moduleSize); - for (int x = 0; x < matrixWidth; x++) - { - if (image[left + (int)(x * moduleSize), iOffset]) - { - bits[x, y] = true; - } - } - } - return bits; - } - - private static bool moduleSize(int[] leftTopBlack, BitMatrix image, out float msize) - { - int height = image.Height; - int width = image.Width; - int x = leftTopBlack[0]; - int y = leftTopBlack[1]; - bool inBlack = true; - int transitions = 0; - while (x < width && y < height) - { - if (inBlack != image[x, y]) - { - if (++transitions == 5) - { - break; - } - inBlack = !inBlack; - } - x++; - y++; - } - if (x == width || y == height) - { - msize = 0.0f; - return false; - } - msize = (x - leftTopBlack[0]) / 7.0f; - return true; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/BitMatrixParser.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/BitMatrixParser.cs deleted file mode 100755 index 6a328faa..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,281 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using ZXing.Common; - -namespace ZXing.QrCode.Internal -{ - /// Sean Owen - sealed class BitMatrixParser - { - private readonly BitMatrix bitMatrix; - private Version parsedVersion; - private FormatInformation parsedFormatInfo; - private bool mirrored; - - /// {@link BitMatrix} to parse - /// ReaderException if dimension is not >= 21 and 1 mod 4 - internal static BitMatrixParser createBitMatrixParser(BitMatrix bitMatrix) - { - int dimension = bitMatrix.Height; - if (dimension < 21 || (dimension & 0x03) != 1) - { - return null; - } - return new BitMatrixParser(bitMatrix); - } - - private BitMatrixParser(BitMatrix bitMatrix) - { - // Should only be called from createBitMatrixParser with the important checks before - this.bitMatrix = bitMatrix; - } - - ///

Reads format information from one of its two locations within the QR Code.

- /// - ///
- /// {@link FormatInformation} encapsulating the QR Code's format info - /// - /// ReaderException if both format information locations cannot be parsed as - /// the valid encoding of format information - /// - internal FormatInformation readFormatInformation() - { - if (parsedFormatInfo != null) - { - return parsedFormatInfo; - } - - // Read top-left format info bits - int formatInfoBits1 = 0; - for (int i = 0; i < 6; i++) - { - formatInfoBits1 = copyBit(i, 8, formatInfoBits1); - } - // .. and skip a bit in the timing pattern ... - formatInfoBits1 = copyBit(7, 8, formatInfoBits1); - formatInfoBits1 = copyBit(8, 8, formatInfoBits1); - formatInfoBits1 = copyBit(8, 7, formatInfoBits1); - // .. and skip a bit in the timing pattern ... - for (int j = 5; j >= 0; j--) - { - formatInfoBits1 = copyBit(8, j, formatInfoBits1); - } - // Read the top-right/bottom-left pattern too - int dimension = bitMatrix.Height; - int formatInfoBits2 = 0; - int jMin = dimension - 7; - for (int j = dimension - 1; j >= jMin; j--) - { - formatInfoBits2 = copyBit(8, j, formatInfoBits2); - } - for (int i = dimension - 8; i < dimension; i++) - { - formatInfoBits2 = copyBit(i, 8, formatInfoBits2); - } - - parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits1, formatInfoBits2); - if (parsedFormatInfo != null) - { - return parsedFormatInfo; - } - return null; - } - - ///

Reads version information from one of its two locations within the QR Code.

- /// - ///
- /// {@link Version} encapsulating the QR Code's version - /// - /// ReaderException if both version information locations cannot be parsed as - /// the valid encoding of version information - /// - internal Version readVersion() - { - if (parsedVersion != null) - { - return parsedVersion; - } - - int dimension = bitMatrix.Height; - - int provisionalVersion = (dimension - 17) >> 2; - if (provisionalVersion <= 6) - { - return Version.getVersionForNumber(provisionalVersion); - } - - // Read top-right version info: 3 wide by 6 tall - int versionBits = 0; - int ijMin = dimension - 11; - for (int j = 5; j >= 0; j--) - { - for (int i = dimension - 9; i >= ijMin; i--) - { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension) - { - return parsedVersion; - } - - // Hmm, failed. Try bottom left: 6 wide by 3 tall - versionBits = 0; - for (int i = 5; i >= 0; i--) - { - for (int j = dimension - 9; j >= ijMin; j--) - { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension) - { - return parsedVersion; - } - return null; - } - - private int copyBit(int i, int j, int versionBits) - { - bool bit = mirrored ? bitMatrix[j, i] : bitMatrix[i, j]; - return bit ? (versionBits << 1) | 0x1 : versionBits << 1; - } - - ///

Reads the bits in the {@link BitMatrix} representing the finder pattern in the - /// correct order in order to reconstruct the codewords bytes contained within the - /// QR Code.

- /// - ///
- /// bytes encoded within the QR Code - /// - /// ReaderException if the exact number of bytes expected is not read - internal byte[] readCodewords() - { - FormatInformation formatInfo = readFormatInformation(); - if (formatInfo == null) - return null; - Version version = readVersion(); - if (version == null) - return null; - - // Get the data mask for the format used in this QR Code. This will exclude - // some bits from reading as we wind through the bit matrix. - DataMask dataMask = DataMask.forReference(formatInfo.DataMask); - int dimension = bitMatrix.Height; - dataMask.unmaskBitMatrix(bitMatrix, dimension); - - BitMatrix functionPattern = version.buildFunctionPattern(); - - bool readingUp = true; - byte[] result = new byte[version.TotalCodewords]; - int resultOffset = 0; - int currentByte = 0; - int bitsRead = 0; - // Read columns in pairs, from right to left - for (int j = dimension - 1; j > 0; j -= 2) - { - if (j == 6) - { - // Skip whole column with vertical alignment pattern; - // saves time and makes the other code proceed more cleanly - j--; - } - // Read alternatingly from bottom to top then top to bottom - for (int count = 0; count < dimension; count++) - { - int i = readingUp ? dimension - 1 - count : count; - for (int col = 0; col < 2; col++) - { - // Ignore bits covered by the function pattern - if (!functionPattern[j - col, i]) - { - // Read a bit - bitsRead++; - currentByte <<= 1; - if (bitMatrix[j - col, i]) - { - currentByte |= 1; - } - // If we've made a whole byte, save it off - if (bitsRead == 8) - { - result[resultOffset++] = (byte)currentByte; - bitsRead = 0; - currentByte = 0; - } - } - } - } - readingUp ^= true; // readingUp = !readingUp; // switch directions - } - if (resultOffset != version.TotalCodewords) - { - return null; - } - return result; - } - - /** - * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state. - */ - internal void remask() - { - if (parsedFormatInfo == null) - { - return; // We have no format information, and have no data mask - } - DataMask dataMask = DataMask.forReference(parsedFormatInfo.DataMask); - int dimension = bitMatrix.Height; - dataMask.unmaskBitMatrix(bitMatrix, dimension); - } - - /** - * Prepare the parser for a mirrored operation. - * This flag has effect only on the {@link #readFormatInformation()} and the - * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the - * {@link #mirror()} method should be called. - * - * @param mirror Whether to read version and format information mirrored. - */ - internal void setMirror(bool mirror) - { - parsedVersion = null; - parsedFormatInfo = null; - mirrored = mirror; - } - - /** Mirror the bit matrix in order to attempt a second reading. */ - internal void mirror() - { - for (int x = 0; x < bitMatrix.Width; x++) - { - for (int y = x + 1; y < bitMatrix.Height; y++) - { - if (bitMatrix[x, y] != bitMatrix[y, x]) - { - bitMatrix.flip(y, x); - bitMatrix.flip(x, y); - } - } - } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataBlock.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataBlock.cs deleted file mode 100755 index 5860fe6a..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataBlock.cs +++ /dev/null @@ -1,146 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.QrCode.Internal -{ - ///

Encapsulates a block of data within a QR Code. QR Codes may split their data into - /// multiple blocks, each of which is a unit of data and error-correction codewords. Each - /// is represented by an instance of this class.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - internal sealed class DataBlock - { - private readonly int numDataCodewords; - private readonly byte[] codewords; - - private DataBlock(int numDataCodewords, byte[] codewords) - { - this.numDataCodewords = numDataCodewords; - this.codewords = codewords; - } - - ///

When QR Codes use multiple data blocks, they are actually interleaved. - /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - /// method will separate the data into original blocks.

- /// - ///
- /// bytes as read directly from the QR Code - /// - /// version of the QR Code - /// - /// error-correction level of the QR Code - /// - /// {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the - /// QR Code - /// - internal static DataBlock[] getDataBlocks(byte[] rawCodewords, Version version, ErrorCorrectionLevel ecLevel) - { - - if (rawCodewords.Length != version.TotalCodewords) - { - throw new System.ArgumentException(); - } - - // Figure out the number and size of data blocks used by this version and - // error correction level - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - - // First count the total number of data blocks - int totalBlocks = 0; - Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); - foreach (var ecBlock in ecBlockArray) - { - totalBlocks += ecBlock.Count; - } - - // Now establish DataBlocks of the appropriate size and number of data codewords - DataBlock[] result = new DataBlock[totalBlocks]; - int numResultBlocks = 0; - foreach (var ecBlock in ecBlockArray) - { - for (int i = 0; i < ecBlock.Count; i++) - { - int numDataCodewords = ecBlock.DataCodewords; - int numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; - result[numResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]); - } - } - - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 more byte. Figure out where these start. - int shorterBlocksTotalCodewords = result[0].codewords.Length; - int longerBlocksStartAt = result.Length - 1; - while (longerBlocksStartAt >= 0) - { - int numCodewords = result[longerBlocksStartAt].codewords.Length; - if (numCodewords == shorterBlocksTotalCodewords) - { - break; - } - longerBlocksStartAt--; - } - longerBlocksStartAt++; - - int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; - // The last elements of result may be 1 element longer; - // first fill out as many elements as all of them have - int rawCodewordsOffset = 0; - for (int i = 0; i < shorterBlocksNumDataCodewords; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; - } - } - // Fill out the last data block in the longer ones - for (int j = longerBlocksStartAt; j < numResultBlocks; j++) - { - result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; - } - // Now add in error correction blocks - int max = result[0].codewords.Length; - for (int i = shorterBlocksNumDataCodewords; i < max; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - int iOffset = j < longerBlocksStartAt ? i : i + 1; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; - } - } - return result; - } - - internal int NumDataCodewords - { - get - { - return numDataCodewords; - } - } - - internal byte[] Codewords - { - get - { - return codewords; - } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataMask.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataMask.cs deleted file mode 100755 index a6ac93e6..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataMask.cs +++ /dev/null @@ -1,165 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using ZXing.Common; - -namespace ZXing.QrCode.Internal -{ - ///

Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations - /// of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix, - /// including areas used for finder patterns, timing patterns, etc. These areas should be unused - /// after the point they are unmasked anyway.

- /// - ///

Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position - /// and j is row position. In fact, as the text says, i is row position and j is column position.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - abstract class DataMask - { - /// See ISO 18004:2006 6.8.1 - private static readonly DataMask[] DATA_MASKS = new DataMask[] - { - new DataMask000(), - new DataMask001(), - new DataMask010(), - new DataMask011(), - new DataMask100(), - new DataMask101(), - new DataMask110(), - new DataMask111() - }; - - private DataMask() - { - } - - ///

Implementations of this method reverse the data masking process applied to a QR Code and - /// make its bits ready to read.

- /// - ///
- /// representation of QR Code bits - /// - /// dimension of QR Code, represented by bits, being unmasked - /// - internal void unmaskBitMatrix(BitMatrix bits, int dimension) - { - for (int i = 0; i < dimension; i++) - { - for (int j = 0; j < dimension; j++) - { - if (isMasked(i, j)) - { - bits.flip(j, i); - } - } - } - } - - internal abstract bool isMasked(int i, int j); - - /// a value between 0 and 7 indicating one of the eight possible - /// data mask patterns a QR Code may use - /// - /// {@link DataMask} encapsulating the data mask pattern - /// - internal static DataMask forReference(int reference) - { - if (reference < 0 || reference > 7) - { - throw new System.ArgumentException(); - } - return DATA_MASKS[reference]; - } - - /// 000: mask bits for which (x + y) mod 2 == 0 - private sealed class DataMask000 : DataMask - { - internal override bool isMasked(int i, int j) - { - return ((i + j) & 0x01) == 0; - } - } - - /// 001: mask bits for which x mod 2 == 0 - private sealed class DataMask001 : DataMask - { - internal override bool isMasked(int i, int j) - { - return (i & 0x01) == 0; - } - } - - /// 010: mask bits for which y mod 3 == 0 - private sealed class DataMask010 : DataMask - { - internal override bool isMasked(int i, int j) - { - return j % 3 == 0; - } - } - - /// 011: mask bits for which (x + y) mod 3 == 0 - private sealed class DataMask011 : DataMask - { - internal override bool isMasked(int i, int j) - { - return (i + j) % 3 == 0; - } - } - - /// 100: mask bits for which (x/2 + y/3) mod 2 == 0 - private sealed class DataMask100 : DataMask - { - internal override bool isMasked(int i, int j) - { - return ((((int)((uint)i >> 1)) + (j / 3)) & 0x01) == 0; - } - } - - /// 101: mask bits for which xy mod 2 + xy mod 3 == 0 - private sealed class DataMask101 : DataMask - { - internal override bool isMasked(int i, int j) - { - int temp = i * j; - return (temp & 0x01) + (temp % 3) == 0; - } - } - - /// 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0 - private sealed class DataMask110 : DataMask - { - internal override bool isMasked(int i, int j) - { - int temp = i * j; - return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; - } - } - - /// 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0 - private sealed class DataMask111 : DataMask - { - internal override bool isMasked(int i, int j) - { - return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0; - } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DecodedBitStreamParser.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DecodedBitStreamParser.cs deleted file mode 100755 index 189fb41f..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,514 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Text; - -using ZXing.Common; - -namespace ZXing.QrCode.Internal -{ - ///

QR Codes can encode text as bits in one of several modes, and can use multiple modes - /// in one QR Code. This class decodes the bits back into text.

- /// - ///

See ISO 18004:2006, 6.4.3 - 6.4.7

- /// Sean Owen - ///
- internal static class DecodedBitStreamParser - { - /// - /// See ISO 18004:2006, 6.4.4 Table 5 - /// - private static readonly char[] ALPHANUMERIC_CHARS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', - 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - ' ', '$', '%', '*', '+', '-', '.', '/', ':' - }; - private const int GB2312_SUBSET = 1; - - internal static DecoderResult decode(byte[] bytes, - Version version, - ErrorCorrectionLevel ecLevel, - IDictionary hints) - { - var bits = new BitSource(bytes); - var result = new StringBuilder(50); - var byteSegments = new List(1); - var symbolSequence = -1; - var parityData = -1; - - try - { - // CharacterSetECI currentCharacterSetECI = null; - bool fc1InEffect = false; - Mode mode; - do - { - // While still another segment to read... - if (bits.available() < 4) - { - // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here - mode = Mode.TERMINATOR; - } - else - { - try - { - mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits - } - catch (ArgumentException) - { - return null; - } - } - if (mode != Mode.TERMINATOR) - { - if (mode == Mode.FNC1_FIRST_POSITION || mode == Mode.FNC1_SECOND_POSITION) - { - // We do little with FNC1 except alter the parsed result a bit according to the spec - fc1InEffect = true; - } - else if (mode == Mode.STRUCTURED_APPEND) - { - if (bits.available() < 16) - { - return null; - } - // not really supported; but sequence number and parity is added later to the result metadata - // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue - symbolSequence = bits.readBits(8); - parityData = bits.readBits(8); - } - else if (mode == Mode.ECI) - { - /* - // Count doesn't apply to ECI - int value = parseECIValue(bits); - currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value); - if (currentCharacterSetECI == null) - { - return null; - } - * */ - } - else - { - // First handle Hanzi mode which does not start with character count - if (mode == Mode.HANZI) - { - //chinese mode contains a sub set indicator right after mode indicator - int subset = bits.readBits(4); - int countHanzi = bits.readBits(mode.getCharacterCountBits(version)); - if (subset == GB2312_SUBSET) - { - if (!decodeHanziSegment(bits, result, countHanzi)) - return null; - } - } - else - { - // "Normal" QR code modes: - // How many characters will follow, encoded in this mode? - int count = bits.readBits(mode.getCharacterCountBits(version)); - if (mode == Mode.NUMERIC) - { - if (!decodeNumericSegment(bits, result, count)) - return null; - } - else if (mode == Mode.ALPHANUMERIC) - { - if (!decodeAlphanumericSegment(bits, result, count, fc1InEffect)) - return null; - } - else if (mode == Mode.BYTE) - { - if (!decodeByteSegment(bits, result, count, byteSegments, hints)) - return null; - } - else if (mode == Mode.KANJI) - { - if (!decodeKanjiSegment(bits, result, count)) - return null; - } - else - { - return null; - } - } - } - } - } while (mode != Mode.TERMINATOR); - } - catch (ArgumentException) - { - // from readBits() calls - return null; - } - -#if WindowsCE - var resultString = result.ToString().Replace("\n", "\r\n"); -#else - var resultString = result.ToString().Replace("\r\n", "\n").Replace("\n", Environment.NewLine); -#endif - return new DecoderResult(bytes, - resultString, - byteSegments.Count == 0 ? null : byteSegments, - ecLevel == null ? null : ecLevel.ToString(), - symbolSequence, parityData); - } - - /// - /// See specification GBT 18284-2000 - /// - /// The bits. - /// The result. - /// The count. - /// - private static bool decodeHanziSegment(BitSource bits, - StringBuilder result, - int count) - { - // Don't crash trying to read more bits than we have available. - if (count * 13 > bits.available()) - { - return false; - } - - // Each character will require 2 bytes. Read the characters as 2-byte pairs - // and decode as GB2312 afterwards - byte[] buffer = new byte[2 * count]; - int offset = 0; - while (count > 0) - { - // Each 13 bits encodes a 2-byte character - int twoBytes = bits.readBits(13); - int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060); - if (assembledTwoBytes < 0x003BF) - { - // In the 0xA1A1 to 0xAAFE range - assembledTwoBytes += 0x0A1A1; - } - else - { - // In the 0xB0A1 to 0xFAFE range - assembledTwoBytes += 0x0A6A1; - } - buffer[offset] = (byte)((assembledTwoBytes >> 8) & 0xFF); - buffer[offset + 1] = (byte)(assembledTwoBytes & 0xFF); - offset += 2; - count--; - } - - try - { - result.Append(Encoding.GetEncoding(StringUtils.GB2312).GetString(buffer, 0, buffer.Length)); - } -#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH) - catch (ArgumentException) - { - try - { - // Silverlight only supports a limited number of character sets, trying fallback to UTF-8 - result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length)); - } - catch (Exception) - { - return false; - } - } -#endif - catch (Exception) - { - return false; - } - - return true; - } - - private static bool decodeKanjiSegment(BitSource bits, - StringBuilder result, - int count) - { - // Don't crash trying to read more bits than we have available. - if (count * 13 > bits.available()) - { - return false; - } - - // Each character will require 2 bytes. Read the characters as 2-byte pairs - // and decode as Shift_JIS afterwards - byte[] buffer = new byte[2 * count]; - int offset = 0; - while (count > 0) - { - // Each 13 bits encodes a 2-byte character - int twoBytes = bits.readBits(13); - int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); - if (assembledTwoBytes < 0x01F00) - { - // In the 0x8140 to 0x9FFC range - assembledTwoBytes += 0x08140; - } - else - { - // In the 0xE040 to 0xEBBF range - assembledTwoBytes += 0x0C140; - } - buffer[offset] = (byte)(assembledTwoBytes >> 8); - buffer[offset + 1] = (byte)assembledTwoBytes; - offset += 2; - count--; - } - // Shift_JIS may not be supported in some environments: - try - { - result.Append(Encoding.GetEncoding(StringUtils.SHIFT_JIS).GetString(buffer, 0, buffer.Length)); - } -#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH) - catch (ArgumentException) - { - try - { - // Silverlight only supports a limited number of character sets, trying fallback to UTF-8 - result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length)); - } - catch (Exception) - { - return false; - } - } -#endif - catch (Exception) - { - return false; - } - return true; - } - - private static bool decodeByteSegment(BitSource bits, - StringBuilder result, - int count, - IList byteSegments, - IDictionary hints) - { - // Don't crash trying to read more bits than we have available. - if (count << 3 > bits.available()) - { - return false; - } - - byte[] readBytes = new byte[count]; - for (int i = 0; i < count; i++) - { - readBytes[i] = (byte)bits.readBits(8); - } - String encoding; - encoding = StringUtils.guessEncoding(readBytes, hints); - - try - { - result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length)); - } -#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH) - catch (ArgumentException) - { - try - { - // Silverlight only supports a limited number of character sets, trying fallback to UTF-8 - result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length)); - } - catch (Exception) - { - return false; - } - } -#endif -#if WindowsCE - catch (PlatformNotSupportedException) - { - try - { - // WindowsCE doesn't support all encodings. But it is device depended. - // So we try here the some different ones - if (encoding == "ISO-8859-1") - { - result.Append(Encoding.GetEncoding(1252).GetString(readBytes, 0, readBytes.Length)); - } - else - { - result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length)); - } - } - catch (Exception) - { - return false; - } - } -#endif - catch (Exception) - { - return false; - } - byteSegments.Add(readBytes); - - return true; - } - - private static char toAlphaNumericChar(int value) - { - if (value >= ALPHANUMERIC_CHARS.Length) - { - //throw FormatException.Instance; - } - return ALPHANUMERIC_CHARS[value]; - } - - private static bool decodeAlphanumericSegment(BitSource bits, - StringBuilder result, - int count, - bool fc1InEffect) - { - // Read two characters at a time - int start = result.Length; - while (count > 1) - { - if (bits.available() < 11) - { - return false; - } - int nextTwoCharsBits = bits.readBits(11); - result.Append(toAlphaNumericChar(nextTwoCharsBits / 45)); - result.Append(toAlphaNumericChar(nextTwoCharsBits % 45)); - count -= 2; - } - if (count == 1) - { - // special case: one character left - if (bits.available() < 6) - { - return false; - } - result.Append(toAlphaNumericChar(bits.readBits(6))); - } - - // See section 6.4.8.1, 6.4.8.2 - if (fc1InEffect) - { - // We need to massage the result a bit if in an FNC1 mode: - for (int i = start; i < result.Length; i++) - { - if (result[i] == '%') - { - if (i < result.Length - 1 && result[i + 1] == '%') - { - // %% is rendered as % - result.Remove(i + 1, 1); - } - else - { - // In alpha mode, % should be converted to FNC1 separator 0x1D - result.Remove(i, 1); - result.Insert(i, new[] { (char)0x1D }); - } - } - } - } - - return true; - } - - private static bool decodeNumericSegment(BitSource bits, - StringBuilder result, - int count) - { - // Read three digits at a time - while (count >= 3) - { - // Each 10 bits encodes three digits - if (bits.available() < 10) - { - return false; - } - int threeDigitsBits = bits.readBits(10); - if (threeDigitsBits >= 1000) - { - return false; - } - result.Append(toAlphaNumericChar(threeDigitsBits / 100)); - result.Append(toAlphaNumericChar((threeDigitsBits / 10) % 10)); - result.Append(toAlphaNumericChar(threeDigitsBits % 10)); - - count -= 3; - } - if (count == 2) - { - // Two digits left over to read, encoded in 7 bits - if (bits.available() < 7) - { - return false; - } - int twoDigitsBits = bits.readBits(7); - if (twoDigitsBits >= 100) - { - return false; - } - result.Append(toAlphaNumericChar(twoDigitsBits / 10)); - result.Append(toAlphaNumericChar(twoDigitsBits % 10)); - } - else if (count == 1) - { - // One digit left over to read - if (bits.available() < 4) - { - return false; - } - int digitBits = bits.readBits(4); - if (digitBits >= 10) - { - return false; - } - result.Append(toAlphaNumericChar(digitBits)); - } - - return true; - } - - private static int parseECIValue(BitSource bits) - { - int firstByte = bits.readBits(8); - if ((firstByte & 0x80) == 0) - { - // just one byte - return firstByte & 0x7F; - } - if ((firstByte & 0xC0) == 0x80) - { - // two bytes - int secondByte = bits.readBits(8); - return ((firstByte & 0x3F) << 8) | secondByte; - } - if ((firstByte & 0xE0) == 0xC0) - { - // three bytes - int secondThirdBytes = bits.readBits(16); - return ((firstByte & 0x1F) << 16) | secondThirdBytes; - } - throw new ArgumentException("Bad ECI bits starting with byte " + firstByte); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Decoder.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Decoder.cs deleted file mode 100755 index a5ec8645..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Decoder.cs +++ /dev/null @@ -1,195 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System.Collections.Generic; - -using ZXing.Common; -using ZXing.Common.ReedSolomon; - -namespace ZXing.QrCode.Internal -{ - /// - ///

The main class which implements QR Code decoding -- as opposed to locating and extracting - /// the QR Code from an image.

- ///
- /// - /// Sean Owen - /// - public sealed class Decoder - { - private readonly ReedSolomonDecoder rsDecoder; - - /// - /// Initializes a new instance of the class. - /// - public Decoder() - { - rsDecoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256); - } - - /// - ///

Convenience method that can decode a QR Code represented as a 2D array of booleans. - /// "true" is taken to mean a black module.

- ///
- /// booleans representing white/black QR Code modules - /// The hints. - /// - /// text and bytes encoded within the QR Code - /// - public DecoderResult decode(bool[][] image, IDictionary hints) - { - var dimension = image.Length; - var bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) - { - for (int j = 0; j < dimension; j++) - { - bits[j, i] = image[i][j]; - } - } - return decode(bits, hints); - } - - /// - ///

Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.

- ///
- /// booleans representing white/black QR Code modules - /// The hints. - /// - /// text and bytes encoded within the QR Code - /// - public DecoderResult decode(BitMatrix bits, IDictionary hints) - { - // Construct a parser and read version, error-correction level - var parser = BitMatrixParser.createBitMatrixParser(bits); - if (parser == null) - return null; - - var result = decode(parser, hints); - if (result == null) - { - // Revert the bit matrix - parser.remask(); - - // Will be attempting a mirrored reading of the version and format info. - parser.setMirror(true); - - // Preemptively read the version. - var version = parser.readVersion(); - if (version == null) - return null; - - // Preemptively read the format information. - var formatinfo = parser.readFormatInformation(); - if (formatinfo == null) - return null; - - /* - * Since we're here, this means we have successfully detected some kind - * of version and format information when mirrored. This is a good sign, - * that the QR code may be mirrored, and we should try once more with a - * mirrored content. - */ - // Prepare for a mirrored reading. - parser.mirror(); - - result = decode(parser, hints); - - if (result != null) - { - // Success! Notify the caller that the code was mirrored. - result.Other = new QRCodeDecoderMetaData(true); - } - } - - return result; - } - - private DecoderResult decode(BitMatrixParser parser, IDictionary hints) - { - Version version = parser.readVersion(); - if (version == null) - return null; - var formatinfo = parser.readFormatInformation(); - if (formatinfo == null) - return null; - ErrorCorrectionLevel ecLevel = formatinfo.ErrorCorrectionLevel; - - // Read codewords - byte[] codewords = parser.readCodewords(); - if (codewords == null) - return null; - // Separate into data blocks - DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); - - // Count total number of data bytes - int totalBytes = 0; - foreach (var dataBlock in dataBlocks) - { - totalBytes += dataBlock.NumDataCodewords; - } - byte[] resultBytes = new byte[totalBytes]; - int resultOffset = 0; - - // Error-correct and copy data blocks together into a stream of bytes - foreach (var dataBlock in dataBlocks) - { - byte[] codewordBytes = dataBlock.Codewords; - int numDataCodewords = dataBlock.NumDataCodewords; - if (!correctErrors(codewordBytes, numDataCodewords)) - return null; - for (int i = 0; i < numDataCodewords; i++) - { - resultBytes[resultOffset++] = codewordBytes[i]; - } - } - - // Decode the contents of that stream of bytes - return DecodedBitStreamParser.decode(resultBytes, version, ecLevel, hints); - } - - /// - ///

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - /// correct the errors in-place using Reed-Solomon error correction.

- ///
- /// data and error correction codewords - /// number of codewords that are data bytes - /// - private bool correctErrors(byte[] codewordBytes, int numDataCodewords) - { - int numCodewords = codewordBytes.Length; - // First read into an array of ints - int[] codewordsInts = new int[numCodewords]; - for (int i = 0; i < numCodewords; i++) - { - codewordsInts[i] = codewordBytes[i] & 0xFF; - } - int numECCodewords = codewordBytes.Length - numDataCodewords; - - if (!rsDecoder.decode(codewordsInts, numECCodewords)) - return false; - - // Copy back into array of bytes -- only need to worry about the bytes that were data - // We don't care about errors in the error-correction codewords - for (int i = 0; i < numDataCodewords; i++) - { - codewordBytes[i] = (byte)codewordsInts[i]; - } - - return true; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/ErrorCorrectionLevel.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/ErrorCorrectionLevel.cs deleted file mode 100755 index f3b49347..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/ErrorCorrectionLevel.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.QrCode.Internal -{ - /// - ///

See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels - /// defined by the QR code standard.

- ///
- /// Sean Owen - public sealed class ErrorCorrectionLevel - { - /// L = ~7% correction - public static readonly ErrorCorrectionLevel L = new ErrorCorrectionLevel(0, 0x01, "L"); - /// M = ~15% correction - public static readonly ErrorCorrectionLevel M = new ErrorCorrectionLevel(1, 0x00, "M"); - /// Q = ~25% correction - public static readonly ErrorCorrectionLevel Q = new ErrorCorrectionLevel(2, 0x03, "Q"); - /// H = ~30% correction - public static readonly ErrorCorrectionLevel H = new ErrorCorrectionLevel(3, 0x02, "H"); - - private static readonly ErrorCorrectionLevel[] FOR_BITS = new [] { M, L, H, Q }; - - private readonly int bits; - - private ErrorCorrectionLevel(int ordinal, int bits, String name) - { - this.ordinal_Renamed_Field = ordinal; - this.bits = bits; - this.name = name; - } - - /// - /// Gets the bits. - /// - public int Bits - { - get - { - return bits; - } - } - - /// - /// Gets the name. - /// - public String Name - { - get - { - return name; - } - } - - private readonly int ordinal_Renamed_Field; - private readonly String name; - - /// - /// Ordinals this instance. - /// - /// - public int ordinal() - { - return ordinal_Renamed_Field; - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override String ToString() - { - return name; - } - - /// - /// Fors the bits. - /// - /// int containing the two bits encoding a QR Code's error correction level - /// - /// representing the encoded error correction level - /// - public static ErrorCorrectionLevel forBits(int bits) - { - if (bits < 0 || bits >= FOR_BITS.Length) - { - throw new ArgumentException(); - } - return FOR_BITS[bits]; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/FormatInformation.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/FormatInformation.cs deleted file mode 100755 index 88b5045e..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/FormatInformation.cs +++ /dev/null @@ -1,197 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.QrCode.Internal -{ - - ///

Encapsulates a QR Code's format information, including the data mask used and - /// error correction level.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - /// - /// - /// - /// - sealed class FormatInformation - { - private const int FORMAT_INFO_MASK_QR = 0x5412; - - /// See ISO 18004:2006, Annex C, Table C.1 - private static readonly int[][] FORMAT_INFO_DECODE_LOOKUP = new int[][] - { - new [] { 0x5412, 0x00 }, - new [] { 0x5125, 0x01 }, - new [] { 0x5E7C, 0x02 }, - new [] { 0x5B4B, 0x03 }, - new [] { 0x45F9, 0x04 }, - new [] { 0x40CE, 0x05 }, - new [] { 0x4F97, 0x06 }, - new [] { 0x4AA0, 0x07 }, - new [] { 0x77C4, 0x08 }, - new [] { 0x72F3, 0x09 }, - new [] { 0x7DAA, 0x0A }, - new [] { 0x789D, 0x0B }, - new [] { 0x662F, 0x0C }, - new [] { 0x6318, 0x0D }, - new [] { 0x6C41, 0x0E }, - new [] { 0x6976, 0x0F }, - new [] { 0x1689, 0x10 }, - new [] { 0x13BE, 0x11 }, - new [] { 0x1CE7, 0x12 }, - new [] { 0x19D0, 0x13 }, - new [] { 0x0762, 0x14 }, - new [] { 0x0255, 0x15 }, - new [] { 0x0D0C, 0x16 }, - new [] { 0x083B, 0x17 }, - new [] { 0x355F, 0x18 }, - new [] { 0x3068, 0x19 }, - new [] { 0x3F31, 0x1A }, - new [] { 0x3A06, 0x1B }, - new [] { 0x24B4, 0x1C }, - new [] { 0x2183, 0x1D }, - new [] { 0x2EDA, 0x1E }, - new [] { 0x2BED, 0x1F } - }; - - /// Offset i holds the number of 1 bits in the binary representation of i - private static readonly int[] BITS_SET_IN_HALF_BYTE = new [] - { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; - - private readonly ErrorCorrectionLevel errorCorrectionLevel; - private readonly byte dataMask; - - private FormatInformation(int formatInfo) - { - // Bits 3,4 - errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); - // Bottom 3 bits - dataMask = (byte)(formatInfo & 0x07); - } - - internal static int numBitsDiffering(int a, int b) - { - a ^= b; // a now has a 1 bit exactly where its bit differs with b's - // Count bits set quickly with a series of lookups: - return BITS_SET_IN_HALF_BYTE[a & 0x0F] + - BITS_SET_IN_HALF_BYTE[(((int)((uint)a >> 4)) & 0x0F)] + - BITS_SET_IN_HALF_BYTE[(((int)((uint)a >> 8)) & 0x0F)] + - BITS_SET_IN_HALF_BYTE[(((int)((uint)a >> 12)) & 0x0F)] + - BITS_SET_IN_HALF_BYTE[(((int)((uint)a >> 16)) & 0x0F)] + - BITS_SET_IN_HALF_BYTE[(((int)((uint)a >> 20)) & 0x0F)] + - BITS_SET_IN_HALF_BYTE[(((int)((uint)a >> 24)) & 0x0F)] + - BITS_SET_IN_HALF_BYTE[(((int)((uint)a >> 28)) & 0x0F)]; - } - - /// - /// Decodes the format information. - /// - /// format info indicator, with mask still applied - /// The masked format info2. - /// - /// information about the format it specifies, or null - /// if doesn't seem to match any known pattern - /// - internal static FormatInformation decodeFormatInformation(int maskedFormatInfo1, int maskedFormatInfo2) - { - FormatInformation formatInfo = doDecodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2); - if (formatInfo != null) - { - return formatInfo; - } - // Should return null, but, some QR codes apparently - // do not mask this info. Try again by actually masking the pattern - // first - return doDecodeFormatInformation(maskedFormatInfo1 ^ FORMAT_INFO_MASK_QR, - maskedFormatInfo2 ^ FORMAT_INFO_MASK_QR); - } - - private static FormatInformation doDecodeFormatInformation(int maskedFormatInfo1, int maskedFormatInfo2) - { - // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing - int bestDifference = Int32.MaxValue; - int bestFormatInfo = 0; - foreach (var decodeInfo in FORMAT_INFO_DECODE_LOOKUP) - { - int targetInfo = decodeInfo[0]; - if (targetInfo == maskedFormatInfo1 || targetInfo == maskedFormatInfo2) - { - // Found an exact match - return new FormatInformation(decodeInfo[1]); - } - int bitsDifference = numBitsDiffering(maskedFormatInfo1, targetInfo); - if (bitsDifference < bestDifference) - { - bestFormatInfo = decodeInfo[1]; - bestDifference = bitsDifference; - } - if (maskedFormatInfo1 != maskedFormatInfo2) - { - // also try the other option - bitsDifference = numBitsDiffering(maskedFormatInfo2, targetInfo); - if (bitsDifference < bestDifference) - { - bestFormatInfo = decodeInfo[1]; - bestDifference = bitsDifference; - } - } - } - // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits - // differing means we found a match - if (bestDifference <= 3) - { - return new FormatInformation(bestFormatInfo); - } - return null; - } - - internal ErrorCorrectionLevel ErrorCorrectionLevel - { - get - { - return errorCorrectionLevel; - } - } - - internal byte DataMask - { - get - { - return dataMask; - } - } - - public override int GetHashCode() - { - return (errorCorrectionLevel.ordinal() << 3) | dataMask; - } - - public override bool Equals(Object o) - { - if (!(o is FormatInformation)) - { - return false; - } - var other = (FormatInformation)o; - return errorCorrectionLevel == other.errorCorrectionLevel && dataMask == other.dataMask; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Mode.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Mode.cs deleted file mode 100755 index 548ea6d7..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Mode.cs +++ /dev/null @@ -1,179 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.QrCode.Internal -{ - /// - ///

See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which - /// data can be encoded to bits in the QR code standard.

- ///
- /// Sean Owen - public sealed class Mode - { - /// - /// Gets the name. - /// - public String Name - { - get - { - return name; - } - } - - // No, we can't use an enum here. J2ME doesn't support it. - - /// - /// - /// - public static readonly Mode TERMINATOR = new Mode(new int[] { 0, 0, 0 }, 0x00, "TERMINATOR"); // Not really a mode... - /// - /// - /// - public static readonly Mode NUMERIC = new Mode(new int[] { 10, 12, 14 }, 0x01, "NUMERIC"); - /// - /// - /// - public static readonly Mode ALPHANUMERIC = new Mode(new int[] { 9, 11, 13 }, 0x02, "ALPHANUMERIC"); - /// - /// - /// - public static readonly Mode STRUCTURED_APPEND = new Mode(new int[] { 0, 0, 0 }, 0x03, "STRUCTURED_APPEND"); // Not supported - /// - /// - /// - public static readonly Mode BYTE = new Mode(new int[] { 8, 16, 16 }, 0x04, "BYTE"); - /// - /// - /// - public static readonly Mode ECI = new Mode(null, 0x07, "ECI"); // character counts don't apply - /// - /// - /// - public static readonly Mode KANJI = new Mode(new int[] { 8, 10, 12 }, 0x08, "KANJI"); - /// - /// - /// - public static readonly Mode FNC1_FIRST_POSITION = new Mode(null, 0x05, "FNC1_FIRST_POSITION"); - /// - /// - /// - public static readonly Mode FNC1_SECOND_POSITION = new Mode(null, 0x09, "FNC1_SECOND_POSITION"); - /// See GBT 18284-2000; "Hanzi" is a transliteration of this mode name. - public static readonly Mode HANZI = new Mode(new int[] { 8, 10, 12 }, 0x0D, "HANZI"); - - private readonly int[] characterCountBitsForVersions; - private readonly int bits; - private readonly String name; - - private Mode(int[] characterCountBitsForVersions, int bits, System.String name) - { - this.characterCountBitsForVersions = characterCountBitsForVersions; - this.bits = bits; - this.name = name; - } - - /// - /// Fors the bits. - /// - /// four bits encoding a QR Code data mode - /// - /// encoded by these bits - /// - /// if bits do not correspond to a known mode - public static Mode forBits(int bits) - { - switch (bits) - { - case 0x0: - return TERMINATOR; - case 0x1: - return NUMERIC; - case 0x2: - return ALPHANUMERIC; - case 0x3: - return STRUCTURED_APPEND; - case 0x4: - return BYTE; - case 0x5: - return FNC1_FIRST_POSITION; - case 0x7: - return ECI; - case 0x8: - return KANJI; - case 0x9: - return FNC1_SECOND_POSITION; - case 0xD: - // 0xD is defined in GBT 18284-2000, may not be supported in foreign country - return HANZI; - default: - throw new ArgumentException(); - } - } - - /// version in question - /// - /// number of bits used, in this QR Code symbol {@link Version}, to encode the - /// count of characters that will follow encoded in this {@link Mode} - /// - public int getCharacterCountBits(Version version) - { - if (characterCountBitsForVersions == null) - { - throw new ArgumentException("Character count doesn't apply to this mode"); - } - int number = version.VersionNumber; - int offset; - if (number <= 9) - { - offset = 0; - } - else if (number <= 26) - { - offset = 1; - } - else - { - offset = 2; - } - return characterCountBitsForVersions[offset]; - } - - /// - /// Gets the bits. - /// - public int Bits - { - get - { - return bits; - } - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override String ToString() - { - return name; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/QRCodeDecoderMetaData.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/QRCodeDecoderMetaData.cs deleted file mode 100755 index cc059aa9..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/QRCodeDecoderMetaData.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2013 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace ZXing.QrCode.Internal -{ - /// - /// Meta-data container for QR Code decoding. Instances of this class may be used to convey information back to the - /// decoding caller. Callers are expected to process this. - /// - public sealed class QRCodeDecoderMetaData - { - private readonly bool mirrored; - - /// - /// Initializes a new instance of the class. - /// - /// if set to true [mirrored]. - public QRCodeDecoderMetaData(bool mirrored) - { - this.mirrored = mirrored; - } - - /// - /// true if the QR Code was mirrored. - /// - public bool IsMirrored - { - get { return mirrored; } - } - - /// - /// Apply the result points' order correction due to mirroring. - /// - /// Array of points to apply mirror correction to. - public void applyMirroredCorrection(ResultPoint[] points) - { - if (!mirrored || points == null || points.Length < 3) - { - return; - } - ResultPoint bottomLeft = points[0]; - points[0] = points[2]; - points[2] = bottomLeft; - // No need to 'fix' top-left and alignment pattern. - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Version.cs b/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Version.cs deleted file mode 100755 index e619933d..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/decoder/Version.cs +++ /dev/null @@ -1,424 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -using ZXing.Common; - -namespace ZXing.QrCode.Internal -{ - /// - /// See ISO 18004:2006 Annex D - /// - /// Sean Owen - public sealed class Version - { - /// See ISO 18004:2006 Annex D. - /// Element i represents the raw version bits that specify version i + 7 - /// - private static readonly int[] VERSION_DECODE_INFO = new[] - { - 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, - 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, - 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, - 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, - 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, - 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, - 0x2542E, 0x26A64, 0x27541, 0x28C69 - }; - - private static readonly Version[] VERSIONS = buildVersions(); - - private readonly int versionNumber; - private readonly int[] alignmentPatternCenters; - private readonly ECBlocks[] ecBlocks; - private readonly int totalCodewords; - - private Version(int versionNumber, int[] alignmentPatternCenters, params ECBlocks[] ecBlocks) - { - this.versionNumber = versionNumber; - this.alignmentPatternCenters = alignmentPatternCenters; - this.ecBlocks = ecBlocks; - int total = 0; - int ecCodewords = ecBlocks[0].ECCodewordsPerBlock; - ECB[] ecbArray = ecBlocks[0].getECBlocks(); - foreach (var ecBlock in ecbArray) - { - total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); - } - this.totalCodewords = total; - } - - /// - /// Gets the version number. - /// - public int VersionNumber - { - get - { - return versionNumber; - } - - } - - /// - /// Gets the alignment pattern centers. - /// - public int[] AlignmentPatternCenters - { - get - { - return alignmentPatternCenters; - } - - } - - /// - /// Gets the total codewords. - /// - public int TotalCodewords - { - get - { - return totalCodewords; - } - - } - - /// - /// Gets the dimension for version. - /// - public int DimensionForVersion - { - get - { - return 17 + 4 * versionNumber; - } - - } - - /// - /// Gets the EC blocks for level. - /// - /// The ec level. - /// - public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel) - { - return ecBlocks[ecLevel.ordinal()]; - } - - ///

Deduces version information purely from QR Code dimensions.

- /// - ///
- /// dimension in modules - /// - /// for a QR Code of that dimension or null - public static Version getProvisionalVersionForDimension(int dimension) - { - if (dimension % 4 != 1) - { - return null; - } - try - { - return getVersionForNumber((dimension - 17) >> 2); - } - catch (ArgumentException) - { - return null; - } - } - - /// - /// Gets the version for number. - /// - /// The version number. - /// - public static Version getVersionForNumber(int versionNumber) - { - if (versionNumber < 1 || versionNumber > 40) - { - throw new ArgumentException(); - } - return VERSIONS[versionNumber - 1]; - } - - internal static Version decodeVersionInformation(int versionBits) - { - int bestDifference = Int32.MaxValue; - int bestVersion = 0; - for (int i = 0; i < VERSION_DECODE_INFO.Length; i++) - { - int targetVersion = VERSION_DECODE_INFO[i]; - // Do the version info bits match exactly? done. - if (targetVersion == versionBits) - { - return getVersionForNumber(i + 7); - } - // Otherwise see if this is the closest to a real version info bit string - // we have seen so far - int bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); - if (bitsDifference < bestDifference) - { - bestVersion = i + 7; - bestDifference = bitsDifference; - } - } - // We can tolerate up to 3 bits of error since no two version info codewords will - // differ in less than 8 bits. - if (bestDifference <= 3) - { - return getVersionForNumber(bestVersion); - } - // If we didn't find a close enough match, fail - return null; - } - - /// See ISO 18004:2006 Annex E - internal BitMatrix buildFunctionPattern() - { - int dimension = DimensionForVersion; - BitMatrix bitMatrix = new BitMatrix(dimension); - - // Top left finder pattern + separator + format - bitMatrix.setRegion(0, 0, 9, 9); - // Top right finder pattern + separator + format - bitMatrix.setRegion(dimension - 8, 0, 8, 9); - // Bottom left finder pattern + separator + format - bitMatrix.setRegion(0, dimension - 8, 9, 8); - - // Alignment patterns - int max = alignmentPatternCenters.Length; - for (int x = 0; x < max; x++) - { - int i = alignmentPatternCenters[x] - 2; - for (int y = 0; y < max; y++) - { - if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) - { - // No alignment patterns near the three finder paterns - continue; - } - bitMatrix.setRegion(alignmentPatternCenters[y] - 2, i, 5, 5); - } - } - - // Vertical timing pattern - bitMatrix.setRegion(6, 9, 1, dimension - 17); - // Horizontal timing pattern - bitMatrix.setRegion(9, 6, dimension - 17, 1); - - if (versionNumber > 6) - { - // Version info, top right - bitMatrix.setRegion(dimension - 11, 0, 3, 6); - // Version info, bottom left - bitMatrix.setRegion(0, dimension - 11, 6, 3); - } - - return bitMatrix; - } - - ///

Encapsulates a set of error-correction blocks in one symbol version. Most versions will - /// use blocks of differing sizes within one version, so, this encapsulates the parameters for - /// each set of blocks. It also holds the number of error-correction codewords per block since it - /// will be the same across all blocks within one version.

- ///
- public sealed class ECBlocks - { - private readonly int ecCodewordsPerBlock; - private readonly ECB[] ecBlocks; - - internal ECBlocks(int ecCodewordsPerBlock, params ECB[] ecBlocks) - { - this.ecCodewordsPerBlock = ecCodewordsPerBlock; - this.ecBlocks = ecBlocks; - } - - /// - /// Gets the EC codewords per block. - /// - public int ECCodewordsPerBlock - { - get - { - return ecCodewordsPerBlock; - } - } - - /// - /// Gets the num blocks. - /// - public int NumBlocks - { - get - { - int total = 0; - foreach (var ecBlock in ecBlocks) - { - total += ecBlock.Count; - } - return total; - } - } - - /// - /// Gets the total EC codewords. - /// - public int TotalECCodewords - { - get - { - return ecCodewordsPerBlock * NumBlocks; - } - } - - /// - /// Gets the EC blocks. - /// - /// - public ECB[] getECBlocks() - { - return ecBlocks; - } - } - - ///

Encapsualtes the parameters for one error-correction block in one symbol version. - /// This includes the number of data codewords, and the number of times a block with these - /// parameters is used consecutively in the QR code version's format.

- ///
- public sealed class ECB - { - private readonly int count; - private readonly int dataCodewords; - - internal ECB(int count, int dataCodewords) - { - this.count = count; - this.dataCodewords = dataCodewords; - } - - /// - /// Gets the count. - /// - public int Count - { - get - { - return count; - } - - } - /// - /// Gets the data codewords. - /// - public int DataCodewords - { - get - { - return dataCodewords; - } - - } - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override String ToString() - { - return Convert.ToString(versionNumber); - } - - /// See ISO 18004:2006 6.5.1 Table 9 - private static Version[] buildVersions() - { - return new Version[]{ - new Version(1, new int[]{}, - new ECBlocks(7, new ECB(1, 19)), - new ECBlocks(10, new ECB(1, 16)), - new ECBlocks(13, new ECB(1, 13)), - new ECBlocks(17, new ECB(1, 9))), - new Version(2, new int[]{6, 18}, - new ECBlocks(10, new ECB(1, 34)), - new ECBlocks(16, new ECB(1, 28)), - new ECBlocks(22, new ECB(1, 22)), - new ECBlocks(28, new ECB(1, 16))), - new Version(3, new int[]{6, 22}, - new ECBlocks(15, new ECB(1, 55)), - new ECBlocks(26, new ECB(1, 44)), - new ECBlocks(18, new ECB(2, 17)), - new ECBlocks(22, new ECB(2, 13))), - new Version(4, new int[]{6, 26}, - new ECBlocks(20, new ECB(1, 80)), - new ECBlocks(18, new ECB(2, 32)), - new ECBlocks(26, new ECB(2, 24)), - new ECBlocks(16, new ECB(4, 9))), - new Version(5, new int[]{6, 30}, - new ECBlocks(26, new ECB(1, 108)), - new ECBlocks(24, new ECB(2, 43)), - new ECBlocks(18, new ECB(2, 15), - new ECB(2, 16)), - new ECBlocks(22, new ECB(2, 11), - new ECB(2, 12))), - new Version(6, new int[]{6, 34}, - new ECBlocks(18, new ECB(2, 68)), - new ECBlocks(16, new ECB(4, 27)), - new ECBlocks(24, new ECB(4, 19)), - new ECBlocks(28, new ECB(4, 15))), - new Version(7, new int[]{6, 22, 38}, - new ECBlocks(20, new ECB(2, 78)), - new ECBlocks(18, new ECB(4, 31)), - new ECBlocks(18, new ECB(2, 14), - new ECB(4, 15)), - new ECBlocks(26, new ECB(4, 13), - new ECB(1, 14))), - new Version(8, new int[]{6, 24, 42}, - new ECBlocks(24, new ECB(2, 97)), - new ECBlocks(22, new ECB(2, 38), - new ECB(2, 39)), - new ECBlocks(22, new ECB(4, 18), - new ECB(2, 19)), - new ECBlocks(26, new ECB(4, 14), - new ECB(2, 15))), - new Version(9, new int[]{6, 26, 46}, - new ECBlocks(30, new ECB(2, 116)), - new ECBlocks(22, new ECB(3, 36), - new ECB(2, 37)), - new ECBlocks(20, new ECB(4, 16), - new ECB(4, 17)), - new ECBlocks(24, new ECB(4, 12), - new ECB(4, 13))), - new Version(10, new int[]{6, 28, 50}, - new ECBlocks(18, new ECB(2, 68), - new ECB(2, 69)), - new ECBlocks(26, new ECB(4, 43), - new ECB(1, 44)), - new ECBlocks(24, new ECB(6, 19), - new ECB(2, 20)), - new ECBlocks(28, new ECB(6, 15), - new ECB(2, 16))), - new Version(11, new int[]{6, 30, 54}, new ECBlocks(20, new ECB(4, 81)), - new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), new Version(12, new int[]{6, 32, 58}, new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), new Version(13, new int[]{6, 34, 62}, new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), new Version(14, new int[]{6, 26, 46, 66}, new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), new Version(15, new int[]{6, 26, 48, 70}, new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), new Version(16, new int[]{6, 26, 50, 74}, new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), new Version(17, new int[]{6, 30, 54, 78}, new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), new Version(18, new int[]{6, 30, 56, 82}, new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), new Version(19, new int[]{6, 30, 58, 86}, new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), - new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), new Version(20, new int[]{6, 34, 62, 90}, new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), new Version(21, new int[]{6, 28, 50, 72, 94}, new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), new Version(22, new int[]{6, 26, 50, 74, 98}, new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), new Version(23, new int[]{6, 30, 54, 74, 102}, new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), new Version(24, new int[]{6, 28, 54, 80, 106}, new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), new Version(25, new int[]{6, 32, 58, 84, 110}, new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), new Version(26, new int[]{6, 30, 58, 86, 114}, new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), new Version(27, new int[]{6, 34, 62, 90, 118}, new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), - new ECB(28, 16))), new Version(28, new int[]{6, 26, 50, 74, 98, 122}, new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), new Version(29, new int[]{6, 30, 54, 78, 102, 126}, new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), new Version(30, new int[]{6, 26, 52, 78, 104, 130}, new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), new Version(31, new int[]{6, 30, 56, 82, 108, 134}, new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), new Version(32, new int[]{6, 34, 60, 86, 112, 138}, new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), new Version(33, new int[]{6, 30, 58, 86, 114, 142}, new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), new Version(34, new int[]{6, 34, 62, 90, 118, 146}, new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), new Version(35, new int[]{6, 30, 54, 78, 102, 126, 150}, new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new - ECB(14, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), new Version(36, new int[]{6, 24, 50, 76, 102, 128, 154}, new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), new Version(37, new int[]{6, 28, 54, 80, 106, 132, 158}, new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), new Version(38, new int[]{6, 32, 58, 84, 110, 136, 162}, new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), new Version(39, new int[]{6, 26, 54, 82, 110, 138, 166}, new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), new Version(40, new int[]{6, 30, 58, 86, 114, 142, 170}, new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))}; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPattern.cs b/shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPattern.cs deleted file mode 100755 index e7dd9460..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPattern.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.QrCode.Internal -{ - ///

Encapsulates an alignment pattern, which are the smaller square patterns found in - /// all but the simplest QR Codes.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class AlignmentPattern : ResultPoint - { - private float estimatedModuleSize; - - internal AlignmentPattern(float posX, float posY, float estimatedModuleSize) - : base(posX, posY) - { - this.estimatedModuleSize = estimatedModuleSize; - } - - ///

Determines if this alignment pattern "about equals" an alignment pattern at the stated - /// position and size -- meaning, it is at nearly the same center with nearly the same size.

- ///
- internal bool aboutEquals(float moduleSize, float i, float j) - { - if (Math.Abs(i - Y) <= moduleSize && Math.Abs(j - X) <= moduleSize) - { - float moduleSizeDiff = Math.Abs(moduleSize - estimatedModuleSize); - return moduleSizeDiff <= 1.0f || moduleSizeDiff <= estimatedModuleSize; - } - return false; - } - - /// - /// Combines this object's current estimate of a finder pattern position and module size - /// with a new estimate. It returns a new {@code FinderPattern} containing an average of the two. - /// - /// The i. - /// The j. - /// New size of the module. - /// - internal AlignmentPattern combineEstimate(float i, float j, float newModuleSize) - { - float combinedX = (X + j) / 2.0f; - float combinedY = (Y + i) / 2.0f; - float combinedModuleSize = (estimatedModuleSize + newModuleSize) / 2.0f; - return new AlignmentPattern(combinedX, combinedY, combinedModuleSize); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPatternFinder.cs b/shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPatternFinder.cs deleted file mode 100755 index b8cdec5b..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPatternFinder.cs +++ /dev/null @@ -1,324 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; - -using ZXing.Common; - -namespace ZXing.QrCode.Internal -{ - ///

This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder - /// patterns but are smaller and appear at regular intervals throughout the image.

- /// - ///

At the moment this only looks for the bottom-right alignment pattern.

- /// - ///

This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied, - /// pasted and stripped down here for maximum performance but does unfortunately duplicate - /// some code.

- /// - ///

This class is thread-safe but not reentrant. Each thread must allocate its own object.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class AlignmentPatternFinder - { - private readonly BitMatrix image; - private readonly IList possibleCenters; - private readonly int startX; - private readonly int startY; - private readonly int width; - private readonly int height; - private readonly float moduleSize; - private readonly int[] crossCheckStateCount; - private readonly ResultPointCallback resultPointCallback; - - ///

Creates a finder that will look in a portion of the whole image.

- /// - ///
- /// image to search - /// - /// left column from which to start searching - /// - /// top row from which to start searching - /// - /// width of region to search - /// - /// height of region to search - /// - /// estimated module size so far - /// - internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback) - { - this.image = image; - this.possibleCenters = new List(5); - this.startX = startX; - this.startY = startY; - this.width = width; - this.height = height; - this.moduleSize = moduleSize; - this.crossCheckStateCount = new int[3]; - this.resultPointCallback = resultPointCallback; - } - - ///

This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since - /// it's pretty performance-critical and so is written to be fast foremost.

- /// - ///
- /// {@link AlignmentPattern} if found - /// - internal AlignmentPattern find() - { - int startX = this.startX; - int height = this.height; - int maxJ = startX + width; - int middleI = startY + (height >> 1); - // We are looking for black/white/black modules in 1:1:1 ratio; - // this tracks the number of black/white/black modules seen so far - int[] stateCount = new int[3]; - for (int iGen = 0; iGen < height; iGen++) - { - // Search from middle outwards - int i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1)); - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - int j = startX; - // Burn off leading white pixels before anything else; if we start in the middle of - // a white run, it doesn't make sense to count its length, since we don't know if the - // white run continued to the left of the start point - while (j < maxJ && !image[j, i]) - { - j++; - } - int currentState = 0; - while (j < maxJ) - { - if (image[j, i]) - { - // Black pixel - if (currentState == 1) - { - // Counting black pixels - stateCount[currentState]++; - } - else - { - // Counting white pixels - if (currentState == 2) - { - // A winner? - if (foundPatternCross(stateCount)) - { - // Yes - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j); - if (confirmed != null) - { - return confirmed; - } - } - stateCount[0] = stateCount[2]; - stateCount[1] = 1; - stateCount[2] = 0; - currentState = 1; - } - else - { - stateCount[++currentState]++; - } - } - } - else - { - // White pixel - if (currentState == 1) - { - // Counting black pixels - currentState++; - } - stateCount[currentState]++; - } - j++; - } - if (foundPatternCross(stateCount)) - { - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ); - if (confirmed != null) - { - return confirmed; - } - } - } - - // Hmm, nothing we saw was observed and confirmed twice. If we had - // any guess at all, return it. - if (possibleCenters.Count != 0) - { - return possibleCenters[0]; - } - - return null; - } - - /// Given a count of black/white/black pixels just seen and an end position, - /// figures the location of the center of this black/white/black run. - /// - private static float? centerFromEnd(int[] stateCount, int end) - { - var result = (end - stateCount[2]) - stateCount[1] / 2.0f; - if (Single.IsNaN(result)) - return null; - return result; - } - - /// count of black/white/black pixels just read - /// - /// true iff the proportions of the counts is close enough to the 1/1/1 ratios - /// used by alignment patterns to be considered a match - /// - private bool foundPatternCross(int[] stateCount) - { - float maxVariance = moduleSize / 2.0f; - for (int i = 0; i < 3; i++) - { - if (Math.Abs(moduleSize - stateCount[i]) >= maxVariance) - { - return false; - } - } - return true; - } - - /// - ///

After a horizontal scan finds a potential alignment pattern, this method - /// "cross-checks" by scanning down vertically through the center of the possible - /// alignment pattern to see if the same proportion is detected.

- ///
- /// row where an alignment pattern was detected - /// center of the section that appears to cross an alignment pattern - /// maximum reasonable number of modules that should be - /// observed in any reading state, based on the results of the horizontal scan - /// The original state count total. - /// - /// vertical center of alignment pattern, or null if not found - /// - private float? crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) - { - int maxI = image.Height; - int[] stateCount = crossCheckStateCount; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - - // Start counting up from center - int i = startI; - while (i >= 0 && image[centerJ, i] && stateCount[1] <= maxCount) - { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) - { - return null; - } - while (i >= 0 && !image[centerJ, i] && stateCount[0] <= maxCount) - { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) - { - return null; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image[centerJ, i] && stateCount[1] <= maxCount) - { - stateCount[1]++; - i++; - } - if (i == maxI || stateCount[1] > maxCount) - { - return null; - } - while (i < maxI && !image[centerJ, i] && stateCount[2] <= maxCount) - { - stateCount[2]++; - i++; - } - if (stateCount[2] > maxCount) - { - return null; - } - - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) - { - return null; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : null; - } - - ///

This is called when a horizontal scan finds a possible alignment pattern. It will - /// cross check with a vertical scan, and if successful, will see if this pattern had been - /// found on a previous horizontal scan. If so, we consider it confirmed and conclude we have - /// found the alignment pattern.

- /// - ///
- /// reading state module counts from horizontal scan - /// - /// row where alignment pattern may be found - /// - /// end of possible alignment pattern in row - /// - /// {@link AlignmentPattern} if we have found the same pattern twice, or null if not - /// - private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) - { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - float? centerJ = centerFromEnd(stateCount, j); - if (centerJ == null) - return null; - float? centerI = crossCheckVertical(i, (int)centerJ, 2 * stateCount[1], stateCountTotal); - if (centerI != null) - { - float estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f; - foreach (var center in possibleCenters) - { - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI.Value, centerJ.Value)) - { - return center.combineEstimate(centerI.Value, centerJ.Value, estimatedModuleSize); - } - } - // Hadn't found this before; save it - var point = new AlignmentPattern(centerJ.Value, centerI.Value, estimatedModuleSize); - possibleCenters.Add(point); - if (resultPointCallback != null) - { - resultPointCallback(point); - } - } - return null; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/detector/Detector.cs b/shadowsocks-csharp/3rd/zxing/qrcode/detector/Detector.cs deleted file mode 100755 index 7ae8e3db..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/detector/Detector.cs +++ /dev/null @@ -1,429 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; - -using ZXing.Common; -using ZXing.Common.Detector; - -namespace ZXing.QrCode.Internal -{ - /// - ///

Encapsulates logic that can detect a QR Code in an image, even if the QR Code - /// is rotated or skewed, or partially obscured.

- ///
- /// Sean Owen - public class Detector - { - private readonly BitMatrix image; - private ResultPointCallback resultPointCallback; - - /// - /// Initializes a new instance of the class. - /// - /// The image. - public Detector(BitMatrix image) - { - this.image = image; - } - - /// - /// Gets the image. - /// - virtual protected internal BitMatrix Image - { - get - { - return image; - } - } - - /// - /// Gets the result point callback. - /// - virtual protected internal ResultPointCallback ResultPointCallback - { - get - { - return resultPointCallback; - } - } - - /// - ///

Detects a QR Code in an image, simply.

- ///
- /// - /// encapsulating results of detecting a QR Code - /// - public virtual DetectorResult detect() - { - return detect(null); - } - - /// - ///

Detects a QR Code in an image, simply.

- ///
- /// optional hints to detector - /// - /// encapsulating results of detecting a QR Code - /// - public virtual DetectorResult detect(IDictionary hints) - { - resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null : (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]; - - FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback); - FinderPatternInfo info = finder.find(hints); - if (info == null) - return null; - - return processFinderPatternInfo(info); - } - - /// - /// Processes the finder pattern info. - /// - /// The info. - /// - protected internal virtual DetectorResult processFinderPatternInfo(FinderPatternInfo info) - { - FinderPattern topLeft = info.TopLeft; - FinderPattern topRight = info.TopRight; - FinderPattern bottomLeft = info.BottomLeft; - - float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); - if (moduleSize < 1.0f) - { - return null; - } - int dimension; - if (!computeDimension(topLeft, topRight, bottomLeft, moduleSize, out dimension)) - return null; - Internal.Version provisionalVersion = Internal.Version.getProvisionalVersionForDimension(dimension); - if (provisionalVersion == null) - return null; - int modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; - - AlignmentPattern alignmentPattern = null; - // Anything above version 1 has an alignment pattern - if (provisionalVersion.AlignmentPatternCenters.Length > 0) - { - - // Guess where a "bottom right" finder pattern would have been - float bottomRightX = topRight.X - topLeft.X + bottomLeft.X; - float bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; - - // Estimate that alignment pattern is closer by 3 modules - // from "bottom right" to known top left location - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float correctionToTopLeft = 1.0f - 3.0f / (float)modulesBetweenFPCenters; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int estAlignmentX = (int)(topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int estAlignmentY = (int)(topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); - - // Kind of arbitrary -- expand search radius before giving up - for (int i = 4; i <= 16; i <<= 1) - { - alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float)i); - if (alignmentPattern == null) - continue; - break; - } - // If we didn't find alignment pattern... well try anyway without it - } - - PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); - - BitMatrix bits = sampleGrid(image, transform, dimension); - if (bits == null) - return null; - - ResultPoint[] points; - if (alignmentPattern == null) - { - points = new ResultPoint[] { bottomLeft, topLeft, topRight }; - } - else - { - points = new ResultPoint[] { bottomLeft, topLeft, topRight, alignmentPattern }; - } - return new DetectorResult(bits, points); - } - - private static PerspectiveTransform createTransform(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint alignmentPattern, int dimension) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float dimMinusThree = (float)dimension - 3.5f; - float bottomRightX; - float bottomRightY; - float sourceBottomRightX; - float sourceBottomRightY; - if (alignmentPattern != null) - { - bottomRightX = alignmentPattern.X; - bottomRightY = alignmentPattern.Y; - sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f; - } - else - { - // Don't have an alignment pattern, just make up the bottom-right point - bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; - bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; - sourceBottomRightX = sourceBottomRightY = dimMinusThree; - } - - return PerspectiveTransform.quadrilateralToQuadrilateral( - 3.5f, - 3.5f, - dimMinusThree, - 3.5f, - sourceBottomRightX, - sourceBottomRightY, - 3.5f, - dimMinusThree, - topLeft.X, - topLeft.Y, - topRight.X, - topRight.Y, - bottomRightX, - bottomRightY, - bottomLeft.X, - bottomLeft.Y); - } - - private static BitMatrix sampleGrid(BitMatrix image, PerspectiveTransform transform, int dimension) - { - GridSampler sampler = GridSampler.Instance; - return sampler.sampleGrid(image, dimension, dimension, transform); - } - - ///

Computes the dimension (number of modules on a size) of the QR Code based on the position - /// of the finder patterns and estimated module size.

- ///
- private static bool computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize, out int dimension) - { - int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize); - int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize); - dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; - switch (dimension & 0x03) - { - // mod 4 - case 0: - dimension++; - break; - // 1? do nothing - case 2: - dimension--; - break; - case 3: - return true; - } - return true; - } - - ///

Computes an average estimated module size based on estimated derived from the positions - /// of the three finder patterns.

- ///
- protected internal virtual float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) - { - // Take the average - return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; - } - - ///

Estimates module size based on two finder patterns -- it uses - /// {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the - /// width of each, measuring along the axis between their centers.

- ///
- private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int)pattern.X, (int)pattern.Y, (int)otherPattern.X, (int)otherPattern.Y); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int)otherPattern.X, (int)otherPattern.Y, (int)pattern.X, (int)pattern.Y); - if (Single.IsNaN(moduleSizeEst1)) - { - return moduleSizeEst2 / 7.0f; - } - if (Single.IsNaN(moduleSizeEst2)) - { - return moduleSizeEst1 / 7.0f; - } - // Average them, and divide by 7 since we've counted the width of 3 black modules, - // and 1 white and 1 black module on either side. Ergo, divide sum by 14. - return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; - } - - /// See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of - /// a finder pattern by looking for a black-white-black run from the center in the direction - /// of another point (another finder pattern center), and in the opposite direction too. - /// - private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) - { - - float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); - - // Now count other way -- don't run off image though of course - float scale = 1.0f; - int otherToX = fromX - (toX - fromX); - if (otherToX < 0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float)fromX / (float)(fromX - otherToX); - otherToX = 0; - } - else if (otherToX >= image.Width) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float)(image.Width - 1 - fromX) / (float)(otherToX - fromX); - otherToX = image.Width - 1; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int otherToY = (int)(fromY - (toY - fromY) * scale); - - scale = 1.0f; - if (otherToY < 0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float)fromY / (float)(fromY - otherToY); - otherToY = 0; - } - else if (otherToY >= image.Height) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float)(image.Height - 1 - fromY) / (float)(otherToY - fromY); - otherToY = image.Height - 1; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - otherToX = (int)(fromX + (otherToX - fromX) * scale); - - result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); - return result - 1.0f; // -1 because we counted the middle pixel twice - } - - ///

This method traces a line from a point in the image, in the direction towards another point. - /// It begins in a black region, and keeps going until it finds white, then black, then white again. - /// It reports the distance from the start to this point.

- /// - ///

This is used when figuring out how wide a finder pattern is, when the finder pattern - /// may be skewed or rotated.

- ///
- private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) - { - // Mild variant of Bresenham's algorithm; - // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm - bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX); - if (steep) - { - int temp = fromX; - fromX = fromY; - fromY = temp; - temp = toX; - toX = toY; - toY = temp; - } - - int dx = Math.Abs(toX - fromX); - int dy = Math.Abs(toY - fromY); - int error = -dx >> 1; - int xstep = fromX < toX ? 1 : -1; - int ystep = fromY < toY ? 1 : -1; - - // In black pixels, looking for white, first or second time. - int state = 0; - // Loop up until x == toX, but not beyond - int xLimit = toX + xstep; - for (int x = fromX, y = fromY; x != xLimit; x += xstep) - { - int realX = steep ? y : x; - int realY = steep ? x : y; - - // Does current pixel mean we have moved white to black or vice versa? - // Scanning black in state 0,2 and white in state 1, so if we find the wrong - // color, advance to next state or end if we are in state 2 already - if ((state == 1) == image[realX, realY]) - { - if (state == 2) - { - return MathUtils.distance(x, y, fromX, fromY); - } - state++; - } - error += dy; - if (error > 0) - { - if (y == toY) - { - - - break; - } - y += ystep; - error -= dx; - } - } - // Found black-white-black; give the benefit of the doubt that the next pixel outside the image - // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a - // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this. - if (state == 2) - { - return MathUtils.distance(toX + xstep, toY, fromX, fromY); - } - // else we didn't find even black-white-black; no estimate is really possible - return Single.NaN; - - } - - /// - ///

Attempts to locate an alignment pattern in a limited region of the image, which is - /// guessed to contain it. This method uses {@link AlignmentPattern}.

- ///
- /// estimated module size so far - /// x coordinate of center of area probably containing alignment pattern - /// y coordinate of above - /// number of pixels in all directions to search from the center - /// - /// if found, or null otherwise - /// - protected AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor) - { - // Look for an alignment pattern (3 modules in size) around where it - // should be - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int allowance = (int)(allowanceFactor * overallEstModuleSize); - int alignmentAreaLeftX = Math.Max(0, estAlignmentX - allowance); - int alignmentAreaRightX = Math.Min(image.Width - 1, estAlignmentX + allowance); - if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) - { - return null; - } - - int alignmentAreaTopY = Math.Max(0, estAlignmentY - allowance); - int alignmentAreaBottomY = Math.Min(image.Height - 1, estAlignmentY + allowance); - - var alignmentFinder = new AlignmentPatternFinder( - image, - alignmentAreaLeftX, - alignmentAreaTopY, - alignmentAreaRightX - alignmentAreaLeftX, - alignmentAreaBottomY - alignmentAreaTopY, - overallEstModuleSize, - resultPointCallback); - - return alignmentFinder.find(); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPattern.cs b/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPattern.cs deleted file mode 100755 index 80469bf7..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPattern.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.QrCode.Internal -{ - /// - ///

Encapsulates a finder pattern, which are the three square patterns found in - /// the corners of QR Codes. It also encapsulates a count of similar finder patterns, - /// as a convenience to the finder's bookkeeping.

- ///
- /// Sean Owen - public sealed class FinderPattern : ResultPoint - { - private readonly float estimatedModuleSize; - private int count; - - internal FinderPattern(float posX, float posY, float estimatedModuleSize) - : this(posX, posY, estimatedModuleSize, 1) - { - this.estimatedModuleSize = estimatedModuleSize; - this.count = 1; - } - - internal FinderPattern(float posX, float posY, float estimatedModuleSize, int count) - : base(posX, posY) - { - this.estimatedModuleSize = estimatedModuleSize; - this.count = count; - } - - /// - /// Gets the size of the estimated module. - /// - /// - /// The size of the estimated module. - /// - public float EstimatedModuleSize - { - get - { - return estimatedModuleSize; - } - } - - internal int Count - { - get - { - return count; - } - } - - /* - internal void incrementCount() - { - this.count++; - } - */ - - ///

Determines if this finder pattern "about equals" a finder pattern at the stated - /// position and size -- meaning, it is at nearly the same center with nearly the same size.

- ///
- internal bool aboutEquals(float moduleSize, float i, float j) - { - if (Math.Abs(i - Y) <= moduleSize && Math.Abs(j - X) <= moduleSize) - { - float moduleSizeDiff = Math.Abs(moduleSize - estimatedModuleSize); - return moduleSizeDiff <= 1.0f || moduleSizeDiff <= estimatedModuleSize; - - } - return false; - } - - /// - /// Combines this object's current estimate of a finder pattern position and module size - /// with a new estimate. It returns a new {@code FinderPattern} containing a weighted average - /// based on count. - /// - /// The i. - /// The j. - /// New size of the module. - /// - internal FinderPattern combineEstimate(float i, float j, float newModuleSize) - { - int combinedCount = count + 1; - float combinedX = (count * X + j) / combinedCount; - float combinedY = (count * Y + i) / combinedCount; - float combinedModuleSize = (count * estimatedModuleSize + newModuleSize) / combinedCount; - return new FinderPattern(combinedX, combinedY, combinedModuleSize, combinedCount); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternFinder.cs b/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternFinder.cs deleted file mode 100755 index 7b4c5113..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternFinder.cs +++ /dev/null @@ -1,808 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; - -using ZXing.Common; - -namespace ZXing.QrCode.Internal -{ - /// - ///

This class attempts to find finder patterns in a QR Code. Finder patterns are the square - /// markers at three corners of a QR Code.

- /// - ///

This class is thread-safe but not reentrant. Each thread must allocate its own object. - ///

- /// Sean Owen - public class FinderPatternFinder - { - private const int CENTER_QUORUM = 2; - /// - /// 1 pixel/module times 3 modules/center - /// - protected internal const int MIN_SKIP = 3; - /// - /// support up to version 10 for mobile clients - /// - protected internal const int MAX_MODULES = 57; - private const int INTEGER_MATH_SHIFT = 8; - - private readonly BitMatrix image; - private List possibleCenters; - private bool hasSkipped; - private readonly int[] crossCheckStateCount; - private readonly ResultPointCallback resultPointCallback; - - /// - ///

Creates a finder that will search the image for three finder patterns.

- ///
- /// image to search - public FinderPatternFinder(BitMatrix image) - : this(image, null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The image. - /// The result point callback. - public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) - { - this.image = image; - this.possibleCenters = new List(); - this.crossCheckStateCount = new int[5]; - this.resultPointCallback = resultPointCallback; - } - - /// - /// Gets the image. - /// - virtual protected internal BitMatrix Image - { - get - { - return image; - } - } - - /// - /// Gets the possible centers. - /// - virtual protected internal List PossibleCenters - { - get - { - return possibleCenters; - } - } - - internal virtual FinderPatternInfo find(IDictionary hints) - { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - bool pureBarcode = hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE); - int maxI = image.Height; - int maxJ = image.Width; - // We are looking for black/white/black/white/black modules in - // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far - - // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the - // image, and then account for the center being 3 modules in size. This gives the smallest - // number of pixels the center could be, so skip this often. When trying harder, look for all - // QR versions regardless of how dense they are. - int iSkip = (3 * maxI) / (4 * MAX_MODULES); - if (iSkip < MIN_SKIP || tryHarder) - { - iSkip = MIN_SKIP; - } - - bool done = false; - int[] stateCount = new int[5]; - for (int i = iSkip - 1; i < maxI && !done; i += iSkip) - { - // Get a row of black/white values - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - int currentState = 0; - for (int j = 0; j < maxJ; j++) - { - if (image[j, i]) - { - // Black pixel - if ((currentState & 1) == 1) - { - // Counting white pixels - currentState++; - } - stateCount[currentState]++; - } - else - { - // White pixel - if ((currentState & 1) == 0) - { - // Counting black pixels - if (currentState == 4) - { - // A winner? - if (foundPatternCross(stateCount)) - { - // Yes - bool confirmed = handlePossibleCenter(stateCount, i, j, pureBarcode); - if (confirmed) - { - // Start examining every other line. Checking each line turned out to be too - // expensive and didn't improve performance. - iSkip = 2; - if (hasSkipped) - { - done = haveMultiplyConfirmedCenters(); - } - else - { - int rowSkip = findRowSkip(); - if (rowSkip > stateCount[2]) - { - // Skip rows between row of lower confirmed center - // and top of presumed third confirmed center - // but back up a bit to get a full chance of detecting - // it, entire width of center of finder pattern - - // Skip by rowSkip, but back off by stateCount[2] (size of last center - // of pattern we saw) to be conservative, and also back off by iSkip which - // is about to be re-added - i += rowSkip - stateCount[2] - iSkip; - j = maxJ - 1; - } - } - } - else - { - stateCount[0] = stateCount[2]; - stateCount[1] = stateCount[3]; - stateCount[2] = stateCount[4]; - stateCount[3] = 1; - stateCount[4] = 0; - currentState = 3; - continue; - } - // Clear state to start looking again - currentState = 0; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - } - else - { - // No, shift counts back by two - stateCount[0] = stateCount[2]; - stateCount[1] = stateCount[3]; - stateCount[2] = stateCount[4]; - stateCount[3] = 1; - stateCount[4] = 0; - currentState = 3; - } - } - else - { - stateCount[++currentState]++; - } - } - else - { - // Counting white pixels - stateCount[currentState]++; - } - } - } - if (foundPatternCross(stateCount)) - { - bool confirmed = handlePossibleCenter(stateCount, i, maxJ, pureBarcode); - if (confirmed) - { - iSkip = stateCount[0]; - if (hasSkipped) - { - // Found a third one - done = haveMultiplyConfirmedCenters(); - } - } - } - } - - FinderPattern[] patternInfo = selectBestPatterns(); - if (patternInfo == null) - return null; - - ResultPoint.orderBestPatterns(patternInfo); - - return new FinderPatternInfo(patternInfo); - } - - /// Given a count of black/white/black/white/black pixels just seen and an end position, - /// figures the location of the center of this run. - /// - private static float? centerFromEnd(int[] stateCount, int end) - { - var result = (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; - if (Single.IsNaN(result)) - return null; - return result; - } - - /// count of black/white/black/white/black pixels just read - /// - /// true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios - /// used by finder patterns to be considered a match - /// - protected internal static bool foundPatternCross(int[] stateCount) - { - int totalModuleSize = 0; - for (int i = 0; i < 5; i++) - { - int count = stateCount[i]; - if (count == 0) - { - return false; - } - totalModuleSize += count; - } - if (totalModuleSize < 7) - { - return false; - } - int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; - int maxVariance = moduleSize / 2; - // Allow less than 50% variance from 1-1-3-1-1 proportions - return Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && - Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; - } - - private int[] CrossCheckStateCount - { - get - { - crossCheckStateCount[0] = 0; - crossCheckStateCount[1] = 0; - crossCheckStateCount[2] = 0; - crossCheckStateCount[3] = 0; - crossCheckStateCount[4] = 0; - return crossCheckStateCount; - } - } - - /// - /// After a vertical and horizontal scan finds a potential finder pattern, this method - /// "cross-cross-cross-checks" by scanning down diagonally through the center of the possible - /// finder pattern to see if the same proportion is detected. - /// - /// row where a finder pattern was detected - /// center of the section that appears to cross a finder pattern - /// maximum reasonable number of modules that should be observed in any reading state, based on the results of the horizontal scan - /// The original state count total. - /// true if proportions are withing expected limits - private bool crossCheckDiagonal(int startI, int centerJ, int maxCount, int originalStateCountTotal) - { - int maxI = image.Height; - int maxJ = image.Width; - int[] stateCount = CrossCheckStateCount; - - // Start counting up, left from center finding black center mass - int i = 0; - while (startI - i >= 0 && image[centerJ - i, startI - i]) - { - stateCount[2]++; - i++; - } - - if ((startI - i < 0) || (centerJ - i < 0)) - { - return false; - } - - // Continue up, left finding white space - while ((startI - i >= 0) && (centerJ - i >= 0) && !image[centerJ - i, startI - i] && stateCount[1] <= maxCount) - { - stateCount[1]++; - i++; - } - - // If already too many modules in this state or ran off the edge: - if ((startI - i < 0) || (centerJ - i < 0) || stateCount[1] > maxCount) - { - return false; - } - - // Continue up, left finding black border - while ((startI - i >= 0) && (centerJ - i >= 0) && image[centerJ - i, startI - i] && stateCount[0] <= maxCount) - { - stateCount[0]++; - i++; - } - if (stateCount[0] > maxCount) - { - return false; - } - - // Now also count down, right from center - i = 1; - while ((startI + i < maxI) && (centerJ + i < maxJ) && image[centerJ + i, startI + i]) - { - stateCount[2]++; - i++; - } - - // Ran off the edge? - if ((startI + i >= maxI) || (centerJ + i >= maxJ)) - { - return false; - } - - while ((startI + i < maxI) && (centerJ + i < maxJ) && !image[centerJ + i, startI + i] && stateCount[3] < maxCount) - { - stateCount[3]++; - i++; - } - - if ((startI + i >= maxI) || (centerJ + i >= maxJ) || stateCount[3] >= maxCount) - { - return false; - } - - while ((startI + i < maxI) && (centerJ + i < maxJ) && image[centerJ + i, startI + i] && stateCount[4] < maxCount) - { - stateCount[4]++; - i++; - } - - if (stateCount[4] >= maxCount) - { - return false; - } - - // If we found a finder-pattern-like section, but its size is more than 100% different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - return Math.Abs(stateCountTotal - originalStateCountTotal) < 2*originalStateCountTotal && - foundPatternCross(stateCount); - } - - /// - ///

After a horizontal scan finds a potential finder pattern, this method - /// "cross-checks" by scanning down vertically through the center of the possible - /// finder pattern to see if the same proportion is detected.

- ///
- /// row where a finder pattern was detected - /// center of the section that appears to cross a finder pattern - /// maximum reasonable number of modules that should be - /// observed in any reading state, based on the results of the horizontal scan - /// The original state count total. - /// - /// vertical center of finder pattern, or null if not found - /// - private float? crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) - { - int maxI = image.Height; - int[] stateCount = CrossCheckStateCount; - - // Start counting up from center - int i = startI; - while (i >= 0 && image[centerJ, i]) - { - stateCount[2]++; - i--; - } - if (i < 0) - { - return null; - } - while (i >= 0 && !image[centerJ, i] && stateCount[1] <= maxCount) - { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) - { - return null; - } - while (i >= 0 && image[centerJ, i] && stateCount[0] <= maxCount) - { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) - { - return null; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image[centerJ, i]) - { - stateCount[2]++; - i++; - } - if (i == maxI) - { - return null; - } - while (i < maxI && !image[centerJ, i] && stateCount[3] < maxCount) - { - stateCount[3]++; - i++; - } - if (i == maxI || stateCount[3] >= maxCount) - { - return null; - } - while (i < maxI && image[centerJ, i] && stateCount[4] < maxCount) - { - stateCount[4]++; - i++; - } - if (stateCount[4] >= maxCount) - { - return null; - } - - // If we found a finder-pattern-like section, but its size is more than 40% different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) - { - return null; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : null; - } - - ///

Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, - /// except it reads horizontally instead of vertically. This is used to cross-cross - /// check a vertical cross check and locate the real center of the alignment pattern.

- ///
- private float? crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) - { - int maxJ = image.Width; - int[] stateCount = CrossCheckStateCount; - - int j = startJ; - while (j >= 0 && image[j, centerI]) - { - stateCount[2]++; - j--; - } - if (j < 0) - { - return null; - } - while (j >= 0 && !image[j, centerI] && stateCount[1] <= maxCount) - { - stateCount[1]++; - j--; - } - if (j < 0 || stateCount[1] > maxCount) - { - return null; - } - while (j >= 0 && image[j, centerI] && stateCount[0] <= maxCount) - { - stateCount[0]++; - j--; - } - if (stateCount[0] > maxCount) - { - return null; - } - - j = startJ + 1; - while (j < maxJ && image[j, centerI]) - { - stateCount[2]++; - j++; - } - if (j == maxJ) - { - return null; - } - while (j < maxJ && !image[j, centerI] && stateCount[3] < maxCount) - { - stateCount[3]++; - j++; - } - if (j == maxJ || stateCount[3] >= maxCount) - { - return null; - } - while (j < maxJ && image[j, centerI] && stateCount[4] < maxCount) - { - stateCount[4]++; - j++; - } - if (stateCount[4] >= maxCount) - { - return null; - } - - // If we found a finder-pattern-like section, but its size is significantly different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) - { - return null; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : null; - } - - /// - ///

This is called when a horizontal scan finds a possible alignment pattern. It will - /// cross check with a vertical scan, and if successful, will, ah, cross-cross-check - /// with another horizontal scan. This is needed primarily to locate the real horizontal - /// center of the pattern in cases of extreme skew. - /// And then we cross-cross-cross check with another diagonal scan.

- /// If that succeeds the finder pattern location is added to a list that tracks - /// the number of times each location has been nearly-matched as a finder pattern. - /// Each additional find is more evidence that the location is in fact a finder - /// pattern center - ///
- /// reading state module counts from horizontal scan - /// row where finder pattern may be found - /// end of possible finder pattern in row - /// if set to true [pure barcode]. - /// - /// true if a finder pattern candidate was found this time - /// - protected bool handlePossibleCenter(int[] stateCount, int i, int j, bool pureBarcode) - { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + - stateCount[4]; - float? centerJ = centerFromEnd(stateCount, j); - if (centerJ == null) - return false; - float? centerI = crossCheckVertical(i, (int)centerJ.Value, stateCount[2], stateCountTotal); - if (centerI != null) - { - // Re-cross check - centerJ = crossCheckHorizontal((int)centerJ.Value, (int)centerI.Value, stateCount[2], stateCountTotal); - if (centerJ != null && - (!pureBarcode || crossCheckDiagonal((int) centerI, (int) centerJ, stateCount[2], stateCountTotal))) - { - float estimatedModuleSize = stateCountTotal / 7.0f; - bool found = false; - for (int index = 0; index < possibleCenters.Count; index++) - { - var center = possibleCenters[index]; - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI.Value, centerJ.Value)) - { - possibleCenters.RemoveAt(index); - possibleCenters.Insert(index, center.combineEstimate(centerI.Value, centerJ.Value, estimatedModuleSize)); - - found = true; - break; - } - } - if (!found) - { - var point = new FinderPattern(centerJ.Value, centerI.Value, estimatedModuleSize); - - possibleCenters.Add(point); - if (resultPointCallback != null) - { - - resultPointCallback(point); - } - } - return true; - } - } - return false; - } - - /// number of rows we could safely skip during scanning, based on the first - /// two finder patterns that have been located. In some cases their position will - /// allow us to infer that the third pattern must lie below a certain point farther - /// down in the image. - /// - private int findRowSkip() - { - int max = possibleCenters.Count; - if (max <= 1) - { - return 0; - } - ResultPoint firstConfirmedCenter = null; - foreach (var center in possibleCenters) - { - if (center.Count >= CENTER_QUORUM) - { - if (firstConfirmedCenter == null) - { - firstConfirmedCenter = center; - } - else - { - // We have two confirmed centers - // How far down can we skip before resuming looking for the next - // pattern? In the worst case, only the difference between the - // difference in the x / y coordinates of the two centers. - // This is the case where you find top left last. - hasSkipped = true; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (int)(Math.Abs(firstConfirmedCenter.X - center.X) - Math.Abs(firstConfirmedCenter.Y - center.Y)) / 2; - } - } - } - return 0; - } - - /// true iff we have found at least 3 finder patterns that have been detected - /// at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the - /// candidates is "pretty similar" - /// - private bool haveMultiplyConfirmedCenters() - { - int confirmedCount = 0; - float totalModuleSize = 0.0f; - int max = possibleCenters.Count; - foreach (var pattern in possibleCenters) - { - if (pattern.Count >= CENTER_QUORUM) - { - confirmedCount++; - totalModuleSize += pattern.EstimatedModuleSize; - } - } - if (confirmedCount < 3) - { - return false; - } - // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" - // and that we need to keep looking. We detect this by asking if the estimated module sizes - // vary too much. We arbitrarily say that when the total deviation from average exceeds - // 5% of the total module size estimates, it's too much. - float average = totalModuleSize / max; - float totalDeviation = 0.0f; - for (int i = 0; i < max; i++) - { - var pattern = possibleCenters[i]; - totalDeviation += Math.Abs(pattern.EstimatedModuleSize - average); - } - return totalDeviation <= 0.05f * totalModuleSize; - } - - /// the 3 best {@link FinderPattern}s from our list of candidates. The "best" are - /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module - /// size differs from the average among those patterns the least - /// - private FinderPattern[] selectBestPatterns() - { - int startSize = possibleCenters.Count; - if (startSize < 3) - { - // Couldn't find enough finder patterns - return null; - } - - // Filter outlier possibilities whose module size is too different - if (startSize > 3) - { - // But we can only afford to do so if we have at least 4 possibilities to choose from - float totalModuleSize = 0.0f; - float square = 0.0f; - foreach (var center in possibleCenters) - { - float size = center.EstimatedModuleSize; - totalModuleSize += size; - square += size * size; - } - float average = totalModuleSize / startSize; - float stdDev = (float)Math.Sqrt(square / startSize - average * average); - - possibleCenters.Sort(new FurthestFromAverageComparator(average)); - - float limit = Math.Max(0.2f * average, stdDev); - - for (int i = 0; i < possibleCenters.Count && possibleCenters.Count > 3; i++) - { - FinderPattern pattern = possibleCenters[i]; - if (Math.Abs(pattern.EstimatedModuleSize - average) > limit) - { - possibleCenters.RemoveAt(i); - i--; - } - } - } - - if (possibleCenters.Count > 3) - { - // Throw away all but those first size candidate points we found. - - float totalModuleSize = 0.0f; - foreach (var possibleCenter in possibleCenters) - { - totalModuleSize += possibleCenter.EstimatedModuleSize; - } - - float average = totalModuleSize / possibleCenters.Count; - - possibleCenters.Sort(new CenterComparator(average)); - - //possibleCenters.subList(3, possibleCenters.Count).clear(); - possibleCenters = possibleCenters.GetRange(0, 3); - } - - return new[] - { - possibleCenters[0], - possibleCenters[1], - possibleCenters[2] - }; - } - - /// - /// Orders by furthest from average - /// - private sealed class FurthestFromAverageComparator : IComparer - { - private readonly float average; - - public FurthestFromAverageComparator(float f) - { - average = f; - } - - public int Compare(FinderPattern x, FinderPattern y) - { - float dA = Math.Abs(y.EstimatedModuleSize - average); - float dB = Math.Abs(x.EstimatedModuleSize - average); - return dA < dB ? -1 : dA == dB ? 0 : 1; - } - } - - ///

Orders by {@link FinderPattern#getCount()}, descending.

- private sealed class CenterComparator : IComparer - { - private readonly float average; - - public CenterComparator(float f) - { - average = f; - } - - public int Compare(FinderPattern x, FinderPattern y) - { - if (y.Count == x.Count) - { - float dA = Math.Abs(y.EstimatedModuleSize - average); - float dB = Math.Abs(x.EstimatedModuleSize - average); - return dA < dB ? 1 : dA == dB ? 0 : -1; - } - return y.Count - x.Count; - } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternInfo.cs b/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternInfo.cs deleted file mode 100755 index 982b755a..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternInfo.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.QrCode.Internal -{ - /// - ///

Encapsulates information about finder patterns in an image, including the location of - /// the three finder patterns, and their estimated module size.

- ///
- /// Sean Owen - public sealed class FinderPatternInfo - { - private readonly FinderPattern bottomLeft; - private readonly FinderPattern topLeft; - private readonly FinderPattern topRight; - - /// - /// Initializes a new instance of the class. - /// - /// The pattern centers. - public FinderPatternInfo(FinderPattern[] patternCenters) - { - this.bottomLeft = patternCenters[0]; - this.topLeft = patternCenters[1]; - this.topRight = patternCenters[2]; - } - - /// - /// Gets the bottom left. - /// - public FinderPattern BottomLeft - { - get - { - return bottomLeft; - } - } - - /// - /// Gets the top left. - /// - public FinderPattern TopLeft - { - get - { - return topLeft; - } - } - - /// - /// Gets the top right. - /// - public FinderPattern TopRight - { - get - { - return topRight; - } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/BlockPair.cs b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/BlockPair.cs deleted file mode 100755 index b1afff46..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/BlockPair.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -namespace ZXing.QrCode.Internal -{ - internal sealed class BlockPair - { - private readonly byte[] dataBytes; - private readonly byte[] errorCorrectionBytes; - - public BlockPair(byte[] data, byte[] errorCorrection) - { - dataBytes = data; - errorCorrectionBytes = errorCorrection; - } - - public byte[] DataBytes - { - get { return dataBytes; } - } - - public byte[] ErrorCorrectionBytes - { - get { return errorCorrectionBytes; } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/ByteMatrix.cs b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/ByteMatrix.cs deleted file mode 100755 index e3d372fd..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/ByteMatrix.cs +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Text; - -namespace ZXing.QrCode.Internal -{ - /// - /// JAVAPORT: The original code was a 2D array of ints, but since it only ever gets assigned - /// 0, 1 and 2 I'm going to use less memory and go with bytes. - /// - /// dswitkin@google.com (Daniel Switkin) - public sealed class ByteMatrix - { - private readonly byte[][] bytes; - private readonly int width; - private readonly int height; - - /// - /// Initializes a new instance of the class. - /// - /// The width. - /// The height. - public ByteMatrix(int width, int height) - { - bytes = new byte[height][]; - for (var i = 0; i < height; i++) - bytes[i] = new byte[width]; - this.width = width; - this.height = height; - } - - /// - /// Gets the height. - /// - public int Height - { - get { return height; } - } - - /// - /// Gets the width. - /// - public int Width - { - get { return width; } - } - - /// - /// Gets or sets the with the specified x. - /// - public int this[int x, int y] - { - get { return bytes[y][x]; } - set { bytes[y][x] = (byte)value; } - } - - /// - /// an internal representation as bytes, in row-major order. array[y][x] represents point (x,y) - /// - public byte[][] Array - { - get { return bytes; } - } - - /// - /// Sets the specified x. - /// - /// The x. - /// The y. - /// The value. - public void set(int x, int y, byte value) - { - bytes[y][x] = value; - } - - /// - /// Sets the specified x. - /// - /// The x. - /// The y. - /// if set to true [value]. - public void set(int x, int y, bool value) - { - bytes[y][x] = (byte)(value ? 1 : 0); - } - - /// - /// Clears the specified value. - /// - /// The value. - public void clear(byte value) - { - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - bytes[y][x] = value; - } - } - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - override public String ToString() - { - var result = new StringBuilder(2 * width * height + 2); - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - switch (bytes[y][x]) - { - case 0: - result.Append(" 0"); - break; - case 1: - result.Append(" 1"); - break; - default: - result.Append(" "); - break; - } - } - result.Append('\n'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs deleted file mode 100755 index 56c9a9a8..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs +++ /dev/null @@ -1,596 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections.Generic; -using System.Text; - -using ZXing.Common; -using ZXing.Common.ReedSolomon; - -namespace ZXing.QrCode.Internal -{ - /// - /// - /// satorux@google.com (Satoru Takabayashi) - creator - /// dswitkin@google.com (Daniel Switkin) - ported from C++ - public static class Encoder - { - - // The original table is defined in the table 5 of JISX0510:2004 (p.19). - private static readonly int[] ALPHANUMERIC_TABLE = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f - 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f - -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f - }; - - internal static String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1"; - - // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. - // Basically it applies four rules and summate all penalties. - private static int calculateMaskPenalty(ByteMatrix matrix) - { - return MaskUtil.applyMaskPenaltyRule1(matrix) - + MaskUtil.applyMaskPenaltyRule2(matrix) - + MaskUtil.applyMaskPenaltyRule3(matrix) - + MaskUtil.applyMaskPenaltyRule4(matrix); - } - - /// - /// Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen - /// internally by chooseMode(). On success, store the result in "qrCode". - /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for - /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very - /// strong error correction for this purpose. - /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() - /// with which clients can specify the encoding mode. For now, we don't need the functionality. - /// - /// The content. - /// The ec level. - public static QRCode encode(String content, ErrorCorrectionLevel ecLevel) - { - return encode(content, ecLevel, null); - } - - /// - /// Encodes the specified content. - /// - /// The content. - /// The ec level. - /// The hints. - /// - public static QRCode encode(String content, - ErrorCorrectionLevel ecLevel, - IDictionary hints) - { - // Determine what character encoding has been specified by the caller, if any -#if !SILVERLIGHT || WINDOWS_PHONE - String encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET]; - if (encoding == null) - { - encoding = DEFAULT_BYTE_MODE_ENCODING; - } - bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding); -#else - // Silverlight supports only UTF-8 and UTF-16 out-of-the-box - const string encoding = "UTF-8"; - // caller of the method can only control if the ECI segment should be written - // character set is fixed to UTF-8; but some scanners doesn't like the ECI segment - bool generateECI = (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET)); -#endif - - // Pick an encoding mode appropriate for the content. Note that this will not attempt to use - // multiple modes / segments even if that were more efficient. Twould be nice. - Mode mode = chooseMode(content, encoding); - - // This will store the header information, like mode and - // length, as well as "header" segments like an ECI segment. - BitArray headerBits = new BitArray(); - - - // (With ECI in place,) Write the mode marker - appendModeInfo(mode, headerBits); - - // Collect data within the main segment, separately, to count its size if needed. Don't add it to - // main payload yet. - BitArray dataBits = new BitArray(); - appendBytes(content, mode, dataBits, encoding); - - // Hard part: need to know version to know how many bits length takes. But need to know how many - // bits it takes to know version. First we take a guess at version by assuming version will be - // the minimum, 1: - - int provisionalBitsNeeded = headerBits.Size - + mode.getCharacterCountBits(Version.getVersionForNumber(1)) - + dataBits.Size; - Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel); - - // Use that guess to calculate the right version. I am still not sure this works in 100% of cases. - int bitsNeeded = headerBits.Size - + mode.getCharacterCountBits(provisionalVersion) - + dataBits.Size; - Version version = chooseVersion(bitsNeeded, ecLevel); - - BitArray headerAndDataBits = new BitArray(); - headerAndDataBits.appendBitArray(headerBits); - // Find "length" of main segment and write it - int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length; - appendLengthInfo(numLetters, version, mode, headerAndDataBits); - // Put data together into the overall payload - headerAndDataBits.appendBitArray(dataBits); - - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - int numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords; - - // Terminate the bits properly. - terminateBits(numDataBytes, headerAndDataBits); - - // Interleave data bits with error correction code. - BitArray finalBits = interleaveWithECBytes(headerAndDataBits, - version.TotalCodewords, - numDataBytes, - ecBlocks.NumBlocks); - - QRCode qrCode = new QRCode - { - ECLevel = ecLevel, - Mode = mode, - Version = version - }; - - // Choose the mask pattern and set to "qrCode". - int dimension = version.DimensionForVersion; - ByteMatrix matrix = new ByteMatrix(dimension, dimension); - int maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix); - qrCode.MaskPattern = maskPattern; - - // Build the matrix and set it to "qrCode". - MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix); - qrCode.Matrix = matrix; - - return qrCode; - } - - /// - /// Gets the alphanumeric code. - /// - /// The code. - /// the code point of the table used in alphanumeric mode or - /// -1 if there is no corresponding code in the table. - internal static int getAlphanumericCode(int code) - { - if (code < ALPHANUMERIC_TABLE.Length) - { - return ALPHANUMERIC_TABLE[code]; - } - return -1; - } - - /// - /// Chooses the mode. - /// - /// The content. - /// - public static Mode chooseMode(String content) - { - return chooseMode(content, null); - } - - /// - /// Choose the best mode by examining the content. Note that 'encoding' is used as a hint; - /// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}. - /// - /// The content. - /// The encoding. - /// - private static Mode chooseMode(String content, String encoding) - { - return Mode.BYTE; - } - - private static int chooseMaskPattern(BitArray bits, - ErrorCorrectionLevel ecLevel, - Version version, - ByteMatrix matrix) - { - int minPenalty = Int32.MaxValue; // Lower penalty is better. - int bestMaskPattern = -1; - // We try all mask patterns to choose the best one. - for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) - { - - MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); - int penalty = calculateMaskPenalty(matrix); - if (penalty < minPenalty) - { - - minPenalty = penalty; - bestMaskPattern = maskPattern; - } - } - return bestMaskPattern; - } - - private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) - { - // In the following comments, we use numbers of Version 7-H. - for (int versionNum = 1; versionNum <= 40; versionNum++) - { - Version version = Version.getVersionForNumber(versionNum); - // numBytes = 196 - int numBytes = version.TotalCodewords; - // getNumECBytes = 130 - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - int numEcBytes = ecBlocks.TotalECCodewords; - // getNumDataBytes = 196 - 130 = 66 - int numDataBytes = numBytes - numEcBytes; - int totalInputBytes = (numInputBits + 7) / 8; - if (numDataBytes >= totalInputBytes) - { - return version; - } - } - throw new WriterException("Data too big"); - } - - /// - /// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). - /// - /// The num data bytes. - /// The bits. - internal static void terminateBits(int numDataBytes, BitArray bits) - { - int capacity = numDataBytes << 3; - if (bits.Size > capacity) - { - throw new WriterException("data bits cannot fit in the QR Code" + bits.Size + " > " + - capacity); - } - for (int i = 0; i < 4 && bits.Size < capacity; ++i) - { - bits.appendBit(false); - } - // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. - // If the last byte isn't 8-bit aligned, we'll add padding bits. - int numBitsInLastByte = bits.Size & 0x07; - if (numBitsInLastByte > 0) - { - for (int i = numBitsInLastByte; i < 8; i++) - { - bits.appendBit(false); - } - } - // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). - int numPaddingBytes = numDataBytes - bits.SizeInBytes; - for (int i = 0; i < numPaddingBytes; ++i) - { - bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8); - } - if (bits.Size != capacity) - { - throw new WriterException("Bits size does not equal capacity"); - } - } - - /// - /// Get number of data bytes and number of error correction bytes for block id "blockID". Store - /// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of - /// JISX0510:2004 (p.30) - /// - /// The num total bytes. - /// The num data bytes. - /// The num RS blocks. - /// The block ID. - /// The num data bytes in block. - /// The num EC bytes in block. - internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, - int numDataBytes, - int numRSBlocks, - int blockID, - int[] numDataBytesInBlock, - int[] numECBytesInBlock) - { - if (blockID >= numRSBlocks) - { - throw new WriterException("Block ID too large"); - } - // numRsBlocksInGroup2 = 196 % 5 = 1 - int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; - // numRsBlocksInGroup1 = 5 - 1 = 4 - int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; - // numTotalBytesInGroup1 = 196 / 5 = 39 - int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; - // numTotalBytesInGroup2 = 39 + 1 = 40 - int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; - // numDataBytesInGroup1 = 66 / 5 = 13 - int numDataBytesInGroup1 = numDataBytes / numRSBlocks; - // numDataBytesInGroup2 = 13 + 1 = 14 - int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; - // numEcBytesInGroup1 = 39 - 13 = 26 - int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; - // numEcBytesInGroup2 = 40 - 14 = 26 - int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; - // Sanity checks. - // 26 = 26 - if (numEcBytesInGroup1 != numEcBytesInGroup2) - { - - throw new WriterException("EC bytes mismatch"); - } - // 5 = 4 + 1. - if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) - { - - throw new WriterException("RS blocks mismatch"); - } - // 196 = (13 + 26) * 4 + (14 + 26) * 1 - if (numTotalBytes != - ((numDataBytesInGroup1 + numEcBytesInGroup1) * - numRsBlocksInGroup1) + - ((numDataBytesInGroup2 + numEcBytesInGroup2) * - numRsBlocksInGroup2)) - { - throw new WriterException("Total bytes mismatch"); - } - - if (blockID < numRsBlocksInGroup1) - { - - numDataBytesInBlock[0] = numDataBytesInGroup1; - numECBytesInBlock[0] = numEcBytesInGroup1; - } - else - { - - - numDataBytesInBlock[0] = numDataBytesInGroup2; - numECBytesInBlock[0] = numEcBytesInGroup2; - } - } - - /// - /// Interleave "bits" with corresponding error correction bytes. On success, store the result in - /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details. - /// - /// The bits. - /// The num total bytes. - /// The num data bytes. - /// The num RS blocks. - /// - internal static BitArray interleaveWithECBytes(BitArray bits, - int numTotalBytes, - int numDataBytes, - int numRSBlocks) - { - // "bits" must have "getNumDataBytes" bytes of data. - if (bits.SizeInBytes != numDataBytes) - { - - throw new WriterException("Number of bits and data bytes does not match"); - } - - // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll - // store the divided data bytes blocks and error correction bytes blocks into "blocks". - int dataBytesOffset = 0; - int maxNumDataBytes = 0; - int maxNumEcBytes = 0; - - // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. - var blocks = new List(numRSBlocks); - - for (int i = 0; i < numRSBlocks; ++i) - { - - int[] numDataBytesInBlock = new int[1]; - int[] numEcBytesInBlock = new int[1]; - getNumDataBytesAndNumECBytesForBlockID( - numTotalBytes, numDataBytes, numRSBlocks, i, - numDataBytesInBlock, numEcBytesInBlock); - - int size = numDataBytesInBlock[0]; - byte[] dataBytes = new byte[size]; - bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size); - byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); - blocks.Add(new BlockPair(dataBytes, ecBytes)); - - maxNumDataBytes = Math.Max(maxNumDataBytes, size); - maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.Length); - dataBytesOffset += numDataBytesInBlock[0]; - } - if (numDataBytes != dataBytesOffset) - { - - throw new WriterException("Data bytes does not match offset"); - } - - BitArray result = new BitArray(); - - // First, place data blocks. - for (int i = 0; i < maxNumDataBytes; ++i) - { - foreach (BlockPair block in blocks) - { - byte[] dataBytes = block.DataBytes; - if (i < dataBytes.Length) - { - result.appendBits(dataBytes[i], 8); - } - } - } - // Then, place error correction blocks. - for (int i = 0; i < maxNumEcBytes; ++i) - { - foreach (BlockPair block in blocks) - { - byte[] ecBytes = block.ErrorCorrectionBytes; - if (i < ecBytes.Length) - { - result.appendBits(ecBytes[i], 8); - } - } - } - if (numTotalBytes != result.SizeInBytes) - { // Should be same. - throw new WriterException("Interleaving error: " + numTotalBytes + " and " + - result.SizeInBytes + " differ."); - } - - return result; - } - - internal static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock) - { - int numDataBytes = dataBytes.Length; - int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; - for (int i = 0; i < numDataBytes; i++) - { - toEncode[i] = dataBytes[i] & 0xFF; - - } - new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock); - - byte[] ecBytes = new byte[numEcBytesInBlock]; - for (int i = 0; i < numEcBytesInBlock; i++) - { - ecBytes[i] = (byte)toEncode[numDataBytes + i]; - - } - return ecBytes; - } - - /// - /// Append mode info. On success, store the result in "bits". - /// - /// The mode. - /// The bits. - internal static void appendModeInfo(Mode mode, BitArray bits) - { - bits.appendBits(mode.Bits, 4); - } - - - /// - /// Append length info. On success, store the result in "bits". - /// - /// The num letters. - /// The version. - /// The mode. - /// The bits. - internal static void appendLengthInfo(int numLetters, Version version, Mode mode, BitArray bits) - { - int numBits = mode.getCharacterCountBits(version); - if (numLetters >= (1 << numBits)) - { - throw new WriterException(numLetters + " is bigger than " + ((1 << numBits) - 1)); - } - bits.appendBits(numLetters, numBits); - } - - /// - /// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits". - /// - /// The content. - /// The mode. - /// The bits. - /// The encoding. - internal static void appendBytes(String content, - Mode mode, - BitArray bits, - String encoding) - { - if (mode.Equals(Mode.BYTE)) - append8BitBytes(content, bits, encoding); - else - throw new WriterException("Invalid mode: " + mode); - } - - internal static void appendNumericBytes(String content, BitArray bits) - { - int length = content.Length; - - int i = 0; - while (i < length) - { - int num1 = content[i] - '0'; - if (i + 2 < length) - { - // Encode three numeric letters in ten bits. - int num2 = content[i + 1] - '0'; - int num3 = content[i + 2] - '0'; - bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); - i += 3; - } - else if (i + 1 < length) - { - // Encode two numeric letters in seven bits. - int num2 = content[i + 1] - '0'; - bits.appendBits(num1 * 10 + num2, 7); - i += 2; - } - else - { - // Encode one numeric letter in four bits. - bits.appendBits(num1, 4); - i++; - } - } - } - - - internal static void append8BitBytes(String content, BitArray bits, String encoding) - { - byte[] bytes; - try - { - bytes = Encoding.GetEncoding(encoding).GetBytes(content); - } -#if WindowsCE - catch (PlatformNotSupportedException) - { - try - { - // WindowsCE doesn't support all encodings. But it is device depended. - // So we try here the some different ones - if (encoding == "ISO-8859-1") - { - bytes = Encoding.GetEncoding(1252).GetBytes(content); - } - else - { - bytes = Encoding.GetEncoding("UTF-8").GetBytes(content); - } - } - catch (Exception uee) - { - throw new WriterException(uee.Message, uee); - } - } -#endif - catch (Exception uee) - { - throw new WriterException(uee.Message, uee); - } - foreach (byte b in bytes) - { - bits.appendBits(b, 8); - } - } - - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/MaskUtil.cs b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/MaskUtil.cs deleted file mode 100755 index 24e85cc1..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/MaskUtil.cs +++ /dev/null @@ -1,271 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - -namespace ZXing.QrCode.Internal -{ - /// - /// - /// - /// Satoru Takabayashi - /// Daniel Switkin - /// Sean Owen - public static class MaskUtil - { - // Penalty weights from section 6.8.2.1 - private const int N1 = 3; - private const int N2 = 3; - private const int N3 = 40; - private const int N4 = 10; - - /// - /// Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and - /// give penalty to them. Example: 00000 or 11111. - /// - /// The matrix. - /// - public static int applyMaskPenaltyRule1(ByteMatrix matrix) - { - return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false); - } - - /// - /// Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give - /// penalty to them. This is actually equivalent to the spec's rule, which is to find MxN blocks and give a - /// penalty proportional to (M-1)x(N-1), because this is the number of 2x2 blocks inside such a block. - /// - /// The matrix. - /// - public static int applyMaskPenaltyRule2(ByteMatrix matrix) - { - int penalty = 0; - var array = matrix.Array; - int width = matrix.Width; - int height = matrix.Height; - for (int y = 0; y < height - 1; y++) - { - for (int x = 0; x < width - 1; x++) - { - int value = array[y][x]; - if (value == array[y][x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1]) - { - penalty++; - } - } - } - return N2 * penalty; - } - - /// - /// Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or - /// 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give - /// penalties twice (i.e. 40 * 2). - /// - /// The matrix. - /// - public static int applyMaskPenaltyRule3(ByteMatrix matrix) - { - int numPenalties = 0; - byte[][] array = matrix.Array; - int width = matrix.Width; - int height = matrix.Height; - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - byte[] arrayY = array[y]; // We can at least optimize this access - if (x + 6 < width && - arrayY[x] == 1 && - arrayY[x + 1] == 0 && - arrayY[x + 2] == 1 && - arrayY[x + 3] == 1 && - arrayY[x + 4] == 1 && - arrayY[x + 5] == 0 && - arrayY[x + 6] == 1 && - (isWhiteHorizontal(arrayY, x - 4, x) || isWhiteHorizontal(arrayY, x + 7, x + 11))) - { - numPenalties++; - } - if (y + 6 < height && - array[y][x] == 1 && - array[y + 1][x] == 0 && - array[y + 2][x] == 1 && - array[y + 3][x] == 1 && - array[y + 4][x] == 1 && - array[y + 5][x] == 0 && - array[y + 6][x] == 1 && - (isWhiteVertical(array, x, y - 4, y) || isWhiteVertical(array, x, y + 7, y + 11))) - { - numPenalties++; - } - } - } - return numPenalties * N3; - } - - private static bool isWhiteHorizontal(byte[] rowArray, int from, int to) - { - for (int i = from; i < to; i++) - { - if (i >= 0 && i < rowArray.Length && rowArray[i] == 1) - { - return false; - } - } - return true; - } - - private static bool isWhiteVertical(byte[][] array, int col, int from, int to) - { - for (int i = from; i < to; i++) - { - if (i >= 0 && i < array.Length && array[i][col] == 1) - { - return false; - } - } - return true; - } - - /// - /// Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give - /// penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance. - /// - /// The matrix. - /// - public static int applyMaskPenaltyRule4(ByteMatrix matrix) - { - int numDarkCells = 0; - var array = matrix.Array; - int width = matrix.Width; - int height = matrix.Height; - for (int y = 0; y < height; y++) - { - var arrayY = array[y]; - for (int x = 0; x < width; x++) - { - if (arrayY[x] == 1) - { - numDarkCells++; - } - } - } - var numTotalCells = matrix.Height * matrix.Width; - var darkRatio = (double)numDarkCells / numTotalCells; - var fivePercentVariances = (int)(Math.Abs(darkRatio - 0.5) * 20.0); // * 100.0 / 5.0 - return fivePercentVariances * N4; - } - - /// - /// Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask - /// pattern conditions. - /// - /// The mask pattern. - /// The x. - /// The y. - /// - public static bool getDataMaskBit(int maskPattern, int x, int y) - { - int intermediate, temp; - switch (maskPattern) - { - - case 0: - intermediate = (y + x) & 0x1; - break; - - case 1: - intermediate = y & 0x1; - break; - - case 2: - intermediate = x % 3; - break; - - case 3: - intermediate = (y + x) % 3; - break; - - case 4: - intermediate = (((int)((uint)y >> 1)) + (x / 3)) & 0x1; - break; - - case 5: - temp = y * x; - intermediate = (temp & 0x1) + (temp % 3); - break; - - case 6: - temp = y * x; - intermediate = (((temp & 0x1) + (temp % 3)) & 0x1); - break; - - case 7: - temp = y * x; - intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1); - break; - - default: - throw new ArgumentException("Invalid mask pattern: " + maskPattern); - - } - return intermediate == 0; - } - - /// - /// Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both - /// vertical and horizontal orders respectively. - /// - /// The matrix. - /// if set to true [is horizontal]. - /// - private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal) - { - int penalty = 0; - int iLimit = isHorizontal ? matrix.Height : matrix.Width; - int jLimit = isHorizontal ? matrix.Width : matrix.Height; - var array = matrix.Array; - for (int i = 0; i < iLimit; i++) - { - int numSameBitCells = 0; - int prevBit = -1; - for (int j = 0; j < jLimit; j++) - { - int bit = isHorizontal ? array[i][j] : array[j][i]; - if (bit == prevBit) - { - numSameBitCells++; - } - else - { - if (numSameBitCells >= 5) - { - penalty += N1 + (numSameBitCells - 5); - } - numSameBitCells = 1; // Include the cell itself. - prevBit = bit; - } - } - if (numSameBitCells >= 5) - { - penalty += N1 + (numSameBitCells - 5); - } - } - return penalty; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/MatrixUtil.cs b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/MatrixUtil.cs deleted file mode 100755 index 9fcde4e1..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/MatrixUtil.cs +++ /dev/null @@ -1,600 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using ZXing.Common; - -namespace ZXing.QrCode.Internal -{ - /// - /// - /// - /// - /// satorux@google.com (Satoru Takabayashi) - creator - /// - public static class MatrixUtil - { - private static readonly int[][] POSITION_DETECTION_PATTERN = new int[][] - { - new int[] { 1, 1, 1, 1, 1, 1, 1 }, - new int[] { 1, 0, 0, 0, 0, 0, 1 }, - new int[] { 1, 0, 1, 1, 1, 0, 1 }, - new int[] { 1, 0, 1, 1, 1, 0, 1 }, - new int[] { 1, 0, 1, 1, 1, 0, 1 }, - new int[] { 1, 0, 0, 0, 0, 0, 1 }, - new int[] { 1, 1, 1, 1, 1, 1, 1 } - }; - - private static readonly int[][] POSITION_ADJUSTMENT_PATTERN = new int[][] - { - new int[] { 1, 1, 1, 1, 1 }, - new int[] { 1, 0, 0, 0, 1 }, - new int[] { 1, 0, 1, 0, 1 }, - new int[] { 1, 0, 0, 0, 1 }, - new int[] { 1, 1, 1, 1, 1 } - }; - - // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. - private static readonly int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = new int[][] - { - new int[] { -1, -1, -1, -1, -1, -1, -1 }, - new int[] { 6, 18, -1, -1, -1, -1, -1 }, - new int[] { 6, 22, -1, -1, -1, -1, -1 }, - new int[] { 6, 26, -1, -1, -1, -1, -1 }, - new int[] { 6, 30, -1, -1, -1, -1, -1 }, - new int[] { 6, 34, -1, -1, -1, -1, -1 }, - new int[] { 6, 22, 38, -1, -1, -1, -1 }, - new int[] { 6, 24, 42, -1, -1, -1, -1 }, - new int[] { 6, 26, 46, -1, -1, -1, -1 }, - new int[] { 6, 28, 50, -1, -1, -1, -1 }, - new int[] { 6, 30, 54, -1, -1, -1, -1 }, - new int[] { 6, 32, 58, -1, -1, -1, -1 }, - new int[] { 6, 34, 62, -1, -1, -1, -1 }, - new int[] { 6, 26, 46, 66, -1, -1, -1 }, - new int[] { 6, 26, 48, 70, -1, -1, -1 }, - new int[] { 6, 26, 50, 74, -1, -1, -1 }, - new int[] { 6, 30, 54, 78, -1, -1, -1 }, - new int[] { 6, 30, 56, 82, -1, -1, -1 }, - new int[] { 6, 30, 58, 86, -1, -1, -1 }, - new int[] { 6, 34, 62, 90, -1, -1, -1 }, - new int[] { 6, 28, 50, 72, 94, -1, -1 }, - new int[] { 6, 26, 50, 74, 98, -1, -1 }, - new int[] { 6, 30, 54, 78, 102, -1, -1 }, - new int[] { 6, 28, 54, 80, 106, -1, -1 }, - new int[] { 6, 32, 58, 84, 110, -1, -1 }, - new int[] { 6, 30, 58, 86, 114, -1, -1 }, - new int[] { 6, 34, 62, 90, 118, -1, -1 }, - new int[] { 6, 26, 50, 74, 98, 122, -1 }, - new int[] { 6, 30, 54, 78, 102, 126, -1 }, - new int[] { 6, 26, 52, 78, 104, 130, -1 }, - new int[] { 6, 30, 56, 82, 108, 134, -1 }, - new int[] { 6, 34, 60, 86, 112, 138, -1 }, - new int[] { 6, 30, 58, 86, 114, 142, -1 }, - new int[] { 6, 34, 62, 90, 118, 146, -1 }, - new int[] { 6, 30, 54, 78, 102, 126, 150 }, - new int[] { 6, 24, 50, 76, 102, 128, 154 }, - new int[] { 6, 28, 54, 80, 106, 132, 158 }, - new int[] { 6, 32, 58, 84, 110, 136, 162 }, - new int[] { 6, 26, 54, 82, 110, 138, 166 }, - new int[] { 6, 30, 58, 86, 114, 142, 170 } - }; - - // Type info cells at the left top corner. - private static readonly int[][] TYPE_INFO_COORDINATES = new int[][] - { - new int[] { 8, 0 }, - new int[] { 8, 1 }, - new int[] { 8, 2 }, - new int[] { 8, 3 }, - new int[] { 8, 4 }, - new int[] { 8, 5 }, - new int[] { 8, 7 }, - new int[] { 8, 8 }, - new int[] { 7, 8 }, - new int[] { 5, 8 }, - new int[] { 4, 8 }, - new int[] { 3, 8 }, - new int[] { 2, 8 }, - new int[] { 1, 8 }, - new int[] { 0, 8 } - }; - - // From Appendix D in JISX0510:2004 (p. 67) - private const int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 - - // From Appendix C in JISX0510:2004 (p.65). - private const int TYPE_INFO_POLY = 0x537; - private const int TYPE_INFO_MASK_PATTERN = 0x5412; - - /// - /// Set all cells to 2. 2 means that the cell is empty (not set yet). - /// - /// JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding - /// with the ByteMatrix initialized all to zero. - /// - /// The matrix. - public static void clearMatrix(ByteMatrix matrix) - { - matrix.clear(2); - } - - /// - /// Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On - /// success, store the result in "matrix" and return true. - /// - /// The data bits. - /// The ec level. - /// The version. - /// The mask pattern. - /// The matrix. - public static void buildMatrix(BitArray dataBits, ErrorCorrectionLevel ecLevel, Version version, int maskPattern, ByteMatrix matrix) - { - clearMatrix(matrix); - embedBasicPatterns(version, matrix); - // Type information appear with any version. - embedTypeInfo(ecLevel, maskPattern, matrix); - // Version info appear if version >= 7. - maybeEmbedVersionInfo(version, matrix); - // Data should be embedded at end. - embedDataBits(dataBits, maskPattern, matrix); - } - - /// - /// Embed basic patterns. On success, modify the matrix and return true. - /// The basic patterns are: - /// - Position detection patterns - /// - Timing patterns - /// - Dark dot at the left bottom corner - /// - Position adjustment patterns, if need be - /// - /// The version. - /// The matrix. - public static void embedBasicPatterns(Version version, ByteMatrix matrix) - { - // Let's get started with embedding big squares at corners. - embedPositionDetectionPatternsAndSeparators(matrix); - // Then, embed the dark dot at the left bottom corner. - embedDarkDotAtLeftBottomCorner(matrix); - - // Position adjustment patterns appear if version >= 2. - maybeEmbedPositionAdjustmentPatterns(version, matrix); - // Timing patterns should be embedded after position adj. patterns. - embedTimingPatterns(matrix); - } - - /// - /// Embed type information. On success, modify the matrix. - /// - /// The ec level. - /// The mask pattern. - /// The matrix. - public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) - { - BitArray typeInfoBits = new BitArray(); - makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); - - for (int i = 0; i < typeInfoBits.Size; ++i) - { - // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in - // "typeInfoBits". - int bit = typeInfoBits[typeInfoBits.Size - 1 - i] ? 1 : 0; - - // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). - int x1 = TYPE_INFO_COORDINATES[i][0]; - int y1 = TYPE_INFO_COORDINATES[i][1]; - matrix[x1, y1] = bit; - - if (i < 8) - { - // Right top corner. - int x2 = matrix.Width - i - 1; - int y2 = 8; - matrix[x2, y2] = bit; - } - else - { - // Left bottom corner. - int x2 = 8; - int y2 = matrix.Height - 7 + (i - 8); - matrix[x2, y2] = bit; - } - } - } - - /// - /// Embed version information if need be. On success, modify the matrix and return true. - /// See 8.10 of JISX0510:2004 (p.47) for how to embed version information. - /// - /// The version. - /// The matrix. - public static void maybeEmbedVersionInfo(Version version, ByteMatrix matrix) - { - if (version.VersionNumber < 7) - { - // Version info is necessary if version >= 7. - return; // Don't need version info. - } - BitArray versionInfoBits = new BitArray(); - makeVersionInfoBits(version, versionInfoBits); - - int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. - for (int i = 0; i < 6; ++i) - { - for (int j = 0; j < 3; ++j) - { - // Place bits in LSB (least significant bit) to MSB order. - var bit = versionInfoBits[bitIndex] ? 1 : 0; - bitIndex--; - // Left bottom corner. - matrix[i, matrix.Height - 11 + j] = bit; - // Right bottom corner. - matrix[matrix.Height - 11 + j, i] = bit; - } - } - } - - /// - /// Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. - /// For debugging purposes, it skips masking process if "getMaskPattern" is -1. - /// See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. - /// - /// The data bits. - /// The mask pattern. - /// The matrix. - public static void embedDataBits(BitArray dataBits, int maskPattern, ByteMatrix matrix) - { - int bitIndex = 0; - int direction = -1; - // Start from the right bottom cell. - int x = matrix.Width - 1; - int y = matrix.Height - 1; - while (x > 0) - { - // Skip the vertical timing pattern. - if (x == 6) - { - x -= 1; - } - while (y >= 0 && y < matrix.Height) - { - for (int i = 0; i < 2; ++i) - { - int xx = x - i; - // Skip the cell if it's not empty. - if (!isEmpty(matrix[xx, y])) - { - continue; - } - int bit; - if (bitIndex < dataBits.Size) - { - bit = dataBits[bitIndex] ? 1 : 0; - ++bitIndex; - } - else - { - // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described - // in 8.4.9 of JISX0510:2004 (p. 24). - bit = 0; - } - - // Skip masking if mask_pattern is -1. - if (maskPattern != -1) - { - if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) - { - bit ^= 0x1; - } - } - matrix[xx, y] = bit; - } - y += direction; - } - direction = -direction; // Reverse the direction. - y += direction; - x -= 2; // Move to the left. - } - // All bits should be consumed. - if (bitIndex != dataBits.Size) - { - throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.Size); - } - } - - /// - /// Return the position of the most significant bit set (to one) in the "value". The most - /// significant bit is position 32. If there is no bit set, return 0. Examples: - /// - findMSBSet(0) => 0 - /// - findMSBSet(1) => 1 - /// - findMSBSet(255) => 8 - /// - /// The value_ renamed. - /// - public static int findMSBSet(int value_Renamed) - { - int numDigits = 0; - while (value_Renamed != 0) - { - value_Renamed = (int)((uint)value_Renamed >> 1); - ++numDigits; - } - return numDigits; - } - - /// - /// Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH - /// code is used for encoding type information and version information. - /// Example: Calculation of version information of 7. - /// f(x) is created from 7. - /// - 7 = 000111 in 6 bits - /// - f(x) = x^2 + x^2 + x^1 - /// g(x) is given by the standard (p. 67) - /// - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 - /// Multiply f(x) by x^(18 - 6) - /// - f'(x) = f(x) * x^(18 - 6) - /// - f'(x) = x^14 + x^13 + x^12 - /// Calculate the remainder of f'(x) / g(x) - /// x^2 - /// __________________________________________________ - /// g(x) )x^14 + x^13 + x^12 - /// x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 - /// -------------------------------------------------- - /// x^11 + x^10 + x^7 + x^4 + x^2 - /// - /// The remainder is x^11 + x^10 + x^7 + x^4 + x^2 - /// Encode it in binary: 110010010100 - /// The return value is 0xc94 (1100 1001 0100) - /// - /// Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit - /// operations. We don't care if cofficients are positive or negative. - /// - /// The value. - /// The poly. - /// - public static int calculateBCHCode(int value, int poly) - { - // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 - // from 13 to make it 12. - int msbSetInPoly = findMSBSet(poly); - value <<= msbSetInPoly - 1; - // Do the division business using exclusive-or operations. - while (findMSBSet(value) >= msbSetInPoly) - { - value ^= poly << (findMSBSet(value) - msbSetInPoly); - } - // Now the "value" is the remainder (i.e. the BCH code) - return value; - } - - /// - /// Make bit vector of type information. On success, store the result in "bits" and return true. - /// Encode error correction level and mask pattern. See 8.9 of - /// JISX0510:2004 (p.45) for details. - /// - /// The ec level. - /// The mask pattern. - /// The bits. - public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) - { - if (!QRCode.isValidMaskPattern(maskPattern)) - { - throw new WriterException("Invalid mask pattern"); - } - int typeInfo = (ecLevel.Bits << 3) | maskPattern; - bits.appendBits(typeInfo, 5); - - int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); - bits.appendBits(bchCode, 10); - - BitArray maskBits = new BitArray(); - maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); - bits.xor(maskBits); - - if (bits.Size != 15) - { - // Just in case. - throw new WriterException("should not happen but we got: " + bits.Size); - } - } - - /// - /// Make bit vector of version information. On success, store the result in "bits" and return true. - /// See 8.10 of JISX0510:2004 (p.45) for details. - /// - /// The version. - /// The bits. - public static void makeVersionInfoBits(Version version, BitArray bits) - { - bits.appendBits(version.VersionNumber, 6); - int bchCode = calculateBCHCode(version.VersionNumber, VERSION_INFO_POLY); - bits.appendBits(bchCode, 12); - - if (bits.Size != 18) - { - // Just in case. - throw new WriterException("should not happen but we got: " + bits.Size); - } - } - - /// - /// Check if "value" is empty. - /// - /// The value. - /// - /// true if the specified value is empty; otherwise, false. - /// - private static bool isEmpty(int value) - { - return value == 2; - } - - private static void embedTimingPatterns(ByteMatrix matrix) - { - // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical - // separation patterns (size 1). Thus, 8 = 7 + 1. - for (int i = 8; i < matrix.Width - 8; ++i) - { - int bit = (i + 1) % 2; - // Horizontal line. - if (isEmpty(matrix[i, 6])) - { - matrix[i, 6] = bit; - } - // Vertical line. - if (isEmpty(matrix[6, i])) - { - matrix[6, i] = bit; - } - } - } - - /// - /// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) - /// - /// The matrix. - private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) - { - if (matrix[8, matrix.Height - 8] == 0) - { - throw new WriterException(); - } - matrix[8, matrix.Height - 8] = 1; - } - - private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) - { - for (int x = 0; x < 8; ++x) - { - if (!isEmpty(matrix[xStart + x, yStart])) - { - throw new WriterException(); - } - matrix[xStart + x, yStart] = 0; - } - } - - private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) - { - for (int y = 0; y < 7; ++y) - { - if (!isEmpty(matrix[xStart, yStart + y])) - { - throw new WriterException(); - } - matrix[xStart, yStart + y] = 0; - } - } - - /// - /// Note that we cannot unify the function with embedPositionDetectionPattern() despite they are - /// almost identical, since we cannot write a function that takes 2D arrays in different sizes in - /// C/C++. We should live with the fact. - /// - /// The x start. - /// The y start. - /// The matrix. - private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) - { - for (int y = 0; y < 5; ++y) - { - for (int x = 0; x < 5; ++x) - { - matrix[xStart + x, yStart + y] = POSITION_ADJUSTMENT_PATTERN[y][x]; - } - } - } - - private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) - { - for (int y = 0; y < 7; ++y) - { - for (int x = 0; x < 7; ++x) - { - matrix[xStart + x, yStart + y] = POSITION_DETECTION_PATTERN[y][x]; - } - } - } - - /// - /// Embed position detection patterns and surrounding vertical/horizontal separators. - /// - /// The matrix. - private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) - { - // Embed three big squares at corners. - int pdpWidth = POSITION_DETECTION_PATTERN[0].Length; - // Left top corner. - embedPositionDetectionPattern(0, 0, matrix); - // Right top corner. - embedPositionDetectionPattern(matrix.Width - pdpWidth, 0, matrix); - // Left bottom corner. - embedPositionDetectionPattern(0, matrix.Width - pdpWidth, matrix); - - // Embed horizontal separation patterns around the squares. - const int hspWidth = 8; - // Left top corner. - embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); - // Right top corner. - embedHorizontalSeparationPattern(matrix.Width - hspWidth, hspWidth - 1, matrix); - // Left bottom corner. - embedHorizontalSeparationPattern(0, matrix.Width - hspWidth, matrix); - - // Embed vertical separation patterns around the squares. - const int vspSize = 7; - // Left top corner. - embedVerticalSeparationPattern(vspSize, 0, matrix); - // Right top corner. - embedVerticalSeparationPattern(matrix.Height - vspSize - 1, 0, matrix); - // Left bottom corner. - embedVerticalSeparationPattern(vspSize, matrix.Height - vspSize, matrix); - } - - /// - /// Embed position adjustment patterns if need be. - /// - /// The version. - /// The matrix. - private static void maybeEmbedPositionAdjustmentPatterns(Version version, ByteMatrix matrix) - { - if (version.VersionNumber < 2) - { - // The patterns appear if version >= 2 - return; - } - int index = version.VersionNumber - 1; - int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; - int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].Length; - for (int i = 0; i < numCoordinates; ++i) - { - for (int j = 0; j < numCoordinates; ++j) - { - int y = coordinates[i]; - int x = coordinates[j]; - if (x == -1 || y == -1) - { - continue; - } - // If the cell is unset, we embed the position adjustment pattern here. - if (isEmpty(matrix[x, y])) - { - // -2 is necessary since the x/y coordinates point to the center of the pattern, not the - // left top corner. - embedPositionAdjustmentPattern(x - 2, y - 2, matrix); - } - } - } - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/QRCode.cs b/shadowsocks-csharp/3rd/zxing/qrcode/encoder/QRCode.cs deleted file mode 100755 index 90d10bf5..00000000 --- a/shadowsocks-csharp/3rd/zxing/qrcode/encoder/QRCode.cs +++ /dev/null @@ -1,125 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Text; - -namespace ZXing.QrCode.Internal -{ - /// satorux@google.com (Satoru Takabayashi) - creator - /// dswitkin@google.com (Daniel Switkin) - ported from C++ - public sealed class QRCode - { - /// - /// - /// - public static int NUM_MASK_PATTERNS = 8; - - /// - /// Initializes a new instance of the class. - /// - public QRCode() - { - MaskPattern = -1; - } - - /// - /// Gets or sets the mode. - /// - /// - /// The mode. - /// - public Mode Mode { get; set; } - - /// - /// Gets or sets the EC level. - /// - /// - /// The EC level. - /// - public ErrorCorrectionLevel ECLevel { get; set; } - - /// - /// Gets or sets the version. - /// - /// - /// The version. - /// - public Version Version { get; set; } - - /// - /// Gets or sets the mask pattern. - /// - /// - /// The mask pattern. - /// - public int MaskPattern { get; set; } - - /// - /// Gets or sets the matrix. - /// - /// - /// The matrix. - /// - public ByteMatrix Matrix { get; set; } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override String ToString() - { - var result = new StringBuilder(200); - result.Append("<<\n"); - result.Append(" mode: "); - result.Append(Mode); - result.Append("\n ecLevel: "); - result.Append(ECLevel); - result.Append("\n version: "); - if (Version == null) - result.Append("null"); - else - result.Append(Version); - result.Append("\n maskPattern: "); - result.Append(MaskPattern); - if (Matrix == null) - { - result.Append("\n matrix: null\n"); - } - else - { - result.Append("\n matrix:\n"); - result.Append(Matrix.ToString()); - } - result.Append(">>\n"); - return result.ToString(); - } - - /// - /// Check if "mask_pattern" is valid. - /// - /// The mask pattern. - /// - /// true if [is valid mask pattern] [the specified mask pattern]; otherwise, false. - /// - public static bool isValidMaskPattern(int maskPattern) - { - return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/Controller/AutoStartup.cs b/shadowsocks-csharp/Controller/AutoStartup.cs deleted file mode 100644 index 36ad775f..00000000 --- a/shadowsocks-csharp/Controller/AutoStartup.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Windows.Forms; -using Microsoft.Win32; - -namespace Shadowsocks.Controller -{ - class AutoStartup - { - public static bool Set(bool enabled) - { - try - { - string path = Application.ExecutablePath; - RegistryKey runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); - if (enabled) - { - runKey.SetValue("Shadowsocks", path); - } - else - { - runKey.DeleteValue("Shadowsocks"); - } - runKey.Close(); - return true; - } - catch (Exception e) - { - Logging.LogUsefulException(e); - return false; - } - } - - public static bool Check() - { - try - { - string path = Application.ExecutablePath; - RegistryKey runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); - string[] runList = runKey.GetValueNames(); - runKey.Close(); - foreach (string item in runList) - { - if (item.Equals("Shadowsocks")) - return true; - } - return false; - } - catch (Exception e) - { - Logging.LogUsefulException(e); - return false; - } - } - } -} diff --git a/shadowsocks-csharp/Controller/FileManager.cs b/shadowsocks-csharp/Controller/FileManager.cs deleted file mode 100755 index cc8f3bf9..00000000 --- a/shadowsocks-csharp/Controller/FileManager.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Text; - -namespace Shadowsocks.Controller -{ - public class FileManager - { - public static bool ByteArrayToFile(string fileName, byte[] content) - { - try - { - System.IO.FileStream _FileStream = - new System.IO.FileStream(fileName, System.IO.FileMode.Create, - System.IO.FileAccess.Write); - _FileStream.Write(content, 0, content.Length); - _FileStream.Close(); - return true; - } - catch (Exception _Exception) - { - Console.WriteLine("Exception caught in process: {0}", - _Exception.ToString()); - } - return false; - } - - public static void UncompressFile(string fileName, byte[] content) - { - FileStream destinationFile = File.Create(fileName); - - // Because the uncompressed size of the file is unknown, - // we are using an arbitrary buffer size. - byte[] buffer = new byte[4096]; - int n; - - using (GZipStream input = new GZipStream(new MemoryStream(content), - CompressionMode.Decompress, false)) - { - while (true) - { - n = input.Read(buffer, 0, buffer.Length); - if (n == 0) - { - break; - } - destinationFile.Write(buffer, 0, n); - } - } - destinationFile.Close(); - } - } -} diff --git a/shadowsocks-csharp/Controller/GfwListUpdater.cs b/shadowsocks-csharp/Controller/GfwListUpdater.cs deleted file mode 100644 index 70720fb9..00000000 --- a/shadowsocks-csharp/Controller/GfwListUpdater.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Net; -using System.IO; -using Shadowsocks.Properties; -using SimpleJson; -using Shadowsocks.Util; -using Shadowsocks.Model; - -namespace Shadowsocks.Controller -{ - public class GFWListUpdater - { - private const string GFWLIST_URL = "https://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt"; - - private static string PAC_FILE = PACServer.PAC_FILE; - - private static string USER_RULE_FILE = PACServer.USER_RULE_FILE; - - public event EventHandler UpdateCompleted; - - public event ErrorEventHandler Error; - - public class ResultEventArgs : EventArgs - { - public bool Success; - - public ResultEventArgs(bool success) - { - this.Success = success; - } - } - - private void http_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) - { - try - { - List lines = ParseResult(e.Result); - if (File.Exists(USER_RULE_FILE)) - { - string local = File.ReadAllText(USER_RULE_FILE, Encoding.UTF8); - string[] rules = local.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); - foreach(string rule in rules) - { - if (rule.StartsWith("!") || rule.StartsWith("[")) - continue; - lines.Add(rule); - } - } - string abpContent = Utils.UnGzip(Resources.abp_js); - abpContent = abpContent.Replace("__RULES__", SimpleJson.SimpleJson.SerializeObject(lines)); - if (File.Exists(PAC_FILE)) - { - string original = File.ReadAllText(PAC_FILE, Encoding.UTF8); - if (original == abpContent) - { - UpdateCompleted(this, new ResultEventArgs(false)); - return; - } - } - File.WriteAllText(PAC_FILE, abpContent, Encoding.UTF8); - if (UpdateCompleted != null) - { - UpdateCompleted(this, new ResultEventArgs(true)); - } - } - catch (Exception ex) - { - if (Error != null) - { - Error(this, new ErrorEventArgs(ex)); - } - } - } - - public void UpdatePACFromGFWList(Configuration config) - { - WebClient http = new WebClient(); - http.Proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort); - http.DownloadStringCompleted += http_DownloadStringCompleted; - http.DownloadStringAsync(new Uri(GFWLIST_URL)); - } - - public List ParseResult(string response) - { - byte[] bytes = Convert.FromBase64String(response); - string content = Encoding.ASCII.GetString(bytes); - string[] lines = content.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); - List valid_lines = new List(lines.Length); - foreach (string line in lines) - { - if (line.StartsWith("!") || line.StartsWith("[")) - continue; - valid_lines.Add(line); - } - return valid_lines; - } - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/Controller/I18N.cs b/shadowsocks-csharp/Controller/I18N.cs deleted file mode 100755 index 3ac09a41..00000000 --- a/shadowsocks-csharp/Controller/I18N.cs +++ /dev/null @@ -1,42 +0,0 @@ -using Shadowsocks.Properties; -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; - -namespace Shadowsocks.Controller -{ - public class I18N - { - protected static Dictionary Strings; - static I18N() - { - Strings = new Dictionary(); - - if (System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag.ToLowerInvariant().StartsWith("zh")) - { - string[] lines = Regex.Split(Resources.cn, "\r\n|\r|\n"); - foreach (string line in lines) - { - string[] kv = Regex.Split(line, "="); - if (kv.Length == 2) - { - Strings[kv[0]] = kv[1]; - } - } - } - } - - public static string GetString(string key) - { - if (Strings.ContainsKey(key)) - { - return Strings[key]; - } - else - { - return key; - } - } - } -} diff --git a/shadowsocks-csharp/Controller/Listener.cs b/shadowsocks-csharp/Controller/Listener.cs deleted file mode 100755 index 9943e536..00000000 --- a/shadowsocks-csharp/Controller/Listener.cs +++ /dev/null @@ -1,163 +0,0 @@ -using Shadowsocks.Model; -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Text; - -namespace Shadowsocks.Controller -{ - public class Listener - { - public interface Service - { - bool Handle(byte[] firstPacket, int length, Socket socket); - } - - Configuration _config; - bool _shareOverLAN; - Socket _socket; - IList _services; - - public Listener(IList services) - { - this._services = services; - } - - private bool CheckIfPortInUse(int port) - { - IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties(); - IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners(); - - foreach (IPEndPoint endPoint in ipEndPoints) - { - if (endPoint.Port == port) - { - return true; - } - } - return false; - } - - public void Start(Configuration config) - { - this._config = config; - this._shareOverLAN = config.shareOverLan; - - if (CheckIfPortInUse(_config.localPort)) - throw new Exception(I18N.GetString("Port already in use")); - - try - { - // Create a TCP/IP socket. - _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - IPEndPoint localEndPoint = null; - if (_shareOverLAN) - { - localEndPoint = new IPEndPoint(IPAddress.Any, _config.localPort); - } - else - { - localEndPoint = new IPEndPoint(IPAddress.Loopback, _config.localPort); - } - - // Bind the socket to the local endpoint and listen for incoming connections. - _socket.Bind(localEndPoint); - _socket.Listen(1024); - - - // Start an asynchronous socket to listen for connections. - Console.WriteLine("Shadowsocks started"); - _socket.BeginAccept( - new AsyncCallback(AcceptCallback), - _socket); - } - catch (SocketException) - { - _socket.Close(); - throw; - } - } - - public void Stop() - { - if (_socket != null) - { - _socket.Close(); - _socket = null; - } - } - - public void AcceptCallback(IAsyncResult ar) - { - Socket listener = (Socket)ar.AsyncState; - try - { - Socket conn = listener.EndAccept(ar); - - byte[] buf = new byte[4096]; - object[] state = new object[] { - conn, - buf - }; - - conn.BeginReceive(buf, 0, buf.Length, 0, - new AsyncCallback(ReceiveCallback), state); - } - catch (ObjectDisposedException) - { - } - catch (Exception e) - { - Console.WriteLine(e); - } - finally - { - try - { - listener.BeginAccept( - new AsyncCallback(AcceptCallback), - listener); - } - catch (ObjectDisposedException) - { - // do nothing - } - catch (Exception e) - { - Logging.LogUsefulException(e); - } - } - } - - - private void ReceiveCallback(IAsyncResult ar) - { - object[] state = (object[])ar.AsyncState; - - Socket conn = (Socket)state[0]; - byte[] buf = (byte[])state[1]; - try - { - int bytesRead = conn.EndReceive(ar); - foreach (Service service in _services) - { - if (service.Handle(buf, bytesRead, conn)) - { - return; - } - } - // no service found for this - // shouldn't happen - conn.Close(); - } - catch (Exception e) - { - Console.WriteLine(e); - conn.Close(); - } - } - } -} diff --git a/shadowsocks-csharp/Controller/Local.cs b/shadowsocks-csharp/Controller/Local.cs deleted file mode 100755 index 5489ea52..00000000 --- a/shadowsocks-csharp/Controller/Local.cs +++ /dev/null @@ -1,399 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Net.Sockets; -using System.Net; -using Shadowsocks.Encryption; -using Shadowsocks.Model; - -namespace Shadowsocks.Controller -{ - - class Local : Listener.Service - { - private Configuration _config; - public Local(Configuration config) - { - this._config = config; - } - - public bool Handle(byte[] firstPacket, int length, Socket socket) - { - if (length < 2 || firstPacket[0] != 5) - { - return false; - } - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); - Handler handler = new Handler(); - handler.connection = socket; - Server server = _config.GetCurrentServer(); - handler.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password); - handler.server = server; - - handler.Start(firstPacket, length); - return true; - } - } - - class Handler - { - //public Encryptor encryptor; - public IEncryptor encryptor; - public Server server; - // Client socket. - public Socket remote; - public Socket connection; - - private byte[] _firstPacket; - private int _firstPacketLength; - // Size of receive buffer. - public const int RecvSize = 16384; - public const int BufferSize = RecvSize + 32; - // remote receive buffer - private byte[] remoteRecvBuffer = new byte[RecvSize]; - // remote send buffer - private byte[] remoteSendBuffer = new byte[BufferSize]; - // connection receive buffer - private byte[] connetionRecvBuffer = new byte[RecvSize]; - // connection send buffer - private byte[] connetionSendBuffer = new byte[BufferSize]; - // Received data string. - - private bool connectionShutdown = false; - private bool remoteShutdown = false; - private bool closed = false; - - private object encryptionLock = new object(); - private object decryptionLock = new object(); - - public void Start(byte[] firstPacket, int length) - { - this._firstPacket = firstPacket; - this._firstPacketLength = length; - try - { - // TODO async resolving - IPAddress ipAddress; - bool parsed = IPAddress.TryParse(server.server, out ipAddress); - if (!parsed) - { - IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server); - ipAddress = ipHostInfo.AddressList[0]; - } - IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port); - - - remote = new Socket(ipAddress.AddressFamily, - SocketType.Stream, ProtocolType.Tcp); - remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); - - // Connect to the remote endpoint. - remote.BeginConnect(remoteEP, - new AsyncCallback(ConnectCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void CheckClose() - { - if (connectionShutdown && remoteShutdown) - { - this.Close(); - } - } - - public void Close() - { - lock (this) - { - if (closed) - { - return; - } - closed = true; - } - if (connection != null) - { - try - { - connection.Shutdown(SocketShutdown.Both); - connection.Close(); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - } - } - if (remote != null) - { - try - { - remote.Shutdown(SocketShutdown.Both); - remote.Close(); - } - catch (SocketException e) - { - Logging.LogUsefulException(e); - } - } - lock (encryptionLock) - { - lock (decryptionLock) - { - ((IDisposable)encryptor).Dispose(); - } - } - } - - private void ConnectCallback(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - // Complete the connection. - remote.EndConnect(ar); - - //Console.WriteLine("Socket connected to {0}", - // remote.RemoteEndPoint.ToString()); - - HandshakeReceive(); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void HandshakeReceive() - { - if (closed) - { - return; - } - try - { - int bytesRead = _firstPacketLength; - - if (bytesRead > 1) - { - byte[] response = { 5, 0 }; - if (_firstPacket[0] != 5) - { - // reject socks 4 - response = new byte[] { 0, 91 }; - Console.WriteLine("socks 5 protocol error"); - } - connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(HandshakeSendCallback), null); - } - else - { - this.Close(); - } - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void HandshakeSendCallback(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - connection.EndSend(ar); - - // +----+-----+-------+------+----------+----------+ - // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | - // +----+-----+-------+------+----------+----------+ - // | 1 | 1 | X'00' | 1 | Variable | 2 | - // +----+-----+-------+------+----------+----------+ - // Skip first 3 bytes - // TODO validate - connection.BeginReceive(connetionRecvBuffer, 0, 3, 0, - new AsyncCallback(handshakeReceive2Callback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void handshakeReceive2Callback(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - int bytesRead = connection.EndReceive(ar); - - if (bytesRead > 0) - { - byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 }; - connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(StartPipe), null); - } - else - { - Console.WriteLine("failed to recv data in handshakeReceive2Callback"); - this.Close(); - } - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - - private void StartPipe(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - connection.EndReceive(ar); - remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeRemoteReceiveCallback), null); - connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeConnectionReceiveCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeRemoteReceiveCallback(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - int bytesRead = remote.EndReceive(ar); - - if (bytesRead > 0) - { - int bytesToSend; - lock (decryptionLock) - { - if (closed) - { - return; - } - encryptor.Decrypt(remoteRecvBuffer, bytesRead, remoteSendBuffer, out bytesToSend); - } - connection.BeginSend(remoteSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeConnectionSendCallback), null); - } - else - { - //Console.WriteLine("bytesRead: " + bytesRead.ToString()); - connection.Shutdown(SocketShutdown.Send); - connectionShutdown = true; - CheckClose(); - } - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeConnectionReceiveCallback(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - int bytesRead = connection.EndReceive(ar); - - if (bytesRead > 0) - { - int bytesToSend; - lock (encryptionLock) - { - if (closed) - { - return; - } - encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend); - } - remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null); - } - else - { - remote.Shutdown(SocketShutdown.Send); - remoteShutdown = true; - CheckClose(); - } - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeRemoteSendCallback(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - remote.EndSend(ar); - connection.BeginReceive(this.connetionRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeConnectionReceiveCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeConnectionSendCallback(IAsyncResult ar) - { - if (closed) - { - return; - } - try - { - connection.EndSend(ar); - remote.BeginReceive(this.remoteRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeRemoteReceiveCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - } - -} diff --git a/shadowsocks-csharp/Controller/Logging.cs b/shadowsocks-csharp/Controller/Logging.cs deleted file mode 100755 index 81f16dd8..00000000 --- a/shadowsocks-csharp/Controller/Logging.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Sockets; -using System.Text; - -namespace Shadowsocks.Controller -{ - public class Logging - { - public static string LogFile; - - public static bool OpenLogFile() - { - try - { - string temppath = Path.GetTempPath(); - LogFile = Path.Combine(temppath, "shadowsocks.log"); - FileStream fs = new FileStream(LogFile, FileMode.Append); - StreamWriterWithTimestamp sw = new StreamWriterWithTimestamp(fs); - sw.AutoFlush = true; - Console.SetOut(sw); - Console.SetError(sw); - - return true; - } - catch (IOException e) - { - Console.WriteLine(e.ToString()); - return false; - } - } - - public static void LogUsefulException(Exception e) - { - // just log useful exceptions, not all of them - if (e is SocketException) - { - SocketException se = (SocketException)e; - if (se.SocketErrorCode == SocketError.ConnectionAborted) - { - // closed by browser when sending - // normally happens when download is canceled or a tab is closed before page is loaded - } - else if (se.SocketErrorCode == SocketError.ConnectionReset) - { - // received rst - } - else if (se.SocketErrorCode == SocketError.NotConnected) - { - // close when not connected - } - else - { - Console.WriteLine(e); - } - } - else - { - Console.WriteLine(e); - } - } - - } - - // Simply extended System.IO.StreamWriter for adding timestamp workaround - public class StreamWriterWithTimestamp : StreamWriter - { - public StreamWriterWithTimestamp(Stream stream) : base(stream) - { - } - - private string GetTimestamp() - { - return "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] "; - } - - public override void WriteLine(string value) - { - base.WriteLine(GetTimestamp() + value); - } - - public override void Write(string value) - { - base.Write(GetTimestamp() + value); - } - } - -} diff --git a/shadowsocks-csharp/Controller/PACServer.cs b/shadowsocks-csharp/Controller/PACServer.cs deleted file mode 100755 index 934a7855..00000000 --- a/shadowsocks-csharp/Controller/PACServer.cs +++ /dev/null @@ -1,194 +0,0 @@ -using Shadowsocks.Model; -using Shadowsocks.Properties; -using Shadowsocks.Util; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.IO.Compression; -using System.Net; -using System.Net.Sockets; -using System.Text; - -namespace Shadowsocks.Controller -{ - class PACServer : Listener.Service - { - public static string PAC_FILE = "pac.txt"; - - public static string USER_RULE_FILE = "user-rule.txt"; - - FileSystemWatcher watcher; - private Configuration _config; - - public event EventHandler PACFileChanged; - - public PACServer() - { - this.WatchPacFile(); - } - - public void UpdateConfiguration(Configuration config) - { - this._config = config; - } - - public bool Handle(byte[] firstPacket, int length, Socket socket) - { - try - { - string request = Encoding.UTF8.GetString(firstPacket, 0, length); - string[] lines = request.Split('\r', '\n'); - bool hostMatch = false, pathMatch = false, useSocks = false; - foreach (string line in lines) - { - string[] kv = line.Split(new char[]{':'}, 2); - if (kv.Length == 2) - { - if (kv[0] == "Host") - { - if (kv[1].Trim() == ((IPEndPoint)socket.LocalEndPoint).ToString()) - { - hostMatch = true; - } - } - else if (kv[0] == "User-Agent") - { - // we need to drop connections when changing servers - /* if (kv[1].IndexOf("Chrome") >= 0) - { - useSocks = true; - } */ - } - } - else if (kv.Length == 1) - { - if (line.IndexOf("pac") >= 0) - { - pathMatch = true; - } - } - } - if (hostMatch && pathMatch) - { - SendResponse(firstPacket, length, socket, useSocks); - return true; - } - return false; - } - catch (ArgumentException) - { - return false; - } - } - - - public string TouchPACFile() - { - if (File.Exists(PAC_FILE)) - { - return PAC_FILE; - } - else - { - FileManager.UncompressFile(PAC_FILE, Resources.proxy_pac_txt); - return PAC_FILE; - } - } - - private string GetPACContent() - { - if (File.Exists(PAC_FILE)) - { - return File.ReadAllText(PAC_FILE, Encoding.UTF8); - } - else - { - return Utils.UnGzip(Resources.proxy_pac_txt); - } - } - - public void SendResponse(byte[] firstPacket, int length, Socket socket, bool useSocks) - { - try - { - string pac = GetPACContent(); - - IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint; - - string proxy = GetPACAddress(firstPacket, length, localEndPoint, useSocks); - - pac = pac.Replace("__PROXY__", proxy); - - string text = String.Format(@"HTTP/1.1 200 OK -Server: Shadowsocks -Content-Type: application/x-ns-proxy-autoconfig -Content-Length: {0} -Connection: Close - -", System.Text.Encoding.UTF8.GetBytes(pac).Length) + pac; - byte[] response = System.Text.Encoding.UTF8.GetBytes(text); - socket.BeginSend(response, 0, response.Length, 0, new AsyncCallback(SendCallback), socket); - Util.Utils.ReleaseMemory(); - } - catch (Exception e) - { - Console.WriteLine(e); - socket.Close(); - } - } - - private void SendCallback(IAsyncResult ar) - { - Socket conn = (Socket)ar.AsyncState; - try - { - conn.Shutdown(SocketShutdown.Send); - } - catch - { } - } - - private void WatchPacFile() - { - if (watcher != null) - { - watcher.Dispose(); - } - watcher = new FileSystemWatcher(Directory.GetCurrentDirectory()); - watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; - watcher.Filter = PAC_FILE; - watcher.Changed += Watcher_Changed; - watcher.Created += Watcher_Changed; - watcher.Deleted += Watcher_Changed; - watcher.Renamed += Watcher_Changed; - watcher.EnableRaisingEvents = true; - } - - private void Watcher_Changed(object sender, FileSystemEventArgs e) - { - if (PACFileChanged != null) - { - PACFileChanged(this, new EventArgs()); - } - } - - private string GetPACAddress(byte[] requestBuf, int length, IPEndPoint localEndPoint, bool useSocks) - { - //try - //{ - // string requestString = Encoding.UTF8.GetString(requestBuf); - // if (requestString.IndexOf("AppleWebKit") >= 0) - // { - // string address = "" + localEndPoint.Address + ":" + config.GetCurrentServer().local_port; - // proxy = "SOCKS5 " + address + "; SOCKS " + address + ";"; - // } - //} - //catch (Exception e) - //{ - // Console.WriteLine(e); - //} - return (useSocks ? "SOCKS5 " : "PROXY ") + localEndPoint.Address + ":" + this._config.localPort + ";"; - } - } -} diff --git a/shadowsocks-csharp/Controller/PolipoRunner.cs b/shadowsocks-csharp/Controller/PolipoRunner.cs deleted file mode 100755 index ae0b46f1..00000000 --- a/shadowsocks-csharp/Controller/PolipoRunner.cs +++ /dev/null @@ -1,126 +0,0 @@ -using Shadowsocks.Model; -using Shadowsocks.Properties; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.IO.Compression; -using System.Text; -using System.Net.NetworkInformation; -using System.Net; - -namespace Shadowsocks.Controller -{ - class PolipoRunner - { - private Process _process; - private static string temppath; - private int _runningPort; - - static PolipoRunner() - { - temppath = Path.GetTempPath(); - try - { - FileManager.UncompressFile(temppath + "/ss_polipo.exe", Resources.polipo_exe); - } - catch (IOException e) - { - Logging.LogUsefulException(e); - } - } - - public int RunningPort - { - get - { - return _runningPort; - } - } - - public void Start(Configuration configuration) - { - Server server = configuration.GetCurrentServer(); - if (_process == null) - { - Process[] existingPolipo = Process.GetProcessesByName("ss_polipo"); - foreach (Process p in existingPolipo) - { - try - { - p.Kill(); - p.WaitForExit(); - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - } - string polipoConfig = Resources.polipo_config; - _runningPort = this.GetFreePort(); - polipoConfig = polipoConfig.Replace("__SOCKS_PORT__", configuration.localPort.ToString()); - polipoConfig = polipoConfig.Replace("__POLIPO_BIND_PORT__", _runningPort.ToString()); - polipoConfig = polipoConfig.Replace("__POLIPO_BIND_IP__", configuration.shareOverLan ? "0.0.0.0" : "127.0.0.1"); - FileManager.ByteArrayToFile(temppath + "/polipo.conf", System.Text.Encoding.UTF8.GetBytes(polipoConfig)); - - _process = new Process(); - // Configure the process using the StartInfo properties. - _process.StartInfo.FileName = temppath + "/ss_polipo.exe"; - _process.StartInfo.Arguments = "-c \"" + temppath + "/polipo.conf\""; - _process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; - _process.StartInfo.UseShellExecute = true; - _process.StartInfo.CreateNoWindow = true; - //_process.StartInfo.RedirectStandardOutput = true; - //_process.StartInfo.RedirectStandardError = true; - _process.Start(); - } - } - - public void Stop() - { - if (_process != null) - { - try - { - _process.Kill(); - _process.WaitForExit(); - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - _process = null; - } - } - - private int GetFreePort() - { - int defaultPort = 8123; - try - { - IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); - IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners(); - - List usedPorts = new List(); - foreach (IPEndPoint endPoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()) - { - usedPorts.Add(endPoint.Port); - } - for (int port = defaultPort; port <= 65535; port++) - { - if (!usedPorts.Contains(port)) - { - return port; - } - } - } - catch (Exception e) - { - // in case access denied - Logging.LogUsefulException(e); - return defaultPort; - } - throw new Exception("No free port found."); - } - } -} diff --git a/shadowsocks-csharp/Controller/PortForwarder.cs b/shadowsocks-csharp/Controller/PortForwarder.cs deleted file mode 100755 index 1057143f..00000000 --- a/shadowsocks-csharp/Controller/PortForwarder.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Sockets; -using System.Text; - -namespace Shadowsocks.Controller -{ - class PortForwarder : Listener.Service - { - int _targetPort; - - public PortForwarder(int targetPort) - { - this._targetPort = targetPort; - } - - public bool Handle(byte[] firstPacket, int length, Socket socket) - { - new Handler().Start(firstPacket, length, socket, this._targetPort); - return true; - } - - class Handler - { - private byte[] _firstPacket; - private int _firstPacketLength; - private Socket _local; - private Socket _remote; - private bool _closed = false; - private bool _localShutdown = false; - private bool _remoteShutdown = false; - public const int RecvSize = 16384; - // remote receive buffer - private byte[] remoteRecvBuffer = new byte[RecvSize]; - // connection receive buffer - private byte[] connetionRecvBuffer = new byte[RecvSize]; - - public void Start(byte[] firstPacket, int length, Socket socket, int targetPort) - { - this._firstPacket = firstPacket; - this._firstPacketLength = length; - this._local = socket; - try - { - // TODO async resolving - IPAddress ipAddress; - bool parsed = IPAddress.TryParse("127.0.0.1", out ipAddress); - IPEndPoint remoteEP = new IPEndPoint(ipAddress, targetPort); - - - _remote = new Socket(ipAddress.AddressFamily, - SocketType.Stream, ProtocolType.Tcp); - _remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); - - // Connect to the remote endpoint. - _remote.BeginConnect(remoteEP, - new AsyncCallback(ConnectCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void ConnectCallback(IAsyncResult ar) - { - if (_closed) - { - return; - } - try - { - _remote.EndConnect(ar); - HandshakeReceive(); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void HandshakeReceive() - { - if (_closed) - { - return; - } - try - { - _remote.BeginSend(_firstPacket, 0, _firstPacketLength, 0, new AsyncCallback(StartPipe), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - - private void StartPipe(IAsyncResult ar) - { - if (_closed) - { - return; - } - try - { - _remote.EndSend(ar); - _remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeRemoteReceiveCallback), null); - _local.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeConnectionReceiveCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeRemoteReceiveCallback(IAsyncResult ar) - { - if (_closed) - { - return; - } - try - { - int bytesRead = _remote.EndReceive(ar); - - if (bytesRead > 0) - { - _local.BeginSend(remoteRecvBuffer, 0, bytesRead, 0, new AsyncCallback(PipeConnectionSendCallback), null); - } - else - { - //Console.WriteLine("bytesRead: " + bytesRead.ToString()); - _local.Shutdown(SocketShutdown.Send); - _localShutdown = true; - CheckClose(); - } - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeConnectionReceiveCallback(IAsyncResult ar) - { - if (_closed) - { - return; - } - try - { - int bytesRead = _local.EndReceive(ar); - - if (bytesRead > 0) - { - _remote.BeginSend(connetionRecvBuffer, 0, bytesRead, 0, new AsyncCallback(PipeRemoteSendCallback), null); - } - else - { - _remote.Shutdown(SocketShutdown.Send); - _remoteShutdown = true; - CheckClose(); - } - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeRemoteSendCallback(IAsyncResult ar) - { - if (_closed) - { - return; - } - try - { - _remote.EndSend(ar); - _local.BeginReceive(this.connetionRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeConnectionReceiveCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void PipeConnectionSendCallback(IAsyncResult ar) - { - if (_closed) - { - return; - } - try - { - _local.EndSend(ar); - _remote.BeginReceive(this.remoteRecvBuffer, 0, RecvSize, 0, - new AsyncCallback(PipeRemoteReceiveCallback), null); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - this.Close(); - } - } - - private void CheckClose() - { - if (_localShutdown && _remoteShutdown) - { - this.Close(); - } - } - - public void Close() - { - lock (this) - { - if (_closed) - { - return; - } - _closed = true; - } - if (_local != null) - { - try - { - _local.Shutdown(SocketShutdown.Both); - _local.Close(); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - } - } - if (_remote != null) - { - try - { - _remote.Shutdown(SocketShutdown.Both); - _remote.Close(); - } - catch (SocketException e) - { - Logging.LogUsefulException(e); - } - } - } - } - } -} diff --git a/shadowsocks-csharp/Controller/ShadowsocksController.cs b/shadowsocks-csharp/Controller/ShadowsocksController.cs deleted file mode 100755 index 203417c2..00000000 --- a/shadowsocks-csharp/Controller/ShadowsocksController.cs +++ /dev/null @@ -1,313 +0,0 @@ -using System.IO; -using Shadowsocks.Model; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Net.Sockets; - -namespace Shadowsocks.Controller -{ - public class ShadowsocksController - { - // controller: - // handle user actions - // manipulates UI - // interacts with low level logic - - private Thread _ramThread; - - private Listener _listener; - private PACServer _pacServer; - private Configuration _config; - private PolipoRunner polipoRunner; - private GFWListUpdater gfwListUpdater; - private bool stopped = false; - - private bool _systemProxyIsDirty = false; - - public class PathEventArgs : EventArgs - { - public string Path; - } - - public event EventHandler ConfigChanged; - public event EventHandler EnableStatusChanged; - public event EventHandler EnableGlobalChanged; - public event EventHandler ShareOverLANStatusChanged; - - // when user clicked Edit PAC, and PAC file has already created - public event EventHandler PACFileReadyToOpen; - - public event EventHandler UpdatePACFromGFWListCompleted; - - public event ErrorEventHandler UpdatePACFromGFWListError; - - public event ErrorEventHandler Errored; - - public ShadowsocksController() - { - _config = Configuration.Load(); - } - - public void Start() - { - Reload(); - } - - protected void ReportError(Exception e) - { - if (Errored != null) - { - Errored(this, new ErrorEventArgs(e)); - } - } - - public Server GetCurrentServer() - { - return _config.GetCurrentServer(); - } - - // always return copy - public Configuration GetConfiguration() - { - return Configuration.Load(); - } - - public void SaveServers(List servers, int localPort) - { - _config.configs = servers; - _config.localPort = localPort; - SaveConfig(_config); - } - - public bool AddServerBySSURL(string ssURL) - { - try - { - var server = new Server(ssURL); - _config.configs.Add(server); - _config.index = _config.configs.Count - 1; - SaveConfig(_config); - return true; - } - catch (Exception e) - { - Logging.LogUsefulException(e); - return false; - } - } - - public void ToggleEnable(bool enabled) - { - _config.enabled = enabled; - UpdateSystemProxy(); - SaveConfig(_config); - if (EnableStatusChanged != null) - { - EnableStatusChanged(this, new EventArgs()); - } - } - - public void ToggleGlobal(bool global) - { - _config.global = global; - UpdateSystemProxy(); - SaveConfig(_config); - if (EnableGlobalChanged != null) - { - EnableGlobalChanged(this, new EventArgs()); - } - } - - public void ToggleShareOverLAN(bool enabled) - { - _config.shareOverLan = enabled; - SaveConfig(_config); - if (ShareOverLANStatusChanged != null) - { - ShareOverLANStatusChanged(this, new EventArgs()); - } - } - - public void SelectServerIndex(int index) - { - _config.index = index; - SaveConfig(_config); - } - - public void Stop() - { - if (stopped) - { - return; - } - stopped = true; - if (_listener != null) - { - _listener.Stop(); - } - if (polipoRunner != null) - { - polipoRunner.Stop(); - } - if (_config.enabled) - { - SystemProxy.Update(_config, true); - } - } - - public void TouchPACFile() - { - string pacFilename = _pacServer.TouchPACFile(); - if (PACFileReadyToOpen != null) - { - PACFileReadyToOpen(this, new PathEventArgs() { Path = pacFilename }); - } - } - - public string GetQRCodeForCurrentServer() - { - Server server = GetCurrentServer(); - string parts = server.method + ":" + server.password + "@" + server.server + ":" + server.server_port; - string base64 = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(parts)); - return "ss://" + base64; - } - - public void UpdatePACFromGFWList() - { - if (gfwListUpdater != null) - { - gfwListUpdater.UpdatePACFromGFWList(_config); - } - } - - protected void Reload() - { - // some logic in configuration updated the config when saving, we need to read it again - _config = Configuration.Load(); - - if (polipoRunner == null) - { - polipoRunner = new PolipoRunner(); - } - if (_pacServer == null) - { - _pacServer = new PACServer(); - _pacServer.PACFileChanged += pacServer_PACFileChanged; - } - _pacServer.UpdateConfiguration(_config); - if (gfwListUpdater == null) - { - gfwListUpdater = new GFWListUpdater(); - gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted; - gfwListUpdater.Error += pacServer_PACUpdateError; - } - - if (_listener != null) - { - _listener.Stop(); - } - - // don't put polipoRunner.Start() before pacServer.Stop() - // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 - // though UseShellExecute is set to true now - // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open - polipoRunner.Stop(); - try - { - polipoRunner.Start(_config); - - Local local = new Local(_config); - List services = new List(); - services.Add(local); - services.Add(_pacServer); - services.Add(new PortForwarder(polipoRunner.RunningPort)); - _listener = new Listener(services); - _listener.Start(_config); - } - catch (Exception e) - { - // translate Microsoft language into human language - // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use - if (e is SocketException) - { - SocketException se = (SocketException)e; - if (se.SocketErrorCode == SocketError.AccessDenied) - { - e = new Exception(I18N.GetString("Port already in use"), e); - } - } - Logging.LogUsefulException(e); - ReportError(e); - } - - if (ConfigChanged != null) - { - ConfigChanged(this, new EventArgs()); - } - - UpdateSystemProxy(); - Util.Utils.ReleaseMemory(); - } - - - protected void SaveConfig(Configuration newConfig) - { - Configuration.Save(newConfig); - Reload(); - } - - - private void UpdateSystemProxy() - { - if (_config.enabled) - { - SystemProxy.Update(_config, false); - _systemProxyIsDirty = true; - } - else - { - // only switch it off if we have switched it on - if (_systemProxyIsDirty) - { - SystemProxy.Update(_config, false); - _systemProxyIsDirty = false; - } - } - } - - private void pacServer_PACFileChanged(object sender, EventArgs e) - { - UpdateSystemProxy(); - } - - private void pacServer_PACUpdateCompleted(object sender, GFWListUpdater.ResultEventArgs e) - { - if (UpdatePACFromGFWListCompleted != null) - UpdatePACFromGFWListCompleted(this, e); - } - - private void pacServer_PACUpdateError(object sender, ErrorEventArgs e) - { - if (UpdatePACFromGFWListError != null) - UpdatePACFromGFWListError(this, e); - } - - private void StartReleasingMemory() - { - _ramThread = new Thread(new ThreadStart(ReleaseMemory)); - _ramThread.IsBackground = true; - _ramThread.Start(); - } - - private void ReleaseMemory() - { - while (true) - { - Util.Utils.ReleaseMemory(); - Thread.Sleep(30 * 1000); - } - } - } -} diff --git a/shadowsocks-csharp/Controller/SystemProxy.cs b/shadowsocks-csharp/Controller/SystemProxy.cs deleted file mode 100755 index dfbc4bc1..00000000 --- a/shadowsocks-csharp/Controller/SystemProxy.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Windows.Forms; -using Microsoft.Win32; -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; -using System.IO; -using Shadowsocks.Model; - -namespace Shadowsocks.Controller -{ - public class SystemProxy - { - - [DllImport("wininet.dll")] - public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); - public const int INTERNET_OPTION_SETTINGS_CHANGED = 39; - public const int INTERNET_OPTION_REFRESH = 37; - static bool _settingsReturn, _refreshReturn; - - public static void NotifyIE() - { - // These lines implement the Interface in the beginning of program - // They cause the OS to refresh the settings, causing IP to realy update - _settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); - _refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); - } - - public static void Update(Configuration config, bool forceDisable) - { - bool global = config.global; - bool enabled = config.enabled; - if (forceDisable) - { - enabled = false; - } - try - { - RegistryKey registry = - Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", - true); - if (enabled) - { - if (global) - { - registry.SetValue("ProxyEnable", 1); - registry.SetValue("ProxyServer", "127.0.0.1:" + config.localPort.ToString()); - registry.SetValue("AutoConfigURL", ""); - } - else - { - registry.SetValue("ProxyEnable", 0); - registry.SetValue("ProxyServer", ""); - registry.SetValue("AutoConfigURL", "http://127.0.0.1:" + config.localPort.ToString() + "/pac?t=" + GetTimestamp(DateTime.Now)); - } - } - else - { - registry.SetValue("ProxyEnable", 0); - registry.SetValue("ProxyServer", ""); - registry.SetValue("AutoConfigURL", ""); - } - SystemProxy.NotifyIE(); - //Must Notify IE first, or the connections do not chanage - CopyProxySettingFromLan(); - } - catch (Exception e) - { - Logging.LogUsefulException(e); - // TODO this should be moved into views - MessageBox.Show(I18N.GetString("Failed to update registry")); - } - } - - private static void CopyProxySettingFromLan() - { - RegistryKey registry = - Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections", - true); - var defaultValue = registry.GetValue("DefaultConnectionSettings"); - try - { - var connections = registry.GetValueNames(); - foreach (String each in connections) - { - if (!(each.Equals("DefaultConnectionSettings") - || each.Equals("LAN Connection") - || each.Equals("SavedLegacySettings"))) - { - //set all the connections's proxy as the lan - registry.SetValue(each, defaultValue); - } - } - SystemProxy.NotifyIE(); - } catch (IOException e) { - Logging.LogUsefulException(e); - } - } - - private static String GetTimestamp(DateTime value) - { - return value.ToString("yyyyMMddHHmmssffff"); - } - } -} diff --git a/shadowsocks-csharp/Controller/UpdateChecker.cs b/shadowsocks-csharp/Controller/UpdateChecker.cs deleted file mode 100755 index 00aab2a0..00000000 --- a/shadowsocks-csharp/Controller/UpdateChecker.cs +++ /dev/null @@ -1,159 +0,0 @@ -using Shadowsocks.Model; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; - -namespace Shadowsocks.Controller -{ - public class UpdateChecker - { - private const string UpdateURL = "https://sourceforge.net/api/file/index/project-id/1817190/path/dist/mtime/desc/limit/10/rss"; - - public string LatestVersionNumber; - public string LatestVersionURL; - public event EventHandler NewVersionFound; - - public const string Version = "2.3"; - - public void CheckUpdate(Configuration config) - { - // TODO test failures - WebClient http = new WebClient(); - http.Proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort); - http.DownloadStringCompleted += http_DownloadStringCompleted; - http.DownloadStringAsync(new Uri(UpdateURL)); - } - - public static int CompareVersion(string l, string r) - { - var ls = l.Split('.'); - var rs = r.Split('.'); - for (int i = 0; i < Math.Max(ls.Length, rs.Length); i++) - { - int lp = (i < ls.Length) ? int.Parse(ls[i]) : 0; - int rp = (i < rs.Length) ? int.Parse(rs[i]) : 0; - if (lp != rp) - { - return lp - rp; - } - } - return 0; - } - - public class VersionComparer : IComparer - { - // Calls CaseInsensitiveComparer.Compare with the parameters reversed. - public int Compare(string x, string y) - { - return CompareVersion(ParseVersionFromURL(x), ParseVersionFromURL(y)); - } - - } - - private static string ParseVersionFromURL(string url) - { - Match match = Regex.Match(url, @".*Shadowsocks-win.*?-([\d\.]+)\.\w+", RegexOptions.IgnoreCase); - if (match.Success) - { - if (match.Groups.Count == 2) - { - return match.Groups[1].Value; - } - } - return null; - } - - private void SortVersions(List versions) - { - versions.Sort(new VersionComparer()); - } - - private bool IsNewVersion(string url) - { - if (url.IndexOf("prerelease") >= 0) - { - return false; - } - // check dotnet 4.0 - AssemblyName[] references = Assembly.GetExecutingAssembly().GetReferencedAssemblies(); - Version dotNetVersion = Environment.Version; - foreach (AssemblyName reference in references) - { - if (reference.Name == "mscorlib") - { - dotNetVersion = reference.Version; - } - } - if (dotNetVersion.Major >= 4) - { - if (url.IndexOf("dotnet4.0") < 0) - { - return false; - } - } - else - { - if (url.IndexOf("dotnet4.0") >= 0) - { - return false; - } - } - string version = ParseVersionFromURL(url); - if (version == null) - { - return false; - } - string currentVersion = Version; - - return CompareVersion(version, currentVersion) > 0; - } - - private void http_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) - { - try - { - string response = e.Result; - - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(response); - XmlNodeList elements = xmlDoc.GetElementsByTagName("media:content"); - List versions = new List(); - foreach (XmlNode el in elements) - { - foreach (XmlAttribute attr in el.Attributes) - { - if (attr.Name == "url") - { - if (IsNewVersion(attr.Value)) - { - versions.Add(attr.Value); - } - } - } - } - if (versions.Count == 0) - { - return; - } - // sort versions - SortVersions(versions); - LatestVersionURL = versions[versions.Count - 1]; - LatestVersionNumber = ParseVersionFromURL(LatestVersionURL); - if (NewVersionFound != null) - { - NewVersionFound(this, new EventArgs()); - } - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - return; - } - } - } -} diff --git a/shadowsocks-csharp/Data/abp.js.gz b/shadowsocks-csharp/Data/abp.js.gz deleted file mode 100755 index 0577c7f5..00000000 Binary files a/shadowsocks-csharp/Data/abp.js.gz and /dev/null differ diff --git a/shadowsocks-csharp/Data/cn.txt b/shadowsocks-csharp/Data/cn.txt deleted file mode 100644 index 32765e9e..00000000 --- a/shadowsocks-csharp/Data/cn.txt +++ /dev/null @@ -1,51 +0,0 @@ -Shadowsocks=Shadowsocks -Enable System Proxy=启用系统代理 -Mode=系统代理模式 -PAC=PAC 模式 -Global=全局模式 -Servers=服务器 -Edit Servers...=编辑服务器... -Start on Boot=开机启动 -Allow Clients from LAN=允许来自局域网的连接 -Edit PAC File...=编辑 PAC 文件... -Show QRCode...=显示二维码... -Scan QRCode from Screen...=扫描屏幕上的二维码... -Show Logs...=显示日志... -About...=关于... -Quit=退出 -Edit Servers=编辑服务器 -&Add=添加(&A) -&Delete=删除(&D) -Server=服务器 -Server IP=服务器 IP -Server Port=服务器端口 -Password=密码 -Encryption=加密 -Proxy Port=代理端口 -Remarks=备注 -OK=确定 -Cancel=取消 -New server=未配置的服务器 -QRCode=二维码 -Shadowsocks Error: {0}=Shadowsocks 错误: {0} -Port already in use=端口已被占用 -Illegal port number format=非法端口格式 -Please add at least one server=请添加至少一个服务器 -Server IP can not be blank=服务器 IP 不能为空 -Password can not be blank=密码不能为空 -Port out of range=端口超出范围 -Shadowsocks {0} Update Found=Shadowsocks {0} 更新 -Click here to download=点击这里下载 -Shadowsocks is here=Shadowsocks 在这里 -You can turn on/off Shadowsocks in the context menu=可以在右键菜单中开关 Shadowsocks -System Proxy Enabled=系统代理已启用 -System Proxy Disabled=系统代理未启用 -Update PAC from GFWList=从 GFWList 更新 PAC -Failed to update PAC file =更新 PAC 文件失败 -PAC updated=更新 PAC 成功 -No updates found. Please report to GFWList if you have problems with it.=未发现更新。如有问题请提交给 GFWList。 -No QRCode found. Try to zoom in or move it to the center of the screen.=未发现二维码,尝试把它放大或移动到靠近屏幕中间的位置 -Failed to decode QRCode=无法解析二维码 -Failed to update registry=无法修改注册表 -System Proxy On: =系统代理已启用: -Running: Port {0}=正在运行:端口 {0} \ No newline at end of file diff --git a/shadowsocks-csharp/Data/libsscrypto.dll.gz b/shadowsocks-csharp/Data/libsscrypto.dll.gz deleted file mode 100755 index 66a1185e..00000000 Binary files a/shadowsocks-csharp/Data/libsscrypto.dll.gz and /dev/null differ diff --git a/shadowsocks-csharp/Data/polipo.exe.gz b/shadowsocks-csharp/Data/polipo.exe.gz deleted file mode 100755 index c7038e12..00000000 Binary files a/shadowsocks-csharp/Data/polipo.exe.gz and /dev/null differ diff --git a/shadowsocks-csharp/Data/polipo_config.txt b/shadowsocks-csharp/Data/polipo_config.txt deleted file mode 100755 index fabeab66..00000000 --- a/shadowsocks-csharp/Data/polipo_config.txt +++ /dev/null @@ -1,10 +0,0 @@ -proxyAddress = "__POLIPO_BIND_IP__" -proxyPort = 8123 - -socksParentProxy = "127.0.0.1:__SOCKS_PORT__" -socksProxyType = socks5 -diskCacheRoot = "" -localDocumentRoot = "" - -allowedPorts = 1-65535 -tunnelAllowedPorts = 1-65535 \ No newline at end of file diff --git a/shadowsocks-csharp/Data/proxy.pac.txt.gz b/shadowsocks-csharp/Data/proxy.pac.txt.gz deleted file mode 100755 index 3e8d18ad..00000000 Binary files a/shadowsocks-csharp/Data/proxy.pac.txt.gz and /dev/null differ diff --git a/shadowsocks-csharp/Encryption/EncryptorBase.cs b/shadowsocks-csharp/Encryption/EncryptorBase.cs deleted file mode 100644 index 8b5cd61a..00000000 --- a/shadowsocks-csharp/Encryption/EncryptorBase.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Security.Cryptography; -using System.Text; - -namespace Shadowsocks.Encryption -{ - public abstract class EncryptorBase - : IEncryptor - { - public const int MAX_INPUT_SIZE = 32768; - - protected EncryptorBase(string method, string password) - { - Method = method; - Password = password; - } - - protected string Method; - protected string Password; - - protected byte[] GetPasswordHash() - { - byte[] inputBytes = Encoding.UTF8.GetBytes(Password); - byte[] hash = MD5.Create().ComputeHash(inputBytes); - return hash; - } - - public abstract void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength); - - public abstract void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength); - - public abstract void Dispose(); - } -} diff --git a/shadowsocks-csharp/Encryption/EncryptorFactory.cs b/shadowsocks-csharp/Encryption/EncryptorFactory.cs deleted file mode 100644 index d5ff15e3..00000000 --- a/shadowsocks-csharp/Encryption/EncryptorFactory.cs +++ /dev/null @@ -1,43 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.Reflection; -namespace Shadowsocks.Encryption -{ - public static class EncryptorFactory - { - private static Dictionary _registeredEncryptors; - - private static Type[] _constructorTypes = new Type[] { typeof(string), typeof(string) }; - - static EncryptorFactory() - { - _registeredEncryptors = new Dictionary(); - foreach (string method in TableEncryptor.SupportedCiphers()) - { - _registeredEncryptors.Add(method, typeof(TableEncryptor)); - } - foreach (string method in PolarSSLEncryptor.SupportedCiphers()) - { - _registeredEncryptors.Add(method, typeof(PolarSSLEncryptor)); - } - foreach (string method in SodiumEncryptor.SupportedCiphers()) - { - _registeredEncryptors.Add(method, typeof(SodiumEncryptor)); - } - } - - public static IEncryptor GetEncryptor(string method, string password) - { - if (string.IsNullOrEmpty(method)) - { - method = "table"; - } - method = method.ToLowerInvariant(); - Type t = _registeredEncryptors[method]; - ConstructorInfo c = t.GetConstructor(_constructorTypes); - IEncryptor result = (IEncryptor)c.Invoke(new object[] { method, password }); - return result; - } - } -} diff --git a/shadowsocks-csharp/Encryption/IEncryptor.cs b/shadowsocks-csharp/Encryption/IEncryptor.cs deleted file mode 100644 index b45c62c7..00000000 --- a/shadowsocks-csharp/Encryption/IEncryptor.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Shadowsocks.Encryption -{ - public interface IEncryptor : IDisposable - { - void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength); - void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength); - } -} diff --git a/shadowsocks-csharp/Encryption/IVEncryptor.cs b/shadowsocks-csharp/Encryption/IVEncryptor.cs deleted file mode 100755 index 0a59a0df..00000000 --- a/shadowsocks-csharp/Encryption/IVEncryptor.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Security.Cryptography; -using System.Text; - -namespace Shadowsocks.Encryption -{ - public abstract class IVEncryptor - : EncryptorBase - { - protected static byte[] tempbuf = new byte[MAX_INPUT_SIZE]; - - protected Dictionary ciphers; - - private static readonly Dictionary CachedKeys = new Dictionary(); - protected byte[] _encryptIV; - protected byte[] _decryptIV; - protected bool _decryptIVReceived; - protected bool _encryptIVSent; - protected int _encryptIVOffset = 0; - protected int _decryptIVOffset = 0; - protected string _method; - protected int _cipher; - protected int[] _cipherInfo; - protected byte[] _key; - protected int keyLen; - protected int ivLen; - - - public IVEncryptor(string method, string password) - : base(method, password) - { - InitKey(method, password); - } - - protected abstract Dictionary getCiphers(); - - protected void InitKey(string method, string password) - { - method = method.ToLower(); - _method = method; - string k = method + ":" + password; - ciphers = getCiphers(); - _cipherInfo = ciphers[_method]; - _cipher = _cipherInfo[2]; - if (_cipher == 0) - { - throw new Exception("method not found"); - } - keyLen = ciphers[_method][0]; - ivLen = ciphers[_method][1]; - if (CachedKeys.ContainsKey(k)) - { - _key = CachedKeys[k]; - } - else - { - byte[] passbuf = Encoding.UTF8.GetBytes(password); - _key = new byte[32]; - byte[] iv = new byte[16]; - bytesToKey(passbuf, _key); - CachedKeys[k] = _key; - } - } - - protected void bytesToKey(byte[] password, byte[] key) - { - byte[] result = new byte[password.Length + 16]; - int i = 0; - byte[] md5sum = null; - while (i < key.Length) - { - MD5 md5 = MD5.Create(); - if (i == 0) - { - md5sum = md5.ComputeHash(password); - } - else - { - md5sum.CopyTo(result, 0); - password.CopyTo(result, md5sum.Length); - md5sum = md5.ComputeHash(result); - } - md5sum.CopyTo(key, i); - i += md5sum.Length; - } - } - - protected static void randBytes(byte[] buf, int length) - { - byte[] temp = new byte[length]; - new Random().NextBytes(temp); - temp.CopyTo(buf, 0); - } - - protected virtual void initCipher(byte[] iv, bool isCipher) - { - if (ivLen > 0) - { - if (isCipher) - { - _encryptIV = new byte[ivLen]; - Array.Copy(iv, _encryptIV, ivLen); - } - else - { - _decryptIV = new byte[ivLen]; - Array.Copy(iv, _decryptIV, ivLen); - } - } - } - - protected abstract void cipherUpdate(bool isCipher, int length, byte[] buf, byte[] outbuf); - - public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength) - { - if (!_encryptIVSent) - { - _encryptIVSent = true; - randBytes(outbuf, ivLen); - initCipher(outbuf, true); - outlength = length + ivLen; - lock (tempbuf) - { - cipherUpdate(true, length, buf, tempbuf); - outlength = length + ivLen; - Buffer.BlockCopy(tempbuf, 0, outbuf, ivLen, length); - } - } - else - { - outlength = length; - cipherUpdate(true, length, buf, outbuf); - } - } - - public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength) - { - if (!_decryptIVReceived) - { - _decryptIVReceived = true; - initCipher(buf, false); - outlength = length - ivLen; - lock (tempbuf) - { - // C# could be multi-threaded - Buffer.BlockCopy(buf, ivLen, tempbuf, 0, length - ivLen); - cipherUpdate(false, length - ivLen, tempbuf, outbuf); - } - } - else - { - outlength = length; - cipherUpdate(false, length, buf, outbuf); - } - } - } -} diff --git a/shadowsocks-csharp/Encryption/PolarSSL.cs b/shadowsocks-csharp/Encryption/PolarSSL.cs deleted file mode 100755 index 93b662a8..00000000 --- a/shadowsocks-csharp/Encryption/PolarSSL.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Shadowsocks.Controller; -using Shadowsocks.Properties; -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; - -namespace Shadowsocks.Encryption -{ - public class PolarSSL - { - const string DLLNAME = "libsscrypto"; - - public const int AES_CTX_SIZE = 8 + 4 * 68; - public const int AES_ENCRYPT = 1; - public const int AES_DECRYPT = 0; - - static PolarSSL() - { - string tempPath = Path.GetTempPath(); - string dllPath = tempPath + "/libsscrypto.dll"; - try - { - FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll); - } - catch (IOException) - { - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - LoadLibrary(dllPath); - } - - [DllImport("Kernel32.dll")] - private static extern IntPtr LoadLibrary(string path); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static void aes_init(IntPtr ctx); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static void aes_free(IntPtr ctx); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static int aes_setkey_enc(IntPtr ctx, byte[] key, int keysize); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static int aes_crypt_cfb128(IntPtr ctx, int mode, int length, ref int iv_off, byte[] iv, byte[] input, byte[] output); - - - public const int ARC4_CTX_SIZE = 264; - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static void arc4_init(IntPtr ctx); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static void arc4_free(IntPtr ctx); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static void arc4_setup(IntPtr ctx, byte[] key, int keysize); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static int arc4_crypt(IntPtr ctx, int length, byte[] input, byte[] output); - - } -} diff --git a/shadowsocks-csharp/Encryption/PolarSSLEncryptor.cs b/shadowsocks-csharp/Encryption/PolarSSLEncryptor.cs deleted file mode 100755 index 6216c24d..00000000 --- a/shadowsocks-csharp/Encryption/PolarSSLEncryptor.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; -using System.Threading; - -namespace Shadowsocks.Encryption -{ - public class PolarSSLEncryptor - : IVEncryptor, IDisposable - { - const int CIPHER_AES = 1; - const int CIPHER_RC4 = 2; - - private IntPtr _encryptCtx = IntPtr.Zero; - private IntPtr _decryptCtx = IntPtr.Zero; - - public PolarSSLEncryptor(string method, string password) - : base(method, password) - { - InitKey(method, password); - } - - private static Dictionary _ciphers = new Dictionary { - {"aes-128-cfb", new int[]{16, 16, CIPHER_AES, PolarSSL.AES_CTX_SIZE}}, - {"aes-192-cfb", new int[]{24, 16, CIPHER_AES, PolarSSL.AES_CTX_SIZE}}, - {"aes-256-cfb", new int[]{32, 16, CIPHER_AES, PolarSSL.AES_CTX_SIZE}}, - {"rc4", new int[]{16, 0, CIPHER_RC4, PolarSSL.ARC4_CTX_SIZE}}, - {"rc4-md5", new int[]{16, 16, CIPHER_RC4, PolarSSL.ARC4_CTX_SIZE}}, - }; - - public static List SupportedCiphers() - { - return new List(_ciphers.Keys); - } - - protected override Dictionary getCiphers() - { - return _ciphers; - } - - protected override void initCipher(byte[] iv, bool isCipher) - { - base.initCipher(iv, isCipher); - - IntPtr ctx; - ctx = Marshal.AllocHGlobal(_cipherInfo[3]); - if (isCipher) - { - _encryptCtx = ctx; - } - else - { - _decryptCtx = ctx; - } - byte[] realkey; - if (_method == "rc4-md5") - { - byte[] temp = new byte[keyLen + ivLen]; - realkey = new byte[keyLen]; - Array.Copy(_key, 0, temp, 0, keyLen); - Array.Copy(iv, 0, temp, keyLen, ivLen); - realkey = MD5.Create().ComputeHash(temp); - } - else - { - realkey = _key; - } - if (_cipher == CIPHER_AES) - { - PolarSSL.aes_init(ctx); - // PolarSSL takes key length by bit - // since we'll use CFB mode, here we both do enc, not dec - PolarSSL.aes_setkey_enc(ctx, realkey, keyLen * 8); - } - else if (_cipher == CIPHER_RC4) - { - PolarSSL.arc4_init(ctx); - // PolarSSL RC4 takes key length by byte - PolarSSL.arc4_setup(ctx, realkey, keyLen); - } - } - - protected override void cipherUpdate(bool isCipher, int length, byte[] buf, byte[] outbuf) - { - // C# could be multi-threaded - if (_disposed) - { - throw new ObjectDisposedException(this.ToString()); - } - byte[] iv; - int ivOffset; - IntPtr ctx; - if (isCipher) - { - iv = _encryptIV; - ivOffset = _encryptIVOffset; - ctx = _encryptCtx; - } - else - { - iv = _decryptIV; - ivOffset = _decryptIVOffset; - ctx = _decryptCtx; - } - switch (_cipher) - { - case CIPHER_AES: - PolarSSL.aes_crypt_cfb128(ctx, isCipher ? PolarSSL.AES_ENCRYPT : PolarSSL.AES_DECRYPT, length, ref ivOffset, iv, buf, outbuf); - if (isCipher) - { - _encryptIVOffset = ivOffset; - } - else - { - _decryptIVOffset = ivOffset; - } - break; - case CIPHER_RC4: - PolarSSL.arc4_crypt(ctx, length, buf, outbuf); - break; - } - } - - #region IDisposable - private bool _disposed; - - public override void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - ~PolarSSLEncryptor() - { - Dispose(false); - } - - protected virtual void Dispose(bool disposing) - { - lock (this) - { - if (_disposed) - { - return; - } - _disposed = true; - } - - if (disposing) - { - if (_encryptCtx != IntPtr.Zero) - { - switch (_cipher) - { - case CIPHER_AES: - PolarSSL.aes_free(_encryptCtx); - break; - case CIPHER_RC4: - PolarSSL.arc4_free(_encryptCtx); - break; - } - Marshal.FreeHGlobal(_encryptCtx); - _encryptCtx = IntPtr.Zero; - } - if (_decryptCtx != IntPtr.Zero) - { - switch (_cipher) - { - case CIPHER_AES: - PolarSSL.aes_free(_decryptCtx); - break; - case CIPHER_RC4: - PolarSSL.arc4_free(_decryptCtx); - break; - } - Marshal.FreeHGlobal(_decryptCtx); - _decryptCtx = IntPtr.Zero; - } - } - } - #endregion - } -} diff --git a/shadowsocks-csharp/Encryption/Sodium.cs b/shadowsocks-csharp/Encryption/Sodium.cs deleted file mode 100755 index 9bc72d32..00000000 --- a/shadowsocks-csharp/Encryption/Sodium.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Shadowsocks.Controller; -using Shadowsocks.Properties; -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; - -namespace Shadowsocks.Encryption -{ - public class Sodium - { - const string DLLNAME = "libsscrypto"; - - static Sodium() - { - string tempPath = Path.GetTempPath(); - string dllPath = tempPath + "/libsscrypto.dll"; - try - { - FileManager.UncompressFile(dllPath, Resources.libsscrypto_dll); - LoadLibrary(dllPath); - } - catch (IOException) - { - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - LoadLibrary(dllPath); - } - - [DllImport("Kernel32.dll")] - private static extern IntPtr LoadLibrary(string path); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static void crypto_stream_salsa20_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, ulong ic, byte[] k); - - [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] - public extern static void crypto_stream_chacha20_xor_ic(byte[] c, byte[] m, ulong mlen, byte[] n, ulong ic, byte[] k); - } -} diff --git a/shadowsocks-csharp/Encryption/SodiumEncryptor.cs b/shadowsocks-csharp/Encryption/SodiumEncryptor.cs deleted file mode 100755 index 5d6165eb..00000000 --- a/shadowsocks-csharp/Encryption/SodiumEncryptor.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Shadowsocks.Encryption -{ - public class SodiumEncryptor - : IVEncryptor, IDisposable - { - const int CIPHER_SALSA20 = 1; - const int CIPHER_CHACHA20 = 2; - - const int SODIUM_BLOCK_SIZE = 64; - - protected int _encryptBytesRemaining; - protected int _decryptBytesRemaining; - protected ulong _encryptIC; - protected ulong _decryptIC; - protected byte[] _encryptBuf; - protected byte[] _decryptBuf; - - public SodiumEncryptor(string method, string password) - : base(method, password) - { - InitKey(method, password); - _encryptBuf = new byte[MAX_INPUT_SIZE + SODIUM_BLOCK_SIZE]; - _decryptBuf = new byte[MAX_INPUT_SIZE + SODIUM_BLOCK_SIZE]; - } - - private static Dictionary _ciphers = new Dictionary { - {"salsa20", new int[]{32, 8, CIPHER_SALSA20, PolarSSL.AES_CTX_SIZE}}, - {"chacha20", new int[]{32, 8, CIPHER_CHACHA20, PolarSSL.AES_CTX_SIZE}}, - }; - - protected override Dictionary getCiphers() - { - return _ciphers; - } - - public static List SupportedCiphers() - { - return new List(_ciphers.Keys); - } - - protected override void cipherUpdate(bool isCipher, int length, byte[] buf, byte[] outbuf) - { - // TODO write a unidirection cipher so we don't have to if if if - int bytesRemaining; - ulong ic; - byte[] sodiumBuf; - byte[] iv; - if (isCipher) - { - bytesRemaining = _encryptBytesRemaining; - ic = _encryptIC; - sodiumBuf = _encryptBuf; - iv = _encryptIV; - } - else - { - bytesRemaining = _decryptBytesRemaining; - ic = _decryptIC; - sodiumBuf = _decryptBuf; - iv = _decryptIV; - } - int padding = bytesRemaining; - Buffer.BlockCopy(buf, 0, sodiumBuf, padding, length); - - switch (_cipher) - { - case CIPHER_SALSA20: - Sodium.crypto_stream_salsa20_xor_ic(sodiumBuf, sodiumBuf, (ulong)(padding + length), iv, ic, _key); - break; - case CIPHER_CHACHA20: - Sodium.crypto_stream_chacha20_xor_ic(sodiumBuf, sodiumBuf, (ulong)(padding + length), iv, ic, _key); - break; - } - Buffer.BlockCopy(sodiumBuf, padding, outbuf, 0, length); - padding += length; - ic += (ulong)padding / SODIUM_BLOCK_SIZE; - bytesRemaining = padding % SODIUM_BLOCK_SIZE; - - if (isCipher) - { - _encryptBytesRemaining = bytesRemaining; - _encryptIC = ic; - } - else - { - _decryptBytesRemaining = bytesRemaining; - _decryptIC = ic; - } - } - - public override void Dispose() - { - } - } -} diff --git a/shadowsocks-csharp/Encryption/TableEncryptor.cs b/shadowsocks-csharp/Encryption/TableEncryptor.cs deleted file mode 100644 index 3dd526d4..00000000 --- a/shadowsocks-csharp/Encryption/TableEncryptor.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Shadowsocks.Encryption -{ - public class TableEncryptor - : EncryptorBase - { - public TableEncryptor(string method, string password) - : base(method, password) - { - byte[] hash = GetPasswordHash(); - // TODO endian - ulong a = BitConverter.ToUInt64(hash, 0); - for (int i = 0; i < 256; i++) - { - _encryptTable[i] = (byte)i; - } - for (int i = 1; i < 1024; i++) - { - _encryptTable = MergeSort(_encryptTable, a, i); - } - for (int i = 0; i < 256; i++) - { - _decryptTable[_encryptTable[i]] = (byte)i; - } - } - - public static List SupportedCiphers() - { - return new List(new string[]{"table"}); - } - - public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength) - { - byte[] result = new byte[length]; - for (int i = 0; i < length; i++) - { - outbuf[i] = _encryptTable[buf[i]]; - } - outlength = length; - } - - - public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength) - { - byte[] result = new byte[length]; - for (int i = 0; i < length; i++) - { - outbuf[i] = _decryptTable[buf[i]]; - } - outlength = length; - } - - private readonly byte[] _encryptTable = new byte[256]; - private readonly byte[] _decryptTable = new byte[256]; - - private static long Compare(byte x, byte y, ulong a, int i) - { - return (long)(a % (ulong)(x + i)) - (long)(a % (ulong)(y + i)); - } - - private byte[] MergeSort(byte[] array, ulong a, int j) - { - if (array.Length == 1) - { - return array; - } - int middle = array.Length / 2; - byte[] left = new byte[middle]; - for (int i = 0; i < middle; i++) - { - left[i] = array[i]; - } - byte[] right = new byte[array.Length - middle]; - for (int i = 0; i < array.Length - middle; i++) - { - right[i] = array[i + middle]; - } - left = MergeSort(left, a, j); - right = MergeSort(right, a, j); - - int leftptr = 0; - int rightptr = 0; - - byte[] sorted = new byte[array.Length]; - for (int k = 0; k < array.Length; k++) - { - if (rightptr == right.Length || ((leftptr < left.Length) && (Compare(left[leftptr], right[rightptr], a, j) <= 0))) - { - sorted[k] = left[leftptr]; - leftptr++; - } - else if (leftptr == left.Length || ((rightptr < right.Length) && (Compare(right[rightptr], left[leftptr], a, j)) <= 0)) - { - sorted[k] = right[rightptr]; - rightptr++; - } - } - return sorted; - } - - - public override void Dispose() - { - } - } -} diff --git a/shadowsocks-csharp/Model/Configuration.cs b/shadowsocks-csharp/Model/Configuration.cs deleted file mode 100755 index 56c91759..00000000 --- a/shadowsocks-csharp/Model/Configuration.cs +++ /dev/null @@ -1,150 +0,0 @@ -using Shadowsocks.Controller; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Windows.Forms; - -namespace Shadowsocks.Model -{ - [Serializable] - public class Configuration - { - public List configs; - public int index; - public bool global; - public bool enabled; - public bool shareOverLan; - public bool isDefault; - public int localPort; - - private static string CONFIG_FILE = "gui-config.json"; - - public Server GetCurrentServer() - { - if (index >= 0 && index < configs.Count) - { - return configs[index]; - } - else - { - return GetDefaultServer(); - } - } - - public static void CheckServer(Server server) - { - CheckPort(server.server_port); - CheckPassword(server.password); - CheckServer(server.server); - } - - public static Configuration Load() - { - try - { - string configContent = File.ReadAllText(CONFIG_FILE); - Configuration config = SimpleJson.SimpleJson.DeserializeObject(configContent, new JsonSerializerStrategy()); - config.isDefault = false; - if (config.localPort == 0) - { - config.localPort = 1080; - } - return config; - } - catch (Exception e) - { - if (!(e is FileNotFoundException)) - { - Console.WriteLine(e); - } - return new Configuration - { - index = 0, - isDefault = true, - localPort = 1080, - configs = new List() - { - GetDefaultServer() - } - }; - } - } - - public static void Save(Configuration config) - { - if (config.index >= config.configs.Count) - { - config.index = config.configs.Count - 1; - } - if (config.index < 0) - { - config.index = 0; - } - config.isDefault = false; - try - { - using (StreamWriter sw = new StreamWriter(File.Open(CONFIG_FILE, FileMode.Create))) - { - string jsonString = SimpleJson.SimpleJson.SerializeObject(config); - sw.Write(jsonString); - sw.Flush(); - } - } - catch (IOException e) - { - Console.Error.WriteLine(e); - } - } - - public static Server GetDefaultServer() - { - return new Server(); - } - - private static void Assert(bool condition) - { - if (!condition) - { - throw new Exception(I18N.GetString("assertion failure")); - } - } - - public static void CheckPort(int port) - { - if (port <= 0 || port > 65535) - { - throw new ArgumentException(I18N.GetString("Port out of range")); - } - } - - private static void CheckPassword(string password) - { - if (string.IsNullOrEmpty(password)) - { - throw new ArgumentException(I18N.GetString("Password can not be blank")); - } - } - - private static void CheckServer(string server) - { - if (string.IsNullOrEmpty(server)) - { - throw new ArgumentException(I18N.GetString("Server IP can not be blank")); - } - } - - private class JsonSerializerStrategy : SimpleJson.PocoJsonSerializerStrategy - { - // convert string to int - public override object DeserializeObject(object value, Type type) - { - if (type == typeof(Int32) && value.GetType() == typeof(string)) - { - return Int32.Parse(value.ToString()); - } - return base.DeserializeObject(value, type); - } - } - } -} diff --git a/shadowsocks-csharp/Model/Server.cs b/shadowsocks-csharp/Model/Server.cs deleted file mode 100755 index 4acc3a0e..00000000 --- a/shadowsocks-csharp/Model/Server.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Diagnostics; -using SimpleJson; -using Shadowsocks.Controller; -using System.Text.RegularExpressions; - -namespace Shadowsocks.Model -{ - [Serializable] - public class Server - { - public string server; - public int server_port; - public string password; - public string method; - public string remarks; - - public string FriendlyName() - { - if (string.IsNullOrEmpty(server)) - { - return I18N.GetString("New server"); - } - if (string.IsNullOrEmpty(remarks)) - { - return server + ":" + server_port; - } - else - { - return remarks + " (" + server + ":" + server_port + ")"; - } - } - - public Server() - { - this.server = ""; - this.server_port = 8388; - this.method = "aes-256-cfb"; - this.password = ""; - this.remarks = ""; - } - - public Server(string ssURL) : this() - { - string[] r1 = Regex.Split(ssURL, "ss://", RegexOptions.IgnoreCase); - string base64 = r1[1].ToString(); - byte[] bytes = null; - for (var i = 0; i < 3; i++) - { - try - { - bytes = System.Convert.FromBase64String(base64); - } - catch (FormatException) - { - base64 += "="; - } - } - if (bytes == null) - { - throw new FormatException(); - } - try - { - string data = Encoding.UTF8.GetString(bytes); - int indexLastAt = data.LastIndexOf('@'); - - string afterAt = data.Substring(indexLastAt + 1); - int indexLastColon = afterAt.LastIndexOf(':'); - this.server_port = int.Parse(afterAt.Substring(indexLastColon + 1)); - this.server = afterAt.Substring(0, indexLastColon); - - string beforeAt = data.Substring(0, indexLastAt); - string[] parts = beforeAt.Split(new[] { ':' }); - this.method = parts[0]; - this.password = parts[1]; - } - catch (IndexOutOfRangeException) - { - throw new FormatException(); - } - } - } -} diff --git a/shadowsocks-csharp/Program.cs b/shadowsocks-csharp/Program.cs deleted file mode 100755 index 8ca485d7..00000000 --- a/shadowsocks-csharp/Program.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Shadowsocks.Controller; -using Shadowsocks.Properties; -using Shadowsocks.View; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Threading; -using System.Windows.Forms; - -namespace Shadowsocks -{ - static class Program - { - /// - /// 应用程序的主入口点。 - /// - [STAThread] - static void Main() - { - Util.Utils.ReleaseMemory(); - using (Mutex mutex = new Mutex(false, "Global\\" + "71981632-A427-497F-AB91-241CD227EC1F")) - { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - - if (!mutex.WaitOne(0, false)) - { - Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks"); - if (oldProcesses.Length > 0) - { - Process oldProcess = oldProcesses[0]; - } - MessageBox.Show("Shadowsocks is already running.\n\nFind Shadowsocks icon in your notify tray."); - return; - } - Directory.SetCurrentDirectory(Application.StartupPath); -#if !DEBUG - Logging.OpenLogFile(); -#endif - ShadowsocksController controller = new ShadowsocksController(); - - MenuViewController viewController = new MenuViewController(controller); - - controller.Start(); - - Application.Run(); - } - } - } -} diff --git a/shadowsocks-csharp/Properties/AssemblyInfo.cs b/shadowsocks-csharp/Properties/AssemblyInfo.cs deleted file mode 100755 index 2a6fc3db..00000000 --- a/shadowsocks-csharp/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Shadowsocks.Controller; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// 有关程序集的常规信息通过下列属性集 -// 控制。更改这些属性值可修改 -// 与程序集关联的信息。 -[assembly: AssemblyTitle("Shadowsocks")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Shadowsocks")] -[assembly: AssemblyCopyright("Copyright © clowwindy 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// 将 ComVisible 设置为 false 使此程序集中的类型 -// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, -// 则将该类型上的 ComVisible 属性设置为 true。 -[assembly: ComVisible(false)] - -// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID -[assembly: Guid("f8334709-4309-436a-8bbd-6165dcf4a660")] - -// 程序集的版本信息由下面四个值组成: -// -// 主版本 -// 次版本 -// 内部版本号 -// 修订号 -// -// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, -// 方法是按如下所示使用“*”: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion(UpdateChecker.Version)] -// [assembly: AssemblyFileVersion("2.0.0")] diff --git a/shadowsocks-csharp/Properties/Resources.Designer.cs b/shadowsocks-csharp/Properties/Resources.Designer.cs deleted file mode 100755 index c44569de..00000000 --- a/shadowsocks-csharp/Properties/Resources.Designer.cs +++ /dev/null @@ -1,199 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.34209 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Shadowsocks.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shadowsocks.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized resource of type System.Byte[]. - /// - internal static byte[] abp_js { - get { - object obj = ResourceManager.GetObject("abp_js", resourceCulture); - return ((byte[])(obj)); - } - } - - /// - /// Looks up a localized string similar to Shadowsocks=Shadowsocks - ///Enable System Proxy=启用系统代理 - ///Mode=系统代理模式 - ///PAC=PAC 模式 - ///Global=全局模式 - ///Servers=服务器 - ///Edit Servers...=编辑服务器... - ///Start on Boot=开机启动 - ///Allow Clients from LAN=允许来自局域网的连接 - ///Edit PAC File...=编辑 PAC 文件... - ///Show QRCode...=显示二维码... - ///Scan QRCode from Screen...=扫描屏幕上的二维码... - ///Show Logs...=显示日志... - ///About...=关于... - ///Quit=退出 - ///Edit Servers=编辑服务器 - ///&Add=添加(&A) - ///&Delete=删除(&D) - ///Server=服务器 - ///Server IP=服务器 IP - ///Server Port=服务器端口 - ///Password=密码 - ///Encryption=加密 - ///Proxy Port=代理端口 - ///Remarks=备注 - ///OK=确定 - ///Cancel=取消 - ///New server=未配置的服务器 - ///QRCode=二维码 - ///Shadows [rest of string was truncated]";. - /// - internal static string cn { - get { - return ResourceManager.GetString("cn", resourceCulture); - } - } - - /// - /// Looks up a localized resource of type System.Byte[]. - /// - internal static byte[] libsscrypto_dll { - get { - object obj = ResourceManager.GetObject("libsscrypto_dll", resourceCulture); - return ((byte[])(obj)); - } - } - - /// - /// Looks up a localized string similar to proxyAddress = "__POLIPO_BIND_IP__" - ///proxyPort = 8123 - /// - ///socksParentProxy = "127.0.0.1:__SOCKS_PORT__" - ///socksProxyType = socks5 - ///diskCacheRoot = "" - ///localDocumentRoot = "" - /// - ///allowedPorts = 1-65535 - ///tunnelAllowedPorts = 1-65535. - /// - internal static string polipo_config { - get { - return ResourceManager.GetString("polipo_config", resourceCulture); - } - } - - /// - /// Looks up a localized resource of type System.Byte[]. - /// - internal static byte[] polipo_exe { - get { - object obj = ResourceManager.GetObject("polipo_exe", resourceCulture); - return ((byte[])(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Byte[]. - /// - internal static byte[] proxy_pac_txt { - get { - object obj = ResourceManager.GetObject("proxy_pac_txt", resourceCulture); - return ((byte[])(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ss16 { - get { - object obj = ResourceManager.GetObject("ss16", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ss20 { - get { - object obj = ResourceManager.GetObject("ss20", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ss24 { - get { - object obj = ResourceManager.GetObject("ss24", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ssw128 { - get { - object obj = ResourceManager.GetObject("ssw128", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - } -} diff --git a/shadowsocks-csharp/Properties/Resources.resx b/shadowsocks-csharp/Properties/Resources.resx deleted file mode 100755 index ee5f98ea..00000000 --- a/shadowsocks-csharp/Properties/Resources.resx +++ /dev/null @@ -1,151 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - ..\Data\abp.js.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - ..\data\cn.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - - ..\data\libsscrypto.dll.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - ..\Data\polipo_config.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;gb2312 - - - ..\Data\polipo.exe.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - ..\Data\proxy.pac.txt.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - ..\Resources\ss16.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\ss20.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\ss24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\ssw128.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - \ No newline at end of file diff --git a/shadowsocks-csharp/Resources/ss16.png b/shadowsocks-csharp/Resources/ss16.png deleted file mode 100755 index eb3aaee2..00000000 Binary files a/shadowsocks-csharp/Resources/ss16.png and /dev/null differ diff --git a/shadowsocks-csharp/Resources/ss20.png b/shadowsocks-csharp/Resources/ss20.png deleted file mode 100755 index e0c5dd8a..00000000 Binary files a/shadowsocks-csharp/Resources/ss20.png and /dev/null differ diff --git a/shadowsocks-csharp/Resources/ss24.png b/shadowsocks-csharp/Resources/ss24.png deleted file mode 100755 index 9a155ff1..00000000 Binary files a/shadowsocks-csharp/Resources/ss24.png and /dev/null differ diff --git a/shadowsocks-csharp/Resources/ssw128.png b/shadowsocks-csharp/Resources/ssw128.png deleted file mode 100755 index f9676a25..00000000 Binary files a/shadowsocks-csharp/Resources/ssw128.png and /dev/null differ diff --git a/shadowsocks-csharp/Util/Util.cs b/shadowsocks-csharp/Util/Util.cs deleted file mode 100755 index 15463a3a..00000000 --- a/shadowsocks-csharp/Util/Util.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.IO.Compression; -using System.Runtime.InteropServices; -using System.Text; - -namespace Shadowsocks.Util -{ - public class Utils - { - public static void ReleaseMemory() - { - // release any unused pages - // making the numbers look good in task manager - // this is totally nonsense in programming - // but good for those users who care - // making them happier with their everyday life - // which is part of user experience - GC.Collect(GC.MaxGeneration); - GC.WaitForPendingFinalizers(); - SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, - (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF); - } - - public static string UnGzip(byte[] buf) - { - byte[] buffer = new byte[1024]; - int n; - using (MemoryStream sb = new MemoryStream()) - { - using (GZipStream input = new GZipStream(new MemoryStream(buf), - CompressionMode.Decompress, false)) - { - while ((n = input.Read(buffer, 0, buffer.Length)) > 0) - { - sb.Write(buffer, 0, n); - } - } - return System.Text.Encoding.UTF8.GetString(sb.ToArray()); - } - } - - [DllImport("kernel32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetProcessWorkingSetSize(IntPtr process, - UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize); - } -} diff --git a/shadowsocks-csharp/View/ConfigForm.Designer.cs b/shadowsocks-csharp/View/ConfigForm.Designer.cs deleted file mode 100755 index 83dae64a..00000000 --- a/shadowsocks-csharp/View/ConfigForm.Designer.cs +++ /dev/null @@ -1,458 +0,0 @@ -namespace Shadowsocks.View -{ - partial class ConfigForm - { - /// - /// 必需的设计器变量。 - /// - private System.ComponentModel.IContainer components = null; - - /// - /// 清理所有正在使用的资源。 - /// - /// 如果应释放托管资源,为 true;否则为 false。 - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows 窗体设计器生成的代码 - - /// - /// 设计器支持所需的方法 - 不要 - /// 使用代码编辑器修改此方法的内容。 - /// - private void InitializeComponent() - { - this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); - this.RemarksTextBox = new System.Windows.Forms.TextBox(); - this.RemarksLabel = new System.Windows.Forms.Label(); - this.IPLabel = new System.Windows.Forms.Label(); - this.ServerPortLabel = new System.Windows.Forms.Label(); - this.PasswordLabel = new System.Windows.Forms.Label(); - this.IPTextBox = new System.Windows.Forms.TextBox(); - this.ServerPortTextBox = new System.Windows.Forms.TextBox(); - this.PasswordTextBox = new System.Windows.Forms.TextBox(); - this.EncryptionLabel = new System.Windows.Forms.Label(); - this.EncryptionSelect = new System.Windows.Forms.ComboBox(); - this.panel2 = new System.Windows.Forms.Panel(); - this.OKButton = new System.Windows.Forms.Button(); - this.MyCancelButton = new System.Windows.Forms.Button(); - this.DeleteButton = new System.Windows.Forms.Button(); - this.AddButton = new System.Windows.Forms.Button(); - this.ServerGroupBox = new System.Windows.Forms.GroupBox(); - this.ServersListBox = new System.Windows.Forms.ListBox(); - this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); - this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); - this.ProxyPortTextBox = new System.Windows.Forms.TextBox(); - this.ProxyPortLabel = new System.Windows.Forms.Label(); - this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); - this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); - this.tableLayoutPanel1.SuspendLayout(); - this.ServerGroupBox.SuspendLayout(); - this.tableLayoutPanel2.SuspendLayout(); - this.tableLayoutPanel5.SuspendLayout(); - this.tableLayoutPanel3.SuspendLayout(); - this.tableLayoutPanel4.SuspendLayout(); - this.SuspendLayout(); - // - // tableLayoutPanel1 - // - this.tableLayoutPanel1.AutoSize = true; - this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.tableLayoutPanel1.ColumnCount = 2; - this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel1.Controls.Add(this.RemarksTextBox, 1, 5); - this.tableLayoutPanel1.Controls.Add(this.RemarksLabel, 0, 5); - this.tableLayoutPanel1.Controls.Add(this.IPLabel, 0, 0); - this.tableLayoutPanel1.Controls.Add(this.ServerPortLabel, 0, 1); - this.tableLayoutPanel1.Controls.Add(this.PasswordLabel, 0, 2); - this.tableLayoutPanel1.Controls.Add(this.IPTextBox, 1, 0); - this.tableLayoutPanel1.Controls.Add(this.ServerPortTextBox, 1, 1); - this.tableLayoutPanel1.Controls.Add(this.PasswordTextBox, 1, 2); - this.tableLayoutPanel1.Controls.Add(this.EncryptionLabel, 0, 3); - this.tableLayoutPanel1.Controls.Add(this.EncryptionSelect, 1, 3); - this.tableLayoutPanel1.Location = new System.Drawing.Point(8, 21); - this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel1.Name = "tableLayoutPanel1"; - this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(3); - this.tableLayoutPanel1.RowCount = 6; - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.Size = new System.Drawing.Size(238, 137); - this.tableLayoutPanel1.TabIndex = 0; - // - // RemarksTextBox - // - this.RemarksTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); - this.RemarksTextBox.Location = new System.Drawing.Point(72, 111); - this.RemarksTextBox.MaxLength = 32; - this.RemarksTextBox.Name = "RemarksTextBox"; - this.RemarksTextBox.Size = new System.Drawing.Size(160, 20); - this.RemarksTextBox.TabIndex = 10; - this.RemarksTextBox.WordWrap = false; - // - // RemarksLabel - // - this.RemarksLabel.Anchor = System.Windows.Forms.AnchorStyles.Right; - this.RemarksLabel.AutoSize = true; - this.RemarksLabel.Location = new System.Drawing.Point(17, 114); - this.RemarksLabel.Name = "RemarksLabel"; - this.RemarksLabel.Size = new System.Drawing.Size(49, 13); - this.RemarksLabel.TabIndex = 9; - this.RemarksLabel.Text = "Remarks"; - // - // IPLabel - // - this.IPLabel.Anchor = System.Windows.Forms.AnchorStyles.Right; - this.IPLabel.AutoSize = true; - this.IPLabel.Location = new System.Drawing.Point(15, 9); - this.IPLabel.Name = "IPLabel"; - this.IPLabel.Size = new System.Drawing.Size(51, 13); - this.IPLabel.TabIndex = 0; - this.IPLabel.Text = "Server IP"; - // - // ServerPortLabel - // - this.ServerPortLabel.Anchor = System.Windows.Forms.AnchorStyles.Right; - this.ServerPortLabel.AutoSize = true; - this.ServerPortLabel.Location = new System.Drawing.Point(6, 35); - this.ServerPortLabel.Name = "ServerPortLabel"; - this.ServerPortLabel.Size = new System.Drawing.Size(60, 13); - this.ServerPortLabel.TabIndex = 1; - this.ServerPortLabel.Text = "Server Port"; - // - // PasswordLabel - // - this.PasswordLabel.Anchor = System.Windows.Forms.AnchorStyles.Right; - this.PasswordLabel.AutoSize = true; - this.PasswordLabel.Location = new System.Drawing.Point(13, 61); - this.PasswordLabel.Name = "PasswordLabel"; - this.PasswordLabel.Size = new System.Drawing.Size(53, 13); - this.PasswordLabel.TabIndex = 2; - this.PasswordLabel.Text = "Password"; - // - // IPTextBox - // - this.IPTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); - this.IPTextBox.Location = new System.Drawing.Point(72, 6); - this.IPTextBox.MaxLength = 512; - this.IPTextBox.Name = "IPTextBox"; - this.IPTextBox.Size = new System.Drawing.Size(160, 20); - this.IPTextBox.TabIndex = 0; - this.IPTextBox.WordWrap = false; - // - // ServerPortTextBox - // - this.ServerPortTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); - this.ServerPortTextBox.Location = new System.Drawing.Point(72, 32); - this.ServerPortTextBox.MaxLength = 10; - this.ServerPortTextBox.Name = "ServerPortTextBox"; - this.ServerPortTextBox.Size = new System.Drawing.Size(160, 20); - this.ServerPortTextBox.TabIndex = 1; - this.ServerPortTextBox.WordWrap = false; - // - // PasswordTextBox - // - this.PasswordTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); - this.PasswordTextBox.Location = new System.Drawing.Point(72, 58); - this.PasswordTextBox.MaxLength = 256; - this.PasswordTextBox.Name = "PasswordTextBox"; - this.PasswordTextBox.PasswordChar = '*'; - this.PasswordTextBox.Size = new System.Drawing.Size(160, 20); - this.PasswordTextBox.TabIndex = 2; - this.PasswordTextBox.WordWrap = false; - // - // EncryptionLabel - // - this.EncryptionLabel.Anchor = System.Windows.Forms.AnchorStyles.Right; - this.EncryptionLabel.AutoSize = true; - this.EncryptionLabel.Location = new System.Drawing.Point(9, 88); - this.EncryptionLabel.Name = "EncryptionLabel"; - this.EncryptionLabel.Size = new System.Drawing.Size(57, 13); - this.EncryptionLabel.TabIndex = 8; - this.EncryptionLabel.Text = "Encryption"; - // - // EncryptionSelect - // - this.EncryptionSelect.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.EncryptionSelect.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.EncryptionSelect.FormattingEnabled = true; - this.EncryptionSelect.ImeMode = System.Windows.Forms.ImeMode.NoControl; - this.EncryptionSelect.ItemHeight = 13; - this.EncryptionSelect.Items.AddRange(new object[] { - "table", - "rc4-md5", - "salsa20", - "chacha20", - "aes-256-cfb", - "aes-192-cfb", - "aes-128-cfb", - "rc4"}); - this.EncryptionSelect.Location = new System.Drawing.Point(72, 84); - this.EncryptionSelect.Name = "EncryptionSelect"; - this.EncryptionSelect.Size = new System.Drawing.Size(160, 21); - this.EncryptionSelect.TabIndex = 3; - // - // panel2 - // - this.panel2.Anchor = System.Windows.Forms.AnchorStyles.Top; - this.panel2.AutoSize = true; - this.panel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.panel2.Location = new System.Drawing.Point(207, 187); - this.panel2.Name = "panel2"; - this.panel2.Size = new System.Drawing.Size(0, 0); - this.panel2.TabIndex = 1; - // - // OKButton - // - this.OKButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.OKButton.Dock = System.Windows.Forms.DockStyle.Right; - this.OKButton.Location = new System.Drawing.Point(3, 3); - this.OKButton.Margin = new System.Windows.Forms.Padding(3, 3, 3, 0); - this.OKButton.Name = "OKButton"; - this.OKButton.Size = new System.Drawing.Size(75, 23); - this.OKButton.TabIndex = 8; - this.OKButton.Text = "OK"; - this.OKButton.UseVisualStyleBackColor = true; - this.OKButton.Click += new System.EventHandler(this.OKButton_Click); - // - // MyCancelButton - // - this.MyCancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.MyCancelButton.Dock = System.Windows.Forms.DockStyle.Right; - this.MyCancelButton.Location = new System.Drawing.Point(84, 3); - this.MyCancelButton.Margin = new System.Windows.Forms.Padding(3, 3, 0, 0); - this.MyCancelButton.Name = "MyCancelButton"; - this.MyCancelButton.Size = new System.Drawing.Size(75, 23); - this.MyCancelButton.TabIndex = 9; - this.MyCancelButton.Text = "Cancel"; - this.MyCancelButton.UseVisualStyleBackColor = true; - this.MyCancelButton.Click += new System.EventHandler(this.CancelButton_Click); - // - // DeleteButton - // - this.DeleteButton.Dock = System.Windows.Forms.DockStyle.Right; - this.DeleteButton.Location = new System.Drawing.Point(86, 6); - this.DeleteButton.Margin = new System.Windows.Forms.Padding(3, 6, 0, 3); - this.DeleteButton.Name = "DeleteButton"; - this.DeleteButton.Size = new System.Drawing.Size(80, 23); - this.DeleteButton.TabIndex = 7; - this.DeleteButton.Text = "&Delete"; - this.DeleteButton.UseVisualStyleBackColor = true; - this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click); - // - // AddButton - // - this.AddButton.Dock = System.Windows.Forms.DockStyle.Left; - this.AddButton.Location = new System.Drawing.Point(0, 6); - this.AddButton.Margin = new System.Windows.Forms.Padding(0, 6, 3, 3); - this.AddButton.Name = "AddButton"; - this.AddButton.Size = new System.Drawing.Size(80, 23); - this.AddButton.TabIndex = 6; - this.AddButton.Text = "&Add"; - this.AddButton.UseVisualStyleBackColor = true; - this.AddButton.Click += new System.EventHandler(this.AddButton_Click); - // - // ServerGroupBox - // - this.ServerGroupBox.AutoSize = true; - this.ServerGroupBox.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.ServerGroupBox.Controls.Add(this.tableLayoutPanel1); - this.ServerGroupBox.Location = new System.Drawing.Point(178, 0); - this.ServerGroupBox.Margin = new System.Windows.Forms.Padding(12, 0, 0, 0); - this.ServerGroupBox.Name = "ServerGroupBox"; - this.ServerGroupBox.Size = new System.Drawing.Size(249, 174); - this.ServerGroupBox.TabIndex = 6; - this.ServerGroupBox.TabStop = false; - this.ServerGroupBox.Text = "Server"; - // - // ServersListBox - // - this.ServersListBox.FormattingEnabled = true; - this.ServersListBox.IntegralHeight = false; - this.ServersListBox.Location = new System.Drawing.Point(0, 0); - this.ServersListBox.Margin = new System.Windows.Forms.Padding(0); - this.ServersListBox.Name = "ServersListBox"; - this.ServersListBox.Size = new System.Drawing.Size(166, 148); - this.ServersListBox.TabIndex = 5; - this.ServersListBox.SelectedIndexChanged += new System.EventHandler(this.ServersListBox_SelectedIndexChanged); - // - // tableLayoutPanel2 - // - this.tableLayoutPanel2.AutoSize = true; - this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.tableLayoutPanel2.ColumnCount = 2; - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel2.Controls.Add(this.tableLayoutPanel5, 1, 1); - this.tableLayoutPanel2.Controls.Add(this.tableLayoutPanel3, 1, 2); - this.tableLayoutPanel2.Controls.Add(this.ServersListBox, 0, 0); - this.tableLayoutPanel2.Controls.Add(this.ServerGroupBox, 1, 0); - this.tableLayoutPanel2.Controls.Add(this.tableLayoutPanel4, 0, 1); - this.tableLayoutPanel2.Location = new System.Drawing.Point(12, 12); - this.tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel2.Name = "tableLayoutPanel2"; - this.tableLayoutPanel2.RowCount = 3; - this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel2.Size = new System.Drawing.Size(427, 238); - this.tableLayoutPanel2.TabIndex = 7; - // - // tableLayoutPanel5 - // - this.tableLayoutPanel5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Right))); - this.tableLayoutPanel5.AutoSize = true; - this.tableLayoutPanel5.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.tableLayoutPanel5.ColumnCount = 2; - this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel5.Controls.Add(this.ProxyPortTextBox, 1, 0); - this.tableLayoutPanel5.Controls.Add(this.ProxyPortLabel, 0, 0); - this.tableLayoutPanel5.Location = new System.Drawing.Point(241, 174); - this.tableLayoutPanel5.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel5.Name = "tableLayoutPanel5"; - this.tableLayoutPanel5.Padding = new System.Windows.Forms.Padding(3); - this.tableLayoutPanel5.RowCount = 1; - this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); - this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); - this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); - this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); - this.tableLayoutPanel5.Size = new System.Drawing.Size(186, 32); - this.tableLayoutPanel5.TabIndex = 9; - // - // ProxyPortTextBox - // - this.ProxyPortTextBox.Anchor = System.Windows.Forms.AnchorStyles.Left; - this.ProxyPortTextBox.Location = new System.Drawing.Point(67, 6); - this.ProxyPortTextBox.MaxLength = 10; - this.ProxyPortTextBox.Name = "ProxyPortTextBox"; - this.ProxyPortTextBox.Size = new System.Drawing.Size(113, 20); - this.ProxyPortTextBox.TabIndex = 4; - this.ProxyPortTextBox.WordWrap = false; - // - // ProxyPortLabel - // - this.ProxyPortLabel.Anchor = System.Windows.Forms.AnchorStyles.Right; - this.ProxyPortLabel.AutoSize = true; - this.ProxyPortLabel.Location = new System.Drawing.Point(6, 9); - this.ProxyPortLabel.Name = "ProxyPortLabel"; - this.ProxyPortLabel.Size = new System.Drawing.Size(55, 13); - this.ProxyPortLabel.TabIndex = 3; - this.ProxyPortLabel.Text = "Proxy Port"; - // - // tableLayoutPanel3 - // - this.tableLayoutPanel3.AutoSize = true; - this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.tableLayoutPanel3.ColumnCount = 2; - this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); - this.tableLayoutPanel3.Controls.Add(this.MyCancelButton, 1, 0); - this.tableLayoutPanel3.Controls.Add(this.OKButton, 0, 0); - this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Right; - this.tableLayoutPanel3.Location = new System.Drawing.Point(268, 209); - this.tableLayoutPanel3.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3); - this.tableLayoutPanel3.Name = "tableLayoutPanel3"; - this.tableLayoutPanel3.RowCount = 1; - this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel3.Size = new System.Drawing.Size(159, 26); - this.tableLayoutPanel3.TabIndex = 8; - // - // tableLayoutPanel4 - // - this.tableLayoutPanel4.AutoSize = true; - this.tableLayoutPanel4.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.tableLayoutPanel4.ColumnCount = 2; - this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.tableLayoutPanel4.Controls.Add(this.DeleteButton, 1, 0); - this.tableLayoutPanel4.Controls.Add(this.AddButton, 0, 0); - this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Top; - this.tableLayoutPanel4.Location = new System.Drawing.Point(0, 174); - this.tableLayoutPanel4.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel4.Name = "tableLayoutPanel4"; - this.tableLayoutPanel4.RowCount = 1; - this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel4.Size = new System.Drawing.Size(166, 32); - this.tableLayoutPanel4.TabIndex = 8; - // - // ConfigForm - // - this.AcceptButton = this.OKButton; - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoSize = true; - this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.CancelButton = this.MyCancelButton; - this.ClientSize = new System.Drawing.Size(574, 367); - this.Controls.Add(this.tableLayoutPanel2); - this.Controls.Add(this.panel2); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "ConfigForm"; - this.Padding = new System.Windows.Forms.Padding(12, 12, 12, 9); - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "Edit Servers"; - this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ConfigForm_FormClosed); - this.Load += new System.EventHandler(this.ConfigForm_Load); - this.Shown += new System.EventHandler(this.ConfigForm_Shown); - this.tableLayoutPanel1.ResumeLayout(false); - this.tableLayoutPanel1.PerformLayout(); - this.ServerGroupBox.ResumeLayout(false); - this.ServerGroupBox.PerformLayout(); - this.tableLayoutPanel2.ResumeLayout(false); - this.tableLayoutPanel2.PerformLayout(); - this.tableLayoutPanel5.ResumeLayout(false); - this.tableLayoutPanel5.PerformLayout(); - this.tableLayoutPanel3.ResumeLayout(false); - this.tableLayoutPanel4.ResumeLayout(false); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; - private System.Windows.Forms.Label IPLabel; - private System.Windows.Forms.Label ServerPortLabel; - private System.Windows.Forms.Label PasswordLabel; - private System.Windows.Forms.TextBox IPTextBox; - private System.Windows.Forms.TextBox ServerPortTextBox; - private System.Windows.Forms.TextBox PasswordTextBox; - private System.Windows.Forms.Label EncryptionLabel; - private System.Windows.Forms.ComboBox EncryptionSelect; - private System.Windows.Forms.Panel panel2; - private System.Windows.Forms.Button OKButton; - private System.Windows.Forms.Button MyCancelButton; - private System.Windows.Forms.Button DeleteButton; - private System.Windows.Forms.Button AddButton; - private System.Windows.Forms.GroupBox ServerGroupBox; - private System.Windows.Forms.ListBox ServersListBox; - private System.Windows.Forms.TextBox RemarksTextBox; - private System.Windows.Forms.Label RemarksLabel; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; - private System.Windows.Forms.TextBox ProxyPortTextBox; - private System.Windows.Forms.Label ProxyPortLabel; - } -} - diff --git a/shadowsocks-csharp/View/ConfigForm.cs b/shadowsocks-csharp/View/ConfigForm.cs deleted file mode 100755 index 574fafd5..00000000 --- a/shadowsocks-csharp/View/ConfigForm.cs +++ /dev/null @@ -1,227 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Diagnostics; -using Microsoft.Win32; -using Shadowsocks.Controller; -using Shadowsocks.Model; -using Shadowsocks.Properties; - -namespace Shadowsocks.View -{ - public partial class ConfigForm : Form - { - private ShadowsocksController controller; - - // this is a copy of configuration that we are working on - private Configuration _modifiedConfiguration; - private int _oldSelectedIndex = -1; - - public ConfigForm(ShadowsocksController controller) - { - this.Font = System.Drawing.SystemFonts.MessageBoxFont; - InitializeComponent(); - - // a dirty hack - this.ServersListBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.PerformLayout(); - - UpdateTexts(); - this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon()); - - this.controller = controller; - controller.ConfigChanged += controller_ConfigChanged; - - LoadCurrentConfiguration(); - } - - private void UpdateTexts() - { - AddButton.Text = I18N.GetString("&Add"); - DeleteButton.Text = I18N.GetString("&Delete"); - IPLabel.Text = I18N.GetString("Server IP"); - ServerPortLabel.Text = I18N.GetString("Server Port"); - PasswordLabel.Text = I18N.GetString("Password"); - EncryptionLabel.Text = I18N.GetString("Encryption"); - ProxyPortLabel.Text = I18N.GetString("Proxy Port"); - RemarksLabel.Text = I18N.GetString("Remarks"); - ServerGroupBox.Text = I18N.GetString("Server"); - OKButton.Text = I18N.GetString("OK"); - MyCancelButton.Text = I18N.GetString("Cancel"); - this.Text = I18N.GetString("Edit Servers"); - } - - private void controller_ConfigChanged(object sender, EventArgs e) - { - LoadCurrentConfiguration(); - } - - private void ShowWindow() - { - this.Opacity = 1; - this.Show(); - IPTextBox.Focus(); - } - - private bool SaveOldSelectedServer() - { - try - { - if (_oldSelectedIndex == -1 || _oldSelectedIndex >= _modifiedConfiguration.configs.Count) - { - return true; - } - Server server = new Server - { - server = IPTextBox.Text, - server_port = int.Parse(ServerPortTextBox.Text), - password = PasswordTextBox.Text, - method = EncryptionSelect.Text, - remarks = RemarksTextBox.Text - }; - int localPort = int.Parse(ProxyPortTextBox.Text); - Configuration.CheckServer(server); - Configuration.CheckPort(localPort); - _modifiedConfiguration.configs[_oldSelectedIndex] = server; - _modifiedConfiguration.localPort = localPort; - - return true; - } - catch (FormatException) - { - MessageBox.Show(I18N.GetString("Illegal port number format")); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message); - } - return false; - } - - private void LoadSelectedServer() - { - if (ServersListBox.SelectedIndex >= 0 && ServersListBox.SelectedIndex < _modifiedConfiguration.configs.Count) - { - Server server = _modifiedConfiguration.configs[ServersListBox.SelectedIndex]; - - IPTextBox.Text = server.server; - ServerPortTextBox.Text = server.server_port.ToString(); - PasswordTextBox.Text = server.password; - ProxyPortTextBox.Text = _modifiedConfiguration.localPort.ToString(); - EncryptionSelect.Text = server.method ?? "aes-256-cfb"; - RemarksTextBox.Text = server.remarks; - ServerGroupBox.Visible = true; - //IPTextBox.Focus(); - } - else - { - ServerGroupBox.Visible = false; - } - } - - private void LoadConfiguration(Configuration configuration) - { - ServersListBox.Items.Clear(); - foreach (Server server in _modifiedConfiguration.configs) - { - ServersListBox.Items.Add(server.FriendlyName()); - } - } - - private void LoadCurrentConfiguration() - { - _modifiedConfiguration = controller.GetConfiguration(); - LoadConfiguration(_modifiedConfiguration); - _oldSelectedIndex = _modifiedConfiguration.index; - ServersListBox.SelectedIndex = _modifiedConfiguration.index; - LoadSelectedServer(); - } - - private void ConfigForm_Load(object sender, EventArgs e) - { - - } - - private void ServersListBox_SelectedIndexChanged(object sender, EventArgs e) - { - if (_oldSelectedIndex == ServersListBox.SelectedIndex) - { - // we are moving back to oldSelectedIndex or doing a force move - return; - } - if (!SaveOldSelectedServer()) - { - // why this won't cause stack overflow? - ServersListBox.SelectedIndex = _oldSelectedIndex; - return; - } - LoadSelectedServer(); - _oldSelectedIndex = ServersListBox.SelectedIndex; - } - - private void AddButton_Click(object sender, EventArgs e) - { - if (!SaveOldSelectedServer()) - { - return; - } - Server server = Configuration.GetDefaultServer(); - _modifiedConfiguration.configs.Add(server); - LoadConfiguration(_modifiedConfiguration); - ServersListBox.SelectedIndex = _modifiedConfiguration.configs.Count - 1; - _oldSelectedIndex = ServersListBox.SelectedIndex; - } - - private void DeleteButton_Click(object sender, EventArgs e) - { - _oldSelectedIndex = ServersListBox.SelectedIndex; - if (_oldSelectedIndex >= 0 && _oldSelectedIndex < _modifiedConfiguration.configs.Count) - { - _modifiedConfiguration.configs.RemoveAt(_oldSelectedIndex); - } - if (_oldSelectedIndex >= _modifiedConfiguration.configs.Count) - { - // can be -1 - _oldSelectedIndex = _modifiedConfiguration.configs.Count - 1; - } - ServersListBox.SelectedIndex = _oldSelectedIndex; - LoadConfiguration(_modifiedConfiguration); - ServersListBox.SelectedIndex = _oldSelectedIndex; - LoadSelectedServer(); - } - - private void OKButton_Click(object sender, EventArgs e) - { - if (!SaveOldSelectedServer()) - { - return; - } - if (_modifiedConfiguration.configs.Count == 0) - { - MessageBox.Show(I18N.GetString("Please add at least one server")); - return; - } - controller.SaveServers(_modifiedConfiguration.configs, _modifiedConfiguration.localPort); - this.Close(); - } - - private void CancelButton_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void ConfigForm_Shown(object sender, EventArgs e) - { - IPTextBox.Focus(); - } - - private void ConfigForm_FormClosed(object sender, FormClosedEventArgs e) - { - controller.ConfigChanged -= controller_ConfigChanged; - } - - } -} diff --git a/shadowsocks-csharp/View/ConfigForm.resx b/shadowsocks-csharp/View/ConfigForm.resx deleted file mode 100755 index ff31a6db..00000000 --- a/shadowsocks-csharp/View/ConfigForm.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/shadowsocks-csharp/View/MenuViewController.cs b/shadowsocks-csharp/View/MenuViewController.cs deleted file mode 100755 index 9fe9fcd3..00000000 --- a/shadowsocks-csharp/View/MenuViewController.cs +++ /dev/null @@ -1,477 +0,0 @@ -using Shadowsocks.Controller; -using Shadowsocks.Model; -using Shadowsocks.Properties; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using ZXing; -using ZXing.Common; -using ZXing.QrCode; - -namespace Shadowsocks.View -{ - public class MenuViewController - { - // yes this is just a menu view controller - // when config form is closed, it moves away from RAM - // and it should just do anything related to the config form - - private ShadowsocksController controller; - private UpdateChecker updateChecker; - - private NotifyIcon _notifyIcon; - private ContextMenu contextMenu1; - - private bool _isFirstRun; - private MenuItem enableItem; - private MenuItem modeItem; - private MenuItem AutoStartupItem; - private MenuItem ShareOverLANItem; - private MenuItem SeperatorItem; - private MenuItem ConfigItem; - private MenuItem ServersItem; - private MenuItem globalModeItem; - private MenuItem PACModeItem; - private ConfigForm configForm; - private string _urlToOpen; - - public MenuViewController(ShadowsocksController controller) - { - this.controller = controller; - - LoadMenu(); - - controller.EnableStatusChanged += controller_EnableStatusChanged; - controller.ConfigChanged += controller_ConfigChanged; - controller.PACFileReadyToOpen += controller_PACFileReadyToOpen; - controller.ShareOverLANStatusChanged += controller_ShareOverLANStatusChanged; - controller.EnableGlobalChanged += controller_EnableGlobalChanged; - controller.Errored += controller_Errored; - controller.UpdatePACFromGFWListCompleted += controller_UpdatePACFromGFWListCompleted; - controller.UpdatePACFromGFWListError += controller_UpdatePACFromGFWListError; - - _notifyIcon = new NotifyIcon(); - UpdateTrayIcon(); - _notifyIcon.Visible = true; - _notifyIcon.ContextMenu = contextMenu1; - _notifyIcon.MouseDoubleClick += notifyIcon1_DoubleClick; - - this.updateChecker = new UpdateChecker(); - updateChecker.NewVersionFound += updateChecker_NewVersionFound; - - LoadCurrentConfiguration(); - - updateChecker.CheckUpdate(controller.GetConfiguration()); - - if (controller.GetConfiguration().isDefault) - { - _isFirstRun = true; - ShowConfigForm(); - } - } - - void controller_Errored(object sender, System.IO.ErrorEventArgs e) - { - MessageBox.Show(e.GetException().ToString(), String.Format(I18N.GetString("Shadowsocks Error: {0}"), e.GetException().Message)); - } - - private void UpdateTrayIcon() - { - int dpi; - Graphics graphics = Graphics.FromHwnd(IntPtr.Zero); - dpi = (int)graphics.DpiX; - graphics.Dispose(); - Bitmap icon = null; - if (dpi < 97) - { - // dpi = 96; - icon = Resources.ss16; - } - else if (dpi < 121) - { - // dpi = 120; - icon = Resources.ss20; - } - else - { - icon = Resources.ss24; - } - Configuration config = controller.GetConfiguration(); - bool enabled = config.enabled; - bool global = config.global; - if (!enabled) - { - Bitmap iconCopy = new Bitmap(icon); - for (int x = 0; x < iconCopy.Width; x++) - { - for (int y = 0; y < iconCopy.Height; y++) - { - Color color = icon.GetPixel(x, y); - iconCopy.SetPixel(x, y, Color.FromArgb((byte)(color.A / 1.25), color.R, color.G, color.B)); - } - } - icon = iconCopy; - } - _notifyIcon.Icon = Icon.FromHandle(icon.GetHicon()); - - // we want to show more details but notify icon title is limited to 63 characters - string text = I18N.GetString("Shadowsocks") + " " + UpdateChecker.Version + "\n" + - (enabled ? - I18N.GetString("System Proxy On: ") + (global ? I18N.GetString("Global") : I18N.GetString("PAC")) : - String.Format(I18N.GetString("Running: Port {0}"), config.localPort)) // this feedback is very important because they need to know Shadowsocks is running - + "\n" + config.GetCurrentServer().FriendlyName(); - _notifyIcon.Text = text.Substring(0, Math.Min(63, text.Length)); - } - - private MenuItem CreateMenuItem(string text, EventHandler click) - { - return new MenuItem(I18N.GetString(text), click); - } - - private MenuItem CreateMenuGroup(string text, MenuItem[] items) - { - return new MenuItem(I18N.GetString(text), items); - } - - private void LoadMenu() - { - this.contextMenu1 = new ContextMenu(new MenuItem[] { - this.enableItem = CreateMenuItem("Enable System Proxy", new EventHandler(this.EnableItem_Click)), - this.modeItem = CreateMenuGroup("Mode", new MenuItem[] { - this.PACModeItem = CreateMenuItem("PAC", new EventHandler(this.PACModeItem_Click)), - this.globalModeItem = CreateMenuItem("Global", new EventHandler(this.GlobalModeItem_Click)) - }), - this.ServersItem = CreateMenuGroup("Servers", new MenuItem[] { - this.SeperatorItem = new MenuItem("-"), - this.ConfigItem = CreateMenuItem("Edit Servers...", new EventHandler(this.Config_Click)), - CreateMenuItem("Show QRCode...", new EventHandler(this.QRCodeItem_Click)), - CreateMenuItem("Scan QRCode from Screen...", new EventHandler(this.ScanQRCodeItem_Click)) - }), - new MenuItem("-"), - this.AutoStartupItem = CreateMenuItem("Start on Boot", new EventHandler(this.AutoStartupItem_Click)), - this.ShareOverLANItem = CreateMenuItem("Allow Clients from LAN", new EventHandler(this.ShareOverLANItem_Click)), - CreateMenuItem("Edit PAC File...", new EventHandler(this.EditPACFileItem_Click)), - CreateMenuItem("Update PAC from GFWList", new EventHandler(this.UpdatePACFromGFWListItem_Click)), - new MenuItem("-"), - CreateMenuItem("Show Logs...", new EventHandler(this.ShowLogItem_Click)), - CreateMenuItem("About...", new EventHandler(this.AboutItem_Click)), - new MenuItem("-"), - CreateMenuItem("Quit", new EventHandler(this.Quit_Click)) - }); - } - - private void controller_ConfigChanged(object sender, EventArgs e) - { - LoadCurrentConfiguration(); - UpdateTrayIcon(); - } - - private void controller_EnableStatusChanged(object sender, EventArgs e) - { - enableItem.Checked = controller.GetConfiguration().enabled; - modeItem.Enabled = enableItem.Checked; - } - - void controller_ShareOverLANStatusChanged(object sender, EventArgs e) - { - ShareOverLANItem.Checked = controller.GetConfiguration().shareOverLan; - } - - void controller_EnableGlobalChanged(object sender, EventArgs e) - { - globalModeItem.Checked = controller.GetConfiguration().global; - PACModeItem.Checked = !globalModeItem.Checked; - } - - void controller_PACFileReadyToOpen(object sender, ShadowsocksController.PathEventArgs e) - { - string argument = @"/select, " + e.Path; - - System.Diagnostics.Process.Start("explorer.exe", argument); - } - - void ShowBalloonTip(string title, string content, ToolTipIcon icon, int timeout) - { - _notifyIcon.BalloonTipTitle = title; - _notifyIcon.BalloonTipText = content; - _notifyIcon.BalloonTipIcon = icon; - _notifyIcon.ShowBalloonTip(timeout); - } - - void controller_UpdatePACFromGFWListError(object sender, System.IO.ErrorEventArgs e) - { - ShowBalloonTip(I18N.GetString("Failed to update PAC file"), e.GetException().Message, ToolTipIcon.Error, 5000); - Logging.LogUsefulException(e.GetException()); - } - - void controller_UpdatePACFromGFWListCompleted(object sender, GFWListUpdater.ResultEventArgs e) - { - string result = e.Success ? I18N.GetString("PAC updated") : I18N.GetString("No updates found. Please report to GFWList if you have problems with it."); - ShowBalloonTip(I18N.GetString("Shadowsocks"), result, ToolTipIcon.Info, 1000); - } - - void updateChecker_NewVersionFound(object sender, EventArgs e) - { - ShowBalloonTip(String.Format(I18N.GetString("Shadowsocks {0} Update Found"), updateChecker.LatestVersionNumber), I18N.GetString("Click here to download"), ToolTipIcon.Info, 5000); - _notifyIcon.BalloonTipClicked += notifyIcon1_BalloonTipClicked; - _isFirstRun = false; - } - - void notifyIcon1_BalloonTipClicked(object sender, EventArgs e) - { - System.Diagnostics.Process.Start(updateChecker.LatestVersionURL); - _notifyIcon.BalloonTipClicked -= notifyIcon1_BalloonTipClicked; - } - - - private void LoadCurrentConfiguration() - { - Configuration config = controller.GetConfiguration(); - UpdateServersMenu(); - enableItem.Checked = config.enabled; - modeItem.Enabled = config.enabled; - globalModeItem.Checked = config.global; - PACModeItem.Checked = !config.global; - ShareOverLANItem.Checked = config.shareOverLan; - AutoStartupItem.Checked = AutoStartup.Check(); - } - - private void UpdateServersMenu() - { - var items = ServersItem.MenuItems; - while (items[0] != SeperatorItem) - { - items.RemoveAt(0); - } - - Configuration configuration = controller.GetConfiguration(); - for (int i = 0; i < configuration.configs.Count; i++) - { - Server server = configuration.configs[i]; - MenuItem item = new MenuItem(server.FriendlyName()); - item.Tag = i; - item.Click += AServerItem_Click; - items.Add(i, item); - } - - if (configuration.index >= 0 && configuration.index < configuration.configs.Count) - { - items[configuration.index].Checked = true; - } - } - - private void ShowConfigForm() - { - if (configForm != null) - { - configForm.Activate(); - } - else - { - configForm = new ConfigForm(controller); - configForm.Show(); - configForm.FormClosed += configForm_FormClosed; - } - } - - void configForm_FormClosed(object sender, FormClosedEventArgs e) - { - configForm = null; - Util.Utils.ReleaseMemory(); - ShowFirstTimeBalloon(); - } - - private void Config_Click(object sender, EventArgs e) - { - ShowConfigForm(); - } - - private void Quit_Click(object sender, EventArgs e) - { - controller.Stop(); - _notifyIcon.Visible = false; - Application.Exit(); - } - - private void ShowFirstTimeBalloon() - { - if (_isFirstRun) - { - _notifyIcon.BalloonTipTitle = I18N.GetString("Shadowsocks is here"); - _notifyIcon.BalloonTipText = I18N.GetString("You can turn on/off Shadowsocks in the context menu"); - _notifyIcon.BalloonTipIcon = ToolTipIcon.Info; - _notifyIcon.ShowBalloonTip(0); - _isFirstRun = false; - } - } - - private void AboutItem_Click(object sender, EventArgs e) - { - Process.Start("https://github.com/shadowsocks/shadowsocks-csharp"); - } - - private void notifyIcon1_DoubleClick(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) - { - ShowConfigForm(); - } - } - - private void EnableItem_Click(object sender, EventArgs e) - { - controller.ToggleEnable(!enableItem.Checked); - } - - private void GlobalModeItem_Click(object sender, EventArgs e) - { - controller.ToggleGlobal(true); - } - - private void PACModeItem_Click(object sender, EventArgs e) - { - controller.ToggleGlobal(false); - } - - private void ShareOverLANItem_Click(object sender, EventArgs e) - { - ShareOverLANItem.Checked = !ShareOverLANItem.Checked; - controller.ToggleShareOverLAN(ShareOverLANItem.Checked); - } - - private void EditPACFileItem_Click(object sender, EventArgs e) - { - controller.TouchPACFile(); - } - - private void UpdatePACFromGFWListItem_Click(object sender, EventArgs e) - { - controller.UpdatePACFromGFWList(); - } - - private void AServerItem_Click(object sender, EventArgs e) - { - MenuItem item = (MenuItem)sender; - controller.SelectServerIndex((int)item.Tag); - } - - private void ShowLogItem_Click(object sender, EventArgs e) - { - string argument = Logging.LogFile; - - System.Diagnostics.Process.Start("notepad.exe", argument); - } - - private void QRCodeItem_Click(object sender, EventArgs e) - { - QRCodeForm qrCodeForm = new QRCodeForm(controller.GetQRCodeForCurrentServer()); - //qrCodeForm.Icon = this.Icon; - // TODO - qrCodeForm.Show(); - } - - private void ScanQRCodeItem_Click(object sender, EventArgs e) - { - foreach (Screen screen in Screen.AllScreens) - { - using (Bitmap fullImage = new Bitmap(screen.Bounds.Width, - screen.Bounds.Height)) - { - using (Graphics g = Graphics.FromImage(fullImage)) - { - g.CopyFromScreen(screen.Bounds.X, - screen.Bounds.Y, - 0, 0, - fullImage.Size, - CopyPixelOperation.SourceCopy); - } - int maxTry = 10; - for (int i = 0; i < maxTry; i++) - { - int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry); - int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry); - Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2); - Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height); - - double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width; - using (Graphics g = Graphics.FromImage(target)) - { - g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height), - cropRect, - GraphicsUnit.Pixel); - } - var source = new BitmapLuminanceSource(target); - var bitmap = new BinaryBitmap(new HybridBinarizer(source)); - QRCodeReader reader = new QRCodeReader(); - var result = reader.decode(bitmap); - if (result != null) - { - var success = controller.AddServerBySSURL(result.Text); - QRCodeSplashForm splash = new QRCodeSplashForm(); - if (success) - { - splash.FormClosed += splash_FormClosed; - } - else if (result.Text.StartsWith("http://") || result.Text.StartsWith("https://")) - { - _urlToOpen = result.Text; - splash.FormClosed += openURLFromQRCode; - } - else - { - MessageBox.Show(I18N.GetString("Failed to decode QRCode")); - return; - } - double minX = Int32.MaxValue, minY = Int32.MaxValue, maxX = 0, maxY = 0; - foreach (ResultPoint point in result.ResultPoints) - { - minX = Math.Min(minX, point.X); - minY = Math.Min(minY, point.Y); - maxX = Math.Max(maxX, point.X); - maxY = Math.Max(maxY, point.Y); - } - minX /= imageScale; - minY /= imageScale; - maxX /= imageScale; - maxY /= imageScale; - // make it 20% larger - double margin = (maxX - minX) * 0.20f; - minX += -margin + marginLeft; - maxX += margin + marginLeft; - minY += -margin + marginTop; - maxY += margin + marginTop; - splash.Location = new Point(screen.Bounds.X, screen.Bounds.Y); - // we need a panel because a window has a minimal size - // TODO: test on high DPI - splash.TargetRect = new Rectangle((int)minX + screen.Bounds.X, (int)minY + screen.Bounds.Y, (int)maxX - (int)minX, (int)maxY - (int)minY); - splash.Size = new Size(fullImage.Width, fullImage.Height); - splash.Show(); - return; - } - } - } - } - MessageBox.Show(I18N.GetString("No QRCode found. Try to zoom in or move it to the center of the screen.")); - } - - void splash_FormClosed(object sender, FormClosedEventArgs e) - { - ShowConfigForm(); - } - - void openURLFromQRCode(object sender, FormClosedEventArgs e) - { - Process.Start(_urlToOpen); - } - - private void AutoStartupItem_Click(object sender, EventArgs e) { - AutoStartupItem.Checked = !AutoStartupItem.Checked; - if (!AutoStartup.Set(AutoStartupItem.Checked)) { - MessageBox.Show(I18N.GetString("Failed to update registry")); - } - } - } -} diff --git a/shadowsocks-csharp/View/QRCodeForm.Designer.cs b/shadowsocks-csharp/View/QRCodeForm.Designer.cs deleted file mode 100755 index ca0a0006..00000000 --- a/shadowsocks-csharp/View/QRCodeForm.Designer.cs +++ /dev/null @@ -1,71 +0,0 @@ -namespace Shadowsocks.View -{ - partial class QRCodeForm - { - /// - /// 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.pictureBox1 = new System.Windows.Forms.PictureBox(); - ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); - this.SuspendLayout(); - // - // pictureBox1 - // - this.pictureBox1.Location = new System.Drawing.Point(10, 10); - this.pictureBox1.Margin = new System.Windows.Forms.Padding(0); - this.pictureBox1.Name = "pictureBox1"; - this.pictureBox1.Size = new System.Drawing.Size(210, 210); - this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; - this.pictureBox1.TabIndex = 1; - this.pictureBox1.TabStop = false; - // - // QRCodeForm - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoSize = true; - this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.BackColor = System.Drawing.Color.White; - this.ClientSize = new System.Drawing.Size(338, 274); - this.Controls.Add(this.pictureBox1); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "QRCodeForm"; - this.Padding = new System.Windows.Forms.Padding(10); - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "QRCode"; - this.Load += new System.EventHandler(this.QRCodeForm_Load); - ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.PictureBox pictureBox1; - } -} \ No newline at end of file diff --git a/shadowsocks-csharp/View/QRCodeForm.cs b/shadowsocks-csharp/View/QRCodeForm.cs deleted file mode 100755 index 2741d4ff..00000000 --- a/shadowsocks-csharp/View/QRCodeForm.cs +++ /dev/null @@ -1,60 +0,0 @@ -using ZXing.QrCode.Internal; -using Shadowsocks.Controller; -using Shadowsocks.Properties; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.IO; -using System.IO.Compression; -using System.Text; -using System.Windows.Forms; - -namespace Shadowsocks.View -{ - public partial class QRCodeForm : Form - { - private string code; - - public QRCodeForm(string code) - { - this.code = code; - InitializeComponent(); - this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon()); - this.Text = I18N.GetString("QRCode"); - } - - private void GenQR(string ssconfig) - { - string qrText = ssconfig; - QRCode code = ZXing.QrCode.Internal.Encoder.encode(qrText, ErrorCorrectionLevel.M); - ByteMatrix m = code.Matrix; - int blockSize = Math.Max(pictureBox1.Height / m.Height, 1); - Bitmap drawArea = new Bitmap((m.Width * blockSize), (m.Height * blockSize)); - using (Graphics g = Graphics.FromImage(drawArea)) - { - g.Clear(Color.White); - using (Brush b = new SolidBrush(Color.Black)) - { - for (int row = 0; row < m.Width; row++) - { - for (int col = 0; col < m.Height; col++) - { - if (m[row, col] != 0) - { - g.FillRectangle(b, blockSize * row, blockSize * col, blockSize, blockSize); - } - } - } - } - } - pictureBox1.Image = drawArea; - } - - private void QRCodeForm_Load(object sender, EventArgs e) - { - GenQR(code); - } - } -} diff --git a/shadowsocks-csharp/View/QRCodeForm.resx b/shadowsocks-csharp/View/QRCodeForm.resx deleted file mode 100755 index 5ea0895e..00000000 --- a/shadowsocks-csharp/View/QRCodeForm.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/shadowsocks-csharp/View/QRCodeSplashForm.cs b/shadowsocks-csharp/View/QRCodeSplashForm.cs deleted file mode 100755 index ac9828e4..00000000 --- a/shadowsocks-csharp/View/QRCodeSplashForm.cs +++ /dev/null @@ -1,302 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Drawing.Imaging; -using System.Runtime.InteropServices; -using System.Diagnostics; - - -namespace Shadowsocks.View -{ - public class QRCodeSplashForm : PerPixelAlphaForm - { - public Rectangle TargetRect; - - public QRCodeSplashForm() - { - this.Load += QRCodeSplashForm_Load; - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; - this.BackColor = System.Drawing.Color.White; - this.ClientSize = new System.Drawing.Size(1, 1); - this.ControlBox = false; - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "QRCodeSplashForm"; - this.ShowIcon = false; - this.ShowInTaskbar = false; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; - this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; - this.TopMost = true; - } - - private Timer timer; - private int flashStep; - private static double FPS = 1.0 / 15 * 1000; // System.Windows.Forms.Timer resolution is 15ms - private static double ANIMATION_TIME = 0.5; - private static int ANIMATION_STEPS = (int)(ANIMATION_TIME * FPS); - Stopwatch sw; - int x; - int y; - int w; - int h; - Bitmap bitmap; - Graphics g; - Pen pen; - SolidBrush brush; - - private void QRCodeSplashForm_Load(object sender, EventArgs e) - { - SetStyle(ControlStyles.SupportsTransparentBackColor, true); - this.BackColor = Color.Transparent; - flashStep = 0; - x = 0; - y = 0; - w = Width; - h = Height; - sw = Stopwatch.StartNew(); - timer = new Timer(); - timer.Interval = (int)(ANIMATION_TIME * 1000 / ANIMATION_STEPS); - timer.Tick += timer_Tick; - timer.Start(); - bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); - g = Graphics.FromImage(bitmap); - pen = new Pen(Color.Red, 3); - brush = new SolidBrush(Color.FromArgb(30, Color.Red)); - } - - protected override CreateParams CreateParams - { - get - { - CreateParams cp = base.CreateParams; - cp.ExStyle |= 0x00080000; // This form has to have the WS_EX_LAYERED extended style - return cp; - } - } - - void timer_Tick(object sender, EventArgs e) - { - double percent = (double)sw.ElapsedMilliseconds / 1000.0 / (double)ANIMATION_TIME; - if (percent < 1) - { - // ease out - percent = 1 - Math.Pow((1 - percent), 4); - x = (int)(TargetRect.X * percent); - y = (int)(TargetRect.Y * percent); - w = (int)(TargetRect.Width * percent + this.Size.Width * (1 - percent)); - h = (int)(TargetRect.Height * percent + this.Size.Height * (1 - percent)); - //codeRectView.Location = new Point(x, y); - //codeRectView.Size = new Size(w, h); - pen.Color = Color.FromArgb((int)(255 * percent), Color.Red); - brush.Color = Color.FromArgb((int)(30 * percent), Color.Red); - g.Clear(Color.Transparent); - g.FillRectangle(brush, x, y, w, h); - g.DrawRectangle(pen, x, y, w, h); - SetBitmap(bitmap); - } - else - { - if (flashStep == 0) - { - timer.Interval = 100; - g.Clear(Color.Transparent); - SetBitmap(bitmap); - } - else if (flashStep == 1) - { - timer.Interval = 50; - g.FillRectangle(brush, x, y, w, h); - g.DrawRectangle(pen, x, y, w, h); - SetBitmap(bitmap); - } - else if (flashStep == 1) - { - g.Clear(Color.Transparent); - SetBitmap(bitmap); - } - else if (flashStep == 2) - { - g.FillRectangle(brush, x, y, w, h); - g.DrawRectangle(pen, x, y, w, h); - SetBitmap(bitmap); - } - else if (flashStep == 3) - { - g.Clear(Color.Transparent); - SetBitmap(bitmap); - } - else if (flashStep == 4) - { - g.FillRectangle(brush, x, y, w, h); - g.DrawRectangle(pen, x, y, w, h); - SetBitmap(bitmap); - } - else - { - sw.Stop(); - timer.Stop(); - pen.Dispose(); - brush.Dispose(); - bitmap.Dispose(); - this.Close(); - } - flashStep++; - } - } - } - - - // class that exposes needed win32 gdi functions. - class Win32 - { - - [StructLayout(LayoutKind.Sequential)] - public struct Point - { - public Int32 x; - public Int32 y; - - public Point(Int32 x, Int32 y) { this.x = x; this.y = y; } - } - - - [StructLayout(LayoutKind.Sequential)] - public struct Size - { - public Int32 cx; - public Int32 cy; - - public Size(Int32 cx, Int32 cy) { this.cx = cx; this.cy = cy; } - } - - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - struct ARGB - { - public byte Blue; - public byte Green; - public byte Red; - public byte Alpha; - } - - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct BLENDFUNCTION - { - public byte BlendOp; - public byte BlendFlags; - public byte SourceConstantAlpha; - public byte AlphaFormat; - } - - - public const Int32 ULW_COLORKEY = 0x00000001; - public const Int32 ULW_ALPHA = 0x00000002; - public const Int32 ULW_OPAQUE = 0x00000004; - - public const byte AC_SRC_OVER = 0x00; - public const byte AC_SRC_ALPHA = 0x01; - - - [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)] - public static extern int UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pprSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags); - - [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)] - public static extern IntPtr GetDC(IntPtr hWnd); - - [DllImport("user32.dll", ExactSpelling = true)] - public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); - - [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] - public static extern IntPtr CreateCompatibleDC(IntPtr hDC); - - [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] - public static extern int DeleteDC(IntPtr hdc); - - [DllImport("gdi32.dll", ExactSpelling = true)] - public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); - - [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)] - public static extern int DeleteObject(IntPtr hObject); - } - - - public class PerPixelAlphaForm : Form - { - // http://www.codeproject.com/Articles/1822/Per-Pixel-Alpha-Blend-in-C - // Rui Lopes - - public PerPixelAlphaForm() - { - // This form should not have a border or else Windows will clip it. - FormBorderStyle = FormBorderStyle.None; - } - - public void SetBitmap(Bitmap bitmap) - { - SetBitmap(bitmap, 255); - } - - - /// Changes the current bitmap with a custom opacity level. Here is where all happens! - public void SetBitmap(Bitmap bitmap, byte opacity) - { - if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) - throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); - - // The idea of this is very simple, - // 1. Create a compatible DC with screen; - // 2. Select the bitmap with 32bpp with alpha-channel in the compatible DC; - // 3. Call the UpdateLayeredWindow. - - IntPtr screenDc = Win32.GetDC(IntPtr.Zero); - IntPtr memDc = Win32.CreateCompatibleDC(screenDc); - IntPtr hBitmap = IntPtr.Zero; - IntPtr oldBitmap = IntPtr.Zero; - - try - { - hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); // grab a GDI handle from this GDI+ bitmap - oldBitmap = Win32.SelectObject(memDc, hBitmap); - - Win32.Size size = new Win32.Size(bitmap.Width, bitmap.Height); - Win32.Point pointSource = new Win32.Point(0, 0); - Win32.Point topPos = new Win32.Point(Left, Top); - Win32.BLENDFUNCTION blend = new Win32.BLENDFUNCTION(); - blend.BlendOp = Win32.AC_SRC_OVER; - blend.BlendFlags = 0; - blend.SourceConstantAlpha = opacity; - blend.AlphaFormat = Win32.AC_SRC_ALPHA; - - Win32.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, Win32.ULW_ALPHA); - } - finally - { - Win32.ReleaseDC(IntPtr.Zero, screenDc); - if (hBitmap != IntPtr.Zero) - { - Win32.SelectObject(memDc, oldBitmap); - //Windows.DeleteObject(hBitmap); // The documentation says that we have to use the Windows.DeleteObject... but since there is no such method I use the normal DeleteObject from Win32 GDI and it's working fine without any resource leak. - Win32.DeleteObject(hBitmap); - } - Win32.DeleteDC(memDc); - } - } - - - protected override CreateParams CreateParams - { - get - { - CreateParams cp = base.CreateParams; - cp.ExStyle |= 0x00080000; // This form has to have the WS_EX_LAYERED extended style - return cp; - } - } - } -} diff --git a/shadowsocks-csharp/app.config b/shadowsocks-csharp/app.config deleted file mode 100755 index 867ff468..00000000 --- a/shadowsocks-csharp/app.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/shadowsocks-csharp/app.manifest b/shadowsocks-csharp/app.manifest deleted file mode 100755 index 2f6c64aa..00000000 --- a/shadowsocks-csharp/app.manifest +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - true - - - \ No newline at end of file diff --git a/shadowsocks-csharp/shadowsocks-csharp.csproj b/shadowsocks-csharp/shadowsocks-csharp.csproj deleted file mode 100755 index 3d51fabb..00000000 --- a/shadowsocks-csharp/shadowsocks-csharp.csproj +++ /dev/null @@ -1,244 +0,0 @@ - - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {8C02D2F7-7CDB-4D55-9F25-CD03EF4AA062} - WinExe - Properties - Shadowsocks - Shadowsocks - v2.0 - 512 - - - shadowsocks.ico - false - - - - - 3.5 - - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 1 - 1.0.0.%2a - false - true - - - true - bin\x86\Debug\ - TRACE;DEBUG - full - x86 - prompt - ManagedMinimumRules.ruleset - false - - - bin\x86\Release\ - TRACE - true - pdbonly - x86 - prompt - ManagedMinimumRules.ruleset - false - true - - - app.manifest - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - Resources.resx - - - - Form - - - ConfigForm.cs - - - - - - - - - - Form - - - QRCodeForm.cs - - - Form - - - ConfigForm.cs - Designer - - - ResXFileCodeGenerator - Designer - Resources.Designer.cs - - - QRCodeForm.cs - - - - Designer - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 2.0 %28x86%29 - false - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - true - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - \ No newline at end of file diff --git a/shadowsocks-csharp/shadowsocks.ico b/shadowsocks-csharp/shadowsocks.ico deleted file mode 100755 index 26ec8059..00000000 Binary files a/shadowsocks-csharp/shadowsocks.ico and /dev/null differ diff --git a/test/Properties/AssemblyInfo.cs b/test/Properties/AssemblyInfo.cs deleted file mode 100755 index 26e77a34..00000000 --- a/test/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -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 -// associated with an assembly. -[assembly: AssemblyTitle("test")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("test")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("f74e87ac-7e3a-444b-a1d9-8b91a674c60f")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/test/UnitTest.cs b/test/UnitTest.cs deleted file mode 100755 index 8fdf3f28..00000000 --- a/test/UnitTest.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Shadowsocks.Controller; -using Shadowsocks.Encryption; -using System.Threading; -using System.Collections.Generic; - -namespace test -{ - [TestClass] - public class UnitTest - { - [TestMethod] - public void TestCompareVersion() - { - Assert.IsTrue(UpdateChecker.CompareVersion("2.3.1.0", "2.3.1") == 0); - Assert.IsTrue(UpdateChecker.CompareVersion("1.2", "1.3") < 0); - Assert.IsTrue(UpdateChecker.CompareVersion("1.3", "1.2") > 0); - Assert.IsTrue(UpdateChecker.CompareVersion("1.3", "1.3") == 0); - Assert.IsTrue(UpdateChecker.CompareVersion("1.2.1", "1.2") > 0); - Assert.IsTrue(UpdateChecker.CompareVersion("2.3.1", "2.4") < 0); - Assert.IsTrue(UpdateChecker.CompareVersion("1.3.2", "1.3.1") > 0); - } - - private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor) - { - byte[] plain = new byte[16384]; - byte[] cipher = new byte[plain.Length + 16]; - byte[] plain2 = new byte[plain.Length + 16]; - int outLen = 0; - int outLen2 = 0; - var random = new Random(); - random.NextBytes(plain); - encryptor.Encrypt(plain, plain.Length, cipher, out outLen); - decryptor.Decrypt(cipher, outLen, plain2, out outLen2); - Assert.AreEqual(plain.Length, outLen2); - for (int j = 0; j < plain.Length; j++) - { - Assert.AreEqual(plain[j], plain2[j]); - } - encryptor.Encrypt(plain, 1000, cipher, out outLen); - decryptor.Decrypt(cipher, outLen, plain2, out outLen2); - Assert.AreEqual(1000, outLen2); - for (int j = 0; j < outLen2; j++) - { - Assert.AreEqual(plain[j], plain2[j]); - } - encryptor.Encrypt(plain, 12333, cipher, out outLen); - decryptor.Decrypt(cipher, outLen, plain2, out outLen2); - Assert.AreEqual(12333, outLen2); - for (int j = 0; j < outLen2; j++) - { - Assert.AreEqual(plain[j], plain2[j]); - } - } - - private static bool encryptionFailed = false; - private static object locker = new object(); - - [TestMethod] - public void TestPolarSSLEncryption() - { - // run it once before the multi-threading test to initialize global tables - RunSinglePolarSSLEncryptionThread(); - List threads = new List(); - for (int i = 0; i < 10; i++) - { - Thread t = new Thread(new ThreadStart(RunSinglePolarSSLEncryptionThread)); - threads.Add(t); - t.Start(); - } - foreach (Thread t in threads) - { - t.Join(); - } - Assert.IsFalse(encryptionFailed); - } - - private void RunSinglePolarSSLEncryptionThread() - { - try - { - for (int i = 0; i < 100; i++) - { - IEncryptor encryptor; - IEncryptor decryptor; - encryptor = new PolarSSLEncryptor("aes-256-cfb", "barfoo!"); - decryptor = new PolarSSLEncryptor("aes-256-cfb", "barfoo!"); - RunEncryptionRound(encryptor, decryptor); - } - } - catch - { - encryptionFailed = true; - throw; - } - } - - [TestMethod] - public void TestRC4Encryption() - { - // run it once before the multi-threading test to initialize global tables - RunSingleRC4EncryptionThread(); - List threads = new List(); - for (int i = 0; i < 10; i++) - { - Thread t = new Thread(new ThreadStart(RunSingleRC4EncryptionThread)); - threads.Add(t); - t.Start(); - } - foreach (Thread t in threads) - { - t.Join(); - } - Assert.IsFalse(encryptionFailed); - } - - private void RunSingleRC4EncryptionThread() - { - try - { - for (int i = 0; i < 100; i++) - { - var random = new Random(); - IEncryptor encryptor; - IEncryptor decryptor; - encryptor = new PolarSSLEncryptor("rc4-md5", "barfoo!"); - decryptor = new PolarSSLEncryptor("rc4-md5", "barfoo!"); - RunEncryptionRound(encryptor, decryptor); - } - } - catch - { - encryptionFailed = true; - throw; - } - } - - [TestMethod] - public void TestSodiumEncryption() - { - // run it once before the multi-threading test to initialize global tables - RunSingleSodiumEncryptionThread(); - List threads = new List(); - for (int i = 0; i < 10; i++) - { - Thread t = new Thread(new ThreadStart(RunSingleSodiumEncryptionThread)); - threads.Add(t); - t.Start(); - } - foreach (Thread t in threads) - { - t.Join(); - } - Assert.IsFalse(encryptionFailed); - } - - private void RunSingleSodiumEncryptionThread() - { - try - { - for (int i = 0; i < 100; i++) - { - var random = new Random(); - IEncryptor encryptor; - IEncryptor decryptor; - encryptor = new SodiumEncryptor("salsa20", "barfoo!"); - decryptor = new SodiumEncryptor("salsa20", "barfoo!"); - RunEncryptionRound(encryptor, decryptor); - } - } - catch - { - encryptionFailed = true; - throw; - } - } - } -} diff --git a/test/test.csproj b/test/test.csproj deleted file mode 100755 index d7420145..00000000 --- a/test/test.csproj +++ /dev/null @@ -1,84 +0,0 @@ - - - - Debug - AnyCPU - {45913187-0685-4903-B250-DCEF0479CD86} - Library - Properties - test - test - v4.5 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages - False - UnitTest - - - - bin\x86\Debug\ - x86 - - - bin\x86\Release\ - x86 - - - - - - - - - - - - - - - - - - - - - - - - - - {8c02d2f7-7cdb-4d55-9f25-cd03ef4aa062} - shadowsocks-csharp - - - - - - - False - - - False - - - False - - - False - - - - - - - - \ No newline at end of file