Compare commits

...

2 Commits
main ... rm

Author SHA1 Message Date
  clowwindy c688584d48 rm 9 years ago
  clowwindy 31f98d01b7 rm 9 years ago
100 changed files with 1 additions and 17132 deletions
Split View
  1. +0
    -7
      .gitignore
  2. +0
    -89
      CHANGES
  3. +0
    -28
      CONTRIBUTING.md
  4. +0
    -118
      LICENSE.txt
  5. +1
    -45
      README.md
  6. +0
    -6
      packaging/upload.sh
  7. +0
    -30
      shadowsocks-csharp.sln
  8. +0
    -1883
      shadowsocks-csharp/3rd/SimpleJson.cs
  9. +0
    -89
      shadowsocks-csharp/3rd/zxing/BarcodeFormat.cs
  10. +0
    -206
      shadowsocks-csharp/3rd/zxing/BaseLuminanceSource.cs
  11. +0
    -104
      shadowsocks-csharp/3rd/zxing/Binarizer.cs
  12. +0
    -186
      shadowsocks-csharp/3rd/zxing/BinaryBitmap.cs
  13. +0
    -242
      shadowsocks-csharp/3rd/zxing/BitmapLuminanceSource.cs
  14. +0
    -125
      shadowsocks-csharp/3rd/zxing/DecodeHintType.cs
  15. +0
    -131
      shadowsocks-csharp/3rd/zxing/EncodeHintType.cs
  16. +0
    -198
      shadowsocks-csharp/3rd/zxing/LuminanceSource.cs
  17. +0
    -161
      shadowsocks-csharp/3rd/zxing/Result.cs
  18. +0
    -102
      shadowsocks-csharp/3rd/zxing/ResultMetadataType.cs
  19. +0
    -191
      shadowsocks-csharp/3rd/zxing/ResultPoint.cs
  20. +0
    -26
      shadowsocks-csharp/3rd/zxing/ResultPointCallback.cs
  21. +0
    -55
      shadowsocks-csharp/3rd/zxing/WriterException.cs
  22. +0
    -278
      shadowsocks-csharp/3rd/zxing/common/BitArray.cs
  23. +0
    -259
      shadowsocks-csharp/3rd/zxing/common/BitMatrix.cs
  24. +0
    -124
      shadowsocks-csharp/3rd/zxing/common/BitSource.cs
  25. +0
    -76
      shadowsocks-csharp/3rd/zxing/common/DecoderResult.cs
  26. +0
    -82
      shadowsocks-csharp/3rd/zxing/common/DefaultGridSampler.cs
  27. +0
    -39
      shadowsocks-csharp/3rd/zxing/common/DetectorResult.cs
  28. +0
    -243
      shadowsocks-csharp/3rd/zxing/common/GlobalHistogramBinarizer.cs
  29. +0
    -192
      shadowsocks-csharp/3rd/zxing/common/GridSampler.cs
  30. +0
    -288
      shadowsocks-csharp/3rd/zxing/common/HybridBinarizer.cs
  31. +0
    -159
      shadowsocks-csharp/3rd/zxing/common/PerspectiveTransform.cs
  32. +0
    -266
      shadowsocks-csharp/3rd/zxing/common/StringUtils.cs
  33. +0
    -48
      shadowsocks-csharp/3rd/zxing/common/detector/MathUtils.cs
  34. +0
    -242
      shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGF.cs
  35. +0
    -331
      shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs
  36. +0
    -227
      shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonDecoder.cs
  37. +0
    -84
      shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonEncoder.cs
  38. +0
    -255
      shadowsocks-csharp/3rd/zxing/qrcode/QRCodeReader.cs
  39. +0
    -281
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/BitMatrixParser.cs
  40. +0
    -146
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataBlock.cs
  41. +0
    -165
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataMask.cs
  42. +0
    -514
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/DecodedBitStreamParser.cs
  43. +0
    -195
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/Decoder.cs
  44. +0
    -109
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/ErrorCorrectionLevel.cs
  45. +0
    -197
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/FormatInformation.cs
  46. +0
    -179
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/Mode.cs
  47. +0
    -60
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/QRCodeDecoderMetaData.cs
  48. +0
    -424
      shadowsocks-csharp/3rd/zxing/qrcode/decoder/Version.cs
  49. +0
    -68
      shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPattern.cs
  50. +0
    -324
      shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPatternFinder.cs
  51. +0
    -429
      shadowsocks-csharp/3rd/zxing/qrcode/detector/Detector.cs
  52. +0
    -107
      shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPattern.cs
  53. +0
    -808
      shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternFinder.cs
  54. +0
    -74
      shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternInfo.cs
  55. +0
    -40
      shadowsocks-csharp/3rd/zxing/qrcode/encoder/BlockPair.cs
  56. +0
    -148
      shadowsocks-csharp/3rd/zxing/qrcode/encoder/ByteMatrix.cs
  57. +0
    -596
      shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs
  58. +0
    -271
      shadowsocks-csharp/3rd/zxing/qrcode/encoder/MaskUtil.cs
  59. +0
    -600
      shadowsocks-csharp/3rd/zxing/qrcode/encoder/MatrixUtil.cs
  60. +0
    -125
      shadowsocks-csharp/3rd/zxing/qrcode/encoder/QRCode.cs
  61. +0
    -55
      shadowsocks-csharp/Controller/AutoStartup.cs
  62. +0
    -55
      shadowsocks-csharp/Controller/FileManager.cs
  63. +0
    -100
      shadowsocks-csharp/Controller/GfwListUpdater.cs
  64. +0
    -42
      shadowsocks-csharp/Controller/I18N.cs
  65. +0
    -163
      shadowsocks-csharp/Controller/Listener.cs
  66. +0
    -399
      shadowsocks-csharp/Controller/Local.cs
  67. +0
    -89
      shadowsocks-csharp/Controller/Logging.cs
  68. +0
    -194
      shadowsocks-csharp/Controller/PACServer.cs
  69. +0
    -126
      shadowsocks-csharp/Controller/PolipoRunner.cs
  70. +0
    -264
      shadowsocks-csharp/Controller/PortForwarder.cs
  71. +0
    -313
      shadowsocks-csharp/Controller/ShadowsocksController.cs
  72. +0
    -105
      shadowsocks-csharp/Controller/SystemProxy.cs
  73. +0
    -159
      shadowsocks-csharp/Controller/UpdateChecker.cs
  74. BIN
      shadowsocks-csharp/Data/abp.js.gz
  75. +0
    -51
      shadowsocks-csharp/Data/cn.txt
  76. BIN
      shadowsocks-csharp/Data/libsscrypto.dll.gz
  77. BIN
      shadowsocks-csharp/Data/polipo.exe.gz
  78. +0
    -10
      shadowsocks-csharp/Data/polipo_config.txt
  79. BIN
      shadowsocks-csharp/Data/proxy.pac.txt.gz
  80. +0
    -33
      shadowsocks-csharp/Encryption/EncryptorBase.cs
  81. +0
    -43
      shadowsocks-csharp/Encryption/EncryptorFactory.cs
  82. +0
    -12
      shadowsocks-csharp/Encryption/IEncryptor.cs
  83. +0
    -158
      shadowsocks-csharp/Encryption/IVEncryptor.cs
  84. +0
    -68
      shadowsocks-csharp/Encryption/PolarSSL.cs
  85. +0
    -185
      shadowsocks-csharp/Encryption/PolarSSLEncryptor.cs
  86. +0
    -43
      shadowsocks-csharp/Encryption/Sodium.cs
  87. +0
    -99
      shadowsocks-csharp/Encryption/SodiumEncryptor.cs
  88. +0
    -108
      shadowsocks-csharp/Encryption/TableEncryptor.cs
  89. +0
    -150
      shadowsocks-csharp/Model/Configuration.cs
  90. +0
    -87
      shadowsocks-csharp/Model/Server.cs
  91. +0
    -51
      shadowsocks-csharp/Program.cs
  92. +0
    -37
      shadowsocks-csharp/Properties/AssemblyInfo.cs
  93. +0
    -199
      shadowsocks-csharp/Properties/Resources.Designer.cs
  94. +0
    -151
      shadowsocks-csharp/Properties/Resources.resx
  95. BIN
      shadowsocks-csharp/Resources/ss16.png
  96. BIN
      shadowsocks-csharp/Resources/ss20.png
  97. BIN
      shadowsocks-csharp/Resources/ss24.png
  98. BIN
      shadowsocks-csharp/Resources/ssw128.png
  99. +0
    -50
      shadowsocks-csharp/Util/Util.cs
  100. +0
    -458
      shadowsocks-csharp/View/ConfigForm.Designer.cs

+ 0
- 7
.gitignore View File

@@ -1,7 +0,0 @@
Backup/
bin/
obj/
shadowsocks-csharp/shadowsocks-csharp.csproj.user
TestResults
*.suo


+ 0
- 89
CHANGES View File

@@ -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

+ 0
- 28
CONTRIBUTING.md View File

@@ -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

+ 0
- 118
LICENSE.txt View File

@@ -1,118 +0,0 @@
shadowsocks-csharp
==================
Copyright (C) 2015 clowwindy <clowwindy42@gmail.com>
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 <http://www.gnu.org/licenses/>.
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 <j at pureftpd dot org>
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.

+ 1
- 45
README.md View File

@@ -1,45 +1 @@
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/
Removed according to regulations.

+ 0
- 6
packaging/upload.sh View File

@@ -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/

+ 0
- 30
shadowsocks-csharp.sln View File

@@ -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

+ 0
- 1883
shadowsocks-csharp/3rd/SimpleJson.cs
File diff suppressed because it is too large
View File


+ 0
- 89
shadowsocks-csharp/3rd/zxing/BarcodeFormat.cs View File

@@ -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
{
/// <summary>
/// Enumerates barcode formats known to this package.
/// </summary>
/// <author>Sean Owen</author>
[System.Flags]
public enum BarcodeFormat
{
/// <summary>Aztec 2D barcode format.</summary>
AZTEC = 1,
/// <summary>CODABAR 1D format.</summary>
CODABAR = 2,
/// <summary>Code 39 1D format.</summary>
CODE_39 = 4,
/// <summary>Code 93 1D format.</summary>
CODE_93 = 8,
/// <summary>Code 128 1D format.</summary>
CODE_128 = 16,
/// <summary>Data Matrix 2D barcode format.</summary>
DATA_MATRIX = 32,
/// <summary>EAN-8 1D format.</summary>
EAN_8 = 64,
/// <summary>EAN-13 1D format.</summary>
EAN_13 = 128,
/// <summary>ITF (Interleaved Two of Five) 1D format.</summary>
ITF = 256,
/// <summary>MaxiCode 2D barcode format.</summary>
MAXICODE = 512,
/// <summary>PDF417 format.</summary>
PDF_417 = 1024,
/// <summary>QR Code 2D barcode format.</summary>
QR_CODE = 2048,
/// <summary>RSS 14</summary>
RSS_14 = 4096,
/// <summary>RSS EXPANDED</summary>
RSS_EXPANDED = 8192,
/// <summary>UPC-A 1D format.</summary>
UPC_A = 16384,
/// <summary>UPC-E 1D format.</summary>
UPC_E = 32768,
/// <summary>UPC/EAN extension format. Not a stand-alone format.</summary>
UPC_EAN_EXTENSION = 65536,
/// <summary>MSI</summary>
MSI = 131072,
/// <summary>Plessey</summary>
PLESSEY = 262144,
/// <summary>
/// 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)
/// </summary>
All_1D = UPC_A | UPC_E | EAN_13 | EAN_8 | CODABAR | CODE_39 | CODE_93 | CODE_128 | ITF | RSS_14 | RSS_EXPANDED
}
}

+ 0
- 206
shadowsocks-csharp/3rd/zxing/BaseLuminanceSource.cs View File

