hlp:荆州版本

This commit is contained in:
kite_lucs
2026-10-19 17:03:47 +08:00
parent e533ea8e0b
commit 065b146998
438 changed files with 163143 additions and 185387 deletions
+77 -77
View File
@@ -1,78 +1,78 @@
# 基本 Qt 项目 .gitignore — 忽略中间文件和构建产物
# 构建目录(你的工作区包含这些目录)
arm_build/
arm_debug_build/
x86_build/
build*/
*/build/
# Qt Creator / qmake
*.pro.user
*.pro.user.*
.qmake.stash
# Make / ninja / qmake 生成文件
Makefile
Makefile.*
cmake_install.cmake
CMakeCache.txt
# 对象文件和库
*.o
*.obj
*.lo
*.la
*.al
*.a
*.so
*.dylib
*.dll
*.lib
*.exe
# moc / uic / rcc 生成的源和头
moc_*
*moc.cpp
ui_*.h
ui_*.hpp
qrc_*.cpp
qrc_*.h
*.moc
# 临时/备份/日志
*.log
*.tmp
*.swp
*~
*.orig
# IDE / 编辑器
.idea/
.vscode/
*.user
# macOS / Windows
.DS_Store
Thumbs.db
# 覆盖率 / 测试输出
coverage/
*.gcda
*.gcno
# QML/Qt 缓存(可选)
qmlcache/
# 其他可能的二进制产物
dist/
bin/
。
.svn/
.cproject
.project
printImage.*
printImageScene.bmp
printSceneView.png
# 基本 Qt 项目 .gitignore — 忽略中间文件和构建产物
# 构建目录(你的工作区包含这些目录)
arm_build/
arm_debug_build/
x86_build/
build*/
*/build/
# Qt Creator / qmake
*.pro.user
*.pro.user.*
.qmake.stash
# Make / ninja / qmake 生成文件
Makefile
Makefile.*
cmake_install.cmake
CMakeCache.txt
# 对象文件和库
*.o
*.obj
*.lo
*.la
*.al
*.a
*.so
*.dylib
*.dll
*.lib
*.exe
# moc / uic / rcc 生成的源和头
moc_*
*moc.cpp
ui_*.h
ui_*.hpp
qrc_*.cpp
qrc_*.h
*.moc
# 临时/备份/日志
*.log
*.tmp
*.swp
*~
*.orig
# IDE / 编辑器
.idea/
.vscode/
*.user
# macOS / Windows
.DS_Store
Thumbs.db
# 覆盖率 / 测试输出
coverage/
*.gcda
*.gcno
# QML/Qt 缓存(可选)
qmlcache/
# 其他可能的二进制产物
dist/
bin/
。
.svn/
.cproject
.project
printImage.*
printImageScene.bmp
printSceneView.png
dbg.txt
+529 -529
View File
File diff suppressed because it is too large Load Diff
+134 -134
View File
@@ -1,134 +1,134 @@
#ifndef __TAESCLASS_H__
#define __TAESCLASS_H__
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef unsigned long DWORD;
typedef unsigned char UCHAR,*PUCHAR;
typedef void *PVOID,*LPVOID;
typedef unsigned char byte;
typedef DWORD *PDWORD,*LPDWORD;
#ifndef VOID
#define VOID void
#endif
//#pragma once
//enum KeySize { Bits128, Bits192, Bits256 }; // key size, in bits, for construtor
#define Bits128 16
#define Bits192 24
#define Bits256 32
#if 0
static unsigned char AesSbox[16*16]=
{// populate the Sbox matrix
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/*0*/ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
/*1*/ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
/*2*/ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
/*3*/ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
/*4*/ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
/*5*/ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
/*6*/ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
/*7*/ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
/*8*/ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
/*9*/ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
/*a*/ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
/*b*/ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
/*c*/ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
/*d*/ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
/*e*/ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
/*f*/ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
static unsigned char AesiSbox[16*16]=
{
// populate the iSbox matrix
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/*0*/ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
/*1*/ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
/*2*/ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
/*3*/ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
/*4*/ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
/*5*/ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
/*6*/ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
/*7*/ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
/*8*/ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
/*9*/ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
/*a*/ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
/*b*/ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
/*c*/ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
/*d*/ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
/*e*/ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
/*f*/ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
static unsigned char AesRcon[11*4]=
{
0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00,
0x80, 0x00, 0x00, 0x00,
0x1b, 0x00, 0x00, 0x00,
0x36, 0x00, 0x00, 0x00
};
#endif
extern unsigned char AesSbox[16*16];
extern unsigned char AesiSbox[16*16];
extern unsigned char AesRcon[11*4];
class Aes // Advanced Encryption Standard
{
public:
~Aes();
Aes();
Aes(int keySize, unsigned char* keyBytes);
unsigned char State[4][4];
void Cipher(unsigned char* input, unsigned char* output); // encipher 16-bit input
void InvCipher(unsigned char* input, unsigned char* output); // decipher 16-bit input
private:
int Nb; // block size in 32-bit words. Always 4 for AES. (128 bits).
int Nk; // key size in 32-bit words. 4, 6, 8. (128, 192, 256 bits).
int Nr; // number of rounds. 10, 12, 14.
unsigned char key[32];
unsigned char w[16*15];
void SetNbNkNr(int keySize);
void AddRoundKey(int round); //轮密钥加
void SubBytes(); //S盒字节代换
void InvSubBytes(); //逆S盒字节代换
void ShiftRows(); //行移位
void InvShiftRows();
void MixColumns(); //列混淆
void InvMixColumns();
unsigned char gfmultby01(unsigned char b);
unsigned char gfmultby02(unsigned char b);
unsigned char gfmultby03(unsigned char b);
unsigned char gfmultby09(unsigned char b);
unsigned char gfmultby0b(unsigned char b);
unsigned char gfmultby0d(unsigned char b);
unsigned char gfmultby0e(unsigned char b);
void KeyExpansion(); //密钥扩展
unsigned char* SubWord(unsigned char* word); //密钥S盒字代换
unsigned char* RotWord(unsigned char* word); //密钥移位
};
class TAesClass
{
public:
TAesClass();
~TAesClass();
void InitializePrivateKey(DWORD KeySize,UCHAR *KeyBytes); //AES 密钥初始化
DWORD OnAesEncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 加密数据
DWORD OnAesUncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 解密数据
private:
Aes * m_lpAes;
};
#endif
#ifndef __TAESCLASS_H__
#define __TAESCLASS_H__
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef unsigned long DWORD;
typedef unsigned char UCHAR,*PUCHAR;
typedef void *PVOID,*LPVOID;
typedef unsigned char byte;
typedef DWORD *PDWORD,*LPDWORD;
#ifndef VOID
#define VOID void
#endif
//#pragma once
//enum KeySize { Bits128, Bits192, Bits256 }; // key size, in bits, for construtor
#define Bits128 16
#define Bits192 24
#define Bits256 32
#if 0
static unsigned char AesSbox[16*16]=
{// populate the Sbox matrix
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/*0*/ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
/*1*/ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
/*2*/ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
/*3*/ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
/*4*/ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
/*5*/ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
/*6*/ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
/*7*/ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
/*8*/ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
/*9*/ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
/*a*/ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
/*b*/ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
/*c*/ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
/*d*/ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
/*e*/ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
/*f*/ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
static unsigned char AesiSbox[16*16]=
{
// populate the iSbox matrix
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/*0*/ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
/*1*/ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
/*2*/ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
/*3*/ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
/*4*/ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
/*5*/ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
/*6*/ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
/*7*/ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
/*8*/ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
/*9*/ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
/*a*/ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
/*b*/ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
/*c*/ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
/*d*/ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
/*e*/ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
/*f*/ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
static unsigned char AesRcon[11*4]=
{
0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00,
0x80, 0x00, 0x00, 0x00,
0x1b, 0x00, 0x00, 0x00,
0x36, 0x00, 0x00, 0x00
};
#endif
extern unsigned char AesSbox[16*16];
extern unsigned char AesiSbox[16*16];
extern unsigned char AesRcon[11*4];
class Aes // Advanced Encryption Standard
{
public:
~Aes();
Aes();
Aes(int keySize, unsigned char* keyBytes);
unsigned char State[4][4];
void Cipher(unsigned char* input, unsigned char* output); // encipher 16-bit input
void InvCipher(unsigned char* input, unsigned char* output); // decipher 16-bit input
private:
int Nb; // block size in 32-bit words. Always 4 for AES. (128 bits).
int Nk; // key size in 32-bit words. 4, 6, 8. (128, 192, 256 bits).
int Nr; // number of rounds. 10, 12, 14.
unsigned char key[32];
unsigned char w[16*15];
void SetNbNkNr(int keySize);
void AddRoundKey(int round); //轮密钥加
void SubBytes(); //S盒字节代换
void InvSubBytes(); //逆S盒字节代换
void ShiftRows(); //行移位
void InvShiftRows();
void MixColumns(); //列混淆
void InvMixColumns();
unsigned char gfmultby01(unsigned char b);
unsigned char gfmultby02(unsigned char b);
unsigned char gfmultby03(unsigned char b);
unsigned char gfmultby09(unsigned char b);
unsigned char gfmultby0b(unsigned char b);
unsigned char gfmultby0d(unsigned char b);
unsigned char gfmultby0e(unsigned char b);
void KeyExpansion(); //密钥扩展
unsigned char* SubWord(unsigned char* word); //密钥S盒字代换
unsigned char* RotWord(unsigned char* word); //密钥移位
};
class TAesClass
{
public:
TAesClass();
~TAesClass();
void InitializePrivateKey(DWORD KeySize,UCHAR *KeyBytes); //AES 密钥初始化
DWORD OnAesEncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 加密数据
DWORD OnAesUncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 解密数据
private:
Aes * m_lpAes;
};
#endif
+119 -119
View File
@@ -1,119 +1,119 @@
/*
* barcode.h -- definitions for libbarcode
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _BARCODE_H_
#define _BARCODE_H_
#include <stdio.h>
#define BARCODE_VERSION "0.98"
#define BARCODE_VERSION_INT 9800
/*
* The object
*/
struct Barcode_Item {
int flags; /* type of encoding and decoding */
char *ascii; /* malloced */
char *partial; /* malloced too */
char *textinfo; /* information about text positioning */
char *encoding; /* code name, filled by encoding engine */
int width, height; /* output units */
int xoff, yoff; /* output units */
int margin; /* output units */
double scalef; /* requested scaling for barcode */
int error; /* an errno-like value, in case of failure */
};
/*
* The flags field
*/
#define BARCODE_DEFAULT_FLAGS 0x00000000
#define BARCODE_ENCODING_MASK 0x000000ff /* 256 possibilites... */
#define BARCODE_NO_ASCII 0x00000100 /* avoid text in output */
#define BARCODE_NO_CHECKSUM 0x00000200 /* avoid checksum in output */
#define BARCODE_OUTPUT_MASK 0x000ff000 /* 256 output types */
#define BARCODE_OUT_EPS 0x00001000
#define BARCODE_OUT_PS 0x00002000
#define BARCODE_OUT_PCL 0x00004000 /* by Andrea Scopece */
/* PCL_III 0x00008000 */
#define BARCODE_OUT_PCL_III 0x0000C000
#define BARCODE_OUT_NOHEADERS 0x00100000 /* no header nor footer */
enum {
BARCODE_ANY = 0, /* choose best-fit */
BARCODE_EAN,
BARCODE_UPC, /* upc == 12-digit ean */
BARCODE_ISBN, /* isbn numbers (still EAN13) */
BARCODE_39, /* code 39 */
BARCODE_128, /* code 128 (a,b,c: autoselection) */
BARCODE_128C, /* code 128 (compact form for digits) */
BARCODE_128B, /* code 128, full printable ascii */
BARCODE_I25, /* interleaved 2 of 5 (only digits) */
BARCODE_128RAW, /* Raw code 128 (by Leonid A. Broukhis) */
BARCODE_CBR, /* Codabar (by Leonid A. Broukhis) */
BARCODE_MSI, /* MSI (by Leonid A. Broukhis) */
BARCODE_PLS, /* Plessey (by Leonid A. Broukhis) */
BARCODE_93 /* code 93 (by Nathan D. Holmes) */
};
#define BARCODE_DEFAULT_MARGIN 10
#ifdef __cplusplus
extern "C" {
#endif
/*
* Create and destroy barcode structures
*/
extern struct Barcode_Item *Barcode_Create(char *text);
extern int Barcode_Delete(struct Barcode_Item *bc);
/*
* Encode and print
*/
extern int Barcode_Encode(struct Barcode_Item *bc, int flags);
extern int Barcode_Print(struct Barcode_Item *bc, FILE *f, int flags);
/*
* Choose the position
*/
extern int Barcode_Position(struct Barcode_Item *bc, int wid, int hei,
int xoff, int yoff, double scalef);
/*
* Do it all in one step
*/
extern int Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags);
/*
* Return current version (integer and string)
*/
extern int Barcode_Version(char *versionname);
#ifdef __cplusplus
}
#endif
#endif /* _BARCODE_H_ */
/*
* barcode.h -- definitions for libbarcode
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _BARCODE_H_
#define _BARCODE_H_
#include <stdio.h>
#define BARCODE_VERSION "0.98"
#define BARCODE_VERSION_INT 9800
/*
* The object
*/
struct Barcode_Item {
int flags; /* type of encoding and decoding */
char *ascii; /* malloced */
char *partial; /* malloced too */
char *textinfo; /* information about text positioning */
char *encoding; /* code name, filled by encoding engine */
int width, height; /* output units */
int xoff, yoff; /* output units */
int margin; /* output units */
double scalef; /* requested scaling for barcode */
int error; /* an errno-like value, in case of failure */
};
/*
* The flags field
*/
#define BARCODE_DEFAULT_FLAGS 0x00000000
#define BARCODE_ENCODING_MASK 0x000000ff /* 256 possibilites... */
#define BARCODE_NO_ASCII 0x00000100 /* avoid text in output */
#define BARCODE_NO_CHECKSUM 0x00000200 /* avoid checksum in output */
#define BARCODE_OUTPUT_MASK 0x000ff000 /* 256 output types */
#define BARCODE_OUT_EPS 0x00001000
#define BARCODE_OUT_PS 0x00002000
#define BARCODE_OUT_PCL 0x00004000 /* by Andrea Scopece */
/* PCL_III 0x00008000 */
#define BARCODE_OUT_PCL_III 0x0000C000
#define BARCODE_OUT_NOHEADERS 0x00100000 /* no header nor footer */
enum {
BARCODE_ANY = 0, /* choose best-fit */
BARCODE_EAN,
BARCODE_UPC, /* upc == 12-digit ean */
BARCODE_ISBN, /* isbn numbers (still EAN13) */
BARCODE_39, /* code 39 */
BARCODE_128, /* code 128 (a,b,c: autoselection) */
BARCODE_128C, /* code 128 (compact form for digits) */
BARCODE_128B, /* code 128, full printable ascii */
BARCODE_I25, /* interleaved 2 of 5 (only digits) */
BARCODE_128RAW, /* Raw code 128 (by Leonid A. Broukhis) */
BARCODE_CBR, /* Codabar (by Leonid A. Broukhis) */
BARCODE_MSI, /* MSI (by Leonid A. Broukhis) */
BARCODE_PLS, /* Plessey (by Leonid A. Broukhis) */
BARCODE_93 /* code 93 (by Nathan D. Holmes) */
};
#define BARCODE_DEFAULT_MARGIN 10
#ifdef __cplusplus
extern "C" {
#endif
/*
* Create and destroy barcode structures
*/
extern struct Barcode_Item *Barcode_Create(char *text);
extern int Barcode_Delete(struct Barcode_Item *bc);
/*
* Encode and print
*/
extern int Barcode_Encode(struct Barcode_Item *bc, int flags);
extern int Barcode_Print(struct Barcode_Item *bc, FILE *f, int flags);
/*
* Choose the position
*/
extern int Barcode_Position(struct Barcode_Item *bc, int wid, int hei,
int xoff, int yoff, double scalef);
/*
* Do it all in one step
*/
extern int Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags);
/*
* Return current version (integer and string)
*/
extern int Barcode_Version(char *versionname);
#ifdef __cplusplus
}
#endif
#endif /* _BARCODE_H_ */
+177 -177
View File
@@ -1,177 +1,177 @@
/*
* cmdline.c -- parse a command line using getopt, environment and defaults
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* Changes:
* Michele Comitini (mcm@glisco.it): better handling of numeric type args.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef NO_GETOPT
/* use replacement */
#include "compat/getopt.h"
#else
#include <getopt.h>
#endif
#include "cmdline.h"
/* In case of error, print help string and return error (-1) */
int commandline_errormsg(FILE *f, struct commandline *args,
char *prgname, char *messagehead)
{
char *buffer;
char *buffer2;
int len;
struct commandline *ptr;
if (!messagehead) {
fprintf(f,"%s: Error in cmdline\nPossible options:\n",prgname);
} else {
fprintf(f,"%s: %s",prgname,messagehead);
}
for (ptr = args; ptr->option; ptr++) {
if (ptr->descrip) {
len = strlen(ptr->descrip);
len += ptr->default_v ? strlen(ptr->default_v) : 6;
len += ptr->env ? strlen(ptr->env) : 6;
buffer2 = malloc(len+3); /* 3 to be safe :) */
len += 32;
if (buffer2) {
buffer = malloc(len);
if (buffer) {
sprintf(buffer2, ptr->descrip,
ptr->default_v ? ptr->default_v : "(none)",
ptr->env ? ptr->env : "(none)");
sprintf(buffer, " -%c %s %s", ptr->option,
ptr->type ? "<arg>" : " ", buffer2);
fprintf(f, "%s\n",buffer);
free(buffer);
}
free(buffer2);
}
}
}
return -1;
}
/*
* Associate formats to type.
*/
struct type_fmt {
enum option_type type;
char *fmt;
};
static struct type_fmt formats[] = {
{CMDLINE_I, "%i%s"}, /* the trailing "%s" is used for error check */
{CMDLINE_D, "%d%s"},
{CMDLINE_X, "%x%s"},
{CMDLINE_O, "%o%s"},
{CMDLINE_F, "%lf%s"},
{CMDLINE_P, "%p%s"},
{0, NULL} /* If we get here, it's CMDLINE_S: no sscanf buf strcpy() */
};
/* Parse one argument (default or provided) */
static int commandline_oneopt(struct commandline *ptr, char *value)
{
struct type_fmt *tptr;
char *trash = value ? strdup(value) : NULL;
/* convert it, if needed */
if ((ptr->type != CMDLINE_NONE) && ptr->result) {
for (tptr = formats; tptr->type; tptr++)
if (tptr->type == ptr->type)
break;
if (!tptr->type) /* not found: it is a string */
*(char **)(ptr->result) = value;
else
if (sscanf(value, tptr->fmt, ptr->result, trash)!=1) {
free(trash);
return -1;
}
}
if (trash)
free(trash);
if ((ptr->type == CMDLINE_NONE) && ptr->result) /* no type, just count */
(*(int *)(ptr->result))++;
/* call the function, if needed */
if (ptr->fun) {
if (ptr->type) {
if (ptr->result) return ptr->fun(ptr->result); /* converted */
return ptr->fun(value); /* type, but not converted */
}
return ptr->fun(NULL); /* no type: just call it */
}
return 0;
}
/* The main function */
int commandline(struct commandline *args, int argc, char **argv,
char *errorhead)
{
struct commandline *ptr;
char *getopt_desc = (char *)calloc(512, 1);
int desc_offset = 0;
int opt, retval;
char *value;
/* Build getopt string and process defaults values */
for (ptr = args; ptr->option; ptr++) {
getopt_desc[desc_offset++] = ptr->option;
if (ptr->type) getopt_desc[desc_offset++] = ':';
value = NULL;
if (ptr->env)
value = getenv(ptr->env);
if (!value)
value = ptr->default_v;
if (value && (retval = commandline_oneopt(ptr, value))) {
/*
* if the function returns a specific (not -1) value, it already
* printed its message, so avoid the generic help
*/
if (retval == -1)
commandline_errormsg(stderr, args, argv[0], errorhead);
return retval;
}
}
/* Run getopt and process material */
while ((opt = getopt(argc, argv, getopt_desc)) != -1) {
for (ptr = args; ptr->option; ptr++)
if (opt == ptr->option)
break;
if (!ptr->option) /* unknown option */
return commandline_errormsg(stderr, args, argv[0], errorhead);
if ( (retval = commandline_oneopt(ptr, optarg)) ) { /* wrong arg */
if (retval == -1)
commandline_errormsg(stderr, args, argv[0], errorhead);
return retval;
}
}
return 0;
}
/*
* cmdline.c -- parse a command line using getopt, environment and defaults
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* Changes:
* Michele Comitini (mcm@glisco.it): better handling of numeric type args.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef NO_GETOPT
/* use replacement */
#include "compat/getopt.h"
#else
#include <getopt.h>
#endif
#include "cmdline.h"
/* In case of error, print help string and return error (-1) */
int commandline_errormsg(FILE *f, struct commandline *args,
char *prgname, char *messagehead)
{
char *buffer;
char *buffer2;
int len;
struct commandline *ptr;
if (!messagehead) {
fprintf(f,"%s: Error in cmdline\nPossible options:\n",prgname);
} else {
fprintf(f,"%s: %s",prgname,messagehead);
}
for (ptr = args; ptr->option; ptr++) {
if (ptr->descrip) {
len = strlen(ptr->descrip);
len += ptr->default_v ? strlen(ptr->default_v) : 6;
len += ptr->env ? strlen(ptr->env) : 6;
buffer2 = malloc(len+3); /* 3 to be safe :) */
len += 32;
if (buffer2) {
buffer = malloc(len);
if (buffer) {
sprintf(buffer2, ptr->descrip,
ptr->default_v ? ptr->default_v : "(none)",
ptr->env ? ptr->env : "(none)");
sprintf(buffer, " -%c %s %s", ptr->option,
ptr->type ? "<arg>" : " ", buffer2);
fprintf(f, "%s\n",buffer);
free(buffer);
}
free(buffer2);
}
}
}
return -1;
}
/*
* Associate formats to type.
*/
struct type_fmt {
enum option_type type;
char *fmt;
};
static struct type_fmt formats[] = {
{CMDLINE_I, "%i%s"}, /* the trailing "%s" is used for error check */
{CMDLINE_D, "%d%s"},
{CMDLINE_X, "%x%s"},
{CMDLINE_O, "%o%s"},
{CMDLINE_F, "%lf%s"},
{CMDLINE_P, "%p%s"},
{0, NULL} /* If we get here, it's CMDLINE_S: no sscanf buf strcpy() */
};
/* Parse one argument (default or provided) */
static int commandline_oneopt(struct commandline *ptr, char *value)
{
struct type_fmt *tptr;
char *trash = value ? strdup(value) : NULL;
/* convert it, if needed */
if ((ptr->type != CMDLINE_NONE) && ptr->result) {
for (tptr = formats; tptr->type; tptr++)
if (tptr->type == ptr->type)
break;
if (!tptr->type) /* not found: it is a string */
*(char **)(ptr->result) = value;
else
if (sscanf(value, tptr->fmt, ptr->result, trash)!=1) {
free(trash);
return -1;
}
}
if (trash)
free(trash);
if ((ptr->type == CMDLINE_NONE) && ptr->result) /* no type, just count */
(*(int *)(ptr->result))++;
/* call the function, if needed */
if (ptr->fun) {
if (ptr->type) {
if (ptr->result) return ptr->fun(ptr->result); /* converted */
return ptr->fun(value); /* type, but not converted */
}
return ptr->fun(NULL); /* no type: just call it */
}
return 0;
}
/* The main function */
int commandline(struct commandline *args, int argc, char **argv,
char *errorhead)
{
struct commandline *ptr;
char *getopt_desc = (char *)calloc(512, 1);
int desc_offset = 0;
int opt, retval;
char *value;
/* Build getopt string and process defaults values */
for (ptr = args; ptr->option; ptr++) {
getopt_desc[desc_offset++] = ptr->option;
if (ptr->type) getopt_desc[desc_offset++] = ':';
value = NULL;
if (ptr->env)
value = getenv(ptr->env);
if (!value)
value = ptr->default_v;
if (value && (retval = commandline_oneopt(ptr, value))) {
/*
* if the function returns a specific (not -1) value, it already
* printed its message, so avoid the generic help
*/
if (retval == -1)
commandline_errormsg(stderr, args, argv[0], errorhead);
return retval;
}
}
/* Run getopt and process material */
while ((opt = getopt(argc, argv, getopt_desc)) != -1) {
for (ptr = args; ptr->option; ptr++)
if (opt == ptr->option)
break;
if (!ptr->option) /* unknown option */
return commandline_errormsg(stderr, args, argv[0], errorhead);
if ( (retval = commandline_oneopt(ptr, optarg)) ) { /* wrong arg */
if (retval == -1)
commandline_errormsg(stderr, args, argv[0], errorhead);
return retval;
}
}
return 0;
}
+58 -58
View File
@@ -1,58 +1,58 @@
/*
* cmdline.h -- generic commandline editing (uses getopt, only short)
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
*/
/*
* The options may have different arguments of different type
*/
enum option_type {
CMDLINE_NONE=0, /* no argument after option */
CMDLINE_I, /* integer (any base) */
CMDLINE_D, /* decimal integer */
CMDLINE_X, /* hex integer */
CMDLINE_O, /* octal integer */
CMDLINE_S, /* string */
CMDLINE_F, /* double float */
CMDLINE_P, /* pointer */
};
struct commandline {
int option; /* Single byte: option id */
int type; /* Type of argument, used in sscanf */
void *result; /* Store data here, if non null */
int (*fun)(void *); /* Call if defined: arg is "result" or input string */
char *env; /* Where to get runtime defaults, may be NULL */
char *default_v; /* The compile-time default, may be NULL */
char *descrip; /* For err msg. May have %s's for default and env */
};
/* returns: 0 or -1. "optarg" is global (see getopt) */
extern int commandline(struct commandline *args,
int argc, char **argv, char *errorhead);
/* prints an error message based on "args" */
extern int commandline_errormsg(FILE *f, struct commandline *args,
char *prgname, char *messagehead);
/*
* cmdline.h -- generic commandline editing (uses getopt, only short)
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
*/
/*
* The options may have different arguments of different type
*/
enum option_type {
CMDLINE_NONE=0, /* no argument after option */
CMDLINE_I, /* integer (any base) */
CMDLINE_D, /* decimal integer */
CMDLINE_X, /* hex integer */
CMDLINE_O, /* octal integer */
CMDLINE_S, /* string */
CMDLINE_F, /* double float */
CMDLINE_P, /* pointer */
};
struct commandline {
int option; /* Single byte: option id */
int type; /* Type of argument, used in sscanf */
void *result; /* Store data here, if non null */
int (*fun)(void *); /* Call if defined: arg is "result" or input string */
char *env; /* Where to get runtime defaults, may be NULL */
char *default_v; /* The compile-time default, may be NULL */
char *descrip; /* For err msg. May have %s's for default and env */
};
/* returns: 0 or -1. "optarg" is global (see getopt) */
extern int commandline(struct commandline *args,
int argc, char **argv, char *errorhead);
/* prints an error message based on "args" */
extern int commandline_errormsg(FILE *f, struct commandline *args,
char *prgname, char *messagehead);
+182 -182
View File
@@ -1,182 +1,182 @@
/*
* codabar.c -- encoding for Codabar
*
* Copyright (c) 2000 Leonid A. Broukhis (leob@mailcom.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"0123456789" "-$:/.+ABCD";
#define CODE_A 16
#define CODE_B 17
#define NARROW 12
#define WIDE 14
/* Patterns */
static char *patterns[] = {
"1111133","1111331","1113113","3311111","1131131",
"3111131","1311113","1311311","1331111","3113111",
"1113311","1133111","3111313","3131113","3131311",
"1131313","1133131","1313113","1113133","1113331" };
/*
* Check that the text can be encoded. Returns 0 or -1.
* If it's all lowecase convert to uppercase and accept it.
* If the first character is a letter (A to D), the last one must be too;
* no other character should be a letter.
*/
int Barcode_cbr_verify(unsigned char *text)
{
int i, lower=0, upper=0;
int startpresent = 0;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
char * pos;
if (isupper(text[i])) upper++;
if (islower(text[i])) lower++;
pos = strchr(alphabet,toupper(text[i]));
if (!pos)
return -1;
if (i == 0 && pos - alphabet >= CODE_A)
startpresent = 1;
else if (pos - alphabet >= CODE_A &&
(!startpresent || i != strlen(text) - 1))
return -1;
}
if (lower && upper)
return -1;
return 0;
}
static int add_one(char *ptr, int code)
{
sprintf(ptr,"1%s", /* separator */ patterns[code]);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_cbr_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *ptr, *textptr;
int i, code, textpos, usesum, checksum = 0, startpresent;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("codabar");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 8 * (head + text + check + tail) + margin + term. */
partial = malloc( (strlen(text) + 3) * 8 + 2);
if (!partial) {
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * (strlen + check) +term */
textinfo = malloc(10*(strlen(text) + 1) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
ptr = partial;
textptr = textinfo;
textpos = 0;
usesum = bc->flags & BARCODE_NO_CHECKSUM ? 0 : 1;
/* if no start character specified, A is used as a start character */
if (!isalpha(text[0])) {
add_one(ptr, CODE_A);
ptr += strlen(ptr);
textpos = WIDE;
checksum = CODE_A;
startpresent = 0;
} else {
startpresent = 1;
}
for (i=0; i<strlen(text); i++) {
c = strchr(alphabet, toupper(text[i]));
if (!c) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
return -1;
}
code = c - alphabet;
add_one(ptr, code);
sprintf(textptr, "%i:12:%c ", textpos, toupper(text[i]));
textpos += code < 12 ? NARROW : WIDE;
textptr += strlen(textptr);
ptr += strlen(ptr);
checksum += code;
if (startpresent && usesum && i == strlen(text) - 2) {
/* stuff a check symbol before the stop */
c = strchr(alphabet, toupper(text[i+1]));
if (!c) /* impossible */
continue;
code = c - alphabet;
checksum += code;
/* Complement to a multiple of 16 */
checksum = (checksum + 15) / 16 * 16 - checksum;
add_one(ptr, checksum);
ptr += strlen(ptr);
}
}
if (!startpresent) {
if (usesum) {
/* if no start character specified, B is used as a stop char */
checksum += CODE_B;
checksum = (checksum + 15) / 16 * 16 - checksum;
add_one(ptr, checksum);
ptr += strlen(ptr);
}
add_one(ptr, CODE_B);
}
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
/*
* codabar.c -- encoding for Codabar
*
* Copyright (c) 2000 Leonid A. Broukhis (leob@mailcom.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"0123456789" "-$:/.+ABCD";
#define CODE_A 16
#define CODE_B 17
#define NARROW 12
#define WIDE 14
/* Patterns */
static char *patterns[] = {
"1111133","1111331","1113113","3311111","1131131",
"3111131","1311113","1311311","1331111","3113111",
"1113311","1133111","3111313","3131113","3131311",
"1131313","1133131","1313113","1113133","1113331" };
/*
* Check that the text can be encoded. Returns 0 or -1.
* If it's all lowecase convert to uppercase and accept it.
* If the first character is a letter (A to D), the last one must be too;
* no other character should be a letter.
*/
int Barcode_cbr_verify(unsigned char *text)
{
int i, lower=0, upper=0;
int startpresent = 0;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
char * pos;
if (isupper(text[i])) upper++;
if (islower(text[i])) lower++;
pos = strchr(alphabet,toupper(text[i]));
if (!pos)
return -1;
if (i == 0 && pos - alphabet >= CODE_A)
startpresent = 1;
else if (pos - alphabet >= CODE_A &&
(!startpresent || i != strlen(text) - 1))
return -1;
}
if (lower && upper)
return -1;
return 0;
}
static int add_one(char *ptr, int code)
{
sprintf(ptr,"1%s", /* separator */ patterns[code]);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_cbr_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *ptr, *textptr;
int i, code, textpos, usesum, checksum = 0, startpresent;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("codabar");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 8 * (head + text + check + tail) + margin + term. */
partial = malloc( (strlen(text) + 3) * 8 + 2);
if (!partial) {
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * (strlen + check) +term */
textinfo = malloc(10*(strlen(text) + 1) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
ptr = partial;
textptr = textinfo;
textpos = 0;
usesum = bc->flags & BARCODE_NO_CHECKSUM ? 0 : 1;
/* if no start character specified, A is used as a start character */
if (!isalpha(text[0])) {
add_one(ptr, CODE_A);
ptr += strlen(ptr);
textpos = WIDE;
checksum = CODE_A;
startpresent = 0;
} else {
startpresent = 1;
}
for (i=0; i<strlen(text); i++) {
c = strchr(alphabet, toupper(text[i]));
if (!c) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
return -1;
}
code = c - alphabet;
add_one(ptr, code);
sprintf(textptr, "%i:12:%c ", textpos, toupper(text[i]));
textpos += code < 12 ? NARROW : WIDE;
textptr += strlen(textptr);
ptr += strlen(ptr);
checksum += code;
if (startpresent && usesum && i == strlen(text) - 2) {
/* stuff a check symbol before the stop */
c = strchr(alphabet, toupper(text[i+1]));
if (!c) /* impossible */
continue;
code = c - alphabet;
checksum += code;
/* Complement to a multiple of 16 */
checksum = (checksum + 15) / 16 * 16 - checksum;
add_one(ptr, checksum);
ptr += strlen(ptr);
}
}
if (!startpresent) {
if (usesum) {
/* if no start character specified, B is used as a stop char */
checksum += CODE_B;
checksum = (checksum + 15) / 16 * 16 - checksum;
add_one(ptr, checksum);
ptr += strlen(ptr);
}
add_one(ptr, CODE_B);
}
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
+618 -618
View File
File diff suppressed because it is too large Load Diff
+173 -173
View File
@@ -1,173 +1,173 @@
/*
* code39.c -- encoding for code39
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"1234567890" "ABCDEFGHIJ" "KLMNOPQRST" "UVWXYZ-. *" "$/+%";
/* the checksum alphabet has a different order */
static char checkbet[] =
"0123456789" "ABCDEFGHIJ" "KLMNOPQRST" "UVWXYZ-. $" "/+%";
/* The first 40 symbols repeat this bar pattern */
static char *bars[] = {
"31113","13113","33111","11313","31311",
"13311","11133","31131","13131","11331"};
/* The first 4 decades use these space patterns */
static char *spaces[] = {"1311","1131","1113","3111"};
/* the last four symbols are special */
static char *specialbars[] = {
"11111","11111","11111","11111"};
static char *specialspaces[] = {
"3331","3313","3133","1333"};
static char *fillers[]= {
"0a3a1c1c1a",
"1a3a1c1c1a"
};
/*
* Check that the text can be encoded. Returns 0 or -1.
* If it's all lowecase convert to uppercase and accept it
*/
int Barcode_39_verify(unsigned char *text)
{
int i, lower=0, upper=0;
if (text[0] == '\0')
return -1;
for (i=0; text[i]; i++) {
if (isupper(text[i])) upper++;
if (islower(text[i])) lower++;
if (!strchr(alphabet,toupper(text[i])))
return -1;
}
if (lower && upper)
return -1;
return 0;
}
static int add_one(char *ptr, int code)
{
char *b, *s;
if (code < 40) {
b = bars[code%10];
s = spaces[code/10];
} else {
b = specialbars[code-40];
s = specialspaces[code-40];
}
sprintf(ptr,"1%c%c%c%c%c%c%c%c%c", /* separator */
b[0], s[0], b[1], s[1], b[2], s[2],
b[3], s[3], b[4]);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_39_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *ptr, *textptr;
int i, code, textpos, checksum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("code 39");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 10* (head + text + check + tail) + margin + term. */
partial = malloc( (strlen(text) + 3) * 10 +2);
if (!partial) {
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
strcpy(partial, fillers[0]);
ptr = partial + strlen(partial);
textptr = textinfo;
textpos = 22;
for (i=0; text[i]; i++) {
c = strchr(alphabet, toupper(text[i]));
if (!c) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
return -1;
}
code = c - alphabet;
add_one(ptr, code);
c = strchr(checkbet,*c);
if (c) /* the '*' is not there */
checksum += (c-checkbet);
sprintf(textptr, "%i:12:%c ", textpos, toupper(text[i]));
textpos += 16; /* width of each code */
textptr += strlen(textptr);
ptr += strlen(ptr);
}
/* Add the checksum */
if ( (bc->flags & BARCODE_NO_CHECKSUM)==0 ) {
code = (strchr(alphabet, checkbet[checksum % 43]) - alphabet);
add_one(ptr, code);
}
strcat(ptr, fillers[1]); /* end */
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
/*
* code39.c -- encoding for code39
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"1234567890" "ABCDEFGHIJ" "KLMNOPQRST" "UVWXYZ-. *" "$/+%";
/* the checksum alphabet has a different order */
static char checkbet[] =
"0123456789" "ABCDEFGHIJ" "KLMNOPQRST" "UVWXYZ-. $" "/+%";
/* The first 40 symbols repeat this bar pattern */
static char *bars[] = {
"31113","13113","33111","11313","31311",
"13311","11133","31131","13131","11331"};
/* The first 4 decades use these space patterns */
static char *spaces[] = {"1311","1131","1113","3111"};
/* the last four symbols are special */
static char *specialbars[] = {
"11111","11111","11111","11111"};
static char *specialspaces[] = {
"3331","3313","3133","1333"};
static char *fillers[]= {
"0a3a1c1c1a",
"1a3a1c1c1a"
};
/*
* Check that the text can be encoded. Returns 0 or -1.
* If it's all lowecase convert to uppercase and accept it
*/
int Barcode_39_verify(unsigned char *text)
{
int i, lower=0, upper=0;
if (text[0] == '\0')
return -1;
for (i=0; text[i]; i++) {
if (isupper(text[i])) upper++;
if (islower(text[i])) lower++;
if (!strchr(alphabet,toupper(text[i])))
return -1;
}
if (lower && upper)
return -1;
return 0;
}
static int add_one(char *ptr, int code)
{
char *b, *s;
if (code < 40) {
b = bars[code%10];
s = spaces[code/10];
} else {
b = specialbars[code-40];
s = specialspaces[code-40];
}
sprintf(ptr,"1%c%c%c%c%c%c%c%c%c", /* separator */
b[0], s[0], b[1], s[1], b[2], s[2],
b[3], s[3], b[4]);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_39_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *ptr, *textptr;
int i, code, textpos, checksum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("code 39");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 10* (head + text + check + tail) + margin + term. */
partial = malloc( (strlen(text) + 3) * 10 +2);
if (!partial) {
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
strcpy(partial, fillers[0]);
ptr = partial + strlen(partial);
textptr = textinfo;
textpos = 22;
for (i=0; text[i]; i++) {
c = strchr(alphabet, toupper(text[i]));
if (!c) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
return -1;
}
code = c - alphabet;
add_one(ptr, code);
c = strchr(checkbet,*c);
if (c) /* the '*' is not there */
checksum += (c-checkbet);
sprintf(textptr, "%i:12:%c ", textpos, toupper(text[i]));
textpos += 16; /* width of each code */
textptr += strlen(textptr);
ptr += strlen(ptr);
}
/* Add the checksum */
if ( (bc->flags & BARCODE_NO_CHECKSUM)==0 ) {
code = (strchr(alphabet, checkbet[checksum % 43]) - alphabet);
add_one(ptr, code);
}
strcat(ptr, fillers[1]); /* end */
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
+213 -213
View File
@@ -1,213 +1,213 @@
/*
* code39.c -- encoding for code39
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
* Copyright (c) 2001 Nathan D. Holmes / FedEx Services (ndholmes@fedex.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%";
static char *codeset[] = {
"131112", "111213", "111312", "111411", "121113", /* 0 - 4 */
"121212", "121311", "111114", "131211", "141111", /* 5 - 9 */
"211113", "211212", "211311", "221112", "221211", /* A - E */
"231111", "112113", "112212", "112311", "122112", /* F - J */
"132111", "111123", "111222", "111321", "121122", /* K - O */
"131121", "212112", "212211", "211122", "211221", /* P - T */
"221121", "222111", "112122", "112221", "122121", /* U - Y */
"123111", "121131", "311112", "311211", "321111", /* Z - $ */
"112131", "113121", "211131", "121221", "312111", /* / - (%) */
"311121", "122211", "111141" /* (/) - (terminator) */
};
/* 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111 */
/* 00000000001111111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000111111111122222222 */
/* 01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567 */
static char shiftset[] =
"%$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%% /// ///// / /%%%%%% %%%%%%++++++++++++++++++++++++++%%%%%";
static char shiftset2[] =
"UABCDEFGHIJKLMNOPQRSTUVWXYZABCDE ABC FGHIJ L ZFGHIJV KLMNOWABCDEFGHIJLKMNOPQRSTUVWXYZPQRST";
#define START_STOP 47
#define EXTEND_DOLLAR 43
#define EXTEND_PERCENT 44
#define EXTEND_SLASH 45
#define EXTEND_PLUS 46
/*
* Check that the text can be encoded. Returns 0 or -1.
* All of ASCII-7 is accepted.
*/
int Barcode_93_verify(unsigned char *text)
{
int i;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
/* Test if beyond the range of 7-bit ASCII */
if ((int)text[i] > 127)
return -1;
}
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_93_encode(struct Barcode_Item *bc)
{
static unsigned char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *textptr;
int *checksum_str;
int i, code, textpos, checksum_len=0;
int c_checksum = 0;
int k_checksum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("code 93");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 6 * (head + 2* text + 2* check + tail) + margin + term. */
partial = malloc( (strlen(text) *2 + 4) * 6 +2);
if (!partial) {
bc->error = errno;
return -1;
}
checksum_str = (int *)malloc( (strlen(text) + 3) * 2 * sizeof(int));
if (!checksum_str) {
free(partial);
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
free(checksum_str);
return -1;
}
textptr = textinfo;
textpos = 22;
strcpy(partial, "0");
strcat(partial, codeset[START_STOP]);
for (i=0; i<strlen(text); i++) {
c = strchr(alphabet, text[i]);
if (!c) {
/* Encode the shift character */
switch(shiftset[text[i]])
{
case '$':
code = EXTEND_DOLLAR;
break;
case '%':
code = EXTEND_PERCENT;
break;
case '/':
code = EXTEND_SLASH;
break;
case '+':
code = EXTEND_PLUS;
break;
default:
code = 0;
break;
}
strcat(partial, codeset[code]);
checksum_str[checksum_len++] = code;
/* Encode the second character */
code = strchr(alphabet, shiftset2[text[i]]) - alphabet;
strcat(partial, codeset[code]);
checksum_str[checksum_len++] = code;
} else {
/* Character is natively supported by the symbology, encode directly */
code = c - alphabet;
strcat(partial, codeset[c -alphabet]);
checksum_str[checksum_len++] = code;
}
sprintf(textptr, "%i:12:%c ", textpos, text[i]);
textptr += strlen(textptr);
/*
* width of each code is 9; composed codes are 18, but aligning
* the text behind the right bars would be ugly, so use 9 anyways
*/
textpos += 9;
}
c_checksum=0;
k_checksum=0;
/* Add the checksum */
if ( (bc->flags & BARCODE_NO_CHECKSUM)==0 )
{
for(i=1; i<=checksum_len; i++)
{
c_checksum += i * (int)checksum_str[checksum_len - i];
k_checksum += (i+1) * (int)checksum_str[checksum_len - i];
}
c_checksum = c_checksum % 47;
k_checksum += c_checksum;
k_checksum = k_checksum % 47;
strcat(partial, codeset[c_checksum]);
strcat(partial, codeset[k_checksum]);
}
strcat(partial, codeset[START_STOP]); /* end */
/* Encodes final 1-unit width bar to turn the start character into a stop char */
strcat(partial, "1");
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
/*
* code39.c -- encoding for code39
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
* Copyright (c) 2001 Nathan D. Holmes / FedEx Services (ndholmes@fedex.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%";
static char *codeset[] = {
"131112", "111213", "111312", "111411", "121113", /* 0 - 4 */
"121212", "121311", "111114", "131211", "141111", /* 5 - 9 */
"211113", "211212", "211311", "221112", "221211", /* A - E */
"231111", "112113", "112212", "112311", "122112", /* F - J */
"132111", "111123", "111222", "111321", "121122", /* K - O */
"131121", "212112", "212211", "211122", "211221", /* P - T */
"221121", "222111", "112122", "112221", "122121", /* U - Y */
"123111", "121131", "311112", "311211", "321111", /* Z - $ */
"112131", "113121", "211131", "121221", "312111", /* / - (%) */
"311121", "122211", "111141" /* (/) - (terminator) */
};
/* 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111 */
/* 00000000001111111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000111111111122222222 */
/* 01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567 */
static char shiftset[] =
"%$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%% /// ///// / /%%%%%% %%%%%%++++++++++++++++++++++++++%%%%%";
static char shiftset2[] =
"UABCDEFGHIJKLMNOPQRSTUVWXYZABCDE ABC FGHIJ L ZFGHIJV KLMNOWABCDEFGHIJLKMNOPQRSTUVWXYZPQRST";
#define START_STOP 47
#define EXTEND_DOLLAR 43
#define EXTEND_PERCENT 44
#define EXTEND_SLASH 45
#define EXTEND_PLUS 46
/*
* Check that the text can be encoded. Returns 0 or -1.
* All of ASCII-7 is accepted.
*/
int Barcode_93_verify(unsigned char *text)
{
int i;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
/* Test if beyond the range of 7-bit ASCII */
if ((int)text[i] > 127)
return -1;
}
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_93_encode(struct Barcode_Item *bc)
{
static unsigned char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *textptr;
int *checksum_str;
int i, code, textpos, checksum_len=0;
int c_checksum = 0;
int k_checksum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("code 93");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 6 * (head + 2* text + 2* check + tail) + margin + term. */
partial = malloc( (strlen(text) *2 + 4) * 6 +2);
if (!partial) {
bc->error = errno;
return -1;
}
checksum_str = (int *)malloc( (strlen(text) + 3) * 2 * sizeof(int));
if (!checksum_str) {
free(partial);
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
free(checksum_str);
return -1;
}
textptr = textinfo;
textpos = 22;
strcpy(partial, "0");
strcat(partial, codeset[START_STOP]);
for (i=0; i<strlen(text); i++) {
c = strchr(alphabet, text[i]);
if (!c) {
/* Encode the shift character */
switch(shiftset[text[i]])
{
case '$':
code = EXTEND_DOLLAR;
break;
case '%':
code = EXTEND_PERCENT;
break;
case '/':
code = EXTEND_SLASH;
break;
case '+':
code = EXTEND_PLUS;
break;
default:
code = 0;
break;
}
strcat(partial, codeset[code]);
checksum_str[checksum_len++] = code;
/* Encode the second character */
code = strchr(alphabet, shiftset2[text[i]]) - alphabet;
strcat(partial, codeset[code]);
checksum_str[checksum_len++] = code;
} else {
/* Character is natively supported by the symbology, encode directly */
code = c - alphabet;
strcat(partial, codeset[c -alphabet]);
checksum_str[checksum_len++] = code;
}
sprintf(textptr, "%i:12:%c ", textpos, text[i]);
textptr += strlen(textptr);
/*
* width of each code is 9; composed codes are 18, but aligning
* the text behind the right bars would be ugly, so use 9 anyways
*/
textpos += 9;
}
c_checksum=0;
k_checksum=0;
/* Add the checksum */
if ( (bc->flags & BARCODE_NO_CHECKSUM)==0 )
{
for(i=1; i<=checksum_len; i++)
{
c_checksum += i * (int)checksum_str[checksum_len - i];
k_checksum += (i+1) * (int)checksum_str[checksum_len - i];
}
c_checksum = c_checksum % 47;
k_checksum += c_checksum;
k_checksum = k_checksum % 47;
strcat(partial, codeset[c_checksum]);
strcat(partial, codeset[k_checksum]);
}
strcat(partial, codeset[START_STOP]); /* end */
/* Encodes final 1-unit width bar to turn the start character into a stop char */
strcat(partial, "1");
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
+774 -774
View File
File diff suppressed because it is too large Load Diff
+164 -164
View File
@@ -1,164 +1,164 @@
/*
* i25.c -- "interleaved 2 of 5"
*
* Copyright (c) 1999,2000 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
static char *codes[] = {
"11331", "31113", "13113", "33111", "11313",
"31311", "13311", "11133", "31131", "13131"
};
static char *guard[] = {"a1a1", "c1a"}; /* begin end */
int Barcode_i25_verify(unsigned char *text)
{
if (!text[0])
return -1;
while (*text && isdigit(*text))
text++;
if (*text)
return -1; /* a non-digit char */
return 0; /* ok */
}
int Barcode_i25_encode(struct Barcode_Item *bc)
{
unsigned char *text;
unsigned char *partial; /* dynamic */
unsigned char *textinfo; /* dynamic */
unsigned char *textptr, *p1, *p2, *pd;
int i, len, sum[2], textpos, usesum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("interleaved 2 of 5");
text = bc->ascii;
if (!bc->ascii) {
bc->error = EINVAL;
return -1;
}
if ((bc->flags & BARCODE_NO_CHECKSUM)) usesum = 0; else usesum = 1;
/* create the real text string, padded to an even number of digits */
text = malloc(strlen(bc->ascii) + 3); /* leading 0, checksum, term. */
if (!text) {
bc->error = errno;
return -1;
}
/* add the leading 0 if needed */
i = strlen(bc->ascii) + usesum;
if (i % 2) {
/* add a leading 0 */
text[0] = '0';
strcpy(text+1, bc->ascii);
} else {
strcpy(text, bc->ascii);
}
/* add the trailing checksum if needed, the leading 0 is ignored */
if (usesum) {
sum[0] = sum[1] = 0;
for (i=0; text[i]; i++)
sum[i%2] += text[i]-'0';
/*
* The "even" sum must be multiplied by three, and the *
* rightmost digit is defined as "even". The digits' position
* is already correct, whether or not we added a leading zero.
* (e.g., they are in pos. 0..4 or 1..4 of the string)
*/
i = sum[0] * 3 + sum[1];
strcat(text, "0");
text[strlen(text)-1] += (10 - (i%10)) % 10;
}
/* the partial code is 5 * (text + check) + 4(head) + 3(tail) + term. */
partial = malloc( (strlen(text) + 3) * 5 +2); /* be large... */
if (!partial) {
bc->error = errno;
free(text);
return -1;
}
/* the text information is at most "nnn:fff:c " * (strlen+1) +term */
textinfo = malloc(10*(strlen(text)+1) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
free(text);
return -1;
}
strcpy(partial, "0"); /* the first space */
strcat(partial, guard[0]); /* start */
textpos = 4; /* width of initial guard */
textptr = textinfo;
len = strlen(text);
for (i=0; i<len; i+=2) {
if (!isdigit(text[i]) || !isdigit(text[i+1])) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
free(text);
return -1;
}
/* interleave two digits */
p1 = codes[text[i]-'0'];
p2 = codes[text[i+1]-'0'];
pd = partial + strlen(partial); /* destination */
while (*p1) {
*(pd++) = *(p1++);
*(pd++) = *(p2++);
}
*pd = '\0';
/* and print the ascii text (but don't print the checksum, if any */
if (usesum && strlen(text+i)==2) {
/* print only one digit, discard the checksum */
sprintf(textptr, "%i:12:%c ", textpos, text[i]);
} else {
sprintf(textptr, "%i:12:%c %i:12:%c ", textpos, text[i],
textpos+9, text[i+1]);
}
textpos += 18; /* width of two codes */
textptr += strlen(textptr);
}
strcat(partial, guard[1]);
bc->partial = partial;
bc->textinfo = textinfo;
free(text);
return 0;
}
/*
* i25.c -- "interleaved 2 of 5"
*
* Copyright (c) 1999,2000 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
static char *codes[] = {
"11331", "31113", "13113", "33111", "11313",
"31311", "13311", "11133", "31131", "13131"
};
static char *guard[] = {"a1a1", "c1a"}; /* begin end */
int Barcode_i25_verify(unsigned char *text)
{
if (!text[0])
return -1;
while (*text && isdigit(*text))
text++;
if (*text)
return -1; /* a non-digit char */
return 0; /* ok */
}
int Barcode_i25_encode(struct Barcode_Item *bc)
{
unsigned char *text;
unsigned char *partial; /* dynamic */
unsigned char *textinfo; /* dynamic */
unsigned char *textptr, *p1, *p2, *pd;
int i, len, sum[2], textpos, usesum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("interleaved 2 of 5");
text = bc->ascii;
if (!bc->ascii) {
bc->error = EINVAL;
return -1;
}
if ((bc->flags & BARCODE_NO_CHECKSUM)) usesum = 0; else usesum = 1;
/* create the real text string, padded to an even number of digits */
text = malloc(strlen(bc->ascii) + 3); /* leading 0, checksum, term. */
if (!text) {
bc->error = errno;
return -1;
}
/* add the leading 0 if needed */
i = strlen(bc->ascii) + usesum;
if (i % 2) {
/* add a leading 0 */
text[0] = '0';
strcpy(text+1, bc->ascii);
} else {
strcpy(text, bc->ascii);
}
/* add the trailing checksum if needed, the leading 0 is ignored */
if (usesum) {
sum[0] = sum[1] = 0;
for (i=0; text[i]; i++)
sum[i%2] += text[i]-'0';
/*
* The "even" sum must be multiplied by three, and the *
* rightmost digit is defined as "even". The digits' position
* is already correct, whether or not we added a leading zero.
* (e.g., they are in pos. 0..4 or 1..4 of the string)
*/
i = sum[0] * 3 + sum[1];
strcat(text, "0");
text[strlen(text)-1] += (10 - (i%10)) % 10;
}
/* the partial code is 5 * (text + check) + 4(head) + 3(tail) + term. */
partial = malloc( (strlen(text) + 3) * 5 +2); /* be large... */
if (!partial) {
bc->error = errno;
free(text);
return -1;
}
/* the text information is at most "nnn:fff:c " * (strlen+1) +term */
textinfo = malloc(10*(strlen(text)+1) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
free(text);
return -1;
}
strcpy(partial, "0"); /* the first space */
strcat(partial, guard[0]); /* start */
textpos = 4; /* width of initial guard */
textptr = textinfo;
len = strlen(text);
for (i=0; i<len; i+=2) {
if (!isdigit(text[i]) || !isdigit(text[i+1])) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
free(text);
return -1;
}
/* interleave two digits */
p1 = codes[text[i]-'0'];
p2 = codes[text[i+1]-'0'];
pd = partial + strlen(partial); /* destination */
while (*p1) {
*(pd++) = *(p1++);
*(pd++) = *(p2++);
}
*pd = '\0';
/* and print the ascii text (but don't print the checksum, if any */
if (usesum && strlen(text+i)==2) {
/* print only one digit, discard the checksum */
sprintf(textptr, "%i:12:%c ", textpos, text[i]);
} else {
sprintf(textptr, "%i:12:%c %i:12:%c ", textpos, text[i],
textpos+9, text[i+1]);
}
textpos += 18; /* width of two codes */
textptr += strlen(textptr);
}
strcat(partial, guard[1]);
bc->partial = partial;
bc->textinfo = textinfo;
free(text);
return 0;
}
+247 -247
View File
@@ -1,247 +1,247 @@
/*
* library.c -- external functions of libbarcode
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef HAVE_UNISTD_H /* sometimes (windows, for instance) it's missing */
# include <unistd.h>
#endif
#include <errno.h>
#include "barcode.h"
//#include "QFile.h"
//#include "QString.h"
/*
* This function allocates a barcode structure and strdup()s the
* text string. It returns NULL in case of error
*/
struct Barcode_Item *Barcode_Create(char *text)
{
struct Barcode_Item *bc;
bc = malloc(sizeof(*bc));
if (!bc) return NULL;
memset(bc, 0, sizeof(*bc));
bc->ascii = strdup(text);
bc->margin = BARCODE_DEFAULT_MARGIN; /* default margin */
return bc;
}
/*
* Free a barcode structure
*/
int Barcode_Delete(struct Barcode_Item *bc)
{
if (bc->ascii)
free(bc->ascii);
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
if (bc->encoding)
free(bc->encoding);
free(bc);
return 0; /* always success */
}
/*
* The various supported encodings. This might be extended to support
* dynamic addition of extra encodings
*/
extern int Barcode_ean_verify(unsigned char *text);
extern int Barcode_ean_encode(struct Barcode_Item *bc);
extern int Barcode_upc_verify(unsigned char *text);
extern int Barcode_upc_encode(struct Barcode_Item *bc);
extern int Barcode_isbn_verify(unsigned char *text);
extern int Barcode_isbn_encode(struct Barcode_Item *bc);
extern int Barcode_39_verify(unsigned char *text);
extern int Barcode_39_encode(struct Barcode_Item *bc);
extern int Barcode_128b_verify(unsigned char *text);
extern int Barcode_128b_encode(struct Barcode_Item *bc);
extern int Barcode_128c_verify(unsigned char *text);
extern int Barcode_128c_encode(struct Barcode_Item *bc);
extern int Barcode_128_verify(unsigned char *text);
extern int Barcode_128_encode(struct Barcode_Item *bc);
extern int Barcode_128raw_verify(unsigned char *text);
extern int Barcode_128raw_encode(struct Barcode_Item *bc);
extern int Barcode_i25_verify(unsigned char *text);
extern int Barcode_i25_encode(struct Barcode_Item *bc);
extern int Barcode_cbr_verify(unsigned char *text);
extern int Barcode_cbr_encode(struct Barcode_Item *bc);
extern int Barcode_msi_verify(unsigned char *text);
extern int Barcode_msi_encode(struct Barcode_Item *bc);
extern int Barcode_pls_verify(unsigned char *text);
extern int Barcode_pls_encode(struct Barcode_Item *bc);
extern int Barcode_93_verify(unsigned char *text);
extern int Barcode_93_encode(struct Barcode_Item *bc);
struct encoding {
int type;
int (*verify)(unsigned char *text);
int (*encode)(struct Barcode_Item *bc);
};
struct encoding encodings[] = {
{BARCODE_EAN, Barcode_ean_verify, Barcode_ean_encode},
{BARCODE_UPC, Barcode_upc_verify, Barcode_upc_encode},
{BARCODE_ISBN, Barcode_isbn_verify, Barcode_isbn_encode},
{BARCODE_128B, Barcode_128b_verify, Barcode_128b_encode},
{BARCODE_128C, Barcode_128c_verify, Barcode_128c_encode},
{BARCODE_128RAW, Barcode_128raw_verify, Barcode_128raw_encode},
{BARCODE_39, Barcode_39_verify, Barcode_39_encode},
{BARCODE_I25, Barcode_i25_verify, Barcode_i25_encode},
{BARCODE_128, Barcode_128_verify, Barcode_128_encode},
{BARCODE_CBR, Barcode_cbr_verify, Barcode_cbr_encode},
{BARCODE_PLS, Barcode_pls_verify, Barcode_pls_encode},
{BARCODE_MSI, Barcode_msi_verify, Barcode_msi_encode},
{BARCODE_93, Barcode_93_verify, Barcode_93_encode},
{0, NULL, NULL}
};
/*
* A function to encode a string into bc->partial, ready for
* postprocessing to the output file. Meaningful bits for "flags" are
* the encoding mask and the no-checksum flag. These bits
* get saved in the data structure.
*/
int Barcode_Encode(struct Barcode_Item *bc, int flags)
{
int validbits = BARCODE_ENCODING_MASK | BARCODE_NO_CHECKSUM;
struct encoding *cptr;
/* If any flag is cleared in "flags", inherit it from "bc->flags" */
if (!(flags & BARCODE_ENCODING_MASK))
flags |= bc->flags & BARCODE_ENCODING_MASK;
if (!(flags & BARCODE_NO_CHECKSUM))
flags |= bc->flags & BARCODE_NO_CHECKSUM;
flags = bc->flags = (flags & validbits) | (bc->flags & ~validbits);
if (!(flags & BARCODE_ENCODING_MASK)) {
/* get the first code able to handle the text */
for (cptr = encodings; cptr->verify; cptr++)
if (cptr->verify((unsigned char *)bc->ascii)==0)
break;
if (!cptr->verify) {
bc->error = EINVAL; /* no code can handle this text */
return -1;
}
flags |= cptr->type; /* this works */
bc->flags |= cptr->type;
}
for (cptr = encodings; cptr->verify; cptr++)
if (cptr->type == (flags & BARCODE_ENCODING_MASK))
break;
if (!cptr->verify) {
bc->error = EINVAL; /* invalid barcode type */
return -1;
}
if (cptr->verify(bc->ascii) != 0) {
bc->error = EINVAL;
return -1;
}
return cptr->encode(bc);
}
/*
* When multiple output formats are supported, there will
* be a jumpt table like the one for the types. Now we don't need it
*/
extern int Barcode_ps_print(struct Barcode_Item *bc, FILE *f);
extern int Barcode_pcl_print(struct Barcode_Item *bc, FILE *f);
/*
* A function to print a partially decoded string. Meaningful bits for
* "flags" are the output mask etc. These bits get saved in the data
* structure.
*/
int Barcode_Print(struct Barcode_Item *bc, FILE *f, int flags)
{
int validbits = BARCODE_OUTPUT_MASK | BARCODE_NO_ASCII
| BARCODE_OUT_NOHEADERS;
/* If any flag is clear in "flags", inherit it from "bc->flags" */
if (!(flags & BARCODE_OUTPUT_MASK))
flags |= bc->flags & BARCODE_OUTPUT_MASK;
if (!(flags & BARCODE_NO_ASCII))
flags |= bc->flags & BARCODE_NO_ASCII;
if (!(flags & BARCODE_OUT_NOHEADERS))
flags |= bc->flags & BARCODE_OUT_NOHEADERS;
flags = bc->flags = (flags & validbits) | (bc->flags & ~validbits);
if (bc->flags & BARCODE_OUT_PCL)
return Barcode_pcl_print(bc, f);
return Barcode_ps_print(bc, f);
}
/*
* Choose the position
*/
int Barcode_Position(struct Barcode_Item *bc, int wid, int hei,
int xoff, int yoff, double scalef)
{
bc->width = wid; bc->height = hei;
bc->xoff = xoff; bc->yoff = yoff;
bc->scalef = scalef;
return 0;
}
/*
* Do it all in one step
*/
int Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags)
{
struct Barcode_Item * bc;
if (!(bc=Barcode_Create(text))) {
errno = -ENOMEM;
return -1;
}
if ( Barcode_Position(bc, wid, hei, xoff, yoff, 0.0) < 0
|| Barcode_Encode(bc, flags) < 0
|| Barcode_Print(bc, f, flags) < 0) {
errno = bc->error;
Barcode_Delete(bc);
return -1;
}
Barcode_Delete(bc);
return 0;
}
/*
* Return the version
*/
int Barcode_Version(char *vptr)
{
if (vptr)
strcpy(vptr, BARCODE_VERSION);
return BARCODE_VERSION_INT;
}
/*
* library.c -- external functions of libbarcode
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef HAVE_UNISTD_H /* sometimes (windows, for instance) it's missing */
# include <unistd.h>
#endif
#include <errno.h>
#include "barcode.h"
//#include "QFile.h"
//#include "QString.h"
/*
* This function allocates a barcode structure and strdup()s the
* text string. It returns NULL in case of error
*/
struct Barcode_Item *Barcode_Create(char *text)
{
struct Barcode_Item *bc;
bc = malloc(sizeof(*bc));
if (!bc) return NULL;
memset(bc, 0, sizeof(*bc));
bc->ascii = strdup(text);
bc->margin = BARCODE_DEFAULT_MARGIN; /* default margin */
return bc;
}
/*
* Free a barcode structure
*/
int Barcode_Delete(struct Barcode_Item *bc)
{
if (bc->ascii)
free(bc->ascii);
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
if (bc->encoding)
free(bc->encoding);
free(bc);
return 0; /* always success */
}
/*
* The various supported encodings. This might be extended to support
* dynamic addition of extra encodings
*/
extern int Barcode_ean_verify(unsigned char *text);
extern int Barcode_ean_encode(struct Barcode_Item *bc);
extern int Barcode_upc_verify(unsigned char *text);
extern int Barcode_upc_encode(struct Barcode_Item *bc);
extern int Barcode_isbn_verify(unsigned char *text);
extern int Barcode_isbn_encode(struct Barcode_Item *bc);
extern int Barcode_39_verify(unsigned char *text);
extern int Barcode_39_encode(struct Barcode_Item *bc);
extern int Barcode_128b_verify(unsigned char *text);
extern int Barcode_128b_encode(struct Barcode_Item *bc);
extern int Barcode_128c_verify(unsigned char *text);
extern int Barcode_128c_encode(struct Barcode_Item *bc);
extern int Barcode_128_verify(unsigned char *text);
extern int Barcode_128_encode(struct Barcode_Item *bc);
extern int Barcode_128raw_verify(unsigned char *text);
extern int Barcode_128raw_encode(struct Barcode_Item *bc);
extern int Barcode_i25_verify(unsigned char *text);
extern int Barcode_i25_encode(struct Barcode_Item *bc);
extern int Barcode_cbr_verify(unsigned char *text);
extern int Barcode_cbr_encode(struct Barcode_Item *bc);
extern int Barcode_msi_verify(unsigned char *text);
extern int Barcode_msi_encode(struct Barcode_Item *bc);
extern int Barcode_pls_verify(unsigned char *text);
extern int Barcode_pls_encode(struct Barcode_Item *bc);
extern int Barcode_93_verify(unsigned char *text);
extern int Barcode_93_encode(struct Barcode_Item *bc);
struct encoding {
int type;
int (*verify)(unsigned char *text);
int (*encode)(struct Barcode_Item *bc);
};
struct encoding encodings[] = {
{BARCODE_EAN, Barcode_ean_verify, Barcode_ean_encode},
{BARCODE_UPC, Barcode_upc_verify, Barcode_upc_encode},
{BARCODE_ISBN, Barcode_isbn_verify, Barcode_isbn_encode},
{BARCODE_128B, Barcode_128b_verify, Barcode_128b_encode},
{BARCODE_128C, Barcode_128c_verify, Barcode_128c_encode},
{BARCODE_128RAW, Barcode_128raw_verify, Barcode_128raw_encode},
{BARCODE_39, Barcode_39_verify, Barcode_39_encode},
{BARCODE_I25, Barcode_i25_verify, Barcode_i25_encode},
{BARCODE_128, Barcode_128_verify, Barcode_128_encode},
{BARCODE_CBR, Barcode_cbr_verify, Barcode_cbr_encode},
{BARCODE_PLS, Barcode_pls_verify, Barcode_pls_encode},
{BARCODE_MSI, Barcode_msi_verify, Barcode_msi_encode},
{BARCODE_93, Barcode_93_verify, Barcode_93_encode},
{0, NULL, NULL}
};
/*
* A function to encode a string into bc->partial, ready for
* postprocessing to the output file. Meaningful bits for "flags" are
* the encoding mask and the no-checksum flag. These bits
* get saved in the data structure.
*/
int Barcode_Encode(struct Barcode_Item *bc, int flags)
{
int validbits = BARCODE_ENCODING_MASK | BARCODE_NO_CHECKSUM;
struct encoding *cptr;
/* If any flag is cleared in "flags", inherit it from "bc->flags" */
if (!(flags & BARCODE_ENCODING_MASK))
flags |= bc->flags & BARCODE_ENCODING_MASK;
if (!(flags & BARCODE_NO_CHECKSUM))
flags |= bc->flags & BARCODE_NO_CHECKSUM;
flags = bc->flags = (flags & validbits) | (bc->flags & ~validbits);
if (!(flags & BARCODE_ENCODING_MASK)) {
/* get the first code able to handle the text */
for (cptr = encodings; cptr->verify; cptr++)
if (cptr->verify((unsigned char *)bc->ascii)==0)
break;
if (!cptr->verify) {
bc->error = EINVAL; /* no code can handle this text */
return -1;
}
flags |= cptr->type; /* this works */
bc->flags |= cptr->type;
}
for (cptr = encodings; cptr->verify; cptr++)
if (cptr->type == (flags & BARCODE_ENCODING_MASK))
break;
if (!cptr->verify) {
bc->error = EINVAL; /* invalid barcode type */
return -1;
}
if (cptr->verify(bc->ascii) != 0) {
bc->error = EINVAL;
return -1;
}
return cptr->encode(bc);
}
/*
* When multiple output formats are supported, there will
* be a jumpt table like the one for the types. Now we don't need it
*/
extern int Barcode_ps_print(struct Barcode_Item *bc, FILE *f);
extern int Barcode_pcl_print(struct Barcode_Item *bc, FILE *f);
/*
* A function to print a partially decoded string. Meaningful bits for
* "flags" are the output mask etc. These bits get saved in the data
* structure.
*/
int Barcode_Print(struct Barcode_Item *bc, FILE *f, int flags)
{
int validbits = BARCODE_OUTPUT_MASK | BARCODE_NO_ASCII
| BARCODE_OUT_NOHEADERS;
/* If any flag is clear in "flags", inherit it from "bc->flags" */
if (!(flags & BARCODE_OUTPUT_MASK))
flags |= bc->flags & BARCODE_OUTPUT_MASK;
if (!(flags & BARCODE_NO_ASCII))
flags |= bc->flags & BARCODE_NO_ASCII;
if (!(flags & BARCODE_OUT_NOHEADERS))
flags |= bc->flags & BARCODE_OUT_NOHEADERS;
flags = bc->flags = (flags & validbits) | (bc->flags & ~validbits);
if (bc->flags & BARCODE_OUT_PCL)
return Barcode_pcl_print(bc, f);
return Barcode_ps_print(bc, f);
}
/*
* Choose the position
*/
int Barcode_Position(struct Barcode_Item *bc, int wid, int hei,
int xoff, int yoff, double scalef)
{
bc->width = wid; bc->height = hei;
bc->xoff = xoff; bc->yoff = yoff;
bc->scalef = scalef;
return 0;
}
/*
* Do it all in one step
*/
int Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags)
{
struct Barcode_Item * bc;
if (!(bc=Barcode_Create(text))) {
errno = -ENOMEM;
return -1;
}
if ( Barcode_Position(bc, wid, hei, xoff, yoff, 0.0) < 0
|| Barcode_Encode(bc, flags) < 0
|| Barcode_Print(bc, f, flags) < 0) {
errno = bc->error;
Barcode_Delete(bc);
return -1;
}
Barcode_Delete(bc);
return 0;
}
/*
* Return the version
*/
int Barcode_Version(char *vptr)
{
if (vptr)
strcpy(vptr, BARCODE_VERSION);
return BARCODE_VERSION_INT;
}
+155 -155
View File
@@ -1,155 +1,155 @@
/*
* msi.c -- encoding for MSI-Plessey
*
* Copyright (c) 2000 Leonid A. Broukhis (leob@mailcom.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* Patterns */
static char *patterns[] = { "13", "31" };
static char *fillers[] = { "031", "131" };
static int width = 16 /* each character uses 4 patterns */,
startpos = 6 /* length of the first filler */;
/*
* Check that the text can be encoded. Returns 0 or -1.
*/
int Barcode_msi_verify(unsigned char *text)
{
int i;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
if (!isdigit(text[i]))
return -1;
}
return 0;
}
static int add_one(char *ptr, int code)
{
sprintf(ptr, "%s%s%s%s",
patterns[(code >> 3) & 1],
patterns[(code >> 2) & 1],
patterns[(code >> 1) & 1],
patterns[code & 1]);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_msi_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *ptr, *textptr;
int i, code, textpos, usesum, checksum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("msi");
if ((bc->flags & BARCODE_NO_CHECKSUM))
usesum = 0;
else
usesum = 1;
text = bc->ascii;
/* the partial code is head + 8 * (text + check) + tail + margin + term. */
partial = malloc( 3 + 8 * (strlen(text) + 1) + 3 + 2 );
if (!partial) {
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
strcpy(partial, fillers[0]);
ptr = partial + strlen(partial);
textptr = textinfo;
textpos = startpos;
for (i=0; i<strlen(text); i++) {
code = text[i] - '0';
add_one(ptr, code);
sprintf(textptr, "%i:12:%c ", textpos, text[i]);
textpos += width; /* width of each code */
textptr += strlen(textptr);
ptr += strlen(ptr);
if (usesum) {
/* For a code ...FEDCBA the checksum is computed
* as the sum of digits of the number ...FDB plus
* the sum of digits of the number ...ECA * 2.
* Which is equivalent to the sum of each digit of ...ECA doubled
* plus carry.
*/
if ((i ^ strlen(text)) & 1) {
/* a last digit, 2 away from last, etc. */
checksum += 2 * code + (2 * code) / 10;
} else {
checksum += code;
}
}
}
/* Some implementations use a double checksum. Currently the only way
* to print a barcode with double checksum is to put the checksum
* digit printed below at the end of a code in the command line
* and re-run the program.
*/
if (usesum) {
/* the check digit is the complement of the checksum
* to a multiple of 10.
*/
checksum = (checksum + 9) / 10 * 10 - checksum;
/* fprintf(stderr, "Checksum: %d\n", checksum); */
add_one(ptr, checksum);
ptr += strlen(ptr);
}
strcpy(ptr, fillers[1]);
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
/*
* msi.c -- encoding for MSI-Plessey
*
* Copyright (c) 2000 Leonid A. Broukhis (leob@mailcom.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
/* Patterns */
static char *patterns[] = { "13", "31" };
static char *fillers[] = { "031", "131" };
static int width = 16 /* each character uses 4 patterns */,
startpos = 6 /* length of the first filler */;
/*
* Check that the text can be encoded. Returns 0 or -1.
*/
int Barcode_msi_verify(unsigned char *text)
{
int i;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
if (!isdigit(text[i]))
return -1;
}
return 0;
}
static int add_one(char *ptr, int code)
{
sprintf(ptr, "%s%s%s%s",
patterns[(code >> 3) & 1],
patterns[(code >> 2) & 1],
patterns[(code >> 1) & 1],
patterns[code & 1]);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_msi_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *ptr, *textptr;
int i, code, textpos, usesum, checksum = 0;
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("msi");
if ((bc->flags & BARCODE_NO_CHECKSUM))
usesum = 0;
else
usesum = 1;
text = bc->ascii;
/* the partial code is head + 8 * (text + check) + tail + margin + term. */
partial = malloc( 3 + 8 * (strlen(text) + 1) + 3 + 2 );
if (!partial) {
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
strcpy(partial, fillers[0]);
ptr = partial + strlen(partial);
textptr = textinfo;
textpos = startpos;
for (i=0; i<strlen(text); i++) {
code = text[i] - '0';
add_one(ptr, code);
sprintf(textptr, "%i:12:%c ", textpos, text[i]);
textpos += width; /* width of each code */
textptr += strlen(textptr);
ptr += strlen(ptr);
if (usesum) {
/* For a code ...FEDCBA the checksum is computed
* as the sum of digits of the number ...FDB plus
* the sum of digits of the number ...ECA * 2.
* Which is equivalent to the sum of each digit of ...ECA doubled
* plus carry.
*/
if ((i ^ strlen(text)) & 1) {
/* a last digit, 2 away from last, etc. */
checksum += 2 * code + (2 * code) / 10;
} else {
checksum += code;
}
}
}
/* Some implementations use a double checksum. Currently the only way
* to print a barcode with double checksum is to put the checksum
* digit printed below at the end of a code in the command line
* and re-run the program.
*/
if (usesum) {
/* the check digit is the complement of the checksum
* to a multiple of 10.
*/
checksum = (checksum + 9) / 10 * 10 - checksum;
/* fprintf(stderr, "Checksum: %d\n", checksum); */
add_one(ptr, checksum);
ptr += strlen(ptr);
}
strcpy(ptr, fillers[1]);
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
+185 -185
View File
@@ -1,185 +1,185 @@
/*
* pcl.c -- printing the "partial" bar encoding in PCL format
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
* Copyright (c) 2001 Andrea Scopece (a.scopece@tin.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
#define SHRINK_AMOUNT 0.15 /* shrink the bars to account for ink spreading */
/*
* How do the "partial" and "textinfo" strings work? See file "ps.c"
*/
int Barcode_pcl_print(struct Barcode_Item *bc, FILE *f)
{
int i, j, k, barlen;
double f1, f2, fsav=0;
int mode = '-'; /* text below bars */
double scalef=1, xpos, x0, y0, yr;
unsigned char *ptr;
unsigned char c;
char font_id[6]; /* default font, should be "scalable" */
/* 0 Line printer, use on older LJet II, isn't scalable */
/* 4148 Univers, use on LJet III series, and Lj 4L, 5L */
/* 16602 Arial, default LJ family 4, 5, 6, Color, Djet */
if (!bc->partial || !bc->textinfo) {
bc->error = EINVAL;
return -1;
}
/*
* Maybe this first part can be made common to several printing back-ends,
* we'll see how that works when other ouput engines are added
*/
/* First, calculate barlen */
barlen = bc->partial[0] - '0';
for (ptr = bc->partial+1; *ptr; ptr++)
if (isdigit(*ptr))
barlen += (*ptr - '0');
else if (islower(*ptr))
barlen += (*ptr - 'a'+1);
/* The scale factor depends on bar length */
if (!bc->scalef) {
if (!bc->width) bc->width = barlen; /* default */
scalef = bc->scalef = (double)bc->width / (double)barlen;
}
/* The width defaults to "just enough" */
if (!bc->width) bc->width = barlen * scalef +1;
/* But it can be too small, in this case enlarge and center the area */
if (bc->width < barlen * scalef) {
int wid = barlen * scalef + 1;
bc->xoff -= (wid - bc->width)/2 ;
bc->width = wid;
/* Can't extend too far on the left */
if (bc->xoff < 0) {
bc->width += -bc->xoff;
bc->xoff = 0;
}
}
/* The height defaults to 80 points (rescaled) */
if (!bc->height) bc->height = 80 * scalef;
i = 5 + 10 * ((bc->flags & BARCODE_NO_ASCII)==0);
if (bc->height < i * scalef ) {
double scaleg = ((double)bc->height) / i;
int wid = bc->width * scaleg / scalef;
bc->xoff += (bc->width - wid)/2;
bc->width = wid;
scalef = scaleg;
}
/*
* deal with PCL output
*/
xpos = bc->margin + (bc->partial[0]-'0') * scalef;
for (ptr = bc->partial+1, i=1; *ptr; ptr++, i++) {
/* special cases: '+' and '-' */
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; /* don't count it */ i++; continue;
}
/* j is the width of this bar/space */
if (isdigit (*ptr)) j = *ptr-'0';
else j = *ptr-'a'+1;
if (i%2) { /* bar */
x0 = bc->xoff + xpos;
y0 = bc->yoff + bc->margin;
yr = bc->height;
if (!(bc->flags & BARCODE_NO_ASCII)) { /* leave space for text */
if (mode == '-') {
/* text below bars: 10 points or five points */
yr -= (isdigit(*ptr) ? 10 : 5) * scalef;
} else { /* '+' */
/* text above bars: 10 or 0 from bottom, and 10 from top */
y0 += (isdigit(*ptr) ? 10 : 0) * scalef;
yr -= (isdigit(*ptr) ? 20 : 10) * scalef;
}
}
fprintf(f,"%c&a%.0fH", 27, x0 * 10.0);
fprintf(f,"%c&a%.0fV", 27, y0 * 10.0);
fprintf(f,"%c*c%.0fH", 27, ((j*scalef)-SHRINK_AMOUNT) * 10.0);
fprintf(f,"%c*c%.0fV", 27, yr * 10.0);
fprintf(f,"%c*c0P\n", 27);
}
xpos += j * scalef;
}
/* the text */
mode = '-'; /* reinstantiate default */
if (!(bc->flags & BARCODE_NO_ASCII)) {
k=0; /* k is the "previous font size" */
for (ptr = bc->textinfo; ptr; ptr = strchr(ptr, ' ')) {
while (*ptr == ' ') ptr++;
if (!*ptr) break;
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; continue;
}
if (sscanf(ptr, "%lf:%lf:%c", &f1, &f2, &c) != 3) {
fprintf(stderr, "barcode: impossible data: %s\n", ptr);
continue;
}
/* select a Scalable Font */
if (fsav != f2)
{
if ((bc->flags & BARCODE_OUT_PCL_III) == BARCODE_OUT_PCL_III)
{ strcpy(font_id, "4148"); /* font Univers */
}
else
{ strcpy(font_id, "16602"); /* font Arial */
}
fprintf(f,"%c(8U%c(s1p%5.2fv0s0b%sT", 27, 27, f2 * scalef, font_id);
}
fsav = f2;
fprintf(f,"%c&a%.0fH", 27, (bc->xoff + f1 * scalef + bc->margin) * 10.0);
fprintf(f,"%c&a%.0fV", 27,
mode != '-'
? ((double)bc->yoff + bc->margin + 8*scalef) * 10.0
: ((double)bc->yoff + bc->margin + bc->height ) * 10.0);
fprintf(f, "%c", c);
}
}
return 0;
}
/*
* pcl.c -- printing the "partial" bar encoding in PCL format
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
* Copyright (c) 2001 Andrea Scopece (a.scopece@tin.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
#define SHRINK_AMOUNT 0.15 /* shrink the bars to account for ink spreading */
/*
* How do the "partial" and "textinfo" strings work? See file "ps.c"
*/
int Barcode_pcl_print(struct Barcode_Item *bc, FILE *f)
{
int i, j, k, barlen;
double f1, f2, fsav=0;
int mode = '-'; /* text below bars */
double scalef=1, xpos, x0, y0, yr;
unsigned char *ptr;
unsigned char c;
char font_id[6]; /* default font, should be "scalable" */
/* 0 Line printer, use on older LJet II, isn't scalable */
/* 4148 Univers, use on LJet III series, and Lj 4L, 5L */
/* 16602 Arial, default LJ family 4, 5, 6, Color, Djet */
if (!bc->partial || !bc->textinfo) {
bc->error = EINVAL;
return -1;
}
/*
* Maybe this first part can be made common to several printing back-ends,
* we'll see how that works when other ouput engines are added
*/
/* First, calculate barlen */
barlen = bc->partial[0] - '0';
for (ptr = bc->partial+1; *ptr; ptr++)
if (isdigit(*ptr))
barlen += (*ptr - '0');
else if (islower(*ptr))
barlen += (*ptr - 'a'+1);
/* The scale factor depends on bar length */
if (!bc->scalef) {
if (!bc->width) bc->width = barlen; /* default */
scalef = bc->scalef = (double)bc->width / (double)barlen;
}
/* The width defaults to "just enough" */
if (!bc->width) bc->width = barlen * scalef +1;
/* But it can be too small, in this case enlarge and center the area */
if (bc->width < barlen * scalef) {
int wid = barlen * scalef + 1;
bc->xoff -= (wid - bc->width)/2 ;
bc->width = wid;
/* Can't extend too far on the left */
if (bc->xoff < 0) {
bc->width += -bc->xoff;
bc->xoff = 0;
}
}
/* The height defaults to 80 points (rescaled) */
if (!bc->height) bc->height = 80 * scalef;
i = 5 + 10 * ((bc->flags & BARCODE_NO_ASCII)==0);
if (bc->height < i * scalef ) {
double scaleg = ((double)bc->height) / i;
int wid = bc->width * scaleg / scalef;
bc->xoff += (bc->width - wid)/2;
bc->width = wid;
scalef = scaleg;
}
/*
* deal with PCL output
*/
xpos = bc->margin + (bc->partial[0]-'0') * scalef;
for (ptr = bc->partial+1, i=1; *ptr; ptr++, i++) {
/* special cases: '+' and '-' */
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; /* don't count it */ i++; continue;
}
/* j is the width of this bar/space */
if (isdigit (*ptr)) j = *ptr-'0';
else j = *ptr-'a'+1;
if (i%2) { /* bar */
x0 = bc->xoff + xpos;
y0 = bc->yoff + bc->margin;
yr = bc->height;
if (!(bc->flags & BARCODE_NO_ASCII)) { /* leave space for text */
if (mode == '-') {
/* text below bars: 10 points or five points */
yr -= (isdigit(*ptr) ? 10 : 5) * scalef;
} else { /* '+' */
/* text above bars: 10 or 0 from bottom, and 10 from top */
y0 += (isdigit(*ptr) ? 10 : 0) * scalef;
yr -= (isdigit(*ptr) ? 20 : 10) * scalef;
}
}
fprintf(f,"%c&a%.0fH", 27, x0 * 10.0);
fprintf(f,"%c&a%.0fV", 27, y0 * 10.0);
fprintf(f,"%c*c%.0fH", 27, ((j*scalef)-SHRINK_AMOUNT) * 10.0);
fprintf(f,"%c*c%.0fV", 27, yr * 10.0);
fprintf(f,"%c*c0P\n", 27);
}
xpos += j * scalef;
}
/* the text */
mode = '-'; /* reinstantiate default */
if (!(bc->flags & BARCODE_NO_ASCII)) {
k=0; /* k is the "previous font size" */
for (ptr = bc->textinfo; ptr; ptr = strchr(ptr, ' ')) {
while (*ptr == ' ') ptr++;
if (!*ptr) break;
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; continue;
}
if (sscanf(ptr, "%lf:%lf:%c", &f1, &f2, &c) != 3) {
fprintf(stderr, "barcode: impossible data: %s\n", ptr);
continue;
}
/* select a Scalable Font */
if (fsav != f2)
{
if ((bc->flags & BARCODE_OUT_PCL_III) == BARCODE_OUT_PCL_III)
{ strcpy(font_id, "4148"); /* font Univers */
}
else
{ strcpy(font_id, "16602"); /* font Arial */
}
fprintf(f,"%c(8U%c(s1p%5.2fv0s0b%sT", 27, 27, f2 * scalef, font_id);
}
fsav = f2;
fprintf(f,"%c&a%.0fH", 27, (bc->xoff + f1 * scalef + bc->margin) * 10.0);
fprintf(f,"%c&a%.0fV", 27,
mode != '-'
? ((double)bc->yoff + bc->margin + 8*scalef) * 10.0
: ((double)bc->yoff + bc->margin + bc->height ) * 10.0);
fprintf(f, "%c", c);
}
}
return 0;
}
+164 -164
View File
@@ -1,164 +1,164 @@
/*
* plessey.c -- encoding for Plessey
*
* Copyright (c) 2000 Leonid A. Broukhis (leob@mailcom.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
static char * patterns[] = { "13", "31" };
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"0123456789" "ABCDEF";
/* stop sequence may be 231311313 (barcodemill.com) */
static char *fillers[] = { "031311331", "331311313" };
static int width = 16, startpos = 16;
/*
* Check that the text can be encoded. Returns 0 or -1.
* If it's all lowecase convert to uppercase and accept it
*/
int Barcode_pls_verify(unsigned char *text)
{
int i, upper = 0, lower = 0;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
if (!strchr(alphabet,toupper(text[i])))
return -1;
if (isupper(text[i])) upper++;
if (islower(text[i])) lower++;
}
if (upper && lower)
return -1;
return 0;
}
static int add_one(char *ptr, int code)
{
sprintf(ptr, "%s%s%s%s",
patterns[code & 1],
patterns[(code >> 1) & 1],
patterns[(code >> 2) & 1],
patterns[(code >> 3) & 1]
);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_pls_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *ptr, *textptr;
unsigned char *checkptr;
int i, code, textpos;
static char check[9] = {1,1,1,1,0,1,0,0,1};
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("plessey");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 8 * (head + text + check + tail) + margin + term. */
partial = malloc( (strlen(text) + 4) * 8 + 3);
checkptr = calloc (1, strlen(text) * 4 + 8);
if (!partial || !checkptr) {
if (partial) free(partial);
if (checkptr) free(checkptr);
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
strcpy(partial, fillers[0]);
ptr = partial + strlen(partial);
textptr = textinfo;
textpos = startpos;
for (i=0; i<strlen(text); i++) {
c = strchr(alphabet, toupper(text[i]));
if (!c) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
return -1;
}
code = c - alphabet;
add_one(ptr, code);
sprintf(textptr, "%i:12:%c ", textpos, toupper(text[i]));
textpos += width; /* width of each code */
textptr += strlen(textptr);
ptr += strlen(ptr);
checkptr[4*i] = code & 1;
checkptr[4*i+1] = (code >> 1) & 1;
checkptr[4*i+2] = (code >> 2) & 1;
checkptr[4*i+3] = (code >> 3) & 1;
}
/* The CRC checksum is required */
for (i=0; i < 4*strlen(text); i++) {
int j;
if (checkptr[i])
for (j = 0; j < 9; j++)
checkptr[i+j] ^= check[j];
}
for (i = 0; i < 8; i++) {
sprintf(ptr, patterns[checkptr[strlen(text) * 4 + i]]);
ptr += 2;
}
fprintf(stderr, "CRC: ");
for (i = 0; i < 8; i++) {
fputc('0' + checkptr[strlen(text) * 4 + i], stderr);
}
fputc('\n', stderr);
strcpy(ptr, fillers[1]);
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
/*
* plessey.c -- encoding for Plessey
*
* Copyright (c) 2000 Leonid A. Broukhis (leob@mailcom.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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
static char * patterns[] = { "13", "31" };
/* this is ordered in decades to simplify encoding */
static char alphabet[] =
"0123456789" "ABCDEF";
/* stop sequence may be 231311313 (barcodemill.com) */
static char *fillers[] = { "031311331", "331311313" };
static int width = 16, startpos = 16;
/*
* Check that the text can be encoded. Returns 0 or -1.
* If it's all lowecase convert to uppercase and accept it
*/
int Barcode_pls_verify(unsigned char *text)
{
int i, upper = 0, lower = 0;
if (!strlen(text))
return -1;
for (i=0; text[i]; i++) {
if (!strchr(alphabet,toupper(text[i])))
return -1;
if (isupper(text[i])) upper++;
if (islower(text[i])) lower++;
}
if (upper && lower)
return -1;
return 0;
}
static int add_one(char *ptr, int code)
{
sprintf(ptr, "%s%s%s%s",
patterns[code & 1],
patterns[(code >> 1) & 1],
patterns[(code >> 2) & 1],
patterns[(code >> 3) & 1]
);
return 0;
}
/*
* The encoding functions fills the "partial" and "textinfo" fields.
* Lowercase chars are converted to uppercase
*/
int Barcode_pls_encode(struct Barcode_Item *bc)
{
static char *text;
static char *partial; /* dynamic */
static char *textinfo; /* dynamic */
char *c, *ptr, *textptr;
unsigned char *checkptr;
int i, code, textpos;
static char check[9] = {1,1,1,1,0,1,0,0,1};
if (bc->partial)
free(bc->partial);
if (bc->textinfo)
free(bc->textinfo);
bc->partial = bc->textinfo = NULL; /* safe */
if (!bc->encoding)
bc->encoding = strdup("plessey");
text = bc->ascii;
if (!text) {
bc->error = EINVAL;
return -1;
}
/* the partial code is 8 * (head + text + check + tail) + margin + term. */
partial = malloc( (strlen(text) + 4) * 8 + 3);
checkptr = calloc (1, strlen(text) * 4 + 8);
if (!partial || !checkptr) {
if (partial) free(partial);
if (checkptr) free(checkptr);
bc->error = errno;
return -1;
}
/* the text information is at most "nnn:fff:c " * strlen +term */
textinfo = malloc(10*strlen(text) + 2);
if (!textinfo) {
bc->error = errno;
free(partial);
return -1;
}
strcpy(partial, fillers[0]);
ptr = partial + strlen(partial);
textptr = textinfo;
textpos = startpos;
for (i=0; i<strlen(text); i++) {
c = strchr(alphabet, toupper(text[i]));
if (!c) {
bc->error = EINVAL; /* impossible if text is verified */
free(partial);
free(textinfo);
return -1;
}
code = c - alphabet;
add_one(ptr, code);
sprintf(textptr, "%i:12:%c ", textpos, toupper(text[i]));
textpos += width; /* width of each code */
textptr += strlen(textptr);
ptr += strlen(ptr);
checkptr[4*i] = code & 1;
checkptr[4*i+1] = (code >> 1) & 1;
checkptr[4*i+2] = (code >> 2) & 1;
checkptr[4*i+3] = (code >> 3) & 1;
}
/* The CRC checksum is required */
for (i=0; i < 4*strlen(text); i++) {
int j;
if (checkptr[i])
for (j = 0; j < 9; j++)
checkptr[i+j] ^= check[j];
}
for (i = 0; i < 8; i++) {
sprintf(ptr, patterns[checkptr[strlen(text) * 4 + i]]);
ptr += 2;
}
fprintf(stderr, "CRC: ");
for (i = 0; i < 8; i++) {
fputc('0' + checkptr[strlen(text) * 4 + i], stderr);
}
fputc('\n', stderr);
strcpy(ptr, fillers[1]);
bc->partial = partial;
bc->textinfo = textinfo;
return 0;
}
+259 -259
View File
@@ -1,259 +1,259 @@
/*
* ps.c -- printing the "partial" bar encoding
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
#define SHRINK_AMOUNT 0.15 /* shrink the bars to account for ink spreading */
/*
* How do the "partial" and "textinfo" strings work?
*
* The first char in "partial" tells how much extra space to add to the
* left of the bars. For EAN-13, it is used to leave space to print the
* first digit, other codes may have '0' for no-extra-space-needed.
*
* The next characters are alternating bars and spaces, as multiples
* of the base dimension which is 1 unless the code is
* rescaled. Rescaling is calculated as the ratio from the requested
* width and the calculated width. Digits represent bar/space
* dimensions. Lower-case letters represent those bars that should
* extend lower than the others: 'a' is equivalent to '1', 'b' is '2' and
* so on.
*
* The "textinfo" string is made up of fields "%lf:%lf:%c" separated by
* blank space. The first integer is the x position of the character,
* the second is the font size (before rescaling) and the char item is
* the charcter to be printed.
*
* Both the "partial" and "textinfo" strings may include "-" or "+" as
* special characters (in "textinfo" the char should be a standalone
* word). They state where the text should be printed: below the bars
* ("-", default) or above the bars. This is used, for example, to
* print the add-5 and add-2 codes to the right of UPC or EAN codes
* (the add-5 extension is mostly used in ISBN codes.
*/
int Barcode_ps_print(struct Barcode_Item *bc, FILE *f)
{
int i, j, k, barlen, printable=1;
double f1, f2, fsav=0;
int mode = '-'; /* text below bars */
double scalef=1, xpos, x0, y0, yr;
unsigned char *ptr;
unsigned char c;
if (!bc->partial || !bc->textinfo) {
bc->error = EINVAL;
return -1;
}
/*
* Maybe this first part can be made common to several printing back-ends,
* we'll see how that works when other ouput engines are added
*/
/* First, calculate barlen */
barlen = bc->partial[0] - '0';
for (ptr = bc->partial+1; *ptr; ptr++)
if (isdigit(*ptr))
barlen += (*ptr - '0');
else if (islower(*ptr))
barlen += (*ptr - 'a'+1);
/* The scale factor depends on bar length */
if (!bc->scalef) {
if (!bc->width) bc->width = barlen; /* default */
scalef = bc->scalef = (double)bc->width / (double)barlen;
}
/* The width defaults to "just enough" */
if (!bc->width) bc->width = barlen * scalef +1;
/* But it can be too small, in this case enlarge and center the area */
if (bc->width < barlen * scalef) {
int wid = barlen * scalef + 1;
bc->xoff -= (wid - bc->width)/2 ;
bc->width = wid;
/* Can't extend too far on the left */
if (bc->xoff < 0) {
bc->width += -bc->xoff;
bc->xoff = 0;
}
}
/* The height defaults to 80 points (rescaled) */
if (!bc->height) bc->height = 80 * scalef;
/* If too small (5 + text), reduce the scale factor and center */
i = 5 + 10 * ((bc->flags & BARCODE_NO_ASCII)==0);
if (bc->height < i * scalef ) {
double scaleg = ((double)bc->height) / i;
int wid = bc->width * scaleg / scalef;
bc->xoff += (bc->width - wid)/2;
bc->width = wid;
scalef = scaleg;
}
/*
* Ok, then deal with actual ps (eps) output
*/
if (!(bc->flags & BARCODE_OUT_NOHEADERS)) { /* spit a header first */
if (bc->flags & BARCODE_OUT_EPS)
fprintf(f, "%%!PS-Adobe-2.0 EPSF-1.2\n");
else
fprintf(f, "%%!PS-Adobe-2.0\n");
fprintf(f, "%%%%Creator: libbarcode\n");
if (bc->flags & BARCODE_OUT_EPS) {
fprintf(f, "%%%%BoundingBox: %i %i %i %i\n",
bc->xoff,
bc->yoff,
bc->xoff + bc->width + 2* bc->margin,
bc->yoff + bc->height + 2* bc->margin);
}
fprintf(f, "%%%%EndComments\n");
if (bc->flags & BARCODE_OUT_PS) {
fprintf(f, "%%%%EndProlog\n\n");
fprintf(f, "%%%%Page: 1 1\n\n");
}
}
/* Print some informative comments */
for (i=0; bc->ascii[i]; i++)
if (bc->ascii[i] < ' ')
printable = 0;
fprintf(f,"%% Printing barcode for \"%s\", scaled %5.2f",
printable ? bc->ascii : "<unprintable string>", scalef);
if (bc->encoding)
fprintf(f,", encoded using \"%s\"",bc->encoding);
fprintf(f, "\n");
fprintf(f,"%% The space/bar succession is represented "
"by the following widths (space first):\n"
"%% ");
for (i=0; i<strlen(bc->partial); i++) {
unsigned char c = bc->partial[i];
if (isdigit(c)) putc(c, f);
if (islower(c)) putc(c-'a'+'1', f);
if (isupper(c)) putc(c-'A'+'1', f);
}
/* open array for "forall" */
fprintf(f, "\n[\n%% height xpos ypos width"
" height xpos ypos width\n");
xpos = bc->margin + (bc->partial[0]-'0') * scalef;
for (ptr = bc->partial+1, i=1; *ptr; ptr++, i++) {
/* special cases: '+' and '-' */
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; /* don't count it */ i++; continue;
}
/* j is the width of this bar/space */
if (isdigit (*ptr)) j = *ptr-'0';
else j = *ptr-'a'+1;
if (i%2) { /* bar */
x0 = bc->xoff + xpos + (j*scalef)/2;
y0 = bc->yoff + bc->margin;
yr = bc->height;
if (!(bc->flags & BARCODE_NO_ASCII)) { /* leave space for text */
if (mode == '-') {
/* text below bars: 10 points or five points */
y0 += (isdigit(*ptr) ? 10 : 5) * scalef;
yr -= (isdigit(*ptr) ? 10 : 5) * scalef;
} else { /* '+' */
/* text above bars: 10 or 0 from bottom, and 10 from top */
y0 += (isdigit(*ptr) ? 10 : 0) * scalef;
yr -= (isdigit(*ptr) ? 20 : 10) * scalef;
}
}
/* Define an array and then use "forall" (Hans Schou) */
fprintf(f," [%5.2f %6.2f %6.2f %5.2f]%s",
yr, x0, y0, (j * scalef) - SHRINK_AMOUNT,
i%4 == 1 ? " " : "\n");
}
xpos += j * scalef;
}
fprintf(f,"\n]\t{ {} forall setlinewidth moveto 0 exch rlineto stroke} "
"bind forall\n");
/* Then, the text */
mode = '-'; /* reinstantiate default */
if (!(bc->flags & BARCODE_NO_ASCII)) {
fprintf(f, "[\n%% char xpos ypos fontsize\n");
k=0; /* k is the "previous font size" */
for (ptr = bc->textinfo; ptr; ptr = strchr(ptr, ' ')) {
while (*ptr == ' ') ptr++;
if (!*ptr) break;
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; continue;
}
if (sscanf(ptr, "%lf:%lf:%c", &f1, &f2, &c) != 3) {
fprintf(stderr, "barcode: impossible data: %s\n", ptr);
continue;
}
fprintf(f, " [(");
/* Both the backslash and the two parens are special */
if (c=='\\' || c==')' || c=='(')
fprintf(f, "\\%c) ", c);
else
fprintf(f, "%c) ", c);
fprintf(f, "%6.2f %6.2f %5.2f]\n",
bc->xoff + f1 * scalef + bc->margin,
mode == '-'
? (double)bc->yoff + bc->margin
: (double)bc->yoff + bc->margin+bc->height - 8*scalef,
fsav == f2 ? 0.0 : f2 * scalef);
fsav = f2;
}
fprintf(f,"] { {} forall dup 0.00 ne {\n\t"
"/Helvetica findfont exch scalefont setfont\n"
" } {pop} ifelse\n"
" moveto show} bind forall\n");
}
fprintf(f,"%% End barcode for \"%s\"\n\n",
printable ? bc->ascii : "<unprintable string>");
if (!(bc->flags & BARCODE_OUT_NOHEADERS)) {
if (bc->flags & BARCODE_OUT_PS) {
fprintf(f,"showpage\n");
fprintf(f, "%%%%Trailer\n\n");
}
}
return 0;
}
/*
* ps.c -- printing the "partial" bar encoding
*
* Copyright (c) 1999 Alessandro Rubini (rubini@gnu.org)
* Copyright (c) 1999 Prosa Srl. (prosa@prosa.it)
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "barcode.h"
#define SHRINK_AMOUNT 0.15 /* shrink the bars to account for ink spreading */
/*
* How do the "partial" and "textinfo" strings work?
*
* The first char in "partial" tells how much extra space to add to the
* left of the bars. For EAN-13, it is used to leave space to print the
* first digit, other codes may have '0' for no-extra-space-needed.
*
* The next characters are alternating bars and spaces, as multiples
* of the base dimension which is 1 unless the code is
* rescaled. Rescaling is calculated as the ratio from the requested
* width and the calculated width. Digits represent bar/space
* dimensions. Lower-case letters represent those bars that should
* extend lower than the others: 'a' is equivalent to '1', 'b' is '2' and
* so on.
*
* The "textinfo" string is made up of fields "%lf:%lf:%c" separated by
* blank space. The first integer is the x position of the character,
* the second is the font size (before rescaling) and the char item is
* the charcter to be printed.
*
* Both the "partial" and "textinfo" strings may include "-" or "+" as
* special characters (in "textinfo" the char should be a standalone
* word). They state where the text should be printed: below the bars
* ("-", default) or above the bars. This is used, for example, to
* print the add-5 and add-2 codes to the right of UPC or EAN codes
* (the add-5 extension is mostly used in ISBN codes.
*/
int Barcode_ps_print(struct Barcode_Item *bc, FILE *f)
{
int i, j, k, barlen, printable=1;
double f1, f2, fsav=0;
int mode = '-'; /* text below bars */
double scalef=1, xpos, x0, y0, yr;
unsigned char *ptr;
unsigned char c;
if (!bc->partial || !bc->textinfo) {
bc->error = EINVAL;
return -1;
}
/*
* Maybe this first part can be made common to several printing back-ends,
* we'll see how that works when other ouput engines are added
*/
/* First, calculate barlen */
barlen = bc->partial[0] - '0';
for (ptr = bc->partial+1; *ptr; ptr++)
if (isdigit(*ptr))
barlen += (*ptr - '0');
else if (islower(*ptr))
barlen += (*ptr - 'a'+1);
/* The scale factor depends on bar length */
if (!bc->scalef) {
if (!bc->width) bc->width = barlen; /* default */
scalef = bc->scalef = (double)bc->width / (double)barlen;
}
/* The width defaults to "just enough" */
if (!bc->width) bc->width = barlen * scalef +1;
/* But it can be too small, in this case enlarge and center the area */
if (bc->width < barlen * scalef) {
int wid = barlen * scalef + 1;
bc->xoff -= (wid - bc->width)/2 ;
bc->width = wid;
/* Can't extend too far on the left */
if (bc->xoff < 0) {
bc->width += -bc->xoff;
bc->xoff = 0;
}
}
/* The height defaults to 80 points (rescaled) */
if (!bc->height) bc->height = 80 * scalef;
/* If too small (5 + text), reduce the scale factor and center */
i = 5 + 10 * ((bc->flags & BARCODE_NO_ASCII)==0);
if (bc->height < i * scalef ) {
double scaleg = ((double)bc->height) / i;
int wid = bc->width * scaleg / scalef;
bc->xoff += (bc->width - wid)/2;
bc->width = wid;
scalef = scaleg;
}
/*
* Ok, then deal with actual ps (eps) output
*/
if (!(bc->flags & BARCODE_OUT_NOHEADERS)) { /* spit a header first */
if (bc->flags & BARCODE_OUT_EPS)
fprintf(f, "%%!PS-Adobe-2.0 EPSF-1.2\n");
else
fprintf(f, "%%!PS-Adobe-2.0\n");
fprintf(f, "%%%%Creator: libbarcode\n");
if (bc->flags & BARCODE_OUT_EPS) {
fprintf(f, "%%%%BoundingBox: %i %i %i %i\n",
bc->xoff,
bc->yoff,
bc->xoff + bc->width + 2* bc->margin,
bc->yoff + bc->height + 2* bc->margin);
}
fprintf(f, "%%%%EndComments\n");
if (bc->flags & BARCODE_OUT_PS) {
fprintf(f, "%%%%EndProlog\n\n");
fprintf(f, "%%%%Page: 1 1\n\n");
}
}
/* Print some informative comments */
for (i=0; bc->ascii[i]; i++)
if (bc->ascii[i] < ' ')
printable = 0;
fprintf(f,"%% Printing barcode for \"%s\", scaled %5.2f",
printable ? bc->ascii : "<unprintable string>", scalef);
if (bc->encoding)
fprintf(f,", encoded using \"%s\"",bc->encoding);
fprintf(f, "\n");
fprintf(f,"%% The space/bar succession is represented "
"by the following widths (space first):\n"
"%% ");
for (i=0; i<strlen(bc->partial); i++) {
unsigned char c = bc->partial[i];
if (isdigit(c)) putc(c, f);
if (islower(c)) putc(c-'a'+'1', f);
if (isupper(c)) putc(c-'A'+'1', f);
}
/* open array for "forall" */
fprintf(f, "\n[\n%% height xpos ypos width"
" height xpos ypos width\n");
xpos = bc->margin + (bc->partial[0]-'0') * scalef;
for (ptr = bc->partial+1, i=1; *ptr; ptr++, i++) {
/* special cases: '+' and '-' */
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; /* don't count it */ i++; continue;
}
/* j is the width of this bar/space */
if (isdigit (*ptr)) j = *ptr-'0';
else j = *ptr-'a'+1;
if (i%2) { /* bar */
x0 = bc->xoff + xpos + (j*scalef)/2;
y0 = bc->yoff + bc->margin;
yr = bc->height;
if (!(bc->flags & BARCODE_NO_ASCII)) { /* leave space for text */
if (mode == '-') {
/* text below bars: 10 points or five points */
y0 += (isdigit(*ptr) ? 10 : 5) * scalef;
yr -= (isdigit(*ptr) ? 10 : 5) * scalef;
} else { /* '+' */
/* text above bars: 10 or 0 from bottom, and 10 from top */
y0 += (isdigit(*ptr) ? 10 : 0) * scalef;
yr -= (isdigit(*ptr) ? 20 : 10) * scalef;
}
}
/* Define an array and then use "forall" (Hans Schou) */
fprintf(f," [%5.2f %6.2f %6.2f %5.2f]%s",
yr, x0, y0, (j * scalef) - SHRINK_AMOUNT,
i%4 == 1 ? " " : "\n");
}
xpos += j * scalef;
}
fprintf(f,"\n]\t{ {} forall setlinewidth moveto 0 exch rlineto stroke} "
"bind forall\n");
/* Then, the text */
mode = '-'; /* reinstantiate default */
if (!(bc->flags & BARCODE_NO_ASCII)) {
fprintf(f, "[\n%% char xpos ypos fontsize\n");
k=0; /* k is the "previous font size" */
for (ptr = bc->textinfo; ptr; ptr = strchr(ptr, ' ')) {
while (*ptr == ' ') ptr++;
if (!*ptr) break;
if (*ptr == '+' || *ptr == '-') {
mode = *ptr; continue;
}
if (sscanf(ptr, "%lf:%lf:%c", &f1, &f2, &c) != 3) {
fprintf(stderr, "barcode: impossible data: %s\n", ptr);
continue;
}
fprintf(f, " [(");
/* Both the backslash and the two parens are special */
if (c=='\\' || c==')' || c=='(')
fprintf(f, "\\%c) ", c);
else
fprintf(f, "%c) ", c);
fprintf(f, "%6.2f %6.2f %5.2f]\n",
bc->xoff + f1 * scalef + bc->margin,
mode == '-'
? (double)bc->yoff + bc->margin
: (double)bc->yoff + bc->margin+bc->height - 8*scalef,
fsav == f2 ? 0.0 : f2 * scalef);
fsav = f2;
}
fprintf(f,"] { {} forall dup 0.00 ne {\n\t"
"/Helvetica findfont exch scalefont setfont\n"
" } {pop} ifelse\n"
" moveto show} bind forall\n");
}
fprintf(f,"%% End barcode for \"%s\"\n\n",
printable ? bc->ascii : "<unprintable string>");
if (!(bc->flags & BARCODE_OUT_NOHEADERS)) {
if (bc->flags & BARCODE_OUT_PS) {
fprintf(f,"showpage\n");
fprintf(f, "%%%%Trailer\n\n");
}
}
return 0;
}
+178 -178
View File
@@ -1,178 +1,178 @@
#include "QBarCode.h"
#include "ui_myBarCode.h"
#include "QImage"
#include "QFile"
#include "QFileInfo"
#include "QDebug"
#include "stdio.h"
QBarCode::QBarCode(QWidget *parent) :
QDialog(parent),
ui(new Ui::QBarCode)
{
ui->setupUi(this);
connect(ui->BarCodeGenerate,SIGNAL(pressed()),this,SLOT(onEnCodeBar()));
ui->lineEdit->setText("12345678ABCDEFG");
//onEnCodeBar();
}
QBarCode::~QBarCode()
{
delete ui;
}
void QBarCode::onEnCodeBar(){
QFile f1;
//ui->lineEdit->setText("dfdsfdsfdsfdsf");
int ps = 1, pcl = 0, oflags;
ps = 0; pcl = 0;
oflags = BARCODE_OUT_PS | BARCODE_OUT_NOHEADERS;
// char *txt = ui->lineEdit->text.toStdString().c_str();
//sprintf(txt,"%s", (char *)ui->lineEdit->text().data());
/* and my data as code-128B autodetected */
QString txt =ui->lineEdit->text();
Barcode_Encode_and_Print((char *)txt.toStdString().c_str(),stdout, 0, 60, 240, 510,
oflags);
/* A few code-39 ones */
// Barcode_Encode_and_Print("silly code",stdout, 0, 0, 40, 320,
// BARCODE_39 | oflags);
// Barcode_Encode_and_Print("SAMPLE CODES",stdout, 100, 30, 400, 80,
// BARCODE_39 | oflags);
/* ISBN with add-5 */
// Barcode_Encode_and_Print("1-56592-292-1 90000",stdout, 0, 0, 40, 430,
// BARCODE_ISBN | oflags);
}
/*
* Do it all in one step
*/
int QBarCode::Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags)
{
struct Barcode_Item * bc;
if (!(bc=Barcode_Create(text))) {
qDebug()<<"mem less then:";//<< -ENOMEM ;
return -1;
}
if ( Barcode_Position(bc, wid, hei, xoff, yoff, 0.0) < 0
|| Barcode_Encode(bc, flags) < 0
//|| Barcode_Print(bc, f, flags) < 0
) {
qDebug()<< bc->error;
Barcode_Delete(bc);
return -1;
}
//QFile f1;
bcText = text;
bcTextinfo = bc->textinfo;
bcPartial = bc->partial;
ui->textEdit->setText(bcPartial);
Barcode_ToImage(bc);
Barcode_Delete(bc);
return 0;
}
// 将条形码编码转换成点阵图形
int QBarCode::Barcode_ToImage(Barcode_Item * bc ){
bc->ascii;
bc->partial;
bc->textinfo;
int len =QString(bc->partial).length();
bcWidth =6;
for(int i=0;i<len;i++)
bcWidth+= (bc->partial[i]&0x0f);
//
//bcWidth = len;
bcHeight = 40;
QImage image(bcWidth,bcHeight,QImage::Format_ARGB32);
//image.dotsPerMeterX()
//image.size().setHeight(50);
image.fill(0x00ffffff);
//QPainter painter(&image);
//ui->textEdit->document()->drawContents (&painter, image.rect()); /*将text写到pic*/
QString txt = bc->ascii;
ui->textEdit->setText( QString().sprintf("W:%d,H:%d,Len:%d",ui->BarCodeView->width(),ui->BarCodeView->height(),len));
//0b1a2a4123221223211221132221231213212223112312131311222314111b3c1a1b
//11:12:1 22:12:2 33:12:3 44:12:4 55:12:5 66:12:6 77:12:7 88:12:8
//02112141232212232112211322212312132122231123121313112223141112331112
memset(pointMap,0,sizeof(pointMap));
unsigned char *img= image.bits();
for(int j=0;j< 20;j++){
int i=3;
unsigned char p=0;
for(int n=0;( n<len);n++)
{
int c= bc->partial[n];
if(c<0x30 || c>127) continue;
c = c-0x30;
if(n%2==1){
for(int r=0;r<c;r++){
*( img+j*bcWidth*4+i*4)= 0;
*( img+j*bcWidth*4+i*4+1)= 0;
*( img+j*bcWidth*4+i*4+2)= 0;
*( img+j*bcWidth*4+i*4+3)= 0;
i++;
// p= (p<<1) | 0x01;
// pointMap[j*bcWidth+i]=1;
}
}
else i+=c;
}
}
QString fileName="\\home\\plg\\doc\\"+ txt + ".BMP" ;
image.save(fileName);
QFileInfo(fileName).fileName();
// ui->labBarCode->setPixmap(QPixmap(QString::fromUtf8(".\\imgd.BMP")));
//ui->widgetPrintTextDisplay->dat = pointMap;
ShowBarCode(fileName);
}
void QBarCode::ShowBarCode(QString fileName)
{
/****************界面初始化********************************/
this->pictureName =fileName ;
scene = new QGraphicsScene;
scene->setSceneRect( -200,0,bcWidth*4+200,bcHeight);
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
QPixmap pixmap(this->pictureName);
pixmap = pixmap.scaledToWidth(2.5*bcWidth);
item = scene->addPixmap(pixmap);
/***************设置view的场景*****************************/
ui->BarCodeView->setScene(scene);
ui->BarCodeView->setRenderHint(QPainter::Antialiasing);
ui->BarCodeView->setCacheMode(QGraphicsView::CacheBackground);
ui->BarCodeView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
ui->BarCodeView->setDragMode(QGraphicsView::ScrollHandDrag);
//ui->graphicsView->resize(400,300);
ui->BarCodeView->setScene(scene);//设置view的场景
}
#include "QBarCode.h"
#include "ui_myBarCode.h"
#include "QImage"
#include "QFile"
#include "QFileInfo"
#include "QDebug"
#include "stdio.h"
QBarCode::QBarCode(QWidget *parent) :
QDialog(parent),
ui(new Ui::QBarCode)
{
ui->setupUi(this);
connect(ui->BarCodeGenerate,SIGNAL(pressed()),this,SLOT(onEnCodeBar()));
ui->lineEdit->setText("12345678ABCDEFG");
//onEnCodeBar();
}
QBarCode::~QBarCode()
{
delete ui;
}
void QBarCode::onEnCodeBar(){
QFile f1;
//ui->lineEdit->setText("dfdsfdsfdsfdsf");
int ps = 1, pcl = 0, oflags;
ps = 0; pcl = 0;
oflags = BARCODE_OUT_PS | BARCODE_OUT_NOHEADERS;
// char *txt = ui->lineEdit->text.toStdString().c_str();
//sprintf(txt,"%s", (char *)ui->lineEdit->text().data());
/* and my data as code-128B autodetected */
QString txt =ui->lineEdit->text();
Barcode_Encode_and_Print((char *)txt.toStdString().c_str(),stdout, 0, 60, 240, 510,
oflags);
/* A few code-39 ones */
// Barcode_Encode_and_Print("silly code",stdout, 0, 0, 40, 320,
// BARCODE_39 | oflags);
// Barcode_Encode_and_Print("SAMPLE CODES",stdout, 100, 30, 400, 80,
// BARCODE_39 | oflags);
/* ISBN with add-5 */
// Barcode_Encode_and_Print("1-56592-292-1 90000",stdout, 0, 0, 40, 430,
// BARCODE_ISBN | oflags);
}
/*
* Do it all in one step
*/
int QBarCode::Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags)
{
struct Barcode_Item * bc;
if (!(bc=Barcode_Create(text))) {
qDebug()<<"mem less then:";//<< -ENOMEM ;
return -1;
}
if ( Barcode_Position(bc, wid, hei, xoff, yoff, 0.0) < 0
|| Barcode_Encode(bc, flags) < 0
//|| Barcode_Print(bc, f, flags) < 0
) {
qDebug()<< bc->error;
Barcode_Delete(bc);
return -1;
}
//QFile f1;
bcText = text;
bcTextinfo = bc->textinfo;
bcPartial = bc->partial;
ui->textEdit->setText(bcPartial);
Barcode_ToImage(bc);
Barcode_Delete(bc);
return 0;
}
// 将条形码编码转换成点阵图形
int QBarCode::Barcode_ToImage(Barcode_Item * bc ){
bc->ascii;
bc->partial;
bc->textinfo;
int len =QString(bc->partial).length();
bcWidth =6;
for(int i=0;i<len;i++)
bcWidth+= (bc->partial[i]&0x0f);
//
//bcWidth = len;
bcHeight = 40;
QImage image(bcWidth,bcHeight,QImage::Format_ARGB32);
//image.dotsPerMeterX()
//image.size().setHeight(50);
image.fill(0x00ffffff);
//QPainter painter(&image);
//ui->textEdit->document()->drawContents (&painter, image.rect()); /*将text写到pic*/
QString txt = bc->ascii;
ui->textEdit->setText( QString().sprintf("W:%d,H:%d,Len:%d",ui->BarCodeView->width(),ui->BarCodeView->height(),len));
//0b1a2a4123221223211221132221231213212223112312131311222314111b3c1a1b
//11:12:1 22:12:2 33:12:3 44:12:4 55:12:5 66:12:6 77:12:7 88:12:8
//02112141232212232112211322212312132122231123121313112223141112331112
memset(pointMap,0,sizeof(pointMap));
unsigned char *img= image.bits();
for(int j=0;j< 20;j++){
int i=3;
unsigned char p=0;
for(int n=0;( n<len);n++)
{
int c= bc->partial[n];
if(c<0x30 || c>127) continue;
c = c-0x30;
if(n%2==1){
for(int r=0;r<c;r++){
*( img+j*bcWidth*4+i*4)= 0;
*( img+j*bcWidth*4+i*4+1)= 0;
*( img+j*bcWidth*4+i*4+2)= 0;
*( img+j*bcWidth*4+i*4+3)= 0;
i++;
// p= (p<<1) | 0x01;
// pointMap[j*bcWidth+i]=1;
}
}
else i+=c;
}
}
QString fileName="\\home\\plg\\doc\\"+ txt + ".BMP" ;
image.save(fileName);
QFileInfo(fileName).fileName();
// ui->labBarCode->setPixmap(QPixmap(QString::fromUtf8(".\\imgd.BMP")));
//ui->widgetPrintTextDisplay->dat = pointMap;
ShowBarCode(fileName);
}
void QBarCode::ShowBarCode(QString fileName)
{
/****************界面初始化********************************/
this->pictureName =fileName ;
scene = new QGraphicsScene;
scene->setSceneRect( -200,0,bcWidth*4+200,bcHeight);
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
QPixmap pixmap(this->pictureName);
pixmap = pixmap.scaledToWidth(2.5*bcWidth);
item = scene->addPixmap(pixmap);
/***************设置view的场景*****************************/
ui->BarCodeView->setScene(scene);
ui->BarCodeView->setRenderHint(QPainter::Antialiasing);
ui->BarCodeView->setCacheMode(QGraphicsView::CacheBackground);
ui->BarCodeView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
ui->BarCodeView->setDragMode(QGraphicsView::ScrollHandDrag);
//ui->graphicsView->resize(400,300);
ui->BarCodeView->setScene(scene);//设置view的场景
}
+44 -44
View File
@@ -1,44 +1,44 @@
#ifndef QBARCODE_H
#define QBARCODE_H
#include <QDialog>
#include "barcode.h"
#include "QGraphicsScene"
#include "QGraphicsPixmapItem"
namespace Ui {
class QBarCode;
}
class QBarCode : public QDialog
{
Q_OBJECT
public:
explicit QBarCode(QWidget *parent = 0);
~QBarCode();
unsigned char pointMap[40*1000];
QString pictureName;//当前显示的图片
private slots:
void onEnCodeBar();
private:
void ShowBarCode(QString fileName);
int Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags);
int Barcode_ToImage(Barcode_Item * bc );
QGraphicsScene *scene;//声明scene
QGraphicsPixmapItem *item;//声明item
QString bcPartial;
QString bcTextinfo;
QString bcText;
int bcWidth,bcHeight;
private:
Ui::QBarCode *ui;
};
#endif // QBARCODE_H
#ifndef QBARCODE_H
#define QBARCODE_H
#include <QDialog>
#include "barcode.h"
#include "QGraphicsScene"
#include "QGraphicsPixmapItem"
namespace Ui {
class QBarCode;
}
class QBarCode : public QDialog
{
Q_OBJECT
public:
explicit QBarCode(QWidget *parent = 0);
~QBarCode();
unsigned char pointMap[40*1000];
QString pictureName;//当前显示的图片
private slots:
void onEnCodeBar();
private:
void ShowBarCode(QString fileName);
int Barcode_Encode_and_Print(char *text, FILE *f, int wid, int hei,
int xoff, int yoff, int flags);
int Barcode_ToImage(Barcode_Item * bc );
QGraphicsScene *scene;//声明scene
QGraphicsPixmapItem *item;//声明item
QString bcPartial;
QString bcTextinfo;
QString bcText;
int bcWidth,bcHeight;
private:
Ui::QBarCode *ui;
};
#endif // QBARCODE_H
+147 -147
View File
@@ -1,147 +1,147 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>QBarCode</class>
<widget class="QWidget" name="QBarCode">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>680</width>
<height>316</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="7">
<widget class="QGraphicsView" name="BarCodeView"/>
</item>
<item row="2" column="0" colspan="2">
<widget class="QLabel" name="label">
<property name="text">
<string>条形码类型</string>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QLabel" name="label_2">
<property name="text">
<string>字体</string>
</property>
</widget>
</item>
<item row="2" column="3">
<widget class="QLabel" name="label_3">
<property name="text">
<string>条形码高度</string>
</property>
</widget>
</item>
<item row="2" column="4">
<widget class="QLabel" name="label_4">
<property name="text">
<string>放大等级</string>
</property>
</widget>
</item>
<item row="3" column="0" colspan="2">
<widget class="QComboBox" name="BarCodeType"/>
</item>
<item row="3" column="2">
<widget class="QComboBox" name="BarCodeFont">
<property name="minimumSize">
<size>
<width>120</width>
<height>0</height>
</size>
</property>
</widget>
</item>
<item row="3" column="3">
<widget class="QComboBox" name="BarCodeHeigh"/>
</item>
<item row="3" column="4">
<widget class="QSpinBox" name="BarCodeScale">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>10</number>
</property>
<property name="value">
<number>1</number>
</property>
</widget>
</item>
<item row="3" column="6">
<widget class="QPushButton" name="BarCodeInsert">
<property name="text">
<string>插入文档</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>文本信息</string>
</property>
</widget>
</item>
<item row="4" column="1" colspan="4">
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item row="1" column="0" colspan="7">
<widget class="QTextEdit" name="textEdit">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>60</height>
</size>
</property>
</widget>
</item>
<item row="2" column="5" colspan="2">
<widget class="QLabel" name="labFileName">
<property name="text">
<string>FileName</string>
</property>
</widget>
</item>
<item row="3" column="5">
<widget class="QPushButton" name="pushBtnOpenFile">
<property name="text">
<string>打开文件</string>
</property>
</widget>
</item>
<item row="4" column="5">
<widget class="QPushButton" name="BarCodeGenerate">
<property name="text">
<string>生成条形码</string>
</property>
</widget>
</item>
<item row="4" column="6">
<widget class="QPushButton" name="pushBtnColse">
<property name="text">
<string>关闭</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labStatus">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>QBarCode</class>
<widget class="QWidget" name="QBarCode">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>680</width>
<height>316</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="7">
<widget class="QGraphicsView" name="BarCodeView"/>
</item>
<item row="2" column="0" colspan="2">
<widget class="QLabel" name="label">
<property name="text">
<string>条形码类型</string>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QLabel" name="label_2">
<property name="text">
<string>字体</string>
</property>
</widget>
</item>
<item row="2" column="3">
<widget class="QLabel" name="label_3">
<property name="text">
<string>条形码高度</string>
</property>
</widget>
</item>
<item row="2" column="4">
<widget class="QLabel" name="label_4">
<property name="text">
<string>放大等级</string>
</property>
</widget>
</item>
<item row="3" column="0" colspan="2">
<widget class="QComboBox" name="BarCodeType"/>
</item>
<item row="3" column="2">
<widget class="QComboBox" name="BarCodeFont">
<property name="minimumSize">
<size>
<width>120</width>
<height>0</height>
</size>
</property>
</widget>
</item>
<item row="3" column="3">
<widget class="QComboBox" name="BarCodeHeigh"/>
</item>
<item row="3" column="4">
<widget class="QSpinBox" name="BarCodeScale">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>10</number>
</property>
<property name="value">
<number>1</number>
</property>
</widget>
</item>
<item row="3" column="6">
<widget class="QPushButton" name="BarCodeInsert">
<property name="text">
<string>插入文档</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>文本信息</string>
</property>
</widget>
</item>
<item row="4" column="1" colspan="4">
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item row="1" column="0" colspan="7">
<widget class="QTextEdit" name="textEdit">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>60</height>
</size>
</property>
</widget>
</item>
<item row="2" column="5" colspan="2">
<widget class="QLabel" name="labFileName">
<property name="text">
<string>FileName</string>
</property>
</widget>
</item>
<item row="3" column="5">
<widget class="QPushButton" name="pushBtnOpenFile">
<property name="text">
<string>打开文件</string>
</property>
</widget>
</item>
<item row="4" column="5">
<widget class="QPushButton" name="BarCodeGenerate">
<property name="text">
<string>生成条形码</string>
</property>
</widget>
</item>
<item row="4" column="6">
<widget class="QPushButton" name="pushBtnColse">
<property name="text">
<string>关闭</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labStatus">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
+141 -141
View File
@@ -1,141 +1,141 @@
#include "Binarization.h"
CBinarization::CBinarization( QString imgPath )
: threshold(0)
{
// 加载图片
_img = new QImage();
if (NULL != _img)
{
_img->load(imgPath);
}
}
// 生成灰度图像
QImage* CBinarization::grayScaleImg()
{
if (NULL == _img)
{
return NULL;
}
int nWidth = _img->width();
int nHeight = _img->height();
// 这里留意,我使用了QImage::Format_Grayscale8格式的图片,这种图片每个像素只用了8bit存储灰度颜色值
QImage* grayImg = new QImage(nWidth, nHeight, QImage::Format_RGB888);
QRgb rgbVal = 0;
int grayVal = 0;
for (int x = 0; x < nWidth; ++x)
{
for (int y = 0; y < nHeight; ++y)
{
rgbVal = _img->pixel(x, y);
grayVal = qGray(rgbVal); // 这里调用Qt的函数,使用(R * 11 + G * 16 + B * 5)/32的方法计算
grayImg->setPixel(x, y, QColor(grayVal, grayVal, grayVal).rgb());
}
}
return grayImg;
}
int CBinarization::Otsu(QImage* img)
{
if (NULL == img)
{
return -1;
}
vector<int> histogram = Histogram(img);
int total = 0;
for (int i = 0; i != histogram.size(); ++i)
{
total += histogram[i];
}
double sum = 0.0;
for (unsigned int i = 1; i < histogram.size(); ++i)
sum += i * histogram[i];
double sumB = 0.0;
double wB = 0.0;
double wF = 0.0;
double mB = 0.0;
double mF = 0.0;
double max = 0.0;
double between = 0.0;
double threshold = 0.0;
for (int i = 0; i != 256; ++i)
{
wB += histogram[i];
if (wB == 0)
continue;
wF = total - wB;
if (wF == 0)
break;
sumB += i * histogram[i];
mB = sumB / wB;
mF = (sum - sumB) / wF;
between = wB * wF * (mB - mF) * (mB - mF);
if ( between > max )
{
threshold = i;
max = between;
}
}
return threshold;
}
QImage* CBinarization::process(QImage* img)
{
if (NULL == img)
{
return NULL;
}
int width = img->width();
int height = img->height();
int bytePerLine = img->bytesPerLine(); // 每一行的字节数
unsigned char *data = img->bits();
unsigned char *binarydata = new unsigned char[bytePerLine * height];
unsigned char g = 0;
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
g = *(data + i * bytePerLine + j * 3); // 这里j 乘以 3
if(int(g) >= threshold)
{
binarydata[ i * bytePerLine + j * 3] = 0xFF; // 每个色值需要对3个字节赋值
binarydata[ i * bytePerLine + j * 3 + 1] = 0xFF;
binarydata[ i * bytePerLine + j * 3 + 2] = 0xFF;
}
else
{
binarydata[ i * bytePerLine + j * 3] = 0x00;
binarydata[ i * bytePerLine + j * 3 + 1] = 0x00;
binarydata[ i * bytePerLine + j * 3 + 2] = 0x00;
}
}
}
QImage *ret = new QImage(binarydata, width, height, bytePerLine, QImage::Format_RGB888);
return ret;
}
std::vector<int> CBinarization::Histogram( QImage* img )
{
unsigned char* graydata = img->bits();
vector<int> hist(256); // 256色
for (int i = 0; i != img->width(); ++i)
{
for (int j = 0; j != img->height(); ++j)
{
int index = int(*graydata);
hist[index] += 1;
graydata += 1; // step
}
}
graydata = NULL;
return hist;
}
#include "Binarization.h"
CBinarization::CBinarization( QString imgPath )
: threshold(0)
{
// 加载图片
_img = new QImage();
if (NULL != _img)
{
_img->load(imgPath);
}
}
// 生成灰度图像
QImage* CBinarization::grayScaleImg()
{
if (NULL == _img)
{
return NULL;
}
int nWidth = _img->width();
int nHeight = _img->height();
// 这里留意,我使用了QImage::Format_Grayscale8格式的图片,这种图片每个像素只用了8bit存储灰度颜色值
QImage* grayImg = new QImage(nWidth, nHeight, QImage::Format_RGB888);
QRgb rgbVal = 0;
int grayVal = 0;
for (int x = 0; x < nWidth; ++x)
{
for (int y = 0; y < nHeight; ++y)
{
rgbVal = _img->pixel(x, y);
grayVal = qGray(rgbVal); // 这里调用Qt的函数,使用(R * 11 + G * 16 + B * 5)/32的方法计算
grayImg->setPixel(x, y, QColor(grayVal, grayVal, grayVal).rgb());
}
}
return grayImg;
}
int CBinarization::Otsu(QImage* img)
{
if (NULL == img)
{
return -1;
}
vector<int> histogram = Histogram(img);
int total = 0;
for (int i = 0; i != histogram.size(); ++i)
{
total += histogram[i];
}
double sum = 0.0;
for (unsigned int i = 1; i < histogram.size(); ++i)
sum += i * histogram[i];
double sumB = 0.0;
double wB = 0.0;
double wF = 0.0;
double mB = 0.0;
double mF = 0.0;
double max = 0.0;
double between = 0.0;
double threshold = 0.0;
for (int i = 0; i != 256; ++i)
{
wB += histogram[i];
if (wB == 0)
continue;
wF = total - wB;
if (wF == 0)
break;
sumB += i * histogram[i];
mB = sumB / wB;
mF = (sum - sumB) / wF;
between = wB * wF * (mB - mF) * (mB - mF);
if ( between > max )
{
threshold = i;
max = between;
}
}
return threshold;
}
QImage* CBinarization::process(QImage* img)
{
if (NULL == img)
{
return NULL;
}
int width = img->width();
int height = img->height();
int bytePerLine = img->bytesPerLine(); // 每一行的字节数
unsigned char *data = img->bits();
unsigned char *binarydata = new unsigned char[bytePerLine * height];
unsigned char g = 0;
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
g = *(data + i * bytePerLine + j * 3); // 这里j 乘以 3
if(int(g) >= threshold)
{
binarydata[ i * bytePerLine + j * 3] = 0xFF; // 每个色值需要对3个字节赋值
binarydata[ i * bytePerLine + j * 3 + 1] = 0xFF;
binarydata[ i * bytePerLine + j * 3 + 2] = 0xFF;
}
else
{
binarydata[ i * bytePerLine + j * 3] = 0x00;
binarydata[ i * bytePerLine + j * 3 + 1] = 0x00;
binarydata[ i * bytePerLine + j * 3 + 2] = 0x00;
}
}
}
QImage *ret = new QImage(binarydata, width, height, bytePerLine, QImage::Format_RGB888);
return ret;
}
std::vector<int> CBinarization::Histogram( QImage* img )
{
unsigned char* graydata = img->bits();
vector<int> hist(256); // 256色
for (int i = 0; i != img->width(); ++i)
{
for (int j = 0; j != img->height(); ++j)
{
int index = int(*graydata);
hist[index] += 1;
graydata += 1; // step
}
}
graydata = NULL;
return hist;
}
+24 -24
View File
@@ -1,24 +1,24 @@
#ifndef CBINARIZATION_H
#define CBINARIZATION_H
#include <QImage>
#include <QColor>
using namespace std;
class CBinarization
{
public:
CBinarization(QString imgPath);
QImage* grayScaleImg();
int Otsu(QImage* img);
QImage* process(QImage* img);
int threshold;
private:
QImage* _img;
vector<int> Histogram(QImage* img);
};
#endif
#ifndef CBINARIZATION_H
#define CBINARIZATION_H
#include <QImage>
#include <QColor>
using namespace std;
class CBinarization
{
public:
CBinarization(QString imgPath);
QImage* grayScaleImg();
int Otsu(QImage* img);
QImage* process(QImage* img);
int threshold;
private:
QImage* _img;
vector<int> Histogram(QImage* img);
};
#endif
+3813 -3813
View File
File diff suppressed because it is too large Load Diff
+6 -6
View File
@@ -1,6 +1,6 @@
#include <ClickLabel.h>
#include <stdio.h>
void ClickLabel::mousePressEvent(QMouseEvent *evt)
{
emit pressed();
}
#include <ClickLabel.h>
#include <stdio.h>
void ClickLabel::mousePressEvent(QMouseEvent *evt)
{
emit pressed();
}
+20 -20
View File
@@ -1,20 +1,20 @@
#ifndef __CLICKLABEL__
#define __CLICKLABEL__
#include <QLabel>
class ClickLabel:public QLabel{
Q_OBJECT
signals:
void pressed(void);
public:
ClickLabel(QWidget *parent=0): QLabel(parent){
}
protected:
void mousePressEvent( QMouseEvent* );
};
#endif
#ifndef __CLICKLABEL__
#define __CLICKLABEL__
#include <QLabel>
class ClickLabel:public QLabel{
Q_OBJECT
signals:
void pressed(void);
public:
ClickLabel(QWidget *parent=0): QLabel(parent){
}
protected:
void mousePressEvent( QMouseEvent* );
};
#endif
+96 -96
View File
@@ -1,96 +1,96 @@
#include "DacDisplayAndEdit.h"
#include "ui_dacdisplayandedit.h"
#include "QLatin1Char"
#include "qdebug.h"
#include "qmessagebox.h"
DacDisplayAndEdit::DacDisplayAndEdit(QWidget *parent) :
QWidget(parent),
ui(new Ui::DacDisplayAndEdit)
{
ui->setupUi(this);
for(int i = 0; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
memLineEdit[i] = new QLineEdit(this);
memLineEdit[i]->setAccessibleName(QString::number(i));
memLineEdit[i]->setEnabled(false);
ui->gridLayoutMem->addWidget(memLineEdit[i],(i/DAC_GRID_MAX_COL) + 1,(i%DAC_GRID_MAX_COL) + 1);
connect(memLineEdit[i],SIGNAL(editingFinished ()),this,SLOT(onLineEditEditingFinished()));
}
for(int i = 0; i < DAC_GRID_MAX_ROW; i++){
rowLabel[i] = new QLabel(this);
ui->gridLayoutMem->addWidget(rowLabel[i],i + 1,0);
}
editFlag = false;
writeMemBaseAddr = 0;
readMemBaseAddr = 0;
setEnabled(1);
}
DacDisplayAndEdit::~DacDisplayAndEdit()
{
delete ui;
}
// updateSysStatusToUI
void DacDisplayAndEdit::updateSysStatusToUI(void){
//
}
void DacDisplayAndEdit::updateAuthorization(int auth)
{
//qDebug ()<<auth;
}
void DacDisplayAndEdit::updateSysParaToUI(void){
if(sysPara && !editFlag){
memLineEdit[0]->setText(QString(" "));
for(int i = 1; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
if(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]>25)sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]=25;
if(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]<5) sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]=5;
memLineEdit[i]->setText(QString("%1").arg(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK],2,10/*,QLatin1Char('0')*/));
}
}
}
void DacDisplayAndEdit::on_pushButtonEdit_pressed()
{//ddd
if(sysPara){
editFlag = !editFlag;
for(int i = 1; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
memLineEdit[i]->setEnabled(editFlag);
if(editFlag) memLineEdit[i]->setText(QString("%1").arg(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK],2,10,QLatin1Char('0')));
}
ui->pushButtonEdit->setText(editFlag?tr("完成"):tr("编辑"));
}
}
void DacDisplayAndEdit::on_pushButtonDefault_pressed()// pushButtonDefault pushButtonDefault
{
if(sysPara){
QMessageBox msgBox(QMessageBox::Information,tr("提示"),tr("是否将点距微调参数设置为默认值?"));
QPushButton *saveButton = msgBox.addButton(tr("是"), QMessageBox::ActionRole);
QPushButton *cancleSaveButton = msgBox.addButton(tr("否"), QMessageBox::ActionRole);
QPushButton *abortButton = msgBox.addButton(QMessageBox::Cancel);
msgBox.exec();
if (msgBox.clickedButton() == saveButton) {
for(int i = 1; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]=15;
memLineEdit[i]->setText(tr("%1").arg(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK],2,10,QLatin1Char('0')));
}
}
}
else qDebug()<<"sysPara not bind!";
}
void DacDisplayAndEdit::onLineEditEditingFinished(){
int val,addr=0;
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
QString name = edit->accessibleName();
val = edit->text().toInt(&ok,10);
if(sysPara){
addr = name.toInt(&ok);
if(val>25)val=25;
if(val<5) val =5;
sysPara->para.adjVolDacRate[(addr)&MAX_RD_DAC_SIZE_MASK] = (unsigned char)val;
}
}
#include "DacDisplayAndEdit.h"
#include "ui_dacdisplayandedit.h"
#include "QLatin1Char"
#include "qdebug.h"
#include "qmessagebox.h"
DacDisplayAndEdit::DacDisplayAndEdit(QWidget *parent) :
QWidget(parent),
ui(new Ui::DacDisplayAndEdit)
{
ui->setupUi(this);
for(int i = 0; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
memLineEdit[i] = new QLineEdit(this);
memLineEdit[i]->setAccessibleName(QString::number(i));
memLineEdit[i]->setEnabled(false);
ui->gridLayoutMem->addWidget(memLineEdit[i],(i/DAC_GRID_MAX_COL) + 1,(i%DAC_GRID_MAX_COL) + 1);
connect(memLineEdit[i],SIGNAL(editingFinished ()),this,SLOT(onLineEditEditingFinished()));
}
for(int i = 0; i < DAC_GRID_MAX_ROW; i++){
rowLabel[i] = new QLabel(this);
ui->gridLayoutMem->addWidget(rowLabel[i],i + 1,0);
}
editFlag = false;
writeMemBaseAddr = 0;
readMemBaseAddr = 0;
setEnabled(1);
}
DacDisplayAndEdit::~DacDisplayAndEdit()
{
delete ui;
}
// updateSysStatusToUI
void DacDisplayAndEdit::updateSysStatusToUI(void){
//
}
void DacDisplayAndEdit::updateAuthorization(int auth)
{
//qDebug ()<<auth;
}
void DacDisplayAndEdit::updateSysParaToUI(void){
if(sysPara && !editFlag){
memLineEdit[0]->setText(QString(" "));
for(int i = 1; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
if(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]>25)sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]=25;
if(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]<5) sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]=5;
memLineEdit[i]->setText(QString("%1").arg(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK],2,10/*,QLatin1Char('0')*/));
}
}
}
void DacDisplayAndEdit::on_pushButtonEdit_pressed()
{//ddd
if(sysPara){
editFlag = !editFlag;
for(int i = 1; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
memLineEdit[i]->setEnabled(editFlag);
if(editFlag) memLineEdit[i]->setText(QString("%1").arg(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK],2,10,QLatin1Char('0')));
}
ui->pushButtonEdit->setText(editFlag?tr("完成"):tr("编辑"));
}
}
void DacDisplayAndEdit::on_pushButtonDefault_pressed()// pushButtonDefault pushButtonDefault
{
if(sysPara){
QMessageBox msgBox(QMessageBox::Information,tr("提示"),tr("是否将点距微调参数设置为默认值?"));
QPushButton *saveButton = msgBox.addButton(tr("是"), QMessageBox::ActionRole);
QPushButton *cancleSaveButton = msgBox.addButton(tr("否"), QMessageBox::ActionRole);
QPushButton *abortButton = msgBox.addButton(QMessageBox::Cancel);
msgBox.exec();
if (msgBox.clickedButton() == saveButton) {
for(int i = 1; i < DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL; i++){
sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK]=15;
memLineEdit[i]->setText(tr("%1").arg(sysPara->para.adjVolDacRate[i&MAX_RD_DAC_SIZE_MASK],2,10,QLatin1Char('0')));
}
}
}
else qDebug()<<"sysPara not bind!";
}
void DacDisplayAndEdit::onLineEditEditingFinished(){
int val,addr=0;
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
QString name = edit->accessibleName();
val = edit->text().toInt(&ok,10);
if(sysPara){
addr = name.toInt(&ok);
if(val>25)val=25;
if(val<5) val =5;
sysPara->para.adjVolDacRate[(addr)&MAX_RD_DAC_SIZE_MASK] = (unsigned char)val;
}
}
+45 -45
View File
@@ -1,45 +1,45 @@
#ifndef DACDISPLAYANDEDIT_H
#define DACDISPLAYANDEDIT_H
#include <QWidget>
#include <QLineEdit>
#include <ParaSettingUI.h>
#include <QLabel>
#define DAC_GRID_MAX_ROW 4
#define DAC_GRID_MAX_COL 10
#define MAX_RD_DAC_SIZE_MASK 0x3f
#define MAX_WR_DAC_SIZE_MASK 0x3f
namespace Ui {
class DacDisplayAndEdit;
}
class DacDisplayAndEdit : public QWidget,public ParaSettingUI
{
Q_OBJECT
public:
explicit DacDisplayAndEdit(QWidget *parent = 0);
~DacDisplayAndEdit();
void updateSysStatusToUI(void);
void updateSysParaToUI(void);
void updateAuthorization(int auth);
private slots:
void on_pushButtonEdit_pressed();
void on_pushButtonDefault_pressed();
void onLineEditEditingFinished();
private:
Ui::DacDisplayAndEdit *ui;
QLineEdit *memLineEdit[DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL];
QLabel *rowLabel[DAC_GRID_MAX_ROW];
bool editFlag; //是否当前处于编辑模式
int writeMemBaseAddr;
int readMemBaseAddr;
};
#endif
// DacDisplayANDEDIT_H
#ifndef DACDISPLAYANDEDIT_H
#define DACDISPLAYANDEDIT_H
#include <QWidget>
#include <QLineEdit>
#include <ParaSettingUI.h>
#include <QLabel>
#define DAC_GRID_MAX_ROW 4
#define DAC_GRID_MAX_COL 10
#define MAX_RD_DAC_SIZE_MASK 0x3f
#define MAX_WR_DAC_SIZE_MASK 0x3f
namespace Ui {
class DacDisplayAndEdit;
}
class DacDisplayAndEdit : public QWidget,public ParaSettingUI
{
Q_OBJECT
public:
explicit DacDisplayAndEdit(QWidget *parent = 0);
~DacDisplayAndEdit();
void updateSysStatusToUI(void);
void updateSysParaToUI(void);
void updateAuthorization(int auth);
private slots:
void on_pushButtonEdit_pressed();
void on_pushButtonDefault_pressed();
void onLineEditEditingFinished();
private:
Ui::DacDisplayAndEdit *ui;
QLineEdit *memLineEdit[DAC_GRID_MAX_ROW*DAC_GRID_MAX_COL];
QLabel *rowLabel[DAC_GRID_MAX_ROW];
bool editFlag; //是否当前处于编辑模式
int writeMemBaseAddr;
int readMemBaseAddr;
};
#endif
// DacDisplayANDEDIT_H
+158 -158
View File
@@ -1,158 +1,158 @@
#include "dbredis.h"
#include <QDateTime>
QSqlDatabase DBRedis::m_DataBase;
QString DBRedis::m_ConnectName = "dbredis";
bool DBRedis::m_HasInit = false;
DBRedis::DBRedis()
{
}
DBRedis::~DBRedis()
{
if (m_DataBase.isOpen())
{
m_DataBase.close();
}
}
int DBRedis::deleteExpiredEntries()
{
int res = init();
if (res)
{
return res;
}
qint64 currentTimestamp = QDateTime::currentDateTime().toSecsSinceEpoch();
QSqlQuery query(m_DataBase);
query.prepare("DELETE FROM data_store WHERE expiry > 0 AND expiry < :currentTimestamp");
query.bindValue(":currentTimestamp", currentTimestamp);
if (!query.exec())
{
qDebug() << "Error deleting expired entries:" << query.lastError().text();
return 1;
}
return 0;
}
int DBRedis::setData(const QString & key, const QString & value, uint32_t expiry)
{
int res = deleteExpiredEntries();
if (res)
{
return res;
}
QSqlQuery query(m_DataBase);
query.prepare("SELECT COUNT(*) FROM data_store WHERE key = :key");
query.bindValue(":key", key);
if (!query.exec())
{
qDebug() << "Error checking existing key";
return 1;
}
int count = 0;
while (query.next())
{
count += query.value(0).toInt();
}
if (count > 0)
{
query.prepare("UPDATE data_store SET value = :value, expiry = :expiry WHERE key = :key");
query.bindValue(":value", value);
query.bindValue(":expiry", expiry > 0 ? QDateTime::currentDateTime().toSecsSinceEpoch() + expiry : 0);
query.bindValue(":key", key);
}
else
{
query.prepare("INSERT INTO data_store (key, value, expiry) VALUES (:key, :value, :expiry)");
query.bindValue(":key", key);
query.bindValue(":value", value);
query.bindValue(":expiry", expiry > 0 ? QDateTime::currentDateTime().toSecsSinceEpoch() + expiry : 0);
}
if (!query.exec())
{
qDebug() << "Error setting value:" << query.lastError().text();
return 1;
}
return 0;
}
int DBRedis::getData(const QString & key, QString & value)
{
value.clear();
int res = deleteExpiredEntries();
if (res)
{
return res;
}
QSqlQuery query(m_DataBase);
query.prepare("SELECT value FROM data_store WHERE key = :key");
query.bindValue(":key", key);
if (!query.exec())
{
qDebug() << "Error getting value:" << query.lastError().text();
return 1;
}
if (!query.next())
{
qDebug() << "Error getting value:" << query.lastError().text();
return 2;
}
value = query.value(0).toString();
return 0;
}
int DBRedis::deleteData(const QString & key)
{
int res = deleteExpiredEntries();
if (res)
{
return res;
}
QSqlQuery query(m_DataBase);
query.prepare("DELETE FROM data_store WHERE key = :key");
query.bindValue(":key", key);
if (!query.exec())
{
qDebug() << "Error deleting value:" << query.lastError().text();
return 1;
}
return 0;
}
int DBRedis::init()
{
if (m_HasInit)
{
return 0;
}
m_DataBase = QSqlDatabase::addDatabase("QSQLITE", m_ConnectName);
m_DataBase.setDatabaseName("dbredis.db");
if (m_DataBase.open())
{
QString table = "CREATE TABLE IF NOT EXISTS data_store(key TEXT, value TEXT, expiry INTEGER)";
QSqlQuery query(QSqlDatabase::database(m_ConnectName));
if (!query.exec(table.toUtf8()))
{
qDebug() << "Error deleting value:" << query.lastError().text();
return 1;
}
}
else
{
qDebug() << "Error db open fail";
return 3;
}
m_HasInit = true;
return 0;
}
#include "dbredis.h"
#include <QDateTime>
QSqlDatabase DBRedis::m_DataBase;
QString DBRedis::m_ConnectName = "dbredis";
bool DBRedis::m_HasInit = false;
DBRedis::DBRedis()
{
}
DBRedis::~DBRedis()
{
if (m_DataBase.isOpen())
{
m_DataBase.close();
}
}
int DBRedis::deleteExpiredEntries()
{
int res = init();
if (res)
{
return res;
}
qint64 currentTimestamp = QDateTime::currentDateTime().toSecsSinceEpoch();
QSqlQuery query(m_DataBase);
query.prepare("DELETE FROM data_store WHERE expiry > 0 AND expiry < :currentTimestamp");
query.bindValue(":currentTimestamp", currentTimestamp);
if (!query.exec())
{
qDebug() << "Error deleting expired entries:" << query.lastError().text();
return 1;
}
return 0;
}
int DBRedis::setData(const QString & key, const QString & value, uint32_t expiry)
{
int res = deleteExpiredEntries();
if (res)
{
return res;
}
QSqlQuery query(m_DataBase);
query.prepare("SELECT COUNT(*) FROM data_store WHERE key = :key");
query.bindValue(":key", key);
if (!query.exec())
{
qDebug() << "Error checking existing key";
return 1;
}
int count = 0;
while (query.next())
{
count += query.value(0).toInt();
}
if (count > 0)
{
query.prepare("UPDATE data_store SET value = :value, expiry = :expiry WHERE key = :key");
query.bindValue(":value", value);
query.bindValue(":expiry", expiry > 0 ? QDateTime::currentDateTime().toSecsSinceEpoch() + expiry : 0);
query.bindValue(":key", key);
}
else
{
query.prepare("INSERT INTO data_store (key, value, expiry) VALUES (:key, :value, :expiry)");
query.bindValue(":key", key);
query.bindValue(":value", value);
query.bindValue(":expiry", expiry > 0 ? QDateTime::currentDateTime().toSecsSinceEpoch() + expiry : 0);
}
if (!query.exec())
{
qDebug() << "Error setting value:" << query.lastError().text();
return 1;
}
return 0;
}
int DBRedis::getData(const QString & key, QString & value)
{
value.clear();
int res = deleteExpiredEntries();
if (res)
{
return res;
}
QSqlQuery query(m_DataBase);
query.prepare("SELECT value FROM data_store WHERE key = :key");
query.bindValue(":key", key);
if (!query.exec())
{
qDebug() << "Error getting value:" << query.lastError().text();
return 1;
}
if (!query.next())
{
qDebug() << "Error getting value:" << query.lastError().text();
return 2;
}
value = query.value(0).toString();
return 0;
}
int DBRedis::deleteData(const QString & key)
{
int res = deleteExpiredEntries();
if (res)
{
return res;
}
QSqlQuery query(m_DataBase);
query.prepare("DELETE FROM data_store WHERE key = :key");
query.bindValue(":key", key);
if (!query.exec())
{
qDebug() << "Error deleting value:" << query.lastError().text();
return 1;
}
return 0;
}
int DBRedis::init()
{
if (m_HasInit)
{
return 0;
}
m_DataBase = QSqlDatabase::addDatabase("QSQLITE", m_ConnectName);
m_DataBase.setDatabaseName("dbredis.db");
if (m_DataBase.open())
{
QString table = "CREATE TABLE IF NOT EXISTS data_store(key TEXT, value TEXT, expiry INTEGER)";
QSqlQuery query(QSqlDatabase::database(m_ConnectName));
if (!query.exec(table.toUtf8()))
{
qDebug() << "Error deleting value:" << query.lastError().text();
return 1;
}
}
else
{
qDebug() << "Error db open fail";
return 3;
}
m_HasInit = true;
return 0;
}
+80 -80
View File
@@ -1,80 +1,80 @@
#ifndef __DBREDIS_H
#define __DBREDIS_H
#include <QtSql>
class DBRedis
{
public:
DBRedis();
~DBRedis();
/***
* @描述 : 设定值
* @入参 : key 键
value 值
expiry 单位为秒 默认为 0
0 为永不过期
其他值必须大于0
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int setData(const QString&key, const QString&value, uint32_t expiry = 0);
/***
* @描述 : 获取值
* @入参 : key 键
* @输出 : value 值
* @返回 : 0 成功
1 数据库错误
2 不存在该数据或已过期
3 数据库错误
*/
static int getData(const QString&key, QString&value);
/***
* @描述 : 删除值
* @入参 : key 键
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int deleteData(const QString&key);
private:
static QSqlDatabase m_DataBase;
static QString m_ConnectName;
static bool m_HasInit;
private:
/***
* @描述 : 初始化
* @入参 : 无
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int init();
/***
* @描述 : 删除过期的条目
* @入参 : 无
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int deleteExpiredEntries();
};
#endif // !__DBREDIS_H
#ifndef __DBREDIS_H
#define __DBREDIS_H
#include <QtSql>
class DBRedis
{
public:
DBRedis();
~DBRedis();
/***
* @描述 : 设定值
* @入参 : key 键
value 值
expiry 单位为秒 默认为 0
0 为永不过期
其他值必须大于0
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int setData(const QString&key, const QString&value, uint32_t expiry = 0);
/***
* @描述 : 获取值
* @入参 : key 键
* @输出 : value 值
* @返回 : 0 成功
1 数据库错误
2 不存在该数据或已过期
3 数据库错误
*/
static int getData(const QString&key, QString&value);
/***
* @描述 : 删除值
* @入参 : key 键
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int deleteData(const QString&key);
private:
static QSqlDatabase m_DataBase;
static QString m_ConnectName;
static bool m_HasInit;
private:
/***
* @描述 : 初始化
* @入参 : 无
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int init();
/***
* @描述 : 删除过期的条目
* @入参 : 无
* @输出 : 无
* @返回 : 0 成功
1 数据库错误
3 数据库错误
*/
static int deleteExpiredEntries();
};
#endif // !__DBREDIS_H
+28 -28
View File
@@ -1,28 +1,28 @@
#include "DialogAuthorization.h"
#include "ui_dialogauthorization.h"
DialogAuthorization::DialogAuthorization(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogAuthorization)
{
ui->setupUi(this);
this->setWindowTitle(tr("输入密码"));
this->setFixedSize(this->geometry().width(),this->geometry().height());
ui->lineEditAuth->setEchoMode(QLineEdit::Password); // 密码不回显
}
DialogAuthorization::~DialogAuthorization()
{
delete ui;
}
QString DialogAuthorization::getAuth(){
return ui->lineEditAuth->text();
}
void DialogAuthorization::clearAuth(){
ui->lineEditAuth->setText(tr(""));
}
#include "DialogAuthorization.h"
#include "ui_dialogauthorization.h"
DialogAuthorization::DialogAuthorization(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogAuthorization)
{
ui->setupUi(this);
this->setWindowTitle(tr("输入密码"));
this->setFixedSize(this->geometry().width(),this->geometry().height());
ui->lineEditAuth->setEchoMode(QLineEdit::Password); // 密码不回显
}
DialogAuthorization::~DialogAuthorization()
{
delete ui;
}
QString DialogAuthorization::getAuth(){
return ui->lineEditAuth->text();
}
void DialogAuthorization::clearAuth(){
ui->lineEditAuth->setText(tr(""));
}
+25 -25
View File
@@ -1,25 +1,25 @@
#ifndef DIALOGAUTHORIZATION_H
#define DIALOGAUTHORIZATION_H
#include <QDialog>
namespace Ui {
class DialogAuthorization;
}
class DialogAuthorization : public QDialog
{
Q_OBJECT
public:
explicit DialogAuthorization(QWidget *parent = 0);
~DialogAuthorization();
QString getAuth();
void clearAuth();
private:
Ui::DialogAuthorization *ui;
//QTimer time1;
};
#endif // DIALOGAUTHORIZATION_H
#ifndef DIALOGAUTHORIZATION_H
#define DIALOGAUTHORIZATION_H
#include <QDialog>
namespace Ui {
class DialogAuthorization;
}
class DialogAuthorization : public QDialog
{
Q_OBJECT
public:
explicit DialogAuthorization(QWidget *parent = 0);
~DialogAuthorization();
QString getAuth();
void clearAuth();
private:
Ui::DialogAuthorization *ui;
//QTimer time1;
};
#endif // DIALOGAUTHORIZATION_H
+28 -28
View File
@@ -1,28 +1,28 @@
#include "DialogAuthorizationPrint.h"
#include "ui_dialogAuthorizationPrint.h"
DialogAuthorizationPrint::DialogAuthorizationPrint(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogAuthorizationPrint)
{
ui->setupUi(this);
this->setWindowTitle(tr("请输入打印密码"));
this->setFixedSize(this->geometry().width(),this->geometry().height());
ui->lineEditAuth->setEchoMode(QLineEdit::Password); // 密码不回显
}
DialogAuthorizationPrint::~DialogAuthorizationPrint()
{
delete ui;
}
QString DialogAuthorizationPrint::getAuth(){
return ui->lineEditAuth->text();
}
void DialogAuthorizationPrint::clearAuth(){
ui->lineEditAuth->setText(tr(""));
}
#include "DialogAuthorizationPrint.h"
#include "ui_dialogAuthorizationPrint.h"
DialogAuthorizationPrint::DialogAuthorizationPrint(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogAuthorizationPrint)
{
ui->setupUi(this);
this->setWindowTitle(tr("请输入打印密码"));
this->setFixedSize(this->geometry().width(),this->geometry().height());
ui->lineEditAuth->setEchoMode(QLineEdit::Password); // 密码不回显
}
DialogAuthorizationPrint::~DialogAuthorizationPrint()
{
delete ui;
}
QString DialogAuthorizationPrint::getAuth(){
return ui->lineEditAuth->text();
}
void DialogAuthorizationPrint::clearAuth(){
ui->lineEditAuth->setText(tr(""));
}
+25 -25
View File
@@ -1,25 +1,25 @@
#ifndef DIALOGAUTHORIZATIONPRINT_H
#define DIALOGAUTHORIZATIONPRINT_H
#include <QDialog>
namespace Ui {
class DialogAuthorizationPrint;
}
class DialogAuthorizationPrint : public QDialog
{
Q_OBJECT
public:
explicit DialogAuthorizationPrint(QWidget *parent = 0);
~DialogAuthorizationPrint();
QString getAuth();
void clearAuth();
private:
Ui::DialogAuthorizationPrint *ui;
//QTimer time1;
};
#endif // DIALOGAUTHORIZATIONPRINT_H
#ifndef DIALOGAUTHORIZATIONPRINT_H
#define DIALOGAUTHORIZATIONPRINT_H
#include <QDialog>
namespace Ui {
class DialogAuthorizationPrint;
}
class DialogAuthorizationPrint : public QDialog
{
Q_OBJECT
public:
explicit DialogAuthorizationPrint(QWidget *parent = 0);
~DialogAuthorizationPrint();
QString getAuth();
void clearAuth();
private:
Ui::DialogAuthorizationPrint *ui;
//QTimer time1;
};
#endif // DIALOGAUTHORIZATIONPRINT_H
+427 -427
View File
@@ -1,427 +1,427 @@
#include "DialogFileOperation.h"
#include "ui_dialogfileoperation.h"
#include <QDir>
#include <QStringListModel>
#include <SysPara.h>
#include <QAbstractItemView>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <Public.h>
#include <QTextCodec>
#include <QByteArray>
#include <QDebug>
#include <QProcess>
#include<QStandardItemModel>
#include"HtmlDelegate.h"
#include"myinclude.h"
#include<iostream>
#include<string>
#include "LogInfo.h"
// 递归复制目录/文件。true 表示全部成功,false 表示有失败
static bool copyRecursively(const QString &srcPath, const QString &dstPath)
{
QFileInfo srcInfo(srcPath);
if (!srcInfo.exists()) return false;
if (srcInfo.isDir()) {
QDir dstDir(dstPath);
if (!dstDir.exists()) {
if (!QDir().mkpath(dstPath)) return false;
}
QDir srcDir(srcPath);
QFileInfoList entries = srcDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries);
for (const QFileInfo &fi : entries) {
QString src = fi.absoluteFilePath();
QString dst = QDir(dstPath).filePath(fi.fileName());
if (!copyRecursively(src, dst)) return false;
}
return true;
} else {
// 文件
if (QFile::exists(dstPath)) {
QFile::remove(dstPath);
}
return QFile::copy(srcPath, dstPath);
}
}
// 只复制 srcDirPath 根目录下的文件(不递归到子目录)。true 表示全部成功,false 表示有失败或源目录不存在
static bool copyFilesOneLevel(const QString &srcDirPath, const QString &dstDirPath)
{
QDir srcDir(srcDirPath);
if (!srcDir.exists()) return false;
QDir dstDir(dstDirPath);
if (!dstDir.exists()) {
if (!QDir().mkpath(dstDirPath)) return false;
}
QFileInfoList files = srcDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
bool allOk = true;
for (const QFileInfo &fi : files) {
QString src = fi.absoluteFilePath();
QString dst = dstDir.filePath(fi.fileName());
if (QFile::exists(dst)) QFile::remove(dst);
if (!QFile::copy(src, dst)) {
LogInfo::setRunStatusText(QString("Copy file failed: %1 -> %2").arg(src).arg(dst));
allOk = false;
}
}
return allOk;
}
DialogFileOperation::DialogFileOperation(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogFileOperation)
{
ui->setupUi(this);
this->setWindowTitle(tr("文件操作"));
ui->textEditView->setReadOnly(true);
ui->textEditView->setLineWrapMode(QTextEdit::NoWrap);
ui->textEditView->document()->setDocumentMargin(0);
this->setFixedSize(this->geometry().width(),this->geometry().height());
EditMode=4;
}
void DialogFileOperation::refreshListView(int mode){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
QDir dir(dirPath);
QStringList filters;
EditMode = mode;
if(mode==TXTFILE) filters << "*.html" << "*.txt" << "*.TXT" << "*.jpeg" << "*.gif" << "*.jpg" << "*.bmp"<< "*.BMP"<< "*.bin"; // txtmode
// else if(mode==PICFILE) filters << "*.png";// <<"*.jpg" ; // picmode
else if(mode==PICFILE) filters << "*.png" << "*.jpeg" << "*.gif" << "*.jpg" << "*.bmp"<< "*.BMP";
else if(mode==SCENE) filters << "*.xml";
else filters << "*.html" << "*.bmp" << "*.BMP"<<"*.jpg"<<"*.gif";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files);
#ifndef EnableArabic
QStringListModel *model = new QStringListModel(dir.entryList());
#else
QStringList entries=dir.entryList();
QStandardItemModel *model = new QStandardItemModel();
for(int i=0;i<entries.size();i++){
//qDebug()<<"entries:"<<entries.at(i);
QStandardItem *item1 = new QStandardItem(entries.at(i));
int lastIndex=entries.at(i).lastIndexOf(".");
if(lastIndex != -1){
int secondLastIndex = entries.at(i).lastIndexOf(".",lastIndex-1);
if(secondLastIndex != -1){
QString subsuffix=entries.at(i).mid(secondLastIndex);
if(subsuffix.contains(".a.")){
QString subsuffix2=entries.at(i).mid(lastIndex);
QString subname=entries.at(i).mid(0,secondLastIndex);
QString stringhtml=QString("<span style=font-family:'biyangarabic';>%1</span><span style=font-family:'biyang';>%2</span>").arg(subname).arg(subsuffix2);
QStandardItem *item2 = new QStandardItem(stringhtml);
model->appendRow(item2);
}
}else{
model->appendRow(item1);
}
}
}
ui->listViewFile->setItemDelegate(new HtmlDelegate);
#endif
ui->listViewFile->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->listViewFile->setModel(model); //useList是个QListView
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(0 , 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
DialogFileOperation::~DialogFileOperation()
{
delete ui;
}
void DialogFileOperation::on_listViewFile_entered(const QModelIndex &index)
{
#ifdef EnableArabic
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
#endif
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString filePath = dirPath + fileName;
#endif
if(filePath.endsWith(".gif") || filePath.endsWith(".jpeg") || filePath.endsWith(".jpg") ||
filePath.endsWith(".png") || filePath.endsWith(".bmp")|| filePath.endsWith(".BMP")|| filePath.endsWith(".nda")){
ui->textEditView->clear();
ui->textEditView->setHtml(QString("<img src='%1'/>").arg(filePath));
}
else if(filePath.endsWith(".xml"))
{
emit createSceneImage(filePath);
ui->textEditView->setHtml(QString("<img src='%1'/>").arg("./printSceneView.png"));
}
else {
QFile file(filePath);
if (!file.open(QFile::ReadOnly))
return ;
if (filePath.endsWith(".txt") || filePath.endsWith(".TXT"))
{
qint64 size = file.size();
if(size/1024 > 10)
{
return;
}
}
QByteArray data = file.readAll();
QTextCodec *codec = Qt::codecForHtml(data);
QString str = codec->toUnicode(data);
if (Qt::mightBeRichText(str)) {
if(!ui->radioButtonLocal->isChecked())
str.replace(DOC_ROOT_DIR,UDISK_DOC_ROOT_DIR); //必须替换相应的路径
ui->textEditView->setHtml(str);
} else {
str = QString::fromLocal8Bit(data);
ui->textEditView->setPlainText(str);
}
}
}
void DialogFileOperation::on_listViewFile_clicked(const QModelIndex &index)
{
on_listViewFile_entered(index);
}
void DialogFileOperation::on_pushButtonNext_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index((currIndex.row() + 1)%count, 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
void DialogFileOperation::on_pushButtonLast_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(currIndex.row() == 0?(count - 1):(currIndex.row() - 1), 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
void DialogFileOperation::on_pushButtonExit_pressed()
{
hide();
}
void DialogFileOperation::on_pushButtonDelFile_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, tr("警告"),
tr("是否确认删除当前文件?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QModelIndex index = ui->listViewFile->currentIndex();
int currRow = index.row();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
QString filePath=dirPath+fileName;
#endif
QFile file(filePath);
if(!QFileInfo(filePath).baseName().startsWith("UP")){
if(file.exists())file.remove();
file.setFileName(PARA_ROOT_DIR + QFileInfo(filePath).baseName()+".dpn" );
//file.setFileName( PARA_ROOT_DIR + QFileInfo(filePath).baseName()+".dpn" );
if(file.exists())file.remove();
}
//Public::resetPara(); // 20140923 这个BUG导致系统参数被恢复
refreshListView(EditMode);
int count = ui->listViewFile->model()->rowCount();
if(count){
index = ui->listViewFile->model()->index((currRow > (count - 1))?(count - 1):currRow , 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
}
void DialogFileOperation::on_pushButtonDelAll_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, tr("警告"),
tr("是否确认删除所有文件?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
// 删除所有文件的方法要改进
system((char *)((QString("mkdir %1").arg(TESTDIR)).toLatin1().data()));
system((char *)((QString("cp %1/UP* %2/. ").arg(DOC_ROOT_DIR).arg(TESTDIR)).toLatin1().data())); //先备份UP*
system((char *)((QString("rm %1/*.*").arg(dirPath)).toLatin1().data()));// 删除所有打印文件
system((char *)((QString("rm %1*.ini").arg(PARA_ROOT_DIR)).toLatin1().data())); // 删除所有参数文件
system((char *)((QString("rm %1*.dpn").arg(PARA_ROOT_DIR)).toLatin1().data()));
system((char *)((QString("cp %1/UP.* %1/UP1.* %2/. ").arg(TESTDIR).arg(DOC_ROOT_DIR)).toLatin1().data()));
//system((char *)((QString("cp %1* %2/. ").arg(TESTDIR).arg(PARA_ROOT_DIR)).toLatin1().data()));
refreshListView(EditMode);
}
}
void DialogFileOperation::on_pushButtonImport_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认从U盘导入所有文件?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
bool ok = true;
// 拷贝参数文件
QString srcHi = QDir(UDISK_DOC_ROOT_DIR).filePath("VoltParaHi.bin");
QString dstHi = QDir(PARA_ROOT_DIR).filePath("VoltParaHi.bin");
if (QFile::exists(srcHi)) {
if (QFile::exists(dstHi)) QFile::remove(dstHi);
if (!QFile::copy(srcHi, dstHi)) {
LogInfo::setRunStatusText("Copy VoltParaHi.bin failed");
ok = false;
}
}
QString srcStd = QDir(UDISK_DOC_ROOT_DIR).filePath("VoltParaStd.bin");
QString dstStd = QDir(PARA_ROOT_DIR).filePath("VoltParaStd.bin");
if (QFile::exists(srcStd)) {
if (QFile::exists(dstStd)) QFile::remove(dstStd);
if (!QFile::copy(srcStd, dstStd)) {
LogInfo::setRunStatusText("Copy VoltParaStd.bin failed");
ok = false;
}
}
// 复制 U 盘文档到本地(仅复制一级文件,不递归)
bool cpOk = copyFilesOneLevel(UDISK_DOC_ROOT_DIR, DOC_ROOT_DIR);
qDebug() << "copyRecursively import result:" << cpOk;
QProcess::execute("sync");
refreshListView(EditMode);
if (ok && cpOk) {
QMessageBox::information(this, tr("提示"), tr("成功从U盘导入"));
} else {
QMessageBox::warning(this, tr("警告"), tr("从U盘导入时部分文件失败"));
}
}
}
void DialogFileOperation::on_pushButtonExport_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将所有文件导出到U盘?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
QDir dir(UDISK_DOC_ROOT_DIR);
if(!dir.exists()){
if (!QDir().mkpath(UDISK_DOC_ROOT_DIR)){
QMessageBox::warning(this,tr("警告"),tr("U盘doc目录创建失败"));
return;
}
}
// 仅复制本地文档根目录下的文件到 U 盘(不递归)
bool ok = copyFilesOneLevel(DOC_ROOT_DIR, UDISK_DOC_ROOT_DIR);
QProcess::execute("sync");
refreshListView(EditMode);
if (ok) {
QMessageBox::information(this, tr("提示"), tr("成功导出到U盘"));
} else {
QMessageBox::warning(this, tr("警告"), tr("导出到U盘时有文件失败"));
}
}
}
void DialogFileOperation::on_pushButtonInsert_clicked()
{
QModelIndex index = ui->listViewFile->currentIndex();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
QString filePath = dirPath + fileName;
#endif
emit openFile(filePath,true);
hide();
}
void DialogFileOperation::on_pushButtonOpen_clicked()
{
QModelIndex index = ui->listViewFile->currentIndex();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
QString filePath = dirPath + fileName;
#endif
emit openFile(filePath,false);
hide();
}
void DialogFileOperation::on_radioButtonLocal_released()
{
refreshListView(EditMode);
}
void DialogFileOperation::on_radioButtonUdisk_released()
{
QDir dir(UDISK_DOC_ROOT_DIR);
if(!dir.exists()){
dir.mkdir("/udisk/doc");
QMessageBox::warning(0,tr("警告"),tr("U盘未插入或U盘根目录下的doc文件夹不存在!"));
}
refreshListView(EditMode);
}
void DialogFileOperation::modbus_openfile(QString filename)
{
emit openFile(filename,true);
}
#include "DialogFileOperation.h"
#include "ui_dialogfileoperation.h"
#include <QDir>
#include <QStringListModel>
#include <SysPara.h>
#include <QAbstractItemView>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <Public.h>
#include <QTextCodec>
#include <QByteArray>
#include <QDebug>
#include <QProcess>
#include<QStandardItemModel>
#include"HtmlDelegate.h"
#include"myinclude.h"
#include<iostream>
#include<string>
#include "LogInfo.h"
// 递归复制目录/文件。true 表示全部成功,false 表示有失败
static bool copyRecursively(const QString &srcPath, const QString &dstPath)
{
QFileInfo srcInfo(srcPath);
if (!srcInfo.exists()) return false;
if (srcInfo.isDir()) {
QDir dstDir(dstPath);
if (!dstDir.exists()) {
if (!QDir().mkpath(dstPath)) return false;
}
QDir srcDir(srcPath);
QFileInfoList entries = srcDir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries);
for (const QFileInfo &fi : entries) {
QString src = fi.absoluteFilePath();
QString dst = QDir(dstPath).filePath(fi.fileName());
if (!copyRecursively(src, dst)) return false;
}
return true;
} else {
// 文件
if (QFile::exists(dstPath)) {
QFile::remove(dstPath);
}
return QFile::copy(srcPath, dstPath);
}
}
// 只复制 srcDirPath 根目录下的文件(不递归到子目录)。true 表示全部成功,false 表示有失败或源目录不存在
static bool copyFilesOneLevel(const QString &srcDirPath, const QString &dstDirPath)
{
QDir srcDir(srcDirPath);
if (!srcDir.exists()) return false;
QDir dstDir(dstDirPath);
if (!dstDir.exists()) {
if (!QDir().mkpath(dstDirPath)) return false;
}
QFileInfoList files = srcDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
bool allOk = true;
for (const QFileInfo &fi : files) {
QString src = fi.absoluteFilePath();
QString dst = dstDir.filePath(fi.fileName());
if (QFile::exists(dst)) QFile::remove(dst);
if (!QFile::copy(src, dst)) {
LogInfo::setRunStatusText(QString("Copy file failed: %1 -> %2").arg(src).arg(dst));
allOk = false;
}
}
return allOk;
}
DialogFileOperation::DialogFileOperation(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogFileOperation)
{
ui->setupUi(this);
this->setWindowTitle(tr("文件操作"));
ui->textEditView->setReadOnly(true);
ui->textEditView->setLineWrapMode(QTextEdit::NoWrap);
ui->textEditView->document()->setDocumentMargin(0);
this->setFixedSize(this->geometry().width(),this->geometry().height());
EditMode=4;
}
void DialogFileOperation::refreshListView(int mode){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
QDir dir(dirPath);
QStringList filters;
EditMode = mode;
if(mode==TXTFILE) filters << "*.html" << "*.txt" << "*.TXT" << "*.jpeg" << "*.gif" << "*.jpg" << "*.bmp"<< "*.BMP"<< "*.bin"; // txtmode
// else if(mode==PICFILE) filters << "*.png";// <<"*.jpg" ; // picmode
else if(mode==PICFILE) filters << "*.png" << "*.jpeg" << "*.gif" << "*.jpg" << "*.bmp"<< "*.BMP";
else if(mode==SCENE) filters << "*.xml";
else filters << "*.html" << "*.bmp" << "*.BMP"<<"*.jpg"<<"*.gif";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files);
#ifndef EnableArabic
QStringListModel *model = new QStringListModel(dir.entryList());
#else
QStringList entries=dir.entryList();
QStandardItemModel *model = new QStandardItemModel();
for(int i=0;i<entries.size();i++){
//qDebug()<<"entries:"<<entries.at(i);
QStandardItem *item1 = new QStandardItem(entries.at(i));
int lastIndex=entries.at(i).lastIndexOf(".");
if(lastIndex != -1){
int secondLastIndex = entries.at(i).lastIndexOf(".",lastIndex-1);
if(secondLastIndex != -1){
QString subsuffix=entries.at(i).mid(secondLastIndex);
if(subsuffix.contains(".a.")){
QString subsuffix2=entries.at(i).mid(lastIndex);
QString subname=entries.at(i).mid(0,secondLastIndex);
QString stringhtml=QString("<span style=font-family:'biyangarabic';>%1</span><span style=font-family:'biyang';>%2</span>").arg(subname).arg(subsuffix2);
QStandardItem *item2 = new QStandardItem(stringhtml);
model->appendRow(item2);
}
}else{
model->appendRow(item1);
}
}
}
ui->listViewFile->setItemDelegate(new HtmlDelegate);
#endif
ui->listViewFile->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->listViewFile->setModel(model); //useList是个QListView
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(0 , 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
DialogFileOperation::~DialogFileOperation()
{
delete ui;
}
void DialogFileOperation::on_listViewFile_entered(const QModelIndex &index)
{
#ifdef EnableArabic
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
#endif
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString filePath = dirPath + fileName;
#endif
if(filePath.endsWith(".gif") || filePath.endsWith(".jpeg") || filePath.endsWith(".jpg") ||
filePath.endsWith(".png") || filePath.endsWith(".bmp")|| filePath.endsWith(".BMP")|| filePath.endsWith(".nda")){
ui->textEditView->clear();
ui->textEditView->setHtml(QString("<img src='%1'/>").arg(filePath));
}
else if(filePath.endsWith(".xml"))
{
emit createSceneImage(filePath);
ui->textEditView->setHtml(QString("<img src='%1'/>").arg("./printSceneView.png"));
}
else {
QFile file(filePath);
if (!file.open(QFile::ReadOnly))
return ;
if (filePath.endsWith(".txt") || filePath.endsWith(".TXT"))
{
qint64 size = file.size();
if(size/1024 > 10)
{
return;
}
}
QByteArray data = file.readAll();
QTextCodec *codec = Qt::codecForHtml(data);
QString str = codec->toUnicode(data);
if (Qt::mightBeRichText(str)) {
if(!ui->radioButtonLocal->isChecked())
str.replace(DOC_ROOT_DIR,UDISK_DOC_ROOT_DIR); //必须替换相应的路径
ui->textEditView->setHtml(str);
} else {
str = QString::fromLocal8Bit(data);
ui->textEditView->setPlainText(str);
}
}
}
void DialogFileOperation::on_listViewFile_clicked(const QModelIndex &index)
{
on_listViewFile_entered(index);
}
void DialogFileOperation::on_pushButtonNext_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index((currIndex.row() + 1)%count, 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
void DialogFileOperation::on_pushButtonLast_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(currIndex.row() == 0?(count - 1):(currIndex.row() - 1), 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
void DialogFileOperation::on_pushButtonExit_pressed()
{
hide();
}
void DialogFileOperation::on_pushButtonDelFile_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, tr("警告"),
tr("是否确认删除当前文件?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QModelIndex index = ui->listViewFile->currentIndex();
int currRow = index.row();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
QString filePath=dirPath+fileName;
#endif
QFile file(filePath);
if(!QFileInfo(filePath).baseName().startsWith("UP")){
if(file.exists())file.remove();
file.setFileName(PARA_ROOT_DIR + QFileInfo(filePath).baseName()+".dpn" );
//file.setFileName( PARA_ROOT_DIR + QFileInfo(filePath).baseName()+".dpn" );
if(file.exists())file.remove();
}
//Public::resetPara(); // 20140923 这个BUG导致系统参数被恢复
refreshListView(EditMode);
int count = ui->listViewFile->model()->rowCount();
if(count){
index = ui->listViewFile->model()->index((currRow > (count - 1))?(count - 1):currRow , 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
}
}
void DialogFileOperation::on_pushButtonDelAll_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, tr("警告"),
tr("是否确认删除所有文件?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
// 删除所有文件的方法要改进
system((char *)((QString("mkdir %1").arg(TESTDIR)).toLatin1().data()));
system((char *)((QString("cp %1/UP* %2/. ").arg(DOC_ROOT_DIR).arg(TESTDIR)).toLatin1().data())); //先备份UP*
system((char *)((QString("rm %1/*.*").arg(dirPath)).toLatin1().data()));// 删除所有打印文件
system((char *)((QString("rm %1*.ini").arg(PARA_ROOT_DIR)).toLatin1().data())); // 删除所有参数文件
system((char *)((QString("rm %1*.dpn").arg(PARA_ROOT_DIR)).toLatin1().data()));
system((char *)((QString("cp %1/UP.* %1/UP1.* %2/. ").arg(TESTDIR).arg(DOC_ROOT_DIR)).toLatin1().data()));
//system((char *)((QString("cp %1* %2/. ").arg(TESTDIR).arg(PARA_ROOT_DIR)).toLatin1().data()));
refreshListView(EditMode);
}
}
void DialogFileOperation::on_pushButtonImport_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认从U盘导入所有文件?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
bool ok = true;
// 拷贝参数文件
QString srcHi = QDir(UDISK_DOC_ROOT_DIR).filePath("VoltParaHi.bin");
QString dstHi = QDir(PARA_ROOT_DIR).filePath("VoltParaHi.bin");
if (QFile::exists(srcHi)) {
if (QFile::exists(dstHi)) QFile::remove(dstHi);
if (!QFile::copy(srcHi, dstHi)) {
LogInfo::setRunStatusText("Copy VoltParaHi.bin failed");
ok = false;
}
}
QString srcStd = QDir(UDISK_DOC_ROOT_DIR).filePath("VoltParaStd.bin");
QString dstStd = QDir(PARA_ROOT_DIR).filePath("VoltParaStd.bin");
if (QFile::exists(srcStd)) {
if (QFile::exists(dstStd)) QFile::remove(dstStd);
if (!QFile::copy(srcStd, dstStd)) {
LogInfo::setRunStatusText("Copy VoltParaStd.bin failed");
ok = false;
}
}
// 复制 U 盘文档到本地(仅复制一级文件,不递归)
bool cpOk = copyFilesOneLevel(UDISK_DOC_ROOT_DIR, DOC_ROOT_DIR);
qDebug() << "copyRecursively import result:" << cpOk;
QProcess::execute("sync");
refreshListView(EditMode);
if (ok && cpOk) {
QMessageBox::information(this, tr("提示"), tr("成功从U盘导入"));
} else {
QMessageBox::warning(this, tr("警告"), tr("从U盘导入时部分文件失败"));
}
}
}
void DialogFileOperation::on_pushButtonExport_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将所有文件导出到U盘?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
QDir dir(UDISK_DOC_ROOT_DIR);
if(!dir.exists()){
if (!QDir().mkpath(UDISK_DOC_ROOT_DIR)){
QMessageBox::warning(this,tr("警告"),tr("U盘doc目录创建失败"));
return;
}
}
// 仅复制本地文档根目录下的文件到 U 盘(不递归)
bool ok = copyFilesOneLevel(DOC_ROOT_DIR, UDISK_DOC_ROOT_DIR);
QProcess::execute("sync");
refreshListView(EditMode);
if (ok) {
QMessageBox::information(this, tr("提示"), tr("成功导出到U盘"));
} else {
QMessageBox::warning(this, tr("警告"), tr("导出到U盘时有文件失败"));
}
}
}
void DialogFileOperation::on_pushButtonInsert_clicked()
{
QModelIndex index = ui->listViewFile->currentIndex();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
QString filePath = dirPath + fileName;
#endif
emit openFile(filePath,true);
hide();
}
void DialogFileOperation::on_pushButtonOpen_clicked()
{
QModelIndex index = ui->listViewFile->currentIndex();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}
QString filePath = dirPath + fileName;
#endif
emit openFile(filePath,false);
hide();
}
void DialogFileOperation::on_radioButtonLocal_released()
{
refreshListView(EditMode);
}
void DialogFileOperation::on_radioButtonUdisk_released()
{
QDir dir(UDISK_DOC_ROOT_DIR);
if(!dir.exists()){
dir.mkdir("/udisk/doc");
QMessageBox::warning(0,tr("警告"),tr("U盘未插入或U盘根目录下的doc文件夹不存在!"));
}
refreshListView(EditMode);
}
void DialogFileOperation::modbus_openfile(QString filename)
{
emit openFile(filename,true);
}
+68 -68
View File
@@ -1,68 +1,68 @@
#ifndef DIALOGFILEOPERATION_H
#define DIALOGFILEOPERATION_H
#include <QDialog>
#include "DialogFileOperation.h"
#include <QModelIndex>
namespace Ui {
class DialogFileOperation;
}
class DialogFileOperation : public QDialog
{
Q_OBJECT
public:
explicit DialogFileOperation(QWidget *parent = 0);
~DialogFileOperation();
void refreshListView(int mode);
void modbus_openfile(QString filename);
int EditMode;
private slots:
void on_pushButtonNext_pressed();
void on_pushButtonLast_pressed();
void on_pushButtonExit_pressed();
void on_pushButtonDelFile_pressed();
void on_pushButtonDelAll_pressed();
void on_pushButtonImport_pressed();
void on_pushButtonExport_pressed();
void on_pushButtonInsert_clicked();
void on_pushButtonOpen_clicked();
void on_radioButtonLocal_released();
void on_radioButtonUdisk_released();
void on_listViewFile_entered(const QModelIndex &index);
void on_listViewFile_clicked(const QModelIndex &index);
Q_SIGNALS:
void openFile(QString filePath,bool insertFlag);
void createSceneImage(QString filePath);
private:
Ui::DialogFileOperation *ui;
};
#endif // DIALOGFILEOPERATION_H
#ifndef DIALOGFILEOPERATION_H
#define DIALOGFILEOPERATION_H
#include <QDialog>
#include "DialogFileOperation.h"
#include <QModelIndex>
namespace Ui {
class DialogFileOperation;
}
class DialogFileOperation : public QDialog
{
Q_OBJECT
public:
explicit DialogFileOperation(QWidget *parent = 0);
~DialogFileOperation();
void refreshListView(int mode);
void modbus_openfile(QString filename);
int EditMode;
private slots:
void on_pushButtonNext_pressed();
void on_pushButtonLast_pressed();
void on_pushButtonExit_pressed();
void on_pushButtonDelFile_pressed();
void on_pushButtonDelAll_pressed();
void on_pushButtonImport_pressed();
void on_pushButtonExport_pressed();
void on_pushButtonInsert_clicked();
void on_pushButtonOpen_clicked();
void on_radioButtonLocal_released();
void on_radioButtonUdisk_released();
void on_listViewFile_entered(const QModelIndex &index);
void on_listViewFile_clicked(const QModelIndex &index);
Q_SIGNALS:
void openFile(QString filePath,bool insertFlag);
void createSceneImage(QString filePath);
private:
Ui::DialogFileOperation *ui;
};
#endif // DIALOGFILEOPERATION_H
+477 -477
View File
@@ -1,477 +1,477 @@
#include "DialogFontSize.h"
#include "ui_dialogfontsize.h"
#include <QDebug>
#include <QFileInfo>
#include <QDateTime>
#include <QFontDatabase>
#include <QString>
#include <QDir>
#include <iostream>
#include "myinclude.h"
#include "Public.h"
DialogFontSize::DialogFontSize(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogFontSize)
{
ui->setupUi(this);
this->setFixedSize(this->geometry().width(),this->geometry().height());
this->setWindowTitle(tr("选择字体大小"));
font.setFamily("WenQuanYi12");
QString langurageType = Public::ReadLanguageName();
if(langurageType != "English" && langurageType != "Chinese")
font.setFamily("Yanglabeldot12");
font.setPixelSize(12);
ui->lineEdit->setFont(font);
connect(ui->radioButton7Bangla,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton7PointNum,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton5Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriL(bool)));
connect(ui->radioButton7Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton9Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriL(bool)));
connect(ui->radioButton12Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton16Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriL(bool)));
connect(ui->radioButton24Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton21PointNum,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton32Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
#ifdef VNLGXX
ui->checkBoxBold->hide();
ui->radioButton5Point->hide();
ui->radioButton7Point->hide();
ui->radioButton9Point->hide();
ui->radioButton12Point->hide();
ui->radioButton16Point->hide();
ui->radioButton24Point->hide();
#else
// ui->checkBoxBold->hide();
// ui->labelFont->hide();
// ui->fontComboBox->hide();
// ui->comboBoxFontSize->hide();
#endif
GetFileInfo();
flagOfLeft = false;
flagOfRight = false;
#ifdef EnableBangla
ui->radioButton7Bangla->setEnabled(1);
#else
ui->radioButton7Bangla->setEnabled(0);
#endif
//ui->checkBox_Left->setStyleSheet("QCheckBox { font-size: 24pt; }");
}
DialogFontSize::~DialogFontSize()
{
delete ui;
}
void DialogFontSize::Button7HoriL(bool ok){
int pixsize;
getValue(&pixsize);
//qDebug()<<ui->lineEdit->font().family()<<ui->lineEdit->font().pixelSize();
qDebug() << "click L";
}
void DialogFontSize::Button7HoriR(bool ok){
int pixsize;
getValue(&pixsize);
//qDebug()<<ui->lineEdit->font().family()<<ui->lineEdit->font().pixelSize();
qDebug() << "click R";
}
void DialogFontSize::ChangeFont(QString fontFamily){
font.setFamily(fontFamily);
//font.setPixelSize(pixelSize);
ui->lineEdit->setFont(font); // 设置预览字体
// if(fontFamily=="wenquanyi" ){
// ui->comboBoxFontSize->clear();
// ui->comboBoxFontSize->addItem("12");
// ui->comboBoxFontSize->addItem("16");
// //ui->comboBoxFontSize->addItem("12");
// }
// else if(fontFamily=="biyang"){
// ui->comboBoxFontSize->clear();
// ui->comboBoxFontSize->addItem("5");
// ui->comboBoxFontSize->addItem("7");
// ui->comboBoxFontSize->addItem("9");
// //ui->comboBoxFontSize->addItem("10");
// }
// else {
// ui->comboBoxFontSize->clear();
// ui->comboBoxFontSize->addItem("14");
// ui->comboBoxFontSize->addItem("16");
// ui->comboBoxFontSize->addItem("18");
// ui->comboBoxFontSize->addItem("20");
// ui->comboBoxFontSize->addItem("24");
// ui->comboBoxFontSize->addItem("28");
// ui->comboBoxFontSize->addItem("32");
// ui->comboBoxFontSize->addItem("36");
// }
}
void DialogFontSize::GetFileInfo(){
QString fileName;
QString fileDate="";
QString fontPath="/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/";
QDir FontsFile("/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/");
if(FontsFile.exists("/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/"))//2451
{
fontPath = "/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/";
}
if(FontsFile.exists("/usr/lib/fonts/"))//am335x
{
fontPath = "/usr/lib/fonts/";
}
fileName.sprintf("_%d_50.qpf2",font.pixelSize());
QFileInfo fileInfo;
if(font.family()=="SerifL")
fileName = fontPath +"serifl_7_50.qpf2";
else if(font.family()=="SerifR")
fileName = fontPath +"serifr_7_50.qpf2";
else if(font.family()=="SerifL9")
fileName = fontPath +"serifl_9_50.qpf2";
else if(font.family()=="SerifR9")
fileName = fontPath +"serifr_9_50.qpf2";
else fileName = fontPath +font.family()+fileName;
fileInfo.setFile(fileName);
QDateTime dt= fileInfo.created();
//fileInfo.lastModified();
QString s = dt.toString("yyyy-MM-dd hh:mm:ss");
//qDebug()<<"GetFileInfo"<<font.family()<<fileName;
//qDebug()<< s<<fileInfo.baseName();
QFile fp;
fp.setFileName(fileName);
fp.open(QFile::ReadOnly);
QByteArray fdat =fp.read(fp.size());
unsigned int chsum = qChecksum(fdat,fp.size());
//ui->labFontInfo->setText(fileInfo.fileName()+" "+s+"");
ui->labFontInfo->setText( QString("%1").arg(chsum));
}
/*
void DialogFontSize::getValue(int *size){
int pixelSize = 12;
bool ok;
font.setFamily("wenquanyi");
#ifdef VNLGXX
int n = ui->comboBoxFontSize->currentText().toInt(&ok,10);
if(ok) pixelSize = n;
#else
if(ui->radioButton5Point->isChecked()){
pixelSize = 5;
font.setFamily("biyang");
}
else if(ui->radioButton7Point->isChecked()){
pixelSize = 7;
font.setFamily("biyang");
}
else if(ui->radioButton9Point->isChecked()){
pixelSize = 9;
font.setFamily("biyang");
}
else if(ui->radioButton12Point->isChecked()){
pixelSize = 12;
}
else if(ui->radioButton16Point->isChecked()){
pixelSize = 16;
}
else if(ui->radioButton24Point->isChecked()){
pixelSize = 24;
}
else if(ui->radioButton7HoriL->isChecked()){
pixelSize = 5;
font.setFamily("SerifL");
}
else if(ui->radioButton7HoriR->isChecked()){
pixelSize = 5;
font.setFamily("SerifR");
}
else if(ui->radioButton9HoriL->isChecked()){
pixelSize = 7;
font.setFamily("SerifL9");
}
else if(ui->radioButton9HoriR->isChecked()){
pixelSize = 7;
font.setFamily("SerifR9");
}
else if(ui->radioButton7Bangla->isChecked()){
pixelSize = 7;
font.setFamily("bangla");
}
else if(ui->radioButton7PointNum->isChecked()){
pixelSize = 7;
font.setFamily("biyangF");
}
else if(ui->radioButton21PointNum->isChecked()){
pixelSize = 24;
font.setFamily("biyangF");
}
else if(ui->radioButton12NewRoman->isChecked()){
pixelSize = 12;
font.setFamily("Roman");
}
else if(ui->radioButton32Point->isChecked()){
pixelSize = 32;
}
// radioButton7Hori
// else if(ui->radioButton28Point->isChecked()){
// pixelSize = 28;
// }
// else if(ui->radioButton32Point->isChecked()){
// pixelSize = 32;
// }
#endif
font.setPixelSize(pixelSize);
ui->lineEdit->setFont(font); // 设置预览字体
*size = pixelSize;
}
*/
void DialogFontSize::getValue(int *size){
int pixelSize = 12;
bool ok;
font.setFamily("WenQuanYi12");
if(ui->radioButton5Point->isChecked()){
pixelSize = 5;
if(flagOfLeft){
font.setFamily("WenQuanYiL5");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR5");
}else{
font.setFamily("WenQuanYi5");
}
}
else if(ui->radioButton7Point->isChecked()){
pixelSize = 7;
if(flagOfLeft){
font.setFamily("WenQuanYiL7");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR7");
}else{
font.setFamily("WenQuanYi7");
}
}
else if(ui->radioButton9Point->isChecked()){
pixelSize = 9;
if(flagOfLeft){
font.setFamily("DinkieL9");
}
else if(flagOfRight){
font.setFamily("DinkieR9");
}else{
font.setFamily("Dinkie9");
}
}
else if(ui->radioButton12Point->isChecked()){
pixelSize = 12;
if(flagOfLeft){
font.setFamily("WenQuanYiL12");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR12");
}
else{
font.setFamily("WenQuanYi12");
}
}
else if(ui->radioButton16Point->isChecked()){
pixelSize = 16;
if(flagOfLeft){
font.setFamily("WenQuanYiL16");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR16");
}
else{
font.setFamily("WenQuanYi16");
}
}
else if(ui->radioButton24Point->isChecked()){
pixelSize = 24;
if(flagOfLeft){
font.setFamily("WenQuanYiL24");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR24");
}
else{
font.setFamily("WenQuanYi24");
}
}
else if(ui->radioButton7Bangla->isChecked()){
pixelSize = 7;
font.setFamily("bangla");
}
else if(ui->radioButton7PointNum->isChecked()){
pixelSize = 7;
font.setFamily("biyangF");
}
else if(ui->radioButton21PointNum->isChecked()){
pixelSize = 24;
font.setFamily("biyangF");
}
else if(ui->radioButton12NewRoman->isChecked()){
pixelSize = 12;
font.setFamily("Roman");
}
else if(ui->radioButton32Point->isChecked()){
pixelSize = 32;
font.setFamily("WenQuanYi32");
if(flagOfLeft){
font.setFamily("WenQuanYiL32");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR32");
}
else{
font.setFamily("WenQuanYi32");
}
}
font.setPixelSize(pixelSize);
ui->lineEdit->setFont(font); // 设置预览字体
*size = pixelSize;
}
void DialogFontSize::setValue(int value){
#ifdef VNLGXX
//QString s;
//s.sprintf("%d",value);
//ui->comboBoxFontSize->setEditText(s);
//if(value<12) ui->fontComboBox->setCurrentIndex(0);
#else
if(value == 5 && font.family()=="biyang"){
ui->radioButton5Point->setChecked(true);
}
// else if(value == 5 && font.family()=="SerifL"){
// ui->radioButton7HoriL->setChecked(true);
// }
// else if(value == 5 && font.family()=="SerifR" ){
// ui->radioButton7HoriR->setChecked(true);
// }
// else if(value == 7 && font.family()=="SerifL9"){
// ui->radioButton9HoriL->setChecked(true);
// }
// else if(value == 7 && font.family()=="SerifR9"){
// ui->radioButton9HoriR->setChecked(true);
// }
else if(value == 7 && font.family()=="bangla"){
ui->radioButton7Bangla->setChecked(true);
}
else if(value == 7 && font.family()=="biyangF"){
ui->radioButton7PointNum->setChecked(true);
}
else if(value == 21 && font.family()=="biyangF"){
ui->radioButton21PointNum->setChecked(true);
}
else if(value == 12 && font.family()=="Roman"){
ui->radioButton12NewRoman->setChecked(true);
}
else if(value == 7){
ui->radioButton7Point->setChecked(true);
}
else if(value == 9){
ui->radioButton9Point->setChecked(true);
}
else if(value == 12){
ui->radioButton12Point->setChecked(true);
}
else if(value == 16){
ui->radioButton16Point->setChecked(true);
}
else if(value == 24){
ui->radioButton24Point->setChecked(true);
}
else if(value == 32){
ui->radioButton32Point->setChecked(true);
}
/*
else if(value == 28){
ui->radioButton28Point->setChecked(true);
}
else if(value == 32){
ui->radioButton32Point->setChecked(true);
}
*/
#endif
}
QString DialogFontSize::getFontFamily(){
return ui->lineEdit->font().family();
}
QFont DialogFontSize::getFont(){
return ui->lineEdit->font();
}
void DialogFontSize::on_pushButton_pressed()
{
GetFileInfo();// 显示字库校验码
}
void DialogFontSize::on_checkBox_Left_clicked()
{
auto b = ui->checkBox_Right->blockSignals(true);
ui->checkBox_Right->setChecked(false);
ui->checkBox_Right->blockSignals(b);
flagOfRight = false;
flagOfLeft = !flagOfLeft;
int pixsize;
getValue(&pixsize);
}
void DialogFontSize::on_checkBox_Right_clicked()
{
auto b = ui->checkBox_Left->blockSignals(true);
ui->checkBox_Left->setChecked(false);
ui->checkBox_Left->blockSignals(b);
flagOfLeft = false;
flagOfRight = !flagOfRight;
int pixsize;
getValue(&pixsize);
}
#include "DialogFontSize.h"
#include "ui_dialogfontsize.h"
#include <QDebug>
#include <QFileInfo>
#include <QDateTime>
#include <QFontDatabase>
#include <QString>
#include <QDir>
#include <iostream>
#include "myinclude.h"
#include "Public.h"
DialogFontSize::DialogFontSize(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogFontSize)
{
ui->setupUi(this);
this->setFixedSize(this->geometry().width(),this->geometry().height());
this->setWindowTitle(tr("选择字体大小"));
font.setFamily("WenQuanYi12");
QString langurageType = Public::ReadLanguageName();
if(langurageType != "English" && langurageType != "Chinese")
font.setFamily("Yanglabeldot12");
font.setPixelSize(12);
ui->lineEdit->setFont(font);
connect(ui->radioButton7Bangla,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton7PointNum,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton5Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriL(bool)));
connect(ui->radioButton7Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton9Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriL(bool)));
connect(ui->radioButton12Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton16Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriL(bool)));
connect(ui->radioButton24Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton21PointNum,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
connect(ui->radioButton32Point,SIGNAL(clicked(bool)),this,SLOT(Button7HoriR(bool)));
#ifdef VNLGXX
ui->checkBoxBold->hide();
ui->radioButton5Point->hide();
ui->radioButton7Point->hide();
ui->radioButton9Point->hide();
ui->radioButton12Point->hide();
ui->radioButton16Point->hide();
ui->radioButton24Point->hide();
#else
// ui->checkBoxBold->hide();
// ui->labelFont->hide();
// ui->fontComboBox->hide();
// ui->comboBoxFontSize->hide();
#endif
GetFileInfo();
flagOfLeft = false;
flagOfRight = false;
#ifdef EnableBangla
ui->radioButton7Bangla->setEnabled(1);
#else
ui->radioButton7Bangla->setEnabled(0);
#endif
//ui->checkBox_Left->setStyleSheet("QCheckBox { font-size: 24pt; }");
}
DialogFontSize::~DialogFontSize()
{
delete ui;
}
void DialogFontSize::Button7HoriL(bool ok){
int pixsize;
getValue(&pixsize);
//qDebug()<<ui->lineEdit->font().family()<<ui->lineEdit->font().pixelSize();
qDebug() << "click L";
}
void DialogFontSize::Button7HoriR(bool ok){
int pixsize;
getValue(&pixsize);
//qDebug()<<ui->lineEdit->font().family()<<ui->lineEdit->font().pixelSize();
qDebug() << "click R";
}
void DialogFontSize::ChangeFont(QString fontFamily){
font.setFamily(fontFamily);
//font.setPixelSize(pixelSize);
ui->lineEdit->setFont(font); // 设置预览字体
// if(fontFamily=="wenquanyi" ){
// ui->comboBoxFontSize->clear();
// ui->comboBoxFontSize->addItem("12");
// ui->comboBoxFontSize->addItem("16");
// //ui->comboBoxFontSize->addItem("12");
// }
// else if(fontFamily=="biyang"){
// ui->comboBoxFontSize->clear();
// ui->comboBoxFontSize->addItem("5");
// ui->comboBoxFontSize->addItem("7");
// ui->comboBoxFontSize->addItem("9");
// //ui->comboBoxFontSize->addItem("10");
// }
// else {
// ui->comboBoxFontSize->clear();
// ui->comboBoxFontSize->addItem("14");
// ui->comboBoxFontSize->addItem("16");
// ui->comboBoxFontSize->addItem("18");
// ui->comboBoxFontSize->addItem("20");
// ui->comboBoxFontSize->addItem("24");
// ui->comboBoxFontSize->addItem("28");
// ui->comboBoxFontSize->addItem("32");
// ui->comboBoxFontSize->addItem("36");
// }
}
void DialogFontSize::GetFileInfo(){
QString fileName;
QString fileDate="";
QString fontPath="/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/";
QDir FontsFile("/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/");
if(FontsFile.exists("/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/"))//2451
{
fontPath = "/usr/local/Trolltech/QtEmbedded-4.6.3-arm/lib/fonts/";
}
if(FontsFile.exists("/usr/lib/fonts/"))//am335x
{
fontPath = "/usr/lib/fonts/";
}
fileName.sprintf("_%d_50.qpf2",font.pixelSize());
QFileInfo fileInfo;
if(font.family()=="SerifL")
fileName = fontPath +"serifl_7_50.qpf2";
else if(font.family()=="SerifR")
fileName = fontPath +"serifr_7_50.qpf2";
else if(font.family()=="SerifL9")
fileName = fontPath +"serifl_9_50.qpf2";
else if(font.family()=="SerifR9")
fileName = fontPath +"serifr_9_50.qpf2";
else fileName = fontPath +font.family()+fileName;
fileInfo.setFile(fileName);
QDateTime dt= fileInfo.created();
//fileInfo.lastModified();
QString s = dt.toString("yyyy-MM-dd hh:mm:ss");
//qDebug()<<"GetFileInfo"<<font.family()<<fileName;
//qDebug()<< s<<fileInfo.baseName();
QFile fp;
fp.setFileName(fileName);
fp.open(QFile::ReadOnly);
QByteArray fdat =fp.read(fp.size());
unsigned int chsum = qChecksum(fdat,fp.size());
//ui->labFontInfo->setText(fileInfo.fileName()+" "+s+"");
ui->labFontInfo->setText( QString("%1").arg(chsum));
}
/*
void DialogFontSize::getValue(int *size){
int pixelSize = 12;
bool ok;
font.setFamily("wenquanyi");
#ifdef VNLGXX
int n = ui->comboBoxFontSize->currentText().toInt(&ok,10);
if(ok) pixelSize = n;
#else
if(ui->radioButton5Point->isChecked()){
pixelSize = 5;
font.setFamily("biyang");
}
else if(ui->radioButton7Point->isChecked()){
pixelSize = 7;
font.setFamily("biyang");
}
else if(ui->radioButton9Point->isChecked()){
pixelSize = 9;
font.setFamily("biyang");
}
else if(ui->radioButton12Point->isChecked()){
pixelSize = 12;
}
else if(ui->radioButton16Point->isChecked()){
pixelSize = 16;
}
else if(ui->radioButton24Point->isChecked()){
pixelSize = 24;
}
else if(ui->radioButton7HoriL->isChecked()){
pixelSize = 5;
font.setFamily("SerifL");
}
else if(ui->radioButton7HoriR->isChecked()){
pixelSize = 5;
font.setFamily("SerifR");
}
else if(ui->radioButton9HoriL->isChecked()){
pixelSize = 7;
font.setFamily("SerifL9");
}
else if(ui->radioButton9HoriR->isChecked()){
pixelSize = 7;
font.setFamily("SerifR9");
}
else if(ui->radioButton7Bangla->isChecked()){
pixelSize = 7;
font.setFamily("bangla");
}
else if(ui->radioButton7PointNum->isChecked()){
pixelSize = 7;
font.setFamily("biyangF");
}
else if(ui->radioButton21PointNum->isChecked()){
pixelSize = 24;
font.setFamily("biyangF");
}
else if(ui->radioButton12NewRoman->isChecked()){
pixelSize = 12;
font.setFamily("Roman");
}
else if(ui->radioButton32Point->isChecked()){
pixelSize = 32;
}
// radioButton7Hori
// else if(ui->radioButton28Point->isChecked()){
// pixelSize = 28;
// }
// else if(ui->radioButton32Point->isChecked()){
// pixelSize = 32;
// }
#endif
font.setPixelSize(pixelSize);
ui->lineEdit->setFont(font); // 设置预览字体
*size = pixelSize;
}
*/
void DialogFontSize::getValue(int *size){
int pixelSize = 12;
bool ok;
font.setFamily("WenQuanYi12");
if(ui->radioButton5Point->isChecked()){
pixelSize = 5;
if(flagOfLeft){
font.setFamily("WenQuanYiL5");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR5");
}else{
font.setFamily("WenQuanYi5");
}
}
else if(ui->radioButton7Point->isChecked()){
pixelSize = 7;
if(flagOfLeft){
font.setFamily("WenQuanYiL7");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR7");
}else{
font.setFamily("WenQuanYi7");
}
}
else if(ui->radioButton9Point->isChecked()){
pixelSize = 9;
if(flagOfLeft){
font.setFamily("DinkieL9");
}
else if(flagOfRight){
font.setFamily("DinkieR9");
}else{
font.setFamily("Dinkie9");
}
}
else if(ui->radioButton12Point->isChecked()){
pixelSize = 12;
if(flagOfLeft){
font.setFamily("WenQuanYiL12");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR12");
}
else{
font.setFamily("WenQuanYi12");
}
}
else if(ui->radioButton16Point->isChecked()){
pixelSize = 16;
if(flagOfLeft){
font.setFamily("WenQuanYiL16");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR16");
}
else{
font.setFamily("WenQuanYi16");
}
}
else if(ui->radioButton24Point->isChecked()){
pixelSize = 24;
if(flagOfLeft){
font.setFamily("WenQuanYiL24");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR24");
}
else{
font.setFamily("WenQuanYi24");
}
}
else if(ui->radioButton7Bangla->isChecked()){
pixelSize = 7;
font.setFamily("bangla");
}
else if(ui->radioButton7PointNum->isChecked()){
pixelSize = 7;
font.setFamily("biyangF");
}
else if(ui->radioButton21PointNum->isChecked()){
pixelSize = 24;
font.setFamily("biyangF");
}
else if(ui->radioButton12NewRoman->isChecked()){
pixelSize = 12;
font.setFamily("Roman");
}
else if(ui->radioButton32Point->isChecked()){
pixelSize = 32;
font.setFamily("WenQuanYi32");
if(flagOfLeft){
font.setFamily("WenQuanYiL32");
}
else if(flagOfRight){
font.setFamily("WenQuanYiR32");
}
else{
font.setFamily("WenQuanYi32");
}
}
font.setPixelSize(pixelSize);
ui->lineEdit->setFont(font); // 设置预览字体
*size = pixelSize;
}
void DialogFontSize::setValue(int value){
#ifdef VNLGXX
//QString s;
//s.sprintf("%d",value);
//ui->comboBoxFontSize->setEditText(s);
//if(value<12) ui->fontComboBox->setCurrentIndex(0);
#else
if(value == 5 && font.family()=="biyang"){
ui->radioButton5Point->setChecked(true);
}
// else if(value == 5 && font.family()=="SerifL"){
// ui->radioButton7HoriL->setChecked(true);
// }
// else if(value == 5 && font.family()=="SerifR" ){
// ui->radioButton7HoriR->setChecked(true);
// }
// else if(value == 7 && font.family()=="SerifL9"){
// ui->radioButton9HoriL->setChecked(true);
// }
// else if(value == 7 && font.family()=="SerifR9"){
// ui->radioButton9HoriR->setChecked(true);
// }
else if(value == 7 && font.family()=="bangla"){
ui->radioButton7Bangla->setChecked(true);
}
else if(value == 7 && font.family()=="biyangF"){
ui->radioButton7PointNum->setChecked(true);
}
else if(value == 21 && font.family()=="biyangF"){
ui->radioButton21PointNum->setChecked(true);
}
else if(value == 12 && font.family()=="Roman"){
ui->radioButton12NewRoman->setChecked(true);
}
else if(value == 7){
ui->radioButton7Point->setChecked(true);
}
else if(value == 9){
ui->radioButton9Point->setChecked(true);
}
else if(value == 12){
ui->radioButton12Point->setChecked(true);
}
else if(value == 16){
ui->radioButton16Point->setChecked(true);
}
else if(value == 24){
ui->radioButton24Point->setChecked(true);
}
else if(value == 32){
ui->radioButton32Point->setChecked(true);
}
/*
else if(value == 28){
ui->radioButton28Point->setChecked(true);
}
else if(value == 32){
ui->radioButton32Point->setChecked(true);
}
*/
#endif
}
QString DialogFontSize::getFontFamily(){
return ui->lineEdit->font().family();
}
QFont DialogFontSize::getFont(){
return ui->lineEdit->font();
}
void DialogFontSize::on_pushButton_pressed()
{
GetFileInfo();// 显示字库校验码
}
void DialogFontSize::on_checkBox_Left_clicked()
{
auto b = ui->checkBox_Right->blockSignals(true);
ui->checkBox_Right->setChecked(false);
ui->checkBox_Right->blockSignals(b);
flagOfRight = false;
flagOfLeft = !flagOfLeft;
int pixsize;
getValue(&pixsize);
}
void DialogFontSize::on_checkBox_Right_clicked()
{
auto b = ui->checkBox_Left->blockSignals(true);
ui->checkBox_Left->setChecked(false);
ui->checkBox_Left->blockSignals(b);
flagOfLeft = false;
flagOfRight = !flagOfRight;
int pixsize;
getValue(&pixsize);
}
+43 -43
View File
@@ -1,43 +1,43 @@
#ifndef DIALOGFONTSIZE_H
#define DIALOGFONTSIZE_H
#include <QDialog>
namespace Ui {
class DialogFontSize;
}
class DialogFontSize : public QDialog
{
Q_OBJECT
public:
explicit DialogFontSize(QWidget *parent = 0);
~DialogFontSize();
void getValue(int *size);
void setValue(int value);
QFont font;
QString getFontFamily();
QFont getFont();
void GetFileInfo();//String fileName, String fileDate
public slots:
void ChangeFont(QString fontFamily);
void Button7HoriL(bool ok);
void Button7HoriR(bool ok);
private slots:
void on_pushButton_pressed();
void on_checkBox_Left_clicked();
void on_checkBox_Right_clicked();
private:
Ui::DialogFontSize *ui;
bool flagOfLeft;
bool flagOfRight;
};
#endif // DIALOGFONTSIZE_H
#ifndef DIALOGFONTSIZE_H
#define DIALOGFONTSIZE_H
#include <QDialog>
namespace Ui {
class DialogFontSize;
}
class DialogFontSize : public QDialog
{
Q_OBJECT
public:
explicit DialogFontSize(QWidget *parent = 0);
~DialogFontSize();
void getValue(int *size);
void setValue(int value);
QFont font;
QString getFontFamily();
QFont getFont();
void GetFileInfo();//String fileName, String fileDate
public slots:
void ChangeFont(QString fontFamily);
void Button7HoriL(bool ok);
void Button7HoriR(bool ok);
private slots:
void on_pushButton_pressed();
void on_checkBox_Left_clicked();
void on_checkBox_Right_clicked();
private:
Ui::DialogFontSize *ui;
bool flagOfLeft;
bool flagOfRight;
};
#endif // DIALOGFONTSIZE_H
+14 -14
View File
@@ -1,14 +1,14 @@
#include "DialogInputTxt.h"
#include "ui_DialogInputTxt.h"
DialogInputTxt::DialogInputTxt(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogInputTxt)
{
ui->setupUi(this);
}
DialogInputTxt::~DialogInputTxt()
{
delete ui;
}
#include "DialogInputTxt.h"
#include "ui_DialogInputTxt.h"
DialogInputTxt::DialogInputTxt(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogInputTxt)
{
ui->setupUi(this);
}
DialogInputTxt::~DialogInputTxt()
{
delete ui;
}
+22 -22
View File
@@ -1,22 +1,22 @@
#ifndef DIALOGINPUTTXT_H
#define DIALOGINPUTTXT_H
#include <QDialog>
namespace Ui {
class DialogInputTxt;
}
class DialogInputTxt : public QDialog
{
Q_OBJECT
public:
explicit DialogInputTxt(QWidget *parent = 0);
~DialogInputTxt();
private:
Ui::DialogInputTxt *ui;
};
#endif // DIALOGINPUTTXT_H
#ifndef DIALOGINPUTTXT_H
#define DIALOGINPUTTXT_H
#include <QDialog>
namespace Ui {
class DialogInputTxt;
}
class DialogInputTxt : public QDialog
{
Q_OBJECT
public:
explicit DialogInputTxt(QWidget *parent = 0);
~DialogInputTxt();
private:
Ui::DialogInputTxt *ui;
};
#endif // DIALOGINPUTTXT_H
+78 -78
View File
@@ -1,78 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DialogInputTxt</class>
<widget class="QDialog" name="DialogInputTxt">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>117</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>20</x>
<y>80</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
<widget class="QLineEdit" name="lineEdit">
<property name="geometry">
<rect>
<x>20</x>
<y>30</y>
<width>361</width>
<height>27</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>DialogInputTxt</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>DialogInputTxt</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DialogInputTxt</class>
<widget class="QDialog" name="DialogInputTxt">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>117</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>20</x>
<y>80</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
<widget class="QLineEdit" name="lineEdit">
<property name="geometry">
<rect>
<x>20</x>
<y>30</y>
<width>361</width>
<height>27</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>DialogInputTxt</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>DialogInputTxt</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>
+227 -227
View File
@@ -1,227 +1,227 @@
#include "DialogInsertVari.h"
#include "ui_dialoginsertvari.h"
#include "myinclude.h"
//#include "SysPara.h"
DialogInsertVari::DialogInsertVari(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogInsertVari)
{
ui->setupUi(this);
this->setWindowTitle(tr("变量插入"));
//this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowContextHelpButtonHint | Qt::WindowMaximizeButtonHint);
//this->setWindowFlags(windowFlags()&~Qt::WindowCloseButtonHint);
//setWindowFlags(Qt::WindowTitleHint | Qt::WindowContextHelpButtonHint);
//setWindowFlags(Qt::CustomizeWindowHint);
this->setFixedSize(this->geometry().width(),this->geometry().height());
bool Flag=0;
digitWidth = 4;
ui->radioButtonDigital9->setDisabled(!Flag);
ui->radioButtonDigitalA->setDisabled(!Flag);
ui->radioButtonDigitalB->setDisabled(!Flag);
ui->radioButtonDigitalC->setDisabled(!Flag);
ui->radioButtonDigitalD->setDisabled(!Flag);
ui->radioButtonDigitalE->setDisabled(!Flag);
ui->radioButtonDigitalF->setDisabled(!Flag);
//ui->radioButtonDigitalH->setDisabled(!Flag);
connect(ui->radioButtonVarRandom,SIGNAL(toggled(bool)),this,SLOT(onRanDomPressed(bool)));
connect(ui->radioButtonHour,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonMinute,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonWeek,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonMonth,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonSecond,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonDay,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonXDay,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonYear,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
connect(ui->radioButtonVar1,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
connect(ui->radioButtonVar2,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
connect(ui->radioButtonCNT3,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
#ifdef _2DCODE_
connect(ui->radioButtonBarCode,SIGNAL(toggled(bool)),this,SLOT( onDigitOtherBit(bool)));
connect(ui->radioButtonQRCode,SIGNAL(toggled(bool)),this,SLOT( onDigitOtherBit(bool)));
connect(ui->radioButtonDataMatrix,SIGNAL(toggled(bool)),this,SLOT( onDigitOtherBit(bool)));
#else
delete ui->radioButtonBarCode;
delete ui->radioButtonQRCode;
delete ui->radioButtonDataMatrix;
#endif
ui->radioButtonXDay->hide();
}
DialogInsertVari::~DialogInsertVari()
{
delete ui;
}
void DialogInsertVari::setValue(QString txt){
//ui->label_2->setText(txt);
}
void DialogInsertVari::onRanDomPressed(bool Flag){
if(Flag) ui->radioButtonDigitalD->setChecked(Flag);
else ui->radioButtonDigital4->setChecked(1);
ui->radioButtonDigital9->setDisabled(!Flag);
ui->radioButtonDigitalA->setDisabled(!Flag);
ui->radioButtonDigitalB->setDisabled(!Flag);
ui->radioButtonDigitalC->setDisabled(!Flag);
ui->radioButtonDigitalD->setDisabled(!Flag);
ui->radioButtonDigitalE->setDisabled(!Flag);
ui->radioButtonDigitalF->setDisabled(!Flag);
//ui->radioButtonDigitalH->setDisabled(!Flag);
}
void DialogInsertVari::onDigitOtherBit(bool Flag){
if(digitWidth>8)
ui->radioButtonDigital4->setChecked(1);
ui->radioButtonDigital9->setDisabled(Flag);
ui->radioButtonDigitalA->setDisabled(Flag);
ui->radioButtonDigitalB->setDisabled(Flag);
ui->radioButtonDigitalC->setDisabled(Flag);
ui->radioButtonDigitalD->setDisabled(Flag);
ui->radioButtonDigitalE->setDisabled(Flag);
ui->radioButtonDigitalF->setDisabled(Flag);
//ui->radioButtonDigitalH->setDisabled(Flag);
}
void DialogInsertVari::onDigitTwoBit(bool Flag){
if(ui->radioButtonXDay->isChecked())ui->radioButtonDigital3->setChecked(Flag);
else if(Flag)ui->radioButtonDigital2->setChecked(Flag);
else ui->radioButtonDigital4->setChecked(1);
ui->radioButtonDigital9->setDisabled(Flag);
ui->radioButtonDigitalA->setDisabled(Flag);
ui->radioButtonDigitalB->setDisabled(Flag);
ui->radioButtonDigitalC->setDisabled(Flag);
ui->radioButtonDigitalD->setDisabled(Flag);
ui->radioButtonDigitalE->setDisabled(Flag);
ui->radioButtonDigitalF->setDisabled(Flag);
//ui->radioButtonDigitalH->setDisabled(Flag);
}
void DialogInsertVari::onDigitFourBit(bool Flag){
if(Flag)ui->radioButtonDigital4->setChecked(Flag);
else ui->radioButtonDigital2->setChecked(1);
ui->radioButtonDigital9->setDisabled(Flag);
ui->radioButtonDigitalA->setDisabled(Flag);
ui->radioButtonDigitalB->setDisabled(Flag);
ui->radioButtonDigitalC->setDisabled(Flag);
ui->radioButtonDigitalD->setDisabled(Flag);
ui->radioButtonDigitalE->setDisabled(Flag);
ui->radioButtonDigitalF->setDisabled(Flag);
//ui->radioButtonDigitalH->setDisabled(Flag);
}
void DialogInsertVari::getValue(int *varType,int *digitalWidth,unsigned char *splitMode){
int type = 0,width = 0;
if(ui->radioButtonYear->isChecked())
type = 0;
else if(ui->radioButtonMonth->isChecked())
type = 1;
else if(ui->radioButtonDay->isChecked())
type = 2;
else if(ui->radioButtonWeek->isChecked())
type = 3;
else if(ui->radioButtonHour->isChecked())
type = 4;
else if(ui->radioButtonMinute->isChecked())
type = 5;
else if(ui->radioButtonSecond->isChecked())
type = 6;
else if(ui->radioButtonVar1->isChecked())
type = 7;
else if(ui->radioButtonVar2->isChecked())
type = 8;
#ifdef _2DCODE_
else if(ui->radioButtonDataMatrix->isChecked())
type = 9;
else if(ui->radioButtonQRCode->isChecked())
type = 10;
else if(ui->radioButtonBarCode->isChecked())
type = 11;
#endif
else if(ui->radioButtonVarRandom->isChecked())
type = 12;
else if(ui->radioButtonCNT3->isChecked())
type = 13;
else if(ui->radioButtonXDay->isChecked())
type = 14;
else if(ui->radioButtonCNT4->isChecked())
type = 15;
else if(ui->radioButtonExpiry->isChecked())
{
type = 80;
}
else if(ui->radioButtonCurDate->isChecked())
{
type = 81;
}
// else if(ui->radioButtonClass->isChecked())
// {
// type = 82;
// }
if(ui->radioButtonDigital1->isChecked())
width = 1;
else if(ui->radioButtonDigital2->isChecked())
width = 2;
else if(ui->radioButtonDigital3->isChecked())
width = 3;
else if(ui->radioButtonDigital4->isChecked())
width = 4;
else if(ui->radioButtonDigital5->isChecked())
width = 5;
else if(ui->radioButtonDigital6->isChecked())
width = 6;
else if(ui->radioButtonDigital7->isChecked())
width = 7;
else if(ui->radioButtonDigital8->isChecked())
width = 8;
else if(ui->radioButtonDigital9->isChecked())
width = 9;
else if(ui->radioButtonDigitalA->isChecked())
width = 10;
else if(ui->radioButtonDigitalB->isChecked())
width = 11;
else if(ui->radioButtonDigitalC->isChecked())
width = 12;
else if(ui->radioButtonDigitalD->isChecked())
width = 13;
else if(ui->radioButtonDigitalE->isChecked())
width = 14;
else if(ui->radioButtonDigitalF->isChecked())
width = 15;
//else if(ui->radioButtonDigitalH->isChecked())
// width = 16;
if(varType && digitalWidth){
*varType = type;
*digitalWidth = width;
digitWidth = width;
}
if (type == 82) { // class
*digitalWidth = 1;
digitWidth = 1;
}
}
void DialogInsertVari::on_buttonBox_accepted()
{
}
void DialogInsertVari::EnableHiddenValue(bool select)
{
if(!select)
ui->radioButtonVar1->setChecked(true);
ui->radioButtonCNT4->setEnabled(select);
}
#include "DialogInsertVari.h"
#include "ui_dialoginsertvari.h"
#include "myinclude.h"
//#include "SysPara.h"
DialogInsertVari::DialogInsertVari(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogInsertVari)
{
ui->setupUi(this);
this->setWindowTitle(tr("变量插入"));
//this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowContextHelpButtonHint | Qt::WindowMaximizeButtonHint);
//this->setWindowFlags(windowFlags()&~Qt::WindowCloseButtonHint);
//setWindowFlags(Qt::WindowTitleHint | Qt::WindowContextHelpButtonHint);
//setWindowFlags(Qt::CustomizeWindowHint);
this->setFixedSize(this->geometry().width(),this->geometry().height());
bool Flag=0;
digitWidth = 4;
ui->radioButtonDigital9->setDisabled(!Flag);
ui->radioButtonDigitalA->setDisabled(!Flag);
ui->radioButtonDigitalB->setDisabled(!Flag);
ui->radioButtonDigitalC->setDisabled(!Flag);
ui->radioButtonDigitalD->setDisabled(!Flag);
ui->radioButtonDigitalE->setDisabled(!Flag);
ui->radioButtonDigitalF->setDisabled(!Flag);
//ui->radioButtonDigitalH->setDisabled(!Flag);
connect(ui->radioButtonVarRandom,SIGNAL(toggled(bool)),this,SLOT(onRanDomPressed(bool)));
connect(ui->radioButtonHour,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonMinute,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonWeek,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonMonth,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonSecond,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonDay,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonXDay,SIGNAL(toggled(bool)),this,SLOT( onDigitTwoBit(bool)));
connect(ui->radioButtonYear,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
connect(ui->radioButtonVar1,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
connect(ui->radioButtonVar2,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
connect(ui->radioButtonCNT3,SIGNAL(toggled(bool)),this,SLOT( onDigitFourBit(bool)));
#ifdef _2DCODE_
connect(ui->radioButtonBarCode,SIGNAL(toggled(bool)),this,SLOT( onDigitOtherBit(bool)));
connect(ui->radioButtonQRCode,SIGNAL(toggled(bool)),this,SLOT( onDigitOtherBit(bool)));
connect(ui->radioButtonDataMatrix,SIGNAL(toggled(bool)),this,SLOT( onDigitOtherBit(bool)));
#else
delete ui->radioButtonBarCode;
delete ui->radioButtonQRCode;
delete ui->radioButtonDataMatrix;
#endif
ui->radioButtonXDay->hide();
}
DialogInsertVari::~DialogInsertVari()
{
delete ui;
}
void DialogInsertVari::setValue(QString txt){
//ui->label_2->setText(txt);
}
void DialogInsertVari::onRanDomPressed(bool Flag){
if(Flag) ui->radioButtonDigitalD->setChecked(Flag);
else ui->radioButtonDigital4->setChecked(1);
ui->radioButtonDigital9->setDisabled(!Flag);
ui->radioButtonDigitalA->setDisabled(!Flag);
ui->radioButtonDigitalB->setDisabled(!Flag);
ui->radioButtonDigitalC->setDisabled(!Flag);
ui->radioButtonDigitalD->setDisabled(!Flag);
ui->radioButtonDigitalE->setDisabled(!Flag);
ui->radioButtonDigitalF->setDisabled(!Flag);
//ui->radioButtonDigitalH->setDisabled(!Flag);
}
void DialogInsertVari::onDigitOtherBit(bool Flag){
if(digitWidth>8)
ui->radioButtonDigital4->setChecked(1);
ui->radioButtonDigital9->setDisabled(Flag);
ui->radioButtonDigitalA->setDisabled(Flag);
ui->radioButtonDigitalB->setDisabled(Flag);
ui->radioButtonDigitalC->setDisabled(Flag);
ui->radioButtonDigitalD->setDisabled(Flag);
ui->radioButtonDigitalE->setDisabled(Flag);
ui->radioButtonDigitalF->setDisabled(Flag);
//ui->radioButtonDigitalH->setDisabled(Flag);
}
void DialogInsertVari::onDigitTwoBit(bool Flag){
if(ui->radioButtonXDay->isChecked())ui->radioButtonDigital3->setChecked(Flag);
else if(Flag)ui->radioButtonDigital2->setChecked(Flag);
else ui->radioButtonDigital4->setChecked(1);
ui->radioButtonDigital9->setDisabled(Flag);
ui->radioButtonDigitalA->setDisabled(Flag);
ui->radioButtonDigitalB->setDisabled(Flag);
ui->radioButtonDigitalC->setDisabled(Flag);
ui->radioButtonDigitalD->setDisabled(Flag);
ui->radioButtonDigitalE->setDisabled(Flag);
ui->radioButtonDigitalF->setDisabled(Flag);
//ui->radioButtonDigitalH->setDisabled(Flag);
}
void DialogInsertVari::onDigitFourBit(bool Flag){
if(Flag)ui->radioButtonDigital4->setChecked(Flag);
else ui->radioButtonDigital2->setChecked(1);
ui->radioButtonDigital9->setDisabled(Flag);
ui->radioButtonDigitalA->setDisabled(Flag);
ui->radioButtonDigitalB->setDisabled(Flag);
ui->radioButtonDigitalC->setDisabled(Flag);
ui->radioButtonDigitalD->setDisabled(Flag);
ui->radioButtonDigitalE->setDisabled(Flag);
ui->radioButtonDigitalF->setDisabled(Flag);
//ui->radioButtonDigitalH->setDisabled(Flag);
}
void DialogInsertVari::getValue(int *varType,int *digitalWidth,unsigned char *splitMode){
int type = 0,width = 0;
if(ui->radioButtonYear->isChecked())
type = 0;
else if(ui->radioButtonMonth->isChecked())
type = 1;
else if(ui->radioButtonDay->isChecked())
type = 2;
else if(ui->radioButtonWeek->isChecked())
type = 3;
else if(ui->radioButtonHour->isChecked())
type = 4;
else if(ui->radioButtonMinute->isChecked())
type = 5;
else if(ui->radioButtonSecond->isChecked())
type = 6;
else if(ui->radioButtonVar1->isChecked())
type = 7;
else if(ui->radioButtonVar2->isChecked())
type = 8;
#ifdef _2DCODE_
else if(ui->radioButtonDataMatrix->isChecked())
type = 9;
else if(ui->radioButtonQRCode->isChecked())
type = 10;
else if(ui->radioButtonBarCode->isChecked())
type = 11;
#endif
else if(ui->radioButtonVarRandom->isChecked())
type = 12;
else if(ui->radioButtonCNT3->isChecked())
type = 13;
else if(ui->radioButtonXDay->isChecked())
type = 14;
else if(ui->radioButtonCNT4->isChecked())
type = 15;
else if(ui->radioButtonExpiry->isChecked())
{
type = 80;
}
else if(ui->radioButtonCurDate->isChecked())
{
type = 81;
}
// else if(ui->radioButtonClass->isChecked())
// {
// type = 82;
// }
if(ui->radioButtonDigital1->isChecked())
width = 1;
else if(ui->radioButtonDigital2->isChecked())
width = 2;
else if(ui->radioButtonDigital3->isChecked())
width = 3;
else if(ui->radioButtonDigital4->isChecked())
width = 4;
else if(ui->radioButtonDigital5->isChecked())
width = 5;
else if(ui->radioButtonDigital6->isChecked())
width = 6;
else if(ui->radioButtonDigital7->isChecked())
width = 7;
else if(ui->radioButtonDigital8->isChecked())
width = 8;
else if(ui->radioButtonDigital9->isChecked())
width = 9;
else if(ui->radioButtonDigitalA->isChecked())
width = 10;
else if(ui->radioButtonDigitalB->isChecked())
width = 11;
else if(ui->radioButtonDigitalC->isChecked())
width = 12;
else if(ui->radioButtonDigitalD->isChecked())
width = 13;
else if(ui->radioButtonDigitalE->isChecked())
width = 14;
else if(ui->radioButtonDigitalF->isChecked())
width = 15;
//else if(ui->radioButtonDigitalH->isChecked())
// width = 16;
if(varType && digitalWidth){
*varType = type;
*digitalWidth = width;
digitWidth = width;
}
if (type == 82) { // class
*digitalWidth = 1;
digitWidth = 1;
}
}
void DialogInsertVari::on_buttonBox_accepted()
{
}
void DialogInsertVari::EnableHiddenValue(bool select)
{
if(!select)
ui->radioButtonVar1->setChecked(true);
ui->radioButtonCNT4->setEnabled(select);
}
+33 -33
View File
@@ -1,33 +1,33 @@
#ifndef DIALOGINSERTVARI_H
#define DIALOGINSERTVARI_H
#include <QDialog>
namespace Ui {
class DialogInsertVari;
}
class DialogInsertVari : public QDialog
{
Q_OBJECT
public:
explicit DialogInsertVari(QWidget *parent = 0);
~DialogInsertVari();
void getValue(int *varType,int *digitalWidth,unsigned char *splitMode);
void setValue(QString txt);
void EnableHiddenValue(bool select);
protected slots:
void onRanDomPressed(bool Flag);
void onDigitOtherBit(bool Flag);
void onDigitTwoBit(bool Flag);
void onDigitFourBit(bool Flag);
private slots:
void on_buttonBox_accepted();
private:
Ui::DialogInsertVari *ui;
int digitWidth;
};
#endif // DIALOGINSERTVARI_H
#ifndef DIALOGINSERTVARI_H
#define DIALOGINSERTVARI_H
#include <QDialog>
namespace Ui {
class DialogInsertVari;
}
class DialogInsertVari : public QDialog
{
Q_OBJECT
public:
explicit DialogInsertVari(QWidget *parent = 0);
~DialogInsertVari();
void getValue(int *varType,int *digitalWidth,unsigned char *splitMode);
void setValue(QString txt);
void EnableHiddenValue(bool select);
protected slots:
void onRanDomPressed(bool Flag);
void onDigitOtherBit(bool Flag);
void onDigitTwoBit(bool Flag);
void onDigitFourBit(bool Flag);
private slots:
void on_buttonBox_accepted();
private:
Ui::DialogInsertVari *ui;
int digitWidth;
};
#endif // DIALOGINSERTVARI_H
+75 -75
View File
@@ -1,75 +1,75 @@
#include "DialogLineSpace.h"
#include "ui_dialoglinespace.h"
DialogLineSpace::DialogLineSpace(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogLineSpace)
{
ui->setupUi(this);
this->setFixedSize(this->geometry().width(),this->geometry().height());
this->setWindowTitle(tr("选择行间距和字符间距"));
}
DialogLineSpace::~DialogLineSpace()
{
delete ui;
}
void DialogLineSpace::getValue(int *lineSpace,int *charSpace){
*lineSpace = 0;
if(ui->radioButton0Pixel->isChecked())
*lineSpace = 0;
else if(ui->radioButton1Pixel->isChecked())
*lineSpace = 1;
else if(ui->radioButton2Pixel->isChecked())
*lineSpace = 2;
else if(ui->radioButton3Pixel->isChecked())
*lineSpace = 3;
else if(ui->radioButton4Pixel->isChecked())
*lineSpace = 4;
else if(ui->radioButton5Pixel->isChecked())
*lineSpace = 5;
else if(ui->radioButton6Pixel->isChecked())
*lineSpace = 6;
else if(ui->radioButton7Pixel->isChecked())
*lineSpace = 7;
*charSpace = 0;
if(ui->radioButtonCharSpace0Pixel->isChecked())
*charSpace = 0;
else if(ui->radioButtonCharSpace1Pixel->isChecked())
*charSpace = 1;
else if(ui->radioButtonCharSpace2Pixel->isChecked())
*charSpace = 2;
else if(ui->radioButtonCharSpace3Pixel->isChecked())
*charSpace = 3;
else if(ui->radioButtonCharSpace4Pixel->isChecked())
*charSpace = 4;
else if(ui->radioButtonCharSpace5Pixel->isChecked())
*charSpace = 5;
}
void DialogLineSpace::setValue(int lineSpace,int charSpace){
if(lineSpace>0)
lineSpace = lineSpace-1; //新系统行间距需要加1
if(lineSpace > 7 || lineSpace < 0)
lineSpace = 0;
ui->radioButton0Pixel->setChecked(lineSpace == 0);
ui->radioButton1Pixel->setChecked(lineSpace == 1);
ui->radioButton2Pixel->setChecked(lineSpace == 2);
ui->radioButton3Pixel->setChecked(lineSpace == 3);
ui->radioButton4Pixel->setChecked(lineSpace == 4);
ui->radioButton5Pixel->setChecked(lineSpace == 5);
ui->radioButton6Pixel->setChecked(lineSpace == 6);
ui->radioButton7Pixel->setChecked(lineSpace == 7);
if(charSpace > 5 || charSpace < 0)
charSpace = 0;
ui->radioButtonCharSpace0Pixel->setChecked(charSpace == 0);
ui->radioButtonCharSpace1Pixel->setChecked(charSpace == 1);
ui->radioButtonCharSpace2Pixel->setChecked(charSpace == 2);
ui->radioButtonCharSpace3Pixel->setChecked(charSpace == 3);
ui->radioButtonCharSpace4Pixel->setChecked(charSpace == 4);
ui->radioButtonCharSpace5Pixel->setChecked(charSpace == 5);
}
#include "DialogLineSpace.h"
#include "ui_dialoglinespace.h"
DialogLineSpace::DialogLineSpace(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogLineSpace)
{
ui->setupUi(this);
this->setFixedSize(this->geometry().width(),this->geometry().height());
this->setWindowTitle(tr("选择行间距和字符间距"));
}
DialogLineSpace::~DialogLineSpace()
{
delete ui;
}
void DialogLineSpace::getValue(int *lineSpace,int *charSpace){
*lineSpace = 0;
if(ui->radioButton0Pixel->isChecked())
*lineSpace = 0;
else if(ui->radioButton1Pixel->isChecked())
*lineSpace = 1;
else if(ui->radioButton2Pixel->isChecked())
*lineSpace = 2;
else if(ui->radioButton3Pixel->isChecked())
*lineSpace = 3;
else if(ui->radioButton4Pixel->isChecked())
*lineSpace = 4;
else if(ui->radioButton5Pixel->isChecked())
*lineSpace = 5;
else if(ui->radioButton6Pixel->isChecked())
*lineSpace = 6;
else if(ui->radioButton7Pixel->isChecked())
*lineSpace = 7;
*charSpace = 0;
if(ui->radioButtonCharSpace0Pixel->isChecked())
*charSpace = 0;
else if(ui->radioButtonCharSpace1Pixel->isChecked())
*charSpace = 1;
else if(ui->radioButtonCharSpace2Pixel->isChecked())
*charSpace = 2;
else if(ui->radioButtonCharSpace3Pixel->isChecked())
*charSpace = 3;
else if(ui->radioButtonCharSpace4Pixel->isChecked())
*charSpace = 4;
else if(ui->radioButtonCharSpace5Pixel->isChecked())
*charSpace = 5;
}
void DialogLineSpace::setValue(int lineSpace,int charSpace){
if(lineSpace>0)
lineSpace = lineSpace-1; //新系统行间距需要加1
if(lineSpace > 7 || lineSpace < 0)
lineSpace = 0;
ui->radioButton0Pixel->setChecked(lineSpace == 0);
ui->radioButton1Pixel->setChecked(lineSpace == 1);
ui->radioButton2Pixel->setChecked(lineSpace == 2);
ui->radioButton3Pixel->setChecked(lineSpace == 3);
ui->radioButton4Pixel->setChecked(lineSpace == 4);
ui->radioButton5Pixel->setChecked(lineSpace == 5);
ui->radioButton6Pixel->setChecked(lineSpace == 6);
ui->radioButton7Pixel->setChecked(lineSpace == 7);
if(charSpace > 5 || charSpace < 0)
charSpace = 0;
ui->radioButtonCharSpace0Pixel->setChecked(charSpace == 0);
ui->radioButtonCharSpace1Pixel->setChecked(charSpace == 1);
ui->radioButtonCharSpace2Pixel->setChecked(charSpace == 2);
ui->radioButtonCharSpace3Pixel->setChecked(charSpace == 3);
ui->radioButtonCharSpace4Pixel->setChecked(charSpace == 4);
ui->radioButtonCharSpace5Pixel->setChecked(charSpace == 5);
}
+24 -24
View File
@@ -1,24 +1,24 @@
#ifndef DIALOGLINESPACE_H
#define DIALOGLINESPACE_H
#include <QDialog>
namespace Ui {
class DialogLineSpace;
}
class DialogLineSpace : public QDialog
{
Q_OBJECT
public:
explicit DialogLineSpace(QWidget *parent = 0);
~DialogLineSpace();
void getValue(int *lineSpace,int *charSpace);
void setValue(int lineSpace,int charSpace);
private:
Ui::DialogLineSpace *ui;
};
#endif // DIALOGLINESPACE_H
#ifndef DIALOGLINESPACE_H
#define DIALOGLINESPACE_H
#include <QDialog>
namespace Ui {
class DialogLineSpace;
}
class DialogLineSpace : public QDialog
{
Q_OBJECT
public:
explicit DialogLineSpace(QWidget *parent = 0);
~DialogLineSpace();
void getValue(int *lineSpace,int *charSpace);
void setValue(int lineSpace,int charSpace);
private:
Ui::DialogLineSpace *ui;
};
#endif // DIALOGLINESPACE_H
+239 -239
View File
@@ -1,239 +1,239 @@
#include "DialogSaveFile.h"
#include "ui_dialogsavefile.h"
#include <QDir>
#include <QStringListModel>
#include <SysPara.h>
#include <QAbstractItemView>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <Public.h>
#include<QStandardItemModel>
#include"HtmlDelegate.h"
#include <QTextCodec>
#include <QByteArray>
#include <QDebug>
DialogSaveFile::DialogSaveFile(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogSaveFile)
{
ui->setupUi(this);
this->setWindowTitle(tr("保存"));
ui->textEditView->setReadOnly(true);
ui->textEditView->setLineWrapMode(QTextEdit::NoWrap);
ui->textEditView->document()->setDocumentMargin(0);
this->setFixedSize(this->geometry().width(),this->geometry().height());
EditMode=4;
#ifdef EnableArabic
setFileNameFlag=false;
#endif
}
void DialogSaveFile::refreshListView(int mode){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
QDir dir(dirPath);
QStringList filters;
EditMode = mode;
if(mode == TXTFILE) filters << "*.html" << "*.txt" << "*.TXT" << "*.jpeg" << "*.gif" << "*.jpg" << "*.bmp"<< "*.BMP"; // txtmode
else if(mode == PICFILE) filters << "*.png";// <<"*.jpg" ; // picmode
else if(mode == SCENE) filters << "*.xml";// scene mode
else filters << "*.html" << "*.bmp" << "*.BMP" <<"*.jpg"<<"*.gif";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files);
#ifndef EnableArabic
QStringListModel *model = new QStringListModel(dir.entryList());
#else
QStringList entries=dir.entryList();
QStandardItemModel *model = new QStandardItemModel();
for(int i=0;i<entries.size();i++){
QStandardItem *item1 = new QStandardItem(entries.at(i));
int lastIndex=entries.at(i).lastIndexOf(".");
if(lastIndex != -1){
int secondLastIndex = entries.at(i).lastIndexOf(".",lastIndex-1);
if(secondLastIndex != -1){
QString subsuffix=entries.at(i).mid(secondLastIndex);
if(subsuffix.contains(".a.")){
QString subsuffix2=entries.at(i).mid(lastIndex);
QString subname=entries.at(i).mid(0,secondLastIndex);
QString stringhtml=QString("<span style=font-family:'biyangarabic';>%1</span><span style=font-family:'biyang';>%2</span>").arg(subname).arg(subsuffix2);
QStandardItem *item2 = new QStandardItem(stringhtml);
model->appendRow(item2);
}
}else{
model->appendRow(item1);
}
}
}
ui->listViewFile->setItemDelegate(new HtmlDelegate);
#endif
ui->listViewFile->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->listViewFile->setModel(model); //useList是个QListView
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(0 , 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
#ifdef EnableArabic
QFont font;
if(!setFileNameFlag){
font.setFamily("biyang");
ui->lineEdit->setFont(font);
}else {
font.setFamily("biyangarabic");
ui->lineEdit->setFont(font);
}
#endif
}
DialogSaveFile::~DialogSaveFile()
{
delete ui;
}
void DialogSaveFile::on_listViewFile_entered(const QModelIndex &index)
{
#ifdef EnableArabic
QFont font;
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
font.setFamily("biyangarabic");
ui->lineEdit->setFont(font);
ui->lineEdit->setText(QString(QFileInfo(fileName).baseName()));
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}else{
font.setFamily("biyang");
ui->lineEdit->setFont(font);
ui->lineEdit->setText( QFileInfo(fileName).baseName() );
}
#endif
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString filePath = dirPath + fileName;
#endif
if(filePath.endsWith(".gif") || filePath.endsWith(".jpeg") || filePath.endsWith(".jpg") ||
filePath.endsWith(".png") || filePath.endsWith(".bmp")|| filePath.endsWith(".BMP")|| filePath.endsWith(".nda")){
ui->textEditView->clear();
ui->textEditView->setHtml(QString("<img src='%1'/>").arg(filePath));
}
else {
QFile file(filePath);
if (!file.open(QFile::ReadOnly))
return ;
QByteArray data = file.readAll();
QTextCodec *codec = Qt::codecForHtml(data);
QString str = codec->toUnicode(data);
if (Qt::mightBeRichText(str)) {
if(!ui->radioButtonLocal->isChecked())
str.replace(DOC_ROOT_DIR,UDISK_DOC_ROOT_DIR); //必须替换相应的路径
ui->textEditView->setHtml(str);
} else {
str = QString::fromLocal8Bit(data);
ui->textEditView->setPlainText(str);
}
}
#ifndef EnableArabic
ui->lineEdit->setText( QFileInfo(ui->listViewFile->currentIndex().data().toString()).baseName() );
#endif
}
void DialogSaveFile::on_listViewFile_clicked(const QModelIndex &index)
{
on_listViewFile_entered(index);
}
void DialogSaveFile::on_pushButtonNext_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index((currIndex.row() + 1)%count, 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
ui->lineEdit->setText(QFileInfo(ui->listViewFile->currentIndex().data().toString()).baseName());
}
void DialogSaveFile::on_pushButtonLast_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(currIndex.row() == 0?(count - 1):(currIndex.row() - 1), 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
ui->lineEdit->setText(QFileInfo(ui->listViewFile->currentIndex().data().toString()).baseName());
}
void DialogSaveFile::on_pushButtonExit_pressed()
{
hide();
}
//void DialogSaveFile::on_lostfocuse_pressed()
//{
// hide();
//}
void DialogSaveFile::on_pushButtonSave_clicked()
{
QModelIndex index = ui->listViewFile->currentIndex();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
//QString filePath = dirPath + index.data().toString();
QString filePath = dirPath + ui->lineEdit->text();// index.data().toString();
#ifdef EnableArabic
if(setFileNameFlag){
filePath = dirPath + ui->lineEdit->text()+".a";
}
#endif
emit saveFile(filePath,false);
hide();
}
void DialogSaveFile::on_radioButtonLocal_released()
{
refreshListView(EditMode);
}
void DialogSaveFile::on_radioButtonUdisk_released()
{
QDir dir(UDISK_DOC_ROOT_DIR);
if(!dir.exists()){
QMessageBox::warning(0,tr("警告"),tr("U盘未插入或U盘根目录下的doc文件夹不存在!"));
}
refreshListView(EditMode);
}
void DialogSaveFile::setEnterFileName(QString strFile)
{
ui->lineEdit->setText(strFile);
//ui->lineEdit->setFocus();
}
void DialogSaveFile::setTitleTxt(QString str)
{
setWindowTitle(str);
}
#ifdef EnableArabic
void DialogSaveFile::setFileNameEnglishOrArabic(bool flag){
QFont font;
setFileNameFlag=flag;
//qDebug()<<"setFileNameFlag :"<<flag;
if(flag){
font.setFamily("biyangarabic");
}else {
font.setFamily("biyang");
}
ui->lineEdit->setFont(font);
}
#endif
#include "DialogSaveFile.h"
#include "ui_dialogsavefile.h"
#include <QDir>
#include <QStringListModel>
#include <SysPara.h>
#include <QAbstractItemView>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <Public.h>
#include<QStandardItemModel>
#include"HtmlDelegate.h"
#include <QTextCodec>
#include <QByteArray>
#include <QDebug>
DialogSaveFile::DialogSaveFile(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogSaveFile)
{
ui->setupUi(this);
this->setWindowTitle(tr("保存"));
ui->textEditView->setReadOnly(true);
ui->textEditView->setLineWrapMode(QTextEdit::NoWrap);
ui->textEditView->document()->setDocumentMargin(0);
this->setFixedSize(this->geometry().width(),this->geometry().height());
EditMode=4;
#ifdef EnableArabic
setFileNameFlag=false;
#endif
}
void DialogSaveFile::refreshListView(int mode){
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
QDir dir(dirPath);
QStringList filters;
EditMode = mode;
if(mode == TXTFILE) filters << "*.html" << "*.txt" << "*.TXT" << "*.jpeg" << "*.gif" << "*.jpg" << "*.bmp"<< "*.BMP"; // txtmode
else if(mode == PICFILE) filters << "*.png";// <<"*.jpg" ; // picmode
else if(mode == SCENE) filters << "*.xml";// scene mode
else filters << "*.html" << "*.bmp" << "*.BMP" <<"*.jpg"<<"*.gif";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files);
#ifndef EnableArabic
QStringListModel *model = new QStringListModel(dir.entryList());
#else
QStringList entries=dir.entryList();
QStandardItemModel *model = new QStandardItemModel();
for(int i=0;i<entries.size();i++){
QStandardItem *item1 = new QStandardItem(entries.at(i));
int lastIndex=entries.at(i).lastIndexOf(".");
if(lastIndex != -1){
int secondLastIndex = entries.at(i).lastIndexOf(".",lastIndex-1);
if(secondLastIndex != -1){
QString subsuffix=entries.at(i).mid(secondLastIndex);
if(subsuffix.contains(".a.")){
QString subsuffix2=entries.at(i).mid(lastIndex);
QString subname=entries.at(i).mid(0,secondLastIndex);
QString stringhtml=QString("<span style=font-family:'biyangarabic';>%1</span><span style=font-family:'biyang';>%2</span>").arg(subname).arg(subsuffix2);
QStandardItem *item2 = new QStandardItem(stringhtml);
model->appendRow(item2);
}
}else{
model->appendRow(item1);
}
}
}
ui->listViewFile->setItemDelegate(new HtmlDelegate);
#endif
ui->listViewFile->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->listViewFile->setModel(model); //useList是个QListView
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(0 , 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
#ifdef EnableArabic
QFont font;
if(!setFileNameFlag){
font.setFamily("biyang");
ui->lineEdit->setFont(font);
}else {
font.setFamily("biyangarabic");
ui->lineEdit->setFont(font);
}
#endif
}
DialogSaveFile::~DialogSaveFile()
{
delete ui;
}
void DialogSaveFile::on_listViewFile_entered(const QModelIndex &index)
{
#ifdef EnableArabic
QFont font;
QString fileName=index.data().toString();
if(fileName.endsWith("</span>")){
QTextDocument doc;
doc.setHtml(fileName);
fileName= doc.toPlainText();
font.setFamily("biyangarabic");
ui->lineEdit->setFont(font);
ui->lineEdit->setText(QString(QFileInfo(fileName).baseName()));
int position = fileName.lastIndexOf(".");
fileName.insert(position,".a");
}else{
font.setFamily("biyang");
ui->lineEdit->setFont(font);
ui->lineEdit->setText( QFileInfo(fileName).baseName() );
}
#endif
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
#ifndef EnableArabic
QString filePath = dirPath + index.data().toString();
#else
QString filePath = dirPath + fileName;
#endif
if(filePath.endsWith(".gif") || filePath.endsWith(".jpeg") || filePath.endsWith(".jpg") ||
filePath.endsWith(".png") || filePath.endsWith(".bmp")|| filePath.endsWith(".BMP")|| filePath.endsWith(".nda")){
ui->textEditView->clear();
ui->textEditView->setHtml(QString("<img src='%1'/>").arg(filePath));
}
else {
QFile file(filePath);
if (!file.open(QFile::ReadOnly))
return ;
QByteArray data = file.readAll();
QTextCodec *codec = Qt::codecForHtml(data);
QString str = codec->toUnicode(data);
if (Qt::mightBeRichText(str)) {
if(!ui->radioButtonLocal->isChecked())
str.replace(DOC_ROOT_DIR,UDISK_DOC_ROOT_DIR); //必须替换相应的路径
ui->textEditView->setHtml(str);
} else {
str = QString::fromLocal8Bit(data);
ui->textEditView->setPlainText(str);
}
}
#ifndef EnableArabic
ui->lineEdit->setText( QFileInfo(ui->listViewFile->currentIndex().data().toString()).baseName() );
#endif
}
void DialogSaveFile::on_listViewFile_clicked(const QModelIndex &index)
{
on_listViewFile_entered(index);
}
void DialogSaveFile::on_pushButtonNext_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index((currIndex.row() + 1)%count, 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
ui->lineEdit->setText(QFileInfo(ui->listViewFile->currentIndex().data().toString()).baseName());
}
void DialogSaveFile::on_pushButtonLast_pressed()
{
QModelIndex currIndex = ui->listViewFile->currentIndex();
int count = ui->listViewFile->model()->rowCount();
if(count){
QModelIndex index = ui->listViewFile->model()->index(currIndex.row() == 0?(count - 1):(currIndex.row() - 1), 0);
ui->listViewFile->setCurrentIndex(index);
on_listViewFile_entered(index);
}
ui->lineEdit->setText(QFileInfo(ui->listViewFile->currentIndex().data().toString()).baseName());
}
void DialogSaveFile::on_pushButtonExit_pressed()
{
hide();
}
//void DialogSaveFile::on_lostfocuse_pressed()
//{
// hide();
//}
void DialogSaveFile::on_pushButtonSave_clicked()
{
QModelIndex index = ui->listViewFile->currentIndex();
QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_DOC_ROOT_DIR;
//QString filePath = dirPath + index.data().toString();
QString filePath = dirPath + ui->lineEdit->text();// index.data().toString();
#ifdef EnableArabic
if(setFileNameFlag){
filePath = dirPath + ui->lineEdit->text()+".a";
}
#endif
emit saveFile(filePath,false);
hide();
}
void DialogSaveFile::on_radioButtonLocal_released()
{
refreshListView(EditMode);
}
void DialogSaveFile::on_radioButtonUdisk_released()
{
QDir dir(UDISK_DOC_ROOT_DIR);
if(!dir.exists()){
QMessageBox::warning(0,tr("警告"),tr("U盘未插入或U盘根目录下的doc文件夹不存在!"));
}
refreshListView(EditMode);
}
void DialogSaveFile::setEnterFileName(QString strFile)
{
ui->lineEdit->setText(strFile);
//ui->lineEdit->setFocus();
}
void DialogSaveFile::setTitleTxt(QString str)
{
setWindowTitle(str);
}
#ifdef EnableArabic
void DialogSaveFile::setFileNameEnglishOrArabic(bool flag){
QFont font;
setFileNameFlag=flag;
//qDebug()<<"setFileNameFlag :"<<flag;
if(flag){
font.setFamily("biyangarabic");
}else {
font.setFamily("biyang");
}
ui->lineEdit->setFont(font);
}
#endif
+54 -54
View File
@@ -1,54 +1,54 @@
#ifndef DialogSaveFile_H
#define DialogSaveFile_H
#include <QDialog>
#include "DialogSaveFile.h"
#include <QModelIndex>
#include "myinclude.h"
namespace Ui {
class DialogSaveFile;
}
class DialogSaveFile : public QDialog
{
Q_OBJECT
public:
explicit DialogSaveFile(QWidget *parent = 0);
~DialogSaveFile();
void refreshListView(int mode);
int EditMode;
void setEnterFileName(QString strFile);
void setTitleTxt(QString str);
#ifdef EnableArabic
void setFileNameEnglishOrArabic(bool flag);
#endif
private slots:
void on_pushButtonNext_pressed();
void on_pushButtonLast_pressed();
void on_pushButtonExit_pressed();
void on_pushButtonSave_clicked();
void on_radioButtonLocal_released();
void on_radioButtonUdisk_released();
void on_listViewFile_entered(const QModelIndex &index);
void on_listViewFile_clicked(const QModelIndex &index);
Q_SIGNALS:
void saveFile(QString filePath,bool Flag);
private:
Ui::DialogSaveFile *ui;
#ifdef EnableArabic
bool setFileNameFlag;
#endif
};
#endif // DialogSaveFile_H
#ifndef DialogSaveFile_H
#define DialogSaveFile_H
#include <QDialog>
#include "DialogSaveFile.h"
#include <QModelIndex>
#include "myinclude.h"
namespace Ui {
class DialogSaveFile;
}
class DialogSaveFile : public QDialog
{
Q_OBJECT
public:
explicit DialogSaveFile(QWidget *parent = 0);
~DialogSaveFile();
void refreshListView(int mode);
int EditMode;
void setEnterFileName(QString strFile);
void setTitleTxt(QString str);
#ifdef EnableArabic
void setFileNameEnglishOrArabic(bool flag);
#endif
private slots:
void on_pushButtonNext_pressed();
void on_pushButtonLast_pressed();
void on_pushButtonExit_pressed();
void on_pushButtonSave_clicked();
void on_radioButtonLocal_released();
void on_radioButtonUdisk_released();
void on_listViewFile_entered(const QModelIndex &index);
void on_listViewFile_clicked(const QModelIndex &index);
Q_SIGNALS:
void saveFile(QString filePath,bool Flag);
private:
Ui::DialogSaveFile *ui;
#ifdef EnableArabic
bool setFileNameFlag;
#endif
};
#endif // DialogSaveFile_H
+76 -76
View File
@@ -1,76 +1,76 @@
#include "DigitalInput.h"
#include "ui_digitalinput.h"
#include "MyInputMethod.h"
#include <QObject>
#include <QSpinBox>
DigitalInput::DigitalInput(MyInputMethod *myInputMethod,QWidget *parent) :
QWidget(parent,(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool|Qt::WindowDoesNotAcceptFocus|Qt::BypassWindowManagerHint)),
ui(new Ui::DigitalInput)
{
ui->setupUi(this);
this->myInputMethod = myInputMethod;
connect(ui->Key_0,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_1,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_2,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_3,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_4,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_5,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_6,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_7,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_8,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_9,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_pluse,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_backspace,SIGNAL(pressed()),this,SLOT(onKeyBackspacePressed()));
connect(ui->Key_selectAll,SIGNAL(pressed()),this,SLOT(onKeySelectAllPressed()));
connect(ui->Key_up,SIGNAL(pressed()),this,SLOT(onKeyUpPressed()));
connect(ui->Key_down,SIGNAL(pressed()),this,SLOT(onKeyDownPressed()));
}
DigitalInput::~DigitalInput()
{
delete ui;
}
void DigitalInput::onCharPressed(){
QPushButton * button = qobject_cast<QPushButton *>(sender());
QString text = button->text();
myInputMethod->sendString (text);
}
void DigitalInput::onKeyBackspacePressed(){
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_Backspace,Qt::NoModifier,true,false); //向系统发送键盘事件
MyInputMethod::sendEvent(Qt::Key_Backspace,Qt::NoModifier);
#endif
}
void DigitalInput::onKeySelectAllPressed(){
//static int init = 0;
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_A,Qt::ControlModifier,true,false); //向系统发送键盘事件
//if(!init)
// QWSServer::sendKeyEvent(0,Qt::Key_A,Qt::ControlModifier,true,false); //向系统发送键盘事件
//init = 1;
MyInputMethod::sendEvent(Qt::Key_A, Qt::ControlModifier);
#endif
}
void DigitalInput::onKeyUpPressed(){
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_Up,Qt::NoModifier,true,false); //向系统发送键盘事件
MyInputMethod::sendEvent(Qt::Key_Up,Qt::NoModifier);
#endif
}
void DigitalInput::onKeyDownPressed(){
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_Down,Qt::NoModifier,true,false); //向系统发送键盘事件
MyInputMethod::sendEvent(Qt::Key_Down,Qt::NoModifier);
#endif
}
#include "DigitalInput.h"
#include "ui_digitalinput.h"
#include "MyInputMethod.h"
#include <QObject>
#include <QSpinBox>
DigitalInput::DigitalInput(MyInputMethod *myInputMethod,QWidget *parent) :
QWidget(parent,(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool|Qt::WindowDoesNotAcceptFocus|Qt::BypassWindowManagerHint)),
ui(new Ui::DigitalInput)
{
ui->setupUi(this);
this->myInputMethod = myInputMethod;
connect(ui->Key_0,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_1,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_2,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_3,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_4,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_5,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_6,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_7,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_8,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_9,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_pluse,SIGNAL(pressed()),this,SLOT(onCharPressed()));
connect(ui->Key_backspace,SIGNAL(pressed()),this,SLOT(onKeyBackspacePressed()));
connect(ui->Key_selectAll,SIGNAL(pressed()),this,SLOT(onKeySelectAllPressed()));
connect(ui->Key_up,SIGNAL(pressed()),this,SLOT(onKeyUpPressed()));
connect(ui->Key_down,SIGNAL(pressed()),this,SLOT(onKeyDownPressed()));
}
DigitalInput::~DigitalInput()
{
delete ui;
}
void DigitalInput::onCharPressed(){
QPushButton * button = qobject_cast<QPushButton *>(sender());
QString text = button->text();
myInputMethod->sendString (text);
}
void DigitalInput::onKeyBackspacePressed(){
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_Backspace,Qt::NoModifier,true,false); //向系统发送键盘事件
MyInputMethod::sendEvent(Qt::Key_Backspace,Qt::NoModifier);
#endif
}
void DigitalInput::onKeySelectAllPressed(){
//static int init = 0;
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_A,Qt::ControlModifier,true,false); //向系统发送键盘事件
//if(!init)
// QWSServer::sendKeyEvent(0,Qt::Key_A,Qt::ControlModifier,true,false); //向系统发送键盘事件
//init = 1;
MyInputMethod::sendEvent(Qt::Key_A, Qt::ControlModifier);
#endif
}
void DigitalInput::onKeyUpPressed(){
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_Up,Qt::NoModifier,true,false); //向系统发送键盘事件
MyInputMethod::sendEvent(Qt::Key_Up,Qt::NoModifier);
#endif
}
void DigitalInput::onKeyDownPressed(){
#ifndef Q_OS_WIN32
//QWSServer::sendKeyEvent(0,Qt::Key_Down,Qt::NoModifier,true,false); //向系统发送键盘事件
MyInputMethod::sendEvent(Qt::Key_Down,Qt::NoModifier);
#endif
}
+33 -33
View File
@@ -1,33 +1,33 @@
#ifndef DIGITALINPUT_H
#define DIGITALINPUT_H
#include <QWidget>
class MyInputMethod;
namespace Ui {
class DigitalInput;
}
class DigitalInput : public QWidget
{
Q_OBJECT
public:
explicit DigitalInput(MyInputMethod *myInputMethod,QWidget *parent = 0);
~DigitalInput();
private slots:
void onCharPressed();
void onKeyBackspacePressed();
void onKeySelectAllPressed();
void onKeyUpPressed();
void onKeyDownPressed();
private:
Ui::DigitalInput *ui;
MyInputMethod *myInputMethod;
};
#endif // DIGITALINPUT_H
#ifndef DIGITALINPUT_H
#define DIGITALINPUT_H
#include <QWidget>
class MyInputMethod;
namespace Ui {
class DigitalInput;
}
class DigitalInput : public QWidget
{
Q_OBJECT
public:
explicit DigitalInput(MyInputMethod *myInputMethod,QWidget *parent = 0);
~DigitalInput();
private slots:
void onCharPressed();
void onKeyBackspacePressed();
void onKeySelectAllPressed();
void onKeyUpPressed();
void onKeyDownPressed();
private:
Ui::DigitalInput *ui;
MyInputMethod *myInputMethod;
};
#endif // DIGITALINPUT_H
+391 -391
View File
@@ -1,391 +1,391 @@
#include "DlgVoltePara25Dots.h"
#include "DevOp.h"
#include <QFile>
#include <LogInfo.h>
DlgVoltePara25Dots::DlgVoltePara25Dots(DevOp *devOp, QWidget *parent)
: QDialog(parent)
, m_devOp(devOp)
{
memset(editContinuous, 0, sizeof(editContinuous));
memset(editRowDelay, 0, sizeof(editRowDelay));
memset(editHead1RowDelay, 0, sizeof(editHead1RowDelay));
memset(editSingleDot, 0, sizeof(editSingleDot));
memset(edit1Dot, 0, sizeof(edit1Dot));
memset(edit2Dots, 0, sizeof(edit2Dots));
memset(edit3Dots, 0, sizeof(edit3Dots));
memset(edit4Dots, 0, sizeof(edit4Dots));
memset(edit5Dots, 0, sizeof(edit5Dots));
memset(editDiff, 0, sizeof(editDiff));
memset(editGiant, 0, sizeof(editGiant));
memset(editAdjustPara, 0, sizeof(editAdjustPara));
setupUI();
}
DlgVoltePara25Dots::~DlgVoltePara25Dots()
{
}
// 创建4列×16行网格布局的tab页(竖排: v0~v15第1列, v16~v31第2列, ...)
QWidget* DlgVoltePara25Dots::createGridTab(int count, QLineEdit* edits[], int numCols)
{
QWidget *page = new QWidget(this);
QGridLayout *grid = new QGridLayout(page);
grid->setSpacing(2);
grid->setContentsMargins(4, 4, 4, 4);
int rowsPerCol = (count + numCols - 1) / numCols;
for (int i = 0; i < count; i++) {
int col = i / rowsPerCol;
int row = i % rowsPerCol;
QLabel *label = new QLabel(QString("v%1").arg(i), page);
label->setFixedWidth(28);
label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
QLineEdit *edit = new QLineEdit("0", page);
edit->setAlignment(Qt::AlignCenter);
edits[i] = edit;
grid->addWidget(label, row, col * 2);
grid->addWidget(edit, row, col * 2 + 1);
}
for (int c = 0; c < numCols; c++) {
grid->setColumnStretch(c * 2, 0);
grid->setColumnStretch(c * 2 + 1, 1);
}
return page;
}
void DlgVoltePara25Dots::setupUI()
{
setWindowTitle(QString("25点阵充电参数编辑"));
//setFixedSize(750, 500);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setContentsMargins(4, 4, 4, 4);
mainLayout->setSpacing(4);
tabWidget = new QTabWidget(this);
// 基本tab
tabWidget->addTab(createGridTab(64, editContinuous), QString("连续电压"));
tabWidget->addTab(createGridTab(64, editRowDelay), QString("点延迟"));
tabWidget->addTab(createGridTab(64, editHead1RowDelay), QString("首1点延迟"));
// 通用参数
tabWidget->addTab(createGridTab(8, editAdjustPara), QString("通用参数"));
tabWidget->addTab(createGridTab(64, editSingleDot), QString("单点"));
tabWidget->addTab(createGridTab(64, edit1Dot), QString("一点"));
tabWidget->addTab(createGridTab(64, edit2Dots), QString("两点"));
tabWidget->addTab(createGridTab(64, edit3Dots), QString("三点"));
tabWidget->addTab(createGridTab(64, edit4Dots), QString("四点"));
tabWidget->addTab(createGridTab(64, edit5Dots), QString("五点"));
// 巨点补偿:16组,分4个tab(5,5,5,1组)
// 前3个tab:流式切分[5][64]=320值÷5=64个lineEdit
// 第4个tab:流式切分[1][64]=64值÷5=13个lineEdit(最后一个放4个值)
int giantEditCount[4] = {64, 64, 64, 13};
for (int t = 0; t < 4; t++) {
tabWidget->addTab(createGridTab(giantEditCount[t], editGiant[t]),
QString("巨点补偿%1").arg(t + 1));
}
// 差分补偿:50组÷5=10个tab,每个tab 64通道,每个lineEdit放5个逗号分隔值
static const char* diffTabNames[10] = {
"1点隔1-5点差", "1点隔6-10点差",
"2点隔1-5点差", "2点隔6-10点差",
"3点隔1-5点差", "3点隔6-10点差",
"4点隔1-5点差", "4点隔6-10点差",
"5点隔1-5点差", "5点隔6-10点差"
};
for (int t = 0; t < 10; t++) {
tabWidget->addTab(createGridTab(64, editDiff[t], 5),
QString(diffTabNames[t]));
}
mainLayout->addWidget(tabWidget);
// 底部按钮栏
QHBoxLayout *btnLayout = new QHBoxLayout();
btnLoad = new QPushButton(QString("读取当前值"), this);
btnSave = new QPushButton(QString("保存并推送FPGA"), this);
btnLoad->setMinimumHeight(40);
btnSave->setMinimumHeight(40);
btnLayout->addWidget(btnLoad);
btnLayout->addStretch();
btnLayout->addWidget(btnSave);
mainLayout->addLayout(btnLayout);
connect(btnLoad, SIGNAL(clicked()), this, SLOT(onBtnLoadClicked()));
connect(btnSave, SIGNAL(clicked()), this, SLOT(onBtnSaveClicked()));
}
// ========== 数据加载:结构体 → UI ==========
void DlgVoltePara25Dots::loadDataToUI()
{
if (!sysPara) return;
voltePara_t_25Dots &data = sysPara->voltePara_25Dots;
// 连续电压(单值)
for (int i = 0; i < 64; i++)
editContinuous[i]->setText(QString::number(data.matchContinousDACArray[i]));
// 点延迟(单值)
for (int i = 0; i < 64; i++)
editRowDelay[i]->setText(QString::number(data.matchExtraLineDACArray[i]));
// 首1点延迟(有符号)
for (int i = 0; i < 64; i++)
editHead1RowDelay[i]->setText(QString::number((qint8)data.matchFirstOnePointExtraLineDACArray[i]));
// 单点(首1)
for (int i = 0; i < 64; i++)
editSingleDot[i]->setText(QString::number(data.matchTotalTableDACArrayFirst1[i]));
// 一点
for (int i = 0; i < 64; i++)
edit1Dot[i]->setText(QString::number(data.matchTotalTableDACArray1[i]));
// 两点(2值逗号分隔)
for (int i = 0; i < 64; i++) {
edit2Dots[i]->setText(QString("%1,%2")
.arg(data.matchTotalTableDACArray2[i][0])
.arg(data.matchTotalTableDACArray2[i][1]));
}
// 三点(3值逗号分隔)
for (int i = 0; i < 64; i++) {
edit3Dots[i]->setText(QString("%1,%2,%3")
.arg(data.matchTotalTableDACArray3[i][0])
.arg(data.matchTotalTableDACArray3[i][1])
.arg(data.matchTotalTableDACArray3[i][2]));
}
// 四点(4值逗号分隔)
for (int i = 0; i < 64; i++) {
edit4Dots[i]->setText(QString("%1,%2,%3,%4")
.arg(data.matchTotalTableDACArray4[i][0])
.arg(data.matchTotalTableDACArray4[i][1])
.arg(data.matchTotalTableDACArray4[i][2])
.arg(data.matchTotalTableDACArray4[i][3]));
}
// 五点(5值逗号分隔)
for (int i = 0; i < 64; i++) {
edit5Dots[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.matchTotalTableDACArray5[i][0])
.arg(data.matchTotalTableDACArray5[i][1])
.arg(data.matchTotalTableDACArray5[i][2])
.arg(data.matchTotalTableDACArray5[i][3])
.arg(data.matchTotalTableDACArray5[i][4]));
}
// 差分补偿:matchTotalDiffVoltageValue[50][64]
// 每5组一个tab,把[5][64]=320个值按内存顺序展平,每5个连续值放一个lineEdit,共64个lineEdit
// 与oldProject的Load_voltage_diff逻辑一致
for (int t = 0; t < 10; t++) {
int k = 0; // 当前lineEdit内已累积的值计数(1~5)
int num = 0; // 当前lineEdit序号
QString strTemp;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 64; j++) {
k++;
if (k < 5) {
strTemp += QString::number((qint8)data.matchTotalDiffVoltageValue[t * 5 + i][j]);
strTemp += ",";
} else {
strTemp += QString::number((qint8)data.matchTotalDiffVoltageValue[t * 5 + i][j]);
editDiff[t][num]->setText(strTemp);
strTemp = "";
k = 0;
num++;
}
}
}
}
// 巨点补偿:matchGiantPointVoltageValue[16][64]
// 与oldProject一致:流式切分,前3个tab用Load_voltage_diff逻辑,第4个tab用Load_voltage_giant逻辑
{
int giantGroupsPerTab[4] = {5, 5, 5, 1};
int giantOffset = 0;
for (int t = 0; t < 4; t++) {
int groups = giantGroupsPerTab[t];
int k = 0;
int num = 0;
QString strTemp;
for (int i = 0; i < groups; i++) {
for (int j = 0; j < 64; j++) {
k++;
if (k < 5) {
strTemp += QString::number((qint8)data.matchGiantPointVoltageValue[giantOffset + i][j]);
strTemp += ",";
// 第4个tab特殊处理:最后一个值时不足5个也要输出
if (t == 3 && i == groups - 1 && j == 63) {
strTemp.chop(1); // 去掉末尾逗号
editGiant[t][num]->setText(strTemp);
}
} else {
strTemp += QString::number((qint8)data.matchGiantPointVoltageValue[giantOffset + i][j]);
editGiant[t][num]->setText(strTemp);
strTemp = "";
k = 0;
num++;
}
}
}
giantOffset += groups;
}
}
// 通用参数
for (int i = 0; i < 8; i++)
editAdjustPara[i]->setText(QString::number((qint8)data.matchAdjustParaDACArray[i]));
}
// ========== 数据保存:UI → 结构体 ==========
void DlgVoltePara25Dots::saveDataFromUI()
{
if (!sysPara) return;
voltePara_t_25Dots &data = sysPara->voltePara_25Dots;
// 连续电压
for (int i = 0; i < 64; i++)
data.matchContinousDACArray[i] = (quint16)editContinuous[i]->text().toUInt();
// 点延迟
for (int i = 0; i < 64; i++)
data.matchExtraLineDACArray[i] = (quint8)editRowDelay[i]->text().toUInt();
// 首1点延迟
for (int i = 0; i < 64; i++)
data.matchFirstOnePointExtraLineDACArray[i] = (qint8)editHead1RowDelay[i]->text().toInt();
// 单点(首1)
for (int i = 0; i < 64; i++)
data.matchTotalTableDACArrayFirst1[i] = (quint16)editSingleDot[i]->text().toUInt();
// 一点
for (int i = 0; i < 64; i++)
data.matchTotalTableDACArray1[i] = (quint16)edit1Dot[i]->text().toUInt();
// 两点
for (int i = 0; i < 64; i++) {
QStringList parts = edit2Dots[i]->text().split(",");
for (int j = 0; j < 2; j++)
data.matchTotalTableDACArray2[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 三点
for (int i = 0; i < 64; i++) {
QStringList parts = edit3Dots[i]->text().split(",");
for (int j = 0; j < 3; j++)
data.matchTotalTableDACArray3[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 四点
for (int i = 0; i < 64; i++) {
QStringList parts = edit4Dots[i]->text().split(",");
for (int j = 0; j < 4; j++)
data.matchTotalTableDACArray4[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 五点
for (int i = 0; i < 64; i++) {
QStringList parts = edit5Dots[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.matchTotalTableDACArray5[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 差分补偿:与oldProject的Save_voltage_diff逻辑一致
// 每个tab的64个lineEdit各含5个逗号分隔值,展平后按内存顺序写回[5][64]
for (int t = 0; t < 10; t++) {
// 先把64个lineEdit的值全部拼成一个大列表(320个值)
QStringList allValues;
for (int num = 0; num < 64; num++) {
QStringList parts = editDiff[t][num]->text().split(",");
allValues.append(parts);
}
// 按内存顺序写回 [5][64]
int idx = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 64; j++) {
data.matchTotalDiffVoltageValue[t * 5 + i][j] =
idx < allValues.size() ? (qint8)allValues[idx].toInt() : 0;
idx++;
}
}
}
// 巨点补偿:与oldProject一致,流式反解析
{
int giantGroupsPerTab[4] = {5, 5, 5, 1};
int giantEditCount[4] = {64, 64, 64, 13};
int giantOffset = 0;
for (int t = 0; t < 4; t++) {
int groups = giantGroupsPerTab[t];
// 把所有lineEdit的值拼成一个大列表
QStringList allValues;
for (int num = 0; num < giantEditCount[t]; num++) {
QStringList parts = editGiant[t][num]->text().split(",");
allValues.append(parts);
}
// 按内存顺序写回 [groups][64]
int idx = 0;
for (int i = 0; i < groups; i++) {
for (int j = 0; j < 64; j++) {
data.matchGiantPointVoltageValue[giantOffset + i][j] =
idx < allValues.size() ? (qint8)allValues[idx].toInt() : 0;
idx++;
}
}
giantOffset += groups;
}
}
// 通用参数
for (int i = 0; i < 8; i++)
data.matchAdjustParaDACArray[i] = (qint8)editAdjustPara[i]->text().toInt();
}
// ========== 按钮槽函数 ==========
void DlgVoltePara25Dots::onBtnLoadClicked()
{
loadDataToUI();
}
void DlgVoltePara25Dots::onBtnSaveClicked()
{
saveDataFromUI();
if (m_devOp) {
m_devOp->writeDacValue2Fpga_No72NewVoltData();
}
QFile file(DOC_ROOT_DIR"VoltDataStd25.bin");
if(!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, QString("注意"), QString("充电数据已经写入FPGA, 但是没有保存到文件。"));
return;
}
int written = file.write((const char*)&(sysPara->voltePara_25Dots), sizeof(voltePara_t_25Dots));
file.close();
if(written != sizeof(voltePara_t_25Dots)) {
LogInfo::setRunStatusText("写入文件VoltDataStd25.bin失败");
}
QMessageBox::information(this, QString("完成"), QString("充电参数已保存并推送至FPGA。"));
}
#include "DlgVoltePara25Dots.h"
#include "DevOp.h"
#include <QFile>
#include <LogInfo.h>
DlgVoltePara25Dots::DlgVoltePara25Dots(DevOp *devOp, QWidget *parent)
: QDialog(parent)
, m_devOp(devOp)
{
memset(editContinuous, 0, sizeof(editContinuous));
memset(editRowDelay, 0, sizeof(editRowDelay));
memset(editHead1RowDelay, 0, sizeof(editHead1RowDelay));
memset(editSingleDot, 0, sizeof(editSingleDot));
memset(edit1Dot, 0, sizeof(edit1Dot));
memset(edit2Dots, 0, sizeof(edit2Dots));
memset(edit3Dots, 0, sizeof(edit3Dots));
memset(edit4Dots, 0, sizeof(edit4Dots));
memset(edit5Dots, 0, sizeof(edit5Dots));
memset(editDiff, 0, sizeof(editDiff));
memset(editGiant, 0, sizeof(editGiant));
memset(editAdjustPara, 0, sizeof(editAdjustPara));
setupUI();
}
DlgVoltePara25Dots::~DlgVoltePara25Dots()
{
}
// 创建4列×16行网格布局的tab页(竖排: v0~v15第1列, v16~v31第2列, ...)
QWidget* DlgVoltePara25Dots::createGridTab(int count, QLineEdit* edits[], int numCols)
{
QWidget *page = new QWidget(this);
QGridLayout *grid = new QGridLayout(page);
grid->setSpacing(2);
grid->setContentsMargins(4, 4, 4, 4);
int rowsPerCol = (count + numCols - 1) / numCols;
for (int i = 0; i < count; i++) {
int col = i / rowsPerCol;
int row = i % rowsPerCol;
QLabel *label = new QLabel(QString("v%1").arg(i), page);
label->setFixedWidth(28);
label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
QLineEdit *edit = new QLineEdit("0", page);
edit->setAlignment(Qt::AlignCenter);
edits[i] = edit;
grid->addWidget(label, row, col * 2);
grid->addWidget(edit, row, col * 2 + 1);
}
for (int c = 0; c < numCols; c++) {
grid->setColumnStretch(c * 2, 0);
grid->setColumnStretch(c * 2 + 1, 1);
}
return page;
}
void DlgVoltePara25Dots::setupUI()
{
setWindowTitle(QString("25点阵充电参数编辑"));
//setFixedSize(750, 500);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setContentsMargins(4, 4, 4, 4);
mainLayout->setSpacing(4);
tabWidget = new QTabWidget(this);
// 基本tab
tabWidget->addTab(createGridTab(64, editContinuous), QString("连续电压"));
tabWidget->addTab(createGridTab(64, editRowDelay), QString("点延迟"));
tabWidget->addTab(createGridTab(64, editHead1RowDelay), QString("首1点延迟"));
// 通用参数
tabWidget->addTab(createGridTab(8, editAdjustPara), QString("通用参数"));
tabWidget->addTab(createGridTab(64, editSingleDot), QString("单点"));
tabWidget->addTab(createGridTab(64, edit1Dot), QString("一点"));
tabWidget->addTab(createGridTab(64, edit2Dots), QString("两点"));
tabWidget->addTab(createGridTab(64, edit3Dots), QString("三点"));
tabWidget->addTab(createGridTab(64, edit4Dots), QString("四点"));
tabWidget->addTab(createGridTab(64, edit5Dots), QString("五点"));
// 巨点补偿:16组,分4个tab(5,5,5,1组)
// 前3个tab:流式切分[5][64]=320值÷5=64个lineEdit
// 第4个tab:流式切分[1][64]=64值÷5=13个lineEdit(最后一个放4个值)
int giantEditCount[4] = {64, 64, 64, 13};
for (int t = 0; t < 4; t++) {
tabWidget->addTab(createGridTab(giantEditCount[t], editGiant[t]),
QString("巨点补偿%1").arg(t + 1));
}
// 差分补偿:50组÷5=10个tab,每个tab 64通道,每个lineEdit放5个逗号分隔值
static const char* diffTabNames[10] = {
"1点隔1-5点差", "1点隔6-10点差",
"2点隔1-5点差", "2点隔6-10点差",
"3点隔1-5点差", "3点隔6-10点差",
"4点隔1-5点差", "4点隔6-10点差",
"5点隔1-5点差", "5点隔6-10点差"
};
for (int t = 0; t < 10; t++) {
tabWidget->addTab(createGridTab(64, editDiff[t], 5),
QString(diffTabNames[t]));
}
mainLayout->addWidget(tabWidget);
// 底部按钮栏
QHBoxLayout *btnLayout = new QHBoxLayout();
btnLoad = new QPushButton(QString("读取当前值"), this);
btnSave = new QPushButton(QString("保存并推送FPGA"), this);
btnLoad->setMinimumHeight(40);
btnSave->setMinimumHeight(40);
btnLayout->addWidget(btnLoad);
btnLayout->addStretch();
btnLayout->addWidget(btnSave);
mainLayout->addLayout(btnLayout);
connect(btnLoad, SIGNAL(clicked()), this, SLOT(onBtnLoadClicked()));
connect(btnSave, SIGNAL(clicked()), this, SLOT(onBtnSaveClicked()));
}
// ========== 数据加载:结构体 → UI ==========
void DlgVoltePara25Dots::loadDataToUI()
{
if (!sysPara) return;
voltePara_t_25Dots &data = sysPara->voltePara_25Dots;
// 连续电压(单值)
for (int i = 0; i < 64; i++)
editContinuous[i]->setText(QString::number(data.matchContinousDACArray[i]));
// 点延迟(单值)
for (int i = 0; i < 64; i++)
editRowDelay[i]->setText(QString::number(data.matchExtraLineDACArray[i]));
// 首1点延迟(有符号)
for (int i = 0; i < 64; i++)
editHead1RowDelay[i]->setText(QString::number((qint8)data.matchFirstOnePointExtraLineDACArray[i]));
// 单点(首1)
for (int i = 0; i < 64; i++)
editSingleDot[i]->setText(QString::number(data.matchTotalTableDACArrayFirst1[i]));
// 一点
for (int i = 0; i < 64; i++)
edit1Dot[i]->setText(QString::number(data.matchTotalTableDACArray1[i]));
// 两点(2值逗号分隔)
for (int i = 0; i < 64; i++) {
edit2Dots[i]->setText(QString("%1,%2")
.arg(data.matchTotalTableDACArray2[i][0])
.arg(data.matchTotalTableDACArray2[i][1]));
}
// 三点(3值逗号分隔)
for (int i = 0; i < 64; i++) {
edit3Dots[i]->setText(QString("%1,%2,%3")
.arg(data.matchTotalTableDACArray3[i][0])
.arg(data.matchTotalTableDACArray3[i][1])
.arg(data.matchTotalTableDACArray3[i][2]));
}
// 四点(4值逗号分隔)
for (int i = 0; i < 64; i++) {
edit4Dots[i]->setText(QString("%1,%2,%3,%4")
.arg(data.matchTotalTableDACArray4[i][0])
.arg(data.matchTotalTableDACArray4[i][1])
.arg(data.matchTotalTableDACArray4[i][2])
.arg(data.matchTotalTableDACArray4[i][3]));
}
// 五点(5值逗号分隔)
for (int i = 0; i < 64; i++) {
edit5Dots[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.matchTotalTableDACArray5[i][0])
.arg(data.matchTotalTableDACArray5[i][1])
.arg(data.matchTotalTableDACArray5[i][2])
.arg(data.matchTotalTableDACArray5[i][3])
.arg(data.matchTotalTableDACArray5[i][4]));
}
// 差分补偿:matchTotalDiffVoltageValue[50][64]
// 每5组一个tab,把[5][64]=320个值按内存顺序展平,每5个连续值放一个lineEdit,共64个lineEdit
// 与oldProject的Load_voltage_diff逻辑一致
for (int t = 0; t < 10; t++) {
int k = 0; // 当前lineEdit内已累积的值计数(1~5)
int num = 0; // 当前lineEdit序号
QString strTemp;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 64; j++) {
k++;
if (k < 5) {
strTemp += QString::number((qint8)data.matchTotalDiffVoltageValue[t * 5 + i][j]);
strTemp += ",";
} else {
strTemp += QString::number((qint8)data.matchTotalDiffVoltageValue[t * 5 + i][j]);
editDiff[t][num]->setText(strTemp);
strTemp = "";
k = 0;
num++;
}
}
}
}
// 巨点补偿:matchGiantPointVoltageValue[16][64]
// 与oldProject一致:流式切分,前3个tab用Load_voltage_diff逻辑,第4个tab用Load_voltage_giant逻辑
{
int giantGroupsPerTab[4] = {5, 5, 5, 1};
int giantOffset = 0;
for (int t = 0; t < 4; t++) {
int groups = giantGroupsPerTab[t];
int k = 0;
int num = 0;
QString strTemp;
for (int i = 0; i < groups; i++) {
for (int j = 0; j < 64; j++) {
k++;
if (k < 5) {
strTemp += QString::number((qint8)data.matchGiantPointVoltageValue[giantOffset + i][j]);
strTemp += ",";
// 第4个tab特殊处理:最后一个值时不足5个也要输出
if (t == 3 && i == groups - 1 && j == 63) {
strTemp.chop(1); // 去掉末尾逗号
editGiant[t][num]->setText(strTemp);
}
} else {
strTemp += QString::number((qint8)data.matchGiantPointVoltageValue[giantOffset + i][j]);
editGiant[t][num]->setText(strTemp);
strTemp = "";
k = 0;
num++;
}
}
}
giantOffset += groups;
}
}
// 通用参数
for (int i = 0; i < 8; i++)
editAdjustPara[i]->setText(QString::number((qint8)data.matchAdjustParaDACArray[i]));
}
// ========== 数据保存:UI → 结构体 ==========
void DlgVoltePara25Dots::saveDataFromUI()
{
if (!sysPara) return;
voltePara_t_25Dots &data = sysPara->voltePara_25Dots;
// 连续电压
for (int i = 0; i < 64; i++)
data.matchContinousDACArray[i] = (quint16)editContinuous[i]->text().toUInt();
// 点延迟
for (int i = 0; i < 64; i++)
data.matchExtraLineDACArray[i] = (quint8)editRowDelay[i]->text().toUInt();
// 首1点延迟
for (int i = 0; i < 64; i++)
data.matchFirstOnePointExtraLineDACArray[i] = (qint8)editHead1RowDelay[i]->text().toInt();
// 单点(首1)
for (int i = 0; i < 64; i++)
data.matchTotalTableDACArrayFirst1[i] = (quint16)editSingleDot[i]->text().toUInt();
// 一点
for (int i = 0; i < 64; i++)
data.matchTotalTableDACArray1[i] = (quint16)edit1Dot[i]->text().toUInt();
// 两点
for (int i = 0; i < 64; i++) {
QStringList parts = edit2Dots[i]->text().split(",");
for (int j = 0; j < 2; j++)
data.matchTotalTableDACArray2[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 三点
for (int i = 0; i < 64; i++) {
QStringList parts = edit3Dots[i]->text().split(",");
for (int j = 0; j < 3; j++)
data.matchTotalTableDACArray3[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 四点
for (int i = 0; i < 64; i++) {
QStringList parts = edit4Dots[i]->text().split(",");
for (int j = 0; j < 4; j++)
data.matchTotalTableDACArray4[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 五点
for (int i = 0; i < 64; i++) {
QStringList parts = edit5Dots[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.matchTotalTableDACArray5[i][j] = parts.size() > j ? (quint16)parts[j].toUInt() : 0;
}
// 差分补偿:与oldProject的Save_voltage_diff逻辑一致
// 每个tab的64个lineEdit各含5个逗号分隔值,展平后按内存顺序写回[5][64]
for (int t = 0; t < 10; t++) {
// 先把64个lineEdit的值全部拼成一个大列表(320个值)
QStringList allValues;
for (int num = 0; num < 64; num++) {
QStringList parts = editDiff[t][num]->text().split(",");
allValues.append(parts);
}
// 按内存顺序写回 [5][64]
int idx = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 64; j++) {
data.matchTotalDiffVoltageValue[t * 5 + i][j] =
idx < allValues.size() ? (qint8)allValues[idx].toInt() : 0;
idx++;
}
}
}
// 巨点补偿:与oldProject一致,流式反解析
{
int giantGroupsPerTab[4] = {5, 5, 5, 1};
int giantEditCount[4] = {64, 64, 64, 13};
int giantOffset = 0;
for (int t = 0; t < 4; t++) {
int groups = giantGroupsPerTab[t];
// 把所有lineEdit的值拼成一个大列表
QStringList allValues;
for (int num = 0; num < giantEditCount[t]; num++) {
QStringList parts = editGiant[t][num]->text().split(",");
allValues.append(parts);
}
// 按内存顺序写回 [groups][64]
int idx = 0;
for (int i = 0; i < groups; i++) {
for (int j = 0; j < 64; j++) {
data.matchGiantPointVoltageValue[giantOffset + i][j] =
idx < allValues.size() ? (qint8)allValues[idx].toInt() : 0;
idx++;
}
}
giantOffset += groups;
}
}
// 通用参数
for (int i = 0; i < 8; i++)
data.matchAdjustParaDACArray[i] = (qint8)editAdjustPara[i]->text().toInt();
}
// ========== 按钮槽函数 ==========
void DlgVoltePara25Dots::onBtnLoadClicked()
{
loadDataToUI();
}
void DlgVoltePara25Dots::onBtnSaveClicked()
{
saveDataFromUI();
if (m_devOp) {
m_devOp->writeDacValue2Fpga_No72NewVoltData();
}
QFile file(DOC_ROOT_DIR"VoltDataStd25.bin");
if(!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, QString("注意"), QString("充电数据已经写入FPGA, 但是没有保存到文件。"));
return;
}
int written = file.write((const char*)&(sysPara->voltePara_25Dots), sizeof(voltePara_t_25Dots));
file.close();
if(written != sizeof(voltePara_t_25Dots)) {
LogInfo::setRunStatusText("写入文件VoltDataStd25.bin失败");
}
QMessageBox::information(this, QString("完成"), QString("充电参数已保存并推送至FPGA。"));
}
+66 -66
View File
@@ -1,66 +1,66 @@
#ifndef DLGVOLTEPARA25DOTS_H
#define DLGVOLTEPARA25DOTS_H
#include <QDialog>
#include <QTabWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include "ParaSettingUI.h"
class DevOp;
class DlgVoltePara25Dots : public QDialog, public ParaSettingUI
{
Q_OBJECT
public:
explicit DlgVoltePara25Dots(DevOp *devOp, QWidget *parent = nullptr);
~DlgVoltePara25Dots();
public slots:
void onBtnLoadClicked();
void onBtnSaveClicked();
private:
void setupUI();
QWidget* createGridTab(int count, QLineEdit* edits[], int numCols = 4);
void loadDataToUI();
void saveDataFromUI();
// UI 控件
QTabWidget *tabWidget;
QPushButton *btnLoad;
QPushButton *btnSave;
DevOp *m_devOp;
// 单值64通道 tab
QLineEdit *editContinuous[64]; // 连续点电压 matchContinousDACArray[64]
QLineEdit *editRowDelay[64]; // 点延迟 matchExtraLineDACArray[64]
QLineEdit *editHead1RowDelay[64]; // 首1点延迟 matchFirstOnePointExtraLineDACArray[64]
QLineEdit *editSingleDot[64]; // 单点(首1) matchTotalTableDACArrayFirst1[64]
QLineEdit *edit1Dot[64]; // 一点 matchTotalTableDACArray1[64]
// 多值64通道 tab(每个lineEdit放逗号分隔的多个值)
QLineEdit *edit2Dots[64]; // 两点 matchTotalTableDACArray2[64][2]
QLineEdit *edit3Dots[64]; // 三点 matchTotalTableDACArray3[64][3]
QLineEdit *edit4Dots[64]; // 四点 matchTotalTableDACArray4[64][4]
QLineEdit *edit5Dots[64]; // 五点 matchTotalTableDACArray5[64][5]
// 差分补偿:50组×64通道,每5组一个tab,共10个tab
// 每个tab有64个lineEdit,每个lineEdit放5个逗号分隔值
QLineEdit *editDiff[10][64]; // matchTotalDiffVoltageValue[50][64]
// 巨点补偿:16组×64通道,分4个tab(5,5,5,1组)
// 前3个tab各64个lineEdit(流式切分320值÷5),第4个tab 13个lineEdit(流式切分64值÷5)
QLineEdit *editGiant[4][64]; // matchGiantPointVoltageValue[16][64]
// 通用参数
QLineEdit *editAdjustPara[8]; // matchAdjustParaDACArray[8]
};
#endif // DLGVOLTEPARA25DOTS_H
#ifndef DLGVOLTEPARA25DOTS_H
#define DLGVOLTEPARA25DOTS_H
#include <QDialog>
#include <QTabWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include "ParaSettingUI.h"
class DevOp;
class DlgVoltePara25Dots : public QDialog, public ParaSettingUI
{
Q_OBJECT
public:
explicit DlgVoltePara25Dots(DevOp *devOp, QWidget *parent = nullptr);
~DlgVoltePara25Dots();
public slots:
void onBtnLoadClicked();
void onBtnSaveClicked();
private:
void setupUI();
QWidget* createGridTab(int count, QLineEdit* edits[], int numCols = 4);
void loadDataToUI();
void saveDataFromUI();
// UI 控件
QTabWidget *tabWidget;
QPushButton *btnLoad;
QPushButton *btnSave;
DevOp *m_devOp;
// 单值64通道 tab
QLineEdit *editContinuous[64]; // 连续点电压 matchContinousDACArray[64]
QLineEdit *editRowDelay[64]; // 点延迟 matchExtraLineDACArray[64]
QLineEdit *editHead1RowDelay[64]; // 首1点延迟 matchFirstOnePointExtraLineDACArray[64]
QLineEdit *editSingleDot[64]; // 单点(首1) matchTotalTableDACArrayFirst1[64]
QLineEdit *edit1Dot[64]; // 一点 matchTotalTableDACArray1[64]
// 多值64通道 tab(每个lineEdit放逗号分隔的多个值)
QLineEdit *edit2Dots[64]; // 两点 matchTotalTableDACArray2[64][2]
QLineEdit *edit3Dots[64]; // 三点 matchTotalTableDACArray3[64][3]
QLineEdit *edit4Dots[64]; // 四点 matchTotalTableDACArray4[64][4]
QLineEdit *edit5Dots[64]; // 五点 matchTotalTableDACArray5[64][5]
// 差分补偿:50组×64通道,每5组一个tab,共10个tab
// 每个tab有64个lineEdit,每个lineEdit放5个逗号分隔值
QLineEdit *editDiff[10][64]; // matchTotalDiffVoltageValue[50][64]
// 巨点补偿:16组×64通道,分4个tab(5,5,5,1组)
// 前3个tab各64个lineEdit(流式切分320值÷5),第4个tab 13个lineEdit(流式切分64值÷5)
QLineEdit *editGiant[4][64]; // matchGiantPointVoltageValue[16][64]
// 通用参数
QLineEdit *editAdjustPara[8]; // matchAdjustParaDACArray[8]
};
#endif // DLGVOLTEPARA25DOTS_H
+348 -348
View File
@@ -1,348 +1,348 @@
#include "DlgVolteParaNo73.h"
#include "DevOp.h"
#include <QFile>
DlgVolteParaNo73::DlgVolteParaNo73(DevOp *devOp, QWidget *parent)
: QDialog(parent)
, m_devOp(devOp)
{
memset(editContinuous, 0, sizeof(editContinuous));
memset(editFull, 0, sizeof(editFull));
memset(editFullRowDelay, 0, sizeof(editFullRowDelay));
memset(editRowDelay, 0, sizeof(editRowDelay));
memset(editHead1RowDelay, 0, sizeof(editHead1RowDelay));
memset(edit1Dot, 0, sizeof(edit1Dot));
memset(editOtherAdjust, 0, sizeof(editOtherAdjust));
memset(edit2Dots, 0, sizeof(edit2Dots));
memset(edit3Dots, 0, sizeof(edit3Dots));
memset(edit4Dots, 0, sizeof(edit4Dots));
memset(edit5Dots, 0, sizeof(edit5Dots));
memset(editGap3Dot, 0, sizeof(editGap3Dot));
memset(editGap, 0, sizeof(editGap));
memset(editBigDot, 0, sizeof(editBigDot));
memset(editGeneralPara, 0, sizeof(editGeneralPara));
setupUI();
}
DlgVolteParaNo73::~DlgVolteParaNo73()
{
}
// 创建4列网格布局的tab页(竖排)
QWidget* DlgVolteParaNo73::createGridTab(int count, QLineEdit* edits[])
{
QWidget *page = new QWidget(this);
QGridLayout *grid = new QGridLayout(page);
grid->setSpacing(2);
grid->setContentsMargins(4, 4, 4, 4);
int numCols = 4;
int rowsPerCol = (count + numCols - 1) / numCols;
for (int i = 0; i < count; i++) {
int col = i / rowsPerCol;
int row = i % rowsPerCol;
QLabel *label = new QLabel(QString("v%1").arg(i), page);
label->setFixedWidth(28);
label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
QLineEdit *edit = new QLineEdit("0", page);
edit->setAlignment(Qt::AlignCenter);
edits[i] = edit;
grid->addWidget(label, row, col * 2);
grid->addWidget(edit, row, col * 2 + 1);
}
for (int c = 0; c < numCols; c++) {
grid->setColumnStretch(c * 2, 0);
grid->setColumnStretch(c * 2 + 1, 1);
}
return page;
}
void DlgVolteParaNo73::setupUI()
{
setWindowTitle(QString("No73充电参数编辑"));
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setContentsMargins(4, 4, 4, 4);
mainLayout->setSpacing(4);
tabWidget = new QTabWidget(this);
tabWidget->addTab(createGridTab(48, editContinuous), QString("连续电压"));
tabWidget->addTab(createGridTab(48, editFullRowDelay), QString("满电延迟"));
tabWidget->addTab(createGridTab(48, editRowDelay), QString("点延迟"));
tabWidget->addTab(createGridTab(48, editHead1RowDelay), QString("首1点延迟"));
tabWidget->addTab(createGridTab(48, editOtherAdjust), QString("其他调整"));
tabWidget->addTab(createGridTab(48, editFull), QString("满电"));
tabWidget->addTab(createGridTab(48, edit1Dot), QString("单点"));
tabWidget->addTab(createGridTab(48, edit2Dots), QString("两点"));
tabWidget->addTab(createGridTab(48, edit3Dots), QString("三点"));
tabWidget->addTab(createGridTab(48, edit4Dots), QString("四点"));
tabWidget->addTab(createGridTab(48, edit5Dots), QString("五点"));
tabWidget->addTab(createGridTab(48, editGap3Dot), QString("3_空点"));
tabWidget->addTab(createGridTab(48, editGap), QString("空点"));
tabWidget->addTab(createGridTab(8, editBigDot), QString("巨点"));
tabWidget->addTab(createGridTab(80, editGeneralPara), QString("通用参数"));
mainLayout->addWidget(tabWidget);
// 底部按钮栏
QHBoxLayout *btnLayout = new QHBoxLayout();
btnLoad = new QPushButton(QString("读取当前值"), this);
btnSave = new QPushButton(QString("保存并推送FPGA"), this);
btnLoad->setMinimumHeight(40);
btnSave->setMinimumHeight(40);
btnLayout->addWidget(btnLoad);
btnLayout->addStretch();
btnLayout->addWidget(btnSave);
mainLayout->addLayout(btnLayout);
connect(btnLoad, SIGNAL(clicked()), this, SLOT(onBtnLoadClicked()));
connect(btnSave, SIGNAL(clicked()), this, SLOT(onBtnSaveClicked()));
}
// ========== 数据加载:结构体 → UI ==========
void DlgVolteParaNo73::loadDataToUI()
{
if (!sysPara) return;
voltePara_t_No73 &data = sysPara->voltePara_No73;
// 连续电压
for (int i = 0; i < 48; i++)
editContinuous[i]->setText(QString::number(data.pixel_continous_table[i]));
// 满电延迟
for (int i = 0; i < 48; i++)
editFullRowDelay[i]->setText(QString::number(data.full_row_delay_table[i]));
// 点延迟
for (int i = 0; i < 48; i++)
editRowDelay[i]->setText(QString::number(data.row_delay_table[i]));
// 首1点延迟
for (int i = 0; i < 48; i++)
editHead1RowDelay[i]->setText(QString::number(data.head1_row_delay_table[i]));
// 其他调整:steal,head2,head3,tail2 四个值逗号分隔
for (int i = 0; i < 48; i++) {
editOtherAdjust[i]->setText(QString("%1,%2,%3,%4")
.arg(data.pixel_steal_table[i])
.arg(data.pixel_head2_table[i])
.arg(data.pixel_head3_table[i])
.arg(data.pixel_tail2_table[i]));
}
// 满电
for (int i = 0; i < 48; i++)
editFull[i]->setText(QString::number(data.pixel_full_table[i]));
// 单点
for (int i = 0; i < 48; i++)
edit1Dot[i]->setText(QString::number(data.pixel_1_table[i]));
// 两点(2值逗号分隔)
for (int i = 0; i < 48; i++) {
edit2Dots[i]->setText(QString("%1,%2")
.arg(data.pixel_2_table[i][0])
.arg(data.pixel_2_table[i][1]));
}
// 三点(3值逗号分隔)
for (int i = 0; i < 48; i++) {
edit3Dots[i]->setText(QString("%1,%2,%3")
.arg(data.pixel_3_table[i][0])
.arg(data.pixel_3_table[i][1])
.arg(data.pixel_3_table[i][2]));
}
// 四点(4值逗号分隔)
for (int i = 0; i < 48; i++) {
edit4Dots[i]->setText(QString("%1,%2,%3,%4")
.arg(data.pixel_4_table[i][0])
.arg(data.pixel_4_table[i][1])
.arg(data.pixel_4_table[i][2])
.arg(data.pixel_4_table[i][3]));
}
// 五点(5值逗号分隔)
for (int i = 0; i < 48; i++) {
edit5Dots[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.pixel_5_table[i][0])
.arg(data.pixel_5_table[i][1])
.arg(data.pixel_5_table[i][2])
.arg(data.pixel_5_table[i][3])
.arg(data.pixel_5_table[i][4]));
}
// 3_空点(5值逗号分隔)
for (int i = 0; i < 48; i++) {
editGap3Dot[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.pixel_gap_post_3dot_table[i][0])
.arg(data.pixel_gap_post_3dot_table[i][1])
.arg(data.pixel_gap_post_3dot_table[i][2])
.arg(data.pixel_gap_post_3dot_table[i][3])
.arg(data.pixel_gap_post_3dot_table[i][4]));
}
// 空点(5值逗号分隔)
for (int i = 0; i < 48; i++) {
editGap[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.pixel_gap_table[i][0])
.arg(data.pixel_gap_table[i][1])
.arg(data.pixel_gap_table[i][2])
.arg(data.pixel_gap_table[i][3])
.arg(data.pixel_gap_table[i][4]));
}
// 巨点 pixel_big_table[8][8],每行8个逗号分隔值
for (int i = 0; i < 8; i++) {
QString str;
for (int j = 0; j < 8; j++) {
if (j > 0) str += ",";
str += QString::number((qint8)data.pixel_big_table[i][j]);
}
editBigDot[i]->setText(str);
}
// 通用参数:前16项为pixel_para_table,后64项为pixel_general_dac_parameter
for (int i = 0; i < 16; i++)
editGeneralPara[i]->setText(QString::number(data.pixel_para_table[i]));
for (int i = 0; i < 64; i++)
editGeneralPara[16 + i]->setText(QString::number(data.pixel_general_dac_parameter[i]));
}
// ========== 数据保存:UI → 结构体 ==========
void DlgVolteParaNo73::saveDataFromUI()
{
if (!sysPara) return;
voltePara_t_No73 &data = sysPara->voltePara_No73;
// 连续电压
for (int i = 0; i < 48; i++)
data.pixel_continous_table[i] = (qint16)editContinuous[i]->text().toInt();
// 满电延迟
for (int i = 0; i < 48; i++)
data.full_row_delay_table[i] = (qint16)editFullRowDelay[i]->text().toInt();
// 点延迟
for (int i = 0; i < 48; i++)
data.row_delay_table[i] = (qint16)editRowDelay[i]->text().toInt();
// 首1点延迟
for (int i = 0; i < 48; i++)
data.head1_row_delay_table[i] = (qint16)editHead1RowDelay[i]->text().toInt();
// 其他调整:steal,head2,head3,tail2
for (int i = 0; i < 48; i++) {
QStringList parts = editOtherAdjust[i]->text().split(",");
data.pixel_steal_table[i] = parts.size() > 0 ? (qint16)parts[0].toInt() : 0;
data.pixel_head2_table[i] = parts.size() > 1 ? (qint16)parts[1].toInt() : 0;
data.pixel_head3_table[i] = parts.size() > 2 ? (qint16)parts[2].toInt() : 0;
data.pixel_tail2_table[i] = parts.size() > 3 ? (qint16)parts[3].toInt() : 0;
}
// 满电
for (int i = 0; i < 48; i++)
data.pixel_full_table[i] = (qint16)editFull[i]->text().toInt();
// 单点
for (int i = 0; i < 48; i++)
data.pixel_1_table[i] = (qint16)edit1Dot[i]->text().toInt();
// 两点
for (int i = 0; i < 48; i++) {
QStringList parts = edit2Dots[i]->text().split(",");
for (int j = 0; j < 2; j++)
data.pixel_2_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 三点
for (int i = 0; i < 48; i++) {
QStringList parts = edit3Dots[i]->text().split(",");
for (int j = 0; j < 3; j++)
data.pixel_3_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 四点
for (int i = 0; i < 48; i++) {
QStringList parts = edit4Dots[i]->text().split(",");
for (int j = 0; j < 4; j++)
data.pixel_4_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 五点
for (int i = 0; i < 48; i++) {
QStringList parts = edit5Dots[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.pixel_5_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 3_空点
for (int i = 0; i < 48; i++) {
QStringList parts = editGap3Dot[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.pixel_gap_post_3dot_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 空点
for (int i = 0; i < 48; i++) {
QStringList parts = editGap[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.pixel_gap_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 巨点
for (int i = 0; i < 8; i++) {
QStringList parts = editBigDot[i]->text().split(",");
for (int j = 0; j < 8; j++)
data.pixel_big_table[i][j] = parts.size() > j ? (qint8)parts[j].toInt() : 0;
}
// 通用参数
for (int i = 0; i < 16; i++)
data.pixel_para_table[i] = (qint16)editGeneralPara[i]->text().toInt();
for (int i = 0; i < 64; i++)
data.pixel_general_dac_parameter[i] = (qint16)editGeneralPara[16 + i]->text().toInt();
}
// ========== 按钮槽函数 ==========
void DlgVolteParaNo73::onBtnLoadClicked()
{
loadDataToUI();
}
void DlgVolteParaNo73::onBtnSaveClicked()
{
saveDataFromUI();
QFile file(DOC_ROOT_DIR"voltePara_No73.bin");
if(!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, QString("注意"), QString("充电数据已经写入FPGA, 但是没有保存到文件。"));
return;
}
int written = file.write((const char*)&(sysPara->voltePara_No73), sizeof(voltePara_t_No73));
file.close();
if(written != sizeof(voltePara_t_No73)) {
QMessageBox::information(this, QString("注意"), QString("写入文件voltePara_No73.bin失败"));
}
if (m_devOp) {
m_devOp->writeDacValue2Fpga_No73();
}
QMessageBox::information(this, QString("完成"), QString("充电参数已保存并推送至FPGA。"));
}
#include "DlgVolteParaNo73.h"
#include "DevOp.h"
#include <QFile>
DlgVolteParaNo73::DlgVolteParaNo73(DevOp *devOp, QWidget *parent)
: QDialog(parent)
, m_devOp(devOp)
{
memset(editContinuous, 0, sizeof(editContinuous));
memset(editFull, 0, sizeof(editFull));
memset(editFullRowDelay, 0, sizeof(editFullRowDelay));
memset(editRowDelay, 0, sizeof(editRowDelay));
memset(editHead1RowDelay, 0, sizeof(editHead1RowDelay));
memset(edit1Dot, 0, sizeof(edit1Dot));
memset(editOtherAdjust, 0, sizeof(editOtherAdjust));
memset(edit2Dots, 0, sizeof(edit2Dots));
memset(edit3Dots, 0, sizeof(edit3Dots));
memset(edit4Dots, 0, sizeof(edit4Dots));
memset(edit5Dots, 0, sizeof(edit5Dots));
memset(editGap3Dot, 0, sizeof(editGap3Dot));
memset(editGap, 0, sizeof(editGap));
memset(editBigDot, 0, sizeof(editBigDot));
memset(editGeneralPara, 0, sizeof(editGeneralPara));
setupUI();
}
DlgVolteParaNo73::~DlgVolteParaNo73()
{
}
// 创建4列网格布局的tab页(竖排)
QWidget* DlgVolteParaNo73::createGridTab(int count, QLineEdit* edits[])
{
QWidget *page = new QWidget(this);
QGridLayout *grid = new QGridLayout(page);
grid->setSpacing(2);
grid->setContentsMargins(4, 4, 4, 4);
int numCols = 4;
int rowsPerCol = (count + numCols - 1) / numCols;
for (int i = 0; i < count; i++) {
int col = i / rowsPerCol;
int row = i % rowsPerCol;
QLabel *label = new QLabel(QString("v%1").arg(i), page);
label->setFixedWidth(28);
label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
QLineEdit *edit = new QLineEdit("0", page);
edit->setAlignment(Qt::AlignCenter);
edits[i] = edit;
grid->addWidget(label, row, col * 2);
grid->addWidget(edit, row, col * 2 + 1);
}
for (int c = 0; c < numCols; c++) {
grid->setColumnStretch(c * 2, 0);
grid->setColumnStretch(c * 2 + 1, 1);
}
return page;
}
void DlgVolteParaNo73::setupUI()
{
setWindowTitle(QString("No73充电参数编辑"));
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setContentsMargins(4, 4, 4, 4);
mainLayout->setSpacing(4);
tabWidget = new QTabWidget(this);
tabWidget->addTab(createGridTab(48, editContinuous), QString("连续电压"));
tabWidget->addTab(createGridTab(48, editFullRowDelay), QString("满电延迟"));
tabWidget->addTab(createGridTab(48, editRowDelay), QString("点延迟"));
tabWidget->addTab(createGridTab(48, editHead1RowDelay), QString("首1点延迟"));
tabWidget->addTab(createGridTab(48, editOtherAdjust), QString("其他调整"));
tabWidget->addTab(createGridTab(48, editFull), QString("满电"));
tabWidget->addTab(createGridTab(48, edit1Dot), QString("单点"));
tabWidget->addTab(createGridTab(48, edit2Dots), QString("两点"));
tabWidget->addTab(createGridTab(48, edit3Dots), QString("三点"));
tabWidget->addTab(createGridTab(48, edit4Dots), QString("四点"));
tabWidget->addTab(createGridTab(48, edit5Dots), QString("五点"));
tabWidget->addTab(createGridTab(48, editGap3Dot), QString("3_空点"));
tabWidget->addTab(createGridTab(48, editGap), QString("空点"));
tabWidget->addTab(createGridTab(8, editBigDot), QString("巨点"));
tabWidget->addTab(createGridTab(80, editGeneralPara), QString("通用参数"));
mainLayout->addWidget(tabWidget);
// 底部按钮栏
QHBoxLayout *btnLayout = new QHBoxLayout();
btnLoad = new QPushButton(QString("读取当前值"), this);
btnSave = new QPushButton(QString("保存并推送FPGA"), this);
btnLoad->setMinimumHeight(40);
btnSave->setMinimumHeight(40);
btnLayout->addWidget(btnLoad);
btnLayout->addStretch();
btnLayout->addWidget(btnSave);
mainLayout->addLayout(btnLayout);
connect(btnLoad, SIGNAL(clicked()), this, SLOT(onBtnLoadClicked()));
connect(btnSave, SIGNAL(clicked()), this, SLOT(onBtnSaveClicked()));
}
// ========== 数据加载:结构体 → UI ==========
void DlgVolteParaNo73::loadDataToUI()
{
if (!sysPara) return;
voltePara_t_No73 &data = sysPara->voltePara_No73;
// 连续电压
for (int i = 0; i < 48; i++)
editContinuous[i]->setText(QString::number(data.pixel_continous_table[i]));
// 满电延迟
for (int i = 0; i < 48; i++)
editFullRowDelay[i]->setText(QString::number(data.full_row_delay_table[i]));
// 点延迟
for (int i = 0; i < 48; i++)
editRowDelay[i]->setText(QString::number(data.row_delay_table[i]));
// 首1点延迟
for (int i = 0; i < 48; i++)
editHead1RowDelay[i]->setText(QString::number(data.head1_row_delay_table[i]));
// 其他调整:steal,head2,head3,tail2 四个值逗号分隔
for (int i = 0; i < 48; i++) {
editOtherAdjust[i]->setText(QString("%1,%2,%3,%4")
.arg(data.pixel_steal_table[i])
.arg(data.pixel_head2_table[i])
.arg(data.pixel_head3_table[i])
.arg(data.pixel_tail2_table[i]));
}
// 满电
for (int i = 0; i < 48; i++)
editFull[i]->setText(QString::number(data.pixel_full_table[i]));
// 单点
for (int i = 0; i < 48; i++)
edit1Dot[i]->setText(QString::number(data.pixel_1_table[i]));
// 两点(2值逗号分隔)
for (int i = 0; i < 48; i++) {
edit2Dots[i]->setText(QString("%1,%2")
.arg(data.pixel_2_table[i][0])
.arg(data.pixel_2_table[i][1]));
}
// 三点(3值逗号分隔)
for (int i = 0; i < 48; i++) {
edit3Dots[i]->setText(QString("%1,%2,%3")
.arg(data.pixel_3_table[i][0])
.arg(data.pixel_3_table[i][1])
.arg(data.pixel_3_table[i][2]));
}
// 四点(4值逗号分隔)
for (int i = 0; i < 48; i++) {
edit4Dots[i]->setText(QString("%1,%2,%3,%4")
.arg(data.pixel_4_table[i][0])
.arg(data.pixel_4_table[i][1])
.arg(data.pixel_4_table[i][2])
.arg(data.pixel_4_table[i][3]));
}
// 五点(5值逗号分隔)
for (int i = 0; i < 48; i++) {
edit5Dots[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.pixel_5_table[i][0])
.arg(data.pixel_5_table[i][1])
.arg(data.pixel_5_table[i][2])
.arg(data.pixel_5_table[i][3])
.arg(data.pixel_5_table[i][4]));
}
// 3_空点(5值逗号分隔)
for (int i = 0; i < 48; i++) {
editGap3Dot[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.pixel_gap_post_3dot_table[i][0])
.arg(data.pixel_gap_post_3dot_table[i][1])
.arg(data.pixel_gap_post_3dot_table[i][2])
.arg(data.pixel_gap_post_3dot_table[i][3])
.arg(data.pixel_gap_post_3dot_table[i][4]));
}
// 空点(5值逗号分隔)
for (int i = 0; i < 48; i++) {
editGap[i]->setText(QString("%1,%2,%3,%4,%5")
.arg(data.pixel_gap_table[i][0])
.arg(data.pixel_gap_table[i][1])
.arg(data.pixel_gap_table[i][2])
.arg(data.pixel_gap_table[i][3])
.arg(data.pixel_gap_table[i][4]));
}
// 巨点 pixel_big_table[8][8],每行8个逗号分隔值
for (int i = 0; i < 8; i++) {
QString str;
for (int j = 0; j < 8; j++) {
if (j > 0) str += ",";
str += QString::number((qint8)data.pixel_big_table[i][j]);
}
editBigDot[i]->setText(str);
}
// 通用参数:前16项为pixel_para_table,后64项为pixel_general_dac_parameter
for (int i = 0; i < 16; i++)
editGeneralPara[i]->setText(QString::number(data.pixel_para_table[i]));
for (int i = 0; i < 64; i++)
editGeneralPara[16 + i]->setText(QString::number(data.pixel_general_dac_parameter[i]));
}
// ========== 数据保存:UI → 结构体 ==========
void DlgVolteParaNo73::saveDataFromUI()
{
if (!sysPara) return;
voltePara_t_No73 &data = sysPara->voltePara_No73;
// 连续电压
for (int i = 0; i < 48; i++)
data.pixel_continous_table[i] = (qint16)editContinuous[i]->text().toInt();
// 满电延迟
for (int i = 0; i < 48; i++)
data.full_row_delay_table[i] = (qint16)editFullRowDelay[i]->text().toInt();
// 点延迟
for (int i = 0; i < 48; i++)
data.row_delay_table[i] = (qint16)editRowDelay[i]->text().toInt();
// 首1点延迟
for (int i = 0; i < 48; i++)
data.head1_row_delay_table[i] = (qint16)editHead1RowDelay[i]->text().toInt();
// 其他调整:steal,head2,head3,tail2
for (int i = 0; i < 48; i++) {
QStringList parts = editOtherAdjust[i]->text().split(",");
data.pixel_steal_table[i] = parts.size() > 0 ? (qint16)parts[0].toInt() : 0;
data.pixel_head2_table[i] = parts.size() > 1 ? (qint16)parts[1].toInt() : 0;
data.pixel_head3_table[i] = parts.size() > 2 ? (qint16)parts[2].toInt() : 0;
data.pixel_tail2_table[i] = parts.size() > 3 ? (qint16)parts[3].toInt() : 0;
}
// 满电
for (int i = 0; i < 48; i++)
data.pixel_full_table[i] = (qint16)editFull[i]->text().toInt();
// 单点
for (int i = 0; i < 48; i++)
data.pixel_1_table[i] = (qint16)edit1Dot[i]->text().toInt();
// 两点
for (int i = 0; i < 48; i++) {
QStringList parts = edit2Dots[i]->text().split(",");
for (int j = 0; j < 2; j++)
data.pixel_2_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 三点
for (int i = 0; i < 48; i++) {
QStringList parts = edit3Dots[i]->text().split(",");
for (int j = 0; j < 3; j++)
data.pixel_3_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 四点
for (int i = 0; i < 48; i++) {
QStringList parts = edit4Dots[i]->text().split(",");
for (int j = 0; j < 4; j++)
data.pixel_4_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 五点
for (int i = 0; i < 48; i++) {
QStringList parts = edit5Dots[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.pixel_5_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 3_空点
for (int i = 0; i < 48; i++) {
QStringList parts = editGap3Dot[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.pixel_gap_post_3dot_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 空点
for (int i = 0; i < 48; i++) {
QStringList parts = editGap[i]->text().split(",");
for (int j = 0; j < 5; j++)
data.pixel_gap_table[i][j] = parts.size() > j ? (qint16)parts[j].toInt() : 0;
}
// 巨点
for (int i = 0; i < 8; i++) {
QStringList parts = editBigDot[i]->text().split(",");
for (int j = 0; j < 8; j++)
data.pixel_big_table[i][j] = parts.size() > j ? (qint8)parts[j].toInt() : 0;
}
// 通用参数
for (int i = 0; i < 16; i++)
data.pixel_para_table[i] = (qint16)editGeneralPara[i]->text().toInt();
for (int i = 0; i < 64; i++)
data.pixel_general_dac_parameter[i] = (qint16)editGeneralPara[16 + i]->text().toInt();
}
// ========== 按钮槽函数 ==========
void DlgVolteParaNo73::onBtnLoadClicked()
{
loadDataToUI();
}
void DlgVolteParaNo73::onBtnSaveClicked()
{
saveDataFromUI();
QFile file(DOC_ROOT_DIR"voltePara_No73.bin");
if(!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, QString("注意"), QString("充电数据已经写入FPGA, 但是没有保存到文件。"));
return;
}
int written = file.write((const char*)&(sysPara->voltePara_No73), sizeof(voltePara_t_No73));
file.close();
if(written != sizeof(voltePara_t_No73)) {
QMessageBox::information(this, QString("注意"), QString("写入文件voltePara_No73.bin失败"));
}
if (m_devOp) {
m_devOp->writeDacValue2Fpga_No73();
}
QMessageBox::information(this, QString("完成"), QString("充电参数已保存并推送至FPGA。"));
}
+68 -68
View File
@@ -1,68 +1,68 @@
#ifndef DLGVOLTEPARANO73_H
#define DLGVOLTEPARANO73_H
#include <QDialog>
#include <QTabWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include "ParaSettingUI.h"
class DevOp;
class DlgVolteParaNo73 : public QDialog, public ParaSettingUI
{
Q_OBJECT
public:
explicit DlgVolteParaNo73(DevOp *devOp, QWidget *parent = nullptr);
~DlgVolteParaNo73();
public slots:
void onBtnLoadClicked();
void onBtnSaveClicked();
private:
void setupUI();
QWidget* createGridTab(int count, QLineEdit* edits[]);
void loadDataToUI();
void saveDataFromUI();
// UI 控件
QTabWidget *tabWidget;
QPushButton *btnLoad;
QPushButton *btnSave;
DevOp *m_devOp;
// 单值48通道 tab
QLineEdit *editContinuous[48]; // 连续电压 pixel_continous_table[48]
QLineEdit *editFull[48]; // 满电 pixel_full_table[48]
QLineEdit *editFullRowDelay[48]; // 满电延迟 full_row_delay_table[48]
QLineEdit *editRowDelay[48]; // 点延迟 row_delay_table[48]
QLineEdit *editHead1RowDelay[48]; // 首1点延迟 head1_row_delay_table[48]
QLineEdit *edit1Dot[48]; // 单点 pixel_1_table[48]
// 其他调整:pixel_steal_table[48], pixel_head2_table[48], pixel_head3_table[48], pixel_tail2_table[48]
// 每个lineEdit放4个逗号分隔值(steal,head2,head3,tail2)
QLineEdit *editOtherAdjust[48];
// 多值48通道 tab
QLineEdit *edit2Dots[48]; // 两点 pixel_2_table[48][2]
QLineEdit *edit3Dots[48]; // 三点 pixel_3_table[48][3]
QLineEdit *edit4Dots[48]; // 四点 pixel_4_table[48][4]
QLineEdit *edit5Dots[48]; // 五点 pixel_5_table[48][5]
QLineEdit *editGap3Dot[48]; // 3_空点 pixel_gap_post_3dot_table[48][5]
QLineEdit *editGap[48]; // 空点 pixel_gap_table[48][5]
// 巨点 pixel_big_table[8][8],8行每行8个逗号分隔值
QLineEdit *editBigDot[8];
// 通用参数 pixel_para_table[16] + pixel_general_dac_parameter[64],共80项
QLineEdit *editGeneralPara[80];
};
#endif // DLGVOLTEPARANO73_H
#ifndef DLGVOLTEPARANO73_H
#define DLGVOLTEPARANO73_H
#include <QDialog>
#include <QTabWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include "ParaSettingUI.h"
class DevOp;
class DlgVolteParaNo73 : public QDialog, public ParaSettingUI
{
Q_OBJECT
public:
explicit DlgVolteParaNo73(DevOp *devOp, QWidget *parent = nullptr);
~DlgVolteParaNo73();
public slots:
void onBtnLoadClicked();
void onBtnSaveClicked();
private:
void setupUI();
QWidget* createGridTab(int count, QLineEdit* edits[]);
void loadDataToUI();
void saveDataFromUI();
// UI 控件
QTabWidget *tabWidget;
QPushButton *btnLoad;
QPushButton *btnSave;
DevOp *m_devOp;
// 单值48通道 tab
QLineEdit *editContinuous[48]; // 连续电压 pixel_continous_table[48]
QLineEdit *editFull[48]; // 满电 pixel_full_table[48]
QLineEdit *editFullRowDelay[48]; // 满电延迟 full_row_delay_table[48]
QLineEdit *editRowDelay[48]; // 点延迟 row_delay_table[48]
QLineEdit *editHead1RowDelay[48]; // 首1点延迟 head1_row_delay_table[48]
QLineEdit *edit1Dot[48]; // 单点 pixel_1_table[48]
// 其他调整:pixel_steal_table[48], pixel_head2_table[48], pixel_head3_table[48], pixel_tail2_table[48]
// 每个lineEdit放4个逗号分隔值(steal,head2,head3,tail2)
QLineEdit *editOtherAdjust[48];
// 多值48通道 tab
QLineEdit *edit2Dots[48]; // 两点 pixel_2_table[48][2]
QLineEdit *edit3Dots[48]; // 三点 pixel_3_table[48][3]
QLineEdit *edit4Dots[48]; // 四点 pixel_4_table[48][4]
QLineEdit *edit5Dots[48]; // 五点 pixel_5_table[48][5]
QLineEdit *editGap3Dot[48]; // 3_空点 pixel_gap_post_3dot_table[48][5]
QLineEdit *editGap[48]; // 空点 pixel_gap_table[48][5]
// 巨点 pixel_big_table[8][8],8行每行8个逗号分隔值
QLineEdit *editBigDot[8];
// 通用参数 pixel_para_table[16] + pixel_general_dac_parameter[64],共80项
QLineEdit *editGeneralPara[80];
};
#endif // DLGVOLTEPARANO73_H
+3873 -3873
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1 +1 @@
ref: refs/heads/master
ref: refs/heads/master
+36 -36
View File
@@ -1,36 +1,36 @@
#include "HtmlDelegate.h"
HtmlDelegate::HtmlDelegate(QObject *parent) : QAbstractItemDelegate(parent){}
//HtmlDelegate::HtmlDelegate(QObject *parent = nullptr) : QAbstractItemDelegate(parent) {}
void HtmlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
QString html = index.model()->data(index, Qt::DisplayRole).toString();
QTextDocument doc;
doc.setHtml(html);
doc.setTextWidth(option.rect.width());
painter->save();
painter->setClipRect(option.rect);
if (option.state & QStyle::State_Selected) {
// 绘制选中项的背景颜色
painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));
}
painter->translate(option.rect.topLeft());
doc.drawContents(painter, QRectF(QPointF(0, 0), QSizeF(option.rect.size())));
painter->restore();
}
QSize HtmlDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
QString html = index.model()->data(index, Qt::DisplayRole).toString();
QTextDocument doc;
doc.setHtml(html);
doc.setTextWidth(option.rect.width());
return QSize(doc.idealWidth(), doc.size().height());
}
#include "HtmlDelegate.h"
HtmlDelegate::HtmlDelegate(QObject *parent) : QAbstractItemDelegate(parent){}
//HtmlDelegate::HtmlDelegate(QObject *parent = nullptr) : QAbstractItemDelegate(parent) {}
void HtmlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
QString html = index.model()->data(index, Qt::DisplayRole).toString();
QTextDocument doc;
doc.setHtml(html);
doc.setTextWidth(option.rect.width());
painter->save();
painter->setClipRect(option.rect);
if (option.state & QStyle::State_Selected) {
// 绘制选中项的背景颜色
painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));
}
painter->translate(option.rect.topLeft());
doc.drawContents(painter, QRectF(QPointF(0, 0), QSizeF(option.rect.size())));
painter->restore();
}
QSize HtmlDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
QString html = index.model()->data(index, Qt::DisplayRole).toString();
QTextDocument doc;
doc.setHtml(html);
doc.setTextWidth(option.rect.width());
return QSize(doc.idealWidth(), doc.size().height());
}
+23 -23
View File
@@ -1,23 +1,23 @@
#ifndef HTMLDELEGATE_H
#define HTMLDELEGATE_H
#include <QAbstractItemDelegate>
#include <QWidget>
#include <QPainter>
#include <QTextDocument>
class HtmlDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
explicit HtmlDelegate(QObject *parent = 0);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
signals:
public slots:
};
#endif // HTMLDELEGATE_H
#ifndef HTMLDELEGATE_H
#define HTMLDELEGATE_H
#include <QAbstractItemDelegate>
#include <QWidget>
#include <QPainter>
#include <QTextDocument>
class HtmlDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
explicit HtmlDelegate(QObject *parent = 0);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
signals:
public slots:
};
#endif // HTMLDELEGATE_H
+66
View File
@@ -325,6 +325,7 @@ InkJetPrinter::InkJetPrinter(QWidget *parent) :
removeTab(indexOf(ui->tabDacAdjust));
removeTab(indexOf(ui->tabFpgaDebug));
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tab_3));
removeTab(indexOf(ui->tab_pressure));
ui->vol0SpinBox->setMinimum(0);
ui->vol1SpinBox->setMinimum(0);
@@ -723,6 +724,63 @@ void InkJetPrinter::initCntGroup()
SectionalManager::instance(), &SectionalManager::sig_updateCntGroupDisp);
}
void InkJetPrinter::appendPressureRecord(int pressure, int targetPressure)
{
QTextBrowser *browser = ui->textBrowser; // tab_pressure 里的控件
if (!browser) return;
QString line = QString("[%1] 压力:%2 / 目标:%3 %4")
.arg(QDateTime::currentDateTime().toString("hh:mm:ss.zzz"))
.arg(pressure)
.arg(targetPressure)
.arg(getValvePumpStatusString());
appendLineToBrowser(line);
if (pressure > 700) {
if (!m_pressureAlarmActive) {
m_pressureAlarmActive = true;
QMessageBox::warning(this, tr("超压报警"),
tr("当前压力 %1 超过 700!").arg(pressure));
}
} else {
m_pressureAlarmActive = false;
}
}
void InkJetPrinter::appendLineToBrowser(const QString &line)
{
QTextBrowser *browser = ui->textBrowser;
if (!browser) return;
browser->append(line);
if (browser->document()->blockCount() > 500) {
QTextCursor cursor(browser->document());
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor,
browser->document()->blockCount() - 500);
cursor.removeSelectedText();
}
}
static int numLine = 0;
QString InkJetPrinter::getValvePumpStatusString()
{
if (!sysPara || !sysPara->devOp) return QString();
return QString("[供墨:%1 循环:%2 混合:%3 泄压:%4 回收:%5 粘度:%6 主墨:%7 压缩:%8]-%9")
.arg(sysPara->devOp->isInkValveOpen() ? 1 : 0)
.arg(sysPara->devOp->isCycleValveOpen() ? 1 : 0)
.arg(sysPara->devOp->isMixValveOpen() ? 1 : 0)
.arg(sysPara->devOp->isReleaseValveOpen() ? 1 : 0)
.arg(sysPara->devOp->isReclaimPumpOpen() ? 1 : 0)
.arg(sysPara->devOp->isViscosityPumpOpen() ? 1 : 0)
.arg(sysPara->devOp->isMainInkPumpOpen() ? 1 : 0)
.arg(sysPara->devOp->isCompressPumpOpen() ? 1 : 0)
.arg(numLine++);
}
float PID_realize(float speed);
struct _pid{
@@ -1774,6 +1832,14 @@ void InkJetPrinter::timerHandler(void){
if(widget == ui->tabMainWindow && pulse_100ms) {
ui->tabMainWindow->updateSysStatusToUI();
}
// if (pulse_100ms &&
// (sysPara->status.PRESSURE > sysPara->para.pressure + 10
// ||sysPara->status.PRESSURE < sysPara->para.pressure - 10)) {
// //压力记录
// appendPressureRecord(sysPara->status.PRESSURE, sysPara->para.pressure);
// }
else if(widget == ui->tabTriggerMode){
ui->tabTriggerMode->updateSysStatusToUI();
if(sysPara->status.fpgaVersionNum != 0){
+5
View File
@@ -203,6 +203,11 @@ private:
unsigned char rWarnViscoReady;
void initCntGroup();
// 压力记录
bool m_pressureAlarmActive = false;
void appendPressureRecord(int pressure, int targetPressure);
void appendLineToBrowser(const QString &line);
QString getValvePumpStatusString();
public:
bool eventFilter(QObject *watched, QEvent *event);
};
+1748 -1748
View File
File diff suppressed because it is too large Load Diff
+161 -161
View File
@@ -1,161 +1,161 @@
#ifndef INPUTMETHOD_H
#define INPUTMETHOD_H
#include <QWidget>
#include <QHash>
#include <QMap>
#include <QList>
#include <QLabel>
#include <QTextEdit>
#include <ClickLabel.h>
#include <QStringList>
#include <QTimer>
#include "InsertSpaceNumDialog.h"
#include "myinclude.h"
class MyInputMethod;
namespace Ui {
class InputMethod;
}
#define HANZI_SELECT_NUM 5 //显示汉字的个数,由UI文件决定
#define INPUT_METHOD_TYPE_ENGLISH 0
#define INPUT_METHOD_TYPE_CHINESE 1
#define INPUT_METHOD_TYPE_VIETNAM 2
#define INPUT_METHOD_TYPE_RUSSIAN 3 // Russian
#define INPUT_METHOD_TYPE_JAPANESE 4 //Japanese
#define INPUT_METHOD_TYPE_KOREAN 5 // Korean
#define INPUT_METHOD_TYPE_SPANISH 6 // Korean
#define INPUT_METHOD_TYPE_THAI 7 // Thai
#define INPUT_METHOD_TYPE_Farsi 8
#define INPUT_FILE_CHINESE "WINPY_utf8.txt"
#define INPUT_FILE_ENGLISH "WINPY_utf8.txt"
#define INPUT_FILE_VIETNAM "YN_utf8.txt"
#define INPUT_FILE_RUSSIAN "WINPY_utf8.txt"
#define INPUT_FILE_JAPANESE "WINPY_utf8.txt"
#define INPUT_FILE_KOREAN "WINPY_utf8.txt"
#define MIN(a,b) (((a) < (b))?(a):(b))
#define MAX(a,b) (((a) > (b))?(a):(b))
class InputMethod : public QWidget
{
Q_OBJECT
public:
explicit InputMethod(MyInputMethod *myInputMethod,QWidget *parent = 0);
static bool initInputMethod(QString &filename); /*用文件初始化输入法的字库*/
static void showPinyinHash(void);
~InputMethod();
void switchKeyBoardBengalDisply(bool);
void switchKeyBoardBengalLowerLetters();
void switchKeyBoardBengalCapitalLetters();
void switchKeyBoardBengalDigit();
#ifdef EnableArabic
void setArabicDisplay(bool);
void showArabicPage1Key();
void showArabicPage2Key();
void showEnglishKey();
void showArabicPage3Key();
void setSwitchArabicFlag(bool flag);
#endif
public slots:
void onpushButtonCapspressed();
void onDigitalPunctuationClicked();
void onCharClicked();
void onShiftClicked();
void onInputMethodClicked();
void onBackspaceClicked();
void onHanziLabelClicked();
void onKeyLastClicked();
void onKeyNextClicked();
void onEnterClicked();
void userInputed(QString str); //用户输入一个字符
void onHiden();
void on_Key_Backspace_released();
private slots:
void onKeyLeftpressed();
void onKeyDownpressed();
void onKeyUppressed();
void onKeyRightpressed();
void onKeyHomepressed();
void onKeyEndpressed();
void onKeydeletepressed();
void onKeySpecialCharpressed();
void onKeyCtrlpressed();
void onKeyReleased();
void onKeyPressed();
void spaceKeyPressed();
void spaceKeyRelease();
void spaceKeyLongPressed();
void backKeyLongPressed();
void onInsertSpaceNumDialogAccepted();
void on_pushBottonHide_released();
void on_Key_Backspace_pressed();
//void on_Key_Backspace_released();
private:
MyInputMethod *myInputMethod;
QMap<QString,QString> keyMap;
Ui::InputMethod *ui;
static QHash<QString,QList<QString> *> *pinyinHash; //用来存放哈拼音的哈希表,所有都共用一份
static QList <QString> pinyinHashKeys;
static QStringList pinyinHashQStringList;
QList <QString> *currPinyinList;
QStringList currPinyins; //自动侯选的拼音
ClickLabel *hanziDisplayLabels[HANZI_SELECT_NUM];
int currentInputMethodType;
int matchStartIndex;
int matchEndIndex;
int bNotFound;
bool shiftFlag; //是否按过shift键
bool CapsFlag;
bool userPinyinInputAppending; //是否用户已经在拼音输入法下完成输入
QString currPinyinStr; //记录当前用户已经输入的字符
int pinyinPage; /*当一个拼音有很多汉字时,分多页存放,记录当前的页数*/
int back_count_timeout; //回退键超时处理
bool bengalFlag;
bool CtrlFlag;
#ifdef EnableArabic
bool arabicFlag;
bool englishOrArabicFlag;
#endif
void switchKeyboardDisplay(void); //当按shift,输入法时,切换键盘显示
void displayHanziToLabel(); //显示汉字到label
void fillPinyinLabel(bool bActFromCharInput);
void asciiTyped(int ascii);
void digitalTyped(int ascii);
void buttonConnect(QPushButton *sender,
const QObject *receiver, const char *member);
void setHanziLabelVisible(bool enable);
QLabel labelInputTip; //输入提示
QTimer spaceTimer;
QTimer backtimer;
InsertSpaceNumDialog insertSpaceNumDialog;
bool hanZiLabelVisibleEnable;
bool ctrlAppending;//Ctrl+C ..之类的
QString specialKeyMap(QString ch);
};
#endif // INPUTMETHOD_H
#ifndef INPUTMETHOD_H
#define INPUTMETHOD_H
#include <QWidget>
#include <QHash>
#include <QMap>
#include <QList>
#include <QLabel>
#include <QTextEdit>
#include <ClickLabel.h>
#include <QStringList>
#include <QTimer>
#include "InsertSpaceNumDialog.h"
#include "myinclude.h"
class MyInputMethod;
namespace Ui {
class InputMethod;
}
#define HANZI_SELECT_NUM 5 //显示汉字的个数,由UI文件决定
#define INPUT_METHOD_TYPE_ENGLISH 0
#define INPUT_METHOD_TYPE_CHINESE 1
#define INPUT_METHOD_TYPE_VIETNAM 2
#define INPUT_METHOD_TYPE_RUSSIAN 3 // Russian
#define INPUT_METHOD_TYPE_JAPANESE 4 //Japanese
#define INPUT_METHOD_TYPE_KOREAN 5 // Korean
#define INPUT_METHOD_TYPE_SPANISH 6 // Korean
#define INPUT_METHOD_TYPE_THAI 7 // Thai
#define INPUT_METHOD_TYPE_Farsi 8
#define INPUT_FILE_CHINESE "WINPY_utf8.txt"
#define INPUT_FILE_ENGLISH "WINPY_utf8.txt"
#define INPUT_FILE_VIETNAM "YN_utf8.txt"
#define INPUT_FILE_RUSSIAN "WINPY_utf8.txt"
#define INPUT_FILE_JAPANESE "WINPY_utf8.txt"
#define INPUT_FILE_KOREAN "WINPY_utf8.txt"
#define MIN(a,b) (((a) < (b))?(a):(b))
#define MAX(a,b) (((a) > (b))?(a):(b))
class InputMethod : public QWidget
{
Q_OBJECT
public:
explicit InputMethod(MyInputMethod *myInputMethod,QWidget *parent = 0);
static bool initInputMethod(QString &filename); /*用文件初始化输入法的字库*/
static void showPinyinHash(void);
~InputMethod();
void switchKeyBoardBengalDisply(bool);
void switchKeyBoardBengalLowerLetters();
void switchKeyBoardBengalCapitalLetters();
void switchKeyBoardBengalDigit();
#ifdef EnableArabic
void setArabicDisplay(bool);
void showArabicPage1Key();
void showArabicPage2Key();
void showEnglishKey();
void showArabicPage3Key();
void setSwitchArabicFlag(bool flag);
#endif
public slots:
void onpushButtonCapspressed();
void onDigitalPunctuationClicked();
void onCharClicked();
void onShiftClicked();
void onInputMethodClicked();
void onBackspaceClicked();
void onHanziLabelClicked();
void onKeyLastClicked();
void onKeyNextClicked();
void onEnterClicked();
void userInputed(QString str); //用户输入一个字符
void onHiden();
void on_Key_Backspace_released();
private slots:
void onKeyLeftpressed();
void onKeyDownpressed();
void onKeyUppressed();
void onKeyRightpressed();
void onKeyHomepressed();
void onKeyEndpressed();
void onKeydeletepressed();
void onKeySpecialCharpressed();
void onKeyCtrlpressed();
void onKeyReleased();
void onKeyPressed();
void spaceKeyPressed();
void spaceKeyRelease();
void spaceKeyLongPressed();
void backKeyLongPressed();
void onInsertSpaceNumDialogAccepted();
void on_pushBottonHide_released();
void on_Key_Backspace_pressed();
//void on_Key_Backspace_released();
private:
MyInputMethod *myInputMethod;
QMap<QString,QString> keyMap;
Ui::InputMethod *ui;
static QHash<QString,QList<QString> *> *pinyinHash; //用来存放哈拼音的哈希表,所有都共用一份
static QList <QString> pinyinHashKeys;
static QStringList pinyinHashQStringList;
QList <QString> *currPinyinList;
QStringList currPinyins; //自动侯选的拼音
ClickLabel *hanziDisplayLabels[HANZI_SELECT_NUM];
int currentInputMethodType;
int matchStartIndex;
int matchEndIndex;
int bNotFound;
bool shiftFlag; //是否按过shift键
bool CapsFlag;
bool userPinyinInputAppending; //是否用户已经在拼音输入法下完成输入
QString currPinyinStr; //记录当前用户已经输入的字符
int pinyinPage; /*当一个拼音有很多汉字时,分多页存放,记录当前的页数*/
int back_count_timeout; //回退键超时处理
bool bengalFlag;
bool CtrlFlag;
#ifdef EnableArabic
bool arabicFlag;
bool englishOrArabicFlag;
#endif
void switchKeyboardDisplay(void); //当按shift,输入法时,切换键盘显示
void displayHanziToLabel(); //显示汉字到label
void fillPinyinLabel(bool bActFromCharInput);
void asciiTyped(int ascii);
void digitalTyped(int ascii);
void buttonConnect(QPushButton *sender,
const QObject *receiver, const char *member);
void setHanziLabelVisible(bool enable);
QLabel labelInputTip; //输入提示
QTimer spaceTimer;
QTimer backtimer;
InsertSpaceNumDialog insertSpaceNumDialog;
bool hanZiLabelVisibleEnable;
bool ctrlAppending;//Ctrl+C ..之类的
QString specialKeyMap(QString ch);
};
#endif // INPUTMETHOD_H
+2851 -2851
View File
File diff suppressed because it is too large Load Diff
+19 -19
View File
@@ -1,19 +1,19 @@
#include "InsertSpaceNumDialog.h"
#include "ui_insertspacenumdialog.h"
InsertSpaceNumDialog::InsertSpaceNumDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::InsertSpaceNumDialog)
{
ui->setupUi(this);
this->setFixedSize(this->geometry().width(),this->geometry().height());
}
InsertSpaceNumDialog::~InsertSpaceNumDialog()
{
delete ui;
}
QSpinBox *InsertSpaceNumDialog::getSpinBoxSpaceNum(){
return ui->spinBoxSpaceNum;
}
#include "InsertSpaceNumDialog.h"
#include "ui_insertspacenumdialog.h"
InsertSpaceNumDialog::InsertSpaceNumDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::InsertSpaceNumDialog)
{
ui->setupUi(this);
this->setFixedSize(this->geometry().width(),this->geometry().height());
}
InsertSpaceNumDialog::~InsertSpaceNumDialog()
{
delete ui;
}
QSpinBox *InsertSpaceNumDialog::getSpinBoxSpaceNum(){
return ui->spinBoxSpaceNum;
}
+22 -22
View File
@@ -1,22 +1,22 @@
#ifndef INSERTSPACENUMDIALOG_H
#define INSERTSPACENUMDIALOG_H
#include <QDialog>
#include <QSpinBox>
namespace Ui {
class InsertSpaceNumDialog;
}
class InsertSpaceNumDialog : public QDialog
{
Q_OBJECT
public:
explicit InsertSpaceNumDialog(QWidget *parent = 0);
~InsertSpaceNumDialog();
QSpinBox *getSpinBoxSpaceNum();
private:
Ui::InsertSpaceNumDialog *ui;
};
#endif // INSERTSPACENUMDIALOG_H
#ifndef INSERTSPACENUMDIALOG_H
#define INSERTSPACENUMDIALOG_H
#include <QDialog>
#include <QSpinBox>
namespace Ui {
class InsertSpaceNumDialog;
}
class InsertSpaceNumDialog : public QDialog
{
Q_OBJECT
public:
explicit InsertSpaceNumDialog(QWidget *parent = 0);
~InsertSpaceNumDialog();
QSpinBox *getSpinBoxSpaceNum();
private:
Ui::InsertSpaceNumDialog *ui;
};
#endif // INSERTSPACENUMDIALOG_H
+438 -438
View File
@@ -1,438 +1,438 @@
#include "LicenseManger.h"
#include "dlginputaddr.h"
#include <QFile>
#include <QMessageBox>
#include <QDate>
#include <QDateEdit>
#include <time.h>
#include <QDebug>
#include <QTime>
#include <QDate>
#include "qnamespace.h"
#include <QtCore/QCoreApplication>
#include <QCryptographicHash>
MACHINE_INFO_t machine_info;
LICENSE_DATA_t license_data;
QMutex machine_info_mutex;
QMutex license_data_mutex;
void adjustDateAndTime(int year, int mon, int mday, int hour, int min, int sec);
LicenseManger::LicenseManger()
{
#if 1
UCHAR e_key[1024] = "dangerous IOP 0908 ";
pAes = new TAesClass;
pAes->InitializePrivateKey(16, e_key); //进行初始化
//setMachineInfo(16);
#endif
}
//set machine info
qint32 LicenseManger::setMachineInfo(quint32 serial_num)
{
//check serial number size
if(serial_num>999999)
{
return -1;
}
machine_info_mutex.lock();
QString serial;
serial.sprintf("VB%06d", serial_num);
QByteArray hash_data;
hash_data = QCryptographicHash::hash(serial.toAscii(),QCryptographicHash::Md5 );
//MACHINE_INFO_t machine_info;
machine_info.serial_number=serial_num;
memcpy(&machine_info.md5[0],hash_data.data(),MD5_LENGTH);
//qDebug()<<"org sn info"<<machine_info.serial_number;
//qDebug()<<"org machine md5 size"<<sizeof(machine_info.md5);
#if 0
QString md5;
md5.append(hash_data);
qDebug()<<"org machine md5 "<<md5;
for(int i=0;i<16;i++)
{
qDebug()<<tr("org md5[%1]").arg(i)<<machine_info.md5[i];
}
#endif
#if 1
char encrypt_buff[1024];
QFile file(MACH_INFO_FILE);
//encrypt the data then write to file
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
file.seek(0);
pAes->OnAesEncrypt((LPVOID)&machine_info, sizeof(machine_info), (LPVOID)encrypt_buff); //进行加密
//qDebug()<<"sn jiami:"<<encrypt_buff;
file.write((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
file.close();
#else
QFile file(MACH_INFO_FILE);
//encrypt the data then write to file
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
file.seek(0);
file.write((char *)&machine_info,(qint64)sizeof(machine_info));
file.close();
#endif
machine_info_mutex.unlock();
return 0;
}
// check machine info from flash is available
qint32 LicenseManger::checkMachineInfoAvailable()
{
static bool bmachine_info_availble;
QFile file(MACH_INFO_FILE);
if(!file.exists())
{
bmachine_info_availble=false;
return 0;
}
if(bmachine_info_availble)
{
return 1;
}
#if 1
machine_info_mutex.lock();
char encrypt_buff[1024];
char decrypt_buff[1024];
MACHINE_INFO_t machine_info_from_flash;
file.open(QIODevice::ReadOnly | QIODevice::Truncate);
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy(&machine_info_from_flash,decrypt_buff,sizeof(machine_info_from_flash));
file.close();
#else
MACHINE_INFO_t machine_info_from_flash;
file.open(QIODevice::ReadOnly | QIODevice::Truncate);
file.seek(0);
file.read((char *)&machine_info_from_flash,(qint64)sizeof(machine_info_from_flash));
file.close();
qDebug()<<"duchu:sn"<<machine_info_from_flash.serial_number;
#endif
qDebug()<<"jiemi:sn"<<machine_info_from_flash.serial_number;
QString serial_from_flash;
serial_from_flash.sprintf("VB%06d", machine_info_from_flash.serial_number);
QString md5_from_calc;
QByteArray hash_data;
hash_data = QCryptographicHash::hash(serial_from_flash.toAscii(),QCryptographicHash::Md5 );
md5_from_calc.append(hash_data);
if(!memcmp(hash_data.data(),&machine_info_from_flash.md5[0],16))
{
bmachine_info_availble=true;
memcpy(&machine_info,&machine_info_from_flash,sizeof(machine_info));
qDebug()<<"machine info is available"<<machine_info.serial_number;
machine_info_mutex.unlock();
return 1;
}
else
{
bmachine_info_availble=false;
qDebug()<<"machine info is not available";
machine_info_mutex.unlock();
return 0;
}
}
qint8 LicenseManger::getLicState()
{
qint8 lic_state = LICENSE_STATE_OK;
if(!checkMachineInfoAvailable())
{
lic_state = -LICENSE_STATE_MACH_INFO_DAMAGED;
}
else
{
if(!CheckLicDataValid())
{
lic_state = -LICENSE_STATE_LIC_DATA_DAMAGED;
}
}
return lic_state;
}
void LicenseManger::SaveLicData2File()
{
#if 0
QFile file("/lib/syst");
#else
QFile file(LIC_FILE);
qint32 encryp_len;
#endif
if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString(QObject::tr("无法打开license文件")) );
}
else {
qDebug()<<"save license file start";
license_data_mutex.lock();
QByteArray ba_licdata((char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
//memcpy(ba_licdata.data(),(char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
QByteArray hash_data;
hash_data = QCryptographicHash::hash(ba_licdata,QCryptographicHash::Md5 );
memcpy(&license_data.md5[0],hash_data.data(),LIC_DATA_MD5_LEN);
#if 0
file.seek(0);
file.write((char *)&license_data.serial_number,(long long int)sizeof(license_data));
file.close();
#else
char encrypt_buff[1024];
file.seek(0);
encryp_len = pAes->OnAesEncrypt((LPVOID)&license_data, sizeof(license_data), (LPVOID)encrypt_buff); //进行加密
//qDebug()<<"jiami:"<<encrypt_buff;
file.write((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
file.close();
#endif
license_data_mutex.unlock();
qDebug()<<"save license file end";
}
}
void LicenseManger::ReadLicDataFromFile()
{
#if 0
QFile file("/lib/syst");
#else
QFile file(LIC_FILE);
#endif
if(!file.exists())
{
if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
QMessageBox::warning(0,QObject::tr("警告"),QString(QObject::tr("无法打开license文件") ));
}
else {
//file.seek(0);
file.close();
ResetLicDataFile();
//show();
}
}
else {
if(!file.open(QIODevice::ReadOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString("无法打开license文件") );
}
else
{
license_data_mutex.lock();
qDebug()<<"read license file start";
#if 0
file.read((char *)&license_data.serial_number,(long long int)sizeof(license_data));
file.close();
#else
char encrypt_buff[1024];
char decrypt_buff[1024];
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy((char *)&license_data,decrypt_buff,sizeof(license_data));
file.close();
#endif
license_data_mutex.unlock();
qDebug()<<"read license file end";
}
}
}
void LicenseManger::ResetLicDataFile()
{
memset((char *)&license_data.serial_number,0,sizeof(license_data));
license_data.serial_number = 100001;
license_data.powerEn=1;
license_data.printEn =1;
license_data.enable =1;
license_data.powerMinuteCnt=0;
license_data.printCnt=0;
license_data.powerMinuteMax=1*31*18*60;// minute cnt
license_data.printMax = 0xfffff000;
curDate =QDate::currentDate();
QDate curDate1;
QDate buildDate = QLocale(QLocale::English).toDate(QString( __DATE__ ).replace(" ", " 0"), "MMM dd yyyy");
QTime buildTime = QTime::fromString( __TIME__, "hh:mm:ss" );
if(curDate<buildDate) {
curDate=buildDate;
int year = buildDate.year();
int month = buildDate.month();
int day = buildDate.day();
int hour = buildTime.hour();
int minute = buildTime.minute();
int sec = buildTime.second();
adjustDateAndTime(year, month, day, hour, minute, sec);//set system date and time
}
license_data.start =curDate.toString("yyyyMMdd").toInt(0);
license_data.nDate = license_data.start; //
//curDate1.toString("yyyyMMdd").toInt(0);
curDate1 = curDate.addMonths(1);
//curDate1.setYMD(curDate.year()+license_data.validity/12, (curDate.month()+license_data.validity)%12,curDate.day());
license_data.end = curDate1.toString("yyyyMMdd").toInt(0);
license_data.workout = 0x1;
license_data.remainingTime = 6*60*18*180; //half year,one day work 18 hours
license_data.printer_auth_flag = ~0x00;
license_data.printer_bworkout = 1;
//qDebug()<<license_data.start<<license_data.end ;
SaveLicData2File();
}
#include <time.h>
void adjustDateAndTime(int year, int mon, int mday, int hour, int min, int sec) {
time_t t;
struct tm nowtime;
nowtime.tm_sec = sec; // Seconds.[0-60] (1 leap second)
nowtime.tm_min = min; // Minutes.[0-59]
nowtime.tm_hour = hour; // Hours. [0-23]
nowtime.tm_mday = mday; // Day.[1-31]
nowtime.tm_mon = mon - 1; // Month. [0-11]
nowtime.tm_year = year - 1900; // Year- 1900.
nowtime.tm_isdst = -1; // DST.[-1/0/1]
t = mktime(&nowtime);
// qDebug()<<t<<year<<mon<<mday<<hour<<min<<sec;
#ifdef ARMUART
stime(&t);
#endif
}
int LicenseManger::CheckLicDataValid()
{
/* read data from file */
ReadLicDataFromFile();
/* check remaining time */
if(license_data.remainingTime >= 6*60*18*367)
{
qDebug()<<"license file was invalid";
return 0;
}
if(license_data.vernon_bach_version != VERNONBACH_VERSION_CODE)
{
qDebug()<<"license file was invalid";
return 0;
}
qDebug()<<"license serial number"<<license_data.serial_number;
/* check md5 value */
QByteArray ba_licdata((char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
//memcpy(ba_licdata.data(),(char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
QByteArray hash_data;
hash_data = QCryptographicHash::hash(ba_licdata, QCryptographicHash::Md5);
if(memcmp(&license_data.md5[0],hash_data.data(),LIC_DATA_MD5_LEN))
{
qDebug()<<"license file was damaged";
return 0;
}
else
{
return 1;
}
}
quint32 LicenseManger::CheckRemainingTime()
{
/* read data from file */
ReadLicDataFromFile();
/* check remaining time */
if(license_data.remainingTime >= 6*60*18*367)
{
qDebug()<<"license file was invalid";
return 0;
}
if(license_data.remainingTime)
license_data.remainingTime--;
if(license_data.remainingTime<=0)
{
license_data.workout = 1;
}
SaveLicData2File();
//license_data.remainingTime=0;
return license_data.remainingTime;
}
quint32 LicenseManger::CheckUpdateFileState()
{
QFile file(UPDATE_LIC_FILE);
LICENSE_DATA_t update_license_data;
quint32 state = UPDATE_LICENSE_FILE_OK;
if(!file.exists())
{
state = -UPDATE_LICENSE_FILE_NOT_EXIT;
}
else
{
if(!file.open(QIODevice::ReadOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString("无法打开license文件") );
state = -UPDATE_LICENSE_FILE_OPEN_FAILED;
}
else
{
//license_data_mutex.lock();
char encrypt_buff[1024];
char decrypt_buff[1024];
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy(&update_license_data,decrypt_buff,sizeof(update_license_data));
file.close();
//license_data_mutex.unlock();
/* check md5 value */
QByteArray ba_update_licdata;
memcpy(ba_update_licdata.data(),(char *)&update_license_data,(sizeof(update_license_data) - sizeof(update_license_data.md5)));
QByteArray hash_data;
hash_data = QCryptographicHash::hash(ba_update_licdata,QCryptographicHash::Md5 );
if(memcmp(&update_license_data.md5[0],hash_data.data(),LIC_DATA_MD5_LEN)) //file is invalid
{
state = -UPDATE_LICENSE_FILE_MD5_VALUE_ERR;
}
if( update_license_data.serial_number != machine_info.serial_number)
{
state = -UPDATE_LICENSE_FILE_SERIAL_NUMBER_ERR;
}
else if( update_license_data.printer_active_count <= license_data.printer_active_count ||
update_license_data.printer_active_count >= (license_data.printer_active_count+3) )
{
state = -UPDATE_LICENSE_FILE_ACTIVE_NUMBER_ERR;
}
else if(update_license_data.vernon_bach_version != VERNONBACH_VERSION_CODE)
{
state = -UPDATE_LICENSE_FILE_SW_VERSION_ERR;
}
}
}
return state;
}
quint32 LicenseManger::UpdateLicenseFileData()
{
QFile file(UPDATE_LIC_FILE);
LICENSE_DATA_t update_license_data;
quint32 state = UPDATE_LICENSE_FILE_OK;
if(!file.exists())
{
state = -UPDATE_LICENSE_FILE_NOT_EXIT;
}
else
{
if(!file.open(QIODevice::ReadOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString("无法打开更新license文件") );
state = -UPDATE_LICENSE_FILE_OPEN_FAILED;
}
else
{
//license_data_mutex.lock();
char encrypt_buff[1024];
char decrypt_buff[1024];
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy(&update_license_data,decrypt_buff,sizeof(update_license_data));
file.close();
//license_data_mutex.unlock();
memcpy(&license_data, &update_license_data, sizeof(update_license_data));
SaveLicData2File();
}
}
return state;
}
#include "LicenseManger.h"
#include "dlginputaddr.h"
#include <QFile>
#include <QMessageBox>
#include <QDate>
#include <QDateEdit>
#include <time.h>
#include <QDebug>
#include <QTime>
#include <QDate>
#include "qnamespace.h"
#include <QtCore/QCoreApplication>
#include <QCryptographicHash>
MACHINE_INFO_t machine_info;
LICENSE_DATA_t license_data;
QMutex machine_info_mutex;
QMutex license_data_mutex;
void adjustDateAndTime(int year, int mon, int mday, int hour, int min, int sec);
LicenseManger::LicenseManger()
{
#if 1
UCHAR e_key[1024] = "dangerous IOP 0908 ";
pAes = new TAesClass;
pAes->InitializePrivateKey(16, e_key); //进行初始化
//setMachineInfo(16);
#endif
}
//set machine info
qint32 LicenseManger::setMachineInfo(quint32 serial_num)
{
//check serial number size
if(serial_num>999999)
{
return -1;
}
machine_info_mutex.lock();
QString serial;
serial.sprintf("VB%06d", serial_num);
QByteArray hash_data;
hash_data = QCryptographicHash::hash(serial.toAscii(),QCryptographicHash::Md5 );
//MACHINE_INFO_t machine_info;
machine_info.serial_number=serial_num;
memcpy(&machine_info.md5[0],hash_data.data(),MD5_LENGTH);
//qDebug()<<"org sn info"<<machine_info.serial_number;
//qDebug()<<"org machine md5 size"<<sizeof(machine_info.md5);
#if 0
QString md5;
md5.append(hash_data);
qDebug()<<"org machine md5 "<<md5;
for(int i=0;i<16;i++)
{
qDebug()<<tr("org md5[%1]").arg(i)<<machine_info.md5[i];
}
#endif
#if 1
char encrypt_buff[1024];
QFile file(MACH_INFO_FILE);
//encrypt the data then write to file
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
file.seek(0);
pAes->OnAesEncrypt((LPVOID)&machine_info, sizeof(machine_info), (LPVOID)encrypt_buff); //进行加密
//qDebug()<<"sn jiami:"<<encrypt_buff;
file.write((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
file.close();
#else
QFile file(MACH_INFO_FILE);
//encrypt the data then write to file
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
file.seek(0);
file.write((char *)&machine_info,(qint64)sizeof(machine_info));
file.close();
#endif
machine_info_mutex.unlock();
return 0;
}
// check machine info from flash is available
qint32 LicenseManger::checkMachineInfoAvailable()
{
static bool bmachine_info_availble;
QFile file(MACH_INFO_FILE);
if(!file.exists())
{
bmachine_info_availble=false;
return 0;
}
if(bmachine_info_availble)
{
return 1;
}
#if 1
machine_info_mutex.lock();
char encrypt_buff[1024];
char decrypt_buff[1024];
MACHINE_INFO_t machine_info_from_flash;
file.open(QIODevice::ReadOnly | QIODevice::Truncate);
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy(&machine_info_from_flash,decrypt_buff,sizeof(machine_info_from_flash));
file.close();
#else
MACHINE_INFO_t machine_info_from_flash;
file.open(QIODevice::ReadOnly | QIODevice::Truncate);
file.seek(0);
file.read((char *)&machine_info_from_flash,(qint64)sizeof(machine_info_from_flash));
file.close();
qDebug()<<"duchu:sn"<<machine_info_from_flash.serial_number;
#endif
qDebug()<<"jiemi:sn"<<machine_info_from_flash.serial_number;
QString serial_from_flash;
serial_from_flash.sprintf("VB%06d", machine_info_from_flash.serial_number);
QString md5_from_calc;
QByteArray hash_data;
hash_data = QCryptographicHash::hash(serial_from_flash.toAscii(),QCryptographicHash::Md5 );
md5_from_calc.append(hash_data);
if(!memcmp(hash_data.data(),&machine_info_from_flash.md5[0],16))
{
bmachine_info_availble=true;
memcpy(&machine_info,&machine_info_from_flash,sizeof(machine_info));
qDebug()<<"machine info is available"<<machine_info.serial_number;
machine_info_mutex.unlock();
return 1;
}
else
{
bmachine_info_availble=false;
qDebug()<<"machine info is not available";
machine_info_mutex.unlock();
return 0;
}
}
qint8 LicenseManger::getLicState()
{
qint8 lic_state = LICENSE_STATE_OK;
if(!checkMachineInfoAvailable())
{
lic_state = -LICENSE_STATE_MACH_INFO_DAMAGED;
}
else
{
if(!CheckLicDataValid())
{
lic_state = -LICENSE_STATE_LIC_DATA_DAMAGED;
}
}
return lic_state;
}
void LicenseManger::SaveLicData2File()
{
#if 0
QFile file("/lib/syst");
#else
QFile file(LIC_FILE);
qint32 encryp_len;
#endif
if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString(QObject::tr("无法打开license文件")) );
}
else {
qDebug()<<"save license file start";
license_data_mutex.lock();
QByteArray ba_licdata((char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
//memcpy(ba_licdata.data(),(char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
QByteArray hash_data;
hash_data = QCryptographicHash::hash(ba_licdata,QCryptographicHash::Md5 );
memcpy(&license_data.md5[0],hash_data.data(),LIC_DATA_MD5_LEN);
#if 0
file.seek(0);
file.write((char *)&license_data.serial_number,(long long int)sizeof(license_data));
file.close();
#else
char encrypt_buff[1024];
file.seek(0);
encryp_len = pAes->OnAesEncrypt((LPVOID)&license_data, sizeof(license_data), (LPVOID)encrypt_buff); //进行加密
//qDebug()<<"jiami:"<<encrypt_buff;
file.write((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
file.close();
#endif
license_data_mutex.unlock();
qDebug()<<"save license file end";
}
}
void LicenseManger::ReadLicDataFromFile()
{
#if 0
QFile file("/lib/syst");
#else
QFile file(LIC_FILE);
#endif
if(!file.exists())
{
if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
QMessageBox::warning(0,QObject::tr("警告"),QString(QObject::tr("无法打开license文件") ));
}
else {
//file.seek(0);
file.close();
ResetLicDataFile();
//show();
}
}
else {
if(!file.open(QIODevice::ReadOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString("无法打开license文件") );
}
else
{
license_data_mutex.lock();
qDebug()<<"read license file start";
#if 0
file.read((char *)&license_data.serial_number,(long long int)sizeof(license_data));
file.close();
#else
char encrypt_buff[1024];
char decrypt_buff[1024];
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy((char *)&license_data,decrypt_buff,sizeof(license_data));
file.close();
#endif
license_data_mutex.unlock();
qDebug()<<"read license file end";
}
}
}
void LicenseManger::ResetLicDataFile()
{
memset((char *)&license_data.serial_number,0,sizeof(license_data));
license_data.serial_number = 100001;
license_data.powerEn=1;
license_data.printEn =1;
license_data.enable =1;
license_data.powerMinuteCnt=0;
license_data.printCnt=0;
license_data.powerMinuteMax=1*31*18*60;// minute cnt
license_data.printMax = 0xfffff000;
curDate =QDate::currentDate();
QDate curDate1;
QDate buildDate = QLocale(QLocale::English).toDate(QString( __DATE__ ).replace(" ", " 0"), "MMM dd yyyy");
QTime buildTime = QTime::fromString( __TIME__, "hh:mm:ss" );
if(curDate<buildDate) {
curDate=buildDate;
int year = buildDate.year();
int month = buildDate.month();
int day = buildDate.day();
int hour = buildTime.hour();
int minute = buildTime.minute();
int sec = buildTime.second();
adjustDateAndTime(year, month, day, hour, minute, sec);//set system date and time
}
license_data.start =curDate.toString("yyyyMMdd").toInt(0);
license_data.nDate = license_data.start; //
//curDate1.toString("yyyyMMdd").toInt(0);
curDate1 = curDate.addMonths(1);
//curDate1.setYMD(curDate.year()+license_data.validity/12, (curDate.month()+license_data.validity)%12,curDate.day());
license_data.end = curDate1.toString("yyyyMMdd").toInt(0);
license_data.workout = 0x1;
license_data.remainingTime = 6*60*18*180; //half year,one day work 18 hours
license_data.printer_auth_flag = ~0x00;
license_data.printer_bworkout = 1;
//qDebug()<<license_data.start<<license_data.end ;
SaveLicData2File();
}
#include <time.h>
void adjustDateAndTime(int year, int mon, int mday, int hour, int min, int sec) {
time_t t;
struct tm nowtime;
nowtime.tm_sec = sec; // Seconds.[0-60] (1 leap second)
nowtime.tm_min = min; // Minutes.[0-59]
nowtime.tm_hour = hour; // Hours. [0-23]
nowtime.tm_mday = mday; // Day.[1-31]
nowtime.tm_mon = mon - 1; // Month. [0-11]
nowtime.tm_year = year - 1900; // Year- 1900.
nowtime.tm_isdst = -1; // DST.[-1/0/1]
t = mktime(&nowtime);
// qDebug()<<t<<year<<mon<<mday<<hour<<min<<sec;
#ifdef ARMUART
stime(&t);
#endif
}
int LicenseManger::CheckLicDataValid()
{
/* read data from file */
ReadLicDataFromFile();
/* check remaining time */
if(license_data.remainingTime >= 6*60*18*367)
{
qDebug()<<"license file was invalid";
return 0;
}
if(license_data.vernon_bach_version != VERNONBACH_VERSION_CODE)
{
qDebug()<<"license file was invalid";
return 0;
}
qDebug()<<"license serial number"<<license_data.serial_number;
/* check md5 value */
QByteArray ba_licdata((char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
//memcpy(ba_licdata.data(),(char *)&license_data,(sizeof(license_data) - sizeof(license_data.md5)));
QByteArray hash_data;
hash_data = QCryptographicHash::hash(ba_licdata, QCryptographicHash::Md5);
if(memcmp(&license_data.md5[0],hash_data.data(),LIC_DATA_MD5_LEN))
{
qDebug()<<"license file was damaged";
return 0;
}
else
{
return 1;
}
}
quint32 LicenseManger::CheckRemainingTime()
{
/* read data from file */
ReadLicDataFromFile();
/* check remaining time */
if(license_data.remainingTime >= 6*60*18*367)
{
qDebug()<<"license file was invalid";
return 0;
}
if(license_data.remainingTime)
license_data.remainingTime--;
if(license_data.remainingTime<=0)
{
license_data.workout = 1;
}
SaveLicData2File();
//license_data.remainingTime=0;
return license_data.remainingTime;
}
quint32 LicenseManger::CheckUpdateFileState()
{
QFile file(UPDATE_LIC_FILE);
LICENSE_DATA_t update_license_data;
quint32 state = UPDATE_LICENSE_FILE_OK;
if(!file.exists())
{
state = -UPDATE_LICENSE_FILE_NOT_EXIT;
}
else
{
if(!file.open(QIODevice::ReadOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString("无法打开license文件") );
state = -UPDATE_LICENSE_FILE_OPEN_FAILED;
}
else
{
//license_data_mutex.lock();
char encrypt_buff[1024];
char decrypt_buff[1024];
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy(&update_license_data,decrypt_buff,sizeof(update_license_data));
file.close();
//license_data_mutex.unlock();
/* check md5 value */
QByteArray ba_update_licdata;
memcpy(ba_update_licdata.data(),(char *)&update_license_data,(sizeof(update_license_data) - sizeof(update_license_data.md5)));
QByteArray hash_data;
hash_data = QCryptographicHash::hash(ba_update_licdata,QCryptographicHash::Md5 );
if(memcmp(&update_license_data.md5[0],hash_data.data(),LIC_DATA_MD5_LEN)) //file is invalid
{
state = -UPDATE_LICENSE_FILE_MD5_VALUE_ERR;
}
if( update_license_data.serial_number != machine_info.serial_number)
{
state = -UPDATE_LICENSE_FILE_SERIAL_NUMBER_ERR;
}
else if( update_license_data.printer_active_count <= license_data.printer_active_count ||
update_license_data.printer_active_count >= (license_data.printer_active_count+3) )
{
state = -UPDATE_LICENSE_FILE_ACTIVE_NUMBER_ERR;
}
else if(update_license_data.vernon_bach_version != VERNONBACH_VERSION_CODE)
{
state = -UPDATE_LICENSE_FILE_SW_VERSION_ERR;
}
}
}
return state;
}
quint32 LicenseManger::UpdateLicenseFileData()
{
QFile file(UPDATE_LIC_FILE);
LICENSE_DATA_t update_license_data;
quint32 state = UPDATE_LICENSE_FILE_OK;
if(!file.exists())
{
state = -UPDATE_LICENSE_FILE_NOT_EXIT;
}
else
{
if(!file.open(QIODevice::ReadOnly | QIODevice::Truncate)){
QMessageBox::warning(0,"警告",QString("无法打开更新license文件") );
state = -UPDATE_LICENSE_FILE_OPEN_FAILED;
}
else
{
//license_data_mutex.lock();
char encrypt_buff[1024];
char decrypt_buff[1024];
file.read((char *)encrypt_buff,(qint64)sizeof(encrypt_buff));
pAes->OnAesUncrypt((LPVOID)encrypt_buff, (DWORD)sizeof(encrypt_buff),(LPVOID)decrypt_buff); //进行解密
//qDebug()<<"jiemi:"<<decrypt_buff;
memcpy(&update_license_data,decrypt_buff,sizeof(update_license_data));
file.close();
//license_data_mutex.unlock();
memcpy(&license_data, &update_license_data, sizeof(update_license_data));
SaveLicData2File();
}
}
return state;
}
+92 -92
View File
@@ -1,92 +1,92 @@
#ifndef LICENSEMANGER_H
#define LICENSEMANGER_H
#include <QtGlobal>
#include <QDate>
#include <QMutex>
#include "Aes/TAesClass.h"
#include "VerBVersion.h"
#define LIC_FILE "/etc/licenseData"
#define UPDATE_LIC_FILE "/udisk/lic_update_file"
//#define MACH_INFO_FILE "/home/student/mini2440/UP/QtUI/machine_info"
#define MACH_INFO_FILE "/etc/appdata/machine_info"
#define LICENSE_STATE_OK 0
#define LICENSE_STATE_MACH_INFO_DAMAGED 1
#define LICENSE_STATE_LIC_DATA_DAMAGED 2
#define LICENSE_STATE_REMAIN_TIME_WARNING 3 //提前提示维护码到期
#define LICENSE_STATE_REMAIN_TIME_REARCH 4
#define UPDATE_LICENSE_FILE_OK 0
#define UPDATE_LICENSE_FILE_NOT_EXIT 1
#define UPDATE_LICENSE_FILE_OPEN_FAILED 2
#define UPDATE_LICENSE_FILE_SERIAL_NUMBER_ERR 3 //提前提示维护码到期
#define UPDATE_LICENSE_FILE_ACTIVE_NUMBER_ERR 4
#define UPDATE_LICENSE_FILE_SW_VERSION_ERR 5
#define UPDATE_LICENSE_FILE_MD5_VALUE_ERR 66
#define LIC_DATA_MD5_LEN 16
typedef struct {
unsigned int serial_number;
unsigned char md5[LIC_DATA_MD5_LEN];
}MACHINE_INFO_t;
typedef struct {
unsigned int serial_number;
unsigned char enable; //1Byte
unsigned char powerEn; // 1Byte
unsigned char printEn; // 1Byte
unsigned int powerMinuteMax;
unsigned int powerMinuteCnt;
unsigned int printMax;
unsigned int printCnt; // printDot/1024
unsigned int start;// yyyymmdd
unsigned int end; // yyyymmdd
unsigned int nDate;
unsigned int workout;
unsigned int remainingTime;//10 second count: 1 day = 6x60x24=8640; 1 week = 7x8640 = 60480; 1 year=8640 x 365 = 3153600
unsigned int printer_bworkout;
unsigned int printer_active_count;
unsigned int printer_auth_flag;
unsigned int vernon_bach_version;
unsigned char md5[LIC_DATA_MD5_LEN];
}LICENSE_DATA_t;
typedef enum {
LicenseState_eLicAvailable,
LicenseState_eLicTimeOut,
LicenseState_eMachineError
}LicenseState_e;
class LicenseManger
{
private:
public:
LicenseManger();
qint32 setMachineInfo(quint32 serial_num);
qint32 checkMachineInfoAvailable();
qint8 getLicState();
void SaveLicData2File();
void ReadLicDataFromFile();
void ResetLicDataFile();
int CheckLicDataValid();
quint32 CheckRemainingTime();
quint32 CheckUpdateFileState();
quint32 UpdateLicenseFileData();
private:
QDate curDate;
TAesClass *pAes;
};
extern MACHINE_INFO_t machine_info;
extern LICENSE_DATA_t license_data;
#endif // LICENSEMANGER_H
#ifndef LICENSEMANGER_H
#define LICENSEMANGER_H
#include <QtGlobal>
#include <QDate>
#include <QMutex>
#include "Aes/TAesClass.h"
#include "VerBVersion.h"
#define LIC_FILE "/etc/licenseData"
#define UPDATE_LIC_FILE "/udisk/lic_update_file"
//#define MACH_INFO_FILE "/home/student/mini2440/UP/QtUI/machine_info"
#define MACH_INFO_FILE "/etc/appdata/machine_info"
#define LICENSE_STATE_OK 0
#define LICENSE_STATE_MACH_INFO_DAMAGED 1
#define LICENSE_STATE_LIC_DATA_DAMAGED 2
#define LICENSE_STATE_REMAIN_TIME_WARNING 3 //提前提示维护码到期
#define LICENSE_STATE_REMAIN_TIME_REARCH 4
#define UPDATE_LICENSE_FILE_OK 0
#define UPDATE_LICENSE_FILE_NOT_EXIT 1
#define UPDATE_LICENSE_FILE_OPEN_FAILED 2
#define UPDATE_LICENSE_FILE_SERIAL_NUMBER_ERR 3 //提前提示维护码到期
#define UPDATE_LICENSE_FILE_ACTIVE_NUMBER_ERR 4
#define UPDATE_LICENSE_FILE_SW_VERSION_ERR 5
#define UPDATE_LICENSE_FILE_MD5_VALUE_ERR 66
#define LIC_DATA_MD5_LEN 16
typedef struct {
unsigned int serial_number;
unsigned char md5[LIC_DATA_MD5_LEN];
}MACHINE_INFO_t;
typedef struct {
unsigned int serial_number;
unsigned char enable; //1Byte
unsigned char powerEn; // 1Byte
unsigned char printEn; // 1Byte
unsigned int powerMinuteMax;
unsigned int powerMinuteCnt;
unsigned int printMax;
unsigned int printCnt; // printDot/1024
unsigned int start;// yyyymmdd
unsigned int end; // yyyymmdd
unsigned int nDate;
unsigned int workout;
unsigned int remainingTime;//10 second count: 1 day = 6x60x24=8640; 1 week = 7x8640 = 60480; 1 year=8640 x 365 = 3153600
unsigned int printer_bworkout;
unsigned int printer_active_count;
unsigned int printer_auth_flag;
unsigned int vernon_bach_version;
unsigned char md5[LIC_DATA_MD5_LEN];
}LICENSE_DATA_t;
typedef enum {
LicenseState_eLicAvailable,
LicenseState_eLicTimeOut,
LicenseState_eMachineError
}LicenseState_e;
class LicenseManger
{
private:
public:
LicenseManger();
qint32 setMachineInfo(quint32 serial_num);
qint32 checkMachineInfoAvailable();
qint8 getLicState();
void SaveLicData2File();
void ReadLicDataFromFile();
void ResetLicDataFile();
int CheckLicDataValid();
quint32 CheckRemainingTime();
quint32 CheckUpdateFileState();
quint32 UpdateLicenseFileData();
private:
QDate curDate;
TAesClass *pAes;
};
extern MACHINE_INFO_t machine_info;
extern LICENSE_DATA_t license_data;
#endif // LICENSEMANGER_H
+21 -21
View File
@@ -1,21 +1,21 @@
#include "dualfilelogger.h"
DualFileLogger::DualFileLogger(QSettings *firstSettings, QSettings* secondSettings, const int refreshInterval, QObject* parent)
:Logger(parent)
{
firstLogger=new FileLogger(firstSettings, refreshInterval, this);
secondLogger=new FileLogger(secondSettings, refreshInterval, this);
}
void DualFileLogger::log(const QtMsgType type, const QString& message, const QString &file, const QString &function, const int line)
{
firstLogger->log(type,message,file,function,line);
secondLogger->log(type,message,file,function,line);
}
void DualFileLogger::clear(const bool buffer, const bool variables)
{
firstLogger->clear(buffer,variables);
secondLogger->clear(buffer,variables);
}
#include "dualfilelogger.h"
DualFileLogger::DualFileLogger(QSettings *firstSettings, QSettings* secondSettings, const int refreshInterval, QObject* parent)
:Logger(parent)
{
firstLogger=new FileLogger(firstSettings, refreshInterval, this);
secondLogger=new FileLogger(secondSettings, refreshInterval, this);
}
void DualFileLogger::log(const QtMsgType type, const QString& message, const QString &file, const QString &function, const int line)
{
firstLogger->log(type,message,file,function,line);
secondLogger->log(type,message,file,function,line);
}
void DualFileLogger::clear(const bool buffer, const bool variables)
{
firstLogger->clear(buffer,variables);
secondLogger->clear(buffer,variables);
}
+35 -35
View File
@@ -1,35 +1,35 @@
#ifndef DUALFILELOGGER_H
#define DUALFILELOGGER_H
#include <QString>
#include <QSettings>
#include <QtGlobal>
#include "logglobal.h"
#include "logger.h"
#include "filelogger.h"
class DECLSPEC DualFileLogger : public Logger {
Q_OBJECT
Q_DISABLE_COPY(DualFileLogger)
public:
DualFileLogger(QSettings* firstSettings, QSettings* secondSettings,
const int refreshInterval=10000, QObject *parent = nullptr);
virtual void log(const QtMsgType type, const QString& message, const QString &file="",
const QString &function="", const int line=0);
virtual void clear(const bool buffer=true, const bool variables=true);
private:
FileLogger* firstLogger;
FileLogger* secondLogger;
};
#endif // DUALFILELOGGER_H
#ifndef DUALFILELOGGER_H
#define DUALFILELOGGER_H
#include <QString>
#include <QSettings>
#include <QtGlobal>
#include "logglobal.h"
#include "logger.h"
#include "filelogger.h"
class DECLSPEC DualFileLogger : public Logger {
Q_OBJECT
Q_DISABLE_COPY(DualFileLogger)
public:
DualFileLogger(QSettings* firstSettings, QSettings* secondSettings,
const int refreshInterval=10000, QObject *parent = nullptr);
virtual void log(const QtMsgType type, const QString& message, const QString &file="",
const QString &function="", const int line=0);
virtual void clear(const bool buffer=true, const bool variables=true);
private:
FileLogger* firstLogger;
FileLogger* secondLogger;
};
#endif // DUALFILELOGGER_H
+273 -273
View File
@@ -1,273 +1,273 @@
#include "filelogger.h"
#include <QTime>
#include <QStringList>
#include <QThread>
#include <QtGlobal>
#include <QFile>
#include <QTimerEvent>
#include <QDir>
#include <QFileInfo>
#include <stdio.h>
#include<iostream>
#include<string>
#include<QDate>
#include "LogInfo.h"
#define LOG_FILE_PATH "/home/plg/loginfo/"
void FileLogger::refreshSettings()
{
mutex.lock();
QString oldFileName=fileName;
settings->sync();
fileName = LOG_FILE_PATH;
// fileName=settings->value("fileName").toString();
// LogInfo::setRunStatusText(tr("fileName: %1").arg(fileName));
QDate today = QDate::currentDate();
QString todayString=today.toString(Qt::ISODate);
// 计算前七天的日期
//QDate oneWeekAgo = today.addDays(-7);
fileName+=today.toString(Qt::ISODate);
fileName+="/";
fileName+="log.txt";
static QString lastDay = "";
if(lastDay!=todayString)
{
TimerDel->start(30000);
lastDay=todayString;
}
#ifdef Q_OS_WIN32
if (QDir::isRelativePath(fileName) && settings->format()!=QSettings::NativeFormat)
#else
if (QDir::isRelativePath(fileName))
#endif
{
QFileInfo configFile(settings->fileName());
fileName=QFileInfo(configFile.absolutePath(),fileName).absoluteFilePath();
}
maxSize=settings->value("maxSize",0).toLongLong();
maxBackups=settings->value("maxBackups",0).toInt();
msgFormat=settings->value("msgFormat","{timestamp} {type} {msg}").toString();
timestampFormat=settings->value("timestampFormat","yyyy-MM-dd hh:mm:ss.zzz").toString();
bufferSize=settings->value("bufferSize",0).toInt();
QByteArray minLevelStr = settings->value("minLevel","ALL").toByteArray();
if (minLevelStr=="ALL" || minLevelStr=="DEBUG" || minLevelStr=="0")
{
minLevel=QtDebugMsg;
}
else if (minLevelStr=="WARNING" || minLevelStr=="WARN" || minLevelStr=="1")
{
minLevel=QtWarningMsg;
}
else if (minLevelStr=="ERROR" || minLevelStr=="CRITICAL" || minLevelStr=="2")
{
minLevel=QtCriticalMsg;
}
else if (minLevelStr=="FATAL" || minLevelStr=="3")
{
// minLevel=QtMsgType::QtFatalMsg;
minLevel=QtFatalMsg;
}
// else if (minLevelStr=="INFO" || minLevelStr=="4")
// {
// minLevel=QtMsgType::QtInfoMsg;
// }
if (oldFileName!=fileName)
{
fprintf(stderr,"Logging to %s\n",qPrintable(fileName));
close();
open();
}
mutex.unlock();
}
FileLogger::FileLogger(QSettings *settings, const int refreshInterval, QObject* parent)
: Logger(parent)
{
TimerDel = new QTimer(this);
connect(TimerDel,SIGNAL(timeout()),this,SLOT(timeOutToDelete()));
Q_ASSERT(settings!=nullptr);
Q_ASSERT(refreshInterval>=0);
this->settings=settings;
file=nullptr;
if (refreshInterval>0)
{
refreshTimer.start(refreshInterval,this);
}
flushTimer.start(1000,this);
refreshSettings();
}
FileLogger::~FileLogger()
{
close();
}
void FileLogger::write(const LogMessage* logMessage)
{
if (file)
{
// qDebug()<<"Critical message output test\n";
// qCritical("This is a critical message of test\n");
file->write(qPrintable(logMessage->toString(msgFormat,timestampFormat)));
if (logMessage->getType()>=QtCriticalMsg)
{
file->flush();
}
if (file->error())
{
qWarning("Cannot write to log file %s: %s",qPrintable(fileName),qPrintable(file->errorString()));
close();
}
}
if (!file)
{
Logger::write(logMessage);
}
}
void FileLogger::open()
{
if (fileName.isEmpty())
{
qWarning("Name of logFile is empty");
}
else {
file=new QFile(fileName);
QFileInfo fileInfo(fileName);
// 检查文件路径是否有效
if (!fileInfo.exists()) {
// 获取文件所在的目录路径
QString dirPath = QFileInfo(fileName).absoluteDir().path();
// 检查目录是否存在
if (!QDir(dirPath).exists()) {
// 如果目录不存在,则创建目录
QDir().mkpath(dirPath);
if (!QDir(dirPath).exists()) {
// 如果创建目录失败,显示错误消息
qDebug("Cannot create directory for log file: %s", qPrintable(dirPath));
delete file;
file = nullptr;
return;
}
}
}
if (!file->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
qWarning("Cannot open log file %s: %s",qPrintable(fileName),qPrintable(file->errorString()));
file=nullptr;
}
}
}
void FileLogger::close()
{
if (file)
{
file->close();
delete file;
file=nullptr;
}
}
void FileLogger::rotate() {
int count=0;
forever
{
QFile bakFile(QString("%1.%2").arg(fileName).arg(count+1));
if (bakFile.exists())
{
++count;
}
else
{
break;
}
}
while (maxBackups>0 && count>=maxBackups)
{
QFile::remove(QString("%1.%2").arg(fileName).arg(count));
--count;
}
for (int i=count; i>0; --i) {
QFile::rename(QString("%1.%2").arg(fileName).arg(i),QString("%1.%2").arg(fileName).arg(i+1));
}
QFile::rename(fileName,fileName+".1");
}
void FileLogger::timerEvent(QTimerEvent* event)
{
if (!event)
{
return;
}
else if (event->timerId()==refreshTimer.timerId())
{
refreshSettings();
}
else if (event->timerId()==flushTimer.timerId() && file)
{
mutex.lock();
file->flush();
if (maxSize>0 && file->size()>=maxSize)
{
close();
rotate();
open();
}
mutex.unlock();
}
}
bool FileLogger::removeDirectory(const QString &directoryPath) {
// 检查目录是否存在
QDir dir(directoryPath);
if (dir.exists()) {
system((char *)((QString("rm -r %1").arg(directoryPath)).toLatin1().data()));
return true;
}
return false;
}
void FileLogger::timeOutToDelete(){
QDate today = QDate::currentDate();
for(int daysAgo=14;daysAgo>=7;--daysAgo){
QString needToDelFoldPath=LOG_FILE_PATH;
QDate pastDate=today.addDays(-daysAgo);
needToDelFoldPath+=pastDate.toString(Qt::ISODate);
needToDelFoldPath+="/";
if (QDir(needToDelFoldPath).exists()) {
bool result= removeDirectory(needToDelFoldPath);
if(result){
qDebug()<<"The directory and all its contents have been removed";
LogInfo::setRunStatusText(tr("The directory and all its contents have been removed"));
}else{
qDebug() << "Failed to remove the directory";
LogInfo::setRunStatusText(tr("Failed to remove the directory"));
}
}
}
TimerDel->stop();
}
#include "filelogger.h"
#include <QTime>
#include <QStringList>
#include <QThread>
#include <QtGlobal>
#include <QFile>
#include <QTimerEvent>
#include <QDir>
#include <QFileInfo>
#include <stdio.h>
#include<iostream>
#include<string>
#include<QDate>
#include "LogInfo.h"
#define LOG_FILE_PATH "/home/plg/loginfo/"
void FileLogger::refreshSettings()
{
mutex.lock();
QString oldFileName=fileName;
settings->sync();
fileName = LOG_FILE_PATH;
// fileName=settings->value("fileName").toString();
// LogInfo::setRunStatusText(tr("fileName: %1").arg(fileName));
QDate today = QDate::currentDate();
QString todayString=today.toString(Qt::ISODate);
// 计算前七天的日期
//QDate oneWeekAgo = today.addDays(-7);
fileName+=today.toString(Qt::ISODate);
fileName+="/";
fileName+="log.txt";
static QString lastDay = "";
if(lastDay!=todayString)
{
TimerDel->start(30000);
lastDay=todayString;
}
#ifdef Q_OS_WIN32
if (QDir::isRelativePath(fileName) && settings->format()!=QSettings::NativeFormat)
#else
if (QDir::isRelativePath(fileName))
#endif
{
QFileInfo configFile(settings->fileName());
fileName=QFileInfo(configFile.absolutePath(),fileName).absoluteFilePath();
}
maxSize=settings->value("maxSize",0).toLongLong();
maxBackups=settings->value("maxBackups",0).toInt();
msgFormat=settings->value("msgFormat","{timestamp} {type} {msg}").toString();
timestampFormat=settings->value("timestampFormat","yyyy-MM-dd hh:mm:ss.zzz").toString();
bufferSize=settings->value("bufferSize",0).toInt();
QByteArray minLevelStr = settings->value("minLevel","ALL").toByteArray();
if (minLevelStr=="ALL" || minLevelStr=="DEBUG" || minLevelStr=="0")
{
minLevel=QtDebugMsg;
}
else if (minLevelStr=="WARNING" || minLevelStr=="WARN" || minLevelStr=="1")
{
minLevel=QtWarningMsg;
}
else if (minLevelStr=="ERROR" || minLevelStr=="CRITICAL" || minLevelStr=="2")
{
minLevel=QtCriticalMsg;
}
else if (minLevelStr=="FATAL" || minLevelStr=="3")
{
// minLevel=QtMsgType::QtFatalMsg;
minLevel=QtFatalMsg;
}
// else if (minLevelStr=="INFO" || minLevelStr=="4")
// {
// minLevel=QtMsgType::QtInfoMsg;
// }
if (oldFileName!=fileName)
{
fprintf(stderr,"Logging to %s\n",qPrintable(fileName));
close();
open();
}
mutex.unlock();
}
FileLogger::FileLogger(QSettings *settings, const int refreshInterval, QObject* parent)
: Logger(parent)
{
TimerDel = new QTimer(this);
connect(TimerDel,SIGNAL(timeout()),this,SLOT(timeOutToDelete()));
Q_ASSERT(settings!=nullptr);
Q_ASSERT(refreshInterval>=0);
this->settings=settings;
file=nullptr;
if (refreshInterval>0)
{
refreshTimer.start(refreshInterval,this);
}
flushTimer.start(1000,this);
refreshSettings();
}
FileLogger::~FileLogger()
{
close();
}
void FileLogger::write(const LogMessage* logMessage)
{
if (file)
{
// qDebug()<<"Critical message output test\n";
// qCritical("This is a critical message of test\n");
file->write(qPrintable(logMessage->toString(msgFormat,timestampFormat)));
if (logMessage->getType()>=QtCriticalMsg)
{
file->flush();
}
if (file->error())
{
qWarning("Cannot write to log file %s: %s",qPrintable(fileName),qPrintable(file->errorString()));
close();
}
}
if (!file)
{
Logger::write(logMessage);
}
}
void FileLogger::open()
{
if (fileName.isEmpty())
{
qWarning("Name of logFile is empty");
}
else {
file=new QFile(fileName);
QFileInfo fileInfo(fileName);
// 检查文件路径是否有效
if (!fileInfo.exists()) {
// 获取文件所在的目录路径
QString dirPath = QFileInfo(fileName).absoluteDir().path();
// 检查目录是否存在
if (!QDir(dirPath).exists()) {
// 如果目录不存在,则创建目录
QDir().mkpath(dirPath);
if (!QDir(dirPath).exists()) {
// 如果创建目录失败,显示错误消息
qDebug("Cannot create directory for log file: %s", qPrintable(dirPath));
delete file;
file = nullptr;
return;
}
}
}
if (!file->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
qWarning("Cannot open log file %s: %s",qPrintable(fileName),qPrintable(file->errorString()));
file=nullptr;
}
}
}
void FileLogger::close()
{
if (file)
{
file->close();
delete file;
file=nullptr;
}
}
void FileLogger::rotate() {
int count=0;
forever
{
QFile bakFile(QString("%1.%2").arg(fileName).arg(count+1));
if (bakFile.exists())
{
++count;
}
else
{
break;
}
}
while (maxBackups>0 && count>=maxBackups)
{
QFile::remove(QString("%1.%2").arg(fileName).arg(count));
--count;
}
for (int i=count; i>0; --i) {
QFile::rename(QString("%1.%2").arg(fileName).arg(i),QString("%1.%2").arg(fileName).arg(i+1));
}
QFile::rename(fileName,fileName+".1");
}
void FileLogger::timerEvent(QTimerEvent* event)
{
if (!event)
{
return;
}
else if (event->timerId()==refreshTimer.timerId())
{
refreshSettings();
}
else if (event->timerId()==flushTimer.timerId() && file)
{
mutex.lock();
file->flush();
if (maxSize>0 && file->size()>=maxSize)
{
close();
rotate();
open();
}
mutex.unlock();
}
}
bool FileLogger::removeDirectory(const QString &directoryPath) {
// 检查目录是否存在
QDir dir(directoryPath);
if (dir.exists()) {
system((char *)((QString("rm -r %1").arg(directoryPath)).toLatin1().data()));
return true;
}
return false;
}
void FileLogger::timeOutToDelete(){
QDate today = QDate::currentDate();
for(int daysAgo=14;daysAgo>=7;--daysAgo){
QString needToDelFoldPath=LOG_FILE_PATH;
QDate pastDate=today.addDays(-daysAgo);
needToDelFoldPath+=pastDate.toString(Qt::ISODate);
needToDelFoldPath+="/";
if (QDir(needToDelFoldPath).exists()) {
bool result= removeDirectory(needToDelFoldPath);
if(result){
qDebug()<<"The directory and all its contents have been removed";
LogInfo::setRunStatusText(tr("The directory and all its contents have been removed"));
}else{
qDebug() << "Failed to remove the directory";
LogInfo::setRunStatusText(tr("Failed to remove the directory"));
}
}
}
TimerDel->stop();
}
+62 -62
View File
@@ -1,62 +1,62 @@
#ifndef FILELOGGER_H
#define FILELOGGER_H
#include <QtGlobal>
#include <QSettings>
#include <QFile>
#include <QMutex>
#include <QBasicTimer>
#include "logglobal.h"
#include "logger.h"
#include <QTimer>
class DECLSPEC FileLogger : public Logger {
Q_OBJECT
Q_DISABLE_COPY(FileLogger)
public:
FileLogger(QSettings* settings, const int refreshInterval=10000, QObject* parent = nullptr);
virtual ~FileLogger();
virtual void write(const LogMessage* logMessage);
public slots:
void timeOutToDelete();
protected:
void timerEvent(QTimerEvent* event);
private:
QString fileName;
long maxSize;
int maxBackups;
QSettings* settings;
QFile* file;
QBasicTimer refreshTimer;
QBasicTimer flushTimer;
QTimer *TimerDel;
void open();
void close();
void rotate();
void refreshSettings();
bool removeDirectory(const QString &directoryPath);
};
#endif // FILELOGGER_H
#ifndef FILELOGGER_H
#define FILELOGGER_H
#include <QtGlobal>
#include <QSettings>
#include <QFile>
#include <QMutex>
#include <QBasicTimer>
#include "logglobal.h"
#include "logger.h"
#include <QTimer>
class DECLSPEC FileLogger : public Logger {
Q_OBJECT
Q_DISABLE_COPY(FileLogger)
public:
FileLogger(QSettings* settings, const int refreshInterval=10000, QObject* parent = nullptr);
virtual ~FileLogger();
virtual void write(const LogMessage* logMessage);
public slots:
void timeOutToDelete();
protected:
void timerEvent(QTimerEvent* event);
private:
QString fileName;
long maxSize;
int maxBackups;
QSettings* settings;
QFile* file;
QBasicTimer refreshTimer;
QBasicTimer flushTimer;
QTimer *TimerDel;
void open();
void close();
void rotate();
void refreshSettings();
bool removeDirectory(const QString &directoryPath);
};
#endif // FILELOGGER_H
+247 -247
View File
@@ -1,247 +1,247 @@
#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <QDateTime>
#include <QThread>
#include <QObject>
#include <iostream>
Logger* Logger::defaultLogger=nullptr;
QThreadStorage<QHash<QString,QString>*> Logger::logVars;
QMutex Logger::mutex;
Logger::Logger(QObject* parent)
: QObject(parent),
msgFormat("{timestamp} {type} {msg}"),
timestampFormat("dd.MM.yyyy hh:mm:ss.zzz"),
minLevel(QtDebugMsg),
bufferSize(0)
{}
Logger::Logger(const QString msgFormat, const QString timestampFormat, const QtMsgType minLevel, const int bufferSize, QObject* parent)
:QObject(parent)
{
this->msgFormat=msgFormat;
this->timestampFormat=timestampFormat;
this->minLevel=minLevel;
this->bufferSize=bufferSize;
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
static QRecursiveMutex recursiveMutex;
static QMutex nonRecursiveMutex;
#else
static QMutex recursiveMutex(QMutex::Recursive);
static QMutex nonRecursiveMutex(QMutex::NonRecursive);
#endif
void Logger::msgHandler(const QtMsgType type, const QString &message, const QString &file, const QString &function, const int line)
{
recursiveMutex.lock();
if (defaultLogger && nonRecursiveMutex.tryLock())
{
defaultLogger->log(type, message, file, function, line);
nonRecursiveMutex.unlock();
}
else
{
fputs(qPrintable(message),stderr);
fflush(stderr);
}
if (type==QtFatalMsg)
{
abort();
}
recursiveMutex.unlock();
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
void Logger::msgHandler5(const QtMsgType type, const QMessageLogContext &context, const QString &message)
{
(void)(context);
msgHandler(type,message,context.file,context.function,context.line);
}
#else
void Logger::msgHandler4(const QtMsgType type, const char* message)
{
msgHandler(type,message);
}
#endif
Logger::~Logger()
{
if (defaultLogger==this)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
qInstallMessageHandler(nullptr);
#else
qInstallMsgHandler(nullptr);
#endif
defaultLogger=nullptr;
}
}
void Logger::write(const LogMessage* logMessage)
{
fputs(qPrintable(logMessage->toString(msgFormat,timestampFormat)),stderr);
fflush(stderr);
}
void Logger::installMsgHandler()
{
defaultLogger=this;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
qInstallMessageHandler(msgHandler5);
#else
qInstallMsgHandler(msgHandler4);
#endif
}
void Logger::set(const QString& name, const QString& value)
{
mutex.lock();
if (!logVars.hasLocalData())
{
logVars.setLocalData(new QHash<QString,QString>);
}
logVars.localData()->insert(name,value);
mutex.unlock();
}
void Logger::clear(const bool buffer, const bool variables)
{
mutex.lock();
if (buffer && buffers.hasLocalData())
{
QList<LogMessage*>* buffer=buffers.localData();
while (buffer && !buffer->isEmpty())
{
LogMessage* logMessage=buffer->takeLast();
delete logMessage;
}
}
if (variables && logVars.hasLocalData())
{
logVars.localData()->clear();
}
mutex.unlock();
}
void Logger::log(const QtMsgType type, const QString& message, const QString &file, const QString &function, const int line)
{
bool toPrint=false;
switch (type)
{
case QtDebugMsg:
if (minLevel==QtDebugMsg)
{
toPrint=true;
}
break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
case QtInfoMsg:
if (minLevel==QtDebugMsg ||
minLevel==QtInfoMsg)
{
toPrint=true;
}
break;
#endif
case QtWarningMsg:
if (minLevel==QtDebugMsg ||
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
minLevel==QtInfoMsg ||
#endif
minLevel==QtWarningMsg)
{
toPrint=true;
}
break;
case QtCriticalMsg:
if (minLevel==QtDebugMsg ||
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
minLevel==QtInfoMsg ||
#endif
minLevel==QtWarningMsg ||
minLevel==QtCriticalMsg)
{
toPrint=true;
}
break;
case QtFatalMsg:
toPrint=true;
break;
default:
toPrint=true;
}
mutex.lock();
LogMessage echoMsg(type,message,logVars.localData(),file,function,line);
#ifndef BNS_AARCH64_DEBUG
std::cout << qPrintable(echoMsg.toString(msgFormat,timestampFormat)) << std::flush;
#endif
if (bufferSize>0)
{
if (!buffers.hasLocalData())
{
buffers.setLocalData(new QList<LogMessage*>());
}
QList<LogMessage*>* buffer=buffers.localData();
LogMessage* logMessage=new LogMessage(type,message,logVars.localData(),file,function,line);
buffer->append(logMessage);
if (buffer->size()>bufferSize)
{
delete buffer->takeFirst();
}
if (toPrint)
{
while (!buffer->isEmpty())
{
LogMessage* logMessage=buffer->takeFirst();
write(logMessage);
delete logMessage;
}
}
}
else
{
if (toPrint)
{
LogMessage logMessage(type,message,logVars.localData(),file,function,line);
write(&logMessage);
}
}
mutex.unlock();
}
#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <QDateTime>
#include <QThread>
#include <QObject>
#include <iostream>
Logger* Logger::defaultLogger=nullptr;
QThreadStorage<QHash<QString,QString>*> Logger::logVars;
QMutex Logger::mutex;
Logger::Logger(QObject* parent)
: QObject(parent),
msgFormat("{timestamp} {type} {msg}"),
timestampFormat("dd.MM.yyyy hh:mm:ss.zzz"),
minLevel(QtDebugMsg),
bufferSize(0)
{}
Logger::Logger(const QString msgFormat, const QString timestampFormat, const QtMsgType minLevel, const int bufferSize, QObject* parent)
:QObject(parent)
{
this->msgFormat=msgFormat;
this->timestampFormat=timestampFormat;
this->minLevel=minLevel;
this->bufferSize=bufferSize;
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
static QRecursiveMutex recursiveMutex;
static QMutex nonRecursiveMutex;
#else
static QMutex recursiveMutex(QMutex::Recursive);
static QMutex nonRecursiveMutex(QMutex::NonRecursive);
#endif
void Logger::msgHandler(const QtMsgType type, const QString &message, const QString &file, const QString &function, const int line)
{
recursiveMutex.lock();
if (defaultLogger && nonRecursiveMutex.tryLock())
{
defaultLogger->log(type, message, file, function, line);
nonRecursiveMutex.unlock();
}
else
{
fputs(qPrintable(message),stderr);
fflush(stderr);
}
if (type==QtFatalMsg)
{
abort();
}
recursiveMutex.unlock();
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
void Logger::msgHandler5(const QtMsgType type, const QMessageLogContext &context, const QString &message)
{
(void)(context);
msgHandler(type,message,context.file,context.function,context.line);
}
#else
void Logger::msgHandler4(const QtMsgType type, const char* message)
{
msgHandler(type,message);
}
#endif
Logger::~Logger()
{
if (defaultLogger==this)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
qInstallMessageHandler(nullptr);
#else
qInstallMsgHandler(nullptr);
#endif
defaultLogger=nullptr;
}
}
void Logger::write(const LogMessage* logMessage)
{
fputs(qPrintable(logMessage->toString(msgFormat,timestampFormat)),stderr);
fflush(stderr);
}
void Logger::installMsgHandler()
{
defaultLogger=this;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
qInstallMessageHandler(msgHandler5);
#else
qInstallMsgHandler(msgHandler4);
#endif
}
void Logger::set(const QString& name, const QString& value)
{
mutex.lock();
if (!logVars.hasLocalData())
{
logVars.setLocalData(new QHash<QString,QString>);
}
logVars.localData()->insert(name,value);
mutex.unlock();
}
void Logger::clear(const bool buffer, const bool variables)
{
mutex.lock();
if (buffer && buffers.hasLocalData())
{
QList<LogMessage*>* buffer=buffers.localData();
while (buffer && !buffer->isEmpty())
{
LogMessage* logMessage=buffer->takeLast();
delete logMessage;
}
}
if (variables && logVars.hasLocalData())
{
logVars.localData()->clear();
}
mutex.unlock();
}
void Logger::log(const QtMsgType type, const QString& message, const QString &file, const QString &function, const int line)
{
bool toPrint=false;
switch (type)
{
case QtDebugMsg:
if (minLevel==QtDebugMsg)
{
toPrint=true;
}
break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
case QtInfoMsg:
if (minLevel==QtDebugMsg ||
minLevel==QtInfoMsg)
{
toPrint=true;
}
break;
#endif
case QtWarningMsg:
if (minLevel==QtDebugMsg ||
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
minLevel==QtInfoMsg ||
#endif
minLevel==QtWarningMsg)
{
toPrint=true;
}
break;
case QtCriticalMsg:
if (minLevel==QtDebugMsg ||
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
minLevel==QtInfoMsg ||
#endif
minLevel==QtWarningMsg ||
minLevel==QtCriticalMsg)
{
toPrint=true;
}
break;
case QtFatalMsg:
toPrint=true;
break;
default:
toPrint=true;
}
mutex.lock();
LogMessage echoMsg(type,message,logVars.localData(),file,function,line);
#ifndef BNS_AARCH64_DEBUG
std::cout << qPrintable(echoMsg.toString(msgFormat,timestampFormat)) << std::flush;
#endif
if (bufferSize>0)
{
if (!buffers.hasLocalData())
{
buffers.setLocalData(new QList<LogMessage*>());
}
QList<LogMessage*>* buffer=buffers.localData();
LogMessage* logMessage=new LogMessage(type,message,logVars.localData(),file,function,line);
buffer->append(logMessage);
if (buffer->size()>bufferSize)
{
delete buffer->takeFirst();
}
if (toPrint)
{
while (!buffer->isEmpty())
{
LogMessage* logMessage=buffer->takeFirst();
write(logMessage);
delete logMessage;
}
}
}
else
{
if (toPrint)
{
LogMessage logMessage(type,message,logVars.localData(),file,function,line);
write(&logMessage);
}
}
mutex.unlock();
}
+76 -76
View File
@@ -1,76 +1,76 @@
#ifndef LOGGER_H
#define LOGGER_H
#include <QtGlobal>
#include <QThreadStorage>
#include <QHash>
#include <QStringList>
#include <QMutex>
#include <QObject>
#include "logglobal.h"
#include "logmessage.h"
#include <QDebug>
class DECLSPEC Logger : public QObject {
Q_OBJECT
Q_DISABLE_COPY(Logger)
public:
Logger(QObject* parent);
Logger(const QString msgFormat="{timestamp} {type} {msg}",
const QString timestampFormat="dd.MM.yyyy hh:mm:ss.zzz",
const QtMsgType minLevel=QtDebugMsg, const int bufferSize=0,
QObject* parent = nullptr);
virtual ~Logger();
virtual void log(const QtMsgType type, const QString& message, const QString &file="",
const QString &function="", const int line=0);
void installMsgHandler();
static void set(const QString& name, const QString& value);
virtual void clear(const bool buffer=true, const bool variables=true);
protected:
QString msgFormat;
QString timestampFormat;
QtMsgType minLevel;
int bufferSize;
static QMutex mutex;
virtual void write(const LogMessage* logMessage);
private:
static Logger* defaultLogger;
static void msgHandler(const QtMsgType type, const QString &message, const QString &file="",
const QString &function="", const int line=0);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
static void msgHandler5(const QtMsgType type, const QMessageLogContext& context, const QString &message);
#else
static void msgHandler4(const QtMsgType type, const char * message);
#endif
static QThreadStorage<QHash<QString,QString>*> logVars;
QThreadStorage<QList<LogMessage*>*> buffers;
};
#endif // LOGGER_H
#ifndef LOGGER_H
#define LOGGER_H
#include <QtGlobal>
#include <QThreadStorage>
#include <QHash>
#include <QStringList>
#include <QMutex>
#include <QObject>
#include "logglobal.h"
#include "logmessage.h"
#include <QDebug>
class DECLSPEC Logger : public QObject {
Q_OBJECT
Q_DISABLE_COPY(Logger)
public:
Logger(QObject* parent);
Logger(const QString msgFormat="{timestamp} {type} {msg}",
const QString timestampFormat="dd.MM.yyyy hh:mm:ss.zzz",
const QtMsgType minLevel=QtDebugMsg, const int bufferSize=0,
QObject* parent = nullptr);
virtual ~Logger();
virtual void log(const QtMsgType type, const QString& message, const QString &file="",
const QString &function="", const int line=0);
void installMsgHandler();
static void set(const QString& name, const QString& value);
virtual void clear(const bool buffer=true, const bool variables=true);
protected:
QString msgFormat;
QString timestampFormat;
QtMsgType minLevel;
int bufferSize;
static QMutex mutex;
virtual void write(const LogMessage* logMessage);
private:
static Logger* defaultLogger;
static void msgHandler(const QtMsgType type, const QString &message, const QString &file="",
const QString &function="", const int line=0);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
static void msgHandler5(const QtMsgType type, const QMessageLogContext& context, const QString &message);
#else
static void msgHandler4(const QtMsgType type, const char * message);
#endif
static QThreadStorage<QHash<QString,QString>*> logVars;
QThreadStorage<QList<LogMessage*>*> buffers;
};
#endif // LOGGER_H
+23 -23
View File
@@ -1,23 +1,23 @@
#ifndef LOGGLOBAL_H
#define LOGGLOBAL_H
#include <QtGlobal>
#if defined(Q_OS_WIN)
#if defined(QTWEBAPPLIB_EXPORT)
#define DECLSPEC Q_DECL_EXPORT
#elif defined(QTWEBAPPLIB_IMPORT)
#define DECLSPEC Q_DECL_IMPORT
#endif
#endif
#if !defined(DECLSPEC)
#define DECLSPEC
#endif
#if __cplusplus < 201103L
#define nullptr 0
#endif
#endif // LOGGLOBAL_H
#ifndef LOGGLOBAL_H
#define LOGGLOBAL_H
#include <QtGlobal>
#if defined(Q_OS_WIN)
#if defined(QTWEBAPPLIB_EXPORT)
#define DECLSPEC Q_DECL_EXPORT
#elif defined(QTWEBAPPLIB_IMPORT)
#define DECLSPEC Q_DECL_IMPORT
#endif
#endif
#if !defined(DECLSPEC)
#define DECLSPEC
#endif
#if __cplusplus < 201103L
#define nullptr 0
#endif
#endif // LOGGLOBAL_H
+78 -78
View File
@@ -1,78 +1,78 @@
#include "logmessage.h"
#include <QThread>
LogMessage::LogMessage(const QtMsgType type, const QString& message, const QHash<QString, QString> *logVars, const QString &file, const QString &function, const int line)
{
this->type=type;
this->message=message;
this->file=file;
this->function=function;
this->line=line;
timestamp=QDateTime::currentDateTime();
threadId=QThread::currentThreadId();
if (logVars)
{
this->logVars=*logVars;
}
}
QString LogMessage::toString(const QString& msgFormat, const QString& timestampFormat) const
{
QString decorated=msgFormat+"\n";
decorated.replace("{msg}",message);
if (decorated.contains("{timestamp}"))
{
decorated.replace("{timestamp}",timestamp.toString(timestampFormat));
}
QString typeNr;
typeNr.setNum(type);
decorated.replace("{typeNr}",typeNr);
switch (type)
{
case QtDebugMsg:
decorated.replace("{type}","DEBUG ");
break;
case QtWarningMsg:
decorated.replace("{type}","WARNING ");
break;
case QtCriticalMsg:
decorated.replace("{type}","CRITICAL");
break;
case QtFatalMsg:
decorated.replace("{type}","FATAL ");
break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
case QtInfoMsg:
decorated.replace("{type}","INFO ");
break;
#endif
}
decorated.replace("{file}",file);
decorated.replace("{function}",function);
decorated.replace("{line}",QString::number(line));
QString threadId = QString("0x%1").arg(qulonglong(QThread::currentThreadId()), 8, 16, QLatin1Char('0'));
decorated.replace("{thread}",threadId);
if (decorated.contains("{") && !logVars.isEmpty())
{
QList<QString> keys=logVars.keys();
foreach (QString key, keys)
{
decorated.replace("{"+key+"}",logVars.value(key));
}
}
return decorated;
}
QtMsgType LogMessage::getType() const
{
return type;
}
#include "logmessage.h"
#include <QThread>
LogMessage::LogMessage(const QtMsgType type, const QString& message, const QHash<QString, QString> *logVars, const QString &file, const QString &function, const int line)
{
this->type=type;
this->message=message;
this->file=file;
this->function=function;
this->line=line;
timestamp=QDateTime::currentDateTime();
threadId=QThread::currentThreadId();
if (logVars)
{
this->logVars=*logVars;
}
}
QString LogMessage::toString(const QString& msgFormat, const QString& timestampFormat) const
{
QString decorated=msgFormat+"\n";
decorated.replace("{msg}",message);
if (decorated.contains("{timestamp}"))
{
decorated.replace("{timestamp}",timestamp.toString(timestampFormat));
}
QString typeNr;
typeNr.setNum(type);
decorated.replace("{typeNr}",typeNr);
switch (type)
{
case QtDebugMsg:
decorated.replace("{type}","DEBUG ");
break;
case QtWarningMsg:
decorated.replace("{type}","WARNING ");
break;
case QtCriticalMsg:
decorated.replace("{type}","CRITICAL");
break;
case QtFatalMsg:
decorated.replace("{type}","FATAL ");
break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
case QtInfoMsg:
decorated.replace("{type}","INFO ");
break;
#endif
}
decorated.replace("{file}",file);
decorated.replace("{function}",function);
decorated.replace("{line}",QString::number(line));
QString threadId = QString("0x%1").arg(qulonglong(QThread::currentThreadId()), 8, 16, QLatin1Char('0'));
decorated.replace("{thread}",threadId);
if (decorated.contains("{") && !logVars.isEmpty())
{
QList<QString> keys=logVars.keys();
foreach (QString key, keys)
{
decorated.replace("{"+key+"}",logVars.value(key));
}
}
return decorated;
}
QtMsgType LogMessage::getType() const
{
return type;
}
+44 -44
View File
@@ -1,44 +1,44 @@
#ifndef LOGMESSAGE_H
#define LOGMESSAGE_H
#include <QtGlobal>
#include <QDateTime>
#include <QHash>
#include "logglobal.h"
class DECLSPEC LogMessage
{
Q_DISABLE_COPY(LogMessage)
public:
LogMessage(const QtMsgType type, const QString& message, const QHash<QString,QString>* logVars,
const QString &file, const QString &function, const int line);
QString toString(const QString& msgFormat, const QString& timestampFormat) const;
QtMsgType getType() const;
private:
QHash<QString,QString> logVars;
QDateTime timestamp;
QtMsgType type;
Qt::HANDLE threadId;
QString message;
QString file;
QString function;
int line;
};
#endif // LOGMESSAGE_H
#ifndef LOGMESSAGE_H
#define LOGMESSAGE_H
#include <QtGlobal>
#include <QDateTime>
#include <QHash>
#include "logglobal.h"
class DECLSPEC LogMessage
{
Q_DISABLE_COPY(LogMessage)
public:
LogMessage(const QtMsgType type, const QString& message, const QHash<QString,QString>* logVars,
const QString &file, const QString &function, const int line);
QString toString(const QString& msgFormat, const QString& timestampFormat) const;
QtMsgType getType() const;
private:
QHash<QString,QString> logVars;
QDateTime timestamp;
QtMsgType type;
Qt::HANDLE threadId;
QString message;
QString file;
QString function;
int line;
};
#endif // LOGMESSAGE_H
+461 -461
View File
@@ -1,461 +1,461 @@
#include "LogInfo.h"
#include "ui_loginfo.h"
#include <QTime>
#include <QDir>
#include <QDebug>
#include <QFile>
#include <QIODevice>
#include <QTextDocumentWriter>
#include <QMessageBox>
#include "DevOp.h"
#include <stdio.h>
#include "myinclude.h"
#include <QScrollBar>
#include <QSettings>
#ifndef LOGINFOFILE_DIR
#define LOGINFOFILE_DIR "/home/plg/loginfo/"
#endif
#define UDISK_LOGINFO_ROOT_DIR "/udisk/log/"
LogInfo::LogInfo(QWidget *parent) :
QWidget(parent),
ui(new Ui::LogInfo)
{
ui->setupUi(this);
ui->textEditRunStatus->setReadOnly(true);
ui->textEditRunStatus_2->setReadOnly(true);
textEdit = ui->textEditRunStatus;
textEdit->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 40px; }");
textEdit2 = ui->textEditRunStatus_2;
//textEdit2->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 40px; }");
textEdit2->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 40px; }");
textEditMachInfo = ui->machinInformation;
runStatusTextIndex = 0;
openFileName ="";
ui->labelPreFileName->setText("");
//currenDate="";
//r_CurrentDate=QDate::currentDate().toString("yyyyMMdd");
textEdit2->append(tr("请先打开历史状态文件!"));
if(!QDir("/home/plg").exists())
QDir("/home/plg").mkdir("/home/plg");
readRunStatusText();
runStatusTextIndex = textEdit->document()->lineCount();
fileDialog=0; // 先初始化为0 ,否则会死机
QFile file(SYS_ROOT_DIR"UseEn");
if(!file.exists()){
onReadRecorder( );
}
timerLogdel=new QTimer(this);
connect(timerLogdel, SIGNAL(timeout()), this, SLOT(deleteOldLog()));
//延时60秒删除日志文件
timerLogdel->start(60000);
setScrollBar();
}
LogInfo::~LogInfo()
{
textEdit = 0;
textEdit2 = 0;
textEditMachInfo = 0;
if(fileDialog)
delete fileDialog;
delete ui;
disconnect(timerLogdel, SIGNAL(timeout()), this, SLOT(deleteOldLog()));
timerLogdel->stop();
}
QTextEdit *LogInfo::textEdit = 0;
QTextEdit *LogInfo::textEdit2 = 0;
QTextEdit *LogInfo::textEditMachInfo = 0;
int LogInfo::runStatusTextIndex = 0;
void LogInfo::showMachineInformation(QString Mac,QString SerialNum, QString VernonBachVer, QString FpgaVer)
{
QString machInfo;
machInfo = "Mac:" + Mac + "\n";
machInfo += "VernonBach Ver:" + VernonBachVer + "\n";
machInfo += "FPGA Ver:" + FpgaVer;
textEditMachInfo->setText(machInfo);
}
void LogInfo::showVerionInformation(QString Mac,QString VernonBachVer, QString FpgaVer,QString STM32Ver,bool powerOnMode)
{
static bool flag = false;
if(!flag){
QString machInfo;
machInfo = "Mac:" + Mac + "\n";
machInfo += "VernonBach Ver:" + VernonBachVer +"|"+STM32Ver+ "\n";
machInfo += "FPGA Ver: NO" + FpgaVer + "\n";
machInfo += "PowerOnMode: " + QString::number(powerOnMode) + "\n";
textEditMachInfo->append(machInfo);
}
}
void LogInfo::showRemoteControll(QString SuperNode, QString edgeIP)
{
QString machInfo = textEditMachInfo->toPlainText();
machInfo += "SuperNode:" + SuperNode + "\n";
machInfo += "edgeIP:" + edgeIP + "\n";
textEditMachInfo->setText(machInfo);
}
//edit@01-11
void LogInfo::setRunStatusText(QString str){
if(!textEdit){
return;
}
const int maxTextEditHeight = 2000;
if(textEdit->document()->size().height() > maxTextEditHeight)
{
textEdit->clear(); //显示今天全部信息,加载太多可能会死机
}
str.prepend(QString("%1. %2:").arg(QString::number(runStatusTextIndex ++ )).arg(QTime::currentTime().toString("hh:mm:ss")));
textEdit->append(str);
{
// 使用静态缓冲区批量写入,避免每次调用都 open/close 文件导致 ARM 板 I/O 繁忙
static QStringList pendingLines;
static QString lastDate;
static int pendingTotalLen = 0; // 增量维护总字符数,避免每次扫描
const QString dts = QDate::currentDate().toString("yyyyMMdd");
if(dts != lastDate){
// 日期变化时先把旧缓冲写入旧文件
if(!pendingLines.isEmpty() && !lastDate.isEmpty()){
QString oldFile = QString(LOGINFOFILE_DIR) + lastDate + "_1.txt";
QFile f(oldFile);
if(f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
QTextStream out(&f);
for(const QString &line : pendingLines)
out << line << endl;
f.close();
}
pendingLines.clear();
pendingTotalLen = 0;
}
lastDate = dts;
}
pendingLines.append(str);
pendingTotalLen += str.length();
// 每累积 10 条或字符总量超过 2KB 时批量写入一次
if(pendingLines.size() >= 10 || pendingTotalLen > 2048){
QString fileNameL = QString(LOGINFOFILE_DIR) + dts + "_1.txt";
QFile file(fileNameL);
if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
QTextStream out(&file);
for(const QString &line : pendingLines)
out << line << endl;
file.close();
}
pendingLines.clear();
pendingTotalLen = 0;
truncatelog();
}
}
}
QString LogInfo::getRunStatusText(void){
return "";
}
void LogInfo::readRunStatusText()
{
QString fileName;
if(textEdit){
QDir dir1;
dir1.setPath(LOGINFOFILE_DIR);
if(!dir1.exists())
dir1.mkdir(QString ("/home/plg/loginfo/"));
fileName=QString("/home/plg/loginfo/")+QDate::currentDate().toString("yyyyMMdd")+"_1.txt";
QFile file(fileName);
if(file.exists()){
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QMessageBox::warning(this,tr("警告"),tr("无法打开文件") + file.fileName());
}
else{
QTextStream in (&file);
textEdit->setText(in.readAll());
}
file.close();
ui->tabWidget->setCurrentWidget(ui->tab);
}
QDate date1 = QDate::currentDate();
for(int i=0;i<8;i++)
{
fileName=QString("/home/plg/loginfo/")+date1.addDays(-i-5).toString("yyyyMMdd")+".txt";
file.setFileName(fileName);
if(file.exists()){
file.remove();
}
}
}
}
void LogInfo::on_pushButtonExportFile_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将所有日志文件导出到U盘?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
//QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_LOGINFO_ROOT_DIR;
QDir dir(UDISK_LOGINFO_ROOT_DIR);
if(!dir.exists()){
// system((char *)((QString("mkdir -p %1").arg(UDISK_LOGINFO_ROOT_DIR)).toLatin1().data()));
system((char *)((QString("mkdir -p %1").arg(UDISK_LOGINFO_ROOT_DIR)).toLocal8Bit().data()));
}
if(!dir.exists()){
QMessageBox::warning(this,tr("警告"),tr("U盘目录创建失败"));
return;
}
//插入U盘后,检测目录usb-storage是否存在
if(!QDir("/proc/scsi/usb-storage/").exists()){
QMessageBox::warning(this,tr("警告"),tr("U盘未插入或无法识别,请重新插拔设备!"));
return;
}
// system((char *)((QString("cp -r %1/* %2/").arg(LOGINFOFILE_DIR).arg(UDISK_LOGINFO_ROOT_DIR)).toLatin1().data()));
system((char *)((QString("cp -r %1/* %2/").arg(LOGINFOFILE_DIR).arg(UDISK_LOGINFO_ROOT_DIR)).toLocal8Bit().data()));
//refreshListView(EditMode);
system("sync");
QMessageBox::information(this, tr("提示"),
tr("成功导出到U盘"));
}
}
void LogInfo::on_pushButtonPreState_pressed(){
if(textEdit2){
//setRunStatusText(QString("FILE COUNT:%1").arg( QDir("/home/plg/loginfo/").count()));
//if( QDir("/home/plg/loginfo/").count()<4) {
if( QDir("/home/plg/loginfo/").count()<1) {
//QMessageBox::warning(this,"警告","没有历史文件");
textEdit2->setText( "目前历史文件数量为0个");
return;
}
//qDebug()<<"3333";
if(openFileName.isEmpty()) textEdit2->clear();
if(fileDialog) {
// qDebug()<<"4444";
disconnect(fileDialog,SIGNAL(accepted()),0,0); // 如果对话框已经定义,则删除控件关联,否则也会出错。
}
else {//qDebug()<<"5";
fileDialog = new MyFileDialog(0);
//qDebug()<<"6";
}
//qDebug()<<"7";
QDir dir1;
dir1.setPath(QString ("/home/plg/loginfo/"));
if(!dir1.exists())
{dir1.mkdir(QString ("/home/plg/loginfo/"));}
if(fileDialog){
//qDebug()<<"8";
if(fileDialog->directory().path()!="/home/plg/loginfo")
fileDialog->setDirectory(QDir("/home/plg/loginfo"));
//qDebug()<<"read File 3.2"<<dir1.Name;
connect(fileDialog,SIGNAL(accepted()),this,SLOT(onOpen_FIle_select()));
//qDebug()<<"read File 4"<<dir1.Name;
fileDialog->showFileDialog(tr("选择历史记录文件"),dir1.path(),QString("Txt files (*.txt)"));
//qDebug()<<"read File 5";
}
//else qDebug()<<"read File:"<<dir1.path();
}
}
void LogInfo::onOpen_FIle_select()
{
QStringList files = fileDialog->selectedFiles();
if( files.size()==0) return ;
if(QString(files[0]).isNull()) return;
QString fileName = files[0];
if(!fileName.endsWith(".txt",Qt::CaseInsensitive)) return ;
openFileName = fileName;
QFile file(openFileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QMessageBox::warning(this,tr("警告"),tr("无法打开文件") + openFileName);
}
else{
QTextStream in (&file);
textEdit2->setText(in.readAll());
textEdit2->moveCursor(QTextCursor::End);//滚动条移到底部
//ui->labelPreFileName->setText(file.fileName());
QFileInfo info(file.fileName());
ui->labelPreFileName->setText(info.fileName());
}
file.close();
ui->tabWidget->setCurrentWidget(ui->tab_2);
}
void LogInfo::on_pushButtonClear_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将历史日志文件全部清除?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QDir dir1(QString("/home/plg/loginfo/"));
if(dir1.exists())
{
system((char *)QString("rm /home/plg/loginfo/*.*").toLatin1().data());
deleteDirectoryContents(dir1);
}
else system((char *)QString("mkdir /home/plg/loginfo/").toLatin1().data());
}
}
void LogInfo::on_pushButtonClearCurrent_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将当前日志全部清除?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
textEdit->clear();
runStatusTextIndex=0;
}
}
void LogInfo::onReadRecorder()
{
QString fileName = ":/buge_record.txt";
if(!fileName.endsWith(".txt",Qt::CaseInsensitive)) return ;
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QMessageBox::warning(this,tr("警告"),tr("无法打开文件") + openFileName);
}
else{
QTextStream in (&file);
textEditMachInfo->setText(in.readAll());
}
}
void LogInfo::deleteDirectoryContents(const QDir &directory) {
QList<QFileInfo> entries = directory.entryInfoList(
QDir::NoDotAndDotDot | QDir::AllEntries);
QString today = QDate::currentDate().toString(Qt::ISODate);
// 使用传统的 for 循环遍历所有条目
for (int i = 0; i < entries.size(); ++i) {
QFileInfo entryInfo = entries.at(i);
QString dirName=entryInfo.baseName();
if(today==dirName)
continue;
QString fullPath = entryInfo.absoluteFilePath();
if (entryInfo.isFile() || entryInfo.isSymLink()) {
// 如果是文件或符号链接,尝试删除
if (!QFile::remove(fullPath)) {
qDebug() << "Failed to remove file or symlink:" << fullPath;
}
} else if (entryInfo.isDir()) {
// 如果是目录,递归调用以删除其内容
QDir subDir(fullPath);
deleteDirectoryContents(subDir);
// 目录现在应该是空的,尝试删除它
if (!QDir().rmdir(fullPath)) {
qDebug() << "Failed to remove directory:" << fullPath;
}
}
}
}
// 删除指定文件夹超过七天的文件
void LogInfo::deleteOldLog(const QString folderPath,int days){
QDir dir(folderPath); // 创建一个QDir对象用于操作传入的文件夹路径
if (!dir.exists()) { // 判断传入文件夹是否存在
qDebug() << "文件夹不存在";
return;
}
QDateTime currentDateTime = QDateTime::currentDateTime(); // 获取当前时间
QDateTime sevenDaysAgo = currentDateTime.addDays(-days); // 计算days天前的日期时间
// 目录下的文件和子目录的信息列表,列出所有文件和子目录并按照最后修改时间排序
QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time);
foreach (QFileInfo fileInfo ,fileInfoList) {
if (!fileInfo.isDir()){
QString fileExtension = fileInfo.suffix().toLower(); // 获取文件的扩展名并确保它是小写的
// 选择删除那种图片类型
if (fileExtension == "txt") {
if (fileInfo.lastModified() < sevenDaysAgo && fileInfo.fileName().indexOf('_')!=-1) { // 获取最后一个文件夹修改时间和days传入的时间最对比
if (QFile::remove(fileInfo.absoluteFilePath())) { // 删除满足条件的文件的绝对路径
qDebug() << "删除成功" << fileInfo.absoluteFilePath();
} else {
qDebug() << "文件删除失败" << fileInfo.absoluteFilePath();
}
}
}
}
}
}
void LogInfo::deleteOldLog()
{
qDebug()<<"延时60秒删除过期日志";
deleteOldLog(LOGINFOFILE_DIR,7);//删除一周前的日志
timerLogdel->stop();
}
void LogInfo::truncatelog()
{
const QString dts=QDate::currentDate().toString("yyyyMMdd") ;
const QString fileNameL=QString(LOGINFOFILE_DIR)+dts +"_1.txt";
QFile file(fileNameL);
if(file.size()>204800)//文件大小
{
QSettings settings("MySoft", "MyApp");
int filenum=settings.value(dts,2).toInt();
if(filenum==2)
settings.clear();
settings.setValue(dts,filenum+1);
qDebug()<<"rename="<<fileNameL << QString(LOGINFOFILE_DIR)+dts +QString("_%1.txt").arg(filenum);
file.rename(QString(LOGINFOFILE_DIR)+dts +QString("_%1.txt").arg(filenum));
}
}
void LogInfo::setScrollBar(){
QString styleSheet = "\n\
QTextEdit QScrollBar:vertical {\n\
width: 50px; /* 设置垂直滚动条的宽度 */\n\
background: rgba(0, 0, 0, 0); /* 滚动条背景透明 */\n\
margin: 20px 0 20px 0; /* 为按钮留出空间 */\n\
}\n\
QTextEdit QScrollBar::handle:vertical {\n\
background: rgb(125, 170, 177); /* 滑块颜色 */\n\
border-radius: 5px; /* 滑块圆角 */\n\
min-height: 40px; /* 滑块最小高度 */\n\
}\n\
QTextEdit QScrollBar::add-line:vertical {\n\
height: 40px; /* 设置向下按钮的高度 */\n\
background: rgb(255, 170, 127); /* 按钮颜色 */\n\
subcontrol-position: bottom;\n\
subcontrol-origin: margin;\n\
}\n\
QTextEdit QScrollBar::sub-line:vertical {\n\
height: 40px; /* 设置向上按钮的高度 */\n\
background: rgb(255, 170, 127); /* 按钮颜色 */\n\
subcontrol-position: top;\n\
subcontrol-origin: margin;\n\
}";
ui->textEditRunStatus->setStyleSheet(styleSheet);
ui->textEditRunStatus_2->setStyleSheet(styleSheet);
}
#include "LogInfo.h"
#include "ui_loginfo.h"
#include <QTime>
#include <QDir>
#include <QDebug>
#include <QFile>
#include <QIODevice>
#include <QTextDocumentWriter>
#include <QMessageBox>
#include "DevOp.h"
#include <stdio.h>
#include "myinclude.h"
#include <QScrollBar>
#include <QSettings>
#ifndef LOGINFOFILE_DIR
#define LOGINFOFILE_DIR "/home/plg/loginfo/"
#endif
#define UDISK_LOGINFO_ROOT_DIR "/udisk/log/"
LogInfo::LogInfo(QWidget *parent) :
QWidget(parent),
ui(new Ui::LogInfo)
{
ui->setupUi(this);
ui->textEditRunStatus->setReadOnly(true);
ui->textEditRunStatus_2->setReadOnly(true);
textEdit = ui->textEditRunStatus;
textEdit->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 40px; }");
textEdit2 = ui->textEditRunStatus_2;
//textEdit2->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 40px; }");
textEdit2->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 40px; }");
textEditMachInfo = ui->machinInformation;
runStatusTextIndex = 0;
openFileName ="";
ui->labelPreFileName->setText("");
//currenDate="";
//r_CurrentDate=QDate::currentDate().toString("yyyyMMdd");
textEdit2->append(tr("请先打开历史状态文件!"));
if(!QDir("/home/plg").exists())
QDir("/home/plg").mkdir("/home/plg");
readRunStatusText();
runStatusTextIndex = textEdit->document()->lineCount();
fileDialog=0; // 先初始化为0 ,否则会死机
QFile file(SYS_ROOT_DIR"UseEn");
if(!file.exists()){
onReadRecorder( );
}
timerLogdel=new QTimer(this);
connect(timerLogdel, SIGNAL(timeout()), this, SLOT(deleteOldLog()));
//延时60秒删除日志文件
timerLogdel->start(60000);
setScrollBar();
}
LogInfo::~LogInfo()
{
textEdit = 0;
textEdit2 = 0;
textEditMachInfo = 0;
if(fileDialog)
delete fileDialog;
delete ui;
disconnect(timerLogdel, SIGNAL(timeout()), this, SLOT(deleteOldLog()));
timerLogdel->stop();
}
QTextEdit *LogInfo::textEdit = 0;
QTextEdit *LogInfo::textEdit2 = 0;
QTextEdit *LogInfo::textEditMachInfo = 0;
int LogInfo::runStatusTextIndex = 0;
void LogInfo::showMachineInformation(QString Mac,QString SerialNum, QString VernonBachVer, QString FpgaVer)
{
QString machInfo;
machInfo = "Mac:" + Mac + "\n";
machInfo += "VernonBach Ver:" + VernonBachVer + "\n";
machInfo += "FPGA Ver:" + FpgaVer;
textEditMachInfo->setText(machInfo);
}
void LogInfo::showVerionInformation(QString Mac,QString VernonBachVer, QString FpgaVer,QString STM32Ver,bool powerOnMode)
{
static bool flag = false;
if(!flag){
QString machInfo;
machInfo = "Mac:" + Mac + "\n";
machInfo += "VernonBach Ver:" + VernonBachVer +"|"+STM32Ver+ "\n";
machInfo += "FPGA Ver: NO" + FpgaVer + "\n";
machInfo += "PowerOnMode: " + QString::number(powerOnMode) + "\n";
textEditMachInfo->append(machInfo);
}
}
void LogInfo::showRemoteControll(QString SuperNode, QString edgeIP)
{
QString machInfo = textEditMachInfo->toPlainText();
machInfo += "SuperNode:" + SuperNode + "\n";
machInfo += "edgeIP:" + edgeIP + "\n";
textEditMachInfo->setText(machInfo);
}
//edit@01-11
void LogInfo::setRunStatusText(QString str){
if(!textEdit){
return;
}
const int maxTextEditHeight = 2000;
if(textEdit->document()->size().height() > maxTextEditHeight)
{
textEdit->clear(); //显示今天全部信息,加载太多可能会死机
}
str.prepend(QString("%1. %2:").arg(QString::number(runStatusTextIndex ++ )).arg(QTime::currentTime().toString("hh:mm:ss")));
textEdit->append(str);
{
// 使用静态缓冲区批量写入,避免每次调用都 open/close 文件导致 ARM 板 I/O 繁忙
static QStringList pendingLines;
static QString lastDate;
static int pendingTotalLen = 0; // 增量维护总字符数,避免每次扫描
const QString dts = QDate::currentDate().toString("yyyyMMdd");
if(dts != lastDate){
// 日期变化时先把旧缓冲写入旧文件
if(!pendingLines.isEmpty() && !lastDate.isEmpty()){
QString oldFile = QString(LOGINFOFILE_DIR) + lastDate + "_1.txt";
QFile f(oldFile);
if(f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
QTextStream out(&f);
for(const QString &line : pendingLines)
out << line << endl;
f.close();
}
pendingLines.clear();
pendingTotalLen = 0;
}
lastDate = dts;
}
pendingLines.append(str);
pendingTotalLen += str.length();
// 每累积 10 条或字符总量超过 2KB 时批量写入一次
if(pendingLines.size() >= 10 || pendingTotalLen > 2048){
QString fileNameL = QString(LOGINFOFILE_DIR) + dts + "_1.txt";
QFile file(fileNameL);
if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
QTextStream out(&file);
for(const QString &line : pendingLines)
out << line << endl;
file.close();
}
pendingLines.clear();
pendingTotalLen = 0;
truncatelog();
}
}
}
QString LogInfo::getRunStatusText(void){
return "";
}
void LogInfo::readRunStatusText()
{
QString fileName;
if(textEdit){
QDir dir1;
dir1.setPath(LOGINFOFILE_DIR);
if(!dir1.exists())
dir1.mkdir(QString ("/home/plg/loginfo/"));
fileName=QString("/home/plg/loginfo/")+QDate::currentDate().toString("yyyyMMdd")+"_1.txt";
QFile file(fileName);
if(file.exists()){
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QMessageBox::warning(this,tr("警告"),tr("无法打开文件") + file.fileName());
}
else{
QTextStream in (&file);
textEdit->setText(in.readAll());
}
file.close();
ui->tabWidget->setCurrentWidget(ui->tab);
}
QDate date1 = QDate::currentDate();
for(int i=0;i<8;i++)
{
fileName=QString("/home/plg/loginfo/")+date1.addDays(-i-5).toString("yyyyMMdd")+".txt";
file.setFileName(fileName);
if(file.exists()){
file.remove();
}
}
}
}
void LogInfo::on_pushButtonExportFile_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将所有日志文件导出到U盘?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
//QString dirPath = ui->radioButtonLocal->isChecked()?DOC_ROOT_DIR:UDISK_LOGINFO_ROOT_DIR;
QDir dir(UDISK_LOGINFO_ROOT_DIR);
if(!dir.exists()){
// system((char *)((QString("mkdir -p %1").arg(UDISK_LOGINFO_ROOT_DIR)).toLatin1().data()));
system((char *)((QString("mkdir -p %1").arg(UDISK_LOGINFO_ROOT_DIR)).toLocal8Bit().data()));
}
if(!dir.exists()){
QMessageBox::warning(this,tr("警告"),tr("U盘目录创建失败"));
return;
}
//插入U盘后,检测目录usb-storage是否存在
if(!QDir("/proc/scsi/usb-storage/").exists()){
QMessageBox::warning(this,tr("警告"),tr("U盘未插入或无法识别,请重新插拔设备!"));
return;
}
// system((char *)((QString("cp -r %1/* %2/").arg(LOGINFOFILE_DIR).arg(UDISK_LOGINFO_ROOT_DIR)).toLatin1().data()));
system((char *)((QString("cp -r %1/* %2/").arg(LOGINFOFILE_DIR).arg(UDISK_LOGINFO_ROOT_DIR)).toLocal8Bit().data()));
//refreshListView(EditMode);
system("sync");
QMessageBox::information(this, tr("提示"),
tr("成功导出到U盘"));
}
}
void LogInfo::on_pushButtonPreState_pressed(){
if(textEdit2){
//setRunStatusText(QString("FILE COUNT:%1").arg( QDir("/home/plg/loginfo/").count()));
//if( QDir("/home/plg/loginfo/").count()<4) {
if( QDir("/home/plg/loginfo/").count()<1) {
//QMessageBox::warning(this,"警告","没有历史文件");
textEdit2->setText( "目前历史文件数量为0个");
return;
}
//qDebug()<<"3333";
if(openFileName.isEmpty()) textEdit2->clear();
if(fileDialog) {
// qDebug()<<"4444";
disconnect(fileDialog,SIGNAL(accepted()),0,0); // 如果对话框已经定义,则删除控件关联,否则也会出错。
}
else {//qDebug()<<"5";
fileDialog = new MyFileDialog(0);
//qDebug()<<"6";
}
//qDebug()<<"7";
QDir dir1;
dir1.setPath(QString ("/home/plg/loginfo/"));
if(!dir1.exists())
{dir1.mkdir(QString ("/home/plg/loginfo/"));}
if(fileDialog){
//qDebug()<<"8";
if(fileDialog->directory().path()!="/home/plg/loginfo")
fileDialog->setDirectory(QDir("/home/plg/loginfo"));
//qDebug()<<"read File 3.2"<<dir1.Name;
connect(fileDialog,SIGNAL(accepted()),this,SLOT(onOpen_FIle_select()));
//qDebug()<<"read File 4"<<dir1.Name;
fileDialog->showFileDialog(tr("选择历史记录文件"),dir1.path(),QString("Txt files (*.txt)"));
//qDebug()<<"read File 5";
}
//else qDebug()<<"read File:"<<dir1.path();
}
}
void LogInfo::onOpen_FIle_select()
{
QStringList files = fileDialog->selectedFiles();
if( files.size()==0) return ;
if(QString(files[0]).isNull()) return;
QString fileName = files[0];
if(!fileName.endsWith(".txt",Qt::CaseInsensitive)) return ;
openFileName = fileName;
QFile file(openFileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QMessageBox::warning(this,tr("警告"),tr("无法打开文件") + openFileName);
}
else{
QTextStream in (&file);
textEdit2->setText(in.readAll());
textEdit2->moveCursor(QTextCursor::End);//滚动条移到底部
//ui->labelPreFileName->setText(file.fileName());
QFileInfo info(file.fileName());
ui->labelPreFileName->setText(info.fileName());
}
file.close();
ui->tabWidget->setCurrentWidget(ui->tab_2);
}
void LogInfo::on_pushButtonClear_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将历史日志文件全部清除?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
QDir dir1(QString("/home/plg/loginfo/"));
if(dir1.exists())
{
system((char *)QString("rm /home/plg/loginfo/*.*").toLatin1().data());
deleteDirectoryContents(dir1);
}
else system((char *)QString("mkdir /home/plg/loginfo/").toLatin1().data());
}
}
void LogInfo::on_pushButtonClearCurrent_pressed()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::information(this, tr("提示"),
tr("是否确认将当前日志全部清除?"),
QMessageBox::Ok | QMessageBox::Cancel);
if (ret == QMessageBox::Ok){
textEdit->clear();
runStatusTextIndex=0;
}
}
void LogInfo::onReadRecorder()
{
QString fileName = ":/buge_record.txt";
if(!fileName.endsWith(".txt",Qt::CaseInsensitive)) return ;
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QMessageBox::warning(this,tr("警告"),tr("无法打开文件") + openFileName);
}
else{
QTextStream in (&file);
textEditMachInfo->setText(in.readAll());
}
}
void LogInfo::deleteDirectoryContents(const QDir &directory) {
QList<QFileInfo> entries = directory.entryInfoList(
QDir::NoDotAndDotDot | QDir::AllEntries);
QString today = QDate::currentDate().toString(Qt::ISODate);
// 使用传统的 for 循环遍历所有条目
for (int i = 0; i < entries.size(); ++i) {
QFileInfo entryInfo = entries.at(i);
QString dirName=entryInfo.baseName();
if(today==dirName)
continue;
QString fullPath = entryInfo.absoluteFilePath();
if (entryInfo.isFile() || entryInfo.isSymLink()) {
// 如果是文件或符号链接,尝试删除
if (!QFile::remove(fullPath)) {
qDebug() << "Failed to remove file or symlink:" << fullPath;
}
} else if (entryInfo.isDir()) {
// 如果是目录,递归调用以删除其内容
QDir subDir(fullPath);
deleteDirectoryContents(subDir);
// 目录现在应该是空的,尝试删除它
if (!QDir().rmdir(fullPath)) {
qDebug() << "Failed to remove directory:" << fullPath;
}
}
}
}
// 删除指定文件夹超过七天的文件
void LogInfo::deleteOldLog(const QString folderPath,int days){
QDir dir(folderPath); // 创建一个QDir对象用于操作传入的文件夹路径
if (!dir.exists()) { // 判断传入文件夹是否存在
qDebug() << "文件夹不存在";
return;
}
QDateTime currentDateTime = QDateTime::currentDateTime(); // 获取当前时间
QDateTime sevenDaysAgo = currentDateTime.addDays(-days); // 计算days天前的日期时间
// 目录下的文件和子目录的信息列表,列出所有文件和子目录并按照最后修改时间排序
QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time);
foreach (QFileInfo fileInfo ,fileInfoList) {
if (!fileInfo.isDir()){
QString fileExtension = fileInfo.suffix().toLower(); // 获取文件的扩展名并确保它是小写的
// 选择删除那种图片类型
if (fileExtension == "txt") {
if (fileInfo.lastModified() < sevenDaysAgo && fileInfo.fileName().indexOf('_')!=-1) { // 获取最后一个文件夹修改时间和days传入的时间最对比
if (QFile::remove(fileInfo.absoluteFilePath())) { // 删除满足条件的文件的绝对路径
qDebug() << "删除成功" << fileInfo.absoluteFilePath();
} else {
qDebug() << "文件删除失败" << fileInfo.absoluteFilePath();
}
}
}
}
}
}
void LogInfo::deleteOldLog()
{
qDebug()<<"延时60秒删除过期日志";
deleteOldLog(LOGINFOFILE_DIR,7);//删除一周前的日志
timerLogdel->stop();
}
void LogInfo::truncatelog()
{
const QString dts=QDate::currentDate().toString("yyyyMMdd") ;
const QString fileNameL=QString(LOGINFOFILE_DIR)+dts +"_1.txt";
QFile file(fileNameL);
if(file.size()>204800)//文件大小
{
QSettings settings("MySoft", "MyApp");
int filenum=settings.value(dts,2).toInt();
if(filenum==2)
settings.clear();
settings.setValue(dts,filenum+1);
qDebug()<<"rename="<<fileNameL << QString(LOGINFOFILE_DIR)+dts +QString("_%1.txt").arg(filenum);
file.rename(QString(LOGINFOFILE_DIR)+dts +QString("_%1.txt").arg(filenum));
}
}
void LogInfo::setScrollBar(){
QString styleSheet = "\n\
QTextEdit QScrollBar:vertical {\n\
width: 50px; /* 设置垂直滚动条的宽度 */\n\
background: rgba(0, 0, 0, 0); /* 滚动条背景透明 */\n\
margin: 20px 0 20px 0; /* 为按钮留出空间 */\n\
}\n\
QTextEdit QScrollBar::handle:vertical {\n\
background: rgb(125, 170, 177); /* 滑块颜色 */\n\
border-radius: 5px; /* 滑块圆角 */\n\
min-height: 40px; /* 滑块最小高度 */\n\
}\n\
QTextEdit QScrollBar::add-line:vertical {\n\
height: 40px; /* 设置向下按钮的高度 */\n\
background: rgb(255, 170, 127); /* 按钮颜色 */\n\
subcontrol-position: bottom;\n\
subcontrol-origin: margin;\n\
}\n\
QTextEdit QScrollBar::sub-line:vertical {\n\
height: 40px; /* 设置向上按钮的高度 */\n\
background: rgb(255, 170, 127); /* 按钮颜色 */\n\
subcontrol-position: top;\n\
subcontrol-origin: margin;\n\
}";
ui->textEditRunStatus->setStyleSheet(styleSheet);
ui->textEditRunStatus_2->setStyleSheet(styleSheet);
}
+56 -56
View File
@@ -1,56 +1,56 @@
#ifndef LOGINFO_H
#define LOGINFO_H
#include <QWidget>
#include <QTextEdit>
#include "MyFileDialog.h"
#include <QDate>
#include <QTimer>
namespace Ui {
class LogInfo;
}
class LogInfo : public QWidget
{
Q_OBJECT
public:
explicit LogInfo(QWidget *parent = 0);
~LogInfo();
static QString getRunStatusText(void);
static void setRunStatusText(QString str);
static void showMachineInformation(QString Mac,QString SerialNum, QString VernonBachVer, QString FpgaVer);
static void showRemoteControll(QString SuperNode, QString edgeIP);
void onReadRecorder();
void deleteDirectoryContents(const QDir &directory);
static void truncatelog();
static void showVerionInformation(QString,QString,QString,QString,bool);
void setScrollBar();
protected slots:
void deleteOldLog(const QString folderPath, int days);
void deleteOldLog();
private slots:
void on_pushButtonClear_pressed();
void on_pushButtonPreState_pressed();
void on_pushButtonExportFile_pressed();
void on_pushButtonClearCurrent_pressed();
void onOpen_FIle_select();
void readRunStatusText();
private:
Ui::LogInfo *ui;
static QTextEdit *textEdit;
static QTextEdit *textEdit2;
static QTextEdit *textEditMachInfo;
static int runStatusTextIndex;
MyFileDialog *fileDialog;
QString openFileName;
static QString currenDate;
static QString r_CurrentDate;
QTimer *timerLogdel;
};
#endif // LOGINFO_H
#ifndef LOGINFO_H
#define LOGINFO_H
#include <QWidget>
#include <QTextEdit>
#include "MyFileDialog.h"
#include <QDate>
#include <QTimer>
namespace Ui {
class LogInfo;
}
class LogInfo : public QWidget
{
Q_OBJECT
public:
explicit LogInfo(QWidget *parent = 0);
~LogInfo();
static QString getRunStatusText(void);
static void setRunStatusText(QString str);
static void showMachineInformation(QString Mac,QString SerialNum, QString VernonBachVer, QString FpgaVer);
static void showRemoteControll(QString SuperNode, QString edgeIP);
void onReadRecorder();
void deleteDirectoryContents(const QDir &directory);
static void truncatelog();
static void showVerionInformation(QString,QString,QString,QString,bool);
void setScrollBar();
protected slots:
void deleteOldLog(const QString folderPath, int days);
void deleteOldLog();
private slots:
void on_pushButtonClear_pressed();
void on_pushButtonPreState_pressed();
void on_pushButtonExportFile_pressed();
void on_pushButtonClearCurrent_pressed();
void onOpen_FIle_select();
void readRunStatusText();
private:
Ui::LogInfo *ui;
static QTextEdit *textEdit;
static QTextEdit *textEdit2;
static QTextEdit *textEditMachInfo;
static int runStatusTextIndex;
MyFileDialog *fileDialog;
QString openFileName;
static QString currenDate;
static QString r_CurrentDate;
QTimer *timerLogdel;
};
#endif // LOGINFO_H
+351 -351
View File
@@ -1,351 +1,351 @@
/* common.c - Contains functions needed for a number of barcodes */
/*
libzint - the open source barcode library
Copyright (C) 2008 Robin Stuart <robin@zint.org.uk>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
int ustrlen(unsigned char data[]) {
/* Local replacement for strlen() with unsigned char strings */
int i;
for (i=0;data[i];i++);
return i;
}
void ustrcpy(unsigned char target[], unsigned char source[]) {
/* Local replacement for strcpy() with unsigned char strings */
int i, len;
len = ustrlen(source);
for(i = 0; i < len; i++) {
target[i] = source[i];
}
target[i] = '\0';
}
void concat(char dest[], char source[])
{ /* Concatinates dest[] with the contents of source[], copying /0 as well */
unsigned int i, j, n;
j = strlen(dest);
n = strlen(source);
for(i = 0; i <= n; i++) {
dest[i + j] = source[i]; }
}
void uconcat(unsigned char dest[], unsigned char source[])
{ /* Concatinates dest[] with the contents of source[], copying /0 as well */
unsigned int i, j;
j = ustrlen(dest);
for(i = 0; i <= ustrlen(source); i++) {
dest[i + j] = source[i]; }
}
int ctoi(char source)
{ /* Converts a character 0-9 to its equivalent integer value */
if((source >= '0') && (source <= '9'))
return (source - '0');
return(source - 'A' + 10);
}
char itoc(int source)
{ /* Converts an integer value to its hexadecimal character */
if ((source >= 0) && (source <= 9)) {
return ('0' + source); }
else {
return ('A' + (source - 10)); }
}
void to_upper(unsigned char source[])
{ /* Converts lower case characters to upper case in a string source[] */
unsigned int i, src_len = ustrlen(source);
for (i = 0; i < src_len; i++) {
if ((source[i] >= 'a') && (source[i] <= 'z')) {
source [i] = (source[i] - 'a') + 'A'; }
}
}
int is_sane(char test_string[], unsigned char source[], int length)
{ /* Verifies that a string only uses valid characters */
unsigned int i, j, latch;
unsigned int lt = strlen(test_string);
for(i = 0; i < length; i++) {
latch = FALSE;
for(j = 0; j < lt; j++) {
if (source[i] == test_string[j]) {
latch = TRUE;
break;
}
}
if (!(latch)) {
return ERROR_INVALID_DATA;
}
}
return 0;
}
int posn(char set_string[], char data)
{ /* Returns the position of data in set_string */
unsigned int i, n = strlen(set_string);
for(i = 0; i < n; i++) {
if (data == set_string[i]) { return i; } }
return 0;
}
void lookup(char set_string[], char *table[], char data, char dest[])
{ /* Replaces huge switch statements for looking up in tables */
unsigned int i, n = strlen(set_string);
for(i = 0; i < n; i++) {
if (data == set_string[i]) { concat(dest, table[i]); } }
}
int module_is_set(struct zint_symbol *symbol, int y_coord, int x_coord)
{
return (symbol->encoded_data[y_coord][x_coord / 7] & (1 << (x_coord % 7))) ? 1 : 0;
}
void set_module(struct zint_symbol *symbol, int y_coord, int x_coord)
{
if(module_is_set(symbol, y_coord, x_coord)) { return; }
symbol->encoded_data[y_coord][x_coord / 7] += 1 << (x_coord % 7);
}
void unset_module(struct zint_symbol *symbol, int y_coord, int x_coord)
{
if(!(module_is_set(symbol, y_coord, x_coord))) { return; }
symbol->encoded_data[y_coord][x_coord / 7] -= 1 << (x_coord % 7);
}
void expand(struct zint_symbol *symbol, char data[])
{ /* Expands from a width pattern to a bit pattern */
unsigned int reader, n = strlen(data);
int writer, i;
char latch;
writer = 0;
latch = '1';
for(reader = 0; reader < n; reader++) {
for(i = 0; i < ctoi(data[reader]); i++) {
if(latch == '1') { set_module(symbol, symbol->rows, writer); }
writer++;
}
if(latch == '1') {
latch = '0';
} else {
latch = '1';
}
}
if(symbol->symbology != BARCODE_PHARMA) {
if(writer > symbol->width) {
symbol->width = writer;
}
} else {
/* Pharmacode One ends with a space - adjust for this */
if(writer > symbol->width + 2) {
symbol->width = writer - 2;
}
}
symbol->rows = symbol->rows + 1;
}
int is_stackable(int symbology) {
/* Indicates which symbologies can have row binding */
if(symbology < BARCODE_PDF417) { return 1; }
if(symbology == BARCODE_CODE128B) { return 1; }
if(symbology == BARCODE_ISBNX) { return 1; }
if(symbology == BARCODE_EAN14) { return 1; }
if(symbology == BARCODE_NVE18) { return 1; }
if(symbology == BARCODE_KOREAPOST) { return 1; }
if(symbology == BARCODE_PLESSEY) { return 1; }
if(symbology == BARCODE_TELEPEN_NUM) { return 1; }
if(symbology == BARCODE_ITF14) { return 1; }
if(symbology == BARCODE_CODE32) { return 1; }
return 0;
}
int is_extendable(int symbology) {
/* Indicates which symbols can have addon */
if(symbology == BARCODE_EANX) { return 1; }
if(symbology == BARCODE_UPCA) { return 1; }
if(symbology == BARCODE_UPCE) { return 1; }
if(symbology == BARCODE_ISBNX) { return 1; }
if(symbology == BARCODE_UPCA_CC) { return 1; }
if(symbology == BARCODE_UPCE_CC) { return 1; }
if(symbology == BARCODE_EANX_CC) { return 1; }
return 0;
}
int roundup(float input)
{
float remainder;
int integer_part;
integer_part = (int)input;
remainder = input - integer_part;
if(remainder > 0.1) {
integer_part++;
}
return integer_part;
}
int istwodigits(unsigned char source[], int position)
{
if((source[position] >= '0') && (source[position] <= '9')) {
if((source[position + 1] >= '0') && (source[position + 1] <= '9')) {
return 1;
}
}
return 0;
}
float froundup(float input)
{
float fraction, output = 0.0;
fraction = input - (int)input;
if(fraction > 0.01) { output = (input - fraction) + 1.0; } else { output = input; }
return output;
}
int latin1_process(struct zint_symbol *symbol, unsigned char source[], unsigned char preprocessed[], int *length)
{
int j, i, next;
/* Convert Unicode to Latin-1 for those symbologies which only support Latin-1 */
j = 0;
i = 0;
do {
next = -1;
if(source[i] < 128) {
preprocessed[j] = source[i];
j++;
next = i + 1;
} else {
if(source[i] == 0xC2) {
preprocessed[j] = source[i + 1];
j++;
next = i + 2;
}
if(source[i] == 0xC3) {
preprocessed[j] = source[i + 1] + 64;
j++;
next = i + 2;
}
}
if(next == -1) {
strcpy(symbol->errtxt, "error: Invalid character in input string (only Latin-1 characters supported)");
return ERROR_INVALID_DATA;
}
i = next;
} while(i < *length);
preprocessed[j] = '\0';
*length = j;
return 0;
}
int utf8toutf16(struct zint_symbol *symbol, unsigned char source[], int vals[], int *length)
{
int bpos, jpos, error_number, done;
int next;
bpos = 0;
jpos = 0;
error_number = 0;
next = 0;
do {
done = 0;
if(source[bpos] <= 0x7f) {
/* 1 byte mode (7-bit ASCII) */
vals[jpos] = source[bpos];
next = bpos + 1;
jpos++;
done = 1;
}
if(done == 0) {
if((source[bpos] >= 0x80) && (source[bpos] <= 0xbf)) {
strcpy(symbol->errtxt, "Corrupt Unicode data");
return ERROR_INVALID_DATA;
}
}
if(done == 0) {
if((source[bpos] >= 0xc0) && (source[bpos] <= 0xc1)) {
strcpy(symbol->errtxt, "Overlong encoding not supported");
return ERROR_INVALID_DATA;
}
}
if(done == 0) {
if((source[bpos] >= 0xc2) && (source[bpos] <= 0xdf)) {
/* 2 byte mode */
vals[jpos] = ((source[bpos] & 0x1f) << 6) + (source[bpos + 1] & 0x3f);
next = bpos + 2;
jpos++;
done = 1;
}
}
if(done == 0) {
if((source[bpos] >= 0xe0) && (source[bpos] <= 0xef)) {
/* 3 byte mode */
vals[jpos] = ((source[bpos] & 0x0f) << 12) + ((source[bpos + 1] & 0x3f) << 6) + (source[bpos + 2] & 0x3f);
next = bpos + 3;
jpos ++;
done = 1;
}
}
if(done == 0) {
if(source[bpos] >= 0xf0) {
strcpy(symbol->errtxt, "Unicode sequences of more than 3 bytes not supported");
return ERROR_INVALID_DATA;
}
}
bpos = next;
} while(bpos < *length);
*length = jpos;
return error_number;
}
/* common.c - Contains functions needed for a number of barcodes */
/*
libzint - the open source barcode library
Copyright (C) 2008 Robin Stuart <robin@zint.org.uk>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
int ustrlen(unsigned char data[]) {
/* Local replacement for strlen() with unsigned char strings */
int i;
for (i=0;data[i];i++);
return i;
}
void ustrcpy(unsigned char target[], unsigned char source[]) {
/* Local replacement for strcpy() with unsigned char strings */
int i, len;
len = ustrlen(source);
for(i = 0; i < len; i++) {
target[i] = source[i];
}
target[i] = '\0';
}
void concat(char dest[], char source[])
{ /* Concatinates dest[] with the contents of source[], copying /0 as well */
unsigned int i, j, n;
j = strlen(dest);
n = strlen(source);
for(i = 0; i <= n; i++) {
dest[i + j] = source[i]; }
}
void uconcat(unsigned char dest[], unsigned char source[])
{ /* Concatinates dest[] with the contents of source[], copying /0 as well */
unsigned int i, j;
j = ustrlen(dest);
for(i = 0; i <= ustrlen(source); i++) {
dest[i + j] = source[i]; }
}
int ctoi(char source)
{ /* Converts a character 0-9 to its equivalent integer value */
if((source >= '0') && (source <= '9'))
return (source - '0');
return(source - 'A' + 10);
}
char itoc(int source)
{ /* Converts an integer value to its hexadecimal character */
if ((source >= 0) && (source <= 9)) {
return ('0' + source); }
else {
return ('A' + (source - 10)); }
}
void to_upper(unsigned char source[])
{ /* Converts lower case characters to upper case in a string source[] */
unsigned int i, src_len = ustrlen(source);
for (i = 0; i < src_len; i++) {
if ((source[i] >= 'a') && (source[i] <= 'z')) {
source [i] = (source[i] - 'a') + 'A'; }
}
}
int is_sane(char test_string[], unsigned char source[], int length)
{ /* Verifies that a string only uses valid characters */
unsigned int i, j, latch;
unsigned int lt = strlen(test_string);
for(i = 0; i < length; i++) {
latch = FALSE;
for(j = 0; j < lt; j++) {
if (source[i] == test_string[j]) {
latch = TRUE;
break;
}
}
if (!(latch)) {
return ERROR_INVALID_DATA;
}
}
return 0;
}
int posn(char set_string[], char data)
{ /* Returns the position of data in set_string */
unsigned int i, n = strlen(set_string);
for(i = 0; i < n; i++) {
if (data == set_string[i]) { return i; } }
return 0;
}
void lookup(char set_string[], char *table[], char data, char dest[])
{ /* Replaces huge switch statements for looking up in tables */
unsigned int i, n = strlen(set_string);
for(i = 0; i < n; i++) {
if (data == set_string[i]) { concat(dest, table[i]); } }
}
int module_is_set(struct zint_symbol *symbol, int y_coord, int x_coord)
{
return (symbol->encoded_data[y_coord][x_coord / 7] & (1 << (x_coord % 7))) ? 1 : 0;
}
void set_module(struct zint_symbol *symbol, int y_coord, int x_coord)
{
if(module_is_set(symbol, y_coord, x_coord)) { return; }
symbol->encoded_data[y_coord][x_coord / 7] += 1 << (x_coord % 7);
}
void unset_module(struct zint_symbol *symbol, int y_coord, int x_coord)
{
if(!(module_is_set(symbol, y_coord, x_coord))) { return; }
symbol->encoded_data[y_coord][x_coord / 7] -= 1 << (x_coord % 7);
}
void expand(struct zint_symbol *symbol, char data[])
{ /* Expands from a width pattern to a bit pattern */
unsigned int reader, n = strlen(data);
int writer, i;
char latch;
writer = 0;
latch = '1';
for(reader = 0; reader < n; reader++) {
for(i = 0; i < ctoi(data[reader]); i++) {
if(latch == '1') { set_module(symbol, symbol->rows, writer); }
writer++;
}
if(latch == '1') {
latch = '0';
} else {
latch = '1';
}
}
if(symbol->symbology != BARCODE_PHARMA) {
if(writer > symbol->width) {
symbol->width = writer;
}
} else {
/* Pharmacode One ends with a space - adjust for this */
if(writer > symbol->width + 2) {
symbol->width = writer - 2;
}
}
symbol->rows = symbol->rows + 1;
}
int is_stackable(int symbology) {
/* Indicates which symbologies can have row binding */
if(symbology < BARCODE_PDF417) { return 1; }
if(symbology == BARCODE_CODE128B) { return 1; }
if(symbology == BARCODE_ISBNX) { return 1; }
if(symbology == BARCODE_EAN14) { return 1; }
if(symbology == BARCODE_NVE18) { return 1; }
if(symbology == BARCODE_KOREAPOST) { return 1; }
if(symbology == BARCODE_PLESSEY) { return 1; }
if(symbology == BARCODE_TELEPEN_NUM) { return 1; }
if(symbology == BARCODE_ITF14) { return 1; }
if(symbology == BARCODE_CODE32) { return 1; }
return 0;
}
int is_extendable(int symbology) {
/* Indicates which symbols can have addon */
if(symbology == BARCODE_EANX) { return 1; }
if(symbology == BARCODE_UPCA) { return 1; }
if(symbology == BARCODE_UPCE) { return 1; }
if(symbology == BARCODE_ISBNX) { return 1; }
if(symbology == BARCODE_UPCA_CC) { return 1; }
if(symbology == BARCODE_UPCE_CC) { return 1; }
if(symbology == BARCODE_EANX_CC) { return 1; }
return 0;
}
int roundup(float input)
{
float remainder;
int integer_part;
integer_part = (int)input;
remainder = input - integer_part;
if(remainder > 0.1) {
integer_part++;
}
return integer_part;
}
int istwodigits(unsigned char source[], int position)
{
if((source[position] >= '0') && (source[position] <= '9')) {
if((source[position + 1] >= '0') && (source[position + 1] <= '9')) {
return 1;
}
}
return 0;
}
float froundup(float input)
{
float fraction, output = 0.0;
fraction = input - (int)input;
if(fraction > 0.01) { output = (input - fraction) + 1.0; } else { output = input; }
return output;
}
int latin1_process(struct zint_symbol *symbol, unsigned char source[], unsigned char preprocessed[], int *length)
{
int j, i, next;
/* Convert Unicode to Latin-1 for those symbologies which only support Latin-1 */
j = 0;
i = 0;
do {
next = -1;
if(source[i] < 128) {
preprocessed[j] = source[i];
j++;
next = i + 1;
} else {
if(source[i] == 0xC2) {
preprocessed[j] = source[i + 1];
j++;
next = i + 2;
}
if(source[i] == 0xC3) {
preprocessed[j] = source[i + 1] + 64;
j++;
next = i + 2;
}
}
if(next == -1) {
strcpy(symbol->errtxt, "error: Invalid character in input string (only Latin-1 characters supported)");
return ERROR_INVALID_DATA;
}
i = next;
} while(i < *length);
preprocessed[j] = '\0';
*length = j;
return 0;
}
int utf8toutf16(struct zint_symbol *symbol, unsigned char source[], int vals[], int *length)
{
int bpos, jpos, error_number, done;
int next;
bpos = 0;
jpos = 0;
error_number = 0;
next = 0;
do {
done = 0;
if(source[bpos] <= 0x7f) {
/* 1 byte mode (7-bit ASCII) */
vals[jpos] = source[bpos];
next = bpos + 1;
jpos++;
done = 1;
}
if(done == 0) {
if((source[bpos] >= 0x80) && (source[bpos] <= 0xbf)) {
strcpy(symbol->errtxt, "Corrupt Unicode data");
return ERROR_INVALID_DATA;
}
}
if(done == 0) {
if((source[bpos] >= 0xc0) && (source[bpos] <= 0xc1)) {
strcpy(symbol->errtxt, "Overlong encoding not supported");
return ERROR_INVALID_DATA;
}
}
if(done == 0) {
if((source[bpos] >= 0xc2) && (source[bpos] <= 0xdf)) {
/* 2 byte mode */
vals[jpos] = ((source[bpos] & 0x1f) << 6) + (source[bpos + 1] & 0x3f);
next = bpos + 2;
jpos++;
done = 1;
}
}
if(done == 0) {
if((source[bpos] >= 0xe0) && (source[bpos] <= 0xef)) {
/* 3 byte mode */
vals[jpos] = ((source[bpos] & 0x0f) << 12) + ((source[bpos + 1] & 0x3f) << 6) + (source[bpos + 2] & 0x3f);
next = bpos + 3;
jpos ++;
done = 1;
}
}
if(done == 0) {
if(source[bpos] >= 0xf0) {
strcpy(symbol->errtxt, "Unicode sequences of more than 3 bytes not supported");
return ERROR_INVALID_DATA;
}
}
bpos = next;
} while(bpos < *length);
*length = jpos;
return error_number;
}
+53 -53
View File
@@ -1,53 +1,53 @@
/* Used in some logic */
#ifndef __COMMON_H
#define __COMMON_H
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
/* The most commonly used set */
#define NEON "0123456789"
#include "zint.h"
#define U08 unsigned char
#define U16 unsigned short
#define U32 unsigned int
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
extern int ustrlen(unsigned char source[]);
extern void ustrcpy(unsigned char target[], unsigned char source[]);
extern void concat(char dest[], char source[]);
extern void uconcat(unsigned char dest[], unsigned char source[]);
extern int ctoi(char source);
extern char itoc(int source);
extern void to_upper(unsigned char source[]);
extern int is_sane(char test_string[], unsigned char source[], int length);
extern void lookup(char set_string[], char *table[], char data, char dest[]);
extern int posn(char set_string[], char data);
extern void expand(struct zint_symbol *symbol, char data[]);
extern int is_stackable(int symbology);
extern int is_extendable(int symbology);
extern int roundup(float input);
extern int module_is_set(struct zint_symbol *symbol, int y_coord, int x_coord);
extern void set_module(struct zint_symbol *symbol, int y_coord, int x_coord);
extern void unset_module(struct zint_symbol *symbol, int y_coord, int x_coord);
extern int istwodigits(unsigned char source[], int position);
extern float froundup(float input);
extern int parunmodd(unsigned char llyth);
extern int latin1_process(struct zint_symbol *symbol, unsigned char source[], unsigned char preprocessed[], int *length);
extern int utf8toutf16(struct zint_symbol *symbol, unsigned char source[], int vals[], int *length);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __COMMON_H */
/* Used in some logic */
#ifndef __COMMON_H
#define __COMMON_H
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
/* The most commonly used set */
#define NEON "0123456789"
#include "zint.h"
#define U08 unsigned char
#define U16 unsigned short
#define U32 unsigned int
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
extern int ustrlen(unsigned char source[]);
extern void ustrcpy(unsigned char target[], unsigned char source[]);
extern void concat(char dest[], char source[]);
extern void uconcat(unsigned char dest[], unsigned char source[]);
extern int ctoi(char source);
extern char itoc(int source);
extern void to_upper(unsigned char source[]);
extern int is_sane(char test_string[], unsigned char source[], int length);
extern void lookup(char set_string[], char *table[], char data, char dest[]);
extern int posn(char set_string[], char data);
extern void expand(struct zint_symbol *symbol, char data[]);
extern int is_stackable(int symbology);
extern int is_extendable(int symbology);
extern int roundup(float input);
extern int module_is_set(struct zint_symbol *symbol, int y_coord, int x_coord);
extern void set_module(struct zint_symbol *symbol, int y_coord, int x_coord);
extern void unset_module(struct zint_symbol *symbol, int y_coord, int x_coord);
extern int istwodigits(unsigned char source[], int position);
extern float froundup(float input);
extern int parunmodd(unsigned char llyth);
extern int latin1_process(struct zint_symbol *symbol, unsigned char source[], unsigned char preprocessed[], int *length);
extern int utf8toutf16(struct zint_symbol *symbol, unsigned char source[], int vals[], int *length);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __COMMON_H */
+943 -943
View File
File diff suppressed because it is too large Load Diff
+162 -162
View File
@@ -1,162 +1,162 @@
/* dm200.h - Handles Data Matrix ECC 200 */
/*
libzint - the open source barcode library
Copyright (C) 2009 Robin Stuart <robin@zint.org.uk>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "common.h"
#ifndef __IEC16022ECC200_H
#define __IEC16022ECC200_H
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
//void MatrixEnCode(unsigned char *intext);
//extern int data_matrix_200(struct zint_symbol *symbol, unsigned char source[]);
extern unsigned char *iec16022ecc200(short *Wptr, short *Hptr, unsigned char *barcode, short* type);
void Draw_Matrix(unsigned char *buffer);
//char DataMatrixdDrawImg(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize);
//char DataMatrixdDrawImg(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize,QImage *pImg);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#define MAXBARCODE 3116
#define DM_ASCII 1
#define DM_C40 2
#define DM_TEXT 3
#define DM_X12 4
#define DM_EDIFACT 5
#define DM_BASE256 6
static int c40_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
static int c40_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,
22,23,24,25,26,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 };
static int text_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3 };
static int text_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
22,23,24,25,26,0,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,27,28,29,30,31 };
static int intsymbol[] = {
0,1,3,5,7,8,10,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,2,4,6,9,11,14 };
static int matrixH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 32, 36, 40, 44, 48,
52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixW[] = {
10, 12, 18, 14, 32, 16, 26, 18, 20, 36, 22, 36, 24, 26, 48, 32, 36, 40, 44,
48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixFH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 16, 18, 20, 22, 24,
26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixFW[] = {
10, 12, 18, 14, 16, 16, 26, 18, 20, 18, 22, 18, 24, 26, 24, 16, 18, 20, 22,
24, 26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixbytes[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 204, 280, 368, 456, 576, 696, 816, 1050, 1304, 1558 };
static int matrixdatablock[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 102, 140, 92, 114, 144, 174, 136, 175, 163, 156 };
static int matrixrsblock[] = {
5, 7, 7, 10, 11, 12, 14, 14, 18, 18, 20, 24, 24, 28, 28, 36, 42, 48, 56, 68,
42, 56, 36, 48, 56, 68, 56, 68, 62, 62 };
/*
static int c40_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
static int c40_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,
22,23,24,25,26,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 };
static int text_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3 };
static int text_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
22,23,24,25,26,0,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,27,28,29,30,31 };
static int intsymbol[] = {
0,1,3,5,7,8,10,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,2,4,6,9,11,14 };
static int matrixH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 32, 36, 40, 44, 48,
52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixW[] = {
10, 12, 18, 14, 32, 16, 26, 18, 20, 36, 22, 36, 24, 26, 48, 32, 36, 40, 44,
48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixFH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 16, 18, 20, 22, 24,
26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixFW[] = {
10, 12, 18, 14, 16, 16, 26, 18, 20, 18, 22, 18, 24, 26, 24, 16, 18, 20, 22,
24, 26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixbytes[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 204, 280, 368, 456, 576, 696, 816, 1050, 1304, 1558 };
static int matrixdatablock[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 102, 140, 92, 114, 144, 174, 136, 175, 163, 156 };
static int matrixrsblock[] = {
5, 7, 7, 10, 11, 12, 14, 14, 18, 18, 20, 24, 24, 28, 28, 36, 42, 48, 56, 68,
42, 56, 36, 48, 56, 68, 56, 68, 62, 62 };
*/
#endif /* __IEC16022ECC200_H */
/* dm200.h - Handles Data Matrix ECC 200 */
/*
libzint - the open source barcode library
Copyright (C) 2009 Robin Stuart <robin@zint.org.uk>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "common.h"
#ifndef __IEC16022ECC200_H
#define __IEC16022ECC200_H
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
//void MatrixEnCode(unsigned char *intext);
//extern int data_matrix_200(struct zint_symbol *symbol, unsigned char source[]);
extern unsigned char *iec16022ecc200(short *Wptr, short *Hptr, unsigned char *barcode, short* type);
void Draw_Matrix(unsigned char *buffer);
//char DataMatrixdDrawImg(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize);
//char DataMatrixdDrawImg(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize,QImage *pImg);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#define MAXBARCODE 3116
#define DM_ASCII 1
#define DM_C40 2
#define DM_TEXT 3
#define DM_X12 4
#define DM_EDIFACT 5
#define DM_BASE256 6
static int c40_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
static int c40_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,
22,23,24,25,26,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 };
static int text_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3 };
static int text_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
22,23,24,25,26,0,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,27,28,29,30,31 };
static int intsymbol[] = {
0,1,3,5,7,8,10,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,2,4,6,9,11,14 };
static int matrixH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 32, 36, 40, 44, 48,
52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixW[] = {
10, 12, 18, 14, 32, 16, 26, 18, 20, 36, 22, 36, 24, 26, 48, 32, 36, 40, 44,
48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixFH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 16, 18, 20, 22, 24,
26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixFW[] = {
10, 12, 18, 14, 16, 16, 26, 18, 20, 18, 22, 18, 24, 26, 24, 16, 18, 20, 22,
24, 26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixbytes[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 204, 280, 368, 456, 576, 696, 816, 1050, 1304, 1558 };
static int matrixdatablock[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 102, 140, 92, 114, 144, 174, 136, 175, 163, 156 };
static int matrixrsblock[] = {
5, 7, 7, 10, 11, 12, 14, 14, 18, 18, 20, 24, 24, 28, 28, 36, 42, 48, 56, 68,
42, 56, 36, 48, 56, 68, 56, 68, 62, 62 };
/*
static int c40_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
static int c40_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,
22,23,24,25,26,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 };
static int text_shift[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3 };
static int text_value[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
3,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,4,5,6,7,8,9,10,11,12,13,
15,16,17,18,19,20,21,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
22,23,24,25,26,0,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,27,28,29,30,31 };
static int intsymbol[] = {
0,1,3,5,7,8,10,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,2,4,6,9,11,14 };
static int matrixH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 32, 36, 40, 44, 48,
52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixW[] = {
10, 12, 18, 14, 32, 16, 26, 18, 20, 36, 22, 36, 24, 26, 48, 32, 36, 40, 44,
48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
static int matrixFH[] = {
10, 12, 8, 14, 8, 16, 12, 18, 20, 12, 22, 16, 24, 26, 16, 16, 18, 20, 22, 24,
26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixFW[] = {
10, 12, 18, 14, 16, 16, 26, 18, 20, 18, 22, 18, 24, 26, 24, 16, 18, 20, 22,
24, 26, 16, 18, 20, 22, 24, 26, 20, 22, 24 };
static int matrixbytes[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 204, 280, 368, 456, 576, 696, 816, 1050, 1304, 1558 };
static int matrixdatablock[] = {
3, 5, 5, 8, 10, 12, 16, 18, 22, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144,
174, 102, 140, 92, 114, 144, 174, 136, 175, 163, 156 };
static int matrixrsblock[] = {
5, 7, 7, 10, 11, 12, 14, 14, 18, 18, 20, 24, 24, 28, 28, 36, 42, 48, 56, 68,
42, 56, 36, 48, 56, 68, 56, 68, 62, 62 };
*/
#endif /* __IEC16022ECC200_H */
+68 -68
View File
@@ -1,68 +1,68 @@
#include <stdio.h>
#include <string.h>
//
// U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize
#include "dm200.h"
#include "QImage"
#include "QDebug"
#define MAX_WIDTH_BYTE 48 // 384/8
char DataMatrixdDraw(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize);
//char DataMatrixdDrawImg(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize,QImage *pImg);
void Draw_Matrix(unsigned char *buffer)
{
U16 sColumns, sRows;
U08 *Grid;
sColumns = sRows = 0;
Grid = 0;
sColumns = sRows = 0;
short sizeType = 0;
Grid = iec16022ecc200((short*)&sRows, (short*)&sColumns, buffer, &sizeType);
DataMatrixdDraw(Grid,sRows,sColumns,2);
}
char DataMatrixdDraw(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize)
{
int Size=MSize;
int w = cColumns*Size;
int h = cRows*Size;
//qDebug()<<w<<h<<Size;
QImage QRImage(w,h,QImage::Format_ARGB32 );
QImage *img;
img = &QRImage;
img->fill(0x00ffffff);
/* data */
int margin=0;
U08 *p = OutBuff;
int ypos=0;//margin * Size;
int xpos=0;
int x,y,xx,yy,bit;
for(y=0; y<cRows; y++) {
bit = 7;
bit = 7 - (margin * Size % 8);
xpos=margin * Size;
for(x=0; x<cColumns; x++) {
for(xx=0; xx<Size; xx++) {
if((*p & 1) << bit){
for(yy=0; yy<Size; yy++) {
img->setPixel(xpos,h-1-(ypos+yy),0xff000000);
}
}
xpos++;
}
p++;
bit--;
if(bit < 0) {
//q++;
bit = 7;
}
}
ypos+=Size;
}
img->save("Myqr.bmp");
return 0;
}
#include <stdio.h>
#include <string.h>
//
// U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize
#include "dm200.h"
#include "QImage"
#include "QDebug"
#define MAX_WIDTH_BYTE 48 // 384/8
char DataMatrixdDraw(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize);
//char DataMatrixdDrawImg(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize,QImage *pImg);
void Draw_Matrix(unsigned char *buffer)
{
U16 sColumns, sRows;
U08 *Grid;
sColumns = sRows = 0;
Grid = 0;
sColumns = sRows = 0;
short sizeType = 0;
Grid = iec16022ecc200((short*)&sRows, (short*)&sColumns, buffer, &sizeType);
DataMatrixdDraw(Grid,sRows,sColumns,2);
}
char DataMatrixdDraw(U08 *OutBuff, U16 cRows, U16 cColumns, U08 MSize)
{
int Size=MSize;
int w = cColumns*Size;
int h = cRows*Size;
//qDebug()<<w<<h<<Size;
QImage QRImage(w,h,QImage::Format_ARGB32 );
QImage *img;
img = &QRImage;
img->fill(0x00ffffff);
/* data */
int margin=0;
U08 *p = OutBuff;
int ypos=0;//margin * Size;
int xpos=0;
int x,y,xx,yy,bit;
for(y=0; y<cRows; y++) {
bit = 7;
bit = 7 - (margin * Size % 8);
xpos=margin * Size;
for(x=0; x<cColumns; x++) {
for(xx=0; xx<Size; xx++) {
if((*p & 1) << bit){
for(yy=0; yy<Size; yy++) {
img->setPixel(xpos,h-1-(ypos+yy),0xff000000);
}
}
xpos++;
}
p++;
bit--;
if(bit < 0) {
//q++;
bit = 7;
}
}
ypos+=Size;
}
img->save("Myqr.bmp");
return 0;
}
+173 -173
View File
@@ -1,173 +1,173 @@
/**
*
* This is a simple Reed-Solomon encoder
* (C) Cliff Hones 2004
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
// It is not written with high efficiency in mind, so is probably
// not suitable for real-time encoding. The aim was to keep it
// simple, general and clear.
//
// <Some notes on the theory and implementation need to be added here>
// Usage:
// First call rs_init_gf(poly) to set up the Galois Field parameters.
// Then call rs_init_code(size, index) to set the encoding size
// Then call rs_encode(datasize, data, out) to encode the data.
//
// These can be called repeatedly as required - but note that
// rs_init_code must be called following any rs_init_gf call.
//
// If the parameters are fixed, some of the statics below can be
// replaced with constants in the obvious way, and additionally
// malloc/free can be avoided by using static arrays of a suitable
// size.
#include <stdio.h> // only needed for debug (main)
#include <stdlib.h> // only needed for malloc/free
#include "reedsol.h"
//#pragma section data begin
//#pragma section _sdram
int gfpoly;
int symsize; // in bits
int logmod; // 2**symsize - 1
int rlen;
int *log = NULL, *alog = NULL, *rspoly = NULL;
void rs_init_gf(int poly)
{
int m, b, p, v;
// Return storage from previous setup
if (log) {
free(log);
if (alog)free(alog);
if (rspoly)free(rspoly);
rspoly = NULL;
log =NULL;
alog = NULL;
}
// Find the top bit, and hence the symbol size
for (b = 1, m = 0; b <= poly; b <<= 1)
m++;
b >>= 1;
m--;
gfpoly = poly;
symsize = m;
// Calculate the log/alog tables
logmod = (1 << m) - 1;
log = (int *)malloc(sizeof(int) * (logmod + 1));
alog = (int *)malloc(sizeof(int) * logmod);
// log = (int *)QRcode_malloc(sizeof(int) * (logmod + 1));
// alog = (int *)QRcode_malloc(sizeof(int) * logmod);
for (p = 1, v = 0; v < logmod; v++) {
alog[v] = p;
log[p] = v;
p <<= 1;
if (p & b)
p ^= poly;
}
}
// rs_init_code(nsym, index) initialises the Reed-Solomon encoder
// nsym is the number of symbols to be generated (to be appended
// to the input data). index is usually 1 - it is the index of
// the constant in the first term (i) of the RS generator polynomial:
// (x + 2**i)*(x + 2**(i+1))*... [nsym terms]
// For ECC200, index is 1.
void rs_init_code(int nsym, int index)
{
int i, k;
if (rspoly)
free(rspoly);
rspoly = (int *)malloc(sizeof(int) * (nsym + 1));
//rspoly = (int *)QRcode_malloc(sizeof(int) * (nsym + 1));
rlen = nsym;
rspoly[0] = 1;
for (i = 1; i <= nsym; i++) {
rspoly[i] = 1;
for (k = i - 1; k > 0; k--) {
if (rspoly[k])
rspoly[k] = alog[(log[rspoly[k]] + index) % logmod];
rspoly[k] ^= rspoly[k - 1];
}
rspoly[0] = alog[(log[rspoly[0]] + index) % logmod];
index++;
}
}
void rs_encode(int len, unsigned char *data, unsigned char *res)
{
int i, k, m;
for (i = 0; i < rlen; i++)
res[i] = 0;
for (i = 0; i < len; i++) {
m = res[rlen - 1] ^ data[i];
for (k = rlen - 1; k > 0; k--) {
if (m && rspoly[k])
res[k] = res[k - 1] ^ alog[(log[m] + log[rspoly[k]]) % logmod];
else
res[k] = res[k - 1];
}
if (m && rspoly[0])
res[0] = alog[(log[m] + log[rspoly[0]]) % logmod];
else
res[0] = 0;
}
}
void rs_encode_long(int len, unsigned int *data, unsigned int *res)
{ /* The same as above but for larger bitlengths - Aztec code compatible */
int i, k, m;
for (i = 0; i < rlen; i++)
res[i] = 0;
for (i = 0; i < len; i++) {
m = res[rlen - 1] ^ data[i];
for (k = rlen - 1; k > 0; k--) {
if (m && rspoly[k])
res[k] = res[k - 1] ^ alog[(log[m] + log[rspoly[k]]) % logmod];
else
res[k] = res[k - 1];
}
if (m && rspoly[0])
res[0] = alog[(log[m] + log[rspoly[0]]) % logmod];
else
res[0] = 0;
}
}
void rs_free(void)
{ /* Free memory */
free(log);
free(alog);
free(rspoly);
log =NULL;
alog = NULL;
rspoly = NULL;
}
/**
*
* This is a simple Reed-Solomon encoder
* (C) Cliff Hones 2004
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
// It is not written with high efficiency in mind, so is probably
// not suitable for real-time encoding. The aim was to keep it
// simple, general and clear.
//
// <Some notes on the theory and implementation need to be added here>
// Usage:
// First call rs_init_gf(poly) to set up the Galois Field parameters.
// Then call rs_init_code(size, index) to set the encoding size
// Then call rs_encode(datasize, data, out) to encode the data.
//
// These can be called repeatedly as required - but note that
// rs_init_code must be called following any rs_init_gf call.
//
// If the parameters are fixed, some of the statics below can be
// replaced with constants in the obvious way, and additionally
// malloc/free can be avoided by using static arrays of a suitable
// size.
#include <stdio.h> // only needed for debug (main)
#include <stdlib.h> // only needed for malloc/free
#include "reedsol.h"
//#pragma section data begin
//#pragma section _sdram
int gfpoly;
int symsize; // in bits
int logmod; // 2**symsize - 1
int rlen;
int *log = NULL, *alog = NULL, *rspoly = NULL;
void rs_init_gf(int poly)
{
int m, b, p, v;
// Return storage from previous setup
if (log) {
free(log);
if (alog)free(alog);
if (rspoly)free(rspoly);
rspoly = NULL;
log =NULL;
alog = NULL;
}
// Find the top bit, and hence the symbol size
for (b = 1, m = 0; b <= poly; b <<= 1)
m++;
b >>= 1;
m--;
gfpoly = poly;
symsize = m;
// Calculate the log/alog tables
logmod = (1 << m) - 1;
log = (int *)malloc(sizeof(int) * (logmod + 1));
alog = (int *)malloc(sizeof(int) * logmod);
// log = (int *)QRcode_malloc(sizeof(int) * (logmod + 1));
// alog = (int *)QRcode_malloc(sizeof(int) * logmod);
for (p = 1, v = 0; v < logmod; v++) {
alog[v] = p;
log[p] = v;
p <<= 1;
if (p & b)
p ^= poly;
}
}
// rs_init_code(nsym, index) initialises the Reed-Solomon encoder
// nsym is the number of symbols to be generated (to be appended
// to the input data). index is usually 1 - it is the index of
// the constant in the first term (i) of the RS generator polynomial:
// (x + 2**i)*(x + 2**(i+1))*... [nsym terms]
// For ECC200, index is 1.
void rs_init_code(int nsym, int index)
{
int i, k;
if (rspoly)
free(rspoly);
rspoly = (int *)malloc(sizeof(int) * (nsym + 1));
//rspoly = (int *)QRcode_malloc(sizeof(int) * (nsym + 1));
rlen = nsym;
rspoly[0] = 1;
for (i = 1; i <= nsym; i++) {
rspoly[i] = 1;
for (k = i - 1; k > 0; k--) {
if (rspoly[k])
rspoly[k] = alog[(log[rspoly[k]] + index) % logmod];
rspoly[k] ^= rspoly[k - 1];
}
rspoly[0] = alog[(log[rspoly[0]] + index) % logmod];
index++;
}
}
void rs_encode(int len, unsigned char *data, unsigned char *res)
{
int i, k, m;
for (i = 0; i < rlen; i++)
res[i] = 0;
for (i = 0; i < len; i++) {
m = res[rlen - 1] ^ data[i];
for (k = rlen - 1; k > 0; k--) {
if (m && rspoly[k])
res[k] = res[k - 1] ^ alog[(log[m] + log[rspoly[k]]) % logmod];
else
res[k] = res[k - 1];
}
if (m && rspoly[0])
res[0] = alog[(log[m] + log[rspoly[0]]) % logmod];
else
res[0] = 0;
}
}
void rs_encode_long(int len, unsigned int *data, unsigned int *res)
{ /* The same as above but for larger bitlengths - Aztec code compatible */
int i, k, m;
for (i = 0; i < rlen; i++)
res[i] = 0;
for (i = 0; i < len; i++) {
m = res[rlen - 1] ^ data[i];
for (k = rlen - 1; k > 0; k--) {
if (m && rspoly[k])
res[k] = res[k - 1] ^ alog[(log[m] + log[rspoly[k]]) % logmod];
else
res[k] = res[k - 1];
}
if (m && rspoly[0])
res[0] = alog[(log[m] + log[rspoly[0]]) % logmod];
else
res[0] = 0;
}
}
void rs_free(void)
{ /* Free memory */
free(log);
free(alog);
free(rspoly);
log =NULL;
alog = NULL;
rspoly = NULL;
}
+40 -40
View File
@@ -1,40 +1,40 @@
/**
*
* This is a simple Reed-Solomon encoder
* (C) Cliff Hones 2004
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __REEDSOL_H
#define __REEDSOL_H
/*#ifdef __cplusplus
extern "C"
{
#endif */ /* __cplusplus */
extern void rs_init_gf(int poly);
extern void rs_init_code(int nsym, int index);
extern void rs_encode(int len, unsigned char *data, unsigned char *res);
extern void rs_encode_long(int len, unsigned int *data, unsigned int *res);
extern void rs_free(void);
/*#ifdef __cplusplus
}
#endif */ /* __cplusplus */
#endif /* __REEDSOL_H */
/**
*
* This is a simple Reed-Solomon encoder
* (C) Cliff Hones 2004
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef __REEDSOL_H
#define __REEDSOL_H
/*#ifdef __cplusplus
extern "C"
{
#endif */ /* __cplusplus */
extern void rs_init_gf(int poly);
extern void rs_init_code(int nsym, int index);
extern void rs_encode(int len, unsigned char *data, unsigned char *res);
extern void rs_encode_long(int len, unsigned int *data, unsigned int *res);
extern void rs_free(void);
/*#ifdef __cplusplus
}
#endif */ /* __cplusplus */
#endif /* __REEDSOL_H */
+209 -209
View File
@@ -1,209 +1,209 @@
/* zint.h - definitions for libzint
libzint - the open source barcode library
Copyright (C) 2009 Robin Stuart <robin@zint.org.uk>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef ZINT_H
#define ZINT_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
//#pragma section data begin
struct zint_symbol {
int symbology;
int height;
int whitespace_width;
int border_width;
int output_options;
char fgcolour[10];
char bgcolour[10];
char outfile[256];
float scale;
int option_1;
int option_2;
int option_3;
int show_hrt;
int input_mode;
unsigned char text[128];
int rows;
int width;
char primary[128];
unsigned char encoded_data[178][143];
int row_height[178]; /* Largest symbol is 177x177 QR Code */
char errtxt[100];
char *bitmap;
int bitmap_width;
int bitmap_height;
};
//#pragma section data end
/* Tbarcode 7 codes */
#define BARCODE_CODE11 1
#define BARCODE_C25MATRIX 2
#define BARCODE_C25INTER 3
#define BARCODE_C25IATA 4
#define BARCODE_C25LOGIC 6
#define BARCODE_C25IND 7
//#define BARCODE_CODE39 8
#define BARCODE_EXCODE39 9
#define BARCODE_EANX 13
//#define BARCODE_EAN128 16
//#define BARCODE_CODABAR 18
//#define BARCODE_CODE128 20
#define BARCODE_DPLEIT 21
#define BARCODE_DPIDENT 22
#define BARCODE_CODE16K 23
#define BARCODE_CODE49 24
//#define BARCODE_CODE93 25
#define BARCODE_FLAT 28
#define BARCODE_RSS14 29
#define BARCODE_RSS_LTD 30
#define BARCODE_RSS_EXP 31
#define BARCODE_TELEPEN 32
#define BARCODE_UPCA 34
#define BARCODE_UPCE 37
//#define BARCODE_POSTNET 40
#define BARCODE_MSI_PLESSEY 47
#define BARCODE_FIM 49
#define BARCODE_LOGMARS 50
#define BARCODE_PHARMA 51
#define BARCODE_PZN 52
#define BARCODE_PHARMA_TWO 53
#define BARCODE_PDF417 55
#define BARCODE_PDF417TRUNC 56
#define BARCODE_MAXICODE 57
#define BARCODE_QRCODE 58
#define BARCODE_CODE128B 60
#define BARCODE_AUSPOST 63
#define BARCODE_AUSREPLY 66
#define BARCODE_AUSROUTE 67
#define BARCODE_AUSREDIRECT 68
#define BARCODE_ISBNX 69
#define BARCODE_RM4SCC 70
#define BARCODE_DATAMATRIX 71
#define BARCODE_EAN14 72
#define BARCODE_CODABLOCKF 74
#define BARCODE_NVE18 75
#define BARCODE_JAPANPOST 76
#define BARCODE_KOREAPOST 77
#define BARCODE_RSS14STACK 79
#define BARCODE_RSS14STACK_OMNI 80
#define BARCODE_RSS_EXPSTACK 81
//#define BARCODE_PLANET 82
#define BARCODE_MICROPDF417 84
#define BARCODE_ONECODE 85
#define BARCODE_PLESSEY 86
/* Tbarcode 8 codes */
#define BARCODE_TELEPEN_NUM 87
#define BARCODE_ITF14 89
#define BARCODE_KIX 90
#define BARCODE_AZTEC 92
#define BARCODE_DAFT 93
#define BARCODE_MICROQR 97
/* Tbarcode 9 codes */
#define BARCODE_HIBC_128 98
#define BARCODE_HIBC_39 99
#define BARCODE_HIBC_DM 102
#define BARCODE_HIBC_QR 104
#define BARCODE_HIBC_PDF 106
#define BARCODE_HIBC_MICPDF 108
#define BARCODE_HIBC_BLOCKF 110
#define BARCODE_HIBC_AZTEC 112
/* Zint specific */
#define BARCODE_AZRUNE 128
#define BARCODE_CODE32 129
#define BARCODE_EANX_CC 130
#define BARCODE_EAN128_CC 131
#define BARCODE_RSS14_CC 132
#define BARCODE_RSS_LTD_CC 133
#define BARCODE_RSS_EXP_CC 134
#define BARCODE_UPCA_CC 135
#define BARCODE_UPCE_CC 136
#define BARCODE_RSS14STACK_CC 137
#define BARCODE_RSS14_OMNI_CC 138
#define BARCODE_RSS_EXPSTACK_CC 139
#define BARCODE_CHANNEL 140
#define BARCODE_CODEONE 141
#define BARCODE_GRIDMATRIX 142
#define BARCODE_NO_ASCII 1
#define BARCODE_BIND 2
#define BARCODE_BOX 4
#define BARCODE_STDOUT 8
#define READER_INIT 16
#define DATA_MODE 0
#define UNICODE_MODE 1
#define GS1_MODE 2
#define KANJI_MODE 3
#define SJIS_MODE 4
#define DM_SQUARE 100
#define WARN_INVALID_OPTION 2
#define ERROR_TOO_LONG 5
#define ERROR_INVALID_DATA 6
#define ERROR_INVALID_CHECK 7
#define ERROR_INVALID_OPTION 8
#define ERROR_ENCODING_PROBLEM 9
#define ERROR_FILE_ACCESS 10
#define ERROR_MEMORY 11
#if defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(_MSC_VER)
# if defined (DLL_EXPORT) || defined(PIC) || defined(_USRDLL)
# define ZINT_EXTERN __declspec(dllexport)
# elif defined(ZINT_DLL)
# define ZINT_EXTERN __declspec(dllimport)
# else
# define ZINT_EXTERN extern
# endif
#else
# define ZINT_EXTERN extern
#endif
ZINT_EXTERN struct zint_symbol *ZBarcode_Create(void);
ZINT_EXTERN void ZBarcode_Clear(struct zint_symbol *symbol);
ZINT_EXTERN void ZBarcode_Delete(struct zint_symbol *symbol);
ZINT_EXTERN int ZBarcode_Encode(struct zint_symbol *symbol, unsigned char *input, int length);
ZINT_EXTERN int ZBarcode_Encode_File(struct zint_symbol *symbol, char *filename);
ZINT_EXTERN int ZBarcode_Print(struct zint_symbol *symbol, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_and_Print(struct zint_symbol *symbol, unsigned char *input, int length, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_File_and_Print(struct zint_symbol *symbol, char *filename, int rotate_angle);
ZINT_EXTERN int ZBarcode_Buffer(struct zint_symbol *symbol, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_and_Buffer(struct zint_symbol *symbol, unsigned char *input, int length, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_File_and_Buffer(struct zint_symbol *symbol, char *filename, int rotate_angle);
ZINT_EXTERN int ZBarcode_ValidID(int symbol_id);
/* Depreciated */
ZINT_EXTERN int ZBarcode_Print_Rotated(struct zint_symbol *symbol, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_and_Print_Rotated(struct zint_symbol *symbol, unsigned char *input, int rotate_angle);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* ZINT_H */
/* zint.h - definitions for libzint
libzint - the open source barcode library
Copyright (C) 2009 Robin Stuart <robin@zint.org.uk>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef ZINT_H
#define ZINT_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
//#pragma section data begin
struct zint_symbol {
int symbology;
int height;
int whitespace_width;
int border_width;
int output_options;
char fgcolour[10];
char bgcolour[10];
char outfile[256];
float scale;
int option_1;
int option_2;
int option_3;
int show_hrt;
int input_mode;
unsigned char text[128];
int rows;
int width;
char primary[128];
unsigned char encoded_data[178][143];
int row_height[178]; /* Largest symbol is 177x177 QR Code */
char errtxt[100];
char *bitmap;
int bitmap_width;
int bitmap_height;
};
//#pragma section data end
/* Tbarcode 7 codes */
#define BARCODE_CODE11 1
#define BARCODE_C25MATRIX 2
#define BARCODE_C25INTER 3
#define BARCODE_C25IATA 4
#define BARCODE_C25LOGIC 6
#define BARCODE_C25IND 7
//#define BARCODE_CODE39 8
#define BARCODE_EXCODE39 9
#define BARCODE_EANX 13
//#define BARCODE_EAN128 16
//#define BARCODE_CODABAR 18
//#define BARCODE_CODE128 20
#define BARCODE_DPLEIT 21
#define BARCODE_DPIDENT 22
#define BARCODE_CODE16K 23
#define BARCODE_CODE49 24
//#define BARCODE_CODE93 25
#define BARCODE_FLAT 28
#define BARCODE_RSS14 29
#define BARCODE_RSS_LTD 30
#define BARCODE_RSS_EXP 31
#define BARCODE_TELEPEN 32
#define BARCODE_UPCA 34
#define BARCODE_UPCE 37
//#define BARCODE_POSTNET 40
#define BARCODE_MSI_PLESSEY 47
#define BARCODE_FIM 49
#define BARCODE_LOGMARS 50
#define BARCODE_PHARMA 51
#define BARCODE_PZN 52
#define BARCODE_PHARMA_TWO 53
#define BARCODE_PDF417 55
#define BARCODE_PDF417TRUNC 56
#define BARCODE_MAXICODE 57
#define BARCODE_QRCODE 58
#define BARCODE_CODE128B 60
#define BARCODE_AUSPOST 63
#define BARCODE_AUSREPLY 66
#define BARCODE_AUSROUTE 67
#define BARCODE_AUSREDIRECT 68
#define BARCODE_ISBNX 69
#define BARCODE_RM4SCC 70
#define BARCODE_DATAMATRIX 71
#define BARCODE_EAN14 72
#define BARCODE_CODABLOCKF 74
#define BARCODE_NVE18 75
#define BARCODE_JAPANPOST 76
#define BARCODE_KOREAPOST 77
#define BARCODE_RSS14STACK 79
#define BARCODE_RSS14STACK_OMNI 80
#define BARCODE_RSS_EXPSTACK 81
//#define BARCODE_PLANET 82
#define BARCODE_MICROPDF417 84
#define BARCODE_ONECODE 85
#define BARCODE_PLESSEY 86
/* Tbarcode 8 codes */
#define BARCODE_TELEPEN_NUM 87
#define BARCODE_ITF14 89
#define BARCODE_KIX 90
#define BARCODE_AZTEC 92
#define BARCODE_DAFT 93
#define BARCODE_MICROQR 97
/* Tbarcode 9 codes */
#define BARCODE_HIBC_128 98
#define BARCODE_HIBC_39 99
#define BARCODE_HIBC_DM 102
#define BARCODE_HIBC_QR 104
#define BARCODE_HIBC_PDF 106
#define BARCODE_HIBC_MICPDF 108
#define BARCODE_HIBC_BLOCKF 110
#define BARCODE_HIBC_AZTEC 112
/* Zint specific */
#define BARCODE_AZRUNE 128
#define BARCODE_CODE32 129
#define BARCODE_EANX_CC 130
#define BARCODE_EAN128_CC 131
#define BARCODE_RSS14_CC 132
#define BARCODE_RSS_LTD_CC 133
#define BARCODE_RSS_EXP_CC 134
#define BARCODE_UPCA_CC 135
#define BARCODE_UPCE_CC 136
#define BARCODE_RSS14STACK_CC 137
#define BARCODE_RSS14_OMNI_CC 138
#define BARCODE_RSS_EXPSTACK_CC 139
#define BARCODE_CHANNEL 140
#define BARCODE_CODEONE 141
#define BARCODE_GRIDMATRIX 142
#define BARCODE_NO_ASCII 1
#define BARCODE_BIND 2
#define BARCODE_BOX 4
#define BARCODE_STDOUT 8
#define READER_INIT 16
#define DATA_MODE 0
#define UNICODE_MODE 1
#define GS1_MODE 2
#define KANJI_MODE 3
#define SJIS_MODE 4
#define DM_SQUARE 100
#define WARN_INVALID_OPTION 2
#define ERROR_TOO_LONG 5
#define ERROR_INVALID_DATA 6
#define ERROR_INVALID_CHECK 7
#define ERROR_INVALID_OPTION 8
#define ERROR_ENCODING_PROBLEM 9
#define ERROR_FILE_ACCESS 10
#define ERROR_MEMORY 11
#if defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(_MSC_VER)
# if defined (DLL_EXPORT) || defined(PIC) || defined(_USRDLL)
# define ZINT_EXTERN __declspec(dllexport)
# elif defined(ZINT_DLL)
# define ZINT_EXTERN __declspec(dllimport)
# else
# define ZINT_EXTERN extern
# endif
#else
# define ZINT_EXTERN extern
#endif
ZINT_EXTERN struct zint_symbol *ZBarcode_Create(void);
ZINT_EXTERN void ZBarcode_Clear(struct zint_symbol *symbol);
ZINT_EXTERN void ZBarcode_Delete(struct zint_symbol *symbol);
ZINT_EXTERN int ZBarcode_Encode(struct zint_symbol *symbol, unsigned char *input, int length);
ZINT_EXTERN int ZBarcode_Encode_File(struct zint_symbol *symbol, char *filename);
ZINT_EXTERN int ZBarcode_Print(struct zint_symbol *symbol, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_and_Print(struct zint_symbol *symbol, unsigned char *input, int length, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_File_and_Print(struct zint_symbol *symbol, char *filename, int rotate_angle);
ZINT_EXTERN int ZBarcode_Buffer(struct zint_symbol *symbol, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_and_Buffer(struct zint_symbol *symbol, unsigned char *input, int length, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_File_and_Buffer(struct zint_symbol *symbol, char *filename, int rotate_angle);
ZINT_EXTERN int ZBarcode_ValidID(int symbol_id);
/* Depreciated */
ZINT_EXTERN int ZBarcode_Print_Rotated(struct zint_symbol *symbol, int rotate_angle);
ZINT_EXTERN int ZBarcode_Encode_and_Print_Rotated(struct zint_symbol *symbol, unsigned char *input, int rotate_angle);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* ZINT_H */
+151 -151
View File
@@ -1,151 +1,151 @@
#include "MemDisplayAndEdit.h"
#include "ui_memdisplayandedit.h"
#include "QLatin1Char"
MemDisplayAndEdit::MemDisplayAndEdit(QWidget *parent) :
QWidget(parent),
ui(new Ui::MemDisplayAndEdit)
{
ui->setupUi(this);
for(int i = 0; i < MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL; i++){
memLineEdit[i] = new QLineEdit(this);
//memLineEdit[i]->setAccessibleName(QString::number(i));
memLineEdit[i]->setEnabled(false);
ui->gridLayoutMem->addWidget(memLineEdit[i],(i/MEM_GRID_MAX_COL) + 1,(i%MEM_GRID_MAX_COL) + 1);
connect(memLineEdit[i],SIGNAL(editingFinished ()),this,SLOT(onLineEditEditingFinished()));
}
for(int i = 0; i < MEM_GRID_MAX_ROW; i++){
rowLabel[i] = new QLabel(this);
ui->gridLayoutMem->addWidget(rowLabel[i],i + 1,0);
}
editFlag = false;
writeMemMode = false;
ui->radioButtonRead->setChecked(!writeMemMode);
ui->radioButtonWrite->setChecked(writeMemMode);
writeMemBaseAddr = 0;
readMemBaseAddr = 0;
}
MemDisplayAndEdit::~MemDisplayAndEdit()
{
delete ui;
}
void MemDisplayAndEdit::updateSysStatusToUI(void){
if(sysPara && !editFlag){
for(int i = 0; i < MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL; i++){
if(writeMemMode)
memLineEdit[i]->setText(QString("%1").arg(sysPara->devOp->memWrMap[(writeMemBaseAddr + i)&MAX_WR_MEM_SIZE_MASK],2,16,QLatin1Char('0')));
else
memLineEdit[i]->setText(QString("%1").arg(sysPara->devOp->memRdMap[(readMemBaseAddr + i)&MAX_RD_MEM_SIZE_MASK],2,16,QLatin1Char('0')));
}
for(int i = 0; i < MEM_GRID_MAX_ROW; i++){
if(writeMemMode)
rowLabel[i]->setText(QString("%1").arg((writeMemBaseAddr + i*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK,4,16,QLatin1Char('0')));
else
rowLabel[i]->setText(QString("%1").arg((readMemBaseAddr + i*MEM_GRID_MAX_COL)&MAX_RD_MEM_SIZE_MASK,4,16,QLatin1Char('0')));
}
}
}
void MemDisplayAndEdit::on_comboBoxBaseAddress_activated(const QString &str)
{
bool ok;
if(writeMemMode){
writeMemBaseAddr = str.toInt(&ok,0);
}
else
readMemBaseAddr = str.toInt(&ok,0);
}
void MemDisplayAndEdit::on_radioButtonRead_pressed()
{
writeMemMode = false;
if(sysPara){
ui->pushButtonEdit->setEnabled(sysPara->devOp->fpgaDevOpenFlag?false:true);
}
if(editFlag)
on_pushButtonEdit_pressed();
ui->comboBoxBaseAddress->setEditText(QString("0x%1").arg(readMemBaseAddr,4,16,QLatin1Char('0')));
}
void MemDisplayAndEdit::on_radioButtonWrite_pressed()
{
writeMemMode = true;
ui->pushButtonEdit->setEnabled(true);
if(editFlag)
on_pushButtonEdit_pressed();
ui->comboBoxBaseAddress->setEditText(QString("0x%1").arg(writeMemBaseAddr,4,16,QLatin1Char('0')));
}
void MemDisplayAndEdit::on_pushButtonEdit_pressed()
{
editFlag = !editFlag;
for(int i = 0; i < MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL; i++){
memLineEdit[i]->setEnabled(editFlag);
}
ui->pushButtonEdit->setText(editFlag?tr("完成"):tr("编辑"));
}
void MemDisplayAndEdit::on_pushButtonLastPage_pressed()
{
if(writeMemMode){
writeMemBaseAddr = (writeMemBaseAddr - MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK;
}
else
readMemBaseAddr = (readMemBaseAddr - MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK;
}
void MemDisplayAndEdit::on_pushButtonNextPage_pressed()
{
if(writeMemMode){
writeMemBaseAddr = (writeMemBaseAddr + MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK;
}
else
readMemBaseAddr = (readMemBaseAddr + MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_RD_MEM_SIZE_MASK;
}
unsigned char dataOfTempVal[1];
void MemDisplayAndEdit::onLineEditEditingFinished(){
int val,addr;
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
QString name ="" ;// edit->accessibleName();
val = edit->text().toInt(&ok,16);
dataOfTempVal[0]=val;
if(sysPara){
if(writeMemMode){
addr = writeMemBaseAddr + name.toInt(&ok);
sysPara->devOp->fpgaWr(addr,dataOfTempVal,1);
}
else {
if(!sysPara->devOp->fpgaDevOpenFlag){
addr = readMemBaseAddr + name.toInt(&ok);
sysPara->devOp->memRdMap[(addr)&MAX_RD_MEM_SIZE_MASK] = (unsigned char)val;
}
}
}
}
void MemDisplayAndEdit::on_lineEditDec_editingFinished()
{
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
unsigned int val = edit->text().toUInt(&ok,10);
ui->lineEditHex->setText(QString("%1").arg(val,0,16));
}
void MemDisplayAndEdit::on_lineEditHex_editingFinished()
{
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
unsigned int val = edit->text().toUInt(&ok,16);
ui->lineEditDec->setText(QString("%1").arg(val,0,10));
}
#include "MemDisplayAndEdit.h"
#include "ui_memdisplayandedit.h"
#include "QLatin1Char"
MemDisplayAndEdit::MemDisplayAndEdit(QWidget *parent) :
QWidget(parent),
ui(new Ui::MemDisplayAndEdit)
{
ui->setupUi(this);
for(int i = 0; i < MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL; i++){
memLineEdit[i] = new QLineEdit(this);
//memLineEdit[i]->setAccessibleName(QString::number(i));
memLineEdit[i]->setEnabled(false);
ui->gridLayoutMem->addWidget(memLineEdit[i],(i/MEM_GRID_MAX_COL) + 1,(i%MEM_GRID_MAX_COL) + 1);
connect(memLineEdit[i],SIGNAL(editingFinished ()),this,SLOT(onLineEditEditingFinished()));
}
for(int i = 0; i < MEM_GRID_MAX_ROW; i++){
rowLabel[i] = new QLabel(this);
ui->gridLayoutMem->addWidget(rowLabel[i],i + 1,0);
}
editFlag = false;
writeMemMode = false;
ui->radioButtonRead->setChecked(!writeMemMode);
ui->radioButtonWrite->setChecked(writeMemMode);
writeMemBaseAddr = 0;
readMemBaseAddr = 0;
}
MemDisplayAndEdit::~MemDisplayAndEdit()
{
delete ui;
}
void MemDisplayAndEdit::updateSysStatusToUI(void){
if(sysPara && !editFlag){
for(int i = 0; i < MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL; i++){
if(writeMemMode)
memLineEdit[i]->setText(QString("%1").arg(sysPara->devOp->memWrMap[(writeMemBaseAddr + i)&MAX_WR_MEM_SIZE_MASK],2,16,QLatin1Char('0')));
else
memLineEdit[i]->setText(QString("%1").arg(sysPara->devOp->memRdMap[(readMemBaseAddr + i)&MAX_RD_MEM_SIZE_MASK],2,16,QLatin1Char('0')));
}
for(int i = 0; i < MEM_GRID_MAX_ROW; i++){
if(writeMemMode)
rowLabel[i]->setText(QString("%1").arg((writeMemBaseAddr + i*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK,4,16,QLatin1Char('0')));
else
rowLabel[i]->setText(QString("%1").arg((readMemBaseAddr + i*MEM_GRID_MAX_COL)&MAX_RD_MEM_SIZE_MASK,4,16,QLatin1Char('0')));
}
}
}
void MemDisplayAndEdit::on_comboBoxBaseAddress_activated(const QString &str)
{
bool ok;
if(writeMemMode){
writeMemBaseAddr = str.toInt(&ok,0);
}
else
readMemBaseAddr = str.toInt(&ok,0);
}
void MemDisplayAndEdit::on_radioButtonRead_pressed()
{
writeMemMode = false;
if(sysPara){
ui->pushButtonEdit->setEnabled(sysPara->devOp->fpgaDevOpenFlag?false:true);
}
if(editFlag)
on_pushButtonEdit_pressed();
ui->comboBoxBaseAddress->setEditText(QString("0x%1").arg(readMemBaseAddr,4,16,QLatin1Char('0')));
}
void MemDisplayAndEdit::on_radioButtonWrite_pressed()
{
writeMemMode = true;
ui->pushButtonEdit->setEnabled(true);
if(editFlag)
on_pushButtonEdit_pressed();
ui->comboBoxBaseAddress->setEditText(QString("0x%1").arg(writeMemBaseAddr,4,16,QLatin1Char('0')));
}
void MemDisplayAndEdit::on_pushButtonEdit_pressed()
{
editFlag = !editFlag;
for(int i = 0; i < MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL; i++){
memLineEdit[i]->setEnabled(editFlag);
}
ui->pushButtonEdit->setText(editFlag?tr("完成"):tr("编辑"));
}
void MemDisplayAndEdit::on_pushButtonLastPage_pressed()
{
if(writeMemMode){
writeMemBaseAddr = (writeMemBaseAddr - MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK;
}
else
readMemBaseAddr = (readMemBaseAddr - MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK;
}
void MemDisplayAndEdit::on_pushButtonNextPage_pressed()
{
if(writeMemMode){
writeMemBaseAddr = (writeMemBaseAddr + MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_WR_MEM_SIZE_MASK;
}
else
readMemBaseAddr = (readMemBaseAddr + MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL)&MAX_RD_MEM_SIZE_MASK;
}
unsigned char dataOfTempVal[1];
void MemDisplayAndEdit::onLineEditEditingFinished(){
int val,addr;
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
QString name ="" ;// edit->accessibleName();
val = edit->text().toInt(&ok,16);
dataOfTempVal[0]=val;
if(sysPara){
if(writeMemMode){
addr = writeMemBaseAddr + name.toInt(&ok);
sysPara->devOp->fpgaWr(addr,dataOfTempVal,1);
}
else {
if(!sysPara->devOp->fpgaDevOpenFlag){
addr = readMemBaseAddr + name.toInt(&ok);
sysPara->devOp->memRdMap[(addr)&MAX_RD_MEM_SIZE_MASK] = (unsigned char)val;
}
}
}
}
void MemDisplayAndEdit::on_lineEditDec_editingFinished()
{
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
unsigned int val = edit->text().toUInt(&ok,10);
ui->lineEditHex->setText(QString("%1").arg(val,0,16));
}
void MemDisplayAndEdit::on_lineEditHex_editingFinished()
{
bool ok;
QLineEdit * edit = qobject_cast<QLineEdit *>(sender());
unsigned int val = edit->text().toUInt(&ok,16);
ui->lineEditDec->setText(QString("%1").arg(val,0,10));
}
+56 -56
View File
@@ -1,56 +1,56 @@
#ifndef MEMDISPLAYANDEDIT_H
#define MEMDISPLAYANDEDIT_H
#include <QWidget>
#include <QLineEdit>
#include <ParaSettingUI.h>
#include <QLabel>
#define MEM_GRID_MAX_ROW 5
#define MEM_GRID_MAX_COL 16
namespace Ui {
class MemDisplayAndEdit;
}
class MemDisplayAndEdit : public QWidget,public ParaSettingUI
{
Q_OBJECT
public:
explicit MemDisplayAndEdit(QWidget *parent = 0);
~MemDisplayAndEdit();
void updateSysStatusToUI(void);
private slots:
void on_comboBoxBaseAddress_activated(const QString &arg1);
void on_radioButtonRead_pressed();
void on_radioButtonWrite_pressed();
void on_pushButtonEdit_pressed();
void on_pushButtonLastPage_pressed();
void on_pushButtonNextPage_pressed();
void onLineEditEditingFinished();
void on_lineEditDec_editingFinished();
void on_lineEditHex_editingFinished();
private:
Ui::MemDisplayAndEdit *ui;
QLineEdit *memLineEdit[MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL];
QLabel *rowLabel[MEM_GRID_MAX_ROW];
bool editFlag; //是否当前处于编辑模式
bool writeMemMode; //是否当前处于写地址模式
int writeMemBaseAddr;
int readMemBaseAddr;
};
#endif // MEMDISPLAYANDEDIT_H
#ifndef MEMDISPLAYANDEDIT_H
#define MEMDISPLAYANDEDIT_H
#include <QWidget>
#include <QLineEdit>
#include <ParaSettingUI.h>
#include <QLabel>
#define MEM_GRID_MAX_ROW 5
#define MEM_GRID_MAX_COL 16
namespace Ui {
class MemDisplayAndEdit;
}
class MemDisplayAndEdit : public QWidget,public ParaSettingUI
{
Q_OBJECT
public:
explicit MemDisplayAndEdit(QWidget *parent = 0);
~MemDisplayAndEdit();
void updateSysStatusToUI(void);
private slots:
void on_comboBoxBaseAddress_activated(const QString &arg1);
void on_radioButtonRead_pressed();
void on_radioButtonWrite_pressed();
void on_pushButtonEdit_pressed();
void on_pushButtonLastPage_pressed();
void on_pushButtonNextPage_pressed();
void onLineEditEditingFinished();
void on_lineEditDec_editingFinished();
void on_lineEditHex_editingFinished();
private:
Ui::MemDisplayAndEdit *ui;
QLineEdit *memLineEdit[MEM_GRID_MAX_ROW*MEM_GRID_MAX_COL];
QLabel *rowLabel[MEM_GRID_MAX_ROW];
bool editFlag; //是否当前处于编辑模式
bool writeMemMode; //是否当前处于写地址模式
int writeMemBaseAddr;
int readMemBaseAddr;
};
#endif // MEMDISPLAYANDEDIT_H
+57 -57
View File
@@ -1,57 +1,57 @@
/*
* MyFileDialog.cpp
*
* Created on: Jul 14, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#include "MyFileDialog.h"
#include "SysPara.h"
#include <QDir>
#include <QDesktopServices>
#include <QUrl>
MyFileDialog::MyFileDialog(QWidget *parent):QFileDialog(parent){
setFileMode(QFileDialog::AnyFile);
//setLabelText(QFileDialog::LookIn,tr("文件夹"));
// setLabelText(QFileDialog::FileName,tr("文件名"));
// setLabelText(QFileDialog::FileType,tr("文件类型"));
setLabelText(QFileDialog::Accept,tr("确定"));
// setLabelText(QFileDialog::Reject,tr("取消"));
setViewMode(QFileDialog::Detail);
setOption(QFileDialog::ReadOnly,true);
//setOption(QFileDialog::DontUseNativeDialog,true);
QList<QUrl> urls;
urls << QUrl::fromLocalFile(DOC_ROOT_DIR) ;//<< QUrl::fromLocalFile(UDISK_DOC_ROOT_DIR) ;
setSidebarUrls (urls );
this->setFixedSize(this->geometry().width(),this->geometry().height());
}
MyFileDialog::~MyFileDialog(){
}
void MyFileDialog::showFileDialog(QString title,QString dir,QString filter){
setNameFilter(filter);
setDirectory (dir);
setWindowTitle(title);
//autoCompleteFileName("dfdfs");
setViewMode(QFileDialog::Detail);
//setOption(QFileDialog::ReadOnly,true);
//setOption(QFileDialog::DontUseSheet,true);
//setOption(QFileDialog::HideNameFilterDetails,true);
//setResolveSymlinks(0);
if(isMinimized()){
setWindowState(Qt::WindowMaximized);
}
show();
QWidget *widget = focusWidget () ;
if(widget){
widget->clearFocus(); //默认不要弹出输入法
}
}
/*
* MyFileDialog.cpp
*
* Created on: Jul 14, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#include "MyFileDialog.h"
#include "SysPara.h"
#include <QDir>
#include <QDesktopServices>
#include <QUrl>
MyFileDialog::MyFileDialog(QWidget *parent):QFileDialog(parent){
setFileMode(QFileDialog::AnyFile);
//setLabelText(QFileDialog::LookIn,tr("文件夹"));
// setLabelText(QFileDialog::FileName,tr("文件名"));
// setLabelText(QFileDialog::FileType,tr("文件类型"));
setLabelText(QFileDialog::Accept,tr("确定"));
// setLabelText(QFileDialog::Reject,tr("取消"));
setViewMode(QFileDialog::Detail);
setOption(QFileDialog::ReadOnly,true);
//setOption(QFileDialog::DontUseNativeDialog,true);
QList<QUrl> urls;
urls << QUrl::fromLocalFile(DOC_ROOT_DIR) ;//<< QUrl::fromLocalFile(UDISK_DOC_ROOT_DIR) ;
setSidebarUrls (urls );
this->setFixedSize(this->geometry().width(),this->geometry().height());
}
MyFileDialog::~MyFileDialog(){
}
void MyFileDialog::showFileDialog(QString title,QString dir,QString filter){
setNameFilter(filter);
setDirectory (dir);
setWindowTitle(title);
//autoCompleteFileName("dfdfs");
setViewMode(QFileDialog::Detail);
//setOption(QFileDialog::ReadOnly,true);
//setOption(QFileDialog::DontUseSheet,true);
//setOption(QFileDialog::HideNameFilterDetails,true);
//setResolveSymlinks(0);
if(isMinimized()){
setWindowState(Qt::WindowMaximized);
}
show();
QWidget *widget = focusWidget () ;
if(widget){
widget->clearFocus(); //默认不要弹出输入法
}
}
+28 -28
View File
@@ -1,28 +1,28 @@
/*
* MyFileDialog.h
*
* Created on: Jul 14, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#ifndef MYFILEDIALOG_H_
#define MYFILEDIALOG_H_
#include <QFileDialog>
class MyFileDialog:public QFileDialog{
Q_OBJECT
public:
MyFileDialog(QWidget *parent = 0);
~MyFileDialog();
void showFileDialog(QString title,QString filter,QString dir);
};
#endif /* MYFILEDIALOG_H_ */
/*
* MyFileDialog.h
*
* Created on: Jul 14, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#ifndef MYFILEDIALOG_H_
#define MYFILEDIALOG_H_
#include <QFileDialog>
class MyFileDialog:public QFileDialog{
Q_OBJECT
public:
MyFileDialog(QWidget *parent = 0);
~MyFileDialog();
void showFileDialog(QString title,QString filter,QString dir);
};
#endif /* MYFILEDIALOG_H_ */
+159 -159
View File
@@ -1,159 +1,159 @@
/*
* MyInputMethod.cpp
*
* Created on: Jun 23, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#include "MyInputMethod.h"
#include <QDebug>
#include <QDesktopWidget>
#include <QCursor>
#include <QWidget>
#include <QPoint>
#include <QApplication>
#include <QSpinBox>
#include <QFile>
#include <QTableWidget>
#include "Public.h"
#include<iostream>
#include<string>
#include<QLineEdit>
#include "InkJetPrinter.h"
extern InkJetPrinter *pInkJectPrinter;
MyInputMethod::MyInputMethod(QWidget *parent)
:QObject(parent)
{
InputMethod *input = new InputMethod(this,parent);
QString filename = Public::readLanguageType();
input->initInputMethod(filename);
inputMethod = input;
digitalInput = new DigitalInput(this,parent);
}
void MyInputMethod::SetInputFile(QString filename){
inputMethod->initInputMethod(filename);
}
InputMethod* MyInputMethod::getInputMethod()
{
return inputMethod;
}
//bool MyInputMethod::filter ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat ){
// qDebug() << "MyInputMethod::filter ";
// return true;
//}
MyInputMethod::~MyInputMethod(){
delete inputMethod;
delete digitalInput;
}
void MyInputMethod::sendString(QString &str){
#ifndef Q_OS_WIN32
QWidget *watched = QApplication::focusWidget();
QSpinBox *qsb=qobject_cast<QSpinBox*>(watched);
QLineEdit *qle=qobject_cast<QLineEdit*>(watched);
QTextEdit *qte=qobject_cast<QTextEdit*>(watched);
if(qle)qle->insert(str);
if(qte)qte->insertPlainText(str);
if(qsb)
{
const QObjectList objectList=qsb->children();
foreach (QObject * const obj, objectList) {
if(QLineEdit * const qcle=qobject_cast<QLineEdit *const >(obj))
{
qcle->insert(str);
break;
}
}
}
#endif
}
void MyInputMethod::updateHandler ( int type ){
QWidget *widget = QApplication::focusWidget();
#ifndef Q_OS_WIN32
switch(type){
case 0:break;
case 1:
if (widget && dynamic_cast<QTableWidget *>(widget)) {
int a = 0;
}
if(widget && dynamic_cast<QSpinBox *>(widget)){
if(digitalInput->isHidden()){
QRect rec = QApplication::desktop()->screenGeometry();
QPoint point = widget->mapToGlobal (QPoint(0,0)); //全局坐标
QRect myRec = digitalInput->geometry();
digitalInput->setGeometry((point.x() > rec.width()/2)?(point.x() - myRec.width() - 20):(point.x() + 20),
(point.y() > rec.height()/2)?(point.y() - myRec.height() - 20):(point.y() + 20),
myRec.width(),myRec.height());
digitalInput->show();
}
}
else {
if(inputMethod->isHidden()){
//QCursor cursor(Qt::PointingHandCursor);
//inputMethod->setCursor(cursor);
QRect rec = QApplication::desktop()->screenGeometry();
QRect myRec = inputMethod->geometry();
if(widget){
QPoint point = widget->mapToGlobal (QPoint(0,0)); //全局坐标
QPoint topLeft=pInkJectPrinter->pos();
if(point.y() < rec.height()/2) /*如果组件在上,则将输入法放在上面,否则放在下面*/
inputMethod->setGeometry(topLeft.x(),rec.height() - myRec.height(),myRec.width(),myRec.height());
// inputMethod->setGeometry(0,rec.height() - myRec.height()-12,myRec.width(),myRec.height());
else
// inputMethod->setGeometry(0,0,myRec.width(),myRec.height());
inputMethod->setGeometry(topLeft.x(),30,myRec.width(),myRec.height());
inputMethod->show();
}
}
}
break;
case 2://QWSInputMethod::FocusOut:
inputMethod->hide();
digitalInput->hide();
inputMethod->onHiden();
break;
}
#endif
}
void MyInputMethod::switchBangalInput(bool flag){
inputMethod->switchKeyBoardBengalDisply(flag);
}
#ifdef EnableArabic
void MyInputMethod::getArabicFlag(bool flag){
inputMethod->setArabicDisplay(flag);
}
void MyInputMethod::getArabicPage(int page){
emit selectArabicPage(page);
}
void MyInputMethod::getEnglishOrAarbic(bool flag){
emit switchEnglishOrArabic(flag);
}
void MyInputMethod::switchArabicFlag(bool flag){
inputMethod->setSwitchArabicFlag(flag);
}
#endif
void MyInputMethod::sendEvent(int key,Qt::KeyboardModifiers modifiers)
{
QKeyEvent pressEvent(QEvent::KeyPress, key, modifiers);
QKeyEvent releaseEvent(QEvent::KeyRelease, key, modifiers);
QCoreApplication::sendEvent(QApplication::focusWidget(), &pressEvent);
QCoreApplication::sendEvent(QApplication::focusWidget(), &releaseEvent);
}
/*
* MyInputMethod.cpp
*
* Created on: Jun 23, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#include "MyInputMethod.h"
#include <QDebug>
#include <QDesktopWidget>
#include <QCursor>
#include <QWidget>
#include <QPoint>
#include <QApplication>
#include <QSpinBox>
#include <QFile>
#include <QTableWidget>
#include "Public.h"
#include<iostream>
#include<string>
#include<QLineEdit>
#include "InkJetPrinter.h"
extern InkJetPrinter *pInkJectPrinter;
MyInputMethod::MyInputMethod(QWidget *parent)
:QObject(parent)
{
InputMethod *input = new InputMethod(this,parent);
QString filename = Public::readLanguageType();
input->initInputMethod(filename);
inputMethod = input;
digitalInput = new DigitalInput(this,parent);
}
void MyInputMethod::SetInputFile(QString filename){
inputMethod->initInputMethod(filename);
}
InputMethod* MyInputMethod::getInputMethod()
{
return inputMethod;
}
//bool MyInputMethod::filter ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat ){
// qDebug() << "MyInputMethod::filter ";
// return true;
//}
MyInputMethod::~MyInputMethod(){
delete inputMethod;
delete digitalInput;
}
void MyInputMethod::sendString(QString &str){
#ifndef Q_OS_WIN32
QWidget *watched = QApplication::focusWidget();
QSpinBox *qsb=qobject_cast<QSpinBox*>(watched);
QLineEdit *qle=qobject_cast<QLineEdit*>(watched);
QTextEdit *qte=qobject_cast<QTextEdit*>(watched);
if(qle)qle->insert(str);
if(qte)qte->insertPlainText(str);
if(qsb)
{
const QObjectList objectList=qsb->children();
foreach (QObject * const obj, objectList) {
if(QLineEdit * const qcle=qobject_cast<QLineEdit *const >(obj))
{
qcle->insert(str);
break;
}
}
}
#endif
}
void MyInputMethod::updateHandler ( int type ){
QWidget *widget = QApplication::focusWidget();
#ifndef Q_OS_WIN32
switch(type){
case 0:break;
case 1:
if (widget && dynamic_cast<QTableWidget *>(widget)) {
int a = 0;
}
if(widget && dynamic_cast<QSpinBox *>(widget)){
if(digitalInput->isHidden()){
QRect rec = QApplication::desktop()->screenGeometry();
QPoint point = widget->mapToGlobal (QPoint(0,0)); //全局坐标
QRect myRec = digitalInput->geometry();
digitalInput->setGeometry((point.x() > rec.width()/2)?(point.x() - myRec.width() - 20):(point.x() + 20),
(point.y() > rec.height()/2)?(point.y() - myRec.height() - 20):(point.y() + 20),
myRec.width(),myRec.height());
digitalInput->show();
}
}
else {
if(inputMethod->isHidden()){
//QCursor cursor(Qt::PointingHandCursor);
//inputMethod->setCursor(cursor);
QRect rec = QApplication::desktop()->screenGeometry();
QRect myRec = inputMethod->geometry();
if(widget){
QPoint point = widget->mapToGlobal (QPoint(0,0)); //全局坐标
QPoint topLeft=pInkJectPrinter->pos();
if(point.y() < rec.height()/2) /*如果组件在上,则将输入法放在上面,否则放在下面*/
inputMethod->setGeometry(topLeft.x(),rec.height() - myRec.height(),myRec.width(),myRec.height());
// inputMethod->setGeometry(0,rec.height() - myRec.height()-12,myRec.width(),myRec.height());
else
// inputMethod->setGeometry(0,0,myRec.width(),myRec.height());
inputMethod->setGeometry(topLeft.x(),30,myRec.width(),myRec.height());
inputMethod->show();
}
}
}
break;
case 2://QWSInputMethod::FocusOut:
inputMethod->hide();
digitalInput->hide();
inputMethod->onHiden();
break;
}
#endif
}
void MyInputMethod::switchBangalInput(bool flag){
inputMethod->switchKeyBoardBengalDisply(flag);
}
#ifdef EnableArabic
void MyInputMethod::getArabicFlag(bool flag){
inputMethod->setArabicDisplay(flag);
}
void MyInputMethod::getArabicPage(int page){
emit selectArabicPage(page);
}
void MyInputMethod::getEnglishOrAarbic(bool flag){
emit switchEnglishOrArabic(flag);
}
void MyInputMethod::switchArabicFlag(bool flag){
inputMethod->setSwitchArabicFlag(flag);
}
#endif
void MyInputMethod::sendEvent(int key,Qt::KeyboardModifiers modifiers)
{
QKeyEvent pressEvent(QEvent::KeyPress, key, modifiers);
QKeyEvent releaseEvent(QEvent::KeyRelease, key, modifiers);
QCoreApplication::sendEvent(QApplication::focusWidget(), &pressEvent);
QCoreApplication::sendEvent(QApplication::focusWidget(), &releaseEvent);
}
+57 -57
View File
@@ -1,57 +1,57 @@
/*
* MyInputMethod.h
*
* Created on: Jun 23, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#ifndef MYINPUTMETHOD_H_
#define MYINPUTMETHOD_H_
#include "InputMethod.h"
#include "DigitalInput.h"
#ifndef Q_OS_WIN32
//#include <QWSInputMethod>
//#include <QWSServer>
//#include "myinclude.h"
class MyInputMethod:public QObject//QWSInputMethod
{
Q_OBJECT
#else
class MyInputMethod
{
#endif
public:
MyInputMethod(QWidget *parent = 0);
~MyInputMethod();
void updateHandler ( int type );
void sendString(QString &str);
void SetInputFile(QString filename="WINPY_utf8.txt");
InputMethod* getInputMethod();
#ifdef EnableArabic
void getArabicPage(int page);
void getEnglishOrAarbic(bool flag);
#endif
static void sendEvent(int key,Qt::KeyboardModifiers modifiers);
private slots:
void switchBangalInput(bool);
#ifdef EnableArabic
public slots:
void getArabicFlag(bool);
void switchArabicFlag(bool flag);
signals:
void selectArabicPage(int);
void switchEnglishOrArabic(bool);
#endif
private:
InputMethod *inputMethod;
DigitalInput *digitalInput;
};
#endif /* MYINPUTMETHOD_H_ */
/*
* MyInputMethod.h
*
* Created on: Jun 23, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#ifndef MYINPUTMETHOD_H_
#define MYINPUTMETHOD_H_
#include "InputMethod.h"
#include "DigitalInput.h"
#ifndef Q_OS_WIN32
//#include <QWSInputMethod>
//#include <QWSServer>
//#include "myinclude.h"
class MyInputMethod:public QObject//QWSInputMethod
{
Q_OBJECT
#else
class MyInputMethod
{
#endif
public:
MyInputMethod(QWidget *parent = 0);
~MyInputMethod();
void updateHandler ( int type );
void sendString(QString &str);
void SetInputFile(QString filename="WINPY_utf8.txt");
InputMethod* getInputMethod();
#ifdef EnableArabic
void getArabicPage(int page);
void getEnglishOrAarbic(bool flag);
#endif
static void sendEvent(int key,Qt::KeyboardModifiers modifiers);
private slots:
void switchBangalInput(bool);
#ifdef EnableArabic
public slots:
void getArabicFlag(bool);
void switchArabicFlag(bool flag);
signals:
void selectArabicPage(int);
void switchEnglishOrArabic(bool);
#endif
private:
InputMethod *inputMethod;
DigitalInput *digitalInput;
};
#endif /* MYINPUTMETHOD_H_ */
+143 -143
View File
@@ -1,143 +1,143 @@
/*
* MyTextEdit.cpp
*
* Created on: Aug 7, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#include <MyTextEdit.h>
#include "SysPara.h"
#include <QTextDocument>
#include <QTextCursor>
#include <QTextBlockFormat>
#include <QTextBlock>
#include <QDebug>
#include <QKeyEvent>
//#include <QWSServer>
#include <QGuiApplication>
MyTextEdit::MyTextEdit(QWidget *parent):QTextEdit(parent){
this->document()->setDocumentMargin(0);
// QTextDocument *doc = this->document(); //获取文档对象
// QTextFrame *rootFrame = doc->rootFrame(); //获取根框架
// QTextFrameFormat frameFormat; //创建框架格式
// frameFormat.setBorderBrush(Qt::red); //设置边界颜色
// frameFormat.setBorder(0); //设置边界宽度
// rootFrame->setFrameFormat(frameFormat); //给框架使用格式
//this->setTextInteractionFlags(Qt::TextEditable);//不能选中
this->setLineWrapMode(QTextEdit::NoWrap);
for(QTextBlock textBlock = this->document()->begin();
textBlock != this->document()->end();
textBlock = textBlock.next()){
QTextBlockFormat textBlockFormat = textBlock.blockFormat();
textBlockFormat.setBottomMargin(0);
QTextCursor textCursor = this->textCursor();
textCursor.setBlockFormat(textBlockFormat);
this->setTextCursor(textCursor);
}
}
void MyTextEdit::dragEnterEvent ( QDragEnterEvent * e ){
e->ignore();
}
void MyTextEdit::dragLeaveEvent ( QDragLeaveEvent * e ){
e->ignore();
}
void MyTextEdit::dragMoveEvent ( QDragMoveEvent * e ){
e->ignore();
}
void MyTextEdit::mouseDoubleClickEvent ( QMouseEvent * e ){
e->ignore();
}
void MyTextEdit::mousePressEvent(QMouseEvent * e)
{
//获取点击的下标
// qDebug() << e->x() << ":" << e->y();
if(this->toPlainText().length()>1 && cursorForPosition(e->pos()).atEnd())
{
int textHeight=this->height();
QPoint currentPt=e->pos();
QTextCursor textCursor=cursorForPosition(currentPt);
while(textCursor.atEnd() && 0<--textHeight && 0<currentPt.y())
{
int textWidth=this->width();
currentPt.setX(e->pos().x());
currentPt.setY(currentPt.y()-5);
textCursor=cursorForPosition(currentPt);
while(textCursor.atEnd() && 0<--textWidth && 0<currentPt.x())
{
currentPt.setX(currentPt.x()-8);
textCursor=cursorForPosition(currentPt);
}
}
if(0<currentPt.x() && 0<currentPt.y())
{
currentPt.setX(e->pos().x()+8);
this->setTextCursor(cursorForPosition(currentPt));
return;
}
}
if(e->button() == Qt::LeftButton)
{
// QWSServer::sendKeyEvent(0,Qt::Key_Left1,Qt::NoModifier,true,false);
// QWSServer::sendKeyEvent(0,Qt::Key_Left,Qt::NoModifier,true,false); //向系统发送键盘事件
// QWSServer::sendKeyEvent(0,Qt::Key_Right1,Qt::NoModifier,true,false);
// QWSServer::sendKeyEvent(0,Qt::Key_Right,Qt::NoModifier,true,false);
//setCursor();
//QTextCursor textCursor = this->textCursor();
//textCursor.clearSelection();
//textCursor.setPosition(e->x());
//textCursor.setBlockFormat(textBlockFormat);
//this->setTextCursor(textCursor);
}
// if(e->button() == Qt::RightButton)
// {
// e->ignore();
// }
// else
{
QTextEdit::mousePressEvent(e);
}
}
//bool MyTextEdit::qwsEvent ( QWSEvent * event ){
//}
//void MyTextEdit::mouseMoveEvent ( QMouseEvent * e ){
// //e->ignore();
//}
//
//void MyTextEdit::changeEvent ( QEvent * event ){
// if(event->type()==QEvent::FontChange)
// {
// }
// QTextEdit::changeEvent(event);
//}
//void MyTextEdit::mouseReleaseEvent(QMouseEvent * e)
//{
// QTextCursor textCursor = this->textCursor();
// textCursor.clearSelection();
// QTextEdit::mouseReleaseEvent(e);
//}
/*
* MyTextEdit.cpp
*
* Created on: Aug 7, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#include <MyTextEdit.h>
#include "SysPara.h"
#include <QTextDocument>
#include <QTextCursor>
#include <QTextBlockFormat>
#include <QTextBlock>
#include <QDebug>
#include <QKeyEvent>
//#include <QWSServer>
#include <QGuiApplication>
MyTextEdit::MyTextEdit(QWidget *parent):QTextEdit(parent){
this->document()->setDocumentMargin(0);
// QTextDocument *doc = this->document(); //获取文档对象
// QTextFrame *rootFrame = doc->rootFrame(); //获取根框架
// QTextFrameFormat frameFormat; //创建框架格式
// frameFormat.setBorderBrush(Qt::red); //设置边界颜色
// frameFormat.setBorder(0); //设置边界宽度
// rootFrame->setFrameFormat(frameFormat); //给框架使用格式
//this->setTextInteractionFlags(Qt::TextEditable);//不能选中
this->setLineWrapMode(QTextEdit::NoWrap);
for(QTextBlock textBlock = this->document()->begin();
textBlock != this->document()->end();
textBlock = textBlock.next()){
QTextBlockFormat textBlockFormat = textBlock.blockFormat();
textBlockFormat.setBottomMargin(0);
QTextCursor textCursor = this->textCursor();
textCursor.setBlockFormat(textBlockFormat);
this->setTextCursor(textCursor);
}
}
void MyTextEdit::dragEnterEvent ( QDragEnterEvent * e ){
e->ignore();
}
void MyTextEdit::dragLeaveEvent ( QDragLeaveEvent * e ){
e->ignore();
}
void MyTextEdit::dragMoveEvent ( QDragMoveEvent * e ){
e->ignore();
}
void MyTextEdit::mouseDoubleClickEvent ( QMouseEvent * e ){
e->ignore();
}
void MyTextEdit::mousePressEvent(QMouseEvent * e)
{
//获取点击的下标
// qDebug() << e->x() << ":" << e->y();
if(this->toPlainText().length()>1 && cursorForPosition(e->pos()).atEnd())
{
int textHeight=this->height();
QPoint currentPt=e->pos();
QTextCursor textCursor=cursorForPosition(currentPt);
while(textCursor.atEnd() && 0<--textHeight && 0<currentPt.y())
{
int textWidth=this->width();
currentPt.setX(e->pos().x());
currentPt.setY(currentPt.y()-5);
textCursor=cursorForPosition(currentPt);
while(textCursor.atEnd() && 0<--textWidth && 0<currentPt.x())
{
currentPt.setX(currentPt.x()-8);
textCursor=cursorForPosition(currentPt);
}
}
if(0<currentPt.x() && 0<currentPt.y())
{
currentPt.setX(e->pos().x()+8);
this->setTextCursor(cursorForPosition(currentPt));
return;
}
}
if(e->button() == Qt::LeftButton)
{
// QWSServer::sendKeyEvent(0,Qt::Key_Left1,Qt::NoModifier,true,false);
// QWSServer::sendKeyEvent(0,Qt::Key_Left,Qt::NoModifier,true,false); //向系统发送键盘事件
// QWSServer::sendKeyEvent(0,Qt::Key_Right1,Qt::NoModifier,true,false);
// QWSServer::sendKeyEvent(0,Qt::Key_Right,Qt::NoModifier,true,false);
//setCursor();
//QTextCursor textCursor = this->textCursor();
//textCursor.clearSelection();
//textCursor.setPosition(e->x());
//textCursor.setBlockFormat(textBlockFormat);
//this->setTextCursor(textCursor);
}
// if(e->button() == Qt::RightButton)
// {
// e->ignore();
// }
// else
{
QTextEdit::mousePressEvent(e);
}
}
//bool MyTextEdit::qwsEvent ( QWSEvent * event ){
//}
//void MyTextEdit::mouseMoveEvent ( QMouseEvent * e ){
// //e->ignore();
//}
//
//void MyTextEdit::changeEvent ( QEvent * event ){
// if(event->type()==QEvent::FontChange)
// {
// }
// QTextEdit::changeEvent(event);
//}
//void MyTextEdit::mouseReleaseEvent(QMouseEvent * e)
//{
// QTextCursor textCursor = this->textCursor();
// textCursor.clearSelection();
// QTextEdit::mouseReleaseEvent(e);
//}
+39 -39
View File
@@ -1,39 +1,39 @@
/*
* MyTextEdit.h
*
* Created on: Aug 7, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#ifndef MYTEXTEDIT_H_
#define MYTEXTEDIT_H_
#include <QTextEdit>
#include <QDragEnterEvent>
//#include <QWSEvent>
class MyTextEdit:public QTextEdit{
Q_OBJECT
public:
explicit MyTextEdit(QWidget *parent = 0);
protected:
void dragEnterEvent ( QDragEnterEvent * e );
void dragLeaveEvent ( QDragLeaveEvent * e );
void dragMoveEvent ( QDragMoveEvent * e );
void mouseDoubleClickEvent ( QMouseEvent * e );
void mousePressEvent(QMouseEvent * e);
// void mouseReleaseEvent(QMouseEvent *e);
// void changeEvent ( QEvent * event );
// void mouseMoveEvent ( QMouseEvent * e );
// void keyPressEvent(QKeyEvent * event);
// bool qwsEvent ( QWSEvent * event );
};
#endif /* MYTEXTEDIT_H_ */
/*
* MyTextEdit.h
*
* Created on: Aug 7, 2013
* Author: yiyu
* QQ:1036184468
* Descriptoin:
*/
#ifndef MYTEXTEDIT_H_
#define MYTEXTEDIT_H_
#include <QTextEdit>
#include <QDragEnterEvent>
//#include <QWSEvent>
class MyTextEdit:public QTextEdit{
Q_OBJECT
public:
explicit MyTextEdit(QWidget *parent = 0);
protected:
void dragEnterEvent ( QDragEnterEvent * e );
void dragLeaveEvent ( QDragLeaveEvent * e );
void dragMoveEvent ( QDragMoveEvent * e );
void mouseDoubleClickEvent ( QMouseEvent * e );
void mousePressEvent(QMouseEvent * e);
// void mouseReleaseEvent(QMouseEvent *e);
// void changeEvent ( QEvent * event );
// void mouseMoveEvent ( QMouseEvent * e );
// void keyPressEvent(QKeyEvent * event);
// bool qwsEvent ( QWSEvent * event );
};
#endif /* MYTEXTEDIT_H_ */
+160 -160
View File
@@ -1,160 +1,160 @@
#include "IPEdit.h"
#include <QPainter>
#include <QApplication>
#include <QStyle>
#include <QStyleOptionButton>
#include <QKeyEvent>
#include <QShortcutEvent>
#include <QRegExpValidator>
#include <QRegExp>
#include <QClipboard>
#include <QDebug>
IPEdit::IPEdit(QWidget *parent) : QWidget(parent)
{
init();
}
IPEdit::~IPEdit()
{
}
void IPEdit::init()
{
m_layout = new QHBoxLayout(this);
m_layout->setSpacing(3);
m_layout->setContentsMargins(2, 0, 2, 0);
m_edit1 = new QLineEdit(this);
m_edit2 = new QLineEdit(this);
m_edit3 = new QLineEdit(this);
m_edit4 = new QLineEdit(this);
initForEdit(m_edit1);
initForEdit(m_edit2);
initForEdit(m_edit3);
initForEdit(m_edit4);
m_dot1 = new QLabel(".", this);
m_dot2 = new QLabel(".", this);
m_dot3 = new QLabel(".", this);
m_layout->addWidget(m_edit1, 1);
m_layout->addWidget(m_dot1);
m_layout->addWidget(m_edit2, 1);
m_layout->addWidget(m_dot2);
m_layout->addWidget(m_edit3, 1);
m_layout->addWidget(m_dot3);
m_layout->addWidget(m_edit4, 1);
}
void IPEdit::initForEdit(QLineEdit* edit)
{
edit->setFrame(false);
edit->setAlignment(Qt::AlignCenter);
edit->installEventFilter(this);
QRegExpValidator* validator = new QRegExpValidator(QRegExp("^(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$"), this);
edit->setValidator(validator);
connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(editTextChanged(const QString&)));
}
QLineEdit* IPEdit::nextEdit(QLineEdit* curEdit)
{
if (curEdit == m_edit1)
return m_edit2;
else if (curEdit == m_edit2)
return m_edit3;
else if (curEdit == m_edit3)
return m_edit4;
else
return NULL;
}
bool IPEdit::isEdit(QObject* object)
{
return (object == m_edit1 ||
object == m_edit2 ||
object == m_edit3 ||
object == m_edit4);
}
QString IPEdit::text()
{
QString sec1 = m_edit1->text().isEmpty() ? "0" : m_edit1->text();
QString sec2 = m_edit2->text().isEmpty() ? "0" : m_edit2->text();
QString sec3 = m_edit3->text().isEmpty() ? "0" : m_edit3->text();
QString sec4 = m_edit4->text().isEmpty() ? "0" : m_edit4->text();
return QString("%1.%2.%3.%4").arg(sec1).arg(sec2).arg(sec3).arg(sec4);
}
void IPEdit::setText(const QString& text)
{
QRegExp reg("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$");
if (!reg.exactMatch(text))
return;
QStringList ips = text.split(".");
m_edit1->setText(ips.at(0));
m_edit2->setText(ips.at(1));
m_edit3->setText(ips.at(2));
m_edit4->setText(ips.at(3));
}
void IPEdit::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
QStyleOptionFrame option;
option.initFrom(this);
option.lineWidth = 1;
style()->drawPrimitive(QStyle::PE_PanelLineEdit, &option, &painter, this);
QWidget::paintEvent(event);
}
bool IPEdit::eventFilter(QObject* object, QEvent* event)
{
if (isEdit(object))
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Period)
{
QLineEdit* next = nextEdit(qobject_cast<QLineEdit*>(object));
if (next)
{
next->setFocus();
next->selectAll();
}
}
else if (keyEvent->matches(QKeySequence::Paste))
{
QString clip = QApplication::clipboard()->text(QClipboard::Clipboard);
if (clip.split(".").size() == 4)
{
setText(clip);
return true;
}
}
}
}
return QWidget::eventFilter(object, event);
}
void IPEdit::editTextChanged(const QString& text)
{
QLineEdit* curEdit = qobject_cast<QLineEdit*>(sender());
if (text.size() == 3)
{
QLineEdit* next = nextEdit(curEdit);
if (next)
{
next->setFocus();
next->selectAll();
}
}
}
#include "IPEdit.h"
#include <QPainter>
#include <QApplication>
#include <QStyle>
#include <QStyleOptionButton>
#include <QKeyEvent>
#include <QShortcutEvent>
#include <QRegExpValidator>
#include <QRegExp>
#include <QClipboard>
#include <QDebug>
IPEdit::IPEdit(QWidget *parent) : QWidget(parent)
{
init();
}
IPEdit::~IPEdit()
{
}
void IPEdit::init()
{
m_layout = new QHBoxLayout(this);
m_layout->setSpacing(3);
m_layout->setContentsMargins(2, 0, 2, 0);
m_edit1 = new QLineEdit(this);
m_edit2 = new QLineEdit(this);
m_edit3 = new QLineEdit(this);
m_edit4 = new QLineEdit(this);
initForEdit(m_edit1);
initForEdit(m_edit2);
initForEdit(m_edit3);
initForEdit(m_edit4);
m_dot1 = new QLabel(".", this);
m_dot2 = new QLabel(".", this);
m_dot3 = new QLabel(".", this);
m_layout->addWidget(m_edit1, 1);
m_layout->addWidget(m_dot1);
m_layout->addWidget(m_edit2, 1);
m_layout->addWidget(m_dot2);
m_layout->addWidget(m_edit3, 1);
m_layout->addWidget(m_dot3);
m_layout->addWidget(m_edit4, 1);
}
void IPEdit::initForEdit(QLineEdit* edit)
{
edit->setFrame(false);
edit->setAlignment(Qt::AlignCenter);
edit->installEventFilter(this);
QRegExpValidator* validator = new QRegExpValidator(QRegExp("^(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$"), this);
edit->setValidator(validator);
connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(editTextChanged(const QString&)));
}
QLineEdit* IPEdit::nextEdit(QLineEdit* curEdit)
{
if (curEdit == m_edit1)
return m_edit2;
else if (curEdit == m_edit2)
return m_edit3;
else if (curEdit == m_edit3)
return m_edit4;
else
return NULL;
}
bool IPEdit::isEdit(QObject* object)
{
return (object == m_edit1 ||
object == m_edit2 ||
object == m_edit3 ||
object == m_edit4);
}
QString IPEdit::text()
{
QString sec1 = m_edit1->text().isEmpty() ? "0" : m_edit1->text();
QString sec2 = m_edit2->text().isEmpty() ? "0" : m_edit2->text();
QString sec3 = m_edit3->text().isEmpty() ? "0" : m_edit3->text();
QString sec4 = m_edit4->text().isEmpty() ? "0" : m_edit4->text();
return QString("%1.%2.%3.%4").arg(sec1).arg(sec2).arg(sec3).arg(sec4);
}
void IPEdit::setText(const QString& text)
{
QRegExp reg("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$");
if (!reg.exactMatch(text))
return;
QStringList ips = text.split(".");
m_edit1->setText(ips.at(0));
m_edit2->setText(ips.at(1));
m_edit3->setText(ips.at(2));
m_edit4->setText(ips.at(3));
}
void IPEdit::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
QStyleOptionFrame option;
option.initFrom(this);
option.lineWidth = 1;
style()->drawPrimitive(QStyle::PE_PanelLineEdit, &option, &painter, this);
QWidget::paintEvent(event);
}
bool IPEdit::eventFilter(QObject* object, QEvent* event)
{
if (isEdit(object))
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Period)
{
QLineEdit* next = nextEdit(qobject_cast<QLineEdit*>(object));
if (next)
{
next->setFocus();
next->selectAll();
}
}
else if (keyEvent->matches(QKeySequence::Paste))
{
QString clip = QApplication::clipboard()->text(QClipboard::Clipboard);
if (clip.split(".").size() == 4)
{
setText(clip);
return true;
}
}
}
}
return QWidget::eventFilter(object, event);
}
void IPEdit::editTextChanged(const QString& text)
{
QLineEdit* curEdit = qobject_cast<QLineEdit*>(sender());
if (text.size() == 3)
{
QLineEdit* next = nextEdit(curEdit);
if (next)
{
next->setFocus();
next->selectAll();
}
}
}
+44 -44
View File
@@ -1,44 +1,44 @@
#ifndef IPEDIT_H
#define IPEDIT_H
#include <QWidget>
#include <QLineEdit>
#include <QSpinBox>
#include <QLabel>
#include <QBoxLayout>
#include <QPaintEvent>
class IPEdit : public QWidget
{
Q_OBJECT
public:
explicit IPEdit(QWidget *parent = 0);
~IPEdit();
QString text();
void setText(const QString& text);
protected:
void init();
void initForEdit(QLineEdit* edit);
QLineEdit* nextEdit(QLineEdit* curEdit);
bool isEdit(QObject* object);
virtual void paintEvent(QPaintEvent* event);
virtual bool eventFilter(QObject* object, QEvent* event);
protected slots:
void editTextChanged(const QString& text);
private:
QBoxLayout* m_layout;
QLineEdit* m_edit1;
QLineEdit* m_edit2;
QLineEdit* m_edit3;
QLineEdit* m_edit4;
QLabel* m_dot1;
QLabel* m_dot2;
QLabel* m_dot3;
};
#endif // IPEDIT_H
#ifndef IPEDIT_H
#define IPEDIT_H
#include <QWidget>
#include <QLineEdit>
#include <QSpinBox>
#include <QLabel>
#include <QBoxLayout>
#include <QPaintEvent>
class IPEdit : public QWidget
{
Q_OBJECT
public:
explicit IPEdit(QWidget *parent = 0);
~IPEdit();
QString text();
void setText(const QString& text);
protected:
void init();
void initForEdit(QLineEdit* edit);
QLineEdit* nextEdit(QLineEdit* curEdit);
bool isEdit(QObject* object);
virtual void paintEvent(QPaintEvent* event);
virtual bool eventFilter(QObject* object, QEvent* event);
protected slots:
void editTextChanged(const QString& text);
private:
QBoxLayout* m_layout;
QLineEdit* m_edit1;
QLineEdit* m_edit2;
QLineEdit* m_edit3;
QLineEdit* m_edit4;
QLabel* m_dot1;
QLabel* m_dot2;
QLabel* m_dot3;
};
#endif // IPEDIT_H
+8 -8
View File
@@ -1,9 +1,9 @@
# 用法
``` cpp
IPEdit* ipEdit = new IPEdit(this);
ipEdit->setGeometry(10, 10, 130, 25);
ipEdit->show();
ipEdit->setText("255.255.255.0");
QString text = ipEdit->text();
# 用法
``` cpp
IPEdit* ipEdit = new IPEdit(this);
ipEdit->setGeometry(10, 10, 130, 25);
ipEdit->show();
ipEdit->setText("255.255.255.0");
QString text = ipEdit->text();
```
+1819 -1819
View File
File diff suppressed because it is too large Load Diff
+142 -142
View File
@@ -1,142 +1,142 @@
#ifndef __NETWORKMANAGER_H__
#define __NETWORKMANAGER_H__
#include <QWidget>
#include <QProcess>
#include <QSocketNotifier>
#include <QMap>
#include "ParaSettingUI.h"
#include "wpamsg.h"
#include <QTimer>
#include "myinclude.h"
#include "print_net.h"
namespace Ui {
class NetworkManager;
}
enum {
AUTH_NONE_OPEN,
AUTH_NONE_WEP,
AUTH_NONE_WEP_SHARED,
AUTH_IEEE8021X,
AUTH_WPA_PSK,
AUTH_WPA_EAP,
AUTH_WPA2_PSK,
AUTH_WPA2_EAP
};
struct ScanResult{
char ssid[50];
char bssid[50];
char qual[20];
char flags[80];
};
#define WPA_GUI_KEY_DATA "[key is configured]"
class NetworkManager : public QWidget,public ParaSettingUI
{
Q_OBJECT
public:
explicit NetworkManager(QWidget *parent = 0);
~NetworkManager();
void bindSysPara(SysPara *sysPara);
void applyUIPara();
void updateSysStatusToUI();
void applyLanUIPara(void);
qint32 isIpv4Address(QString ip);
void updateAuthorization(int auth);
QString processHandle(QString);
bool isWifiConnected(const QString &output);
public slots:
virtual int ctrlRequest(const char *cmd, char *buf, size_t *buflen);
virtual void updateStatus();
virtual void updateResults();
virtual void updateNetworks();
virtual void selectSSID( const QString & sel );
virtual void selectNetwork( const QString & sel );
virtual void processMsg(char *msg);
virtual void receiveMsgs();
virtual int setNetworkParam(int id, const char *field,
const char *value, bool quote);
virtual void addNetwork();
virtual void triggerUpdate();
virtual void authChanged(int sel);
virtual void ping();
virtual void removeNetwork();
Q_SIGNALS:
void updateJSONData();
void net_startPrint();
void net_pausePrint();
void net_stopPrint();
void OpenNewFile();
private slots:
void on_pushButtonSetIP_clicked(bool checked);
void on_pushButtonSetCancel_clicked(bool checked);
void on_pushButtonScan_pressed();
void on_pushButtonConnect_pressed();
void on_pushButtonDisconnect_pressed();
void on_scanSSIDSelect_activated(const QString &arg1);
void on_pushButtonAddNetworkd_pressed();
void on_pushButtonRemove_pressed();
void on_GetJsonpushButton_clicked();
void onfinish_get_json();
void onjson_timer_handler();
void onjson_server_error();
void on_applicate_pushButton_clicked();
void ShowNet_dataMessege();
//void on_checkBoxShortNet_clicked(bool checked);
void on_checkBoxRemoveDigitCode_clicked(bool checked);
void on_checkBoxRemoveCode_clicked(bool checked);
void on_radioButtonGetDataEnable_clicked(bool checked);
void setEth0StaticIP_Thread();
private:
Ui::NetworkManager *ui;
QProcess *processNetwork;
bool networkMayHaveChanged;
bool beSentScanCmd;
char *ctrl_iface;
int edit_network_id;
struct wpa_ctrl *ctrl_conn;
int pingsToStatusUpdate;
//WpaMsgList msgs;
char *ctrl_iface_dir;
struct wpa_ctrl *monitor_conn;
//UserDataRequest *udr;
QSocketNotifier *msgNotifier;
WpaMsgList msgs;
//struct ScanResult scanResult[30];
QMap<QString, QStringList> scanResultMap;
PrintNet *net_data;
int openCtrlConnection(const char *ifname);
QString wpaStateTranslate(char *state);
QString bssid;
QTimer *timer;
QTimer *Json_timer;
bool Jsom_timer_stop;
bool wlanStartUpFailed;
bool Json_ip_init_done;
bool setEth0StaticIP();
QString getCurrentNetworkIP()const ;
};
#endif // __NETWORKMANAGER_H__
#ifndef __NETWORKMANAGER_H__
#define __NETWORKMANAGER_H__
#include <QWidget>
#include <QProcess>
#include <QSocketNotifier>
#include <QMap>
#include "ParaSettingUI.h"
#include "wpamsg.h"
#include <QTimer>
#include "myinclude.h"
#include "print_net.h"
namespace Ui {
class NetworkManager;
}
enum {
AUTH_NONE_OPEN,
AUTH_NONE_WEP,
AUTH_NONE_WEP_SHARED,
AUTH_IEEE8021X,
AUTH_WPA_PSK,
AUTH_WPA_EAP,
AUTH_WPA2_PSK,
AUTH_WPA2_EAP
};
struct ScanResult{
char ssid[50];
char bssid[50];
char qual[20];
char flags[80];
};
#define WPA_GUI_KEY_DATA "[key is configured]"
class NetworkManager : public QWidget,public ParaSettingUI
{
Q_OBJECT
public:
explicit NetworkManager(QWidget *parent = 0);
~NetworkManager();
void bindSysPara(SysPara *sysPara);
void applyUIPara();
void updateSysStatusToUI();
void applyLanUIPara(void);
qint32 isIpv4Address(QString ip);
void updateAuthorization(int auth);
QString processHandle(QString);
bool isWifiConnected(const QString &output);
public slots:
virtual int ctrlRequest(const char *cmd, char *buf, size_t *buflen);
virtual void updateStatus();
virtual void updateResults();
virtual void updateNetworks();
virtual void selectSSID( const QString & sel );
virtual void selectNetwork( const QString & sel );
virtual void processMsg(char *msg);
virtual void receiveMsgs();
virtual int setNetworkParam(int id, const char *field,
const char *value, bool quote);
virtual void addNetwork();
virtual void triggerUpdate();
virtual void authChanged(int sel);
virtual void ping();
virtual void removeNetwork();
Q_SIGNALS:
void updateJSONData();
void net_startPrint();
void net_pausePrint();
void net_stopPrint();
void OpenNewFile();
private slots:
void on_pushButtonSetIP_clicked(bool checked);
void on_pushButtonSetCancel_clicked(bool checked);
void on_pushButtonScan_pressed();
void on_pushButtonConnect_pressed();
void on_pushButtonDisconnect_pressed();
void on_scanSSIDSelect_activated(const QString &arg1);
void on_pushButtonAddNetworkd_pressed();
void on_pushButtonRemove_pressed();
void on_GetJsonpushButton_clicked();
void onfinish_get_json();
void onjson_timer_handler();
void onjson_server_error();
void on_applicate_pushButton_clicked();
void ShowNet_dataMessege();
//void on_checkBoxShortNet_clicked(bool checked);
void on_checkBoxRemoveDigitCode_clicked(bool checked);
void on_checkBoxRemoveCode_clicked(bool checked);
void on_radioButtonGetDataEnable_clicked(bool checked);
void setEth0StaticIP_Thread();
private:
Ui::NetworkManager *ui;
QProcess *processNetwork;
bool networkMayHaveChanged;
bool beSentScanCmd;
char *ctrl_iface;
int edit_network_id;
struct wpa_ctrl *ctrl_conn;
int pingsToStatusUpdate;
//WpaMsgList msgs;
char *ctrl_iface_dir;
struct wpa_ctrl *monitor_conn;
//UserDataRequest *udr;
QSocketNotifier *msgNotifier;
WpaMsgList msgs;
//struct ScanResult scanResult[30];
QMap<QString, QStringList> scanResultMap;
PrintNet *net_data;
int openCtrlConnection(const char *ifname);
QString wpaStateTranslate(char *state);
QString bssid;
QTimer *timer;
QTimer *Json_timer;
bool Jsom_timer_stop;
bool wlanStartUpFailed;
bool Json_ip_init_done;
bool setEth0StaticIP();
QString getCurrentNetworkIP()const ;
};
#endif // __NETWORKMANAGER_H__
+827 -827
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -1,4 +1,4 @@
.moc
.obj
.ui
qrc_icons.cpp
.moc
.obj
.ui
qrc_icons.cpp
+245 -245
View File
@@ -1,245 +1,245 @@
/*
* wpa_gui - AddInterface class
* Copyright (c) 2008, Jouni Malinen <j@w1.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#include <cstdio>
#include "common/wpa_ctrl.h"
#include <QMessageBox>
#include "wpagui.h"
#include "addinterface.h"
#ifdef CONFIG_NATIVE_WINDOWS
#include <windows.h>
#ifndef WPA_KEY_ROOT
#define WPA_KEY_ROOT HKEY_LOCAL_MACHINE
#endif
#ifndef WPA_KEY_PREFIX
#define WPA_KEY_PREFIX TEXT("SOFTWARE\\wpa_supplicant")
#endif
#endif /* CONFIG_NATIVE_WINDOWS */
AddInterface::AddInterface(WpaGui *_wpagui, QWidget *parent)
: QDialog(parent), wpagui(_wpagui)
{
setWindowTitle(tr("Select network interface to add"));
resize(400, 200);
vboxLayout = new QVBoxLayout(this);
interfaceWidget = new QTreeWidget(this);
interfaceWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
interfaceWidget->setUniformRowHeights(true);
interfaceWidget->setSortingEnabled(true);
interfaceWidget->setColumnCount(3);
interfaceWidget->headerItem()->setText(0, tr("driver"));
interfaceWidget->headerItem()->setText(1, tr("interface"));
interfaceWidget->headerItem()->setText(2, tr("description"));
interfaceWidget->setItemsExpandable(FALSE);
interfaceWidget->setRootIsDecorated(FALSE);
vboxLayout->addWidget(interfaceWidget);
connect(interfaceWidget,
SIGNAL(itemActivated(QTreeWidgetItem *, int)), this,
SLOT(interfaceSelected(QTreeWidgetItem *)));
addInterfaces();
}
void AddInterface::addInterfaces()
{
#ifdef CONFIG_CTRL_IFACE_NAMED_PIPE
struct wpa_ctrl *ctrl;
int ret;
char buf[2048];
size_t len;
ctrl = wpa_ctrl_open(NULL);
if (ctrl == NULL)
return;
len = sizeof(buf) - 1;
ret = wpa_ctrl_request(ctrl, "INTERFACE_LIST", 14, buf, &len, NULL);
if (ret < 0) {
wpa_ctrl_close(ctrl);
return;
}
buf[len] = '\0';
wpa_ctrl_close(ctrl);
QString ifaces(buf);
QStringList lines = ifaces.split(QRegExp("\\n"));
for (QStringList::Iterator it = lines.begin();
it != lines.end(); it++) {
QStringList arg = (*it).split(QChar('\t'));
if (arg.size() < 3)
continue;
QTreeWidgetItem *item = new QTreeWidgetItem(interfaceWidget);
if (!item)
break;
item->setText(0, arg[0]);
item->setText(1, arg[1]);
item->setText(2, arg[2]);
}
interfaceWidget->resizeColumnToContents(0);
interfaceWidget->resizeColumnToContents(1);
interfaceWidget->resizeColumnToContents(2);
#endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */
}
#ifdef CONFIG_NATIVE_WINDOWS
bool AddInterface::addRegistryInterface(const QString &ifname)
{
HKEY hk, ihk;
LONG ret;
int id, tmp;
TCHAR name[10];
DWORD val, i;
ret = RegOpenKeyEx(WPA_KEY_ROOT, WPA_KEY_PREFIX TEXT("\\interfaces"),
0, KEY_ENUMERATE_SUB_KEYS | KEY_CREATE_SUB_KEY,
&hk);
if (ret != ERROR_SUCCESS)
return false;
id = -1;
for (i = 0; ; i++) {
TCHAR name[255];
DWORD namelen;
namelen = 255;
ret = RegEnumKeyEx(hk, i, name, &namelen, NULL, NULL, NULL,
NULL);
if (ret == ERROR_NO_MORE_ITEMS)
break;
if (ret != ERROR_SUCCESS)
break;
if (namelen >= 255)
namelen = 255 - 1;
name[namelen] = '\0';
#ifdef UNICODE
QString s((QChar *) name, namelen);
#else /* UNICODE */
QString s(name);
#endif /* UNICODE */
tmp = s.toInt();
if (tmp > id)
id = tmp;
}
id += 1;
#ifdef UNICODE
wsprintf(name, L"%04d", id);
#else /* UNICODE */
os_snprintf(name, sizeof(name), "%04d", id);
#endif /* UNICODE */
ret = RegCreateKeyEx(hk, name, 0, NULL, 0, KEY_WRITE, NULL, &ihk,
NULL);
RegCloseKey(hk);
if (ret != ERROR_SUCCESS)
return false;
#ifdef UNICODE
RegSetValueEx(ihk, TEXT("adapter"), 0, REG_SZ,
(LPBYTE) ifname.unicode(),
(ifname.length() + 1) * sizeof(TCHAR));
#else /* UNICODE */
RegSetValueEx(ihk, TEXT("adapter"), 0, REG_SZ,
(LPBYTE) ifname.toLocal8Bit(), ifname.length() + 1);
#endif /* UNICODE */
RegSetValueEx(ihk, TEXT("config"), 0, REG_SZ,
(LPBYTE) TEXT("default"), 8 * sizeof(TCHAR));
RegSetValueEx(ihk, TEXT("ctrl_interface"), 0, REG_SZ,
(LPBYTE) TEXT(""), 1 * sizeof(TCHAR));
val = 1;
RegSetValueEx(ihk, TEXT("skip_on_error"), 0, REG_DWORD, (LPBYTE) &val,
sizeof(val));
RegCloseKey(ihk);
return true;
}
#endif /* CONFIG_NATIVE_WINDOWS */
void AddInterface::interfaceSelected(QTreeWidgetItem *sel)
{
if (!sel)
return;
#ifdef CONFIG_CTRL_IFACE_NAMED_PIPE
struct wpa_ctrl *ctrl;
int ret;
char buf[20], cmd[256];
size_t len;
/*
* INTERFACE_ADD <ifname>TAB<confname>TAB<driver>TAB<ctrl_interface>TAB
* <driver_param>TAB<bridge_name>
*/
snprintf(cmd, sizeof(cmd),
"INTERFACE_ADD %s\t%s\t%s\t%s\t%s\t%s",
sel->text(1).toAscii().constData(),
"default",
sel->text(0).toAscii().constData(),
"yes", "", "");
cmd[sizeof(cmd) - 1] = '\0';
ctrl = wpa_ctrl_open(NULL);
if (ctrl == NULL)
return;
len = sizeof(buf) - 1;
ret = wpa_ctrl_request(ctrl, cmd, strlen(cmd), buf, &len, NULL);
wpa_ctrl_close(ctrl);
if (ret < 0) {
QMessageBox::warning(this, "wpa_gui",
tr("Add interface command could not be "
"completed."));
return;
}
buf[len] = '\0';
if (buf[0] != 'O' || buf[1] != 'K') {
QMessageBox::warning(this, "wpa_gui",
tr("Failed to add the interface."));
return;
}
#endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */
#ifdef CONFIG_NATIVE_WINDOWS
if (!addRegistryInterface(sel->text(1))) {
QMessageBox::information(this, "wpa_gui",
tr("Failed to add the interface into "
"registry."));
}
#endif /* CONFIG_NATIVE_WINDOWS */
wpagui->selectAdapter(sel->text(1));
close();
}
/*
* wpa_gui - AddInterface class
* Copyright (c) 2008, Jouni Malinen <j@w1.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#include <cstdio>
#include "common/wpa_ctrl.h"
#include <QMessageBox>
#include "wpagui.h"
#include "addinterface.h"
#ifdef CONFIG_NATIVE_WINDOWS
#include <windows.h>
#ifndef WPA_KEY_ROOT
#define WPA_KEY_ROOT HKEY_LOCAL_MACHINE
#endif
#ifndef WPA_KEY_PREFIX
#define WPA_KEY_PREFIX TEXT("SOFTWARE\\wpa_supplicant")
#endif
#endif /* CONFIG_NATIVE_WINDOWS */
AddInterface::AddInterface(WpaGui *_wpagui, QWidget *parent)
: QDialog(parent), wpagui(_wpagui)
{
setWindowTitle(tr("Select network interface to add"));
resize(400, 200);
vboxLayout = new QVBoxLayout(this);
interfaceWidget = new QTreeWidget(this);
interfaceWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
interfaceWidget->setUniformRowHeights(true);
interfaceWidget->setSortingEnabled(true);
interfaceWidget->setColumnCount(3);
interfaceWidget->headerItem()->setText(0, tr("driver"));
interfaceWidget->headerItem()->setText(1, tr("interface"));
interfaceWidget->headerItem()->setText(2, tr("description"));
interfaceWidget->setItemsExpandable(FALSE);
interfaceWidget->setRootIsDecorated(FALSE);
vboxLayout->addWidget(interfaceWidget);
connect(interfaceWidget,
SIGNAL(itemActivated(QTreeWidgetItem *, int)), this,
SLOT(interfaceSelected(QTreeWidgetItem *)));
addInterfaces();
}
void AddInterface::addInterfaces()
{
#ifdef CONFIG_CTRL_IFACE_NAMED_PIPE
struct wpa_ctrl *ctrl;
int ret;
char buf[2048];
size_t len;
ctrl = wpa_ctrl_open(NULL);
if (ctrl == NULL)
return;
len = sizeof(buf) - 1;
ret = wpa_ctrl_request(ctrl, "INTERFACE_LIST", 14, buf, &len, NULL);
if (ret < 0) {
wpa_ctrl_close(ctrl);
return;
}
buf[len] = '\0';
wpa_ctrl_close(ctrl);
QString ifaces(buf);
QStringList lines = ifaces.split(QRegExp("\\n"));
for (QStringList::Iterator it = lines.begin();
it != lines.end(); it++) {
QStringList arg = (*it).split(QChar('\t'));
if (arg.size() < 3)
continue;
QTreeWidgetItem *item = new QTreeWidgetItem(interfaceWidget);
if (!item)
break;
item->setText(0, arg[0]);
item->setText(1, arg[1]);
item->setText(2, arg[2]);
}
interfaceWidget->resizeColumnToContents(0);
interfaceWidget->resizeColumnToContents(1);
interfaceWidget->resizeColumnToContents(2);
#endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */
}
#ifdef CONFIG_NATIVE_WINDOWS
bool AddInterface::addRegistryInterface(const QString &ifname)
{
HKEY hk, ihk;
LONG ret;
int id, tmp;
TCHAR name[10];
DWORD val, i;
ret = RegOpenKeyEx(WPA_KEY_ROOT, WPA_KEY_PREFIX TEXT("\\interfaces"),
0, KEY_ENUMERATE_SUB_KEYS | KEY_CREATE_SUB_KEY,
&hk);
if (ret != ERROR_SUCCESS)
return false;
id = -1;
for (i = 0; ; i++) {
TCHAR name[255];
DWORD namelen;
namelen = 255;
ret = RegEnumKeyEx(hk, i, name, &namelen, NULL, NULL, NULL,
NULL);
if (ret == ERROR_NO_MORE_ITEMS)
break;
if (ret != ERROR_SUCCESS)
break;
if (namelen >= 255)
namelen = 255 - 1;
name[namelen] = '\0';
#ifdef UNICODE
QString s((QChar *) name, namelen);
#else /* UNICODE */
QString s(name);
#endif /* UNICODE */
tmp = s.toInt();
if (tmp > id)
id = tmp;
}
id += 1;
#ifdef UNICODE
wsprintf(name, L"%04d", id);
#else /* UNICODE */
os_snprintf(name, sizeof(name), "%04d", id);
#endif /* UNICODE */
ret = RegCreateKeyEx(hk, name, 0, NULL, 0, KEY_WRITE, NULL, &ihk,
NULL);
RegCloseKey(hk);
if (ret != ERROR_SUCCESS)
return false;
#ifdef UNICODE
RegSetValueEx(ihk, TEXT("adapter"), 0, REG_SZ,
(LPBYTE) ifname.unicode(),
(ifname.length() + 1) * sizeof(TCHAR));
#else /* UNICODE */
RegSetValueEx(ihk, TEXT("adapter"), 0, REG_SZ,
(LPBYTE) ifname.toLocal8Bit(), ifname.length() + 1);
#endif /* UNICODE */
RegSetValueEx(ihk, TEXT("config"), 0, REG_SZ,
(LPBYTE) TEXT("default"), 8 * sizeof(TCHAR));
RegSetValueEx(ihk, TEXT("ctrl_interface"), 0, REG_SZ,
(LPBYTE) TEXT(""), 1 * sizeof(TCHAR));
val = 1;
RegSetValueEx(ihk, TEXT("skip_on_error"), 0, REG_DWORD, (LPBYTE) &val,
sizeof(val));
RegCloseKey(ihk);
return true;
}
#endif /* CONFIG_NATIVE_WINDOWS */
void AddInterface::interfaceSelected(QTreeWidgetItem *sel)
{
if (!sel)
return;
#ifdef CONFIG_CTRL_IFACE_NAMED_PIPE
struct wpa_ctrl *ctrl;
int ret;
char buf[20], cmd[256];
size_t len;
/*
* INTERFACE_ADD <ifname>TAB<confname>TAB<driver>TAB<ctrl_interface>TAB
* <driver_param>TAB<bridge_name>
*/
snprintf(cmd, sizeof(cmd),
"INTERFACE_ADD %s\t%s\t%s\t%s\t%s\t%s",
sel->text(1).toAscii().constData(),
"default",
sel->text(0).toAscii().constData(),
"yes", "", "");
cmd[sizeof(cmd) - 1] = '\0';
ctrl = wpa_ctrl_open(NULL);
if (ctrl == NULL)
return;
len = sizeof(buf) - 1;
ret = wpa_ctrl_request(ctrl, cmd, strlen(cmd), buf, &len, NULL);
wpa_ctrl_close(ctrl);
if (ret < 0) {
QMessageBox::warning(this, "wpa_gui",
tr("Add interface command could not be "
"completed."));
return;
}
buf[len] = '\0';
if (buf[0] != 'O' || buf[1] != 'K') {
QMessageBox::warning(this, "wpa_gui",
tr("Failed to add the interface."));
return;
}
#endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */
#ifdef CONFIG_NATIVE_WINDOWS
if (!addRegistryInterface(sel->text(1))) {
QMessageBox::information(this, "wpa_gui",
tr("Failed to add the interface into "
"registry."));
}
#endif /* CONFIG_NATIVE_WINDOWS */
wpagui->selectAdapter(sel->text(1));
close();
}

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