Merge branch 'master' into gxs_mail_experiments

This commit is contained in:
Gioacchino Mazzurco 2017-02-27 08:43:29 +01:00
commit 9a3af092eb
136 changed files with 5570 additions and 3846 deletions

View File

@ -114,7 +114,7 @@ install:
- copy C:\msys64\mingw64\x86_64-w64-mingw32\bin\ranlib.exe C:\msys64\mingw64\bin\x86_64-w64-mingw32-ranlib.exe - copy C:\msys64\mingw64\x86_64-w64-mingw32\bin\ranlib.exe C:\msys64\mingw64\bin\x86_64-w64-mingw32-ranlib.exe
- copy C:\msys64\mingw64\bin\windres.exe C:\msys64\mingw64\bin\x86_64-w64-mingw32-windres.exe - copy C:\msys64\mingw64\bin\windres.exe C:\msys64\mingw64\bin\x86_64-w64-mingw32-windres.exe
# Build missing Libs # Build missing Libs
- C:\msys64\mingw32_shell.bat -lc "cd /c/projects/RetroShare/msys2_build_libs/ && make" - C:\msys64\mingw32.exe -lc "cd /c/projects/RetroShare/msys2_build_libs/ && make"
# Clone RetroShare # Clone RetroShare
#- git clone -q --branch={branch} https://github.com/RetroShare/RetroShare.git C:\projects\RetroShare #- git clone -q --branch={branch} https://github.com/RetroShare/RetroShare.git C:\projects\RetroShare

View File

@ -537,6 +537,7 @@ bool AEAD_chacha20_sha256(uint8_t key[32], uint8_t nonce[12],uint8_t *data,uint3
uint8_t computed_tag[EVP_MAX_MD_SIZE]; uint8_t computed_tag[EVP_MAX_MD_SIZE];
unsigned int md_size ; unsigned int md_size ;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
HMAC_CTX hmac_ctx ; HMAC_CTX hmac_ctx ;
HMAC_CTX_init(&hmac_ctx) ; HMAC_CTX_init(&hmac_ctx) ;
@ -544,6 +545,17 @@ bool AEAD_chacha20_sha256(uint8_t key[32], uint8_t nonce[12],uint8_t *data,uint3
HMAC_Update(&hmac_ctx,aad,aad_size) ; HMAC_Update(&hmac_ctx,aad,aad_size) ;
HMAC_Update(&hmac_ctx,data,data_size) ; HMAC_Update(&hmac_ctx,data,data_size) ;
HMAC_Final(&hmac_ctx,computed_tag,&md_size) ; HMAC_Final(&hmac_ctx,computed_tag,&md_size) ;
#else
HMAC_CTX *hmac_ctx = HMAC_CTX_new();
HMAC_Init_ex(hmac_ctx,key,32,EVP_sha256(),NULL) ;
HMAC_Update(hmac_ctx,aad,aad_size) ;
HMAC_Update(hmac_ctx,data,data_size) ;
HMAC_Final(hmac_ctx,computed_tag,&md_size) ;
HMAC_CTX_free(hmac_ctx) ;
hmac_ctx=NULL;
#endif
assert(md_size >= 16); assert(md_size >= 16);
@ -556,6 +568,7 @@ bool AEAD_chacha20_sha256(uint8_t key[32], uint8_t nonce[12],uint8_t *data,uint3
uint8_t computed_tag[EVP_MAX_MD_SIZE]; uint8_t computed_tag[EVP_MAX_MD_SIZE];
unsigned int md_size ; unsigned int md_size ;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
HMAC_CTX hmac_ctx ; HMAC_CTX hmac_ctx ;
HMAC_CTX_init(&hmac_ctx) ; HMAC_CTX_init(&hmac_ctx) ;
@ -563,6 +576,17 @@ bool AEAD_chacha20_sha256(uint8_t key[32], uint8_t nonce[12],uint8_t *data,uint3
HMAC_Update(&hmac_ctx,aad,aad_size) ; HMAC_Update(&hmac_ctx,aad,aad_size) ;
HMAC_Update(&hmac_ctx,data,data_size) ; HMAC_Update(&hmac_ctx,data,data_size) ;
HMAC_Final(&hmac_ctx,computed_tag,&md_size) ; HMAC_Final(&hmac_ctx,computed_tag,&md_size) ;
#else
HMAC_CTX *hmac_ctx = HMAC_CTX_new();
HMAC_Init_ex(hmac_ctx,key,32,EVP_sha256(),NULL) ;
HMAC_Update(hmac_ctx,aad,aad_size) ;
HMAC_Update(hmac_ctx,data,data_size) ;
HMAC_Final(hmac_ctx,computed_tag,&md_size) ;
HMAC_CTX_free(hmac_ctx) ;
hmac_ctx=NULL;
#endif
// decrypt // decrypt

View File

@ -70,24 +70,28 @@ void LocalDirectoryUpdater::setEnabled(bool b)
void LocalDirectoryUpdater::data_tick() void LocalDirectoryUpdater::data_tick()
{ {
time_t now = time(NULL) ; time_t now = time(NULL) ;
if (mIsEnabled)
if(now > mDelayBetweenDirectoryUpdates + mLastSweepTime)
{ {
if(sweepSharedDirectories())
{ if(now > mDelayBetweenDirectoryUpdates + mLastSweepTime)
mNeedsFullRecheck = false ; {
mLastSweepTime = now; if(sweepSharedDirectories())
mSharedDirectories->notifyTSChanged() ; {
} mNeedsFullRecheck = false;
else mLastSweepTime = now ;
std::cerr << "(WW) sweepSharedDirectories() failed. Will do it again in a short time." << std::endl; mSharedDirectories->notifyTSChanged();
}
else
std::cerr << "(WW) sweepSharedDirectories() failed. Will do it again in a short time." << std::endl;
}
if(now > DELAY_BETWEEN_LOCAL_DIRECTORIES_TS_UPDATE + mLastTSUpdateTime)
{
mSharedDirectories->updateTimeStamps() ;
mLastTSUpdateTime = now ;
}
} }
if(now > DELAY_BETWEEN_LOCAL_DIRECTORIES_TS_UPDATE + mLastTSUpdateTime)
{
mSharedDirectories->updateTimeStamps() ;
mLastTSUpdateTime = now ;
}
usleep(10*1000*1000); usleep(10*1000*1000);
} }

View File

@ -179,7 +179,7 @@ int p3FileDatabase::tick()
#endif #endif
last_print_time = now ; last_print_time = now ;
//#warning this should be removed, but it's necessary atm for updating the GUI #warning mr-alice 2016-08-19: This should be removed, but it's necessary atm for updating the GUI
RsServer::notify()->notifyListChange(NOTIFY_LIST_DIRLIST_LOCAL, 0); RsServer::notify()->notifyListChange(NOTIFY_LIST_DIRLIST_LOCAL, 0);
} }

View File

@ -41,20 +41,31 @@ static const uint32_t MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE = 256 ;
static RsGxsId getRsaKeyFingerprint_old_insecure_method(RSA *pubkey) static RsGxsId getRsaKeyFingerprint_old_insecure_method(RSA *pubkey)
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
int lenn = BN_num_bytes(pubkey -> n); int lenn = BN_num_bytes(pubkey -> n);
RsTemporaryMemory tmp(lenn) ; RsTemporaryMemory tmp(lenn) ;
BN_bn2bin(pubkey -> n, tmp); BN_bn2bin(pubkey -> n, tmp);
#else
const BIGNUM *nn=NULL,*ee=NULL ;
RSA_get0_key(pubkey,&nn,&ee,NULL) ;
int lenn = BN_num_bytes(nn);
RsTemporaryMemory tmp(lenn) ;
BN_bn2bin(nn, tmp);
#endif
// Copy first CERTSIGNLEN bytes from the hash of the public modulus and exponent // Copy first CERTSIGNLEN bytes from the hash of the public modulus and exponent
// We should not be using strings here, but a real ID. To be done later. // We should not be using strings here, but a real ID. To be done later.
assert(lenn >= CERTSIGNLEN) ; assert(lenn >= CERTSIGNLEN) ;
return RsGxsId((unsigned char*)tmp) ; return RsGxsId((unsigned char*)tmp) ;
} }
static RsGxsId getRsaKeyFingerprint(RSA *pubkey) static RsGxsId getRsaKeyFingerprint(RSA *pubkey)
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
int lenn = BN_num_bytes(pubkey -> n); int lenn = BN_num_bytes(pubkey -> n);
int lene = BN_num_bytes(pubkey -> e); int lene = BN_num_bytes(pubkey -> e);
@ -62,6 +73,18 @@ static RsGxsId getRsaKeyFingerprint(RSA *pubkey)
BN_bn2bin(pubkey -> n, tmp); BN_bn2bin(pubkey -> n, tmp);
BN_bn2bin(pubkey -> e, &tmp[lenn]); BN_bn2bin(pubkey -> e, &tmp[lenn]);
#else
const BIGNUM *nn=NULL,*ee=NULL ;
RSA_get0_key(pubkey,&nn,&ee,NULL) ;
int lenn = BN_num_bytes(nn);
int lene = BN_num_bytes(ee);
RsTemporaryMemory tmp(lenn+lene) ;
BN_bn2bin(nn, tmp);
BN_bn2bin(ee, &tmp[lenn]);
#endif
Sha1CheckSum s = RsDirUtil::sha1sum(tmp,lenn+lene) ; Sha1CheckSum s = RsDirUtil::sha1sum(tmp,lenn+lene) ;
@ -530,11 +553,10 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
return false; return false;
} }
EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
int eklen, net_ekl; int eklen, net_ekl;
unsigned char *ek; unsigned char *ek;
unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH];
EVP_CIPHER_CTX_init(&ctx);
int out_currOffset = 0; int out_currOffset = 0;
int out_offset = 0; int out_offset = 0;
@ -551,7 +573,7 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
int max_outlen = inlen + cipher_block_size + EVP_MAX_IV_LENGTH + max_evp_key_size + size_net_ekl; int max_outlen = inlen + cipher_block_size + EVP_MAX_IV_LENGTH + max_evp_key_size + size_net_ekl;
// intialize context and send store encrypted cipher in ek // intialize context and send store encrypted cipher in ek
if(!EVP_SealInit(&ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &public_key, 1)) return false; if(!EVP_SealInit(ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &public_key, 1)) return false;
// now assign memory to out accounting for data, and cipher block size, key length, and key length val // now assign memory to out accounting for data, and cipher block size, key length, and key length val
out = (uint8_t*)rs_malloc(inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH) ; out = (uint8_t*)rs_malloc(inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH) ;
@ -570,7 +592,7 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
out_offset += EVP_MAX_IV_LENGTH; out_offset += EVP_MAX_IV_LENGTH;
// now encrypt actual data // now encrypt actual data
if(!EVP_SealUpdate(&ctx, (unsigned char*) out + out_offset, &out_currOffset, (unsigned char*) in, inlen)) if(!EVP_SealUpdate(ctx, (unsigned char*) out + out_offset, &out_currOffset, (unsigned char*) in, inlen))
{ {
free(out) ; free(out) ;
out = NULL ; out = NULL ;
@ -581,7 +603,7 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
out_offset += out_currOffset; out_offset += out_currOffset;
// add padding // add padding
if(!EVP_SealFinal(&ctx, (unsigned char*) out + out_offset, &out_currOffset)) if(!EVP_SealFinal(ctx, (unsigned char*) out + out_offset, &out_currOffset))
{ {
free(out) ; free(out) ;
out = NULL ; out = NULL ;
@ -602,7 +624,7 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
// free encrypted key data // free encrypted key data
free(ek); free(ek);
EVP_CIPHER_CTX_cleanup(&ctx); EVP_CIPHER_CTX_free(ctx);
outlen = out_offset; outlen = out_offset;
return true; return true;
@ -613,152 +635,151 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
#ifdef DISTRIB_DEBUG #ifdef DISTRIB_DEBUG
std::cerr << "GxsSecurity::encrypt() " << std::endl; std::cerr << "GxsSecurity::encrypt() " << std::endl;
#endif #endif
// Encrypts (in,inlen) into (out,outlen) using the given RSA public key. // Encrypts (in,inlen) into (out,outlen) using the given RSA public key.
// The format of the encrypted data is: // The format of the encrypted data is:
// //
// [--- ID ---|--- number of encrypted keys---| n * (--- Encrypted session keys ---) |--- IV ---|---- Encrypted data ---] // [--- ID ---|--- number of encrypted keys---| n * (--- Encrypted session keys ---) |--- IV ---|---- Encrypted data ---]
// 2 bytes 2 byte = n 256 bytes EVP_MAX_IV_LENGTH Rest of packet // 2 bytes 2 byte = n 256 bytes EVP_MAX_IV_LENGTH Rest of packet
// //
out = NULL ;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
std::vector<EVP_PKEY *> public_keys(keys.size(),NULL);
try
{
for(uint32_t i=0;i<keys.size();++i)
{
RSA *tmpkey = ::extractPublicKey(keys[i]) ;
RSA *rsa_publish_pub = RSAPublicKey_dup(tmpkey) ;
RSA_free(tmpkey) ;
if(rsa_publish_pub != NULL)
{
public_keys[i] = EVP_PKEY_new();
EVP_PKEY_assign_RSA(public_keys[i], rsa_publish_pub);
}
else
{
std::cerr << "GxsSecurity(): Could not generate public key for key id " << keys[i].keyId << std::endl;
throw std::runtime_error("Cannot extract public key") ;
}
}
unsigned char iv[EVP_MAX_IV_LENGTH];
std::vector<unsigned char *> ek(keys.size(),NULL) ;
std::vector<int> eklen(keys.size(),0) ;
for(uint32_t i=0;i<keys.size();++i)
{
int max_evp_key_size = EVP_PKEY_size(public_keys[i]);
if(max_evp_key_size != MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE)
throw std::runtime_error("EVP_PKEY_size should be equal to 256. It's not!") ;
ek[i] = (unsigned char*)rs_malloc(max_evp_key_size);
if(ek[i] == NULL)
throw std::runtime_error("malloc error on encrypted keys") ;
}
const EVP_CIPHER *cipher = EVP_aes_128_cbc();
int cipher_block_size = EVP_CIPHER_block_size(cipher);
// intialize context and send store encrypted cipher in ek
if(!EVP_SealInit(&ctx, EVP_aes_128_cbc(), ek.data(), eklen.data(), iv, public_keys.data(), keys.size()))
return false;
// now we can release the encryption keys
for(uint32_t i=0;i<public_keys.size();++i)
EVP_PKEY_free(public_keys[i]) ;
public_keys.clear() ;
int total_ek_size = MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE * keys.size() ;
int max_outlen = MULTI_ENCRYPTION_FORMAT_v001_HEADER_SIZE + MULTI_ENCRYPTION_FORMAT_v001_NUMBER_OF_KEYS_SIZE + total_ek_size + EVP_MAX_IV_LENGTH + (inlen + cipher_block_size) ;
// now assign memory to out accounting for data, and cipher block size, key length, and key length val
out = (uint8_t*)rs_malloc(max_outlen);
if(out == NULL)
return false ;
int out_offset = 0;
// header
out[out_offset++] = MULTI_ENCRYPTION_FORMAT_v001_HEADER & 0xff ;
out[out_offset++] = (MULTI_ENCRYPTION_FORMAT_v001_HEADER >> 8) & 0xff ;
// number of keys
out[out_offset++] = keys.size() & 0xff ;
out[out_offset++] = (keys.size() >> 8) & 0xff ;
// encrypted keys, each preceeded with its length
for(uint32_t i=0;i<keys.size();++i)
{
if(eklen[i] != MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE)
{
std::cerr << "(EE) eklen[i]=" << eklen[i] << " in " << __PRETTY_FUNCTION__ << " for key id " << keys[i].keyId << ". This is unexpected. Cannot encrypt." << std::endl;
throw std::runtime_error("Encryption error") ;
}
memcpy((unsigned char*)out + out_offset, ek[i],eklen[i]) ;
out_offset += eklen[i] ;
}
memcpy((unsigned char*)out + out_offset, iv, EVP_MAX_IV_LENGTH);
out_offset += EVP_MAX_IV_LENGTH;
int out_currOffset = 0;
// now encrypt actual data
if(!EVP_SealUpdate(&ctx, (unsigned char*) out + out_offset, &out_currOffset, (unsigned char*) in, inlen))
throw std::runtime_error("Encryption error in SealUpdate()") ;
// move along to partial block space
out_offset += out_currOffset;
// add padding
if(!EVP_SealFinal(&ctx, (unsigned char*) out + out_offset, &out_currOffset))
throw std::runtime_error("Encryption error in SealFinal()") ;
// move to end
out_offset += out_currOffset;
// make sure offset has not gone passed valid memory bounds
if(out_offset > max_outlen)
throw std::runtime_error("Memory used by encryption exceeds allocated memory block") ;
// free encrypted key data
for(uint32_t i=0;i<keys.size();++i)
if(ek[i]) free(ek[i]);
outlen = out_offset;
EVP_CIPHER_CTX_cleanup(&ctx);
return true;
}
catch(std::exception& e)
{
std::cerr << "(EE) Exception caught while encrypting: " << e.what() << std::endl;
EVP_CIPHER_CTX_cleanup(&ctx);
if(out) free(out) ;
out = NULL ; out = NULL ;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
std::vector<EVP_PKEY *> public_keys(keys.size(),NULL);
for(uint32_t i=0;i<public_keys.size();++i) try
EVP_PKEY_free(public_keys[i]) ; {
public_keys.clear() ; for(uint32_t i=0;i<keys.size();++i)
{
RSA *tmpkey = ::extractPublicKey(keys[i]) ;
RSA *rsa_publish_pub = RSAPublicKey_dup(tmpkey) ;
RSA_free(tmpkey) ;
return false ; if(rsa_publish_pub != NULL)
} {
public_keys[i] = EVP_PKEY_new();
EVP_PKEY_assign_RSA(public_keys[i], rsa_publish_pub);
}
else
{
std::cerr << "GxsSecurity(): Could not generate public key for key id " << keys[i].keyId << std::endl;
throw std::runtime_error("Cannot extract public key") ;
}
}
unsigned char iv[EVP_MAX_IV_LENGTH];
std::vector<unsigned char *> ek(keys.size(),NULL) ;
std::vector<int> eklen(keys.size(),0) ;
for(uint32_t i=0;i<keys.size();++i)
{
int max_evp_key_size = EVP_PKEY_size(public_keys[i]);
if(max_evp_key_size != MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE)
throw std::runtime_error("EVP_PKEY_size should be equal to 256. It's not!") ;
ek[i] = (unsigned char*)rs_malloc(max_evp_key_size);
if(ek[i] == NULL)
throw std::runtime_error("malloc error on encrypted keys") ;
}
const EVP_CIPHER *cipher = EVP_aes_128_cbc();
int cipher_block_size = EVP_CIPHER_block_size(cipher);
// intialize context and send store encrypted cipher in ek
if(!EVP_SealInit(ctx, EVP_aes_128_cbc(), ek.data(), eklen.data(), iv, public_keys.data(), keys.size()))
return false;
// now we can release the encryption keys
for(uint32_t i=0;i<public_keys.size();++i)
EVP_PKEY_free(public_keys[i]) ;
public_keys.clear() ;
int total_ek_size = MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE * keys.size() ;
int max_outlen = MULTI_ENCRYPTION_FORMAT_v001_HEADER_SIZE + MULTI_ENCRYPTION_FORMAT_v001_NUMBER_OF_KEYS_SIZE + total_ek_size + EVP_MAX_IV_LENGTH + (inlen + cipher_block_size) ;
// now assign memory to out accounting for data, and cipher block size, key length, and key length val
out = (uint8_t*)rs_malloc(max_outlen);
if(out == NULL)
return false ;
int out_offset = 0;
// header
out[out_offset++] = MULTI_ENCRYPTION_FORMAT_v001_HEADER & 0xff ;
out[out_offset++] = (MULTI_ENCRYPTION_FORMAT_v001_HEADER >> 8) & 0xff ;
// number of keys
out[out_offset++] = keys.size() & 0xff ;
out[out_offset++] = (keys.size() >> 8) & 0xff ;
// encrypted keys, each preceeded with its length
for(uint32_t i=0;i<keys.size();++i)
{
if(eklen[i] != MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE)
{
std::cerr << "(EE) eklen[i]=" << eklen[i] << " in " << __PRETTY_FUNCTION__ << " for key id " << keys[i].keyId << ". This is unexpected. Cannot encrypt." << std::endl;
throw std::runtime_error("Encryption error") ;
}
memcpy((unsigned char*)out + out_offset, ek[i],eklen[i]) ;
out_offset += eklen[i] ;
}
memcpy((unsigned char*)out + out_offset, iv, EVP_MAX_IV_LENGTH);
out_offset += EVP_MAX_IV_LENGTH;
int out_currOffset = 0;
// now encrypt actual data
if(!EVP_SealUpdate(ctx, (unsigned char*) out + out_offset, &out_currOffset, (unsigned char*) in, inlen))
throw std::runtime_error("Encryption error in SealUpdate()") ;
// move along to partial block space
out_offset += out_currOffset;
// add padding
if(!EVP_SealFinal(ctx, (unsigned char*) out + out_offset, &out_currOffset))
throw std::runtime_error("Encryption error in SealFinal()") ;
// move to end
out_offset += out_currOffset;
// make sure offset has not gone passed valid memory bounds
if(out_offset > max_outlen)
throw std::runtime_error("Memory used by encryption exceeds allocated memory block") ;
// free encrypted key data
for(uint32_t i=0;i<keys.size();++i)
if(ek[i]) free(ek[i]);
outlen = out_offset;
EVP_CIPHER_CTX_free(ctx);
return true;
}
catch(std::exception& e)
{
std::cerr << "(EE) Exception caught while encrypting: " << e.what() << std::endl;
EVP_CIPHER_CTX_free(ctx);
if(out) free(out) ;
out = NULL ;
for(uint32_t i=0;i<public_keys.size();++i)
EVP_PKEY_free(public_keys[i]) ;
public_keys.clear() ;
return false ;
}
} }
bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in, uint32_t inlen, const RsTlvPrivateRSAKey &key) bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in, uint32_t inlen, const RsTlvPrivateRSAKey &key)
@ -794,7 +815,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
} }
EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
int eklen = 0, net_ekl = 0; int eklen = 0, net_ekl = 0;
unsigned char *ek = (unsigned char*)rs_malloc(EVP_PKEY_size(privateKey)); unsigned char *ek = (unsigned char*)rs_malloc(EVP_PKEY_size(privateKey));
@ -802,7 +823,6 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
return false ; return false ;
unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH];
EVP_CIPHER_CTX_init(&ctx);
int in_offset = 0, out_currOffset = 0; int in_offset = 0, out_currOffset = 0;
int size_net_ekl = sizeof(net_ekl); int size_net_ekl = sizeof(net_ekl);
@ -827,7 +847,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
const EVP_CIPHER* cipher = EVP_aes_128_cbc(); const EVP_CIPHER* cipher = EVP_aes_128_cbc();
if(!EVP_OpenInit(&ctx, cipher, ek, eklen, iv, privateKey)) if(!EVP_OpenInit(ctx, cipher, ek, eklen, iv, privateKey))
{ {
std::cerr << "(EE) Cannot decrypt data. Most likely reason: private GXS key is missing." << std::endl; std::cerr << "(EE) Cannot decrypt data. Most likely reason: private GXS key is missing." << std::endl;
return false; return false;
@ -843,7 +863,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
if(out == NULL) if(out == NULL)
return false; return false;
if(!EVP_OpenUpdate(&ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + in_offset, inlen - in_offset)) if(!EVP_OpenUpdate(ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + in_offset, inlen - in_offset))
{ {
free(out) ; free(out) ;
out = NULL ; out = NULL ;
@ -852,7 +872,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
outlen = out_currOffset; outlen = out_currOffset;
if(!EVP_OpenFinal(&ctx, (unsigned char*)out + out_currOffset, &out_currOffset)) if(!EVP_OpenFinal(ctx, (unsigned char*)out + out_currOffset, &out_currOffset))
{ {
free(out) ; free(out) ;
out = NULL ; out = NULL ;
@ -862,7 +882,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
outlen += out_currOffset; outlen += out_currOffset;
free(ek); free(ek);
EVP_CIPHER_CTX_cleanup(&ctx); EVP_CIPHER_CTX_free(ctx);
return true; return true;
} }
@ -879,8 +899,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
#ifdef DISTRIB_DEBUG #ifdef DISTRIB_DEBUG
std::cerr << "GxsSecurity::decrypt() " << std::endl; std::cerr << "GxsSecurity::decrypt() " << std::endl;
#endif #endif
EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(&ctx);
try try
{ {
@ -951,10 +970,10 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
for(uint32_t i=0;i<number_of_keys && !succeed;++i) for(uint32_t i=0;i<number_of_keys && !succeed;++i)
{ {
succeed = EVP_OpenInit(&ctx, EVP_aes_128_cbc(),in + encrypted_keys_offset + i*MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE , MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE, in+IV_offset, privateKey); succeed = EVP_OpenInit(ctx, EVP_aes_128_cbc(),in + encrypted_keys_offset + i*MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE , MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE, in+IV_offset, privateKey);
if(!succeed) if(!succeed)
EVP_CIPHER_CTX_cleanup(&ctx); EVP_CIPHER_CTX_cleanup(ctx);
#ifdef GXS_SECURITY_DEBUG #ifdef GXS_SECURITY_DEBUG
std::cerr << " encrypted key at offset " << encrypted_keys_offset + i*MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE << ": " << succeed << std::endl; std::cerr << " encrypted key at offset " << encrypted_keys_offset + i*MULTI_ENCRYPTION_FORMAT_v001_ENCRYPTED_KEY_SIZE << ": " << succeed << std::endl;
@ -978,12 +997,12 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
int out_currOffset = 0 ; int out_currOffset = 0 ;
if(!EVP_OpenUpdate(&ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + encrypted_block_offset, encrypted_block_size)) if(!EVP_OpenUpdate(ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + encrypted_block_offset, encrypted_block_size))
throw std::runtime_error("Decryption error in EVP_OpenUpdate") ; throw std::runtime_error("Decryption error in EVP_OpenUpdate") ;
outlen = out_currOffset; outlen = out_currOffset;
if(!EVP_OpenFinal(&ctx, (unsigned char*)out + out_currOffset, &out_currOffset)) if(!EVP_OpenFinal(ctx, (unsigned char*)out + out_currOffset, &out_currOffset))
throw std::runtime_error("Decryption error in EVP_OpenFinal") ; throw std::runtime_error("Decryption error in EVP_OpenFinal") ;
outlen += out_currOffset; outlen += out_currOffset;
@ -991,7 +1010,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
#ifdef GXS_SECURITY_DEBUG #ifdef GXS_SECURITY_DEBUG
std::cerr << " successfully decrypted block of size " << outlen << std::endl; std::cerr << " successfully decrypted block of size " << outlen << std::endl;
#endif #endif
EVP_CIPHER_CTX_cleanup(&ctx); EVP_CIPHER_CTX_free(ctx);
return true; return true;
} }
catch(std::exception& e) catch(std::exception& e)
@ -1007,7 +1026,7 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
out = NULL ; out = NULL ;
} }
EVP_CIPHER_CTX_cleanup(&ctx); EVP_CIPHER_CTX_free(ctx);
return false; return false;
} }
} }

View File

@ -1055,7 +1055,13 @@ bool p3GxsTunnelService::locked_sendDHPublicKey(const DH *dh,const RsGxsId& own_
} }
RsGxsTunnelDHPublicKeyItem *dhitem = new RsGxsTunnelDHPublicKeyItem ; RsGxsTunnelDHPublicKeyItem *dhitem = new RsGxsTunnelDHPublicKeyItem ;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
dhitem->public_key = BN_dup(dh->pub_key) ; dhitem->public_key = BN_dup(dh->pub_key) ;
#else
const BIGNUM *pub_key=NULL ;
DH_get0_key(dh,&pub_key,NULL) ;
dhitem->public_key = BN_dup(pub_key) ;
#endif
// we should also sign the data and check the signature on the other end. // we should also sign the data and check the signature on the other end.
// //
@ -1133,8 +1139,18 @@ bool p3GxsTunnelService::locked_initDHSessionKey(DH *& dh)
return false ; return false ;
} }
#if OPENSSL_VERSION_NUMBER < 0x10100000L
BN_hex2bn(&dh->p,dh_prime_2048_hex.c_str()) ; BN_hex2bn(&dh->p,dh_prime_2048_hex.c_str()) ;
BN_hex2bn(&dh->g,"5") ; BN_hex2bn(&dh->g,"5") ;
#else
BIGNUM *pp=NULL ;
BIGNUM *gg=NULL ;
BN_hex2bn(&pp,dh_prime_2048_hex.c_str()) ;
BN_hex2bn(&gg,"5") ;
DH_set0_pqg(dh,pp,NULL,gg) ;
#endif
int codes = 0 ; int codes = 0 ;

View File

@ -431,12 +431,25 @@ unsigned short RsCertificate::loc_port_us() const
return (int)ipv4_internal_ip_and_port[4]*256 + (int)ipv4_internal_ip_and_port[5] ; return (int)ipv4_internal_ip_and_port[4]*256 + (int)ipv4_internal_ip_and_port[5] ;
} }
bool RsCertificate::cleanCertificate(const std::string& input,std::string& output,Format& format,int& error_code) bool RsCertificate::cleanCertificate(const std::string& input,std::string& output,Format& format,int& error_code,bool check_content)
{ {
if(cleanCertificate(input,output,error_code)) if(cleanCertificate(input,output,error_code))
{ {
format = RS_CERTIFICATE_RADIX ; format = RS_CERTIFICATE_RADIX ;
return true ;
if(!check_content)
return true ;
try
{
RsCertificate c(input) ;
return true ;
}
catch(uint32_t err_code)
{
error_code = err_code ;
return false;
}
} }
return false ; return false ;

View File

@ -41,7 +41,7 @@ class RsCertificate
const unsigned char *pgp_key() const { return binary_pgp_key ; } const unsigned char *pgp_key() const { return binary_pgp_key ; }
size_t pgp_key_size() const { return binary_pgp_key_size ; } size_t pgp_key_size() const { return binary_pgp_key_size ; }
static bool cleanCertificate(const std::string& input,std::string& output,RsCertificate::Format& format,int& error_code) ; static bool cleanCertificate(const std::string& input, std::string& output, RsCertificate::Format& format, int& error_code, bool check_content) ;
private: private:
static bool cleanCertificate(const std::string& input,std::string& output,int&) ; // new radix format static bool cleanCertificate(const std::string& input,std::string& output,int&) ; // new radix format

View File

@ -245,12 +245,18 @@ sslcert::sslcert(X509 *x509, const RsPeerId& pid)
{ {
certificate = x509; certificate = x509;
id = pid; id = pid;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
name = getX509CNString(x509->cert_info->subject); name = getX509CNString(x509->cert_info->subject);
org = getX509OrgString(x509->cert_info->subject); org = getX509OrgString(x509->cert_info->subject);
location = getX509LocString(x509->cert_info->subject); location = getX509LocString(x509->cert_info->subject);
email = "";
issuer = RsPgpId(std::string(getX509CNString(x509->cert_info->issuer))); issuer = RsPgpId(std::string(getX509CNString(x509->cert_info->issuer)));
#else
name = getX509CNString(X509_get_subject_name(x509));
org = getX509OrgString(X509_get_subject_name(x509));
location = getX509LocString(X509_get_subject_name(x509));
issuer = RsPgpId(std::string(getX509CNString(X509_get_issuer_name(x509))));
#endif
email = "";
authed = false; authed = false;
} }
@ -371,8 +377,17 @@ static int initLib = 0;
if (dh) if (dh)
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
BN_hex2bn(&dh->p,dh_prime_4096_hex.c_str()) ; BN_hex2bn(&dh->p,dh_prime_4096_hex.c_str()) ;
BN_hex2bn(&dh->g,"5") ; BN_hex2bn(&dh->g,"5") ;
#else
BIGNUM *pp=NULL,*gg=NULL ;
BN_hex2bn(&pp,dh_prime_4096_hex.c_str()) ;
BN_hex2bn(&gg,"5");
DH_set0_pqg(dh,pp,NULL,gg) ;
#endif
std::cout.flush() ; std::cout.flush() ;
@ -776,47 +791,72 @@ X509 *AuthSSLimpl::SignX509ReqWithGPG(X509_REQ *req, long /*days*/)
std::cerr << "X509 Cert, prepared for signing" << std::endl; std::cerr << "X509 Cert, prepared for signing" << std::endl;
/*** NOW The Manual signing bit (HACKED FROM asn1/a_sign.c) ***/ /*** NOW The Manual signing bit (HACKED FROM asn1/a_sign.c) ***/
//
// The code has been copied in order to use the PGP signing instead of supplying the
// private EVP_KEY to ASN1_sign(), which would be another alternative.
#if OPENSSL_VERSION_NUMBER < 0x10100000L
int (*i2d)(X509_CINF*, unsigned char**) = i2d_X509_CINF; int (*i2d)(X509_CINF*, unsigned char**) = i2d_X509_CINF;
X509_ALGOR *algor1 = x509->cert_info->signature; X509_ALGOR *algor1 = x509->cert_info->signature;
X509_ALGOR *algor2 = x509->sig_alg; X509_ALGOR *algor2 = x509->sig_alg;
ASN1_BIT_STRING *signature = x509->signature; ASN1_BIT_STRING *signature = x509->signature;
X509_CINF *data = x509->cert_info; X509_CINF *data = x509->cert_info;
#else
const X509_ALGOR *algor1 = X509_get0_tbs_sigalg(x509) ;
const X509_ALGOR *algor2 = NULL ;
const ASN1_BIT_STRING *tmp_signature = NULL ;
X509_get0_signature(&tmp_signature,&algor2,x509);
ASN1_BIT_STRING *signature = const_cast<ASN1_BIT_STRING*>(tmp_signature);
#endif
//EVP_PKEY *pkey = NULL; //EVP_PKEY *pkey = NULL;
const EVP_MD *type = EVP_sha1(); const EVP_MD *type = EVP_sha1();
EVP_MD_CTX ctx; EVP_MD_CTX *ctx = EVP_MD_CTX_create();
unsigned char *p,*buf_in=NULL; unsigned char *p,*buf_in=NULL;
unsigned char *buf_hashout=NULL,*buf_sigout=NULL; unsigned char *buf_hashout=NULL,*buf_sigout=NULL;
int inl=0,hashoutl=0; int inl=0,hashoutl=0;
int sigoutl=0; int sigoutl=0;
X509_ALGOR *a; X509_ALGOR *a;
EVP_MD_CTX_init(&ctx);
/* FIX ALGORITHMS */ /* FIX ALGORITHMS */
a = algor1; a = const_cast<X509_ALGOR*>(algor1);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ASN1_TYPE_free(a->parameter); ASN1_TYPE_free(a->parameter);
a->parameter=ASN1_TYPE_new(); a->parameter=ASN1_TYPE_new();
a->parameter->type=V_ASN1_NULL; a->parameter->type=V_ASN1_NULL;
ASN1_OBJECT_free(a->algorithm); ASN1_OBJECT_free(a->algorithm);
a->algorithm=OBJ_nid2obj(type->pkey_type); a->algorithm=OBJ_nid2obj(type->pkey_type);
#else
X509_ALGOR_set0(a,OBJ_nid2obj(EVP_MD_pkey_type(type)),V_ASN1_NULL,NULL);
#endif
a = algor2; a = const_cast<X509_ALGOR*>(algor2);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ASN1_TYPE_free(a->parameter); ASN1_TYPE_free(a->parameter);
a->parameter=ASN1_TYPE_new(); a->parameter=ASN1_TYPE_new();
a->parameter->type=V_ASN1_NULL; a->parameter->type=V_ASN1_NULL;
ASN1_OBJECT_free(a->algorithm); ASN1_OBJECT_free(a->algorithm);
a->algorithm=OBJ_nid2obj(type->pkey_type); a->algorithm=OBJ_nid2obj(type->pkey_type);
#else
X509_ALGOR_set0(a,OBJ_nid2obj(EVP_MD_pkey_type(type)),V_ASN1_NULL,NULL);
#endif
std::cerr << "Algorithms Fixed" << std::endl; std::cerr << "Algorithms Fixed" << std::endl;
/* input buffer */ /* input buffer */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
inl=i2d(data,NULL); inl=i2d(data,NULL);
buf_in=(unsigned char *)OPENSSL_malloc((unsigned int)inl); buf_in=(unsigned char *)OPENSSL_malloc((unsigned int)inl);
#else
inl=i2d_re_X509_tbs(x509,&buf_in) ; // this does the i2d over x509->cert_info
#endif
hashoutl=EVP_MD_size(type); hashoutl=EVP_MD_size(type);
buf_hashout=(unsigned char *)OPENSSL_malloc((unsigned int)hashoutl); buf_hashout=(unsigned char *)OPENSSL_malloc((unsigned int)hashoutl);
@ -831,15 +871,17 @@ X509 *AuthSSLimpl::SignX509ReqWithGPG(X509_REQ *req, long /*days*/)
fprintf(stderr, "AuthSSLimpl::SignX509Req: ASN1err(ASN1_F_ASN1_SIGN,ERR_R_MALLOC_FAILURE)\n"); fprintf(stderr, "AuthSSLimpl::SignX509Req: ASN1err(ASN1_F_ASN1_SIGN,ERR_R_MALLOC_FAILURE)\n");
goto err; goto err;
} }
p=buf_in;
std::cerr << "Buffers Allocated" << std::endl; std::cerr << "Buffers Allocated" << std::endl;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
p=buf_in;
i2d(data,&p); i2d(data,&p);
#endif
/* data in buf_in, ready to be hashed */ /* data in buf_in, ready to be hashed */
EVP_DigestInit_ex(&ctx,type, NULL); EVP_DigestInit_ex(ctx,type, NULL);
EVP_DigestUpdate(&ctx,(unsigned char *)buf_in,inl); EVP_DigestUpdate(ctx,(unsigned char *)buf_in,inl);
if (!EVP_DigestFinal(&ctx,(unsigned char *)buf_hashout, if (!EVP_DigestFinal(ctx,(unsigned char *)buf_hashout,
(unsigned int *)&hashoutl)) (unsigned int *)&hashoutl))
{ {
hashoutl=0; hashoutl=0;
@ -879,6 +921,8 @@ X509 *AuthSSLimpl::SignX509ReqWithGPG(X509_REQ *req, long /*days*/)
std::cerr << "Certificate Complete" << std::endl; std::cerr << "Certificate Complete" << std::endl;
EVP_MD_CTX_destroy(ctx) ;
return x509; return x509;
/* XXX CLEANUP */ /* XXX CLEANUP */
@ -915,7 +959,11 @@ bool AuthSSLimpl::AuthX509WithGPG(X509 *x509,uint32_t& diagnostic)
} }
/* extract CN for peer Id */ /* extract CN for peer Id */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
RsPgpId issuer(std::string(getX509CNString(x509->cert_info->issuer))); RsPgpId issuer(std::string(getX509CNString(x509->cert_info->issuer)));
#else
RsPgpId issuer(std::string(getX509CNString(X509_get_issuer_name(x509))));
#endif
RsPeerDetails pd; RsPeerDetails pd;
#ifdef AUTHSSL_DEBUG #ifdef AUTHSSL_DEBUG
std::cerr << "Checking GPG issuer : " << issuer.toStdString() << std::endl ; std::cerr << "Checking GPG issuer : " << issuer.toStdString() << std::endl ;
@ -930,22 +978,33 @@ bool AuthSSLimpl::AuthX509WithGPG(X509 *x509,uint32_t& diagnostic)
/*** NOW The Manual signing bit (HACKED FROM asn1/a_sign.c) ***/ /*** NOW The Manual signing bit (HACKED FROM asn1/a_sign.c) ***/
int (*i2d)(X509_CINF*, unsigned char**) = i2d_X509_CINF; int (*i2d)(X509_CINF*, unsigned char**) = i2d_X509_CINF;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ASN1_BIT_STRING *signature = x509->signature; ASN1_BIT_STRING *signature = x509->signature;
X509_CINF *data = x509->cert_info; X509_CINF *data = x509->cert_info;
#else
const ASN1_BIT_STRING *signature = NULL ;
const X509_ALGOR *algor2=NULL;
X509_get0_signature(&signature,&algor2,x509);
#endif
const EVP_MD *type = EVP_sha1(); const EVP_MD *type = EVP_sha1();
EVP_MD_CTX ctx; EVP_MD_CTX *ctx = EVP_MD_CTX_create();
unsigned char *p,*buf_in=NULL; unsigned char *p,*buf_in=NULL;
unsigned char *buf_hashout=NULL,*buf_sigout=NULL; unsigned char *buf_hashout=NULL,*buf_sigout=NULL;
int inl=0,hashoutl=0; int inl=0,hashoutl=0;
int sigoutl=0; int sigoutl=0;
//X509_ALGOR *a;
EVP_MD_CTX_init(&ctx);
/* input buffer */ /* input buffer */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
inl=i2d(data,NULL); inl=i2d(data,NULL);
buf_in=(unsigned char *)OPENSSL_malloc((unsigned int)inl); buf_in=(unsigned char *)OPENSSL_malloc((unsigned int)inl);
#else
inl=i2d_re_X509_tbs(x509,&buf_in) ; // this does the i2d over x509->cert_info
#endif
hashoutl=EVP_MD_size(type); hashoutl=EVP_MD_size(type);
buf_hashout=(unsigned char *)OPENSSL_malloc((unsigned int)hashoutl); buf_hashout=(unsigned char *)OPENSSL_malloc((unsigned int)hashoutl);
@ -973,11 +1032,13 @@ bool AuthSSLimpl::AuthX509WithGPG(X509 *x509,uint32_t& diagnostic)
std::cerr << "Buffers Allocated" << std::endl; std::cerr << "Buffers Allocated" << std::endl;
#endif #endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
i2d(data,&p); i2d(data,&p);
#endif
/* data in buf_in, ready to be hashed */ /* data in buf_in, ready to be hashed */
EVP_DigestInit_ex(&ctx,type, NULL); EVP_DigestInit_ex(ctx,type, NULL);
EVP_DigestUpdate(&ctx,(unsigned char *)buf_in,inl); EVP_DigestUpdate(ctx,(unsigned char *)buf_in,inl);
if (!EVP_DigestFinal(&ctx,(unsigned char *)buf_hashout, if (!EVP_DigestFinal(ctx,(unsigned char *)buf_hashout,
(unsigned int *)&hashoutl)) (unsigned int *)&hashoutl))
{ {
hashoutl=0; hashoutl=0;
@ -1017,6 +1078,7 @@ bool AuthSSLimpl::AuthX509WithGPG(X509 *x509,uint32_t& diagnostic)
#ifdef AUTHSSL_DEBUG #ifdef AUTHSSL_DEBUG
std::cerr << "AuthSSLimpl::AuthX509() X509 authenticated" << std::endl; std::cerr << "AuthSSLimpl::AuthX509() X509 authenticated" << std::endl;
#endif #endif
EVP_MD_CTX_destroy(ctx) ;
OPENSSL_free(buf_in) ; OPENSSL_free(buf_in) ;
OPENSSL_free(buf_hashout) ; OPENSSL_free(buf_hashout) ;
@ -1093,21 +1155,34 @@ static int verify_x509_callback(int preverify_ok, X509_STORE_CTX *ctx)
if(x509 != NULL) if(x509 != NULL)
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
RsPgpId gpgid (std::string(getX509CNString(x509->cert_info->issuer))); RsPgpId gpgid (std::string(getX509CNString(x509->cert_info->issuer)));
#else
RsPgpId gpgid (std::string(getX509CNString(X509_get_issuer_name(x509))));
#endif
if(gpgid.isNull()) if(gpgid.isNull())
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
std::cerr << "verify_x509_callback(): wrong PGP id \"" << std::string(getX509CNString(x509->cert_info->issuer)) << "\"" << std::endl; std::cerr << "verify_x509_callback(): wrong PGP id \"" << std::string(getX509CNString(x509->cert_info->issuer)) << "\"" << std::endl;
#else
std::cerr << "verify_x509_callback(): wrong PGP id \"" << std::string(getX509CNString(X509_get_issuer_name(x509))) << "\"" << std::endl;
#endif
return false ; return false ;
} }
#if OPENSSL_VERSION_NUMBER < 0x10100000L
std::string sslcn = getX509CNString(x509->cert_info->subject); std::string sslcn = getX509CNString(x509->cert_info->subject);
#else
std::string sslcn = getX509CNString(X509_get_subject_name(x509));
#endif
RsPeerId sslid ; RsPeerId sslid ;
getX509id(x509,sslid); getX509id(x509,sslid);
if(sslid.isNull()) if(sslid.isNull())
{ {
std::cerr << "verify_x509_callback(): wrong SSL id \"" << std::string(getX509CNString(x509->cert_info->subject)) << "\"" << std::endl; std::cerr << "verify_x509_callback(): wrong PGP id \"" << sslcn << "\"" << std::endl;
return false ; return false ;
} }
@ -1185,7 +1260,11 @@ int AuthSSLimpl::VerifyX509Callback(int preverify_ok, X509_STORE_CTX *ctx)
std::cerr << "(WW) Certificate was rejected because authentication failed. Diagnostic = " << auth_diagnostic << std::endl; std::cerr << "(WW) Certificate was rejected because authentication failed. Diagnostic = " << auth_diagnostic << std::endl;
return false; return false;
} }
RsPgpId pgpid = RsPgpId(std::string(getX509CNString(X509_STORE_CTX_get_current_cert(ctx)->cert_info->issuer))); #if OPENSSL_VERSION_NUMBER < 0x10100000L
RsPgpId pgpid(std::string(getX509CNString(X509_STORE_CTX_get_current_cert(ctx)->cert_info->issuer)));
#else
RsPgpId pgpid(std::string(getX509CNString(X509_get_issuer_name(X509_STORE_CTX_get_current_cert(ctx)))));
#endif
if (pgpid != AuthGPG::getAuthGPG()->getGPGOwnId() && !AuthGPG::getAuthGPG()->isGPGAccepted(pgpid)) if (pgpid != AuthGPG::getAuthGPG()->getGPGOwnId() && !AuthGPG::getAuthGPG()->isGPGAccepted(pgpid))
{ {
@ -1258,15 +1337,18 @@ bool AuthSSLimpl::encrypt(void *&out, int &outlen, const void *in, int inlen,
#endif #endif
return false; return false;
} else { } else {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
public_key = mCerts[peerId]->certificate->cert_info->key->pkey; public_key = mCerts[peerId]->certificate->cert_info->key->pkey;
#else
public_key = X509_get0_pubkey(mCerts[peerId]->certificate) ;
#endif
} }
} }
EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
int eklen, net_ekl; int eklen, net_ekl;
unsigned char *ek; unsigned char *ek;
unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH];
EVP_CIPHER_CTX_init(&ctx);
int out_currOffset = 0; int out_currOffset = 0;
int out_offset = 0; int out_offset = 0;
@ -1283,7 +1365,7 @@ bool AuthSSLimpl::encrypt(void *&out, int &outlen, const void *in, int inlen,
int max_outlen = inlen + cipher_block_size + EVP_MAX_IV_LENGTH + max_evp_key_size + size_net_ekl; int max_outlen = inlen + cipher_block_size + EVP_MAX_IV_LENGTH + max_evp_key_size + size_net_ekl;
// intialize context and send store encrypted cipher in ek // intialize context and send store encrypted cipher in ek
if(!EVP_SealInit(&ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &public_key, 1)) { if(!EVP_SealInit(ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &public_key, 1)) {
free(ek); free(ek);
return false; return false;
} }
@ -1307,7 +1389,7 @@ bool AuthSSLimpl::encrypt(void *&out, int &outlen, const void *in, int inlen,
out_offset += EVP_MAX_IV_LENGTH; out_offset += EVP_MAX_IV_LENGTH;
// now encrypt actual data // now encrypt actual data
if(!EVP_SealUpdate(&ctx, (unsigned char*) out + out_offset, &out_currOffset, (unsigned char*) in, inlen)) { if(!EVP_SealUpdate(ctx, (unsigned char*) out + out_offset, &out_currOffset, (unsigned char*) in, inlen)) {
free(ek); free(ek);
free(out); free(out);
out = NULL; out = NULL;
@ -1318,7 +1400,7 @@ bool AuthSSLimpl::encrypt(void *&out, int &outlen, const void *in, int inlen,
out_offset += out_currOffset; out_offset += out_currOffset;
// add padding // add padding
if(!EVP_SealFinal(&ctx, (unsigned char*) out + out_offset, &out_currOffset)) { if(!EVP_SealFinal(ctx, (unsigned char*) out + out_offset, &out_currOffset)) {
free(ek); free(ek);
free(out) ; free(out) ;
out = NULL; out = NULL;
@ -1334,7 +1416,7 @@ bool AuthSSLimpl::encrypt(void *&out, int &outlen, const void *in, int inlen,
// free encrypted key data // free encrypted key data
free(ek); free(ek);
EVP_CIPHER_CTX_cleanup(&ctx); EVP_CIPHER_CTX_free(ctx);
outlen = out_offset; outlen = out_offset;
@ -1358,7 +1440,7 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
// out = malloc(inlen); // out = malloc(inlen);
// memcpy(out, in, inlen); // memcpy(out, in, inlen);
// outlen = inlen; // outlen = inlen;
EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
int eklen = 0, net_ekl = 0; int eklen = 0, net_ekl = 0;
unsigned char *ek = NULL; unsigned char *ek = NULL;
unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH];
@ -1370,7 +1452,6 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
std::cerr << "(EE) Cannot allocate memory for " << ek_mkl << " bytes in " << __PRETTY_FUNCTION__ << std::endl; std::cerr << "(EE) Cannot allocate memory for " << ek_mkl << " bytes in " << __PRETTY_FUNCTION__ << std::endl;
return false ; return false ;
} }
EVP_CIPHER_CTX_init(&ctx);
int in_offset = 0, out_currOffset = 0; int in_offset = 0, out_currOffset = 0;
int size_net_ekl = sizeof(net_ekl); int size_net_ekl = sizeof(net_ekl);
@ -1402,7 +1483,7 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
const EVP_CIPHER* cipher = EVP_aes_128_cbc(); const EVP_CIPHER* cipher = EVP_aes_128_cbc();
if(0 == EVP_OpenInit(&ctx, cipher, ek, eklen, iv, mOwnPrivateKey)) { if(0 == EVP_OpenInit(ctx, cipher, ek, eklen, iv, mOwnPrivateKey)) {
free(ek); free(ek);
return false; return false;
} }
@ -1414,7 +1495,7 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
free(ek) ; free(ek) ;
return false ; return false ;
} }
if(!EVP_OpenUpdate(&ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + in_offset, inlen - in_offset)) { if(!EVP_OpenUpdate(ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + in_offset, inlen - in_offset)) {
free(ek); free(ek);
free(out) ; free(out) ;
out = NULL; out = NULL;
@ -1424,7 +1505,7 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
in_offset += out_currOffset; in_offset += out_currOffset;
outlen += out_currOffset; outlen += out_currOffset;
if(!EVP_OpenFinal(&ctx, (unsigned char*)out + out_currOffset, &out_currOffset)) { if(!EVP_OpenFinal(ctx, (unsigned char*)out + out_currOffset, &out_currOffset)) {
free(ek); free(ek);
free(out) ; free(out) ;
out = NULL; out = NULL;
@ -1436,7 +1517,7 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
if(ek != NULL) if(ek != NULL)
free(ek); free(ek);
EVP_CIPHER_CTX_cleanup(&ctx); EVP_CIPHER_CTX_free(ctx);
#ifdef AUTHSSL_DEBUG #ifdef AUTHSSL_DEBUG
std::cerr << "AuthSSLimpl::decrypt() finished with outlen : " << outlen << std::endl; std::cerr << "AuthSSLimpl::decrypt() finished with outlen : " << outlen << std::endl;

View File

@ -245,8 +245,37 @@ void p3Notify::notifyDownloadComplete (const std::string& fileHash )
void p3Notify::notifyDownloadCompleteCount (uint32_t count ) { FOR_ALL_NOTIFY_CLIENTS (*it)->notifyDownloadCompleteCount (count) ; } void p3Notify::notifyDownloadCompleteCount (uint32_t count ) { FOR_ALL_NOTIFY_CLIENTS (*it)->notifyDownloadCompleteCount (count) ; }
void p3Notify::notifyHistoryChanged (uint32_t msgId , int type) { FOR_ALL_NOTIFY_CLIENTS (*it)->notifyHistoryChanged (msgId,type) ; } void p3Notify::notifyHistoryChanged (uint32_t msgId , int type) { FOR_ALL_NOTIFY_CLIENTS (*it)->notifyHistoryChanged (msgId,type) ; }
bool p3Notify::cachePgpPassphrase(const std::string& s)
{
clearPgpPassphrase() ;
cached_pgp_passphrase = s ;
std::cerr << "(WW) Caching PGP passphrase." << std::endl;
return true ;
}
bool p3Notify::clearPgpPassphrase()
{
std::cerr << "(WW) Clearing PGP passphrase." << std::endl;
// Just whipe out the memory instead of just releasing it.
for(uint32_t i=0;i<cached_pgp_passphrase.length();++i)
cached_pgp_passphrase[i] = 0 ;
cached_pgp_passphrase.clear();
return true ;
}
bool p3Notify::askForPassword (const std::string& title , const std::string& key_details , bool prev_is_bad , std::string& password,bool *cancelled) bool p3Notify::askForPassword (const std::string& title , const std::string& key_details , bool prev_is_bad , std::string& password,bool *cancelled)
{ {
if(!prev_is_bad && !cached_pgp_passphrase.empty())
{
password = cached_pgp_passphrase ;
if(cancelled)
*cancelled = false ;
return true ;
}
FOR_ALL_NOTIFY_CLIENTS FOR_ALL_NOTIFY_CLIENTS
if( (*it)->askForPassword(title,key_details,prev_is_bad,password,*cancelled)) if( (*it)->askForPassword(title,key_details,prev_is_bad,password,*cancelled))
return true ; return true ;

View File

@ -124,6 +124,9 @@ class p3Notify: public RsNotify
bool askForPassword (const std::string& title, const std::string& /* key_details */, bool /* prev_is_bad */, std::string&, bool *cancelled /* password */ ) ; bool askForPassword (const std::string& title, const std::string& /* key_details */, bool /* prev_is_bad */, std::string&, bool *cancelled /* password */ ) ;
bool askForPluginConfirmation (const std::string& /* plugin_filename */, const std::string& /* plugin_file_hash */) ; bool askForPluginConfirmation (const std::string& /* plugin_filename */, const std::string& /* plugin_file_hash */) ;
virtual bool cachePgpPassphrase (const std::string& /* pgp_passphrase */) ;
virtual bool clearPgpPassphrase () ;
private: private:
RsMutex noteMtx; RsMutex noteMtx;
@ -134,6 +137,8 @@ class p3Notify: public RsNotify
std::list<RsFeedItem> pendingNewsFeed; std::list<RsFeedItem> pendingNewsFeed;
std::list<NotifyClient*> notifyClients ; std::list<NotifyClient*> notifyClients ;
std::string cached_pgp_passphrase ;
}; };

View File

@ -361,7 +361,11 @@ void pqissl::getCryptoParams(RsPeerCryptoParams& params)
bool pqissl::actAsServer() bool pqissl::actAsServer()
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
return (bool)ssl_connection->server; return (bool)ssl_connection->server;
#else
return (bool)SSL_is_server(ssl_connection);
#endif
} }
/* returns ... /* returns ...
@ -1226,8 +1230,13 @@ int pqissl::Extract_Failed_SSL_Certificate()
RsPeerId sslid ; RsPeerId sslid ;
getX509id(peercert, sslid) ; getX509id(peercert, sslid) ;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
RsPgpId gpgid(getX509CNString(peercert->cert_info->issuer)); RsPgpId gpgid(getX509CNString(peercert->cert_info->issuer));
std::string sslcn = getX509CNString(peercert->cert_info->subject); std::string sslcn = getX509CNString(peercert->cert_info->subject);
#else
RsPgpId gpgid(getX509CNString(X509_get_issuer_name(peercert)));
std::string sslcn = getX509CNString(X509_get_subject_name(peercert));
#endif
AuthSSL::getAuthSSL()->FailedCertificate(peercert, gpgid,sslid,sslcn,remote_addr, false); AuthSSL::getAuthSSL()->FailedCertificate(peercert, gpgid,sslid,sslcn,remote_addr, false);
mLinkMgr->notifyDeniedConnection(gpgid, sslid, sslcn, remote_addr, false); mLinkMgr->notifyDeniedConnection(gpgid, sslid, sslcn, remote_addr, false);

View File

@ -214,7 +214,6 @@ int pqissllistenbase::setuplisten()
if (!mPeerMgr->isHidden()) std::cerr << "Zeroed tmpaddr: " << sockaddr_storage_tostring(tmpaddr) << std::endl; if (!mPeerMgr->isHidden()) std::cerr << "Zeroed tmpaddr: " << sockaddr_storage_tostring(tmpaddr) << std::endl;
#endif #endif
exit(1);
return -1; return -1;
} }
else else
@ -494,8 +493,13 @@ int pqissllistenbase::continueSSL(IncomingSSLInfo& incoming_connexion_info, bool
#endif #endif
if(x509 != NULL) if(x509 != NULL)
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
incoming_connexion_info.gpgid = RsPgpId(std::string(getX509CNString(x509->cert_info->issuer))); incoming_connexion_info.gpgid = RsPgpId(std::string(getX509CNString(x509->cert_info->issuer)));
incoming_connexion_info.sslcn = getX509CNString(x509->cert_info->subject); incoming_connexion_info.sslcn = getX509CNString(x509->cert_info->subject);
#else
incoming_connexion_info.gpgid = RsPgpId(std::string(getX509CNString(X509_get_issuer_name(x509))));
incoming_connexion_info.sslcn = getX509CNString(X509_get_subject_name(x509));
#endif
getX509id(x509,incoming_connexion_info.sslid); getX509id(x509,incoming_connexion_info.sslid);
@ -888,7 +892,11 @@ int pqissllistener::completeConnection(int fd, IncomingSSLInfo& info)
AuthSSL::getAuthSSL()->CheckCertificate(newPeerId, peercert); AuthSSL::getAuthSSL()->CheckCertificate(newPeerId, peercert);
/* now need to get GPG id too */ /* now need to get GPG id too */
#if OPENSSL_VERSION_NUMBER < 0x10100000L
RsPgpId pgpid(std::string(getX509CNString(peercert->cert_info->issuer))); RsPgpId pgpid(std::string(getX509CNString(peercert->cert_info->issuer)));
#else
RsPgpId pgpid(std::string(getX509CNString(X509_get_issuer_name(peercert))));
#endif
mPeerMgr->addFriend(newPeerId, pgpid); mPeerMgr->addFriend(newPeerId, pgpid);
X509_free(peercert); X509_free(peercert);

View File

@ -26,6 +26,7 @@
#include "pqi/pqistreamer.h" #include "pqi/pqistreamer.h"
#include <sys/time.h> // for gettimeofday
#include <stdlib.h> // for free, realloc, exit #include <stdlib.h> // for free, realloc, exit
#include <string.h> // for memcpy, memset, memcmp #include <string.h> // for memcpy, memset, memcmp
#include <time.h> // for NULL, time, time_t #include <time.h> // for NULL, time, time_t
@ -48,8 +49,10 @@ static struct RsLog::logInfo pqistreamerzoneInfo = {RsLog::Default, "pqistreamer
#define pqistreamerzone &pqistreamerzoneInfo #define pqistreamerzone &pqistreamerzoneInfo
static const int PQISTREAM_ABS_MAX = 100000000; /* 100 MB/sec (actually per loop) */ static const int PQISTREAM_ABS_MAX = 100000000; /* 100 MB/sec (actually per loop) */
static const int PQISTREAM_AVG_PERIOD = 5; // update speed estimate every 5 seconds static const int PQISTREAM_AVG_PERIOD = 1; // update speed estimate every second
static const float PQISTREAM_AVG_FRAC = 0.8; // for bandpass filter over speed estimate. static const float PQISTREAM_AVG_FRAC = 0.8; // for bandpass filter over speed estimate.
static const float PQISTREAM_AVG_DT_FRAC = 0.99; // for low pass filter over elapsed time
static const int PQISTREAM_OPTIMAL_PACKET_SIZE = 512; // It is believed that this value should be lower than TCP slices and large enough as compare to encryption padding. static const int PQISTREAM_OPTIMAL_PACKET_SIZE = 512; // It is believed that this value should be lower than TCP slices and large enough as compare to encryption padding.
// most importantly, it should be constant, so as to allow correct QoS. // most importantly, it should be constant, so as to allow correct QoS.
static const int PQISTREAM_SLICE_FLAG_STARTS = 0x01; // static const int PQISTREAM_SLICE_FLAG_STARTS = 0x01; //
@ -100,7 +103,8 @@ pqistreamer::pqistreamer(RsSerialiser *rss, const RsPeerId& id, BinInterface *bi
mPkt_wpending(NULL), mPkt_wpending_size(0), mPkt_wpending(NULL), mPkt_wpending_size(0),
mTotalRead(0), mTotalSent(0), mTotalRead(0), mTotalSent(0),
mCurrRead(0), mCurrSent(0), mCurrRead(0), mCurrSent(0),
mAvgReadCount(0), mAvgSentCount(0) mAvgReadCount(0), mAvgSentCount(0),
mAvgDtOut(0), mAvgDtIn(0)
{ {
// 100 B/s (minimal) // 100 B/s (minimal)
@ -114,8 +118,7 @@ pqistreamer::pqistreamer(RsSerialiser *rss, const RsPeerId& id, BinInterface *bi
mAcceptsPacketSlicing = false ; // by default. Will be turned into true when everyone's ready. mAcceptsPacketSlicing = false ; // by default. Will be turned into true when everyone's ready.
mLastSentPacketSlicingProbe = 0 ; mLastSentPacketSlicingProbe = 0 ;
mAvgLastUpdate = time(NULL); mAvgLastUpdate = mCurrSentTS = mCurrReadTS = getCurrentTS();
mCurrSentTS = mCurrReadTS = getCurrentTS();
mIncomingSize = 0 ; mIncomingSize = 0 ;
@ -231,47 +234,46 @@ void pqistreamer::setRate(bool b,float f)
void pqistreamer::updateRates() void pqistreamer::updateRates()
{ {
// now update rates both ways. // update rates both ways.
time_t t = time(NULL); // get current timestep. double t = getCurrentTS(); // get current timestamp.
int64_t diff ; double diff ;
{ {
RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/
diff = t - mAvgLastUpdate ;
}
diff = int64_t(t) - int64_t(mAvgLastUpdate) ; if (diff > PQISTREAM_AVG_PERIOD)
} {
float avgReadpSec = PQISTREAM_AVG_FRAC * getRate(true ) + (1.0 - PQISTREAM_AVG_FRAC) * mAvgReadCount/(1024.0 * diff);
if (diff > PQISTREAM_AVG_PERIOD) float avgSentpSec = PQISTREAM_AVG_FRAC * getRate(false) + (1.0 - PQISTREAM_AVG_FRAC) * mAvgSentCount/(1024.0 * diff);
{
float avgReadpSec = getRate(true ) * PQISTREAM_AVG_FRAC + (1.0 - PQISTREAM_AVG_FRAC) * mAvgReadCount/(1024.0 * float(diff));
float avgSentpSec = getRate(false) * PQISTREAM_AVG_FRAC + (1.0 - PQISTREAM_AVG_FRAC) * mAvgSentCount/(1024.0 * float(diff));
#ifdef DEBUG_PQISTREAMER #ifdef DEBUG_PQISTREAMER
std::cerr << "Peer " << PeerId() << ": Current speed estimates: " << avgReadpSec << " / " << avgSentpSec << std::endl; uint64_t t_now = 1000 * getCurrentTS();
std::cerr << std::dec << t_now << " DEBUG_PQISTREAMER pqistreamer::updateRates PeerId " << this->PeerId().toStdString() << " Current speed estimates: down " << std::dec << (int)(1024 * avgReadpSec) << " B/s / up " << (int)(1024 * avgSentpSec) << " B/s" << std::endl;
#endif #endif
/* pretend our rate is zero if we are
* not bandwidthLimited().
*/
if (mBio->bandwidthLimited())
{
setRate(true, avgReadpSec);
setRate(false, avgSentpSec);
}
else
{
std::cerr << "Warning: setting to 0" << std::endl;
setRate(true, 0);
setRate(false, 0);
}
{ // now store the new rates, zero meaning that we are not bandwidthLimited()
RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/
mAvgLastUpdate = t; if (mBio->bandwidthLimited())
mAvgReadCount = 0; {
mAvgSentCount = 0; setRate(true, avgReadpSec);
} setRate(false, avgSentpSec);
} }
else
{
setRate(true, 0);
setRate(false, 0);
}
{
RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/
mAvgLastUpdate = t;
mAvgReadCount = 0;
mAvgSentCount = 0;
}
}
} }
int pqistreamer::tick_bio() int pqistreamer::tick_bio()
@ -1114,12 +1116,11 @@ float pqistreamer::outTimeSlice_locked()
return 1; return 1;
} }
// very simple.....
int pqistreamer::outAllowedBytes_locked() int pqistreamer::outAllowedBytes_locked()
{ {
double t = getCurrentTS() ; // Grabs today's time in sec, with ms accuracy. Allows a much more accurate allocation of bw double t = getCurrentTS() ; // in sec, with high accuracy
/* allow a lot if not bandwidthLimited */ // allow a lot if not bandwidthLimited()
if (!mBio->bandwidthLimited()) if (!mBio->bandwidthLimited())
{ {
mCurrSent = 0; mCurrSent = 0;
@ -1127,70 +1128,80 @@ int pqistreamer::outAllowedBytes_locked()
return PQISTREAM_ABS_MAX; return PQISTREAM_ABS_MAX;
} }
double dt = t - mCurrSentTS; // dt is the time elapsed since the last round of sending data
double dt = t - mCurrSentTS;
// limiter -> for when currSentTs -> 0. // ignore cases where dt > 1s
if (dt > 5) if (dt > 1)
dt = 5; dt = 1;
double maxout = getMaxRate(false) * 1024.0; // low pass filter on mAvgDtOut
mAvgDtOut = PQISTREAM_AVG_DT_FRAC * mAvgDtOut + (1 - PQISTREAM_AVG_DT_FRAC) * dt;
mCurrSent -= int(dt * maxout); double maxout = getMaxRate(false) * 1024.0;
// this is used to take into account a possible excess of data sent during the previous round
mCurrSent -= int(dt * maxout);
if (mCurrSent < 0) if (mCurrSent < 0)
mCurrSent = 0; mCurrSent = 0;
mCurrSentTS = t; mCurrSentTS = t;
// now calculate the max amount of data allowed to be sent during the next round
// we limit this quota to what should be sent at most during mAvgDtOut, taking into account the excess of data possibly sent during the previous round
double quota = mAvgDtOut * maxout - mCurrSent;
#ifdef DEBUG_PQISTREAMER #ifdef DEBUG_PQISTREAMER
{ uint64_t t_now = 1000 * getCurrentTS();
std::string out; std::cerr << std::dec << t_now << " DEBUG_PQISTREAMER pqistreamer::outAllowedBytes_locked PeerId " << this->PeerId().toStdString() << " dt " << (int)(1000 * dt) << "ms, mAvgDtOut " << (int)(1000 * mAvgDtOut) << "ms, maxout " << (int)(maxout) << " bytes/s, mCurrSent " << mCurrSent << " bytes, quota " << (int)(quota) << " bytes" << std::endl;
rs_sprintf(out, "pqistreamer::outAllowedBytes() is %d/%d", maxout - mCurrSent, maxout);
pqioutput(PQL_DEBUG_ALL, pqistreamerzone, out);
}
#endif #endif
return quota;
return maxout - mCurrSent;
} }
int pqistreamer::inAllowedBytes_locked() int pqistreamer::inAllowedBytes_locked()
{ {
double t = getCurrentTS(); // in secs, with a ms accuracy double t = getCurrentTS(); // in sec, with high accuracy
/* allow a lot if not bandwidthLimited */ // allow a lot if not bandwidthLimited()
if (!mBio->bandwidthLimited()) if (!mBio->bandwidthLimited())
{ {
mCurrRead = 0;
mCurrReadTS = t; mCurrReadTS = t;
mCurrRead = 0;
return PQISTREAM_ABS_MAX; return PQISTREAM_ABS_MAX;
} }
double dt = t - mCurrReadTS; // dt is the time elapsed since the last round of receiving data
double dt = t - mCurrReadTS;
// limiter -> for when currReadTs -> 0. // limit dt to 1s
if (dt > 5) if (dt > 1)
dt = 5; dt = 1;
double maxin = getMaxRate(true) * 1024.0; // low pass filter on mAvgDtIn
mAvgDtIn = PQISTREAM_AVG_DT_FRAC * mAvgDtIn + (1 - PQISTREAM_AVG_DT_FRAC) * dt;
mCurrRead -= int(dt * maxin); double maxin = getMaxRate(true) * 1024.0;
// this is used to take into account a possible excess of data received during the previous round
mCurrRead -= int(dt * maxin);
if (mCurrRead < 0) if (mCurrRead < 0)
mCurrRead = 0; mCurrRead = 0;
mCurrReadTS = t; mCurrReadTS = t;
// now calculate the max amount of data allowed to be received during the next round
// we limit this quota to what should be received at most during mAvgDtOut, taking into account the excess of data possibly received during the previous round
double quota = mAvgDtIn * maxin - mCurrRead;
#ifdef DEBUG_PQISTREAMER #ifdef DEBUG_PQISTREAMER
{ uint64_t t_now = 1000 * getCurrentTS();
std::string out; std::cerr << std::dec << t_now << " DEBUG_PQISTREAMER pqistreamer::inAllowedBytes_locked PeerId " << this->PeerId().toStdString() << " dt " << (int)(1000 * dt) << "ms, mAvgDtIn " << (int)(1000 * mAvgDtIn) << "ms, maxin " << (int)(maxin) << " bytes/s, mCurrRead " << mCurrRead << " bytes, quota " << (int)(quota) << " bytes" << std::endl;
rs_sprintf(out, "pqistreamer::inAllowedBytes() is %d/%d", maxin - mCurrRead, maxin);
pqioutput(PQL_DEBUG_ALL, pqistreamerzone, out);
}
#endif #endif
return quota;
return maxin - mCurrRead;
} }

View File

@ -162,10 +162,13 @@ class pqistreamer: public PQInterface
double mCurrReadTS; // TS from which these are measured. double mCurrReadTS; // TS from which these are measured.
double mCurrSentTS; double mCurrSentTS;
time_t mAvgLastUpdate; // TS from which these are measured. double mAvgLastUpdate; // TS from which these are measured.
uint32_t mAvgReadCount; uint32_t mAvgReadCount;
uint32_t mAvgSentCount; uint32_t mAvgSentCount;
double mAvgDtOut; // average time diff between 2 rounds of sending data
double mAvgDtIn; // average time diff between 2 rounds of receiving data
time_t mLastIncomingTs; time_t mLastIncomingTs;
// traffic statistics // traffic statistics

View File

@ -242,6 +242,7 @@ X509_REQ *GenerateX509Req(
#define SERIAL_RAND_BITS 64 #define SERIAL_RAND_BITS 64
#ifdef UNUSED_CODE
X509 *SignX509Certificate(X509_NAME *issuer, EVP_PKEY *privkey, X509_REQ *req, long days) X509 *SignX509Certificate(X509_NAME *issuer, EVP_PKEY *privkey, X509_REQ *req, long days)
{ {
const EVP_MD *digest = EVP_sha1(); const EVP_MD *digest = EVP_sha1();
@ -369,6 +370,7 @@ X509 *SignX509Certificate(X509_NAME *issuer, EVP_PKEY *privkey, X509_REQ *req, l
return x509; return x509;
} }
#endif
/********************************************************************************/ /********************************************************************************/
/********************************************************************************/ /********************************************************************************/
@ -600,7 +602,14 @@ bool getX509id(X509 *x509, RsPeerId& xid)
} }
// get the signature from the cert, and copy to the array. // get the signature from the cert, and copy to the array.
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ASN1_BIT_STRING *signature = x509->signature; ASN1_BIT_STRING *signature = x509->signature;
#else
const ASN1_BIT_STRING *signature = NULL ;
const X509_ALGOR *algor ;
X509_get0_signature(&signature,&algor,x509);
#endif
int signlen = ASN1_STRING_length(signature); int signlen = ASN1_STRING_length(signature);
if (signlen < CERTSIGNLEN) if (signlen < CERTSIGNLEN)
{ {
@ -612,12 +621,14 @@ bool getX509id(X509 *x509, RsPeerId& xid)
} }
// else copy in the first CERTSIGNLEN. // else copy in the first CERTSIGNLEN.
unsigned char *signdata = ASN1_STRING_data(signature); unsigned char *signdata = ASN1_STRING_data(const_cast<ASN1_BIT_STRING*>(signature));
/* switched to the other end of the signature. for /* switched to the other end of the signature. for
* more randomness * more randomness
*/ */
#warning this is cryptographically horrible. We should do a hash of the public key here!!!
xid = RsPeerId(&signdata[signlen - CERTSIGNLEN]) ; xid = RsPeerId(&signdata[signlen - CERTSIGNLEN]) ;
//for(int i = signlen - CERTSIGNLEN; i < signlen; i++) //for(int i = signlen - CERTSIGNLEN; i < signlen; i++)
@ -689,8 +700,13 @@ int LoadCheckX509(const char *cert_file, RsPgpId& issuerName, std::string &locat
if (valid) if (valid)
{ {
// extract the name. // extract the name.
#if OPENSSL_VERSION_NUMBER < 0x10100000L
issuerName = RsPgpId(std::string(getX509CNString(x509->cert_info->issuer))); issuerName = RsPgpId(std::string(getX509CNString(x509->cert_info->issuer)));
location = getX509LocString(x509->cert_info->subject); location = getX509LocString(x509->cert_info->subject);
#else
issuerName = RsPgpId(std::string(getX509CNString(X509_get_issuer_name(x509))));
location = getX509LocString(X509_get_subject_name(x509));
#endif
} }
#ifdef AUTHSSL_DEBUG #ifdef AUTHSSL_DEBUG

View File

@ -199,6 +199,9 @@ class RsNotify
virtual bool NotifyLogMessage(uint32_t &sysid, uint32_t &type, std::string &title, std::string &msg) = 0; virtual bool NotifyLogMessage(uint32_t &sysid, uint32_t &type, std::string &title, std::string &msg) = 0;
virtual bool GetFeedItem(RsFeedItem &item) = 0; virtual bool GetFeedItem(RsFeedItem &item) = 0;
virtual bool cachePgpPassphrase (const std::string& /* pgp_passphrase */) { return false ; }
virtual bool clearPgpPassphrase () { return false ; }
}; };
class NotifyClient class NotifyClient

View File

@ -1218,7 +1218,7 @@ bool p3Peers::cleanCertificate(const std::string &certstr, std::string &cleanCer
{ {
RsCertificate::Format format ; RsCertificate::Format format ;
return RsCertificate::cleanCertificate(certstr,cleanCert,format,error_code) ; return RsCertificate::cleanCertificate(certstr,cleanCert,format,error_code,true) ;
} }
bool p3Peers::saveCertificateToFile(const RsPeerId &id, const std::string &/*fname*/) bool p3Peers::saveCertificateToFile(const RsPeerId &id, const std::string &/*fname*/)

View File

@ -1095,9 +1095,8 @@ bool p3GxsReputation::saveList(bool& cleanup, std::list<RsItem*> &savelist)
cleanup = true; cleanup = true;
RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/
#ifdef DEBUG_REPUTATION
std::cerr << "p3GxsReputation::saveList()" << std::endl; std::cerr << "p3GxsReputation::saveList()" << std::endl;
#endif
/* save */ /* save */
std::map<RsPeerId, ReputationConfig>::iterator it; std::map<RsPeerId, ReputationConfig>::iterator it;
for(it = mConfig.begin(); it != mConfig.end(); ++it) for(it = mConfig.begin(); it != mConfig.end(); ++it)

View File

@ -90,7 +90,28 @@ static int clear_tou_socket_error(int s);
#include "tou.h" #include "tou.h"
#if OPENSSL_VERSION_NUMBER < 0x10100000L
//static void BIO_set_shutdown(BIO *a,int s) { a->shutdown=s; }
static int BIO_get_shutdown(BIO *a) { return a->shutdown; }
static int BIO_get_init(BIO *a) { return a->init; }
static void BIO_set_init(BIO *a,int i) { a->init=i; }
static void BIO_set_data(BIO *a,void *p) { a->ptr = p; }
#else
typedef struct bio_method_st {
int type;
const char *name;
int (*bwrite) (BIO *, const char *, int);
int (*bread) (BIO *, char *, int);
int (*bputs) (BIO *, const char *);
int (*bgets) (BIO *, char *, int);
long (*ctrl) (BIO *, int, long, void *);
int (*create) (BIO *);
int (*destroy) (BIO *);
long (*callback_ctrl) (BIO *, int, bio_info_cb *);
} BIO_METHOD;
#endif
static BIO_METHOD methods_tou_sockp= static BIO_METHOD methods_tou_sockp=
{ {
@ -132,10 +153,10 @@ static int tou_socket_new(BIO *bi)
#ifdef DEBUG_TOU_BIO #ifdef DEBUG_TOU_BIO
fprintf(stderr, "tou_socket_new()\n"); fprintf(stderr, "tou_socket_new()\n");
#endif #endif
bi->init=0; BIO_set_init(bi,0) ;
bi->num=0; BIO_set_data(bi,NULL) ; // sets bi->ptr
bi->ptr=NULL; BIO_set_flags(bi,0) ;
bi->flags=0; BIO_set_fd(bi,0,0) ;
return(1); return(1);
} }
@ -145,14 +166,15 @@ static int tou_socket_free(BIO *a)
fprintf(stderr, "tou_socket_free()\n"); fprintf(stderr, "tou_socket_free()\n");
#endif #endif
if (a == NULL) return(0); if (a == NULL) return(0);
if (a->shutdown)
if(BIO_get_shutdown(a))
{ {
if (a->init) if(BIO_get_init(a))
{ {
tou_close(a->num); tou_close(BIO_get_fd(a,NULL));
} }
a->init=0; BIO_set_init(a,0) ;
a->flags=0; BIO_set_flags(a,0) ;
} }
return(1); return(1);
} }
@ -166,13 +188,13 @@ static int tou_socket_read(BIO *b, char *out, int outl)
if (out != NULL) if (out != NULL)
{ {
clear_tou_socket_error(b->num); clear_tou_socket_error(BIO_get_fd(b,NULL));
/* call tou library */ /* call tou library */
ret=tou_read(b->num,out,outl); ret=tou_read(BIO_get_fd(b,NULL),out,outl);
BIO_clear_retry_flags(b); BIO_clear_retry_flags(b);
if (ret <= 0) if (ret <= 0)
{ {
if (BIO_tou_socket_should_retry(b->num, ret)) if (BIO_tou_socket_should_retry(BIO_get_fd(b,NULL), ret))
BIO_set_retry_read(b); BIO_set_retry_read(b);
} }
} }
@ -189,13 +211,13 @@ static int tou_socket_write(BIO *b, const char *in, int inl)
fprintf(stderr, "tou_socket_write(%p,%p,%d)\n",b,in,inl); fprintf(stderr, "tou_socket_write(%p,%p,%d)\n",b,in,inl);
#endif #endif
clear_tou_socket_error(b->num); clear_tou_socket_error(BIO_get_fd(b,NULL));
/* call tou library */ /* call tou library */
ret=tou_write(b->num,in,inl); ret=tou_write(BIO_get_fd(b,NULL),in,inl);
BIO_clear_retry_flags(b); BIO_clear_retry_flags(b);
if (ret <= 0) if (ret <= 0)
{ {
if (BIO_tou_socket_should_retry(b->num,ret)) if (BIO_tou_socket_should_retry(BIO_get_fd(b,NULL),ret))
{ {
BIO_set_retry_write(b); BIO_set_retry_write(b);
#ifdef DEBUG_TOU_BIO #ifdef DEBUG_TOU_BIO
@ -212,11 +234,12 @@ static int tou_socket_write(BIO *b, const char *in, int inl)
static long tou_socket_ctrl(BIO *b, int cmd, long num, void *ptr) static long tou_socket_ctrl(BIO *b, int cmd, long num, void *ptr)
{ {
long ret=1; long ret=1;
int *ip;
#ifdef DEBUG_TOU_BIO #ifdef DEBUG_TOU_BIO
fprintf(stderr, "tou_socket_ctrl(%p,%d,%ld)\n", b, cmd, num); fprintf(stderr, "tou_socket_ctrl(%p,%d,%ld)\n", b, cmd, num);
#endif #endif
// We are not allowed to call BIO_set_fd here, because it will trigger a callback, which re-ends here
switch (cmd) switch (cmd)
{ {
case BIO_CTRL_RESET: case BIO_CTRL_RESET:
@ -230,34 +253,26 @@ static long tou_socket_ctrl(BIO *b, int cmd, long num, void *ptr)
break; break;
case BIO_C_SET_FD: case BIO_C_SET_FD:
tou_socket_free(b); tou_socket_free(b);
b->num= *((int *)ptr); ret = BIO_s_fd()->ctrl(b,cmd,num,ptr) ;
b->shutdown=(int)num;
b->init=1;
break; break;
case BIO_C_GET_FD: case BIO_C_GET_FD:
if (b->init) ret = BIO_s_fd()->ctrl(b,cmd,num,ptr) ;
{
ip=(int *)ptr;
if (ip != NULL) *ip=b->num;
ret=b->num;
}
else
ret= -1;
break; break;
case BIO_CTRL_GET_CLOSE: case BIO_CTRL_GET_CLOSE:
ret=b->shutdown; ret = BIO_s_fd()->ctrl(b,cmd,num,ptr) ;
break; break;
case BIO_CTRL_SET_CLOSE: case BIO_CTRL_SET_CLOSE:
b->shutdown=(int)num; ret = BIO_s_fd()->ctrl(b,cmd,num,ptr) ;
break; break;
case BIO_CTRL_PENDING: case BIO_CTRL_PENDING:
ret = tou_maxread(b->num); ret = tou_maxread(BIO_get_fd(b,NULL));
#ifdef DEBUG_TOU_BIO #ifdef DEBUG_TOU_BIO
fprintf(stderr, "tou_pending = %ld\n", ret); fprintf(stderr, "tou_pending = %ld\n", ret);
#endif #endif
break; break;
case BIO_CTRL_WPENDING: case BIO_CTRL_WPENDING:
ret = tou_maxwrite(b->num); ret = tou_maxwrite(BIO_get_fd(b,NULL));
#ifdef DEBUG_TOU_BIO #ifdef DEBUG_TOU_BIO
fprintf(stderr, "tou_wpending = %ld\n", ret); fprintf(stderr, "tou_wpending = %ld\n", ret);
#endif #endif

View File

@ -52,9 +52,8 @@ bool RsAES::aes_crypt_8_16(const uint8_t *input_data,uint32_t input_data_length,
return false ; return false ;
} }
EVP_CIPHER_CTX e_ctx ; EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(&e_ctx); EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_EncryptInit_ex(&e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
/* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */ /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
int c_len = input_data_length + AES_BLOCK_SIZE ; int c_len = input_data_length + AES_BLOCK_SIZE ;
@ -62,31 +61,31 @@ bool RsAES::aes_crypt_8_16(const uint8_t *input_data,uint32_t input_data_length,
if(output_data_length < (uint32_t)c_len) if(output_data_length < (uint32_t)c_len)
{ {
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return false ; return false ;
} }
/* update ciphertext, c_len is filled with the length of ciphertext generated, /* update ciphertext, c_len is filled with the length of ciphertext generated,
*len is the size of plaintext in bytes */ *len is the size of plaintext in bytes */
if(!EVP_EncryptUpdate(&e_ctx, output_data, &c_len, input_data, input_data_length)) if(!EVP_EncryptUpdate(e_ctx, output_data, &c_len, input_data, input_data_length))
{ {
std::cerr << "RsAES: decryption failed at end. Check padding." << std::endl; std::cerr << "RsAES: decryption failed at end. Check padding." << std::endl;
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return false ; return false ;
} }
/* update ciphertext with the final remaining bytes */ /* update ciphertext with the final remaining bytes */
if(!EVP_EncryptFinal_ex(&e_ctx, output_data+c_len, &f_len)) if(!EVP_EncryptFinal_ex(e_ctx, output_data+c_len, &f_len))
{ {
std::cerr << "RsAES: decryption failed at end. Check padding." << std::endl; std::cerr << "RsAES: decryption failed at end. Check padding." << std::endl;
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return false ; return false ;
} }
output_data_length = c_len + f_len; output_data_length = c_len + f_len;
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return true; return true;
} }
@ -108,9 +107,8 @@ bool RsAES::aes_decrypt_8_16(const uint8_t *input_data,uint32_t input_data_lengt
return false ; return false ;
} }
EVP_CIPHER_CTX e_ctx ; EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(&e_ctx); EVP_DecryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_DecryptInit_ex(&e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
/* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */ /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
int c_len = input_data_length + AES_BLOCK_SIZE ; int c_len = input_data_length + AES_BLOCK_SIZE ;
@ -118,7 +116,7 @@ bool RsAES::aes_decrypt_8_16(const uint8_t *input_data,uint32_t input_data_lengt
if(output_data_length < (uint32_t)c_len) if(output_data_length < (uint32_t)c_len)
{ {
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return false ; return false ;
} }
@ -127,24 +125,24 @@ bool RsAES::aes_decrypt_8_16(const uint8_t *input_data,uint32_t input_data_lengt
/* update ciphertext, c_len is filled with the length of ciphertext generated, /* update ciphertext, c_len is filled with the length of ciphertext generated,
*len is the size of plaintext in bytes */ *len is the size of plaintext in bytes */
if(! EVP_DecryptUpdate(&e_ctx, output_data, &c_len, input_data, input_data_length)) if(! EVP_DecryptUpdate(e_ctx, output_data, &c_len, input_data, input_data_length))
{ {
std::cerr << "RsAES: decryption failed." << std::endl; std::cerr << "RsAES: decryption failed." << std::endl;
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return false ; return false ;
} }
/* update ciphertext with the final remaining bytes */ /* update ciphertext with the final remaining bytes */
if(!EVP_DecryptFinal_ex(&e_ctx, output_data+c_len, &f_len)) if(!EVP_DecryptFinal_ex(e_ctx, output_data+c_len, &f_len))
{ {
std::cerr << "RsAES: decryption failed at end. Check padding." << std::endl; std::cerr << "RsAES: decryption failed at end. Check padding." << std::endl;
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return false ; return false ;
} }
output_data_length = c_len + f_len; output_data_length = c_len + f_len;
EVP_CIPHER_CTX_cleanup(&e_ctx) ; EVP_CIPHER_CTX_free(e_ctx) ;
return true; return true;
} }

View File

@ -28,6 +28,7 @@
#include "util/rsrecogn.h" #include "util/rsrecogn.h"
#include "util/radix64.h" #include "util/radix64.h"
#include "util/rsstring.h" #include "util/rsstring.h"
#include "util/rsdir.h"
#include "gxs/gxssecurity.h" #include "gxs/gxssecurity.h"
@ -507,9 +508,23 @@ bool RsRecogn::itemToRadix64(RsItem *item, std::string &radstr)
std::string RsRecogn::getRsaKeyId(RSA *pubkey) std::string RsRecogn::getRsaKeyId(RSA *pubkey)
{ {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
int len = BN_num_bytes(pubkey -> n); int len = BN_num_bytes(pubkey -> n);
unsigned char tmp[len]; unsigned char tmp[len];
BN_bn2bin(pubkey -> n, tmp); BN_bn2bin(pubkey -> n, tmp);
#else
const BIGNUM *nn=NULL ;
RSA_get0_key(pubkey,&nn,NULL,NULL) ;
int len = BN_num_bytes(nn);
unsigned char tmp[len];
BN_bn2bin(nn, tmp);
#endif
return RsDirUtil::sha1sum(tmp,len).toStdString();
#ifdef OLD_VERSION_REMOVED
// (cyril) I removed this because this is cryptographically insane, as it allows to easily forge a RSA key with the same ID.
// copy first CERTSIGNLEN bytes... // copy first CERTSIGNLEN bytes...
if (len > CERTSIGNLEN) if (len > CERTSIGNLEN)
@ -524,6 +539,7 @@ std::string RsRecogn::getRsaKeyId(RSA *pubkey)
} }
return id; return id;
#endif
} }

View File

@ -45,12 +45,21 @@ void test_secret_key(const ops_secret_key_t *skey)
{ {
RSA* test=RSA_new(); RSA* test=RSA_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
test->n=BN_dup(skey->public_key.key.rsa.n); test->n=BN_dup(skey->public_key.key.rsa.n);
test->e=BN_dup(skey->public_key.key.rsa.e); test->e=BN_dup(skey->public_key.key.rsa.e);
test->d=BN_dup(skey->key.rsa.d); test->d=BN_dup(skey->key.rsa.d);
test->p=BN_dup(skey->key.rsa.p); test->p=BN_dup(skey->key.rsa.p);
test->q=BN_dup(skey->key.rsa.q); test->q=BN_dup(skey->key.rsa.q);
#else
RSA_set0_key(test,
BN_dup(skey->public_key.key.rsa.n),
BN_dup(skey->public_key.key.rsa.e),
BN_dup(skey->key.rsa.d));
RSA_set0_factors(test, BN_dup(skey->key.rsa.p), BN_dup(skey->key.rsa.q));
#endif
assert(RSA_check_key(test)==1); assert(RSA_check_key(test)==1);
RSA_free(test); RSA_free(test);
@ -392,8 +401,13 @@ ops_boolean_t ops_dsa_verify(const unsigned char *hash,size_t hash_length,
int ret; int ret;
osig=DSA_SIG_new(); osig=DSA_SIG_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
osig->r=sig->r; osig->r=sig->r;
osig->s=sig->s; osig->s=sig->s;
#else
DSA_SIG_set0(osig,BN_dup(sig->r),BN_dup(sig->s)) ;
#endif
if(BN_num_bits(dsa->q) != 160) if(BN_num_bits(dsa->q) != 160)
{ {
@ -402,16 +416,27 @@ ops_boolean_t ops_dsa_verify(const unsigned char *hash,size_t hash_length,
fprintf(stderr,"(WW) ops_dsa_verify: openssl does only supports 'q' of 160 bits. Current is %d bits.\n",BN_num_bits(dsa->q)) ; fprintf(stderr,"(WW) ops_dsa_verify: openssl does only supports 'q' of 160 bits. Current is %d bits.\n",BN_num_bits(dsa->q)) ;
already_said=ops_true ; already_said=ops_true ;
} }
osig->r=osig->s=NULL;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
osig->r=NULL; // in this case, the values are not copied.
osig->s=NULL;
#endif
DSA_SIG_free(osig); DSA_SIG_free(osig);
return ops_false ; return ops_false ;
} }
odsa=DSA_new(); odsa=DSA_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
odsa->p=dsa->p; odsa->p=dsa->p;
odsa->q=dsa->q; odsa->q=dsa->q;
odsa->g=dsa->g; odsa->g=dsa->g;
odsa->pub_key=dsa->y; odsa->pub_key=dsa->y;
#else
DSA_set0_pqg(odsa,BN_dup(dsa->p),BN_dup(dsa->q),BN_dup(dsa->g));
DSA_set0_key(odsa,BN_dup(dsa->y),NULL) ;
#endif
if (debug) if (debug)
{ {
@ -425,7 +450,8 @@ ops_boolean_t ops_dsa_verify(const unsigned char *hash,size_t hash_length,
} }
//printf("hash_length=%ld\n", hash_length); //printf("hash_length=%ld\n", hash_length);
//printf("Q=%d\n", BN_num_bytes(odsa->q)); //printf("Q=%d\n", BN_num_bytes(odsa->q));
unsigned int qlen=BN_num_bytes(odsa->q); unsigned int qlen=BN_num_bytes(dsa->q);
if (qlen < hash_length) if (qlen < hash_length)
hash_length=qlen; hash_length=qlen;
// ret=DSA_do_verify(hash,hash_length,osig,odsa); // ret=DSA_do_verify(hash,hash_length,osig,odsa);
@ -445,10 +471,17 @@ ops_boolean_t ops_dsa_verify(const unsigned char *hash,size_t hash_length,
return ops_false ; return ops_false ;
} }
odsa->p=odsa->q=odsa->g=odsa->pub_key=NULL; #if OPENSSL_VERSION_NUMBER < 0x10100000L
DSA_free(odsa); osig->r=NULL;
osig->s=NULL;
osig->r=osig->s=NULL; odsa->p=NULL;
odsa->q=NULL;
odsa->g=NULL;
odsa->pub_key=NULL;
#endif
DSA_free(odsa);
DSA_SIG_free(osig); DSA_SIG_free(osig);
return ret != 0; return ret != 0;
@ -470,12 +503,18 @@ int ops_rsa_public_decrypt(unsigned char *out,const unsigned char *in,
int n; int n;
orsa=RSA_new(); orsa=RSA_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=rsa->n; orsa->n=rsa->n;
orsa->e=rsa->e; orsa->e=rsa->e;
#else
RSA_set0_key(orsa,BN_dup(rsa->n),BN_dup(rsa->e),NULL) ;
#endif
n=RSA_public_decrypt(length,in,out,orsa,RSA_NO_PADDING); n=RSA_public_decrypt(length,in,out,orsa,RSA_NO_PADDING);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=orsa->e=NULL; orsa->n=orsa->e=NULL;
#endif
RSA_free(orsa); RSA_free(orsa);
return n; return n;
@ -499,6 +538,7 @@ int ops_rsa_private_encrypt(unsigned char *out,const unsigned char *in,
int n; int n;
orsa=RSA_new(); orsa=RSA_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=rsa->n; // XXX: do we need n? orsa->n=rsa->n; // XXX: do we need n?
orsa->d=srsa->d; orsa->d=srsa->d;
orsa->p=srsa->q; orsa->p=srsa->q;
@ -506,17 +546,28 @@ int ops_rsa_private_encrypt(unsigned char *out,const unsigned char *in,
/* debug */ /* debug */
orsa->e=rsa->e; orsa->e=rsa->e;
// If this isn't set, it's very likely that the programmer hasn't // If this isn't set, it's very likely that the programmer hasn't
// decrypted the secret key. RSA_check_key segfaults in that case. // decrypted the secret key. RSA_check_key segfaults in that case.
// Use ops_decrypt_secret_key_from_data() to do that. // Use ops_decrypt_secret_key_from_data() to do that.
assert(orsa->d); assert(orsa->d);
#else
RSA_set0_key(orsa,BN_dup(rsa->n),BN_dup(rsa->e),BN_dup(srsa->d)) ;
RSA_set0_factors(orsa,BN_dup(srsa->p),BN_dup(srsa->q));
#endif
assert(RSA_check_key(orsa) == 1); assert(RSA_check_key(orsa) == 1);
orsa->e=NULL;
/* end debug */ /* end debug */
// WARNING: this function should *never* be called for direct encryption, because of the padding.
// It's actually only called in the signature function now, where an adapted padding is placed.
n=RSA_private_encrypt(length,in,out,orsa,RSA_NO_PADDING); n=RSA_private_encrypt(length,in,out,orsa,RSA_NO_PADDING);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=orsa->d=orsa->p=orsa->q=NULL; orsa->n=orsa->d=orsa->p=orsa->q=NULL;
orsa->e=NULL;
#endif
RSA_free(orsa); RSA_free(orsa);
return n; return n;
@ -541,15 +592,19 @@ int ops_rsa_private_decrypt(unsigned char *out,const unsigned char *in,
char errbuf[1024]; char errbuf[1024];
orsa=RSA_new(); orsa=RSA_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=rsa->n; // XXX: do we need n? orsa->n=rsa->n; // XXX: do we need n?
orsa->d=srsa->d; orsa->d=srsa->d;
orsa->p=srsa->q; orsa->p=srsa->q;
orsa->q=srsa->p; orsa->q=srsa->p;
orsa->e=rsa->e;
#else
RSA_set0_key(orsa,BN_dup(rsa->n),BN_dup(rsa->e),BN_dup(srsa->d)) ;
RSA_set0_factors(orsa,BN_dup(srsa->p),BN_dup(srsa->q));
#endif
/* debug */ /* debug */
orsa->e=rsa->e;
assert(RSA_check_key(orsa) == 1); assert(RSA_check_key(orsa) == 1);
orsa->e=NULL;
/* end debug */ /* end debug */
n=RSA_private_decrypt(length,in,out,orsa,RSA_NO_PADDING); n=RSA_private_decrypt(length,in,out,orsa,RSA_NO_PADDING);
@ -563,7 +618,10 @@ int ops_rsa_private_decrypt(unsigned char *out,const unsigned char *in,
ERR_error_string(err,&errbuf[0]); ERR_error_string(err,&errbuf[0]);
fprintf(stderr,"openssl error : %s\n",errbuf); fprintf(stderr,"openssl error : %s\n",errbuf);
} }
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=orsa->d=orsa->p=orsa->q=NULL; orsa->n=orsa->d=orsa->p=orsa->q=NULL;
orsa->e=NULL;
#endif
RSA_free(orsa); RSA_free(orsa);
return n; return n;
@ -586,8 +644,12 @@ int ops_rsa_public_encrypt(unsigned char *out,const unsigned char *in,
// printf("ops_rsa_public_encrypt: length=%ld\n", length); // printf("ops_rsa_public_encrypt: length=%ld\n", length);
orsa=RSA_new(); orsa=RSA_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=rsa->n; orsa->n=rsa->n;
orsa->e=rsa->e; orsa->e=rsa->e;
#else
RSA_set0_key(orsa,BN_dup(rsa->n),BN_dup(rsa->e),NULL);
#endif
// printf("len: %ld\n", length); // printf("len: %ld\n", length);
// ops_print_bn("n: ", orsa->n); // ops_print_bn("n: ", orsa->n);
@ -602,7 +664,9 @@ int ops_rsa_public_encrypt(unsigned char *out,const unsigned char *in,
BIO_free(fd_out) ; BIO_free(fd_out) ;
} }
#if OPENSSL_VERSION_NUMBER < 0x10100000L
orsa->n=orsa->e=NULL; orsa->n=orsa->e=NULL;
#endif
RSA_free(orsa); RSA_free(orsa);
return n; return n;
@ -680,8 +744,19 @@ ops_boolean_t ops_rsa_generate_keypair(const int numbits, const unsigned long e,
skey->public_key.days_valid=0; skey->public_key.days_valid=0;
skey->public_key.algorithm= OPS_PKA_RSA; skey->public_key.algorithm= OPS_PKA_RSA;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
skey->public_key.key.rsa.n=BN_dup(rsa->n); skey->public_key.key.rsa.n=BN_dup(rsa->n);
skey->public_key.key.rsa.e=BN_dup(rsa->e); skey->public_key.key.rsa.e=BN_dup(rsa->e);
skey->key.rsa.d=BN_dup(rsa->d);
#else
const BIGNUM *nn=NULL,*ee=NULL,*dd=NULL ;
RSA_get0_key(rsa,&nn,&ee,&dd) ;
skey->public_key.key.rsa.n=BN_dup(nn) ;
skey->public_key.key.rsa.e=BN_dup(ee) ;
skey->key.rsa.d=BN_dup(dd) ;
#endif
skey->s2k_usage=OPS_S2KU_ENCRYPTED_AND_HASHED; skey->s2k_usage=OPS_S2KU_ENCRYPTED_AND_HASHED;
skey->s2k_specifier=OPS_S2KS_SALTED; skey->s2k_specifier=OPS_S2KS_SALTED;
@ -691,10 +766,20 @@ ops_boolean_t ops_rsa_generate_keypair(const int numbits, const unsigned long e,
skey->octet_count=0; skey->octet_count=0;
skey->checksum=0; skey->checksum=0;
skey->key.rsa.d=BN_dup(rsa->d); #if OPENSSL_VERSION_NUMBER < 0x10100000L
skey->key.rsa.p=BN_dup(rsa->p); skey->key.rsa.p=BN_dup(rsa->p);
skey->key.rsa.q=BN_dup(rsa->q); skey->key.rsa.q=BN_dup(rsa->q);
skey->key.rsa.u=BN_mod_inverse(NULL,rsa->p, rsa->q, ctx); skey->key.rsa.u=BN_mod_inverse(NULL,rsa->p, rsa->q, ctx);
#else
const BIGNUM *pp=NULL,*qq=NULL ;
RSA_get0_factors(rsa,&pp,&qq) ;
skey->key.rsa.p=BN_dup(pp);
skey->key.rsa.q=BN_dup(qq);
skey->key.rsa.u=BN_mod_inverse(NULL,pp,qq, ctx);
#endif
assert(skey->key.rsa.u); assert(skey->key.rsa.u);
BN_CTX_free(ctx); BN_CTX_free(ctx);
@ -803,15 +888,22 @@ DSA_SIG* ops_dsa_sign(unsigned char* hashbuf, unsigned hashsize, const ops_dsa_s
DSA_SIG *dsasig; DSA_SIG *dsasig;
odsa=DSA_new(); odsa=DSA_new();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
odsa->p=dsa->p; odsa->p=dsa->p;
odsa->q=dsa->q; odsa->q=dsa->q;
odsa->g=dsa->g; odsa->g=dsa->g;
odsa->pub_key=dsa->y; odsa->pub_key=dsa->y;
odsa->priv_key=sdsa->x; odsa->priv_key=sdsa->x;
#else
DSA_set0_pqg(odsa,BN_dup(dsa->p),BN_dup(dsa->q),BN_dup(dsa->g));
DSA_set0_key(odsa,BN_dup(dsa->y),BN_dup(sdsa->x));
#endif
dsasig=DSA_do_sign(hashbuf,hashsize,odsa); dsasig=DSA_do_sign(hashbuf,hashsize,odsa);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
odsa->p=odsa->q=odsa->g=odsa->pub_key=odsa->priv_key=NULL; odsa->p=odsa->q=odsa->g=odsa->pub_key=odsa->priv_key=NULL;
#endif
DSA_free(odsa); DSA_free(odsa);
return dsasig; return dsasig;

View File

@ -298,8 +298,18 @@ static ops_boolean_t dsa_sign(ops_hash_t *hash, const ops_dsa_public_key_t *dsa,
dsasig=ops_dsa_sign(hashbuf, hashsize, sdsa, dsa); dsasig=ops_dsa_sign(hashbuf, hashsize, sdsa, dsa);
// convert and write the sig out to memory // convert and write the sig out to memory
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ops_write_mpi(dsasig->r, cinfo); ops_write_mpi(dsasig->r, cinfo);
ops_write_mpi(dsasig->s, cinfo); ops_write_mpi(dsasig->s, cinfo);
#else
const BIGNUM *rr=NULL,*ss=NULL ;
DSA_SIG_get0(dsasig,&rr,&ss) ;
ops_write_mpi(rr, cinfo);
ops_write_mpi(ss, cinfo);
#endif
DSA_SIG_free(dsasig); DSA_SIG_free(dsasig);
return ops_true ; return ops_true ;

View File

@ -21,789 +21,17 @@
****************************************************************/ ****************************************************************/
#include "AboutDialog.h" #include "AboutDialog.h"
#include "HelpDialog.h"
#include "rshare.h"
#include <retroshare/rsiface.h>
#include <retroshare/rsplugin.h>
#include <retroshare/rsdisc.h>
#include <retroshare/rspeers.h>
#include "settings/rsharesettings.h"
#ifdef ENABLE_WEBUI
#include <microhttpd.h>
#endif
#include <QClipboard>
#include <QSysInfo>
#include <QHBoxLayout>
#include <QPainter>
#include <QBrush>
#include <QMessageBox>
#include <QStyle>
#include <assert.h>
AboutDialog::AboutDialog(QWidget* parent) AboutDialog::AboutDialog(QWidget* parent)
: QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint) : QDialog(parent,Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint)
{ {
setupUi(this);
QHBoxLayout* l = new QHBoxLayout();
l->setMargin(0);
l->addStretch(1);
l->addStretch(1);
frame->setContentsMargins(0, 0, 0, 0);
frame->setLayout(l);
tWidget = NULL;
installAWidget();
updateTitle();
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
setWindowFlags(windowFlags() | Qt::MSWindowsFixedSizeDialogHint); setWindowFlags(windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
#endif #endif
}
void AboutDialog::installAWidget() { setupUi(this) ;
assert(tWidget == NULL);
AWidget* aWidget = new AWidget();
QVBoxLayout* l = (QVBoxLayout*)frame->layout();
l->insertWidget(0, aWidget);
l->setStretchFactor(aWidget, 100);
}
void AboutDialog::installTWidget() { QObject::connect(widget->close_button,SIGNAL(clicked()),this,SLOT(close()));
assert(tWidget == NULL);
tWidget = new TBoard();
QLabel* npLabel = new NextPieceLabel(tWidget);
tWidget->setNextPieceLabel(npLabel);
QWidget* pan = new QWidget();
QVBoxLayout* vl = new QVBoxLayout(pan);
QLabel* topRecLabel = new QLabel(tr("Max score: %1").arg(tWidget->getMaxScore()));
QLabel* scoreLabel = new QLabel(pan);
QLabel* levelLabel = new QLabel(pan);
vl->addStretch();
vl->addWidget(topRecLabel);
vl->addStretch();
vl->addWidget(npLabel);
vl->addStretch();
vl->addWidget(scoreLabel);
vl->addWidget(levelLabel);
vl->addStretch();
QHBoxLayout* l = (QHBoxLayout*)frame->layout();
l->insertWidget(0, pan);
l->insertWidget(0, tWidget);
QRect cRect = frame->contentsRect();
int height = tWidget->heightForWidth(cRect.width());
tWidget->setFixedSize(cRect.width() * cRect.height() / height, cRect.height());
npLabel->setFixedSize(tWidget->squareWidth()*4, tWidget->squareHeight()*5);
l->setStretchFactor(tWidget, 100);
connect(tWidget, SIGNAL(scoreChanged(int)), SLOT(sl_scoreChanged(int)));
connect(tWidget, SIGNAL(levelChanged(int)), SLOT(sl_levelChanged(int)));
connect(this, SIGNAL(si_scoreChanged(QString)), scoreLabel, SLOT(setText(QString)));
connect(this, SIGNAL(si_levelChanged(QString)), levelLabel, SLOT(setText(QString)));
tWidget->setFocus();
tWidget->start();
}
void AboutDialog::switchPages() {
QLayoutItem* li = NULL;
QLayout* l = frame->layout();
while ((li = l->takeAt(0)) && li->widget()) {
li->widget()->deleteLater();
}
if (tWidget==NULL) {
installTWidget();
} else {
tWidget = NULL;
installAWidget();
}
updateTitle();
}
void AboutDialog::sl_scoreChanged(int sc) {
emit si_scoreChanged(tr("Score: %1").arg(sc));
}
void AboutDialog::sl_levelChanged(int level) {
emit si_levelChanged(tr("Level: %1").arg(level));
}
void AboutDialog::updateTitle()
{
if (tWidget == NULL)
{
setWindowTitle(QString("%1 %2").arg(tr("About RetroShare"), Rshare::retroshareVersion(true)));
}
else
{
setWindowTitle(tr("Have fun ;-)"));
}
}
void AboutDialog::keyPressEvent(QKeyEvent *e) {
if (e->key() == Qt::Key_T) {
switchPages();
} else if (tWidget!=NULL && (e->key() == Qt::Key_P || e->key() == Qt::Key_Pause)) {
tWidget->pause();
}
QDialog::keyPressEvent(e);
}
void AboutDialog::mousePressEvent(QMouseEvent *e) {
QPoint globalPos = mapToGlobal(e->pos());
QPoint framePos = frame->mapFromGlobal(globalPos);
if (frame->contentsRect().contains(framePos)) {
switchPages();
}
QDialog::mousePressEvent(e);
}
void AboutDialog::on_help_button_clicked()
{
HelpDialog helpdlg (this);
helpdlg.exec();
}
AWidget::AWidget() {
setMouseTracking(true);
QImage image(":/images/logo/logo_info.png");
QPainter p(&image);
p.setPen(Qt::black);
QFont font = p.font();
font.setBold(true);
font.setPointSizeF(font.pointSizeF() + 2);
p.setFont(font);
/* Draw RetroShare version */
p.drawText(QRect(10, 10, width()-10, 60), QString("%1 : \n%2").arg(tr("RetroShare version"), Rshare::retroshareVersion(true)));
/* Draw Qt's version number */
p.drawText(QRect(10, 50, width()-10, 60), QString("Qt %1 : \n%2").arg(tr("version"), QT_VERSION_STR));
p.end();
image1 = image2 = image;
setFixedSize(image1.size());
int w = image1.width();
int h = image1.height();
heightField1.resize(w*h);
heightField2.resize(w*h);
density = 5;
page = 0;
startTimer(15);
} }
void AWidget::timerEvent(QTimerEvent* e) {
drawWater((QRgb*)image1.bits(), (QRgb*)image2.bits());
calcWater(page, density);
page ^= 1;
if (qrand() % 128 == 0) {
int r = 3 + qRound((double) qrand() * 4 / RAND_MAX);
int h = 300 + qrand() * 200 / RAND_MAX;
int x = 1 + r + qrand()%(image1.width() -2*r-1);
int y = 1 + r + qrand()%(image1.height()-2*r-1);
addBlob(x, y, r, h);
}
update();
QObject::timerEvent(e);
}
void AWidget::paintEvent(QPaintEvent* e) {
QWidget::paintEvent(e);
QPainter p(this);
p.drawImage(0, 0, image2);
}
void AWidget::mouseMoveEvent(QMouseEvent* e) {
QPoint point = e->pos();
addBlob(point.x() - 15,point.y(), 5, 400);
}
void AWidget::calcWater(int npage, int density) {
int w = image1.width();
int h = image1.height();
int count = w + 1;
// Set up the pointers
int *newptr;
int *oldptr;
if(npage == 0) {
newptr = &heightField1.front();
oldptr = &heightField2.front();
} else {
newptr = &heightField2.front();
oldptr = &heightField1.front();
}
for (int y = (h-1)*w; count < y; count += 2) {
for (int x = count+w-2; count < x; ++count) {
// This does the eight-pixel method. It looks much better.
int newh = ((oldptr[count + w]
+ oldptr[count - w]
+ oldptr[count + 1]
+ oldptr[count - 1]
+ oldptr[count - w - 1]
+ oldptr[count - w + 1]
+ oldptr[count + w - 1]
+ oldptr[count + w + 1]
) >> 2 ) - newptr[count];
newptr[count] = newh - (newh >> density);
}
}
}
void AWidget::addBlob(int x, int y, int radius, int height) {
int w = image1.width();
int h = image1.height();
// Set up the pointers
int *newptr;
// int *oldptr;
if (page == 0) {
newptr = &heightField1.front();
// oldptr = &heightField2.front();
} else {
newptr = &heightField2.front();
// oldptr = &heightField1.front();
}
int rquad = radius * radius;
int left=-radius, right = radius;
int top=-radius, bottom = radius;
// Perform edge clipping...
if (x - radius < 1) left -= (x-radius-1);
if (y - radius < 1) top -= (y-radius-1);
if (x + radius > w-1) right -= (x+radius-w+1);
if (y + radius > h-1) bottom-= (y+radius-h+1);
for(int cy = top; cy < bottom; ++cy) {
int cyq = cy*cy;
for(int cx = left; cx < right; ++cx) {
if (cx*cx + cyq < rquad) {
newptr[w*(cy+y) + (cx+x)] += height;
}
}
}
}
void AWidget::drawWater(QRgb* srcImage,QRgb* dstImage) {
int w = image1.width();
int h = image1.height();
int offset = w + 1;
int lIndex;
int lBreak = w * h;
int *ptr = &heightField1.front();
for (int y = (h-1)*w; offset < y; offset += 2) {
for (int x = offset+w-2; offset < x; ++offset) {
int dx = ptr[offset] - ptr[offset+1];
int dy = ptr[offset] - ptr[offset+w];
lIndex = offset + w*(dy>>3) + (dx>>3);
if(lIndex < lBreak && lIndex > 0) {
QRgb c = srcImage[lIndex];
c = shiftColor(c, dx);
dstImage[offset] = c;
}
++offset;
dx = ptr[offset] - ptr[offset+1];
dy = ptr[offset] - ptr[offset+w];
lIndex = offset + w*(dy>>3) + (dx>>3);
if(lIndex < lBreak && lIndex > 0) {
QRgb c = srcImage[lIndex];
c = shiftColor(c, dx);
dstImage[offset] = c;
}
}
}
}
//////////////////////////////////////////////////////////////////////////
// T
TBoard::TBoard(QWidget *parent) {
Q_UNUSED(parent);
setFocusPolicy(Qt::StrongFocus);
isStarted = false;
isWaitingAfterLine = false;
numLinesRemoved = 0;
numPiecesDropped = 0;
isPaused = false;
clearBoard();
nextPiece.setRandomShape();
score = 0;
level = 0;
curX = 0;
curY = 0;
maxScore = Settings->value("/about/maxsc").toInt();
}
TBoard::~TBoard() {
int oldMax = Settings->value("/about/maxsc").toInt();
int newMax = qMax(maxScore, score);
if (oldMax < newMax) {
Settings->setValue("/about/maxsc", newMax);
}
}
int TBoard::heightForWidth ( int w ) const {
return qRound(BoardHeight * float(w)/BoardWidth);
}
void TBoard::start() {
if (isPaused) {
return;
}
isStarted = true;
isWaitingAfterLine = false;
numLinesRemoved = 0;
numPiecesDropped = 0;
maxScore = qMax(score, maxScore);
score = 0;
level = 1;
clearBoard();
emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);
emit levelChanged(level);
newPiece();
timer.start(timeoutTime(), this);
}
void TBoard::pause() {
if (!isStarted) {
return;
}
isPaused = !isPaused;
if (isPaused) {
timer.stop();
} else {
timer.start(timeoutTime(), this);
}
update();
}
void TBoard::paintEvent(QPaintEvent *event) {
QWidget::paintEvent(event);
QPainter painter(this);
painter.setPen(Qt::black);
painter.drawRect(frameRect());
QRect rect = boardRect();
painter.fillRect(rect, Qt::white);
if (isPaused) {
painter.drawText(rect, Qt::AlignCenter, tr("Pause"));
return;
}
int boardTop = rect.bottom() - BoardHeight*squareHeight();
for (int i = 0; i < BoardHeight; ++i) {
for (int j = 0; j < BoardWidth; ++j) {
TPiece::Shape shape = shapeAt(j, BoardHeight - i - 1);
if (shape != TPiece::NoShape) {
drawSquare(painter, rect.left() + j * squareWidth(), boardTop + i * squareHeight(), shape);
}
}
}
if (curPiece.shape() != TPiece::NoShape) {
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY - curPiece.y(i);
drawSquare(painter, rect.left() + x * squareWidth(), boardTop + (BoardHeight - y - 1) * squareHeight(), curPiece.shape());
}
}
}
void TBoard::keyPressEvent(QKeyEvent *event) {
if (!isStarted || isPaused || curPiece.shape() == TPiece::NoShape) {
QWidget::keyPressEvent(event);
return;
}
switch (event->key()) {
case Qt::Key_Left:
tryMove(curPiece, curX - 1, curY);
break;
case Qt::Key_Right:
tryMove(curPiece, curX + 1, curY);
break;
case Qt::Key_Down:
tryMove(curPiece.rotatedRight(), curX, curY);
break;
case Qt::Key_Up:
tryMove(curPiece.rotatedLeft(), curX, curY);
break;
case Qt::Key_Space:
dropDown();
break;
case Qt::Key_Control:
oneLineDown();
break;
default:
QWidget::keyPressEvent(event);
}
}
void TBoard::timerEvent(QTimerEvent *event) {
if (event->timerId() == timer.timerId()) {
if (isWaitingAfterLine) {
isWaitingAfterLine = false;
newPiece();
timer.start(timeoutTime(), this);
} else {
oneLineDown();
}
} else {
QWidget::timerEvent(event);
}
}
void TBoard::clearBoard() {
for (int i = 0; i < BoardHeight * BoardWidth; ++i) {
board[i] = TPiece::NoShape;
}
}
void TBoard::dropDown() {
int dropHeight = 0;
int newY = curY;
while (newY > 0) {
if (!tryMove(curPiece, curX, newY - 1)) {
break;
}
newY--;
++dropHeight;
}
pieceDropped(dropHeight);
}
void TBoard::oneLineDown() {
if (!tryMove(curPiece, curX, curY - 1))
pieceDropped(0);
}
void TBoard::pieceDropped(int dropHeight) {
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY - curPiece.y(i);
shapeAt(x, y) = curPiece.shape();
}
++numPiecesDropped;
if (numPiecesDropped % 50 == 0) {
++level;
timer.start(timeoutTime(), this);
emit levelChanged(level);
}
score += dropHeight + 7;
emit scoreChanged(score);
removeFullLines();
if (!isWaitingAfterLine) {
newPiece();
}
}
void TBoard::removeFullLines() {
int numFullLines = 0;
for (int i = BoardHeight - 1; i >= 0; --i) {
bool lineIsFull = true;
for (int j = 0; j < BoardWidth; ++j) {
if (shapeAt(j, i) == TPiece::NoShape) {
lineIsFull = false;
break;
}
}
if (lineIsFull) {
++numFullLines;
for (int k = i; k < BoardHeight - 1; ++k) {
for (int j = 0; j < BoardWidth; ++j) {
shapeAt(j, k) = shapeAt(j, k + 1);
}
}
for (int j = 0; j < BoardWidth; ++j) {
shapeAt(j, BoardHeight - 1) = TPiece::NoShape;
}
}
}
if (numFullLines > 0) {
numLinesRemoved += numFullLines;
score += 10 * numFullLines;
emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);
timer.start(500, this);
isWaitingAfterLine = true;
curPiece.setShape(TPiece::NoShape);
update();
}
}
void TBoard::newPiece() {
curPiece = nextPiece;
nextPiece.setRandomShape();
showNextPiece();
curX = BoardWidth / 2 + 1;
curY = BoardHeight - 1 + curPiece.minY();
if (!tryMove(curPiece, curX, curY)) {
curPiece.setShape(TPiece::NoShape);
timer.stop();
isStarted = false;
}
}
void TBoard::showNextPiece() {
if (!nextPieceLabel) {
return;
}
int dx = nextPiece.maxX() - nextPiece.minX() + 1;
int dy = nextPiece.maxY() - nextPiece.minY() + 1;
QPixmap pixmap(dx * squareWidth(), dy * squareHeight());
QPainter painter(&pixmap);
painter.fillRect(pixmap.rect(), nextPieceLabel->palette().background());
for (int i = 0; i < 4; ++i) {
int x = nextPiece.x(i) - nextPiece.minX();
int y = nextPiece.y(i) - nextPiece.minY();
drawSquare(painter, x * squareWidth(), y * squareHeight(), nextPiece.shape());
}
nextPieceLabel->setPixmap(pixmap);
}
bool TBoard::tryMove(const TPiece &newPiece, int newX, int newY) {
for (int i = 0; i < 4; ++i) {
int x = newX + newPiece.x(i);
int y = newY - newPiece.y(i);
if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight) {
return false;
}
if (shapeAt(x, y) != TPiece::NoShape) {
return false;
}
}
curPiece = newPiece;
curX = newX;
curY = newY;
update();
return true;
}
void TBoard::drawSquare(QPainter &painter, int x, int y, TPiece::Shape shape) {
static const QRgb colorTable[8] = { 0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00};
QColor color = colorTable[int(shape)];
painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2, color);
painter.setPen(color.light());
painter.drawLine(x, y + squareHeight() - 1, x, y);
painter.drawLine(x, y, x + squareWidth() - 1, y);
painter.setPen(color.dark());
painter.drawLine(x + 1, y + squareHeight() - 1, x + squareWidth() - 1, y + squareHeight() - 1);
painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1, x + squareWidth() - 1, y + 1);
}
void TPiece::setRandomShape() {
setShape(TPiece::Shape(qrand() % 7 + 1));
}
void TPiece::setShape(TPiece::Shape shape) {
static const int coordsTable[8][4][2] = {
{ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } },
{ { 0, -1 }, { 0, 0 }, { -1, 0 }, { -1, 1 } },
{ { 0, -1 }, { 0, 0 }, { 1, 0 }, { 1, 1 } },
{ { 0, -1 }, { 0, 0 }, { 0, 1 }, { 0, 2 } },
{ { -1, 0 }, { 0, 0 }, { 1, 0 }, { 0, 1 } },
{ { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } },
{ { -1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } },
{ { 1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } }
};
for (int i = 0; i < 4 ; i++) {
for (int j = 0; j < 2; ++j) {
coords[i][j] = coordsTable[shape][i][j];
}
}
pieceShape = shape;
}
int TPiece::minX() const {
int min = coords[0][0];
for (int i = 1; i < 4; ++i) {
min = qMin(min, coords[i][0]);
}
return min;
}
int TPiece::maxX() const {
int max = coords[0][0];
for (int i = 1; i < 4; ++i) {
max = qMax(max, coords[i][0]);
}
return max;
}
int TPiece::minY() const {
int min = coords[0][1];
for (int i = 1; i < 4; ++i) {
min = qMin(min, coords[i][1]);
}
return min;
}
int TPiece::maxY() const {
int max = coords[0][1];
for (int i = 1; i < 4; ++i) {
max = qMax(max, coords[i][1]);
}
return max;
}
TPiece TPiece::rotatedLeft() const {
if (pieceShape == SquareShape) {
return *this;
}
TPiece result;
result.pieceShape = pieceShape;
for (int i = 0; i < 4; ++i) {
result.setX(i, y(i));
result.setY(i, -x(i));
}
return result;
}
TPiece TPiece::rotatedRight() const {
if (pieceShape == SquareShape) {
return *this;
}
TPiece result;
result.pieceShape = pieceShape;
for (int i = 0; i < 4; ++i) {
result.setX(i, -y(i));
result.setY(i, x(i));
}
return result;
}
NextPieceLabel::NextPieceLabel( QWidget* parent /* = 0*/ ) : QLabel(parent)
{
QPalette p = palette();
p.setColor(QPalette::Background, Qt::white);
setPalette(p);
setFrameShape(QFrame::Box);
setAlignment(Qt::AlignCenter);
setAutoFillBackground(true);
}
static QString addLibraries(const std::string &name, const std::list<RsLibraryInfo> &libraries)
{
QString mTextEdit;
mTextEdit+=QString::fromUtf8(name.c_str());
mTextEdit+="\n";
std::list<RsLibraryInfo>::const_iterator libraryIt;
for (libraryIt = libraries.begin(); libraryIt != libraries.end(); ++libraryIt) {
mTextEdit+=" - ";
mTextEdit+=QString::fromUtf8(libraryIt->mName.c_str());
mTextEdit+=": ";
mTextEdit+=QString::fromUtf8(libraryIt->mVersion.c_str());
mTextEdit+="\n";
}
mTextEdit+="\n";
return mTextEdit;
}
void AboutDialog::on_copy_button_clicked()
{
QString verInfo;
QString rsVerString = "RetroShare Version: ";
rsVerString+=Rshare::retroshareVersion(true);
verInfo+=rsVerString;
verInfo+="\n";
#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0)
verInfo+=QSysInfo::prettyProductName();
#endif
#else
#ifdef Q_OS_LINUX
verInfo+="Linux";
#endif
#ifdef Q_OS_WIN
verInfo+="Windows";
#endif
#ifdef Q_OS_MAC
verInfo+="Mac";
#endif
#endif
verInfo+=" ";
QString qtver = QString("QT ")+QT_VERSION_STR;
verInfo+=qtver;
verInfo+="\n\n";
/* Add version numbers of libretroshare */
std::list<RsLibraryInfo> libraries;
RsControl::instance()->getLibraries(libraries);
verInfo+=addLibraries("libretroshare", libraries);
#ifdef ENABLE_WEBUI
/* Add version numbers of RetroShare */
// Add versions here. Find a better place.
libraries.clear();
libraries.push_back(RsLibraryInfo("Libmicrohttpd", MHD_get_version()));
verInfo+=addLibraries("RetroShare", libraries);
#endif // ENABLE_WEBUI
/* Add version numbers of plugins */
if (rsPlugins) {
for (int i = 0; i < rsPlugins->nbPlugins(); ++i) {
RsPlugin *plugin = rsPlugins->plugin(i);
if (plugin) {
libraries.clear();
plugin->getLibraries(libraries);
verInfo+=addLibraries(plugin->getPluginName(), libraries);
}
}
}
QApplication::clipboard()->setText(verInfo);
}

View File

@ -20,186 +20,17 @@
* Boston, MA 02110-1301, USA. * Boston, MA 02110-1301, USA.
****************************************************************/ ****************************************************************/
#ifndef _GB2_ABOUT_DIALOG_ #pragma once
#define _GB2_ABOUT_DIALOG_
#include "ui_AboutDialog.h" #include "ui_AboutDialog.h"
#include "AboutWidget.h"
#include <QBasicTimer>
#include <QPointer>
#include <QDialog> #include <QDialog>
#include <QLabel>
#include <QPaintEvent>
#include <QKeyEvent>
#include <QMouseEvent>
class AWidget;
class TBoard;
class NextPieceLabel;
class AboutDialog : public QDialog, public Ui::AboutDialog class AboutDialog : public QDialog, public Ui::AboutDialog
{ {
Q_OBJECT
public: public:
AboutDialog(QWidget *parent = 0); AboutDialog(QWidget *parent = NULL);
virtual ~AboutDialog() {}
private slots:
void sl_scoreChanged(int);
void sl_levelChanged(int);
void on_help_button_clicked();
void on_copy_button_clicked();
signals:
void si_scoreChanged(QString);
void si_maxScoreChanged(QString);
void si_levelChanged(QString);
protected:
void keyPressEvent(QKeyEvent *event);
void mousePressEvent(QMouseEvent *event);
private:
void switchPages();
void installAWidget();
void installTWidget();
void updateTitle();
TBoard* tWidget;
}; };
//////////////////////////////////////////////////////////////////////////
// A
class AWidget : public QWidget {
Q_OBJECT
public:
AWidget();
protected:
void timerEvent(QTimerEvent* e);
void paintEvent(QPaintEvent* e);
void mouseMoveEvent(QMouseEvent* e);
private:
void calcWater(int npage, int density);
void addBlob(int x, int y, int radius, int height);
void drawWater(QRgb* srcImage, QRgb* dstImage);
static QRgb shiftColor(QRgb color,int shift) {
return qRgb(qBound(0, qRed(color) - shift, 255),
qBound(0, qGreen(color) - shift,255),
qBound(0, qBlue(color) - shift, 255));
}
int page;
int density;
QVector<int> heightField1;
QVector<int> heightField2;
QImage image1;
QImage image2;
};
//////////////////////////////////////////////////////////////////////////
// T
class TPiece {
public:
enum Shape { NoShape, ZShape, SShape, LineShape, TShape, SquareShape, LShape, MirroredLShape };
TPiece() { setShape(NoShape); }
void setRandomShape();
void setShape(Shape shape);
Shape shape() const { return pieceShape; }
int x(int index) const { return coords[index][0]; }
int y(int index) const { return coords[index][1]; }
int minX() const;
int maxX() const;
int minY() const;
int maxY() const;
TPiece rotatedLeft() const;
TPiece rotatedRight() const;
private:
void setX(int index, int x) { coords[index][0] = x; }
void setY(int index, int y) { coords[index][1] = y; }
Shape pieceShape;
int coords[4][2];
};
class TBoard : public QWidget {
Q_OBJECT
public:
TBoard(QWidget *parent = 0);
~TBoard();
int heightForWidth ( int w ) const;
int getScore() const {return score;}
int getMaxScore() const {return qMax(maxScore, score);}
int getLevel() const {return level;}
void setNextPieceLabel(QLabel *label) {nextPieceLabel = label;}
int squareWidth() const { return boardRect().width() / BoardWidth; }
int squareHeight() const { return boardRect().height() / BoardHeight; }
public slots:
void start();
void pause();
signals:
void scoreChanged(int score);
void levelChanged(int level);
void linesRemovedChanged(int numLines);
protected:
void paintEvent(QPaintEvent *event);
void keyPressEvent(QKeyEvent *event);
void timerEvent(QTimerEvent *event);
private:
enum { BoardWidth = 10, BoardHeight = 22 };
TPiece::Shape &shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }
int timeoutTime() const { return 1000 / (1 + level); }
QRect boardRect() const {return QRect(1, 1, width()-2, height()-2);}
QRect frameRect() const {return QRect(0, 0, width()-1, height()-1);}
void clearBoard();
void dropDown();
void oneLineDown();
void pieceDropped(int dropHeight);
void removeFullLines();
void newPiece();
void showNextPiece();
bool tryMove(const TPiece &newPiece, int newX, int newY);
void drawSquare(QPainter &painter, int x, int y, TPiece::Shape shape);
QBasicTimer timer;
QPointer<QLabel> nextPieceLabel;
bool isStarted;
bool isPaused;
bool isWaitingAfterLine;
TPiece curPiece;
TPiece nextPiece;
int curX;
int curY;
int numLinesRemoved;
int numPiecesDropped;
int score;
int maxScore;
int level;
TPiece::Shape board[BoardWidth * BoardHeight];
};
class NextPieceLabel : public QLabel {
public:
NextPieceLabel(QWidget* parent = 0);
};
#endif

View File

@ -6,7 +6,7 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>271</width> <width>422</width>
<height>376</height> <height>376</height>
</rect> </rect>
</property> </property>
@ -36,85 +36,20 @@
<number>9</number> <number>9</number>
</property> </property>
<item> <item>
<widget class="QFrame" name="frame"> <widget class="AboutWidget" name="widget" native="true"/>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="help_button">
<property name="text">
<string>About</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="copy_button">
<property name="text">
<string>Copy Info</string>
</property>
<property name="icon">
<iconset resource="images.qrc">
<normaloff>:/images/copy.png</normaloff>:/images/copy.png</iconset>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="close_button">
<property name="text">
<string>close</string>
</property>
</widget>
</item>
</layout>
</item> </item>
</layout> </layout>
</widget> </widget>
<customwidgets>
<customwidget>
<class>AboutWidget</class>
<extends>QWidget</extends>
<header location="global">gui/AboutWidget.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources> <resources>
<include location="images.qrc"/> <include location="images.qrc"/>
</resources> </resources>
<connections> <connections/>
<connection>
<sender>close_button</sender>
<signal>clicked()</signal>
<receiver>AboutDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>243</x>
<y>281</y>
</hint>
<hint type="destinationlabel">
<x>145</x>
<y>187</y>
</hint>
</hints>
</connection>
</connections>
</ui> </ui>

View File

@ -0,0 +1,989 @@
/****************************************************************
* This file is distributed under the following license:
*
* Copyright (c) 2009, RetroShare Team
* Copyright (C) 2008 Unipro, Russia (http://ugene.unipro.ru)
*
* 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 Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
****************************************************************/
#include "AboutDialog.h"
#include "HelpDialog.h"
#include "rshare.h"
#include <retroshare/rsiface.h>
#include <retroshare/rsplugin.h>
#include <retroshare/rsdisc.h>
#include <retroshare/rspeers.h>
#include "settings/rsharesettings.h"
#ifdef ENABLE_WEBUI
#include <microhttpd.h>
#endif
#include <QClipboard>
#include <QSysInfo>
#include <QHBoxLayout>
#include <QPainter>
#include <QBrush>
#include <QMessageBox>
#include <QStyle>
#include <assert.h>
AboutWidget::AboutWidget(QWidget* parent)
: QWidget(parent)
{
setupUi(this);
QHBoxLayout* l = new QHBoxLayout();
l->setMargin(0);
l->addStretch(1);
l->addStretch(1);
frame->setContentsMargins(0, 0, 0, 0);
frame->setLayout(l);
tWidget = NULL;
aWidget = NULL;
installAWidget();
updateTitle();
QObject::connect(help_button,SIGNAL(clicked()),this,SLOT(on_help_button_clicked()));
QObject::connect(copy_button,SIGNAL(clicked()),this,SLOT(on_copy_button_clicked()));
}
void AboutWidget::installAWidget() {
assert(tWidget == NULL);
aWidget = new AWidget();
QVBoxLayout* l = (QVBoxLayout*)frame->layout();
l->insertWidget(0, aWidget);
l->setStretchFactor(aWidget, 100);
aWidget->setFocus();
delete tWidget ;
tWidget = NULL;
}
void AboutWidget::installTWidget() {
assert(tWidget == NULL);
tWidget = new TBoard();
QLabel* npLabel = new NextPieceLabel(tWidget);
tWidget->setNextPieceLabel(npLabel);
QWidget* pan = new QWidget();
QVBoxLayout* vl = new QVBoxLayout(pan);
QLabel* topRecLabel = new QLabel(tr("Max score: %1").arg(tWidget->getMaxScore()));
QLabel* scoreLabel = new QLabel(pan);
QLabel* levelLabel = new QLabel(pan);
vl->addStretch();
vl->addWidget(topRecLabel);
vl->addStretch();
vl->addWidget(npLabel);
vl->addStretch();
vl->addWidget(scoreLabel);
vl->addWidget(levelLabel);
vl->addStretch();
QHBoxLayout* l = (QHBoxLayout*)frame->layout();
l->insertWidget(0, pan);
l->insertWidget(0, tWidget);
QRect cRect = frame->contentsRect();
int height = tWidget->heightForWidth(cRect.width());
tWidget->setFixedSize(cRect.width() * cRect.height() / height, cRect.height());
npLabel->setFixedSize(tWidget->squareWidth()*4, tWidget->squareHeight()*5);
l->setStretchFactor(tWidget, 100);
connect(tWidget, SIGNAL(scoreChanged(int)), SLOT(sl_scoreChanged(int)));
connect(tWidget, SIGNAL(levelChanged(int)), SLOT(sl_levelChanged(int)));
connect(this, SIGNAL(si_scoreChanged(QString)), scoreLabel, SLOT(setText(QString)));
connect(this, SIGNAL(si_levelChanged(QString)), levelLabel, SLOT(setText(QString)));
tWidget->setFocus();
tWidget->start();
delete aWidget ;
aWidget = NULL;
}
void AboutWidget::switchPages() {
QLayoutItem* li = NULL;
QLayout* l = frame->layout();
while ((li = l->takeAt(0)) && li->widget()) {
li->widget()->deleteLater();
}
if (tWidget==NULL) {
installTWidget();
} else {
tWidget = NULL;
installAWidget();
}
updateTitle();
}
void AboutWidget::sl_scoreChanged(int sc) {
emit si_scoreChanged(tr("Score: %1").arg(sc));
}
void AboutWidget::sl_levelChanged(int level) {
emit si_levelChanged(tr("Level: %1").arg(level));
}
void AboutWidget::updateTitle()
{
if (tWidget == NULL)
{
setWindowTitle(QString("%1 %2").arg(tr("About RetroShare"), Rshare::retroshareVersion(true)));
}
else
{
setWindowTitle(tr("Have fun ;-)"));
}
}
//void AboutWidget::keyPressEvent(QKeyEvent *e) {
// if(aWidget != NULL)
// aWidget->keyPressEvent(e) ;
//}
void AboutWidget::mousePressEvent(QMouseEvent *e)
{
QPoint globalPos = mapToGlobal(e->pos());
QPoint framePos = frame->mapFromGlobal(globalPos);
if (frame->contentsRect().contains(framePos)) {
{
if(e->modifiers() & Qt::ControlModifier)
switchPages();
else
{
if(aWidget)
aWidget->switchState();
}
}
}
QWidget::mousePressEvent(e);
}
void AboutWidget::on_help_button_clicked()
{
HelpDialog helpdlg (this);
helpdlg.exec();
}
void AWidget::switchState()
{
mState = 1 - mState ;
if(mState == 1)
{
mStep = 1.0f ;
initGoL();
drawBitField();
mTimerId = startTimer(50);
}
else
killTimer(mTimerId);
update();
}
void AWidget::resizeEvent(QResizeEvent *e)
{
mImagesReady = false ;
}
void AWidget::initImages()
{
if(width() == 0) return ;
if(height() == 0) return ;
image1 = QImage(width(),height(),QImage::Format_ARGB32);
image1.fill(palette().color(QPalette::Background));
//QImage image(":/images/logo/logo_info.png");
QPixmap image(":/images/logo/logo_splash.png");
QPainter p(&image1);
p.setPen(Qt::black);
QFont font = p.font();
font.setBold(true);
font.setPointSizeF(font.pointSizeF() + 2);
p.setFont(font);
//p.drawPixmap(QRect(10, 10, width()-10, 60), image);
/* Draw RetroShare version */
p.drawText(QPointF(10, 50), QString("%1 : %2").arg(tr("Retroshare version"), Rshare::retroshareVersion(true)));
/* Draw Qt's version number */
p.drawText(QPointF(10, 90), QString("Qt %1 : %2").arg(tr("version"), QT_VERSION_STR));
p.end();
// setFixedSize(image1.size());
image2 = image1 ;
mImagesReady = true ;
drawBitField();
update() ;
}
void AWidget::initGoL()
{
int w = image1.width();
int h = image1.height();
int s = mStep ; // pixels per cell
int bw = w/s ;
int bh = h/s ;
bitfield1.clear();
bitfield1.resize(bw*bh,0);
for(int i=0;i<bw;++i)
for(int j=0;j<bh;++j)
if((image1.pixel((i+0.0)*s,(j+0.0)*s) & 0xff) < 0x80)
bitfield1[i+bw*j] = 1 ;
}
void AWidget::drawBitField()
{
image2.fill(palette().color(QPalette::Background));
QPainter p(&image2) ;
p.setPen(QColor(200,200,200));
int w = image1.width();
int h = image1.height();
int s = mStep ; // pixels per cell
int bw = w/s ;
int bh = h/s ;
if(bitfield1.size() != (unsigned int)bw*bh)
initGoL();
if(mStep >= mMaxStep)
{
for(int i=0;i<=bh;++i) p.drawLine(0,i*s,bw*s,i*s) ;
for(int i=0;i<=bw;++i) p.drawLine(i*s,0,i*s,bh*s) ;
}
p.setPen(Qt::black);
for(int i=0;i<bw;++i)
for(int j=0;j<bh;++j)
if(bitfield1[i+bw*j] == 1)
if(mStep >= mMaxStep)
p.fillRect(QRect(i*s+1,j*s+1,s-1,s-1),QBrush(QColor(50,50,50)));
else
p.fillRect(QRect(i*s,j*s,s,s),QBrush(QColor(50,50,50)));
p.end();
}
AWidget::AWidget() {
setMouseTracking(true);
density = 5;
page = 0;
mMaxStep = QFontMetricsF(font()).width(' ') ;
mStep = 1.0f ;
mState = 0 ;
mImagesReady = false ;
// startTimer(15);
}
void AWidget::computeNextState()
{
int w = image1.width();
int h = image1.height();
int s = mStep ; // pixels per cell
int bw = w/s ;
int bh = h/s ;
if(bitfield1.size() != (unsigned int)bw*bh)
{
initGoL();
}
bitfield2.clear();
bitfield2.resize(bw*bh,0);
for(int i=0;i<bw;++i)
for(int j=0;j<h;++j)
if(bitfield1[i+bw*j] == 1)
for(int k=-1;k<2;++k)
for(int l=-1;l<2;++l)
if(k!=0 || l!=0)
++bitfield2[ ((i+k+bw)%bw )+ ((j+l+bh)%bh )*bw];
for(int i=0;i<bh*bw;++i)
if(bitfield1[i] == 1)
if(bitfield2[i] == 2 || bitfield2[i] == 3)
bitfield1[i] = 1;
else
bitfield1[i] = 0;
else
if(bitfield2[i] == 3)
bitfield1[i] = 1 ;
}
void AWidget::timerEvent(QTimerEvent* e)
{
if(mStep >= mMaxStep)
computeNextState();
else
{
initGoL();
mStep+=0.2f ;
}
drawBitField();
#ifdef REMOVED
drawWater((QRgb*)image1.bits(), (QRgb*)image2.bits());
calcWater(page, density);
page ^= 1;
if (qrand() % 128 == 0) {
int r = 3 + qRound((double) qrand() * 4 / RAND_MAX);
int h = 300 + qrand() * 200 / RAND_MAX;
int x = 1 + r + qrand()%(image1.width() -2*r-1);
int y = 1 + r + qrand()%(image1.height()-2*r-1);
addBlob(x, y, r, h);
}
#endif
update();
QObject::timerEvent(e);
}
void AWidget::paintEvent(QPaintEvent* e)
{
QWidget::paintEvent(e);
if(!mImagesReady) initImages();
switch(mState)
{
default:
case 0:
{
QPainter p(this);
p.drawImage(0, 0, image1);
}
break;
case 1:
{
QPainter p(this);
p.drawImage(0, 0, image2);
}
break;
}
}
#ifdef REMOVED
void AWidget::mouseMoveEvent(QMouseEvent* e) {
QPoint point = e->pos();
addBlob(point.x() - 15,point.y(), 5, 400);
}
void AWidget::calcWater(int npage, int density) {
int w = image1.width();
int h = image1.height();
int count = w + 1;
// Set up the pointers
int *newptr;
int *oldptr;
if(npage == 0) {
newptr = &bitfield1.front();
oldptr = &bitfield2.front();
} else {
newptr = &bitfield2.front();
oldptr = &bitfield1.front();
}
for (int y = (h-1)*w; count < y; count += 2) {
for (int x = count+w-2; count < x; ++count) {
// This does the eight-pixel method. It looks much better.
int newh = ((oldptr[count + w]
+ oldptr[count - w]
+ oldptr[count + 1]
+ oldptr[count - 1]
+ oldptr[count - w - 1]
+ oldptr[count - w + 1]
+ oldptr[count + w - 1]
+ oldptr[count + w + 1]
) >> 2 ) - newptr[count];
newptr[count] = newh - (newh >> density);
}
}
}
void AWidget::addBlob(int x, int y, int radius, int height) {
int w = image1.width();
int h = image1.height();
// Set up the pointers
int *newptr;
// int *oldptr;
if (page == 0) {
newptr = &bitfield1.front();
// oldptr = &heightField2.front();
} else {
newptr = &bitfield2.front();
// oldptr = &heightField1.front();
}
int rquad = radius * radius;
int left=-radius, right = radius;
int top=-radius, bottom = radius;
// Perform edge clipping...
if (x - radius < 1) left -= (x-radius-1);
if (y - radius < 1) top -= (y-radius-1);
if (x + radius > w-1) right -= (x+radius-w+1);
if (y + radius > h-1) bottom-= (y+radius-h+1);
for(int cy = top; cy < bottom; ++cy) {
int cyq = cy*cy;
for(int cx = left; cx < right; ++cx) {
if (cx*cx + cyq < rquad) {
newptr[w*(cy+y) + (cx+x)] += height;
}
}
}
}
void AWidget::drawWater(QRgb* srcImage,QRgb* dstImage) {
int w = image1.width();
int h = image1.height();
int offset = w + 1;
int lIndex;
int lBreak = w * h;
int *ptr = &bitfield1.front();
for (int y = (h-1)*w; offset < y; offset += 2) {
for (int x = offset+w-2; offset < x; ++offset) {
int dx = ptr[offset] - ptr[offset+1];
int dy = ptr[offset] - ptr[offset+w];
lIndex = offset + w*(dy>>3) + (dx>>3);
if(lIndex < lBreak && lIndex > 0) {
QRgb c = srcImage[lIndex];
c = shiftColor(c, dx);
dstImage[offset] = c;
}
++offset;
dx = ptr[offset] - ptr[offset+1];
dy = ptr[offset] - ptr[offset+w];
lIndex = offset + w*(dy>>3) + (dx>>3);
if(lIndex < lBreak && lIndex > 0) {
QRgb c = srcImage[lIndex];
c = shiftColor(c, dx);
dstImage[offset] = c;
}
}
}
}
#endif
//////////////////////////////////////////////////////////////////////////
// T
TBoard::TBoard(QWidget *parent) {
Q_UNUSED(parent);
setFocusPolicy(Qt::StrongFocus);
isStarted = false;
isWaitingAfterLine = false;
numLinesRemoved = 0;
numPiecesDropped = 0;
isPaused = false;
clearBoard();
nextPiece.setRandomShape();
score = 0;
level = 0;
curX = 0;
curY = 0;
maxScore = Settings->value("/about/maxsc").toInt();
}
TBoard::~TBoard() {
int oldMax = Settings->value("/about/maxsc").toInt();
int newMax = qMax(maxScore, score);
if (oldMax < newMax) {
Settings->setValue("/about/maxsc", newMax);
}
}
int TBoard::heightForWidth ( int w ) const {
return qRound(BoardHeight * float(w)/BoardWidth);
}
void TBoard::start() {
if (isPaused) {
return;
}
isStarted = true;
isWaitingAfterLine = false;
numLinesRemoved = 0;
numPiecesDropped = 0;
maxScore = qMax(score, maxScore);
score = 0;
level = 1;
clearBoard();
emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);
emit levelChanged(level);
newPiece();
timer.start(timeoutTime(), this);
}
void TBoard::pause() {
if (!isStarted) {
return;
}
isPaused = !isPaused;
if (isPaused) {
timer.stop();
} else {
timer.start(timeoutTime(), this);
}
update();
}
void TBoard::paintEvent(QPaintEvent *event) {
QWidget::paintEvent(event);
QPainter painter(this);
painter.setPen(Qt::black);
painter.drawRect(frameRect());
QRect rect = boardRect();
painter.fillRect(rect, Qt::white);
if (isPaused) {
painter.drawText(rect, Qt::AlignCenter, tr("Pause"));
return;
}
int boardTop = rect.bottom() - BoardHeight*squareHeight();
for (int i = 0; i < BoardHeight; ++i) {
for (int j = 0; j < BoardWidth; ++j) {
TPiece::Shape shape = shapeAt(j, BoardHeight - i - 1);
if (shape != TPiece::NoShape) {
drawSquare(painter, rect.left() + j * squareWidth(), boardTop + i * squareHeight(), shape);
}
}
}
if (curPiece.shape() != TPiece::NoShape) {
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY - curPiece.y(i);
drawSquare(painter, rect.left() + x * squareWidth(), boardTop + (BoardHeight - y - 1) * squareHeight(), curPiece.shape());
}
}
}
void TBoard::keyPressEvent(QKeyEvent *event) {
if (!isStarted || isPaused || curPiece.shape() == TPiece::NoShape) {
QWidget::keyPressEvent(event);
return;
}
switch (event->key()) {
case Qt::Key_Left:
tryMove(curPiece, curX - 1, curY);
break;
case Qt::Key_Right:
tryMove(curPiece, curX + 1, curY);
break;
case Qt::Key_Down:
tryMove(curPiece.rotatedRight(), curX, curY);
break;
case Qt::Key_Up:
tryMove(curPiece.rotatedLeft(), curX, curY);
break;
case Qt::Key_Space:
dropDown();
break;
case Qt::Key_Control:
oneLineDown();
break;
default:
QWidget::keyPressEvent(event);
}
}
void TBoard::timerEvent(QTimerEvent *event) {
if (event->timerId() == timer.timerId()) {
if (isWaitingAfterLine) {
isWaitingAfterLine = false;
newPiece();
timer.start(timeoutTime(), this);
} else {
oneLineDown();
}
} else {
QWidget::timerEvent(event);
}
}
void TBoard::clearBoard() {
for (int i = 0; i < BoardHeight * BoardWidth; ++i) {
board[i] = TPiece::NoShape;
}
}
void TBoard::dropDown() {
int dropHeight = 0;
int newY = curY;
while (newY > 0) {
if (!tryMove(curPiece, curX, newY - 1)) {
break;
}
newY--;
++dropHeight;
}
pieceDropped(dropHeight);
}
void TBoard::oneLineDown() {
if (!tryMove(curPiece, curX, curY - 1))
pieceDropped(0);
}
void TBoard::pieceDropped(int dropHeight) {
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY - curPiece.y(i);
shapeAt(x, y) = curPiece.shape();
}
++numPiecesDropped;
if (numPiecesDropped % 50 == 0) {
++level;
timer.start(timeoutTime(), this);
emit levelChanged(level);
}
score += dropHeight + 7;
emit scoreChanged(score);
removeFullLines();
if (!isWaitingAfterLine) {
newPiece();
}
}
void TBoard::removeFullLines() {
int numFullLines = 0;
for (int i = BoardHeight - 1; i >= 0; --i) {
bool lineIsFull = true;
for (int j = 0; j < BoardWidth; ++j) {
if (shapeAt(j, i) == TPiece::NoShape) {
lineIsFull = false;
break;
}
}
if (lineIsFull) {
++numFullLines;
for (int k = i; k < BoardHeight - 1; ++k) {
for (int j = 0; j < BoardWidth; ++j) {
shapeAt(j, k) = shapeAt(j, k + 1);
}
}
for (int j = 0; j < BoardWidth; ++j) {
shapeAt(j, BoardHeight - 1) = TPiece::NoShape;
}
}
}
if (numFullLines > 0) {
numLinesRemoved += numFullLines;
score += 10 * numFullLines;
emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);
timer.start(500, this);
isWaitingAfterLine = true;
curPiece.setShape(TPiece::NoShape);
update();
}
}
void TBoard::newPiece() {
curPiece = nextPiece;
nextPiece.setRandomShape();
showNextPiece();
curX = BoardWidth / 2 + 1;
curY = BoardHeight - 1 + curPiece.minY();
if (!tryMove(curPiece, curX, curY)) {
curPiece.setShape(TPiece::NoShape);
timer.stop();
isStarted = false;
}
}
void TBoard::showNextPiece() {
if (!nextPieceLabel) {
return;
}
int dx = nextPiece.maxX() - nextPiece.minX() + 1;
int dy = nextPiece.maxY() - nextPiece.minY() + 1;
QPixmap pixmap(dx * squareWidth(), dy * squareHeight());
QPainter painter(&pixmap);
painter.fillRect(pixmap.rect(), nextPieceLabel->palette().background());
for (int i = 0; i < 4; ++i) {
int x = nextPiece.x(i) - nextPiece.minX();
int y = nextPiece.y(i) - nextPiece.minY();
drawSquare(painter, x * squareWidth(), y * squareHeight(), nextPiece.shape());
}
nextPieceLabel->setPixmap(pixmap);
}
bool TBoard::tryMove(const TPiece &newPiece, int newX, int newY) {
for (int i = 0; i < 4; ++i) {
int x = newX + newPiece.x(i);
int y = newY - newPiece.y(i);
if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight) {
return false;
}
if (shapeAt(x, y) != TPiece::NoShape) {
return false;
}
}
curPiece = newPiece;
curX = newX;
curY = newY;
update();
return true;
}
void TBoard::drawSquare(QPainter &painter, int x, int y, TPiece::Shape shape) {
static const QRgb colorTable[8] = { 0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00};
QColor color = colorTable[int(shape)];
painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2, color);
painter.setPen(color.light());
painter.drawLine(x, y + squareHeight() - 1, x, y);
painter.drawLine(x, y, x + squareWidth() - 1, y);
painter.setPen(color.dark());
painter.drawLine(x + 1, y + squareHeight() - 1, x + squareWidth() - 1, y + squareHeight() - 1);
painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1, x + squareWidth() - 1, y + 1);
}
void TPiece::setRandomShape() {
setShape(TPiece::Shape(qrand() % 7 + 1));
}
void TPiece::setShape(TPiece::Shape shape) {
static const int coordsTable[8][4][2] = {
{ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } },
{ { 0, -1 }, { 0, 0 }, { -1, 0 }, { -1, 1 } },
{ { 0, -1 }, { 0, 0 }, { 1, 0 }, { 1, 1 } },
{ { 0, -1 }, { 0, 0 }, { 0, 1 }, { 0, 2 } },
{ { -1, 0 }, { 0, 0 }, { 1, 0 }, { 0, 1 } },
{ { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } },
{ { -1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } },
{ { 1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } }
};
for (int i = 0; i < 4 ; i++) {
for (int j = 0; j < 2; ++j) {
coords[i][j] = coordsTable[shape][i][j];
}
}
pieceShape = shape;
}
int TPiece::minX() const {
int min = coords[0][0];
for (int i = 1; i < 4; ++i) {
min = qMin(min, coords[i][0]);
}
return min;
}
int TPiece::maxX() const {
int max = coords[0][0];
for (int i = 1; i < 4; ++i) {
max = qMax(max, coords[i][0]);
}
return max;
}
int TPiece::minY() const {
int min = coords[0][1];
for (int i = 1; i < 4; ++i) {
min = qMin(min, coords[i][1]);
}
return min;
}
int TPiece::maxY() const {
int max = coords[0][1];
for (int i = 1; i < 4; ++i) {
max = qMax(max, coords[i][1]);
}
return max;
}
TPiece TPiece::rotatedLeft() const {
if (pieceShape == SquareShape) {
return *this;
}
TPiece result;
result.pieceShape = pieceShape;
for (int i = 0; i < 4; ++i) {
result.setX(i, y(i));
result.setY(i, -x(i));
}
return result;
}
TPiece TPiece::rotatedRight() const {
if (pieceShape == SquareShape) {
return *this;
}
TPiece result;
result.pieceShape = pieceShape;
for (int i = 0; i < 4; ++i) {
result.setX(i, -y(i));
result.setY(i, x(i));
}
return result;
}
NextPieceLabel::NextPieceLabel( QWidget* parent /* = 0*/ ) : QLabel(parent)
{
QPalette p = palette();
p.setColor(QPalette::Background, Qt::white);
setPalette(p);
setFrameShape(QFrame::Box);
setAlignment(Qt::AlignCenter);
setAutoFillBackground(true);
}
static QString addLibraries(const std::string &name, const std::list<RsLibraryInfo> &libraries)
{
QString mTextEdit;
mTextEdit+=QString::fromUtf8(name.c_str());
mTextEdit+="\n";
std::list<RsLibraryInfo>::const_iterator libraryIt;
for (libraryIt = libraries.begin(); libraryIt != libraries.end(); ++libraryIt) {
mTextEdit+=" - ";
mTextEdit+=QString::fromUtf8(libraryIt->mName.c_str());
mTextEdit+=": ";
mTextEdit+=QString::fromUtf8(libraryIt->mVersion.c_str());
mTextEdit+="\n";
}
mTextEdit+="\n";
return mTextEdit;
}
void AboutWidget::on_copy_button_clicked()
{
QString verInfo;
QString rsVerString = "RetroShare Version: ";
rsVerString+=Rshare::retroshareVersion(true);
verInfo+=rsVerString;
verInfo+="\n";
#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0)
verInfo+=QSysInfo::prettyProductName();
#endif
#else
#ifdef Q_OS_LINUX
verInfo+="Linux";
#endif
#ifdef Q_OS_WIN
verInfo+="Windows";
#endif
#ifdef Q_OS_MAC
verInfo+="Mac";
#endif
#endif
verInfo+=" ";
QString qtver = QString("QT ")+QT_VERSION_STR;
verInfo+=qtver;
verInfo+="\n\n";
/* Add version numbers of libretroshare */
std::list<RsLibraryInfo> libraries;
RsControl::instance()->getLibraries(libraries);
verInfo+=addLibraries("libretroshare", libraries);
#ifdef ENABLE_WEBUI
/* Add version numbers of RetroShare */
// Add versions here. Find a better place.
libraries.clear();
libraries.push_back(RsLibraryInfo("Libmicrohttpd", MHD_get_version()));
verInfo+=addLibraries("RetroShare", libraries);
#endif // ENABLE_WEBUI
/* Add version numbers of plugins */
if (rsPlugins) {
for (int i = 0; i < rsPlugins->nbPlugins(); ++i) {
RsPlugin *plugin = rsPlugins->plugin(i);
if (plugin) {
libraries.clear();
plugin->getLibraries(libraries);
verInfo+=addLibraries(plugin->getPluginName(), libraries);
}
}
}
QApplication::clipboard()->setText(verInfo);
}

View File

@ -0,0 +1,220 @@
/****************************************************************
* This file is distributed under the following license:
*
* Copyright (c) 2009, RetroShare Team
* Copyright (C) 2008 Unipro, Russia (http://ugene.unipro.ru)
*
* 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 Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
****************************************************************/
#ifndef _GB2_ABOUT_DIALOG_
#define _GB2_ABOUT_DIALOG_
#include "ui_AboutWidget.h"
#include <QBasicTimer>
#include <QResizeEvent>
#include <QPointer>
#include <QDialog>
#include <QLabel>
#include <QPaintEvent>
#include <QKeyEvent>
#include <QMouseEvent>
class AWidget;
class TBoard;
class NextPieceLabel;
class AboutWidget : public QWidget, public Ui::AboutWidget
{
Q_OBJECT
public:
AboutWidget(QWidget *parent = 0);
private slots:
void sl_scoreChanged(int);
void sl_levelChanged(int);
void on_help_button_clicked();
void on_copy_button_clicked();
signals:
void si_scoreChanged(QString);
void si_maxScoreChanged(QString);
void si_levelChanged(QString);
protected:
//void keyPressEvent(QKeyEvent *event);
void mousePressEvent(QMouseEvent *event);
private:
void switchPages();
void installAWidget();
void installTWidget();
void updateTitle();
AWidget* aWidget;
TBoard* tWidget;
};
//////////////////////////////////////////////////////////////////////////
// A
class AWidget : public QWidget {
Q_OBJECT
public:
AWidget();
void switchState() ;
protected:
void timerEvent(QTimerEvent* e);
void paintEvent(QPaintEvent* e);
//void mouseMoveEvent(QMouseEvent* e);
void resizeEvent(QResizeEvent *);
//void keyPressEvent(QKeyEvent *e);
private:
void initImages();
void computeNextState();
void calcWater(int npage, int density);
void addBlob(int x, int y, int radius, int height);
void drawWater(QRgb* srcImage, QRgb* dstImage);
static QRgb shiftColor(QRgb color,int shift) {
return qRgb(qBound(0, qRed(color) - shift, 255),
qBound(0, qGreen(color) - shift,255),
qBound(0, qBlue(color) - shift, 255));
}
void initGoL();
void drawBitField();
int page;
int density;
std::vector<int> bitfield1;
std::vector<int> bitfield2;
QImage image1;
QImage image2;
bool mImagesReady ;
int mState;
int mTimerId;
float mStep;
int mMaxStep;
};
//////////////////////////////////////////////////////////////////////////
// T
class TPiece {
public:
enum Shape { NoShape, ZShape, SShape, LineShape, TShape, SquareShape, LShape, MirroredLShape };
TPiece() { setShape(NoShape); }
void setRandomShape();
void setShape(Shape shape);
Shape shape() const { return pieceShape; }
int x(int index) const { return coords[index][0]; }
int y(int index) const { return coords[index][1]; }
int minX() const;
int maxX() const;
int minY() const;
int maxY() const;
TPiece rotatedLeft() const;
TPiece rotatedRight() const;
private:
void setX(int index, int x) { coords[index][0] = x; }
void setY(int index, int y) { coords[index][1] = y; }
Shape pieceShape;
int coords[4][2];
};
class TBoard : public QWidget {
Q_OBJECT
public:
TBoard(QWidget *parent = 0);
~TBoard();
int heightForWidth ( int w ) const;
int getScore() const {return score;}
int getMaxScore() const {return qMax(maxScore, score);}
int getLevel() const {return level;}
void setNextPieceLabel(QLabel *label) {nextPieceLabel = label;}
int squareWidth() const { return boardRect().width() / BoardWidth; }
int squareHeight() const { return boardRect().height() / BoardHeight; }
public slots:
void start();
void pause();
signals:
void scoreChanged(int score);
void levelChanged(int level);
void linesRemovedChanged(int numLines);
protected:
void paintEvent(QPaintEvent *event);
void keyPressEvent(QKeyEvent *event);
void timerEvent(QTimerEvent *event);
private:
enum { BoardWidth = 10, BoardHeight = 22 };
TPiece::Shape &shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }
int timeoutTime() const { return 1000 / (1 + level); }
QRect boardRect() const {return QRect(1, 1, width()-2, height()-2);}
QRect frameRect() const {return QRect(0, 0, width()-1, height()-1);}
void clearBoard();
void dropDown();
void oneLineDown();
void pieceDropped(int dropHeight);
void removeFullLines();
void newPiece();
void showNextPiece();
bool tryMove(const TPiece &newPiece, int newX, int newY);
void drawSquare(QPainter &painter, int x, int y, TPiece::Shape shape);
QBasicTimer timer;
QPointer<QLabel> nextPieceLabel;
bool isStarted;
bool isPaused;
bool isWaitingAfterLine;
TPiece curPiece;
TPiece nextPiece;
int curX;
int curY;
int numLinesRemoved;
int numPiecesDropped;
int score;
int maxScore;
int level;
TPiece::Shape board[BoardWidth * BoardHeight];
};
class NextPieceLabel : public QLabel {
public:
NextPieceLabel(QWidget* parent = 0);
};
#endif

View File

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AboutWidget</class>
<widget class="QWidget" name="AboutWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>594</width>
<height>594</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QFrame" name="frame">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="help_button">
<property name="text">
<string>About</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="copy_button">
<property name="text">
<string>Copy Info</string>
</property>
<property name="icon">
<iconset resource="images.qrc">
<normaloff>:/images/copy.png</normaloff>:/images/copy.png</iconset>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="close_button">
<property name="text">
<string>close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources>
<include location="images.qrc"/>
</resources>
<connections/>
</ui>

View File

@ -99,28 +99,28 @@ ChatLobbyWidget::ChatLobbyWidget(QWidget *parent, Qt::WindowFlags flags)
QHeaderView_setSectionResizeModeColumn(header, COLUMN_SUBSCRIBED, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(header, COLUMN_SUBSCRIBED, QHeaderView::Interactive);
privateSubLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER); privateSubLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER);
privateSubLobbyItem->setText(COLUMN_NAME, tr("Private Subscribed Lobbies")); privateSubLobbyItem->setText(COLUMN_NAME, tr("Private Subscribed chat rooms"));
privateSubLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "1"); privateSubLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "1");
// privateLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PRIVATE)); // privateLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PRIVATE));
privateSubLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PRIVATE); privateSubLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PRIVATE);
ui.lobbyTreeWidget->insertTopLevelItem(0, privateSubLobbyItem); ui.lobbyTreeWidget->insertTopLevelItem(0, privateSubLobbyItem);
publicSubLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER); publicSubLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER);
publicSubLobbyItem->setText(COLUMN_NAME, tr("Public Subscribed Lobbies")); publicSubLobbyItem->setText(COLUMN_NAME, tr("Public Subscribed chat rooms"));
publicSubLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "2"); publicSubLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "2");
// publicLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PUBLIC)); // publicLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PUBLIC));
publicSubLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PUBLIC); publicSubLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PUBLIC);
ui.lobbyTreeWidget->insertTopLevelItem(1, publicSubLobbyItem); ui.lobbyTreeWidget->insertTopLevelItem(1, publicSubLobbyItem);
privateLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER); privateLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER);
privateLobbyItem->setText(COLUMN_NAME, tr("Private Lobbies")); privateLobbyItem->setText(COLUMN_NAME, tr("Private chat rooms"));
privateLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "3"); privateLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "3");
// privateLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PRIVATE)); // privateLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PRIVATE));
privateLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PRIVATE); privateLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PRIVATE);
ui.lobbyTreeWidget->insertTopLevelItem(2, privateLobbyItem); ui.lobbyTreeWidget->insertTopLevelItem(2, privateLobbyItem);
publicLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER); publicLobbyItem = new RSTreeWidgetItem(compareRole, TYPE_FOLDER);
publicLobbyItem->setText(COLUMN_NAME, tr("Public Lobbies")); publicLobbyItem->setText(COLUMN_NAME, tr("Public chat rooms"));
publicLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "4"); publicLobbyItem->setData(COLUMN_NAME, ROLE_SORT, "4");
// publicLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PUBLIC)); // publicLobbyItem->setIcon(COLUMN_NAME, QIcon(IMAGE_PUBLIC));
publicLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PUBLIC); publicLobbyItem->setData(COLUMN_DATA, ROLE_PRIVACYLEVEL, CHAT_LOBBY_PRIVACY_LEVEL_PUBLIC);
@ -171,24 +171,25 @@ ChatLobbyWidget::ChatLobbyWidget(QWidget *parent, Qt::WindowFlags flags)
int S = QFontMetricsF(font()).height(); int S = QFontMetricsF(font()).height();
QString help_str = tr("\ QString help_str = tr("\
<h1><img width=\"%1\" src=\":/icons/help_64.png\">&nbsp;&nbsp;Chat Lobbies</h1> \ <h1><img width=\"%1\" src=\":/icons/help_64.png\">&nbsp;&nbsp;Chat Rooms</h1> \
<p>Chat lobbies are distributed chat rooms, and work pretty much like IRC. \ <p>Chat rooms work pretty much like IRC. \
They allow you to talk anonymously with tons of people without the need to make friends.</p> \ They allow you to talk anonymously with tons of people without the need to make friends.</p> \
<p>A chat lobby can be public (your friends see it) or private (your friends can't see it, unless you \ <p>A chat room can be public (your friends see it) or private (your friends can't see it, unless you \
invite them with <img src=\":/images/add_24x24.png\" width=%2/>). \ invite them with <img src=\":/images/add_24x24.png\" width=%2/>). \
Once you have been invited to a private lobby, you will be able to see it when your friends \ Once you have been invited to a private room, you will be able to see it when your friends \
are using it.</p> \ are using it.</p> \
<p>The list at left shows \ <p>The list at left shows \
chat lobbies your friends are participating in. You can either \ chat lobbies your friends are participating in. You can either \
<ul> \ <ul> \
<li>Right click to create a new chat lobby</li> \ <li>Right click to create a new chat room</li> \
<li>Double click a chat lobby to enter, chat, and show it to your friends</li> \ <li>Double click a chat room to enter, chat, and show it to your friends</li> \
</ul> \ </ul> \
Note: For the chat lobbies to work properly, your computer needs be on time. So check your system clock!\ Note: For the chat rooms to work properly, your computer needs be on time. So check your system clock!\
</p> \ </p> \
" "
).arg(QString::number(2*S)).arg(QString::number(S)) ; ).arg(QString::number(2*S)).arg(QString::number(S)) ;
registerHelpButton(ui.helpButton,help_str) ;
registerHelpButton(ui.helpButton,help_str,"ChatLobbyDialog") ;
} }
ChatLobbyWidget::~ChatLobbyWidget() ChatLobbyWidget::~ChatLobbyWidget()
@ -255,7 +256,7 @@ void ChatLobbyWidget::lobbyTreeWidgetCustomPopupMenu(QPoint)
QMenu contextMnu(this); QMenu contextMnu(this);
if (item && item->type() == TYPE_FOLDER) { if (item && item->type() == TYPE_FOLDER) {
QAction *action = contextMnu.addAction(QIcon(IMAGE_CREATE), tr("Create chat lobby"), this, SLOT(createChatLobby())); QAction *action = contextMnu.addAction(QIcon(IMAGE_CREATE), tr("Create chat room"), this, SLOT(createChatLobby()));
action->setData(item->data(COLUMN_DATA, ROLE_PRIVACYLEVEL).toInt()); action->setData(item->data(COLUMN_DATA, ROLE_PRIVACYLEVEL).toInt());
} }
@ -265,7 +266,7 @@ void ChatLobbyWidget::lobbyTreeWidgetCustomPopupMenu(QPoint)
rsIdentity->getOwnIds(own_identities) ; rsIdentity->getOwnIds(own_identities) ;
if (item->data(COLUMN_DATA, ROLE_SUBSCRIBED).toBool()) if (item->data(COLUMN_DATA, ROLE_SUBSCRIBED).toBool())
contextMnu.addAction(QIcon(IMAGE_UNSUBSCRIBE), tr("Leave this lobby"), this, SLOT(unsubscribeItem())); contextMnu.addAction(QIcon(IMAGE_UNSUBSCRIBE), tr("Leave this room"), this, SLOT(unsubscribeItem()));
else else
{ {
QTreeWidgetItem *item = ui.lobbyTreeWidget->currentItem(); QTreeWidgetItem *item = ui.lobbyTreeWidget->currentItem();
@ -280,18 +281,18 @@ void ChatLobbyWidget::lobbyTreeWidgetCustomPopupMenu(QPoint)
if(own_identities.empty()) if(own_identities.empty())
{ {
if(removed) if(removed)
contextMnu.addAction(QIcon(IMAGE_SUBSCRIBE), tr("Create a non anonymous identity and enter this lobby"), this, SLOT(createIdentityAndSubscribe())); contextMnu.addAction(QIcon(IMAGE_SUBSCRIBE), tr("Create a non anonymous identity and enter this room"), this, SLOT(createIdentityAndSubscribe()));
else else
contextMnu.addAction(QIcon(IMAGE_SUBSCRIBE), tr("Create an identity and enter this lobby"), this, SLOT(createIdentityAndSubscribe())); contextMnu.addAction(QIcon(IMAGE_SUBSCRIBE), tr("Create an identity and enter this chat room"), this, SLOT(createIdentityAndSubscribe()));
} }
else if(own_identities.size() == 1) else if(own_identities.size() == 1)
{ {
QAction *action = contextMnu.addAction(QIcon(IMAGE_SUBSCRIBE), tr("Enter this lobby"), this, SLOT(subscribeChatLobbyAs())); QAction *action = contextMnu.addAction(QIcon(IMAGE_SUBSCRIBE), tr("Enter this chat room"), this, SLOT(subscribeChatLobbyAs()));
action->setData(QString::fromStdString((own_identities.front()).toStdString())) ; action->setData(QString::fromStdString((own_identities.front()).toStdString())) ;
} }
else else
{ {
QMenu *mnu = contextMnu.addMenu(QIcon(IMAGE_SUBSCRIBE),tr("Enter this lobby as...")) ; QMenu *mnu = contextMnu.addMenu(QIcon(IMAGE_SUBSCRIBE),tr("Enter this chat room as...")) ;
for(std::list<RsGxsId>::const_iterator it=own_identities.begin();it!=own_identities.end();++it) for(std::list<RsGxsId>::const_iterator it=own_identities.begin();it!=own_identities.end();++it)
{ {
@ -405,7 +406,7 @@ void ChatLobbyWidget::addChatPage(ChatLobbyDialog *d)
if(rsMsgs->getChatLobbyInfo(id,linfo)) if(rsMsgs->getChatLobbyInfo(id,linfo))
_lobby_infos[id].default_icon = (linfo.lobby_flags & RS_CHAT_LOBBY_FLAGS_PUBLIC) ? QIcon(IMAGE_PUBLIC):QIcon(IMAGE_PRIVATE) ; _lobby_infos[id].default_icon = (linfo.lobby_flags & RS_CHAT_LOBBY_FLAGS_PUBLIC) ? QIcon(IMAGE_PUBLIC):QIcon(IMAGE_PRIVATE) ;
else else
std::cerr << "(EE) cannot find info for lobby " << std::hex << id << std::dec << std::endl; std::cerr << "(EE) cannot find info for room " << std::hex << id << std::dec << std::endl;
} }
} }
@ -424,7 +425,7 @@ void ChatLobbyWidget::setCurrentChatPage(ChatLobbyDialog *d)
void ChatLobbyWidget::updateDisplay() void ChatLobbyWidget::updateDisplay()
{ {
#ifdef CHAT_LOBBY_GUI_DEBUG #ifdef CHAT_LOBBY_GUI_DEBUG
std::cerr << "updating chat lobby display!" << std::endl; std::cerr << "updating chat room display!" << std::endl;
#endif #endif
std::vector<VisibleChatLobbyRecord> visibleLobbies; std::vector<VisibleChatLobbyRecord> visibleLobbies;
rsMsgs->getListOfNearbyChatLobbies(visibleLobbies); rsMsgs->getListOfNearbyChatLobbies(visibleLobbies);
@ -795,7 +796,7 @@ void ChatLobbyWidget::subscribeChatLobbyAtItem(QTreeWidgetItem *item)
if( (flags & RS_CHAT_LOBBY_FLAGS_PGP_SIGNED) && !(idd.mFlags & RS_IDENTITY_FLAGS_PGP_LINKED)) if( (flags & RS_CHAT_LOBBY_FLAGS_PGP_SIGNED) && !(idd.mFlags & RS_IDENTITY_FLAGS_PGP_LINKED))
{ {
QMessageBox::warning(NULL,tr("Default identity is anonymous"),tr("You cannot join this lobby with your default identity, since it is anonymous and the lobby forbids it.")) ; QMessageBox::warning(NULL,tr("Default identity is anonymous"),tr("You cannot join this chat room with your default identity, since it is anonymous and the chat room forbids it.")) ;
return ; return ;
} }
} }
@ -840,14 +841,14 @@ void ChatLobbyWidget::showBlankPage(ChatLobbyId id)
ui.lobbysec_lineEdit->setText( (( (*it).lobby_flags & RS_CHAT_LOBBY_FLAGS_PGP_SIGNED)?tr("No anonymous IDs"):tr("Anonymous IDs accepted")) ); ui.lobbysec_lineEdit->setText( (( (*it).lobby_flags & RS_CHAT_LOBBY_FLAGS_PGP_SIGNED)?tr("No anonymous IDs"):tr("Anonymous IDs accepted")) );
ui.lobbypeers_lineEdit->setText( QString::number((*it).total_number_of_peers) ); ui.lobbypeers_lineEdit->setText( QString::number((*it).total_number_of_peers) );
QString text = tr("You're not subscribed to this lobby; Double click-it to enter and chat.") ; QString text = tr("You're not subscribed to this chat room; Double click-it to enter and chat.") ;
if(my_ids.empty()) if(my_ids.empty())
{ {
if( (*it).lobby_flags & RS_CHAT_LOBBY_FLAGS_PGP_SIGNED) if( (*it).lobby_flags & RS_CHAT_LOBBY_FLAGS_PGP_SIGNED)
text += "\n\n"+tr("You will need to create a non anonymous identity in order to join this chat lobby.") ; text += "\n\n"+tr("You will need to create a non anonymous identity in order to join this chat room.") ;
else else
text += "\n\n"+tr("You will need to create an identity in order to join chat lobbies.") ; text += "\n\n"+tr("You will need to create an identity in order to join chat rooms.") ;
} }
ui.lobbyInfoLabel->setText(text); ui.lobbyInfoLabel->setText(text);
@ -861,7 +862,7 @@ void ChatLobbyWidget::showBlankPage(ChatLobbyId id)
ui.lobbypeers_lineEdit->clear(); ui.lobbypeers_lineEdit->clear();
ui.lobbysec_lineEdit->clear(); ui.lobbysec_lineEdit->clear();
QString text = tr("No lobby selected. \nSelect lobbies at left to show details.\nDouble click lobbies to enter and chat.") ; QString text = tr("No chat room selected. \nSelect chat rooms at left to show details.\nDouble click a chat room to enter and chat.") ;
ui.lobbyInfoLabel->setText(text) ; ui.lobbyInfoLabel->setText(text) ;
} }
@ -965,7 +966,7 @@ void ChatLobbyWidget::unsubscribeItem()
void ChatLobbyWidget::unsubscribeChatLobby(ChatLobbyId id) void ChatLobbyWidget::unsubscribeChatLobby(ChatLobbyId id)
{ {
std::cerr << "Unsubscribing from chat lobby" << std::endl; std::cerr << "Unsubscribing from chat room" << std::endl;
// close the tab. // close the tab.
@ -1072,12 +1073,12 @@ void ChatLobbyWidget::readChatLobbyInvites()
for(std::list<ChatLobbyInvite>::const_iterator it(invites.begin());it!=invites.end();++it) for(std::list<ChatLobbyInvite>::const_iterator it(invites.begin());it!=invites.end();++it)
{ {
QMessageBox mb(QObject::tr("Join chat lobby"), QMessageBox mb(QObject::tr("Join chat room"),
tr("%1 invites you to chat lobby named %2").arg(QString::fromUtf8(rsPeers->getPeerName((*it).peer_id).c_str())).arg(RsHtml::plainText(it->lobby_name)), tr("%1 invites you to chat room named %2").arg(QString::fromUtf8(rsPeers->getPeerName((*it).peer_id).c_str())).arg(RsHtml::plainText(it->lobby_name)),
QMessageBox::Question, QMessageBox::Yes,QMessageBox::No, 0); QMessageBox::Question, QMessageBox::Yes,QMessageBox::No, 0);
QLabel *label = new QLabel(tr("Choose an identity for this lobby:")); QLabel *label = new QLabel(tr("Choose an identity for this chat room:"));
GxsIdChooser *idchooser = new GxsIdChooser ; GxsIdChooser *idchooser = new GxsIdChooser ;
idchooser->loadIds(IDCHOOSER_ID_REQUIRED,default_id) ; idchooser->loadIds(IDCHOOSER_ID_REQUIRED,default_id) ;
@ -1112,7 +1113,7 @@ void ChatLobbyWidget::readChatLobbyInvites()
if(rsMsgs->acceptLobbyInvite((*it).lobby_id,chosen_id)) if(rsMsgs->acceptLobbyInvite((*it).lobby_id,chosen_id))
ChatDialog::chatFriend(ChatId((*it).lobby_id),true); ChatDialog::chatFriend(ChatId((*it).lobby_id),true);
else else
std::cerr << "Can't join lobby with id 0x" << std::hex << (*it).lobby_id << std::dec << std::endl; std::cerr << "Can't join chat room with id 0x" << std::hex << (*it).lobby_id << std::dec << std::endl;
} }
} }

View File

@ -35,7 +35,7 @@ public:
~ChatLobbyWidget(); ~ChatLobbyWidget();
virtual QIcon iconPixmap() const { return QIcon(IMAGE_CHATLOBBY) ; } //MainPage virtual QIcon iconPixmap() const { return QIcon(IMAGE_CHATLOBBY) ; } //MainPage
virtual QString pageName() const { return tr("Chat Lobbies") ; } //MainPage virtual QString pageName() const { return tr("Chats") ; } //MainPage
virtual QString helpText() const { return ""; } //MainPage virtual QString helpText() const { return ""; } //MainPage
virtual UserNotify *getUserNotify(QObject *parent); //MainPage virtual UserNotify *getUserNotify(QObject *parent); //MainPage

View File

@ -72,7 +72,7 @@
<item> <item>
<widget class="StyledLabel" name="titleBarLabel"> <widget class="StyledLabel" name="titleBarLabel">
<property name="text"> <property name="text">
<string>Chat lobbies</string> <string>Chat rooms</string>
</property> </property>
</widget> </widget>
</item> </item>
@ -95,7 +95,7 @@
<enum>Qt::NoFocus</enum> <enum>Qt::NoFocus</enum>
</property> </property>
<property name="icon"> <property name="icon">
<iconset resource="images.qrc"> <iconset resource="icons.qrc">
<normaloff>:/icons/help_64.png</normaloff>:/icons/help_64.png</iconset> <normaloff>:/icons/help_64.png</normaloff>:/icons/help_64.png</iconset>
</property> </property>
<property name="checkable"> <property name="checkable">
@ -242,7 +242,7 @@
</font> </font>
</property> </property>
<property name="text"> <property name="text">
<string>Lobby Name:</string> <string>Chat room Name:</string>
</property> </property>
</widget> </widget>
</item> </item>
@ -255,7 +255,7 @@
</font> </font>
</property> </property>
<property name="text"> <property name="text">
<string>Lobby Id:</string> <string>Chat room Id:</string>
</property> </property>
</widget> </widget>
</item> </item>
@ -440,7 +440,6 @@
</customwidget> </customwidget>
</customwidgets> </customwidgets>
<resources> <resources>
<include location="images.qrc"/>
<include location="icons.qrc"/> <include location="icons.qrc"/>
</resources> </resources>
<connections/> <connections/>

View File

@ -489,7 +489,7 @@ TransfersDialog::TransfersDialog(QWidget *parent)
").arg(QString::number(2*S)).arg(QString::number(S)) ; ").arg(QString::number(2*S)).arg(QString::number(S)) ;
registerHelpButton(ui.helpButton,help_str) ; registerHelpButton(ui.helpButton,help_str,"TransfersDialog") ;
} }
TransfersDialog::~TransfersDialog() TransfersDialog::~TransfersDialog()

View File

@ -60,7 +60,7 @@ public:
~TransfersDialog(); ~TransfersDialog();
virtual QIcon iconPixmap() const { return QIcon(IMAGE_TRANSFERS) ; } //MainPage virtual QIcon iconPixmap() const { return QIcon(IMAGE_TRANSFERS) ; } //MainPage
virtual QString pageName() const { return tr("File sharing") ; } //MainPage virtual QString pageName() const { return tr("Files") ; } //MainPage
virtual QString helpText() const { return ""; } //MainPage virtual QString helpText() const { return ""; } //MainPage
virtual UserNotify *getUserNotify(QObject *parent); virtual UserNotify *getUserNotify(QObject *parent);

View File

@ -169,7 +169,7 @@ QList<int> sizes;
</ul> </p> \ </ul> </p> \
") ; ") ;
registerHelpButton(ui.helpButton, hlp_str) ; registerHelpButton(ui.helpButton, hlp_str,"FriendsDialog") ;
} }
FriendsDialog::~FriendsDialog () FriendsDialog::~FriendsDialog ()

View File

@ -57,7 +57,7 @@ public:
~FriendsDialog (); ~FriendsDialog ();
virtual QIcon iconPixmap() const { return QIcon(IMAGE_NETWORK) ; } //MainPage virtual QIcon iconPixmap() const { return QIcon(IMAGE_NETWORK) ; } //MainPage
virtual QString pageName() const { return tr("Network") ; } //MainPage virtual QString pageName() const { return tr("Network") ; } //MainPage
virtual QString helpText() const { return ""; } //MainPage virtual QString helpText() const { return ""; } //MainPage
virtual UserNotify *getUserNotify(QObject *parent); virtual UserNotify *getUserNotify(QObject *parent);

View File

@ -36,6 +36,7 @@
#include <retroshare/rsidentity.h> #include <retroshare/rsidentity.h>
#include <retroshare/rsinit.h> #include <retroshare/rsinit.h>
#include <retroshare/rsnotify.h>
#include <rsserver/rsaccounts.h> #include <rsserver/rsaccounts.h>
#include <util/rsrandom.h> #include <util/rsrandom.h>
@ -43,6 +44,9 @@
#include <math.h> #include <math.h>
#include <iostream> #include <iostream>
#define IMAGE_GOOD ":/images/accepted16.png"
#define IMAGE_BAD ":/images/deletemail24.png"
class EntropyCollectorWidget: public QTextBrowser class EntropyCollectorWidget: public QTextBrowser
{ {
public: public:
@ -104,17 +108,10 @@ void GenCertDialog::grabMouse()
ui.entropy_bar->setValue(count*100/2048) ; ui.entropy_bar->setValue(count*100/2048) ;
if(ui.entropy_bar->value() < 20) if(!mEntropyOk && ui.entropy_bar->value() >= 20)
{ {
ui.genButton->setEnabled(false) ; mEntropyOk = true ;
//ui.genButton->setIcon(QIcon(":/images/delete.png")) ; updateCheckLabels();
ui.genButton->setToolTip(tr("Currently disabled. Please move your mouse around until you reach at least 20%")) ;
}
else
{
ui.genButton->setEnabled(true) ;
//ui.genButton->setIcon(QIcon(":/images/resume.png")) ;
ui.genButton->setToolTip(tr("Click to create your node and/or profile")) ;
} }
RsInit::collectEntropy(E+(F << 16)) ; RsInit::collectEntropy(E+(F << 16)) ;
@ -133,66 +130,55 @@ GenCertDialog::GenCertDialog(bool onlyGenerateIdentity, QWidget *parent)
/* Invoke Qt Designer generated QObject setup routine */ /* Invoke Qt Designer generated QObject setup routine */
ui.setupUi(this); ui.setupUi(this);
ui.headerFrame->setHeaderImage(QPixmap(":/icons/svg/profile.svg")); //ui.headerFrame->setHeaderImage(QPixmap(":/icons/svg/profile.svg"));
ui.headerFrame->setHeaderText(tr("Create a new profile")); //ui.headerFrame->setHeaderText(tr("Create a new profile"));
connect(ui.new_gpg_key_checkbox, SIGNAL(clicked()), this, SLOT(newGPGKeyGenUiSetup())); connect(ui.reuse_existing_node_CB, SIGNAL(clicked()), this, SLOT(switchReuseExistingNode()));
connect(ui.adv_checkbox, SIGNAL(clicked()), this, SLOT(updateUiSetup())); connect(ui.adv_checkbox, SIGNAL(clicked()), this, SLOT(setupState()));
connect(ui.hidden_checkbox, SIGNAL(clicked()), this, SLOT(updateUiSetup())); connect(ui.nodeType_CB, SIGNAL(currentIndexChanged(int)), this, SLOT(setupState()));
connect(ui.genButton, SIGNAL(clicked()), this, SLOT(genPerson())); connect(ui.genButton, SIGNAL(clicked()), this, SLOT(genPerson()));
connect(ui.importIdentity_PB, SIGNAL(clicked()), this, SLOT(importIdentity())); connect(ui.importIdentity_PB, SIGNAL(clicked()), this, SLOT(importIdentity()));
connect(ui.exportIdentity_PB, SIGNAL(clicked()), this, SLOT(exportIdentity())); connect(ui.exportIdentity_PB, SIGNAL(clicked()), this, SLOT(exportIdentity()));
//ui.genName->setFocus(Qt::OtherFocusReason); connect(ui.password_input, SIGNAL(textChanged(QString)), this, SLOT(updateCheckLabels()));
connect(ui.password_input_2, SIGNAL(textChanged(QString)), this, SLOT(updateCheckLabels()));
// QObject *obj = QCoreApplication::eventFilter() ; connect(ui.name_input, SIGNAL(textChanged(QString)), this, SLOT(updateCheckLabels()));
// std::cerr << "Event filter : " << obj << std::endl; connect(ui.node_input, SIGNAL(textChanged(QString)), this, SLOT(updateCheckLabels()));
// QCoreApplication::instance()->setEventFilter(MyEventFilter) ; connect(ui.reuse_existing_node_CB, SIGNAL(toggled(bool)), this, SLOT(updateCheckLabels()));
entropy_timer = new QTimer ; entropy_timer = new QTimer ;
entropy_timer->start(20) ; entropy_timer->start(20) ;
QObject::connect(entropy_timer,SIGNAL(timeout()),this,SLOT(grabMouse())) ; QObject::connect(entropy_timer,SIGNAL(timeout()),this,SLOT(grabMouse())) ;
// EntropyCollectorWidget *ecw = new EntropyCollectorWidget(ui.entropy_bar,this) ;
// ecw->resize(size()) ;
// ecw->move(0,0) ;
//
// QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect ;
// effect->setOpacity(0.2) ;
// ecw->setGraphicsEffect(effect) ;
//ecw->setBackgroundColor(QColor::fromRGB(1,1,1)) ;
// ecw->show() ;
ui.entropy_bar->setValue(0) ; ui.entropy_bar->setValue(0) ;
// make sure that QVariant always takes an 'int' otherwise the program will crash! // make sure that QVariant always takes an 'int' otherwise the program will crash!
ui.keylength_comboBox->addItem("default (2048 bits, recommended)", QVariant(2048)); ui.keylength_comboBox->addItem("Default (2048 bits, recommended)", QVariant(2048));
ui.keylength_comboBox->addItem("high (3072 bits)", QVariant(3072)); ui.keylength_comboBox->addItem("High (3072 bits)", QVariant(3072));
ui.keylength_comboBox->addItem("insane (4096 bits)", QVariant(4096)); ui.keylength_comboBox->addItem("Very high (4096 bits)", QVariant(4096));
#if QT_VERSION >= 0x040700 #if QT_VERSION >= 0x040700
ui.email_input->setPlaceholderText(tr("[Optional] Visible to your friends, and friends of friends.")) ; ui.node_input->setPlaceholderText(tr("[Required] Examples: Home, Laptop,...(Visible to friends).")) ;
ui.node_input->setPlaceholderText(tr("[Required] Examples: Home, Laptop,...")) ; ui.hiddenaddr_input->setPlaceholderText(tr("[Optional] Tor/I2P address (Example: xa76giaf6ifda7ri63i263.onion)")) ;
ui.hiddenaddr_input->setPlaceholderText(tr("[Required] Tor/I2P address - Examples: xa76giaf6ifda7ri63i263.onion (obtained by you from Tor)")) ; ui.name_input->setPlaceholderText(tr("[Required] Visible to friends, and friends of friends."));
ui.name_input->setPlaceholderText(tr("[Required] Visible to your friends, and friends of friends.")); ui.nickname_input->setPlaceholderText(tr("[Optional] Used to write in chat rooms and forums. Can be set later."));
ui.nickname_input->setPlaceholderText(tr("[Optional] Used when you write in chat lobbies, forums and channel comments. Can be setup later if you need one.")); ui.password_input->setPlaceholderText(tr("[Required] This password protects your data. Dont forget it!"));
ui.password_input->setPlaceholderText(tr("[Required] This password protects your private PGP key."));
ui.password_input_2->setPlaceholderText(tr("[Required] Type the same password again here.")); ui.password_input_2->setPlaceholderText(tr("[Required] Type the same password again here."));
#endif #endif
ui.nickname_input->setMaxLength(RSID_MAXIMUM_NICKNAME_SIZE); ui.nickname_input->setMaxLength(RSID_MAXIMUM_NICKNAME_SIZE);
ui.node_input->setToolTip(tr("Enter a meaningful node description. e.g. : home, laptop, etc. \nThis field will be used to differentiate different installations with\nthe same profile (PGP key pair).")) ;
ui.email_input->hide() ;
ui.email_label->hide() ;
/* get all available pgp private certificates.... /* get all available pgp private certificates....
* mark last one as default. * mark last one as default.
*/ */
init(); mAllFieldsOk = false ;
mEntropyOk = false ;
initKeyList();
setupState();
updateCheckLabels();
} }
GenCertDialog::~GenCertDialog() GenCertDialog::~GenCertDialog()
@ -200,7 +186,21 @@ GenCertDialog::~GenCertDialog()
entropy_timer->stop() ; entropy_timer->stop() ;
} }
void GenCertDialog::init() void GenCertDialog::switchReuseExistingNode()
{
if(ui.reuse_existing_node_CB->isChecked())
{
// import an existing identity if needed. If none is available, keep the box unchecked.
if(!haveGPGKeys && !importIdentity())
ui.reuse_existing_node_CB->setChecked(false);
}
initKeyList();
setupState();
}
void GenCertDialog::initKeyList()
{ {
std::cerr << "Finding PGPUsers" << std::endl; std::cerr << "Finding PGPUsers" << std::endl;
@ -209,62 +209,19 @@ void GenCertDialog::init()
std::list<RsPgpId> pgpIds; std::list<RsPgpId> pgpIds;
std::list<RsPgpId>::iterator it; std::list<RsPgpId>::iterator it;
haveGPGKeys = false; haveGPGKeys = false;
#ifdef TO_REMOVE
/* replace with true/false below */ if (RsAccounts::GetPGPLogins(pgpIds)) {
if (!mOnlyGenerateIdentity) { for(it = pgpIds.begin(); it != pgpIds.end(); ++it)
#endif {
if (RsAccounts::GetPGPLogins(pgpIds)) { QVariant userData(QString::fromStdString( (*it).toStdString() ));
for(it = pgpIds.begin(); it != pgpIds.end(); ++it) std::string name, email;
{ RsAccounts::GetPGPLoginDetails(*it, name, email);
QVariant userData(QString::fromStdString( (*it).toStdString() )); std::cerr << "Adding PGPUser: " << name << " id: " << *it << std::endl;
std::string name, email; QString gid = QString::fromStdString( (*it).toStdString()).right(8) ;
RsAccounts::GetPGPLoginDetails(*it, name, email); ui.genPGPuser->addItem(QString::fromUtf8(name.c_str()) + " <" + QString::fromUtf8(email.c_str()) + "> (" + gid + ")", userData);
std::cerr << "Adding PGPUser: " << name << " id: " << *it << std::endl; haveGPGKeys = true;
QString gid = QString::fromStdString( (*it).toStdString()).right(8) ;
ui.genPGPuser->addItem(QString::fromUtf8(name.c_str()) + " <" + QString::fromUtf8(email.c_str()) + "> (" + gid + ")", userData);
haveGPGKeys = true;
}
} }
#ifdef TO_REMOVE
} }
#endif
if (haveGPGKeys) {
ui.no_gpg_key_label->hide();
ui.header_label->show();
ui.new_gpg_key_checkbox->setChecked(false);
setWindowTitle(tr("Create new node"));
ui.genButton->setText(tr("Generate new node"));
ui.headerFrame->setHeaderText(tr("Create a new node"));
genNewGPGKey = false;
} else {
ui.no_gpg_key_label->setVisible(!mOnlyGenerateIdentity);
ui.header_label->setVisible(mOnlyGenerateIdentity);
ui.new_gpg_key_checkbox->setChecked(true);
ui.new_gpg_key_checkbox->setEnabled(true);
setWindowTitle(tr("Create new profile"));
ui.genButton->setText(tr("Generate new profile and node"));
ui.headerFrame->setHeaderText(tr("Create a new profile and node"));
genNewGPGKey = true;
}
#ifdef TO_REMOVE
QString text; /* = ui.header_label->text() + "\n";*/
text += tr("You can create a new profile with this form.");
if (mOnlyGenerateIdentity) {
ui.new_gpg_key_checkbox->setChecked(true);
ui.new_gpg_key_checkbox->hide();
#endif
ui.genprofileinfo_label->hide();
#ifdef TO_REMOVE
} else {
text += "\n";
text += tr("Alternatively you can use an existing profile. Just uncheck \"Create a new profile\"");
}
ui.header_label->setText(text);
#endif
newGPGKeyGenUiSetup();
//updateUiSetup();
} }
void GenCertDialog::mouseMoveEvent(QMouseEvent *e) void GenCertDialog::mouseMoveEvent(QMouseEvent *e)
@ -274,152 +231,84 @@ void GenCertDialog::mouseMoveEvent(QMouseEvent *e)
QDialog::mouseMoveEvent(e) ; QDialog::mouseMoveEvent(e) ;
} }
void GenCertDialog::newGPGKeyGenUiSetup() { void GenCertDialog::setupState()
bool adv_state = ui.adv_checkbox->isChecked(); {
bool hidden_state = ui.hidden_checkbox->isChecked(); bool adv_state = ui.adv_checkbox->isChecked();
if(!adv_state)
{
ui.reuse_existing_node_CB->setChecked(false) ;
ui.nodeType_CB->setCurrentIndex(0) ;
ui.keylength_comboBox->setCurrentIndex(0) ;
}
bool hidden_state = ui.nodeType_CB->currentIndex()==1;
bool generate_new = !ui.reuse_existing_node_CB->isChecked();
genNewGPGKey = generate_new;
ui.no_node_label->setVisible(false); ui.no_node_label->setVisible(false);
if (ui.new_gpg_key_checkbox->isChecked()) { setWindowTitle(generate_new?tr("Create new profile and new Retroshare node"):tr("Create new Retroshare node"));
genNewGPGKey = true; //ui.headerFrame->setHeaderText(generate_new?tr("Create a new profile and node"):tr("Create a new node"));
setWindowTitle(tr("Create new profile"));
ui.headerFrame->setHeaderText(tr("Create a new profile and node"));
if (!mOnlyGenerateIdentity) {
ui.header_label->setVisible(haveGPGKeys);
}
ui.genprofileinfo_label->setVisible(false);
ui.no_gpg_key_label->setText(tr("Welcome to Retroshare. Before you can proceed you need to create a profile and associate a node with it. To do so please fill out this form.\nAlternatively you can import a (previously exported) profile. Just uncheck \"Create a new profile\""));
ui.importIdentity_PB->hide() ; ui.label_nodeType->setVisible(adv_state) ;
ui.exportIdentity_PB->hide(); ui.nodeType_CB->setVisible(adv_state) ;
ui.adv_checkbox->setVisible(true); ui.reuse_existing_node_CB->setVisible(adv_state) ;
ui.importIdentity_PB->setVisible(adv_state && !generate_new) ;
ui.exportIdentity_PB->setVisible(adv_state && !generate_new) ;
ui.genPGPuserlabel->hide(); ui.genPGPuser->setVisible(adv_state && haveGPGKeys && !generate_new) ;
ui.genPGPuser->hide();
ui.name_label->show();
ui.name_input->show();
ui.nickname_label->setVisible(!mOnlyGenerateIdentity);
ui.nickname_input->setVisible(!mOnlyGenerateIdentity);
ui.node_label->setVisible(true);
ui.node_input->setVisible(true);
// ui.email_label->show();
// ui.email_input->show();
ui.password_label->show();
ui.password_label_2->show();
ui.password_input->show();
ui.password_input_2->show();
//ui.keylength_label->show();
//ui.keylength_comboBox->show();
ui.entropy_label->setVisible(true); ui.genprofileinfo_label->setVisible(false);
ui.entropy_bar->setVisible(true); ui.no_gpg_key_label->setText(tr("Welcome to Retroshare. Before you can proceed you need to create a profile and associate a node with it. To do so please fill out this form.\nAlternatively you can import a (previously exported) profile. Just uncheck \"Create a new profile\""));
ui.no_gpg_key_label->setVisible(false);
ui.genButton->setVisible(true); ui.nickname_label->setVisible(adv_state) ;
ui.genButton->setText(tr("Generate new profile and node")); ui.nickname_input->setVisible(adv_state) ;
} else {
genNewGPGKey = false;
setWindowTitle(tr("Create new node"));
ui.headerFrame->setHeaderText(tr("Create a new node"));
ui.header_label->setVisible(false);
//haveGPGKeys = (ui.genPGPuser->count() != 0)?true:false;
if (haveGPGKeys) {
QVariant data = ui.genPGPuser->itemData(ui.genPGPuser->currentIndex());
if (!rsAccounts->selectAccountByString(data.toString().toStdString())) {
ui.no_node_label->setText(tr("No node is associated with the profile named") + " " + ui.genPGPuser->currentText() + ". " +tr("Please create a node for it by providing a node name."));
ui.no_node_label->setVisible(true);
} else {
ui.genprofileinfo_label->show();
}
}
//ui.genprofileinfo_label->show();
ui.no_gpg_key_label->setText(tr("Welcome to Retroshare. Before you can proceed you need to import a profile and after that associate a node with it."));
ui.importIdentity_PB->setVisible(!mOnlyGenerateIdentity); ui.name_label->setVisible(true);
ui.exportIdentity_PB->setVisible(haveGPGKeys); ui.name_input->setVisible(generate_new);
ui.exportIdentity_PB->setEnabled(haveGPGKeys);
ui.adv_checkbox->setVisible(haveGPGKeys);
ui.adv_checkbox->setChecked(haveGPGKeys && adv_state);
//ui.genPGPuserlabel->show(); ui.header_label->setVisible(false) ;
//ui.genPGPuser->show();
ui.genPGPuserlabel->setVisible(haveGPGKeys);
ui.genPGPuser->setVisible(haveGPGKeys);
ui.name_label->hide();
ui.name_input->hide();
ui.nickname_label->setVisible(!mOnlyGenerateIdentity && haveGPGKeys);
ui.nickname_input->setVisible(!mOnlyGenerateIdentity && haveGPGKeys);
ui.node_label->setVisible(haveGPGKeys);
ui.node_input->setVisible(haveGPGKeys);
// ui.email_label->hide();
// ui.email_input->hide();
ui.password_label->hide();
ui.password_input->hide();
ui.password_label_2->hide();
ui.password_input_2->hide();
ui.keylength_label->hide();
ui.keylength_comboBox->hide();
ui.entropy_label->setVisible(haveGPGKeys); ui.nickname_label->setVisible(adv_state && !mOnlyGenerateIdentity);
ui.entropy_bar->setVisible(haveGPGKeys); ui.nickname_input->setVisible(adv_state && !mOnlyGenerateIdentity);
ui.genButton->setText(tr("Generate new node")); ui.node_label->setVisible(true);
ui.genButton->setVisible(haveGPGKeys); ui.node_input->setVisible(true);
}
updateUiSetup();
ui.adv_checkbox->setChecked(adv_state);
ui.hidden_checkbox->setChecked(hidden_state);
}
void GenCertDialog::updateUiSetup() ui.password_input->setVisible(true);
{ ui.password_label->setVisible(true);
if (ui.adv_checkbox->isChecked())
ui.password2_check_LB->setVisible(generate_new);
ui.password_input_2->setVisible(generate_new);
ui.password_label_2->setVisible(generate_new);
ui.keylength_label->setVisible(adv_state);
ui.keylength_comboBox->setVisible(adv_state);
ui.entropy_bar->setVisible(true);
ui.genButton->setVisible(true);
ui.genButton->setText(generate_new?tr("Generate new profile and node"):tr("Generate new node"));
ui.hiddenaddr_input->setVisible(hidden_state);
ui.hiddenaddr_label->setVisible(hidden_state);
ui.hiddenport_label->setVisible(hidden_state);
ui.hiddenport_spinBox->setVisible(hidden_state);
if(mEntropyOk && mAllFieldsOk)
{ {
ui.hidden_checkbox->show(); ui.genButton->setEnabled(true) ;
ui.genButton->setIcon(QIcon(IMAGE_GOOD)) ;
if (ui.new_gpg_key_checkbox->isChecked()) ui.genButton->setToolTip(tr("Click to create your node and/or profile")) ;
{
// key length is only for pgp key creation
ui.keylength_label->show();
ui.keylength_comboBox->show();
}
else
{
ui.keylength_label->hide();
ui.keylength_comboBox->hide();
}
if(ui.hidden_checkbox->isChecked())
{
ui.hiddenaddr_input->show();
ui.hiddenaddr_label->show();
ui.label_hiddenaddr->show();
ui.hiddenport_label->show();
ui.hiddenport_spinBox->show();
}
else
{
ui.hiddenaddr_input->hide();
ui.hiddenaddr_label->hide();
ui.label_hiddenaddr->hide();
ui.hiddenport_label->hide();
ui.hiddenport_spinBox->hide();
}
} }
else else
{ {
ui.hiddenaddr_input->hide(); ui.genButton->setEnabled(false) ;
ui.hiddenaddr_label->hide(); ui.genButton->setIcon(QIcon(IMAGE_BAD)) ;
ui.label_hiddenaddr->hide(); ui.genButton->setToolTip(tr("Disabled until all fields correctly set and enough randomness collected.")) ;
ui.hiddenport_label->hide(); }
ui.hiddenport_spinBox->hide();
ui.hidden_checkbox->hide();
ui.keylength_label->hide();
ui.keylength_comboBox->hide();
if(ui.hidden_checkbox->isChecked())
ui.hidden_checkbox->setChecked(false) ;
}
} }
void GenCertDialog::exportIdentity() void GenCertDialog::exportIdentity()
@ -438,14 +327,63 @@ void GenCertDialog::exportIdentity()
QMessageBox::information(this,tr("Profile not saved"),tr("Your profile was not saved. An error occurred.")) ; QMessageBox::information(this,tr("Profile not saved"),tr("Your profile was not saved. An error occurred.")) ;
} }
void GenCertDialog::importIdentity() void GenCertDialog::updateCheckLabels()
{
QPixmap good( IMAGE_GOOD ) ;
QPixmap bad ( IMAGE_BAD ) ;
bool generate_new = !ui.reuse_existing_node_CB->isChecked();
mAllFieldsOk = true ;
if(ui.node_input->text().length() > 3)
ui.node_name_check_LB ->setPixmap(good) ;
else
{
mAllFieldsOk = false ;
ui.node_name_check_LB ->setPixmap(bad) ;
}
if(!generate_new || ui.name_input->text().length() > 3)
ui.profile_name_check_LB ->setPixmap(good) ;
else
{
mAllFieldsOk = false ;
ui.profile_name_check_LB ->setPixmap(bad) ;
}
if(ui.password_input->text().length() > 3)
ui.password_check_LB ->setPixmap(good) ;
else
{
mAllFieldsOk = false ;
ui.password_check_LB ->setPixmap(bad) ;
}
if(ui.password_input->text().length() > 3 && ui.password_input->text() == ui.password_input_2->text())
ui.password2_check_LB ->setPixmap(good) ;
else
{
if(generate_new)
mAllFieldsOk = false ;
ui.password2_check_LB ->setPixmap(bad) ;
}
if(mEntropyOk)
ui.randomness_check_LB->setPixmap(QPixmap(IMAGE_GOOD)) ;
else
ui.randomness_check_LB->setPixmap(QPixmap(IMAGE_BAD)) ;
setupState();
}
bool GenCertDialog::importIdentity()
{ {
QString fname ; QString fname ;
if(!misc::getOpenFileName(this,RshareSettings::LASTDIR_CERT,tr("Import profile"), tr("RetroShare profile files (*.asc);;All files (*)"),fname)) if(!misc::getOpenFileName(this,RshareSettings::LASTDIR_CERT,tr("Import profile"), tr("RetroShare profile files (*.asc);;All files (*)"),fname))
return ; return false;
if(fname.isNull()) if(fname.isNull())
return ; return false;
RsPgpId gpg_id ; RsPgpId gpg_id ;
std::string err_string ; std::string err_string ;
@ -453,7 +391,7 @@ void GenCertDialog::importIdentity()
if(!RsAccounts::ImportIdentity(fname.toStdString(),gpg_id,err_string)) if(!RsAccounts::ImportIdentity(fname.toStdString(),gpg_id,err_string))
{ {
QMessageBox::information(this,tr("Profile not loaded"),tr("Your profile was not loaded properly:")+" \n "+QString::fromStdString(err_string)) ; QMessageBox::information(this,tr("Profile not loaded"),tr("Your profile was not loaded properly:")+" \n "+QString::fromStdString(err_string)) ;
return ; return false;
} }
else else
{ {
@ -463,9 +401,9 @@ void GenCertDialog::importIdentity()
std::cerr << "Adding PGPUser: " << name << " id: " << gpg_id << std::endl; std::cerr << "Adding PGPUser: " << name << " id: " << gpg_id << std::endl;
QMessageBox::information(this,tr("New profile imported"),tr("Your profile was imported successfully:")+" \n"+"\nName :"+QString::fromStdString(name)+"\nemail: " + QString::fromStdString(email)+"\nKey ID: "+QString::fromStdString(gpg_id.toStdString())+"\n\n"+tr("You can use it now to create a new node.")) ; QMessageBox::information(this,tr("New profile imported"),tr("Your profile was imported successfully:")+" \n"+"\nName :"+QString::fromStdString(name)+"\nemail: " + QString::fromStdString(email)+"\nKey ID: "+QString::fromStdString(gpg_id.toStdString())+"\n\n"+tr("You can use it now to create a new node.")) ;
}
init() ; return true ;
}
} }
void GenCertDialog::genPerson() void GenCertDialog::genPerson()
@ -498,7 +436,7 @@ void GenCertDialog::genPerson()
} }
} }
if (ui.hidden_checkbox->isChecked()) if (ui.nodeType_CB->currentIndex()==1)
{ {
std::string hl = ui.hiddenaddr_input->text().toStdString(); std::string hl = ui.hiddenaddr_input->text().toStdString();
uint16_t port = ui.hiddenport_spinBox->value(); uint16_t port = ui.hiddenport_spinBox->value();
@ -514,7 +452,9 @@ void GenCertDialog::genPerson()
isHiddenLoc = true; isHiddenLoc = true;
} }
if (!genNewGPGKey) {
if (!genNewGPGKey)
{
if (genLoc.length() < 3) { if (genLoc.length() < 3) {
/* Message Dialog */ /* Message Dialog */
QMessageBox::warning(this, QMessageBox::warning(this,
@ -555,27 +495,27 @@ void GenCertDialog::genPerson()
} }
//generate a new gpg key //generate a new gpg key
std::string err_string; std::string err_string;
ui.no_gpg_key_label->setText(tr("Generating new PGP key pair, please be patient: this process needs generating large prime numbers, and can take some minutes on slow computers. \n\nFill in your PGP password when asked, to sign your new key.")); ui.no_gpg_key_label->setText(tr("Generating new node key, please be patient: this process needs generating large prime numbers, and can take some minutes on slow computers. \n\nFill in your password when asked, to sign your new key."));
ui.no_gpg_key_label->show(); ui.no_gpg_key_label->show();
ui.new_gpg_key_checkbox->hide(); ui.reuse_existing_node_CB->hide();
ui.name_label->hide(); ui.name_label->hide();
ui.name_input->hide(); ui.name_input->hide();
ui.nickname_label->hide(); ui.nickname_label->hide();
ui.nickname_input->hide(); ui.nickname_input->hide();
// ui.email_label->hide();
// ui.email_input->hide();
ui.password_label_2->hide(); ui.password_label_2->hide();
ui.password_input_2->hide(); ui.password_input_2->hide();
ui.password2_check_LB->hide();
ui.password_check_LB->hide();
ui.password_label->hide(); ui.password_label->hide();
ui.password_input->hide(); ui.password_input->hide();
ui.genPGPuserlabel->hide(); //ui.genPGPuserlabel->hide();
ui.genPGPuser->hide(); ui.genPGPuser->hide();
ui.node_label->hide(); ui.node_label->hide();
ui.node_input->hide(); ui.node_input->hide();
ui.genButton->hide(); ui.genButton->hide();
ui.importIdentity_PB->hide(); ui.importIdentity_PB->hide();
ui.genprofileinfo_label->hide(); ui.genprofileinfo_label->hide();
ui.hidden_checkbox->hide(); ui.nodeType_CB->hide();
ui.adv_checkbox->hide(); ui.adv_checkbox->hide();
ui.keylength_label->hide(); ui.keylength_label->hide();
ui.keylength_comboBox->hide(); ui.keylength_comboBox->hide();
@ -601,6 +541,8 @@ void GenCertDialog::genPerson()
setCursor(Qt::ArrowCursor) ; setCursor(Qt::ArrowCursor) ;
} }
// now cache the PGP password so that it's not asked again for immediately signing the key
rsNotify->cachePgpPassphrase(ui.password_input->text().toUtf8().constData()) ;
//generate a random ssl password //generate a random ssl password
std::string sslPasswd = RSRandom::random_alphaNumericString(RsInit::getSslPwdLen()) ; std::string sslPasswd = RSRandom::random_alphaNumericString(RsInit::getSslPwdLen()) ;
@ -615,6 +557,8 @@ void GenCertDialog::genPerson()
std::cout << "RsAccounts::GenerateSSLCertificate" << std::endl; std::cout << "RsAccounts::GenerateSSLCertificate" << std::endl;
bool okGen = RsAccounts::GenerateSSLCertificate(PGPId, "", genLoc, "", isHiddenLoc, sslPasswd, sslId, err); bool okGen = RsAccounts::GenerateSSLCertificate(PGPId, "", genLoc, "", isHiddenLoc, sslPasswd, sslId, err);
rsNotify->clearPgpPassphrase() ;
if (okGen) if (okGen)
{ {
/* complete the process */ /* complete the process */

View File

@ -39,14 +39,15 @@ public:
QString getGXSNickname() {return mGXSNickname;} QString getGXSNickname() {return mGXSNickname;}
private slots: private slots:
void genPerson(); void genPerson();
void importIdentity(); bool importIdentity();
void exportIdentity(); void exportIdentity();
void newGPGKeyGenUiSetup(); void setupState();
void switchReuseExistingNode();
void grabMouse(); void grabMouse();
void updateUiSetup(); void updateCheckLabels();
private: private:
void init(); void initKeyList();
/** Qt Designer generated object */ /** Qt Designer generated object */
Ui::GenCertDialog ui; Ui::GenCertDialog ui;
@ -54,6 +55,8 @@ private:
bool genNewGPGKey; bool genNewGPGKey;
bool haveGPGKeys; bool haveGPGKeys;
bool mOnlyGenerateIdentity; bool mOnlyGenerateIdentity;
bool mAllFieldsOk ;
bool mEntropyOk ;
QString mGXSNickname; QString mGXSNickname;
QTimer *entropy_timer ; QTimer *entropy_timer ;

File diff suppressed because it is too large Load Diff

View File

@ -25,6 +25,7 @@
#include "gui/notifyqt.h" #include "gui/notifyqt.h"
#include "gui/msgs/MessageComposer.h" #include "gui/msgs/MessageComposer.h"
#include "gui/connect/ConnectFriendWizard.h" #include "gui/connect/ConnectFriendWizard.h"
#include "gui/connect/FriendRecommendDialog.h"
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) #if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QUrlQuery> #include <QUrlQuery>
@ -60,13 +61,30 @@ HomePage::HomePage(QWidget *parent) :
QAction *SendAction = new QAction(QIcon(),tr("Send via Email"), this); QAction *SendAction = new QAction(QIcon(),tr("Send via Email"), this);
connect(SendAction, SIGNAL(triggered()), this, SLOT(runEmailClient())); connect(SendAction, SIGNAL(triggered()), this, SLOT(runEmailClient()));
QAction *RecAction = new QAction(QIcon(),tr("Recommend friends to each others"), this);
connect(RecAction, SIGNAL(triggered()), this, SLOT(recommendFriends()));
QMenu *menu = new QMenu(); QMenu *menu = new QMenu();
menu->addAction(CopyAction); menu->addAction(CopyAction);
menu->addAction(SaveAction); menu->addAction(SaveAction);
menu->addAction(SendAction); menu->addAction(SendAction);
menu->addAction(RecAction);
ui->shareButton->setMenu(menu); ui->shareButton->setMenu(menu);
int S = QFontMetricsF(font()).height();
QString help_str = tr(
" <h1><img width=\"%1\" src=\":/icons/help_64.png\">&nbsp;&nbsp;Welcome to Retroshare!</h1>\
<p>The first thing you have to do is to <b>make friends</b>. Once you create a network of Retroshare nodes, or join an existing network,\
you'll be able to exchange files, chat, talk in forums, etc. </p>\
<div align=center>\
<IMG align=\"center\" width=\"%2\" src=\":/images/network_map.png\"/> \
</div>\
<p>To do so, use the current page to exchange certificates with other persons you want your Retroshare node to connect to.</p> \
<p>Another option is to search the internet for \"Retroshare chat servers\" (independently administrated). These servers allow you to exchange \
certificates with a dedicated Retroshare node, through which\
you will be able to meet other people anonymously.</p> ").arg(QString::number(2*S)).arg(width()*0.5);
registerHelpButton(ui->helpButton,help_str,"HomePage") ;
} }
HomePage::~HomePage() HomePage::~HomePage()
@ -109,6 +127,11 @@ static void sendMail(QString sAddress, QString sSubject, QString sBody)
QDesktopServices::openUrl (url); QDesktopServices::openUrl (url);
} }
void HomePage::recommendFriends()
{
FriendRecommendDialog::showIt() ;
}
void HomePage::runEmailClient() void HomePage::runEmailClient()
{ {
sendMail("", tr("RetroShare Invite"), ui->userCertEdit->toPlainText()); sendMail("", tr("RetroShare Invite"), ui->userCertEdit->toPlainText());

View File

@ -53,7 +53,8 @@ private slots:
void runEmailClient(); void runEmailClient();
void copyCert(); void copyCert();
void saveCert(); void saveCert();
void addFriend(); void recommendFriends();
void addFriend();
private: private:
Ui::HomePage *ui; Ui::HomePage *ui;

View File

@ -6,31 +6,73 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>886</width> <width>1558</width>
<height>584</height> <height>699</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
<string>Form</string> <string>Form</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_2"> <layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0" colspan="4"> <item row="2" column="1" colspan="2">
<widget class="QLabel" name="label"> <widget class="QFrame" name="addframe">
<property name="sizePolicy"> <property name="styleSheet">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <string notr="true"/>
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="images.qrc">:/images/logo/logo_splash.png</pixmap>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_3">
<property name="font">
<font>
<pointsize>11</pointsize>
</font>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string>Did you receive a certificate from a friend?</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="addButton">
<property name="text">
<string>Add friends certificate</string>
</property>
<property name="icon">
<iconset resource="icons.qrc">
<normaloff>:/icons/png/invite.png</normaloff>:/icons/png/invite.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextBesideIcon</enum>
</property>
<property name="autoRaise">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="helpButton">
<property name="text">
<string>...</string>
</property>
<property name="icon">
<iconset resource="icons.qrc">
<normaloff>:/icons/help_64.png</normaloff>:/icons/help_64.png</iconset>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget> </widget>
</item> </item>
<item row="3" column="1" colspan="2"> <item row="3" column="1" colspan="2">
@ -44,6 +86,33 @@
<property name="verticalSpacing"> <property name="verticalSpacing">
<number>2</number> <number>2</number>
</property> </property>
<item row="2" column="0" colspan="2">
<widget class="QPlainTextEdit" name="userCertEdit">
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="whatsThis">
<string/>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="lineWrapMode">
<enum>QPlainTextEdit::NoWrap</enum>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="tabStopWidth">
<number>80</number>
</property>
<property name="centerOnScroll">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="0"> <item row="1" column="0">
<widget class="QLabel" name="userCertLabel"> <widget class="QLabel" name="userCertLabel">
<property name="sizePolicy"> <property name="sizePolicy">
@ -58,7 +127,7 @@
</font> </font>
</property> </property>
<property name="text"> <property name="text">
<string>The text below is your Retroshare certificate. Copy and share it with your friends</string> <string>The text below is your own Retroshare certificate. Send it to your friends</string>
</property> </property>
<property name="alignment"> <property name="alignment">
<set>Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft</set> <set>Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft</set>
@ -97,33 +166,6 @@
</property> </property>
</widget> </widget>
</item> </item>
<item row="2" column="0" colspan="2">
<widget class="QPlainTextEdit" name="userCertEdit">
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="whatsThis">
<string/>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="lineWrapMode">
<enum>QPlainTextEdit::NoWrap</enum>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="tabStopWidth">
<number>80</number>
</property>
<property name="centerOnScroll">
<bool>false</bool>
</property>
</widget>
</item>
</layout> </layout>
</item> </item>
<item row="4" column="1"> <item row="4" column="1">
@ -152,7 +194,7 @@
</font> </font>
</property> </property>
<property name="text"> <property name="text">
<string>RetroShare is an Open Source cross-platform, <string>Open Source cross-platform,
private and secure decentralized commmunication platform. private and secure decentralized commmunication platform.
</string> </string>
</property> </property>
@ -161,58 +203,34 @@ private and secure decentralized commmunication platform.
</property> </property>
</widget> </widget>
</item> </item>
<item row="2" column="1" colspan="2"> <item row="0" column="0" colspan="4">
<widget class="QFrame" name="addframe"> <widget class="QLabel" name="label">
<property name="styleSheet"> <property name="sizePolicy">
<string notr="true"/> <sizepolicy hsizetype="Expanding" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="images.qrc">:/images/logo/logo_splash.png</pixmap>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_3">
<property name="font">
<font>
<pointsize>11</pointsize>
</font>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string>You get certificate from your friend?</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="addButton">
<property name="text">
<string>Add friends certificate</string>
</property>
<property name="icon">
<iconset resource="icons.qrc">
<normaloff>:/icons/png/invite.png</normaloff>:/icons/png/invite.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextBesideIcon</enum>
</property>
<property name="autoRaise">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget> </widget>
</item> </item>
</layout> </layout>
<zorder>label</zorder>
<zorder>addFrame</zorder>
<zorder>label_2</zorder>
<zorder>addframe</zorder>
</widget> </widget>
<resources> <resources>
<include location="images.qrc"/>
<include location="icons.qrc"/> <include location="icons.qrc"/>
<include location="images.qrc"/>
</resources> </resources>
<connections/> <connections/>
</ui> </ui>

View File

@ -358,7 +358,7 @@ IdDialog::IdDialog(QWidget *parent) :
<p>An <b>circle</b> can be restricted to another circle, thereby limiting its visibility to members of that circle \ <p>An <b>circle</b> can be restricted to another circle, thereby limiting its visibility to members of that circle \
or even self-restricted, meaning that it is only visible to invited members.</p>") ; or even self-restricted, meaning that it is only visible to invited members.</p>") ;
registerHelpButton(ui->helpButton, hlp_str) ; registerHelpButton(ui->helpButton, hlp_str,"PeopleDialog") ;
// load settings // load settings
processSettings(true); processSettings(true);

View File

@ -1,7 +1,9 @@
#include <QToolButton> #include <QToolButton>
#include <QTimer>
#include <retroshare-gui/mainpage.h> #include <retroshare-gui/mainpage.h>
#include "common/FloatingHelpBrowser.h" #include "common/FloatingHelpBrowser.h"
#include "gui/settings/rsharesettings.h"
MainPage::MainPage(QWidget *parent , Qt::WindowFlags flags ) : QWidget(parent, flags) MainPage::MainPage(QWidget *parent , Qt::WindowFlags flags ) : QWidget(parent, flags)
{ {
@ -11,14 +13,28 @@ MainPage::MainPage(QWidget *parent , Qt::WindowFlags flags ) : QWidget(parent, f
mHelp = ""; mHelp = "";
} }
void MainPage::registerHelpButton(QToolButton *button,const QString& help_html_txt) void MainPage::registerHelpButton(QToolButton *button, const QString& help_html_text, const QString &code_name)
{ {
mHelpCodeName = code_name ;
if (mHelpBrowser == NULL) if (mHelpBrowser == NULL)
mHelpBrowser = new FloatingHelpBrowser(this, button) ; mHelpBrowser = new FloatingHelpBrowser(this, button) ;
float S = QFontMetricsF(button->font()).height() ; float S = QFontMetricsF(button->font()).height() ;
button->setIconSize(QSize(S,S)) ; button->setIconSize(QSize(S,S)) ;
mHelpBrowser->setHelpText(help_html_txt) ; mHelpBrowser->setHelpText(help_html_text) ;
} }
void MainPage::showEvent(QShowEvent *s)
{
if(!Settings->getPageAlreadyDisplayed(mHelpCodeName) && mHelpBrowser!=NULL)
{
// I use a timer to make sure that the GUI is able to process that.
QTimer::singleShot(1000, mHelpBrowser,SLOT(show()));
Settings->setPageAlreadyDisplayed(mHelpCodeName,true);
}
QWidget::showEvent(s);
}

View File

@ -19,14 +19,15 @@
* Boston, MA 02110-1301, USA. * Boston, MA 02110-1301, USA.
****************************************************************/ ****************************************************************/
#include <QMessageBox>
#include <QString>
#include <QtDebug>
#include <QIcon>
#include <QPixmap>
#include <QColorDialog> #include <QColorDialog>
#include <QDesktopServices> #include <QDesktopServices>
#include <QIcon>
#include <QMessageBox>
#include <QPixmap>
#include <QStatusBar>
#include <QString>
#include <QUrl> #include <QUrl>
#include <QtDebug>
#ifdef BLOGS #ifdef BLOGS
#include "gui/unfinished/blogs/BlogsDialog.h" #include "gui/unfinished/blogs/BlogsDialog.h"
@ -223,8 +224,11 @@ MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags)
if (!state.isEmpty()) restoreState(state); if (!state.isEmpty()) restoreState(state);
/** StatusBar section ********/ /** StatusBar section ********/
statusBar()->setVisible(Settings->valueFromGroup("StatusBar", "ShowStatusBar", QVariant(true)).toBool());
/* initialize combobox in status bar */ /* initialize combobox in status bar */
statusComboBox = new QComboBox(statusBar()); statusComboBox = new QComboBox(statusBar());
statusComboBox->setVisible(Settings->valueFromGroup("StatusBar", "ShowStatus", QVariant(true)).toBool());
statusComboBox->setFocusPolicy(Qt::ClickFocus); statusComboBox->setFocusPolicy(Qt::ClickFocus);
initializeStatusObject(statusComboBox, true); initializeStatusObject(statusComboBox, true);
@ -237,32 +241,39 @@ MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags)
statusBar()->addWidget(widget); statusBar()->addWidget(widget);
peerstatus = new PeerStatus(); peerstatus = new PeerStatus();
peerstatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowPeer", QVariant(true)).toBool());
statusBar()->addWidget(peerstatus); statusBar()->addWidget(peerstatus);
natstatus = new NATStatus(); natstatus = new NATStatus();
natstatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowNAT", QVariant(true)).toBool());
statusBar()->addWidget(natstatus); statusBar()->addWidget(natstatus);
dhtstatus = new DHTStatus(); dhtstatus = new DHTStatus();
dhtstatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowDHT", QVariant(true)).toBool());
statusBar()->addWidget(dhtstatus); statusBar()->addWidget(dhtstatus);
hashingstatus = new HashingStatus(); hashingstatus = new HashingStatus();
hashingstatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowHashing", QVariant(true)).toBool());
statusBar()->addPermanentWidget(hashingstatus, 1); statusBar()->addPermanentWidget(hashingstatus, 1);
discstatus = new DiscStatus(); discstatus = new DiscStatus();
discstatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowDisc", QVariant(true)).toBool());
statusBar()->addPermanentWidget(discstatus); statusBar()->addPermanentWidget(discstatus);
ratesstatus = new RatesStatus(); ratesstatus = new RatesStatus();
ratesstatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowRate", QVariant(true)).toBool());
statusBar()->addPermanentWidget(ratesstatus); statusBar()->addPermanentWidget(ratesstatus);
opModeStatus = new OpModeStatus(); opModeStatus = new OpModeStatus();
opModeStatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowOpMode", QVariant(true)).toBool());
statusBar()->addPermanentWidget(opModeStatus); statusBar()->addPermanentWidget(opModeStatus);
soundStatus = new SoundStatus(); soundStatus = new SoundStatus();
soundStatus->setHidden(Settings->valueFromGroup("StatusBar", "HideSound", QVariant(false)).toBool()); soundStatus->setVisible(Settings->valueFromGroup("StatusBar", "ShowSound", QVariant(true)).toBool());
statusBar()->addPermanentWidget(soundStatus); statusBar()->addPermanentWidget(soundStatus);
toasterDisable = new ToasterDisable(); toasterDisable = new ToasterDisable();
toasterDisable->setHidden(Settings->valueFromGroup("StatusBar", "HideToaster", QVariant(false)).toBool()); toasterDisable->setVisible(Settings->valueFromGroup("StatusBar", "ShowToaster", QVariant(true)).toBool());
statusBar()->addPermanentWidget(toasterDisable); statusBar()->addPermanentWidget(toasterDisable);
sysTrayStatus = new SysTrayStatus(); sysTrayStatus = new SysTrayStatus();
@ -309,6 +320,7 @@ MainWindow::~MainWindow()
Settings->setValueToGroup("MainWindow", "SplitterState", ui->splitter->saveState()); Settings->setValueToGroup("MainWindow", "SplitterState", ui->splitter->saveState());
Settings->setValueToGroup("MainWindow", "State", saveState()); Settings->setValueToGroup("MainWindow", "State", saveState());
delete statusComboBox;
delete peerstatus; delete peerstatus;
delete natstatus; delete natstatus;
delete dhtstatus; delete dhtstatus;
@ -344,28 +356,24 @@ void MainWindow::initStackedPage()
addPage(homePage = new HomePage(ui->stackPages), grp, NULL); addPage(homePage = new HomePage(ui->stackPages), grp, NULL);
addPage(newsFeed = new NewsFeed(ui->stackPages), grp, &notify);
addPage(friendsDialog = new FriendsDialog(ui->stackPages), grp, &notify);
#ifdef RS_USE_NEW_PEOPLE_DIALOG
PeopleDialog *peopleDialog = NULL;
addPage(peopleDialog = new PeopleDialog(ui->stackPages), grp, &notify);
#endif
addPage(idDialog = new IdDialog(ui->stackPages), grp, &notify);
//#ifdef RS_USE_CIRCLES //#ifdef RS_USE_CIRCLES
// CirclesDialog *circlesDialog = NULL; // CirclesDialog *circlesDialog = NULL;
// addPage(circlesDialog = new CirclesDialog(ui->stackPages), grp, &notify); // addPage(circlesDialog = new CirclesDialog(ui->stackPages), grp, &notify);
//#endif //#endif
addPage(friendsDialog = new FriendsDialog(ui->stackPages), grp, &notify);
addPage(transfersDialog = new TransfersDialog(ui->stackPages), grp, &notify); addPage(idDialog = new IdDialog(ui->stackPages), grp, &notify);
addPage(chatLobbyDialog = new ChatLobbyWidget(ui->stackPages), grp, &notify); addPage(chatLobbyDialog = new ChatLobbyWidget(ui->stackPages), grp, &notify);
addPage(messagesDialog = new MessagesDialog(ui->stackPages), grp, &notify); addPage(messagesDialog = new MessagesDialog(ui->stackPages), grp, &notify);
addPage(transfersDialog = new TransfersDialog(ui->stackPages), grp, &notify);
addPage(gxschannelDialog = new GxsChannelDialog(ui->stackPages), grp, &notify); addPage(gxschannelDialog = new GxsChannelDialog(ui->stackPages), grp, &notify);
addPage(gxsforumDialog = new GxsForumsDialog(ui->stackPages), grp, &notify); addPage(gxsforumDialog = new GxsForumsDialog(ui->stackPages), grp, &notify);
addPage(postedDialog = new PostedDialog(ui->stackPages), grp, &notify); addPage(postedDialog = new PostedDialog(ui->stackPages), grp, &notify);
#ifdef RS_USE_NEW_PEOPLE_DIALOG
PeopleDialog *peopleDialog = NULL;
addPage(peopleDialog = new PeopleDialog(ui->stackPages), grp, &notify);
#endif
addPage(newsFeed = new NewsFeed(ui->stackPages), grp, &notify);
#ifdef RS_USE_WIKI #ifdef RS_USE_WIKI
WikiDialog *wikiDialog = NULL; WikiDialog *wikiDialog = NULL;
addPage(wikiDialog = new WikiDialog(ui->stackPages), grp, &notify); addPage(wikiDialog = new WikiDialog(ui->stackPages), grp, &notify);
@ -417,6 +425,7 @@ void MainWindow::initStackedPage()
addPage(getStartedPage = new GetStartedDialog(ui->stackPages), grp, NULL); addPage(getStartedPage = new GetStartedDialog(ui->stackPages), grp, NULL);
} }
#endif #endif
addPage(settingsDialog = new SettingsPage(ui->stackPages),grp,&notify);
/* Create the toolbar */ /* Create the toolbar */
ui->toolBarPage->addActions(grp->actions()); ui->toolBarPage->addActions(grp->actions());
@ -430,10 +439,14 @@ void MainWindow::initStackedPage()
#endif #endif
/** Add icon on Action bar */ /** Add icon on Action bar */
addAction(new QAction(QIcon(IMAGE_ADDFRIEND), tr("Add"), ui->toolBarAction), &MainWindow::addFriend, SLOT(addFriend())); // I remove add a friend because it's in HOME ghibli
//addAction(new QAction(QIcon(IMAGE_ADDFRIEND), tr("Add"), ui->toolBarAction), &MainWindow::addFriend, SLOT(addFriend()));
//addAction(new QAction(QIcon(IMAGE_NEWRSCOLLECTION), tr("New"), ui->toolBarAction), &MainWindow::newRsCollection, SLOT(newRsCollection())); //addAction(new QAction(QIcon(IMAGE_NEWRSCOLLECTION), tr("New"), ui->toolBarAction), &MainWindow::newRsCollection, SLOT(newRsCollection()));
addAction(new QAction(QIcon(IMAGE_PREFERENCES), tr("Options"), ui->toolBarAction), &MainWindow::showSettings, SLOT(showSettings())); //addAction(new QAction(QIcon(IMAGE_PREFERENCES), tr("Options"), ui->toolBarAction), &MainWindow::showSettings, SLOT(showSettings()));
addAction(new QAction(QIcon(IMAGE_ABOUT), tr("About"), ui->toolBarAction), &MainWindow::showabout, SLOT(showabout()));
// Removed About because it's now in options.
//addAction(new QAction(QIcon(IMAGE_ABOUT), tr("About"), ui->toolBarAction), &MainWindow::showabout, SLOT(showabout()));
addAction(new QAction(QIcon(IMAGE_QUIT), tr("Quit"), ui->toolBarAction), &MainWindow::doQuit, SLOT(doQuit())); addAction(new QAction(QIcon(IMAGE_QUIT), tr("Quit"), ui->toolBarAction), &MainWindow::doQuit, SLOT(doQuit()));
QList<QPair<MainPage*, QPair<QAction*, QListWidgetItem*> > >::iterator notifyIt; QList<QPair<MainPage*, QPair<QAction*, QListWidgetItem*> > >::iterator notifyIt;
@ -758,11 +771,7 @@ void MainWindow::updateFriends()
void MainWindow::postModDirectories(bool update_local) void MainWindow::postModDirectories(bool update_local)
{ {
RSettingsWin::postModDirectories(update_local); //RSettingsPage::postModDirectories(update_local);
// Why would we need that?? The effect is to reset the flags while we're changing them, so it's really not
// a good idea.
//ShareManager::postModDirectories(update_local);
QCoreApplication::flush(); QCoreApplication::flush();
} }
@ -891,6 +900,9 @@ void SetForegroundWindowInternal(HWND hWnd)
_instance->ui->stackPages->setCurrentPage( _instance->transfersDialog ); _instance->ui->stackPages->setCurrentPage( _instance->transfersDialog );
_instance->transfersDialog->activatePage(TransfersDialog::LocalSharedFilesTab) ; _instance->transfersDialog->activatePage(TransfersDialog::LocalSharedFilesTab) ;
break; break;
case Options:
_instance->ui->stackPages->setCurrentPage( _instance->settingsDialog );
break;
case Messages: case Messages:
_instance->ui->stackPages->setCurrentPage( _instance->messagesDialog ); _instance->ui->stackPages->setCurrentPage( _instance->messagesDialog );
break; break;
@ -930,6 +942,9 @@ void SetForegroundWindowInternal(HWND hWnd)
if (page == _instance->friendsDialog) { if (page == _instance->friendsDialog) {
return Friends; return Friends;
} }
if (page == _instance->settingsDialog) {
return Options;
}
if (page == _instance->chatLobbyDialog) { if (page == _instance->chatLobbyDialog) {
return ChatLobby; return ChatLobby;
} }
@ -981,6 +996,8 @@ void SetForegroundWindowInternal(HWND hWnd)
return _instance->idDialog; return _instance->idDialog;
case ChatLobby: case ChatLobby:
return _instance->chatLobbyDialog; return _instance->chatLobbyDialog;
case Options:
return _instance->settingsDialog;
case Transfers: case Transfers:
return _instance->transfersDialog; return _instance->transfersDialog;
case SharedDirectories: case SharedDirectories:
@ -1044,7 +1061,7 @@ MainWindow::showMess()
/** Shows Options */ /** Shows Options */
void MainWindow::showSettings() void MainWindow::showSettings()
{ {
RSettingsWin::showYourself(this); showWindow(MainWindow::Options);
} }
/** Shows Messenger window */ /** Shows Messenger window */
@ -1474,10 +1491,73 @@ void MainWindow::processLastArgs()
} }
} }
void MainWindow::switchVisibilityStatus(StatusElement e,bool b)
{
switch(e)
{
case StatusGrpStatus : getInstance()->statusBar() ->setVisible(b); break ;
case StatusCompactMode : getInstance()->setCompactStatusMode(b) ; break ;
case StatusShowToolTip : getInstance()->toggleStatusToolTip(b) ; break ;
case StatusShowCBox : getInstance()->statusComboBoxInstance() ->setVisible(b); break ;
case StatusShowStatus : getInstance()->peerstatusInstance() ->setVisible(b); break ;
case StatusShowPeer : getInstance()->natstatusInstance() ->setVisible(b); break ;
case StatusShowDHT : getInstance()->dhtstatusInstance() ->setVisible(b); break ;
case StatusShowHashing : getInstance()->hashingstatusInstance() ->setVisible(b); break ;
case StatusShowDisc : getInstance()->discstatusInstance() ->setVisible(b); break ;
case StatusShowRate : getInstance()->ratesstatusInstance() ->setVisible(b); break ;
case StatusShowOpMode : getInstance()->opModeStatusInstance() ->setVisible(b); break ;
case StatusShowSound : getInstance()->soundStatusInstance() ->setVisible(b); break ;
case StatusShowToaster : getInstance()->toasterDisableInstance() ->setVisible(b); break ;
case StatusShowSystray : getInstance()->sysTrayStatusInstance() ->setVisible(b); break ;
default:
std::cerr << "(EE) Unknown object to change visibility of: " << (int)e << std::endl;
}
}
//void MainWindow::servicePermission() //void MainWindow::servicePermission()
//{ //{
// ServicePermissionDialog::showYourself(); // ServicePermissionDialog::showYourself();
//} //}
QComboBox *MainWindow::statusComboBoxInstance()
{
return statusComboBox;
}
PeerStatus *MainWindow::peerstatusInstance()
{
return peerstatus;
}
NATStatus *MainWindow::natstatusInstance()
{
return natstatus;
}
DHTStatus *MainWindow::dhtstatusInstance()
{
return dhtstatus;
}
HashingStatus *MainWindow::hashingstatusInstance()
{
return hashingstatus;
}
DiscStatus *MainWindow::discstatusInstance()
{
return discstatus;
}
RatesStatus *MainWindow::ratesstatusInstance()
{
return ratesstatus;
}
OpModeStatus *MainWindow::opModeStatusInstance()
{
return opModeStatus;
}
SoundStatus *MainWindow::soundStatusInstance() SoundStatus *MainWindow::soundStatusInstance()
{ {

View File

@ -53,6 +53,7 @@ class PostedDialog;
class FriendsDialog; class FriendsDialog;
class IdDialog; class IdDialog;
class ChatLobbyWidget; class ChatLobbyWidget;
class SettingsPage ;
class ChatDialog; class ChatDialog;
class NetworkDialog; class NetworkDialog;
class SearchDialog; class SearchDialog;
@ -104,7 +105,26 @@ public:
Links = 10, /** Links page. */ Links = 10, /** Links page. */
#endif #endif
Posted = 11, /** Posted links */ Posted = 11, /** Posted links */
People = 12 /** People page. */ People = 12, /** People page. */
Options = 13 /** People page. */
};
enum StatusElement {
StatusGrpStatus = 0x01,
StatusCompactMode = 0x02,
StatusShowToolTip = 0x03,
StatusShowStatus = 0x04,
StatusShowPeer = 0x05,
StatusShowDHT = 0x06,
StatusShowHashing = 0x07,
StatusShowDisc = 0x08,
StatusShowRate = 0x09,
StatusShowOpMode = 0x0a,
StatusShowSound = 0x0b,
StatusShowToaster = 0x0c,
StatusShowSystray = 0x0d,
StatusShowCBox = 0x0e
}; };
/** Create main window */ /** Create main window */
@ -142,6 +162,7 @@ public:
IdDialog *idDialog ; IdDialog *idDialog ;
ChatLobbyWidget *chatLobbyDialog; ChatLobbyWidget *chatLobbyDialog;
MessagesDialog *messagesDialog; MessagesDialog *messagesDialog;
SettingsPage *settingsDialog;
SharedFilesDialog *sharedfilesDialog; SharedFilesDialog *sharedfilesDialog;
GxsChannelDialog *gxschannelDialog ; GxsChannelDialog *gxschannelDialog ;
GxsForumsDialog *gxsforumDialog ; GxsForumsDialog *gxsforumDialog ;
@ -168,11 +189,21 @@ public:
static void installNotifyIcons(); static void installNotifyIcons();
static void displayLobbySystrayMsg(const QString&,const QString&); static void displayLobbySystrayMsg(const QString&,const QString&);
static void switchVisibilityStatus(MainWindow::StatusElement e,bool b);
/* initialize widget with status informations, status constant stored in data or in Qt::UserRole */ /* initialize widget with status informations, status constant stored in data or in Qt::UserRole */
void initializeStatusObject(QObject *pObject, bool bConnect); void initializeStatusObject(QObject *pObject, bool bConnect);
void removeStatusObject(QObject *pObject); void removeStatusObject(QObject *pObject);
void setStatus(QObject *pObject, int nStatus); void setStatus(QObject *pObject, int nStatus);
QComboBox *statusComboBoxInstance();
PeerStatus *peerstatusInstance();
NATStatus *natstatusInstance();
DHTStatus *dhtstatusInstance();
HashingStatus *hashingstatusInstance();
DiscStatus *discstatusInstance();
RatesStatus *ratesstatusInstance();
OpModeStatus *opModeStatusInstance();
SoundStatus *soundStatusInstance(); SoundStatus *soundStatusInstance();
ToasterDisable *toasterDisableInstance(); ToasterDisable *toasterDisableInstance();
SysTrayStatus *sysTrayStatusInstance(); SysTrayStatus *sysTrayStatusInstance();

View File

@ -306,7 +306,7 @@ MessagesDialog::MessagesDialog(QWidget *parent)
to a channel's owner.</p> \ to a channel's owner.</p> \
").arg(QString::number(2*S)).arg(QString::number(S)) ; ").arg(QString::number(2*S)).arg(QString::number(S)) ;
registerHelpButton(ui.helpButton,help_str) ; registerHelpButton(ui.helpButton,help_str,"MessagesDialog") ;
} }
MessagesDialog::~MessagesDialog() MessagesDialog::~MessagesDialog()

View File

@ -45,7 +45,7 @@ public:
~MessagesDialog(); ~MessagesDialog();
virtual QIcon iconPixmap() const { return QIcon(IMAGE_MESSAGES) ; } //MainPage virtual QIcon iconPixmap() const { return QIcon(IMAGE_MESSAGES) ; } //MainPage
virtual QString pageName() const { return tr("Messages") ; } //MainPage virtual QString pageName() const { return tr("Mail") ; } //MainPage
virtual QString helpText() const { return ""; } //MainPage virtual QString helpText() const { return ""; } //MainPage
virtual UserNotify *getUserNotify(QObject *parent); virtual UserNotify *getUserNotify(QObject *parent);

View File

@ -124,7 +124,7 @@ NewsFeed::NewsFeed(QWidget *parent) :
QString hlp_str = tr( QString hlp_str = tr(
" <h1><img width=\"32\" src=\":/icons/help_64.png\">&nbsp;&nbsp;News Feed</h1> \ " <h1><img width=\"32\" src=\":/icons/help_64.png\">&nbsp;&nbsp;News Feed</h1> \
<p>The News Feed displays the last events on your network, sorted by the time you received them. \ <p>The Log Feed displays the last events on your network, sorted by the time you received them. \
This gives you a summary of the activity of your friends. \ This gives you a summary of the activity of your friends. \
You can configure which events to show by pressing on <b>Options</b>. </p> \ You can configure which events to show by pressing on <b>Options</b>. </p> \
<p>The various events shown are: \ <p>The various events shown are: \
@ -136,7 +136,7 @@ QString hlp_str = tr(
</ul> </p> \ </ul> </p> \
") ; ") ;
registerHelpButton(ui->helpButton,hlp_str) ; registerHelpButton(ui->helpButton,hlp_str,"NewFeed") ;
// load settings // load settings
processSettings(true); processSettings(true);
@ -1396,5 +1396,5 @@ void NewsFeed::sendNewsFeedChanged()
void NewsFeed::feedoptions() void NewsFeed::feedoptions()
{ {
RSettingsWin::showYourself(this, RSettingsWin::Notify); SettingsPage::showYourself(this, SettingsPage::Notify);
} }

View File

@ -49,7 +49,7 @@ public:
virtual ~NewsFeed(); virtual ~NewsFeed();
virtual QIcon iconPixmap() const { return QIcon(IMAGE_NEWSFEED) ; } //MainPage virtual QIcon iconPixmap() const { return QIcon(IMAGE_NEWSFEED) ; } //MainPage
virtual QString pageName() const { return tr("News feed") ; } //MainPage virtual QString pageName() const { return tr("Log") ; } //MainPage
virtual QString helpText() const { return ""; } //MainPage virtual QString helpText() const { return ""; } //MainPage
virtual UserNotify *getUserNotify(QObject *parent); virtual UserNotify *getUserNotify(QObject *parent);

View File

@ -69,7 +69,7 @@
<item> <item>
<widget class="StyledLabel" name="titleBarLabel"> <widget class="StyledLabel" name="titleBarLabel">
<property name="text"> <property name="text">
<string>News Feed</string> <string>Log entries</string>
</property> </property>
</widget> </widget>
</item> </item>
@ -109,7 +109,7 @@
<enum>Qt::NoFocus</enum> <enum>Qt::NoFocus</enum>
</property> </property>
<property name="icon"> <property name="icon">
<iconset resource="images.qrc"> <iconset resource="icons.qrc">
<normaloff>:/icons/help_64.png</normaloff>:/icons/help_64.png</iconset> <normaloff>:/icons/help_64.png</normaloff>:/icons/help_64.png</iconset>
</property> </property>
<property name="iconSize"> <property name="iconSize">
@ -155,7 +155,6 @@
</customwidget> </customwidget>
</customwidgets> </customwidgets>
<resources> <resources>
<include location="images.qrc"/>
<include location="icons.qrc"/> <include location="icons.qrc"/>
</resources> </resources>
<connections/> <connections/>

View File

@ -39,7 +39,7 @@ public:
~PostedDialog(); ~PostedDialog();
virtual QIcon iconPixmap() const { return QIcon(IMAGE_POSTED) ; } //MainPage virtual QIcon iconPixmap() const { return QIcon(IMAGE_POSTED) ; } //MainPage
virtual QString pageName() const { return tr("Posted") ; } //MainPage virtual QString pageName() const { return tr("Links") ; } //MainPage
virtual QString helpText() const { return ""; } //MainPage virtual QString helpText() const { return ""; } //MainPage
virtual UserNotify *getUserNotify(QObject *parent); virtual UserNotify *getUserNotify(QObject *parent);

View File

@ -6,8 +6,8 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>291</width> <width>430</width>
<height>433</height> <height>552</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -220,7 +220,7 @@
<item> <item>
<widget class="QLabel" name="label_3"> <widget class="QLabel" name="label_3">
<property name="text"> <property name="text">
<string>Name (PGP Id) - location:</string> <string>Profile - Location</string>
</property> </property>
</widget> </widget>
</item> </item>

View File

@ -178,7 +178,7 @@ ChatLobbyDialog::ChatLobbyDialog(const ChatLobbyId& lid, QWidget *parent, Qt::Wi
unsubscribeButton->setMaximumSize(QSize(2.4*S,2.4*S)) ; unsubscribeButton->setMaximumSize(QSize(2.4*S,2.4*S)) ;
unsubscribeButton->setText(QString()) ; unsubscribeButton->setText(QString()) ;
unsubscribeButton->setAutoRaise(true) ; unsubscribeButton->setAutoRaise(true) ;
unsubscribeButton->setToolTip(tr("Leave this lobby (Unsubscribe)")); unsubscribeButton->setToolTip(tr("Leave this chat room (Unsubscribe)"));
{ {
QIcon icon ; QIcon icon ;
@ -314,7 +314,7 @@ void ChatLobbyDialog::init()
{ {
title = QString::fromUtf8(linfo.lobby_name.c_str()); title = QString::fromUtf8(linfo.lobby_name.c_str());
QString msg = tr("Welcome to lobby %1").arg(RsHtml::plainText(linfo.lobby_name)); QString msg = tr("Welcome to chat room %1").arg(RsHtml::plainText(linfo.lobby_name));
_lobby_name = QString::fromUtf8(linfo.lobby_name.c_str()) ; _lobby_name = QString::fromUtf8(linfo.lobby_name.c_str()) ;
if (!linfo.lobby_topic.empty()) { if (!linfo.lobby_topic.empty()) {
msg += "\n" + tr("Topic: %1").arg(RsHtml::plainText(linfo.lobby_topic)); msg += "\n" + tr("Topic: %1").arg(RsHtml::plainText(linfo.lobby_topic));
@ -480,9 +480,9 @@ void ChatLobbyDialog::addChatMsg(const ChatMessage& msg)
QString notifyMsg = name + ": " + editor.toPlainText(); QString notifyMsg = name + ": " + editor.toPlainText();
if(notifyMsg.length() > 30) if(notifyMsg.length() > 30)
MainWindow::displayLobbySystrayMsg(tr("Lobby chat") + ": " + _lobby_name, notifyMsg.left(30) + QString("...")); MainWindow::displayLobbySystrayMsg(tr("Room chat") + ": " + _lobby_name, notifyMsg.left(30) + QString("..."));
else else
MainWindow::displayLobbySystrayMsg(tr("Lobby chat") + ": " + _lobby_name, notifyMsg); MainWindow::displayLobbySystrayMsg(tr("Room chat") + ": " + _lobby_name, notifyMsg);
} }
// also update peer list. // also update peer list.
@ -790,12 +790,12 @@ void ChatLobbyDialog::displayLobbyEvent(int event_type, const RsGxsId& gxs_id, c
{ {
case RS_CHAT_LOBBY_EVENT_PEER_LEFT: case RS_CHAT_LOBBY_EVENT_PEER_LEFT:
qsParticipant=gxs_id; qsParticipant=gxs_id;
ui.chatWidget->addChatMsg(true, tr("Lobby management"), QDateTime::currentDateTime(), QDateTime::currentDateTime(), tr("%1 has left the lobby.").arg(RsHtml::plainText(name)), ChatWidget::MSGTYPE_SYSTEM); ui.chatWidget->addChatMsg(true, tr("Lobby management"), QDateTime::currentDateTime(), QDateTime::currentDateTime(), tr("%1 has left the room.").arg(RsHtml::plainText(name)), ChatWidget::MSGTYPE_SYSTEM);
emit peerLeft(id()) ; emit peerLeft(id()) ;
break; break;
case RS_CHAT_LOBBY_EVENT_PEER_JOINED: case RS_CHAT_LOBBY_EVENT_PEER_JOINED:
qsParticipant=gxs_id; qsParticipant=gxs_id;
ui.chatWidget->addChatMsg(true, tr("Lobby management"), QDateTime::currentDateTime(), QDateTime::currentDateTime(), tr("%1 joined the lobby.").arg(RsHtml::plainText(name)), ChatWidget::MSGTYPE_SYSTEM); ui.chatWidget->addChatMsg(true, tr("Lobby management"), QDateTime::currentDateTime(), QDateTime::currentDateTime(), tr("%1 joined the room.").arg(RsHtml::plainText(name)), ChatWidget::MSGTYPE_SYSTEM);
emit peerJoined(id()) ; emit peerJoined(id()) ;
break; break;
case RS_CHAT_LOBBY_EVENT_PEER_STATUS: case RS_CHAT_LOBBY_EVENT_PEER_STATUS:
@ -827,10 +827,10 @@ void ChatLobbyDialog::displayLobbyEvent(int event_type, const RsGxsId& gxs_id, c
} }
break; break;
case RS_CHAT_LOBBY_EVENT_KEEP_ALIVE: case RS_CHAT_LOBBY_EVENT_KEEP_ALIVE:
//std::cerr << "Received keep alive packet from " << nickname.toStdString() << " in lobby " << getPeerId() << std::endl; //std::cerr << "Received keep alive packet from " << nickname.toStdString() << " in chat room " << getPeerId() << std::endl;
break; break;
default: default:
std::cerr << "ChatLobbyDialog::displayLobbyEvent() Unhandled lobby event type " << event_type << std::endl; std::cerr << "ChatLobbyDialog::displayLobbyEvent() Unhandled chat room event type " << event_type << std::endl;
} }
if (!qsParticipant.isNull()) if (!qsParticipant.isNull())
@ -854,7 +854,7 @@ bool ChatLobbyDialog::canClose()
} }
*/ */
if (QMessageBox::Yes == QMessageBox::question(this, tr("Unsubscribe to lobby"), tr("Do you want to unsubscribe to this chat lobby?"), QMessageBox::Yes | QMessageBox::No)) { if (QMessageBox::Yes == QMessageBox::question(this, tr("Unsubscribe from chat room"), tr("Do you want to unsubscribe to this chat room?"), QMessageBox::Yes | QMessageBox::No)) {
return true; return true;
} }

View File

@ -33,7 +33,7 @@
ChatLobbyUserNotify::ChatLobbyUserNotify(QObject *parent) : ChatLobbyUserNotify::ChatLobbyUserNotify(QObject *parent) :
UserNotify(parent) UserNotify(parent)
{ {
_name = tr("Chat Lobbies"); _name = tr("Chats");
_group = "ChatLobby"; _group = "ChatLobby";
_bCheckForNickName = Settings->valueFromGroup(_group, "CheckForNickName", true).toBool(); _bCheckForNickName = Settings->valueFromGroup(_group, "CheckForNickName", true).toBool();

View File

@ -614,7 +614,6 @@ bool ChatWidget::eventFilter(QObject *obj, QEvent *event)
else { else {
completionWord.clear(); completionWord.clear();
} }
}
if ((keyEvent->modifiers() & ui->chatTextEdit->getCompleterKeyModifiers()) && keyEvent->key() == ui->chatTextEdit->getCompleterKey()) { if ((keyEvent->modifiers() & ui->chatTextEdit->getCompleterKeyModifiers()) && keyEvent->key() == ui->chatTextEdit->getCompleterKey()) {
completer->setModel(modelFromPeers()); completer->setModel(modelFromPeers());
} }
@ -622,6 +621,7 @@ bool ChatWidget::eventFilter(QObject *obj, QEvent *event)
ui->chatTextEdit->forceCompleterShowNextKeyEvent("@"); ui->chatTextEdit->forceCompleterShowNextKeyEvent("@");
completer->setModel(modelFromPeers()); completer->setModel(modelFromPeers());
} }
}
if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) { if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) {
// Enter pressed // Enter pressed
if (Settings->getChatSendMessageWithCtrlReturn()) { if (Settings->getChatSendMessageWithCtrlReturn()) {
@ -631,7 +631,7 @@ bool ChatWidget::eventFilter(QObject *obj, QEvent *event)
return true; // eat event return true; // eat event
} }
} else { } else {
if (keyEvent->modifiers() & Qt::ControlModifier) { if ((keyEvent->modifiers() & Qt::ControlModifier) || (keyEvent->modifiers() & Qt::ShiftModifier)){
// insert return // insert return
ui->chatTextEdit->textCursor().insertText("\n"); ui->chatTextEdit->textCursor().insertText("\n");
} else { } else {
@ -1006,10 +1006,10 @@ void ChatWidget::pasteText(const QString& S)
setColorAndFont(false); setColorAndFont(false);
} }
void ChatWidget::pasteCreateMsgLink() //void ChatWidget::pasteCreateMsgLink()
{ //{
RSettingsWin::showYourself(this, RSettingsWin::Chat); // RSettingsWin::showYourself(this, RSettingsWin::Chat);
} //}
void ChatWidget::contextMenuTextBrowser(QPoint point) void ChatWidget::contextMenuTextBrowser(QPoint point)
{ {
@ -1088,8 +1088,8 @@ void ChatWidget::updateStatusTyping()
#ifdef ONLY_FOR_LINGUIST #ifdef ONLY_FOR_LINGUIST
tr("is typing..."); tr("is typing...");
#endif #endif
if(!Settings->getChatDoNotSendIsTyping())
rsMsgs->sendStatusString(chatId, "is typing..."); rsMsgs->sendStatusString(chatId, "is typing...");
lastStatusSendTime = time(NULL) ; lastStatusSendTime = time(NULL) ;
} }
} }

View File

@ -127,7 +127,7 @@ public slots:
void updateStatus(const QString &peer_id, int status); void updateStatus(const QString &peer_id, int status);
private slots: private slots:
void pasteCreateMsgLink() ; //void pasteCreateMsgLink() ;
void clearChatHistory(); void clearChatHistory();
void deleteChatHistory(); void deleteChatHistory();
void messageHistory(); void messageHistory();

View File

@ -40,7 +40,7 @@ CreateLobbyDialog::CreateLobbyDialog(const std::set<RsPeerId>& peer_list, int pr
ui->setupUi(this); ui->setupUi(this);
ui->headerFrame->setHeaderImage(QPixmap(":/icons/png/chat-lobbies.png")); ui->headerFrame->setHeaderImage(QPixmap(":/icons/png/chat-lobbies.png"));
ui->headerFrame->setHeaderText(tr("Create Chat Lobby")); ui->headerFrame->setHeaderText(tr("Create Chat Room"));
RsGxsId default_identity ; RsGxsId default_identity ;
rsMsgs->getDefaultIdentityForChatLobby(default_identity) ; rsMsgs->getDefaultIdentityForChatLobby(default_identity) ;
@ -48,7 +48,7 @@ CreateLobbyDialog::CreateLobbyDialog(const std::set<RsPeerId>& peer_list, int pr
ui->idChooser_CB->loadIds(IDCHOOSER_ID_REQUIRED, default_identity); ui->idChooser_CB->loadIds(IDCHOOSER_ID_REQUIRED, default_identity);
#if QT_VERSION >= 0x040700 #if QT_VERSION >= 0x040700
ui->lobbyName_LE->setPlaceholderText(tr("Put a sensible lobby name here")); ui->lobbyName_LE->setPlaceholderText(tr("Put a sensible chat room name here"));
ui->lobbyTopic_LE->setPlaceholderText(tr("Set a descriptive topic here")); ui->lobbyTopic_LE->setPlaceholderText(tr("Set a descriptive topic here"));
#endif #endif
@ -149,7 +149,7 @@ void CreateLobbyDialog::createLobby()
ChatLobbyId id = rsMsgs->createChatLobby(lobby_name,gxs_id, lobby_topic, shareList, lobby_flags); ChatLobbyId id = rsMsgs->createChatLobby(lobby_name,gxs_id, lobby_topic, shareList, lobby_flags);
std::cerr << "gui: Created chat lobby " << std::hex << id << std::dec << std::endl ; std::cerr << "gui: Created chat room " << std::hex << id << std::dec << std::endl ;
// open chat window !! // open chat window !!
ChatDialog::chatFriend(ChatId(id)) ; ChatDialog::chatFriend(ChatId(id)) ;

View File

@ -27,8 +27,8 @@
#include "FloatingHelpBrowser.h" #include "FloatingHelpBrowser.h"
FloatingHelpBrowser::FloatingHelpBrowser(QWidget *parent, QAbstractButton *button) : FloatingHelpBrowser::FloatingHelpBrowser(QWidget *parent, QAbstractButton *button)
QTextBrowser(parent), mButton(button) :QTextBrowser(parent), mButton(button)
{ {
QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect(this); QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect(this);
effect->setBlurRadius(30.0); effect->setBlurRadius(30.0);
@ -77,7 +77,7 @@ void FloatingHelpBrowser::showHelp(bool state)
return; return;
} }
resize(p->size() * 0.5); resize(p->size() * 0.75);
move(p->width() / 2 - width() / 2, p->height() / 2 - height() / 2); move(p->width() / 2 - width() / 2, p->height() / 2 - height() / 2);
update(); update();

View File

@ -36,7 +36,7 @@ public:
void setHelpText(const QString &helpText); void setHelpText(const QString &helpText);
public slots: public slots:
void showHelp(bool state); void showHelp(bool state=false);
private slots: private slots:
void textChanged(); void textChanged();

View File

@ -73,12 +73,15 @@
<property name="columnCount"> <property name="columnCount">
<number>3</number> <number>3</number>
</property> </property>
<attribute name="headerDefaultSectionSize">
<number>120</number>
</attribute>
<attribute name="headerStretchLastSection"> <attribute name="headerStretchLastSection">
<bool>false</bool> <bool>false</bool>
</attribute> </attribute>
<column> <column>
<property name="text"> <property name="text">
<string>Friend nodes</string> <string>Trusted nodes</string>
</property> </property>
<property name="textAlignment"> <property name="textAlignment">
<set>AlignCenter</set> <set>AlignCenter</set>

View File

@ -287,7 +287,7 @@ void ConfCertDialog::loadInvitePage()
//infotext += tr("<p>Use this certificate to make new friends. Send it by email, or give it hand to hand.</p>") ; //infotext += tr("<p>Use this certificate to make new friends. Send it by email, or give it hand to hand.</p>") ;
infotext += tr("<p>This certificate contains:") ; infotext += tr("<p>This certificate contains:") ;
infotext += "<UL>" ; infotext += "<UL>" ;
infotext += "<li> a <b>PGP public key</b>"; infotext += "<li> a <b>Profile key</b>";
infotext += " (" + QString::fromUtf8(detail.name.c_str()) + "@" + detail.gpg_id.toStdString().c_str()+") " ; infotext += " (" + QString::fromUtf8(detail.name.c_str()) + "@" + detail.gpg_id.toStdString().c_str()+") " ;
if(ui._shouldAddSignatures_CB->isChecked()) if(ui._shouldAddSignatures_CB->isChecked())
infotext += tr("with")+" "+QString::number(detail.gpgSigners.size()-1)+" "+tr("external signatures</li>") ; infotext += tr("with")+" "+QString::number(detail.gpgSigners.size()-1)+" "+tr("external signatures</li>") ;

View File

@ -7,7 +7,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>722</width> <width>722</width>
<height>546</height> <height>651</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -69,7 +69,7 @@
<item row="0" column="0"> <item row="0" column="0">
<widget class="QTabWidget" name="stabWidget"> <widget class="QTabWidget" name="stabWidget">
<property name="currentIndex"> <property name="currentIndex">
<number>0</number> <number>1</number>
</property> </property>
<widget class="QWidget" name="tab"> <widget class="QWidget" name="tab">
<attribute name="icon"> <attribute name="icon">
@ -270,13 +270,13 @@
<normaloff>:/images/kcmsystem24.png</normaloff>:/images/kcmsystem24.png</iconset> <normaloff>:/images/kcmsystem24.png</normaloff>:/images/kcmsystem24.png</iconset>
</attribute> </attribute>
<attribute name="title"> <attribute name="title">
<string>Advanced</string> <string>Connectivity</string>
</attribute> </attribute>
<layout class="QGridLayout" name="gridLayout_15"> <layout class="QGridLayout" name="gridLayout_15">
<item row="0" column="0"> <item row="0" column="0">
<widget class="QTabWidget" name="tabWidget"> <widget class="QTabWidget" name="tabWidget">
<property name="currentIndex"> <property name="currentIndex">
<number>0</number> <number>1</number>
</property> </property>
<widget class="QWidget" name="tab_5"> <widget class="QWidget" name="tab_5">
<attribute name="title"> <attribute name="title">
@ -424,51 +424,44 @@
</item> </item>
</layout> </layout>
</widget> </widget>
<widget class="QWidget" name="tab_2">
<attribute name="title">
<string>Retroshare Certificate</string>
</attribute>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Use this certificate to make friends:</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QTextEdit" name="userCertificateText"/>
</item>
<item row="2" column="0">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QCheckBox" name="_shouldAddSignatures_CB">
<property name="text">
<string>Include signatures</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</widget> </widget>
</item> </item>
</layout> </layout>
</widget> </widget>
<widget class="QWidget" name="tab_4">
<attribute name="title">
<string>Retroshare Certificate</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTextEdit" name="userCertificateText"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QCheckBox" name="_shouldAddSignatures_CB">
<property name="text">
<string>Include signatures</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</widget> </widget>
</item> </item>
</layout> </layout>

View File

@ -42,6 +42,7 @@
#include <retroshare/rsiface.h> #include <retroshare/rsiface.h>
#include <retroshare/rsbanlist.h> #include <retroshare/rsbanlist.h>
#include <retroshare/rsconfig.h>
#include "ConnectProgressDialog.h" #include "ConnectProgressDialog.h"
#include "gui/GetStartedDialog.h" #include "gui/GetStartedDialog.h"
@ -113,7 +114,7 @@ ConnectFriendWizard::ConnectFriendWizard(QWidget *parent) :
connect(ui->aolButton, SIGNAL(clicked()), this, SLOT(inviteAol())); connect(ui->aolButton, SIGNAL(clicked()), this, SLOT(inviteAol()));
connect(ui->yandexButton, SIGNAL(clicked()), this, SLOT(inviteYandex())); connect(ui->yandexButton, SIGNAL(clicked()), this, SLOT(inviteYandex()));
connect(ui->emailButton, SIGNAL(clicked()), this, SLOT(runEmailClient2())); connect(ui->emailButton, SIGNAL(clicked()), this, SLOT(runEmailClient2()));
connect(ui->toggleadvancedButton, SIGNAL(clicked()), this, SLOT(toggleAdvanced()));
subject = tr("RetroShare Invitation"); subject = tr("RetroShare Invitation");
body = GetStartedDialog::GetInviteText(); body = GetStartedDialog::GetInviteText();
@ -121,7 +122,28 @@ ConnectFriendWizard::ConnectFriendWizard(QWidget *parent) :
body += "\n" + GetStartedDialog::GetCutBelowText(); body += "\n" + GetStartedDialog::GetCutBelowText();
body += "\n\n" + QString::fromUtf8(rsPeers->GetRetroshareInvite(false).c_str()); body += "\n\n" + QString::fromUtf8(rsPeers->GetRetroshareInvite(false).c_str());
ui->userFrame->hide(); std::string advsetting;
if(rsConfig->getConfigurationOption(RS_CONFIG_ADVANCED, advsetting) && (advsetting == "YES"))
{
ui->toggleadvancedButton->setVisible(false);
}
else
{
ui->userFrame->hide(); // certificates page - top half with own cert and it's functions
ui->horizontalLayout_13->hide(); // Advanced options - key sign, whitelist, direct source ...
AdvancedVisible=false;
ui->emailLabel->hide(); // is it ever used?
ui->emailEdit->hide();
ui->trustLabel->hide();
ui->trustEdit->hide();
}
unsigned int onlineCount = 0, friendCount = 0;
rsPeers->getPeerCount (&friendCount, &onlineCount, false);
if(friendCount<30)
ui->makefriend_infolabel->hide();
updateStylesheet(); updateStylesheet();
} }
@ -962,13 +984,14 @@ void ConnectFriendWizard::friendCertChanged()
void ConnectFriendWizard::cleanFriendCert() void ConnectFriendWizard::cleanFriendCert()
{ {
bool certValid = false; bool certValid = false;
QString errorMsg; QString errorMsg ;
std::string cert = ui->friendCertEdit->toPlainText().toUtf8().constData(); std::string cert = ui->friendCertEdit->toPlainText().toUtf8().constData();
if (cert.empty()) { if (cert.empty()) {
ui->friendCertCleanLabel->setPixmap(QPixmap(":/images/delete.png")); ui->friendCertCleanLabel->setPixmap(QPixmap(":/images/delete.png"));
ui->friendCertCleanLabel->setToolTip(""); ui->friendCertCleanLabel->setToolTip("");
ui->friendCertCleanLabel->setStyleSheet(""); ui->friendCertCleanLabel->setStyleSheet("");
errorMsg = tr("");
} else { } else {
std::string cleanCert; std::string cleanCert;
@ -984,23 +1007,27 @@ void ConnectFriendWizard::cleanFriendCert()
ui->friendCertCleanLabel->setStyleSheet(""); ui->friendCertCleanLabel->setStyleSheet("");
connect(ui->friendCertEdit, SIGNAL(textChanged()), this, SLOT(friendCertChanged())); connect(ui->friendCertEdit, SIGNAL(textChanged()), this, SLOT(friendCertChanged()));
} }
errorMsg = tr("Certificate appears to be valid");
ui->friendCertCleanLabel->setPixmap(QPixmap(":/images/accepted16.png"));
} else { } else {
if (error_code > 0) { if (error_code > 0) {
switch (error_code) { switch (error_code) {
case RS_PEER_CERT_CLEANING_CODE_NO_BEGIN_TAG: case CERTIFICATE_PARSING_ERROR_CHECKSUM_ERROR :
errorMsg = tr("No or misspelled BEGIN tag found") ; case CERTIFICATE_PARSING_ERROR_WRONG_VERSION :
break ; case CERTIFICATE_PARSING_ERROR_SIZE_ERROR :
case RS_PEER_CERT_CLEANING_CODE_NO_END_TAG: case CERTIFICATE_PARSING_ERROR_INVALID_LOCATION_ID :
errorMsg = tr("No or misspelled END tag found") ; case CERTIFICATE_PARSING_ERROR_INVALID_EXTERNAL_IP :
break ; case CERTIFICATE_PARSING_ERROR_INVALID_LOCAL_IP :
case RS_PEER_CERT_CLEANING_CODE_NO_CHECKSUM: case CERTIFICATE_PARSING_ERROR_INVALID_CHECKSUM_SECTION :
errorMsg = tr("No checksum found (the last 5 chars should be separated by a '=' char), or no newline after tag line (e.g. line beginning with Version:)") ; case CERTIFICATE_PARSING_ERROR_UNKNOWN_SECTION_PTAG :
break ; case CERTIFICATE_PARSING_ERROR_MISSING_CHECKSUM :
default: default:
errorMsg = tr("Fake certificate: take any real certificate, and replace some of the letters randomly") ; errorMsg = tr("Not a valid Retroshare certificate!") ;
ui->friendCertCleanLabel->setStyleSheet("QLabel#friendCertCleanLabel {border: 2px solid red; border-radius: 6px;}"); ui->friendCertCleanLabel->setStyleSheet("QLabel#friendCertCleanLabel {border: 2px solid red; border-radius: 6px;}");
} }
} }
ui->friendCertCleanLabel->setPixmap(QPixmap(":/images/delete.png"));
} }
} }
@ -1275,3 +1302,19 @@ void ConnectFriendWizard::runEmailClient2()
{ {
sendMail("", subject, body ); sendMail("", subject, body );
} }
void ConnectFriendWizard::toggleAdvanced()
{
if(AdvancedVisible)
{
ui->horizontalLayout_13->hide();
ui->toggleadvancedButton->setText("Show advanced options");
AdvancedVisible=false;
}
else
{
ui->horizontalLayout_13->show();
ui->toggleadvancedButton->setText("Hide advanced options");
AdvancedVisible=true;
}
}

View File

@ -90,12 +90,14 @@ private slots:
void inviteAol(); void inviteAol();
void inviteYandex(); void inviteYandex();
void toggleAdvanced();
private: private:
// returns the translated error string for the error code (to be found in rspeers.h) // returns the translated error string for the error code (to be found in rspeers.h)
QString getErrorString(uint32_t) ; QString getErrorString(uint32_t) ;
void updateStylesheet(); void updateStylesheet();
void setTitleText(QWizardPage *page, const QString &title); void setTitleText(QWizardPage *page, const QString &title);
bool AdvancedVisible;
private: private:
bool error; bool error;

View File

@ -6,8 +6,8 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>691</width> <width>620</width>
<height>533</height> <height>530</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -333,7 +333,7 @@
</font> </font>
</property> </property>
<property name="toolTip"> <property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This box expects your friend's Retroshare certificate. WARNING: this is different from your friend's PGP key. Do not paste your friend's PGP key here (not even a part of it). It's not going to work.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This box expects your friend's Retroshare certificate. WARNING: this is different from your friend's profile key. Do not paste your friend's profile key here (not even a part of it). It's not going to work.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property> </property>
<property name="styleSheet"> <property name="styleSheet">
<string notr="true"/> <string notr="true"/>
@ -1264,6 +1264,9 @@ resources.</string>
</item> </item>
<item row="6" column="1"> <item row="6" column="1">
<widget class="QPlainTextEdit" name="signersEdit"> <widget class="QPlainTextEdit" name="signersEdit">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-size:10pt;&quot;&gt;Signing a friend's key is a way to express your trust into this friend, to your other friends. The signatures below cryptographically attest that owners of the listed keys recognise the current PGP key as authentic.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="readOnly"> <property name="readOnly">
<bool>true</bool> <bool>true</bool>
</property> </property>
@ -1297,108 +1300,132 @@ resources.</string>
</widget> </widget>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout_7"> <widget class="QPushButton" name="toggleadvancedButton">
<item> <property name="text">
<layout class="QVBoxLayout" name="verticalLayout_18"> <string>Show Advanced options</string>
<item> </property>
<widget class="QCheckBox" name="addKeyToKeyring_CB"> </widget>
<property name="text"> </item>
<string>Add key to keyring</string> <item>
</property> <widget class="QFrame" name="horizontalLayout_13">
</widget> <layout class="QHBoxLayout" name="horizontalLayout_7">
</item> <property name="spacing">
<item> <number>6</number>
<widget class="QCheckBox" name="signGPGCheckBox"> </property>
<property name="text"> <item>
<string>Authenticate friend (Sign PGP Key)</string> <layout class="QVBoxLayout" name="verticalLayout_18">
</property> <item>
</widget> <widget class="QCheckBox" name="addKeyToKeyring_CB">
</item> <property name="text">
<item> <string>Add key to keyring</string>
<widget class="QCheckBox" name="acceptNoSignGPGCheckBox"> </property>
<property name="text"> </widget>
<string>Add as friend to connect with</string> </item>
</property> <item>
</widget> <widget class="QCheckBox" name="signGPGCheckBox">
</item> <property name="toolTip">
<item> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-size:10pt;&quot;&gt;Signing a friend's key is a way to express your trust into this friend, to your other friends. It helps them to decide whether to allow connections from that key based on your own trust. Signing a key is absolutely optional and cannot be undone, so do it wisely.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
<layout class="QHBoxLayout" name="horizontalLayout_11"> </property>
<item> <property name="text">
<widget class="QCheckBox" name="_addIPToWhiteList_CB_2"> <string>Authenticate friend (Sign PGP Key)</string>
<property name="text"> </property>
<string>Add IP to whitelist</string> </widget>
</property> </item>
</widget> <item>
</item> <widget class="QCheckBox" name="acceptNoSignGPGCheckBox">
<item> <property name="text">
<widget class="QComboBox" name="_addIPToWhiteList_ComboBox_2"/> <string>Add as friend to connect with</string>
</item> </property>
</layout> </widget>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout_9"> <layout class="QHBoxLayout" name="horizontalLayout_11">
<item>
<widget class="QLabel" name="groupLabel">
<property name="text">
<string>Add friend to group:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="groupComboBox"/>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_19">
<item>
<widget class="QGroupBox" name="_options_GB">
<property name="title">
<string>Options</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_10">
<item> <item>
<widget class="QCheckBox" name="_direct_transfer_CB_2"> <widget class="QCheckBox" name="_addIPToWhiteList_CB_2">
<property name="text"> <property name="text">
<string>Can be used as direct source</string> <string>Add IP to whitelist</string>
</property> </property>
</widget> </widget>
</item> </item>
<item> <item>
<widget class="QCheckBox" name="_allow_push_CB_2"> <widget class="QComboBox" name="_addIPToWhiteList_ComboBox_2"/>
<property name="text">
<string>Auto-download recommended files</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="_require_WL_CB_2">
<property name="text">
<string>Require whitelist clearance to connect</string>
</property>
</widget>
</item> </item>
</layout> </layout>
</widget> </item>
</item> <item>
<item> <layout class="QHBoxLayout" name="horizontalLayout_9">
<spacer name="verticalSpacer_4"> <item>
<property name="orientation"> <widget class="QLabel" name="groupLabel">
<enum>Qt::Vertical</enum> <property name="text">
</property> <string>Add friend to group:</string>
<property name="sizeHint" stdset="0"> </property>
<size> </widget>
<width>38</width> </item>
<height>38</height> <item>
</size> <widget class="QComboBox" name="groupComboBox"/>
</property> </item>
</spacer> </layout>
</item> </item>
</layout> </layout>
</item> </item>
</layout> <item>
<layout class="QVBoxLayout" name="verticalLayout_19">
<item>
<widget class="QGroupBox" name="_options_GB">
<property name="title">
<string>Options</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_10">
<item>
<widget class="QCheckBox" name="_direct_transfer_CB_2">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;justify&quot;&gt;Retroshare periodically checks your friend lists for browsable files matching your transfers, to establish a direct transfer. In this case, your friend knows you're downloading the file.&lt;/p&gt;&lt;p align=&quot;justify&quot;&gt;To prevent this behavior for this friend only, uncheck this box. You can still perform a direct transfer if you explicitly ask for it, by e.g. downloading from your friend's file list. This setting is applied to all locations of the same node.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="text">
<string>Can be used as direct source</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="_allow_push_CB_2">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This option allows you to automatically download a file that is recommended in an message coming from this node. This can be used for instance to send files between your own nodes. Applied to all locations of the same node.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="text">
<string>Auto-download recommended files</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="_require_WL_CB_2">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Peers that have this option cannot connect if their connection address is not in the whitelist. This protects you from traffic forwarding attacks. When used, rejected peers will be reported by &amp;quot;security feed items&amp;quot; in the News Feed section. From there, you can whitelist/blacklist their IP. Applies to all locations of the same node.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="text">
<string>Require whitelist clearance to connect</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer_4">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>38</width>
<height>38</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</item> </item>
<item> <item>
<widget class="StyledLabel" name="requestinfolabel"> <widget class="StyledLabel" name="requestinfolabel">
@ -1480,6 +1507,19 @@ resources.</string>
</property> </property>
</widget> </widget>
</item> </item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</widget> </widget>
<widget class="QWizardPage" name="FriendRecommendationsPage"> <widget class="QWizardPage" name="FriendRecommendationsPage">

View File

@ -0,0 +1,77 @@
#include <QMessageBox>
#include "FriendRecommendDialog.h"
#include "gui/msgs/MessageComposer.h"
FriendRecommendDialog::FriendRecommendDialog(QWidget *parent)
: QDialog(parent), ui(new Ui::FriendRecommendDialog)
{
ui->setupUi(this) ;
}
FriendRecommendDialog::~FriendRecommendDialog()
{
}
void FriendRecommendDialog::load()
{
ui->frec_recommendList->setHeaderText(tr("Recommend friends"));
ui->frec_recommendList->setModus(FriendSelectionWidget::MODUS_CHECK);
ui->frec_recommendList->setShowType(FriendSelectionWidget::SHOW_GROUP | FriendSelectionWidget::SHOW_SSL);
ui->frec_recommendList->start();
ui->frec_toList->setHeaderText(tr("To"));
ui->frec_toList->setModus(FriendSelectionWidget::MODUS_CHECK);
ui->frec_toList->start();
ui->frec_messageEdit->setText(MessageComposer::recommendMessage());
}
void FriendRecommendDialog::showIt()
{
FriendRecommendDialog *dialog = instance();
dialog->load();
dialog->show();
dialog->raise();
dialog->activateWindow();
}
FriendRecommendDialog *FriendRecommendDialog::instance()
{
static FriendRecommendDialog *d = NULL ;
if(d == NULL)
d = new FriendRecommendDialog(NULL);
return d;
}
void FriendRecommendDialog::accept()
{
std::set<RsPeerId> recommendIds;
ui->frec_recommendList->selectedIds<RsPeerId,FriendSelectionWidget::IDTYPE_SSL>(recommendIds, false);
if (recommendIds.empty()) {
QMessageBox::warning(this, "RetroShare", tr("Please select at least one friend for recommendation."), QMessageBox::Ok, QMessageBox::Ok);
return ;
}
std::set<RsPeerId> toIds;
ui->frec_toList->selectedIds<RsPeerId,FriendSelectionWidget::IDTYPE_SSL>(toIds, false);
if (toIds.empty()) {
QMessageBox::warning(this, "RetroShare", tr("Please select at least one friend as recipient."), QMessageBox::Ok, QMessageBox::Ok);
return ;
}
std::set<RsPeerId>::iterator toId;
for (toId = toIds.begin(); toId != toIds.end(); ++toId) {
MessageComposer::recommendFriend(recommendIds, *toId, ui->frec_messageEdit->toHtml(), true);
}
QDialog::accept() ;
QMessageBox::information(NULL,tr("Recommendation messages sent!"),tr("A recommendation message was sent to each of the chosen friends!")) ;
}

View File

@ -0,0 +1,22 @@
#pragma once
#include <QDialog>
#include "ui_FriendRecommendDialog.h"
class FriendRecommendDialog: public QDialog
{
public:
FriendRecommendDialog(QWidget *parent) ;
virtual ~FriendRecommendDialog() ;
static void showIt();
private:
static FriendRecommendDialog *instance();
virtual void accept() ;
void load();
Ui::FriendRecommendDialog *ui;
};

View File

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FriendRecommendDialog</class>
<widget class="QDialog" name="FriendRecommendDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1398</width>
<height>774</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_8">
<item>
<widget class="FriendSelectionWidget" name="frec_recommendList" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="FriendSelectionWidget" name="frec_toList" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="frec_label">
<property name="text">
<string>Message:</string>
</property>
</widget>
</item>
<item>
<widget class="QTextEdit" name="frec_messageEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
<zorder>buttonBox</zorder>
<zorder>frec_label</zorder>
<zorder>frec_messageEdit</zorder>
<zorder>layoutWidget</zorder>
<zorder>frec_recommendList</zorder>
</widget>
<customwidgets>
<customwidget>
<class>FriendSelectionWidget</class>
<extends>QWidget</extends>
<header>gui/common/FriendSelectionWidget.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>FriendRecommendDialog</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>FriendRecommendDialog</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>

View File

@ -75,7 +75,7 @@ PGPKeyDialog::PGPKeyDialog(const RsPeerId& id, const RsPgpId &pgp_id, QWidget *p
// } // }
ui.headerFrame->setHeaderImage(QPixmap(":/images/user/identityinfo64.png")); ui.headerFrame->setHeaderImage(QPixmap(":/images/user/identityinfo64.png"));
ui.headerFrame->setHeaderText(tr("PGP Key details")); ui.headerFrame->setHeaderText(tr("Retroshare profile"));
//ui._chat_CB->hide() ; //ui._chat_CB->hide() ;

View File

@ -6,8 +6,8 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>990</width> <width>1071</width>
<height>668</height> <height>718</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -27,11 +27,11 @@
<item> <item>
<widget class="QTabWidget" name="stabWidget"> <widget class="QTabWidget" name="stabWidget">
<property name="currentIndex"> <property name="currentIndex">
<number>0</number> <number>1</number>
</property> </property>
<widget class="QWidget" name="tab"> <widget class="QWidget" name="tab">
<attribute name="title"> <attribute name="title">
<string>PGP Key info</string> <string>Profile info</string>
</attribute> </attribute>
<layout class="QVBoxLayout" name="verticalLayout_2"> <layout class="QVBoxLayout" name="verticalLayout_2">
<item> <item>
@ -41,7 +41,7 @@
<item row="0" column="0"> <item row="0" column="0">
<widget class="QLabel" name="label_name"> <widget class="QLabel" name="label_name">
<property name="text"> <property name="text">
<string>PGP name :</string> <string>Name :</string>
</property> </property>
</widget> </widget>
</item> </item>
@ -153,7 +153,7 @@
</font> </font>
</property> </property>
<property name="text"> <property name="text">
<string>This key has signed your own PGP key</string> <string>This profile has signed your own profile key</string>
</property> </property>
</widget> </widget>
</item> </item>
@ -197,7 +197,7 @@ p, li { white-space: pre-wrap; }
&lt;p align=&quot;justify&quot; style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:10pt;&quot;&gt;Signing a friend's key is a way to express your trust into this friend, to your other friends. It helps them to decide whether to allow connections from that key based on your own trust. Signing a key is absolutely optional and cannot be undone, so do it wisely.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> &lt;p align=&quot;justify&quot; style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:10pt;&quot;&gt;Signing a friend's key is a way to express your trust into this friend, to your other friends. It helps them to decide whether to allow connections from that key based on your own trust. Signing a key is absolutely optional and cannot be undone, so do it wisely.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property> </property>
<property name="text"> <property name="text">
<string>Sign this PGP key</string> <string>Sign this key</string>
</property> </property>
<property name="icon"> <property name="icon">
<iconset resource="../images.qrc"> <iconset resource="../images.qrc">
@ -301,13 +301,13 @@ p, li { white-space: pre-wrap; }
</widget> </widget>
<widget class="QWidget" name="widget"> <widget class="QWidget" name="widget">
<attribute name="title"> <attribute name="title">
<string>ASCII format</string> <string>PGP key</string>
</attribute> </attribute>
<layout class="QVBoxLayout" name="verticalLayout_3"> <layout class="QVBoxLayout" name="verticalLayout_3">
<item> <item>
<widget class="QLabel" name="label_4"> <widget class="QLabel" name="label_4">
<property name="text"> <property name="text">
<string>Below is the node's PGP key. It identifies the node and all its locations. A &quot;Retroshare certificate&quot; that you can exchange in order to make friends, is in the the &quot;details&quot; of each separate location.</string> <string>Below is the node's profile key in PGP ascii format. It identifies all nodes of the same profile. A &quot;Retroshare certificate&quot; that you can exchange in order to make friends, is in the the &quot;details&quot; of each separate node.</string>
</property> </property>
<property name="wordWrap"> <property name="wordWrap">
<bool>true</bool> <bool>true</bool>
@ -348,7 +348,7 @@ p, li { white-space: pre-wrap; }
<item> <item>
<widget class="QLabel" name="label_3"> <widget class="QLabel" name="label_3">
<property name="text"> <property name="text">
<string>These options apply to all locations of the same node:</string> <string>These options apply to all nodes of the profile:</string>
</property> </property>
</widget> </widget>
</item> </item>

View File

@ -123,7 +123,7 @@ GxsGroupFrameDialog::~GxsGroupFrameDialog()
void GxsGroupFrameDialog::initUi() void GxsGroupFrameDialog::initUi()
{ {
registerHelpButton(ui->helpButton, getHelpString()) ; registerHelpButton(ui->helpButton, getHelpString(),pageName()) ;
ui->titleBarPixmap->setPixmap(QPixmap(icon(ICON_NAME))); ui->titleBarPixmap->setPixmap(QPixmap(icon(ICON_NAME)));
ui->titleBarLabel->setText(text(TEXT_NAME)); ui->titleBarLabel->setText(text(TEXT_NAME));

View File

@ -1,5 +1,6 @@
<RCC> <RCC>
<qresource prefix="/"> <qresource prefix="/">
<file>images/network_map.png</file>
<file>images/global_switch_on.png</file> <file>images/global_switch_on.png</file>
<file>images/global_switch_off.png</file> <file>images/global_switch_off.png</file>
<file>images/switch00.png</file> <file>images/switch00.png</file>

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

View File

@ -269,7 +269,7 @@ bool NotifyQt::askForPassword(const std::string& title, const std::string& key_d
QInputDialog dialog; QInputDialog dialog;
if (title == "") { if (title == "") {
dialog.setWindowTitle(tr("PGP key passphrase")); dialog.setWindowTitle(tr("Passphrase required"));
} else if (title == "AuthSSLimpl::SignX509ReqWithGPG()") { } else if (title == "AuthSSLimpl::SignX509ReqWithGPG()") {
dialog.setWindowTitle(tr("You need to sign your node's certificate.")); dialog.setWindowTitle(tr("You need to sign your node's certificate."));
} else if (title == "p3IdService::service_CreateGroup()") { } else if (title == "p3IdService::service_CreateGroup()") {
@ -278,7 +278,7 @@ bool NotifyQt::askForPassword(const std::string& title, const std::string& key_d
dialog.setWindowTitle(QString::fromStdString(title)); dialog.setWindowTitle(QString::fromStdString(title));
} }
dialog.setLabelText((prev_is_bad ? QString("%1\n\n").arg(tr("Wrong password !")) : QString()) + QString("%1:\n %2").arg(tr("Please enter your PGP password for key"), QString::fromUtf8(key_details.c_str()))); dialog.setLabelText((prev_is_bad ? QString("%1\n\n").arg(tr("Wrong password !")) : QString()) + QString("<b>%1</b><br/>Profile: <i>%2</i>\n").arg(tr("Please enter your Retroshare passphrase"), QString::fromUtf8(key_details.c_str())));
dialog.setTextEchoMode(QLineEdit::Password); dialog.setTextEchoMode(QLineEdit::Password);
dialog.setModal(true); dialog.setModal(true);

View File

@ -295,13 +295,14 @@ GetStartedDialog QTextEdit {
/* GenCertDialog */ /* GenCertDialog */
GenCertDialog > QFrame#headerFrame { /* GenCertDialog > QFrame#headerFrame {
background-image: url(:/images/genbackground.png); background-image: url(:/images/genbackground.png);
} }
GenCertDialog > QFrame#headerFrame > QLabel#headerLabel { GenCertDialog > QFrame#headerFrame > QLabel#headerLabel {
color: rgb(255, 255, 255); color: rgb(255, 255, 255);
} }
*/
/* ConnectFriendWizard */ /* ConnectFriendWizard */
@ -663,12 +664,57 @@ IdEditDialog QLabel#info_label
background: #FFFFD7; background: #FFFFD7;
background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #FFFFD7, stop:1 #FFFFB2); background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #FFFFD7, stop:1 #FFFFB2);
} }
GenCertDialog QComboBox#genPGPuser {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QSpinBox#hiddenport_spinBox {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QLineEdit#hiddenaddr_input {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QLineEdit#password_input_2 {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QLineEdit#password_input {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QLineEdit#nickname_input {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QLineEdit#node_input {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QLineEdit#name_input {
border: 4px solid #0099cc;
border-radius: 6px;
background: white;
font: bold;
}
GenCertDialog QPushButton#genButton { GenCertDialog QPushButton#genButton {
border-image: url(:/images/btn_blue.png) 4; border-image: url(:/images/btn_blue.png) 4;
border-width: 4; border-width: 4;
padding: 0px 6px;
font-size: 16px;
font: bold; font: bold;
color: white; color: white;
} }
@ -679,7 +725,7 @@ GenCertDialog QPushButton#genButton:hover {
GenCertDialog QPushButton#genButton:disabled { GenCertDialog QPushButton#genButton:disabled {
border-image: url(:/images/btn_27.png) 4; border-image: url(:/images/btn_27.png) 4;
font-size: 16px; /* font-size: 16px; */
font: bold; font: bold;
color: black; color: black;
} }

View File

@ -0,0 +1,19 @@
#include <iostream>
#include "AboutPage.h"
AboutPage::AboutPage(QWidget * parent , Qt::WindowFlags flags )
: ConfigPage(parent,flags)
{
ui.setupUi(this);
ui.widget->close_button->hide();
}
AboutPage::~AboutPage()
{
}
void AboutPage::load()
{
std::cerr << "Loading AboutPage!" << std::endl;
}

View File

@ -0,0 +1,50 @@
/****************************************************************
* RetroShare is distributed under the following license:
*
* Copyright (C) 2006 - 2009 RetroShare Team
*
* 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 Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
****************************************************************/
#pragma once
#include <QFileDialog>
#include <retroshare-gui/configpage.h>
#include "ui_AboutPage.h"
class AboutPage : public ConfigPage
{
Q_OBJECT
public:
/** Default Constructor */
AboutPage(QWidget * parent = 0, Qt::WindowFlags flags = 0);
/** Default Destructor */
~AboutPage();
/** Loads the settings for this page */
virtual void load();
virtual QPixmap iconPixmap() const { return QPixmap(":/icons/settings/sound.svg") ; }
virtual QString pageName() const { return tr("About") ; }
virtual QString helpText() const { return ""; }
private:
/** Qt Designer generated object */
Ui::AboutPage ui;
};

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AboutPage</class>
<widget class="QWidget" name="AboutPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>507</width>
<height>346</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="AboutWidget" name="widget" native="true"/>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>AboutWidget</class>
<extends>QWidget</extends>
<header location="global">gui/AboutWidget.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@ -19,15 +19,26 @@
* Boston, MA 02110-1301, USA. * Boston, MA 02110-1301, USA.
****************************************************************/ ****************************************************************/
#include <QStyleFactory> #include <QCheckBox>
#include <QFileInfo>
#include <QDir> #include <QDir>
#include <QFileInfo>
#include <QGroupBox>
#include <QStatusBar>
#include <QStyleFactory>
#include "lang/languagesupport.h" #include "lang/languagesupport.h"
#include <rshare.h> #include <rshare.h>
#include "AppearancePage.h" #include "AppearancePage.h"
#include "rsharesettings.h" #include "rsharesettings.h"
#include "gui/MainWindow.h" #include "gui/MainWindow.h"
#include "gui/notifyqt.h"
#include "gui/statusbar/peerstatus.h"
#include "gui/statusbar/natstatus.h"
#include "gui/statusbar/dhtstatus.h"
#include "gui/statusbar/hashingstatus.h"
#include "gui/statusbar/discstatus.h"
#include "gui/statusbar/ratesstatus.h"
#include "gui/statusbar/OpModeStatus.h"
#include "gui/statusbar/SoundStatus.h" #include "gui/statusbar/SoundStatus.h"
#include "gui/statusbar/ToasterDisable.h" #include "gui/statusbar/ToasterDisable.h"
#include "gui/statusbar/SysTrayStatus.h" #include "gui/statusbar/SysTrayStatus.h"
@ -39,13 +50,22 @@ AppearancePage::AppearancePage(QWidget * parent, Qt::WindowFlags flags)
/* Invoke the Qt Designer generated object setup routine */ /* Invoke the Qt Designer generated object setup routine */
ui.setupUi(this); ui.setupUi(this);
MainWindow *pMainWindow = MainWindow::getInstance();
connect(ui.cmboStyleSheet, SIGNAL(activated(int)), this, SLOT(loadStyleSheet(int))); connect(ui.cmboStyleSheet, SIGNAL(activated(int)), this, SLOT(loadStyleSheet(int)));
connect(ui.checkBoxStatusCompactMode, SIGNAL(toggled(bool)), pMainWindow, SLOT(setCompactStatusMode(bool)));
connect(ui.checkBoxHideSoundStatus, SIGNAL(toggled(bool)), pMainWindow->soundStatusInstance(), SLOT(setHidden(bool))); connect(ui.grpStatus, SIGNAL(toggled(bool)), this /* pMainWindow->statusBar(), */, SLOT(switch_status_grpStatus(bool)));
connect(ui.checkBoxHideToasterDisable, SIGNAL(toggled(bool)), pMainWindow->toasterDisableInstance(), SLOT(setHidden(bool))); connect(ui.checkBoxStatusCompactMode, SIGNAL(toggled(bool)), this /* pMainWindow, */, SLOT(switch_status_compactMode(bool)));
connect(ui.checkBoxShowSystrayOnStatus, SIGNAL(toggled(bool)), pMainWindow->sysTrayStatusInstance(), SLOT(setVisible(bool))); connect(ui.checkBoxDisableSysTrayToolTip, SIGNAL(toggled(bool)), this /* pMainWindow, */, SLOT(switch_status_showToolTip(bool)));
connect(ui.checkBoxDisableSysTrayToolTip, SIGNAL(toggled(bool)), pMainWindow, SLOT(toggleStatusToolTip(bool))); connect(ui.checkBoxShowStatusStatus, SIGNAL(toggled(bool)), this /* pMainWindow->statusComboBoxInstance(), */, SLOT(switch_status_ShowCBox(bool)));
connect(ui.checkBoxShowPeerStatus, SIGNAL(toggled(bool)), this /* pMainWindow->peerstatusInstance(), */, SLOT(switch_status_ShowStatus(bool)));
connect(ui.checkBoxShowNATStatus, SIGNAL(toggled(bool)), this /* pMainWindow->natstatusInstance(), */, SLOT(switch_status_ShowPeer(bool)));
connect(ui.checkBoxShowDHTStatus, SIGNAL(toggled(bool)), this /* pMainWindow->dhtstatusInstance(), */, SLOT(switch_status_ShowDHT(bool)));
connect(ui.checkBoxShowHashingStatus, SIGNAL(toggled(bool)), this /* pMainWindow->hashingstatusInstance(), */, SLOT(switch_status_ShowHashing(bool)));
connect(ui.checkBoxShowDiscStatus, SIGNAL(toggled(bool)), this /* pMainWindow->discstatusInstance(), */, SLOT(switch_status_ShowDisc(bool)));
connect(ui.checkBoxShowRateStatus, SIGNAL(toggled(bool)), this /* pMainWindow->ratesstatusInstance(), */, SLOT(switch_status_ShowRate(bool)));
connect(ui.checkBoxShowOpModeStatus, SIGNAL(toggled(bool)), this /* pMainWindow->opModeStatusInstance(), */, SLOT(switch_status_ShowOpMode(bool)));
connect(ui.checkBoxShowSoundStatus, SIGNAL(toggled(bool)), this /* pMainWindow->soundStatusInstance(), */, SLOT(switch_status_ShowSound(bool)));
connect(ui.checkBoxShowToasterDisable, SIGNAL(toggled(bool)), this /* pMainWindow->toasterDisableInstance(), */, SLOT(switch_status_ShowToaster(bool)));
connect(ui.checkBoxShowSystrayOnStatus, SIGNAL(toggled(bool)), this /* pMainWindow->sysTrayStatusInstance(), */, SLOT(switch_status_ShowSystray(bool)));
/* Populate combo boxes */ /* Populate combo boxes */
foreach (QString code, LanguageSupport::languageCodes()) { foreach (QString code, LanguageSupport::languageCodes()) {
@ -64,20 +84,63 @@ AppearancePage::AppearancePage(QWidget * parent, Qt::WindowFlags flags)
foreach (QString name, styleSheets.keys()) { foreach (QString name, styleSheets.keys()) {
ui.cmboStyleSheet->addItem(name, styleSheets[name]); ui.cmboStyleSheet->addItem(name, styleSheets[name]);
} }
connect(ui.cmboTollButtonsSize, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCmboToolButtonSize() ));
// connect(ui.cmboListItemSize, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCmboListItemSize() ));
connect(ui.cmboTollButtonsStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCmboToolButtonStyle()));
connect(ui.cmboLanguage, SIGNAL(currentIndexChanged(int)), this, SLOT(updateLanguageCode() ));
connect(ui.cmboStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(updateInterfaceStyle() ));
connect(ui.cmboStyleSheet, SIGNAL(currentIndexChanged(int)), this, SLOT(updateSheetName() ));
connect(ui.checkBoxDisableSysTrayToolTip, SIGNAL(toggled(bool)), this, SLOT(updateStatusToolTip() ));
connect(ui.mainPageButtonType_CB, SIGNAL(currentIndexChanged(int)), this, SLOT(updateRbtPageOnToolBar() ));
// connect(ui.menuItemsButtonType_CB, SIGNAL(currentIndexChanged(int)), this, SLOT(updateActionButtonLoc() ));
} }
/** Saves the changes on this page */ void AppearancePage::switch_status_grpStatus(bool b) { switch_status(MainWindow::StatusGrpStatus ,"ShowStatusBar", b) ; }
bool AppearancePage::save(QString &errmsg) void AppearancePage::switch_status_compactMode(bool b) { switch_status(MainWindow::StatusCompactMode,"CompactMode", b) ; }
void AppearancePage::switch_status_showToolTip(bool b) { switch_status(MainWindow::StatusShowToolTip,"DisableSysTrayToolTip", b) ; }
void AppearancePage::switch_status_ShowStatus(bool b) { switch_status(MainWindow::StatusShowStatus ,"ShowStatus", b) ; }
void AppearancePage::switch_status_ShowPeer(bool b) { switch_status(MainWindow::StatusShowPeer ,"ShowPeer", b) ; }
void AppearancePage::switch_status_ShowDHT(bool b) { switch_status(MainWindow::StatusShowDHT ,"ShowDHT", b) ; }
void AppearancePage::switch_status_ShowHashing(bool b) { switch_status(MainWindow::StatusShowHashing,"ShowHashing", b) ; }
void AppearancePage::switch_status_ShowDisc(bool b) { switch_status(MainWindow::StatusShowDisc ,"ShowDisc", b) ; }
void AppearancePage::switch_status_ShowRate(bool b) { switch_status(MainWindow::StatusShowRate ,"ShowRate", b) ; }
void AppearancePage::switch_status_ShowOpMode(bool b) { switch_status(MainWindow::StatusShowOpMode ,"ShowOpMode", b) ; }
void AppearancePage::switch_status_ShowSound(bool b) { switch_status(MainWindow::StatusShowSound ,"ShowSound", b) ; }
void AppearancePage::switch_status_ShowToaster(bool b) { switch_status(MainWindow::StatusShowToaster,"ShowToaster", b) ; }
void AppearancePage::switch_status_ShowSystray(bool b) { switch_status(MainWindow::StatusShowSystray,"ShowSysTrayOnStatusBar",b) ; }
void AppearancePage::switch_status_ShowCBox(bool b) { switch_status(MainWindow::StatusShowCBox, "ShowStatusCBox" ,b) ; }
void AppearancePage::switch_status(MainWindow::StatusElement s,const QString& key, bool b)
{ {
Q_UNUSED(errmsg); MainWindow *pMainWindow = MainWindow::getInstance();
QString languageCode = LanguageSupport::languageCode(ui.cmboLanguage->currentText()); if(!pMainWindow)
return ;
Settings->setLanguageCode(languageCode); Settings->setValueToGroup("StatusBar", key, QVariant(b));
Settings->setInterfaceStyle(ui.cmboStyle->currentText());
Settings->setSheetName(ui.cmboStyleSheet->itemData(ui.cmboStyleSheet->currentIndex()).toString()); pMainWindow->switchVisibilityStatus(s,b) ;
Settings->setPageButtonLoc(ui.rbtPageOnToolBar->isChecked()); }
Settings->setActionButtonLoc(ui.rbtActionOnToolBar->isChecked());
void AppearancePage::updateLanguageCode() { Settings->setLanguageCode(LanguageSupport::languageCode(ui.cmboLanguage->currentText())); }
void AppearancePage::updateInterfaceStyle()
{
Rshare::setStyle(ui.cmboStyle->currentText());
Settings->setInterfaceStyle(ui.cmboStyle->currentText());
}
void AppearancePage::updateSheetName() { Settings->setSheetName(ui.cmboStyleSheet->itemData(ui.cmboStyleSheet->currentIndex()).toString()); }
void AppearancePage::updateRbtPageOnToolBar()
{
Settings->setPageButtonLoc(!ui.mainPageButtonType_CB->currentIndex());
Settings->setActionButtonLoc(!ui.mainPageButtonType_CB->currentIndex());
NotifyQt::getInstance()->notifySettingsChanged();
}
void AppearancePage::updateStatusToolTip() { MainWindow::getInstance()->toggleStatusToolTip(ui.checkBoxDisableSysTrayToolTip->isChecked()); }
void AppearancePage::updateCmboToolButtonStyle()
{
switch (ui.cmboTollButtonsStyle->currentIndex()) switch (ui.cmboTollButtonsStyle->currentIndex())
{ {
case 0: case 0:
@ -93,61 +156,67 @@ bool AppearancePage::save(QString &errmsg)
default: default:
Settings->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); Settings->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
} }
NotifyQt::getInstance()->notifySettingsChanged();
}
void AppearancePage::updateCmboToolButtonSize()
{
switch (ui.cmboTollButtonsSize->currentIndex()) switch (ui.cmboTollButtonsSize->currentIndex())
{ {
case 0: case 0:
Settings->setToolButtonSize(8); Settings->setToolButtonSize(8);
break;
case 1:
Settings->setToolButtonSize(16);
break;
case 2:
default:
Settings->setToolButtonSize(24);
break;
case 3:
Settings->setToolButtonSize(32);
break;
case 4:
Settings->setToolButtonSize(64);
break;
case 5:
Settings->setToolButtonSize(128);
}
switch (ui.cmboListItemSize->currentIndex())
{
case 0:
Settings->setListItemIconSize(8); Settings->setListItemIconSize(8);
break; break;
case 1: case 1:
Settings->setToolButtonSize(16);
Settings->setListItemIconSize(16); Settings->setListItemIconSize(16);
break; break;
case 2: case 2:
default: default:
Settings->setToolButtonSize(24);
Settings->setListItemIconSize(24); Settings->setListItemIconSize(24);
break; break;
case 3: case 3:
Settings->setToolButtonSize(32);
Settings->setListItemIconSize(32); Settings->setListItemIconSize(32);
break; break;
case 4: case 4:
Settings->setListItemIconSize(64); Settings->setToolButtonSize(64);
Settings->setListItemIconSize(64);
break; break;
case 5: case 5:
Settings->setListItemIconSize(128); Settings->setToolButtonSize(128);
Settings->setListItemIconSize(128);
} }
NotifyQt::getInstance()->notifySettingsChanged();
/* Set to new style */
Rshare::setStyle(ui.cmboStyle->currentText());
Settings->setValueToGroup("StatusBar", "CompactMode", QVariant(ui.checkBoxStatusCompactMode->isChecked()));
Settings->setValueToGroup("StatusBar", "HideSound", QVariant(ui.checkBoxHideSoundStatus->isChecked()));
Settings->setValueToGroup("StatusBar", "HideToaster", QVariant(ui.checkBoxHideToasterDisable->isChecked()));
Settings->setValueToGroup("StatusBar", "ShowSysTrayOnStatusBar", QVariant(ui.checkBoxShowSystrayOnStatus->isChecked()));
Settings->setValueToGroup("StatusBar", "DisableSysTrayToolTip", QVariant(ui.checkBoxDisableSysTrayToolTip->isChecked()));
MainWindow::getInstance()->toggleStatusToolTip(ui.checkBoxDisableSysTrayToolTip->isChecked());
return true;
} }
// void AppearancePage::updateCmboListItemSize()
// {
// switch (ui.cmboListItemSize->currentIndex())
// {
// case 0:
// Settings->setListItemIconSize(8);
// break;
// case 1:
// Settings->setListItemIconSize(16);
// break;
// case 2:
// default:
// Settings->setListItemIconSize(24);
// break;
// case 3:
// Settings->setListItemIconSize(32);
// break;
// case 4:
// Settings->setListItemIconSize(64);
// break;
// case 5:
// Settings->setListItemIconSize(128);
// }
// NotifyQt::getInstance()->notifySettingsChanged();
// }
void AppearancePage::updateStyle() { Rshare::setStyle(ui.cmboStyle->currentText()); }
/** Loads the settings for this page */ /** Loads the settings for this page */
void AppearancePage::load() void AppearancePage::load()
@ -165,10 +234,9 @@ void AppearancePage::load()
} }
ui.cmboStyleSheet->setCurrentIndex(index); ui.cmboStyleSheet->setCurrentIndex(index);
ui.rbtPageOnToolBar->setChecked(Settings->getPageButtonLoc()); ui.mainPageButtonType_CB->setCurrentIndex(!Settings->getPageButtonLoc());
ui.rbtPageOnListItem->setChecked(!Settings->getPageButtonLoc()); // ui.menuItemsButtonType_CB->setCurrentIndex(!Settings->getActionButtonLoc());
ui.rbtActionOnToolBar->setChecked(Settings->getActionButtonLoc());
ui.rbtActionOnListItem->setChecked(!Settings->getActionButtonLoc());
switch (Settings->getToolButtonStyle()) switch (Settings->getToolButtonStyle())
{ {
case Qt::ToolButtonIconOnly: case Qt::ToolButtonIconOnly:
@ -205,33 +273,42 @@ void AppearancePage::load()
case 128: case 128:
ui.cmboTollButtonsSize->setCurrentIndex(5); ui.cmboTollButtonsSize->setCurrentIndex(5);
} }
switch (Settings->getListItemIconSize()) // switch (Settings->getListItemIconSize())
{ // {
case 8: // case 8:
ui.cmboListItemSize->setCurrentIndex(0); // ui.cmboListItemSize->setCurrentIndex(0);
break; // break;
case 16: // case 16:
ui.cmboListItemSize->setCurrentIndex(1); // ui.cmboListItemSize->setCurrentIndex(1);
break; // break;
case 24: // case 24:
default: // default:
ui.cmboListItemSize->setCurrentIndex(2); // ui.cmboListItemSize->setCurrentIndex(2);
break; // break;
case 32: // case 32:
ui.cmboListItemSize->setCurrentIndex(3); // ui.cmboListItemSize->setCurrentIndex(3);
break; // break;
case 64: // case 64:
ui.cmboListItemSize->setCurrentIndex(4); // ui.cmboListItemSize->setCurrentIndex(4);
break; // break;
case 128: // case 128:
ui.cmboListItemSize->setCurrentIndex(5); // ui.cmboListItemSize->setCurrentIndex(5);
} // }
ui.grpStatus->setChecked(Settings->valueFromGroup("StatusBar", "ShowStatusBar", QVariant(true)).toBool());
ui.checkBoxStatusCompactMode->setChecked(Settings->valueFromGroup("StatusBar", "CompactMode", QVariant(false)).toBool()); ui.checkBoxStatusCompactMode->setChecked(Settings->valueFromGroup("StatusBar", "CompactMode", QVariant(false)).toBool());
ui.checkBoxHideSoundStatus->setChecked(Settings->valueFromGroup("StatusBar", "HideSound", QVariant(false)).toBool());
ui.checkBoxHideToasterDisable->setChecked(Settings->valueFromGroup("StatusBar", "HideToaster", QVariant(false)).toBool());
ui.checkBoxShowSystrayOnStatus->setChecked(Settings->valueFromGroup("StatusBar", "ShowSysTrayOnStatusBar", QVariant(false)).toBool());
ui.checkBoxDisableSysTrayToolTip->setChecked(Settings->valueFromGroup("StatusBar", "DisableSysTrayToolTip", QVariant(false)).toBool()); ui.checkBoxDisableSysTrayToolTip->setChecked(Settings->valueFromGroup("StatusBar", "DisableSysTrayToolTip", QVariant(false)).toBool());
ui.checkBoxShowStatusStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowStatus", QVariant(true)).toBool());
ui.checkBoxShowPeerStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowPeer", QVariant(true)).toBool());
ui.checkBoxShowNATStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowNAT", QVariant(true)).toBool());
ui.checkBoxShowDHTStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowDHT", QVariant(true)).toBool());
ui.checkBoxShowHashingStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowHashing", QVariant(true)).toBool());
ui.checkBoxShowDiscStatus-> setChecked(Settings->valueFromGroup("StatusBar", "Show eDisc", QVariant(true)).toBool());
ui.checkBoxShowRateStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowRate", QVariant(true)).toBool());
ui.checkBoxShowOpModeStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowOpMode", QVariant(true)).toBool());
ui.checkBoxShowSoundStatus-> setChecked(Settings->valueFromGroup("StatusBar", "ShowSound", QVariant(true)).toBool());
ui.checkBoxShowToasterDisable->setChecked(Settings->valueFromGroup("StatusBar", "ShowToaster", QVariant(true)).toBool());
ui.checkBoxShowSystrayOnStatus->setChecked(Settings->valueFromGroup("StatusBar", "ShowSysTrayOnStatusBar", QVariant(false)).toBool());
} }

View File

@ -23,6 +23,7 @@
#define _APPERARANCEPAGE_H #define _APPERARANCEPAGE_H
#include <retroshare-gui/configpage.h> #include <retroshare-gui/configpage.h>
#include "gui/MainWindow.h"
#include "ui_AppearancePage.h" #include "ui_AppearancePage.h"
class AppearancePage : public ConfigPage class AppearancePage : public ConfigPage
@ -33,8 +34,6 @@ public:
/** Default Constructor */ /** Default Constructor */
AppearancePage(QWidget * parent = 0, Qt::WindowFlags flags = 0); AppearancePage(QWidget * parent = 0, Qt::WindowFlags flags = 0);
/** Saves the changes on this page */
virtual bool save(QString &errmsg);
/** Loads the settings for this page */ /** Loads the settings for this page */
virtual void load(); virtual void load();
@ -45,7 +44,36 @@ public:
private slots: private slots:
void loadStyleSheet(int index); void loadStyleSheet(int index);
void switch_status_grpStatus(bool b) ;
void switch_status_compactMode(bool b) ;
void switch_status_showToolTip(bool b) ;
void switch_status_ShowStatus(bool) ;
void switch_status_ShowPeer(bool) ;
void switch_status_ShowDHT(bool) ;
void switch_status_ShowHashing(bool) ;
void switch_status_ShowDisc(bool) ;
void switch_status_ShowRate(bool) ;
void switch_status_ShowOpMode(bool) ;
void switch_status_ShowSound(bool) ;
void switch_status_ShowToaster(bool) ;
void switch_status_ShowSystray(bool) ;
void switch_status_ShowCBox(bool) ;
void updateLanguageCode() ;
void updateInterfaceStyle() ;
void updateSheetName() ;
void updateRbtPageOnToolBar();
// void updateActionButtonLoc() ;
void updateStatusToolTip() ;
void updateCmboToolButtonStyle();
void updateCmboToolButtonSize();
// void updateCmboListItemSize();
void updateStyle() ;
private: private:
void switch_status(MainWindow::StatusElement s,const QString& key,bool b);
/** Qt Designer generated object */ /** Qt Designer generated object */
Ui::AppearancePage ui; Ui::AppearancePage ui;
}; };

View File

@ -6,14 +6,14 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>1160</width> <width>1170</width>
<height>567</height> <height>897</height>
</rect> </rect>
</property> </property>
<property name="contextMenuPolicy"> <property name="contextMenuPolicy">
<enum>Qt::NoContextMenu</enum> <enum>Qt::NoContextMenu</enum>
</property> </property>
<layout class="QGridLayout"> <layout class="QGridLayout" name="AppearancePageGLayout">
<property name="leftMargin"> <property name="leftMargin">
<number>6</number> <number>6</number>
</property> </property>
@ -43,14 +43,7 @@
<property name="title"> <property name="title">
<string>Language</string> <string>Language</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_Language"> <layout class="QGridLayout" name="grpLanguageGLayout">
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="labelLanguage">
<property name="text">
<string>Changes to language will only take effect after restarting RetroShare!</string>
</property>
</widget>
</item>
<item row="1" column="0"> <item row="1" column="0">
<widget class="QComboBox" name="cmboLanguage"> <widget class="QComboBox" name="cmboLanguage">
<property name="minimumSize"> <property name="minimumSize">
@ -70,8 +63,8 @@
</property> </property>
</widget> </widget>
</item> </item>
<item row="1" column="1"> <item row="1" column="2">
<spacer> <spacer name="grpLanguageHSpacer">
<property name="orientation"> <property name="orientation">
<enum>Qt::Horizontal</enum> <enum>Qt::Horizontal</enum>
</property> </property>
@ -83,6 +76,13 @@
</property> </property>
</spacer> </spacer>
</item> </item>
<item row="1" column="1">
<widget class="QLabel" name="labelLanguage">
<property name="text">
<string>(Needs restart)</string>
</property>
</widget>
</item>
</layout> </layout>
</widget> </widget>
</item> </item>
@ -103,7 +103,7 @@
<property name="title"> <property name="title">
<string>Style</string> <string>Style</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_Style"> <layout class="QGridLayout" name="grpStyleGLayout">
<item row="0" column="0"> <item row="0" column="0">
<widget class="QComboBox" name="cmboStyle"> <widget class="QComboBox" name="cmboStyle">
<property name="minimumSize"> <property name="minimumSize">
@ -118,7 +118,7 @@
</widget> </widget>
</item> </item>
<item row="0" column="1"> <item row="0" column="1">
<spacer> <spacer name="grpStyleHSpacer">
<property name="orientation"> <property name="orientation">
<enum>Qt::Horizontal</enum> <enum>Qt::Horizontal</enum>
</property> </property>
@ -144,7 +144,7 @@
<property name="title"> <property name="title">
<string>Style Sheet</string> <string>Style Sheet</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_StyleSheet"> <layout class="QGridLayout" name="grpStyleSheetGLayout">
<item row="0" column="0"> <item row="0" column="0">
<widget class="QComboBox" name="cmboStyleSheet"> <widget class="QComboBox" name="cmboStyleSheet">
<property name="minimumSize"> <property name="minimumSize">
@ -156,7 +156,7 @@
</widget> </widget>
</item> </item>
<item row="0" column="1"> <item row="0" column="1">
<spacer> <spacer name="grpStyleSheetHSpacer">
<property name="orientation"> <property name="orientation">
<enum>Qt::Horizontal</enum> <enum>Qt::Horizontal</enum>
</property> </property>
@ -172,7 +172,7 @@
</widget> </widget>
</item> </item>
<item row="8" column="0"> <item row="8" column="0">
<spacer> <spacer name="AppearancePageVSpacer">
<property name="orientation"> <property name="orientation">
<enum>Qt::Vertical</enum> <enum>Qt::Vertical</enum>
</property> </property>
@ -198,124 +198,46 @@
<property name="title"> <property name="title">
<string>Tool Bar</string> <string>Tool Bar</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout_ToolBar"> <layout class="QVBoxLayout" name="verticalLayout">
<item row="4" column="0"> <item>
<widget class="QFrame" name="frameAction"> <layout class="QHBoxLayout" name="horizontalLayout">
<property name="frameShape"> <item>
<enum>QFrame::StyledPanel</enum> <widget class="QLabel" name="labelPageToolBar">
</property> <property name="text">
<property name="frameShadow"> <string>Main page items:</string>
<enum>QFrame::Plain</enum> </property>
</property> </widget>
<layout class="QHBoxLayout" name="horizontalLayout"> </item>
<property name="leftMargin"> <item>
<number>2</number> <widget class="QComboBox" name="mainPageButtonType_CB">
</property> <item>
<property name="topMargin">
<number>2</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<widget class="QRadioButton" name="rbtActionOnToolBar">
<property name="text"> <property name="text">
<string>On Tool Bar</string> <string>Buttons</string>
</property> </property>
</widget> </item>
</item> <item>
<item>
<widget class="QRadioButton" name="rbtActionOnListItem">
<property name="text"> <property name="text">
<string>On List Ite&amp;m</string> <string>Item list</string>
</property> </property>
</widget> </item>
</item> </widget>
<item> </item>
<spacer> <item>
<property name="orientation"> <spacer name="framePageHSpacer">
<enum>Qt::Horizontal</enum> <property name="orientation">
</property> <enum>Qt::Horizontal</enum>
<property name="sizeHint" stdset="0"> </property>
<size> <property name="sizeHint" stdset="0">
<width>300</width> <size>
<height>16</height> <width>300</width>
</size> <height>16</height>
</property> </size>
</spacer> </property>
</item> </spacer>
</layout> </item>
</widget> </layout>
</item> </item>
<item row="3" column="0"> <item>
<widget class="QLabel" name="labelActionToolBar">
<property name="text">
<string>Where do you want to have the buttons for menu?</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QFrame" name="framePage">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<property name="leftMargin">
<number>2</number>
</property>
<property name="topMargin">
<number>2</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<widget class="QRadioButton" name="rbtPageOnToolBar">
<property name="text">
<string>On Tool Bar</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="rbtPageOnListItem">
<property name="text">
<string>On List Item</string>
</property>
</widget>
</item>
<item>
<spacer>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>300</width>
<height>16</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelPageToolBar">
<property name="text">
<string>Where do you want to have the buttons for the page?</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QFrame" name="frameToolListStyle"> <widget class="QFrame" name="frameToolListStyle">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
@ -326,7 +248,7 @@
<property name="frameShape"> <property name="frameShape">
<enum>QFrame::NoFrame</enum> <enum>QFrame::NoFrame</enum>
</property> </property>
<layout class="QGridLayout" name="gridLayoutToolListStyle"> <layout class="QGridLayout" name="frameToolListStyleGLayout">
<item row="2" column="0"> <item row="2" column="0">
<widget class="QComboBox" name="cmboTollButtonsStyle"> <widget class="QComboBox" name="cmboTollButtonsStyle">
<item> <item>
@ -364,19 +286,6 @@
</property> </property>
</widget> </widget>
</item> </item>
<item row="0" column="1">
<widget class="QLabel" name="labelListItemStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Choose the style of List Items.</string>
</property>
</widget>
</item>
<item row="1" column="0"> <item row="1" column="0">
<widget class="QComboBox" name="cmboTollButtonsSize"> <widget class="QComboBox" name="cmboTollButtonsSize">
<item> <item>
@ -411,40 +320,6 @@
</item> </item>
</widget> </widget>
</item> </item>
<item row="1" column="1">
<widget class="QComboBox" name="cmboListItemSize">
<item>
<property name="text">
<string>Icon Size = 8x8</string>
</property>
</item>
<item>
<property name="text">
<string>Icon Size = 16x16</string>
</property>
</item>
<item>
<property name="text">
<string>Icon Size = 24x24</string>
</property>
</item>
<item>
<property name="text">
<string>Icon Size = 32x32</string>
</property>
</item>
<item>
<property name="text">
<string>Icon Size = 64x64</string>
</property>
</item>
<item>
<property name="text">
<string>Icon Size = 128x128</string>
</property>
</item>
</widget>
</item>
</layout> </layout>
</widget> </widget>
</item> </item>
@ -456,8 +331,77 @@
<property name="title"> <property name="title">
<string>Status Bar</string> <string>Status Bar</string>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout_3"> <property name="checkable">
<item> <bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<layout class="QGridLayout" name="grpStatusGLayout">
<item row="4" column="1">
<widget class="QCheckBox" name="checkBoxShowToasterDisable">
<property name="text">
<string>Show Toaster Disable</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QCheckBox" name="checkBoxShowSoundStatus">
<property name="text">
<string>Show Sound Status</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QCheckBox" name="checkBoxShowRateStatus">
<property name="text">
<string>Show Network Rate Status</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QCheckBox" name="checkBoxShowDiscStatus">
<property name="text">
<string>Show Discovery Status</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QCheckBox" name="checkBoxShowDHTStatus">
<property name="text">
<string>Show DHT Status</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QCheckBox" name="checkBoxShowHashingStatus">
<property name="text">
<string>Show Hashing Status</string>
</property>
</widget>
</item>
<item row="1" column="2">
<widget class="QCheckBox" name="checkBoxShowNATStatus">
<property name="text">
<string>Show NAT Status</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QCheckBox" name="checkBoxShowPeerStatus">
<property name="text">
<string>Show Peer Status</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QCheckBox" name="checkBoxShowStatusStatus">
<property name="text">
<string>Show Status ComboBox</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QCheckBox" name="checkBoxStatusCompactMode"> <widget class="QCheckBox" name="checkBoxStatusCompactMode">
<property name="toolTip"> <property name="toolTip">
<string>Remove surplus text in status bar.</string> <string>Remove surplus text in status bar.</string>
@ -467,34 +411,27 @@
</property> </property>
</widget> </widget>
</item> </item>
<item> <item row="0" column="1">
<widget class="QCheckBox" name="checkBoxHideSoundStatus">
<property name="text">
<string>Hide Sound Status</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxHideToasterDisable">
<property name="text">
<string>Hide Toaster Disable</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxShowSystrayOnStatus">
<property name="text">
<string>Show SysTray on Status Bar</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxDisableSysTrayToolTip"> <widget class="QCheckBox" name="checkBoxDisableSysTrayToolTip">
<property name="text"> <property name="text">
<string>Disable SysTray ToolTip</string> <string>Disable SysTray ToolTip</string>
</property> </property>
</widget> </widget>
</item> </item>
<item row="2" column="2">
<widget class="QCheckBox" name="checkBoxShowOpModeStatus">
<property name="text">
<string>Show Operating Mode Status</string>
</property>
</widget>
</item>
<item row="3" column="2">
<widget class="QCheckBox" name="checkBoxShowSystrayOnStatus">
<property name="text">
<string>Show SysTray on Status Bar</string>
</property>
</widget>
</item>
</layout> </layout>
</widget> </widget>
</item> </item>

View File

@ -30,21 +30,17 @@ ChannelPage::ChannelPage(QWidget * parent, Qt::WindowFlags flags)
/* Initialize GroupFrameSettingsWidget */ /* Initialize GroupFrameSettingsWidget */
ui.groupFrameSettingsWidget->setOpenAllInNewTabText(tr("Open each channel in a new tab")); ui.groupFrameSettingsWidget->setOpenAllInNewTabText(tr("Open each channel in a new tab"));
ui.groupFrameSettingsWidget->setType(GroupFrameSettings::Channel) ;
connect(ui.loadThreadCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateLoadThread)) ;
} }
void ChannelPage::updateLoadThread() { Settings->setChannelLoadThread(ui.loadThreadCheckBox->isChecked()); }
ChannelPage::~ChannelPage() ChannelPage::~ChannelPage()
{ {
} }
/** Saves the changes on this page */
bool ChannelPage::save(QString &/*errmsg*/)
{
Settings->setChannelLoadThread(ui.loadThreadCheckBox->isChecked());
ui.groupFrameSettingsWidget->saveSettings(GroupFrameSettings::Channel);
return true;
}
/** Loads the settings for this page */ /** Loads the settings for this page */
void ChannelPage::load() void ChannelPage::load()
{ {

View File

@ -33,8 +33,6 @@ public:
ChannelPage(QWidget * parent = 0, Qt::WindowFlags flags = 0); ChannelPage(QWidget * parent = 0, Qt::WindowFlags flags = 0);
~ChannelPage(); ~ChannelPage();
/** Saves the changes on this page */
virtual bool save(QString &errmsg);
/** Loads the settings for this page */ /** Loads the settings for this page */
virtual void load(); virtual void load();
@ -42,6 +40,9 @@ public:
virtual QString pageName() const { return tr("Channels") ; } virtual QString pageName() const { return tr("Channels") ; }
virtual QString helpText() const { return ""; } virtual QString helpText() const { return ""; }
protected slots:
void updateLoadThread() ;
private: private:
Ui::ChannelPage ui; Ui::ChannelPage ui;
}; };

View File

@ -34,6 +34,7 @@
#include "gui/chat/ChatDialog.h" #include "gui/chat/ChatDialog.h"
#include "gui/notifyqt.h" #include "gui/notifyqt.h"
#include "rsharesettings.h" #include "rsharesettings.h"
#include <retroshare/rsconfig.h>
#include <retroshare/rshistory.h> #include <retroshare/rshistory.h>
#include <retroshare/rsmsgs.h> #include <retroshare/rsmsgs.h>
@ -44,12 +45,11 @@
#define IMAGE_CHAT_DELETE ":/images/deletemail24.png" #define IMAGE_CHAT_DELETE ":/images/deletemail24.png"
#define IMAGE_CHAT_COPY ":/images/copyrslink.png" #define IMAGE_CHAT_COPY ":/images/copyrslink.png"
static QString loadStyleInfo(ChatStyle::enumStyleType type, QListWidget *listWidget, QComboBox *comboBox, QString &styleVariant) static QString loadStyleInfo(ChatStyle::enumStyleType type, QComboBox *style_CB, QComboBox *comboBox, QString &styleVariant)
{ {
QList<ChatStyleInfo> styles; QList<ChatStyleInfo> styles;
QList<ChatStyleInfo>::iterator style; QList<ChatStyleInfo>::iterator style;
QListWidgetItem *item; int activeItem = 0;
QListWidgetItem *activeItem = NULL;
QString stylePath; QString stylePath;
@ -68,17 +68,22 @@ static QString loadStyleInfo(ChatStyle::enumStyleType type, QListWidget *listWid
} }
ChatStyle::getAvailableStyles(type, styles); ChatStyle::getAvailableStyles(type, styles);
for (style = styles.begin(); style != styles.end(); ++style) {
item = new QListWidgetItem(style->styleName); while(style_CB->count())
item->setData(Qt::UserRole, qVariantFromValue(*style)); style_CB->removeItem(0) ;
listWidget->addItem(item);
int n=0;
for (style = styles.begin(); style != styles.end(); ++style,++n)
{
style_CB->insertItem(n,style->styleName);
style_CB->setItemData(n, qVariantFromValue(*style),Qt::UserRole);
if (style->stylePath == stylePath) { if (style->stylePath == stylePath) {
activeItem = item; activeItem = n;
} }
} }
listWidget->setCurrentItem(activeItem); style_CB->setCurrentIndex(activeItem);
/* now the combobox should be filled */ /* now the combobox should be filled */
@ -92,6 +97,108 @@ static QString loadStyleInfo(ChatStyle::enumStyleType type, QListWidget *listWid
} }
return stylePath; return stylePath;
} }
void ChatPage::updateFontsAndEmotes()
{
Settings->beginGroup(QString("Chat"));
Settings->setValue("Emoteicons_PrivatChat", ui.checkBox_emoteprivchat->isChecked());
Settings->setValue("Emoteicons_GroupChat", ui.checkBox_emotegroupchat->isChecked());
Settings->setValue("EnableCustomFonts", ui.checkBox_enableCustomFonts->isChecked());
Settings->setValue("EnableCustomFontSize", ui.checkBox_enableCustomFontSize->isChecked());
Settings->setValue("MinimumFontSize", ui.minimumFontSize->value());
Settings->setValue("EnableBold", ui.checkBox_enableBold->isChecked());
Settings->setValue("EnableItalics", ui.checkBox_enableItalics->isChecked());
Settings->setValue("MinimumContrast", ui.minimumContrast->value());
Settings->endGroup();
}
/** Saves the changes on this page */
void ChatPage::updateChatParams()
{
// state of distant Chat combobox
Settings->setValue("DistantChat", ui.distantChatComboBox->currentIndex());
Settings->setChatScreenFont(fontTempChat.toString());
NotifyQt::getInstance()->notifyChatFontChanged();
Settings->setChatSendMessageWithCtrlReturn(ui.sendMessageWithCtrlReturn->isChecked());
Settings->setChatSendAsPlainTextByDef(ui.sendAsPlainTextByDef->isChecked());
Settings->setChatLoadEmbeddedImages(ui.loadEmbeddedImages->isChecked());
Settings->setChatDoNotSendIsTyping(ui.DontSendTyping->isChecked());
}
void ChatPage::updateChatSearchParams()
{
Settings->setChatSearchCharToStartSearch(ui.sbSearch_CharToStart->value());
Settings->setChatSearchCaseSensitively(ui.cbSearch_CaseSensitively->isChecked());
Settings->setChatSearchWholeWords(ui.cbSearch_WholeWords->isChecked());
Settings->setChatSearchMoveToCursor(ui.cbSearch_MoveToCursor->isChecked());
Settings->setChatSearchSearchWithoutLimit(ui.cbSearch_WithoutLimit->isChecked());
Settings->setChatSearchMaxSearchLimitColor(ui.sbSearch_MaxLimitColor->value());
Settings->setChatSearchFoundColor(rgbChatSearchFoundColor);
}
void ChatPage::updateDefaultLobbyIdentity()
{
RsGxsId chosen_id ;
switch(ui.chatLobbyIdentity_IC->getChosenId(chosen_id))
{
case GxsIdChooser::KnowId:
case GxsIdChooser::UnKnowId:
rsMsgs->setDefaultIdentityForChatLobby(chosen_id) ;
break ;
default:;
}
}
void ChatPage::updateHistoryParams()
{
Settings->setPublicChatHistoryCount(ui.publicChatLoadCount->value());
Settings->setPrivateChatHistoryCount(ui.privateChatLoadCount->value());
Settings->setLobbyChatHistoryCount(ui.lobbyChatLoadCount->value());
rsHistory->setEnable(RS_HISTORY_TYPE_PUBLIC , ui.publicChatEnable->isChecked());
rsHistory->setEnable(RS_HISTORY_TYPE_PRIVATE, ui.privateChatEnable->isChecked());
rsHistory->setEnable(RS_HISTORY_TYPE_LOBBY , ui.lobbyChatEnable->isChecked());
rsHistory->setSaveCount(RS_HISTORY_TYPE_PUBLIC , ui.publicChatSaveCount->value());
rsHistory->setSaveCount(RS_HISTORY_TYPE_PRIVATE, ui.privateChatSaveCount->value());
rsHistory->setSaveCount(RS_HISTORY_TYPE_LOBBY , ui.lobbyChatSaveCount->value());
}
void ChatPage::updatePublicStyle()
{
ChatStyleInfo info = ui.publicStyle->itemData(ui.historyStyle->currentIndex(),Qt::UserRole).value<ChatStyleInfo>();
if (publicStylePath != info.stylePath || publicStyleVariant != ui.publicComboBoxVariant->currentText()) {
Settings->setPublicChatStyle(info.stylePath, ui.publicComboBoxVariant->currentText());
NotifyQt::getInstance()->notifyChatStyleChanged(ChatStyle::TYPE_PUBLIC);
}
}
void ChatPage::updatePrivateStyle()
{
ChatStyleInfo info = ui.privateStyle->itemData(ui.historyStyle->currentIndex(),Qt::UserRole).value<ChatStyleInfo>();
if (privateStylePath != info.stylePath || privateStyleVariant != ui.privateComboBoxVariant->currentText()) {
Settings->setPrivateChatStyle(info.stylePath, ui.privateComboBoxVariant->currentText());
NotifyQt::getInstance()->notifyChatStyleChanged(ChatStyle::TYPE_PRIVATE);
}
}
void ChatPage::updateHistoryStyle()
{
ChatStyleInfo info = ui.historyStyle->itemData(ui.historyStyle->currentIndex(),Qt::UserRole).value<ChatStyleInfo>();
if (historyStylePath != info.stylePath || historyStyleVariant != ui.historyComboBoxVariant->currentText()) {
Settings->setHistoryChatStyle(info.stylePath, ui.historyComboBoxVariant->currentText());
NotifyQt::getInstance()->notifyChatStyleChanged(ChatStyle::TYPE_HISTORY);
}
}
void ChatPage::updateHistoryStorage() { rsHistory->setMaxStorageDuration(ui.max_storage_period->value() * 86400) ; }
/** Constructor */ /** Constructor */
ChatPage::ChatPage(QWidget * parent, Qt::WindowFlags flags) ChatPage::ChatPage(QWidget * parent, Qt::WindowFlags flags)
@ -100,120 +207,91 @@ ChatPage::ChatPage(QWidget * parent, Qt::WindowFlags flags)
/* Invoke the Qt Designer generated object setup routine */ /* Invoke the Qt Designer generated object setup routine */
ui.setupUi(this); ui.setupUi(this);
connect(ui.distantChatComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(distantChatComboBoxChanged(int)));
#if QT_VERSION < 0x040600 #if QT_VERSION < 0x040600
ui.minimumContrastLabel->hide(); ui.minimumContrastLabel->hide();
ui.minimumContrast->hide(); ui.minimumContrast->hide();
#endif #endif
connect(ui.distantChatComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(distantChatComboBoxChanged(int)));
connect(ui.checkBox_emoteprivchat, SIGNAL(toggled(bool)), this, SLOT(updateFontsAndEmotes()));
connect(ui.checkBox_emotegroupchat, SIGNAL(toggled(bool)), this, SLOT(updateFontsAndEmotes()));
connect(ui.checkBox_enableCustomFonts, SIGNAL(toggled(bool)), this, SLOT(updateFontsAndEmotes()));
connect(ui.minimumFontSize, SIGNAL(valueChanged(int)), this, SLOT(updateFontsAndEmotes()));
connect(ui.checkBox_enableBold, SIGNAL(toggled(bool)), this, SLOT(updateFontsAndEmotes()));
connect(ui.checkBox_enableItalics, SIGNAL(toggled(bool)), this, SLOT(updateFontsAndEmotes()));
connect(ui.minimumContrast, SIGNAL(valueChanged(int)), this, SLOT(updateFontsAndEmotes()));
connect(ui.distantChatComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateChatParams()));
connect(ui.sendMessageWithCtrlReturn, SIGNAL(toggled(bool)), this, SLOT(updateChatParams()));
connect(ui.sendAsPlainTextByDef, SIGNAL(toggled(bool)), this, SLOT(updateChatParams()));
connect(ui.loadEmbeddedImages, SIGNAL(toggled(bool)), this, SLOT(updateChatParams()));
connect(ui.DontSendTyping, SIGNAL(toggled(bool)), this, SLOT(updateChatParams()));
connect(ui.sbSearch_CharToStart, SIGNAL(valueChanged(int)), this, SLOT(updateChatSearchParams()));
connect(ui.cbSearch_CaseSensitively, SIGNAL(toggled(bool)), this, SLOT(updateChatSearchParams()));
connect(ui.cbSearch_WholeWords, SIGNAL(toggled(bool)), this, SLOT(updateChatSearchParams()));
connect(ui.cbSearch_MoveToCursor, SIGNAL(toggled(bool)), this, SLOT(updateChatSearchParams()));
connect(ui.cbSearch_WithoutLimit, SIGNAL(toggled(bool)), this, SLOT(updateChatSearchParams()));
connect(ui.sbSearch_MaxLimitColor, SIGNAL(valueChanged(int)), this, SLOT(updateChatSearchParams()));
connect(ui.chatLobbyIdentity_IC, SIGNAL(currentIndexChanged(int)), this, SLOT(updateDefaultLobbyIdentity()));
connect(ui.publicChatLoadCount, SIGNAL(valueChanged(int)), this, SLOT(updateHistoryParams()));
connect(ui.privateChatLoadCount, SIGNAL(valueChanged(int)), this, SLOT(updateHistoryParams()));
connect(ui.lobbyChatLoadCount, SIGNAL(valueChanged(int)), this, SLOT(updateHistoryParams()));
connect(ui.publicChatEnable, SIGNAL(toggled(bool)), this, SLOT(updateHistoryParams()));
connect(ui.privateChatEnable, SIGNAL(toggled(bool)), this, SLOT(updateHistoryParams()));
connect(ui.lobbyChatEnable, SIGNAL(toggled(bool)), this, SLOT(updateHistoryParams()));
connect(ui.publicChatSaveCount, SIGNAL(valueChanged(int)), this, SLOT(updateHistoryParams()));
connect(ui.privateChatSaveCount, SIGNAL(valueChanged(int)), this, SLOT(updateHistoryParams()));
connect(ui.lobbyChatSaveCount, SIGNAL(valueChanged(int)), this, SLOT(updateHistoryParams()));
connect(ui.publicStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(updatePublicStyle())) ;
connect(ui.publicComboBoxVariant, SIGNAL(currentIndexChanged(int)), this, SLOT(updatePublicStyle())) ;
connect(ui.privateStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(updatePrivateStyle())) ;
connect(ui.privateComboBoxVariant, SIGNAL(currentIndexChanged(int)), this, SLOT(updatePrivateStyle())) ;
connect(ui.historyStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(updateHistoryStyle())) ;
connect(ui.historyComboBoxVariant, SIGNAL(currentIndexChanged(int)), this, SLOT(updateHistoryStyle())) ;
connect(ui.max_storage_period, SIGNAL(valueChanged(int)), this, SLOT(updateHistoryStorage())) ;
connect(ui.chat_NewWindow, SIGNAL(toggled(bool)), this, SLOT(updateChatFlags()));
connect(ui.chat_Focus, SIGNAL(toggled(bool)), this, SLOT(updateChatFlags()));
connect(ui.chat_tabbedWindow, SIGNAL(toggled(bool)), this, SLOT(updateChatFlags()));
connect(ui.chat_Blink, SIGNAL(toggled(bool)), this, SLOT(updateChatFlags()));
connect(ui.chatLobby_Blink, SIGNAL(toggled(bool)), this, SLOT(updateChatLobbyFlags()));
connect(ui.publicStyle, SIGNAL(currentIndexChanged(int)), this,SLOT(on_publicList_currentRowChanged(int)));
connect(ui.privateStyle, SIGNAL(currentIndexChanged(int)), this,SLOT(on_privateList_currentRowChanged(int)));
connect(ui.historyStyle, SIGNAL(currentIndexChanged(int)), this,SLOT(on_historyList_currentRowChanged(int)));
}
void ChatPage::updateChatFlags()
{
uint chatflags = 0;
if (ui.chat_NewWindow->isChecked())
chatflags |= RS_CHAT_OPEN;
if (ui.chat_Focus->isChecked())
chatflags |= RS_CHAT_FOCUS;
if (ui.chat_tabbedWindow->isChecked())
chatflags |= RS_CHAT_TABBED_WINDOW;
if (ui.chat_Blink->isChecked())
chatflags |= RS_CHAT_BLINK;
Settings->setChatFlags(chatflags);
} }
/** Saves the changes on this page */ void ChatPage::updateChatLobbyFlags()
bool
ChatPage::save(QString &/*errmsg*/)
{ {
Settings->beginGroup(QString("Chat")); uint chatLobbyFlags = 0;
Settings->setValue("Emoteicons_PrivatChat", ui.checkBox_emoteprivchat->isChecked());
Settings->setValue("Emoteicons_GroupChat", ui.checkBox_emotegroupchat->isChecked());
Settings->setValue("EnableCustomFonts", ui.checkBox_enableCustomFonts->isChecked());
Settings->setValue("EnableCustomFontSize", ui.checkBox_enableCustomFontSize->isChecked());
Settings->setValue("MinimumFontSize", ui.minimumFontSize->value());
Settings->setValue("EnableBold", ui.checkBox_enableBold->isChecked());
Settings->setValue("EnableItalics", ui.checkBox_enableItalics->isChecked());
Settings->setValue("MinimumContrast", ui.minimumContrast->value());
Settings->endGroup();
// state of distant Chat combobox
Settings->setValue("DistantChat", ui.distantChatComboBox->currentIndex());
Settings->setChatScreenFont(fontTempChat.toString()); if (ui.chatLobby_Blink->isChecked())
NotifyQt::getInstance()->notifyChatFontChanged(); chatLobbyFlags |= RS_CHATLOBBY_BLINK;
Settings->setChatSendMessageWithCtrlReturn(ui.sendMessageWithCtrlReturn->isChecked()); Settings->setChatLobbyFlags(chatLobbyFlags);
Settings->setChatSendAsPlainTextByDef(ui.sendAsPlainTextByDef->isChecked());
Settings->setChatLoadEmbeddedImages(ui.loadEmbeddedImages->isChecked());
Settings->setChatSearchCharToStartSearch(ui.sbSearch_CharToStart->value());
Settings->setChatSearchCaseSensitively(ui.cbSearch_CaseSensitively->isChecked());
Settings->setChatSearchWholeWords(ui.cbSearch_WholeWords->isChecked());
Settings->setChatSearchMoveToCursor(ui.cbSearch_MoveToCursor->isChecked());
Settings->setChatSearchSearchWithoutLimit(ui.cbSearch_WithoutLimit->isChecked());
Settings->setChatSearchMaxSearchLimitColor(ui.sbSearch_MaxLimitColor->value());
Settings->setChatSearchFoundColor(rgbChatSearchFoundColor);
Settings->setPublicChatHistoryCount(ui.publicChatLoadCount->value());
Settings->setPrivateChatHistoryCount(ui.privateChatLoadCount->value());
Settings->setLobbyChatHistoryCount(ui.lobbyChatLoadCount->value());
rsHistory->setEnable(RS_HISTORY_TYPE_PUBLIC , ui.publicChatEnable->isChecked());
rsHistory->setEnable(RS_HISTORY_TYPE_PRIVATE, ui.privateChatEnable->isChecked());
rsHistory->setEnable(RS_HISTORY_TYPE_LOBBY , ui.lobbyChatEnable->isChecked());
rsHistory->setSaveCount(RS_HISTORY_TYPE_PUBLIC , ui.publicChatSaveCount->value());
rsHistory->setSaveCount(RS_HISTORY_TYPE_PRIVATE, ui.privateChatSaveCount->value());
rsHistory->setSaveCount(RS_HISTORY_TYPE_LOBBY , ui.lobbyChatSaveCount->value());
RsGxsId chosen_id ;
switch(ui.chatLobbyIdentity_IC->getChosenId(chosen_id))
{
case GxsIdChooser::KnowId:
case GxsIdChooser::UnKnowId:
rsMsgs->setDefaultIdentityForChatLobby(chosen_id) ;
break ;
default:;
}
ChatStyleInfo info;
QListWidgetItem *item = ui.publicList->currentItem();
if (item) {
info = item->data(Qt::UserRole).value<ChatStyleInfo>();
if (publicStylePath != info.stylePath || publicStyleVariant != ui.publicComboBoxVariant->currentText()) {
Settings->setPublicChatStyle(info.stylePath, ui.publicComboBoxVariant->currentText());
NotifyQt::getInstance()->notifyChatStyleChanged(ChatStyle::TYPE_PUBLIC);
}
}
item = ui.privateList->currentItem();
if (item) {
info = item->data(Qt::UserRole).value<ChatStyleInfo>();
if (privateStylePath != info.stylePath || privateStyleVariant != ui.privateComboBoxVariant->currentText()) {
Settings->setPrivateChatStyle(info.stylePath, ui.privateComboBoxVariant->currentText());
NotifyQt::getInstance()->notifyChatStyleChanged(ChatStyle::TYPE_PRIVATE);
}
}
item = ui.historyList->currentItem();
if (item) {
info = item->data(Qt::UserRole).value<ChatStyleInfo>();
if (historyStylePath != info.stylePath || historyStyleVariant != ui.historyComboBoxVariant->currentText()) {
Settings->setHistoryChatStyle(info.stylePath, ui.historyComboBoxVariant->currentText());
NotifyQt::getInstance()->notifyChatStyleChanged(ChatStyle::TYPE_HISTORY);
}
}
rsHistory->setMaxStorageDuration(ui.max_storage_period->value() * 86400) ;
uint chatflags = 0;
if (ui.chat_NewWindow->isChecked())
chatflags |= RS_CHAT_OPEN;
if (ui.chat_Focus->isChecked())
chatflags |= RS_CHAT_FOCUS;
if (ui.chat_tabbedWindow->isChecked())
chatflags |= RS_CHAT_TABBED_WINDOW;
if (ui.chat_Blink->isChecked())
chatflags |= RS_CHAT_BLINK;
Settings->setChatFlags(chatflags);
uint chatLobbyFlags = 0;
if (ui.chatLobby_Blink->isChecked())
chatLobbyFlags |= RS_CHATLOBBY_BLINK;
Settings->setChatLobbyFlags(chatLobbyFlags);
return true;
} }
/** Loads the settings for this page */ /** Loads the settings for this page */
@ -240,6 +318,13 @@ ChatPage::load()
ui.sendMessageWithCtrlReturn->setChecked(Settings->getChatSendMessageWithCtrlReturn()); ui.sendMessageWithCtrlReturn->setChecked(Settings->getChatSendMessageWithCtrlReturn());
ui.sendAsPlainTextByDef->setChecked(Settings->getChatSendAsPlainTextByDef()); ui.sendAsPlainTextByDef->setChecked(Settings->getChatSendAsPlainTextByDef());
ui.loadEmbeddedImages->setChecked(Settings->getChatLoadEmbeddedImages()); ui.loadEmbeddedImages->setChecked(Settings->getChatLoadEmbeddedImages());
ui.DontSendTyping->setChecked(Settings->getChatDoNotSendIsTyping());
std::string advsetting;
if(rsConfig->getConfigurationOption(RS_CONFIG_ADVANCED, advsetting) && (advsetting == "YES"))
{ }
else
ui.DontSendTyping->hide();
ui.sbSearch_CharToStart->setValue(Settings->getChatSearchCharToStartSearch()); ui.sbSearch_CharToStart->setValue(Settings->getChatSearchCharToStartSearch());
ui.cbSearch_CaseSensitively->setChecked(Settings->getChatSearchCaseSensitively()); ui.cbSearch_CaseSensitively->setChecked(Settings->getChatSearchCaseSensitively());
@ -273,9 +358,9 @@ ChatPage::load()
ui.max_storage_period->setValue(rsHistory->getMaxStorageDuration()/86400) ; ui.max_storage_period->setValue(rsHistory->getMaxStorageDuration()/86400) ;
/* Load styles */ /* Load styles */
publicStylePath = loadStyleInfo(ChatStyle::TYPE_PUBLIC, ui.publicList, ui.publicComboBoxVariant, publicStyleVariant); publicStylePath = loadStyleInfo(ChatStyle::TYPE_PUBLIC, ui.publicStyle, ui.publicComboBoxVariant, publicStyleVariant);
privateStylePath = loadStyleInfo(ChatStyle::TYPE_PRIVATE, ui.privateList, ui.privateComboBoxVariant, privateStyleVariant); privateStylePath = loadStyleInfo(ChatStyle::TYPE_PRIVATE, ui.privateStyle, ui.privateComboBoxVariant, privateStyleVariant);
historyStylePath = loadStyleInfo(ChatStyle::TYPE_HISTORY, ui.historyList, ui.historyComboBoxVariant, historyStyleVariant); historyStylePath = loadStyleInfo(ChatStyle::TYPE_HISTORY, ui.historyStyle, ui.historyComboBoxVariant, historyStyleVariant);
RsGxsId gxs_id ; RsGxsId gxs_id ;
rsMsgs->getDefaultIdentityForChatLobby(gxs_id) ; rsMsgs->getDefaultIdentityForChatLobby(gxs_id) ;
@ -352,23 +437,17 @@ void ChatPage::setPreviewMessages(QString &stylePath, QString styleVariant, QTex
textBrowser->append(style.formatMessage(ChatStyle::FORMATMSG_OUTGOING, tr("UserName"), timestmp, tr("/me is sending a message with /me"), 0, backgroundColor)); textBrowser->append(style.formatMessage(ChatStyle::FORMATMSG_OUTGOING, tr("UserName"), timestmp, tr("/me is sending a message with /me"), 0, backgroundColor));
} }
void ChatPage::fillPreview(QListWidget *listWidget, QComboBox *comboBox, QTextBrowser *textBrowser) void ChatPage::fillPreview(QComboBox *listWidget, QComboBox *comboBox, QTextBrowser *textBrowser)
{ {
QListWidgetItem *item = listWidget->currentItem(); ChatStyleInfo info = listWidget->itemData(listWidget->currentIndex(),Qt::UserRole).value<ChatStyleInfo>();
if (item) {
ChatStyleInfo info = item->data(Qt::UserRole).value<ChatStyleInfo>();
setPreviewMessages(info.stylePath, comboBox->currentText(), textBrowser); setPreviewMessages(info.stylePath, comboBox->currentText(), textBrowser);
} else {
textBrowser->clear();
}
} }
void ChatPage::on_publicList_currentRowChanged(int currentRow) void ChatPage::on_publicList_currentRowChanged(int currentRow)
{ {
if (currentRow != -1) { if (currentRow != -1) {
QListWidgetItem *item = ui.publicList->item(currentRow); ChatStyleInfo info = ui.publicStyle->itemData(currentRow,Qt::UserRole).value<ChatStyleInfo>();
ChatStyleInfo info = item->data(Qt::UserRole).value<ChatStyleInfo>();
QString author = info.authorName; QString author = info.authorName;
if (info.authorEmail.isEmpty() == false) { if (info.authorEmail.isEmpty() == false) {
@ -397,14 +476,13 @@ void ChatPage::on_publicList_currentRowChanged(int currentRow)
ui.publicComboBoxVariant->setDisabled(true); ui.publicComboBoxVariant->setDisabled(true);
} }
fillPreview(ui.publicList, ui.publicComboBoxVariant, ui.publicPreview); fillPreview(ui.publicStyle, ui.publicComboBoxVariant, ui.publicPreview);
} }
void ChatPage::on_privateList_currentRowChanged(int currentRow) void ChatPage::on_privateList_currentRowChanged(int currentRow)
{ {
if (currentRow != -1) { if (currentRow != -1) {
QListWidgetItem *item = ui.privateList->item(currentRow); ChatStyleInfo info = ui.privateStyle->itemData(ui.privateStyle->currentIndex(),Qt::UserRole).value<ChatStyleInfo>();
ChatStyleInfo info = item->data(Qt::UserRole).value<ChatStyleInfo>();
QString author = info.authorName; QString author = info.authorName;
if (info.authorEmail.isEmpty() == false) { if (info.authorEmail.isEmpty() == false) {
@ -433,14 +511,13 @@ void ChatPage::on_privateList_currentRowChanged(int currentRow)
ui.privateComboBoxVariant->setDisabled(true); ui.privateComboBoxVariant->setDisabled(true);
} }
fillPreview(ui.privateList, ui.privateComboBoxVariant, ui.privatePreview); fillPreview(ui.privateStyle, ui.privateComboBoxVariant, ui.privatePreview);
} }
void ChatPage::on_historyList_currentRowChanged(int currentRow) void ChatPage::on_historyList_currentRowChanged(int currentRow)
{ {
if (currentRow != -1) { if (currentRow != -1) {
QListWidgetItem *item = ui.historyList->item(currentRow); ChatStyleInfo info = ui.historyStyle->itemData(ui.historyStyle->currentIndex(),Qt::UserRole).value<ChatStyleInfo>();
ChatStyleInfo info = item->data(Qt::UserRole).value<ChatStyleInfo>();
QString author = info.authorName; QString author = info.authorName;
if (info.authorEmail.isEmpty() == false) { if (info.authorEmail.isEmpty() == false) {
@ -469,22 +546,22 @@ void ChatPage::on_historyList_currentRowChanged(int currentRow)
ui.historyComboBoxVariant->setDisabled(true); ui.historyComboBoxVariant->setDisabled(true);
} }
fillPreview(ui.historyList, ui.historyComboBoxVariant, ui.historyPreview); fillPreview(ui.historyStyle, ui.historyComboBoxVariant, ui.historyPreview);
} }
void ChatPage::on_publicComboBoxVariant_currentIndexChanged(int /*index*/) void ChatPage::on_publicComboBoxVariant_currentIndexChanged(int /*index*/)
{ {
fillPreview(ui.publicList, ui.publicComboBoxVariant, ui.publicPreview); fillPreview(ui.publicStyle, ui.publicComboBoxVariant, ui.publicPreview);
} }
void ChatPage::on_privateComboBoxVariant_currentIndexChanged(int /*index*/) void ChatPage::on_privateComboBoxVariant_currentIndexChanged(int /*index*/)
{ {
fillPreview(ui.privateList, ui.privateComboBoxVariant, ui.privatePreview); fillPreview(ui.privateStyle, ui.privateComboBoxVariant, ui.privatePreview);
} }
void ChatPage::on_historyComboBoxVariant_currentIndexChanged(int /*index*/) void ChatPage::on_historyComboBoxVariant_currentIndexChanged(int /*index*/)
{ {
fillPreview(ui.historyList, ui.historyComboBoxVariant, ui.historyPreview); fillPreview(ui.historyStyle, ui.historyComboBoxVariant, ui.historyPreview);
} }
void ChatPage::on_cbSearch_WithoutLimit_toggled(bool checked) void ChatPage::on_cbSearch_WithoutLimit_toggled(bool checked)

View File

@ -35,8 +35,6 @@ class ChatPage : public ConfigPage
/** Default Destructor */ /** Default Destructor */
~ChatPage() {} ~ChatPage() {}
/** Saves the changes on this page */
virtual bool save(QString &errmsg);
/** Loads the settings for this page */ /** Loads the settings for this page */
virtual void load(); virtual void load();
@ -58,10 +56,21 @@ class ChatPage : public ConfigPage
void distantChatComboBoxChanged(int); void distantChatComboBoxChanged(int);
void updateFontsAndEmotes();
void updateChatParams();
void updateChatSearchParams();
void updateDefaultLobbyIdentity() ;
void updateHistoryParams();
void updatePublicStyle() ;
void updatePrivateStyle() ;
void updateHistoryStyle() ;
void updateHistoryStorage();
void updateChatFlags();
void updateChatLobbyFlags();
private: private:
void setPreviewMessages(QString &stylePath, QString styleVariant, QTextBrowser *textBrowser); void setPreviewMessages(QString &stylePath, QString styleVariant, QTextBrowser *textBrowser);
void fillPreview(QListWidget *listWidget, QComboBox *comboBox, QTextBrowser *textBrowser); void fillPreview(QComboBox *listWidget, QComboBox *comboBox, QTextBrowser *textBrowser);
QFont fontTempChat; QFont fontTempChat;

View File

@ -6,15 +6,15 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>635</width> <width>1216</width>
<height>600</height> <height>1107</height>
</rect> </rect>
</property> </property>
<layout class="QGridLayout"> <layout class="QGridLayout">
<item row="3" column="0"> <item row="3" column="0">
<widget class="QTabWidget" name="tabWidget"> <widget class="QTabWidget" name="tabWidget">
<property name="currentIndex"> <property name="currentIndex">
<number>0</number> <number>2</number>
</property> </property>
<widget class="QWidget" name="general"> <widget class="QWidget" name="general">
<attribute name="title"> <attribute name="title">
@ -271,6 +271,13 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<widget class="QCheckBox" name="DontSendTyping">
<property name="text">
<string>Do not send typing notifications</string>
</property>
</widget>
</item>
</layout> </layout>
</widget> </widget>
</item> </item>
@ -859,109 +866,75 @@
<enum>QTabWidget::North</enum> <enum>QTabWidget::North</enum>
</property> </property>
<property name="currentIndex"> <property name="currentIndex">
<number>0</number> <number>2</number>
</property> </property>
<widget class="QWidget" name="publicTab"> <widget class="QWidget" name="publicTab">
<attribute name="title"> <attribute name="title">
<string>Group chat</string> <string>Group chat</string>
</attribute> </attribute>
<layout class="QVBoxLayout" name="publicTabVLayout"> <layout class="QVBoxLayout" name="verticalLayout">
<item> <item>
<layout class="QHBoxLayout" name="publicStyleHLayout"> <widget class="QTextBrowser" name="publicPreview">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item> <item>
<layout class="QVBoxLayout" name="publicStyleListVLayout"> <widget class="QLabel" name="label">
<item> <property name="text">
<widget class="QListWidget" name="publicList"> <string>Style:</string>
<property name="sizePolicy"> </property>
<sizepolicy hsizetype="Fixed" vsizetype="Preferred"> </widget>
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>170</width>
<height>16777215</height>
</size>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="publicStyleVarHLayout">
<item>
<widget class="QLabel" name="publicLabelVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Variant</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="publicComboBoxVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item> </item>
<item> <item>
<widget class="QTextBrowser" name="publicPreview"> <widget class="QComboBox" name="publicStyle"/>
</item>
<item>
<widget class="QLabel" name="publicLabelVariant">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Variant:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="publicComboBoxVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch> <horstretch>0</horstretch>
<verstretch>0</verstretch> <verstretch>0</verstretch>
</sizepolicy> </sizepolicy>
</property> </property>
</widget> </widget>
</item> </item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="publicInfoLayout"> <layout class="QHBoxLayout" name="publicInfoLayout">
<item>
<layout class="QVBoxLayout" name="publicLabelLayout">
<property name="sizeConstraint">
<enum>QLayout::SetFixedSize</enum>
</property>
<item>
<widget class="QLabel" name="publicLabelAuthor">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Author:</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="publicLabelDescription">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Description:</string>
</property>
</widget>
</item>
</layout>
</item>
<item> <item>
<layout class="QVBoxLayout" name="publicLayout"> <layout class="QVBoxLayout" name="publicLayout">
<item> <item>
@ -992,6 +965,19 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</item> </item>
</layout> </layout>
@ -1000,103 +986,69 @@
<attribute name="title"> <attribute name="title">
<string>Private chat</string> <string>Private chat</string>
</attribute> </attribute>
<layout class="QVBoxLayout" name="privateTabVLayout"> <layout class="QVBoxLayout" name="verticalLayout_2">
<item> <item>
<layout class="QHBoxLayout" name="privateStyleHLayout"> <widget class="QTextBrowser" name="privatePreview">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item> <item>
<layout class="QVBoxLayout" name="privateStyleListVLayout"> <widget class="QLabel" name="label_2">
<item> <property name="text">
<widget class="QListWidget" name="privateList"> <string>Style:</string>
<property name="sizePolicy"> </property>
<sizepolicy hsizetype="Fixed" vsizetype="Preferred"> </widget>
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>170</width>
<height>16777215</height>
</size>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="privateStyleVarHLayout">
<item>
<widget class="QLabel" name="privateLabelVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Variant</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="privateComboBoxVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item> </item>
<item> <item>
<widget class="QTextBrowser" name="privatePreview"> <widget class="QComboBox" name="privateStyle"/>
</item>
<item>
<widget class="QLabel" name="privateLabelVariant">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Variant:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="privateComboBoxVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch> <horstretch>0</horstretch>
<verstretch>0</verstretch> <verstretch>0</verstretch>
</sizepolicy> </sizepolicy>
</property> </property>
</widget> </widget>
</item> </item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="privateInfoLayout"> <layout class="QHBoxLayout" name="privateInfoLayout">
<item>
<layout class="QVBoxLayout" name="privateLabelLayout">
<property name="sizeConstraint">
<enum>QLayout::SetFixedSize</enum>
</property>
<item>
<widget class="QLabel" name="privateLabelAuthor">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Author:</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="privateLabelDescription">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Description:</string>
</property>
</widget>
</item>
</layout>
</item>
<item> <item>
<layout class="QVBoxLayout" name="privateLayout"> <layout class="QVBoxLayout" name="privateLayout">
<item> <item>
@ -1127,6 +1079,19 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</item> </item>
</layout> </layout>
@ -1135,103 +1100,69 @@
<attribute name="title"> <attribute name="title">
<string>History</string> <string>History</string>
</attribute> </attribute>
<layout class="QVBoxLayout" name="historyTabVLayout"> <layout class="QVBoxLayout" name="verticalLayout_3">
<item> <item>
<layout class="QHBoxLayout" name="historyStyleHLayout"> <widget class="QTextBrowser" name="historyPreview">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item> <item>
<layout class="QVBoxLayout" name="historyStyleListVLayout"> <widget class="QLabel" name="label_3">
<item> <property name="text">
<widget class="QListWidget" name="historyList"> <string>Style:</string>
<property name="sizePolicy"> </property>
<sizepolicy hsizetype="Fixed" vsizetype="Preferred"> </widget>
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>170</width>
<height>16777215</height>
</size>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="historyStyleVarHLayout">
<item>
<widget class="QLabel" name="historyLabelVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Variant</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="historyComboBoxVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item> </item>
<item> <item>
<widget class="QTextBrowser" name="historyPreview"> <widget class="QComboBox" name="historyStyle"/>
</item>
<item>
<widget class="QLabel" name="historyLabelVariant">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Variant:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="historyComboBoxVariant">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch> <horstretch>0</horstretch>
<verstretch>0</verstretch> <verstretch>0</verstretch>
</sizepolicy> </sizepolicy>
</property> </property>
</widget> </widget>
</item> </item>
<item>
<spacer name="horizontalSpacer_6">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="historyInfoLayout"> <layout class="QHBoxLayout" name="historyInfoLayout">
<item>
<layout class="QVBoxLayout" name="historyLabelLayout">
<property name="sizeConstraint">
<enum>QLayout::SetFixedSize</enum>
</property>
<item>
<widget class="QLabel" name="historyLabelAuthor">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Author:</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="historyLabelDescription">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Description:</string>
</property>
</widget>
</item>
</layout>
</item>
<item> <item>
<layout class="QVBoxLayout" name="historyLayout"> <layout class="QVBoxLayout" name="historyLayout">
<item> <item>
@ -1262,6 +1193,19 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<spacer name="horizontalSpacer_5">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</item> </item>
</layout> </layout>

View File

@ -92,13 +92,6 @@ CryptoPage::~CryptoPage()
{ {
} }
/** Saves the changes on this page */
bool
CryptoPage::save(QString &/*errmsg*/)
{
return true;
}
/** Loads the settings for this page */ /** Loads the settings for this page */
void void
CryptoPage::load() CryptoPage::load()

View File

@ -35,8 +35,6 @@ class CryptoPage : public ConfigPage
/** Default Destructor */ /** Default Destructor */
~CryptoPage(); ~CryptoPage();
/** Saves the changes on this page */
virtual bool save(QString &errmsg);
/** Loads the settings for this page */ /** Loads the settings for this page */
virtual QPixmap iconPixmap() const { return QPixmap(":/icons/settings/profile.svg") ; } virtual QPixmap iconPixmap() const { return QPixmap(":/icons/settings/profile.svg") ; }
@ -46,9 +44,9 @@ class CryptoPage : public ConfigPage
private slots: private slots:
virtual void load(); virtual void load();
void copyPublicKey(); void copyPublicKey();
void copyRSLink() ; void copyRSLink() ;
virtual void showEvent ( QShowEvent * event ); virtual void showEvent ( QShowEvent * event );
void profilemanager(); void profilemanager();
bool fileSave(); bool fileSave();
bool fileSaveAs(); bool fileSaveAs();
void showStats(); void showStats();

View File

@ -37,6 +37,11 @@ DirectoriesPage::DirectoriesPage(QWidget * parent, Qt::WindowFlags flags)
connect(ui.partialButton, SIGNAL(clicked( bool ) ), this , SLOT( setPartialsDirectory() ) ); connect(ui.partialButton, SIGNAL(clicked( bool ) ), this , SLOT( setPartialsDirectory() ) );
connect(ui.editShareButton, SIGNAL(clicked()), this, SLOT(editDirectories())); connect(ui.editShareButton, SIGNAL(clicked()), this, SLOT(editDirectories()));
connect(ui.autoCheckDirectories_CB, SIGNAL(clicked(bool)), this, SLOT(toggleAutoCheckDirectories(bool))); connect(ui.autoCheckDirectories_CB, SIGNAL(clicked(bool)), this, SLOT(toggleAutoCheckDirectories(bool)));
connect(ui.autoCheckDirectories_CB, SIGNAL(toggled(bool)), this,SLOT(updateAutoCheckDirectories())) ;
connect(ui.autoCheckDirectoriesDelay_SB,SIGNAL(valueChanged(int)),this,SLOT(updateAutoScanDirectoriesPeriod())) ;
connect(ui.shareDownloadDirectoryCB, SIGNAL(toggled(bool)), this,SLOT(updateShareDownloadDirectory())) ;
connect(ui.followSymLinks_CB, SIGNAL(toggled(bool)), this,SLOT(updateFollowSymLinks())) ;
} }
void DirectoriesPage::toggleAutoCheckDirectories(bool b) void DirectoriesPage::toggleAutoCheckDirectories(bool b)
@ -49,29 +54,10 @@ void DirectoriesPage::editDirectories()
ShareManager::showYourself() ; ShareManager::showYourself() ;
} }
/** Saves the changes on this page */ void DirectoriesPage::updateAutoCheckDirectories() { rsFiles->setWatchEnabled(ui.autoCheckDirectories_CB->isChecked()) ; }
bool DirectoriesPage::save(QString &/*errmsg*/) void DirectoriesPage::updateAutoScanDirectoriesPeriod() { rsFiles->setWatchPeriod(ui.autoCheckDirectoriesDelay_SB->value()); }
{ void DirectoriesPage::updateShareDownloadDirectory() { rsFiles->shareDownloadDirectory(ui.shareDownloadDirectoryCB->isChecked());}
std::string dir = ui.incomingDir->text().toUtf8().constData(); void DirectoriesPage::updateFollowSymLinks() { rsFiles->setFollowSymLinks(ui.followSymLinks_CB->isChecked()); }
if (!dir.empty())
{
rsFiles->setDownloadDirectory(dir);
}
dir = ui.partialsDir->text().toUtf8().constData();
if (!dir.empty())
{
rsFiles->setPartialsDirectory(dir);
}
rsFiles->setWatchEnabled(ui.autoCheckDirectories_CB->isChecked()) ;
rsFiles->setWatchPeriod(ui.autoCheckDirectoriesDelay_SB->value());
rsFiles->shareDownloadDirectory(ui.shareDownloadDirectoryCB->isChecked());
rsFiles->setFollowSymLinks(ui.followSymLinks_CB->isChecked());
return true;
}
/** Loads the settings for this page */ /** Loads the settings for this page */
void DirectoriesPage::load() void DirectoriesPage::load()
@ -95,6 +81,10 @@ void DirectoriesPage::setIncomingDirectory()
} }
ui.incomingDir->setText(qdir); ui.incomingDir->setText(qdir);
std::string dir = ui.incomingDir->text().toUtf8().constData();
if(!dir.empty())
rsFiles->setDownloadDirectory(dir);
} }
void DirectoriesPage::setPartialsDirectory() void DirectoriesPage::setPartialsDirectory()
@ -105,4 +95,7 @@ void DirectoriesPage::setPartialsDirectory()
} }
ui.partialsDir->setText(qdir); ui.partialsDir->setText(qdir);
std::string dir = ui.partialsDir->text().toUtf8().constData();
if (!dir.empty())
rsFiles->setPartialsDirectory(dir);
} }

View File

@ -32,8 +32,6 @@ class DirectoriesPage: public ConfigPage
public: public:
DirectoriesPage(QWidget * parent = 0, Qt::WindowFlags flags = 0); DirectoriesPage(QWidget * parent = 0, Qt::WindowFlags flags = 0);
/** Saves the changes on this page */
virtual bool save(QString &errmsg);
/** Loads the settings for this page */ /** Loads the settings for this page */
virtual void load(); virtual void load();
@ -47,6 +45,11 @@ private slots:
void setPartialsDirectory(); void setPartialsDirectory();
void toggleAutoCheckDirectories(bool); void toggleAutoCheckDirectories(bool);
void updateAutoCheckDirectories() ;
void updateAutoScanDirectoriesPeriod() ;
void updateShareDownloadDirectory() ;
void updateFollowSymLinks() ;
private: private:
Ui::DirectoriesPage ui; Ui::DirectoriesPage ui;
}; };

View File

@ -131,38 +131,6 @@ FileAssociationsPage::~FileAssociationsPage()
{ {
} }
//============================================================================
bool
FileAssociationsPage::save (QString &/*errmsg*/)
{
// RshareSettings settings;
// settings.beginGroup("FileAssotiations");
// settings.setValue(".s01", "s01 test");
// settings.setValue(".s02", "s02 test");
// settings.setValue(".s03", "s03 test");
// settings.setValue(".s04", "s04 test");
// QMap<QString, QString>::const_iterator ati = ations.constBegin();
// while (ati != ations.constEnd())
// {
// settings.setValue( ati.key(), ati.value() );
// qDebug() << " - " << ati.key() << ati.value() << "\n" ;
// ++ati;
// }
//
// settings.endGroup();
// settings.sync();
// delete settings;
/* */
return true;
}
//============================================================================
void void
FileAssociationsPage::load() FileAssociationsPage::load()
{ {

View File

@ -52,7 +52,6 @@ public:
virtual ~FileAssociationsPage(); virtual ~FileAssociationsPage();
virtual void load(); virtual void load();
virtual bool save (QString &errmsg);
virtual QPixmap iconPixmap() const { return QPixmap(":/images/filetype-association.png") ; } virtual QPixmap iconPixmap() const { return QPixmap(":/images/filetype-association.png") ; }
virtual QString pageName() const { return tr("Associations") ; } virtual QString pageName() const { return tr("Associations") ; }

View File

@ -30,24 +30,23 @@ ForumPage::ForumPage(QWidget * parent, Qt::WindowFlags flags)
/* Initialize GroupFrameSettingsWidget */ /* Initialize GroupFrameSettingsWidget */
ui.groupFrameSettingsWidget->setOpenAllInNewTabText(tr("Open each forum in a new tab")); ui.groupFrameSettingsWidget->setOpenAllInNewTabText(tr("Open each forum in a new tab"));
connect(ui.setMsgToReadOnActivate,SIGNAL(toggled(bool)),this,SLOT(updateMsgReadOnActivate())) ;
connect(ui.expandNewMessages , SIGNAL(toggled(bool)), this, SLOT( updateExpandNewMessages()));
connect(ui.loadEmbeddedImages , SIGNAL(toggled(bool)), this, SLOT(updateLoadEmbeddedImage() ));
connect(ui.loadEmoticons , SIGNAL(toggled(bool)), this, SLOT( updateLoadEmoticons() ));
ui.groupFrameSettingsWidget->setType(GroupFrameSettings::Forum) ;
} }
ForumPage::~ForumPage() ForumPage::~ForumPage()
{ {
} }
/** Saves the changes on this page */ void ForumPage::updateMsgReadOnActivate() { Settings->setForumMsgSetToReadOnActivate(ui.setMsgToReadOnActivate->isChecked()); }
bool ForumPage::save(QString &/*errmsg*/) void ForumPage::updateExpandNewMessages() { Settings->setForumExpandNewMessages( ui.expandNewMessages ->isChecked());}
{ void ForumPage::updateLoadEmbeddedImages() { Settings->setForumLoadEmbeddedImages( ui.loadEmbeddedImages ->isChecked());}
Settings->setForumMsgSetToReadOnActivate(ui.setMsgToReadOnActivate->isChecked()); void ForumPage::updateLoadEmoticons() { Settings->setForumLoadEmoticons( ui.loadEmoticons ->isChecked()); }
Settings->setForumExpandNewMessages(ui.expandNewMessages->isChecked());
Settings->setForumLoadEmbeddedImages(ui.loadEmbeddedImages->isChecked());
Settings->setForumLoadEmoticons(ui.loadEmoticons->isChecked());
ui.groupFrameSettingsWidget->saveSettings(GroupFrameSettings::Forum);
return true;
}
/** Loads the settings for this page */ /** Loads the settings for this page */
void ForumPage::load() void ForumPage::load()

View File

@ -33,8 +33,6 @@ public:
ForumPage(QWidget * parent = 0, Qt::WindowFlags flags = 0); ForumPage(QWidget * parent = 0, Qt::WindowFlags flags = 0);
~ForumPage(); ~ForumPage();
/** Saves the changes on this page */
virtual bool save(QString &errmsg);
/** Loads the settings for this page */ /** Loads the settings for this page */
virtual void load(); virtual void load();
@ -42,6 +40,12 @@ public:
virtual QString pageName() const { return tr("Forum") ; } virtual QString pageName() const { return tr("Forum") ; }
virtual QString helpText() const { return ""; } virtual QString helpText() const { return ""; }
protected slots:
void updateMsgReadOnActivate();
void updateExpandNewMessages();
void updateLoadEmbeddedImages();
void updateLoadEmoticons();
private: private:
Ui::ForumPage ui; Ui::ForumPage ui;
}; };

View File

@ -38,8 +38,6 @@ GeneralPage::GeneralPage(QWidget * parent, Qt::WindowFlags flags) :
/* Invoke the Qt Designer generated object setup routine */ /* Invoke the Qt Designer generated object setup routine */
ui.setupUi(this); ui.setupUi(this);
/* Connect signals */
connect(ui.runStartWizard_PB,SIGNAL(clicked()), this,SLOT(runStartWizard())) ;
/* Hide platform specific features */ /* Hide platform specific features */
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@ -82,6 +80,19 @@ GeneralPage::GeneralPage(QWidget * parent, Qt::WindowFlags flags) :
ui.autoLogin->setEnabled(false); ui.autoLogin->setEnabled(false);
ui.autoLogin->setToolTip(tr("Your RetroShare build has auto-login disabled.")); ui.autoLogin->setToolTip(tr("Your RetroShare build has auto-login disabled."));
#endif // RS_AUTOLOGIN #endif // RS_AUTOLOGIN
/* Connect signals */
connect(ui.useLocalServer, SIGNAL(toggled(bool)), this,SLOT(updateUseLocalServer())) ;
connect(ui.idleSpinBox, SIGNAL(valueChanged(int)), this,SLOT(updateMaxTimeBeforeIdle())) ;
connect(ui.checkStartMinimized, SIGNAL(toggled(bool)), this,SLOT(updateStartMinimized())) ;
connect(ui.checkQuit, SIGNAL(toggled(bool)), this,SLOT(updateDoQuit())) ;
connect(ui.checkCloseToTray, SIGNAL(toggled(bool)), this,SLOT(updateCloseToTray())) ;
connect(ui.autoLogin, SIGNAL(toggled(bool)), this,SLOT(updateAutoLogin())) ;
connect(ui.chkRunRetroshareAtSystemStartup, SIGNAL(toggled(bool)), this,SLOT(updateRunRSOnBoot())) ;
connect(ui.chkRunRetroshareAtSystemStartupMinimized, SIGNAL(toggled(bool)), this,SLOT(updateRunRSOnBoot())) ;
connect(ui.runStartWizard_PB, SIGNAL(clicked()), this,SLOT(runStartWizard())) ;
connect(ui.checkAdvanced, SIGNAL(toggled(bool)), this,SLOT(updateAdvancedMode())) ;
connect(ui.registerRetroShareProtocol, SIGNAL(toggled(bool)), this,SLOT(updateRegisterRSProtocol())) ;
} }
/** Destructor */ /** Destructor */
@ -93,48 +104,48 @@ void GeneralPage::runStartWizard()
QuickStartWizard(this).exec(); QuickStartWizard(this).exec();
} }
/** Saves the changes on this page */ void GeneralPage::updateAdvancedMode()
bool GeneralPage::save(QString &/*errmsg*/) {
if (ui.checkAdvanced->isChecked())
{
std::string opt("YES");
rsConfig->setConfigurationOption(RS_CONFIG_ADVANCED, opt);
}
else
{
std::string opt("NO");
rsConfig->setConfigurationOption(RS_CONFIG_ADVANCED, opt);
}
}
void GeneralPage::updateUseLocalServer() { Settings->setUseLocalServer(ui.useLocalServer->isChecked()); }
void GeneralPage::updateMaxTimeBeforeIdle(){ Settings->setMaxTimeBeforeIdle(ui.idleSpinBox->value()); }
void GeneralPage::updateStartMinimized() { Settings->setStartMinimized(ui.checkStartMinimized->isChecked()); }
void GeneralPage::updateDoQuit() { Settings->setValue("doQuit", ui.checkQuit->isChecked()); }
void GeneralPage::updateCloseToTray() { Settings->setCloseToTray(ui.checkCloseToTray->isChecked()); }
void GeneralPage::updateAutoLogin() { RsInit::setAutoLogin(ui.autoLogin->isChecked());}
void GeneralPage::updateRunRSOnBoot()
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#ifndef QT_DEBUG #ifndef QT_DEBUG
Settings->setRunRetroshareOnBoot(ui.chkRunRetroshareAtSystemStartup->isChecked(), ui.chkRunRetroshareAtSystemStartupMinimized->isChecked()); Settings->setRunRetroshareOnBoot(ui.chkRunRetroshareAtSystemStartup->isChecked(), ui.chkRunRetroshareAtSystemStartupMinimized->isChecked());
#endif #endif
#endif #endif
}
Settings->setStartMinimized(ui.checkStartMinimized->isChecked()); void GeneralPage::updateRegisterRSProtocol()
{
if (ui.checkAdvanced->isChecked()) if (ui.registerRetroShareProtocol->isChecked() != Settings->getRetroShareProtocol())
{ {
std::string opt("YES"); QString error ="";
rsConfig->setConfigurationOption(RS_CONFIG_ADVANCED, opt); if (Settings->setRetroShareProtocol(ui.registerRetroShareProtocol->isChecked(), error) == false) {
} if (ui.registerRetroShareProtocol->isChecked()) {
else QMessageBox::critical(this, tr("Error"), tr("Could not add retroshare:// as protocol.").append("\n").append(error));
{ } else {
std::string opt("NO"); QMessageBox::critical(this, tr("Error"), tr("Could not remove retroshare:// protocol.").append("\n").append(error));
rsConfig->setConfigurationOption(RS_CONFIG_ADVANCED, opt); }
} }
}
Settings->setValue("doQuit", ui.checkQuit->isChecked());
Settings->setCloseToTray(ui.checkCloseToTray->isChecked());
RsInit::setAutoLogin(ui.autoLogin->isChecked());
if (ui.registerRetroShareProtocol->isChecked() != Settings->getRetroShareProtocol()) {
QString error ="";
if (Settings->setRetroShareProtocol(ui.registerRetroShareProtocol->isChecked(), error) == false) {
if (ui.registerRetroShareProtocol->isChecked()) {
QMessageBox::critical(this, tr("Error"), tr("Could not add retroshare:// as protocol.").append("\n").append(error));
} else {
QMessageBox::critical(this, tr("Error"), tr("Could not remove retroshare:// protocol.").append("\n").append(error));
}
}
}
Settings->setUseLocalServer(ui.useLocalServer->isChecked());
Settings->setMaxTimeBeforeIdle(ui.idleSpinBox->value());
return true;
} }
/** Loads the settings for this page */ /** Loads the settings for this page */

View File

@ -28,28 +28,37 @@
class GeneralPage : public ConfigPage class GeneralPage : public ConfigPage
{ {
Q_OBJECT Q_OBJECT
public: public:
/** Default Constructor */ /** Default Constructor */
GeneralPage(QWidget * parent = 0, Qt::WindowFlags flags = 0); GeneralPage(QWidget * parent = 0, Qt::WindowFlags flags = 0);
/** Default Destructor */ /** Default Destructor */
~GeneralPage(); ~GeneralPage();
/** Saves the changes on this page */ /** Saves the changes on this page */
virtual bool save(QString &errmsg); /** Loads the settings for this page */
/** Loads the settings for this page */ virtual void load();
virtual void load();
virtual QPixmap iconPixmap() const { return QPixmap(":/icons/settings/general.svg") ; } virtual QPixmap iconPixmap() const { return QPixmap(":/icons/settings/general.svg") ; }
virtual QString pageName() const { return tr("General") ; } virtual QString pageName() const { return tr("General") ; }
virtual QString helpText() const { return ""; } virtual QString helpText() const { return ""; }
public slots:
void runStartWizard() ;
void updateAdvancedMode();
void updateUseLocalServer() ;
void updateMaxTimeBeforeIdle();
void updateStartMinimized() ;
void updateDoQuit() ;
void updateCloseToTray() ;
void updateAutoLogin() ;
void updateRunRSOnBoot() ;
void updateRegisterRSProtocol();
public slots:
void runStartWizard() ;
private: private:
/** Qt Designer generated object */ /** Qt Designer generated object */
Ui::GeneralPage ui; Ui::GeneralPage ui;
}; };
#endif #endif

View File

@ -1,3 +1,6 @@
#include <iostream>
#include "gui/notifyqt.h"
#include "GroupFrameSettingsWidget.h" #include "GroupFrameSettingsWidget.h"
#include "ui_GroupFrameSettingsWidget.h" #include "ui_GroupFrameSettingsWidget.h"
@ -7,7 +10,11 @@ GroupFrameSettingsWidget::GroupFrameSettingsWidget(QWidget *parent) :
{ {
ui->setupUi(this); ui->setupUi(this);
mType = GroupFrameSettings::Nothing ;
mEnable = true; mEnable = true;
connect(ui->openAllInNewTabCheckBox, SIGNAL(toggled(bool)),this,SLOT(saveSettings())) ;
connect(ui->hideTabBarWithOneTabCheckBox,SIGNAL(toggled(bool)),this,SLOT(saveSettings())) ;
} }
GroupFrameSettingsWidget::~GroupFrameSettingsWidget() GroupFrameSettingsWidget::~GroupFrameSettingsWidget()
@ -22,6 +29,8 @@ void GroupFrameSettingsWidget::setOpenAllInNewTabText(const QString &text)
void GroupFrameSettingsWidget::loadSettings(GroupFrameSettings::Type type) void GroupFrameSettingsWidget::loadSettings(GroupFrameSettings::Type type)
{ {
mType = type ;
GroupFrameSettings groupFrameSettings; GroupFrameSettings groupFrameSettings;
if (Settings->getGroupFrameSettings(type, groupFrameSettings)) { if (Settings->getGroupFrameSettings(type, groupFrameSettings)) {
ui->openAllInNewTabCheckBox->setChecked(groupFrameSettings.mOpenAllInNewTab); ui->openAllInNewTabCheckBox->setChecked(groupFrameSettings.mOpenAllInNewTab);
@ -32,13 +41,22 @@ void GroupFrameSettingsWidget::loadSettings(GroupFrameSettings::Type type)
} }
} }
void GroupFrameSettingsWidget::saveSettings(GroupFrameSettings::Type type) void GroupFrameSettingsWidget::saveSettings()
{ {
if (mEnable) { if(mType == GroupFrameSettings::Nothing)
{
std::cerr << "(EE) No type initialized for groupFrameSettings. This is a bug." << std::endl;
return;
}
if (mEnable)
{
GroupFrameSettings groupFrameSettings; GroupFrameSettings groupFrameSettings;
groupFrameSettings.mOpenAllInNewTab = ui->openAllInNewTabCheckBox->isChecked(); groupFrameSettings.mOpenAllInNewTab = ui->openAllInNewTabCheckBox->isChecked();
groupFrameSettings.mHideTabBarWithOneTab = ui->hideTabBarWithOneTabCheckBox->isChecked(); groupFrameSettings.mHideTabBarWithOneTab = ui->hideTabBarWithOneTabCheckBox->isChecked();
Settings->setGroupFrameSettings(type, groupFrameSettings); Settings->setGroupFrameSettings(mType, groupFrameSettings);
NotifyQt::getInstance()->notifySettingsChanged();
} }
} }

View File

@ -20,11 +20,15 @@ public:
void setOpenAllInNewTabText(const QString &text); void setOpenAllInNewTabText(const QString &text);
void loadSettings(GroupFrameSettings::Type type); void loadSettings(GroupFrameSettings::Type type);
void saveSettings(GroupFrameSettings::Type type);
void setType(GroupFrameSettings::Type type) { mType = type ; }
protected slots:
void saveSettings();
private: private:
bool mEnable; bool mEnable;
Ui::GroupFrameSettingsWidget *ui; Ui::GroupFrameSettingsWidget *ui;
GroupFrameSettings::Type mType ;
}; };
#endif // GROUPFRAMESETTINGSWIDGET_H #endif // GROUPFRAMESETTINGSWIDGET_H

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