@@ -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
{
/// <summary>
/// The base class for luminance sources which supports
/// cropping and rotating based upon the luminance values.
/// </summary>
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;
/// <summary>
///
/// </summary>
protected byte[] luminances;
/// <summary>
/// Initializes a new instance of the <see cref="BaseLuminanceSource"/> class.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
protected BaseLuminanceSource(int width, int height)
: base(width, height)
{
luminances = new byte[width * height];
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseLuminanceSource"/> class.
/// </summary>
/// <param name="luminanceArray">The luminance array.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
protected BaseLuminanceSource(byte[] luminanceArray, int width, int height)
: base(width, height)
{
luminances = new byte[width * height];
Buffer.BlockCopy(luminanceArray, 0, luminances, 0, width * height);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="y">The row to fetch, 0 &lt;= y &lt; Height.</param>
/// <param name="row">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.</param>
/// <returns>
/// An array containing the luminance data.
/// </returns>
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; }
}
/// <summary>
/// Returns a new object with rotated image data by 90 degrees counterclockwise.
/// Only callable if {@link #isRotateSupported()} is true.
/// </summary>
/// <returns>
/// A rotated version of this object.
/// </returns>
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);
}
/// <summary>
/// TODO: not implemented yet
/// </summary>
/// <returns>
/// A rotated version of this object.
/// </returns>
public override LuminanceSource rotateCounterClockwise45()
{
// TODO: implement a good 45 degrees rotation without lost of information
return base.rotateCounterClockwise45();
}
/// <summary>
/// </summary>
/// <returns> Whether this subclass supports counter-clockwise rotation.</returns>
public override bool RotateSupported
{
get
{
return true;
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="left">The left coordinate, 0 &lt;= left &lt; Width.</param>
/// <param name="top">The top coordinate, 0 &lt;= top &lt;= Height.</param>
/// <param name="width">The width of the rectangle to crop.</param>
/// <param name="height">The height of the rectangle to crop.</param>
/// <returns>
/// A cropped version of this object.
/// </returns>
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);
}
/// <summary>
/// </summary>
/// <returns> Whether this subclass supports cropping.</returns>
public override bool CropSupported
{
get
{
return true;
}
}
/// <summary>
/// </summary>
/// <returns>Whether this subclass supports invertion.</returns>
public override bool InversionSupported
{
get
{
return true;
}
}
/// <summary>
/// Should create a new luminance source with the right class type.
/// The method is used in methods crop and rotate.
/// </summary>
/// <param name="newLuminances">The new luminances.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <returns></returns>
protected abstract LuminanceSource CreateLuminanceSource(byte[] newLuminances, int width, int height);
}
}

+ 0
- 104
shadowsocks-csharp/3rd/zxing/Binarizer.cs View File

@@ -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
{
/// <summary> 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.
///
/// <author>dswitkin@google.com (Daniel Switkin)</author>
/// </summary>
public abstract class Binarizer
{
private readonly LuminanceSource source;
/// <summary>
/// Initializes a new instance of the <see cref="Binarizer"/> class.
/// </summary>
/// <param name="source">The source.</param>
protected internal Binarizer(LuminanceSource source)
{
if (source == null)
{
throw new ArgumentException("Source must be non-null.");
}
this.source = source;
}
/// <summary>
/// Gets the luminance source object.
/// </summary>
virtual public LuminanceSource LuminanceSource
{
get
{
return source;
}
}
/// <summary> 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.
/// </summary>
/// <param name="y">The row to fetch, 0 &lt;= y &lt; bitmap height.</param>
/// <param name="row">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.
/// </param>
/// <returns> The array of bits for this row (true means black).</returns>
public abstract BitArray getBlackRow(int y, BitArray row);
/// <summary> 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.
/// </summary>
/// <returns> The 2D array of bits for the image (true means black).</returns>
public abstract BitMatrix BlackMatrix { get; }
/// <summary> 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.
/// </summary>
/// <param name="source">The LuminanceSource this Binarizer will operate on.</param>
/// <returns> A new concrete Binarizer implementation object.</returns>
public abstract Binarizer createBinarizer(LuminanceSource source);
/// <summary>
/// Gets the width of the luminance source object.
/// </summary>
public int Width
{
get { return source.Width; }
}
/// <summary>
/// Gets the height of the luminance source object.
/// </summary>
public int Height
{
get { return source.Height; }
}
}
}

+ 0
- 186
shadowsocks-csharp/3rd/zxing/BinaryBitmap.cs View File

@@ -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
{
/// <summary> 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.
///
/// </summary>
/// <author> dswitkin@google.com (Daniel Switkin)
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
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;
}
/// <returns> The width of the bitmap.
/// </returns>
public int Width
{
get
{
return binarizer.Width;
}
}
/// <returns> The height of the bitmap.
/// </returns>
public int Height
{
get
{
return binarizer.Height;
}
}
/// <summary> 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.
///
/// </summary>
/// <param name="y">The row to fetch, 0 &lt;= y &lt; bitmap height.
/// </param>
/// <param name="row">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.
/// </param>
/// <returns> The array of bits for this row (true means black).
/// </returns>
public BitArray getBlackRow(int y, BitArray row)
{
return binarizer.getBlackRow(y, row);
}
/// <summary> 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.
///
/// </summary>
/// <returns> The 2D array of bits for the image (true means black).
/// </returns>
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;
}
}
/// <returns> Whether this bitmap can be cropped.
/// </returns>
public bool CropSupported
{
get
{
return binarizer.LuminanceSource.CropSupported;
}
}
/// <summary> 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.
///
/// </summary>
/// <param name="left">The left coordinate, 0 &lt;= left &lt; getWidth().
/// </param>
/// <param name="top">The top coordinate, 0 &lt;= top &lt;= getHeight().
/// </param>
/// <param name="width">The width of the rectangle to crop.
/// </param>
/// <param name="height">The height of the rectangle to crop.
/// </param>
/// <returns> A cropped version of this object.
/// </returns>
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));
}
/// <returns> Whether this bitmap supports counter-clockwise rotation.
/// </returns>
public bool RotateSupported
{
get
{
return binarizer.LuminanceSource.RotateSupported;
}
}
/// <summary>
/// Returns a new object with rotated image data by 90 degrees counterclockwise.
/// Only callable if {@link #isRotateSupported()} is true.
/// </summary>
/// <returns> A rotated version of this object.
/// </returns>
public BinaryBitmap rotateCounterClockwise()
{
var newSource = binarizer.LuminanceSource.rotateCounterClockwise();
return new BinaryBitmap(binarizer.createBinarizer(newSource));
}
/// <summary>
/// Returns a new object with rotated image data by 45 degrees counterclockwise.
/// Only callable if {@link #isRotateSupported()} is true.
/// </summary>
/// <returns>A rotated version of this object.</returns>
public BinaryBitmap rotateCounterClockwise45()
{
LuminanceSource newSource = binarizer.LuminanceSource.rotateCounterClockwise45();
return new BinaryBitmap(binarizer.createBinarizer(newSource));
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var blackMatrix = BlackMatrix;
return blackMatrix != null ? blackMatrix.ToString() : String.Empty;
}
}
}

+ 0
- 242
shadowsocks-csharp/3rd/zxing/BitmapLuminanceSource.cs View File

@@ -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
{
/// <summary>
/// Initializes a new instance of the <see cref="BitmapLuminanceSource"/> class.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
protected BitmapLuminanceSource(int width, int height)
: base(width, height)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapLuminanceSource"/> class
/// with the image of a Bitmap instance
/// </summary>
/// <param name="bitmap">The bitmap.</param>
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);
}
}
/// <summary>
/// Should create a new luminance source with the right class type.
/// The method is used in methods crop and rotate.
/// </summary>
/// <param name="newLuminances">The new luminances.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <returns></returns>
protected override LuminanceSource CreateLuminanceSource(byte[] newLuminances, int width, int height)
{
return new BitmapLuminanceSource(width, height) { luminances = newLuminances };
}
}
}

+ 0
- 125
shadowsocks-csharp/3rd/zxing/DecodeHintType.cs View File

@@ -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
{
/// <summary>
/// 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.
/// <seealso cref="Reader.decode(BinaryBitmap, IDictionary{DecodeHintType, object})" />
/// </summary>
/// <author>Sean Owen</author>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
public enum DecodeHintType
{
/// <summary>
/// Unspecified, application-specific hint. Maps to an unspecified <see cref="System.Object" />.
/// </summary>
OTHER,
/// <summary>
/// Image is a pure monochrome image of a barcode. Doesn't matter what it maps to;
/// use <see cref="bool" /> = true.
/// </summary>
PURE_BARCODE,
/// <summary>
/// Image is known to be of one of a few possible formats.
/// Maps to a <see cref="System.Collections.ICollection" /> of <see cref="BarcodeFormat" />s.
/// </summary>
POSSIBLE_FORMATS,
/// <summary>
/// Spend more time to try to find a barcode; optimize for accuracy, not speed.
/// Doesn't matter what it maps to; use <see cref="bool" /> = true.
/// </summary>
TRY_HARDER,
/// <summary>
/// Specifies what character encoding to use when decoding, where applicable (type String)
/// </summary>
CHARACTER_SET,
/// <summary>
/// Allowed lengths of encoded data -- reject anything else. Maps to an int[].
/// </summary>
ALLOWED_LENGTHS,
/// <summary>
/// Assume Code 39 codes employ a check digit. Maps to <see cref="bool" />.
/// </summary>
ASSUME_CODE_39_CHECK_DIGIT,
/// <summary>
/// The caller needs to be notified via callback when a possible <see cref="ResultPoint" />
/// is found. Maps to a <see cref="ResultPointCallback" />.
/// </summary>
NEED_RESULT_POINT_CALLBACK,
/// <summary>
/// Assume MSI codes employ a check digit. Maps to <see cref="bool" />.
/// </summary>
ASSUME_MSI_CHECK_DIGIT,
/// <summary>
/// if Code39 could be detected try to use extended mode for full ASCII character set
/// Maps to <see cref="bool" />.
/// </summary>
USE_CODE_39_EXTENDED_MODE,
/// <summary>
/// Don't fail if a Code39 is detected but can't be decoded in extended mode.
/// Return the raw Code39 result instead. Maps to <see cref="bool" />.
/// </summary>
RELAXED_CODE_39_EXTENDED_MODE,
/// <summary>
/// 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 <see cref="bool" />.
/// </summary>
TRY_HARDER_WITHOUT_ROTATION,
/// <summary>
/// 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 <see cref="bool" />.
/// </summary>
ASSUME_GS1,
/// <summary>
/// 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 <see cref="bool" />.
/// </summary>
RETURN_CODABAR_START_END,
/// <summary>
/// Allowed extension lengths for EAN or UPC barcodes. Other formats will ignore this.
/// Maps to an <see cref="Array.int" /> 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.
/// </summary>
ALLOWED_EAN_EXTENSIONS
}
}

+ 0
- 131
shadowsocks-csharp/3rd/zxing/EncodeHintType.cs View File

@@ -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
{
/// <summary>
/// These are a set of hints that you may pass to Writers to specify their behavior.
/// </summary>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
public enum EncodeHintType
{
/// <summary>
/// Specifies the width of the barcode image
/// type: <see cref="System.Int32" />
/// </summary>
WIDTH,
/// <summary>
/// Specifies the height of the barcode image
/// type: <see cref="System.Int32" />
/// </summary>
HEIGHT,
/// <summary>
/// Don't put the content string into the output image.
/// type: <see cref="System.Boolean" />
/// </summary>
PURE_BARCODE,
/// <summary>
/// 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
/// <see cref="ZXing.QrCode.Internal.ErrorCorrectionLevel" />
/// For Aztec it is of type <see cref="System.Int32" />, 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 <see cref="ZXing.PDF417.Internal.PDF417ErrorCorrectionLevel"/> or <see cref="System.Int32" /> (between 0 and 8),
/// </summary>
ERROR_CORRECTION,
/// <summary>
/// Specifies what character encoding to use where applicable.
/// type: <see cref="System.String" />
/// </summary>
CHARACTER_SET,
/// <summary>
/// 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: <see cref="System.Int32" />
/// </summary>
MARGIN,
/// <summary>
/// Specifies whether to use compact mode for PDF417.
/// type: <see cref="System.Boolean" />
/// </summary>
PDF417_COMPACT,
/// <summary>
/// Specifies what compaction mode to use for PDF417.
/// type: <see cref="ZXing.PDF417.Internal.Compaction" />
/// </summary>
PDF417_COMPACTION,
/// <summary>
/// Specifies the minimum and maximum number of rows and columns for PDF417.
/// type: <see cref="ZXing.PDF417.Internal.Dimensions" />
/// </summary>
PDF417_DIMENSIONS,
/// <summary>
/// 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: <see cref="System.Boolean" />
/// </summary>
DISABLE_ECI,
/// <summary>
/// Specifies the matrix shape for Data Matrix (type <see cref="ZXing.Datamatrix.Encoder.SymbolShapeHint"/>)
/// </summary>
DATA_MATRIX_SHAPE,
/// <summary>
/// Specifies a minimum barcode size (type <see cref="ZXing.Dimension"/>). Only applicable to Data Matrix now.
/// </summary>
MIN_SIZE,
/// <summary>
/// Specifies a maximum barcode size (type <see cref="ZXing.Dimension"/>). Only applicable to Data Matrix now.
/// </summary>
MAX_SIZE,
/// <summary>
/// if true, don't switch to codeset C for numbers
/// </summary>
CODE128_FORCE_CODESET_B,
/// <summary>
/// Specifies the default encodation for Data Matrix (type <see cref="ZXing.Datamatrix.Encoder.Encodation"/>)
/// Make sure that the content fits into the encodation value, otherwise there will be an exception thrown.
/// standard value: Encodation.ASCII
/// </summary>
DATA_MATRIX_DEFAULT_ENCODATION,
/// <summary>
/// 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
/// </summary>
AZTEC_LAYERS,
}
}

