├── .gitignore
├── LICENSE
├── README.md
├── core
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── willswill
│ │ └── qrtunnel
│ │ └── core
│ │ ├── AppConfigs.java
│ │ ├── Const.java
│ │ ├── DecodeException.java
│ │ ├── Decoder.java
│ │ ├── DecoderCallback.java
│ │ ├── Encoder.java
│ │ ├── EncoderCallback.java
│ │ ├── FileInfo.java
│ │ ├── SenderLayout.java
│ │ └── Util.java
│ └── test
│ └── java
│ └── com
│ └── willswill
│ └── qrtunnel
│ └── Test.java
├── gui
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── willswill
│ └── qrtunnel
│ └── gui
│ ├── ConfigsForm.form
│ ├── ConfigsForm.java
│ ├── GetCodeCoordinates.java
│ ├── ImageView.java
│ ├── IncorrectConfigsException.java
│ ├── Launcher.java
│ ├── ReceiverForm.form
│ ├── ReceiverForm.java
│ ├── RingBuffer.java
│ ├── SenderForm.form
│ └── SenderForm.java
└── pom.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | /.idea
2 | target/
3 | /logs
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # qrtunnel
2 | A fancy way to transfer files, via QR code!
3 |
4 | # See how it works
5 | https://imgur.com/a/eZuybJV
6 |
7 | # Why qrtunnel
8 | When you are working with remote desktop, and you are restricted from copy files/clipboard access from inside desctop to outside, then this tool will helps you.
9 |
10 | # How to use
11 | 1. Copy qrtunnel into remote desctop.
12 | 2. Run it inside remote desctop, click "Sender".
13 | 3. Make sure the whole UI of qrtunnel's SenderForm is not coverd by any window or remote desctop border. You can change the size and layout of QR code images in "Configs"(enter from ReceiverForm).
14 | 4. Run qrtunnel outside remote desktop, click "Start", you will see a message that describes the capture region. If not, probably because the SenderForm is not fully displayed.
15 | 5. Switch to SenderForm inside remote desktop, choose a file/folder to be sent. Then click "Send". You will see progresses on both side.
16 | 6. Wait for thansfer complete.
17 |
18 | # 为什么使用qrtunnel
19 | 当你使用的远程桌面的时候,你发现你不能从远程桌面内部拷贝文件到外部,让这个小工具来帮助你。
20 |
21 | # 如何使用
22 | 1. 把qrtunnel复制到远程桌面里面。
23 | 2. 在远程桌面内运行qrtunnel,点击"Sender"。
24 | 3. 保证SenderForm的界面完整显示,不被其他窗口或者远程桌面的边框所遮盖。你可以在设置界面调整QR code图片的大小和布局(从ReceiverForm进)。
25 | 4. 在远程桌面外运行qrtunnel,点击"Start",你会看到一个消息描述了捕捉区域,如果没有,很可能是因为SenderForm被挡住了没有完全显示。
26 | 5. 在远程桌面里的SenderForm界面选择需要发送的文件/文件夹,然后点击"Send",你会在两边都看到传输进度条。
27 | 6. 等待传输完成。
28 |
--------------------------------------------------------------------------------
/core/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | qr-tunnel
7 | com.willswill.qrtunnel
8 | 1.0
9 |
10 | 4.0.0
11 |
12 | core
13 |
14 |
15 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/AppConfigs.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import lombok.Data;
4 |
5 | /**
6 | * @author Will
7 | */
8 | @Data
9 | public class AppConfigs {
10 | private int chunkSize = 2000; // 每张图片所包含的数据大小,最大值是
11 | private int sendInterval = 200; // 发送端每张图片停顿时间(毫秒)
12 |
13 | private int imageWidth = 500; // 生成的图片宽度
14 | private int imageHeight = 500; // 生成的图片高度
15 |
16 | private String senderLayout; // 发送端图片布局
17 |
18 | private String saveDir; // 接收端文件保存路径
19 | private String rootPath; // 发送端文件相对路径的最上层
20 | }
21 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/Const.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | /**
4 | * @author Will
5 | */
6 | public interface Const {
7 | int VERSION_1 = 0x010000;
8 | int TYPE_FILE = 0x01;
9 | int TYPE_DATA = 0x10;
10 | }
11 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/DecodeException.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import java.io.IOException;
4 |
5 | /**
6 | * @author Will
7 | */
8 | public class DecodeException extends IOException {
9 | public DecodeException(String message) {
10 | super(message);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/Decoder.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import com.google.zxing.BinaryBitmap;
4 | import com.google.zxing.DecodeHintType;
5 | import com.google.zxing.ReaderException;
6 | import com.google.zxing.Result;
7 | import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
8 | import com.google.zxing.common.HybridBinarizer;
9 | import com.google.zxing.qrcode.QRCodeReader;
10 | import lombok.extern.slf4j.Slf4j;
11 |
12 | import java.awt.image.BufferedImage;
13 | import java.io.File;
14 | import java.io.IOException;
15 | import java.io.RandomAccessFile;
16 | import java.nio.charset.StandardCharsets;
17 | import java.util.Arrays;
18 | import java.util.EnumMap;
19 | import java.util.Map;
20 | import java.util.zip.CRC32;
21 |
22 | /**
23 | * @author Will
24 | */
25 | @Slf4j
26 | public class Decoder {
27 | private final QRCodeReader qrCodeReader;
28 | private final Map hints;
29 |
30 | private final AppConfigs appConfigs;
31 | private final DecoderCallback callback;
32 |
33 | private FileInfo fileInfo;
34 | private RandomAccessFile dataFile;
35 | private RandomAccessFile configFile;
36 | private File configFileFile;
37 | private byte[] receivedFlags;
38 |
39 | public Decoder(AppConfigs appConfigs, DecoderCallback callback) {
40 | this.appConfigs = appConfigs;
41 | this.callback = callback;
42 |
43 | qrCodeReader = new QRCodeReader();
44 | hints = new EnumMap<>(DecodeHintType.class);
45 | hints.put(DecodeHintType.CHARACTER_SET, "ISO-8859-1");
46 | hints.put(DecodeHintType.PURE_BARCODE, "true");
47 | }
48 |
49 | public int decode(BufferedImage image, int lastNonce) throws ReaderException, IOException {
50 | BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
51 | BinaryBitmap binaryBmp = new BinaryBitmap(new HybridBinarizer(source));
52 |
53 | try {
54 | Result result = qrCodeReader.decode(binaryBmp, hints);
55 | byte[] buf = result.getText().getBytes(StandardCharsets.ISO_8859_1);
56 | return decode(buf, lastNonce);
57 | } finally {
58 | qrCodeReader.reset();
59 | }
60 | }
61 |
62 | public int decode(byte[] buf, int lastNonce) throws IOException {
63 | if (buf.length < 20) {
64 | return 0;
65 | }
66 |
67 | long crc = Util.bytesToLong(Arrays.copyOfRange(buf, 0, 8));
68 | int nonce = Util.bytesToInt(Arrays.copyOfRange(buf, 8, 12));
69 | int type = Util.bytesToInt(Arrays.copyOfRange(buf, 12, 16));
70 |
71 | if (nonce == lastNonce) {
72 | return nonce;
73 | }
74 |
75 | CRC32 crc32 = new CRC32();
76 | crc32.update(buf, 8, buf.length - 8);
77 | if (crc != crc32.getValue()) {
78 | throw new DecodeException("Chunk CRC32 is not match!");
79 | }
80 |
81 | int version = type & 0xffff0000;
82 | type = type & 0xffff;
83 | if (version == Const.VERSION_1) {
84 | int num = Util.bytesToInt(Arrays.copyOfRange(buf, 16, 20));
85 | int len = buf.length - 20;
86 |
87 | log.info("Received chunk " + num);
88 |
89 | if (type == Const.TYPE_FILE) {
90 | byte[] bFileInfo = Arrays.copyOfRange(buf, 20, len + 20);
91 | FileInfo fileInfo = FileInfo.deserialize(bFileInfo);
92 | if (this.fileInfo == null || !this.fileInfo.equals(fileInfo)) {
93 | reset();
94 | this.fileInfo = fileInfo;
95 | beginFile();
96 | }
97 | } else if (type == Const.TYPE_DATA) {
98 | if (fileInfo == null) {
99 | throw new DecodeException("File info is missing!");
100 | }
101 |
102 | writeFilePart(num, buf, 20, len);
103 | } else {
104 | throw new DecodeException("Type " + type + " is not supported!");
105 | }
106 | } else {
107 | throw new DecodeException("Version " + version + " is not supported!");
108 | }
109 | return nonce;
110 | }
111 |
112 | void beginFile() throws IOException {
113 | log.info("Begin file " + fileInfo.getFilename());
114 | File dir;
115 | if (fileInfo.getPath() == null || fileInfo.getPath().length() == 0 || fileInfo.getPath().equals("/")) {
116 | dir = new File(appConfigs.getSaveDir());
117 | } else {
118 | dir = new File(appConfigs.getSaveDir(), fileInfo.getPath());
119 | }
120 | if (!dir.exists()) {
121 | dir.mkdirs();
122 | }
123 |
124 | dataFile = new RandomAccessFile(new File(dir, fileInfo.getFilename()), "rw");
125 | dataFile.setLength(fileInfo.getLength());
126 |
127 | configFileFile = new File(dir, fileInfo.getFilename() + ".cfg");
128 | configFile = new RandomAccessFile(configFileFile, "rw");
129 | configFile.setLength(fileInfo.getChunkCount());
130 |
131 | receivedFlags = new byte[fileInfo.getChunkCount()];
132 |
133 | if (callback != null) {
134 | callback.fileBegin(fileInfo);
135 | }
136 | }
137 |
138 | synchronized void writeFilePart(int num, byte[] buf, int offset, int len) throws IOException {
139 | int pos = (num - 1) * fileInfo.getChunkSize();
140 | dataFile.seek(pos);
141 | dataFile.write(buf, offset, len);
142 |
143 | configFile.seek(num - 1);
144 | configFile.writeByte(1);
145 |
146 | receivedFlags[num - 1] = 1;
147 |
148 | if (callback != null) {
149 | callback.imageReceived(num);
150 | }
151 |
152 | // check if file is completed
153 | if (checkFileEnd()) {
154 | endFile();
155 | }
156 | }
157 |
158 | boolean checkFileEnd() {
159 | for (byte receivedFlag : receivedFlags) {
160 | if (receivedFlag == 0) {
161 | return false;
162 | }
163 | }
164 | return true;
165 | }
166 |
167 | void endFile() throws IOException {
168 | log.info("End file " + fileInfo.getFilename());
169 |
170 | // check crc32
171 | long crc32 = Util.getCrc32(dataFile);
172 | if (crc32 != fileInfo.getCrc32()) {
173 | log.error("File CRC32 is not match! Desired:" + fileInfo.getCrc32() + ", Received:" + crc32);
174 | }
175 |
176 | dataFile.close();
177 | configFile.close();
178 | configFileFile.delete();
179 |
180 | if (callback != null) {
181 | callback.fileEnd(fileInfo, crc32 == fileInfo.getCrc32());
182 | }
183 |
184 | reset();
185 | }
186 |
187 | public void reset() throws IOException {
188 | fileInfo = null;
189 | if (dataFile != null) {
190 | dataFile.close();
191 | dataFile = null;
192 | }
193 | if (configFile != null) {
194 | configFile.close();
195 | configFile = null;
196 | }
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/DecoderCallback.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | /**
4 | * @author Will
5 | */
6 | public interface DecoderCallback {
7 | default void imageReceived(int num) {
8 | }
9 |
10 | default void fileBegin(FileInfo fileInfo) {
11 | }
12 |
13 | default void fileEnd(FileInfo fileInfo, boolean crc32Matches) {
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/Encoder.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import com.google.zxing.BarcodeFormat;
4 | import com.google.zxing.EncodeHintType;
5 | import com.google.zxing.WriterException;
6 | import com.google.zxing.client.j2se.MatrixToImageWriter;
7 | import com.google.zxing.common.BitMatrix;
8 | import com.google.zxing.qrcode.QRCodeWriter;
9 | import lombok.Data;
10 | import lombok.extern.slf4j.Slf4j;
11 |
12 | import java.awt.image.BufferedImage;
13 | import java.io.File;
14 | import java.io.FileInputStream;
15 | import java.io.IOException;
16 | import java.io.InputStream;
17 | import java.nio.charset.StandardCharsets;
18 | import java.util.EnumMap;
19 | import java.util.Map;
20 | import java.util.Random;
21 | import java.util.zip.CRC32;
22 |
23 | /**
24 | * @author Will
25 | */
26 | @Slf4j
27 | @Data
28 | public class Encoder {
29 | private byte[] buf;
30 | private CRC32 crc32;
31 | private Random random;
32 | private QRCodeWriter qrCodeWriter;
33 | private Map hints;
34 |
35 | private AppConfigs appConfigs;
36 | private EncoderCallback callback;
37 | private boolean running;
38 |
39 | public Encoder(AppConfigs appConfigs, EncoderCallback callback) {
40 | this.appConfigs = appConfigs;
41 | this.callback = callback;
42 |
43 | buf = new byte[appConfigs.getChunkSize() + 20];
44 | crc32 = new CRC32();
45 | random = new Random();
46 | qrCodeWriter = new QRCodeWriter();
47 | hints = new EnumMap<>(EncodeHintType.class);
48 | hints.put(EncodeHintType.MARGIN, 0);
49 | hints.put(EncodeHintType.CHARACTER_SET, "ISO-8859-1");
50 | }
51 |
52 | public void encode(File file) throws IOException, WriterException {
53 | log.info("Begin file " + file.getAbsolutePath());
54 | FileInfo fileInfo = new FileInfo(
55 | appConfigs.getRootPath() == null ? "/" : file.getParentFile().getAbsolutePath().substring(appConfigs.getRootPath().length()),
56 | file.getName(),
57 | file.length(),
58 | Util.getCrc32(file),
59 | appConfigs.getChunkSize(),
60 | (int) Math.ceil(file.length() / (double) appConfigs.getChunkSize()));
61 |
62 | if (callback != null) {
63 | callback.fileBegin(fileInfo);
64 | }
65 |
66 | // file info
67 | byte[] bFileInfo = FileInfo.serialize(fileInfo);
68 | if (bFileInfo.length > appConfigs.getChunkSize()) {
69 | throw new IOException("File name or path is too long!");
70 | }
71 | System.arraycopy(bFileInfo, 0, buf, 20, bFileInfo.length);
72 | encode(Const.VERSION_1 | Const.TYPE_FILE, 0, bFileInfo.length);
73 |
74 | // file content
75 | try (InputStream inputStream = new FileInputStream(file)) {
76 | running = true;
77 | int num = 1;
78 | while (running && inputStream.available() > 0) {
79 | int len = inputStream.read(buf, 20, appConfigs.getChunkSize());
80 | if (len > 0) {
81 | log.info("Send chunk " + (num));
82 |
83 | encode(Const.VERSION_1 | Const.TYPE_DATA, num, len);
84 | }
85 | num++;
86 | }
87 | running = false;
88 | }
89 |
90 | // file end
91 | if (callback != null) {
92 | callback.fileEnd(fileInfo);
93 | }
94 | }
95 |
96 | // crc/nonce/type/num
97 | // 8 /4 /4 /4 /4
98 | private void encode(int type, int num, int len) throws WriterException {
99 | // nonce
100 | System.arraycopy(Util.intToBytes(random.nextInt()), 0, buf, 8, 4);
101 | // type
102 | System.arraycopy(Util.intToBytes(type), 0, buf, 12, 4);
103 | // num
104 | System.arraycopy(Util.intToBytes(num), 0, buf, 16, 4);
105 |
106 | // crc
107 | crc32.reset();
108 | crc32.update(buf, 8, len + 12);
109 | System.arraycopy(Util.longToBytes(crc32.getValue()), 0, buf, 0, 8);
110 |
111 | // generate image
112 | String content = new String(buf, 0, len + 20, StandardCharsets.ISO_8859_1);
113 | BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, appConfigs.getImageWidth(), appConfigs.getImageHeight(), hints);
114 | BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
115 |
116 | // callback
117 | if (callback != null) {
118 | callback.imageCreated(num, image);
119 | }
120 | }
121 |
122 | public void interrupt() {
123 | running = false;
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/EncoderCallback.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import java.awt.image.BufferedImage;
4 |
5 | /**
6 | * @author Will
7 | */
8 | public interface EncoderCallback {
9 | default void imageCreated(int num, BufferedImage image) {
10 | }
11 |
12 | default void fileBegin(FileInfo fileInfo) {
13 | }
14 |
15 | default void fileEnd(FileInfo fileInfo) {
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/FileInfo.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 |
6 | import java.io.*;
7 |
8 | /**
9 | * @author Will
10 | */
11 | @Data
12 | @AllArgsConstructor
13 | public class FileInfo {
14 | private String path;
15 | private String filename;
16 | private long length;
17 | private long crc32;
18 | private int chunkSize;
19 | private int chunkCount;
20 |
21 | public static byte[] serialize(FileInfo fileInfo) throws IOException {
22 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
23 | try (ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {
24 | oos.writeUTF(fileInfo.path);
25 | oos.writeUTF(fileInfo.filename);
26 | oos.writeLong(fileInfo.length);
27 | oos.writeLong(fileInfo.crc32);
28 | oos.writeInt(fileInfo.chunkSize);
29 | oos.writeInt(fileInfo.chunkCount);
30 | oos.flush();
31 | return outputStream.toByteArray();
32 | }
33 | }
34 |
35 | public static FileInfo deserialize(byte[] bytes) throws IOException {
36 | ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
37 | try (ObjectInputStream ois = new ObjectInputStream(inputStream)) {
38 | return new FileInfo(ois.readUTF(), ois.readUTF(), ois.readLong(), ois.readLong(), ois.readInt(), ois.readInt());
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/SenderLayout.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import lombok.Data;
4 |
5 | /**
6 | * @author Will
7 | */
8 | @Data
9 | public class SenderLayout {
10 | private int width;
11 | private int height;
12 | private int num;
13 |
14 | private int rows;
15 | private int columns;
16 | }
17 |
--------------------------------------------------------------------------------
/core/src/main/java/com/willswill/qrtunnel/core/Util.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.core;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.io.RandomAccessFile;
6 | import java.nio.ByteBuffer;
7 | import java.util.zip.CRC32;
8 |
9 | /**
10 | * @author Will
11 | */
12 | public class Util {
13 | public static byte[] intToBytes(int a) {
14 | return new byte[]{
15 | (byte) ((a >> 24) & 0xFF),
16 | (byte) ((a >> 16) & 0xFF),
17 | (byte) ((a >> 8) & 0xFF),
18 | (byte) (a & 0xFF)
19 | };
20 | }
21 |
22 | public static int bytesToInt(byte[] b) {
23 | return b[3] & 0xFF |
24 | (b[2] & 0xFF) << 8 |
25 | (b[1] & 0xFF) << 16 |
26 | (b[0] & 0xFF) << 24;
27 | }
28 |
29 | public static byte[] longToBytes(long x) {
30 | ByteBuffer buffer = ByteBuffer.allocate(8);
31 | buffer.putLong(0, x);
32 | return buffer.array();
33 | }
34 |
35 | public static long bytesToLong(byte[] bytes) {
36 | ByteBuffer buffer = ByteBuffer.allocate(8);
37 | buffer.put(bytes, 0, bytes.length);
38 | buffer.flip(); // need flip
39 | return buffer.getLong();
40 | }
41 |
42 | public static long getCrc32(File file) throws IOException {
43 | try (RandomAccessFile file1 = new RandomAccessFile(file, "r")) {
44 | return getCrc32(file1);
45 | }
46 | }
47 |
48 | public static long getCrc32(RandomAccessFile file) throws IOException {
49 | CRC32 crc32 = new CRC32();
50 | byte[] bytes = new byte[1024];
51 | file.seek(0);
52 | int len = file.read(bytes);
53 | while (len > 0) {
54 | crc32.update(bytes, 0, len);
55 | len = file.read(bytes);
56 | }
57 | return crc32.getValue();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/core/src/test/java/com/willswill/qrtunnel/Test.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel;
2 |
3 | import com.willswill.qrtunnel.core.AppConfigs;
4 | import com.willswill.qrtunnel.core.Decoder;
5 | import com.willswill.qrtunnel.core.Encoder;
6 | import com.willswill.qrtunnel.core.EncoderCallback;
7 |
8 | import java.awt.image.BufferedImage;
9 | import java.io.File;
10 |
11 | /**
12 | * @author Will
13 | */
14 | public class Test {
15 | public static void main(String[] args) {
16 | test2();
17 | }
18 |
19 | public static void test2() {
20 | AppConfigs appConfigs = new AppConfigs();
21 | appConfigs.setSaveDir("Received");
22 | Decoder decoder = new Decoder(appConfigs, null);
23 |
24 | Encoder encoder = new Encoder(appConfigs, new EncoderCallback() {
25 | @Override
26 | public void imageCreated(int num, BufferedImage image) {
27 | try {
28 | decoder.decode(image, 0);
29 | } catch (Exception e) {
30 | e.printStackTrace();
31 | }
32 | }
33 | });
34 |
35 | File file = new File("D:\\Temp\\1.png");
36 | try {
37 | encoder.encode(file);
38 | } catch (Exception e) {
39 | e.printStackTrace();
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/gui/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | qr-tunnel
7 | com.willswill.qrtunnel
8 | 1.0
9 |
10 | 4.0.0
11 |
12 | gui
13 |
14 |
15 |
16 | com.willswill.qrtunnel
17 | core
18 | 1.0
19 |
20 |
21 |
22 |
23 | qr-tunnel
24 |
25 |
26 | org.springframework.boot
27 | spring-boot-maven-plugin
28 | ${spring.boot.version}
29 |
30 |
31 |
32 | org.projectlombok
33 | lombok
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/ConfigsForm.form:
--------------------------------------------------------------------------------
1 |
2 |
203 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/ConfigsForm.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | import com.willswill.qrtunnel.core.AppConfigs;
4 | import lombok.extern.slf4j.Slf4j;
5 |
6 | import javax.swing.*;
7 | import java.awt.*;
8 | import java.io.File;
9 |
10 | /**
11 | * @author Will
12 | */
13 | @Slf4j
14 | public class ConfigsForm {
15 | private JPanel panel1;
16 | private JTextArea saveDirTextField;
17 | private JButton chooseButton;
18 | private JTextField chunkSizeTextField;
19 | private JTextField imageWidthTextField;
20 | private JTextField sendIntervalTextField;
21 | private JComboBox senderLayoutComboBox;
22 | private JButton saveConfigsButton;
23 |
24 | private JFrame frame;
25 |
26 | public static ConfigsForm create() {
27 | JFrame frame = new JFrame("ConfigsForm");
28 | ConfigsForm form = new ConfigsForm();
29 | frame.setContentPane(form.panel1);
30 | frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
31 | frame.setResizable(false);
32 | form.frame = frame;
33 |
34 | form.initComponents();
35 | form.fillForm();
36 |
37 | frame.pack();
38 | frame.setVisible(true);
39 | return form;
40 | }
41 |
42 | void initComponents() {
43 | chooseButton.addActionListener(e -> {
44 | String selectedDir = saveDirTextField.getText();
45 | JFileChooser fileChooser = new JFileChooser(new File(selectedDir));
46 | fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
47 | fileChooser.setDialogTitle("Choose Save Directory");
48 | fileChooser.showDialog(new JLabel(), "Choose");
49 | File file = fileChooser.getSelectedFile();
50 | if (file != null && file.exists()) {
51 | saveDirTextField.setText(file.getAbsolutePath());
52 | saveDirTextField.setToolTipText(file.getAbsolutePath());
53 | }
54 | });
55 |
56 | saveConfigsButton.addActionListener(e -> {
57 | try {
58 | saveForm();
59 | if (Launcher.self.getSenderForm() != null) {
60 | Launcher.self.getSenderForm().resetLayout();
61 | }
62 | frame.setVisible(false);
63 | } catch (IncorrectConfigsException ex) {
64 | JOptionPane.showMessageDialog(panel1, ex.getMessage());
65 | } catch (Exception ex) {
66 | log.error("Save configs failed!", ex);
67 | JOptionPane.showMessageDialog(panel1, ex.getClass().getName() + ": " + ex.getMessage());
68 | }
69 | });
70 | }
71 |
72 | public void show() {
73 | fillForm();
74 | frame.setVisible(true);
75 | }
76 |
77 | void saveForm() {
78 | AppConfigs appConfigs = Launcher.getAppConfigs();
79 | appConfigs.setSaveDir(saveDirTextField.getText());
80 | appConfigs.setImageWidth(Integer.parseInt(imageWidthTextField.getText()));
81 | appConfigs.setImageHeight(appConfigs.getImageWidth());
82 | int chunkSize = Integer.parseInt(chunkSizeTextField.getText());
83 | if (chunkSize > 2000) {
84 | throw new IncorrectConfigsException("The max value of chunk size is 2000");
85 | }
86 | appConfigs.setChunkSize(chunkSize);
87 | appConfigs.setSendInterval(Integer.parseInt(sendIntervalTextField.getText()));
88 | appConfigs.setSenderLayout(senderLayoutComboBox.getSelectedItem().toString());
89 | }
90 |
91 | void fillForm() {
92 | AppConfigs appConfigs = Launcher.getAppConfigs();
93 | saveDirTextField.setText(appConfigs.getSaveDir());
94 | saveDirTextField.setToolTipText(appConfigs.getSaveDir());
95 | imageWidthTextField.setText(String.valueOf(appConfigs.getImageWidth()));
96 | chunkSizeTextField.setText(String.valueOf(appConfigs.getChunkSize()));
97 | sendIntervalTextField.setText(String.valueOf(appConfigs.getSendInterval()));
98 | senderLayoutComboBox.setSelectedItem(appConfigs.getSenderLayout());
99 | }
100 |
101 | {
102 | // GUI initializer generated by IntelliJ IDEA GUI Designer
103 | // >>> IMPORTANT!! <<<
104 | // DO NOT EDIT OR ADD ANY CODE HERE!
105 | $$$setupUI$$$();
106 | }
107 |
108 | /**
109 | * Method generated by IntelliJ IDEA GUI Designer
110 | * >>> IMPORTANT!! <<<
111 | * DO NOT edit this method OR call it in your code!
112 | *
113 | * @noinspection ALL
114 | */
115 | private void $$$setupUI$$$() {
116 | panel1 = new JPanel();
117 | panel1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 5));
118 | panel1.setPreferredSize(new Dimension(400, 250));
119 | final JPanel panel2 = new JPanel();
120 | panel2.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
121 | panel2.setBackground(new Color(-8019262));
122 | panel2.setPreferredSize(new Dimension(400, 17));
123 | panel1.add(panel2);
124 | final JLabel label1 = new JLabel();
125 | Font label1Font = this.$$$getFont$$$(null, Font.BOLD, -1, label1.getFont());
126 | if (label1Font != null) label1.setFont(label1Font);
127 | label1.setText("Receiver Configs");
128 | panel2.add(label1);
129 | final JPanel panel3 = new JPanel();
130 | panel3.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
131 | panel3.setPreferredSize(new Dimension(400, 40));
132 | panel1.add(panel3);
133 | final JLabel label2 = new JLabel();
134 | label2.setText("Save Files To");
135 | panel3.add(label2);
136 | saveDirTextField = new JTextArea();
137 | saveDirTextField.setEditable(false);
138 | saveDirTextField.setEnabled(true);
139 | saveDirTextField.setPreferredSize(new Dimension(220, 20));
140 | panel3.add(saveDirTextField);
141 | chooseButton = new JButton();
142 | chooseButton.setText("Choose");
143 | panel3.add(chooseButton);
144 | final JPanel panel4 = new JPanel();
145 | panel4.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
146 | panel4.setBackground(new Color(-8019262));
147 | panel4.setPreferredSize(new Dimension(400, 17));
148 | panel1.add(panel4);
149 | final JLabel label3 = new JLabel();
150 | Font label3Font = this.$$$getFont$$$(null, Font.BOLD, -1, label3.getFont());
151 | if (label3Font != null) label3.setFont(label3Font);
152 | label3.setText("Sender Configs");
153 | panel4.add(label3);
154 | final JPanel panel5 = new JPanel();
155 | panel5.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
156 | panel5.setPreferredSize(new Dimension(400, 100));
157 | panel1.add(panel5);
158 | final JPanel panel6 = new JPanel();
159 | panel6.setLayout(new BorderLayout(5, 0));
160 | panel5.add(panel6);
161 | final JLabel label4 = new JLabel();
162 | label4.setHorizontalAlignment(4);
163 | label4.setPreferredSize(new Dimension(120, 17));
164 | label4.setText("Image Width");
165 | panel6.add(label4, BorderLayout.WEST);
166 | imageWidthTextField = new JTextField();
167 | imageWidthTextField.setPreferredSize(new Dimension(50, 24));
168 | panel6.add(imageWidthTextField, BorderLayout.CENTER);
169 | final JPanel panel7 = new JPanel();
170 | panel7.setLayout(new BorderLayout(5, 0));
171 | panel5.add(panel7);
172 | final JLabel label5 = new JLabel();
173 | label5.setHorizontalAlignment(4);
174 | label5.setPreferredSize(new Dimension(120, 17));
175 | label5.setText("Chunk Size");
176 | panel7.add(label5, BorderLayout.WEST);
177 | chunkSizeTextField = new JTextField();
178 | chunkSizeTextField.setPreferredSize(new Dimension(50, 24));
179 | panel7.add(chunkSizeTextField, BorderLayout.CENTER);
180 | final JPanel panel8 = new JPanel();
181 | panel8.setLayout(new BorderLayout(5, 0));
182 | panel5.add(panel8);
183 | final JLabel label6 = new JLabel();
184 | label6.setHorizontalAlignment(4);
185 | label6.setPreferredSize(new Dimension(120, 17));
186 | label6.setText("Send Interval (ms)");
187 | panel8.add(label6, BorderLayout.WEST);
188 | sendIntervalTextField = new JTextField();
189 | sendIntervalTextField.setPreferredSize(new Dimension(50, 24));
190 | panel8.add(sendIntervalTextField, BorderLayout.CENTER);
191 | final JPanel panel9 = new JPanel();
192 | panel9.setLayout(new BorderLayout(5, 0));
193 | panel5.add(panel9);
194 | final JLabel label7 = new JLabel();
195 | label7.setHorizontalAlignment(4);
196 | label7.setPreferredSize(new Dimension(120, 17));
197 | label7.setText("Sender Layout");
198 | panel9.add(label7, BorderLayout.WEST);
199 | senderLayoutComboBox = new JComboBox();
200 | final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
201 | defaultComboBoxModel1.addElement("1*1");
202 | defaultComboBoxModel1.addElement("1*2");
203 | defaultComboBoxModel1.addElement("1*3");
204 | defaultComboBoxModel1.addElement("1*4");
205 | defaultComboBoxModel1.addElement("1*5");
206 | defaultComboBoxModel1.addElement("2*1");
207 | defaultComboBoxModel1.addElement("2*2");
208 | defaultComboBoxModel1.addElement("2*3");
209 | defaultComboBoxModel1.addElement("2*4");
210 | defaultComboBoxModel1.addElement("2*5");
211 | defaultComboBoxModel1.addElement("3*1");
212 | defaultComboBoxModel1.addElement("3*2");
213 | defaultComboBoxModel1.addElement("3*3");
214 | defaultComboBoxModel1.addElement("3*4");
215 | defaultComboBoxModel1.addElement("3*5");
216 | senderLayoutComboBox.setModel(defaultComboBoxModel1);
217 | senderLayoutComboBox.setPreferredSize(new Dimension(70, 30));
218 | panel9.add(senderLayoutComboBox, BorderLayout.CENTER);
219 | final JPanel panel10 = new JPanel();
220 | panel10.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
221 | panel10.setPreferredSize(new Dimension(400, 40));
222 | panel1.add(panel10);
223 | saveConfigsButton = new JButton();
224 | saveConfigsButton.setText("Save Configs");
225 | panel10.add(saveConfigsButton);
226 | }
227 |
228 | /**
229 | * @noinspection ALL
230 | */
231 | private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
232 | if (currentFont == null) return null;
233 | String resultName;
234 | if (fontName == null) {
235 | resultName = currentFont.getName();
236 | } else {
237 | Font testFont = new Font(fontName, Font.PLAIN, 10);
238 | if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
239 | resultName = fontName;
240 | } else {
241 | resultName = currentFont.getName();
242 | }
243 | }
244 | return new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize());
245 | }
246 |
247 | /**
248 | * @noinspection ALL
249 | */
250 | public JComponent $$$getRootComponent$$$() {
251 | return panel1;
252 | }
253 |
254 | }
255 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/GetCodeCoordinates.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | import com.google.zxing.*;
4 | import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
5 | import com.google.zxing.common.HybridBinarizer;
6 | import com.google.zxing.qrcode.QRCodeReader;
7 | import com.google.zxing.qrcode.detector.FinderPattern;
8 | import com.willswill.qrtunnel.core.DecodeException;
9 | import lombok.AllArgsConstructor;
10 |
11 | import java.awt.image.BufferedImage;
12 | import java.util.EnumMap;
13 | import java.util.Map;
14 |
15 | /**
16 | * @author Will
17 | */
18 | public class GetCodeCoordinates {
19 | public static Layout detect(BufferedImage image) throws ReaderException, DecodeException {
20 | QRCodeReader qrCodeReader = new QRCodeReader();
21 | Map hints = new EnumMap<>(DecodeHintType.class);
22 | hints.put(DecodeHintType.CHARACTER_SET, "ISO-8859-1");
23 | hints.put(DecodeHintType.TRY_HARDER, "true");
24 |
25 | BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
26 | BinaryBitmap binaryBmp = new BinaryBitmap(new HybridBinarizer(source));
27 |
28 | Result result = qrCodeReader.decode(binaryBmp, hints);
29 | int left = image.getWidth();
30 | int top = image.getHeight();
31 | int right = 0;
32 | int bottom = 0;
33 |
34 | for (ResultPoint point : result.getResultPoints()) {
35 | if (point instanceof FinderPattern) {
36 | FinderPattern fp = (FinderPattern) point;
37 | left = Math.min(left, (int) Math.round(point.getX() - 3.5 * fp.getEstimatedModuleSize()));
38 | top = Math.min(top, (int) Math.round(point.getY() - 3.5 * fp.getEstimatedModuleSize()));
39 | right = Math.max(right, (int) Math.round(point.getX() + 3.5 * fp.getEstimatedModuleSize()));
40 | bottom = Math.max(bottom, (int) Math.round(point.getY() + 3.5 * fp.getEstimatedModuleSize()));
41 | }
42 | }
43 |
44 | int width = right - left;
45 | int height = bottom - top;
46 |
47 | String[] split = result.getText().split("/");
48 | int num = Integer.parseInt(split[0]);
49 | String[] split1 = split[1].split("\\*");
50 | String[] split2 = split[2].split("\\*");
51 | int targetWidth = Integer.parseInt(split2[0]);
52 | int targetHeight = Integer.parseInt(split2[1]);
53 |
54 | if (width != targetWidth) {
55 | int paddingLeft = (targetWidth - width) / 2;
56 | int paddingTop = (targetHeight - height) / 2;
57 | left -= paddingLeft;
58 | top -= paddingTop;
59 | }
60 |
61 | int rows = Integer.parseInt(split1[0]);
62 | int cols = Integer.parseInt(split1[1]);
63 | int index = num - 1;
64 | int rowIndex = index / cols;
65 | int colIndex = index % cols;
66 |
67 | int rect0Left = left - targetWidth * colIndex;
68 | int rect0Top = top - targetHeight * rowIndex;
69 |
70 | // check
71 | if (rect0Left + targetWidth * cols > image.getWidth() || rect0Top + targetHeight * rows > image.getHeight()) {
72 | throw new DecodeException("Capture rect is out of screen");
73 | }
74 |
75 | return new Layout(rect0Left, rect0Top, targetWidth, targetHeight, rows, cols);
76 | }
77 |
78 | @AllArgsConstructor
79 | public static class Layout {
80 | public int left;
81 | public int top;
82 | public int width;
83 | public int height;
84 | public int rows;
85 | public int cols;
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/ImageView.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | import lombok.Getter;
4 |
5 | import javax.swing.*;
6 | import java.awt.*;
7 | import java.awt.image.BufferedImage;
8 |
9 | /**
10 | * @author Will
11 | */
12 | public class ImageView extends JPanel {
13 | @Getter
14 | private final int margin;
15 | @Getter
16 | private final int imageWidth;
17 | @Getter
18 | private final int imageHeight;
19 | private BufferedImage image;
20 |
21 | public ImageView() {
22 | this(null, 500, 500, 0);
23 | }
24 |
25 | public ImageView(BufferedImage image, int imageWidth, int imageHeight, int margin) {
26 | this.image = image;
27 | this.imageWidth = imageWidth;
28 | this.imageHeight = imageHeight;
29 | this.margin = margin;
30 | setLayout(null);
31 | setPreferredSize(new Dimension(imageWidth + margin * 2, imageHeight + margin * 2));
32 | }
33 |
34 | public void setImage(BufferedImage image) {
35 | this.image = image;
36 | this.repaint();
37 | }
38 |
39 | @Override
40 | public void paintComponent(Graphics g1) {
41 | if (this.image == null) {
42 | return;
43 | }
44 |
45 | g1.drawImage(image, margin, margin, image.getWidth(), image.getHeight(), null);
46 | }
47 | }
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/IncorrectConfigsException.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | /**
4 | * @author Will
5 | */
6 | public class IncorrectConfigsException extends RuntimeException {
7 | public IncorrectConfigsException(String message) {
8 | super(message);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/Launcher.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | import com.willswill.qrtunnel.core.AppConfigs;
4 | import lombok.Data;
5 |
6 | import java.io.File;
7 | import java.io.FileNotFoundException;
8 | import java.io.FileOutputStream;
9 | import java.io.PrintStream;
10 | import java.text.SimpleDateFormat;
11 | import java.util.Date;
12 |
13 | /**
14 | * @author Will
15 | */
16 | @Data
17 | public class Launcher {
18 | public static final Launcher self = new Launcher();
19 |
20 | private AppConfigs appConfigs;
21 | private ReceiverForm receiverForm;
22 | private SenderForm senderForm;
23 | private ConfigsForm configsForm;
24 |
25 | public static void main(String[] args) {
26 | self.loadConfigs();
27 | self.showReceiverForm();
28 | }
29 |
30 | private Launcher() {
31 | File logDir = new File("logs");
32 | if (!logDir.exists()) {
33 | logDir.mkdir();
34 | }
35 | String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
36 | File file = new File(logDir, date + ".log");
37 |
38 | try {
39 | PrintStream printStream = new PrintStream(new FileOutputStream(file, true));
40 | System.setOut(printStream);
41 | System.setErr(printStream);
42 | } catch (FileNotFoundException e) {
43 | e.printStackTrace();
44 | }
45 | }
46 |
47 | public static AppConfigs getAppConfigs() {
48 | return self.appConfigs;
49 | }
50 |
51 | public static void log(String s) {
52 | self.receiverForm.addLog(s);
53 | }
54 |
55 | private void loadConfigs() {
56 | self.appConfigs = new AppConfigs();
57 | appConfigs.setImageWidth(330);
58 | appConfigs.setImageHeight(330);
59 | appConfigs.setSenderLayout("2*3");
60 | appConfigs.setSaveDir(new File("Received").getAbsolutePath());
61 | }
62 |
63 | public void showReceiverForm() {
64 | if (receiverForm == null) {
65 | receiverForm = ReceiverForm.create();
66 | }
67 | receiverForm.show();
68 | }
69 |
70 | public void showSenderForm() {
71 | if (senderForm == null) {
72 | senderForm = SenderForm.create();
73 | }
74 | senderForm.show();
75 | }
76 |
77 | public void showConfigsForm() {
78 | if (configsForm == null) {
79 | configsForm = ConfigsForm.create();
80 | }
81 | configsForm.show();
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/ReceiverForm.form:
--------------------------------------------------------------------------------
1 |
2 |
99 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/ReceiverForm.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | import com.google.zxing.ChecksumException;
4 | import com.google.zxing.FormatException;
5 | import com.google.zxing.NotFoundException;
6 | import com.google.zxing.ReaderException;
7 | import com.willswill.qrtunnel.core.DecodeException;
8 | import com.willswill.qrtunnel.core.Decoder;
9 | import com.willswill.qrtunnel.core.DecoderCallback;
10 | import com.willswill.qrtunnel.core.FileInfo;
11 | import lombok.extern.slf4j.Slf4j;
12 |
13 | import javax.swing.*;
14 | import javax.swing.text.DefaultCaret;
15 | import java.awt.*;
16 | import java.awt.image.BufferedImage;
17 | import java.util.stream.Collectors;
18 |
19 | /**
20 | * @author Will
21 | */
22 | @Slf4j
23 | public class ReceiverForm {
24 | private JPanel panel1;
25 | private JButton startButton;
26 | private JTextArea logView;
27 | private JButton stopButton;
28 | private JButton senderButton;
29 | private JProgressBar fileProgress;
30 | private JLabel filenameLabel;
31 | private JButton configButton;
32 |
33 | private JFrame frame;
34 | private Decoder decoder;
35 | GetCodeCoordinates.Layout layout;
36 | boolean running = false;
37 | private final RingBuffer logBuf = new RingBuffer<>(200);
38 |
39 | private int totalImages;
40 | private int imageIndex;
41 |
42 | public static ReceiverForm create() {
43 | JFrame frame = new JFrame("ReceiverForm");
44 | ReceiverForm form = new ReceiverForm();
45 | frame.setContentPane(form.panel1);
46 | frame.setSize(300, 200);
47 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
48 | form.frame = frame;
49 |
50 | form.initComponents();
51 |
52 | frame.pack();
53 | frame.setVisible(true);
54 | return form;
55 | }
56 |
57 | public void show() {
58 | frame.setVisible(true);
59 | }
60 |
61 | void initComponents() {
62 | startButton.addActionListener(e -> {
63 | try {
64 | detectCaptureRect();
65 | } catch (ReaderException ex) {
66 | JOptionPane.showMessageDialog(panel1, "Failed to detect capture rect!");
67 | return;
68 | } catch (DecodeException ex) {
69 | JOptionPane.showMessageDialog(panel1, ex.getMessage());
70 | return;
71 | } catch (Exception ex) {
72 | log.error("Failed to capture screenshot!", ex);
73 | JOptionPane.showMessageDialog(panel1, "Failed to capture screenshot!");
74 | return;
75 | }
76 |
77 | startCaptureAsync();
78 | });
79 |
80 | stopButton.addActionListener(e -> {
81 | running = false;
82 | });
83 |
84 | senderButton.addActionListener(e -> {
85 | Launcher.self.showSenderForm();
86 | });
87 |
88 | configButton.addActionListener(e -> {
89 | Launcher.self.showConfigsForm();
90 | });
91 |
92 | DefaultCaret caret = (DefaultCaret) logView.getCaret();
93 | caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
94 | }
95 |
96 | void detectCaptureRect() throws ReaderException, DecodeException, AWTException {
97 | Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
98 | Robot robot = new Robot();
99 | BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, d.width, d.height));
100 | layout = GetCodeCoordinates.detect(image);
101 | log.info(layout.toString());
102 | Launcher.log("Capture rect is set to " + layout.left + "," + layout.top + " " + layout.width * layout.cols + "*" + layout.height * layout.rows);
103 | }
104 |
105 | void startCaptureAsync() {
106 | decoder = new Decoder(Launcher.getAppConfigs(), new DecoderCallback() {
107 | @Override
108 | public void imageReceived(int num) {
109 | imageIndex = num;
110 | updateProgress();
111 | }
112 |
113 | @Override
114 | public void fileBegin(FileInfo fileInfo) {
115 | totalImages = fileInfo.getChunkCount();
116 | filenameLabel.setText(fileInfo.getFilename());
117 | updateProgress();
118 | Launcher.log("Receiving file " + fileInfo.getFilename());
119 | }
120 |
121 | @Override
122 | public void fileEnd(FileInfo fileInfo, boolean crc32Matches) {
123 | if (crc32Matches) {
124 | Launcher.log("Received file " + fileInfo.getFilename() + " with " + fileInfo.getLength() + "bytes");
125 | } else {
126 | Launcher.log("Received file " + fileInfo.getFilename() + " with error: crc32 is not match");
127 | }
128 | resetProgress();
129 | }
130 | });
131 |
132 | new Thread(() -> {
133 | startButton.setEnabled(false);
134 | stopButton.setEnabled(true);
135 | try {
136 | startCapture();
137 | } catch (Exception e) {
138 | log.error("Capture failed", e);
139 | }
140 | startButton.setEnabled(true);
141 | stopButton.setEnabled(false);
142 | }).start();
143 | }
144 |
145 | void startCapture() throws Exception {
146 | Rectangle captureRect = new Rectangle(layout.left, layout.top, layout.width * layout.cols, layout.height * layout.rows);
147 | Robot robot = new Robot();
148 | BufferedImage image;
149 | running = true;
150 | int[][] nonceArr = new int[layout.rows][layout.cols];
151 | while (running) {
152 | image = robot.createScreenCapture(captureRect);
153 | try {
154 | // crop image
155 | for (int i = 0; i < layout.rows; i++) {
156 | for (int j = 0; j < layout.cols; j++) {
157 | BufferedImage cropped = image.getSubimage(layout.width * j, layout.height * i, layout.width, layout.height);
158 | nonceArr[i][j] = decoder.decode(cropped, nonceArr[i][j]);
159 | }
160 | }
161 | } catch (NotFoundException | FormatException | ChecksumException ignore) {
162 | } catch (DecodeException ex) {
163 | log.error("Decode failed: " + ex.getMessage());
164 | Launcher.log(ex.getClass().getName() + ": " + ex.getMessage());
165 | } catch (Exception ex) {
166 | log.error("Decode failed!", ex);
167 | Launcher.log(ex.getClass().getName() + ": " + ex.getMessage());
168 | }
169 | }
170 | decoder.reset();
171 | resetProgress();
172 | }
173 |
174 | void updateProgress() {
175 | fileProgress.setMaximum(totalImages);
176 | fileProgress.setValue(imageIndex);
177 | }
178 |
179 | void resetProgress() {
180 | totalImages = 0;
181 | imageIndex = 0;
182 | filenameLabel.setText("");
183 | updateProgress();
184 | }
185 |
186 | public void addLog(String s) {
187 | logBuf.put(s);
188 | String text = logBuf.readFully().stream().collect(Collectors.joining("\n"));
189 | logView.setText(text);
190 | }
191 |
192 | {
193 | // GUI initializer generated by IntelliJ IDEA GUI Designer
194 | // >>> IMPORTANT!! <<<
195 | // DO NOT EDIT OR ADD ANY CODE HERE!
196 | $$$setupUI$$$();
197 | }
198 |
199 | /**
200 | * Method generated by IntelliJ IDEA GUI Designer
201 | * >>> IMPORTANT!! <<<
202 | * DO NOT edit this method OR call it in your code!
203 | *
204 | * @noinspection ALL
205 | */
206 | private void $$$setupUI$$$() {
207 | panel1 = new JPanel();
208 | panel1.setLayout(new BorderLayout(0, 0));
209 | panel1.setPreferredSize(new Dimension(400, 200));
210 | final JPanel panel2 = new JPanel();
211 | panel2.setLayout(new BorderLayout(0, 0));
212 | panel1.add(panel2, BorderLayout.NORTH);
213 | final JPanel panel3 = new JPanel();
214 | panel3.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
215 | panel2.add(panel3, BorderLayout.WEST);
216 | startButton = new JButton();
217 | startButton.setText("Start");
218 | panel3.add(startButton);
219 | stopButton = new JButton();
220 | stopButton.setEnabled(false);
221 | stopButton.setText("Stop");
222 | panel3.add(stopButton);
223 | final JPanel panel4 = new JPanel();
224 | panel4.setLayout(new BorderLayout(0, 0));
225 | panel2.add(panel4, BorderLayout.CENTER);
226 | fileProgress = new JProgressBar();
227 | fileProgress.setPreferredSize(new Dimension(146, 6));
228 | panel4.add(fileProgress, BorderLayout.NORTH);
229 | filenameLabel = new JLabel();
230 | filenameLabel.setHorizontalAlignment(0);
231 | filenameLabel.setPreferredSize(new Dimension(0, 17));
232 | filenameLabel.setText("");
233 | panel4.add(filenameLabel, BorderLayout.CENTER);
234 | final JPanel panel5 = new JPanel();
235 | panel5.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
236 | panel2.add(panel5, BorderLayout.EAST);
237 | senderButton = new JButton();
238 | senderButton.setText("Sender");
239 | panel5.add(senderButton);
240 | configButton = new JButton();
241 | configButton.setText("Config");
242 | panel5.add(configButton);
243 | final JScrollPane scrollPane1 = new JScrollPane();
244 | scrollPane1.setHorizontalScrollBarPolicy(31);
245 | panel1.add(scrollPane1, BorderLayout.CENTER);
246 | logView = new JTextArea();
247 | logView.setEditable(false);
248 | logView.setMargin(new Insets(0, 5, 0, 0));
249 | logView.setRows(10);
250 | scrollPane1.setViewportView(logView);
251 | }
252 |
253 | /**
254 | * @noinspection ALL
255 | */
256 | public JComponent $$$getRootComponent$$$() {
257 | return panel1;
258 | }
259 |
260 | }
261 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/RingBuffer.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Will
8 | */
9 | public class RingBuffer {
10 | private final List buf;
11 | private final int maxSize;
12 | private int cursor;
13 |
14 | public RingBuffer(int maxSize) {
15 | this.maxSize = maxSize;
16 | buf = new ArrayList<>(maxSize);
17 | for (int i = 0; i < maxSize; i++) {
18 | buf.add(null);
19 | }
20 | cursor = 0;
21 | }
22 |
23 | public synchronized void put(T object) {
24 | buf.set(cursor++, object);
25 | if (cursor >= maxSize) {
26 | cursor = 0;
27 | }
28 | }
29 |
30 | public List readFully() {
31 | List ret = new ArrayList<>(maxSize);
32 | int cursor = this.cursor;
33 | for (int i = cursor; i < maxSize; i++) {
34 | T t = buf.get(i);
35 | if (t != null) {
36 | ret.add(t);
37 | }
38 | }
39 | for (int i = 0; i < cursor; i++) {
40 | T t = buf.get(i);
41 | if (t != null) {
42 | ret.add(t);
43 | }
44 | }
45 | return ret;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/SenderForm.form:
--------------------------------------------------------------------------------
1 |
2 |
88 |
--------------------------------------------------------------------------------
/gui/src/main/java/com/willswill/qrtunnel/gui/SenderForm.java:
--------------------------------------------------------------------------------
1 | package com.willswill.qrtunnel.gui;
2 |
3 | import com.google.zxing.BarcodeFormat;
4 | import com.google.zxing.client.j2se.MatrixToImageWriter;
5 | import com.google.zxing.common.BitMatrix;
6 | import com.google.zxing.qrcode.QRCodeWriter;
7 | import com.willswill.qrtunnel.core.AppConfigs;
8 | import com.willswill.qrtunnel.core.Encoder;
9 | import com.willswill.qrtunnel.core.EncoderCallback;
10 | import com.willswill.qrtunnel.core.FileInfo;
11 | import lombok.extern.slf4j.Slf4j;
12 |
13 | import javax.swing.*;
14 | import java.awt.*;
15 | import java.awt.image.BufferedImage;
16 | import java.io.File;
17 | import java.util.ArrayList;
18 |
19 | /**
20 | * @author Will
21 | */
22 | @Slf4j
23 | public class SenderForm {
24 | private JPanel panel1;
25 | private JButton startButton;
26 | private JButton chooseButton;
27 | private JPanel imagePanel;
28 | private JButton stopButton;
29 | private JProgressBar totalProgress;
30 | private JProgressBar fileProgress;
31 | private JLabel filenameLabel;
32 | private java.util.List imageViewList;
33 |
34 | private JFrame frame;
35 | private Encoder encoder;
36 | private File selectedFile = null;
37 | private boolean running = false;
38 |
39 | private int totalFiles;
40 | private int fileIndex;
41 | private int totalImages;
42 | private int imageIndex;
43 |
44 | public static SenderForm create() {
45 | JFrame frame = new JFrame("SenderForm");
46 | frame.setSize(500, 500);
47 | SenderForm form = new SenderForm();
48 | frame.setContentPane(form.panel1);
49 | frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
50 | frame.setResizable(false);
51 | form.frame = frame;
52 |
53 | form.initForm();
54 |
55 | frame.pack();
56 | frame.setVisible(true);
57 | return form;
58 | }
59 |
60 | public void show() {
61 | frame.setVisible(true);
62 | }
63 |
64 | public void resetLayout() {
65 | initImagePanel();
66 | showLayoutImage();
67 | }
68 |
69 | public void initForm() {
70 | initEncoder();
71 | initFileChooser();
72 | initImagePanel();
73 | initOtherComponents();
74 | }
75 |
76 | void initEncoder() {
77 | encoder = new Encoder(Launcher.getAppConfigs(), new EncoderCallback() {
78 | @Override
79 | public void imageCreated(int num, BufferedImage image) {
80 | try {
81 | imageIndex = num;
82 | updateProgress();
83 | imageViewList.get(num % imageViewList.size()).setImage(image);
84 | if (num % imageViewList.size() == 0 || num == totalImages) {
85 | Thread.sleep(Launcher.getAppConfigs().getSendInterval());
86 | }
87 | } catch (Exception e) {
88 | log.error("Error displaying image", e);
89 | }
90 | }
91 |
92 | @Override
93 | public void fileBegin(FileInfo fileInfo) {
94 | totalImages = fileInfo.getChunkCount();
95 | updateProgress();
96 | filenameLabel.setText(fileInfo.getFilename());
97 | Launcher.log("Sending file " + fileInfo.getFilename());
98 | }
99 | });
100 | }
101 |
102 | void initFileChooser() {
103 | chooseButton.addActionListener(e -> {
104 | JFileChooser fileChooser = new JFileChooser(selectedFile == null ? new File("").getAbsoluteFile() : selectedFile.getParentFile());
105 | fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
106 | fileChooser.setDialogTitle("Choose File To Send");
107 | fileChooser.showDialog(new JLabel(), "Choose");
108 | File file = fileChooser.getSelectedFile();
109 | if (file != null && file.exists()) {
110 | selectedFile = file;
111 | Launcher.getAppConfigs().setRootPath(selectedFile.getParent());
112 | Launcher.log("Selected File " + file.getAbsolutePath());
113 | }
114 | });
115 | }
116 |
117 | void initOtherComponents() {
118 | startButton.addActionListener(e -> {
119 | if (selectedFile == null) {
120 | JOptionPane.showMessageDialog(panel1, "No file selected!");
121 | return;
122 | }
123 | processFileAsync(selectedFile);
124 | });
125 |
126 | stopButton.addActionListener(e -> {
127 | running = false;
128 | encoder.interrupt();
129 | });
130 |
131 | showLayoutImage();
132 | }
133 |
134 | void initImagePanel() {
135 | imagePanel.removeAll();
136 | imageViewList = new ArrayList<>();
137 | AppConfigs appConfigs = Launcher.getAppConfigs();
138 | String[] split = appConfigs.getSenderLayout().split("\\*");
139 | int rows = Integer.parseInt(split[0]);
140 | int cols = Integer.parseInt(split[1]);
141 | imagePanel.setPreferredSize(new Dimension(appConfigs.getImageWidth() * cols, appConfigs.getImageHeight() * rows));
142 | for (int i = 0; i < rows * cols; i++) {
143 | ImageView imageView = new ImageView(null, appConfigs.getImageWidth(), appConfigs.getImageWidth(), 0);
144 | imagePanel.add(imageView, BorderLayout.CENTER);
145 | imageViewList.add(imageView);
146 | }
147 | imagePanel.updateUI();
148 | frame.pack();
149 | }
150 |
151 | void showLayoutImage() {
152 | try {
153 | AppConfigs appConfigs = Launcher.getAppConfigs();
154 | for (int i = 0; i < imageViewList.size(); i++) {
155 | ImageView imageView = imageViewList.get(i);
156 | String content = (i + 1) + "/" + appConfigs.getSenderLayout() + "/" + imageView.getImageWidth() + "*" + imageView.getImageHeight();
157 | BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, appConfigs.getImageWidth(), appConfigs.getImageWidth());
158 | BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
159 | imageView.setImage(image);
160 | }
161 | } catch (Exception e) {
162 | log.error("Can't create QR code", e);
163 | }
164 | }
165 |
166 | void processFileAsync(File selectedFile) {
167 | new Thread(() -> {
168 | chooseButton.setEnabled(false);
169 | startButton.setEnabled(false);
170 | stopButton.setEnabled(true);
171 | frame.setAlwaysOnTop(true);
172 | try {
173 | processFile(selectedFile);
174 | } catch (Exception ex) {
175 | log.error("Error processing file", ex);
176 | Launcher.log(ex.getClass().getName() + ": " + ex.getMessage());
177 | }
178 | frame.setAlwaysOnTop(false);
179 | chooseButton.setEnabled(true);
180 | startButton.setEnabled(true);
181 | stopButton.setEnabled(false);
182 | }).start();
183 | }
184 |
185 | void processFile(File selectedFile) {
186 | if (!selectedFile.exists()) {
187 | log.error("selected file is not exist: " + selectedFile.getAbsolutePath());
188 | return;
189 | }
190 |
191 | if (selectedFile.isFile()) {
192 | totalFiles = 1;
193 | fileIndex = 1;
194 | updateProgress();
195 | try {
196 | encoder.encode(selectedFile);
197 | } catch (Exception ex) {
198 | log.error("Error processing file", ex);
199 | Launcher.log(ex.getClass().getName() + ": " + ex.getMessage());
200 | }
201 | } else if (selectedFile.isDirectory()) {
202 | java.util.List files = listFiles(selectedFile);
203 | totalFiles = files.size();
204 | running = true;
205 | for (int i = 0; i < files.size(); i++) {
206 | if (!running) {
207 | break;
208 | }
209 | fileIndex = i + 1;
210 | updateProgress();
211 | File file = files.get(i);
212 | try {
213 | encoder.encode(file);
214 | } catch (Exception ex) {
215 | log.error("Error processing file", ex);
216 | Launcher.log(ex.getClass().getName() + ": " + ex.getMessage());
217 | }
218 | }
219 | }
220 | resetProgress();
221 | showLayoutImage();
222 | }
223 |
224 | java.util.List listFiles(File dir) {
225 | java.util.List fileList = new ArrayList<>();
226 | File[] files = dir.listFiles();
227 | for (File file : files) {
228 | if (file.isFile()) {
229 | fileList.add(file);
230 | } else if (file.isDirectory()) {
231 | fileList.addAll(listFiles(file));
232 | }
233 | }
234 | return fileList;
235 | }
236 |
237 | void updateProgress() {
238 | totalProgress.setMaximum(totalFiles);
239 | totalProgress.setValue(fileIndex);
240 | fileProgress.setMaximum(totalImages);
241 | fileProgress.setValue(imageIndex);
242 | }
243 |
244 | void resetProgress() {
245 | totalFiles = 0;
246 | fileIndex = 0;
247 | totalImages = 0;
248 | imageIndex = 0;
249 | filenameLabel.setText("");
250 | updateProgress();
251 | }
252 |
253 | {
254 | // GUI initializer generated by IntelliJ IDEA GUI Designer
255 | // >>> IMPORTANT!! <<<
256 | // DO NOT EDIT OR ADD ANY CODE HERE!
257 | $$$setupUI$$$();
258 | }
259 |
260 | /**
261 | * Method generated by IntelliJ IDEA GUI Designer
262 | * >>> IMPORTANT!! <<<
263 | * DO NOT edit this method OR call it in your code!
264 | *
265 | * @noinspection ALL
266 | */
267 | private void $$$setupUI$$$() {
268 | panel1 = new JPanel();
269 | panel1.setLayout(new BorderLayout(0, 0));
270 | panel1.setMinimumSize(new Dimension(444, 400));
271 | final JPanel panel2 = new JPanel();
272 | panel2.setLayout(new BorderLayout(0, 0));
273 | panel1.add(panel2, BorderLayout.NORTH);
274 | final JPanel panel3 = new JPanel();
275 | panel3.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 0));
276 | panel2.add(panel3, BorderLayout.WEST);
277 | chooseButton = new JButton();
278 | chooseButton.setText("Choose File");
279 | panel3.add(chooseButton);
280 | final JPanel panel4 = new JPanel();
281 | panel4.setLayout(new BorderLayout(0, 0));
282 | panel2.add(panel4, BorderLayout.CENTER);
283 | totalProgress = new JProgressBar();
284 | totalProgress.setForeground(new Color(-11768192));
285 | totalProgress.setPreferredSize(new Dimension(146, 6));
286 | panel4.add(totalProgress, BorderLayout.NORTH);
287 | fileProgress = new JProgressBar();
288 | fileProgress.setForeground(new Color(-11768192));
289 | fileProgress.setPreferredSize(new Dimension(146, 6));
290 | panel4.add(fileProgress, BorderLayout.CENTER);
291 | filenameLabel = new JLabel();
292 | filenameLabel.setHorizontalAlignment(0);
293 | filenameLabel.setPreferredSize(new Dimension(0, 17));
294 | panel4.add(filenameLabel, BorderLayout.SOUTH);
295 | final JPanel panel5 = new JPanel();
296 | panel5.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 0));
297 | panel2.add(panel5, BorderLayout.EAST);
298 | startButton = new JButton();
299 | startButton.setText("Start");
300 | panel5.add(startButton);
301 | stopButton = new JButton();
302 | stopButton.setText("Stop");
303 | panel5.add(stopButton);
304 | imagePanel = new JPanel();
305 | imagePanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
306 | panel1.add(imagePanel, BorderLayout.CENTER);
307 | }
308 |
309 | /**
310 | * @noinspection ALL
311 | */
312 | public JComponent $$$getRootComponent$$$() {
313 | return panel1;
314 | }
315 |
316 | }
317 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.willswill.qrtunnel
8 | qr-tunnel
9 | pom
10 | 1.0
11 |
12 | core
13 | gui
14 |
15 |
16 | org.springframework.boot
17 | spring-boot-starter-parent
18 | 2.1.3.RELEASE
19 |
20 |
21 |
22 |
23 | UTF-8
24 | UTF-8
25 | 1.8
26 | 2.1.3.RELEASE
27 |
28 |
29 |
30 |
31 | org.projectlombok
32 | lombok
33 | 1.18.10
34 | provided
35 |
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-starter
40 |
41 |
42 |
43 | org.springframework.boot
44 | spring-boot-starter-test
45 | test
46 |
47 |
48 |
49 | com.google.zxing
50 | javase
51 | 3.4.1
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------