code
stringlengths
1
2.06M
language
stringclasses
1 value
#include <string> #include <PopupServerUI.hpp> struct MaquiServer : public Popup::ServerUI { MaquiServer(const std::string & p_rcpath = ""); virtual std::string getResourceDir(); virtual std::string getDefaultAvatar(); virtual void onClientConnected(__unused__ const Popup::User & p_client) {} virtual void onClientDisconnected(__unused__ const Popup::User & p_client) {} virtual void onDestroy() {} private: std::string rcpath; };
C++
#include <stdlib.h> #include <iostream> #include "PopupServer.hpp" #include <PopupSqlite3Database.hpp> using namespace std; using namespace Popup; using namespace PopupUtils; int main(int argc, char *argv[]) { int port = 2001; int nbMaxConnections = 512; MaquiServer _svrui("./popup_svr/rc"); PopupSqlite3Database _dbmgr("./popup_svr/db/popup.sqlite"); if (argc > 1) { info("Server port is %s", argv[1]); port = atoi(argv[1]); } if (argc > 2) { info("Max nb connections allowed is %s", argv[2]); nbMaxConnections = atoi(argv[2]); } Server *_svr = Server::newServer(port, nbMaxConnections, &_dbmgr, &_svrui); if (_svr != 0) { _svr->run(); } info("Server exited"); return 0; }
C++
#include <stdlib.h> #include <string> #include <string.h> #include <vector> #include <sstream> #include <iostream> #include <errno.h> #include "PopupServer.hpp" #include "PopupOSAL.hpp" #include "msg/PopupMessages.hpp" using namespace std; using namespace Popup; using namespace PopupUtils; //============================================================================= // Implementation of PopupServer static instantiation method //============================================================================= Server *Server::newServer(unsigned short p_port, unsigned short p_maxNbConnections, DatabaseUI *p_database, ServerUI *p_serverUI) { return ServerImpl::createInstance(p_port, p_maxNbConnections, p_database, p_serverUI); } //============================================================================= // Construction/Destruction //============================================================================= ServerImpl *ServerImpl::instance = 0; ServerImpl::ServerImpl(unsigned short p_port, unsigned short p_maxNbConnections, DatabaseUI *p_database, ServerUI *p_serverUI) : database(p_database), ui(p_serverUI), exit(false), rsahelper() { string _errMsg; serverSocket = PopupUtils::Socket::newServerSocket(p_port, p_maxNbConnections, &_errMsg); if (serverSocket == 0) { error(_errMsg.c_str()); } // Get all users from database if (!p_database->getAllUsers(loginsMap)) { error("Ooops! Failed to retrieve users list from database"); } } //--------------------------------------------------------- ServerImpl::~ServerImpl() { instance = 0; } //--------------------------------------------------------- ServerImpl *ServerImpl::createInstance(unsigned short p_port, unsigned short p_maxNbConnections, DatabaseUI *p_database, ServerUI *p_serverUI) { if (instance != 0) { error("Cannot create a new server. An existing one is running"); return 0; } else { instance = new ServerImpl(p_port, p_maxNbConnections, p_database, p_serverUI); if (instance->serverSocket != 0) { #ifndef WIN32 ::signal(SIGTERM, ServerImpl::signalHandler); ::signal(SIGINT, ServerImpl::signalHandler); ::signal(SIGSTOP, ServerImpl::signalHandler); ::signal(SIGPIPE, SIG_IGN); #endif return instance; } else { return 0; } } } //--------------------------------------------------------- ServerImpl *ServerImpl::getInstance() { if (instance == 0) { error("No instance of the server is currently running!"); return 0; } else { return instance; } } //--------------------------------------------------------- void ServerImpl::signalHandler(int p_sig) { trace("Received signal %d\n", p_sig); if (instance != 0) { instance->kill(); instance->closeAllConnections(); } ::exit(EXIT_FAILURE); } //--------------------------------------------------------- void ServerImpl::kill() { this->exit = true; } //============================================================================= // Connections management //============================================================================= void ServerImpl::run() { fd_set _readfds; fd_set _errfds; Sockets::iterator _itsock; Sessions::iterator _itsession; struct timeval _tv; int _selectRc = 0; int _nfds = 0; // This function is dedicated to listen function info("Entering main loop..."); // Indefinitely read... while (!exit) { // Setup sockets file descriptors set FD_ZERO(&_readfds); FD_ZERO(&_errfds); // Add accept socket _nfds = serverSocket->fd(); FD_SET(_nfds, &_readfds); _itsock = sockets.begin(); while (_itsock != sockets.end()) { if (_itsock->second->disconnect) { deleteSession(_itsock->second); sockets.erase(_itsock++); } else { FD_SET(_itsock->first, &_readfds); FD_SET(_itsock->first, &_errfds); // We need to save the highest socket value we want to poll if (_itsock->first > _nfds) _nfds = _itsock->first; ++_itsock; } } _tv.tv_sec = 0; _tv.tv_usec = 5000; _selectRc = select(_nfds + 1, &_readfds, 0, &_errfds, &_tv); // Error if (_selectRc == -1) { error("select() : %s", strerror(errno)); } // Success else if (_selectRc > 0) { // Handle activity for each selected session for (_itsock = sockets.begin(); _itsock != sockets.end(); _itsock++) { // Process data on the selected socket if (FD_ISSET(_itsock->first, &_readfds)) { if (!processActivity(_itsock->second)) { // Close session/socket in case we failed to manage activity _itsock->second->disconnect = true; } } // Process errors: close session/socket! else if (FD_ISSET(_itsock->first, &_errfds)) { _itsock->second->disconnect = true; } } // New clients to accept? if (FD_ISSET(serverSocket->fd(), &_readfds)) { acceptNewClient(); } } // Timeout else {} } info("Exiting main loop..."); closeAllConnections(); } void ServerImpl::acceptNewClient() { string _errMsg; PopupUtils::Socket *_s = serverSocket->accept(&_errMsg); if (_s != 0) { trace("New connection!"); _s->enableKeepAlive(true, 10); ClientSession *_session = new ClientSession(_s, &rsahelper); sockets[_s->fd()] = _session; } else { error(_errMsg.c_str()); } } bool ServerImpl::processActivity(ClientSession *p_session) { bool _closeConnection = false; Message *_message = 0; RawMessage *_fullMessage = 0; unsigned int _fullMessageSize = 0; if (p_session->networker.receive(&_message, &_fullMessage, &_fullMessageSize)) { switch (_message->header.type) { case POPUP_MSG_TYPE_RSA_PUBLIC_KEY: { trace("Received client RSA public key"); RsaPublicKeyMsg remotekey(_message); if (remotekey.isValid()) { p_session->sslContext.setRemoteRSApublicKey(remotekey.getKey(), remotekey.getSize()); trace("Sending my RSA public key"); RsaPublicKeyMsg localkey(&p_session->sslContext); p_session->networker.send(&localkey); } else { error( "Invalid RSA key message. Client rejected!"); _closeConnection = true; } break; } case POPUP_MSG_TYPE_BLOWFISH_KEY: { trace("Received blowfish key"); BlowfishKeyMsg blowfishKey(_message); if (blowfishKey.isValid()) { p_session->sslContext.setRemoteBlowfishKey(blowfishKey.getKey()); trace("Handshake succeeded!"); } break; } case POPUP_MSG_TYPE_LOGIN: { trace("Received login message"); LoginMsg loginMsg(_message); ConnectionEcode _dbrc = POPUP_CONNECTION_ERR_UNKNOWN; string errorMsg = "Success!"; if (loginMsg.isValid()) { // Search for corresponding user in our map UserLoginMap::iterator _it = loginsMap.find(loginMsg.getLogin()); // Login creation request --------------------------- if (loginMsg.isCreateRequest()) { // Too bad! It already exists! if (_it != loginsMap.end()) { _dbrc = POPUP_CONNECTION_ERR_LOGIN_ALREADY_EXISTS; } // OK to create! else { trace("Creating new client: %s", loginMsg.getLogin().c_str()); _dbrc = database->newUser(loginMsg.getLogin(), loginMsg.getPassword(), loginMsg.getLogin(), ui->getDefaultAvatar(), &p_session->user, errorMsg); if (_dbrc == POPUP_CONNECTION_SUCCESS) { // Add user into all users list loginsMap[loginMsg.getLogin()] = p_session->user; } else { error("Creation failed"); } } } // Standard connection try ------------------------ else { // User not found! if (_it == loginsMap.end()) { _dbrc = POPUP_CONNECTION_ERR_UNKNOWN_USER; } // User found! Validate password! else if (database->authenticate(loginMsg.getLogin(), loginMsg.getPassword(), errorMsg)) { trace("Authentication success"); _dbrc = POPUP_CONNECTION_SUCCESS; p_session->user = _it->second; } else { _dbrc = POPUP_CONNECTION_ERR_INVALID_PASSWORD; trace("Authentication failed"); } } } if (_dbrc != POPUP_CONNECTION_SUCCESS) { trace("Sending NACK to client %s", loginMsg.getLogin().c_str()); ConnectionAck _ack(_dbrc, errorMsg); p_session->networker.send(&_ack); } else { bool alreadyConnected = false; // Make sure user is not already connected alreadyConnected = (sessions.find(p_session->user->getID()) != sessions.end()); if (alreadyConnected) { error("Client %s already connected!", loginMsg.getLogin().c_str()); ConnectionAck _ack(POPUP_CONNECTION_ERR_USER_ALREADY_CONNECTED, "Strange... You are already connected!!"); p_session->networker.send(&_ack); } // OK!! else { User *_user = p_session->user; _user->setAlive(true); // Allocate a new session number for this user short _rand; PopupUtils::randomString((char*)&_rand, sizeof(unsigned short)); p_session->id = (_rand << 16) | _user->getID(); info("Client %s connected.", loginMsg.getLogin().c_str()); ConnectionAck _ack(p_session->id, *_user); p_session->networker.send(&_ack); ui->onClientConnected(*_user); // Notify all users about this new client connection UserUpdateMsg _newUserUpdateMessage(*_user); broadcastMessage(&_newUserUpdateMessage); // Send user statistics string _errMsg; StatisticsUpdateMsg _statsUpdateMessage(_user->getID()); if (database->getUserStatitics(_user->getID(), _statsUpdateMessage.statistics(), _errMsg)) { broadcastMessage(&_statsUpdateMessage); } // Ok! Register session sessions[_user->getID()] = p_session; p_session->registered = true; // Send list of all user to this new client sendAllUsersList(p_session); } } break; } case POPUP_MSG_TYPE_MESSAGE: { UserMessageWrapper msg(_message); sendMessage(_fullMessage, _fullMessageSize, msg.targets); break; } case POPUP_MSG_TYPE_ATTACHMENT: { AttachmentMsg msg(_message); sendMessage(_fullMessage, _fullMessageSize, msg.getTargets()); break; } case POPUP_MSG_TYPE_USER_UPDATE: { ClientSession *_session = p_session; string _errMsg; UserUpdateMsg _msg(_message, ui->getResourceDir()); if ((_msg.getUpdateMask() & POPUP_USER_FIELD_NICKNAME) && database->updateNickname(p_session->user, _msg.getNickname(), _errMsg)) { p_session->user->setNickname(_msg.getNickname()); // Reset session because we want the notification to be sent // to concerned user as well _session = 0; } if ((_msg.getUpdateMask() & POPUP_USER_FIELD_AVATAR) && database->updateAvatar(p_session->user, _msg.getAvatar(), _errMsg)) { p_session->user->setAvatar(_msg.getAvatar()); // Reset session because we want the notification to be sent // to concerned user as well _session = 0; } if (_msg.getUpdateMask() & POPUP_USER_FIELD_MODE) { p_session->user->setMode(_msg.getMode()); } if (_msg.getUpdateMask() & POPUP_USER_FIELD_HEALTH) { p_session->user->setAlive(_msg.isAlive()); } broadcastMessage(_fullMessage, _fullMessageSize, _session); break; } case POPUP_MSG_TYPE_RATE_MESSAGE: { RateUserMessageWrapper _rate(_message); // Forward message to other users sendMessage(_fullMessage, _fullMessageSize, _rate.targets); // Update database string _errMsg; DatabaseUI::StatisticItemUpdateResult _updateResult; if (database->updateUserRates(_rate.msgSenderID, _rate.rateItem, /*(_rate.isUndo? DatabaseUI::ITEM_UPDATE_DECREMENT : DatabaseUI::ITEM_UPDATE_INCREMENT),*/ _updateResult, _errMsg)) { // Notify everybody about this statistic update StatisticsUpdateMsg _statsUpdateMsg(_rate.msgSenderID); _statsUpdateMsg.statistics().set(_rate.rateItem, _updateResult.newItemValue, _updateResult.isNewRecord); broadcastMessage(&_statsUpdateMsg); // If record is a new one, and that recordman changed, tell // about the previous recordman who had been defeated if (_updateResult.isNewRecord && (_updateResult.previousRecordman != 0) && (_updateResult.previousRecordman != _rate.msgSenderID)) { StatisticsUpdateMsg _recordLostMsg(_updateResult.previousRecordman); _recordLostMsg.statistics().set(_rate.rateItem, _updateResult.previousRecordValue, false); broadcastMessage(&_recordLostMsg); } } break; } case POPUP_MSG_TYPE_CANVASS_SUBMIT: { CanvassSubmitMsg _msg(_message); sendMessage(_fullMessage, _fullMessageSize, _msg.targets); break; } case POPUP_MSG_TYPE_CANVASS_VOTE: { CanvassVoteMsg _vote(_message); sendMessage(_fullMessage, _fullMessageSize, _vote.targets); break; } case POPUP_MSG_TYPE_INVITATION: { ThreadInvitationMsg msg(_message); sendMessage(_fullMessage, _fullMessageSize, msg.cc); sendMessage(_fullMessage, _fullMessageSize, msg.invitedUsers); break; } case POPUP_MSG_TYPE_KEEPALIVE_PROBE: { KeepAliveAck _ack; if (!p_session->networker.send(&_ack)) { p_session->disconnect = true; } break; } case POPUP_MSG_TYPE_KEEPALIVE_ACK: { break; } default: info("Received a message with unexpected ID %d", _message->header.type); break; } if (_message) { delete(_message); } if (_fullMessage) { delete(_fullMessage); } } else { _closeConnection = true; } // Client disconnected return (!_closeConnection); } void ServerImpl::deleteSession(ClientSession *p_session) { if (p_session->registered) { info("Client %s disconnected", p_session->user->getLogin().c_str()); sessions.erase(p_session->user->getID()); p_session->user->alive = false; UserUpdateMsg _deadUserUpdateMessage(*p_session->user, POPUP_USER_FIELD_HEALTH); broadcastMessage(&_deadUserUpdateMessage); } else { trace("Client disconnected"); } delete p_session; } void ServerImpl::broadcastMessage(AbstractMessage *p_message, const ClientSession *p_from) { Sessions::iterator it; for (it = sessions.begin(); it != sessions.end(); it++) { ClientSession *_to = it->second; if ((p_from == 0) || (_to != p_from)) { bool _success = _to->networker.send(p_message); if (!_success) { _to->disconnect = true; } } } } void ServerImpl::broadcastMessage(const RawMessage *p_message, unsigned p_messageSize, const ClientSession *p_from) { Sessions::iterator it; for (it = sessions.begin(); it != sessions.end(); it++) { ClientSession *_to = it->second; if ((p_from == 0) || (_to != p_from)) { bool _success = _to->networker.send(p_message, p_messageSize); if (!_success) { _to->disconnect = true; } } } } void ServerImpl::sendMessage(const RawMessage *p_message, unsigned p_messageSize, const UserList & p_targets) { UserList::const_iterator _itTarget; Sessions::const_iterator _itSession; for (_itTarget = p_targets.begin(); _itTarget != p_targets.end(); _itTarget++) { _itSession = sessions.find(*_itTarget); if (_itSession != sessions.end()) { bool _success = _itSession->second->networker.send(p_message, p_messageSize); if (!_success) { _itSession->second->disconnect = true; } } } } bool ServerImpl::sendAllUsersList(ClientSession *p_session) { UserLoginMap::iterator _it; bool _rc = true; string _errMsg; for (_it = loginsMap.begin(); _rc && (_it != loginsMap.end()); _it++) { // Send user info User *_user= _it->second; if (_user->getID() != p_session->user->getID()) { UserUpdateMsg _newUserUpdateMessage(*_user); _rc = p_session->networker.send(&_newUserUpdateMessage); } if (_rc) { // Send user statistics StatisticsUpdateMsg _statsUpdateMessage(_user->getID()); if (database->getUserStatitics(_user->getID(), _statsUpdateMessage.statistics(), _errMsg)) { _rc = p_session->networker.send(&_statsUpdateMessage); } } if (!_rc) { p_session->disconnect = true; } } return _rc; } void ServerImpl::closeAllConnections() { trace("Closing all connections"); Sessions::iterator _it; for (_it = sessions.begin(); _it != sessions.end(); _it++) { delete _it->second; } sessions.clear(); sockets.clear(); if (serverSocket != 0) { serverSocket->close(); } }
C++
/* * PopupUtilities.cpp * * Created on: Mar 28, 2012 * Author: guillou */ #include <stdio.h> #include <string.h> #include "PopupUtilities.hpp" using namespace Popup; void Utils::dumpBuffer(const void *p_buffer, size_t p_size) { for (size_t i = 0; i < p_size; i++) { fprintf(stdout, "%02x", ((const unsigned char*) p_buffer)[i]); if (((i+1) % 32) == 0) { fprintf(stdout, "\n"); } } fprintf(stdout, "\n"); }
C++
#ifndef __POPUP_SSL_HPP__ #define __POPUP_SSL_HPP__ #include <openssl/rsa.h> #include <openssl/blowfish.h> #include <PopupLoggerUI.hpp> namespace Popup { enum SslContextType { CLIENT_CONTEXT, SERVER_CONTEXT }; typedef unsigned char BlowfishKey[128]; struct BlowfishHelper { BlowfishHelper(SslContextType ctxt); ~BlowfishHelper() {} void setKey(const BlowfishKey & p_key); const BlowfishKey & getKey() const; bool encrypt(unsigned char *p_buffOut, const unsigned char *p_buffIn, size_t p_size) const; bool decrypt(unsigned char *p_buffOut, const unsigned char *p_buffIn, size_t p_size) const; private: BF_KEY key; BlowfishKey seed; }; struct RSAHelper { private: enum RSAHelperMode { RSA_MASTER, RSA_SLAVE }; RSA *key; BIGNUM *num; enum RSAHelperMode mode; unsigned char *rawpubkey; size_t rawpubkeySize; public: //! Creates a new RSA context (private/public) RSAHelper(); //! Creates a new RSA context (public only) RSAHelper(const unsigned char *p_publicKey, size_t p_keySize); ~RSAHelper(); //! Returns the public key raw buffer size_t getRawPublicKey(const unsigned char **p_key) const; //! Encrypts the given buffer to the output buffer //! \return true upon success //! false othewise (eg. not enough space in output buffer); bool encrypt(const unsigned char *p_buffIn, size_t p_sizeIn, unsigned char *p_buffOut, size_t *p_sizeOut) const; bool decrypt(const unsigned char *p_buffIn, size_t p_sizeIn, unsigned char *p_buffOut, size_t *p_sizeOut) const; }; struct SslContext { SslContext(SslContextType ctxtType); SslContext(SslContextType ctxtType, RSAHelper *p_localRsaHelper); ~SslContext(); //! Returns the public key raw buffer size_t getLocalRSApublicKey(const unsigned char **p_key) const; const BlowfishKey & getBlowfishKey() const; void setRemoteRSApublicKey(const unsigned char *p_key, size_t p_size); void setRemoteBlowfishKey(const BlowfishKey & p_key); bool blowfishEncrypt(void *p_out, size_t p_size) const; bool blowfishDecrypt(void *p_out, size_t p_size) const; bool blowfishEncrypt(void *p_out, const void *p_in, size_t p_size) const; bool blowfishDecrypt(void *p_out, const void *p_in, size_t p_size) const; bool rsaEncrypt(void *p_out, size_t *p_sizeOut, const void *p_in, size_t p_sizeIn) const; bool rsaDecrypt(void *p_out, size_t *p_sizeOut, const void *p_in, size_t p_sizeIn) const; RSAHelper *rsaLocal; RSAHelper *rsaRemote; bool deleteRsaLocal; BlowfishHelper blowfish; }; } #endif
C++
/* * PopupUtilities.hpp * * Created on: Mar 28, 2012 * Author: guillou */ #ifndef POPUPUTILITIES_HPP_ #define POPUPUTILITIES_HPP_ #include <stdlib.h> #define POPUP_MACRO_MIN(a,b) ((a) < (b) ? (a) : (b)) #define POPUP_MACRO_MAX(a,b) ((a) > (b) ? (a) : (b)) namespace Popup { namespace Utils { void dumpBuffer(const void *p_buffer, size_t p_size); } } #endif /* POPUPUTILITIES_HPP_ */
C++
/* * PopupLibInternalTypes.hpp * * Created on: May 26, 2012 * Author: guillou */ #ifndef POPUPLIBINTERNALTYPES_HPP_ #define POPUPLIBINTERNALTYPES_HPP_ #include <string> #include <PopupLibTypes.hpp> #include <PopupOSAL.hpp> namespace Popup { struct FileTransferExt : public FileTransfer { unsigned int totalNbFrames; unsigned int frameNo; UserList targets; int notificationPeriod; unsigned long long checksum; FileTransferExt() {} ~FileTransferExt() {} // Send constructor FileTransferExt(MessageID p_messageID, AttachmentID p_attachmentID, const UserList & p_targets, PopupUtils::FileStream *p_file, const std::string & p_filepath); bool isNotificationRequired() const; bool isComplete() const; // Receive constructor FileTransferExt(MessageID p_messageID, AttachmentID p_attachmentID, PopupUtils::FileStream *p_file, const std::string & p_filepath, unsigned int p_nbFrames, unsigned int p_totalSize); private: void computeNotificationPeriod(); }; } #endif /* POPUPLIBINTERNALTYPES_HPP_ */
C++
#include <iostream> #include <sstream> #include <string> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <errno.h> #include <msg/PopupMessages.hpp> #include <PopupDatabaseUI.hpp> #include <PopupLoggerUI.hpp> #include "PopupClient.hpp" using namespace std; using namespace Popup; using namespace PopupUtils; //============================================================================= // Construction/Destruction //============================================================================= Client *Client::newClient(ClientUI *p_clientUI) { return new ClientImpl(p_clientUI); } //--------------------------------------------------------- ClientImpl::ClientImpl(ClientUI *p_clientUI) : clientUI(p_clientUI), socket(0), state(CLIENT_STATE_DISCONNECTED), sslContext(CLIENT_CONTEXT), sessionID(-1), networker(0), server(""), port(0), threadCounter(0), messageCounter(0), sendFileCounter(0) { PopupUtils::PopupThread::start( ClientImpl::startAttachmentSenderRoutine, this); } //--------------------------------------------------------- ClientImpl::~ClientImpl() { disconnect(); } //============================================================================= // Connection/Disconnection //============================================================================= ConnectionEcode ClientImpl::connect(const string & p_server, unsigned short p_port, const string & p_login, const string & p_password, bool p_register) { ConnectionEcode _rc = POPUP_CONNECTION_ERR_UNKNOWN; mutex.lock(); if (state != CLIENT_STATE_DISCONNECTED) { mutex.unlock(); error("State machine error: cannot connect"); } else { state = CLIENT_STATE_CONNECTING; clientUI->onConnectionUpdate(false); _rc = doHandshake(p_server, p_port); if (_rc == POPUP_CONNECTION_SUCCESS) { _rc = authenticate(p_login, p_password, p_register); } else { state = CLIENT_STATE_DISCONNECTED; mutex.unlock(); } if (_rc == POPUP_CONNECTION_SUCCESS) { state = CLIENT_STATE_CONNECTED; mutex.unlock(); clientUI->onConnectionUpdate(true, user, sessionID); _rc = listen(); } else { state = CLIENT_STATE_DISCONNECTED; mutex.unlock(); } } return _rc; } //--------------------------------------------------------- bool ClientImpl::disconnect() { bool _rc = false; mutex.lock(); state = CLIENT_STATE_DISCONNECT; _rc = disconnectNoLock(); mutex.unlock(); if (_rc) { clientUI->onConnectionUpdate(false); } return _rc; } //--------------------------------------------------------- bool ClientImpl::disconnectNoLock() { bool _rc = false; if (state != CLIENT_STATE_DISCONNECT) { error("state machine error: cannot disconnect."); } else { if (networker != 0) { delete networker; networker = 0; } if (socket != 0) { socket->close(); delete socket; socket = 0; } state = CLIENT_STATE_DISCONNECTED; _rc = true; } return _rc; } //--------------------------------------------------------- ConnectionEcode ClientImpl::doHandshake(const string & p_server, unsigned short p_port) { string _errMsg = ""; ConnectionEcode _rc = POPUP_CONNECTION_SUCCESS; Message *_message = 0; bool _success = false; info("Connecting to server %s on port %d ...", p_server.c_str(), p_port); // Create client socket socket = PopupUtils::Socket::newClientSocket(p_server, p_port, &_errMsg); if (socket == 0) { _rc = POPUP_CONNECTION_ERR_SERVER_DOWN; error("Failed to connect : %s", _errMsg.c_str()); } // Instantiate networker utility else { socket->enableKeepAlive(true, 10, this); networker = new MessageNetworker(socket, &sslContext); } if (_rc == POPUP_CONNECTION_SUCCESS) { // Send our RSA key to the server RsaPublicKeyMsg msg(&sslContext); trace("Sending RSA key."); _success = networker->send(&msg); // Wait for server RSA key in return if (_success) { if (networker->receive(&_message) && (_message->header.type == POPUP_MSG_TYPE_RSA_PUBLIC_KEY)) { RsaPublicKeyMsg remotekey(_message); _success = remotekey.isValid(); if (_success) { trace("Received server RSA key."); sslContext.setRemoteRSApublicKey(remotekey.getKey(), remotekey.getSize()); } else { error("Failed to receive server RSA key (the one received is not valid)"); } } else { _success = false; error("Did not received server RSA key."); } } // At last send our blowfish key to the server if (_success) { trace("Sending Blowfish key."); BlowfishKeyMsg blowfish(&sslContext); _success = networker->send(&blowfish); } if (_success) { server = p_server; port = p_port; trace("Handshake succeeded!"); } else { error("Handshake failed!"); _rc = POPUP_CONNECTION_ERR_HANDSHAKE_FAILED; } } return _rc; } //--------------------------------------------------------- ConnectionEcode ClientImpl::authenticate(const string & p_userid, const string & p_password, bool p_register) { ConnectionEcode _rc = POPUP_CONNECTION_ERR_UNKNOWN; Message *_message = 0; // Send authentication message to server trace("Sending login request."); LoginMsg msg(p_userid, p_password, p_register); networker->send(&msg); // Wait server acknowledgment trace("Waiting server ACK..."); if (networker->receive(&_message)) { ConnectionAck _ack(_message, clientUI->getResourceDir()); if (_ack.isValid()) { _rc = _ack.getStatus(); if (_rc == POPUP_CONNECTION_SUCCESS) { user = _ack.getUser(); sessionID = _ack.getSessionID(); trace("Connection success! Your session ID is 0x%08X.", sessionID); // Notify client that connection succeeded clientUI->onConnectionUpdate(true, user, sessionID); } else { error("Connection failed (rc=%d) : %s", _ack.getStatus(), _ack.getErrMessage().c_str()); } } else { error("Received a bad acknowledgment message"); } } if (_rc == POPUP_CONNECTION_SUCCESS) { } return _rc; } //============================================================================= // RECEIVE FUNCTIONS IMPLEMENTATION //============================================================================= ConnectionEcode ClientImpl::listen() { Message *_message = 0; bool _rc = true; mutex.lock(); if (state != CLIENT_STATE_CONNECTED) { _rc = false; } mutex.unlock(); while (_rc) { _rc = networker->receive(&_message); if (_rc) { switch (_message->header.type) { case POPUP_MSG_TYPE_USER_UPDATE: { UserUpdateMsg _updateMsg(_message, clientUI->getResourceDir()); processUserUpdate(_updateMsg); break; } case POPUP_MSG_TYPE_MESSAGE: { UserMessageWrapper _userMsg(_message); processUserMessage(_userMsg); break; } case POPUP_MSG_TYPE_RATE_MESSAGE: { RateUserMessageWrapper _reactionMsg(_message); clientUI->onMessageReactionReceived(_reactionMsg); break; } case POPUP_MSG_TYPE_ATTACHMENT: { AttachmentMsg attachment(_message); processAttachment(attachment); break; } case POPUP_MSG_TYPE_CANVASS_SUBMIT: { CanvassSubmitMsg _canvass(_message); CanvassMap::iterator _it = canvassMap.find(_canvass.canvassID); if (_it == canvassMap.end()) { canvassMap[_canvass.canvassID] = new Canvass(_canvass); } clientUI->onOpinionRequested(_canvass); break; } case POPUP_MSG_TYPE_CANVASS_VOTE: { CanvassVoteMsg _vote(_message); clientUI->onVoteReceived(_vote); break; } case POPUP_MSG_TYPE_STATISTICS_UPDATE: { StatisticsUpdateMsg _statsMsg(_message); clientUI->onUserStatisticsUpdate(_statsMsg.getUserID(), _statsMsg.statistics()); break; } case POPUP_MSG_TYPE_INVITATION: { ThreadInvitationMsg _invitation(_message); clientUI->onInvitationReceived(_invitation); break; } case POPUP_MSG_TYPE_KEEPALIVE_PROBE: { KeepAliveAck _ack; _rc = threadSafeMessageSend(_ack); break; } case POPUP_MSG_TYPE_KEEPALIVE_ACK: { // Good!! We're still connected! break; } default: trace("Received an unexpected message"); break; } mutex.lock(); if (state != CLIENT_STATE_CONNECTED) { _rc = false; // This will force listen loop exit! } mutex.unlock(); } } disconnect(); return POPUP_CONNECTION_ERR_LISTEN_LOOP_EXITED; } //--------------------------------------------------------- void ClientImpl::processUserUpdate(const UserUpdateMsg & p_updateMsg) { User* _user = 0; UserMap::iterator _it; mutex.lock(); _it = users.find(p_updateMsg.getID()); // Update of an existing user if (_it != users.end()) { _user = _it->second; _user->update(p_updateMsg, p_updateMsg.getUpdateMask()); clientUI->onUserUpdate(*_user, p_updateMsg.getUpdateMask(), false); if (_user->isAlive() == false) { delete _user; users.erase(_it); } } // New user else { _user = new User(p_updateMsg); users[_user->getID()] = _user; clientUI->onUserUpdate(*_user, p_updateMsg.getUpdateMask(), true); } mutex.unlock(); } //--------------------------------------------------------- void ClientImpl::processUserMessage(const UserMessageWrapper & p_msg) { //------ Message which attachments case if (p_msg.attachmentIDs.size() > 0) { for (set<AttachmentID>::iterator it = p_msg.attachmentIDs.begin(); it != p_msg.attachmentIDs.end(); it++) { } recvMessageMap[p_msg.msgID] = new MessageWithAttachments(p_msg, p_msg.attachmentIDs); } else { clientUI->onMessageReceived(p_msg); } } //--------------------------------------------------------- void ClientImpl::processAttachment(const AttachmentMsg & p_msg) { FileTransferExt *_recvinfo = 0; unsigned int _frameNo = p_msg.getFrameNo(); bool _sameFileAlreadyExists = false; // Retrieve associated recv info RecvFileMap::iterator _it = recvFileMap.find(p_msg.getAttachmentID()); if (_it != recvFileMap.end()) { _recvinfo = _it->second; } // Create if not found! else if (p_msg.getFrameNo() == 1) { PopupUtils::FileStream *_f = 0; // Compute name of the file to create string _filepath = clientUI->getTemporaryDir() + PopupUtils::Defs::FileSeparator + p_msg.getFilename(); int _shiftVal = 1; while (PopupUtils::fexists(_filepath) && !_sameFileAlreadyExists) { // Compute existing file checksum unsigned long long _checksum = PopupUtils::checksum(_filepath); if (p_msg.getChecksum() == _checksum) { // File with the same name already exists!! _sameFileAlreadyExists = true; info("Dropping attachment %s (it already exists!)", _filepath.c_str()); } else { _filepath = clientUI->getTemporaryDir() + PopupUtils::Defs::FileSeparator + PopupUtils::shiftFile(p_msg.getFilename(), _shiftVal++); } } // Open the file if file really needs to be received if (!_sameFileAlreadyExists) { _f = PopupUtils::openFileStream(_filepath.c_str(), "w"); if (_f == 0) { error("Failed to open %s : %s", _filepath.c_str(), strerror(errno)); } } if (_sameFileAlreadyExists || _f != 0) { info("Receiving %s", _filepath.c_str()); _recvinfo = new FileTransferExt(p_msg.getParentMessageID(), p_msg.getAttachmentID(), _f, _filepath, p_msg.getNbFrames(), p_msg.getTotalSize()); recvFileMap[p_msg.getAttachmentID()] = _recvinfo; } } // Strange! else { error("Unexpected attachment message"); } if (_recvinfo != 0) { // Make sure frame number matches expected one if (_frameNo != _recvinfo->frameNo) { error("Ooops! Expected frame %lu, received %lu", _recvinfo->frameNo, _frameNo); } else { // Dump data to file in case descriptor is not null. // If descriptor is null, it means that file already exists // on host => ignore the file content data!! if (_recvinfo->file != 0) { p_msg.getRawData(_recvinfo->file); } // Update counters _recvinfo->nbTransferred += p_msg.getFrameSize(); _recvinfo->nbRemaining -= p_msg.getFrameSize(); // Send notification to GUI if necessary if (_recvinfo->isNotificationRequired()) { clientUI->onFileTransferUpdate(*_recvinfo); } // Transfer not yet over... if (!_recvinfo->isComplete()) { // ... set next expected frame _recvinfo->frameNo += 1; } // Or end up this transfer else { // Close file if (_recvinfo->file != 0) { PopupUtils::closeFileStream(_recvinfo->file); } // Retrieve parent message RecvMessageMap::iterator _it = recvMessageMap.find(p_msg.getParentMessageID()); MessageWithAttachments *_msg = _it->second; _msg->setAttachmentReceived(p_msg.getAttachmentID(), _recvinfo->filepath); // In case all attachments have been successfully received, // client can be notified if (_msg->isComplete()) { clientUI->onMessageReceived(_msg->message); delete(_msg); } } } } } //============================================================================= // SEND FUNCTIONS IMPLEMENTATION //============================================================================= bool ClientImpl::sendProbe() { KeepAliveProbe _probe; return threadSafeMessageSend(_probe); } //--------------------------------------------------------- bool ClientImpl::notifyUserUpdate(const User *p_myself, unsigned short p_updateMask) { UserUpdateMsg _updateMsg(*p_myself, p_updateMask); return threadSafeMessageSend(_updateMsg); } //--------------------------------------------------------- bool ClientImpl::sendMessage(UserMessage & p_message) { bool _rc = true; std::vector<FileTransferExt*> _transfers; // Set thread ID if (p_message.threadID == 0) { threadCounter++; p_message.threadID = (((ThreadID) sessionID) << 32) | threadCounter; } // Set sender ID p_message.senderID = user.getID(); // Set message ID messageCounter++; p_message.msgID = (((MessageID) sessionID) << 32) | messageCounter; // Create message UserMessageWrapper _msg(p_message); // Push all attachment IDs if (p_message.files.size() > 0) { AttachmentList::iterator _it; for (_it = p_message.files.begin(); _it != p_message.files.end(); _it++) { // Try to open file first FileStream *_f = openFileStream(_it->c_str(), "r"); if (_f == 0) { error("Ooops! I'm a crap!! I cannot open this file: %s", _it->c_str()); _rc = false; } else { // Compute attachment ID according to the schema: // <bit63-bit32>: session ID // <bit31-bit00>: counter sendFileCounter++; AttachmentID _attachmentID = (((AttachmentID) sessionID) << 32) | sendFileCounter; // Push into the message the ID of the attachment _msg.attachmentIDs.insert(_attachmentID); // Allocate a new file transfer _transfers.push_back( new FileTransferExt(p_message.msgID, _attachmentID, p_message.targets, _f, *_it)); } } } // Send message only if every previous steps were successful if (_rc) { _rc = threadSafeMessageSend(_msg); if (_rc) { clientUI->onMessageSent(p_message); } } if (_rc) { // Update send queue if (_transfers.size() > 0) { std::vector<FileTransferExt*>::iterator _xfer; mutex.lock(); for (_xfer = _transfers.begin(); _xfer != _transfers.end(); _xfer++) { sendFileQueue.push(*_xfer); } mutex.unlock(); } } return _rc; } //--------------------------------------------------------- bool ClientImpl::sendMessageReaction(const RateUserMessage & p_reaction) { RateUserMessageWrapper _msg(p_reaction); return threadSafeMessageSend(_msg); } //--------------------------------------------------------- bool ClientImpl::sendInvitation(const ThreadInvitation & p_invitation) { ThreadInvitationMsg _invitationMsg(p_invitation); return threadSafeMessageSend(_invitationMsg); } //--------------------------------------------------------- bool ClientImpl::submitCanvass(Canvass & p_canvass) { bool _rc = true; // Set thread ID if (p_canvass.canvassID == 0) { threadCounter++; p_canvass.canvassID = (((ThreadID) sessionID) << 32) | threadCounter; } // Set sender ID p_canvass.senderID = user.getID(); // Create message CanvassSubmitMsg _msg(p_canvass); // Send message _rc = threadSafeMessageSend(_msg); // Store a copy of the canvass in the map if (_rc) { canvassMap[p_canvass.canvassID] = new Canvass(p_canvass); } return _rc; } //--------------------------------------------------------- bool ClientImpl::sendVote(const Vote & p_vote) { bool _rc = true; // Search for this canvass in the map CanvassMap::iterator _it = canvassMap.find(p_vote.canvassID); if (_it == canvassMap.end()) { error("Cannot find canvass %llu", p_vote.canvassID); _rc = false; } else { // Add all other voters in copy Canvass *_canvass = _it->second; UserList _targets; _targets.insert(_canvass->senderID); UserList::iterator _itvoter; for (_itvoter = _canvass->targets.begin(); _itvoter != _canvass->targets.end(); _itvoter++) { _targets.insert(*_itvoter); } CanvassVoteMsg _vote(p_vote, _targets); _vote.voterID = user.getID(); _rc = threadSafeMessageSend(_vote); } return _rc; } //============================================================================= // Attachment sending management //============================================================================= void *ClientImpl::startAttachmentSenderRoutine(void *p_args) { ((ClientImpl*) p_args)->attachmentSenderRoutine(); return 0; } //--------------------------------------------------------- void ClientImpl::attachmentSenderRoutine() { bool _rc = true; FileTransferExt *_sendinfo = 0; while (true) { _rc = true; _sendinfo = 0; mutex.lock(); // We are not connected, let's wait if (state != CLIENT_STATE_CONNECTED) { // Clear the queue if not empty if (sendFileQueue.size() > 0) { SendFileQueue _empty; std::swap(sendFileQueue, _empty); } // And wait mutex.unlock(); PopupUtils::PopupThread::sleep(1000); } // We are connected. Is there something to send? else { if (sendFileQueue.size() > 0) { _sendinfo = sendFileQueue.front(); sendFileQueue.pop(); } mutex.unlock(); } // Nothing to send... Let's sleep if (_sendinfo == 0) { PopupUtils::PopupThread::sleep(1000); } // Hey! Cool! There is something to send! Let's go! else { for (_sendinfo->frameNo = 1; _sendinfo->frameNo <= _sendinfo->totalNbFrames; _sendinfo->frameNo++) { AttachmentMsg _part(_sendinfo); _rc = threadSafeMessageSend(_part); if (_rc) { _sendinfo->nbRemaining -= _part.getFrameSize(); _sendinfo->nbTransferred += _part.getFrameSize(); // Notify client that we're sending this file if (_sendinfo->isNotificationRequired()) { clientUI->onFileTransferUpdate(*_sendinfo); } } else { break; // End loop in case we failed to send message } } PopupUtils::closeFileStream(_sendinfo->file); delete _sendinfo; } } } //============================================================================= // Utilities //============================================================================= bool ClientImpl::threadSafeMessageSend(AbstractMessage & p_message) { bool _rc = true; mutex.lock(); if (state == CLIENT_STATE_CONNECTED) { _rc = networker->send(&p_message); if (!_rc) { printf("Send failed\n"); fflush(stdout); state = CLIENT_STATE_DISCONNECT; disconnectNoLock(); clientUI->onConnectionUpdate(false); } } else { _rc = false; } mutex.unlock(); return _rc; } //--------------------------------------------------------- bool ClientImpl::MessageWithAttachments::isComplete() const { return (attachmentIDs.size() == 0); } //--------------------------------------------------------- void ClientImpl::MessageWithAttachments::setAttachmentReceived( AttachmentID p_attachmentID, const string & p_filepath) { attachmentIDs.erase(p_attachmentID); message.files.push_back(p_filepath); }
C++
#ifndef __POPUP_CLIENT_HPP__ #define __POPUP_CLIENT_HPP__ #include <PopupClientUI.hpp> #include <PopupOSAL.hpp> #include <msg/PopupAbstractMessage.hpp> #include "PopupSSL.hpp" #include <queue> #include <set> class SocketClient; namespace Popup { class ClientImpl: public Client, public PopupUtils::Socket::KeepAliveHelper { public: ClientImpl(ClientUI *p_clientUI); virtual ~ClientImpl(); //! @Override virtual bool sendMessage(UserMessage & p_message); //! @Override virtual bool sendMessageReaction(const RateUserMessage & p_message); //! @Override virtual bool submitCanvass(Canvass & p_canvass); //! @Override virtual bool sendVote(const Vote & p_vote); //! @Override virtual bool sendInvitation(const ThreadInvitation & p_invitation); //!@ Override virtual bool notifyUserUpdate(const User *p_myself, unsigned short p_updateMask); //!@ Override virtual ConnectionEcode connect(const std::string & p_server, unsigned short p_port, const std::string & p_login, const std::string & p_password, bool p_register = false); //!@ Override virtual bool disconnect(); //!@ Override // Keep alive helper virtual bool sendProbe(); private: ConnectionEcode doHandshake(const std::string & p_server, unsigned short p_port); ConnectionEcode authenticate(const std::string & p_login, const std::string & p_password, bool p_register = false); ConnectionEcode listen(); void processUserUpdate(const UserUpdateMsg & p_msg); void processUserMessage(const UserMessageWrapper & p_msg); void processAttachment(const AttachmentMsg & p_msg); void attachmentSenderRoutine(); static void *startAttachmentSenderRoutine(void *p_args); bool threadSafeMessageSend(AbstractMessage & p_message); bool disconnectNoLock(); private: struct MessageWithAttachments { UserMessage message; std::set<AttachmentID> attachmentIDs; MessageWithAttachments(const UserMessage & p_msg, const std::set<AttachmentID> & p_attachmentIDs) : message(p_msg), attachmentIDs(p_attachmentIDs) {} bool isComplete() const; void setAttachmentReceived(AttachmentID p_attachmentID, const std::string & p_filepath); }; typedef std::map<UserID, User*> UserMap; typedef std::map<MessageID, MessageWithAttachments*> RecvMessageMap; typedef std::queue<FileTransferExt*> SendFileQueue; typedef std::map<AttachmentID, FileTransferExt*> RecvFileMap; typedef std::map<CanvassID, Canvass*> CanvassMap; typedef enum { CLIENT_STATE_DISCONNECTED, CLIENT_STATE_CONNECTING, CLIENT_STATE_CONNECTED, CLIENT_STATE_DISCONNECT } ConnectionState; PopupUtils::Mutex mutex; ClientUI* clientUI; PopupUtils::Socket* socket; ConnectionState state; SslContext sslContext; SessionID sessionID; MessageNetworker* networker; std::string server; unsigned short port; unsigned int threadCounter; unsigned int messageCounter; unsigned int sendFileCounter; User user; UserMap users; RecvFileMap recvFileMap; RecvMessageMap recvMessageMap; SendFileQueue sendFileQueue; CanvassMap canvassMap; }; } #endif // __POPUP_CLIENT_HPP__
C++
#ifndef __POPUP_SERVER_HPP__ #define __POPUP_SERVER_HPP__ #include <string> #include <PopupServerUI.hpp> #include <PopupOSAL.hpp> #include <msg/PopupMessages.hpp> #include "PopupSSL.hpp" #include "PopupDatabaseUI.hpp" namespace Popup { struct ClientSession { PopupUtils::Socket *socket; UserID id; bool registered; SslContext sslContext; MessageNetworker networker; User *user; bool disconnect; ClientSession(PopupUtils::Socket *p_socket, RSAHelper *p_rsaHelper) : socket(p_socket), id(0), registered(false), sslContext(SERVER_CONTEXT, p_rsaHelper), networker(p_socket, &sslContext), user(0), disconnect(false) {} ~ClientSession() { delete(socket); } }; class ServerImpl : public Server { public: virtual ~ServerImpl(); static ServerImpl *createInstance(unsigned short p_port, unsigned short p_maxNbConnections, DatabaseUI *p_database, ServerUI *p_serverUI); static ServerImpl *getInstance(); void run(); private: // Constructor is private according to singleton pattern // Use PopupServer::getInstance instead. ServerImpl(unsigned short p_port, unsigned short p_maxNbConnections, DatabaseUI *p_database, ServerUI *p_serverUI); PopupUtils::Socket *serverSocket; static ServerImpl *instance; DatabaseUI *database; ServerUI *ui; bool exit; RSAHelper rsahelper; typedef std::map<UserID, ClientSession*> Sessions; typedef std::map<PopupUtils::OSSocketFd, ClientSession*> Sockets; Sessions sessions; Sockets sockets; UserLoginMap loginsMap; private: static void signalHandler(int p_signal); void initSessions(); void acceptNewClient(); void deleteSession(ClientSession *p_session); bool processActivity(ClientSession *p_session); void kill(); void closeAllConnections(); void broadcastMessage(AbstractMessage *p_message, const ClientSession *p_sender = 0); void broadcastMessage(const RawMessage *p_message, unsigned p_messageSize, const ClientSession *p_from = 0); bool sendAllUsersList(ClientSession *p_session); void sendMessage(const RawMessage *p_message, unsigned p_messageSize, const UserList & p_targets); }; } #endif // __POPUP_SERVER_HPP__
C++
/* * PopupLibTypes.cpp * * Created on: Jul 2, 2012 * Author: guillou */ #include <PopupLibTypes.hpp> using namespace std; using namespace Popup; const UserList EmptyUserList; const User NullUser; void User::update(const User & p_user, unsigned short p_updateMask) { id = p_user.getID(); if (p_updateMask & POPUP_USER_FIELD_NICKNAME) { nickname = p_user.getNickname(); } if (p_updateMask & POPUP_USER_FIELD_AVATAR) { avatar = p_user.getAvatar(); } if (p_updateMask & POPUP_USER_FIELD_MODE) { mode = p_user.getMode(); } if (p_updateMask & POPUP_USER_FIELD_HEALTH) { alive = p_user.isAlive(); } } unsigned short UserStatistics::itemsMask() const { unsigned short _mask = 0x0000; const_iterator _it; for (_it = begin(); _it != end(); _it++) { _mask |= _it->first; } return _mask; } bool UserStatistics::isRecordman(UserRateItem p_item) const { return ((recordMask & p_item) != 0); } void UserStatistics::set(UserRateItem p_item, unsigned int p_value, bool p_isRecord) { (*this)[p_item] = p_value; if (p_isRecord) { recordMask |= p_item; } else { recordMask &= ~p_item; } } bool UserStatistics::get(UserRateItem p_item, unsigned int & p_value, bool & p_isRecord) const { const_iterator _it = find(p_item); if (_it != end()) { p_value = _it->second; p_isRecord = ((recordMask & p_item) != 0); return true; } else { return false; } } void strUserRateItem(UserRateItem p_item, string & p_string) { switch (p_item) { case POPUP_RATE_LIKE: p_string = "like"; break; case POPUP_RATE_DONTLIKE: p_string = "dontlike"; break; case POPUP_RATE_POETRY: p_string = "poetry"; break; case POPUP_RATE_FUCKYOU: p_string = "fuckyou"; break; default: p_string = "unknown"; break; } } void UserStatistics::dump() const { string _itemname; const_iterator _it; for (_it = begin(); _it != end(); _it++) { strUserRateItem(_it->first, _itemname); printf("stats[%s] = %u %s\n", _itemname.c_str(), _it->second, (((recordMask & _it->first) != 0? "*** record! ***" : ""))); } }
C++
#include <iostream> #include <string.h> #include <openssl/x509.h> #include <openssl/rand.h> #include <openssl/err.h> #include <PopupLibTypes.hpp> #include <PopupOSAL.hpp> #include "PopupSSL.hpp" #include "PopupUtilities.hpp" using namespace std; using namespace Popup; static bool randInitialized = false; #define RSA_PLAIN_TEXT_BLOC_SIZE 100 //============================================================================= // SSL context //============================================================================= SslContext::SslContext(SslContextType ctxtType) : rsaLocal(new RSAHelper()), rsaRemote(0), deleteRsaLocal(true), blowfish(ctxtType) { } SslContext::SslContext(SslContextType ctxtType, RSAHelper *p_localRsaHelper) : rsaLocal(p_localRsaHelper), rsaRemote(0), deleteRsaLocal(false), blowfish(ctxtType) { } SslContext::~SslContext() { if (deleteRsaLocal && (rsaLocal != 0)) { delete rsaLocal; } if (rsaRemote != 0) { delete rsaRemote; } } //! Returns the public key raw buffer size_t SslContext::getLocalRSApublicKey(const unsigned char **p_key) const { return rsaLocal->getRawPublicKey(p_key); } //! Returns the blowfish key raw buffer const BlowfishKey & SslContext::getBlowfishKey() const { return blowfish.getKey(); } void SslContext::setRemoteRSApublicKey(const unsigned char *p_key, size_t p_size) { rsaRemote = new RSAHelper(p_key, p_size); } void SslContext::setRemoteBlowfishKey(const BlowfishKey & p_key) { blowfish.setKey(p_key); } bool SslContext::blowfishEncrypt(void *p_out, size_t p_size) const { return blowfish.encrypt((unsigned char*) p_out, (const unsigned char*) p_out, p_size); } bool SslContext::blowfishEncrypt(void *p_out, const void *p_in, size_t p_size) const { return blowfish.encrypt((unsigned char*) p_out, (const unsigned char*) p_in, p_size); } bool SslContext::blowfishDecrypt(void *p_out, size_t p_size) const { return blowfish.decrypt((unsigned char*)p_out, (const unsigned char*)p_out, p_size); } bool SslContext::blowfishDecrypt(void *p_out, const void *p_in, size_t p_size) const { return blowfish.decrypt((unsigned char*)p_out, (const unsigned char*)p_in, p_size); } bool SslContext::rsaEncrypt(void *p_out, size_t *p_sizeOut, const void *p_in, size_t p_sizeIn) const { // Encrypt with remote host public key return rsaRemote->encrypt((const unsigned char*) p_in, p_sizeIn, (unsigned char *) p_out, p_sizeOut); } bool SslContext::rsaDecrypt(void *p_out, size_t *p_sizeOut, const void *p_in, size_t p_sizeIn) const { // Decrypt with local private key return rsaLocal->decrypt((const unsigned char*) p_in, p_sizeIn, (unsigned char*) p_out, p_sizeOut); } //============================================================================= // RSA //============================================================================= RSAHelper::RSAHelper() : key(RSA_new()), num(BN_new()), mode(RSA_MASTER), rawpubkey(0), rawpubkeySize(0) { if (randInitialized == false) { char salt[128]; PopupUtils::randomString(&salt[0], 128); RAND_seed(salt, strlen(salt)); randInitialized = true; } BN_set_word(num, RSA_F4); RSA_generate_key_ex(key, 1024, num, NULL); rawpubkeySize = i2d_RSAPublicKey(key, &rawpubkey); } RSAHelper::RSAHelper(const unsigned char *p_publicKey, size_t p_keySize) : key(d2i_RSAPublicKey(NULL, &p_publicKey, p_keySize)), num(0), mode(RSA_SLAVE), rawpubkey(0), rawpubkeySize(0) { } RSAHelper::~RSAHelper() { if (key != 0) { RSA_free(key); } if (num != 0) { BN_free(num); } if (rawpubkey != 0) { delete rawpubkey; } } size_t RSAHelper::getRawPublicKey(const unsigned char **p_key) const { *p_key = rawpubkey; return rawpubkeySize; } bool RSAHelper::encrypt(const unsigned char *p_buffin, size_t p_sizeIn, unsigned char *p_buffout, size_t *p_sizeOut) const { size_t _blocsize = RSA_size(key); // High estimation of the size required in order to write the first // block into the buffer size_t _encryptedSize = 0; size_t _remainingSize = p_sizeIn; for (size_t offsetin = 0, offsetout = 0; offsetin < p_sizeIn; offsetin += RSA_PLAIN_TEXT_BLOC_SIZE, offsetout += _blocsize) { size_t _size = 0; if (_remainingSize < RSA_PLAIN_TEXT_BLOC_SIZE) { _size = _remainingSize; } else { _size = RSA_PLAIN_TEXT_BLOC_SIZE; } _remainingSize -= _size; _size = RSA_public_encrypt(_size, &p_buffin[offsetin], &p_buffout[offsetout], key, RSA_PKCS1_PADDING); if (_size == (size_t) -1) { return false; } else { _encryptedSize += _size; } } *p_sizeOut = _encryptedSize; return (_encryptedSize > 0); } bool RSAHelper::decrypt(const unsigned char *p_buffin, size_t p_sizeIn, unsigned char *p_buffout, size_t *p_sizeOut) const { size_t _offsetout = 0; size_t _blocsize = RSA_size(key); for (size_t _offsetin = 0; _offsetin < p_sizeIn; _offsetin += _blocsize) { size_t _decsize = RSA_private_decrypt(RSA_size(key), &p_buffin[_offsetin], &p_buffout[_offsetout], key, RSA_PKCS1_PADDING); if (_decsize == (size_t) -1) { return false; } else { _offsetout += _decsize; } } *p_sizeOut = _offsetout; return (_offsetout > 0); } //============================================================================= // Blowfish //============================================================================= #define NULL_IVEC { 0, 0, 0, 0, 0, 0, 0, 0 } BlowfishHelper::BlowfishHelper(SslContextType ctxt) { if (ctxt == CLIENT_CONTEXT) { PopupUtils::randomString((char*)&seed[0], sizeof(BlowfishKey)); BF_set_key(&key, sizeof(BlowfishKey), seed); } } void BlowfishHelper::setKey(const BlowfishKey & p_key) { memcpy(&seed[0], &p_key[0], sizeof(BlowfishKey)); memset(&key, 0, sizeof(BF_KEY)); BF_set_key(&key, sizeof(BlowfishKey), seed); } const BlowfishKey & BlowfishHelper::getKey() const { return seed; } bool BlowfishHelper::encrypt(unsigned char *p_buffOut, const unsigned char *p_buffIn, size_t p_size) const { unsigned char ivec[8] = NULL_IVEC; BF_cbc_encrypt(p_buffIn, p_buffOut, p_size, &key, ivec, BF_ENCRYPT); return true; } bool BlowfishHelper::decrypt(unsigned char *p_buffOut, const unsigned char *p_buffIn, size_t p_size) const { unsigned char ivec[8] = NULL_IVEC; BF_cbc_encrypt(p_buffIn, p_buffOut, p_size, &key, ivec, BF_DECRYPT); return true; }
C++
/* * PopupFileTransferExt.cpp * * Created on: May 26, 2012 * Author: guillou */ #include "PopupUtilities.hpp" #include "PopupFileTransferExt.hpp" using namespace Popup; using namespace std; FileTransferExt::FileTransferExt(MessageID p_messageID, AttachmentID p_attachmentID, const UserList & p_targets, PopupUtils::FileStream * p_file, const string & p_filepath) : FileTransfer(POPUP_DIRECTION_OUT, p_messageID, p_attachmentID, p_filepath, p_file, PopupUtils::getFileSize(p_filepath)), totalNbFrames(0), frameNo(1), targets(p_targets), notificationPeriod(1), checksum(PopupUtils::checksum(p_filepath)) { // Make sureGet file size and compute the number of frames required to send // the attachment totalNbFrames = (totalSize / POPUP_MSG_SPLIT_SIZE); if (totalSize % POPUP_MSG_SPLIT_SIZE != 0) { totalNbFrames += 1; } // Compute nofification period computeNotificationPeriod(); } FileTransferExt::FileTransferExt(MessageID p_messageID, AttachmentID p_attachmentID, PopupUtils::FileStream *p_file, const string & p_filepath, unsigned int p_nbFrames, unsigned int p_totalSize) : FileTransfer(POPUP_DIRECTION_IN, p_messageID, p_attachmentID, p_filepath, p_file, p_totalSize), totalNbFrames(p_nbFrames), frameNo(1), notificationPeriod(1), checksum(0) { // Compute nofification period computeNotificationPeriod(); } void FileTransferExt::computeNotificationPeriod() { notificationPeriod = POPUP_MACRO_MAX(1, (totalNbFrames / 100)); } bool FileTransferExt::isNotificationRequired() const { return ((frameNo % notificationPeriod) == 0 || (frameNo == totalNbFrames)); } bool FileTransferExt::isComplete() const { return (nbTransferred == totalSize); }
C++
#ifndef __POPUPRSAPUBLICKEYMSG_HPP__ #define __POPUPRSAPUBLICKEYMSG_HPP__ #include "PopupAbstractMessage.hpp" #include <PopupSSL.hpp> namespace Popup { struct RsaPublicKeyMsg : public AbstractMessage { enum { RSA_PUBLIC_KEY = 0x1234 }; RsaPublicKeyMsg(const SslContext *p_sslContext) : AbstractMessage(POPUP_MSG_TYPE_RSA_PUBLIC_KEY), sslContext(p_sslContext), receivedKey(0), receivedKeySize(0) {} RsaPublicKeyMsg(const Message *p_message); ~RsaPublicKeyMsg(); //!@Override bool onSend(); //!@Override bool onReceive(); inline const unsigned char *getKey() const { return receivedKey; } inline size_t getSize() const { return receivedKeySize; } private: const SslContext *sslContext; //! RSA key received from a foreign host unsigned char *receivedKey; size_t receivedKeySize; }; } #endif // __POPUPRSAPUBLICKEYMSG_HPP__
C++
#include <string.h> #include "PopupAbstractMessage.hpp" #include "PopupSSL.hpp" using namespace std; using namespace Popup; #define POPUP_BOOLEAN_TRUE 0x01 #define POPUP_BOOLEAN_FALSE 0x00 //============================================================================= // Construction //============================================================================= AbstractMessage::AbstractMessage(MsgType p_id, MsgEncryption p_encryption) : type(p_id), encryption(p_encryption), payloadSize(0), freePayloadSize(0), message(0), fullMessage(0), valid(false), prepareDone(false) { } //--------------------------------------------------------- AbstractMessage::~AbstractMessage() { if (fullMessage != 0) { delete fullMessage; fullMessage = 0; } } //============================================================================= // Payload allocation utilities //============================================================================= bool AbstractMessage::allocate(size_t p_nbBytes) { // Payload is allocated by 256 bytes blocks size_t _allocatedSize = 256 * (((p_nbBytes - freePayloadSize) + 255) / 256); if (encryption != POPUP_ENCRYPTION_NONE) { // Encrypted size shall be a multiple of 8 size_t encrytableSize = sizeof(MessageHeader) + payloadSize + freePayloadSize + _allocatedSize; if (encrytableSize % 8 != 0) { _allocatedSize += (8 - (encrytableSize % 8)); } } // (Re)allocate memory size_t totalMsgSize = sizeof(RawMessageHeader) + sizeof(MessageHeader) + payloadSize + freePayloadSize + _allocatedSize; unsigned char *mem = (unsigned char *) realloc(fullMessage, totalMsgSize); if (mem != 0) { fullMessage = (RawMessage*) mem; message = &fullMessage->message; freePayloadSize += _allocatedSize; memset(&message->payload[payloadSize], 0, freePayloadSize); return true; } else { return false; } } //============================================================================= // Send/Receive management //============================================================================= bool AbstractMessage::prepareSend() { if (prepareDone == true) { return true; } else { if (onSend()) { if ((message == 0) && !allocate(0)) { return false; } else { // Setup message header message->header.type = type; message->header.payloadSize = payloadSize; memset(&message->header.spare[0], 0, sizeof(message->header.spare)); Message_hton(message); prepareDone = true; return true; } } else { return false; } } } //--------------------------------------------------------- bool AbstractMessage::deserialize(const Message *p_message) { bool _rc = true; MessageField *_field = 0; size_t _index = 0; fields.clear(); // Add a pointer to each field in fields map while ((_rc) && (_index < p_message->header.payloadSize)) { _field = (MessageField*) &p_message->payload[_index]; MessageField_ntoh(_field); fields[_field->id] = _field; _index += sizeof(MessageField) + _field->size; //MessageField_dump(_field); } valid = (_rc && onReceive()); return valid; } //============================================================================= // Getters //============================================================================= #define POPUP_BLOWFISH_ALIGNMENT 8 size_t AbstractMessage::getUtilMessageSize() const { if (encryption == POPUP_ENCRYPTION_BLOWFISH) { return POPUP_BLOWFISH_ALIGNMENT * ( (sizeof(MessageHeader) + payloadSize + POPUP_BLOWFISH_ALIGNMENT - 1) / POPUP_BLOWFISH_ALIGNMENT); } else { return sizeof(MessageHeader) + payloadSize; } } //--------------------------------------------------------- size_t AbstractMessage::getTotalMessageSize() const { return sizeof(RawMessageHeader) + sizeof(MessageHeader) + payloadSize; } //============================================================================= // Payload management //============================================================================= bool AbstractMessage::payloadAddData(unsigned short p_fieldId, const void *p_fieldData, size_t p_fieldDataSize, unsigned short p_fieldDataType) { bool _rc = true; size_t _requiredSize = sizeof(MessageField) + p_fieldDataSize; if (freePayloadSize < _requiredSize) { _rc = allocate(_requiredSize); } if (_rc) { MessageField *_field = (MessageField*) &message->payload[payloadSize]; _field->id = p_fieldId; _field->size = p_fieldDataSize; _field->type = p_fieldDataType; memcpy(_field->data, p_fieldData, p_fieldDataSize); MessageField_hton(_field); payloadSize += _requiredSize; freePayloadSize -= _requiredSize; } return _rc; } //--------------------------------------------------------- bool AbstractMessage::payloadAddOpaqueData(unsigned short p_fieldId, size_t p_fieldDataSize, void **p_buffer) { bool _rc = true; size_t _requiredSize = sizeof(MessageField) + p_fieldDataSize; if (freePayloadSize < _requiredSize) { _rc = allocate(_requiredSize); } if (_rc) { MessageField *_field = (MessageField*) &message->payload[payloadSize]; _field->id = p_fieldId; _field->size = p_fieldDataSize; _field->type = POPUP_FIELD_DATA_TYPE_UNK; *p_buffer = &_field->data[0]; MessageField_hton(_field); payloadSize += _requiredSize; freePayloadSize -= _requiredSize; } return _rc; } //--------------------------------------------------------- bool AbstractMessage::payloadAddFileContent(unsigned short p_fieldId, const string & p_path) { bool _rc = true; size_t _filesize = PopupUtils::getFileSize(p_path); if (_filesize == 0) { _rc = false; } else { size_t _requiredSize = sizeof(MessageField) + _filesize; if (freePayloadSize < _requiredSize) { _rc = allocate(_requiredSize); } if (_rc) { MessageField *_field = (MessageField*) &message->payload[payloadSize]; _field->id = p_fieldId; _field->size = _filesize; _field->type = POPUP_FIELD_DATA_TYPE_UNK; memset(&_field->data[0], 0xCA, _filesize); _rc = PopupUtils::dumpFileToBuffer(&_field->data[0], _filesize, p_path); MessageField_hton(_field); payloadSize += _requiredSize; freePayloadSize -= _requiredSize; } } return _rc; } //--------------------------------------------------------- const MessageField *AbstractMessage::payloadGetField( unsigned short p_fieldId) const { FieldsMap::const_iterator it = fields.find(p_fieldId); if (it != fields.end()) { return it->second; } else { return 0; } } //--------------------------------------------------------- bool AbstractMessage::payloadAddString(unsigned short p_fieldId, const string & p_value) { return payloadAddData(p_fieldId, p_value.c_str(), p_value.length() + 1, POPUP_FIELD_DATA_TYPE_STRING); } //--------------------------------------------------------- bool AbstractMessage::payloadAddString(unsigned short p_fieldId, const vector<string> & p_values) { unsigned int _size = 0; vector<string>::const_iterator _it; for (_it = p_values.begin(); _it != p_values.end(); _it++) { _size += _it->length() + 1; } // Allocate a buffer to store all strings content unsigned char *_buffer = new unsigned char[_size]; // Copy all strings to this buffer size_t _pos = 0; for (_it = p_values.begin(); _it != p_values.end(); _it++) { memcpy(&_buffer[_pos], _it->c_str(), _it->length() + 1); _pos += _it->length() + 1; } // Add resulting field as raw data bool _rc = payloadAddData(p_fieldId, _buffer, _size, POPUP_FIELD_DATA_TYPE_UNK); delete _buffer; return _rc; } //----------------------1----------------------------------- bool AbstractMessage::payloadGetString(unsigned short p_fieldId, string & p_value) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { p_value.assign((const char*) _field->data); return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadGetString(unsigned short p_fieldId, vector<string> & p_values) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { unsigned int _index = 0; while (_index < _field->size) { unsigned int _length = PopupUtils::strnlen( (const char*) &_field->data[_index], (_field->size - _index)); string _value; _value.assign((const char*) &_field->data[_index]); _index += (_length+1); p_values.push_back(_value); } return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadAddBoolean(unsigned short p_fieldId, bool p_value) { unsigned char _value = (p_value? POPUP_BOOLEAN_TRUE : POPUP_BOOLEAN_FALSE); return payloadAddData(p_fieldId, &_value, sizeof(unsigned char), POPUP_FIELD_DATA_TYPE_BOOLEAN); } //--------------------------------------------------------- bool AbstractMessage::payloadGetBoolean(unsigned short p_fieldId, bool & p_value) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { unsigned char *_value = (unsigned char*) _field->data; p_value = (*_value == POPUP_BOOLEAN_TRUE); return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadAddShort(unsigned short p_fieldId, unsigned short p_value) { unsigned short _value = p_value; return payloadAddData(p_fieldId, &_value, sizeof(unsigned short), POPUP_FIELD_DATA_TYPE_SHORT); } //--------------------------------------------------------- bool AbstractMessage::payloadAddShort(unsigned short p_fieldId, const vector<unsigned short> & p_values) { unsigned short _values[p_values.size()]; vector<unsigned short>::const_iterator _it; size_t _n; for (_n = 0, _it = p_values.begin(); _it != p_values.end(); _n++, _it++) { _values[_n] = *_it; } return payloadAddData(p_fieldId, _values, _n * sizeof(unsigned short), POPUP_FIELD_DATA_TYPE_SHORT); } //--------------------------------------------------------- bool AbstractMessage::payloadGetShort(unsigned short p_fieldId, unsigned short & p_value) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { unsigned short * _value = (unsigned short*) _field->data; p_value = *_value; return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadGetShort(unsigned short p_fieldId, vector<unsigned short> & p_values) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { size_t _nbValues = _field->size / sizeof(unsigned short); for (size_t _n = 0; _n < _nbValues; _n++) { p_values.push_back(((unsigned short*) _field->data)[_n]); } return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadAddLong(unsigned short p_fieldId, unsigned int p_value) { unsigned int _value = p_value; return payloadAddData(p_fieldId, &_value, sizeof(unsigned int), POPUP_FIELD_DATA_TYPE_LONG); } //--------------------------------------------------------- bool AbstractMessage::payloadAddLong(unsigned short p_fieldId, const set<unsigned int> & p_values) { unsigned int _values[p_values.size()]; set<unsigned int>::const_iterator _it; size_t _n; for (_n = 0, _it = p_values.begin(); _it != p_values.end(); _n++, _it++) { _values[_n] = *_it; } return payloadAddData(p_fieldId, _values, _n * sizeof(unsigned int), POPUP_FIELD_DATA_TYPE_LONG); } //--------------------------------------------------------- bool AbstractMessage::payloadGetLong(unsigned short p_fieldId, unsigned int & p_value) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { unsigned int * _value = (unsigned int*) _field->data; p_value = *_value; return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadGetLong(unsigned short p_fieldId, set<unsigned int> & p_values) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { size_t _nbValues = _field->size / sizeof(unsigned int); for (size_t _n = 0; _n < _nbValues; _n++) { p_values.insert(((unsigned int*) _field->data)[_n]); } return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadAddLongLong(unsigned short p_fieldId, unsigned long long p_value) { unsigned long long _value = p_value; return payloadAddData(p_fieldId, &_value, sizeof(unsigned long long), POPUP_FIELD_DATA_TYPE_LONG_LONG); } //--------------------------------------------------------- bool AbstractMessage::payloadAddLongLong(unsigned short p_fieldId, const set<unsigned long long> & p_values) { unsigned long long _values[p_values.size()]; set<unsigned long long>::const_iterator _it; size_t _n; for (_n = 0, _it = p_values.begin(); _it != p_values.end(); _n++, _it++) { _values[_n] = *_it; } return payloadAddData(p_fieldId, _values, _n * sizeof(unsigned long long), POPUP_FIELD_DATA_TYPE_LONG_LONG); } //--------------------------------------------------------- bool AbstractMessage::payloadGetLongLong(unsigned short p_fieldId, unsigned long long & p_value) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { unsigned long long * _value = (unsigned long long*) _field->data; p_value = *_value; return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadGetLongLong(unsigned short p_fieldId, set<unsigned long long> & p_values) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { size_t _nbValues = _field->size / sizeof(unsigned long long); for (size_t _n = 0; _n < _nbValues; _n++) { p_values.insert(((unsigned long long*) _field->data)[_n]); } return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadDumpFieldToFile(unsigned short p_fieldId, const string & p_path) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { return PopupUtils::dumpBufferToFile(p_path, _field->data, _field->size); } } //--------------------------------------------------------- bool AbstractMessage::payloadDumpFieldToFile(unsigned short p_fieldId, PopupUtils::FileStream *p_file) const { const MessageField *_field = payloadGetField(p_fieldId); if (_field == 0) { return false; } else { size_t _totalWritten = PopupUtils::fillStreamFromBuffer( p_file, &_field->data[0], _field->size); if (_totalWritten != _field->size) { return false; } return true; } } //--------------------------------------------------------- bool AbstractMessage::payloadAddFromFile(unsigned short p_fieldId, PopupUtils::FileStream *p_file, unsigned int p_fieldDataSize) { bool _rc = true; size_t _requiredSize = sizeof(MessageField) + p_fieldDataSize; if (freePayloadSize < _requiredSize) { _rc = allocate(_requiredSize); } if (_rc) { MessageField *_field = (MessageField*) &message->payload[payloadSize]; _field->id = p_fieldId; _field->size = p_fieldDataSize; _field->type = POPUP_FIELD_DATA_TYPE_UNK; size_t _nbRead = PopupUtils::fillBufferFromStream( &_field->data[0], p_fieldDataSize, p_file); if (_nbRead != p_fieldDataSize) { _rc = false; } MessageField_hton(_field); payloadSize += _requiredSize; freePayloadSize -= _requiredSize; } return _rc; }
C++
#ifndef POPUPCLIENTUPDATEMESSAGE_HPP_ #define POPUPCLIENTUPDATEMESSAGE_HPP_ #include <PopupLibTypes.hpp> #include <PopupLoggerUI.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct UserUpdateMsg : public AbstractMessage, public User { enum { USERID, USERNICKNAME, AVATAR_RAW_DATA, AVATAR_FILENAME, MODE, HEALTH }; //! Constructor used in order to send a user update notification UserUpdateMsg(const User & p_user, unsigned short p_updateMask = POPUP_USER_FIELD_ALL) : AbstractMessage(POPUP_MSG_TYPE_USER_UPDATE), User(p_user), updateMask(p_updateMask) {} //! Constructor used in order to receive a user upate notification UserUpdateMsg(const Message *p_message, const std::string & p_resourcePath = "."); //!@Override bool onSend(); //!@Override bool onReceive(); //! Returns update mask unsigned short getUpdateMask() const; void dump() const; private: unsigned short updateMask; std::string resourcePath; }; } #endif // POPUPCLIENTUPDATEMESSAGE_HPP_
C++
#include "PopupConnectionAck.hpp" using namespace std; using namespace Popup; ConnectionAck::ConnectionAck(const Message *p_message, const string & p_resourcePath) : AbstractMessage(POPUP_MSG_TYPE_CONNECTION_ACK), resourcePath(p_resourcePath) { AbstractMessage::deserialize(p_message); } bool ConnectionAck::onSend() { bool _rc = AbstractMessage::payloadAddShort(STATUS, status); if (status != POPUP_CONNECTION_SUCCESS) { return (_rc && AbstractMessage::payloadAddString(ERR_MESSAGE, errMessage)); } else { // Add session ID if (_rc) { _rc = AbstractMessage::payloadAddLong(SESSIONID, sessionID); } // Add user ID if (_rc) { _rc = AbstractMessage::payloadAddLong(USERID, user.getID()); } // Add user nickname if (_rc) { _rc = AbstractMessage::payloadAddString( USERNICKNAME, user.getNickname()); } // Add user health status if (_rc) { _rc = AbstractMessage::payloadAddBoolean(HEALTH, user.isAlive()); } if (_rc) { // Add avatar (not mandatory!) bool _avatarOk = AbstractMessage::payloadAddFileContent(AVATAR_RAW_DATA, user.getAvatar()); if (_avatarOk) { AbstractMessage::payloadAddString(AVATAR_FILENAME, PopupUtils::basename(user.getAvatar())); } } return _rc; } } bool ConnectionAck::onReceive() { bool _rc = payloadGetShort(STATUS, status); if (_rc) { if (status != POPUP_CONNECTION_SUCCESS) { _rc = ((fields.size() == 2) && (payloadGetString(ERR_MESSAGE, errMessage))); } else { _rc = (payloadGetLong(SESSIONID, sessionID) && payloadGetLong(USERID, user.id) && payloadGetString(USERNICKNAME, user.nickname), payloadGetBoolean(HEALTH, user.alive)); if (_rc == true) { string _avatarFilename; if (AbstractMessage::payloadGetString(AVATAR_FILENAME, _avatarFilename)) { string _avatarFullpath = resourcePath + "/" + _avatarFilename; _rc = AbstractMessage::payloadDumpFieldToFile(AVATAR_RAW_DATA, _avatarFullpath); if (_rc) { user.avatar = _avatarFullpath; } } } } } return _rc; }
C++
#include <string.h> #include "PopupRsaPublicKeyMsg.hpp" using namespace Popup; RsaPublicKeyMsg::RsaPublicKeyMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_RSA_PUBLIC_KEY), receivedKey(0), receivedKeySize(0) { AbstractMessage::deserialize(p_message); } RsaPublicKeyMsg::~RsaPublicKeyMsg() { if (receivedKey != 0) { delete receivedKey; } } bool RsaPublicKeyMsg::onSend() { const unsigned char *_key; size_t _size = sslContext->rsaLocal->getRawPublicKey(&_key); return payloadAddData(RsaPublicKeyMsg::RSA_PUBLIC_KEY, _key, _size); } bool RsaPublicKeyMsg::onReceive() { if (fields.size() != 1) { return false; } else { const MessageField *_field = AbstractMessage::payloadGetField(RSA_PUBLIC_KEY); if (_field == 0) { return false; } else { receivedKeySize = _field->size; receivedKey = new unsigned char[receivedKeySize]; memcpy(receivedKey, _field->data, _field->size); return true; } } }
C++
/* * PopupUserMessageWrapper.hpp * * Created on: May 11, 2012 * Author: guillou */ #ifndef POPUPUSERMESSAGEWRAPPER_HPP_ #define POPUPUSERMESSAGEWRAPPER_HPP_ #include <PopupLibTypes.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct UserMessageWrapper : public AbstractMessage, public UserMessage { enum { ID, SENDER, THREAD, TARGETS, TEXT, TITLE, URLS, ATTACHMENT_IDS }; //! Constructor used in order to send a message UserMessageWrapper(const UserMessage & p_message) : AbstractMessage(POPUP_MSG_TYPE_MESSAGE), message(p_message) {} //! Constructor used in order to receive a message UserMessageWrapper(const Message *p_message); virtual ~UserMessageWrapper() {} //!@Override bool onSend(); //!@Override bool onReceive(); public: std::set<AttachmentID> attachmentIDs; private: UserMessage message; }; } #endif /* POPUPUSERMESSAGEWRAPPER_HPP_ */
C++
#ifndef POPUPCONNECTIONACK_HPP_ #define POPUPCONNECTIONACK_HPP_ #include <PopupLibTypes.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct ConnectionAck : public AbstractMessage { enum { STATUS, ERR_MESSAGE, SESSIONID, USERID, USERNICKNAME, AVATAR_RAW_DATA, AVATAR_FILENAME, HEALTH }; //! Constructor used in order to send a connection NACK ConnectionAck(ConnectionEcode p_status, const std::string & p_message = "Blurp!") : AbstractMessage(POPUP_MSG_TYPE_CONNECTION_ACK), status(p_status), errMessage(p_message) {} //! Constructor used in order to send a connection ACK ConnectionAck(SessionID p_sessionID, const User & p_user) : AbstractMessage(POPUP_MSG_TYPE_CONNECTION_ACK), status(POPUP_CONNECTION_SUCCESS), errMessage("Success"), sessionID(p_sessionID), user(p_user) {} //! Constructor used in order to received a login request ConnectionAck(const Message *p_message, const std::string & p_resourcePath = "."); ~ConnectionAck() {} //!@Override bool onSend(); //!@Override bool onReceive(); inline ConnectionEcode getStatus() const { return (ConnectionEcode) status; } inline const std::string & getErrMessage() const { return errMessage; } inline const User & getUser() const { return user; } inline SessionID getSessionID() const { return sessionID; } private: unsigned short status; std::string errMessage; SessionID sessionID; User user; std::string resourcePath; }; } #endif /* POPUPCONNECTIONACK_HPP_ */
C++
/* * PopupSubmitCanvassMsg.cpp * * Created on: Jul 16, 2012 * Author: guillou */ #include "PopupCanvassSubmitMsg.hpp" using namespace std; using namespace Popup; CanvassSubmitMsg::CanvassSubmitMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_CANVASS_SUBMIT) { AbstractMessage::deserialize(p_message); } bool CanvassSubmitMsg::onSend() { bool _rc = payloadAddLongLong(ID, canvass.canvassID); if (_rc) { _rc = payloadAddLong(TARGETS, canvass.targets); } if (_rc) { payloadAddLong(SENDER, canvass.senderID); } if (_rc) { payloadAddString(QUESTION, canvass.question); } if (_rc) { payloadAddString(CHOICES, canvass.choices); } if (_rc) { payloadAddShort(TIMEOUT, canvass.timeout); } if (_rc) { payloadAddBoolean(ANONYMOUS, canvass.isAnonymous); } if (_rc) { payloadAddBoolean(ALLOW_MULTISELECTION, canvass.allowMultiSelection); } return _rc; } bool CanvassSubmitMsg::onReceive() { bool _rc = payloadGetLongLong(ID, canvassID); if (_rc) { _rc = payloadGetLong(TARGETS, targets); } if (_rc) { _rc = payloadGetLong(SENDER, senderID); } if (_rc) { payloadGetString(QUESTION, question); } if (_rc) { payloadGetString(CHOICES, choices); } if (_rc) { payloadGetShort(TIMEOUT, timeout); } if (_rc) { payloadGetBoolean(ANONYMOUS, isAnonymous); } if (_rc) { payloadGetBoolean(ALLOW_MULTISELECTION, allowMultiSelection); } return _rc; }
C++
/* * PopupStatisticsUpdateMsg.hpp * * Created on: Jul 25, 2012 * Author: guillou */ #ifndef POPUPSTATISTICSUPDATEMSG_HPP_ #define POPUPSTATISTICSUPDATEMSG_HPP_ #include <PopupLibTypes.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct StatisticsUpdateMsg : public AbstractMessage { enum { USERID = POPUP_RATE_ITEM_MAX+1, RECORDMASK }; //! Constructor used in order to send StatisticsUpdateMsg(UserID p_userID) : AbstractMessage(POPUP_MSG_TYPE_STATISTICS_UPDATE), userID(p_userID) {} //! Constructor used in order to receive StatisticsUpdateMsg(const Message *p_message); //!@Override bool onSend(); //!@Override bool onReceive(); inline const UserStatistics & statistics() const { return stats; } inline UserStatistics & statistics() { return stats; } inline UserID getUserID() const { return userID; } private: UserID userID; UserStatistics stats; }; } #endif /* POPUPSTATISTICSUPDATEMSG_HPP_ */
C++
#ifndef __POPUPBLOWFISKKEYMSG_HPP__ #define __POPUPBLOWFISKKEYMSG_HPP__ #include "PopupMessage.hpp" #include "PopupAbstractMessage.hpp" #include "PopupSSL.hpp" namespace Popup { struct BlowfishKeyMsg : public AbstractMessage { enum { BLOWFISH_KEY = 0x4321 }; //! Constructor used in order to send our blowfish key to //! a foreign host using RSA encryption public key contained //! in the given SSL context. BlowfishKeyMsg(const SslContext *p_sslContext) : AbstractMessage(POPUP_MSG_TYPE_BLOWFISH_KEY, POPUP_ENCRYPTION_RSA), sslContext(p_sslContext) {} //! Constructor used in order to received a blowfish key from //! a foreign host. Key will be decrypted using private RSA //! key contained in the given SSL context. BlowfishKeyMsg(const Message *p_message); ~BlowfishKeyMsg() {} //!@Override bool onSend(); //!@Override bool onReceive(); inline const BlowfishKey & getKey() { return receivedKey; } private: //! Blowfish key received from a foreign host BlowfishKey receivedKey; const SslContext *sslContext; }; } #endif // __POPUPBLOWFISKKEYMSG_HPP__
C++
#ifndef POPUP_ABSTRACT_MESSAGE_H #define POPUP_ABSTRACT_MESSAGE_H #include <string> #include <vector> #include <set> #include <map> #include <PopupOSAL.hpp> #include "PopupMessage.hpp" #include <PopupLoggerUI.hpp> #include "PopupSSL.hpp" namespace Popup { struct AbstractMessage { public: virtual ~AbstractMessage(); //! Checks for message coherence inline bool isValid() const { return valid; } protected: AbstractMessage(MsgType p_id = POPUP_MSG_TYPE_UNK, MsgEncryption p_encryption = POPUP_ENCRYPTION_NONE); //! Sets up message from the given message bool deserialize(const Message *p_message); //! Sets up message to be ready for sending over the network virtual bool onSend() { return true; } //! Notifies user that a message has been received virtual bool onReceive() { return true; } bool payloadAddData(unsigned short fieldId, const void *p_data = 0, size_t p_size = 0, unsigned short p_type = POPUP_FIELD_DATA_TYPE_UNK); bool payloadAddOpaqueData(unsigned short fieldId, size_t p_size, void **p_payloadBuffer); bool payloadAddFileContent(unsigned short fieldId, const std::string & p_path); bool payloadAddString(unsigned short fieldId, const std::string & p_value); bool payloadAddString(unsigned short fieldId, const std::vector<std::string> & p_values); bool payloadAddBoolean(unsigned short fieldId, bool p_value); bool payloadAddShort(unsigned short p_fieldId, unsigned short p_value); bool payloadAddShort(unsigned short p_fieldId, const std::vector<unsigned short> & p_values); bool payloadAddLong(unsigned short p_fieldId, unsigned int p_value); bool payloadAddLong(unsigned short p_fieldId, const std::set<unsigned int > & p_values); bool payloadAddLongLong(unsigned short p_fieldId, unsigned long long p_value); bool payloadAddLongLong(unsigned short p_fieldId, const std::set<unsigned long long> & p_values); const MessageField *payloadGetField(unsigned short fieldId) const; bool payloadGetString(unsigned short p_fieldId, std::string & p_value) const; bool payloadGetString(unsigned short p_fieldId, std::vector<std::string> & p_values) const; bool payloadGetBoolean(unsigned short p_fieldId, bool & p_value) const; bool payloadGetShort(unsigned short p_fieldId, unsigned short & p_value) const; bool payloadGetShort(unsigned short p_fieldId, std::vector<unsigned short> & p_values) const; bool payloadGetLong(unsigned short p_fieldId, unsigned int & p_value) const; bool payloadGetLong(unsigned short p_fieldId, std::set<unsigned int > & p_values) const; bool payloadGetLongLong(unsigned short p_fieldId, unsigned long long & p_value) const; bool payloadGetLongLong(unsigned short p_fieldId, std::set<unsigned long long> & p_values) const; bool payloadDumpFieldToFile(unsigned short p_fieldId, const std::string & p_filepath) const; bool payloadDumpFieldToFile(unsigned short p_fieldId, PopupUtils::FileStream *p_file) const; bool payloadAddFromFile(unsigned short p_fieldId, PopupUtils::FileStream *p_file, unsigned int p_size); //======================================================== // Private methods which will be used by the friend class // PopupNetworkMessage //======================================================== private: friend class MessageNetworker; //! Sets up raw message to be ready for sending bool prepareSend(); //! Returns util message size (ie. protocol header excluded) size_t getUtilMessageSize() const; //! Returns the total message, protocol header included size_t getTotalMessageSize() const; //======================================================== // Class members //======================================================== protected: FieldsMap fields; private: bool allocate(size_t p_datasize); unsigned short type; MsgEncryption encryption; size_t payloadSize; size_t freePayloadSize; //! Util message Message *message; //! Full message RawMessage *fullMessage; //! Validity of the message bool valid; bool prepareDone; }; } #endif
C++
/* * PopupCanvassVoteMsg.hpp * * Created on: Jul 17, 2012 * Author: guillou */ #ifndef POPUPCANVASSVOTEMSG_HPP_ #define POPUPCANVASSVOTEMSG_HPP_ #include <PopupLibTypes.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct CanvassVoteMsg : public AbstractMessage, public Vote { enum { CANVASS_ID, VOTER, TARGETS, CHOICES }; //! Constructor used in order to send a message CanvassVoteMsg(const Vote & p_vote, const UserList & p_targets) : AbstractMessage(POPUP_MSG_TYPE_CANVASS_VOTE), Vote(p_vote), targets(p_targets) {} //! Constructor used in order to receive a message CanvassVoteMsg(const Message *p_message); virtual ~CanvassVoteMsg() {} //! @Override bool onSend(); //! @Override bool onReceive(); //! Other participants UserList targets; }; } #endif /* POPUPCANVASSVOTEMSG_HPP_ */
C++
/* * PopupInvitationMsg.hpp * * Created on: Sep 12, 2012 * Author: guillou */ #ifndef POPUPINVITATIONMSG_HPP_ #define POPUPINVITATIONMSG_HPP_ #include <PopupLibTypes.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct ThreadInvitationMsg : public AbstractMessage, public ThreadInvitation { enum { THREAD_ID, THREAD_TITLE, INVITER_ID, CC_TARGETS, INVITED_USERS_ID }; //! Constructor used in order to send a message ThreadInvitationMsg(const ThreadInvitation & p_invitation) : AbstractMessage(POPUP_MSG_TYPE_INVITATION), ThreadInvitation(p_invitation) {} //! Constructor used in order to receive a message ThreadInvitationMsg(const Message *p_message); virtual ~ThreadInvitationMsg() {} //! @Override bool onSend(); //! @Override bool onReceive(); }; } #endif /* POPUPINVITATIONMSG_HPP_ */
C++
#include "PopupUserMessage.hpp" using namespace std; using namespace Popup; UserMessageWrapper::UserMessageWrapper(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_MESSAGE) { AbstractMessage::deserialize(p_message); } bool UserMessageWrapper::onSend() { bool _rc = payloadAddLongLong(THREAD, message.threadID); if (_rc) { payloadAddLongLong(ID, message.msgID); } if (_rc) { _rc = payloadAddLong(TARGETS, message.targets); } if (_rc) { payloadAddLong(SENDER, message.senderID); } if (_rc) { payloadAddString(TEXT, message.text); } if (_rc) { payloadAddString(TITLE, message.title); } if (_rc && message.URLs.size() > 0) { payloadAddString(URLS, message.URLs); } if (_rc && attachmentIDs.size() > 0) { payloadAddLongLong(ATTACHMENT_IDS, attachmentIDs); } return _rc; } bool UserMessageWrapper::onReceive() { bool _rc = payloadGetLongLong(THREAD, threadID); if (_rc) { payloadGetLongLong(ID, msgID); } if (_rc) { _rc = payloadGetLong(TARGETS, targets); } if (_rc) { _rc = payloadGetLong(SENDER, senderID); } if (_rc) { payloadGetString(TEXT, text); } if (_rc) { payloadGetString(TITLE, title); } if (_rc) { payloadGetString(URLS, URLs); } if (_rc) { payloadGetLongLong(ATTACHMENT_IDS, attachmentIDs); } return _rc; }
C++
#include "PopupThreadInvitationMsg.hpp" using namespace std; using namespace Popup; ThreadInvitationMsg::ThreadInvitationMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_INVITATION) { AbstractMessage::deserialize(p_message); } bool ThreadInvitationMsg::onSend() { bool _rc = payloadAddLongLong(THREAD_ID, threadID); if (_rc) { payloadAddLong(INVITER_ID, inviter); } if (_rc) { _rc = payloadAddLong(CC_TARGETS, cc); } if (_rc) { payloadAddString(THREAD_TITLE, threadTitle); } if (_rc) { payloadAddLong(INVITED_USERS_ID, invitedUsers); } return _rc; } bool ThreadInvitationMsg::onReceive() { bool _rc = payloadGetLongLong(THREAD_ID, threadID); if (_rc) { _rc = payloadGetLong(CC_TARGETS, cc); } if (_rc) { _rc = payloadGetLong(INVITER_ID, inviter); } if (_rc) { payloadGetString(THREAD_TITLE, threadTitle); } if (_rc) { payloadGetLong(INVITED_USERS_ID, invitedUsers); } return _rc; }
C++
/* * PopupSubmitCanvassMsg.hpp * * Created on: Jul 16, 2012 * Author: guillou */ #ifndef POPUPSUBMITCANVASSMSG_HPP_ #define POPUPSUBMITCANVASSMSG_HPP_ #include <PopupLibTypes.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct CanvassSubmitMsg : public AbstractMessage, public Canvass { enum { ID, SENDER, TARGETS, QUESTION, CHOICES, TIMEOUT, ANONYMOUS, ALLOW_MULTISELECTION }; //! Constructor used in order to send a message CanvassSubmitMsg(const Canvass & p_canvass) : AbstractMessage(POPUP_MSG_TYPE_CANVASS_SUBMIT), canvass(p_canvass) {} //! Constructor used in order to receive a message CanvassSubmitMsg(const Message *p_message); virtual ~CanvassSubmitMsg() {} //! @Override bool onSend(); //! @Override bool onReceive(); private: Canvass canvass; }; } #endif /* POPUPSUBMITCANVASSMSG_HPP_ */
C++
#include "PopupLoginMsg.hpp" using namespace Popup; LoginMsg::LoginMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_LOGIN, POPUP_ENCRYPTION_BLOWFISH) { AbstractMessage::deserialize(p_message); } bool LoginMsg::onSend() { return (AbstractMessage::payloadAddString(LOGIN, login) && AbstractMessage::payloadAddString(PASSWORD, password) && AbstractMessage::payloadAddBoolean(CREATEUSER, createUser)); } bool LoginMsg::onReceive() { return ((fields.size() == 3) && (AbstractMessage::payloadGetString(LOGIN, login)) && (AbstractMessage::payloadGetString(PASSWORD, password)) && (AbstractMessage::payloadGetBoolean(CREATEUSER, createUser))); }
C++
#include "PopupStatisticsUpdateMsg.hpp" using namespace std; using namespace Popup; StatisticsUpdateMsg::StatisticsUpdateMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_STATISTICS_UPDATE) { AbstractMessage::deserialize(p_message); } bool StatisticsUpdateMsg::onSend() { bool _rc = true; if (stats.size() == 0) { _rc = false; } else { unsigned short _item = 0; _rc = payloadAddLong(USERID, userID); payloadAddShort(RECORDMASK, stats.recordMask); map<UserRateItem, unsigned int>::const_iterator _it; for (_it = stats.begin(); _it != stats.end(); _it++) { _item = (unsigned short) _it->first; payloadAddLong(_item, _it->second); } } return _rc; } bool StatisticsUpdateMsg::onReceive() { unsigned int _value = 0; bool _rc = payloadGetLong(USERID, userID); if (_rc) { payloadGetShort(RECORDMASK, stats.recordMask); if (payloadGetLong(POPUP_RATE_LIKE, _value)) { stats[POPUP_RATE_LIKE] = _value; } if (payloadGetLong(POPUP_RATE_DONTLIKE, _value)) { stats[POPUP_RATE_DONTLIKE] = _value; } if (payloadGetLong(POPUP_RATE_POETRY, _value)) { stats[POPUP_RATE_POETRY] = _value; } if (payloadGetLong(POPUP_RATE_FUCKYOU, _value)) { stats[POPUP_RATE_FUCKYOU] = _value; } } return _rc; }
C++
/* * PopupAttachmentMsg.hpp * * Created on: May 12, 2012 * Author: guillou */ #ifndef POPUPATTACHMENTMSG_HPP_ #define POPUPATTACHMENTMSG_HPP_ #include "PopupLibTypes.hpp" #include "PopupAbstractMessage.hpp" #include "PopupFileTransferExt.hpp" namespace Popup { struct AttachmentMsg : public AbstractMessage { enum { MSGID, TARGETS, ATTACHMENTID, TOTALSIZE, FILENAME, NBFRAMES, FRAMENO, FRAMESIZE, RAWDATA, CHECKSUM }; //! Constructor used in order to send a message AttachmentMsg(const FileTransferExt *p_sendinfo) : AbstractMessage(POPUP_MSG_TYPE_ATTACHMENT), sendinfo(p_sendinfo), frameSize(POPUP_MACRO_MIN(p_sendinfo->nbRemaining, POPUP_MSG_SPLIT_SIZE)) {} //! Constructor used in order to receive a message AttachmentMsg(const Message *p_message); virtual ~AttachmentMsg() {} //!@Override bool onSend(); //!@Override bool onReceive(); const MessageID & getParentMessageID() const { return recvinfo.messageID; } const UserList & getTargets() const { return recvinfo.targets; } const AttachmentID & getAttachmentID() const { return recvinfo.attachmentID; } const std::string & getFilename() const { return recvinfo.filepath; } unsigned int getTotalSize() const { return recvinfo.totalSize; } unsigned int getNbFrames() const { return recvinfo.totalNbFrames; } unsigned int getFrameNo() const { return recvinfo.frameNo; } unsigned short getFrameSize() const { return frameSize; } bool getRawData(PopupUtils::FileStream *p_file) const; unsigned long long getChecksum() const { return recvinfo.checksum; } private: const FileTransferExt *sendinfo; FileTransferExt recvinfo; unsigned int frameSize; }; } #endif /* POPUPATTACHMENTMSG_HPP_ */
C++
#ifndef POPUP_MESSAGES_ID #define POPUP_MESSAGES_ID #ifdef _WIN32 #include <winsock2.h> #else #include <arpa/inet.h> #endif #include <PopupOSAL.hpp> #include <PopupSSL.hpp> #include <PopupUtilities.hpp> #include <map> namespace Popup { #define POPUP_MAGIC 0xBEBE //============================================================================ // All popup messages //============================================================================ typedef enum { POPUP_MSG_TYPE_UNK, POPUP_MSG_TYPE_RSA_PUBLIC_KEY, POPUP_MSG_TYPE_BLOWFISH_KEY, POPUP_MSG_TYPE_LOGIN, POPUP_MSG_TYPE_CONNECTION_ACK, POPUP_MSG_TYPE_USER_UPDATE, POPUP_MSG_TYPE_MESSAGE, POPUP_MSG_TYPE_RATE_MESSAGE, POPUP_MSG_TYPE_KILL_ORDER, POPUP_MSG_TYPE_PING, POPUP_MSG_TYPE_PONG, POPUP_MSG_TYPE_STOP_ORDER, POPUP_MSG_TYPE_ATTACHMENT, POPUP_MSG_TYPE_CANVASS_SUBMIT, POPUP_MSG_TYPE_CANVASS_VOTE, POPUP_MSG_TYPE_STATISTICS_UPDATE, POPUP_MSG_TYPE_INVITATION, POPUP_MSG_TYPE_KEEPALIVE_PROBE, POPUP_MSG_TYPE_KEEPALIVE_ACK } MsgType; typedef enum { POPUP_FIELD_DATA_TYPE_UNK = 0x0000, POPUP_FIELD_DATA_TYPE_SHORT = 0x0001, POPUP_FIELD_DATA_TYPE_LONG = 0x0002, POPUP_FIELD_DATA_TYPE_STRING = 0x0003, POPUP_FIELD_DATA_TYPE_BOOLEAN = 0x0004, POPUP_FIELD_DATA_TYPE_LONG_LONG = 0x0005 } MsgFieldType; typedef enum { POPUP_ENCRYPTION_NONE = 0x0000, POPUP_ENCRYPTION_RSA = 0x0001, POPUP_ENCRYPTION_BLOWFISH = 0x0002 } MsgEncryption; //============================================================================ // Message data structures //============================================================================ struct RawMessageHeader { unsigned short magic; unsigned int size; unsigned short encryption; }; struct MessageHeader { unsigned short type; unsigned short spare[29]; unsigned int payloadSize; }; struct Message { MessageHeader header; unsigned char payload[]; }; struct RawMessage { RawMessageHeader header; Message message; }; struct MessageField { unsigned short id; unsigned short type; unsigned int size; unsigned char data[]; }; typedef std::map<unsigned short, MessageField*> FieldsMap; //============================================================================ // Message recv/send utility class //============================================================================ struct AbstractMessage; class MessageNetworker { public: MessageNetworker(PopupUtils::Socket *p_socket, const SslContext *p_sslContext) : socket(p_socket), sslContext(p_sslContext) {} ~MessageNetworker() {} bool receive(Message **p_message, RawMessage **p_fullMessage = 0, unsigned int *p_fullMessageSize = 0); bool send(AbstractMessage *p_message, const SslContext *p_sslContext = 0); bool const_send(AbstractMessage *p_message, const SslContext *p_sslContext = 0); bool send(const RawMessage *p_message, unsigned int p_size); private: bool send(unsigned char *p_message, size_t p_size, MsgEncryption p_encryption, const SslContext *p_sslContext); bool send(const unsigned char *p_message, size_t p_size, MsgEncryption p_encryption, const SslContext *p_sslContext); private: PopupUtils::Socket *socket; const SslContext *sslContext; }; //============================================================================ // Base types init, endianness and dump //============================================================================ void RawMessageHeader_initialize(RawMessageHeader *p_header); void RawMessageHeader_ntoh(RawMessageHeader *p_header); void RawMessageHeader_hton(RawMessageHeader *p_header); void RawMessageHeader_ntoh(RawMessageHeader & p_dest, const RawMessageHeader & p_src); void RawMessageHeader_hton(RawMessageHeader & p_dest, const RawMessageHeader & p_src); void MessageHeader_initialize(MessageHeader *p_header); void MessageHeader_ntoh(MessageHeader *p_header); void MessageHeader_hton(MessageHeader *p_header); void ntohll(unsigned long long *value); void htonll(unsigned long long *value); void MessageField_initialize(MessageField *p_field); void MessageField_ntoh(MessageField *p_field); void MessageField_hton(MessageField *p_field); void MessageField_dump(MessageField *p_field); void Message_initialize(Message *p_msg); void Message_ntoh(Message *p_msg); void Message_hton(Message *p_msg); } #endif
C++
/* * PopupCanvassVoteMsg.cpp * * Created on: Jul 17, 2012 * Author: guillou */ #include "PopupCanvassVoteMsg.hpp" using namespace std; using namespace Popup; CanvassVoteMsg::CanvassVoteMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_CANVASS_VOTE) { AbstractMessage::deserialize(p_message); } bool CanvassVoteMsg::onSend() { bool _rc = payloadAddLongLong(CANVASS_ID, canvassID); if (_rc) { _rc = payloadAddLong(TARGETS, targets); } if (_rc) { payloadAddLong(VOTER, voterID); } if (_rc) { payloadAddShort(CHOICES, choices); } return _rc; } bool CanvassVoteMsg::onReceive() { bool _rc = payloadGetLongLong(CANVASS_ID, canvassID); if (_rc) { _rc = payloadGetLong(TARGETS, targets); } if (_rc) { payloadGetLong(VOTER, voterID); } if (_rc) { payloadGetShort(CHOICES, choices); } return _rc; }
C++
#include "PopupUserMessageReaction.hpp" using namespace std; using namespace Popup; RateUserMessageWrapper::RateUserMessageWrapper(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_RATE_MESSAGE) { AbstractMessage::deserialize(p_message); } bool RateUserMessageWrapper::onSend() { bool _rc = payloadAddLongLong(SOURCE_MSG_ID, reaction.msgID); if (_rc) { _rc = payloadAddLongLong(SOURCE_MSG_THREAD_ID, reaction.threadID); } if (_rc) { _rc = payloadAddLong(TARGETS, reaction.targets); } if (_rc) { payloadAddLong(SOURCE_MSG_SENDER, reaction.msgSenderID); } if (_rc) { payloadAddLong(RATE_SENDER_ID, reaction.rateSenderID); } if (_rc) { payloadAddShort(RATED_ITEM, reaction.rateItem); } if (_rc) { payloadAddBoolean(IS_UNDO, reaction.isUndo); } return _rc; } bool RateUserMessageWrapper::onReceive() { bool _rc = payloadGetLongLong(SOURCE_MSG_ID, msgID); if (_rc) { _rc = payloadGetLongLong(SOURCE_MSG_THREAD_ID, threadID); } if (_rc) { _rc = payloadGetLong(TARGETS, targets); } if (_rc) { _rc = payloadGetLong(SOURCE_MSG_SENDER, msgSenderID); } if (_rc) { _rc = payloadGetLong(RATE_SENDER_ID, rateSenderID); } if (_rc) { unsigned short _reactionTypeValue = 0; _rc = payloadGetShort(RATED_ITEM, _reactionTypeValue); rateItem = (UserRateItem) _reactionTypeValue; } if (_rc) { payloadGetBoolean(IS_UNDO, isUndo); } return _rc; }
C++
/* * PopupUserMessageReaction.hpp * * Created on: Jul 5, 2012 * Author: guillou */ #ifndef POPUPUSERMESSAGEREACTION_HPP_ #define POPUPUSERMESSAGEREACTION_HPP_ #include <PopupLibTypes.hpp> #include "PopupAbstractMessage.hpp" namespace Popup { struct RateUserMessageWrapper : public AbstractMessage, public RateUserMessage { enum { SOURCE_MSG_ID, SOURCE_MSG_SENDER, SOURCE_MSG_THREAD_ID, RATE_SENDER_ID, RATED_ITEM, IS_UNDO, TARGETS }; //! Constructor used in order to send a message RateUserMessageWrapper(const RateUserMessage & p_reaction) : AbstractMessage(POPUP_MSG_TYPE_RATE_MESSAGE), reaction(p_reaction) {} //! Constructor used in order to receive a message RateUserMessageWrapper(const Message *p_message); virtual ~RateUserMessageWrapper() {} //!@Override bool onSend(); //!@Override bool onReceive(); private: RateUserMessage reaction; }; } #endif /* POPUPUSERMESSAGEREACTION_HPP_ */
C++
#include "PopupMessage.hpp" #include "PopupAbstractMessage.hpp" #include <string.h> #include "PopupUtilities.hpp" #include <PopupLoggerUI.hpp> using namespace Popup; using namespace PopupUtils; bool MessageNetworker::receive(Message **p_message, RawMessage **p_rawMessage, unsigned int *p_rawMessageSize) { RawMessageHeader _header; Message *_message = 0; RawMessageHeader_initialize(&_header); // If we are given a non-null pointer, its up to us to free // the memory if (*p_message != 0) { delete *p_message; } if (p_rawMessage != 0 && *p_rawMessage != 0) { delete *p_rawMessage; } // Read next message header bool _rc = socket->receiveBytes(&_header); if (!_rc) { error("Oops! recv() failed."); } if (_rc == true) { RawMessageHeader_ntoh(&_header); // Make sure this is a popup message if (_header.magic != POPUP_MAGIC) { error("Received something which is not from Popup world " "(expected magic=%x received=%x)", POPUP_MAGIC, _header.magic); _rc = false; } } if (_rc == true) { size_t _messageSize = _header.size; unsigned char *_buffer = new unsigned char[_messageSize]; _rc = socket->receiveBytes(_buffer, _header.size); //Utils::dumpBuffer(_buffer, _header.size); // Duplicate original message in case we're asked for! if (p_rawMessage != 0) { *p_rawMessageSize = _header.size + sizeof(RawMessageHeader); *p_rawMessage = (RawMessage*) new unsigned char[*p_rawMessageSize]; // Copy header (restore endianness if necessary) (*p_rawMessage)->header = _header; RawMessageHeader_hton(&(*p_rawMessage)->header); // Copy message memcpy(&(*p_rawMessage)->message, _buffer, _messageSize); } switch (_header.encryption) { case POPUP_ENCRYPTION_NONE: _message = (Message*) _buffer; break; case POPUP_ENCRYPTION_BLOWFISH: _rc = sslContext->blowfishDecrypt((unsigned char*) _buffer, _messageSize); _message = (Message*) _buffer; break; case POPUP_ENCRYPTION_RSA: { // Final message needs to be in another chunk of memory _message = (Message*) new unsigned char[_messageSize]; _rc = sslContext->rsaDecrypt((unsigned char*)_message, &_messageSize, (const unsigned char*)_buffer, _messageSize); delete _buffer; break; } default: error("Not cool!"); break; } } if (_rc) { Message_ntoh(_message); *p_message = _message; } return _rc; } bool MessageNetworker::send(AbstractMessage *p_message, const SslContext *p_sslContext) { if (p_message->encryption == POPUP_ENCRYPTION_RSA) { return const_send(p_message, p_sslContext); } else if (p_message->prepareSend()) { size_t _utilSize = p_message->getUtilMessageSize(); RawMessage *_message = p_message->fullMessage; if (p_message->encryption == POPUP_ENCRYPTION_BLOWFISH) { const SslContext *_sslContext = (p_sslContext != 0)? p_sslContext : sslContext; _sslContext->blowfishEncrypt((unsigned char*) p_message->message, _utilSize); } RawMessageHeader *_header = (RawMessageHeader*) _message; _header->magic = POPUP_MAGIC; _header->encryption = p_message->encryption; _header->size = _utilSize; RawMessageHeader_hton(_header); return socket->sendBytes((unsigned char*) _message, _utilSize + sizeof(RawMessageHeader)); //Utils::dumpBuffer(_message, _utilSize + sizeof(PopupProtocolMsgHeader)); } return false; } bool MessageNetworker::const_send(AbstractMessage *p_message, const SslContext *p_sslContext) { bool _rc = false; if (p_message->prepareSend()) { RawMessage *_message = p_message->fullMessage; const SslContext *_sslContext = (p_sslContext != 0)? p_sslContext : sslContext; unsigned char *_buffer = 0; size_t _utilSize = p_message->getUtilMessageSize(); size_t _rsaCypherGrowSize = 0; switch (p_message->encryption) { case POPUP_ENCRYPTION_NONE: break; case POPUP_ENCRYPTION_BLOWFISH: _buffer = new unsigned char[_utilSize]; _sslContext->blowfishEncrypt(&_buffer[sizeof(RawMessageHeader)], (const unsigned char*) p_message->message, _utilSize); _message = (RawMessage*) _buffer; break; case POPUP_ENCRYPTION_RSA: // We need a buffer which is bigger that original message _buffer = new unsigned char[sizeof(RawMessageHeader) + (2 * _utilSize)]; size_t _encryptedSize = 0; _sslContext->rsaEncrypt(&_buffer[sizeof(RawMessageHeader)], &_encryptedSize, (const unsigned char*) p_message->message, _utilSize); _message = (RawMessage*) _buffer; _rsaCypherGrowSize = _encryptedSize - _utilSize; break; } RawMessageHeader *_header = (RawMessageHeader*) _message; _header->magic = POPUP_MAGIC; _header->encryption = p_message->encryption; _header->size = _utilSize + _rsaCypherGrowSize; RawMessageHeader_hton(_header); _rc = socket->sendBytes((unsigned char*) _message, p_message->getTotalMessageSize() + _rsaCypherGrowSize); if (_buffer != 0) { delete _buffer; } return _rc; } return _rc; } bool MessageNetworker::send(const RawMessage *p_message, unsigned int p_size) { return socket->sendBytes((const unsigned char*) p_message, p_size); } //============================================================================ // Base types init, endianness and dump //============================================================================ void Popup::RawMessageHeader_initialize(RawMessageHeader *p_header) { p_header->magic = POPUP_MAGIC; p_header->encryption = POPUP_ENCRYPTION_NONE; p_header->size = 0; } void Popup::RawMessageHeader_ntoh(RawMessageHeader *p_header) { p_header->magic = ntohs(p_header->magic); p_header->encryption = ntohs(p_header->encryption); p_header->size = ntohl(p_header->size); } void Popup::RawMessageHeader_hton(RawMessageHeader *p_header) { p_header->magic = htons(p_header->magic); p_header->encryption = htons(p_header->encryption); p_header->size = htonl(p_header->size); } void Popup::RawMessageHeader_ntoh(RawMessageHeader & p_dest, const RawMessageHeader & p_src) { p_dest.magic = ntohs(p_src.magic); p_dest.encryption = ntohs(p_src.encryption); p_dest.size = ntohl(p_src.size); } void Popup::RawMessageHeader_hton(RawMessageHeader & p_dest, const RawMessageHeader & p_src) { p_dest.magic = htons(p_src.magic); p_dest.encryption = htons(p_src.encryption); p_dest.size = htonl(p_src.size); } void Popup::MessageHeader_initialize(MessageHeader *p_header) { p_header->type = POPUP_MSG_TYPE_UNK; p_header->payloadSize = 0; } void Popup::MessageHeader_ntoh(MessageHeader *p_header) { p_header->type = ntohs(p_header->type); p_header->payloadSize = ntohl(p_header->payloadSize); } void Popup::MessageHeader_hton(MessageHeader *p_header) { p_header->type = htons(p_header->type); p_header->payloadSize = htonl(p_header->payloadSize); } void Popup::ntohll(unsigned long long *value) { if (ntohs(0x1234) != 0x1234) { *value = ((*value & 0x00000000000000FFULL) << 56) | ((*value & 0x000000000000FF00ULL) << 40) | ((*value & 0x0000000000FF0000ULL) << 24) | ((*value & 0x00000000FF000000ULL) << 8) | ((*value & 0x000000FF00000000ULL) >> 8) | ((*value & 0x0000FF0000000000ULL) >> 24) | ((*value & 0x00FF000000000000ULL) >> 40) | ((*value & 0xFF00000000000000ULL) >> 56); } } void Popup::htonll(unsigned long long *value) { if (htons(0x1234) != 0x1234) { *value = ((*value & 0x00000000000000FFULL) << 56) | ((*value & 0x000000000000FF00ULL) << 40) | ((*value & 0x0000000000FF0000ULL) << 24) | ((*value & 0x00000000FF000000ULL) << 8) | ((*value & 0x000000FF00000000ULL) >> 8) | ((*value & 0x0000FF0000000000ULL) >> 24) | ((*value & 0x00FF000000000000ULL) >> 40) | ((*value & 0xFF00000000000000ULL) >> 56); } } //------------------------------------------------------- void Popup::MessageField_initialize(MessageField *p_field) { p_field->id = 0x0000; p_field->type = POPUP_FIELD_DATA_TYPE_UNK; p_field->size = 0; } void Popup::MessageField_ntoh(MessageField *p_field) { size_t _offset = 0; p_field->id = ntohs(p_field->id); p_field->size = ntohl(p_field->size); p_field->type = ntohs(p_field->type); switch (p_field->type) { case POPUP_FIELD_DATA_TYPE_SHORT: for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned short)) { unsigned short *_val = (unsigned short *) &p_field->data[_offset]; *_val = ntohs(*_val); } break; case POPUP_FIELD_DATA_TYPE_LONG: for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned int)) { unsigned int *_val = (unsigned int *) &p_field->data[_offset]; *_val = ntohl(*_val); } break; case POPUP_FIELD_DATA_TYPE_LONG_LONG: for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned long long)) { unsigned long long *_val = (unsigned long long *) &p_field->data[_offset]; ntohll(_val); } break; case POPUP_FIELD_DATA_TYPE_UNK: case POPUP_FIELD_DATA_TYPE_STRING: case POPUP_FIELD_DATA_TYPE_BOOLEAN: default: break; } } void Popup::MessageField_hton(MessageField *p_field) { size_t _offset = 0; switch (p_field->type) { case POPUP_FIELD_DATA_TYPE_SHORT: for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned short)) { unsigned short *_val = (unsigned short *) &p_field->data[_offset]; *_val = htons(*_val); } break; case POPUP_FIELD_DATA_TYPE_LONG: for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned int)) { unsigned int *_val = (unsigned int *) &p_field->data[_offset]; *_val = htonl(*_val); } break; case POPUP_FIELD_DATA_TYPE_LONG_LONG: for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned long long)) { unsigned long long *_val = (unsigned long long *) &p_field->data[_offset]; htonll(_val); } break; case POPUP_FIELD_DATA_TYPE_STRING: case POPUP_FIELD_DATA_TYPE_UNK: case POPUP_FIELD_DATA_TYPE_BOOLEAN: default: break; } p_field->id = htons(p_field->id); p_field->size = htonl(p_field->size); p_field->type = htons(p_field->type); } void Popup::MessageField_dump(MessageField *p_field) { size_t _offset = 0; printf("BEGIN --> Dumping field (address=%p)\n" " id : 0x%hX\n" " size : %u bytes\n", p_field, p_field->id, p_field->size); switch(p_field->type) { case POPUP_FIELD_DATA_TYPE_SHORT: printf(" type : short\n"); for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned short)) { unsigned short *val = (unsigned short*) &p_field->data[_offset]; printf(" data : %hu\n", *val); } break; case POPUP_FIELD_DATA_TYPE_LONG: printf(" type : long\n"); printf(" data : "); for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned int)) { unsigned int *val = (unsigned int*) &p_field->data[_offset]; printf(" data : %u\n", *val); } printf("\n"); break; case POPUP_FIELD_DATA_TYPE_LONG_LONG: printf(" type : long long\n"); for (_offset = 0; _offset < p_field->size; _offset += sizeof(unsigned long long)) { unsigned long long *val = (unsigned long long*) &p_field->data[_offset]; #ifdef _WIN32 printf(" data : %lX\n", *val); #else printf(" data : %llX\n", *val); #endif } break; case POPUP_FIELD_DATA_TYPE_STRING: printf(" type : string\n"); printf(" data : %s\n", p_field->data); break; case POPUP_FIELD_DATA_TYPE_BOOLEAN: printf(" type : boolean\n"); printf(" data : %s\n", (p_field->data[0] == 0x01? "true" : "false")); break; case POPUP_FIELD_DATA_TYPE_UNK: default: printf(" type : unk (%0xhX)\n", p_field->type); printf(" data :\n"); Popup::Utils::dumpBuffer(&p_field->data[0], p_field->size); break; } printf("<--------- END\n"); } //------------------------------------------------------- void Popup::Message_initialize(Message *p_msg) { MessageHeader_initialize(&p_msg->header); } void Popup::Message_ntoh(Message *p_msg) { MessageHeader_ntoh(&p_msg->header); } void Popup::Message_hton(Message *p_msg) { MessageHeader_hton(&p_msg->header); }
C++
#include <string.h> #include "PopupSSL.hpp" #include "PopupBlowfishKeyMsg.hpp" #include "PopupUtilities.hpp" using namespace Popup; BlowfishKeyMsg::BlowfishKeyMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_BLOWFISH_KEY, POPUP_ENCRYPTION_RSA) { AbstractMessage::deserialize(p_message); } bool BlowfishKeyMsg::onSend() { // Add encrypted key to payload return payloadAddData(BlowfishKeyMsg::BLOWFISH_KEY, (const unsigned char*) sslContext->getBlowfishKey(), sizeof(BlowfishKey)); } bool BlowfishKeyMsg::onReceive() { if (fields.size() != 1) { return false; } else { const MessageField *_field = AbstractMessage::payloadGetField(BLOWFISH_KEY); if (_field == 0) { return false; } else if (_field->size != sizeof(BlowfishKey)) { return false; } else { memcpy(receivedKey, _field->data, sizeof(BlowfishKey)); return true; } } }
C++
/* * PopupMessages.hpp * * Created on: May 11, 2012 * Author: guillou */ #ifndef POPUPMESSAGES_HPP_ #define POPUPMESSAGES_HPP_ #include "PopupMessage.hpp" #include "PopupAbstractMessage.hpp" #include "PopupRsaPublicKeyMsg.hpp" #include "PopupBlowfishKeyMsg.hpp" #include "PopupLoginMsg.hpp" #include "PopupConnectionAck.hpp" #include "PopupUserUpdateMsg.hpp" #include "PopupUserMessage.hpp" #include "PopupUserMessageReaction.hpp" #include "PopupAttachmentMsg.hpp" #include "PopupCanvassSubmitMsg.hpp" #include "PopupCanvassVoteMsg.hpp" #include "PopupStatisticsUpdateMsg.hpp" #include "PopupThreadInvitationMsg.hpp" #include "PopupKeepAliveMsg.hpp" #endif /* POPUPMESSAGES_HPP_ */
C++
/* * PopupKeepAliveMsg.hpp * * Created on: Dec 2, 2012 * Author: guillou */ #ifndef POPUPKEEPALIVEMSG_HPP_ #define POPUPKEEPALIVEMSG_HPP_ #include "PopupAbstractMessage.hpp" namespace Popup { struct KeepAliveProbe : public AbstractMessage { KeepAliveProbe() : AbstractMessage(POPUP_MSG_TYPE_KEEPALIVE_PROBE) {} virtual ~KeepAliveProbe() {} }; struct KeepAliveAck : public AbstractMessage { KeepAliveAck() : AbstractMessage(POPUP_MSG_TYPE_KEEPALIVE_ACK) {} virtual ~KeepAliveAck() {} }; } #endif /* POPUPKEEPALIVEMSG_HPP_ */
C++
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "PopupAttachmentMsg.hpp" using namespace std; using namespace Popup; AttachmentMsg::AttachmentMsg(const Message *p_message) : AbstractMessage(POPUP_MSG_TYPE_ATTACHMENT), sendinfo(0) { AbstractMessage::deserialize(p_message); } bool AttachmentMsg::onSend() { bool _rc = true; _rc &= payloadAddLongLong(MSGID, sendinfo->messageID); _rc &= payloadAddLongLong(ATTACHMENTID, sendinfo->attachmentID); _rc &= payloadAddLong(TARGETS, sendinfo->targets); _rc &= payloadAddLong(FRAMENO, sendinfo->frameNo); _rc &= payloadAddLong(FRAMESIZE, frameSize); _rc &= payloadAddFromFile(RAWDATA, sendinfo->file, frameSize); // In case this is the first frame, we send a few more information if (_rc && sendinfo->frameNo == 1) { _rc &= payloadAddLong(TOTALSIZE, sendinfo->totalSize); _rc &= payloadAddString(FILENAME, PopupUtils::basename(sendinfo->filepath)); _rc &= payloadAddLong(NBFRAMES, sendinfo->totalNbFrames); _rc &= payloadAddLongLong(CHECKSUM, sendinfo->checksum); } return _rc; } bool AttachmentMsg::onReceive() { bool _rc = true; _rc &= payloadGetLongLong(MSGID, recvinfo.messageID); _rc &= payloadGetLongLong(ATTACHMENTID, recvinfo.attachmentID); _rc &= payloadGetLong(TARGETS, recvinfo.targets); _rc &= payloadGetLong(FRAMENO, recvinfo.frameNo); _rc &= payloadGetLong(FRAMESIZE, frameSize); if (_rc && recvinfo.frameNo == 1) { _rc &= payloadGetLong(TOTALSIZE, recvinfo.totalSize); _rc &= payloadGetString(FILENAME, recvinfo.filepath); _rc &= payloadGetLong(NBFRAMES, recvinfo.totalNbFrames); if (!payloadGetLongLong(CHECKSUM, recvinfo.checksum)) { recvinfo.checksum = 0; } } return _rc; } bool AttachmentMsg::getRawData(PopupUtils::FileStream *p_file) const { return payloadDumpFieldToFile(RAWDATA, p_file); }
C++
#ifndef POPUPLOGINMSG_HPP_ #define POPUPLOGINMSG_HPP_ #include "PopupAbstractMessage.hpp" namespace Popup { struct LoginMsg : public AbstractMessage { enum { LOGIN = 0xEBA1, PASSWORD = 0xC0C0, CREATEUSER = 0xCACA }; //! Constructor used in order to send login request LoginMsg(const std::string & p_login, const std::string & p_password, bool p_createUser = false) : AbstractMessage(POPUP_MSG_TYPE_LOGIN, POPUP_ENCRYPTION_BLOWFISH), login(p_login), password(p_password), createUser(p_createUser) {} //! Constructor used in order to received a login request LoginMsg(const Message *p_message); ~LoginMsg() {} //!@Override bool onSend(); //!@Override bool onReceive(); inline const std::string & getLogin() const { return login; } inline const std::string & getPassword() const { return password; } inline bool isCreateRequest() const { return createUser; } private: std::string login; std::string password; bool createUser; }; } #endif // POPUPLOGINMSG_HPP_
C++
#include <sstream> #include "PopupLoggerUI.hpp" #include "PopupUserUpdateMsg.hpp" using namespace std; using namespace Popup; using namespace PopupUtils; UserUpdateMsg::UserUpdateMsg(const Message *p_message, const string & p_resourcePath) : AbstractMessage(POPUP_MSG_TYPE_USER_UPDATE), resourcePath(p_resourcePath) { AbstractMessage::deserialize(p_message); } bool UserUpdateMsg::onSend() { // Add user ID in any case bool _rc = payloadAddLong(USERID, getID()); // Add nickname if (_rc) { if ((updateMask & POPUP_USER_FIELD_NICKNAME) != 0) { _rc = payloadAddString(USERNICKNAME, getNickname()); } } // Add avatar if (_rc) { if ((updateMask & POPUP_USER_FIELD_AVATAR) != 0) { bool _avatarOk = AbstractMessage::payloadAddFileContent( AVATAR_RAW_DATA, getAvatar()); if (_avatarOk) { AbstractMessage::payloadAddString( AVATAR_FILENAME, PopupUtils::basename(getAvatar())); } // If we failed to add avatar, as it was the only element to update // this is really an error!! if (!_avatarOk && updateMask == POPUP_USER_FIELD_AVATAR) { _rc = false; } } } // Add mode if (_rc) { if ((updateMask & POPUP_USER_FIELD_MODE) != 0) { _rc = payloadAddShort(MODE, getMode()); } } // Add health if (_rc) { if ((updateMask & POPUP_USER_FIELD_HEALTH) != 0) { _rc = payloadAddBoolean(HEALTH, isAlive()); } } return _rc; } bool UserUpdateMsg::onReceive() { string _avatarFilename; bool _rc = payloadGetLong(USERID, id); stringstream _path; if (_rc) { // Reset update mask updateMask = 0x0000; if (payloadGetString(USERNICKNAME, nickname)) { updateMask |= POPUP_USER_FIELD_NICKNAME; } if (payloadGetString(AVATAR_FILENAME, _avatarFilename)) { _path << resourcePath << "/clients_rc/" << id; if (PopupUtils::mkdir(_path.str(), 0755)) { _path << "/" << _avatarFilename; if (payloadDumpFieldToFile(AVATAR_RAW_DATA, _path.str())) { avatar = _path.str(); updateMask |= POPUP_USER_FIELD_AVATAR; } } else { error("OOOopps!! Failed to create dir %s\n", _path.str().c_str()); } } unsigned short _mode; if (payloadGetShort(MODE, _mode)) { mode = (UserMode) _mode; updateMask |= POPUP_USER_FIELD_MODE; } if (payloadGetBoolean(HEALTH, alive)) { updateMask |= POPUP_USER_FIELD_HEALTH; } } return _rc; } unsigned short UserUpdateMsg::getUpdateMask() const { return updateMask; } void UserUpdateMsg::dump() const { trace("[User %d updated]", getID()); trace("Update mask = %04X", updateMask); if ((updateMask & POPUP_USER_FIELD_NICKNAME) != 0) { trace("Nickname = %s", getNickname().c_str()); } if ((updateMask & POPUP_USER_FIELD_AVATAR) != 0) { trace("Avatar = %s", getAvatar().c_str()); } if ((updateMask & POPUP_USER_FIELD_MODE) != 0) { trace("Mode = %d", getMode()); } if ((updateMask & POPUP_USER_FIELD_HEALTH) != 0) { trace("isAlive = %d", isAlive()); } }
C++
#ifndef __POPUP_LIB_TYPES_H__ #define __POPUP_LIB_TYPES_H__ #include <string> #include <vector> #include <set> #include <map> #include <stdint.h> #include <PopupOSAL.hpp> #define POPUP_MSG_SPLIT_SIZE 1024 namespace Popup { #ifdef __GNUC__ #define __unused__ __attribute__ ((unused)) #endif typedef enum { POPUP_CONNECTION_SUCCESS, POPUP_CONNECTION_ERR_UNKNOWN, POPUP_CONNECTION_ERR_SERVER_DOWN, POPUP_CONNECTION_ERR_HANDSHAKE_FAILED, POPUP_CONNECTION_ERR_USER_ALREADY_CONNECTED, POPUP_CONNECTION_ERR_SQLITE, POPUP_CONNECTION_ERR_UNKNOWN_USER, POPUP_CONNECTION_ERR_INVALID_PASSWORD, POPUP_CONNECTION_ERR_EMPTY_LOGIN, POPUP_CONNECTION_ERR_LOGIN_ALREADY_EXISTS, POPUP_CONNECTION_ERR_LISTEN_LOOP_EXITED } ConnectionEcode; typedef enum { POPUP_MODE_MUTED = 0, POPUP_MODE_DEFAULT, POPUP_MODE_PROMPT, POPUP_MODE_TEXTONLY, POPUP_NB_MODES } UserMode; typedef enum { POPUP_USER_FIELD_NICKNAME = 0x0001, POPUP_USER_FIELD_AVATAR = 0x0002, POPUP_USER_FIELD_MODE = 0x0004, POPUP_USER_FIELD_HEALTH = 0x0008, POPUP_USER_FIELD_MAX = POPUP_USER_FIELD_HEALTH, POPUP_USER_FIELD_ALL = 0xFFFF } UserField; typedef enum { POPUP_RATE_UNKNOWN = 0x0000, POPUP_RATE_LIKE = 0x0001, POPUP_RATE_DONTLIKE = 0x0002, POPUP_RATE_POETRY = 0x0004, POPUP_RATE_FUCKYOU = 0x0008, POPUP_RATE_ITEM_MAX = POPUP_RATE_FUCKYOU } UserRateItem ; typedef unsigned long long /*uint64_t*/ ThreadID; typedef unsigned long long /*uint64_t*/ MessageID; typedef unsigned long long /*uint64_t*/ AttachmentID; typedef unsigned int /*uint32_t*/ UserID; typedef unsigned long long /*uint64_t*/ CanvassID; typedef unsigned int /*uint32_t*/ SessionID; struct User { #define BAD_AVATAR "badavatar" #define BAD_LOGIN "badlogin" #define BAD_NICKNAME "badnickname" User() : id(-1), login(BAD_LOGIN), alive(false), nickname(BAD_NICKNAME), avatar(BAD_AVATAR), mode(POPUP_MODE_DEFAULT) {} User(const User & p_user) : id(p_user.getID()), login(p_user.getLogin()), alive(p_user.isAlive()), nickname(p_user.getNickname()), avatar(p_user.getAvatar()), mode(p_user.getMode()) {} virtual ~User() {} inline UserID getID() const { return id; } inline const std::string & getLogin() const { return login; } inline const std::string & getNickname() const { return nickname; } inline const std::string & getAvatar() const { return avatar; } inline UserMode getMode() const { return mode; } inline bool isAlive() const { return alive; } inline void setNickname(const std::string & p_nickname) { nickname = p_nickname; } inline void setAvatar(const std::string & p_avatar) { avatar = p_avatar; } inline void setMode(UserMode p_mode) { mode = p_mode; } inline void setAlive(bool p_isAlive) { alive = p_isAlive; } void update(const User & p_user, unsigned short p_updateMask); UserID id; std::string login; bool alive; std::string nickname; std::string avatar; UserMode mode; std::map<unsigned short, unsigned int> statistics; std::vector<unsigned short> records; }; typedef std::set<UserID> UserList; typedef std::set<UserID> UserSet; typedef std::map<UserID, User*> UserMap; typedef std::map<std::string, User*> UserLoginMap; const UserList EmptyUserList; const User NullUser; //============================================================================ // Popup user message //============================================================================ typedef std::vector<std::string> AttachmentList; struct UserMessage { UserMessage(const std::string & p_text = "", const std::string & p_title = "") : msgID(0), senderID(0), threadID(0), text(p_text), title(p_title) {} UserMessage(const UserMessage & p_msg) : msgID(p_msg.msgID), senderID(p_msg.senderID), threadID(p_msg.threadID), targets(p_msg.targets), URLs(p_msg.URLs), files(p_msg.files), text(p_msg.text), title(p_msg.title) {} //! Message ID MessageID msgID; //! Sender UserID senderID; //! Thread ID ThreadID threadID; //! Receivers UserList targets; //! Attached URLs AttachmentList URLs; //! Attached files AttachmentList files; //! Text message std::string text; //! Title std::string title; }; //============================================================================ // Popup user message reaction (like, nice, ... ) //============================================================================ struct RateUserMessage { RateUserMessage(UserRateItem p_reaction = POPUP_RATE_UNKNOWN, UserID p_reactionSenderID = 0, const MessageID & p_sourceMessage = 0, const ThreadID & p_threadID = 0, UserID p_sourceMessageSender = 0, const UserList & p_targets = EmptyUserList, bool p_isUndo = false) : rateItem(p_reaction), rateSenderID(p_reactionSenderID), msgID(p_sourceMessage), threadID(p_threadID), msgSenderID(p_sourceMessageSender), targets(p_targets), isUndo(p_isUndo) {} RateUserMessage(const RateUserMessage & p_reaction) : rateItem(p_reaction.rateItem), rateSenderID(p_reaction.rateSenderID), msgID(p_reaction.msgID), threadID(p_reaction.threadID), msgSenderID(p_reaction.msgSenderID), targets(p_reaction.targets), isUndo(p_reaction.isUndo) {} UserRateItem rateItem; UserID rateSenderID; MessageID msgID; ThreadID threadID; UserID msgSenderID; UserList targets; bool isUndo; }; //============================================================================ // Thread Invitation //============================================================================ struct ThreadInvitation { ThreadInvitation(const ThreadID & p_threadID = 0, const std::string & p_threadTitle = "") : threadID(p_threadID), threadTitle(p_threadTitle), inviter(0) {} // ID ThreadID threadID; // Title std::string threadTitle; // Invited users' IDs UserList invitedUsers; // Invitation sender (will be set automatically when message will be sent) UserID inviter; // CC users already in the thread UserList cc; }; //============================================================================ // Popup canvass //============================================================================ typedef std::vector<std::string> ChoiceList; typedef std::vector<unsigned short> ChoiceIndexList; struct Canvass { Canvass() : canvassID(0), senderID(0), question(""), timeout(0), isAnonymous(false), allowMultiSelection(false) {} Canvass(const Canvass & p_canvass) : canvassID(p_canvass.canvassID), senderID(p_canvass.senderID), targets(p_canvass.targets), question(p_canvass.question), choices(p_canvass.choices), timeout(p_canvass.timeout), isAnonymous(p_canvass.isAnonymous), allowMultiSelection(p_canvass.allowMultiSelection) {} //! Canvass ID CanvassID canvassID; //! Sender UserID senderID; //! Receivers UserList targets; //! Question std::string question; //! Choices ChoiceList choices; //! Timeout unsigned short timeout; //! Anomymous bool isAnonymous; //! Multi selection allowed bool allowMultiSelection; }; struct Vote { Vote() : canvassID(0), voterID(0) {} Vote(const Vote & p_vote) : canvassID(p_vote.canvassID), voterID(p_vote.voterID), choices(p_vote.choices) {} //! Canvass ID CanvassID canvassID; //! Voter UserID voterID; //! Selected choice index ChoiceIndexList choices; }; //============================================================================ // Transfer information //============================================================================ typedef enum { POPUP_DIRECTION_IN, POPUP_DIRECTION_OUT } Direction; struct FileTransfer { Direction direction; PopupUtils::FileStream *file; AttachmentID attachmentID; MessageID messageID; std::string filepath; unsigned int totalSize; unsigned int nbTransferred; unsigned int nbRemaining; // Constructor used by a file receiver FileTransfer(Direction p_direction = POPUP_DIRECTION_IN, MessageID p_messageID = 0, AttachmentID p_attachmentID = 0, const std::string & p_filepath = "", PopupUtils::FileStream *p_file = 0, unsigned int p_totalSize = 0) : direction(p_direction), file(p_file), attachmentID(p_attachmentID), messageID(p_messageID), filepath(p_filepath), totalSize(p_totalSize), nbTransferred(0), nbRemaining(p_totalSize) {} virtual ~FileTransfer() {} }; //============================================================================ // Statistics information //============================================================================ struct UserStatistics : std::map<UserRateItem, unsigned int> { UserStatistics() : recordMask(0) {} void set(UserRateItem, unsigned int p_value, bool p_isRecord = false); bool get(UserRateItem p_item, unsigned int & p_value, bool & p_isRecord) const; bool isRecordman(UserRateItem p_item) const; unsigned short itemsMask() const; void dump() const; //! Bit field telling, for each item, if this is or not the record! unsigned short recordMask; }; } #endif // __POPUP_LIB_TYPES_H__
C++
#ifndef __POPUP_DATABASE_UI_HPP__ #define __POPUP_DATABASE_UI_HPP__ #include <string> #include <PopupLibTypes.hpp> namespace Popup { struct DatabaseUI { virtual ~DatabaseUI() {} struct StatisticItemUpdateResult { StatisticItemUpdateResult() : newItemValue(0), isNewRecord(false), previousRecordman(0), previousRecordValue(0) {} unsigned int newItemValue; bool isNewRecord; UserID previousRecordman; unsigned int previousRecordValue; }; virtual bool getAllUsers(UserLoginMap & p_users) = 0; virtual ConnectionEcode newUser(const std::string & p_login, const std::string & p_password, const std::string & p_nickname, const std::string & p_avatar, User **p_user, std::string & p_message) = 0; //! Tells if a user connection is allowed or not. //! //! \param[in] p_login //! \param[in] p_password //! \param[out] p_errMessage //! //! \return True if the user connection is allowed. //! virtual bool authenticate(const std::string & p_login, const std::string & p_password, std::string & p_message) = 0; virtual bool updateNickname(User *p_user, const std::string & p_newNickname, std::string & p_message) = 0; virtual bool updateAvatar(User *p_user, const std::string & p_newAvatar, std::string & p_message) = 0; virtual bool updateUserRates(UserID p_userID, UserRateItem p_itemKey, StatisticItemUpdateResult & p_updateResult, std::string & p_message) = 0; virtual bool getUserStatitics(UserID p_userID, UserStatistics & p_stats, std::string & p_message) = 0; }; } #endif // __POPUP_DATABASE_UI_HPP__
C++
#ifndef __POPUP_CLIENT_UI_HPP__ #define __POPUP_CLIENT_UI_HPP__ #include <string> #include "PopupLibTypes.hpp" namespace Popup { //============================================================================ // API which a client UI shall implement //============================================================================ //! This class defines the API which a client user interface //! shall implement. struct ClientUI { virtual ~ClientUI() {} //! //! Event raised to notify client UI when a message comes along with //! an attached media file which might take time to be fully received. //! When media is completely received, a last event is raised, with //! (p_totalSize = p_receivedSize). //! //! \param[in] p_file Media file being received //! \param[in] p_totalSize Total size (in bytes) of the media file //! \param[in] p_receivedSize Total size (in bytes) already received. //! virtual void onFileTransferUpdate(const Popup::FileTransfer & p_transfer) = 0; //! //! Event raised when a message has been received //! and is ready to be displayed //! virtual void onMessageReceived(const UserMessage & p_message) = 0; virtual void onMessageSent(const UserMessage & p_message) = 0; //! //! Event raised when a message reaction has been received //! virtual void onMessageReactionReceived(const RateUserMessage & p_reaction) = 0; //! //! Event raised when a message reaction has been received //! virtual void onOpinionRequested(const Canvass & p_canvass) = 0; //! //! A vote had been submitted by a user //! virtual void onVoteReceived(const Vote & p_vote) = 0; //! //! An invitation to an existing thread has been received virtual void onInvitationReceived(const ThreadInvitation & p_invitation) = 0; //! //! Event raised when connection status changed (up or down). //! //! \param[in] p_myself PopupUser Tells if client if connected or not //! virtual void onConnectionUpdate(bool p_connected, const User & p_myself = NullUser, SessionID p_sessionID = 0) = 0; //! //! Event raised when a user info has been updated //! (including user disconnection) //! //! \param[in] p_user Profile of the user which has been updated //! \param[in] p_updateMask Bit field telling which fields have been updated //! \param[in] p_isNewUser Tells if this user has just connected //! virtual void onUserUpdate(const User & p_user, unsigned short p_updateMask, bool p_isNewUser) = 0; //! //! Event raise when statistics are updated //! virtual void onUserStatisticsUpdate(UserID p_userID, UserStatistics & p_stats) = 0; //! //! \return The temporary directory which must be used in order //! to save the media files which are sent by client's friends. //! virtual std::string getTemporaryDir() = 0; //! //! \return The resource directory where user private file are stored //! virtual std::string getResourceDir() = 0; }; //============================================================================ // API of a Popup client //============================================================================ struct Client { virtual ~Client() {} //! Connects to the specified server, using specified login and password virtual ConnectionEcode connect(const std::string & p_server, unsigned short p_port, const std::string & p_login, const std::string & p_password, bool p_register = false) = 0; //! Disconnects from the client virtual bool disconnect() = 0; //! Send the specified message over the network //! \return True upon successful completion //! virtual bool sendMessage(UserMessage & p_message) = 0; //! Send the specified message over the network //! \return True upon successful completion //! virtual bool sendMessageReaction(const RateUserMessage & p_message) = 0; //! Send vote of the user virtual bool sendVote(const Vote & p_vote) = 0; //! Submits a new opinion request //! \return True upon successful completion //! virtual bool submitCanvass(Canvass & p_canvass) = 0; //! Tells server that we've modified our profile virtual bool notifyUserUpdate(const User *p_myself, unsigned short p_updateMask) = 0; //! Sends an invitation to join an existing thread virtual bool sendInvitation(const ThreadInvitation & p_invitation) = 0; //! Connects to the server with specific connection parameters, and //! receives user's profile sent by server //! \return A brand new client instance if connection to server succeeds, //! 0 otherwise. static Client *newClient(ClientUI *p_clientUI); }; } #endif // __POPUP_CLIENT_UI_HPP__
C++
#ifndef __POPUP_SERVER_UI_HPP__ #define __POPUP_SERVER_UI_HPP__ #include "PopupLibTypes.hpp" #include "PopupLoggerUI.hpp" #include "PopupDatabaseUI.hpp" namespace Popup { //============================================================================ // API which a server UI shall implement //============================================================================ //! This class defines the API which a client user interface //! shall implement. struct ServerUI { virtual ~ServerUI() {} //! virtual void onClientConnected(const User & p_client) = 0; //! virtual void onClientDisconnected(const User & p_client) = 0; //! //! Event raised when the PopupServer is about to be destroyed. //! virtual void onDestroy() = 0; //! //! \return The temporary directory which must be used in order //! to save the users avatar files. //! virtual std::string getResourceDir() = 0; //! //! \return The default avatar path //! virtual std::string getDefaultAvatar() = 0; }; //============================================================================ // API of a Popup server //============================================================================ struct Server { virtual ~Server() {} static Server *newServer(unsigned short p_port, unsigned short p_maxNbConnections, DatabaseUI *p_database, ServerUI *p_serverUI); virtual void run() = 0; }; } #endif // __POPUP_SERVER_UI_HPP__
C++
#include <PopupDefaultLogger.hpp> #include <string> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/rand.h> #include <openssl/blowfish.h> #include <openssl/err.h> #include <string.h> using namespace Popup; using namespace std; #define NULL_IVEC { 0, 0, 0, 0, 0, 0, 0, 0 } static PopupDefaultLogger logger; int main(int argc, char *argv[]) { unsigned char *rawpubkey = NULL; unsigned char *rawpubkey2 = NULL; const char *salt = "Iu{àç)àðkzokfsesmdfçsà=q=zerç;'zM%zpo)0a82À=X_&àçuca,éM'c;qie(c,vmey(çyw<s]+&~éé"; const char *data = "bonjour, comment vas-tu? Ben moi ca va pas mal du tout, disons qu'on fait aller quoi!! Bon en tout cas, je te souhaite plein de bonnes choses!! bonjour, comment vas-tu? Ben moi ca va pas mal du tout, disons qu'on fait aller quoi!! Bon en tout cas, je te souhaite plein de bonnes choses!! bonjour, comment vas-tu? Ben moi ca va pas mal du tout, disons qu'on fait aller quoi!! Bon en tout cas, je te souhaite plein de bonnes choses!! bonjour, comment vas-tu? Ben moi ca va pas mal du tout, disons qu'on fait aller quoi!! Bon en tout cas, je te souhaite plein de bonnes choses!! bonjour, comment vas-tu? Ben moi ca va pas mal du tout, disons qu'on fait aller quoi!! Bon en tout cas, je te souhaite plein de bonnes choses!!"; int datasize = strlen(data)+1; char error[256]; BIGNUM *oBigNbr = BN_new(); RSA *key = RSA_new(); RAND_seed(salt, strlen(salt)); //------------- KeyGen BN_set_word(oBigNbr, RSA_F4); RSA_generate_key_ex(key, 1024, oBigNbr, NULL); // Write public key to a buffer int size = i2d_RSAPublicKey(key, &rawpubkey); for (int i = 0; i < size; i+=2) { if (i % 64 == 0) { printf("\n"); } printf("%02hx", rawpubkey[i]); } // Load the public key from the buffer unsigned char *pkey = new unsigned char(1024);// (unsigned char*) malloc(1024);//new unsigned char(1024); memcpy((unsigned char*) pkey, rawpubkey, size); // Read key somewhere else RSA *key2 = d2i_RSAPublicKey(NULL, (const unsigned char**) &pkey, size); //free(pkey); size = i2d_RSAPublicKey(key2, &rawpubkey2); for (int i = 0; i < size; i+=2) { if (i % 64 == 0) { printf("\n"); } printf("%02hx", rawpubkey2[i]); } //------------- Codage RSA printf("\n"); printf("rsasize1 = %d\n", RSA_size(key)); printf("rsasize2 = %d\n", RSA_size(key2)); int blocsize = RSA_size(key); int buffsize = blocsize * (datasize / (2*blocsize) + 1); printf("ALlocated=%d\n", buffsize); unsigned char buffer[1024]; // = (unsigned char*) malloc(buffsize); int encodedsize = 0; int remainingSize = datasize; for (size_t offsetin = 0, offsetout = 0; offsetin < datasize; offsetin += 100, offsetout += blocsize) { int size = 0; if (remainingSize < 100) { size = remainingSize; } else { size = 100; } remainingSize -= size; encodedsize += RSA_public_encrypt(size, (const unsigned char*) &data[offsetin], (unsigned char*) &buffer[offsetout], key2, RSA_PKCS1_PADDING); if (encodedsize == -1) { ERR_error_string(ERR_get_error(), &error[0]); } } printf("Encoded Message = \n"); for (size_t i = 0; i < encodedsize; i+=2) { if (i % 64 == 0) { printf("\n"); } printf("%02hx", buffer[i]); } //--------- Decodage RSA unsigned char decodedMessage[1024]; // = (unsigned char*) malloc(1024); int decsize = 0; int totalsize = 0; for (size_t offsetin = 0, offsetout = 0; offsetin < encodedsize; offsetin += RSA_size(key), offsetout = totalsize) { decsize = RSA_private_decrypt(RSA_size(key), (const unsigned char*)&buffer[offsetin], &decodedMessage[offsetout], key, RSA_PKCS1_PADDING); totalsize += decsize; } printf("\nTotalsize decoded = %d\n", totalsize); printf("Decoded message = \n%s\n", (char*) decodedMessage); //------------ Encodage blowfish static char bfkeyascii[128] = "abcdefghijklmnopqrstuvwxyz1234567abcdefghijklmnopqrstuvwxyz1234567abcdefghijklmnopqrstuvwxyz1234567abcdefghijklmnopqrstuvwxyz16"; BF_KEY bfkey; int alignedDataSize = sizeof(BF_LONG) * ((datasize+sizeof(BF_LONG)-1)/sizeof(BF_LONG)); unsigned char *datacopy = (unsigned char*) malloc(datasize); // unsigned char *datadec = (unsigned char*) malloc(datasize); printf("alignedsize=%d\n", alignedDataSize); memset(datacopy, 0, alignedDataSize); memcpy(datacopy, data, datasize); // memset(datadec, 0, datasize); printf("AVANT ENCRYPT\n"); for (size_t i = 0; i < datasize; i+=2) { if (i % 64 == 0) { printf("\n"); } printf("%02hx", datacopy[i]); } BF_set_key(&bfkey, 128, (unsigned char *)bfkeyascii); unsigned char ivec[8] = NULL_IVEC; BF_cbc_encrypt((const unsigned char*)datacopy, datacopy, datasize, (const BF_KEY*)&bfkey, ivec, BF_ENCRYPT); //for (int i = 0; i < datasize; i += sizeof(BF_LONG)) { // BF_encrypt((BF_LONG*)&datacopy[i], &bfkey); //} printf("\nAPRES ENCRYPT\n"); for (size_t i = 0; i < datasize; i+=2) { if (i % 64 == 0) { printf("\n"); } printf("%02hx", datacopy[i]); } //------------ Decodage blowfish unsigned char ivec2[8] = NULL_IVEC; BF_cbc_encrypt(datacopy, datacopy, datasize, (const BF_KEY*)&bfkey, ivec2, BF_DECRYPT); //for (int i = 0; i < datasize; i += sizeof(BF_LONG)) { // BF_decrypt((BF_LONG*)&datacopy[i], &bfkey); //} printf("APRES DECRYPT\n"); for (size_t i = 0; i < datasize; i+=2) { if (i % 64 == 0) { printf("\n"); } printf("%02hx", datacopy[i]); } printf("%s\n", datacopy); BN_free(oBigNbr); RSA_free(key); //RSA_free(key2); return 0; }
C++
#include <PopupDefaultLogger.hpp> #include <stdarg.h> #include <stdio.h> using namespace Popup; struct MyPopupLogger : public PopupLoggerUI { void appendLog(enum PopupLogLevel p_level, const char *p_format, ...); }; void MyPopupLogger::appendLog(enum PopupLogLevel p_level, const char *p_format, ...) { va_list _args; char log[1024]; va_start(_args, p_format); vsprintf(log, p_format, _args); printf("The trace level is %d : Message=[%s]\n", p_level, log); va_end(_args); } int main(int argc, char *argv[]) { PopupDefaultLogger logger; logger.appendLog(POPUP_LOG_TRACE, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); logger.appendLog(POPUP_LOG_INFO, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); logger.appendLog(POPUP_LOG_WARNING, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); logger.appendLog(POPUP_LOG_ERROR, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); logger.appendLog(POPUP_LOG_CRITICAL, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); MyPopupLogger mylogger; mylogger.appendLog(POPUP_LOG_TRACE, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); mylogger.appendLog(POPUP_LOG_INFO, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); mylogger.appendLog(POPUP_LOG_WARNING, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); mylogger.appendLog(POPUP_LOG_ERROR, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); mylogger.appendLog(POPUP_LOG_CRITICAL, "Function:%s, Line:%d ", __FUNCTION__, __LINE__); return 0; }
C++
#include <iostream> #include <PopupClientUI.hpp> #include <PopupDefaultLogger.hpp> #include <PopupOSAL.hpp> #include <stdlib.h> using namespace std; using namespace Popup; static Client *client; struct MaquiClient : public ClientUI { LoggerUI *logger; MaquiClient(LoggerUI *p_logger) : logger(p_logger) {} //! //! Event raised to notify client UI when a message comes along with //! an attached media file which might take time to be fully received. //! When media is completely received, a last event is raised, with //! (p_totalSize = p_receivedSize). //! //! \param[in] p_file Media file being received //! \param[in] p_totalSize Total size (in bytes) of the media file //! \param[in] p_receivedSize Total size (in bytes) already received. //! virtual void onFileTransferUpdate(__unused__ const FileTransfer *p_tranfer) { /*AttachmentRecvProgressUpdate(__unused__ AttachmentID p_id, __unused__ unsigned long senderId, const std::string & p_attachment, size_t p_totalSize, size_t p_receivedSize) { printf("\r%s [%03d%%] - %dkB", p_attachment.c_str(), int(((float)p_receivedSize/(float)p_totalSize)*100.0), (p_receivedSize/1024)); if (p_totalSize == p_receivedSize) { printf("\n"); } } //! //! Event raised to notify client UI when a message comes along with //! an attached media file which might take time to be fully received. //! When media is completely received, a last event is raised, with //! (p_totalSize = p_receivedSize). //! //! \param[in] p_file Media file being received //! \param[in] p_totalSize Total size (in bytes) of the media file //! \param[in] p_receivedSize Total size (in bytes) already received. //! virtual void onAttachmentSendProgressUpdate(AttachmentID p_id, const std::string & p_attachment, size_t p_totalSize, size_t p_receivedSize) { printf("\r%s [%03d%%] - %dkB", p_attachment.c_str(), int(((float)p_receivedSize/(float)p_totalSize)*100.0), (p_receivedSize/1024)); if (p_totalSize == p_receivedSize) { printf("\n"); } */ } void onMessageReactionReceived(const UserMessageReaction & p_reaction) {} //! //! Event raised when a message has been received //! and is ready to be displayed //! virtual void onMessageSent(const UserMessage & p_message) {} virtual void onMessageReceived(const UserMessage & p_message) { logger->appendLog(POPUP_LOG_TRACE, "Received a message from %d:\n" "%s", p_message.senderID, p_message.text.c_str()); AttachmentList::const_iterator _it; for (_it = p_message.URLs.begin(); _it != p_message.URLs.end(); _it++) { logger->appendLog(POPUP_LOG_TRACE, " URL: %s", _it->c_str()); } for (_it = p_message.files.begin(); _it != p_message.files.end(); _it++) { logger->appendLog(POPUP_LOG_TRACE, " file: %s", _it->c_str()); } } virtual void onMessageSent(__unused__ unsigned short messageId) {} //! //! Event raised when connection status has changed //! //! \param[in] p_isConnected Tells if client if connected or not //! virtual void onConnectionUpdate(bool p_connected, User *p_myself) { if (p_connected) { logger->appendLog(POPUP_LOG_TRACE, "Connection succeeded. My ID is : %d", p_myself->getID()); } } //! //! Event raised when any user profile has been updated //! //! \param[in] p_user Profile of the user which has been updated //! \param[in] p_updatedMask Bit field telling which fields have been updated //! virtual void onUserUpdate(const User *p_user, unsigned short p_updateMask, bool p_isNewUser) { logger->appendLog(POPUP_LOG_TRACE, "[User %d %s]", p_user->getID(), (p_isNewUser? "connected" : "updated")); if ((p_updateMask & POPUP_USER_FIELD_NICKNAME) != 0) { logger->appendLog(POPUP_LOG_TRACE, "Nickname = %s", p_user->getNickname().c_str()); } if ((p_updateMask & POPUP_USER_FIELD_AVATAR) != 0) { logger->appendLog(POPUP_LOG_TRACE, "Avatar = %s", p_user->getAvatar().c_str()); } if ((p_updateMask & POPUP_USER_FIELD_MODE) != 0) { logger->appendLog(POPUP_LOG_TRACE, "Mode = %d", p_user->getMode()); } if ((p_updateMask & POPUP_USER_FIELD_HEALTH) != 0) { logger->appendLog(POPUP_LOG_TRACE, "isAlive = %d", p_user->isAlive()); } if (p_isNewUser && p_user->getID() == 1) { UserMessage message; message.text = "bonjour connard!!! Je te prends, je te retourne, et je t'encule"; message.targets.push_back(p_user->getID()); message.URLs.push_back("http://www.google.fr"); message.URLs.push_back("http://stackoverflow.com/questions/704204/what-data-structure-is-behind-fd-set-and-fd-isset-when-working-with-sockets-in-c"); message.files.push_back("/home/guillou/Photos/IMG_1302.JPG"); message.files.push_back("/home/guillou/Photos/IMG_1306.JPG"); message.files.push_back("/media/DOCUMENTS/Mes vidéos/Humour/Laurent Gerra Flingue La Tele.avi"); (void) client->sendMessage(message); } } //! //! Event raised when the PopupClient is about to be destroyed. //! virtual void onDestroy() {} //! //! \return The temporary directory which must be used in order //! to save the users avatar files. //! virtual std::string getTemporaryDir() { string _path = "/tmp/popup/tmp"; PopupOSAL::mkdir(_path, 0755); return _path; } //! //! \return The temporary directory which must be used in order //! to save the users avatar files. //! virtual std::string getResourceDir() { string _path = "/tmp/popup/resources"; PopupOSAL::mkdir(_path, 0755); return _path; } }; static void closeAll(__unused__ int signal) { client->disconnect(); exit(0); } int main(__unused__ int argc, char *argv[]) { DefaultLogger logger; client = Client::newClient(new MaquiClient(&logger), &logger); signal(SIGINT, closeAll); signal(SIGTERM, closeAll); signal(SIGABRT, closeAll); while (true) { if (client->connect(argv[1], (unsigned short) atoi(argv[2]), argv[3], argv[4]) != POPUP_CONNECTION_SUCCESS) { client->connect(argv[1], (unsigned short) atoi(argv[2]), argv[3], argv[4], true); } sleep(2); } logger.appendLog(POPUP_LOG_INFO, "Exited"); return 0; }
C++
#include "stdafx.h" #include "TrayMenuBtn.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTrayMenuBtn BEGIN_MESSAGE_MAP(CTrayMenuBtn, CWnd) ON_WM_PAINT() END_MESSAGE_MAP() CTrayMenuBtn::CTrayMenuBtn() { m_bBold = false; m_bMouseOver = false; m_bNoHover = false; m_bUseIcon = false; m_bParentCapture = false; m_nBtnID = rand(); m_sIcon.cx = 0; m_sIcon.cy = 0; m_hIcon = NULL; (void)m_strText; (void)m_cfFont; } CTrayMenuBtn::~CTrayMenuBtn() { if (m_hIcon) DestroyIcon(m_hIcon); } void CTrayMenuBtn::OnPaint() { CPaintDC dc(this); // device context for painting CRect rClient; GetClientRect(rClient); CDC MemDC; MemDC.CreateCompatibleDC(&dc); CBitmap MemBMP, *pOldBMP; MemBMP.CreateCompatibleBitmap(&dc, rClient.Width(), rClient.Height()); pOldBMP = MemDC.SelectObject(&MemBMP); CFont *pOldFONT = NULL; if (m_cfFont.GetSafeHandle()) pOldFONT = MemDC.SelectObject(&m_cfFont); BOOL bEnabled = IsWindowEnabled(); if (m_bMouseOver && bEnabled) { FillRect(MemDC.m_hDC, rClient, GetSysColorBrush(COLOR_HIGHLIGHT)); MemDC.SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT)); } else { FillRect(MemDC.m_hDC, rClient, GetSysColorBrush(COLOR_BTNFACE)); MemDC.SetTextColor(GetSysColor(COLOR_BTNTEXT)); } int iLeftOffset = 0; if (m_bUseIcon) { MemDC.DrawState(CPoint(2, rClient.Height()/2 - m_sIcon.cy/2), CSize(16, 16), m_hIcon, DST_ICON | DSS_NORMAL, (CBrush *)NULL); iLeftOffset = m_sIcon.cx + 4; } MemDC.SetBkMode(TRANSPARENT); CRect rText(0, 0, 0, 0); MemDC.DrawText(m_strText, rText, DT_CALCRECT | DT_SINGLELINE | DT_LEFT); CPoint pt(rClient.left + 2 + iLeftOffset, rClient.Height()/2 - rText.Height()/2); CPoint sz(rText.Width(), rText.Height()); MemDC.DrawState(pt, sz, m_strText, DST_TEXT | (bEnabled ? DSS_NORMAL : DSS_DISABLED), FALSE, m_strText.GetLength(), (CBrush*)NULL); dc.BitBlt(0, 0, rClient.Width(), rClient.Height(), &MemDC, 0, 0, SRCCOPY); MemDC.SelectObject(pOldBMP); if (pOldFONT) MemDC.SelectObject(pOldFONT); }
C++
#include "ResourceEntry.h" using namespace std; //====================================================== // Resource class methods //====================================================== LPCTSTR ResourceEntry::getRandomImage() { if (m_imagesPath.size() == 0) return _T(""); srand( (unsigned)time( NULL ) ); return m_imagesPath[rand() % m_imagesPath.size()]; } LPCTSTR ResourceEntry::getRandomSound() { if (m_soundsPath.size() == 0) return _T(""); srand( (unsigned)time( NULL ) ); return m_soundsPath[rand() % m_soundsPath.size()]; } LPCTSTR ResourceEntry::getRandomVideo() { if (m_videosPath.size() == 0) return _T(""); srand( (unsigned)time( NULL ) ); return m_videosPath[rand() % m_videosPath.size()]; } bool ResourceEntry::isSoundNotAvailable() { return (m_soundsPath.size() == 0); } void ResourceEntry::clear() { m_imagesPath.clear(); m_soundsPath.clear(); m_videosPath.clear(); }
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "popup.h" #include "Version.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif
C++
// ResizableGrip.h: interface for the CResizableGrip class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESIZABLEGRIP_H__INCLUDED_) #define AFX_RESIZABLEGRIP_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CResizableGrip { private: class CSizeGrip : public CScrollBar { public: CSizeGrip() { m_bTransparent = FALSE; m_bTriangular = FALSE; } void SetTriangularShape(BOOL bEnable); void SetTransparency(BOOL bActivate); BOOL IsRTL(); // right-to-left layout support virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); SIZE m_size; // holds grip size protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); BOOL m_bTriangular; // triangular shape active BOOL m_bTransparent; // transparency active // memory DCs and bitmaps for transparent grip CDC m_dcGrip, m_dcMask; CBitmap m_bmGrip, m_bmMask; }; CSizeGrip m_wndGrip; // grip control int m_nShowCount; // support for hiding the grip protected: // create a size grip, with options BOOL CreateSizeGrip(BOOL bVisible = TRUE, BOOL bTriangular = TRUE, BOOL bTransparent = FALSE); BOOL IsSizeGripVisible(); // TRUE if grip is set to be visible void SetSizeGripVisibility(BOOL bVisible); // set default visibility void UpdateSizeGrip(); // update the grip's visibility and position void ShowSizeGrip(DWORD* pStatus, DWORD dwMask = 1); // temp show the size grip void HideSizeGrip(DWORD* pStatus, DWORD dwMask = 1); // temp hide the size grip BOOL SetSizeGripBkMode(int nBkMode); // like CDC::SetBkMode void SetSizeGripShape(BOOL bTriangular); virtual CWnd* GetResizableWnd() = 0; public: CResizableGrip(); virtual ~CResizableGrip(); }; #endif // !defined(AFX_RESIZABLEGRIP_H__INCLUDED_)
C++
#if !defined(AFX_RESIZABLESHEETEX_H__INCLUDED_) #define AFX_RESIZABLESHEETEX_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableLayout.h" #include "ResizableGrip.h" #include "ResizableMinMax.h" #include "ResizableState.h" ///////////////////////////////////////////////////////////////////////////// // ResizableSheetEx.h : header file // class CResizableSheetEx : public CPropertySheetEx, public CResizableLayout, public CResizableGrip, public CResizableMinMax, public CResizableState { DECLARE_DYNAMIC(CResizableSheetEx) // Construction public: CResizableSheetEx(); CResizableSheetEx(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0, HBITMAP hbmWatermark = NULL, HPALETTE hpalWatermark = NULL, HBITMAP hbmHeader = NULL); CResizableSheetEx(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0, HBITMAP hbmWatermark = NULL, HPALETTE hpalWatermark = NULL, HBITMAP hbmHeader = NULL); // Attributes private: // support for temporarily hiding the grip DWORD m_dwGripTempState; // flags BOOL m_bEnableSaveRestore; BOOL m_bRectOnly; BOOL m_bSavePage; // layout vars CSize m_sizePageTL, m_sizePageBR; // internal status CString m_sSection; // section name (identifies a parent window) // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizableSheetEx) public: virtual BOOL OnInitDialog(); protected: //}}AFX_VIRTUAL // Implementation public: void RefreshLayout(); virtual ~CResizableSheetEx(); // used internally private: void PresetLayout(); void PrivateConstruct(); void SavePage(); void LoadPage(); BOOL IsWizard() { return (m_psh.dwFlags & PSH_WIZARD); } BOOL IsWizard97() { return (m_psh.dwFlags & PSH_WIZARD97); } // callable from derived classes protected: // section to use in app's profile void EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly = FALSE, BOOL bWithPage = FALSE); int GetMinWidth(); // minimum width to display all buttons virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; // Generated message map functions protected: virtual BOOL ArrangeLayoutCallback(LayoutInfo& layout); //{{AFX_MSG(CResizableSheetEx) afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnDestroy(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg BOOL OnEraseBkgnd(CDC* pDC); //}}AFX_MSG afx_msg BOOL OnPageChanging(NMHDR* pNotifyStruct, LRESULT* pResult); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// #endif // AFX_RESIZABLESHEETEX_H__INCLUDED_
C++
// ResizableLayout.cpp: implementation of the CResizableLayout class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableLayout.h" #include "ResizableMsgSupport.inl" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// // In August 2002 Platform SDK, some guy at MS thought it was time to // add the missing symbol BS_TYPEMASK, but forgot its original meaning // and so now he's telling us not to use that symbol because its // value is likely to change in the future SDK releases, including all // the BS_* style bits in the mask, not just the button's type as the // symbol's name suggests. So now we're forced to use another symbol! #define _BS_TYPEMASK 0x0000000FL void CResizableLayout::AddAnchor(HWND hWnd, CSize sizeTypeTL, CSize sizeTypeBR) { CWnd* pParent = GetResizableWnd(); // child window must be valid ASSERT(::IsWindow(hWnd)); // must be child of parent window ASSERT(::IsChild(pParent->GetSafeHwnd(), hWnd)); // top-left anchor must be valid ASSERT(sizeTypeTL != NOANCHOR); // get control's window class CString sClassName; GetClassName(hWnd, sClassName.GetBufferSetLength(MAX_PATH), MAX_PATH); sClassName.ReleaseBuffer(); // get parent window's rect CRect rectParent; GetTotalClientRect(&rectParent); // and child control's rect CRect rectChild; ::GetWindowRect(hWnd, &rectChild); ::MapWindowPoints(NULL, pParent->m_hWnd, (LPPOINT)&rectChild, 2); // adjust position, if client area has been scrolled rectChild.OffsetRect(-rectParent.TopLeft()); // go calculate margins CSize sizeMarginTL, sizeMarginBR; if (sizeTypeBR == NOANCHOR) sizeTypeBR = sizeTypeTL; // calculate margin for the top-left corner sizeMarginTL.cx = rectChild.left - rectParent.Width() * sizeTypeTL.cx / 100; sizeMarginTL.cy = rectChild.top - rectParent.Height() * sizeTypeTL.cy / 100; // calculate margin for the bottom-right corner sizeMarginBR.cx = rectChild.right - rectParent.Width() * sizeTypeBR.cx / 100; sizeMarginBR.cy = rectChild.bottom - rectParent.Height() * sizeTypeBR.cy / 100; // prepare the structure LayoutInfo layout(hWnd, sizeTypeTL, sizeMarginTL, sizeTypeBR, sizeMarginBR, sClassName); // initialize resize properties (overridable) InitResizeProperties(layout); // must not be already there! // (this is probably due to a duplicate call to AddAnchor) POSITION pos; ASSERT(!m_mapLayout.Lookup(hWnd, pos)); // add to the list and the map pos = m_listLayout.AddTail(layout); m_mapLayout.SetAt(hWnd, pos); } void CResizableLayout::AddAnchorCallback(UINT nCallbackID) { // one callback control cannot rely upon another callback control's // size and/or position (they're updated all together at the end) // it can however use a non-callback control, which is updated before // add to the list LayoutInfo layout; layout.nCallbackID = nCallbackID; m_listLayoutCB.AddTail(layout); } BOOL CResizableLayout::ArrangeLayoutCallback(CResizableLayout::LayoutInfo& /*layout*/) { ASSERT(FALSE); // must be overridden, if callback is used return FALSE; // no output data } void CResizableLayout::ArrangeLayout() { // common vars UINT uFlags; LayoutInfo layout; CRect rectParent, rectChild; GetTotalClientRect(&rectParent); // get parent window's rect int count = m_listLayout.GetCount(); int countCB = m_listLayoutCB.GetCount(); // reposition child windows HDWP hdwp = ::BeginDeferWindowPos(count + countCB); POSITION pos = m_listLayout.GetHeadPosition(); while (pos != NULL) { // get layout info layout = m_listLayout.GetNext(pos); // calculate new child's position, size and flags for SetWindowPos CalcNewChildPosition(layout, rectParent, rectChild, uFlags); // only if size or position changed if ((uFlags & (SWP_NOMOVE|SWP_NOSIZE)) != (SWP_NOMOVE|SWP_NOSIZE)) { hdwp = ::DeferWindowPos(hdwp, layout.hWnd, NULL, rectChild.left, rectChild.top, rectChild.Width(), rectChild.Height(), uFlags); } } // for callback items you may use GetAnchorPosition to know the // new position and size of a non-callback item after resizing pos = m_listLayoutCB.GetHeadPosition(); while (pos != NULL) { // get layout info layout = m_listLayoutCB.GetNext(pos); // request layout data if (!ArrangeLayoutCallback(layout)) continue; // calculate new child's position, size and flags for SetWindowPos CalcNewChildPosition(layout, rectParent, rectChild, uFlags); // only if size or position changed if ((uFlags & (SWP_NOMOVE|SWP_NOSIZE)) != (SWP_NOMOVE|SWP_NOSIZE)) { hdwp = ::DeferWindowPos(hdwp, layout.hWnd, NULL, rectChild.left, rectChild.top, rectChild.Width(), rectChild.Height(), uFlags); } } // finally move all the windows at once ::EndDeferWindowPos(hdwp); } void CResizableLayout::ClipChildWindow(const CResizableLayout::LayoutInfo& layout, CRgn* pRegion) { // obtain window position CRect rect; ::GetWindowRect(layout.hWnd, &rect); ::MapWindowPoints(NULL, GetResizableWnd()->m_hWnd, (LPPOINT)&rect, 2); // use window region if any CRgn rgn; rgn.CreateRectRgn(0,0,0,0); switch (::GetWindowRgn(layout.hWnd, rgn)) { case COMPLEXREGION: case SIMPLEREGION: rgn.OffsetRgn(rect.TopLeft()); break; default: rgn.SetRectRgn(&rect); } // get the clipping property BOOL bClipping = layout.properties.bAskClipping ? LikesClipping(layout) : layout.properties.bCachedLikesClipping; // modify region accordingly if (bClipping) pRegion->CombineRgn(pRegion, &rgn, RGN_DIFF); else pRegion->CombineRgn(pRegion, &rgn, RGN_OR); } void CResizableLayout::GetClippingRegion(CRgn* pRegion) { CWnd* pWnd = GetResizableWnd(); // System's default clipping area is screen's size, // not enough for max track size, for example: // if screen is 1024 x 768 and resizing border is 4 pixels, // maximized size is 1024+4*2=1032 x 768+4*2=776, // but max track size is 4 pixels bigger 1036 x 780 (don't ask me why!) // So, if you resize the window to maximum size, the last 4 pixels // are clipped out by the default clipping region, that gets created // as soon as you call clipping functions (my guess). // reset clipping region to the whole client area CRect rect; pWnd->GetClientRect(&rect); pRegion->CreateRectRgnIndirect(&rect); // clip only anchored controls LayoutInfo layout; POSITION pos = m_listLayout.GetHeadPosition(); while (pos != NULL) { // get layout info layout = m_listLayout.GetNext(pos); if (::IsWindowVisible(layout.hWnd)) ClipChildWindow(layout, pRegion); } pos = m_listLayoutCB.GetHeadPosition(); while (pos != NULL) { // get layout info layout = m_listLayoutCB.GetNext(pos); // request data if (!ArrangeLayoutCallback(layout)) continue; if (::IsWindowVisible(layout.hWnd)) ClipChildWindow(layout, pRegion); } // fix for RTL layouts (1 pixel of horz offset) if (pWnd->GetExStyle() & WS_EX_LAYOUTRTL) pRegion->OffsetRgn(-1,0); } void CResizableLayout::EraseBackground(CDC* pDC) { HWND hWnd = GetResizableWnd()->GetSafeHwnd(); // retrieve the background brush HBRUSH hBrush = NULL; // is this a dialog box? // (using class atom is quickier than using the class name) ATOM atomWndClass = (ATOM)::GetClassLong(hWnd, GCW_ATOM); if (atomWndClass == (ATOM)0x8002) { // send a message to the dialog box hBrush = (HBRUSH)::SendMessage(hWnd, WM_CTLCOLORDLG, (WPARAM)pDC->GetSafeHdc(), (LPARAM)hWnd); } else { // take the background brush from the window's class hBrush = (HBRUSH)::GetClassLong(hWnd, GCL_HBRBACKGROUND); } // fill the clipped background CRgn rgn; GetClippingRegion(&rgn); ::FillRgn(pDC->GetSafeHdc(), rgn, hBrush); } // support legacy code (will disappear in future versions) void CResizableLayout::ClipChildren(CDC* pDC) { CRgn rgn; GetClippingRegion(&rgn); // the clipping region is in device units rgn.OffsetRgn(-pDC->GetWindowOrg()); pDC->SelectClipRgn(&rgn); } void CResizableLayout::GetTotalClientRect(LPRECT lpRect) { GetResizableWnd()->GetClientRect(lpRect); } BOOL CResizableLayout::NeedsRefresh(const CResizableLayout::LayoutInfo& layout, const CRect& rectOld, const CRect& rectNew) { if (layout.bMsgSupport) { REFRESHPROPERTY refresh; refresh.rcOld = rectOld; refresh.rcNew = rectNew; if (Send_NeedsRefresh(layout.hWnd, &refresh)) return refresh.bNeedsRefresh; } int nDiffWidth = (rectNew.Width() - rectOld.Width()); int nDiffHeight = (rectNew.Height() - rectOld.Height()); // is the same size? if (nDiffWidth == 0 && nDiffHeight == 0) return FALSE; // optimistic, no need to refresh BOOL bRefresh = FALSE; // window classes that need refresh when resized if (layout.sWndClass == WC_STATIC) { DWORD style = ::GetWindowLong(layout.hWnd, GWL_STYLE); switch (style & SS_TYPEMASK) { case SS_LEFT: case SS_CENTER: case SS_RIGHT: // word-wrapped text bRefresh = bRefresh || (nDiffWidth != 0); // vertically centered text if (style & SS_CENTERIMAGE) bRefresh = bRefresh || (nDiffHeight != 0); break; case SS_LEFTNOWORDWRAP: // text with ellipsis if (style & SS_ELLIPSISMASK) bRefresh = bRefresh || (nDiffWidth != 0); // vertically centered text if (style & SS_CENTERIMAGE) bRefresh = bRefresh || (nDiffHeight != 0); break; case SS_ENHMETAFILE: case SS_BITMAP: case SS_ICON: // images case SS_BLACKFRAME: case SS_GRAYFRAME: case SS_WHITEFRAME: case SS_ETCHEDFRAME: // and frames bRefresh = TRUE; break; } } // window classes that don't redraw client area correctly // when the hor scroll pos changes due to a resizing BOOL bHScroll = FALSE; if (layout.sWndClass == WC_LISTBOX) bHScroll = TRUE; // fix for horizontally scrollable windows if (bHScroll && (nDiffWidth > 0)) { // get max scroll position SCROLLINFO info; info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; if (::GetScrollInfo(layout.hWnd, SB_HORZ, &info)) { // subtract the page size info.nMax -= __max(info.nPage-1,0); } // resizing will cause the text to scroll on the right // because the scrollbar is going beyond the right limit if ((info.nMax > 0) && (info.nPos + nDiffWidth > info.nMax)) { // needs repainting, due to horiz scrolling bRefresh = TRUE; } } return bRefresh; } BOOL CResizableLayout::LikesClipping(const CResizableLayout::LayoutInfo& layout) { if (layout.bMsgSupport) { CLIPPINGPROPERTY clipping; if (Send_LikesClipping(layout.hWnd, &clipping)) return clipping.bLikesClipping; } DWORD style = ::GetWindowLong(layout.hWnd, GWL_STYLE); // skip windows that wants background repainted if (layout.sWndClass == TOOLBARCLASSNAME && (style & TBSTYLE_TRANSPARENT)) return FALSE; else if (layout.sWndClass == WC_BUTTON) { CRect rect; switch (style & _BS_TYPEMASK) { case BS_GROUPBOX: return FALSE; case BS_OWNERDRAW: // ownerdraw buttons must return correct hittest code // to notify their transparency to the system and this library ::GetWindowRect(layout.hWnd, &rect); if ( HTTRANSPARENT == ::SendMessage(layout.hWnd, WM_NCHITTEST, 0, MAKELPARAM(rect.left, rect.top)) ) return FALSE; break; } return TRUE; } else if (layout.sWndClass == WC_STATIC) { switch (style & SS_TYPEMASK) { case SS_LEFT: case SS_CENTER: case SS_RIGHT: case SS_SIMPLE: case SS_LEFTNOWORDWRAP: // text case SS_BLACKRECT: case SS_GRAYRECT: case SS_WHITERECT: // filled rects case SS_ETCHEDHORZ: case SS_ETCHEDVERT: // etched lines case SS_BITMAP: // bitmaps return TRUE; break; case SS_ICON: case SS_ENHMETAFILE: if (style & SS_CENTERIMAGE) return FALSE; return TRUE; break; default: return FALSE; } } // assume the others like clipping return TRUE; } void CResizableLayout::CalcNewChildPosition(const CResizableLayout::LayoutInfo& layout, const CRect &rectParent, CRect &rectChild, UINT& uFlags) { CWnd* pParent = GetResizableWnd(); ::GetWindowRect(layout.hWnd, &rectChild); ::MapWindowPoints(NULL, pParent->m_hWnd, (LPPOINT)&rectChild, 2); CRect rectNew; // calculate new top-left corner rectNew.left = layout.sizeMarginTL.cx + rectParent.Width() * layout.sizeTypeTL.cx / 100; rectNew.top = layout.sizeMarginTL.cy + rectParent.Height() * layout.sizeTypeTL.cy / 100; // calculate new bottom-right corner rectNew.right = layout.sizeMarginBR.cx + rectParent.Width() * layout.sizeTypeBR.cx / 100; rectNew.bottom = layout.sizeMarginBR.cy + rectParent.Height() * layout.sizeTypeBR.cy / 100; // adjust position, if client area has been scrolled rectNew.OffsetRect(rectParent.TopLeft()); // get the refresh property BOOL bRefresh = layout.properties.bAskRefresh ? NeedsRefresh(layout, rectChild, rectNew) : layout.properties.bCachedNeedsRefresh; // set flags uFlags = SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREPOSITION; if (bRefresh) uFlags |= SWP_NOCOPYBITS; if (rectNew.TopLeft() == rectChild.TopLeft()) uFlags |= SWP_NOMOVE; if (rectNew.Size() == rectChild.Size()) uFlags |= SWP_NOSIZE; // update rect rectChild = rectNew; } void CResizableLayout::InitResizeProperties(CResizableLayout::LayoutInfo &layout) { // check if custom window supports this library // (properties must be correctly set by the window) layout.bMsgSupport = Send_QueryProperties(layout.hWnd, &layout.properties); // default properties if (!layout.bMsgSupport) { // clipping property is assumed as static layout.properties.bAskClipping = FALSE; layout.properties.bCachedLikesClipping = LikesClipping(layout); // refresh property is assumed as dynamic layout.properties.bAskRefresh = TRUE; } }
C++
// ResizablePage.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizablePage.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizablePage IMPLEMENT_DYNCREATE(CResizablePage, CPropertyPage) CResizablePage::CResizablePage() { } CResizablePage::CResizablePage(UINT nIDTemplate, UINT nIDCaption) : CPropertyPage(nIDTemplate, nIDCaption) { } CResizablePage::CResizablePage(LPCTSTR lpszTemplateName, UINT nIDCaption) : CPropertyPage(lpszTemplateName, nIDCaption) { } CResizablePage::~CResizablePage() { } BEGIN_MESSAGE_MAP(CResizablePage, CPropertyPage) //{{AFX_MSG_MAP(CResizablePage) ON_WM_SIZE() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizablePage message handlers void CResizablePage::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); ArrangeLayout(); } BOOL CResizablePage::OnEraseBkgnd(CDC* pDC) { // Windows XP doesn't like clipping regions ...try this! EraseBackground(pDC); return TRUE; /* ClipChildren(pDC); // old-method (for safety) return CPropertyPage::OnEraseBkgnd(pDC); */ }
C++
// ResizableMinMax.cpp: implementation of the CResizableMinMax class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableMinMax.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CResizableMinMax::CResizableMinMax() { m_bUseMinTrack = FALSE; m_bUseMaxTrack = FALSE; m_bUseMaxRect = FALSE; } CResizableMinMax::~CResizableMinMax() { } void CResizableMinMax::MinMaxInfo(LPMINMAXINFO lpMMI) { if (m_bUseMinTrack) lpMMI->ptMinTrackSize = m_ptMinTrackSize; if (m_bUseMaxTrack) lpMMI->ptMaxTrackSize = m_ptMaxTrackSize; if (m_bUseMaxRect) { lpMMI->ptMaxPosition = m_ptMaxPos; lpMMI->ptMaxSize = m_ptMaxSize; } } void CResizableMinMax::SetMaximizedRect(const CRect& rc) { m_bUseMaxRect = TRUE; m_ptMaxPos = rc.TopLeft(); m_ptMaxSize.x = rc.Width(); m_ptMaxSize.y = rc.Height(); } void CResizableMinMax::ResetMaximizedRect() { m_bUseMaxRect = FALSE; } void CResizableMinMax::SetMinTrackSize(const CSize& size) { m_bUseMinTrack = TRUE; m_ptMinTrackSize.x = size.cx; m_ptMinTrackSize.y = size.cy; } void CResizableMinMax::ResetMinTrackSize() { m_bUseMinTrack = FALSE; } void CResizableMinMax::SetMaxTrackSize(const CSize& size) { m_bUseMaxTrack = TRUE; m_ptMaxTrackSize.x = size.cx; m_ptMaxTrackSize.y = size.cy; } void CResizableMinMax::ResetMaxTrackSize() { m_bUseMaxTrack = FALSE; }
C++
// ResizableFrame.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableFrame.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizableFrame IMPLEMENT_DYNCREATE(CResizableFrame, CFrameWnd) CResizableFrame::CResizableFrame() { m_bEnableSaveRestore = FALSE; } CResizableFrame::~CResizableFrame() { } BEGIN_MESSAGE_MAP(CResizableFrame, CFrameWnd) //{{AFX_MSG_MAP(CResizableFrame) ON_WM_GETMINMAXINFO() ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizableFrame message handlers void CResizableFrame::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { MinMaxInfo(lpMMI); CView* pView = GetActiveView(); if (pView == NULL) return; // get the extra size from view to frame CRect rectClient, rectWnd; GetWindowRect(rectWnd); RepositionBars(0, 0xFFFF, AFX_IDW_PANE_FIRST, reposQuery, rectClient); CSize sizeExtra = rectWnd.Size() - rectClient.Size(); // ask the view for track size MINMAXINFO mmiView = *lpMMI; pView->SendMessage(WM_GETMINMAXINFO, 0, (LPARAM)&mmiView); mmiView.ptMaxTrackSize = sizeExtra + mmiView.ptMaxTrackSize; mmiView.ptMinTrackSize = sizeExtra + mmiView.ptMinTrackSize; // min size is the largest lpMMI->ptMinTrackSize.x = __max(lpMMI->ptMinTrackSize.x, mmiView.ptMinTrackSize.x); lpMMI->ptMinTrackSize.y = __max(lpMMI->ptMinTrackSize.y, mmiView.ptMinTrackSize.y); // max size is the shortest lpMMI->ptMaxTrackSize.x = __min(lpMMI->ptMaxTrackSize.x, mmiView.ptMaxTrackSize.x); lpMMI->ptMaxTrackSize.y = __min(lpMMI->ptMaxTrackSize.y, mmiView.ptMaxTrackSize.y); } // NOTE: this must be called after setting the layout // to have the view and its controls displayed properly BOOL CResizableFrame::EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly) { m_sSection = pszSection; m_bEnableSaveRestore = TRUE; m_bRectOnly = bRectOnly; // restore immediately return LoadWindowRect(pszSection, bRectOnly); } void CResizableFrame::OnDestroy() { if (m_bEnableSaveRestore) SaveWindowRect(m_sSection, m_bRectOnly); CFrameWnd::OnDestroy(); }
C++
#if !defined(AFX_RESIZABLEPAGEEX_H__INCLUDED_) #define AFX_RESIZABLEPAGEEX_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ResizablePageEx.h : header file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableLayout.h" ///////////////////////////////////////////////////////////////////////////// // CResizablePageEx window class CResizablePageEx : public CPropertyPageEx, public CResizableLayout { DECLARE_DYNCREATE(CResizablePageEx) // Construction public: CResizablePageEx(); CResizablePageEx(UINT nIDTemplate, UINT nIDCaption = 0, UINT nIDHeaderTitle = 0, UINT nIDHeaderSubTitle = 0); CResizablePageEx(LPCTSTR lpszTemplateName, UINT nIDCaption = 0, UINT nIDHeaderTitle = 0, UINT nIDHeaderSubTitle = 0); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizablePageEx) //}}AFX_VIRTUAL // Implementation public: virtual ~CResizablePageEx(); // callable from derived classes protected: // override to specify refresh for custom or unsupported windows virtual BOOL NeedsRefresh(const CResizableLayout::LayoutInfo &layout, const CRect &rectOld, const CRect &rectNew); virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; // Generated message map functions protected: //{{AFX_MSG(CResizablePageEx) afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RESIZABLEPAGEEX_H__INCLUDED_)
C++
#if !defined(AFX_RESIZABLEFORMVIEW_H__INCLUDED_) #define AFX_RESIZABLEFORMVIEW_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ResizableFormView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableLayout.h" #include "ResizableGrip.h" #include "ResizableMinMax.h" ///////////////////////////////////////////////////////////////////////////// // CResizableFormView form view #ifndef __AFXEXT_H__ #include <afxext.h> #endif class CResizableFormView : public CFormView, public CResizableLayout, public CResizableGrip, public CResizableMinMax { DECLARE_DYNAMIC(CResizableFormView) // Construction protected: // must derive your own class CResizableFormView(UINT nIDTemplate); CResizableFormView(LPCTSTR lpszTemplateName); virtual ~CResizableFormView(); private: void PrivateConstruct(); BOOL m_bInitDone; // if all internal vars initialized // support for temporarily hiding the grip DWORD m_dwGripTempState; enum GripHideReason // bitmask { GHR_MAXIMIZED = 0x01, GHR_SCROLLBAR = 0x02, GHR_ALIGNMENT = 0x04, }; // called from base class protected: virtual void GetTotalClientRect(LPRECT lpRect); virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; // Attributes public: // Operations public: // Overrides public: // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizableFormView) virtual void OnInitialUpdate(); //}}AFX_VIRTUAL // Implementation protected: #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions //{{AFX_MSG(CResizableFormView) afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnDestroy(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RESIZABLEFORMVIEW_H__INCLUDED_)
C++
// ResizableState.cpp: implementation of the CResizableState class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableState.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CResizableState::CResizableState() { } CResizableState::~CResizableState() { } // used to save/restore window's size and position // either in the registry or a private .INI file // depending on your application settings #define PLACEMENT_ENT _T("WindowPlacement") #define PLACEMENT_FMT _T("%d,%d,%d,%d,%d,%d") BOOL CResizableState::SaveWindowRect(LPCTSTR pszSection, BOOL bRectOnly) { CString data; WINDOWPLACEMENT wp; ZeroMemory(&wp, sizeof(WINDOWPLACEMENT)); wp.length = sizeof(WINDOWPLACEMENT); if (!GetResizableWnd()->GetWindowPlacement(&wp)) return FALSE; RECT& rc = wp.rcNormalPosition; // alias if (bRectOnly) // save size/pos only (normal state) { // use screen coordinates GetResizableWnd()->GetWindowRect(&rc); data.Format(PLACEMENT_FMT, rc.left, rc.top, rc.right, rc.bottom, SW_NORMAL, 0); } else // save also min/max state { // use workspace coordinates data.Format(PLACEMENT_FMT, rc.left, rc.top, rc.right, rc.bottom, wp.showCmd, wp.flags); } return AfxGetApp()->WriteProfileString(pszSection, PLACEMENT_ENT, data); } BOOL CResizableState::LoadWindowRect(LPCTSTR pszSection, BOOL bRectOnly) { CString data; WINDOWPLACEMENT wp; data = AfxGetApp()->GetProfileString(pszSection, PLACEMENT_ENT); if (data.IsEmpty()) // never saved before return FALSE; ZeroMemory(&wp, sizeof(WINDOWPLACEMENT)); wp.length = sizeof(WINDOWPLACEMENT); if (!GetResizableWnd()->GetWindowPlacement(&wp)) return FALSE; RECT& rc = wp.rcNormalPosition; // alias if (_stscanf(data, PLACEMENT_FMT, &rc.left, &rc.top, &rc.right, &rc.bottom, &wp.showCmd, &wp.flags) == 6) { if (bRectOnly) // restore size/pos only { CRect rect(rc); return GetResizableWnd()->SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOREPOSITION); } else // restore also min/max state { return GetResizableWnd()->SetWindowPlacement(&wp); } } return FALSE; }
C++
// ResizableSheetEx.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// //#include "stdafx.h" #define _WIN32_IE 0x0400 // for CPropertyPageEx, CPropertySheetEx #define _WIN32_WINNT 0x0500 // for CPropertyPageEx, CPropertySheetEx #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxcmn.h> // MFC support for Windows Common Controls #include "ResizableSheetEx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizableSheetEx IMPLEMENT_DYNAMIC(CResizableSheetEx, CPropertySheetEx) inline void CResizableSheetEx::PrivateConstruct() { m_bEnableSaveRestore = FALSE; m_bSavePage = FALSE; m_dwGripTempState = 1; } CResizableSheetEx::CResizableSheetEx() { PrivateConstruct(); } CResizableSheetEx::CResizableSheetEx(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage, HBITMAP hbmWatermark, HPALETTE hpalWatermark, HBITMAP hbmHeader) : CPropertySheetEx(nIDCaption, pParentWnd, iSelectPage, hbmWatermark, hpalWatermark, hbmHeader) { PrivateConstruct(); } CResizableSheetEx::CResizableSheetEx(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage, HBITMAP hbmWatermark, HPALETTE hpalWatermark, HBITMAP hbmHeader) : CPropertySheetEx(pszCaption, pParentWnd, iSelectPage, hbmWatermark, hpalWatermark, hbmHeader) { PrivateConstruct(); } CResizableSheetEx::~CResizableSheetEx() { } BEGIN_MESSAGE_MAP(CResizableSheetEx, CPropertySheetEx) //{{AFX_MSG_MAP(CResizableSheetEx) ON_WM_GETMINMAXINFO() ON_WM_SIZE() ON_WM_DESTROY() ON_WM_CREATE() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP ON_NOTIFY_REFLECT_EX(PSN_SETACTIVE, OnPageChanging) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizableSheetEx message handlers int CResizableSheetEx::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CPropertySheetEx::OnCreate(lpCreateStruct) == -1) return -1; // keep client area CRect rect; GetClientRect(&rect); // set resizable style ModifyStyle(DS_MODALFRAME, WS_POPUP | WS_THICKFRAME); // adjust size to reflect new style ::AdjustWindowRectEx(&rect, GetStyle(), ::IsMenu(GetMenu()->GetSafeHmenu()), GetExStyle()); SetWindowPos(NULL, 0, 0, rect.Width(), rect.Height(), SWP_FRAMECHANGED| SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOREPOSITION); // create and init the size-grip if (!CreateSizeGrip()) return -1; return 0; } BOOL CResizableSheetEx::OnInitDialog() { BOOL bResult = CPropertySheetEx::OnInitDialog(); // set the initial size as the min track size CRect rc; GetWindowRect(&rc); SetMinTrackSize(rc.Size()); // initialize layout PresetLayout(); // prevent flickering GetTabControl()->ModifyStyle(0, WS_CLIPSIBLINGS); return bResult; } void CResizableSheetEx::OnDestroy() { if (m_bEnableSaveRestore) { SaveWindowRect(m_sSection, m_bRectOnly); SavePage(); } RemoveAllAnchors(); CPropertySheetEx::OnDestroy(); } // maps an index to a button ID and vice-versa static UINT _propButtons[] = { IDOK, IDCANCEL, ID_APPLY_NOW, IDHELP, ID_WIZBACK, ID_WIZNEXT, ID_WIZFINISH }; // horizontal line in wizard mode #define ID_WIZLINE ID_WIZFINISH+1 #define ID_WIZLINEHDR ID_WIZFINISH+2 void CResizableSheetEx::PresetLayout() { if (IsWizard() || IsWizard97()) // wizard mode { // hide tab control GetTabControl()->ShowWindow(SW_HIDE); AddAnchor(ID_WIZLINE, BOTTOM_LEFT, BOTTOM_RIGHT); if (IsWizard97()) // add header line for wizard97 dialogs AddAnchor(ID_WIZLINEHDR, TOP_LEFT, TOP_RIGHT); } else // tab mode { AddAnchor(AFX_IDC_TAB_CONTROL, TOP_LEFT, BOTTOM_RIGHT); } // add a callback for active page (which can change at run-time) AddAnchorCallback(1); // use *total* parent size to have correct margins CRect rectPage, rectSheet; GetTotalClientRect(&rectSheet); GetActivePage()->GetWindowRect(&rectPage); ::MapWindowPoints(NULL, m_hWnd, (LPPOINT)&rectPage, 2); // pre-calculate margins m_sizePageTL = rectPage.TopLeft() - rectSheet.TopLeft(); m_sizePageBR = rectPage.BottomRight() - rectSheet.BottomRight(); // add all possible buttons, if they exist for (int i = 0; i < 7; i++) { if (NULL != GetDlgItem(_propButtons[i])) AddAnchor(_propButtons[i], BOTTOM_RIGHT); } } BOOL CResizableSheetEx::ArrangeLayoutCallback(LayoutInfo &layout) { if (layout.nCallbackID != 1) // we only added 1 callback return CResizableLayout::ArrangeLayoutCallback(layout); // set layout info for active page layout.hWnd = (HWND)::SendMessage(GetSafeHwnd(), PSM_GETCURRENTPAGEHWND, 0, 0); if (!::IsWindow(layout.hWnd)) return FALSE; // set margins if (IsWizard()) // wizard mode { // use pre-calculated margins layout.sizeMarginTL = m_sizePageTL; layout.sizeMarginBR = m_sizePageBR; } else if (IsWizard97()) // wizard 97 { // use pre-calculated margins layout.sizeMarginTL = m_sizePageTL; layout.sizeMarginBR = m_sizePageBR; if (!(GetActivePage()->m_psp.dwFlags & PSP_HIDEHEADER)) { // add header vertical offset CRect rectLine; GetDlgItem(ID_WIZLINEHDR)->GetWindowRect(&rectLine); ::MapWindowPoints(NULL, m_hWnd, (LPPOINT)&rectLine, 2); layout.sizeMarginTL.cy = rectLine.bottom; } } else // tab mode { CTabCtrl* pTab = GetTabControl(); ASSERT(pTab != NULL); // get tab position after resizing and calc page rect CRect rectPage, rectSheet; GetTotalClientRect(&rectSheet); VERIFY(GetAnchorPosition(pTab->m_hWnd, rectSheet, rectPage)); pTab->AdjustRect(FALSE, &rectPage); // set margins layout.sizeMarginTL = rectPage.TopLeft() - rectSheet.TopLeft(); layout.sizeMarginBR = rectPage.BottomRight() - rectSheet.BottomRight(); } // set anchor types layout.sizeTypeTL = TOP_LEFT; layout.sizeTypeBR = BOTTOM_RIGHT; // use this layout info return TRUE; } void CResizableSheetEx::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); if (nType == SIZE_MAXHIDE || nType == SIZE_MAXSHOW) return; // arrangement not needed if (nType == SIZE_MAXIMIZED) HideSizeGrip(&m_dwGripTempState); else ShowSizeGrip(&m_dwGripTempState); // update grip and layout UpdateSizeGrip(); ArrangeLayout(); } BOOL CResizableSheetEx::OnPageChanging(NMHDR* /*pNotifyStruct*/, LRESULT* /*pResult*/) { // update new wizard page // active page changes after this notification PostMessage(WM_SIZE); return FALSE; // continue routing } BOOL CResizableSheetEx::OnEraseBkgnd(CDC* pDC) { // Windows XP doesn't like clipping regions ...try this! EraseBackground(pDC); return TRUE; /* ClipChildren(pDC); // old-method (for safety) return CPropertySheetEx::OnEraseBkgnd(pDC); */ } void CResizableSheetEx::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { MinMaxInfo(lpMMI); } // protected members int CResizableSheetEx::GetMinWidth() { CWnd* pWnd = NULL; CRect rectWnd, rectSheet; GetTotalClientRect(&rectSheet); int max = 0, min = rectSheet.Width(); // search for leftmost and rightmost button margins for (int i = 0; i < 7; i++) { pWnd = GetDlgItem(_propButtons[i]); // exclude not present or hidden buttons if (pWnd == NULL || !(pWnd->GetStyle() & WS_VISIBLE)) continue; // left position is relative to the right border // of the parent window (negative value) pWnd->GetWindowRect(&rectWnd); ::MapWindowPoints(NULL, m_hWnd, (LPPOINT)&rectWnd, 2); int left = rectSheet.right - rectWnd.left; int right = rectSheet.right - rectWnd.right; if (left > max) max = left; if (right < min) min = right; } // sizing border width int border = GetSystemMetrics(SM_CXSIZEFRAME); // compute total width return max + min + 2*border; } // NOTE: this must be called after all the other settings // to have the window and its controls displayed properly void CResizableSheetEx::EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly, BOOL bWithPage) { m_sSection = pszSection; m_bSavePage = bWithPage; m_bEnableSaveRestore = TRUE; m_bRectOnly = bRectOnly; // restore immediately LoadWindowRect(pszSection, bRectOnly); LoadPage(); } // private memebers // used to save/restore active page // either in the registry or a private .INI file // depending on your application settings #define ACTIVEPAGE _T("ActivePage") void CResizableSheetEx::SavePage() { if (!m_bSavePage) return; // saves active page index, zero (the first) if problems // cannot use GetActivePage, because it always fails CTabCtrl *pTab = GetTabControl(); int page = 0; if (pTab != NULL) page = pTab->GetCurSel(); if (page < 0) page = 0; AfxGetApp()->WriteProfileInt(m_sSection, ACTIVEPAGE, page); } void CResizableSheetEx::LoadPage() { // restore active page, zero (the first) if not found int page = AfxGetApp()->GetProfileInt(m_sSection, ACTIVEPAGE, 0); if (m_bSavePage) { SetActivePage(page); ArrangeLayout(); // needs refresh } } void CResizableSheetEx::RefreshLayout() { SendMessage(WM_SIZE); }
C++
// ResizableMDIFrame.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableMDIFrame.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizableMDIFrame IMPLEMENT_DYNCREATE(CResizableMDIFrame, CMDIFrameWnd) CResizableMDIFrame::CResizableMDIFrame() { m_bEnableSaveRestore = FALSE; } CResizableMDIFrame::~CResizableMDIFrame() { } BEGIN_MESSAGE_MAP(CResizableMDIFrame, CMDIFrameWnd) //{{AFX_MSG_MAP(CResizableMDIFrame) ON_WM_GETMINMAXINFO() ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizableMDIFrame message handlers void CResizableMDIFrame::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { MinMaxInfo(lpMMI); BOOL bMaximized = FALSE; CMDIChildWnd* pChild = MDIGetActive(&bMaximized); if (pChild == NULL || !bMaximized) return; // get the extra size from child to frame CRect rectChild, rectWnd; GetWindowRect(rectWnd); RepositionBars(0, 0xFFFF, AFX_IDW_PANE_FIRST, reposQuery, rectChild); CSize sizeExtra = rectWnd.Size() - rectChild.Size(); // ask the child frame for track size MINMAXINFO mmiView = *lpMMI; pChild->SendMessage(WM_GETMINMAXINFO, 0, (LPARAM)&mmiView); mmiView.ptMaxTrackSize = sizeExtra + mmiView.ptMaxTrackSize; mmiView.ptMinTrackSize = sizeExtra + mmiView.ptMinTrackSize; // min size is the largest lpMMI->ptMinTrackSize.x = __max(lpMMI->ptMinTrackSize.x, mmiView.ptMinTrackSize.x); lpMMI->ptMinTrackSize.y = __max(lpMMI->ptMinTrackSize.y, mmiView.ptMinTrackSize.y); // max size is the shortest lpMMI->ptMaxTrackSize.x = __min(lpMMI->ptMaxTrackSize.x, mmiView.ptMaxTrackSize.x); lpMMI->ptMaxTrackSize.y = __min(lpMMI->ptMaxTrackSize.y, mmiView.ptMaxTrackSize.y); // MDI should call default implementation CMDIFrameWnd::OnGetMinMaxInfo(lpMMI); } // NOTE: this must be called after setting the layout // to have the view and its controls displayed properly BOOL CResizableMDIFrame::EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly) { m_sSection = pszSection; m_bEnableSaveRestore = TRUE; m_bRectOnly = bRectOnly; // restore immediately return LoadWindowRect(pszSection, bRectOnly); } void CResizableMDIFrame::OnDestroy() { if (m_bEnableSaveRestore) SaveWindowRect(m_sSection, m_bRectOnly); CMDIFrameWnd::OnDestroy(); }
C++
// ResizableLayout.h: interface for the CResizableLayout class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESIZABLELAYOUT_H__INCLUDED_) #define AFX_RESIZABLELAYOUT_H__INCLUDED_ #include <afxtempl.h> #include "ResizableMsgSupport.h" #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // useful compatibility constants (the only one required is NOANCHOR) const CSize NOANCHOR(-1,-1), TOP_LEFT(0,0), TOP_CENTER(50,0), TOP_RIGHT(100,0), MIDDLE_LEFT(0,50), MIDDLE_CENTER(50,50), MIDDLE_RIGHT(100,50), BOTTOM_LEFT(0,100), BOTTOM_CENTER(50,100), BOTTOM_RIGHT(100,100); class CResizableLayout { protected: class LayoutInfo { public: HWND hWnd; UINT nCallbackID; CString sWndClass; // upper-left corner SIZE sizeTypeTL; SIZE sizeMarginTL; // bottom-right corner SIZE sizeTypeBR; SIZE sizeMarginBR; // custom window support BOOL bMsgSupport; RESIZEPROPERTIES properties; public: LayoutInfo() : hWnd(NULL), nCallbackID(0), bMsgSupport(FALSE) { } LayoutInfo(HWND hwnd, SIZE tl_t, SIZE tl_m, SIZE br_t, SIZE br_m, CString classname) : hWnd(hwnd), nCallbackID(0), sWndClass(classname), bMsgSupport(FALSE), sizeTypeTL(tl_t), sizeMarginTL(tl_m), sizeTypeBR(br_t), sizeMarginBR(br_m) { } }; private: // list of repositionable controls CMap<HWND, HWND, POSITION, POSITION> m_mapLayout; CList<LayoutInfo, LayoutInfo&> m_listLayout; CList<LayoutInfo, LayoutInfo&> m_listLayoutCB; void ClipChildWindow(const CResizableLayout::LayoutInfo &layout, CRgn* pRegion); void CalcNewChildPosition(const CResizableLayout::LayoutInfo &layout, const CRect &rectParent, CRect &rectChild, UINT& uFlags); protected: // override to initialize resize properties (clipping, refresh) virtual void InitResizeProperties(CResizableLayout::LayoutInfo& layout); // override to specify clipping for unsupported windows virtual BOOL LikesClipping(const CResizableLayout::LayoutInfo &layout); // override to specify refresh for unsupported windows virtual BOOL NeedsRefresh(const CResizableLayout::LayoutInfo &layout, const CRect &rectOld, const CRect &rectNew); // paint the background on the given DC (for XP theme's compatibility) void EraseBackground(CDC* pDC); // clip out child windows from the given DC (support old code) void ClipChildren(CDC* pDC); // get the clipping region (without clipped child windows) void GetClippingRegion(CRgn* pRegion); // override for scrollable or expanding parent windows virtual void GetTotalClientRect(LPRECT lpRect); // add anchors to a control, given its HWND void AddAnchor(HWND hWnd, CSize sizeTypeTL, CSize sizeTypeBR = NOANCHOR); // add anchors to a control, given its ID void AddAnchor(UINT nID, CSize sizeTypeTL, CSize sizeTypeBR = NOANCHOR) { AddAnchor(::GetDlgItem(GetResizableWnd()->GetSafeHwnd(), nID), sizeTypeTL, sizeTypeBR); } // add a callback (control ID or HWND is unknown or may change) void AddAnchorCallback(UINT nCallbackID); // get rect of an anchored window, given the parent's client area BOOL GetAnchorPosition(HWND hWnd, const CRect &rectParent, CRect &rectChild, UINT* lpFlags = NULL) { POSITION pos; if (!m_mapLayout.Lookup(hWnd, pos)) return FALSE; UINT uTmpFlags; CalcNewChildPosition(m_listLayout.GetAt(pos), rectParent, rectChild, (lpFlags != NULL) ? (*lpFlags) : uTmpFlags); return TRUE; } // get rect of an anchored window, given the parent's client area BOOL GetAnchorPosition(UINT nID, const CRect &rectParent, CRect &rectChild, UINT* lpFlags = NULL) { return GetAnchorPosition(::GetDlgItem(GetResizableWnd()->GetSafeHwnd(), nID), rectParent, rectChild, lpFlags); } // remove an anchored control from the layout, given its HWND BOOL RemoveAnchor(HWND hWnd) { POSITION pos; if (!m_mapLayout.Lookup(hWnd, pos)) return FALSE; m_listLayout.RemoveAt(pos); return m_mapLayout.RemoveKey(hWnd); } // remove an anchored control from the layout, given its HWND BOOL RemoveAnchor(UINT nID) { return RemoveAnchor(::GetDlgItem(GetResizableWnd()->GetSafeHwnd(), nID)); } // reset layout content void RemoveAllAnchors() { m_mapLayout.RemoveAll(); m_listLayout.RemoveAll(); m_listLayoutCB.RemoveAll(); } // adjust children's layout, when parent's size changes void ArrangeLayout(); // override to provide dynamic control's layout info virtual BOOL ArrangeLayoutCallback(CResizableLayout::LayoutInfo& layout); // override to provide the parent window virtual CWnd* GetResizableWnd() = 0; public: CResizableLayout() { } virtual ~CResizableLayout() { // just for safety RemoveAllAnchors(); } }; #endif // !defined(AFX_RESIZABLELAYOUT_H__INCLUDED_)
C++
#if !defined(AFX_RESIZABLEPAGE_H__INCLUDED_) #define AFX_RESIZABLEPAGE_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ResizablePage.h : header file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableLayout.h" ///////////////////////////////////////////////////////////////////////////// // CResizablePage window class CResizablePage : public CPropertyPage, public CResizableLayout { DECLARE_DYNCREATE(CResizablePage) // Construction public: CResizablePage(); CResizablePage(UINT nIDTemplate, UINT nIDCaption = 0); CResizablePage(LPCTSTR lpszTemplateName, UINT nIDCaption = 0); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizablePage) //}}AFX_VIRTUAL // Implementation public: virtual ~CResizablePage(); // callable from derived classes protected: virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; // Generated message map functions protected: //{{AFX_MSG(CResizablePage) afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RESIZABLEPAGE_H__INCLUDED_)
C++
#if !defined(AFX_RESIZABLEFRAME_H__4BA07057_6EF3_43A4_A80B_A24FA3A8B5C7__INCLUDED_) #define AFX_RESIZABLEFRAME_H__4BA07057_6EF3_43A4_A80B_A24FA3A8B5C7__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ResizableFrame.h : header file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableMinMax.h" #include "ResizableState.h" ///////////////////////////////////////////////////////////////////////////// // CResizableFrame frame class CResizableFrame : public CFrameWnd, public CResizableMinMax, public CResizableState { DECLARE_DYNCREATE(CResizableFrame) protected: CResizableFrame(); // protected constructor used by dynamic creation // Attributes protected: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizableFrame) //}}AFX_VIRTUAL // Implementation protected: virtual ~CResizableFrame(); BOOL EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly = FALSE); virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; private: // flags BOOL m_bEnableSaveRestore; BOOL m_bRectOnly; // internal status CString m_sSection; // section name (identifies a parent window) protected: // Generated message map functions //{{AFX_MSG(CResizableFrame) afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnDestroy(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RESIZABLEFRAME_H__4BA07057_6EF3_43A4_A80B_A24FA3A8B5C7__INCLUDED_)
C++
#if !defined(AFX_RESIZABLEDIALOG_H__INCLUDED_) #define AFX_RESIZABLEDIALOG_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ResizableDialog.h : header file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableLayout.h" #include "ResizableGrip.h" #include "ResizableMinMax.h" #include "ResizableState.h" ///////////////////////////////////////////////////////////////////////////// // CResizableDialog window class CResizableDialog : public CDialog, public CResizableLayout, public CResizableGrip, public CResizableMinMax, public CResizableState { // Construction public: CResizableDialog(); CResizableDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL); CResizableDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL); // Attributes private: // support for temporarily hiding the grip DWORD m_dwGripTempState; // flags BOOL m_bEnableSaveRestore; BOOL m_bRectOnly; // internal status CString m_sSection; // section name (identifies a parent window) // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizableDialog) protected: //}}AFX_VIRTUAL // Implementation public: virtual ~CResizableDialog(); // used internally private: void PrivateConstruct(); // callable from derived classes protected: // section to use in app's profile void EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly = FALSE); virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; // Generated message map functions protected: //{{AFX_MSG(CResizableDialog) afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnDestroy(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg BOOL OnEraseBkgnd(CDC* pDC); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RESIZABLEDIALOG_H__INCLUDED_)
C++
// ResizableMDIChild.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableMDIChild.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizableMDIChild IMPLEMENT_DYNCREATE(CResizableMDIChild, CMDIChildWnd) CResizableMDIChild::CResizableMDIChild() { m_bEnableSaveRestore = FALSE; } CResizableMDIChild::~CResizableMDIChild() { } BEGIN_MESSAGE_MAP(CResizableMDIChild, CMDIChildWnd) //{{AFX_MSG_MAP(CResizableMDIChild) ON_WM_GETMINMAXINFO() ON_WM_SIZE() ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizableMDIChild message handlers void CResizableMDIChild::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { MinMaxInfo(lpMMI); CView* pView = GetActiveView(); if (pView == NULL) return; // get the extra size from view to frame CRect rectClient, rectWnd; if (IsZoomed()) GetClientRect(rectWnd); else GetWindowRect(rectWnd); RepositionBars(0, 0xFFFF, AFX_IDW_PANE_FIRST, reposQuery, rectClient); CSize sizeExtra = rectWnd.Size() - rectClient.Size(); // ask the view for track size MINMAXINFO mmiView = *lpMMI; pView->SendMessage(WM_GETMINMAXINFO, 0, (LPARAM)&mmiView); mmiView.ptMaxTrackSize = sizeExtra + mmiView.ptMaxTrackSize; mmiView.ptMinTrackSize = sizeExtra + mmiView.ptMinTrackSize; // min size is the largest lpMMI->ptMinTrackSize.x = __max(lpMMI->ptMinTrackSize.x, mmiView.ptMinTrackSize.x); lpMMI->ptMinTrackSize.y = __max(lpMMI->ptMinTrackSize.y, mmiView.ptMinTrackSize.y); // max size is the shortest lpMMI->ptMaxTrackSize.x = __min(lpMMI->ptMaxTrackSize.x, mmiView.ptMaxTrackSize.x); lpMMI->ptMaxTrackSize.y = __min(lpMMI->ptMaxTrackSize.y, mmiView.ptMaxTrackSize.y); // MDI should call default implementation CMDIChildWnd::OnGetMinMaxInfo(lpMMI); } void CResizableMDIChild::OnSize(UINT nType, int cx, int cy) { CMDIChildWnd::OnSize(nType, cx, cy); // make sure the MDI parent frame doesn't clip // this child window when it is maximized if (nType == SIZE_MAXIMIZED) { CMDIFrameWnd* pFrame = GetMDIFrame(); CRect rect; pFrame->GetWindowRect(rect); pFrame->MoveWindow(rect); } } // NOTE: this must be called after setting the layout // to have the view and its controls displayed properly BOOL CResizableMDIChild::EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly) { m_sSection = pszSection; m_bEnableSaveRestore = TRUE; m_bRectOnly = bRectOnly; // restore immediately return LoadWindowRect(pszSection, bRectOnly); } void CResizableMDIChild::OnDestroy() { if (m_bEnableSaveRestore) SaveWindowRect(m_sSection, m_bRectOnly); CMDIChildWnd::OnDestroy(); }
C++
// ResizableGrip.cpp: implementation of the CResizableGrip class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableGrip.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CResizableGrip::CResizableGrip() { m_nShowCount = 0; } CResizableGrip::~CResizableGrip() { } void CResizableGrip::UpdateSizeGrip() { ASSERT(::IsWindow(m_wndGrip.m_hWnd)); // size-grip goes bottom right in the client area // (any right-to-left adjustment should go here) RECT rect; GetResizableWnd()->GetClientRect(&rect); rect.left = rect.right - m_wndGrip.m_size.cx; rect.top = rect.bottom - m_wndGrip.m_size.cy; // must stay below other children m_wndGrip.SetWindowPos(&CWnd::wndBottom, rect.left, rect.top, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREPOSITION | (IsSizeGripVisible() ? SWP_SHOWWINDOW : SWP_HIDEWINDOW)); } // pbStatus points to a variable, maintained by the caller, that // holds its visibility status. Initialize the variable with 1 // to allow to temporarily hide the grip, 0 to allow to // temporarily show the grip (with respect to the dwMask bit). // NB: visibility is effective only after an update void CResizableGrip::ShowSizeGrip(DWORD* pStatus, DWORD dwMask /*= 1*/) { ASSERT(pStatus != NULL); if (!(*pStatus & dwMask)) { m_nShowCount++; (*pStatus) |= dwMask; } } void CResizableGrip::HideSizeGrip(DWORD* pStatus, DWORD dwMask /*= 1*/) { ASSERT(pStatus != NULL); if (*pStatus & dwMask) { m_nShowCount--; (*pStatus) &= ~dwMask; } } BOOL CResizableGrip::IsSizeGripVisible() { // NB: visibility is effective only after an update return (m_nShowCount > 0); } void CResizableGrip::SetSizeGripVisibility(BOOL bVisible) { if (bVisible) m_nShowCount = 1; else m_nShowCount = 0; } BOOL CResizableGrip::SetSizeGripBkMode(int nBkMode) { if (::IsWindow(m_wndGrip.m_hWnd)) { if (nBkMode == OPAQUE) m_wndGrip.SetTransparency(FALSE); else if (nBkMode == TRANSPARENT) m_wndGrip.SetTransparency(TRUE); else return FALSE; return TRUE; } return FALSE; } void CResizableGrip::SetSizeGripShape(BOOL bTriangular) { m_wndGrip.SetTriangularShape(bTriangular); } BOOL CResizableGrip::CreateSizeGrip(BOOL bVisible /*= TRUE*/, BOOL bTriangular /*= TRUE*/, BOOL bTransparent /*= FALSE*/) { // create grip CRect rect(0 , 0, m_wndGrip.m_size.cx, m_wndGrip.m_size.cy); BOOL bRet = m_wndGrip.Create(WS_CHILD | WS_CLIPSIBLINGS | SBS_SIZEGRIP, rect, GetResizableWnd(), 0); if (bRet) { // set options m_wndGrip.SetTriangularShape(bTriangular); m_wndGrip.SetTransparency(bTransparent); SetSizeGripVisibility(bVisible); // update position UpdateSizeGrip(); } return bRet; } ///////////////////////////////////////////////////////////////////////////// // CSizeGrip implementation BOOL CResizableGrip::CSizeGrip::IsRTL() { return GetExStyle() & WS_EX_LAYOUTRTL; } BOOL CResizableGrip::CSizeGrip::PreCreateWindow(CREATESTRUCT& cs) { // set window size m_size.cx = GetSystemMetrics(SM_CXVSCROLL); m_size.cy = GetSystemMetrics(SM_CYHSCROLL); cs.cx = m_size.cx; cs.cy = m_size.cy; return CScrollBar::PreCreateWindow(cs); } LRESULT CResizableGrip::CSizeGrip::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_GETDLGCODE: // fix to prevent the control to gain focus, using arrow keys // (standard grip returns DLGC_WANTARROWS, like any standard scrollbar) return DLGC_STATIC; case WM_NCHITTEST: // choose proper cursor shape if (IsRTL()) return HTBOTTOMLEFT; else return HTBOTTOMRIGHT; break; case WM_SETTINGCHANGE: { // update grip's size CSize sizeOld = m_size; m_size.cx = GetSystemMetrics(SM_CXVSCROLL); m_size.cy = GetSystemMetrics(SM_CYHSCROLL); // resize transparency bitmaps if (m_bTransparent) { CClientDC dc(this); // destroy bitmaps m_bmGrip.DeleteObject(); m_bmMask.DeleteObject(); // re-create bitmaps m_bmGrip.CreateCompatibleBitmap(&dc, m_size.cx, m_size.cy); m_bmMask.CreateBitmap(m_size.cx, m_size.cy, 1, 1, NULL); } // re-calc shape if (m_bTriangular) SetTriangularShape(m_bTriangular); // reposition the grip CRect rect; GetWindowRect(rect); rect.InflateRect(m_size.cx - sizeOld.cx, m_size.cy - sizeOld.cy, 0, 0); ::MapWindowPoints(NULL, GetParent()->GetSafeHwnd(), (LPPOINT)&rect, 2); MoveWindow(rect, TRUE); } break; case WM_DESTROY: // perform clean up if (m_bTransparent) SetTransparency(FALSE); break; case WM_PAINT: if (m_bTransparent) { CPaintDC dc(this); // select bitmaps CBitmap *pOldGrip, *pOldMask; pOldGrip = m_dcGrip.SelectObject(&m_bmGrip); pOldMask = m_dcMask.SelectObject(&m_bmMask); // obtain original grip bitmap, make the mask and prepare masked bitmap CScrollBar::WindowProc(WM_PAINT, (WPARAM)m_dcGrip.GetSafeHdc(), lParam); m_dcGrip.SetBkColor(m_dcGrip.GetPixel(0, 0)); m_dcMask.BitBlt(0, 0, m_size.cx, m_size.cy, &m_dcGrip, 0, 0, SRCCOPY); m_dcGrip.BitBlt(0, 0, m_size.cx, m_size.cy, &m_dcMask, 0, 0, 0x00220326); // draw transparently dc.BitBlt(0, 0, m_size.cx, m_size.cy, &m_dcMask, 0, 0, SRCAND); dc.BitBlt(0, 0, m_size.cx, m_size.cy, &m_dcGrip, 0, 0, SRCPAINT); // unselect bitmaps m_dcGrip.SelectObject(pOldGrip); m_dcMask.SelectObject(pOldMask); return 0; } break; } return CScrollBar::WindowProc(message, wParam, lParam); } void CResizableGrip::CSizeGrip::SetTransparency(BOOL bActivate) { // creates or deletes DCs and Bitmaps used for // implementing a transparent size grip if (bActivate && !m_bTransparent) { m_bTransparent = TRUE; CClientDC dc(this); // create memory DCs and bitmaps m_dcGrip.CreateCompatibleDC(&dc); m_bmGrip.CreateCompatibleBitmap(&dc, m_size.cx, m_size.cy); m_dcMask.CreateCompatibleDC(&dc); m_bmMask.CreateBitmap(m_size.cx, m_size.cy, 1, 1, NULL); } else if (!bActivate && m_bTransparent) { m_bTransparent = FALSE; // destroy memory DCs and bitmaps m_dcGrip.DeleteDC(); m_bmGrip.DeleteObject(); m_dcMask.DeleteDC(); m_bmMask.DeleteObject(); } } void CResizableGrip::CSizeGrip::SetTriangularShape(BOOL bEnable) { m_bTriangular = bEnable; if (bEnable) { // set a triangular window region CRect rect; GetWindowRect(rect); rect.OffsetRect(-rect.TopLeft()); POINT arrPoints[] = { { rect.left, rect.bottom }, { rect.right, rect.bottom }, { rect.right, rect.top } }; CRgn rgnGrip; rgnGrip.CreatePolygonRgn(arrPoints, 3, WINDING); SetWindowRgn((HRGN)rgnGrip.Detach(), IsWindowVisible()); } else { SetWindowRgn((HRGN)NULL, IsWindowVisible()); } }
C++
#if !defined(AFX_RESIZABLEMDIFRAME_H__4BA07057_6EF3_43A4_A80B_A24FA3A8B5C7__INCLUDED_) #define AFX_RESIZABLEMDIFRAME_H__4BA07057_6EF3_43A4_A80B_A24FA3A8B5C7__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ResizableMDIFrame.h : header file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableMinMax.h" #include "ResizableState.h" ///////////////////////////////////////////////////////////////////////////// // CResizableMDIFrame frame class CResizableMDIFrame : public CMDIFrameWnd, public CResizableMinMax, public CResizableState { DECLARE_DYNCREATE(CResizableMDIFrame) protected: CResizableMDIFrame(); // protected constructor used by dynamic creation // Attributes protected: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizableMDIFrame) //}}AFX_VIRTUAL // Implementation protected: virtual ~CResizableMDIFrame(); BOOL EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly = FALSE); virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; private: // flags BOOL m_bEnableSaveRestore; BOOL m_bRectOnly; // internal status CString m_sSection; // section name (identifies a parent window) protected: // Generated message map functions //{{AFX_MSG(CResizableMDIFrame) afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnDestroy(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RESIZABLEMDIFRAME_H__4BA07057_6EF3_43A4_A80B_A24FA3A8B5C7__INCLUDED_)
C++
#if !defined(AFX_RESIZABLEMDICHILD_H__EA9AE112_0E99_4D6E_B42B_A3BA9DE3756E__INCLUDED_) #define AFX_RESIZABLEMDICHILD_H__EA9AE112_0E99_4D6E_B42B_A3BA9DE3756E__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ResizableMDIChild.h : header file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableMinMax.h" #include "ResizableState.h" ///////////////////////////////////////////////////////////////////////////// // CResizableMDIChild frame class CResizableMDIChild : public CMDIChildWnd, public CResizableMinMax, public CResizableState { DECLARE_DYNCREATE(CResizableMDIChild) protected: CResizableMDIChild(); // protected constructor used by dynamic creation // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizableMDIChild) protected: //}}AFX_VIRTUAL // Implementation protected: virtual ~CResizableMDIChild(); BOOL EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly = FALSE); virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; private: // flags BOOL m_bEnableSaveRestore; BOOL m_bRectOnly; // internal status CString m_sSection; // section name (identifies a parent window) protected: // Generated message map functions //{{AFX_MSG(CResizableMDIChild) afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnDestroy(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_RESIZABLEMDICHILD_H__EA9AE112_0E99_4D6E_B42B_A3BA9DE3756E__INCLUDED_)
C++
// ResizableState.h: interface for the CResizableState class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESIZABLESTATE_H__INCLUDED_) #define AFX_RESIZABLESTATE_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CResizableState { protected: // non-zero if successful BOOL LoadWindowRect(LPCTSTR pszSection, BOOL bRectOnly); BOOL SaveWindowRect(LPCTSTR pszSection, BOOL bRectOnly); virtual CWnd* GetResizableWnd() = 0; public: CResizableState(); virtual ~CResizableState(); }; #endif // !defined(AFX_RESIZABLESTATE_H__INCLUDED_)
C++
#if !defined(AFX_RESIZABLESHEET_H__INCLUDED_) #define AFX_RESIZABLESHEET_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "ResizableLayout.h" #include "ResizableGrip.h" #include "ResizableMinMax.h" #include "ResizableState.h" ///////////////////////////////////////////////////////////////////////////// // ResizableSheet.h : header file // class CResizableSheet : public CPropertySheet, public CResizableLayout, public CResizableGrip, public CResizableMinMax, public CResizableState { DECLARE_DYNAMIC(CResizableSheet) // Construction public: CResizableSheet(); CResizableSheet(UINT nIDCaption, CWnd *pParentWnd = NULL, UINT iSelectPage = 0); CResizableSheet(LPCTSTR pszCaption, CWnd *pParentWnd = NULL, UINT iSelectPage = 0); // Attributes private: // support for temporarily hiding the grip DWORD m_dwGripTempState; // flags BOOL m_bEnableSaveRestore; BOOL m_bRectOnly; BOOL m_bSavePage; // layout vars CSize m_sizePageTL, m_sizePageBR; // internal status CString m_sSection; // section name (identifies a parent window) // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CResizableSheet) public: virtual BOOL OnInitDialog(); //}}AFX_VIRTUAL protected: // Implementation public: void RefreshLayout(); virtual ~CResizableSheet(); // used internally private: void PresetLayout(); void PrivateConstruct(); void SavePage(); void LoadPage(); BOOL IsWizard() { return (m_psh.dwFlags & PSH_WIZARD); } // callable from derived classes protected: // section to use in app's profile void EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly = FALSE, BOOL bWithPage = FALSE); int GetMinWidth(); // minimum width to display all buttons virtual CWnd* GetResizableWnd() { // make the layout know its parent window return this; }; // Generated message map functions protected: virtual BOOL ArrangeLayoutCallback(LayoutInfo& layout); //{{AFX_MSG(CResizableSheet) afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnDestroy(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg BOOL OnEraseBkgnd(CDC* pDC); //}}AFX_MSG afx_msg BOOL OnPageChanging(NMHDR* pNotifyStruct, LRESULT* pResult); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// #endif // AFX_RESIZABLESHEET_H__INCLUDED_
C++
// ResizableDialog.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizableDialog inline void CResizableDialog::PrivateConstruct() { m_bEnableSaveRestore = FALSE; m_dwGripTempState = 1; } CResizableDialog::CResizableDialog() { PrivateConstruct(); } CResizableDialog::CResizableDialog(UINT nIDTemplate, CWnd* pParentWnd) : CDialog(nIDTemplate, pParentWnd) { PrivateConstruct(); } CResizableDialog::CResizableDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd) : CDialog(lpszTemplateName, pParentWnd) { PrivateConstruct(); } CResizableDialog::~CResizableDialog() { } BEGIN_MESSAGE_MAP(CResizableDialog, CDialog) //{{AFX_MSG_MAP(CResizableDialog) ON_WM_GETMINMAXINFO() ON_WM_SIZE() ON_WM_DESTROY() ON_WM_CREATE() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizableDialog message handlers int CResizableDialog::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialog::OnCreate(lpCreateStruct) == -1) return -1; // child dialogs don't want resizable border or size grip, // nor they can handle the min/max size constraints BOOL bChild = GetStyle() & WS_CHILD; if (!bChild) { // keep client area CRect rect; GetClientRect(&rect); // set resizable style ModifyStyle(DS_MODALFRAME, WS_POPUP | WS_THICKFRAME); // adjust size to reflect new style ::AdjustWindowRectEx(&rect, GetStyle(), ::IsMenu(GetMenu()->GetSafeHmenu()), GetExStyle()); SetWindowPos(NULL, 0, 0, rect.Width(), rect.Height(), SWP_FRAMECHANGED| SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOREPOSITION); // set the initial size as the min track size SetMinTrackSize(rect.Size()); } // create and init the size-grip if (!CreateSizeGrip(!bChild)) return -1; return 0; } void CResizableDialog::OnDestroy() { if (m_bEnableSaveRestore) SaveWindowRect(m_sSection, m_bRectOnly); // remove child windows RemoveAllAnchors(); CDialog::OnDestroy(); } void CResizableDialog::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); if (nType == SIZE_MAXHIDE || nType == SIZE_MAXSHOW) return; // arrangement not needed if (nType == SIZE_MAXIMIZED) HideSizeGrip(&m_dwGripTempState); else ShowSizeGrip(&m_dwGripTempState); // update grip and layout UpdateSizeGrip(); ArrangeLayout(); } void CResizableDialog::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { MinMaxInfo(lpMMI); } // NOTE: this must be called after setting the layout // to have the dialog and its controls displayed properly void CResizableDialog::EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly) { m_sSection = pszSection; m_bEnableSaveRestore = TRUE; m_bRectOnly = bRectOnly; // restore immediately LoadWindowRect(pszSection, bRectOnly); } BOOL CResizableDialog::OnEraseBkgnd(CDC* pDC) { // Windows XP doesn't like clipping regions ...try this! EraseBackground(pDC); return TRUE; /* ClipChildren(pDC); // old-method (for safety) return CDialog::OnEraseBkgnd(pDC); */ }
C++
// ResizableMsgSupport.inl: some definitions to support custom resizable wnds // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// // registered message to communicate with the library // (defined so that in the same executable it is initialized only once) const UINT WMU_RESIZESUPPORT = ::RegisterWindowMessage(_T("WMU_RESIZESUPPORT")); // if the message is implemented the returned value must be non-zero // the default window procedure returns zero for unhandled messages // wParam is one of the following RSZSUP_* values, lParam as specified #define RSZSUP_QUERYPROPERTIES 101 // lParam = LPRESIZEPROPERTIES #define RSZSUP_LIKESCLIPPING 102 // lParam = LPCLIPPINGPROPERTY #define RSZSUP_NEEDSREFRESH 103 // lParam = LPREFRESHPROPERTY ///////////////////////////////////////////////////////////////////////////// // utility functions inline BOOL Send_QueryProperties(HWND hWnd, LPRESIZEPROPERTIES pResizeProperties) { ASSERT(::IsWindow(hWnd)); return (0 != SendMessage(hWnd, WMU_RESIZESUPPORT, RSZSUP_QUERYPROPERTIES, (LPARAM)pResizeProperties)); } inline BOOL Send_LikesClipping(HWND hWnd, LPCLIPPINGPROPERTY pClippingProperty) { ASSERT(::IsWindow(hWnd)); return (0 != SendMessage(hWnd, WMU_RESIZESUPPORT, RSZSUP_LIKESCLIPPING, (LPARAM)pClippingProperty)); } inline BOOL Send_NeedsRefresh(HWND hWnd, LPREFRESHPROPERTY pRefreshProperty) { ASSERT(::IsWindow(hWnd)); return (0 != SendMessage(hWnd, WMU_RESIZESUPPORT, RSZSUP_NEEDSREFRESH, (LPARAM)pRefreshProperty)); }
C++
// ResizablePageEx.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// // #include "stdafx.h" #define _WIN32_IE 0x0400 // for CPropertyPageEx, CPropertySheetEx #define _WIN32_WINNT 0x0500 // for CPropertyPageEx, CPropertySheetEx #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxcmn.h> // MFC support for Windows Common Controls #include "ResizablePageEx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizablePageEx IMPLEMENT_DYNCREATE(CResizablePageEx, CPropertyPageEx) CResizablePageEx::CResizablePageEx() { } CResizablePageEx::CResizablePageEx(UINT nIDTemplate, UINT nIDCaption, UINT nIDHeaderTitle, UINT nIDHeaderSubTitle) : CPropertyPageEx(nIDTemplate, nIDCaption, nIDHeaderTitle, nIDHeaderSubTitle) { } CResizablePageEx::CResizablePageEx(LPCTSTR lpszTemplateName, UINT nIDCaption, UINT nIDHeaderTitle, UINT nIDHeaderSubTitle) : CPropertyPageEx(lpszTemplateName, nIDCaption, nIDHeaderTitle, nIDHeaderSubTitle) { } CResizablePageEx::~CResizablePageEx() { } BEGIN_MESSAGE_MAP(CResizablePageEx, CPropertyPageEx) //{{AFX_MSG_MAP(CResizablePageEx) ON_WM_SIZE() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizablePageEx message handlers void CResizablePageEx::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); ArrangeLayout(); } BOOL CResizablePageEx::OnEraseBkgnd(CDC* pDC) { // Windows XP doesn't like clipping regions ...try this! EraseBackground(pDC); return TRUE; /* ClipChildren(pDC); // old-method (for safety) return CPropertyPageEx::OnEraseBkgnd(pDC); */ } BOOL CResizablePageEx::NeedsRefresh(const CResizableLayout::LayoutInfo& layout, const CRect& rectOld, const CRect& rectNew) { if (m_psp.dwFlags | PSP_HIDEHEADER) return TRUE; return CResizableLayout::NeedsRefresh(layout, rectOld, rectNew); }
C++
// ResizableFormView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableFormView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizableFormView IMPLEMENT_DYNAMIC(CResizableFormView, CFormView) inline void CResizableFormView::PrivateConstruct() { m_bInitDone = FALSE; m_dwGripTempState = GHR_SCROLLBAR | GHR_ALIGNMENT | GHR_MAXIMIZED; } CResizableFormView::CResizableFormView(UINT nIDTemplate) : CFormView(nIDTemplate) { PrivateConstruct(); } CResizableFormView::CResizableFormView(LPCTSTR lpszTemplateName) : CFormView(lpszTemplateName) { PrivateConstruct(); } CResizableFormView::~CResizableFormView() { } BEGIN_MESSAGE_MAP(CResizableFormView, CFormView) //{{AFX_MSG_MAP(CResizableFormView) ON_WM_SIZE() ON_WM_ERASEBKGND() ON_WM_CREATE() ON_WM_GETMINMAXINFO() ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizableFormView diagnostics #ifdef _DEBUG void CResizableFormView::AssertValid() const { CFormView::AssertValid(); } void CResizableFormView::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CResizableFormView message handlers void CResizableFormView::OnSize(UINT nType, int cx, int cy) { CFormView::OnSize(nType, cx, cy); CWnd* pParent = GetParent(); // hide zise grip when parent is maximized if (pParent->IsZoomed()) HideSizeGrip(&m_dwGripTempState, GHR_MAXIMIZED); else ShowSizeGrip(&m_dwGripTempState, GHR_MAXIMIZED); // hide size grip when there are scrollbars CSize size = GetTotalSize(); if (cx < size.cx || cy < size.cy) HideSizeGrip(&m_dwGripTempState, GHR_SCROLLBAR); else ShowSizeGrip(&m_dwGripTempState, GHR_SCROLLBAR); // hide size grip when the parent window is not resizable // or the form is not bottom-right aligned (e.g. there's a statusbar) DWORD dwStyle = pParent->GetStyle(); CRect rectParent, rectChild; GetWindowRect(rectChild); ::MapWindowPoints(NULL, pParent->GetSafeHwnd(), (LPPOINT)&rectChild, 2); pParent->GetClientRect(rectParent); if (!(dwStyle & WS_THICKFRAME) || (rectChild.BottomRight() != rectParent.BottomRight())) HideSizeGrip(&m_dwGripTempState, GHR_ALIGNMENT); else ShowSizeGrip(&m_dwGripTempState, GHR_ALIGNMENT); // update grip and layout UpdateSizeGrip(); ArrangeLayout(); } void CResizableFormView::OnInitialUpdate() { CFormView::OnInitialUpdate(); m_bInitDone = TRUE; // MDI child need this ArrangeLayout(); } void CResizableFormView::GetTotalClientRect(LPRECT lpRect) { GetClientRect(lpRect); // get dialog template's size // (this is set in CFormView::Create) CSize size = GetTotalSize(); // before initialization use dialog's size if (!m_bInitDone) { lpRect->right = lpRect->left + size.cx; lpRect->bottom = lpRect->top + size.cy; return; } // otherwise, give the correct size if scrollbars active if (m_nMapMode < 0) // scrollbars disabled return; // enlarge reported client area when needed CRect rect(lpRect); if (rect.Width() < size.cx) rect.right = rect.left + size.cx; if (rect.Height() < size.cy) rect.bottom = rect.top + size.cy; rect.OffsetRect(-GetScrollPosition()); *lpRect = rect; } BOOL CResizableFormView::OnEraseBkgnd(CDC* pDC) { // Windows XP doesn't like clipping regions ...try this! EraseBackground(pDC); return TRUE; /* ClipChildren(pDC); // old-method (for safety) return CFormView::OnEraseBkgnd(pDC); */ } int CResizableFormView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFormView::OnCreate(lpCreateStruct) == -1) return -1; // create and init the size-grip if (!CreateSizeGrip()) return -1; return 0; } void CResizableFormView::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { MinMaxInfo(lpMMI); } void CResizableFormView::OnDestroy() { RemoveAllAnchors(); CFormView::OnDestroy(); }
C++
// ResizableSheet.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResizableSheet.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CResizableSheet IMPLEMENT_DYNAMIC(CResizableSheet, CPropertySheet) inline void CResizableSheet::PrivateConstruct() { m_bEnableSaveRestore = FALSE; m_bSavePage = FALSE; m_dwGripTempState = 1; } CResizableSheet::CResizableSheet() { PrivateConstruct(); } CResizableSheet::CResizableSheet(UINT nIDCaption, CWnd *pParentWnd, UINT iSelectPage) : CPropertySheet(nIDCaption, pParentWnd, iSelectPage) { PrivateConstruct(); } CResizableSheet::CResizableSheet(LPCTSTR pszCaption, CWnd *pParentWnd, UINT iSelectPage) : CPropertySheet(pszCaption, pParentWnd, iSelectPage) { PrivateConstruct(); } CResizableSheet::~CResizableSheet() { } BEGIN_MESSAGE_MAP(CResizableSheet, CPropertySheet) //{{AFX_MSG_MAP(CResizableSheet) ON_WM_GETMINMAXINFO() ON_WM_SIZE() ON_WM_DESTROY() ON_WM_CREATE() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP ON_NOTIFY_REFLECT_EX(PSN_SETACTIVE, OnPageChanging) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResizableSheet message handlers int CResizableSheet::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CPropertySheet::OnCreate(lpCreateStruct) == -1) return -1; // keep client area CRect rect; GetClientRect(&rect); // set resizable style ModifyStyle(DS_MODALFRAME, WS_POPUP | WS_THICKFRAME); // adjust size to reflect new style ::AdjustWindowRectEx(&rect, GetStyle(), ::IsMenu(GetMenu()->GetSafeHmenu()), GetExStyle()); SetWindowPos(NULL, 0, 0, rect.Width(), rect.Height(), SWP_FRAMECHANGED| SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOREPOSITION); // create and init the size-grip if (!CreateSizeGrip()) return -1; return 0; } BOOL CResizableSheet::OnInitDialog() { BOOL bResult = CPropertySheet::OnInitDialog(); // set the initial size as the min track size CRect rc; GetWindowRect(&rc); SetMinTrackSize(rc.Size()); // initialize layout PresetLayout(); // prevent flickering GetTabControl()->ModifyStyle(0, WS_CLIPSIBLINGS); return bResult; } void CResizableSheet::OnDestroy() { if (m_bEnableSaveRestore) { SaveWindowRect(m_sSection, m_bRectOnly); SavePage(); } RemoveAllAnchors(); CPropertySheet::OnDestroy(); } // maps an index to a button ID and vice-versa static UINT _propButtons[] = { IDOK, IDCANCEL, ID_APPLY_NOW, IDHELP, ID_WIZBACK, ID_WIZNEXT, ID_WIZFINISH }; const int _propButtonsCount = sizeof(_propButtons)/sizeof(UINT); // horizontal line in wizard mode #define ID_WIZLINE ID_WIZFINISH+1 void CResizableSheet::PresetLayout() { if (IsWizard()) // wizard mode { // hide tab control GetTabControl()->ShowWindow(SW_HIDE); AddAnchor(ID_WIZLINE, BOTTOM_LEFT, BOTTOM_RIGHT); } else // tab mode { AddAnchor(AFX_IDC_TAB_CONTROL, TOP_LEFT, BOTTOM_RIGHT); } // add a callback for active page (which can change at run-time) AddAnchorCallback(1); // use *total* parent size to have correct margins CRect rectPage, rectSheet; GetTotalClientRect(&rectSheet); GetActivePage()->GetWindowRect(&rectPage); ::MapWindowPoints(NULL, m_hWnd, (LPPOINT)&rectPage, 2); // pre-calculate margins m_sizePageTL = rectPage.TopLeft() - rectSheet.TopLeft(); m_sizePageBR = rectPage.BottomRight() - rectSheet.BottomRight(); // add all possible buttons, if they exist for (int i = 0; i < _propButtonsCount; i++) { if (NULL != GetDlgItem(_propButtons[i])) AddAnchor(_propButtons[i], BOTTOM_RIGHT); } } BOOL CResizableSheet::ArrangeLayoutCallback(LayoutInfo &layout) { if (layout.nCallbackID != 1) // we only added 1 callback return CResizableLayout::ArrangeLayoutCallback(layout); // set layout info for active page layout.hWnd = (HWND)::SendMessage(m_hWnd, PSM_GETCURRENTPAGEHWND, 0, 0); if (!::IsWindow(layout.hWnd)) return FALSE; // set margins if (IsWizard()) // wizard mode { // use pre-calculated margins layout.sizeMarginTL = m_sizePageTL; layout.sizeMarginBR = m_sizePageBR; } else // tab mode { CTabCtrl* pTab = GetTabControl(); ASSERT(pTab != NULL); // get tab position after resizing and calc page rect CRect rectPage, rectSheet; GetTotalClientRect(&rectSheet); VERIFY(GetAnchorPosition(pTab->m_hWnd, rectSheet, rectPage)); pTab->AdjustRect(FALSE, &rectPage); // set margins layout.sizeMarginTL = rectPage.TopLeft() - rectSheet.TopLeft(); layout.sizeMarginBR = rectPage.BottomRight() - rectSheet.BottomRight(); } // set anchor types layout.sizeTypeTL = TOP_LEFT; layout.sizeTypeBR = BOTTOM_RIGHT; // use this layout info return TRUE; } void CResizableSheet::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); if (nType == SIZE_MAXHIDE || nType == SIZE_MAXSHOW) return; // arrangement not needed if (nType == SIZE_MAXIMIZED) HideSizeGrip(&m_dwGripTempState); else ShowSizeGrip(&m_dwGripTempState); // update grip and layout UpdateSizeGrip(); ArrangeLayout(); } BOOL CResizableSheet::OnPageChanging(NMHDR* /*pNotifyStruct*/, LRESULT* /*pResult*/) { // update new wizard page // active page changes after this notification PostMessage(WM_SIZE); return FALSE; // continue routing } BOOL CResizableSheet::OnEraseBkgnd(CDC* pDC) { // Windows XP doesn't like clipping regions ...try this! EraseBackground(pDC); return TRUE; /* ClipChildren(pDC); // old-method (for safety) return CPropertySheet::OnEraseBkgnd(pDC); */ } void CResizableSheet::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { MinMaxInfo(lpMMI); } // protected members int CResizableSheet::GetMinWidth() { CWnd* pWnd = NULL; CRect rectWnd, rectSheet; GetTotalClientRect(&rectSheet); int max = 0, min = rectSheet.Width(); // search for leftmost and rightmost button margins for (int i = 0; i < 7; i++) { pWnd = GetDlgItem(_propButtons[i]); // exclude not present or hidden buttons if (pWnd == NULL || !(pWnd->GetStyle() & WS_VISIBLE)) continue; // left position is relative to the right border // of the parent window (negative value) pWnd->GetWindowRect(&rectWnd); ::MapWindowPoints(NULL, m_hWnd, (LPPOINT)&rectWnd, 2); int left = rectSheet.right - rectWnd.left; int right = rectSheet.right - rectWnd.right; if (left > max) max = left; if (right < min) min = right; } // sizing border width int border = GetSystemMetrics(SM_CXSIZEFRAME); // compute total width return max + min + 2*border; } // NOTE: this must be called after all the other settings // to have the window and its controls displayed properly void CResizableSheet::EnableSaveRestore(LPCTSTR pszSection, BOOL bRectOnly, BOOL bWithPage) { m_sSection = pszSection; m_bSavePage = bWithPage; m_bEnableSaveRestore = TRUE; m_bRectOnly = bRectOnly; // restore immediately LoadWindowRect(pszSection, bRectOnly); LoadPage(); } // private memebers // used to save/restore active page // either in the registry or a private .INI file // depending on your application settings #define ACTIVEPAGE _T("ActivePage") void CResizableSheet::SavePage() { if (!m_bSavePage) return; // saves active page index, zero (the first) if problems // cannot use GetActivePage, because it always fails CTabCtrl *pTab = GetTabControl(); int page = 0; if (pTab != NULL) page = pTab->GetCurSel(); if (page < 0) page = 0; AfxGetApp()->WriteProfileInt(m_sSection, ACTIVEPAGE, page); } void CResizableSheet::LoadPage() { // restore active page, zero (the first) if not found int page = AfxGetApp()->GetProfileInt(m_sSection, ACTIVEPAGE, 0); if (m_bSavePage) { SetActivePage(page); ArrangeLayout(); // needs refresh } } void CResizableSheet::RefreshLayout() { SendMessage(WM_SIZE); }
C++
// ResizableMinMax.h: interface for the CResizableMinMax class. // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002 by Paolo Messina // (http://www.geocities.com/ppescher - ppescher@yahoo.com) // // The contents of this file are subject to the Artistic License (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.opensource.org/licenses/artistic-license.html // // If you find this code useful, credits would be nice! // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESIZABLEMINMAX_H__INCLUDED_) #define AFX_RESIZABLEMINMAX_H__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CResizableMinMax { // Attributes private: // flags BOOL m_bUseMaxTrack; BOOL m_bUseMinTrack; BOOL m_bUseMaxRect; POINT m_ptMinTrackSize; // min tracking size POINT m_ptMaxTrackSize; // max tracking size POINT m_ptMaxPos; // maximized position POINT m_ptMaxSize; // maximized size public: CResizableMinMax(); virtual ~CResizableMinMax(); protected: void MinMaxInfo(LPMINMAXINFO lpMMI); void SetMaximizedRect(const CRect& rc); // set window rect when maximized void ResetMaximizedRect(); // reset to default maximized rect void SetMinTrackSize(const CSize& size); // set minimum tracking size void ResetMinTrackSize(); // reset to default minimum tracking size void SetMaxTrackSize(const CSize& size); // set maximum tracking size void ResetMaxTrackSize(); // reset to default maximum tracking size }; #endif // !defined(AFX_RESIZABLEMINMAX_H__INCLUDED_)
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include "popup.h" #include "popupDlg.h" #include "PopupClient.h" #include "PopupServer.h" #include "OtherFunctions.h" #include "PopupLibUtilities.h" #include "ResourceEntry.h" #include "PopupClientThread.h" #include "PopupServerThread.h" #include <vector> #include <sstream> #include <string> using namespace std; CMutex CpopupApp::s_clientmutex; /////////////////////////////////////////////////////////////////////////////// // CpopupApp CpopupApp::CpopupApp(LPCTSTR lpszAppName) :CWinApp(lpszAppName), popupdlg(0), m_popupclient(0), m_popupserver(0), m_resetTimer(true), m_automode(POPUP_MODE_MUTED), m_automodeDelay(0) { } CpopupApp theApp(_T("ePopup")); BOOL CpopupApp::InitInstance() { CWinApp::InitInstance(); if (!loadEnvironment()) { AfxMessageBox(_T("Failed everything!! I'm a crap!")); ::ExitProcess(1); } // Create/Touch user directory if (!initUserDirectory()) { AfxMessageBox(_T("Failed to create user dir")); ::ExitProcess(1); } // Load options if (!loadOptions()) { AfxMessageBox(_T("Failed to load options")); ::ExitProcess(1); } // Load resources if (!loadResources()) { AfxMessageBox(_T("Warning : no resource loaded!")); } // Init logger m_logger.setPath(MFCStringToSTLString(m_userdir)); // Create main dialog CpopupDlg *dlg = new CpopupDlg(); popupdlg = dlg; m_pMainWnd = dlg; // Main window (which owns the main thread!) dlg->DoModal(); delete dlg; popupdlg = NULL; return FALSE; } void CpopupApp::exitApp() { popupdlg->EndDialog(0); } bool CpopupApp::loadEnvironment() { ULONG size = USER_NAME_MAX_LENGTH; TCHAR user[USER_NAME_MAX_LENGTH]; char hostname[HOSTNAME_MAX_LENGTH]; bool _res = true; // Get user name if (GetUserName(user, &size) == 0) { _res = false; } else { user[size] = '\0'; m_username = user; } // Start WSA (Fucking MFC!) WORD wVersionRequested; wVersionRequested = MAKEWORD( 2, 2 ); WSADATA wsaData; int _errcode = WSAStartup( wVersionRequested, &wsaData ); // Get hostname if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) { _errcode = WSAGetLastError(); AfxMessageBox(_T("Failed to get hostname! Exiting")); _res = false; } else { m_hostname = hostname; } // Set user directory and ini file TCHAR tcDirName[_MAX_PATH]; GetEnvironmentVariable(_T("userprofile"), tcDirName, _MAX_PATH); m_userdir = CString(tcDirName) + _T("\\popup"); m_tempdir = m_userdir + _T("\\temp"); m_inifile = m_userdir + _T("\\popup.ini"); return _res; } bool CpopupApp::initUserDirectory() { bool _rc = false; if (CreateDirectory(m_userdir, NULL) != 0 || GetLastError() == ERROR_ALREADY_EXISTS) { deleteDirectory(m_tempdir); if (CreateDirectory(m_tempdir, NULL) != 0 || GetLastError() == ERROR_ALREADY_EXISTS) { _rc = true; } } return _rc; } ResourceEntry *CpopupApp::getRandomResource() { ResourceEntry *_res = NULL; if (m_resources.size() > 0) { int _randomIndex = rand() % m_resources.size(); PopupResources::iterator it = m_resources.begin(); for (int i = 0; i < _randomIndex; it++, i++); _res = it->second; } return _res; } bool CpopupApp::saveOptions() { string opt, app, args; int n; if (!m_options.getOption(POPUP_RES_PATH, opt)) { m_options.setOption(POPUP_RES_PATH, MFCStringToSTLString(m_userdir)); } if (!m_options.getOption(SERVER_HOSTNAME, opt)) { m_options.setOption(SERVER_HOSTNAME, "127.0.0.1"); } if (!m_options.getIntOption(SERVER_PORT, n)) { m_options.setIntOption(SERVER_PORT, 2000); } if (!m_options.getOption(CLIENT_USER_NAME, opt)) { m_options.setOption(CLIENT_USER_NAME, MFCStringToSTLString(m_username)); } if (!m_options.getOption(AUTO_MODE, opt)) { m_options.setOption(AUTO_MODE, "normal"); } if (!m_options.getIntOption(AUTO_MODE_DELAY, n)) { m_options.setIntOption(AUTO_MODE_DELAY, 120); } if (!m_options.getOption(WEB_BROWSER_PATH, opt)) { m_options.setOption(WEB_BROWSER_PATH, "iexplore.exe"); } if (!getApplicationByExtension(APP_DEFAULT_EXTENSION, app, args)) { m_options.setOption(APP_DEFAULT_EXTENSION, "explorer.exe", APP_ASSOCIATIONS_KEY); } return m_options.save(MFCStringToSTLString(m_inifile)); } bool CpopupApp::loadOptions() { bool _res = m_options.load(MFCStringToSTLString(m_inifile)); // Save options to force mandatory options to be set! if (_res != true) { AfxMessageBox(_T("Failed to load options. Applying defauls!")); } _res = saveOptions(); // Get server ip and port from option file string _server; int _port = 0; _res = (m_options.getOption(SERVER_HOSTNAME, _server) && m_options.getIntOption(SERVER_PORT, _port)); if (_res == true) { m_servername = _server; m_serverport = _port; } // Eventually, load user name, and auto mode options (not mandatory) string _username; string _automode; int _automodeDelay; if (m_options.getOption(CLIENT_USER_NAME, _username)) { m_username = CString(_username.c_str()); } if (m_options.getOption(AUTO_MODE, _automode)) { m_automode = stringToPopupMode(_automode); } if (m_options.getIntOption(AUTO_MODE_DELAY, _automodeDelay)) { m_automodeDelay = _automodeDelay; } return _res; } CString g_rcPath(""); bool CpopupApp::loadResources() { CFileFind finder; string tmp; string resourcePath; // Get resource path m_options.getOption(POPUP_RES_PATH, resourcePath); absolutePath(resourcePath, resourcePath); m_options.setOption(POPUP_RES_PATH, resourcePath); m_logger << "Resource path = " << resourcePath << endl; m_logger.flush(); // Open it! g_rcPath = (resourcePath + "\\*").c_str(); BOOL ok = finder.FindFile(g_rcPath); if (ok) m_resources.clear(); while (ok) { ok = finder.FindNextFile(); if (finder.IsDirectory() && !finder.IsDots()) { m_logger << _T("Loading resources from ... ") << finder.GetFileName() << endl; loadResourceDir(finder.GetFilePath()); } } m_logger.flush(); dumpResources(); return (m_resources.size() > 0); } bool CpopupApp::loadResourceDir(const CString & p_dir) { CFileFind finder; ResourceEntry *_resource = new ResourceEntry(); BOOL ok = finder.FindFile(p_dir + _T("\\*")); while (ok) { ok = finder.FindNextFile(); if (!finder.IsDirectory() && !finder.IsDots()) { CString filePath = finder.GetFilePath(); if (isImage(filePath)) { _resource->m_imagesPath.push_back(filePath); } else if (isSound(filePath)) { _resource->m_soundsPath.push_back(filePath); } else if (isVideo(filePath)) { _resource->m_videosPath.push_back(filePath); } } } if (_resource->m_imagesPath.size() > 0 || _resource->m_soundsPath.size() > 0 || _resource->m_videosPath.size() > 0 ) { m_resources[basename(p_dir)] = _resource; return true; } else { delete _resource; return false; } } bool CpopupApp::dumpResources() { CpopupApp::PopupResources::iterator _it = m_resources.begin(); m_logger << " List of resources" << endl; m_logger << " ................." << endl; m_logger.flush(); while (_it != m_resources.end()) { ResourceEntry *_rc = _it->second; // Dump images m_logger << " [images]" << endl; vector<CString>::iterator _itImage = _rc->m_imagesPath.begin(); while (_itImage != _rc->m_imagesPath.end()) { m_logger << _T(" + ") << (*_itImage) << endl; _itImage++; } // Dump sounds m_logger << " [sounds]" << endl; vector<CString>::iterator _itSound = _rc->m_soundsPath.begin(); while (_itSound != _rc->m_soundsPath.end()) { m_logger << _T(" + ") << (*_itSound) << endl; _itSound++; } // Dump sounds m_logger << " [videos]" << endl; vector<CString>::iterator _itvideo = _rc->m_videosPath.begin(); while (_itvideo != _rc->m_videosPath.end()) { m_logger << _T(" + ") << (*_itvideo) << endl; _itvideo++; } m_logger.flush(); _it++; } return true; } bool CpopupApp::restartNetwork() { if (m_popupserver != 0) { m_popupserver->kill(); } else { popupdlg->startServer(); } if (m_popupclient != 0) { m_popupclient->kill(); } return true; } bool CpopupApp::getApplicationByExtension(const string & p_extension, string & p_app, string & p_args, bool _setDefault) { bool _rc = true; string _extension = p_extension; // Try to find extension application first if (m_options.getOption(_extension, p_app, APP_ASSOCIATIONS_KEY) == false) { // If not found, try to get default one if (_setDefault && m_options.getOption(APP_DEFAULT_EXTENSION, p_app, APP_ASSOCIATIONS_KEY)) { _extension = APP_DEFAULT_EXTENSION; } // If still nothing, we give up! else { _rc = false; } } // Find arguments associated to the application if (_rc == true) { stringstream _argskey; _argskey << p_extension << APP_ARGS_SUFFIX; m_options.getOption(_argskey.str(), p_args, APP_ASSOCIATIONS_KEY); } return _rc; } bool CpopupApp::openFile(const string & p_file) { // First of all, we have to retrieve the appropriate application // to open the selected file //--------------------- // Let extract the file extension string _extension; if (getFileExtension(p_file, _extension) != true) { _extension = APP_DEFAULT_EXTENSION; } // Now let's try to find an appropriate application... //---------------------- string _app, _args; if (getApplicationByExtension(_extension, _app, _args)) { // Build application arguments stringstream _s; _s << "\"" << p_file << "\" " << _args; CString _applicationArgs(_s.str().c_str()); CString _applicationToUse(_app.c_str()); SHELLEXECUTEINFO ExecuteInfo; memset(&ExecuteInfo, 0, sizeof(ExecuteInfo)); ExecuteInfo.cbSize = sizeof(ExecuteInfo); ExecuteInfo.fMask = 0; ExecuteInfo.hwnd = 0; ExecuteInfo.lpVerb = _T("open"); ExecuteInfo.lpFile = _applicationToUse; ExecuteInfo.lpParameters = _applicationArgs; ExecuteInfo.lpDirectory = 0; ExecuteInfo.nShow = SW_SHOW; ExecuteInfo.hInstApp = 0; if (ShellExecuteEx(&ExecuteInfo) == FALSE) { AfxMessageBox(_T("Failed to open file")); } else { return true; } } else { AfxMessageBox(_T("Failed to find default application => no way to open file!")); } return false; } bool CpopupApp::openURL(const std::string & p_url) { CString _browser; CString _args(p_url.c_str()); if (m_options.getOption(WEB_BROWSER_PATH, _browser) == true) { SHELLEXECUTEINFO ExecuteInfo; memset(&ExecuteInfo, 0, sizeof(ExecuteInfo)); ExecuteInfo.cbSize = sizeof(ExecuteInfo); ExecuteInfo.fMask = 0; ExecuteInfo.hwnd = 0; ExecuteInfo.lpVerb = _T("open"); ExecuteInfo.lpFile = _browser; ExecuteInfo.lpParameters = _args; ExecuteInfo.lpDirectory = 0; ExecuteInfo.nShow = SW_SHOW; ExecuteInfo.hInstApp = 0; if (ShellExecuteEx(&ExecuteInfo) == FALSE) { AfxMessageBox(_T("Failed to open URL!!")); return false; } } else { AfxMessageBox(_T("Web browser is not set => no way to open URL!")); return false; } return true; } bool CpopupApp::getUsers(vector<PopupClientInfo> &users) { PopupClient::UsersList _users; CSingleLock _lock(&s_clientmutex); _lock.Lock(); if (m_popupclient != 0) { _users = m_popupclient->getUsersList(); PopupClient::UsersList::iterator _it; for (_it = _users.begin(); _it != _users.end(); _it++) { users.push_back(*_it); } _lock.Unlock(); return (users.size() > 0); } else { _lock.Unlock(); return false; } }
C++
#include "Logger.h" #include <sstream> #include <string> #include <stdlib.h> #include <stdio.h> using namespace std; //====================================================== // Logging utility //====================================================== Logger::Logger(const string & outputDir /* = "" */) : m_enabled(false) { if (outputDir.length() > 0) { setPath(outputDir); } } bool Logger::setPath(const string & outputDir) { m_logFilePath = outputDir + "\\popup.log"; FILE *fd = fopen(m_logFilePath.c_str(), "w+"); m_enabled = (fd != NULL); fclose(fd); return m_enabled; } void Logger::flush() { if (m_enabled) { FILE *fd = fopen(m_logFilePath.c_str(), "a+"); if (fd != NULL) { fprintf(fd, "%s\n", this->str().c_str()); this->str(""); } fclose(fd); } }
C++
#include "StdAfx.h" #include "PopupAutoModeThread.h" #include "popup.h" #include "popupdlg.h" #include <iostream> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace std; IMPLEMENT_DYNCREATE(PopupAutoModeThread, CWinThread) BOOL PopupAutoModeThread::InitInstance() { return TRUE; } int PopupAutoModeThread::Run() { CpopupApp *_app = (CpopupApp*)AfxGetApp(); CpopupDlg *_dlg = _app->popupdlg; // Constants PopupClientMode & _automode = _app->m_automode; int & _delay = _app->m_automodeDelay; // Variables bool & _reset = _dlg->m_resetTimer; PopupClientMode & _currentmode = _dlg->m_mode; while (true) { // Nothing to do while we are already in the // good mode while (_currentmode == _automode) { Sleep(5000); } // Let's start countdown... size_t _countdown = _delay; while (_countdown > 0) { if (_reset) { _reset = false; _countdown = _delay; } else { Sleep(5000); _countdown -= 5; } } // End of loop we switch to auto mode _dlg->setMode(_automode); } return 0; }
C++
// ------------------------------------------------------------ // CDialogMinTrayBtn template class // MFC CDialog with minimize to systemtray button (0.04) // Supports WinXP styles (thanks to David Yuheng Zhao for CVisualStylesXP - yuheng_zhao@yahoo.com) // ------------------------------------------------------------ // DialogMinTrayBtn.hpp // zegzav - 2002,2003 - ePopup project (http://www.popup-project.net) // ------------------------------------------------------------ #include "stdafx.h" #include "DialogMinTrayBtn.h" #include "ResizableDialog.h" #include "AfxBeginMsgMapTemplate.h" #include "OtherFunctions.h" //#include "MenuCmds.h" #if 0 // define this to use that source file as template #define TEMPLATE template <class BASE> #else // define this to instantiate functions for class 'BASE' right in this CPP module #if _MSC_VER >= 1310 #define TEMPLATE template <> #else #define TEMPLATE #endif #define BASE CResizableDialog #endif // ------------------------------ // constants // ------------------------------ #define CAPTION_BUTTONSPACE (2) #define CAPTION_MINHEIGHT (8) #define TIMERMINTRAYBTN_ID 0x76617a67 #define TIMERMINTRAYBTN_PERIOD 200 // ms #define WP_TRAYBUTTON WP_MINBUTTON BEGIN_TM_PART_STATES(TRAYBUTTON) TM_STATE(1, TRAYBS, NORMAL) TM_STATE(2, TRAYBS, HOT) TM_STATE(3, TRAYBS, PUSHED) TM_STATE(4, TRAYBS, DISABLED) // Inactive TM_STATE(5, TRAYBS, INORMAL) TM_STATE(6, TRAYBS, IHOT) TM_STATE(7, TRAYBS, IPUSHED) TM_STATE(8, TRAYBS, IDISABLED) END_TM_PART_STATES() #define BMP_TRAYBTN_WIDTH (21) #define BMP_TRAYBTN_HEIGHT (21) #define BMP_TRAYBTN_BLUE _T("TRAYBTN_BLUE") #define BMP_TRAYBTN_METALLIC _T("TRAYBTN_METALLIC") #define BMP_TRAYBTN_HOMESTEAD _T("TRAYBTN_HOMESTEAD") #define BMP_TRAYBTN_TRANSCOLOR (RGB(255,0,255)) TEMPLATE const TCHAR *CDialogMinTrayBtn<BASE>::m_pszMinTrayBtnBmpName[] = { BMP_TRAYBTN_BLUE, BMP_TRAYBTN_METALLIC, BMP_TRAYBTN_HOMESTEAD }; #define VISUALSTYLESXP_DEFAULTFILE L"LUNA.MSSTYLES" #define VISUALSTYLESXP_BLUE 0 #define VISUALSTYLESXP_METALLIC 1 #define VISUALSTYLESXP_HOMESTEAD 2 #define VISUALSTYLESXP_NAMEBLUE L"NORMALCOLOR" #define VISUALSTYLESXP_NAMEMETALLIC L"METALLIC" #define VISUALSTYLESXP_NAMEHOMESTEAD L"HOMESTEAD" // _WIN32_WINNT >= 0x0501 (XP only) #define _WM_THEMECHANGED 0x031A #if _MFC_VER>=0x0800 #define _ON_WM_THEMECHANGED() \ { _WM_THEMECHANGED, 0, 0, 0, AfxSig_l, \ (AFX_PMSG)(AFX_PMSGW) \ (static_cast< LRESULT (AFX_MSG_CALL CWnd::*)(void) > ( &ThisClass :: _OnThemeChanged)) }, #else #define _ON_WM_THEMECHANGED() \ { _WM_THEMECHANGED, 0, 0, 0, AfxSig_l, \ (AFX_PMSG)(AFX_PMSGW) \ (static_cast< LRESULT (AFX_MSG_CALL CWnd::*)(void) > (_OnThemeChanged)) \ }, #endif BEGIN_MESSAGE_MAP_TEMPLATE(TEMPLATE, CDialogMinTrayBtn<BASE>, CDialogMinTrayBtn, BASE) ON_WM_NCPAINT() ON_WM_NCACTIVATE() ON_WM_NCHITTEST() ON_WM_NCLBUTTONDOWN() ON_WM_NCRBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_TIMER() _ON_WM_THEMECHANGED() END_MESSAGE_MAP() TEMPLATE CDialogMinTrayBtn<BASE>::CDialogMinTrayBtn() : m_MinTrayBtnPos(0,0), m_MinTrayBtnSize(0,0), m_bMinTrayBtnEnabled(TRUE), m_bMinTrayBtnVisible(TRUE), m_bMinTrayBtnUp(TRUE), m_bMinTrayBtnCapture(FALSE), m_bMinTrayBtnActive(FALSE), m_bMinTrayBtnHitTest(FALSE) { MinTrayBtnInit(); } TEMPLATE CDialogMinTrayBtn<BASE>::CDialogMinTrayBtn(LPCTSTR lpszTemplateName, CWnd* pParentWnd) : BASE(lpszTemplateName, pParentWnd), m_MinTrayBtnPos(0,0), m_MinTrayBtnSize(0,0), m_bMinTrayBtnEnabled(TRUE), m_bMinTrayBtnVisible(TRUE), m_bMinTrayBtnUp(TRUE), m_bMinTrayBtnCapture(FALSE), m_bMinTrayBtnActive(FALSE), m_bMinTrayBtnHitTest(FALSE) { MinTrayBtnInit(); } TEMPLATE CDialogMinTrayBtn<BASE>::CDialogMinTrayBtn(UINT nIDTemplate, CWnd* pParentWnd) : BASE(nIDTemplate, pParentWnd), m_MinTrayBtnPos(0,0), m_MinTrayBtnSize(0,0), m_bMinTrayBtnEnabled(TRUE), m_bMinTrayBtnVisible(TRUE), m_bMinTrayBtnUp(TRUE), m_bMinTrayBtnCapture(FALSE), m_bMinTrayBtnActive(FALSE), m_bMinTrayBtnHitTest(FALSE) { MinTrayBtnInit(); } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnInit() { m_nMinTrayBtnTimerId = 0; BOOL bBmpResult = MinTrayBtnInitBitmap(); // - Never use the 'TransparentBlt' function under Win9x (read SDK) // - Load the 'MSIMG32.DLL' only, if it's really needed. if (!afxIsWin95() && bBmpResult && !_TransparentBlt) { HMODULE hMsImg32 = LoadLibrary(_T("MSIMG32.DLL")); if (hMsImg32) { (FARPROC &)_TransparentBlt = GetProcAddress(hMsImg32, "TransparentBlt"); if (!_TransparentBlt) FreeLibrary(hMsImg32); } } } TEMPLATE BOOL CDialogMinTrayBtn<BASE>::OnInitDialog() { BOOL bReturn = BASE::OnInitDialog(); m_nMinTrayBtnTimerId = SetTimer(TIMERMINTRAYBTN_ID, TIMERMINTRAYBTN_PERIOD, NULL); return bReturn; } TEMPLATE void CDialogMinTrayBtn<BASE>::OnNcPaint() { BASE::OnNcPaint(); MinTrayBtnUpdatePosAndSize(); MinTrayBtnDraw(); } TEMPLATE BOOL CDialogMinTrayBtn<BASE>::OnNcActivate(BOOL bActive) { MinTrayBtnUpdatePosAndSize(); BOOL bResult = BASE::OnNcActivate(bActive); m_bMinTrayBtnActive = bActive; MinTrayBtnDraw(); return bResult; } TEMPLATE #if _MFC_VER>=0x0800 LRESULT #else UINT #endif CDialogMinTrayBtn<BASE>::OnNcHitTest(CPoint point) { BOOL bPreviousHitTest = m_bMinTrayBtnHitTest; m_bMinTrayBtnHitTest = MinTrayBtnHitTest(point); if (!IsWindowsClassicStyle() && m_bMinTrayBtnHitTest != bPreviousHitTest) MinTrayBtnDraw(); // Windows XP Style (hot button) if (m_bMinTrayBtnHitTest) return HTMINTRAYBUTTON; return BASE::OnNcHitTest(point); } TEMPLATE void CDialogMinTrayBtn<BASE>::OnNcLButtonDown(UINT nHitTest, CPoint point) { if ((GetStyle() & WS_DISABLED) || !MinTrayBtnIsEnabled() || !MinTrayBtnIsVisible() || !MinTrayBtnHitTest(point)) { BASE::OnNcLButtonDown(nHitTest, point); return; } SetCapture(); m_bMinTrayBtnCapture = TRUE; MinTrayBtnSetDown(); } TEMPLATE void CDialogMinTrayBtn<BASE>::OnNcRButtonDown(UINT nHitTest, CPoint point) { if ((GetStyle() & WS_DISABLED) || !MinTrayBtnIsVisible() || !MinTrayBtnHitTest(point)) BASE::OnNcRButtonDown(nHitTest, point); } TEMPLATE void CDialogMinTrayBtn<BASE>::OnMouseMove(UINT nFlags, CPoint point) { if ((GetStyle() & WS_DISABLED) || !m_bMinTrayBtnCapture) { BASE::OnMouseMove(nFlags, point); return; } ClientToScreen(&point); m_bMinTrayBtnHitTest = MinTrayBtnHitTest(point); if (m_bMinTrayBtnHitTest) { if (m_bMinTrayBtnUp) MinTrayBtnSetDown(); } else { if (!m_bMinTrayBtnUp) MinTrayBtnSetUp(); } } TEMPLATE void CDialogMinTrayBtn<BASE>::OnLButtonUp(UINT nFlags, CPoint point) { if ((GetStyle() & WS_DISABLED) || !m_bMinTrayBtnCapture) { BASE::OnLButtonUp(nFlags, point); return; } ReleaseCapture(); m_bMinTrayBtnCapture = FALSE; MinTrayBtnSetUp(); ClientToScreen(&point); //if (MinTrayBtnHitTest(point)) // SendMessage(WM_SYSCOMMAND, MP_MINIMIZETOTRAY, MAKELONG(point.x, point.y)); } TEMPLATE void CDialogMinTrayBtn<BASE>::OnTimer(UINT_PTR nIDEvent) { if (!IsWindowsClassicStyle() && nIDEvent == m_nMinTrayBtnTimerId) { // Visual XP Style (hot button) CPoint point; GetCursorPos(&point); BOOL bHitTest = MinTrayBtnHitTest(point); if (m_bMinTrayBtnHitTest != bHitTest) { m_bMinTrayBtnHitTest = bHitTest; MinTrayBtnDraw(); } } } TEMPLATE LRESULT CDialogMinTrayBtn<BASE>::_OnThemeChanged() { // BASE::OnThemeChanged(); MinTrayBtnInitBitmap(); return 0; } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnUpdatePosAndSize() { DWORD dwStyle = GetStyle(); DWORD dwExStyle = GetExStyle(); INT cyCaption = ((dwExStyle & WS_EX_TOOLWINDOW) == 0) ? GetSystemMetrics(SM_CYCAPTION) - 1 : GetSystemMetrics(SM_CYSMCAPTION) - 1; if (cyCaption < CAPTION_MINHEIGHT) cyCaption = CAPTION_MINHEIGHT; CSize borderfixed(-GetSystemMetrics(SM_CXFIXEDFRAME), GetSystemMetrics(SM_CYFIXEDFRAME)); CSize bordersize(-GetSystemMetrics(SM_CXSIZEFRAME), GetSystemMetrics(SM_CYSIZEFRAME)); CRect rcWnd; GetWindowRect(&rcWnd); // get Windows' frame window button width/height (this may not always be a square!) CSize szBtn; szBtn.cy = cyCaption - (CAPTION_BUTTONSPACE * 2); if (IsWindowsClassicStyle()) szBtn.cx = GetSystemMetrics(SM_CXSIZE) - 2; else szBtn.cx = GetSystemMetrics(SM_CXSIZE) - 4; // set our frame window button width/height... if (IsWindowsClassicStyle()){ // ...this is same as Windows' buttons for non WinXP m_MinTrayBtnSize = szBtn; } else{ // ...this is a square for WinXP m_MinTrayBtnSize.cx = szBtn.cy; m_MinTrayBtnSize.cy = szBtn.cy; } m_MinTrayBtnPos.x = rcWnd.Width() - (CAPTION_BUTTONSPACE + m_MinTrayBtnSize.cx + CAPTION_BUTTONSPACE + szBtn.cx); m_MinTrayBtnPos.y = CAPTION_BUTTONSPACE; if ((dwStyle & WS_THICKFRAME) != 0) { // resizable window m_MinTrayBtnPos += bordersize; } else { // fixed window m_MinTrayBtnPos += borderfixed; } if ( ((dwExStyle & WS_EX_TOOLWINDOW) == 0) && (((dwStyle & WS_MINIMIZEBOX) != 0) || ((dwStyle & WS_MAXIMIZEBOX) != 0)) ) { if (IsWindowsClassicStyle()) m_MinTrayBtnPos.x -= (szBtn.cx * 2) + CAPTION_BUTTONSPACE; else m_MinTrayBtnPos.x -= (szBtn.cx + CAPTION_BUTTONSPACE) * 2; } } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnShow() { if (MinTrayBtnIsVisible()) return; m_bMinTrayBtnVisible = TRUE; if (IsWindowVisible()) RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW); } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnHide() { if (!MinTrayBtnIsVisible()) return; m_bMinTrayBtnVisible = FALSE; if (IsWindowVisible()) RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW); } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnEnable() { if (MinTrayBtnIsEnabled()) return; m_bMinTrayBtnEnabled = TRUE; MinTrayBtnSetUp(); } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnDisable() { if (!MinTrayBtnIsEnabled()) return; m_bMinTrayBtnEnabled = FALSE; if (m_bMinTrayBtnCapture) { ReleaseCapture(); m_bMinTrayBtnCapture = FALSE; } MinTrayBtnSetUp(); } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnDraw() { if (!MinTrayBtnIsVisible()) return; CDC *pDC= GetWindowDC(); if (!pDC) return; // panic! if (IsWindowsClassicStyle()) { CBrush black(GetSysColor(COLOR_BTNTEXT)); CBrush gray(GetSysColor(COLOR_GRAYTEXT)); CBrush gray2(GetSysColor(COLOR_BTNHILIGHT)); // button if (m_bMinTrayBtnUp) pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH); else pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH | DFCS_PUSHED); // dot CRect btn = MinTrayBtnGetRect(); btn.DeflateRect(2,2); UINT caption = MinTrayBtnGetSize().cy + (CAPTION_BUTTONSPACE * 2); UINT pixratio = (caption >= 14) ? ((caption >= 20) ? 2 + ((caption - 20) / 8) : 2) : 1; UINT pixratio2 = (caption >= 12) ? 1 + (caption - 12) / 8: 0; UINT dotwidth = (1 + pixratio * 3) >> 1; UINT dotheight = pixratio; CRect dot(CPoint(0,0), CPoint(dotwidth, dotheight)); CSize spc((1 + pixratio2 * 3) >> 1, pixratio2); dot -= dot.Size(); dot += btn.BottomRight(); dot -= spc; if (!m_bMinTrayBtnUp) dot += CPoint(1,1); if (m_bMinTrayBtnEnabled) { pDC->FillRect(dot, &black); } else { pDC->FillRect(dot + CPoint(1,1), &gray2); pDC->FillRect(dot, &gray); } } else { // VisualStylesXP CRect btn = MinTrayBtnGetRect(); int iState; if (!m_bMinTrayBtnEnabled) iState = TRAYBS_DISABLED; else if (GetStyle() & WS_DISABLED) iState = MINBS_NORMAL; else if (m_bMinTrayBtnHitTest) iState = (m_bMinTrayBtnCapture) ? MINBS_PUSHED : MINBS_HOT; else iState = MINBS_NORMAL; // inactive if (!m_bMinTrayBtnActive) iState += 4; // inactive state TRAYBS_Ixxx if (m_bmMinTrayBtnBitmap.m_hObject && _TransparentBlt) { // known theme (bitmap) CBitmap *pBmpOld; CDC dcMem; if (dcMem.CreateCompatibleDC(pDC) && (pBmpOld = dcMem.SelectObject(&m_bmMinTrayBtnBitmap)) != NULL) { _TransparentBlt(pDC->m_hDC, btn.left, btn.top, btn.Width(), btn.Height(), dcMem.m_hDC, 0, BMP_TRAYBTN_HEIGHT * (iState - 1), BMP_TRAYBTN_WIDTH, BMP_TRAYBTN_HEIGHT, BMP_TRAYBTN_TRANSCOLOR); dcMem.SelectObject(pBmpOld); } } } ReleaseDC(pDC); } TEMPLATE BOOL CDialogMinTrayBtn<BASE>::MinTrayBtnHitTest(CPoint ptScreen) const { CRect rcWnd; GetWindowRect(&rcWnd); // adjust 'ptScreen' with possible RTL window layout CRect rcWndOrg(rcWnd); CPoint ptScreenOrg(ptScreen); if (::MapWindowPoints(HWND_DESKTOP, m_hWnd, &rcWnd.TopLeft(), 2) == 0 || ::MapWindowPoints(HWND_DESKTOP, m_hWnd, &ptScreen, 1) == 0) { // several bug reports about not working on NT SP6 (?). in case of any problems with // 'MapWindowPoints' we fall back to old code (does not work for RTL window layout though) rcWnd = rcWndOrg; ptScreen = ptScreenOrg; } ptScreen.Offset(-rcWnd.TopLeft()); CRect rcBtn = MinTrayBtnGetRect(); rcBtn.InflateRect(0, CAPTION_BUTTONSPACE); return rcBtn.PtInRect(ptScreen); } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnSetUp() { m_bMinTrayBtnUp = TRUE; MinTrayBtnDraw(); } TEMPLATE void CDialogMinTrayBtn<BASE>::MinTrayBtnSetDown() { m_bMinTrayBtnUp = FALSE; MinTrayBtnDraw(); } TEMPLATE BOOL CDialogMinTrayBtn<BASE>::IsWindowsClassicStyle() const { return m_bMinTrayBtnWindowsClassicStyle; } TEMPLATE void CDialogMinTrayBtn<BASE>::SetWindowText(LPCTSTR lpszString) { BASE::SetWindowText(lpszString); MinTrayBtnDraw(); } TEMPLATE BOOL CDialogMinTrayBtn<BASE>::MinTrayBtnInitBitmap() { m_bMinTrayBtnWindowsClassicStyle = true; INT nColor = 0; m_bmMinTrayBtnBitmap.DeleteObject(); return m_bmMinTrayBtnBitmap.LoadBitmap(m_pszMinTrayBtnBmpName[nColor]); }
C++
#include "stdafx.h" #include "popup.h" #include "ini2.h" #include "otherfunctions.h" #include "enbitmap.h" #include "TaskbarNotifier.h" #include "popupdlg.h" //#include "UserMsgs.h" #include <atlimage.h> #include <string> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define IDT_HIDDEN 0 #define IDT_APPEARING 1 #define IDT_WAITING 2 #define IDT_DISAPPEARING 3 #define TASKBAR_X_TOLERANCE 10 #define TASKBAR_Y_TOLERANCE 10 using namespace std; //----------------------------------------------- // Reply buttons coords #define POINT_REPLY_SENDER CPoint( 18, 43) #define POINT_REPLY_SMALLRECT CPoint( 24, 71) #define POINT_REPLY_MEDIUMRECT CPoint( 24, 134) #define POINT_REPLY_BIGRECT CPoint(151, 344) // Reply all buttons coords #define POINT_REPLYALL_SENDER CPoint(100, 43) #define POINT_REPLYALL_SMALLRECT CPoint(106, 71) #define POINT_REPLYALL_MEDIUMRECT CPoint(106, 134) #define POINT_REPLYALL_BIGRECT CPoint(233, 344) // Size of the reply and reply all button SIZE REPLY_BTN_SIZE = { 75, 15 }; //----------------------------------------------- inline bool NearlyEqual(int a, int b, int iEpsilon) { return abs(a - b) < iEpsilon / 2; } // CTaskbarNotifier IMPLEMENT_DYNAMIC(CTaskbarNotifier, CWnd) BEGIN_MESSAGE_MAP(CTaskbarNotifier, CWnd) ON_WM_MOUSEMOVE() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() ON_WM_ERASEBKGND() ON_WM_PAINT() ON_WM_SETCURSOR() ON_WM_TIMER() ON_WM_SYSCOLORCHANGE() END_MESSAGE_MAP() CTaskbarNotifier::CTaskbarNotifier() : m_bIsShowingAnim(false) { m_tConfigFileLastModified = -1; (void)m_strCaption; m_pWndParent = NULL; m_bMouseIsOver = FALSE; m_hBitmapRegion = NULL; m_hCursor = NULL; m_crNormalTextColor = RGB(133, 146, 181); m_crSelectedTextColor = RGB(10, 36, 106); m_nBitmapHeight = 0; m_nBitmapWidth = 0; m_bBitmapAlpha = false; m_dwShowEvents = 0; m_dwHideEvents = 0; m_nCurrentPosX = 0; m_nCurrentPosY = 0; m_nCurrentWidth = 0; m_nCurrentHeight = 0; m_nIncrementShow = 0; m_nIncrementHide = 0; m_dwTimeToStay = 4000; m_dwTimeToShow = 500; m_dwTimeToHide = 200; m_nTaskbarPlacement = ABE_BOTTOM; m_nAnimStatus = IDT_HIDDEN; m_rcText.SetRect(0, 0, 0, 0); m_rcCloseBtn.SetRect(0, 0, 0, 0); m_replyRect = CRect(0,0,0,0); m_replyAllRect = CRect(0, 0, 0, 0); m_uTextFormat = DT_MODIFYSTRING | DT_WORDBREAK | DT_PATH_ELLIPSIS | DT_END_ELLIPSIS | DT_NOPREFIX; m_hCursor = ::LoadCursor(NULL, MAKEINTRESOURCE(32649)); // System Hand cursor m_nHistoryPosition = 0; m_bTextSelected = FALSE; // If running on NT, timer precision is 10 ms, if not timer precision is 50 ms OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) m_dwTimerPrecision = 10; else m_dwTimerPrecision = 50; m_pfnAlphaBlend = NULL; m_hMsImg32Dll = LoadLibrary(_T("MSIMG32.DLL")); if (m_hMsImg32Dll) { (FARPROC &)m_pfnAlphaBlend = GetProcAddress(m_hMsImg32Dll, "AlphaBlend"); if (m_pfnAlphaBlend == NULL) { FreeLibrary(m_hMsImg32Dll); m_hMsImg32Dll = NULL; } } SetTextFont(_T("Impact"), 50, TN_TEXT_NORMAL, TN_TEXT_UNDERLINE); } CTaskbarNotifier::~CTaskbarNotifier() { if (m_hMsImg32Dll) FreeLibrary(m_hMsImg32Dll); while (m_MessageHistory.GetCount() > 0) delete (CTaskbarNotifierHistory*)m_MessageHistory.RemoveTail(); } LRESULT CALLBACK My_AfxWndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, nMsg, wParam, lParam); } int CTaskbarNotifier::Create(CWnd *pWndParent) { ASSERT( pWndParent != NULL ); m_pWndParent = pWndParent; WNDCLASSEX wcx; wcx.cbSize = sizeof(wcx); // From: http://www.trigeminal.com/usenet/usenet031.asp?1033 // Subject: If you are using MFC 6.0 or 7.0 and you want to use MSLU... // // There is one additional problem that can occur if you are using AfxWndProc (MFC's main, shared window // proc wrapper) as an actual wndproc in any of your windows. You see, MFC has code in it so that if AfxWndProc // is called and is told that the wndproc to follow up with is AfxWndProc, it notices that it is being asked to // call itself and forwards for DefWindowProc instead. // // Unfortunately, MSLU breaks this code by having its own proc be the one that shows up. MFC has no way of // detecting this case so it calls the MSLU proc which calls AfxWndProc which calls the MSLU proc, etc., until // the stack overflows. By using either DefWindowProc or your own proc yourself, you avoid the stack overflow. bool g_bUnicoWS = true; //false; if (g_bUnicoWS) wcx.lpfnWndProc = My_AfxWndProc; else wcx.lpfnWndProc = AfxWndProc; static const TCHAR s_szClassName[] = _T("ePopup_TaskbarNotifierWndClass"); wcx.style = CS_DBLCLKS | CS_SAVEBITS; wcx.cbClsExtra = 0; wcx.cbWndExtra = 0; wcx.hInstance = AfxGetInstanceHandle(); wcx.hIcon = NULL; wcx.hCursor = LoadCursor(NULL,IDC_ARROW); wcx.hbrBackground=::GetSysColorBrush(COLOR_WINDOW); wcx.lpszMenuName = NULL; wcx.lpszClassName = s_szClassName; wcx.hIconSm = NULL; RegisterClassEx(&wcx); return CreateEx(WS_EX_TOPMOST, s_szClassName, NULL, WS_POPUP, 0, 0, 0, 0, pWndParent->m_hWnd, NULL); } void CTaskbarNotifier::OnSysColorChange() { CWnd::OnSysColorChange(); } bool CTaskbarNotifier::isReady() { return (m_nAnimStatus == IDT_HIDDEN); } void CTaskbarNotifier::SetPopupImage(LPCTSTR strBmpFilePath) { CEnBitmap imgTaskbar; imgTaskbar.LoadImage(strBmpFilePath, (COLORREF)0); SetBitmap(&imgTaskbar, 255, 0, 255); } void CTaskbarNotifier::SetPopupImage(int _rcId) { CEnBitmap imgTaskbar; imgTaskbar.LoadImage(_rcId, _T("GIF")); SetBitmap(&imgTaskbar, 255, 0, 255); } void CTaskbarNotifier::SetTextFont(LPCTSTR pszFont, int nSize, int nNormalStyle, int nSelectedStyle) { LOGFONT lf; m_fontNormal.DeleteObject(); CreatePointFont(m_fontNormal, nSize, pszFont); m_fontNormal.GetLogFont(&lf); // We set the Font of the unselected ITEM if (nNormalStyle & TN_TEXT_BOLD) lf.lfWeight = FW_BOLD; else lf.lfWeight = FW_NORMAL; if (nNormalStyle & TN_TEXT_ITALIC) lf.lfItalic = TRUE; else lf.lfItalic = FALSE; if (nNormalStyle & TN_TEXT_UNDERLINE) lf.lfUnderline = TRUE; else lf.lfUnderline = FALSE; m_fontNormal.DeleteObject(); m_fontNormal.CreateFontIndirect(&lf); // We set the Font of the selected ITEM if (nSelectedStyle & TN_TEXT_BOLD) lf.lfWeight = FW_BOLD; else lf.lfWeight = FW_NORMAL; if (nSelectedStyle & TN_TEXT_ITALIC) lf.lfItalic = TRUE; else lf.lfItalic = FALSE; if (nSelectedStyle & TN_TEXT_UNDERLINE) lf.lfUnderline = TRUE; else lf.lfUnderline = FALSE; m_fontSelected.DeleteObject(); m_fontSelected.CreateFontIndirect(&lf); } void CTaskbarNotifier::SetTextDefaultFont() { LOGFONT lf; AfxGetMainWnd()->GetFont()->GetLogFont(&lf); m_fontNormal.DeleteObject(); m_fontSelected.DeleteObject(); m_fontNormal.CreateFontIndirect(&lf); lf.lfUnderline = TRUE; m_fontSelected.CreateFontIndirect(&lf); } void CTaskbarNotifier::SetTextColor(COLORREF crNormalTextColor, COLORREF crSelectedTextColor) { m_crNormalTextColor = crNormalTextColor; m_crSelectedTextColor = crSelectedTextColor; RedrawWindow(&m_rcText); } void CTaskbarNotifier::SetTextRect(RECT rcText) { m_rcText = rcText; } void CTaskbarNotifier::SetTextFormat(UINT uTextFormat) { m_uTextFormat = uTextFormat; } BOOL CTaskbarNotifier::SetBitmap(UINT nBitmapID, int red, int green, int blue) { m_bitmapBackground.DeleteObject(); if (!m_bitmapBackground.LoadBitmap(nBitmapID)) return FALSE; BITMAP bm; m_bitmapBackground.GetBitmap(&bm); m_nBitmapWidth = bm.bmWidth; m_nBitmapHeight = bm.bmHeight; m_bBitmapAlpha = false; if (red != -1 && green != -1 && blue != -1) { // No need to delete the HRGN, SetWindowRgn() owns it after being called m_hBitmapRegion = CreateRgnFromBitmap(m_bitmapBackground, RGB(red, green, blue)); SetWindowRgn(m_hBitmapRegion, TRUE); } if (m_nBitmapWidth == 0 || m_nBitmapHeight == 0){ ASSERT( false ); return FALSE; } else return TRUE; } BOOL CTaskbarNotifier::SetBitmap(CBitmap* pBitmap, int red, int green, int blue) { m_bitmapBackground.DeleteObject(); if (!m_bitmapBackground.Attach(pBitmap->Detach())) return FALSE; BITMAP bm; m_bitmapBackground.GetBitmap(&bm); m_nBitmapWidth = bm.bmWidth; m_nBitmapHeight = bm.bmHeight; m_bBitmapAlpha = false; if (red != -1 && green != -1 && blue != -1) { // No need to delete the HRGN, SetWindowRgn() owns it after being called m_hBitmapRegion = CreateRgnFromBitmap(m_bitmapBackground, RGB(red, green, blue)); SetWindowRgn(m_hBitmapRegion, TRUE); } return TRUE; } BOOL CTaskbarNotifier::SetBitmap(LPCTSTR pszFileName, int red, int green, int blue) { if (pszFileName == NULL || pszFileName[0] == _T('\0')) return FALSE; CEnBitmap Bitmap; if (!Bitmap.LoadImage(pszFileName)) return FALSE; m_bitmapBackground.DeleteObject(); if (!m_bitmapBackground.Attach(Bitmap.Detach())) return FALSE; BITMAP bm; m_bitmapBackground.GetBitmap(&bm); m_nBitmapWidth = bm.bmWidth; m_nBitmapHeight = bm.bmHeight; m_bBitmapAlpha = false; if (red != -1 && green != -1 && blue != -1) { // No need to delete the HRGN, SetWindowRgn() owns it after being called m_hBitmapRegion = CreateRgnFromBitmap(m_bitmapBackground, RGB(red, green, blue)); SetWindowRgn(m_hBitmapRegion, TRUE); } return TRUE; } void CTaskbarNotifier::setupMessage(LPCTSTR message) { int _rcID; string _splittedMessage; if (message != NULL) { int _nbRows = splitString(MFCStringToSTLString(CString(message)), 30, _splittedMessage); if (_nbRows <= 2) { _rcID = IDR_TEXT_RECT_SENDER; SetTextRect(CRect(10,10,190,40)); m_replyRect = CRect(POINT_REPLY_SENDER, REPLY_BTN_SIZE); m_replyAllRect = CRect(POINT_REPLYALL_SENDER, REPLY_BTN_SIZE); } else if (_nbRows <= 4) { _rcID = IDR_TEXT_RECT; SetTextRect(CRect(10,10,190,80)); m_replyRect = CRect(POINT_REPLY_SMALLRECT, REPLY_BTN_SIZE); m_replyAllRect = CRect(POINT_REPLYALL_SMALLRECT, REPLY_BTN_SIZE); } else if (_nbRows <= 10) { _rcID = IDR_TEXT_RECT_BIG; SetTextRect(CRect(10,10,190,130)); m_replyRect = CRect(POINT_REPLY_MEDIUMRECT, REPLY_BTN_SIZE); m_replyAllRect = CRect(POINT_REPLYALL_MEDIUMRECT, REPLY_BTN_SIZE); } else { _rcID = IDR_TEXT_RECT_EXTRA_BIG; SetTextRect(CRect(10,10,320,400)); m_replyRect = CRect(POINT_REPLY_BIGRECT, REPLY_BTN_SIZE); m_replyAllRect = CRect(POINT_REPLYALL_BIGRECT, REPLY_BTN_SIZE); } SetPopupImage(_rcID); SetTextColor(RGB(0,0,0), RGB(0,0,0)); // Setup message text m_strCaption = message; } } void CTaskbarNotifier::Show(LPCTSTR message, Direction direction, UINT shiftValue, bool p_modal) { m_modal = p_modal; // Setup background of image depending on image size setupMessage(message); if (m_nBitmapHeight == 0 || m_nBitmapWidth == 0) { ASSERT( false ); return; } // Compute popup... startAnimation(direction, shiftValue); // Set the popup at the base position SetWindowPos(&wndTopMost, m_nCurrentPosX, m_nCurrentPosY, m_nCurrentWidth, m_nCurrentHeight, SWP_NOACTIVATE); // and show it! RedrawWindow(&m_rcText); } void CTaskbarNotifier::Hide() { switch (m_nAnimStatus) { case IDT_APPEARING: KillTimer(IDT_APPEARING); break; case IDT_WAITING: KillTimer(IDT_WAITING); break; case IDT_DISAPPEARING: KillTimer(IDT_DISAPPEARING); break; } MoveWindow(0, 0, 0, 0); ShowWindow(SW_HIDE); m_nAnimStatus = IDT_HIDDEN; } void CTaskbarNotifier::startAnimation(Direction direction, UINT shiftValue) { UINT nEvents; UINT nScreenWidth; UINT nScreenHeight; CRect rcTaskbar; nScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); nScreenHeight = ::GetSystemMetrics(SM_CYSCREEN); HWND hWndTaskbar = ::FindWindow(_T("Shell_TrayWnd"), 0); ASSERT(hWndTaskbar != NULL); ::GetWindowRect(hWndTaskbar, &rcTaskbar); switch (direction) { case RIGHT_TO_LEFT: m_nTaskbarPlacement = ABE_RIGHT; m_nImageSize = m_nBitmapWidth; break; case LEFT_TO_RIGHT: m_nTaskbarPlacement = ABE_LEFT; m_nImageSize = m_nBitmapWidth; break; case UP_TO_DOWN: m_nImageSize = m_nBitmapHeight; m_nTaskbarPlacement = ABE_TOP; break; case DOWN_TO_UP: m_nImageSize = m_nBitmapHeight; m_nTaskbarPlacement = ABE_BOTTOM; break; default: AfxMessageBox(_T("Failed to init notifier!")); return; } // We calculate the pixel increment and the timer value for the showing animation // For transparent bitmaps, all animations are disabled. DWORD dwTimeToShow = m_bBitmapAlpha ? 0 : m_dwTimeToShow; if (dwTimeToShow > m_dwTimerPrecision) { nEvents = max(min((dwTimeToShow / m_dwTimerPrecision) / 2, m_nImageSize), 1); //<<-- enkeyDEV(Ottavio84) -Reduced frames of a half- m_dwShowEvents = dwTimeToShow / nEvents; m_nIncrementShow = m_nImageSize / nEvents; } else { m_dwShowEvents = m_dwTimerPrecision; m_nIncrementShow = m_nImageSize; } // We calculate the pixel increment and the timer value for the hiding animation // For transparent bitmaps, all animations are disabled. DWORD dwTimeToHide = m_bBitmapAlpha ? 0 : m_dwTimeToHide; if (dwTimeToHide > m_dwTimerPrecision) { nEvents = max(min((dwTimeToHide / m_dwTimerPrecision / 2), m_nImageSize), 1); //<<-- enkeyDEV(Ottavio84) -Reduced frames of a half- m_dwHideEvents = dwTimeToHide / nEvents; m_nIncrementHide = m_nImageSize / nEvents; } else { m_dwShowEvents = m_dwTimerPrecision; m_nIncrementHide = m_nImageSize; } // Compute init values for the animation switch (m_nAnimStatus) { case IDT_HIDDEN: m_bIsShowingAnim = true; if (m_nTaskbarPlacement == ABE_RIGHT) { m_nCurrentPosX = rcTaskbar.right; m_nCurrentPosY = rcTaskbar.top - m_nBitmapHeight - shiftValue; m_nCurrentWidth = 0; m_nCurrentHeight = m_nBitmapHeight; } else if (m_nTaskbarPlacement == ABE_LEFT) { m_nCurrentPosX = rcTaskbar.right; m_nCurrentPosY = rcTaskbar.bottom - m_nBitmapHeight; m_nCurrentWidth = 0; m_nCurrentHeight = m_nBitmapHeight; } else if (m_nTaskbarPlacement == ABE_TOP) { m_nCurrentPosX = rcTaskbar.right - m_nBitmapWidth; m_nCurrentPosY = rcTaskbar.bottom; m_nCurrentWidth = m_nBitmapWidth; m_nCurrentHeight = 0; } else { // Taskbar is on the bottom or Invisible m_nCurrentPosX = rcTaskbar.right - m_nBitmapWidth; m_nCurrentPosY = rcTaskbar.top; m_nCurrentWidth = m_nBitmapWidth; m_nCurrentHeight = 0; } ShowWindow(SW_SHOWNOACTIVATE); SetTimer(IDT_APPEARING, m_dwShowEvents, NULL); break; case IDT_APPEARING: RedrawWindow(&m_rcText); break; case IDT_WAITING: RedrawWindow(&m_rcText); KillTimer(IDT_WAITING); SetTimer(IDT_WAITING, m_dwTimeToStay, NULL); break; case IDT_DISAPPEARING: KillTimer(IDT_DISAPPEARING); SetTimer(IDT_WAITING, m_dwTimeToStay, NULL); if (m_nTaskbarPlacement == ABE_RIGHT) { m_nCurrentPosX = rcTaskbar.left - m_nBitmapWidth; m_nCurrentWidth = m_nBitmapWidth; } else if (m_nTaskbarPlacement == ABE_LEFT) { m_nCurrentPosX = rcTaskbar.right; m_nCurrentWidth = m_nBitmapWidth; } else if (m_nTaskbarPlacement == ABE_TOP) { m_nCurrentPosY = rcTaskbar.bottom; m_nCurrentHeight = m_nBitmapHeight; } else { m_nCurrentPosY = rcTaskbar.top - m_nBitmapHeight; m_nCurrentHeight = m_nBitmapHeight; m_bIsShowingAnim = false; } break; } } HRGN CTaskbarNotifier::CreateRgnFromBitmap(HBITMAP hBmp, COLORREF color) { if (hBmp == NULL) return NULL; CDC* pDC = GetDC(); if (pDC == NULL) return NULL; BITMAP bm; GetObject(hBmp, sizeof(bm), &bm); ASSERT( !m_bBitmapAlpha ); const BYTE *pBitmapBits = NULL; if (bm.bmBitsPixel == 32 && m_pfnAlphaBlend) { DWORD dwBitmapBitsSize = GetBitmapBits(hBmp, 0, NULL); if (dwBitmapBitsSize) { pBitmapBits = (BYTE *)malloc(dwBitmapBitsSize); if (pBitmapBits) { if (GetBitmapBits(hBmp, dwBitmapBitsSize, (LPVOID)pBitmapBits) == (LONG)dwBitmapBitsSize) { const BYTE *pLine = pBitmapBits; int iLines = bm.bmHeight; while (!m_bBitmapAlpha && iLines-- > 0) { const DWORD *pdwPixel = (const DWORD *)pLine; for (int x = 0; x < bm.bmWidth; x++) { if (*pdwPixel++ & 0xFF000000) { m_bBitmapAlpha = true; break; } } pLine += bm.bmWidthBytes; } } if (!m_bBitmapAlpha) { free((void*)pBitmapBits); pBitmapBits = NULL; } } } } CDC dcBmp; dcBmp.CreateCompatibleDC(pDC); HGDIOBJ hOldBmp = dcBmp.SelectObject(hBmp); HRGN hRgn = NULL; // allocate memory for region data const DWORD MAXBUF = 40; // size of one block in RECTs (i.e. MAXBUF*sizeof(RECT) in bytes) DWORD cBlocks = 0; // number of allocated blocks RGNDATAHEADER *pRgnData = (RGNDATAHEADER *)calloc(sizeof(RGNDATAHEADER) + ++cBlocks * MAXBUF * sizeof(RECT), 1); if (pRgnData) { // fill it by default pRgnData->dwSize = sizeof(RGNDATAHEADER); pRgnData->iType = RDH_RECTANGLES; pRgnData->nCount = 0; INT iFirstXPos = 0; // left position of current scan line where mask was found bool bWasFirst = false; // set when mask was found in current scan line const BYTE *pBitmapLine = pBitmapBits != NULL ? pBitmapBits + bm.bmWidthBytes * (bm.bmHeight - 1) : NULL; for (int y = 0; pRgnData != NULL && y < bm.bmHeight; y++) { for (int x = 0; x < bm.bmWidth; x++) { // get color bool bIsMask; if (pBitmapLine) bIsMask = ((((const DWORD *)pBitmapLine)[x] & 0xFF000000) != 0x00000000); else bIsMask = (dcBmp.GetPixel(x, bm.bmHeight - y - 1) != color); // place part of scan line as RECT region if transparent color found after mask color or // mask color found at the end of mask image if (bWasFirst && ((bIsMask && (x == bm.bmWidth - 1)) || (bIsMask ^ (x < bm.bmWidth)))) { // get offset to RECT array if RGNDATA buffer LPRECT pRects = (LPRECT)(pRgnData + 1); // save current RECT pRects[pRgnData->nCount++] = CRect(iFirstXPos, bm.bmHeight - y - 1, x + (x == bm.bmWidth - 1), bm.bmHeight - y); // if buffer full reallocate it if (pRgnData->nCount >= cBlocks * MAXBUF) { RGNDATAHEADER *pNewRgnData = (RGNDATAHEADER *)realloc(pRgnData, sizeof(RGNDATAHEADER) + ++cBlocks * MAXBUF * sizeof(RECT)); if (pNewRgnData == NULL) { free(pRgnData); pRgnData = NULL; break; } pRgnData = pNewRgnData; } bWasFirst = false; } else if (!bWasFirst && bIsMask) { iFirstXPos = x; bWasFirst = true; } } if (pBitmapBits) pBitmapLine -= bm.bmWidthBytes; } if (pRgnData) { // Create region // WinNT: 'ExtCreateRegion' returns NULL (by Fable@aramszu.net) hRgn = CreateRectRgn(0, 0, 0, 0); if (hRgn) { LPCRECT pRects = (LPRECT)(pRgnData + 1); for (DWORD i = 0; i < pRgnData->nCount; i++) { HRGN hr = CreateRectRgn(pRects[i].left, pRects[i].top, pRects[i].right, pRects[i].bottom); VERIFY( CombineRgn(hRgn, hRgn, hr, RGN_OR) != ERROR ); if (hr) DeleteObject(hr); } } free(pRgnData); } } dcBmp.SelectObject(hOldBmp); dcBmp.DeleteDC(); free((void*)pBitmapBits); ReleaseDC(pDC); return hRgn; } void CTaskbarNotifier::OnMouseMove(UINT nFlags, CPoint point) { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(tme); tme.dwFlags = TME_LEAVE | TME_HOVER; tme.hwndTrack = m_hWnd; tme.dwHoverTime = 1; // We Tell Windows we want to receive WM_MOUSEHOVER and WM_MOUSELEAVE ::_TrackMouseEvent(&tme); CWnd::OnMouseMove(nFlags, point); } void CTaskbarNotifier::addSyncNotifier(CTaskbarNotifier *p_syncNofifier) { m_syncNotifiers.push_back(p_syncNofifier); } void CTaskbarNotifier::OnLButtonDown(UINT /*nFlags*/, CPoint point) { // Display reply dialog if a button has been clicked if (m_replyRect.PtInRect(point)) { m_pWndParent->PostMessage(UM_REPLY_BTN_CLICKED); } else if (m_replyAllRect.PtInRect(point)) { m_pWndParent->PostMessage(UM_REPLYALL_BTN_CLICKED); } // Hide all active notifiers Hide(); vector<CTaskbarNotifier*>::iterator _it; for (_it = m_syncNotifiers.begin(); _it != m_syncNotifiers.end(); _it++) { (*_it)->Hide(); } } BOOL CTaskbarNotifier::OnEraseBkgnd(CDC* pDC) { CDC memDC; memDC.CreateCompatibleDC(pDC); CBitmap *pOldBitmap = memDC.SelectObject(&m_bitmapBackground); if (m_bBitmapAlpha && m_pfnAlphaBlend) { static const BLENDFUNCTION bf = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA }; (*m_pfnAlphaBlend)(pDC->m_hDC, 0, 0, m_nCurrentWidth, m_nCurrentHeight, memDC.m_hDC, 0, 0, m_nCurrentWidth, m_nCurrentHeight, bf); } else { pDC->BitBlt(0, 0, m_nCurrentWidth, m_nCurrentHeight, &memDC, 0, 0, SRCCOPY); } memDC.SelectObject(pOldBitmap); return TRUE; } void CTaskbarNotifier::OnPaint() { CPaintDC dc(this); CFont* pOldFont; if (m_bMouseIsOver) { if (m_rcText.PtInRect(m_ptMousePosition)) { m_bTextSelected = TRUE; dc.SetTextColor(m_crSelectedTextColor); pOldFont = dc.SelectObject(&m_fontSelected); } else { m_bTextSelected = FALSE; dc.SetTextColor(m_crNormalTextColor); pOldFont = dc.SelectObject(&m_fontNormal); } } else { dc.SetTextColor(m_crNormalTextColor); pOldFont = dc.SelectObject(&m_fontNormal); } dc.SetBkMode(TRANSPARENT); dc.DrawText(m_strCaption, m_strCaption.GetLength(), m_rcText, m_uTextFormat); dc.SelectObject(pOldFont); } BOOL CTaskbarNotifier::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { if (nHitTest == HTCLIENT) { if (m_rcCloseBtn.PtInRect(m_ptMousePosition) || m_rcHistoryBtn.PtInRect(m_ptMousePosition) || m_rcText.PtInRect(m_ptMousePosition)) { ::SetCursor(m_hCursor); return TRUE; } } return CWnd::OnSetCursor(pWnd, nHitTest, message); } void CTaskbarNotifier::OnTimer(UINT nIDEvent) { switch (nIDEvent) { case IDT_APPEARING: m_nAnimStatus = IDT_APPEARING; switch (m_nTaskbarPlacement) { case ABE_BOTTOM: if (m_nCurrentHeight < m_nBitmapHeight) { m_nCurrentPosY -= m_nIncrementShow; m_nCurrentHeight += m_nIncrementShow; } else { KillTimer(IDT_APPEARING); SetTimer(IDT_WAITING, m_dwTimeToStay, NULL); m_nAnimStatus = IDT_WAITING; } break; case ABE_TOP: if (m_nCurrentHeight < m_nBitmapHeight) m_nCurrentHeight += m_nIncrementShow; else { KillTimer(IDT_APPEARING); SetTimer(IDT_WAITING, m_dwTimeToStay, NULL); m_nAnimStatus = IDT_WAITING; } break; case ABE_LEFT: if (m_nCurrentWidth < m_nBitmapWidth) m_nCurrentWidth += m_nIncrementShow; else { KillTimer(IDT_APPEARING); SetTimer(IDT_WAITING, m_dwTimeToStay, NULL); m_nAnimStatus = IDT_WAITING; } break; case ABE_RIGHT: if (m_nCurrentWidth < m_nBitmapWidth) { m_nCurrentPosX -= m_nIncrementShow; m_nCurrentWidth += m_nIncrementShow; } else { KillTimer(IDT_APPEARING); SetTimer(IDT_WAITING, m_dwTimeToStay, NULL); m_nAnimStatus = IDT_WAITING; } break; } SetWindowPos(&wndTopMost, m_nCurrentPosX, m_nCurrentPosY, m_nCurrentWidth, m_nCurrentHeight, SWP_NOACTIVATE); break; case IDT_WAITING: KillTimer(IDT_WAITING); if (!m_modal) SetTimer(IDT_DISAPPEARING, m_dwHideEvents, NULL); break; case IDT_DISAPPEARING: m_nAnimStatus = IDT_DISAPPEARING; switch (m_nTaskbarPlacement) { case ABE_BOTTOM: if (m_nCurrentHeight > 0) { m_nCurrentPosY += m_nIncrementHide; m_nCurrentHeight -= m_nIncrementHide; } else { KillTimer(IDT_DISAPPEARING); Hide(); } break; case ABE_TOP: if (m_nCurrentHeight > 0) m_nCurrentHeight -= m_nIncrementHide; else { KillTimer(IDT_DISAPPEARING); Hide(); } break; case ABE_LEFT: if (m_nCurrentWidth > 0) m_nCurrentWidth -= m_nIncrementHide; else { KillTimer(IDT_DISAPPEARING); Hide(); } break; case ABE_RIGHT: if (m_nCurrentWidth > 0) { m_nCurrentPosX += m_nIncrementHide; m_nCurrentWidth -= m_nIncrementHide; } else { KillTimer(IDT_DISAPPEARING); Hide(); } break; } SetWindowPos(&wndTopMost, m_nCurrentPosX, m_nCurrentPosY, m_nCurrentWidth, m_nCurrentHeight, SWP_NOACTIVATE); break; } CWnd::OnTimer(nIDEvent); }
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "EnBitmap.h" #include <atlimage.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif const int HIMETRIC_INCH = 2540; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CEnBitmap::CEnBitmap() { } CEnBitmap::~CEnBitmap() { } BOOL CEnBitmap::LoadImage(UINT uIDRes, LPCTSTR pszResourceType, HMODULE hInst, COLORREF crBack) { return LoadImage(MAKEINTRESOURCE(uIDRes), pszResourceType, hInst, crBack); } BOOL CEnBitmap::LoadImage(LPCTSTR lpszResourceName, LPCTSTR szResourceType, HMODULE hInst, COLORREF crBack) { ASSERT(m_hObject == NULL); // only attach once, detach on destroy if (m_hObject != NULL) return FALSE; BYTE* pBuff = NULL; int nSize = 0; BOOL bResult = FALSE; // first call is to get buffer size if (GetResource(lpszResourceName, szResourceType, hInst, 0, nSize)) { if (nSize > 0) { pBuff = new BYTE[nSize]; // this loads it if (GetResource(lpszResourceName, szResourceType, hInst, pBuff, nSize)) { IPicture* pPicture = LoadFromBuffer(pBuff, nSize); if (pPicture) { bResult = Attach(pPicture, crBack); pPicture->Release(); } } delete [] pBuff; } } return bResult; } BOOL CEnBitmap::LoadImage(LPCTSTR szImagePath, COLORREF crBack) { ASSERT(m_hObject == NULL); // only attach once, detach on destroy if (m_hObject != NULL) return FALSE; // If GDI+ is available, use that API because it supports more file formats and images with alpha channels. // That DLL is installed with WinXP is available as redistributable from Microsoft for Win98+. As this DLL // may not be available on some OS but we have to link statically to it, we have to take some special care. // if (false) // GDI support deactivated for more comptibility! { CImage img; if (SUCCEEDED(img.Load(szImagePath))) { CBitmap::Attach(img.Detach()); return TRUE; } } BOOL bResult = FALSE; CFile cFile; CFileException e; if (cFile.Open(szImagePath, CFile::modeRead | CFile::typeBinary | CFile::shareDenyWrite, &e)) { int nSize = (int)cFile.GetLength(); BYTE* pBuff = new BYTE[nSize]; if (cFile.Read(pBuff, nSize) > 0) { IPicture* pPicture = LoadFromBuffer(pBuff, nSize); if (pPicture) { bResult = Attach(pPicture, crBack); pPicture->Release(); } } delete [] pBuff; } return bResult; } IPicture* CEnBitmap::LoadFromBuffer(BYTE* pBuff, int nSize) { IPicture* pPicture = NULL; HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, nSize); if (hGlobal != NULL) { void* pData = GlobalLock(hGlobal); if (pData != NULL) { memcpy(pData, pBuff, nSize); GlobalUnlock(hGlobal); IStream* pStream = NULL; if (CreateStreamOnHGlobal(hGlobal, TRUE/*fDeleteOnRelease*/, &pStream) == S_OK) { // Not sure what the 'KeepOriginalFormat' property is really used for. But if 'OleLoadPicture' // is invoked with 'fRunmode=FALSE' the function always creates a temporary file which even // does not get deleted when all COM pointers were released. It eventually gets deleted only // when process terminated. Using 'fRunmode=TRUE' does prevent this behaviour and does not // seem to have any other side effects. VERIFY( OleLoadPicture(pStream, nSize, TRUE/*FALSE*/, IID_IPicture, (LPVOID*)&pPicture) == S_OK ); pStream->Release(); } else GlobalFree(hGlobal); } else GlobalFree(hGlobal); } return pPicture; // caller releases } BOOL CEnBitmap::GetResource(LPCTSTR lpName, LPCTSTR lpType, HMODULE hInst, void* pResource, int& nBufSize) { HRSRC hResInfo; HANDLE hRes; LPSTR lpRes = NULL; bool bResult = FALSE; // Find the resource hResInfo = FindResource(hInst, lpName, lpType); if (hResInfo == NULL) return false; // Load the resource hRes = LoadResource(hInst, hResInfo); if (hRes == NULL) return false; // Lock the resource lpRes = (char*)LockResource(hRes); if (lpRes != NULL) { if (pResource == NULL) { nBufSize = SizeofResource(hInst, hResInfo); bResult = true; } else { if (nBufSize >= (int)SizeofResource(hInst, hResInfo)) { memcpy(pResource, lpRes, nBufSize); bResult = true; } } UnlockResource(hRes); } // Free the resource FreeResource(hRes); return bResult; } BOOL CEnBitmap::Attach(IPicture* pPicture, COLORREF crBack) { ASSERT(m_hObject == NULL); // only attach once, detach on destroy if (m_hObject != NULL) return FALSE; ASSERT(pPicture); if (!pPicture) return FALSE; BOOL bResult = FALSE; CDC dcMem; CDC* pDC = CWnd::GetDesktopWindow()->GetDC(); if (dcMem.CreateCompatibleDC(pDC)) { long hmWidth; long hmHeight; pPicture->get_Width(&hmWidth); pPicture->get_Height(&hmHeight); int nWidth = MulDiv(hmWidth, pDC->GetDeviceCaps(LOGPIXELSX), HIMETRIC_INCH); int nHeight = MulDiv(hmHeight, pDC->GetDeviceCaps(LOGPIXELSY), HIMETRIC_INCH); CBitmap bmMem; if (bmMem.CreateCompatibleBitmap(pDC, nWidth, nHeight)) { CBitmap* pOldBM = dcMem.SelectObject(&bmMem); if (crBack != -1) dcMem.FillSolidRect(0, 0, nWidth, nHeight, crBack); HRESULT hr = pPicture->Render(dcMem, 0, 0, nWidth, nHeight, 0, hmHeight, hmWidth, -hmHeight, NULL); dcMem.SelectObject(pOldBM); if (hr == S_OK) bResult = CBitmap::Attach(bmMem.Detach()); } } CWnd::GetDesktopWindow()->ReleaseDC(pDC); return bResult; }
C++
#include "stdafx.h"
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "StringConversion.h" #include <atlenc.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif int utf8towc(LPCSTR pcUtf8, UINT uUtf8Size, LPWSTR pwc, UINT uWideCharSize) { LPWSTR pwc0 = pwc; while (uUtf8Size && uWideCharSize) { BYTE ucChar = *pcUtf8++; if (ucChar < 0x80) { uUtf8Size--; uWideCharSize--; *(pwc++) = ucChar; } else if ((ucChar & 0xC0) != 0xC0) { return -1; // Invalid UTF8 string.. } else { BYTE ucMask = 0xE0; UINT uExpectedBytes = 1; while ((ucChar & ucMask) == ucMask) { ucMask |= ucMask >> 1; if (++uExpectedBytes > 3) return -1; // Invalid UTF8 string.. } if (uUtf8Size <= uExpectedBytes) return -1; // Invalid UTF8 string.. UINT uProcessedBytes = 1 + uExpectedBytes; UINT uWideChar = (UINT)(ucChar & ~ucMask); if (uExpectedBytes == 1) { if ((uWideChar & 0x1E) == 0) return -1; // Invalid UTF8 string.. } else { if (uWideChar == 0 && ((BYTE)*pcUtf8 & 0x3F & (ucMask << 1)) == 0) return -1; // Invalid UTF8 string.. if (uExpectedBytes == 2) { //if (uWideChar == 0x0D && ((BYTE)*pcUtf8 & 0x20)) // return -1; } else if (uExpectedBytes == 3) { if (uWideChar > 4) return -1; // Invalid UTF8 string.. if (uWideChar == 4 && ((BYTE)*pcUtf8 & 0x30)) return -1; // Invalid UTF8 string.. } } if (uWideCharSize < (UINT)(uExpectedBytes > 2) + 1) break; // buffer full while (uExpectedBytes--) { if (((ucChar = (BYTE)*(pcUtf8++)) & 0xC0) != 0x80) return -1; // Invalid UTF8 string.. uWideChar <<= 6; uWideChar |= (ucChar & 0x3F); } uUtf8Size -= uProcessedBytes; if (uWideChar < 0x10000) { uWideCharSize--; *(pwc++) = (WCHAR)uWideChar; } else { uWideCharSize -= 2; uWideChar -= 0x10000; *(pwc++) = (WCHAR)(0xD800 | (uWideChar >> 10)); *(pwc++) = (WCHAR)(0xDC00 | (uWideChar & 0x03FF)); } } } return pwc - pwc0; } int ByteStreamToWideChar(LPCSTR pcUtf8, UINT uUtf8Size, LPWSTR pwc, UINT uWideCharSize) { int iWideChars = utf8towc(pcUtf8, uUtf8Size, pwc, uWideCharSize); if (iWideChars < 0) { LPWSTR pwc0 = pwc; while (uUtf8Size && uWideCharSize) { if ((*pwc++ = (BYTE)*pcUtf8++) == L'\0') break; uUtf8Size--; uWideCharSize--; } iWideChars = pwc - pwc0; } return iWideChars; } //void CreateBOMUTF8String(const CStringW& rwstr, CStringA& rstrUTF8) //{ // int iChars = AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), NULL, 0); // int iRawChars = 3 + iChars; // LPSTR pszUTF8 = rstrUTF8.GetBuffer(iRawChars); // *pszUTF8++ = 0xEFU; // *pszUTF8++ = 0xBBU; // *pszUTF8++ = 0xBFU; // AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), pszUTF8, iRawChars); // rstrUTF8.ReleaseBuffer(iRawChars); //} CStringA wc2utf8(const CStringW& rwstr) { CStringA strUTF8; int iChars = AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), NULL, 0); if (iChars > 0) { LPSTR pszUTF8 = strUTF8.GetBuffer(iChars); AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), pszUTF8, iChars); strUTF8.ReleaseBuffer(iChars); } return strUTF8; } CString OptUtf8ToStr(const CStringA& rastr) { CStringW wstr; int iMaxWideStrLen = rastr.GetLength(); LPWSTR pwsz = wstr.GetBuffer(iMaxWideStrLen); int iWideChars = utf8towc(rastr, rastr.GetLength(), pwsz, iMaxWideStrLen); if (iWideChars <= 0) { // invalid UTF8 string... wstr.ReleaseBuffer(0); wstr = rastr; // convert with local codepage } else wstr.ReleaseBuffer(iWideChars); return wstr; // just return the string } CString OptUtf8ToStr(LPCSTR psz, int iLen) { CStringW wstr; int iMaxWideStrLen = iLen; LPWSTR pwsz = wstr.GetBuffer(iMaxWideStrLen); int iWideChars = utf8towc(psz, iLen, pwsz, iMaxWideStrLen); if (iWideChars <= 0) { // invalid UTF8 string... wstr.ReleaseBuffer(0); wstr = psz; // convert with local codepage } else wstr.ReleaseBuffer(iWideChars); return wstr; // just return the string } CString OptUtf8ToStr(const CStringW& rwstr) { CStringA astr; for (int i = 0; i < rwstr.GetLength(); i++) { if (rwstr[i] > 0xFF) { // this is no UTF8 string (it's already an Unicode string)... return rwstr; // just return the string } astr += (BYTE)rwstr[i]; } return OptUtf8ToStr(astr); } CStringA StrToUtf8(const CString& rstr) { return wc2utf8(rstr); } bool IsValidEd2kString(LPCTSTR psz) { while (*psz != _T('\0')) { // NOTE: The '?' is the character which is returned by windows if user entered an Unicode string into // an edit control (although application runs in ANSI mode). // The '?' is also invalid for search expressions and filenames. if (*psz == _T('?')) return false; psz++; } return true; } bool IsValidEd2kStringA(LPCSTR psz) { while (*psz != '\0') { // NOTE: The '?' is the character which is returned by windows if user entered an Unicode string into // an edit control (although application runs in ANSI mode). // The '?' is also invalid for search expressions and filenames. if (*psz == '?') return false; psz++; } return true; } CString EncodeUrlUtf8(const CString& rstr) { CString url; CStringA utf8(StrToUtf8(rstr)); for (int i = 0; i < utf8.GetLength(); i++) { if ((BYTE)utf8[i] >= 0x7F) url.AppendFormat(_T("%%%02X"), (BYTE)utf8[i]); else url += utf8[i]; } return url; } CStringW DecodeDoubleEncodedUtf8(LPCWSTR pszFileName) { size_t nChars = wcslen(pszFileName); // Check if all characters are valid for UTF-8 value range // for (UINT i = 0; i < nChars; i++) { if ((_TUCHAR)pszFileName[i] > 0xFFU) return pszFileName; // string is already using Unicode character value range; return original } // Transform Unicode string to UTF-8 byte sequence // CStringA strA; LPSTR pszA = strA.GetBuffer(nChars); for (UINT i = 0; i < nChars; i++) pszA[i] = (CHAR)pszFileName[i]; strA.ReleaseBuffer(nChars); // Decode the string with UTF-8 // CStringW strW; LPWSTR pszW = strW.GetBuffer(nChars); int iNewChars = utf8towc(strA, nChars, pszW, nChars); if (iNewChars < 0) { strW.ReleaseBuffer(0); return pszFileName; // conversion error (not a valid UTF-8 string); return original } strW.ReleaseBuffer(iNewChars); return strW; }
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "popup.h" #include "Version.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /* const UINT CpopupApp::m_nVersionMjr = VERSION_MJR; const UINT CpopupApp::m_nVersionMin = VERSION_MIN; const UINT CpopupApp::m_nVersionUpd = VERSION_UPDATE; const UINT CpopupApp::m_nVersionBld = VERSION_BUILD; */
C++
// MyTabCtrl.cpp : implementation file // ///////////////////////////////////////////////////// // This class is provided as is and Ben Hill takes no // responsibility for any loss of any kind in connection // to this code. ///////////////////////////////////////////////////// // Is is meant purely as a educational tool and may // contain bugs. ///////////////////////////////////////////////////// // ben@shido.fsnet.co.uk // http://www.shido.fsnet.co.uk ///////////////////////////////////////////////////// // Thanks to a mystery poster in the C++ forum on // www.codeguru.com I can't find your name to say thanks // for your Control drawing code. If you are that person // thank you very much. I have been able to use some of // you ideas to produce this sample application. ///////////////////////////////////////////////////// #include "stdafx.h" #include "MyTabCtrl.h" #include "SenderDialog.h" #include "PopupPropertiesDlg.h" #include "PopupHistoryDialog.h" #include "Popup.h" #include "PopupDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMyTabCtrl CMyTabCtrl::CMyTabCtrl() : m_senderDialog(new CSenderDialog()), m_historyDialog(new PopupHistoryDialog()), m_pptiesDialog(new PopupPropertiesDlg()) { m_tabPages[POPUP_SENDER_TAB]= m_senderDialog; m_tabPages[POPUP_HISTORY_TAB]= m_historyDialog; m_tabPages[POPUP_PPTIES_TAB]= m_pptiesDialog; m_nNumberOfPages = POPUP_NB_TABS; } CMyTabCtrl::~CMyTabCtrl() { for(int nCount=0; nCount < m_nNumberOfPages; nCount++){ delete m_tabPages[nCount]; } } void CMyTabCtrl::Init() { InsertItem(POPUP_SENDER_TAB, _T("[SEND A MESSAGE]")); InsertItem(POPUP_HISTORY_TAB, _T("[HISTORY]")); InsertItem(POPUP_PPTIES_TAB, _T("[PROPERTIES]")); m_tabCurrent=0; m_tabPages[POPUP_SENDER_TAB]->Create(IDD_DIALOG_SENDEVENT, this); m_tabPages[POPUP_SENDER_TAB]->ShowWindow(SW_SHOW); m_tabPages[POPUP_HISTORY_TAB]->Create(IDD_DIALOG_HISTORY, this); m_tabPages[POPUP_HISTORY_TAB]->ShowWindow(SW_HIDE); m_tabPages[POPUP_PPTIES_TAB]->Create(IDD_DIALOG_PROPERTIES, this); m_tabPages[POPUP_PPTIES_TAB]->ShowWindow(SW_HIDE); SetRectangle(); } void CMyTabCtrl::SetRectangle() { CRect tabRect, itemRect; int nX, nY, nXc, nYc; GetClientRect(&tabRect); GetItemRect(0, &itemRect); nX=itemRect.left; nY=itemRect.bottom+1; nXc=tabRect.right-itemRect.left-1; nYc=tabRect.bottom-nY-1; m_tabPages[0]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_SHOWWINDOW); for(int nCount=1; nCount < m_nNumberOfPages; nCount++){ m_tabPages[nCount]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_HIDEWINDOW); } } BEGIN_MESSAGE_MAP(CMyTabCtrl, CTabCtrl) //{{AFX_MSG_MAP(CMyTabCtrl) ON_WM_LBUTTONDOWN() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMyTabCtrl message handlers BOOL CMyTabCtrl::btnOkClicked() { CDialog *_dlg = m_tabPages[m_tabCurrent]; CSenderDialog *_sender = 0; PopupPropertiesDlg *_ppties = 0; PopupHistoryDialog *_hist = 0; if ((_sender = dynamic_cast<CSenderDialog*>(_dlg)) != 0) { return _sender->validateDialog(); } else if ((_ppties = dynamic_cast<PopupPropertiesDlg*>(_dlg)) != 0) { return _ppties->validateDialog(); } else if ((_hist = dynamic_cast<PopupHistoryDialog*>(_dlg)) != 0) { return _hist->validateDialog(); } return FALSE; } void CMyTabCtrl::OnLButtonDown(UINT nFlags, CPoint point) { CTabCtrl::OnLButtonDown(nFlags, point); setActiveTab(GetCurFocus()); } void CMyTabCtrl::setActiveTab(int p_tabId) { CTabCtrl::SetCurSel(p_tabId); if (m_tabCurrent != p_tabId) { m_tabPages[m_tabCurrent]->ShowWindow(SW_HIDE); m_tabCurrent = p_tabId; m_tabPages[m_tabCurrent]->ShowWindow(SW_SHOW); m_tabPages[m_tabCurrent]->SetFocus(); } }
C++
#pragma once #include "afxwin.h" #include "Popup.h" // PopupPropertiesDlg dialog class PopupPropertiesDlg : public CDialog { DECLARE_DYNAMIC(PopupPropertiesDlg) public: PopupPropertiesDlg(CWnd* pParent = NULL); // standard constructor virtual ~PopupPropertiesDlg(); virtual BOOL validateDialog(); // Dialog Data enum { IDD = IDD_DIALOG_PROPERTIES }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); virtual void OnOK(); virtual void updateControlsForExtension(const CString & p_extension); CpopupApp *m_app; DECLARE_MESSAGE_MAP() public: CString m_serverName; CString m_portNumber; CString m_userName; CString m_resourcePath; CString m_webBrowserPath; CString m_extension; CString m_applicationPath; CString m_applicationArgs; CString m_autoMode; CString m_autoModeDelay; CComboBox m_comboAutoMode; CComboBox m_cbExtension; CEdit m_editWebBrowserPath; CEdit m_editApplicationPath; CEdit m_editApplicationArgs; public: afx_msg void OnBnClickedButtonBrowseRcFolder(); afx_msg void OnBnClickedButtonBrowseInternetBrowser(); afx_msg void OnBnClickedButtonBrowseApplication(); afx_msg void OnCbnSelchangeComboExtension(); afx_msg void OnCbnEditchangeComboExtension(); };
C++
#include "StdAfx.h" #include "PopupEventThread.h" #include "popup.h" #include "popupdlg.h" /* #include "UserMsgs.h" #include "OtherFunctions.h" #include "TaskbarNotifier.h" #include "ResourceEntry.h" #include "SenderDialog.h" #include "PopupClient.h" */ #include <vector> #include <string> #include <sstream> #include <stdlib.h> #include <stdio.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace std; ///////////////////////////////////////////////////////////////////////////////////////// ///PopupEventThread IMPLEMENT_DYNCREATE(PopupEventThread, CWinThread) PopupEventThread::PopupEventThread() : m_popupapp((CpopupApp*) AfxGetApp()), m_popupdlg(m_popupapp->popupdlg) { } BOOL PopupEventThread::InitInstance() { return TRUE; } int PopupEventThread::Run() { PopupMessageList *_messageList = &(m_popupdlg->m_incomingMessages); CSingleLock _lock(&CpopupDlg::s_eventmutex); while (true) { _lock.Lock(); if (!_messageList->empty()) { _lock.Unlock(); while (m_popupdlg->isMuted() == true) { Sleep (3000); } _lock.Lock(); PopupMessageList::iterator _it = _messageList->begin(); PopupMessageInfo _info = (*_it); _messageList->erase(_it); _lock.Unlock(); if (m_popupdlg->isReadyToDisplayNextMessage()) { m_popupdlg->displayMessage(_info); } } _lock.Unlock(); Sleep(1000); } return 0; }
C++
#pragma warning (disable:4786) #include "stdafx.h" #include "Options.h" #include <sstream> #include <stdio.h> #include <string> #include <sstream> using namespace std; //------------------------------------- bool Options::load(const string & path) { char _buff[128]; char *str; string optname; int _nbOptionsLoaded = 0; string _key = OPTIONS_SECTION_KEY; FILE *f = fopen(path.c_str(),"r"); if (f == NULL) { return false; } else { while(fgets(&_buff[0], 128, f) != NULL) { ////// // Case of header ////// if (_buff[0] == SECTION_HEADER_FIRST_CHAR) { _key = strtok(&_buff[1], SECTION_HEADER_LAST_CHAR_STR); } ////// // default case = options list ////// else { // Get opt name if ((str = strtok(_buff, "=")) != NULL) { optname = str; // Get opt value if ((str = strtok(NULL, "\n")) != NULL) { // Add option to map setOption(optname, str, _key); _nbOptionsLoaded++; } } } } fclose(f); return (_nbOptionsLoaded > 0); } } //------------------------------------- bool Options::save(string path) const { FILE *f = fopen(path.c_str(), "w+"); if (f == NULL) { AfxMessageBox(_T("Failed to save options")); return false; } else { const_iterator _it; OptionsAssoc::iterator _itopts; // For each section for (_it = begin(); _it != end(); _it++) { // Print section name fprintf(f, "%c%s%c\n", SECTION_HEADER_FIRST_CHAR, _it->first.c_str(), SECTION_HEADER_LAST_CHAR); // Then, for each option for (_itopts = _it->second->begin(); _itopts != _it->second->end(); _itopts++) { // Dump the option's key and value if (_itopts->first.length() > 0 && _itopts->second.length() > 0) fprintf(f, "%s=%s\n", _itopts->first.c_str(), _itopts->second.c_str()); } fprintf(f, "\n"); } fclose(f); return true; } } //-------------------------------- bool Options::getOptions(const string & sectionName, OptionsAssoc **p_options, bool createIfNotExists) { bool _rc = true; Options::iterator _it = this->find(sectionName); if (_it != this->end()) { *p_options = _it->second; } else if (createIfNotExists) { *p_options = new OptionsAssoc(); (*this)[sectionName] = *p_options; } else { _rc = false; } return _rc; } //-------------------------------- bool Options::getOptionNamesForSection(const string & sectionName, vector<string> & _optionsList) { OptionsAssoc *_options; if (getOptions(sectionName, &_options, true)) { OptionsAssoc::iterator _it; for (_it = _options->begin(); _it != _options->end(); _it++) { _optionsList.push_back(_it->first); } return true; } return false; } void Options::setOption(const string & optionName, const string & optionValue, const string & sectionName) { OptionsAssoc *_options; if (getOptions(sectionName, &_options, true)) { (*_options)[optionName] = optionValue; } } //-------------------------------- bool Options::getOption(const string & optionName, string & optionValue, const string & sectionName) { OptionsAssoc *_options = NULL; if (getOptions(sectionName, &_options)) { OptionsAssoc::const_iterator it = _options->find(optionName); if (it != _options->end()) { optionValue = it->second; return true; } } return false; } //-------------------------------- bool Options::getOption(const string & optionName, CString &optionValue, const string & sectionName) { string s; bool found = getOption(optionName, s, sectionName); if (found) { optionValue = s.c_str(); return true; } return false; } //-------------------------------- void Options::setIntOption(const std::string & optionName, int optionValue, const string & sectionName) { stringstream s; s << optionValue; setOption(optionName, s.str(), sectionName); } //-------------------------------- bool Options::getIntOption(const std::string & optionName, int & optionValue, const string & sectionName) { string strValue; if (getOption(optionName, strValue, sectionName)) { optionValue = strtol(strValue.c_str(), NULL, 10); return true; } else { return false; } } //-------------------------------- void Options::delOption(const string & optionName, const string & sectionName) { Options::iterator _itSection = this->find(sectionName); if (_itSection != this->end()) { OptionsAssoc *_options = _itSection->second; OptionsAssoc::iterator it = _options->find(optionName); if (it != _options->end()) { _options->erase(it); if (_options->size() == 0) { this->erase(_itSection); } } } }
C++
#include "StdAfx.h" #include "PopupServerThread.h" #include "popup.h" #include "popupdlg.h" #include "PopupServer.h" #include <iostream> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace std; IMPLEMENT_DYNCREATE(PopupServerThread, CWinThread) BOOL PopupServerThread::InitInstance() { return TRUE; } int PopupServerThread::Run() { bool _exit = false; int _port = 2000; CpopupApp *_app = (CpopupApp*)AfxGetApp(); _app->m_options.getIntOption(SERVER_PORT, _port); while (!_exit) { _app->popupdlg->ShowWindow(SW_HIDE); cout << "Starting server" << endl; PopupServer *_server = PopupServer::getInstance(_port, 1024); _app->m_popupserver = _server; _server->run(); // Blocking call delete _server; _app->m_popupserver = 0; cout << "Server stopped" << endl; Sleep(5000); } return 0; } void PopupServerThread::kill() { AfxEndThread(0); }
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "StdAfx.h" #include "PopupClientThread.h" #include "popup.h" #include "popupdlg.h" //#include "UserMsgs.h" #include "OtherFunctions.h" #include "TaskbarNotifier.h" #include "ResourceEntry.h" #include "SenderDialog.h" #include "PopupClient.h" #include <vector> #include <string> #include <sstream> #include <stdlib.h> #include <stdio.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace std; ///////////////////////////////////////////////////////////////////////////////////////// ///PopupClientThread IMPLEMENT_DYNCREATE(PopupClientThread, CWinThread) PopupClientThread::PopupClientThread() : m_popupapp((CpopupApp*) AfxGetApp()), m_popupdlg(m_popupapp->popupdlg), m_resources(m_popupapp->m_resources), m_options(m_popupapp->m_options), m_logger(m_popupapp->m_logger) { } BOOL PopupClientThread::InitInstance() { return TRUE; } int PopupClientThread::Run() { m_popupdlg->ShowWindow(SW_HIDE); while (true) { CSingleLock _lock(&CpopupApp::s_clientmutex); _lock.Lock(); m_popupapp->m_popupclient = new PopupClient (m_popupapp->m_servername, m_popupapp->m_serverport, MFCStringToSTLString(m_popupapp->m_username), (PopupClientUI*) m_popupdlg, &(m_popupdlg->m_mode)); _lock.Unlock(); m_logger << "connecting to server" << endl; m_logger.flush(); // Starting main routine (blocking call, until disconnection) m_popupapp->m_popupclient->run(); _lock.Lock(); m_popupdlg->clearClients(); delete m_popupapp->m_popupclient; m_popupapp->m_popupclient = 0; _lock.Unlock(); Sleep (5000); } m_logger << " - Main thread exited" << endl; m_logger.flush(); return 0; } void PopupClientThread::kill() { AfxEndThread(0); }
C++
// PopupMainDialog.cpp : implementation file // #include "stdafx.h" #include "popup.h" #include "PopupMainDialog.h" #include "SenderDialog.h" #include "PopupHistoryDialog.h" // PopupMainDialog dialog IMPLEMENT_DYNAMIC(PopupMainDialog, CDialog) PopupMainDialog::PopupMainDialog(CWnd* pParent /*=NULL*/) : CDialog(PopupMainDialog::IDD, pParent), m_parent((CpopupDlg*)pParent) { } PopupMainDialog::~PopupMainDialog() { } void PopupMainDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_TAB_CTRL, m_tabCtrl); } BOOL PopupMainDialog::OnInitDialog() { UINT nScreenWidth; UINT nScreenHeight; CDialog::OnInitDialog(); m_tabCtrl.Init(); nScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); nScreenHeight = ::GetSystemMetrics(SM_CYSCREEN); SetWindowPos(NULL, nScreenWidth-500, nScreenHeight-700, 0, 0, SWP_NOSIZE); return TRUE; } void PopupMainDialog::OnOK() { if (m_tabCtrl.btnOkClicked()) { CDialog::OnOK(); } } void PopupMainDialog::updateClientStatus(const PopupClientInfo & p_client) { m_tabCtrl.m_senderDialog->updateClientStatus(p_client); } void PopupMainDialog::clearClients() { m_tabCtrl.m_senderDialog->clearClients(); } void PopupMainDialog::appendHistory(const PopupMessageInfo & p_message, bool p_received) { m_tabCtrl.m_historyDialog->appendHistory(p_message, p_received); } // PopupMainDialog message handlers BEGIN_MESSAGE_MAP(PopupMainDialog, CDialog) END_MESSAGE_MAP()
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include <sys/stat.h> #include <share.h> #include <io.h> #include <atlrx.h> #include <algorithm> #include "popup.h" #include "OtherFunctions.h" #include "PopupLibUtilities.h" #include <string> #include <sstream> using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif bool isImage(const CString & filePath) { string _file = MFCStringToSTLString(filePath); string _ext = ""; if (getFileExtension(_file, _ext)) { return (_ext.compare("gif") == 0 || _ext.compare("jpg") == 0); } return false; } bool isVideo(const CString & filePath) { string _file = MFCStringToSTLString(filePath); string _ext = ""; if (getFileExtension(_file, _ext)) { return (_ext.compare("avi") == 0 || _ext.compare("mpg") == 0 || _ext.compare("wmv") == 0); } return false; } bool isSound(const CString & filePath) { string _file = MFCStringToSTLString(filePath); string _ext = ""; if (getFileExtension(_file, _ext)) { return (_ext.compare("wav") == 0); } return false; } bool isJpegImage(const char *p_image) { unsigned short _jpgHeaderLittle = 0xFFD8; unsigned short _jpgHeaderBig = 0xD8FF; unsigned short _header = 0x0000; memcpy(&_header, p_image, 2); return (_header == _jpgHeaderLittle || _header == _jpgHeaderBig); } bool isGifImage(const char *p_image) { unsigned short _gifHeaderLittle = 0x4749; unsigned short _gifHeaderBig = 0x4947; unsigned short _header = 0x0000; memcpy(&_header, p_image, 2); return (_header == _gifHeaderLittle || _header == _gifHeaderBig); } bool isWavSound(const char *p_buffer) { char _format[9] = {'\0'}; strncpy(&_format[0], &(p_buffer[8]), 8); return (strcmp(_format, "WAVEfmt ") == 0); } bool isWmvVideo(const char *p_video) { unsigned short _headerLittle = 0x3026; unsigned short _headerBig = 0x2630; unsigned short _header = 0x0000; memcpy(&_header, p_video, 2); return (_header == _headerLittle || _header == _headerBig); } bool isAviVideo(const char *p_video) { unsigned short _headerLittle = 0x3026; unsigned short _headerBig = 0x2630; unsigned short _header = 0x0000; memcpy(&_header, p_video, 2); return (_header == _headerLittle || _header == _headerBig); } bool isMpegVideo(const char *p_video) { unsigned short _headerLittle = 0x3026; unsigned short _headerBig = 0x2630; unsigned short _header = 0x0000; memcpy(&_header, p_video, 2); return (_header == _headerLittle || _header == _headerBig); } stringstream &operator<<(stringstream &logger, LPCTSTR message) { CT2CA str(message); logger << string(str); return logger; } string MFCStringToSTLString(const CString & str) { stringstream s; s << (LPCTSTR) str; return s.str(); } bool deleteDirectory(CString rep, bool suppressionDefinitive) { SHFILEOPSTRUCT sh; sh.hwnd = NULL; sh.wFunc = FO_DELETE; sh.pFrom = rep; sh.pTo = NULL; sh.fFlags = FOF_NOCONFIRMATION|FOF_SILENT; if(!suppressionDefinitive) sh.fFlags |= FOF_ALLOWUNDO; sh.fAnyOperationsAborted = FALSE; sh.lpszProgressTitle = NULL; sh.hNameMappings = NULL; return (SHFileOperation(&sh)==0); } CString basename(const CString & str) { int lastSlashIndex = str.ReverseFind('\\'); if (lastSlashIndex == -1) { lastSlashIndex = 0; } else { lastSlashIndex++; } return str.Right(str.GetLength() - lastSlashIndex); } bool absolutePath(const CString & str, CString & ref) { CFileFind f; bool _ok = (f.FindFile(str) == TRUE); if (_ok) { f.FindNextFile(); ref = f.GetFilePath(); } return _ok; } bool absolutePath(const string & str, string & ref) { CString in, out; in = str.c_str(); if (absolutePath(in, out)) { ref = MFCStringToSTLString(out); return true; } else { return false; } } unsigned int splitString(const string & p_str, unsigned int p_maxlinelen, string & _res) { size_t _nbRows = 0; size_t _newlineOffset = 0; string _str = p_str; stringstream _splitted; while (_newlineOffset < p_str.length()) { _str = p_str.substr(_newlineOffset, p_maxlinelen); size_t _cropAt = 0; // Search for <CR> in the string size_t _nextcr = _str.find_first_of('\n'); // If one found, let's use it! if (_nextcr != string::npos) { _cropAt = _nextcr; } else if (_str.length() == p_maxlinelen) { size_t _nextdot = _str.find_last_of('.'); size_t _nextsp = _str.find_last_of(' '); if (_nextdot != string::npos) _cropAt = max(_cropAt, _nextdot); if (_nextsp != string::npos) _cropAt = max(_cropAt, _nextsp); } if (_cropAt == 0) _cropAt = string::npos; string s = _str.substr(0, _cropAt); _splitted << s; _newlineOffset = (_cropAt == string::npos? _newlineOffset + p_maxlinelen: _newlineOffset + _cropAt + 1); // Add a <CR> is there is still data to treat if (_newlineOffset < p_str.length()) { _splitted << endl; } _nbRows++; } _res = _splitted.str(); return _nbRows; } CString comboToCString(CComboBox & combo, bool useCursor) { CString str(""); if (useCursor) { int selectedTypeIndex = combo.GetCurSel(); combo.GetLBText(selectedTypeIndex, str); } else { combo.GetWindowTextW(str); } return str; } bool CreatePointFontIndirect(CFont &rFont, const LOGFONT *lpLogFont) { LOGFONT logFont = *lpLogFont; logFont.lfHeight = FontPointSizeToLogUnits(logFont.lfHeight); return rFont.CreateFontIndirect(&logFont) != FALSE; } bool CreatePointFont(CFont &rFont, int nPointSize, LPCTSTR lpszFaceName) { LOGFONT logFont = {0}; logFont.lfCharSet = DEFAULT_CHARSET; logFont.lfHeight = nPointSize; lstrcpyn(logFont.lfFaceName, lpszFaceName, _countof(logFont.lfFaceName)); return CreatePointFontIndirect(rFont, &logFont); } int FontPointSizeToLogUnits(int nPointSize) { HDC hDC = ::GetDC(HWND_DESKTOP); if (hDC) { POINT pt; #if 0 // This is the same math which is performed by "CFont::CreatePointFont", // which is flawed because it does not perform any rounding. But without // performing the correct rounding one can not get the correct LOGFONT-height // for an 8pt font! // // PointSize Result // ------------------- // 8*10 10.666 -> 10 (cut down and thus wrong result) pt.y = GetDeviceCaps(hDC, LOGPIXELSY) * nPointSize; pt.y /= 720; #else // This math accounts for proper rounding and thus we will get the correct results. // // PointSize Result // ------------------- // 8*10 10.666 -> 11 (rounded up and thus correct result) pt.y = MulDiv(GetDeviceCaps(hDC, LOGPIXELSY), nPointSize, 720); #endif pt.x = 0; DPtoLP(hDC, &pt, 1); POINT ptOrg = { 0, 0 }; DPtoLP(hDC, &ptOrg, 1); nPointSize = -abs(pt.y - ptOrg.y); ReleaseDC(HWND_DESKTOP, hDC); } return nPointSize; } // Wrapper for _tmakepath which ensures that the outputbuffer does not exceed MAX_PATH // using a smaller buffer without checking the sizes prior calling this function is not safe // If the resulting path would be bigger than MAX_PATH-1, it will be empty and return false (similar to PathCombine) bool _tmakepathlimit(TCHAR *path, const TCHAR *drive, const TCHAR *dir, const TCHAR *fname, const TCHAR *ext){ if (path == NULL){ ASSERT( false ); return false; } uint32 nSize = 64; // the function should actually only add 4 (+1 nullbyte) bytes max extra if (drive != NULL) nSize += _tcsclen(drive); if (dir != NULL) nSize += _tcsclen(dir); if (fname != NULL) nSize += _tcsclen(fname); if (ext != NULL) nSize += _tcsclen(ext); TCHAR* tchBuffer = new TCHAR[nSize]; _tmakepath(tchBuffer, drive, dir, fname, ext); if (_tcslen(tchBuffer) >= MAX_PATH){ path[0] = _T('\0'); ASSERT( false ); delete[] tchBuffer; return false; } else{ _tcscpy(path, tchBuffer); delete[] tchBuffer; return true; } }
C++
// PopupPropertiesDlg.cpp : implementation file // #include "stdafx.h" #include "popup.h" #include "PopupPropertiesDlg.h" #include "Options.h" #include "OtherFunctions.h" #include <string> using namespace std; // PopupPropertiesDlg dialog IMPLEMENT_DYNAMIC(PopupPropertiesDlg, CDialog) PopupPropertiesDlg::PopupPropertiesDlg(CWnd* pParent /*=NULL*/) : CDialog(PopupPropertiesDlg::IDD, pParent) , m_serverName(_T("")) , m_portNumber(_T("")) , m_userName(_T("")) , m_resourcePath(_T("")) , m_webBrowserPath(_T("")) , m_autoMode(_T("")) , m_autoModeDelay(_T("")) , m_app((CpopupApp*)AfxGetApp()) , m_extension(_T("")) { } PopupPropertiesDlg::~PopupPropertiesDlg() { } void PopupPropertiesDlg::OnOK() { } BOOL PopupPropertiesDlg::OnInitDialog() { CDialog::OnInitDialog(); Options & _options = m_app->m_options; string _opt; int _n; stringstream _s; // Fill resources combo m_comboAutoMode.InsertString(0,_T("normal")); m_comboAutoMode.InsertString(1,_T("muted")); m_comboAutoMode.InsertString(2,_T("prompt")); m_comboAutoMode.InsertString(3,_T("textonly")); if (_options.getOption(POPUP_RES_PATH, _opt)) { m_resourcePath = CString(_opt.c_str()); } if (_options.getOption(SERVER_HOSTNAME, _opt)) { m_serverName = CString(_opt.c_str()); } if (_options.getIntOption(SERVER_PORT, _n)) { _s << _n; m_portNumber = CString(_s.str().c_str()); _s.str(""); } if (_options.getOption(CLIENT_USER_NAME, _opt)) { m_userName = CString(_opt.c_str()); } if (_options.getOption(WEB_BROWSER_PATH, _opt)) { m_webBrowserPath = CString(_opt.c_str()); } if (_options.getOption(AUTO_MODE, _opt)) { m_autoMode = CString(_opt.c_str()); if (m_autoMode == CString("normal")) m_comboAutoMode.SetCurSel(0); else if (m_autoMode == CString("muted")) m_comboAutoMode.SetCurSel(1); else if (m_autoMode == CString("prompt")) m_comboAutoMode.SetCurSel(2); else if (m_autoMode == CString("textonly")) m_comboAutoMode.SetCurSel(3); } if (_options.getIntOption(AUTO_MODE_DELAY, _n)) { _s << _n; m_autoModeDelay = CString(_s.str().c_str()); _s.str(""); } // Fill extensions... vector<string> _extensions; int _pos = 0; if (m_app->m_options.getOptionNamesForSection(APP_ASSOCIATIONS_KEY, _extensions)) { vector<string>::iterator _it; for (_it = _extensions.begin(); _it != _extensions.end(); _it++) { CString _ext(_it->c_str()); CString _argssuffix(APP_ARGS_SUFFIX); if (_ext.Right(strlen(APP_ARGS_SUFFIX)).Compare(_argssuffix) != 0) { m_cbExtension.InsertString(_pos++, _ext); } } // Select default application CString _default(APP_DEFAULT_EXTENSION); m_cbExtension.SelectString(0, _default); string _app, _args; m_app->getApplicationByExtension(APP_DEFAULT_EXTENSION, _app, _args); m_extension = APP_DEFAULT_EXTENSION; m_applicationPath = _app.c_str(); m_applicationArgs = _args.c_str(); } UpdateData(FALSE); // Set window position UINT nScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); UINT nScreenHeight = ::GetSystemMetrics(SM_CYSCREEN); SetWindowPos(NULL, nScreenWidth-640,nScreenHeight-640,0,0,SW_SHOW); return TRUE; } void PopupPropertiesDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_SERVER, m_serverName); DDX_Text(pDX, IDC_EDIT_PORT, m_portNumber); DDX_Text(pDX, IDC_EDIT_USER_NAME, m_userName); DDX_Text(pDX, IDC_EDIT_RESOURCE_PATH, m_resourcePath); DDX_Text(pDX, IDC_EDIT_WEBBROWSER_PATH, m_webBrowserPath); DDX_Text(pDX, IDC_EDIT_APPLICATION_PATH, m_applicationPath); DDX_Text(pDX, IDC_EDIT_APPLICATION_ARGS, m_applicationArgs); DDX_CBString(pDX, IDC_COMBO_AUTOMODE, m_autoMode); DDX_Text(pDX, IDC_EDIT_AUTOMODE_DELAY, m_autoModeDelay); DDX_Control(pDX, IDC_COMBO_AUTOMODE, m_comboAutoMode); DDX_Control(pDX, IDC_EDIT_WEBBROWSER_PATH, m_editWebBrowserPath); DDX_Control(pDX, IDC_EDIT_APPLICATION_PATH, m_editApplicationPath); DDX_Control(pDX, IDC_COMBO_EXTENSION, m_cbExtension); DDX_Control(pDX, IDC_EDIT_APPLICATION_ARGS, m_editApplicationArgs); DDX_CBString(pDX, IDC_COMBO_EXTENSION, m_extension); } BOOL PopupPropertiesDlg::validateDialog() { // save old data to know if we need to reload... // ... the resources bool _reloadResources = false; CString _oldResourcePath = m_resourcePath; // ... the network bool _restartNetwork = false; CString _oldServerName = m_serverName; CString _oldPortNumber = m_portNumber; CString _oldUserName = m_userName; // ... the automode settings bool _reloadMode = false; CString _oldAutoMode = m_autoMode; CString _oldAutoModeDelay = m_autoModeDelay; // Get data from controls (this will update all m_xxx values) UpdateData(); // Reference to the current options Options & _options = m_app->m_options; if (_oldResourcePath != m_resourcePath) { _options.setOption(POPUP_RES_PATH, MFCStringToSTLString(m_resourcePath)); _reloadResources = true; } if (_oldServerName != m_serverName || _oldPortNumber != m_portNumber || _oldUserName != m_userName) { _options.setOption(SERVER_HOSTNAME, MFCStringToSTLString(m_serverName)); _options.setOption(SERVER_PORT, MFCStringToSTLString(m_portNumber)); _options.setOption(CLIENT_USER_NAME, MFCStringToSTLString(m_userName)); _restartNetwork = true; } if (_oldAutoMode != m_autoMode || _oldAutoModeDelay != m_autoModeDelay) { _options.setOption(AUTO_MODE, MFCStringToSTLString(m_autoMode)); _options.setOption(AUTO_MODE_DELAY, MFCStringToSTLString(m_autoModeDelay)); _reloadMode = true; } // Values updated in any case if (m_extension.GetLength() > 0) { _options.setOption(WEB_BROWSER_PATH, MFCStringToSTLString(m_webBrowserPath)); stringstream _argskey; _argskey << MFCStringToSTLString(m_extension) << APP_ARGS_SUFFIX; if (m_applicationPath.GetLength() > 0) { _options.setOption(MFCStringToSTLString(m_extension), MFCStringToSTLString(m_applicationPath), APP_ASSOCIATIONS_KEY); _options.setOption(_argskey.str(), MFCStringToSTLString(m_applicationArgs), APP_ASSOCIATIONS_KEY); int _id = m_cbExtension.FindString(0, m_extension); if (_id >= 0) m_cbExtension.InsertString(m_cbExtension.GetCount(), m_extension); m_cbExtension.SelectString(m_cbExtension.GetCount(), m_extension); } else { if (m_extension.Compare(CString(APP_DEFAULT_EXTENSION)) == 0) { AfxMessageBox(_T("You must define a default application!")); return FALSE; } _options.delOption(MFCStringToSTLString(m_extension), APP_ASSOCIATIONS_KEY); _options.delOption(_argskey.str(), APP_ASSOCIATIONS_KEY); CString _ss(APP_DEFAULT_EXTENSION); int _id = m_cbExtension.FindString(0, m_extension); if (_id >= 0) m_cbExtension.DeleteString(_id); m_cbExtension.SelectString(0, _ss); m_editApplicationArgs.SetSel(0, -1); m_editApplicationArgs.ReplaceSel(_T("")); m_editApplicationArgs.SetSel(0, 0); } } // Save options and reload it _options.save(MFCStringToSTLString(m_app->m_inifile)); m_app->loadOptions(); // Handle special cases if (_reloadResources) m_app->loadResources(); if (_restartNetwork) m_app->restartNetwork(); return TRUE; } BEGIN_MESSAGE_MAP(PopupPropertiesDlg, CDialog) ON_BN_CLICKED(IDC_BUTTON_BROWSE_RC_FOLDER, &PopupPropertiesDlg::OnBnClickedButtonBrowseRcFolder) ON_BN_CLICKED(IDC_BUTTON_BROWSE_INTERNET_BROWSER, &PopupPropertiesDlg::OnBnClickedButtonBrowseInternetBrowser) ON_BN_CLICKED(IDC_BUTTON_BROWSE_APPLICATION, &PopupPropertiesDlg::OnBnClickedButtonBrowseApplication) ON_CBN_SELCHANGE(IDC_COMBO_EXTENSION, &PopupPropertiesDlg::OnCbnSelchangeComboExtension) ON_CBN_EDITCHANGE(IDC_COMBO_EXTENSION, &PopupPropertiesDlg::OnCbnEditchangeComboExtension) END_MESSAGE_MAP() void PopupPropertiesDlg::OnBnClickedButtonBrowseRcFolder() { // TODO: Add your control notification handler code here AfxMessageBox(_T("Sorry! Please do it manually, bastard!")); } void PopupPropertiesDlg::OnBnClickedButtonBrowseInternetBrowser() { CString szFilter = _T("Executables (*.exe)|*.exe||"); CFileDialog dlg(true, NULL, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ENABLESIZING, szFilter); dlg.m_ofn.lpstrTitle = _T("Select internet browser..."); if (dlg.DoModal() == IDOK) { m_editWebBrowserPath.SetSel(0, -1); m_editWebBrowserPath.ReplaceSel(dlg.GetPathName()); m_editWebBrowserPath.SetSel(0, 0); } } void PopupPropertiesDlg::OnBnClickedButtonBrowseApplication() { CString szFilter = _T("Executables (*.exe)|*.exe||"); CFileDialog dlg(true, NULL, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ENABLESIZING, szFilter); dlg.m_ofn.lpstrTitle = _T("Select application..."); if (dlg.DoModal() == IDOK) { m_editApplicationPath.SetSel(0, -1); m_editApplicationPath.ReplaceSel(dlg.GetPathName()); m_editApplicationPath.SetSel(0, 0); } } void PopupPropertiesDlg::updateControlsForExtension(const CString & p_extension) { string _app = "", _args = ""; m_app->getApplicationByExtension(MFCStringToSTLString(p_extension), _app, _args, false); CString _application(_app.c_str()); m_editApplicationPath.SetSel(0, -1); m_editApplicationPath.ReplaceSel(_application); m_editApplicationPath.SetSel(0, 0); CString _arguments(_args.c_str()); m_editApplicationArgs.SetSel(0, -1); m_editApplicationArgs.ReplaceSel(_arguments); m_editApplicationArgs.SetSel(0, 0); m_extension = p_extension; m_applicationPath = _application; m_applicationArgs = _arguments; } void PopupPropertiesDlg::OnCbnSelchangeComboExtension() { CString _selectedExtension = comboToCString(m_cbExtension); updateControlsForExtension(comboToCString(m_cbExtension, true)); } void PopupPropertiesDlg::OnCbnEditchangeComboExtension() { CString _selectedExtension = comboToCString(m_cbExtension); updateControlsForExtension(comboToCString(m_cbExtension, false)); }
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "popup.h" #include "TrayDialog.h" #include "popupdlg.h" #include "TaskbarNotifier.h" //#include "UserMsgs.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define NOTIFYICONDATA_V1_TIP_SIZE 64 ///////////////////////////////////////////////////////////////////////////// // CTrayDialog dialog const UINT WM_TASKBARCREATED = ::RegisterWindowMessage(_T("TaskbarCreated")); BEGIN_MESSAGE_MAP(CTrayDialog, CTrayDialogBase) ON_WM_CREATE() ON_WM_DESTROY() ON_WM_SYSCOMMAND() ON_MESSAGE(UM_TRAY_ICON_NOTIFY_MESSAGE, OnTrayNotify) ON_REGISTERED_MESSAGE(WM_TASKBARCREATED, OnTaskBarCreated) ON_WM_TIMER() END_MESSAGE_MAP() CTrayDialog::CTrayDialog(UINT uIDD,CWnd* pParent /*=NULL*/) : CTrayDialogBase(uIDD, pParent) { m_nidIconData.cbSize = NOTIFYICONDATA_V1_SIZE; m_nidIconData.hWnd = 0; m_nidIconData.uID = 1; m_nidIconData.uCallbackMessage = UM_TRAY_ICON_NOTIFY_MESSAGE; m_nidIconData.hIcon = 0; m_nidIconData.szTip[0] = _T('\0'); m_nidIconData.uFlags = NIF_MESSAGE; m_bTrayIconVisible = FALSE; m_pbMinimizeToTray = NULL; m_nDefaultMenuItem = 0; m_hPrevIconDelete = NULL; m_bCurIconDelete = false; m_bLButtonDblClk = false; m_bLButtonDown = false; m_uSingleClickTimer = 0; } int CTrayDialog::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CTrayDialogBase::OnCreate(lpCreateStruct) == -1) return -1; ASSERT( WM_TASKBARCREATED ); m_nidIconData.hWnd = m_hWnd; m_nidIconData.uID = 1; return 0; } void CTrayDialog::OnDestroy() { KillSingleClickTimer(); CTrayDialogBase::OnDestroy(); // shouldn't that be done before passing the message to DefWinProc? if (m_nidIconData.hWnd && m_nidIconData.uID > 0 && TrayIsVisible()) { VERIFY( Shell_NotifyIcon(NIM_DELETE, &m_nidIconData) ); } } BOOL CTrayDialog::TrayIsVisible() { return m_bTrayIconVisible; } void CTrayDialog::TraySetIcon(HICON hIcon, bool bDelete) { ASSERT( hIcon ); if (hIcon) { //ASSERT(m_hPrevIconDelete == NULL); if (m_bCurIconDelete) { ASSERT( m_nidIconData.hIcon != NULL && (m_nidIconData.uFlags & NIF_ICON) ); m_hPrevIconDelete = m_nidIconData.hIcon; } m_bCurIconDelete = bDelete; m_nidIconData.hIcon = hIcon; m_nidIconData.uFlags |= NIF_ICON; } } void CTrayDialog::TraySetIcon(UINT nResourceID) { TraySetIcon(AfxGetApp()->LoadIcon(nResourceID)); } void CTrayDialog::TraySetIcon(LPCTSTR lpszResourceName) { TraySetIcon(AfxGetApp()->LoadIcon(lpszResourceName)); } void CTrayDialog::TraySetToolTip(LPCTSTR lpszToolTip) { CString _tooltip = lpszToolTip; ASSERT( _tcslen(lpszToolTip) > 0); _tcsncpy(m_nidIconData.szTip, lpszToolTip, NOTIFYICONDATA_V1_TIP_SIZE); if (_tcslen(lpszToolTip) >= NOTIFYICONDATA_V1_TIP_SIZE ) { _tcsncpy(&(m_nidIconData.szTip[NOTIFYICONDATA_V1_TIP_SIZE - 4]), _T("..."), 3); } m_nidIconData.szTip[NOTIFYICONDATA_V1_TIP_SIZE - 1] = _T('\0'); m_nidIconData.uFlags |= NIF_TIP; Shell_NotifyIcon(NIM_MODIFY, &m_nidIconData); } BOOL CTrayDialog::TrayShow() { BOOL bSuccess = FALSE; if (!m_bTrayIconVisible) { bSuccess = Shell_NotifyIcon(NIM_ADD, &m_nidIconData); if (bSuccess) m_bTrayIconVisible = TRUE; } return bSuccess; } BOOL CTrayDialog::TrayHide() { BOOL bSuccess = FALSE; if (m_bTrayIconVisible) { bSuccess = Shell_NotifyIcon(NIM_DELETE, &m_nidIconData); if (bSuccess) m_bTrayIconVisible = FALSE; } return bSuccess; } BOOL CTrayDialog::TrayUpdate() { BOOL bSuccess = FALSE; if (m_bTrayIconVisible) { bSuccess = Shell_NotifyIcon(NIM_MODIFY, &m_nidIconData); if (!bSuccess) { //ASSERT(0); return FALSE; // don't delete 'm_hPrevIconDelete' because it's still attached to the tray } } if (m_hPrevIconDelete != NULL) { VERIFY( ::DestroyIcon(m_hPrevIconDelete) ); m_hPrevIconDelete = NULL; } return bSuccess; } BOOL CTrayDialog::TraySetMenu(UINT nResourceID) { BOOL bSuccess = m_mnuTrayMenu.LoadMenu(nResourceID); ASSERT( bSuccess ); return bSuccess; } BOOL CTrayDialog::TraySetMenu(LPCTSTR lpszMenuName) { BOOL bSuccess = m_mnuTrayMenu.LoadMenu(lpszMenuName); ASSERT( bSuccess ); return bSuccess; } BOOL CTrayDialog::TraySetMenu(HMENU hMenu) { m_mnuTrayMenu.Attach(hMenu); return TRUE; } LRESULT CTrayDialog::OnTrayNotify(WPARAM wParam, LPARAM lParam) { UINT uID = (UINT)wParam; if (uID != 1) return 0; CPoint pt; UINT uMsg = (UINT)lParam; switch (uMsg) { case WM_MOUSEMOVE: GetCursorPos(&pt); ClientToScreen(&pt); OnTrayMouseMove(pt); break; case WM_LBUTTONDOWN: GetCursorPos(&pt); ClientToScreen(&pt); OnTrayLButtonDown(pt); break; case WM_LBUTTONUP: // Handle the WM_LBUTTONUP only if we know that there was also an according // WM_LBUTTONDOWN or WM_LBUTTONDBLCLK on our tray bar icon. If we would handle // WM_LBUTTONUP without checking this, we may get a single WM_LBUTTONUP message // whereby the according WM_LBUTTONDOWN message was meant for some other tray bar // icon. if (m_bLButtonDblClk) { KillSingleClickTimer(); //RestoreWindow(); ((CpopupApp*)AfxGetApp())->exitApp(); m_bLButtonDblClk = false; } else if (m_bLButtonDown) { ((CpopupApp*)AfxGetApp())->popupdlg->m_wndTaskbarNotifier->Hide(); ((CpopupApp*)AfxGetApp())->popupdlg->m_noSleep = true; if (m_uSingleClickTimer == 0) { if (!IsWindowVisible()) m_uSingleClickTimer = SetTimer(IDT_SINGLE_CLICK, 300, NULL); } m_bLButtonDown = false; } break; case WM_LBUTTONDBLCLK: KillSingleClickTimer(); GetCursorPos(&pt); ClientToScreen(&pt); OnTrayLButtonDblClk(pt); break; case WM_RBUTTONUP: case WM_CONTEXTMENU: KillSingleClickTimer(); GetCursorPos(&pt); ClientToScreen(&pt); OnTrayRButtonUp(pt); break; case WM_RBUTTONDBLCLK: KillSingleClickTimer(); GetCursorPos(&pt); ClientToScreen(&pt); OnTrayRButtonDblClk(pt); break; } return 1; } void CTrayDialog::KillSingleClickTimer() { if (m_uSingleClickTimer) { VERIFY( KillTimer(m_uSingleClickTimer) ); m_uSingleClickTimer = 0; } } void CTrayDialog::OnTimer(UINT nIDEvent) { if (nIDEvent == m_uSingleClickTimer) { OnTrayLButtonUp(CPoint(0, 0)); KillSingleClickTimer(); } CDialogMinTrayBtn<CResizableDialog>::OnTimer(nIDEvent); } void CTrayDialog::OnSysCommand(UINT nID, LPARAM lParam) { if (TrayShow()) ShowWindow(SW_HIDE); CTrayDialogBase::OnSysCommand(nID, lParam); } void CTrayDialog::TraySetMinimizeToTray(bool* pbMinimizeToTray) { m_pbMinimizeToTray = pbMinimizeToTray; } void CTrayDialog::TrayMinimizeToTrayChange() { if (m_pbMinimizeToTray == NULL) return; if (*m_pbMinimizeToTray) MinTrayBtnHide(); else MinTrayBtnShow(); } void CTrayDialog::OnTrayRButtonUp(CPoint /*pt*/) { } void CTrayDialog::OnTrayLButtonDown(CPoint /*pt*/) { m_bLButtonDown = true; } void CTrayDialog::OnTrayLButtonUp(CPoint /*pt*/) { } void CTrayDialog::OnTrayLButtonDblClk(CPoint /*pt*/) { m_bLButtonDblClk = true; } void CTrayDialog::OnTrayRButtonDblClk(CPoint /*pt*/) { } void CTrayDialog::OnTrayMouseMove(CPoint /*pt*/) { } LRESULT CTrayDialog::OnTaskBarCreated(WPARAM /*wParam*/, LPARAM /*lParam*/) { if (m_bTrayIconVisible) { BOOL bResult = Shell_NotifyIcon(NIM_ADD, &m_nidIconData); if (!bResult) m_bTrayIconVisible = false; } return 0; } void CTrayDialog::RestoreWindow() { ShowWindow(SW_SHOW); }
C++
//this file is part of ePopup // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once enum E_DebugFSAtion{ DFSA_ADD = 0, DFSA_SUB, DFSA_MUL, DFSA_DIV }; class CEMFileSize { public: CEMFileSize() {m_nSize = (uint64)(-1);} CEMFileSize(uint64 nSize) {m_nSize = nSize; Check();} __declspec(deprecated) CEMFileSize(uint32 nSize) {m_nSize = nSize; Check();} CEMFileSize& operator=(const CEMFileSize& k1) {m_nSize = k1.m_nSize; Check(); return *this; } CEMFileSize& operator=(uint64 k1) {m_nSize = k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator=(sint64 k1) {m_nSize = k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator=(uint32 k1) {m_nSize = k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator=(sint32 k1) {m_nSize = k1; Check(); return *this; } CEMFileSize& operator-=(const CEMFileSize& k1) {Check(); m_nSize -= k1.m_nSize; Check(); return *this; } CEMFileSize& operator-=(uint64 k1) {Check(); m_nSize -= k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator-=(sint64 k1) {Check(); m_nSize -= k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator-=(uint32 k1) {Check(); m_nSize -= k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator-=(sint32 k1) {Check(); m_nSize -= k1; Check(); return *this; } CEMFileSize& operator+=(const CEMFileSize& k1) {Check(); m_nSize += k1.m_nSize; Check(); return *this; } CEMFileSize& operator+=(uint64 k1) {Check(); m_nSize += k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator+=(sint64 k1) {Check(); m_nSize += k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator+=(uint32 k1) {Check(); m_nSize += k1; Check(); return *this; } __declspec(deprecated) CEMFileSize& operator+=(sint32 k1) {Check(); m_nSize += k1; Check(); return *this; } operator uint64() const {return m_nSize;} operator double() const {return (double)m_nSize;} /*__declspec(deprecated)*/ operator float() const {return (float)m_nSize;} /*__declspec(deprecated)*/ operator sint64() const {return (sint64)m_nSize;} __declspec(deprecated) operator uint32() const {ASSERT( m_nSize < 0xFFFFFFFF ); return (uint32)m_nSize;} __declspec(deprecated) operator sint32() const {ASSERT( m_nSize < 0x7FFFFFFF ); return (sint32)m_nSize;} friend bool operator==(const CEMFileSize& k1,const CEMFileSize& k2) {return k1.m_nSize == k2.m_nSize;} friend bool operator==(const CEMFileSize& k1,uint64 k2) {return k1.m_nSize == k2;} friend bool operator==(uint64 k1,const CEMFileSize& k2) {return k1 == k2.m_nSize;} __declspec(deprecated) friend bool operator==(uint32 k1,const CEMFileSize& k2) {return k1 == k2.m_nSize;} __declspec(deprecated) friend bool operator==(const CEMFileSize& k1,uint32 k2) {return k1.m_nSize == k2;} friend bool operator!=(const CEMFileSize& k1,const CEMFileSize& k2) {return k1.m_nSize != k2.m_nSize;} friend bool operator!=(const CEMFileSize& k1,uint64 k2) {return k1.m_nSize != k2;} friend bool operator!=(uint64 k1,const CEMFileSize& k2) {return k1 != k2.m_nSize;} __declspec(deprecated) friend bool operator!=(uint32 k1,const CEMFileSize& k2) {return k1 != k2.m_nSize;} __declspec(deprecated) friend bool operator!=(const CEMFileSize& k1,uint32 k2) {return k1.m_nSize != k2;} friend bool operator>(const CEMFileSize& k1,const CEMFileSize& k2) {return k1.m_nSize > k2.m_nSize;} friend bool operator>(const CEMFileSize& k1,uint64 k2) {return k1.m_nSize > k2;} friend bool operator>(uint64 k1,const CEMFileSize& k2) {return k1 > k2.m_nSize;} __declspec(deprecated) friend bool operator>(uint32 k1,const CEMFileSize& k2) {return k1 > k2.m_nSize;} __declspec(deprecated) friend bool operator>(const CEMFileSize& k1,uint32 k2) {return k1.m_nSize > k2;} friend bool operator<(const CEMFileSize& k1,const CEMFileSize& k2) {return k1.m_nSize < k2.m_nSize;} friend bool operator<(const CEMFileSize& k1,uint64 k2) {return k1.m_nSize < k2;} friend bool operator<(uint64 k1,const CEMFileSize& k2) {return k1 < k2.m_nSize;} __declspec(deprecated) friend bool operator<(uint32 k1,const CEMFileSize& k2) {return k1 < k2.m_nSize;} __declspec(deprecated) friend bool operator<(const CEMFileSize& k1,uint32 k2) {return k1.m_nSize < k2;} friend bool operator>=(const CEMFileSize& k1,const CEMFileSize& k2) {return k1.m_nSize >= k2.m_nSize;} friend bool operator>=(const CEMFileSize& k1,uint64 k2) {return k1.m_nSize >= k2;} friend bool operator>=(uint64 k1,const CEMFileSize& k2) {return k1 >= k2.m_nSize;} __declspec(deprecated) friend bool operator>=(uint32 k1,const CEMFileSize& k2) {return k1 >= k2.m_nSize;} __declspec(deprecated) friend bool operator>=(const CEMFileSize& k1,uint32 k2) {return k1.m_nSize >= k2;} friend bool operator<=(const CEMFileSize& k1,const CEMFileSize& k2) {return k1.m_nSize <= k2.m_nSize;} friend bool operator<=(const CEMFileSize& k1,uint64 k2) {return k1.m_nSize <= k2;} friend bool operator<=(uint64 k1,const CEMFileSize& k2) {return k1 <= k2.m_nSize;} __declspec(deprecated) friend bool operator<=(uint32 k1,const CEMFileSize& k2) {return k1 <= k2.m_nSize;} __declspec(deprecated) friend bool operator<=(const CEMFileSize& k1,uint32 k2) {return k1.m_nSize <= k2;} friend CEMFileSize operator+(const CEMFileSize& k1,const CEMFileSize& k2) {return CEMFileSize(k1.m_nSize, k2.m_nSize, DFSA_ADD);} friend CEMFileSize operator+(const CEMFileSize& k1,uint64 k2) {return CEMFileSize(k1.m_nSize, k2, DFSA_ADD);} friend CEMFileSize operator+(uint64 k1,const CEMFileSize& k2) {return CEMFileSize(k1, k2.m_nSize, DFSA_ADD);} friend CEMFileSize operator-(const CEMFileSize& k1,const CEMFileSize& k2) {return CEMFileSize(k1.m_nSize, k2.m_nSize, DFSA_SUB);} friend CEMFileSize operator-(const CEMFileSize& k1,uint64 k2) {return CEMFileSize(k1.m_nSize, k2, DFSA_SUB);} friend CEMFileSize operator-(uint64 k1,const CEMFileSize& k2) {return CEMFileSize(k1, k2.m_nSize, DFSA_SUB);} __declspec(deprecated) friend CEMFileSize operator-(uint32 k1,const CEMFileSize& k2) {return CEMFileSize(k1, k2.m_nSize, DFSA_SUB);} friend CEMFileSize operator*(const CEMFileSize& k1,const CEMFileSize& k2) {return CEMFileSize(k1.m_nSize, k2.m_nSize, DFSA_MUL);} friend CEMFileSize operator*(const CEMFileSize& k1,uint64 k2) {return CEMFileSize(k1.m_nSize, k2, DFSA_MUL);} friend CEMFileSize operator*(uint64 k1,const CEMFileSize& k2) {return CEMFileSize(k1, k2.m_nSize, DFSA_MUL);} friend CEMFileSize operator/(const CEMFileSize& k1,const CEMFileSize& k2) {return CEMFileSize(k1.m_nSize, k2.m_nSize, DFSA_DIV);} friend CEMFileSize operator/(const CEMFileSize& k1,uint64 k2) {return CEMFileSize(k1.m_nSize, k2, DFSA_DIV);} friend CEMFileSize operator/(uint64 k1,const CEMFileSize& k2) {return CEMFileSize(k1, k2.m_nSize, DFSA_DIV);} private: CEMFileSize(uint64 nSize1, uint64 nSize2, E_DebugFSAtion edfsAction) { if (edfsAction == DFSA_ADD){ m_nSize = nSize1 + nSize2; ASSERT( m_nSize >= nSize1 && m_nSize >= nSize2 && m_nSize <= 0x4000000000 ); } else if (edfsAction == DFSA_SUB){ m_nSize = nSize1 - nSize2; ASSERT( m_nSize <= nSize1 && m_nSize <= 0x4000000000 ); } else if (edfsAction == DFSA_DIV){ if ( nSize2 != 0 ) m_nSize = nSize1 / nSize2; else ASSERT( false ); } else if (edfsAction == DFSA_MUL){ m_nSize = nSize1 * nSize2; ASSERT( m_nSize >= nSize1 && m_nSize >= nSize2 && m_nSize <= 0x4000000000 ); } } void Check() { ASSERT( m_nSize != (uint64)(-1) && m_nSize <= 0x4000000000 ); } uint64 m_nSize; };
C++