+ 0
- 198
shadowsocks-csharp/3rd/zxing/LuminanceSource.cs View File

@@ -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
{
/// <summary> 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.
/// </summary>
/// <author> dswitkin@google.com (Daniel Switkin)
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public abstract class LuminanceSource
{
private int width;
private int height;
protected LuminanceSource(int width, int height)
{
this.width = width;
this.height = height;
}
/// <summary> 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.
///
/// </summary>
/// <param name="y">The row to fetch, 0 &lt;= y &lt; Height.
/// </param>
/// <param name="row">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.
/// </param>
/// <returns> An array containing the luminance data.
/// </returns>
public abstract byte[] getRow(int y, byte[] row);
/// <summary> Fetches luminance data for the underlying bitmap. Values should be fetched using:
/// int luminance = array[y * width + x] &amp; 0xff;
///
/// </summary>
/// <returns> 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.
/// </returns>
public abstract byte[] Matrix { get; }
/// <returns> The width of the bitmap.</returns>
virtual public int Width
{
get
{
return width;
}
protected set
{
width = value;
}
}
/// <returns> The height of the bitmap.</returns>
virtual public int Height
{
get
{
return height;
}
protected set
{
height = value;
}
}
/// <returns> Whether this subclass supports cropping.</returns>
virtual public bool CropSupported
{
get
{
return false;
}
}
/// <summary> 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.
///
/// </summary>
/// <param name="left">The left coordinate, 0 &lt;= left &lt; Width.
/// </param>
/// <param name="top">The top coordinate, 0 &lt;= top &lt;= Height.
/// </param>
/// <param name="width">The width of the rectangle to crop.
/// </param>
/// <param name="height">The height of the rectangle to crop.
/// </param>
/// <returns> A cropped version of this object.
/// </returns>
public virtual LuminanceSource crop(int left, int top, int width, int height)
{
throw new NotSupportedException("This luminance source does not support cropping.");
}
/// <returns> Whether this subclass supports counter-clockwise rotation.</returns>
virtual public bool RotateSupported
{
get
{
return false;
}
}
/// <summary>
/// Returns a new object with rotated image data by 90 degrees counterclockwise.
/// Only callable if {@link #isRotateSupported()} is true.
/// </summary>
/// <returns> A rotated version of this object.
/// </returns>
public virtual LuminanceSource rotateCounterClockwise()
{
throw new NotSupportedException("This luminance source does not support rotation.");
}
/// <summary>
/// Returns a new object with rotated image data by 45 degrees counterclockwise.
/// Only callable if {@link #isRotateSupported()} is true.
/// </summary>
/// <returns>A rotated version of this object.</returns>
public virtual LuminanceSource rotateCounterClockwise45()
{
throw new NotSupportedException("This luminance source does not support rotation by 45 degrees.");
}
/// <summary>
/// </summary>
/// <returns>Whether this subclass supports invertion.</returns>
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();
}
}
}

+ 0
- 161
shadowsocks-csharp/3rd/zxing/Result.cs View File

@@ -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
{
/// <summary>
/// Encapsulates the result of decoding a barcode within an image.
/// </summary>
public sealed class Result
{
/// <returns>raw text encoded by the barcode, if applicable, otherwise <code>null</code></returns>
public String Text { get; private set; }
/// <returns>raw bytes encoded by the barcode, if applicable, otherwise <code>null</code></returns>
public byte[] RawBytes { get; private set; }
/// <returns>
/// 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.
/// </returns>
public ResultPoint[] ResultPoints { get; private set; }
/// <returns>{@link BarcodeFormat} representing the format of the barcode that was decoded</returns>
public BarcodeFormat BarcodeFormat { get; private set; }
/// <returns>
/// {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be
/// <code>null</code>. This contains optional metadata about what was detected about the barcode,
/// like orientation.
/// </returns>
public IDictionary<ResultMetadataType, object> ResultMetadata { get; private set; }
/// <summary>
/// Gets the timestamp.
/// </summary>
public long Timestamp { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Result"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="rawBytes">The raw bytes.</param>
/// <param name="resultPoints">The result points.</param>
/// <param name="format">The format.</param>
public Result(String text,
byte[] rawBytes,
ResultPoint[] resultPoints,
BarcodeFormat format)
: this(text, rawBytes, resultPoints, format, DateTime.Now.Ticks)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Result"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="rawBytes">The raw bytes.</param>
/// <param name="resultPoints">The result points.</param>
/// <param name="format">The format.</param>
/// <param name="timestamp">The timestamp.</param>
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;
}
/// <summary>
/// Adds one metadata to the result
/// </summary>
/// <param name="type">The type.</param>
/// <param name="value">The value.</param>
public void putMetadata(ResultMetadataType type, Object value)
{
if (ResultMetadata == null)
{
ResultMetadata = new Dictionary<ResultMetadataType, object>();
}
ResultMetadata[type] = value;
}
/// <summary>
/// Adds a list of metadata to the result
/// </summary>
/// <param name="metadata">The metadata.</param>
public void putAllMetadata(IDictionary<ResultMetadataType, object> metadata)
{
if (metadata != null)
{
if (ResultMetadata == null)
{
ResultMetadata = metadata;
}
else
{
foreach (var entry in metadata)
ResultMetadata[entry.Key] = entry.Value;
}
}
}
/// <summary>
/// Adds the result points.
/// </summary>
/// <param name="newPoints">The new points.</param>
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;
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override String ToString()
{
if (Text == null)
{
return "[" + RawBytes.Length + " bytes]";
}
return Text;
}
}
}

+ 0
- 102
shadowsocks-csharp/3rd/zxing/ResultMetadataType.cs View File

@@ -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
{
/// <summary>
/// Represents some type of metadata about the result of the decoding that the decoder
/// wishes to communicate back to the caller.
/// </summary>
/// <author>Sean Owen</author>
public enum ResultMetadataType
{
/// <summary>
/// Unspecified, application-specific metadata. Maps to an unspecified {@link Object}.
/// </summary>
OTHER,
/// <summary>
/// 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).
/// </summary>
ORIENTATION,
/// <summary>
/// <p>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.</p>
/// <p>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.</p>
/// </summary>
BYTE_SEGMENTS,
/// <summary>
/// Error correction level used, if applicable. The value type depends on the
/// format, but is typically a String.
/// </summary>
ERROR_CORRECTION_LEVEL,
/// <summary>
/// For some periodicals, indicates the issue number as an {@link Integer}.
/// </summary>
ISSUE_NUMBER,
/// <summary>
/// For some products, indicates the suggested retail price in the barcode as a
/// formatted {@link String}.
/// </summary>
SUGGESTED_PRICE,
/// <summary>
/// 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".
/// </summary>
POSSIBLE_COUNTRY,
/// <summary>
/// For some products, the extension text
/// </summary>
UPC_EAN_EXTENSION,
/// <summary>
/// If the code format supports structured append and
/// the current scanned code is part of one then the
/// sequence number is given with it.
/// </summary>
STRUCTURED_APPEND_SEQUENCE,
/// <summary>
/// If the code format supports structured append and
/// the current scanned code is part of one then the
/// parity is given with it.
/// </summary>
STRUCTURED_APPEND_PARITY,
/// <summary>
/// PDF417-specific metadata
/// </summary>
PDF417_EXTRA_METADATA,
/// <summary>
/// Aztec-specific metadata
/// </summary>
AZTEC_EXTRA_METADATA
}
}

+ 0
- 191
shadowsocks-csharp/3rd/zxing/ResultPoint.cs View File

@@ -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
{
/// <summary>
/// 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.
/// </summary>
/// <author>Sean Owen</author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source</author>
public class ResultPoint
{
private readonly float x;
private readonly float y;
private readonly byte[] bytesX;
private readonly byte[] bytesY;
private String toString;
/// <summary>
/// Initializes a new instance of the <see cref="ResultPoint"/> class.
/// </summary>
public ResultPoint()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultPoint"/> class.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
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);
}
/// <summary>
/// Gets the X.
/// </summary>
virtual public float X
{
get
{
return x;
}
}
/// <summary>
/// Gets the Y.
/// </summary>
virtual public float Y
{
get
{
return y;
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(Object other)
{
var otherPoint = other as ResultPoint;
if (otherPoint == null)
return false;
return x == otherPoint.x && y == otherPoint.y;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
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];
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
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;
}
/// <summary>
/// Orders an array of three ResultPoints in an order [A,B,C] such that AB &lt; AC and
/// BC &lt; AC and the angle between BC and BA is less than 180 degrees.
/// </summary>
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;
}
/// <returns>
/// distance between two points
/// </returns>
public static float distance(ResultPoint pattern1, ResultPoint pattern2)
{
return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y);
}
/// <summary>
/// Returns the z component of the cross product between vectors BC and BA.
/// </summary>
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));
}
}
}

+ 0
- 26
shadowsocks-csharp/3rd/zxing/ResultPointCallback.cs View File

@@ -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
{
/// <summary> Callback which is invoked when a possible result point (significant
/// point in the barcode image such as a corner) is found.
///
/// </summary>
/// <seealso cref="DecodeHintType.NEED_RESULT_POINT_CALLBACK">
/// </seealso>
public delegate void ResultPointCallback(ResultPoint point);
}

+ 0
- 55
shadowsocks-csharp/3rd/zxing/WriterException.cs View File

@@ -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
{
/// <summary>
/// A base class which covers the range of exceptions which may occur when encoding a barcode using
/// the Writer framework.
/// </summary>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
[Serializable]
public sealed class WriterException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="WriterException"/> class.
/// </summary>
public WriterException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WriterException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public WriterException(String message)
:base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WriterException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerExc">The inner exc.</param>
public WriterException(String message, Exception innerExc)
: base(message, innerExc)
{
}
}
}

+ 0
- 278
shadowsocks-csharp/3rd/zxing/common/BitArray.cs View File

@@ -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
{
/// <summary>
/// A simple, fast array of bits, represented compactly by an array of ints internally.
/// </summary>
/// <author>Sean Owen</author>
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
};
/// <summary> Sets a block of 32 bits, starting at bit i.
///
/// </summary>
/// <param name="i">first bit to set
/// </param>
/// <param name="newBits">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.
/// </param>
public void setBulk(int i, int newBits)
{
bits[i >> 5] = newBits;
}
/// <summary> Clears all bits (sets to false).</summary>
public void clear()
{
int max = bits.Length;
for (int i = 0; i < max; i++)
{
bits[i] = 0;
}
}
/// <summary>
/// Appends the bit.
/// </summary>
/// <param name="bit">The bit.</param>
public void appendBit(bool bit)
{
ensureCapacity(size + 1);
if (bit)
{
bits[size >> 5] |= 1 << (size & 0x1F);
}
size++;
}
/// <returns> underlying array of ints. The first element holds the first 32 bits, and the least
/// significant bit is bit 0.
/// </returns>
public int[] Array
{
get { return bits; }
}
/// <summary>
/// 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.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="numBits">The num bits.</param>
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];
}
}
/// <summary>
/// Toes the bytes.
/// </summary>
/// <param name="bitOffset">first bit to start writing</param>
/// <param name="array">array to write into. Bytes are written most-significant byte first. This is the opposite
/// of the internal representation, which is exposed by BitArray</param>
/// <param name="offset">position in array to start writing</param>
/// <param name="numBytes">how many bytes to write</param>
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];
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="o">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
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;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
var hash = size;
foreach (var bit in bits)
{
hash = 31 * hash + bit.GetHashCode();
}
return hash;
}
/// <summary>
/// Erstellt ein neues Objekt, das eine Kopie der aktuellen Instanz darstellt.
/// </summary>
/// <returns>
/// Ein neues Objekt, das eine Kopie dieser Instanz darstellt.
/// </returns>
public object Clone()
{
return new BitArray((int[])bits.Clone(), size);
}
}
}

+ 0
- 259
shadowsocks-csharp/3rd/zxing/common/BitMatrix.cs View File

@@ -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
{
/// <summary>
/// <p>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.</p>
/// <p>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.</p>
/// <p>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.</p>
/// </summary>
/// <author>Sean Owen</author>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
public sealed partial class BitMatrix
{
private readonly int width;
private readonly int height;
private readonly int rowSize;
private readonly int[] bits;
/// <returns> The width of the matrix
/// </returns>
public int Width
{
get
{
return width;
}
}
/// <returns> The height of the matrix
/// </returns>
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;
}
/// <summary> <p>Gets the requested bit, where true means black.</p>
///
/// </summary>
/// <param name="x">The horizontal component (i.e. which column)
/// </param>
/// <param name="y">The vertical component (i.e. which row)
/// </param>
/// <returns> value of given bit in matrix
/// </returns>
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);
}
}
}
/// <summary> <p>Flips the given bit.</p>
///
/// </summary>
/// <param name="x">The horizontal component (i.e. which column)
/// </param>
/// <param name="y">The vertical component (i.e. which row)
/// </param>
public void flip(int x, int y)
{
int offset = y * rowSize + (x >> 5);
bits[offset] ^= 1 << (x & 0x1f);
}
/// <summary> <p>Sets a square region of the bit matrix to true.</p>
///
/// </summary>
/// <param name="left">The horizontal position to begin at (inclusive)
/// </param>
/// <param name="top">The vertical position to begin at (inclusive)
/// </param>
/// <param name="width">The width of the region
/// </param>
/// <param name="height">The height of the region
/// </param>
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);
}
}
}
/// <summary> A fast method to retrieve one row of data from the matrix as a BitArray.
///
/// </summary>
/// <param name="y">The row to retrieve
/// </param>
/// <param name="row">An optional caller-allocated BitArray, will be allocated if null or too small
/// </param>
/// <returns> The resulting BitArray - this reference should always be used even when passing
/// your own row
/// </returns>
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;
}
/// <summary>
/// Sets the row.
/// </summary>
/// <param name="y">row to set</param>
/// <param name="row">{@link BitArray} to copy from</param>
public void setRow(int y, BitArray row)
{
Array.Copy(row.Array, 0, bits, y * rowSize, rowSize);
}
/// <summary>
/// This is useful in detecting a corner of a 'pure' barcode.
/// </summary>
/// <returns>{x,y} coordinate of top-left-most 1 bit, or null if it is all white</returns>
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 };
}
}
}

+ 0
- 124
shadowsocks-csharp/3rd/zxing/common/BitSource.cs View File

@@ -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
{
/// <summary> <p>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.</p>
///
/// <p>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.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public sealed class BitSource
{
private readonly byte[] bytes;
private int byteOffset;
private int bitOffset;
/// <param name="bytes">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.
/// </param>
public BitSource(byte[] bytes)
{
this.bytes = bytes;
}
/// <summary>
/// index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
/// </summary>
public int BitOffset
{
get { return bitOffset; }
}
/// <summary>
/// index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
/// </summary>
public int ByteOffset
{
get { return byteOffset; }
}
/// <param name="numBits">number of bits to read
/// </param>
/// <returns> int representing the bits read. The bits will appear as the least-significant
/// bits of the int
/// </returns>
/// <exception cref="ArgumentException">if numBits isn't in [1,32] or more than is available</exception>
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;
}
/// <returns> number of bits that can be read successfully
/// </returns>
public int available()
{
return 8 * (bytes.Length - byteOffset) - bitOffset;
}
}
}

+ 0
- 76
shadowsocks-csharp/3rd/zxing/common/DecoderResult.cs View File

@@ -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
{
/// <summary>
/// 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.
/// <author>Sean Owen</author>
/// </summary>
public sealed class DecoderResult
{
public byte[] RawBytes { get; private set; }
public String Text { get; private set; }
public IList<byte[]> 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; }
/// <summary>
/// Miscellanseous data value for the various decoders
/// </summary>
/// <value>The other.</value>
public object Other { get; set; }
public DecoderResult(byte[] rawBytes, String text, IList<byte[]> byteSegments, String ecLevel)
: this(rawBytes, text, byteSegments, ecLevel, -1, -1)
{
}
public DecoderResult(byte[] rawBytes, String text, IList<byte[]> 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;
}
}
}

+ 0
- 82
shadowsocks-csharp/3rd/zxing/common/DefaultGridSampler.cs View File

@@ -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
{
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
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;
}
}
}

+ 0
- 39
shadowsocks-csharp/3rd/zxing/common/DetectorResult.cs View File

@@ -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
{
/// <summary> <p>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.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
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;
}
}
}

+ 0
- 243
shadowsocks-csharp/3rd/zxing/common/GlobalHistogramBinarizer.cs View File

@@ -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
{
/// <summary> 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.
///
/// <author>dswitkin@google.com (Daniel Switkin)</author>
/// <author>Sean Owen</author>
/// </summary>
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;
/// <summary>
/// Initializes a new instance of the <see cref="GlobalHistogramBinarizer"/> class.
/// </summary>
/// <param name="source">The source.</param>
public GlobalHistogramBinarizer(LuminanceSource source)
: base(source)
{
luminances = EMPTY;
buckets = new int[LUMINANCE_BUCKETS];
}
/// <summary>
/// Applies simple sharpening to the row data to improve performance of the 1D Readers.
/// </summary>
/// <param name="y"></param>
/// <param name="row"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
/// </summary>
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;
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="source">The LuminanceSource this Binarizer will operate on.</param>
/// <returns>
/// A new concrete Binarizer implementation object.
/// </returns>
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;
}
}
}

+ 0
- 192
shadowsocks-csharp/3rd/zxing/common/GridSampler.cs View File

@@ -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
{
/// <summary> 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.
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public abstract class GridSampler
{
/// <returns> the current implementation of {@link GridSampler}
/// </returns>
public static GridSampler Instance
{
get
{
return gridSampler;
}
}
private static GridSampler gridSampler = new DefaultGridSampler();
/// <summary> 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.
///
/// </summary>
/// <param name="newGridSampler">The platform-specific object to install.
/// </param>
public static void setGridSampler(GridSampler newGridSampler)
{
if (newGridSampler == null)
{
throw new System.ArgumentException();
}
gridSampler = newGridSampler;
}
/// <summary> <p>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.</p>
///
/// <p>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.</p>
///
/// <p>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.</p>
///
/// <p>These 16 parameters define the transformation needed to sample the image.</p>
///
/// </summary>
/// <param name="image">image to sample
/// </param>
/// <param name="dimension">width/height of {@link BitMatrix} to sample from image
/// </param>
/// <returns> {@link BitMatrix} representing a grid of points sampled from the image within a region
/// defined by the "from" parameters
/// </returns>
/// <throws> ReaderException if image can't be sampled, for example, if the transformation defined </throws>
/// <summary> by the given points is invalid or results in sampling outside the image boundaries
/// </summary>
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();
}
/// <summary> <p>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.</p>
///
/// <p>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.</p>
///
/// <p>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.</p>
///
/// </summary>
/// <param name="image">image into which the points should map
/// </param>
/// <param name="points">actual points in x1,y1,...,xn,yn form
/// </param>
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;
}
}
}

+ 0
- 288
shadowsocks-csharp/3rd/zxing/common/HybridBinarizer.cs View File

@@ -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
{
/// <summary> 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.
///
/// </summary>
/// <author> dswitkin@google.com (Daniel Switkin)
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
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);
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
}
/// <summary>
/// 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).
/// </summary>
/// <param name="luminances">The luminances.</param>
/// <param name="subWidth">Width of the sub.</param>
/// <param name="subHeight">Height of the sub.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="blackPoints">The black points.</param>
/// <param name="matrix">The matrix.</param>
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;
}
/// <summary>
/// Applies a single threshold to an 8x8 block of pixels.
/// </summary>
/// <param name="luminances">The luminances.</param>
/// <param name="xoffset">The xoffset.</param>
/// <param name="yoffset">The yoffset.</param>
/// <param name="threshold">The threshold.</param>
/// <param name="stride">The stride.</param>
/// <param name="matrix">The matrix.</param>
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);
}
}
}
/// <summary>
/// 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
/// </summary>
/// <param name="luminances">The luminances.</param>
/// <param name="subWidth">Width of the sub.</param>
/// <param name="subHeight">Height of the sub.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <returns></returns>
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;
}
}
}

+ 0
- 159
shadowsocks-csharp/3rd/zxing/common/PerspectiveTransform.cs View File

@@ -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
{
/// <summary> <p>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.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
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;
}
}
/// <summary>Convenience method, not optimized for performance. </summary>
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);
}
}
}

+ 0
- 266
shadowsocks-csharp/3rd/zxing/common/StringUtils.cs View File

@@ -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
{
/// <summary>
/// Common string-related functions.
/// </summary>
/// <author>Sean Owen</author>
/// <author>Alex Dupre</author>
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;
/// <summary>
/// Guesses the encoding.
/// </summary>
/// <param name="bytes">bytes encoding a string, whose encoding should be guessed</param>
/// <param name="hints">decode hints if applicable</param>
/// <returns>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</returns>
public static String guessEncoding(byte[] bytes, IDictionary<DecodeHintType, object> 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;
}
}
}

+ 0
- 48
shadowsocks-csharp/3rd/zxing/common/detector/MathUtils.cs View File

@@ -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
{
/// <summary>
/// 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.
/// </summary>
/// <param name="d">The d.</param>
/// <returns></returns>
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);
}
}
}

+ 0
- 242
shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGF.cs View File

@@ -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
{
/// <summary>
/// <p>This class contains utility methods for performing mathematical operations over
/// the Galois Fields. Operations use a given primitive polynomial in calculations.</p>
/// <p>Throughout this package, elements of the GF are represented as an {@code int}
/// for convenience and speed (but at the cost of memory).
/// </p>
/// </summary>
/// <author>Sean Owen</author>
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;
/// <summary>
/// Create a representation of GF(size) using the given primitive polynomial.
/// </summary>
/// <param name="primitive">irreducible polynomial whose coefficients are represented by
/// * the bits of an int, where the least-significant bit represents the constant
/// * coefficient</param>
/// <param name="size">the size of the field</param>
/// <param name="genBase">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.</param>
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;
}
}
/// <summary>
/// Builds the monomial.
/// </summary>
/// <param name="degree">The degree.</param>
/// <param name="coefficient">The coefficient.</param>
/// <returns>the monomial representing coefficient * x^degree</returns>
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);
}
/// <summary>
/// Implements both addition and subtraction -- they are the same in GF(size).
/// </summary>
/// <returns>sum/difference of a and b</returns>
static internal int addOrSubtract(int a, int b)
{
return a ^ b;
}
/// <summary>
/// Exps the specified a.
/// </summary>
/// <returns>2 to the power of a in GF(size)</returns>
internal int exp(int a)
{
checkInit();
return expTable[a];
}
/// <summary>
/// Logs the specified a.
/// </summary>
/// <param name="a">A.</param>
/// <returns>base 2 log of a in GF(size)</returns>
internal int log(int a)
{
checkInit();
if (a == 0)
{
throw new ArgumentException();
}
return logTable[a];
}
/// <summary>
/// Inverses the specified a.
/// </summary>
/// <returns>multiplicative inverse of a</returns>
internal int inverse(int a)
{
checkInit();
if (a == 0)
{
throw new ArithmeticException();
}
return expTable[size - logTable[a] - 1];
}
/// <summary>
/// Multiplies the specified a with b.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>product of a and b in GF(size)</returns>
internal int multiply(int a, int b)
{
checkInit();
if (a == 0 || b == 0)
{
return 0;
}
return expTable[(logTable[a] + logTable[b]) % (size - 1)];
}
/// <summary>
/// Gets the size.
/// </summary>
public int Size
{
get { return size; }
}
/// <summary>
/// Gets the generator base.
/// </summary>
public int GeneratorBase
{
get { return generatorBase; }
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
override public String ToString()
{
return "GF(0x" + primitive.ToString("X") + ',' + size + ')';
}
}
}

+ 0
- 331
shadowsocks-csharp/3rd/zxing/common/reedsolomon/GenericGFPoly.cs View File

@@ -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
{
/// <summary>
/// <p>Represents a polynomial whose coefficients are elements of a GF.
/// Instances of this class are immutable.</p>
/// <p>Much credit is due to William Rucklidge since portions of this code are an indirect
/// port of his C++ Reed-Solomon implementation.</p>
/// </summary>
/// <author>Sean Owen</author>
internal sealed class GenericGFPoly
{
private readonly GenericGF field;
private readonly int[] coefficients;
/// <summary>
/// Initializes a new instance of the <see cref="GenericGFPoly"/> class.
/// </summary>
/// <param name="field">the {@link GenericGF} instance representing the field to use
/// to perform computations</param>
/// <param name="coefficients">coefficients as ints representing elements of GF(size), arranged
/// from most significant (highest-power term) coefficient to least significant</param>
/// <exception cref="ArgumentException">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")</exception>
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; }
}
/// <summary>
/// degree of this polynomial
/// </summary>
internal int Degree
{
get
{
return coefficients.Length - 1;
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="GenericGFPoly"/> is zero.
/// </summary>
/// <value>true iff this polynomial is the monomial "0"</value>
internal bool isZero
{
get { return coefficients[0] == 0; }
}
/// <summary>
/// coefficient of x^degree term in this polynomial
/// </summary>
/// <param name="degree">The degree.</param>
/// <returns>coefficient of x^degree term in this polynomial</returns>
internal int getCoefficient(int degree)
{
return coefficients[coefficients.Length - 1 - degree];
}
/// <summary>
/// evaluation of this polynomial at a given point
/// </summary>
/// <param name="a">A.</param>
/// <returns>evaluation of this polynomial at a given point</returns>
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();
}
}
}

+ 0
- 227
shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonDecoder.cs View File

@@ -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
{
/// <summary> <p>Implements Reed-Solomon decoding, as the name implies.</p>
///
/// <p>The algorithm will not be explained here, but the following references were helpful
/// in creating this implementation:</p>
///
/// <ul>
/// <li>Bruce Maggs.
/// <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
/// "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
/// <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
/// "Chapter 5. Generalized Reed-Solomon Codes"</a>
/// (see discussion of Euclidean algorithm)</li>
/// </ul>
///
/// <p>Much credit is due to William Rucklidge since portions of this code are an indirect
/// port of his C++ Reed-Solomon implementation.</p>
///
/// </summary>
/// <author>Sean Owen</author>
/// <author>William Rucklidge</author>
/// <author>sanfordsquires</author>
public sealed class ReedSolomonDecoder
{
private readonly GenericGF field;
public ReedSolomonDecoder(GenericGF field)
{
this.field = field;
}
/// <summary>
/// <p>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.</p>
/// </summary>
/// <param name="received">data and error-correction codewords</param>
/// <param name="twoS">number of error-correction codewords available</param>
/// <returns>false: decoding fails</returns>
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;
}
}
}

+ 0
- 84
shadowsocks-csharp/3rd/zxing/common/reedsolomon/ReedSolomonEncoder.cs View File

@@ -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
{
/// <summary>
/// Implements Reed-Solomon encoding, as the name implies.
/// </summary>
/// <author>Sean Owen</author>
/// <author>William Rucklidge</author>
public sealed class ReedSolomonEncoder
{
private readonly GenericGF field;
private readonly IList<GenericGFPoly> cachedGenerators;
public ReedSolomonEncoder(GenericGF field)
{
this.field = field;
this.cachedGenerators = new List<GenericGFPoly>();
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);
}
}
}

+ 0
- 255
shadowsocks-csharp/3rd/zxing/qrcode/QRCodeReader.cs View File

@@ -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
{
/// <summary>
/// This implementation can detect and decode QR Codes in an image.
/// <author>Sean Owen</author>
/// </summary>
public class QRCodeReader
{
private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0];
private readonly Decoder decoder = new Decoder();
/// <summary>
/// Gets the decoder.
/// </summary>
/// <returns></returns>
protected Decoder getDecoder()
{
return decoder;
}
/// <summary>
/// Locates and decodes a QR code in an image.
///
/// <returns>a String representing the content encoded by the QR code</returns>
/// </summary>
public Result decode(BinaryBitmap image)
{
return decode(image, null);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="image">image of barcode to decode</param>
/// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
/// to arbitrary data. The
/// meaning of the data depends upon the hint type. The implementation may or may not do
/// anything with these hints.</param>
/// <returns>
/// String which the barcode encodes
/// </returns>
public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> 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;
}
/// <summary>
/// Resets any internal state the implementation has after a decode, to prepare it
/// for reuse.
/// </summary>
public void reset()
{
// do nothing
}
/// <summary>
/// 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.
///
/// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" />
/// </summary>
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;
}
}
}

+ 0
- 281
shadowsocks-csharp/3rd/zxing/qrcode/decoder/BitMatrixParser.cs View File

@@ -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
{
/// <author>Sean Owen</author>
sealed class BitMatrixParser
{
private readonly BitMatrix bitMatrix;
private Version parsedVersion;
private FormatInformation parsedFormatInfo;
private bool mirrored;
/// <param name="bitMatrix">{@link BitMatrix} to parse</param>
/// <throws>ReaderException if dimension is not >= 21 and 1 mod 4</throws>
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;
}
/// <summary> <p>Reads format information from one of its two locations within the QR Code.</p>
///
/// </summary>
/// <returns> {@link FormatInformation} encapsulating the QR Code's format info
/// </returns>
/// <throws> ReaderException if both format information locations cannot be parsed as </throws>
/// <summary> the valid encoding of format information
/// </summary>
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;
}
/// <summary> <p>Reads version information from one of its two locations within the QR Code.</p>
///
/// </summary>
/// <returns> {@link Version} encapsulating the QR Code's version
/// </returns>
/// <throws> ReaderException if both version information locations cannot be parsed as </throws>
/// <summary> the valid encoding of version information
/// </summary>
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;
}
/// <summary> <p>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.</p>
///
/// </summary>
/// <returns> bytes encoded within the QR Code
/// </returns>
/// <throws> ReaderException if the exact number of bytes expected is not read </throws>
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);
}
}
}
}
}
}

+ 0
- 146
shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataBlock.cs View File

@@ -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
{
/// <summary> <p>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.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
internal sealed class DataBlock
{
private readonly int numDataCodewords;
private readonly byte[] codewords;
private DataBlock(int numDataCodewords, byte[] codewords)
{
this.numDataCodewords = numDataCodewords;
this.codewords = codewords;
}
/// <summary> <p>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.</p>
///
/// </summary>
/// <param name="rawCodewords">bytes as read directly from the QR Code
/// </param>
/// <param name="version">version of the QR Code
/// </param>
/// <param name="ecLevel">error-correction level of the QR Code
/// </param>
/// <returns> {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the
/// QR Code
/// </returns>
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;
}
}
}
}

+ 0
- 165
shadowsocks-csharp/3rd/zxing/qrcode/decoder/DataMask.cs View File

@@ -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
{
/// <summary> <p>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.</p>
///
/// <p>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.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
abstract class DataMask
{
/// <summary> See ISO 18004:2006 6.8.1</summary>
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()
{
}
/// <summary> <p>Implementations of this method reverse the data masking process applied to a QR Code and
/// make its bits ready to read.</p>
///
/// </summary>
/// <param name="bits">representation of QR Code bits
/// </param>
/// <param name="dimension">dimension of QR Code, represented by bits, being unmasked
/// </param>
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);
/// <param name="reference">a value between 0 and 7 indicating one of the eight possible
/// data mask patterns a QR Code may use
/// </param>
/// <returns> {@link DataMask} encapsulating the data mask pattern
/// </returns>
internal static DataMask forReference(int reference)
{
if (reference < 0 || reference > 7)
{
throw new System.ArgumentException();
}
return DATA_MASKS[reference];
}
/// <summary> 000: mask bits for which (x + y) mod 2 == 0</summary>
private sealed class DataMask000 : DataMask
{
internal override bool isMasked(int i, int j)
{
return ((i + j) & 0x01) == 0;
}
}
/// <summary> 001: mask bits for which x mod 2 == 0</summary>
private sealed class DataMask001 : DataMask
{
internal override bool isMasked(int i, int j)
{
return (i & 0x01) == 0;
}
}
/// <summary> 010: mask bits for which y mod 3 == 0</summary>
private sealed class DataMask010 : DataMask
{
internal override bool isMasked(int i, int j)
{
return j % 3 == 0;
}
}
/// <summary> 011: mask bits for which (x + y) mod 3 == 0</summary>
private sealed class DataMask011 : DataMask
{
internal override bool isMasked(int i, int j)
{
return (i + j) % 3 == 0;
}
}
/// <summary> 100: mask bits for which (x/2 + y/3) mod 2 == 0</summary>
private sealed class DataMask100 : DataMask
{
internal override bool isMasked(int i, int j)
{
return ((((int)((uint)i >> 1)) + (j / 3)) & 0x01) == 0;
}
}
/// <summary> 101: mask bits for which xy mod 2 + xy mod 3 == 0</summary>
private sealed class DataMask101 : DataMask
{
internal override bool isMasked(int i, int j)
{
int temp = i * j;
return (temp & 0x01) + (temp % 3) == 0;
}
}
/// <summary> 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0</summary>
private sealed class DataMask110 : DataMask
{
internal override bool isMasked(int i, int j)
{
int temp = i * j;
return (((temp & 0x01) + (temp % 3)) & 0x01) == 0;
}
}
/// <summary> 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0</summary>
private sealed class DataMask111 : DataMask
{
internal override bool isMasked(int i, int j)
{
return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0;
}
}
}
}

+ 0
- 514
shadowsocks-csharp/3rd/zxing/qrcode/decoder/DecodedBitStreamParser.cs View File

@@ -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
{
/// <summary> <p>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.</p>
///
/// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
/// <author>Sean Owen</author>
/// </summary>
internal static class DecodedBitStreamParser
{
/// <summary>
/// See ISO 18004:2006, 6.4.4 Table 5
/// </summary>
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<DecodeHintType, object> hints)
{
var bits = new BitSource(bytes);
var result = new StringBuilder(50);
var byteSegments = new List<byte[]>(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);
}
/// <summary>
/// See specification GBT 18284-2000
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="result">The result.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
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<byte[]> byteSegments,
IDictionary<DecodeHintType, object> 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);
}
}
}

+ 0
- 195
shadowsocks-csharp/3rd/zxing/qrcode/decoder/Decoder.cs View File

@@ -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
{
/// <summary>
/// <p>The main class which implements QR Code decoding -- as opposed to locating and extracting
/// the QR Code from an image.</p>
/// </summary>
/// <author>
/// Sean Owen
/// </author>
public sealed class Decoder
{
private readonly ReedSolomonDecoder rsDecoder;
/// <summary>
/// Initializes a new instance of the <see cref="Decoder"/> class.
/// </summary>
public Decoder()
{
rsDecoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256);
}
/// <summary>
/// <p>Convenience method that can decode a QR Code represented as a 2D array of booleans.
/// "true" is taken to mean a black module.</p>
/// </summary>
/// <param name="image">booleans representing white/black QR Code modules</param>
/// <param name="hints">The hints.</param>
/// <returns>
/// text and bytes encoded within the QR Code
/// </returns>
public DecoderResult decode(bool[][] image, IDictionary<DecodeHintType, object> 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);
}
/// <summary>
/// <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
/// </summary>
/// <param name="bits">booleans representing white/black QR Code modules</param>
/// <param name="hints">The hints.</param>
/// <returns>
/// text and bytes encoded within the QR Code
/// </returns>
public DecoderResult decode(BitMatrix bits, IDictionary<DecodeHintType, object> 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<DecodeHintType, object> 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);
}
/// <summary>
/// <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
/// correct the errors in-place using Reed-Solomon error correction.</p>
/// </summary>
/// <param name="codewordBytes">data and error correction codewords</param>
/// <param name="numDataCodewords">number of codewords that are data bytes</param>
/// <returns></returns>
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;
}
}
}

+ 0
- 109
shadowsocks-csharp/3rd/zxing/qrcode/decoder/ErrorCorrectionLevel.cs View File

@@ -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
{
/// <summary>
/// <p>See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels
/// defined by the QR code standard.</p>
/// </summary>
/// <author>Sean Owen</author>
public sealed class ErrorCorrectionLevel
{
/// <summary> L = ~7% correction</summary>
public static readonly ErrorCorrectionLevel L = new ErrorCorrectionLevel(0, 0x01, "L");
/// <summary> M = ~15% correction</summary>
public static readonly ErrorCorrectionLevel M = new ErrorCorrectionLevel(1, 0x00, "M");
/// <summary> Q = ~25% correction</summary>
public static readonly ErrorCorrectionLevel Q = new ErrorCorrectionLevel(2, 0x03, "Q");
/// <summary> H = ~30% correction</summary>
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;
}
/// <summary>
/// Gets the bits.
/// </summary>
public int Bits
{
get
{
return bits;
}
}
/// <summary>
/// Gets the name.
/// </summary>
public String Name
{
get
{
return name;
}
}
private readonly int ordinal_Renamed_Field;
private readonly String name;
/// <summary>
/// Ordinals this instance.
/// </summary>
/// <returns></returns>
public int ordinal()
{
return ordinal_Renamed_Field;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override String ToString()
{
return name;
}
/// <summary>
/// Fors the bits.
/// </summary>
/// <param name="bits">int containing the two bits encoding a QR Code's error correction level</param>
/// <returns>
/// <see cref="ErrorCorrectionLevel"/> representing the encoded error correction level
/// </returns>
public static ErrorCorrectionLevel forBits(int bits)
{
if (bits < 0 || bits >= FOR_BITS.Length)
{
throw new ArgumentException();
}
return FOR_BITS[bits];
}
}
}

+ 0
- 197
shadowsocks-csharp/3rd/zxing/qrcode/decoder/FormatInformation.cs View File

@@ -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
{
/// <summary> <p>Encapsulates a QR Code's format information, including the data mask used and
/// error correction level.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
/// <seealso cref="DataMask">
/// </seealso>
/// <seealso cref="ErrorCorrectionLevel">
/// </seealso>
sealed class FormatInformation
{
private const int FORMAT_INFO_MASK_QR = 0x5412;
/// <summary> See ISO 18004:2006, Annex C, Table C.1</summary>
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 }
};
/// <summary> Offset i holds the number of 1 bits in the binary representation of i</summary>
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)];
}
/// <summary>
/// Decodes the format information.
/// </summary>
/// <param name="maskedFormatInfo1">format info indicator, with mask still applied</param>
/// <param name="maskedFormatInfo2">The masked format info2.</param>
/// <returns>
/// information about the format it specifies, or <code>null</code>
/// if doesn't seem to match any known pattern
/// </returns>
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;
}
}
}

+ 0
- 179
shadowsocks-csharp/3rd/zxing/qrcode/decoder/Mode.cs View File

@@ -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
{
/// <summary>
/// <p>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.</p>
/// </summary>
/// <author>Sean Owen</author>
public sealed class Mode
{
/// <summary>
/// Gets the name.
/// </summary>
public String Name
{
get
{
return name;
}
}
// No, we can't use an enum here. J2ME doesn't support it.
/// <summary>
///
/// </summary>
public static readonly Mode TERMINATOR = new Mode(new int[] { 0, 0, 0 }, 0x00, "TERMINATOR"); // Not really a mode...
/// <summary>
///
/// </summary>
public static readonly Mode NUMERIC = new Mode(new int[] { 10, 12, 14 }, 0x01, "NUMERIC");
/// <summary>
///
/// </summary>
public static readonly Mode ALPHANUMERIC = new Mode(new int[] { 9, 11, 13 }, 0x02, "ALPHANUMERIC");
/// <summary>
///
/// </summary>
public static readonly Mode STRUCTURED_APPEND = new Mode(new int[] { 0, 0, 0 }, 0x03, "STRUCTURED_APPEND"); // Not supported
/// <summary>
///
/// </summary>
public static readonly Mode BYTE = new Mode(new int[] { 8, 16, 16 }, 0x04, "BYTE");
/// <summary>
///
/// </summary>
public static readonly Mode ECI = new Mode(null, 0x07, "ECI"); // character counts don't apply
/// <summary>
///
/// </summary>
public static readonly Mode KANJI = new Mode(new int[] { 8, 10, 12 }, 0x08, "KANJI");
/// <summary>
///
/// </summary>
public static readonly Mode FNC1_FIRST_POSITION = new Mode(null, 0x05, "FNC1_FIRST_POSITION");
/// <summary>
///
/// </summary>
public static readonly Mode FNC1_SECOND_POSITION = new Mode(null, 0x09, "FNC1_SECOND_POSITION");
/// <summary>See GBT 18284-2000; "Hanzi" is a transliteration of this mode name.</summary>
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;
}
/// <summary>
/// Fors the bits.
/// </summary>
/// <param name="bits">four bits encoding a QR Code data mode</param>
/// <returns>
/// <see cref="Mode"/> encoded by these bits
/// </returns>
/// <exception cref="ArgumentException">if bits do not correspond to a known mode</exception>
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();
}
}
/// <param name="version">version in question
/// </param>
/// <returns> 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}
/// </returns>
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];
}
/// <summary>
/// Gets the bits.
/// </summary>
public int Bits
{
get
{
return bits;
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override String ToString()
{
return name;
}
}
}

+ 0
- 60
shadowsocks-csharp/3rd/zxing/qrcode/decoder/QRCodeDecoderMetaData.cs View File

@@ -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
{
/// <summary>
/// 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.
/// </summary>
public sealed class QRCodeDecoderMetaData
{
private readonly bool mirrored;
/// <summary>
/// Initializes a new instance of the <see cref="QRCodeDecoderMetaData"/> class.
/// </summary>
/// <param name="mirrored">if set to <c>true</c> [mirrored].</param>
public QRCodeDecoderMetaData(bool mirrored)
{
this.mirrored = mirrored;
}
/// <summary>
/// true if the QR Code was mirrored.
/// </summary>
public bool IsMirrored
{
get { return mirrored; }
}
/// <summary>
/// Apply the result points' order correction due to mirroring.
/// </summary>
/// <param name="points">Array of points to apply mirror correction to.</param>
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.
}
}
}

+ 0
- 424
shadowsocks-csharp/3rd/zxing/qrcode/decoder/Version.cs View File

@@ -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
{
/// <summary>
/// See ISO 18004:2006 Annex D
/// </summary>
/// <author>Sean Owen</author>
public sealed class Version
{
/// <summary> See ISO 18004:2006 Annex D.
/// Element i represents the raw version bits that specify version i + 7
/// </summary>
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;
}
/// <summary>
/// Gets the version number.
/// </summary>
public int VersionNumber
{
get
{
return versionNumber;
}
}
/// <summary>
/// Gets the alignment pattern centers.
/// </summary>
public int[] AlignmentPatternCenters
{
get
{
return alignmentPatternCenters;
}
}
/// <summary>
/// Gets the total codewords.
/// </summary>
public int TotalCodewords
{
get
{
return totalCodewords;
}
}
/// <summary>
/// Gets the dimension for version.
/// </summary>
public int DimensionForVersion
{
get
{
return 17 + 4 * versionNumber;
}
}
/// <summary>
/// Gets the EC blocks for level.
/// </summary>
/// <param name="ecLevel">The ec level.</param>
/// <returns></returns>
public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel)
{
return ecBlocks[ecLevel.ordinal()];
}
/// <summary> <p>Deduces version information purely from QR Code dimensions.</p>
///
/// </summary>
/// <param name="dimension">dimension in modules
/// </param>
/// <returns><see cref="Version" /> for a QR Code of that dimension or null</returns>
public static Version getProvisionalVersionForDimension(int dimension)
{
if (dimension % 4 != 1)
{
return null;
}
try
{
return getVersionForNumber((dimension - 17) >> 2);
}
catch (ArgumentException)
{
return null;
}
}
/// <summary>
/// Gets the version for number.
/// </summary>
/// <param name="versionNumber">The version number.</param>
/// <returns></returns>
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;
}
/// <summary> See ISO 18004:2006 Annex E</summary>
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;
}
/// <summary> <p>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.</p>
/// </summary>
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;
}
/// <summary>
/// Gets the EC codewords per block.
/// </summary>
public int ECCodewordsPerBlock
{
get
{
return ecCodewordsPerBlock;
}
}
/// <summary>
/// Gets the num blocks.
/// </summary>
public int NumBlocks
{
get
{
int total = 0;
foreach (var ecBlock in ecBlocks)
{
total += ecBlock.Count;
}
return total;
}
}
/// <summary>
/// Gets the total EC codewords.
/// </summary>
public int TotalECCodewords
{
get
{
return ecCodewordsPerBlock * NumBlocks;
}
}
/// <summary>
/// Gets the EC blocks.
/// </summary>
/// <returns></returns>
public ECB[] getECBlocks()
{
return ecBlocks;
}
}
/// <summary> <p>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.</p>
/// </summary>
public sealed class ECB
{
private readonly int count;
private readonly int dataCodewords;
internal ECB(int count, int dataCodewords)
{
this.count = count;
this.dataCodewords = dataCodewords;
}
/// <summary>
/// Gets the count.
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// Gets the data codewords.
/// </summary>
public int DataCodewords
{
get
{
return dataCodewords;
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override String ToString()
{
return Convert.ToString(versionNumber);
}
/// <summary> See ISO 18004:2006 6.5.1 Table 9</summary>
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)))};
}
}
}

+ 0
- 68
shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPattern.cs View File

@@ -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
{
/// <summary> <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
/// all but the simplest QR Codes.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public sealed class AlignmentPattern : ResultPoint
{
private float estimatedModuleSize;
internal AlignmentPattern(float posX, float posY, float estimatedModuleSize)
: base(posX, posY)
{
this.estimatedModuleSize = estimatedModuleSize;
}
/// <summary> <p>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.</p>
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="i">The i.</param>
/// <param name="j">The j.</param>
/// <param name="newModuleSize">New size of the module.</param>
/// <returns></returns>
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);
}
}
}

+ 0
- 324
shadowsocks-csharp/3rd/zxing/qrcode/detector/AlignmentPatternFinder.cs View File

@@ -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
{
/// <summary> <p>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.</p>
///
/// <p>At the moment this only looks for the bottom-right alignment pattern.</p>
///
/// <p>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.</p>
///
/// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
sealed class AlignmentPatternFinder
{
private readonly BitMatrix image;
private readonly IList<AlignmentPattern> 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;
/// <summary> <p>Creates a finder that will look in a portion of the whole image.</p>
///
/// </summary>
/// <param name="image">image to search
/// </param>
/// <param name="startX">left column from which to start searching
/// </param>
/// <param name="startY">top row from which to start searching
/// </param>
/// <param name="width">width of region to search
/// </param>
/// <param name="height">height of region to search
/// </param>
/// <param name="moduleSize">estimated module size so far
/// </param>
internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback)
{
this.image = image;
this.possibleCenters = new List<AlignmentPattern>(5);
this.startX = startX;
this.startY = startY;
this.width = width;
this.height = height;
this.moduleSize = moduleSize;
this.crossCheckStateCount = new int[3];
this.resultPointCallback = resultPointCallback;
}
/// <summary> <p>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.</p>
///
/// </summary>
/// <returns> {@link AlignmentPattern} if found
/// </returns>
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;
}
/// <summary> 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.
/// </summary>
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;
}
/// <param name="stateCount">count of black/white/black pixels just read
/// </param>
/// <returns> 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
/// </returns>
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;
}
/// <summary>
/// <p>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.</p>
/// </summary>
/// <param name="startI">row where an alignment pattern was detected</param>
/// <param name="centerJ">center of the section that appears to cross an alignment pattern</param>
/// <param name="maxCount">maximum reasonable number of modules that should be
/// observed in any reading state, based on the results of the horizontal scan</param>
/// <param name="originalStateCountTotal">The original state count total.</param>
/// <returns>
/// vertical center of alignment pattern, or null if not found
/// </returns>
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;
}
/// <summary> <p>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.</p>
///
/// </summary>
/// <param name="stateCount">reading state module counts from horizontal scan
/// </param>
/// <param name="i">row where alignment pattern may be found
/// </param>
/// <param name="j">end of possible alignment pattern in row
/// </param>
/// <returns> {@link AlignmentPattern} if we have found the same pattern twice, or null if not
/// </returns>
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;
}
}
}

+ 0
- 429
shadowsocks-csharp/3rd/zxing/qrcode/detector/Detector.cs View File

@@ -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
{
/// <summary>
/// <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
/// is rotated or skewed, or partially obscured.</p>
/// </summary>
/// <author>Sean Owen</author>
public class Detector
{
private readonly BitMatrix image;
private ResultPointCallback resultPointCallback;
/// <summary>
/// Initializes a new instance of the <see cref="Detector"/> class.
/// </summary>
/// <param name="image">The image.</param>
public Detector(BitMatrix image)
{
this.image = image;
}
/// <summary>
/// Gets the image.
/// </summary>
virtual protected internal BitMatrix Image
{
get
{
return image;
}
}
/// <summary>
/// Gets the result point callback.
/// </summary>
virtual protected internal ResultPointCallback ResultPointCallback
{
get
{
return resultPointCallback;
}
}
/// <summary>
/// <p>Detects a QR Code in an image, simply.</p>
/// </summary>
/// <returns>
/// <see cref="DetectorResult"/> encapsulating results of detecting a QR Code
/// </returns>
public virtual DetectorResult detect()
{
return detect(null);
}
/// <summary>
/// <p>Detects a QR Code in an image, simply.</p>
/// </summary>
/// <param name="hints">optional hints to detector</param>
/// <returns>
/// <see cref="DetectorResult"/> encapsulating results of detecting a QR Code
/// </returns>
public virtual DetectorResult detect(IDictionary<DecodeHintType, object> 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);
}
/// <summary>
/// Processes the finder pattern info.
/// </summary>
/// <param name="info">The info.</param>
/// <returns></returns>
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);
}
/// <summary> <p>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.</p>
/// </summary>
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;
}
/// <summary> <p>Computes an average estimated module size based on estimated derived from the positions
/// of the three finder patterns.</p>
/// </summary>
protected internal virtual float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft)
{
// Take the average
return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
}
/// <summary> <p>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.</p>
/// </summary>
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;
}
/// <summary> 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.
/// </summary>
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
}
/// <summary> <p>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.</p>
///
/// <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
/// may be skewed or rotated.</p>
/// </summary>
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;
}
/// <summary>
/// <p>Attempts to locate an alignment pattern in a limited region of the image, which is
/// guessed to contain it. This method uses {@link AlignmentPattern}.</p>
/// </summary>
/// <param name="overallEstModuleSize">estimated module size so far</param>
/// <param name="estAlignmentX">x coordinate of center of area probably containing alignment pattern</param>
/// <param name="estAlignmentY">y coordinate of above</param>
/// <param name="allowanceFactor">number of pixels in all directions to search from the center</param>
/// <returns>
/// <see cref="AlignmentPattern"/> if found, or null otherwise
/// </returns>
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();
}
}
}

+ 0
- 107
shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPattern.cs View File

@@ -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
{
/// <summary>
/// <p>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.</p>
/// </summary>
/// <author>Sean Owen</author>
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;
}
/// <summary>
/// Gets the size of the estimated module.
/// </summary>
/// <value>
/// The size of the estimated module.
/// </value>
public float EstimatedModuleSize
{
get
{
return estimatedModuleSize;
}
}
internal int Count
{
get
{
return count;
}
}
/*
internal void incrementCount()
{
this.count++;
}
*/
/// <summary> <p>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.</p>
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="i">The i.</param>
/// <param name="j">The j.</param>
/// <param name="newModuleSize">New size of the module.</param>
/// <returns></returns>
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);
}
}
}

+ 0
- 808
shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternFinder.cs View File

@@ -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
{
/// <summary>
/// <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
/// markers at three corners of a QR Code.</p>
///
/// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
/// </summary>
/// <author>Sean Owen</author>
public class FinderPatternFinder
{
private const int CENTER_QUORUM = 2;
/// <summary>
/// 1 pixel/module times 3 modules/center
/// </summary>
protected internal const int MIN_SKIP = 3;
/// <summary>
/// support up to version 10 for mobile clients
/// </summary>
protected internal const int MAX_MODULES = 57;
private const int INTEGER_MATH_SHIFT = 8;
private readonly BitMatrix image;
private List<FinderPattern> possibleCenters;
private bool hasSkipped;
private readonly int[] crossCheckStateCount;
private readonly ResultPointCallback resultPointCallback;
/// <summary>
/// <p>Creates a finder that will search the image for three finder patterns.</p>
/// </summary>
/// <param name="image">image to search</param>
public FinderPatternFinder(BitMatrix image)
: this(image, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FinderPatternFinder"/> class.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="resultPointCallback">The result point callback.</param>
public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback)
{
this.image = image;
this.possibleCenters = new List<FinderPattern>();
this.crossCheckStateCount = new int[5];
this.resultPointCallback = resultPointCallback;
}
/// <summary>
/// Gets the image.
/// </summary>
virtual protected internal BitMatrix Image
{
get
{
return image;
}
}
/// <summary>
/// Gets the possible centers.
/// </summary>
virtual protected internal List<FinderPattern> PossibleCenters
{
get
{
return possibleCenters;
}
}
internal virtual FinderPatternInfo find(IDictionary<DecodeHintType, object> 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);
}
/// <summary> 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.
/// </summary>
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;
}
/// <param name="stateCount">count of black/white/black/white/black pixels just read
/// </param>
/// <returns> 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
/// </returns>
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;
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="startI">row where a finder pattern was detected</param>
/// <param name="centerJ">center of the section that appears to cross a finder pattern</param>
/// <param name="maxCount">maximum reasonable number of modules that should be observed in any reading state, based on the results of the horizontal scan</param>
/// <param name="originalStateCountTotal">The original state count total.</param>
/// <returns>true if proportions are withing expected limits</returns>
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);
}
/// <summary>
/// <p>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.</p>
/// </summary>
/// <param name="startI">row where a finder pattern was detected</param>
/// <param name="centerJ">center of the section that appears to cross a finder pattern</param>
/// <param name="maxCount">maximum reasonable number of modules that should be
/// observed in any reading state, based on the results of the horizontal scan</param>
/// <param name="originalStateCountTotal">The original state count total.</param>
/// <returns>
/// vertical center of finder pattern, or null if not found
/// </returns>
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;
}
/// <summary> <p>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.</p>
/// </summary>
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;
}
/// <summary>
/// <p>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.</p>
/// 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
/// </summary>
/// <param name="stateCount">reading state module counts from horizontal scan</param>
/// <param name="i">row where finder pattern may be found</param>
/// <param name="j">end of possible finder pattern in row</param>
/// <param name="pureBarcode">if set to <c>true</c> [pure barcode].</param>
/// <returns>
/// true if a finder pattern candidate was found this time
/// </returns>
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;
}
/// <returns> 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.
/// </returns>
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;
}
/// <returns> 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"
/// </returns>
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;
}
/// <returns> 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
/// </returns>
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]
};
}
/// <summary>
/// Orders by furthest from average
/// </summary>
private sealed class FurthestFromAverageComparator : IComparer<FinderPattern>
{
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;
}
}
/// <summary> <p>Orders by {@link FinderPattern#getCount()}, descending.</p></summary>
private sealed class CenterComparator : IComparer<FinderPattern>
{
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;
}
}
}
}

+ 0
- 74
shadowsocks-csharp/3rd/zxing/qrcode/detector/FinderPatternInfo.cs View File

@@ -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
{
/// <summary>
/// <p>Encapsulates information about finder patterns in an image, including the location of
/// the three finder patterns, and their estimated module size.</p>
/// </summary>
/// <author>Sean Owen</author>
public sealed class FinderPatternInfo
{
private readonly FinderPattern bottomLeft;
private readonly FinderPattern topLeft;
private readonly FinderPattern topRight;
/// <summary>
/// Initializes a new instance of the <see cref="FinderPatternInfo"/> class.
/// </summary>
/// <param name="patternCenters">The pattern centers.</param>
public FinderPatternInfo(FinderPattern[] patternCenters)
{
this.bottomLeft = patternCenters[0];
this.topLeft = patternCenters[1];
this.topRight = patternCenters[2];
}
/// <summary>
/// Gets the bottom left.
/// </summary>
public FinderPattern BottomLeft
{
get
{
return bottomLeft;
}
}
/// <summary>
/// Gets the top left.
/// </summary>
public FinderPattern TopLeft
{
get
{
return topLeft;
}
}
/// <summary>
/// Gets the top right.
/// </summary>
public FinderPattern TopRight
{
get
{
return topRight;
}
}
}
}

+ 0
- 40
shadowsocks-csharp/3rd/zxing/qrcode/encoder/BlockPair.cs View File

@@ -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; }
}
}
}

+ 0
- 148
shadowsocks-csharp/3rd/zxing/qrcode/encoder/ByteMatrix.cs View File

@@ -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
{
/// <summary>
/// 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.
/// </summary>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
public sealed class ByteMatrix
{
private readonly byte[][] bytes;
private readonly int width;
private readonly int height;
/// <summary>
/// Initializes a new instance of the <see cref="ByteMatrix"/> class.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
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;
}
/// <summary>
/// Gets the height.
/// </summary>
public int Height
{
get { return height; }
}
/// <summary>
/// Gets the width.
/// </summary>
public int Width
{
get { return width; }
}
/// <summary>
/// Gets or sets the <see cref="System.Int32"/> with the specified x.
/// </summary>
public int this[int x, int y]
{
get { return bytes[y][x]; }
set { bytes[y][x] = (byte)value; }
}
/// <summary>
/// an internal representation as bytes, in row-major order. array[y][x] represents point (x,y)
/// </summary>
public byte[][] Array
{
get { return bytes; }
}
/// <summary>
/// Sets the specified x.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="value">The value.</param>
public void set(int x, int y, byte value)
{
bytes[y][x] = value;
}
/// <summary>
/// Sets the specified x.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="value">if set to <c>true</c> [value].</param>
public void set(int x, int y, bool value)
{
bytes[y][x] = (byte)(value ? 1 : 0);
}
/// <summary>
/// Clears the specified value.
/// </summary>
/// <param name="value">The value.</param>
public void clear(byte value)
{
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
bytes[y][x] = value;
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
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();
}
}
}

+ 0
- 596
shadowsocks-csharp/3rd/zxing/qrcode/encoder/Encoder.cs View File

@@ -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
{
/// <summary>
/// </summary>
/// <author>satorux@google.com (Satoru Takabayashi) - creator</author>
/// <author>dswitkin@google.com (Daniel Switkin) - ported from C++</author>
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);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="ecLevel">The ec level.</param>
public static QRCode encode(String content, ErrorCorrectionLevel ecLevel)
{
return encode(content, ecLevel, null);
}
/// <summary>
/// Encodes the specified content.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="ecLevel">The ec level.</param>
/// <param name="hints">The hints.</param>
/// <returns></returns>
public static QRCode encode(String content,
ErrorCorrectionLevel ecLevel,
IDictionary<EncodeHintType, object> 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;
}
/// <summary>
/// Gets the alphanumeric code.
/// </summary>
/// <param name="code">The code.</param>
/// <returns>the code point of the table used in alphanumeric mode or
/// -1 if there is no corresponding code in the table.</returns>
internal static int getAlphanumericCode(int code)
{
if (code < ALPHANUMERIC_TABLE.Length)
{
return ALPHANUMERIC_TABLE[code];
}
return -1;
}
/// <summary>
/// Chooses the mode.
/// </summary>
/// <param name="content">The content.</param>
/// <returns></returns>
public static Mode chooseMode(String content)
{
return chooseMode(content, null);
}
/// <summary>
/// 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}.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
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");
}
/// <summary>
/// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
/// </summary>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="bits">The bits.</param>
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");
}
}
/// <summary>
/// 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)
/// </summary>
/// <param name="numTotalBytes">The num total bytes.</param>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="numRSBlocks">The num RS blocks.</param>
/// <param name="blockID">The block ID.</param>
/// <param name="numDataBytesInBlock">The num data bytes in block.</param>
/// <param name="numECBytesInBlock">The num EC bytes in block.</param>
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;
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="numTotalBytes">The num total bytes.</param>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="numRSBlocks">The num RS blocks.</param>
/// <returns></returns>
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<BlockPair>(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;
}
/// <summary>
/// Append mode info. On success, store the result in "bits".
/// </summary>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
internal static void appendModeInfo(Mode mode, BitArray bits)
{
bits.appendBits(mode.Bits, 4);
}
/// <summary>
/// Append length info. On success, store the result in "bits".
/// </summary>
/// <param name="numLetters">The num letters.</param>
/// <param name="version">The version.</param>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
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);
}
/// <summary>
/// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
/// </summary>
/// <param name="content">The content.</param>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
/// <param name="encoding">The encoding.</param>
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);
}
}
}
}

+ 0
- 271
shadowsocks-csharp/3rd/zxing/qrcode/encoder/MaskUtil.cs View File

@@ -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
{
/// <summary>
///
/// </summary>
/// <author>Satoru Takabayashi</author>
/// <author>Daniel Switkin</author>
/// <author>Sean Owen</author>
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;
/// <summary>
/// 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.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule1(ByteMatrix matrix)
{
return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
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;
}
/// <summary>
/// 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).
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
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;
}
/// <summary>
/// Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
/// pattern conditions.
/// </summary>
/// <param name="maskPattern">The mask pattern.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns></returns>
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;
}
/// <summary>
/// Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both
/// vertical and horizontal orders respectively.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="isHorizontal">if set to <c>true</c> [is horizontal].</param>
/// <returns></returns>
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;
}
}
}

+ 0
- 600
shadowsocks-csharp/3rd/zxing/qrcode/encoder/MatrixUtil.cs View File

@@ -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
{
/// <summary>
///
/// </summary>
/// <author>
/// satorux@google.com (Satoru Takabayashi) - creator
/// </author>
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;
/// <summary>
/// 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.
/// </summary>
/// <param name="matrix">The matrix.</param>
public static void clearMatrix(ByteMatrix matrix)
{
matrix.clear(2);
}
/// <summary>
/// Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
/// success, store the result in "matrix" and return true.
/// </summary>
/// <param name="dataBits">The data bits.</param>
/// <param name="ecLevel">The ec level.</param>
/// <param name="version">The version.</param>
/// <param name="maskPattern">The mask pattern.</param>
/// <param name="matrix">The matrix.</param>
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);
}
/// <summary>
/// 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
/// </summary>
/// <param name="version">The version.</param>
/// <param name="matrix">The matrix.</param>
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);
}
/// <summary>
/// Embed type information. On success, modify the matrix.
/// </summary>
/// <param name="ecLevel">The ec level.</param>
/// <param name="maskPattern">The mask pattern.</param>
/// <param name="matrix">The matrix.</param>
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;
}
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="matrix">The matrix.</param>
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;
}
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="dataBits">The data bits.</param>
/// <param name="maskPattern">The mask pattern.</param>
/// <param name="matrix">The matrix.</param>
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);
}
}
/// <summary>
/// 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
/// </summary>
/// <param name="value_Renamed">The value_ renamed.</param>
/// <returns></returns>
public static int findMSBSet(int value_Renamed)
{
int numDigits = 0;
while (value_Renamed != 0)
{
value_Renamed = (int)((uint)value_Renamed >> 1);
++numDigits;
}
return numDigits;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="poly">The poly.</param>
/// <returns></returns>
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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="ecLevel">The ec level.</param>
/// <param name="maskPattern">The mask pattern.</param>
/// <param name="bits">The bits.</param>
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="bits">The bits.</param>
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);
}
}
/// <summary>
/// Check if "value" is empty.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// <c>true</c> if the specified value is empty; otherwise, <c>false</c>.
/// </returns>
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;
}
}
}
/// <summary>
/// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
/// </summary>
/// <param name="matrix">The matrix.</param>
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;
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="xStart">The x start.</param>
/// <param name="yStart">The y start.</param>
/// <param name="matrix">The matrix.</param>
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];
}
}
}
/// <summary>
/// Embed position detection patterns and surrounding vertical/horizontal separators.
/// </summary>
/// <param name="matrix">The matrix.</param>
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);
}
/// <summary>
/// Embed position adjustment patterns if need be.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="matrix">The matrix.</param>
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);
}
}
}
}
}
}

+ 0
- 125
shadowsocks-csharp/3rd/zxing/qrcode/encoder/QRCode.cs View File

@@ -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
{
/// <author>satorux@google.com (Satoru Takabayashi) - creator</author>
/// <author>dswitkin@google.com (Daniel Switkin) - ported from C++</author>
public sealed class QRCode
{
/// <summary>
///
/// </summary>
public static int NUM_MASK_PATTERNS = 8;
/// <summary>
/// Initializes a new instance of the <see cref="QRCode"/> class.
/// </summary>
public QRCode()
{
MaskPattern = -1;
}
/// <summary>
/// Gets or sets the mode.
/// </summary>
/// <value>
/// The mode.
/// </value>
public Mode Mode { get; set; }
/// <summary>
/// Gets or sets the EC level.
/// </summary>
/// <value>
/// The EC level.
/// </value>
public ErrorCorrectionLevel ECLevel { get; set; }
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>
/// The version.
/// </value>
public Version Version { get; set; }
/// <summary>
/// Gets or sets the mask pattern.
/// </summary>
/// <value>
/// The mask pattern.
/// </value>
public int MaskPattern { get; set; }
/// <summary>
/// Gets or sets the matrix.
/// </summary>
/// <value>
/// The matrix.
/// </value>
public ByteMatrix Matrix { get; set; }
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
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();
}
/// <summary>
/// Check if "mask_pattern" is valid.
/// </summary>
/// <param name="maskPattern">The mask pattern.</param>
/// <returns>
/// <c>true</c> if [is valid mask pattern] [the specified mask pattern]; otherwise, <c>false</c>.
/// </returns>
public static bool isValidMaskPattern(int maskPattern)
{
return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS;
}
}
}

+ 0
- 55
shadowsocks-csharp/Controller/AutoStartup.cs View File

@@ -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;
}
}
}
}

+ 0
- 55
shadowsocks-csharp/Controller/FileManager.cs View File

@@ -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();
}
}
}

+ 0
- 100
shadowsocks-csharp/Controller/GfwListUpdater.cs View File

@@ -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<ResultEventArgs> 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<string> 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<string> 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<string> valid_lines = new List<string>(lines.Length);
foreach (string line in lines)
{
if (line.StartsWith("!") || line.StartsWith("["))
continue;
valid_lines.Add(line);
}
return valid_lines;
}
}
}

+ 0
- 42
shadowsocks-csharp/Controller/I18N.cs View File

@@ -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<string, string> Strings;
static I18N()
{
Strings = new Dictionary<string, string>();
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;
}
}
}
}

+ 0
- 163
shadowsocks-csharp/Controller/Listener.cs View File

@@ -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<Service> _services;
public Listener(IList<Service> 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();
}
}
}
}

+ 0
- 399
shadowsocks-csharp/Controller/Local.cs View File

@@ -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();
}
}
}
}

+ 0
- 89
shadowsocks-csharp/Controller/Logging.cs View File

@@ -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);
}
}
}

+ 0
- 194
shadowsocks-csharp/Controller/PACServer.cs View File

@@ -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 + ";";
}
}
}

+ 0
- 126
shadowsocks-csharp/Controller/PolipoRunner.cs View File

@@ -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<int> usedPorts = new List<int>();
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.");
}
}
}

+ 0
- 264
shadowsocks-csharp/Controller/PortForwarder.cs View File

@@ -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);
}
}
}
}
}
}

+ 0
- 313
shadowsocks-csharp/Controller/ShadowsocksController.cs View File

@@ -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<PathEventArgs> PACFileReadyToOpen;
public event EventHandler<GFWListUpdater.ResultEventArgs> 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<Server> 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<Listener.Service> services = new List<Listener.Service>();
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);
}
}
}
}

+ 0
- 105
shadowsocks-csharp/Controller/SystemProxy.cs View File

@@ -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");
}
}
}

+ 0
- 159
shadowsocks-csharp/Controller/UpdateChecker.cs View File

@@ -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<string>
{
// 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<string> 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<string> versions = new List<string>();
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;
}
}
}
}

BIN
shadowsocks-csharp/Data/abp.js.gz View File


+ 0
- 51
shadowsocks-csharp/Data/cn.txt View File

@@ -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}

BIN
shadowsocks-csharp/Data/libsscrypto.dll.gz View File


BIN
shadowsocks-csharp/Data/polipo.exe.gz View File


+ 0
- 10
shadowsocks-csharp/Data/polipo_config.txt View File

@@ -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

BIN
shadowsocks-csharp/Data/proxy.pac.txt.gz View File


+ 0
- 33
shadowsocks-csharp/Encryption/EncryptorBase.cs View File

@@ -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();
}
}

+ 0
- 43
shadowsocks-csharp/Encryption/EncryptorFactory.cs View File

@@ -1,43 +0,0 @@

using System;
using System.Collections.Generic;
using System.Reflection;
namespace Shadowsocks.Encryption
{
public static class EncryptorFactory
{
private static Dictionary<string, Type> _registeredEncryptors;
private static Type[] _constructorTypes = new Type[] { typeof(string), typeof(string) };
static EncryptorFactory()
{
_registeredEncryptors = new Dictionary<string, Type>();
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;
}
}
}

+ 0
- 12
shadowsocks-csharp/Encryption/IEncryptor.cs View File

@@ -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);
}
}

+ 0
- 158
shadowsocks-csharp/Encryption/IVEncryptor.cs View File

@@ -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<string, int[]> ciphers;
private static readonly Dictionary<string, byte[]> CachedKeys = new Dictionary<string, byte[]>();
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<string, int[]> 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);
}
}
}
}

+ 0
- 68
shadowsocks-csharp/Encryption/PolarSSL.cs View File

@@ -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);
}
}

+ 0
- 185
shadowsocks-csharp/Encryption/PolarSSLEncryptor.cs View File

@@ -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<string, int[]> _ciphers = new Dictionary<string, int[]> {
{"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<string> SupportedCiphers()
{
return new List<string>(_ciphers.Keys);
}
protected override Dictionary<string, int[]> 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
}
}

+ 0
- 43
shadowsocks-csharp/Encryption/Sodium.cs View File

@@ -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);
}
}

+ 0
- 99
shadowsocks-csharp/Encryption/SodiumEncryptor.cs View File

@@ -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<string, int[]> _ciphers = new Dictionary<string, int[]> {
{"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<string, int[]> getCiphers()
{
return _ciphers;
}
public static List<string> SupportedCiphers()
{
return new List<string>(_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()
{
}
}
}

+ 0
- 108
shadowsocks-csharp/Encryption/TableEncryptor.cs View File

@@ -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<string> SupportedCiphers()
{
return new List<string>(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()
{
}
}
}

+ 0
- 150
shadowsocks-csharp/Model/Configuration.cs View File

@@ -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<Server> 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<Configuration>(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<Server>()
{
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);
}
}
}
}

+ 0
- 87
shadowsocks-csharp/Model/Server.cs View File

@@ -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();
}
}
}
}

+ 0
- 51
shadowsocks-csharp/Program.cs View File

@@ -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
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[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();
}
}
}
}

+ 0
- 37
shadowsocks-csharp/Properties/AssemblyInfo.cs View File

@@ -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")]

+ 0
- 199
shadowsocks-csharp/Properties/Resources.Designer.cs View File

@@ -1,199 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 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.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Shadowsocks.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// 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() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[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;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] abp_js {
get {
object obj = ResourceManager.GetObject("abp_js", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// 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=编辑服务器
///&amp;Add=添加(&amp;A)
///&amp;Delete=删除(&amp;D)
///Server=服务器
///Server IP=服务器 IP
///Server Port=服务器端口
///Password=密码
///Encryption=加密
///Proxy Port=代理端口
///Remarks=备注
///OK=确定
///Cancel=取消
///New server=未配置的服务器
///QRCode=二维码
///Shadows [rest of string was truncated]&quot;;.
/// </summary>
internal static string cn {
get {
return ResourceManager.GetString("cn", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] libsscrypto_dll {
get {
object obj = ResourceManager.GetObject("libsscrypto_dll", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized string similar to proxyAddress = &quot;__POLIPO_BIND_IP__&quot;
///proxyPort = 8123
///
///socksParentProxy = &quot;127.0.0.1:__SOCKS_PORT__&quot;
///socksProxyType = socks5
///diskCacheRoot = &quot;&quot;
///localDocumentRoot = &quot;&quot;
///
///allowedPorts = 1-65535
///tunnelAllowedPorts = 1-65535.
/// </summary>
internal static string polipo_config {
get {
return ResourceManager.GetString("polipo_config", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] polipo_exe {
get {
object obj = ResourceManager.GetObject("polipo_exe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] proxy_pac_txt {
get {
object obj = ResourceManager.GetObject("proxy_pac_txt", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ss16 {
get {
object obj = ResourceManager.GetObject("ss16", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ss20 {
get {
object obj = ResourceManager.GetObject("ss20", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ss24 {
get {
object obj = ResourceManager.GetObject("ss24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ssw128 {
get {
object obj = ResourceManager.GetObject("ssw128", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

+ 0
- 151
shadowsocks-csharp/Properties/Resources.resx View File

@@ -1,151 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="abp_js" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\abp.js.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="cn" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\cn.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
<data name="libsscrypto_dll" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\data\libsscrypto.dll.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="polipo_config" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\polipo_config.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;gb2312</value>
</data>
<data name="polipo_exe" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\polipo.exe.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="proxy_pac_txt" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Data\proxy.pac.txt.gz;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="ss16" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ss16.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ss20" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ss20.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ss24" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ss24.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ssw128" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ssw128.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

BIN
shadowsocks-csharp/Resources/ss16.png View File


BIN
shadowsocks-csharp/Resources/ss20.png View File


BIN
shadowsocks-csharp/Resources/ss24.png View File


BIN
shadowsocks-csharp/Resources/ssw128.png View File


+ 0
- 50
shadowsocks-csharp/Util/Util.cs View File

@@ -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);
}
}

+ 0
- 458
shadowsocks-csharp/View/ConfigForm.Designer.cs View File

@@ -1,458 +0,0 @@
namespace Shadowsocks.View
{
partial class ConfigForm
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
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;
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save