summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Swift/Controllers/MainController.cpp3
-rw-r--r--Swift/Controllers/Roster/RosterController.cpp30
-rw-r--r--Swift/Controllers/Roster/RosterController.h5
-rw-r--r--Swift/Controllers/UIInterfaces/MainWindow.h2
-rw-r--r--Swift/Controllers/UnitTest/MockMainWindow.h1
-rw-r--r--Swift/QtUI/QtMainWindow.cpp4
-rw-r--r--Swift/QtUI/QtMainWindow.h1
-rw-r--r--Swift/QtUI/QtRosterHeader.cpp28
-rw-r--r--Swift/QtUI/QtRosterHeader.h8
9 files changed, 70 insertions, 12 deletions
diff --git a/Swift/Controllers/MainController.cpp b/Swift/Controllers/MainController.cpp
index df137f4..f16f8ad 100644
--- a/Swift/Controllers/MainController.cpp
+++ b/Swift/Controllers/MainController.cpp
@@ -1,891 +1,892 @@
/*
* Copyright (c) 2010-2013 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
/*
* Copyright (c) 2013 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swift/Controllers/MainController.h>
#include <cstdlib>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/format.h>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/String.h>
#include <Swiften/StringCodecs/Base64.h>
#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Client/Storages.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/Base/foreach.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Presence/PresenceSender.h>
#include <Swiften/Elements/ChatState.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/VCardUpdate.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Disco/CapsInfoGenerator.h>
#include <Swiften/Disco/GetDiscoInfoRequest.h>
#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/VCards/GetVCardRequest.h>
#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/Network/NetworkFactories.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <SwifTools/Dock/Dock.h>
#include <SwifTools/Notifier/TogglableNotifier.h>
#include <SwifTools/Idle/IdleDetector.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/UIInterfaces/UIFactory.h>
#include <Swift/Controllers/BuildVersion.h>
#include <Swift/Controllers/Chat/UserSearchController.h>
#include <Swift/Controllers/Chat/ChatsManager.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
#include <Swift/Controllers/EventWindowController.h>
#include <Swift/Controllers/UIInterfaces/LoginWindow.h>
#include <Swift/Controllers/UIInterfaces/LoginWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
#include <Swift/Controllers/Chat/MUCController.h>
#include <Swift/Controllers/Roster/RosterController.h>
#include <Swift/Controllers/SoundEventController.h>
#include <Swift/Controllers/SoundPlayer.h>
#include <Swift/Controllers/StatusTracker.h>
#include <Swift/Controllers/SystemTray.h>
#include <Swift/Controllers/SystemTrayController.h>
#include <Swift/Controllers/XMLConsoleController.h>
#include <Swift/Controllers/HistoryController.h>
#include <Swift/Controllers/HistoryViewController.h>
#include <Swift/Controllers/FileTransferListController.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/PresenceNotifier.h>
#include <Swift/Controllers/EventNotifier.h>
#include <Swift/Controllers/Storages/StoragesFactory.h>
#include <Swift/Controllers/WhiteboardManager.h>
#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
#include <Swift/Controllers/UIEvents/JoinMUCUIEvent.h>
#include <Swift/Controllers/Storages/CertificateStorageFactory.h>
#include <Swift/Controllers/Storages/CertificateStorageTrustChecker.h>
#include <Swift/Controllers/ProfileController.h>
#include <Swift/Controllers/ShowProfileController.h>
#include <Swift/Controllers/ContactEditController.h>
#include <Swift/Controllers/XMPPURIController.h>
#include <Swift/Controllers/AdHocManager.h>
#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swift/Controllers/HighlightManager.h>
#include <Swift/Controllers/HighlightEditorController.h>
#include <Swift/Controllers/BlockListController.h>
#include <Swift/Controllers/ContactSuggester.h>
#include <Swift/Controllers/ContactsFromXMPPRoster.h>
namespace Swift {
static const std::string CLIENT_NAME = "Swift";
static const std::string CLIENT_NODE = "http://swift.im";
MainController::MainController(
EventLoop* eventLoop,
NetworkFactories* networkFactories,
UIFactory* uiFactories,
SettingsProvider* settings,
SystemTray* systemTray,
SoundPlayer* soundPlayer,
StoragesFactory* storagesFactory,
CertificateStorageFactory* certificateStorageFactory,
Dock* dock,
Notifier* notifier,
URIHandler* uriHandler,
IdleDetector* idleDetector,
const std::map<std::string, std::string>& emoticons,
bool useDelayForLatency) :
eventLoop_(eventLoop),
networkFactories_(networkFactories),
uiFactory_(uiFactories),
storagesFactory_(storagesFactory),
certificateStorageFactory_(certificateStorageFactory),
settings_(settings),
uriHandler_(uriHandler),
idleDetector_(idleDetector),
loginWindow_(NULL) ,
useDelayForLatency_(useDelayForLatency),
ftOverview_(NULL),
emoticons_(emoticons) {
storages_ = NULL;
certificateStorage_ = NULL;
statusTracker_ = NULL;
presenceNotifier_ = NULL;
eventNotifier_ = NULL;
rosterController_ = NULL;
chatsManager_ = NULL;
historyController_ = NULL;
historyViewController_ = NULL;
eventWindowController_ = NULL;
profileController_ = NULL;
blockListController_ = NULL;
showProfileController_ = NULL;
contactEditController_ = NULL;
userSearchControllerChat_ = NULL;
userSearchControllerAdd_ = NULL;
userSearchControllerInvite_ = NULL;
contactsFromRosterProvider_ = NULL;
contactSuggesterWithoutRoster_ = NULL;
contactSuggesterWithRoster_ = NULL;
whiteboardManager_ = NULL;
adHocManager_ = NULL;
quitRequested_ = false;
clientInitialized_ = false;
offlineRequested_ = false;
timeBeforeNextReconnect_ = -1;
dock_ = dock;
uiEventStream_ = new UIEventStream();
notifier_ = new TogglableNotifier(notifier);
notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
eventController_ = new EventController();
eventController_->onEventQueueLengthChange.connect(boost::bind(&MainController::handleEventQueueLengthChange, this, _1));
systemTrayController_ = new SystemTrayController(eventController_, systemTray);
loginWindow_ = uiFactory_->createLoginWindow(uiEventStream_);
loginWindow_->setShowNotificationToggle(!notifier->isExternallyConfigured());
highlightManager_ = new HighlightManager(settings_);
highlightEditorController_ = new HighlightEditorController(uiEventStream_, uiFactory_, highlightManager_);
soundEventController_ = new SoundEventController(eventController_, soundPlayer, settings, highlightManager_);
xmppURIController_ = new XMPPURIController(uriHandler_, uiEventStream_);
std::string selectedLoginJID = settings_->getSetting(SettingConstants::LAST_LOGIN_JID);
bool loginAutomatically = settings_->getSetting(SettingConstants::LOGIN_AUTOMATICALLY);
std::string cachedPassword;
std::string cachedCertificate;
ClientOptions cachedOptions;
bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
if (!eagle) {
foreach (std::string profile, settings->getAvailableProfiles()) {
ProfileSettingsProvider profileSettings(profile, settings);
std::string password = profileSettings.getStringSetting("pass");
std::string certificate = profileSettings.getStringSetting("certificate");
std::string jid = profileSettings.getStringSetting("jid");
ClientOptions clientOptions = parseClientOptions(profileSettings.getStringSetting("options"));
loginWindow_->addAvailableAccount(jid, password, certificate, clientOptions);
if (jid == selectedLoginJID) {
cachedPassword = password;
cachedCertificate = certificate;
cachedOptions = clientOptions;
}
}
loginWindow_->selectUser(selectedLoginJID);
loginWindow_->setLoginAutomatically(loginAutomatically);
}
loginWindow_->onLoginRequest.connect(boost::bind(&MainController::handleLoginRequest, this, _1, _2, _3, _4, _5, _6, _7));
loginWindow_->onPurgeSavedLoginRequest.connect(boost::bind(&MainController::handlePurgeSavedLoginRequest, this, _1));
loginWindow_->onCancelLoginRequest.connect(boost::bind(&MainController::handleCancelLoginRequest, this));
loginWindow_->onQuitRequest.connect(boost::bind(&MainController::handleQuitRequest, this));
idleDetector_->setIdleTimeSeconds(settings->getSetting(SettingConstants::IDLE_TIMEOUT));
idleDetector_->onIdleChanged.connect(boost::bind(&MainController::handleInputIdleChanged, this, _1));
xmlConsoleController_ = new XMLConsoleController(uiEventStream_, uiFactory_);
fileTransferListController_ = new FileTransferListController(uiEventStream_, uiFactory_);
settings_->onSettingChanged.connect(boost::bind(&MainController::handleSettingChanged, this, _1));
if (loginAutomatically) {
profileSettings_ = new ProfileSettingsProvider(selectedLoginJID, settings_);
/* FIXME: deal with autologin with a cert*/
handleLoginRequest(selectedLoginJID, cachedPassword, cachedCertificate, CertificateWithKey::ref(), cachedOptions, true, true);
} else {
profileSettings_ = NULL;
}
}
MainController::~MainController() {
idleDetector_->onIdleChanged.disconnect(boost::bind(&MainController::handleInputIdleChanged, this, _1));
purgeCachedCredentials();
//setManagersOffline();
eventController_->disconnectAll();
resetClient();
delete highlightEditorController_;
delete highlightManager_;
delete fileTransferListController_;
delete xmlConsoleController_;
delete xmppURIController_;
delete soundEventController_;
delete systemTrayController_;
delete eventController_;
delete notifier_;
delete uiEventStream_;
}
void MainController::purgeCachedCredentials() {
safeClear(password_);
}
void MainController::resetClient() {
purgeCachedCredentials();
resetCurrentError();
resetPendingReconnects();
vCardPhotoHash_.clear();
delete contactEditController_;
contactEditController_ = NULL;
delete profileController_;
profileController_ = NULL;
delete showProfileController_;
showProfileController_ = NULL;
delete eventWindowController_;
eventWindowController_ = NULL;
delete chatsManager_;
chatsManager_ = NULL;
#ifdef SWIFT_EXPERIMENTAL_HISTORY
delete historyViewController_;
historyViewController_ = NULL;
delete historyController_;
historyController_ = NULL;
#endif
delete ftOverview_;
ftOverview_ = NULL;
delete rosterController_;
rosterController_ = NULL;
delete eventNotifier_;
eventNotifier_ = NULL;
delete presenceNotifier_;
presenceNotifier_ = NULL;
delete certificateStorage_;
certificateStorage_ = NULL;
delete storages_;
storages_ = NULL;
delete statusTracker_;
statusTracker_ = NULL;
delete profileSettings_;
profileSettings_ = NULL;
delete userSearchControllerChat_;
userSearchControllerChat_ = NULL;
delete userSearchControllerAdd_;
userSearchControllerAdd_ = NULL;
delete userSearchControllerInvite_;
userSearchControllerInvite_ = NULL;
delete contactSuggesterWithoutRoster_;
contactSuggesterWithoutRoster_ = NULL;
delete contactSuggesterWithRoster_;
contactSuggesterWithRoster_ = NULL;
delete contactsFromRosterProvider_;
contactsFromRosterProvider_ = NULL;
delete adHocManager_;
adHocManager_ = NULL;
delete whiteboardManager_;
whiteboardManager_ = NULL;
clientInitialized_ = false;
}
void MainController::handleSettingChanged(const std::string& settingPath) {
if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) {
notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
}
}
void MainController::resetPendingReconnects() {
timeBeforeNextReconnect_ = -1;
if (reconnectTimer_) {
reconnectTimer_->stop();
reconnectTimer_.reset();
}
resetCurrentError();
}
void MainController::resetCurrentError() {
if (lastDisconnectError_) {
lastDisconnectError_->conclude();
lastDisconnectError_ = boost::shared_ptr<ErrorEvent>();
}
}
void MainController::handleConnected() {
boundJID_ = client_->getJID();
resetCurrentError();
resetPendingReconnects();
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
purgeCachedCredentials();
}
bool freshLogin = rosterController_ == NULL;
myStatusLooksOnline_ = true;
if (freshLogin) {
profileController_ = new ProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_);
showProfileController_ = new ShowProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_);
ftOverview_ = new FileTransferOverview(client_->getFileTransferManager());
fileTransferListController_->setFileTransferOverview(ftOverview_);
- rosterController_ = new RosterController(jid_, client_->getRoster(), client_->getAvatarManager(), uiFactory_, client_->getNickManager(), client_->getNickResolver(), client_->getPresenceOracle(), client_->getSubscriptionManager(), eventController_, uiEventStream_, client_->getIQRouter(), settings_, client_->getEntityCapsProvider(), ftOverview_, client_->getClientBlockListManager(), client_->getVCardManager());
+ rosterController_ = new RosterController(boundJID_, client_->getRoster(), client_->getAvatarManager(), uiFactory_, client_->getNickManager(), client_->getNickResolver(), client_->getPresenceOracle(), client_->getSubscriptionManager(), eventController_, uiEventStream_, client_->getIQRouter(), settings_, client_->getEntityCapsProvider(), ftOverview_, client_->getClientBlockListManager(), client_->getVCardManager());
rosterController_->onChangeStatusRequest.connect(boost::bind(&MainController::handleChangeStatusRequest, this, _1, _2));
rosterController_->onSignOutRequest.connect(boost::bind(&MainController::signOut, this));
rosterController_->getWindow()->onShowCertificateRequest.connect(boost::bind(&MainController::handleShowCertificateRequest, this));
blockListController_ = new BlockListController(client_->getClientBlockListManager(), uiEventStream_, uiFactory_, eventController_);
contactEditController_ = new ContactEditController(rosterController_, client_->getVCardManager(), uiFactory_, uiEventStream_);
whiteboardManager_ = new WhiteboardManager(uiFactory_, uiEventStream_, client_->getNickResolver(), client_->getWhiteboardSessionManager());
/* Doing this early as an ordering fix. Various things later will
* want to have the user's nick available and this means it will
* be before they receive stanzas that need it (e.g. bookmarks).*/
client_->getVCardManager()->requestOwnVCard();
contactSuggesterWithoutRoster_ = new ContactSuggester();
contactSuggesterWithRoster_ = new ContactSuggester();
userSearchControllerInvite_ = new UserSearchController(UserSearchController::InviteToChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle());
#ifdef SWIFT_EXPERIMENTAL_HISTORY
historyController_ = new HistoryController(storages_->getHistoryStorage());
historyViewController_ = new HistoryViewController(jid_, uiEventStream_, historyController_, client_->getNickResolver(), client_->getAvatarManager(), client_->getPresenceOracle(), uiFactory_);
chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, historyController_, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, userSearchControllerInvite_, client_->getVCardManager());
#else
chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, NULL, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, userSearchControllerInvite_, client_->getVCardManager());
#endif
contactsFromRosterProvider_ = new ContactsFromXMPPRoster(client_->getRoster(), client_->getAvatarManager(), client_->getPresenceOracle());
contactSuggesterWithoutRoster_->addContactProvider(chatsManager_);
contactSuggesterWithRoster_->addContactProvider(chatsManager_);
contactSuggesterWithRoster_->addContactProvider(contactsFromRosterProvider_);
client_->onMessageReceived.connect(boost::bind(&ChatsManager::handleIncomingMessage, chatsManager_, _1));
chatsManager_->setAvatarManager(client_->getAvatarManager());
eventWindowController_ = new EventWindowController(eventController_, uiFactory_);
loginWindow_->morphInto(rosterController_->getWindow());
DiscoInfo discoInfo;
discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
discoInfo.addFeature(DiscoInfo::ChatStatesFeature);
discoInfo.addFeature(DiscoInfo::SecurityLabelsFeature);
discoInfo.addFeature(DiscoInfo::MessageCorrectionFeature);
#ifdef SWIFT_EXPERIMENTAL_FT
discoInfo.addFeature(DiscoInfo::JingleFeature);
discoInfo.addFeature(DiscoInfo::JingleFTFeature);
discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
#endif
#ifdef SWIFT_EXPERIMENTAL_WB
discoInfo.addFeature(DiscoInfo::WhiteboardFeature);
#endif
discoInfo.addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
client_->getDiscoManager()->setCapsNode(CLIENT_NODE);
client_->getDiscoManager()->setDiscoInfo(discoInfo);
userSearchControllerChat_ = new UserSearchController(UserSearchController::StartChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle());
userSearchControllerAdd_ = new UserSearchController(UserSearchController::AddContact, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithoutRoster_, client_->getAvatarManager(), client_->getPresenceOracle());
adHocManager_ = new AdHocManager(JID(boundJID_.getDomain()), uiFactory_, client_->getIQRouter(), uiEventStream_, rosterController_->getWindow());
chatsManager_->onImpromptuMUCServiceDiscovered.connect(boost::bind(&UserSearchController::setCanInitiateImpromptuMUC, userSearchControllerChat_, _1));
}
loginWindow_->setIsLoggingIn(false);
client_->requestRoster();
GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(boundJID_.getDomain()), client_->getIQRouter());
discoInfoRequest->onResponse.connect(boost::bind(&MainController::handleServerDiscoInfoResponse, this, _1, _2));
discoInfoRequest->send();
client_->getVCardManager()->requestOwnVCard();
+ rosterController_->setJID(boundJID_);
rosterController_->setEnabled(true);
rosterController_->getWindow()->setStreamEncryptionStatus(client_->isStreamEncrypted());
profileController_->setAvailable(true);
contactEditController_->setAvailable(true);
/* Send presence later to catch all the incoming presences. */
sendPresence(statusTracker_->getNextPresence());
/* Enable chats last of all, so rejoining MUCs has the right sent presence */
assert(chatsManager_);
chatsManager_->setOnline(true);
}
void MainController::handleEventQueueLengthChange(int count) {
dock_->setNumberOfPendingMessages(count);
}
void MainController::reconnectAfterError() {
if (reconnectTimer_) {
reconnectTimer_->stop();
}
performLoginFromCachedCredentials();
}
void MainController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) {
boost::shared_ptr<Presence> presence(new Presence());
if (show == StatusShow::None) {
// Note: this is misleading, None doesn't mean unavailable on the wire.
presence->setType(Presence::Unavailable);
resetPendingReconnects();
myStatusLooksOnline_ = false;
offlineRequested_ = true;
}
else {
offlineRequested_ = false;
presence->setShow(show);
}
presence->setStatus(statusText);
statusTracker_->setRequestedPresence(presence);
if (presence->getType() != Presence::Unavailable) {
profileSettings_->storeInt("lastShow", presence->getShow());
profileSettings_->storeString("lastStatus", presence->getStatus());
}
if (presence->getType() != Presence::Unavailable && !client_->isAvailable()) {
performLoginFromCachedCredentials();
} else {
sendPresence(presence);
}
}
void MainController::sendPresence(boost::shared_ptr<Presence> presence) {
rosterController_->getWindow()->setMyStatusType(presence->getShow());
rosterController_->getWindow()->setMyStatusText(presence->getStatus());
systemTrayController_->setMyStatusType(presence->getShow());
notifier_->setTemporarilyDisabled(presence->getShow() == StatusShow::DND);
// Add information and send
presence->updatePayload(boost::make_shared<VCardUpdate>(vCardPhotoHash_));
client_->getPresenceSender()->sendPresence(presence);
if (presence->getType() == Presence::Unavailable) {
logout();
}
}
void MainController::handleInputIdleChanged(bool idle) {
if (!statusTracker_) {
//Haven't logged in yet.
return;
}
if (settings_->getSetting(SettingConstants::IDLE_GOES_OFFLINE)) {
if (idle) {
logout();
}
}
else {
if (idle) {
if (statusTracker_->goAutoAway(idleDetector_->getIdleTimeSeconds())) {
if (client_ && client_->isAvailable()) {
sendPresence(statusTracker_->getNextPresence());
}
}
} else {
if (statusTracker_->goAutoUnAway()) {
if (client_ && client_->isAvailable()) {
sendPresence(statusTracker_->getNextPresence());
}
}
}
}
}
void MainController::handleShowCertificateRequest() {
std::vector<Certificate::ref> chain = client_->getStanzaChannel()->getPeerCertificateChain();
rosterController_->getWindow()->openCertificateDialog(chain);
}
void MainController::handleLoginRequest(const std::string &username, const std::string &password, const std::string& certificatePath, CertificateWithKey::ref certificate, const ClientOptions& options, bool remember, bool loginAutomatically) {
jid_ = JID(username);
if (!jid_.isValid() || jid_.getNode().empty()) {
loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'alice@wonderland.lit'"));
loginWindow_->setIsLoggingIn(false);
} else {
loginWindow_->setMessage("");
loginWindow_->setIsLoggingIn(true);
profileSettings_ = new ProfileSettingsProvider(username, settings_);
if (!settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
profileSettings_->storeString("jid", username);
profileSettings_->storeString("certificate", certificatePath);
profileSettings_->storeString("pass", (remember || loginAutomatically) ? password : "");
std::string optionString = serializeClientOptions(options);
profileSettings_->storeString("options", optionString);
settings_->storeSetting(SettingConstants::LAST_LOGIN_JID, username);
settings_->storeSetting(SettingConstants::LOGIN_AUTOMATICALLY, loginAutomatically);
loginWindow_->addAvailableAccount(profileSettings_->getStringSetting("jid"), profileSettings_->getStringSetting("pass"), profileSettings_->getStringSetting("certificate"), options);
}
password_ = password;
certificate_ = certificate;
clientOptions_ = options;
performLoginFromCachedCredentials();
}
}
void MainController::handlePurgeSavedLoginRequest(const std::string& username) {
settings_->removeProfile(username);
loginWindow_->removeAvailableAccount(username);
}
void MainController::performLoginFromCachedCredentials() {
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS) && password_.empty()) {
/* Then we can't try to login again. */
return;
}
/* If we logged in with a bare JID, and we have a full bound JID, re-login with the
* bound JID to try and keep dynamically assigned resources */
JID clientJID = jid_;
if (boundJID_.isValid() && jid_.isBare() && boundJID_.toBare() == jid_) {
clientJID = boundJID_;
}
if (!statusTracker_) {
statusTracker_ = new StatusTracker();
}
if (!clientInitialized_) {
storages_ = storagesFactory_->createStorages(jid_.toBare());
certificateStorage_ = certificateStorageFactory_->createCertificateStorage(jid_.toBare());
certificateTrustChecker_ = new CertificateStorageTrustChecker(certificateStorage_);
client_ = boost::make_shared<Swift::Client>(clientJID, createSafeByteArray(password_.c_str()), networkFactories_, storages_);
clientInitialized_ = true;
client_->setCertificateTrustChecker(certificateTrustChecker_);
client_->onDataRead.connect(boost::bind(&XMLConsoleController::handleDataRead, xmlConsoleController_, _1));
client_->onDataWritten.connect(boost::bind(&XMLConsoleController::handleDataWritten, xmlConsoleController_, _1));
client_->onDisconnected.connect(boost::bind(&MainController::handleDisconnected, this, _1));
client_->onConnected.connect(boost::bind(&MainController::handleConnected, this));
client_->setSoftwareVersion(CLIENT_NAME, buildVersion);
client_->getVCardManager()->onVCardChanged.connect(boost::bind(&MainController::handleVCardReceived, this, _1, _2));
presenceNotifier_ = new PresenceNotifier(client_->getStanzaChannel(), notifier_, client_->getMUCRegistry(), client_->getAvatarManager(), client_->getNickResolver(), client_->getPresenceOracle(), networkFactories_->getTimerFactory());
presenceNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
eventNotifier_ = new EventNotifier(eventController_, notifier_, client_->getAvatarManager(), client_->getNickResolver());
eventNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
if (certificate_ && !certificate_->isNull()) {
client_->setCertificate(certificate_);
}
boost::shared_ptr<Presence> presence(new Presence());
presence->setShow(static_cast<StatusShow::Type>(profileSettings_->getIntSetting("lastShow", StatusShow::Online)));
presence->setStatus(profileSettings_->getStringSetting("lastStatus"));
statusTracker_->setRequestedPresence(presence);
} else {
/* In case we're in the middle of another login, make sure they don't overlap */
client_->disconnect();
}
systemTrayController_->setConnecting();
if (rosterController_) {
rosterController_->getWindow()->setConnecting();
}
ClientOptions clientOptions = clientOptions_;
bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
clientOptions.forgetPassword = eagle;
clientOptions.useTLS = eagle ? ClientOptions::RequireTLS : clientOptions_.useTLS;
client_->connect(clientOptions);
}
void MainController::handleDisconnected(const boost::optional<ClientError>& error) {
if (rosterController_) {
rosterController_->getWindow()->setStreamEncryptionStatus(false);
}
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
purgeCachedCredentials();
}
if (quitRequested_) {
resetClient();
loginWindow_->quit();
}
else if (error) {
std::string message;
std::string certificateErrorMessage;
bool forceSignout = false;
switch(error->getType()) {
case ClientError::UnknownError: message = QT_TRANSLATE_NOOP("", "Unknown Error"); break;
case ClientError::DomainNameResolveError: message = QT_TRANSLATE_NOOP("", "Unable to find server"); break;
case ClientError::ConnectionError: message = QT_TRANSLATE_NOOP("", "Error connecting to server"); break;
case ClientError::ConnectionReadError: message = QT_TRANSLATE_NOOP("", "Error while receiving server data"); break;
case ClientError::ConnectionWriteError: message = QT_TRANSLATE_NOOP("", "Error while sending data to the server"); break;
case ClientError::XMLError: message = QT_TRANSLATE_NOOP("", "Error parsing server data"); break;
case ClientError::AuthenticationFailedError: message = QT_TRANSLATE_NOOP("", "Login/password invalid"); break;
case ClientError::CompressionFailedError: message = QT_TRANSLATE_NOOP("", "Error while compressing stream"); break;
case ClientError::ServerVerificationFailedError: message = QT_TRANSLATE_NOOP("", "Server verification failed"); break;
case ClientError::NoSupportedAuthMechanismsError: message = QT_TRANSLATE_NOOP("", "Authentication mechanisms not supported"); break;
case ClientError::UnexpectedElementError: message = QT_TRANSLATE_NOOP("", "Unexpected response"); break;
case ClientError::ResourceBindError: message = QT_TRANSLATE_NOOP("", "Error binding resource"); break;
case ClientError::SessionStartError: message = QT_TRANSLATE_NOOP("", "Error starting session"); break;
case ClientError::StreamError: message = QT_TRANSLATE_NOOP("", "Stream error"); break;
case ClientError::TLSError: message = QT_TRANSLATE_NOOP("", "Encryption error"); break;
case ClientError::ClientCertificateLoadError: message = QT_TRANSLATE_NOOP("", "Error loading certificate (Invalid password?)"); break;
case ClientError::ClientCertificateError: message = QT_TRANSLATE_NOOP("", "Certificate not authorized"); break;
case ClientError::CertificateCardRemoved: message = QT_TRANSLATE_NOOP("", "Certificate card removed"); forceSignout = true; break;
case ClientError::UnknownCertificateError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unknown certificate"); break;
case ClientError::CertificateExpiredError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has expired"); break;
case ClientError::CertificateNotYetValidError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not yet valid"); break;
case ClientError::CertificateSelfSignedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is self-signed"); break;
case ClientError::CertificateRejectedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been rejected"); break;
case ClientError::CertificateUntrustedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not trusted"); break;
case ClientError::InvalidCertificatePurposeError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate cannot be used for encrypting your connection"); break;
case ClientError::CertificatePathLengthExceededError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate path length constraint exceeded"); break;
case ClientError::InvalidCertificateSignatureError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid certificate signature"); break;
case ClientError::InvalidCAError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid Certificate Authority"); break;
case ClientError::InvalidServerIdentityError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate does not match the host identity"); break;
case ClientError::RevokedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been revoked"); break;
case ClientError::RevocationCheckFailedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unable to determine certificate revocation state"); break;
}
bool forceReconnectAfterCertificateTrust = false;
if (!certificateErrorMessage.empty()) {
std::vector<Certificate::ref> certificates = certificateTrustChecker_->getLastCertificateChain();
if (!certificates.empty() && loginWindow_->askUserToTrustCertificatePermanently(certificateErrorMessage, certificates)) {
certificateStorage_->addCertificate(certificates[0]);
forceReconnectAfterCertificateTrust = true;
}
else {
message = QT_TRANSLATE_NOOP("", "Certificate error");
}
}
if (forceReconnectAfterCertificateTrust && settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
forceReconnectAfterCertificateTrust = false;
forceSignout = true;
message = QT_TRANSLATE_NOOP("", "Re-enter credentials and retry");
}
if (forceReconnectAfterCertificateTrust) {
performLoginFromCachedCredentials();
}
else if (forceSignout || !rosterController_) { //hasn't been logged in yet or permanent error
signOut();
loginWindow_->setMessage(message);
loginWindow_->setIsLoggingIn(false);
} else {
logout();
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%. To reconnect, Sign Out and provide your password again.")) % jid_.getDomain() % message);
} else {
if (!offlineRequested_) {
setReconnectTimer();
}
if (lastDisconnectError_) {
message = str(format(QT_TRANSLATE_NOOP("", "Reconnect to %1% failed: %2%. Will retry in %3% seconds.")) % jid_.getDomain() % message % boost::lexical_cast<std::string>(timeBeforeNextReconnect_));
lastDisconnectError_->conclude();
} else {
message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%.")) % jid_.getDomain() % message);
}
lastDisconnectError_ = boost::make_shared<ErrorEvent>(JID(jid_.getDomain()), message);
eventController_->handleIncomingEvent(lastDisconnectError_);
}
}
}
else if (!rosterController_) { //hasn't been logged in yet
loginWindow_->setIsLoggingIn(false);
}
}
void MainController::setReconnectTimer() {
if (timeBeforeNextReconnect_ < 0) {
timeBeforeNextReconnect_ = 1;
} else {
timeBeforeNextReconnect_ = timeBeforeNextReconnect_ >= 150 ? 300 : timeBeforeNextReconnect_ * 2; // Randomly selected by roll of a die, as required by 3920bis
}
if (reconnectTimer_) {
reconnectTimer_->stop();
}
reconnectTimer_ = networkFactories_->getTimerFactory()->createTimer(timeBeforeNextReconnect_ * 1000);
reconnectTimer_->onTick.connect(boost::bind(&MainController::reconnectAfterError, this));
reconnectTimer_->start();
}
void MainController::handleCancelLoginRequest() {
signOut();
}
void MainController::signOut() {
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
purgeCachedCredentials();
}
eventController_->clear();
logout();
loginWindow_->loggedOut();
resetClient();
}
void MainController::logout() {
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
purgeCachedCredentials();
}
systemTrayController_->setMyStatusType(StatusShow::None);
if (clientInitialized_ /*&& client_->isAvailable()*/) {
client_->disconnect();
}
if (rosterController_ && myStatusLooksOnline_) {
rosterController_->getWindow()->setMyStatusType(StatusShow::None);
rosterController_->getWindow()->setMyStatusText("");
myStatusLooksOnline_ = false;
}
setManagersOffline();
}
void MainController::setManagersOffline() {
if (chatsManager_) {
chatsManager_->setOnline(false);
}
if (rosterController_) {
rosterController_->setEnabled(false);
}
if (profileController_) {
profileController_->setAvailable(false);
}
if (contactEditController_) {
contactEditController_->setAvailable(false);
}
}
void MainController::handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error) {
if (!error) {
chatsManager_->setServerDiscoInfo(info);
adHocManager_->setServerDiscoInfo(info);
if (info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
rosterController_->getWindow()->setBlockingCommandAvailable(true);
rosterController_->initBlockingCommand();
}
}
}
void MainController::handleVCardReceived(const JID& jid, VCard::ref vCard) {
if (!jid.equals(jid_, JID::WithoutResource) || !vCard) {
return;
}
std::string hash;
if (!vCard->getPhoto().empty()) {
hash = Hexify::hexify(networkFactories_->getCryptoProvider()->getSHA1Hash(vCard->getPhoto()));
}
if (hash != vCardPhotoHash_) {
vCardPhotoHash_ = hash;
if (client_ && client_->isAvailable()) {
sendPresence(statusTracker_->getNextPresence());
}
}
}
void MainController::handleNotificationClicked(const JID& jid) {
assert(chatsManager_);
if (clientInitialized_) {
if (client_->getMUCRegistry()->isMUC(jid)) {
uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(jid));
}
else {
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(jid)));
}
}
}
void MainController::handleQuitRequest() {
if (client_ && client_->isActive()) {
quitRequested_ = true;
client_->disconnect();
}
else {
resetClient();
loginWindow_->quit();
}
}
#define SERIALIZE_BOOL(option) result += options.option ? "1" : "0"; result += ",";
#define SERIALIZE_INT(option) result += boost::lexical_cast<std::string>(options.option); result += ",";
#define SERIALIZE_STRING(option) result += Base64::encode(createByteArray(options.option)); result += ",";
#define SERIALIZE_SAFE_STRING(option) result += safeByteArrayToString(Base64::encode(options.option)); result += ",";
#define SERIALIZE_URL(option) SERIALIZE_STRING(option.toString())
std::string MainController::serializeClientOptions(const ClientOptions& options) {
std::string result;
SERIALIZE_BOOL(useStreamCompression);
switch (options.useTLS) {
case ClientOptions::NeverUseTLS: result += "1";break;
case ClientOptions::UseTLSWhenAvailable: result += "2";break;
case ClientOptions::RequireTLS: result += "3";break;
}
result += ",";
SERIALIZE_BOOL(allowPLAINWithoutTLS);
SERIALIZE_BOOL(useStreamResumption);
SERIALIZE_BOOL(useAcks);
SERIALIZE_STRING(manualHostname);
SERIALIZE_INT(manualPort);
switch (options.proxyType) {
case ClientOptions::NoProxy: result += "1";break;
case ClientOptions::SystemConfiguredProxy: result += "2";break;
case ClientOptions::SOCKS5Proxy: result += "3";break;
case ClientOptions::HTTPConnectProxy: result += "4";break;
}
result += ",";
SERIALIZE_STRING(manualProxyHostname);
SERIALIZE_INT(manualProxyPort);
SERIALIZE_URL(boshURL);
SERIALIZE_URL(boshHTTPConnectProxyURL);
SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthID);
SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
return result;
}
#define CHECK_PARSE_LENGTH if (i >= segments.size()) {return result;}
#define PARSE_INT_RAW(defaultValue) CHECK_PARSE_LENGTH intVal = defaultValue; try {intVal = boost::lexical_cast<int>(segments[i]);} catch(const boost::bad_lexical_cast&) {};i++;
#define PARSE_STRING_RAW CHECK_PARSE_LENGTH stringVal = byteArrayToString(Base64::decode(segments[i]));i++;
#define PARSE_BOOL(option, defaultValue) PARSE_INT_RAW(defaultValue); result.option = (intVal == 1);
#define PARSE_INT(option, defaultValue) PARSE_INT_RAW(defaultValue); result.option = intVal;
#define PARSE_STRING(option) PARSE_STRING_RAW; result.option = stringVal;
#define PARSE_SAFE_STRING(option) PARSE_STRING_RAW; result.option = SafeString(createSafeByteArray(stringVal));
#define PARSE_URL(option) {PARSE_STRING_RAW; result.option = URL::fromString(stringVal);}
ClientOptions MainController::parseClientOptions(const std::string& optionString) {
ClientOptions result;
size_t i = 0;
int intVal = 0;
std::string stringVal;
std::vector<std::string> segments = String::split(optionString, ',');
PARSE_BOOL(useStreamCompression, 1);
PARSE_INT_RAW(-1);
switch (intVal) {
case 1: result.useTLS = ClientOptions::NeverUseTLS;break;
case 2: result.useTLS = ClientOptions::UseTLSWhenAvailable;break;
case 3: result.useTLS = ClientOptions::RequireTLS;break;
default:;
}
PARSE_BOOL(allowPLAINWithoutTLS, 0);
PARSE_BOOL(useStreamResumption, 0);
PARSE_BOOL(useAcks, 1);
PARSE_STRING(manualHostname);
PARSE_INT(manualPort, -1);
PARSE_INT_RAW(-1);
switch (intVal) {
case 1: result.proxyType = ClientOptions::NoProxy;break;
case 2: result.proxyType = ClientOptions::SystemConfiguredProxy;break;
case 3: result.proxyType = ClientOptions::SOCKS5Proxy;break;
case 4: result.proxyType = ClientOptions::HTTPConnectProxy;break;
}
PARSE_STRING(manualProxyHostname);
PARSE_INT(manualProxyPort, -1);
PARSE_URL(boshURL);
PARSE_URL(boshHTTPConnectProxyURL);
PARSE_SAFE_STRING(boshHTTPConnectProxyAuthID);
PARSE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
return result;
}
}
diff --git a/Swift/Controllers/Roster/RosterController.cpp b/Swift/Controllers/Roster/RosterController.cpp
index d2d024c..6bb5119 100644
--- a/Swift/Controllers/Roster/RosterController.cpp
+++ b/Swift/Controllers/Roster/RosterController.cpp
@@ -1,369 +1,389 @@
/*
* Copyright (c) 2010-2013 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swift/Controllers/Roster/RosterController.h>
#include <boost/bind.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Base/Path.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/NickManager.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/Disco/EntityCapsManager.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Jingle/JingleSessionManager.h>
#include <Swiften/Presence/PresenceOracle.h>
#include <Swiften/Presence/SubscriptionManager.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Roster/GetRosterRequest.h>
#include <Swiften/Roster/SetRosterRequest.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Roster/XMPPRosterItem.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/OfflineRosterFilter.h>
#include <Swift/Controllers/Roster/Roster.h>
#include <Swift/Controllers/Roster/RosterVCardProvider.h>
#include <Swift/Controllers/Roster/ItemOperations/AppearOffline.h>
#include <Swift/Controllers/Roster/ItemOperations/SetAvatar.h>
#include <Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h>
#include <Swift/Controllers/Roster/ItemOperations/SetBlockingState.h>
#include <Swift/Controllers/Roster/ItemOperations/SetName.h>
#include <Swift/Controllers/Roster/ItemOperations/SetPresence.h>
#include <Swift/Controllers/Roster/ItemOperations/SetVCard.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swift/Controllers/UIEvents/AddContactUIEvent.h>
#include <Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h>
#include <Swift/Controllers/UIEvents/RenameGroupUIEvent.h>
#include <Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h>
#include <Swift/Controllers/UIEvents/SendFileUIEvent.h>
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
#include <Swift/Controllers/UIInterfaces/MainWindowFactory.h>
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
#include <Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h>
namespace Swift {
/**
* The controller does not gain ownership of these parameters.
*/
RosterController::RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter, SettingsProvider* settings, EntityCapsProvider* entityCapsManager, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager)
- : myJID_(jid), xmppRoster_(xmppRoster), mainWindowFactory_(mainWindowFactory), mainWindow_(mainWindowFactory_->createMainWindow(uiEventStream)), roster_(new Roster()), offlineFilter_(new OfflineRosterFilter()), nickManager_(nickManager), nickResolver_(nickResolver), uiEventStream_(uiEventStream), entityCapsManager_(entityCapsManager), ftOverview_(fileTransferOverview), clientBlockListManager_(clientBlockListManager) {
+ : myJID_(jid), xmppRoster_(xmppRoster), mainWindowFactory_(mainWindowFactory), mainWindow_(mainWindowFactory_->createMainWindow(uiEventStream)), roster_(new Roster()), offlineFilter_(new OfflineRosterFilter()), vcardManager_(vcardManager), avatarManager_(avatarManager), nickManager_(nickManager), nickResolver_(nickResolver), presenceOracle_(presenceOracle), uiEventStream_(uiEventStream), entityCapsManager_(entityCapsManager), ftOverview_(fileTransferOverview), clientBlockListManager_(clientBlockListManager) {
assert(fileTransferOverview);
iqRouter_ = iqRouter;
- presenceOracle_ = presenceOracle;
subscriptionManager_ = subscriptionManager;
eventController_ = eventController;
settings_ = settings;
expandiness_ = new RosterGroupExpandinessPersister(roster_, settings);
mainWindow_->setRosterModel(roster_);
rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithoutResource);
changeStatusConnection_ = mainWindow_->onChangeStatusRequest.connect(boost::bind(&RosterController::handleChangeStatusRequest, this, _1, _2));
signOutConnection_ = mainWindow_->onSignOutRequest.connect(boost::bind(boost::ref(onSignOutRequest)));
xmppRoster_->onJIDAdded.connect(boost::bind(&RosterController::handleOnJIDAdded, this, _1));
xmppRoster_->onJIDUpdated.connect(boost::bind(&RosterController::handleOnJIDUpdated, this, _1, _2, _3));
xmppRoster_->onJIDRemoved.connect(boost::bind(&RosterController::handleOnJIDRemoved, this, _1));
xmppRoster_->onRosterCleared.connect(boost::bind(&RosterController::handleRosterCleared, this));
subscriptionManager_->onPresenceSubscriptionRequest.connect(boost::bind(&RosterController::handleSubscriptionRequest, this, _1, _2));
presenceOracle_->onPresenceChange.connect(boost::bind(&RosterController::handleIncomingPresence, this, _1));
uiEventConnection_ = uiEventStream->onUIEvent.connect(boost::bind(&RosterController::handleUIEvent, this, _1));
- avatarManager_ = avatarManager;
+
+ vcardManager_->onOwnVCardChanged.connect(boost::bind(&RosterController::handleOwnVCardChanged, this, _1));
avatarManager_->onAvatarChanged.connect(boost::bind(&RosterController::handleAvatarChanged, this, _1));
- mainWindow_->setMyAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_)));
+ presenceOracle_->onPresenceChange.connect(boost::bind(&RosterController::handlePresenceChanged, this, _1));
+ mainWindow_->setMyAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare())));
nickManager_->onOwnNickChanged.connect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1));
mainWindow_->setMyJID(jid);
mainWindow_->setMyNick(nickManager_->getOwnNick());
entityCapsManager_->onCapsChanged.connect(boost::bind(&RosterController::handleOnCapsChanged, this, _1));
settings_->onSettingChanged.connect(boost::bind(&RosterController::handleSettingChanged, this, _1));
handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+
+ ownContact_ = boost::make_shared<ContactRosterItem>(myJID_.toBare(), myJID_.toBare(), nickManager_->getOwnNick(), (GroupRosterItem*)0);
+ ownContact_->setVCard(vcardManager_->getVCard(myJID_.toBare()));
+ ownContact_->setAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare())));
+ mainWindow_->setMyContactRosterItem(ownContact_);
}
RosterController::~RosterController() {
settings_->onSettingChanged.disconnect(boost::bind(&RosterController::handleSettingChanged, this, _1));
nickManager_->onOwnNickChanged.disconnect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1));
delete offlineFilter_;
delete expandiness_;
mainWindow_->setRosterModel(NULL);
if (mainWindow_->canDelete()) {
delete mainWindow_;
}
delete rosterVCardProvider_;
delete roster_;
}
void RosterController::setEnabled(bool enabled) {
if (!enabled) {
roster_->applyOnItems(AppearOffline());
}
}
void RosterController::handleShowOfflineToggled(bool state) {
if (state) {
roster_->removeFilter(offlineFilter_);
} else {
roster_->addFilter(offlineFilter_);
}
}
void RosterController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) {
onChangeStatusRequest(show, statusText);
}
void RosterController::handleOnJIDAdded(const JID& jid) {
std::vector<std::string> groups = xmppRoster_->getGroupsForJID(jid);
std::string name = nickResolver_->jidToNick(jid);
if (!groups.empty()) {
foreach(const std::string& group, groups) {
roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid));
}
}
else {
roster_->addContact(jid, jid, name, QT_TRANSLATE_NOOP("", "Contacts"), avatarManager_->getAvatarPath(jid));
}
applyAllPresenceTo(jid);
}
void RosterController::applyAllPresenceTo(const JID& jid) {
foreach (Presence::ref presence, presenceOracle_->getAllPresence(jid)) {
roster_->applyOnItems(SetPresence(presence));
}
}
void RosterController::handleRosterCleared() {
roster_->removeAll();
}
void RosterController::handleOnJIDRemoved(const JID& jid) {
roster_->removeContact(jid);
}
void RosterController::handleOnJIDUpdated(const JID& jid, const std::string& oldName, const std::vector<std::string>& passedOldGroups) {
if (oldName != xmppRoster_->getNameForJID(jid)) {
roster_->applyOnItems(SetName(nickResolver_->jidToNick(jid), jid));
}
std::vector<std::string> groups = xmppRoster_->getGroupsForJID(jid);
std::vector<std::string> oldGroups = passedOldGroups;
std::string name = nickResolver_->jidToNick(jid);
std::string contactsGroup = QT_TRANSLATE_NOOP("", "Contacts");
if (oldGroups.empty()) {
oldGroups.push_back(contactsGroup);
}
if (groups.empty()) {
groups.push_back(contactsGroup);
}
foreach(const std::string& group, groups) {
if (std::find(oldGroups.begin(), oldGroups.end(), group) == oldGroups.end()) {
roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid));
}
}
foreach(const std::string& group, oldGroups) {
if (std::find(groups.begin(), groups.end(), group) == groups.end()) {
roster_->removeContactFromGroup(jid, group);
if (roster_->getGroup(group)->getChildren().size() == 0) {
roster_->removeGroup(group);
}
}
}
applyAllPresenceTo(jid);
}
void RosterController::handleSettingChanged(const std::string& settingPath) {
if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
}
}
void RosterController::handleBlockingStateChanged() {
if (clientBlockListManager_->getBlockList()->getState() == BlockList::Available) {
foreach(const JID& jid, clientBlockListManager_->getBlockList()->getItems()) {
roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
}
}
}
void RosterController::handleBlockingItemAdded(const JID& jid) {
roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
}
void RosterController::handleBlockingItemRemoved(const JID& jid) {
roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsUnblocked));
}
void RosterController::handleUIEvent(boost::shared_ptr<UIEvent> event) {
if (boost::shared_ptr<AddContactUIEvent> addContactEvent = boost::dynamic_pointer_cast<AddContactUIEvent>(event)) {
RosterItemPayload item;
item.setName(addContactEvent->getName());
item.setJID(addContactEvent->getJID());
item.setGroups(std::vector<std::string>(addContactEvent->getGroups().begin(), addContactEvent->getGroups().end()));
boost::shared_ptr<RosterPayload> roster(new RosterPayload());
roster->addItem(item);
SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
request->send();
subscriptionManager_->requestSubscription(addContactEvent->getJID());
}
else if (boost::shared_ptr<RemoveRosterItemUIEvent> removeEvent = boost::dynamic_pointer_cast<RemoveRosterItemUIEvent>(event)) {
RosterItemPayload item(removeEvent->getJID(), "", RosterItemPayload::Remove);
boost::shared_ptr<RosterPayload> roster(new RosterPayload());
roster->addItem(item);
SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
request->send();
}
else if (boost::shared_ptr<RenameRosterItemUIEvent> renameEvent = boost::dynamic_pointer_cast<RenameRosterItemUIEvent>(event)) {
JID contact(renameEvent->getJID());
RosterItemPayload item(contact, renameEvent->getNewName(), xmppRoster_->getSubscriptionStateForJID(contact));
item.setGroups(xmppRoster_->getGroupsForJID(contact));
boost::shared_ptr<RosterPayload> roster(new RosterPayload());
roster->addItem(item);
SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
request->send();
}
else if (boost::shared_ptr<RenameGroupUIEvent> renameGroupEvent = boost::dynamic_pointer_cast<RenameGroupUIEvent>(event)) {
std::vector<XMPPRosterItem> items = xmppRoster_->getItems();
std::string group = renameGroupEvent->getGroup();
// FIXME: We should handle contacts groups specially to avoid clashes
if (group == QT_TRANSLATE_NOOP("", "Contacts")) {
group = "";
}
foreach(XMPPRosterItem& item, items) {
std::vector<std::string> groups = item.getGroups();
if ( (group.empty() && groups.empty()) || std::find(groups.begin(), groups.end(), group) != groups.end()) {
groups.erase(std::remove(groups.begin(), groups.end(), group), groups.end());
if (std::find(groups.begin(), groups.end(), renameGroupEvent->getNewName()) == groups.end()) {
groups.push_back(renameGroupEvent->getNewName());
}
item.setGroups(groups);
updateItem(item);
}
}
}
else if (boost::shared_ptr<SendFileUIEvent> sendFileEvent = boost::dynamic_pointer_cast<SendFileUIEvent>(event)) {
//TODO add send file dialog to ChatView of receipient jid
ftOverview_->sendFile(sendFileEvent->getJID(), sendFileEvent->getFilename());
}
}
void RosterController::setContactGroups(const JID& jid, const std::vector<std::string>& groups) {
updateItem(XMPPRosterItem(jid, xmppRoster_->getNameForJID(jid), groups, xmppRoster_->getSubscriptionStateForJID(jid)));
}
void RosterController::updateItem(const XMPPRosterItem& item) {
RosterItemPayload itemPayload(item.getJID(), item.getName(), item.getSubscription());
itemPayload.setGroups(item.getGroups());
RosterPayload::ref roster = boost::make_shared<RosterPayload>();
roster->addItem(itemPayload);
SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
request->send();
}
void RosterController::initBlockingCommand() {
boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&RosterController::handleBlockingStateChanged, this));
blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&RosterController::handleBlockingItemAdded, this, _1));
blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&RosterController::handleBlockingItemRemoved, this, _1));
roster_->setBlockingSupported(true);
if (blockList->getState() == BlockList::Available) {
foreach(const JID& jid, blockList->getItems()) {
roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
}
}
}
void RosterController::handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload) {
if (!error) {
return;
}
std::string text = str(format(QT_TRANSLATE_NOOP("", "Server %1% rejected contact list change to item '%2%'")) % myJID_.getDomain() % rosterPayload->getItems()[0].getJID().toString());
if (!error->getText().empty()) {
text += ": " + error->getText();
}
boost::shared_ptr<ErrorEvent> errorEvent(new ErrorEvent(JID(myJID_.getDomain()), text));
eventController_->handleIncomingEvent(errorEvent);
}
void RosterController::handleIncomingPresence(Presence::ref newPresence) {
if (newPresence->getType() == Presence::Error) {
return;
}
roster_->applyOnItems(SetPresence(newPresence));
}
void RosterController::handleSubscriptionRequest(const JID& jid, const std::string& message) {
if (xmppRoster_->containsJID(jid) && (xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::To || xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::Both)) {
subscriptionManager_->confirmSubscription(jid);
return;
}
SubscriptionRequestEvent* eventPointer = new SubscriptionRequestEvent(jid, message);
eventPointer->onAccept.connect(boost::bind(&RosterController::handleSubscriptionRequestAccepted, this, eventPointer));
eventPointer->onDecline.connect(boost::bind(&RosterController::handleSubscriptionRequestDeclined, this, eventPointer));
boost::shared_ptr<StanzaEvent> event(eventPointer);
eventController_->handleIncomingEvent(event);
}
void RosterController::handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event) {
subscriptionManager_->confirmSubscription(event->getJID());
if (!xmppRoster_->containsJID(event->getJID()) || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::None || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::From) {
subscriptionManager_->requestSubscription(event->getJID());
}
}
void RosterController::handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event) {
subscriptionManager_->cancelSubscription(event->getJID());
}
+void RosterController::handleOwnVCardChanged(VCard::ref vcard) {
+ ownContact_->setVCard(vcard);
+ mainWindow_->setMyContactRosterItem(ownContact_);
+}
+
void RosterController::handleAvatarChanged(const JID& jid) {
boost::filesystem::path path = avatarManager_->getAvatarPath(jid);
roster_->applyOnItems(SetAvatar(jid, path));
- if (jid.equals(myJID_, JID::WithoutResource)) {
+ if (jid.equals(myJID_, JID::WithResource)) {
mainWindow_->setMyAvatarPath(pathToString(path));
}
+ ownContact_->setAvatarPath(pathToString(path));
+ mainWindow_->setMyContactRosterItem(ownContact_);
+}
+
+void RosterController::handlePresenceChanged(Presence::ref presence) {
+ if (presence->getFrom().equals(myJID_, JID::WithResource)) {
+ ownContact_->applyPresence(std::string(), presence);
+ mainWindow_->setMyContactRosterItem(ownContact_);
+ }
}
boost::optional<XMPPRosterItem> RosterController::getItem(const JID& jid) const {
return xmppRoster_->getItem(jid);
}
std::set<std::string> RosterController::getGroups() const {
return xmppRoster_->getGroups();
}
void RosterController::handleOnCapsChanged(const JID& jid) {
DiscoInfo::ref info = entityCapsManager_->getCaps(jid);
if (info) {
std::set<ContactRosterItem::Feature> features;
if (FileTransferManager::isSupportedBy(info)) {
features.insert(ContactRosterItem::FileTransferFeature);
}
if (info->hasFeature(DiscoInfo::WhiteboardFeature)) {
features.insert(ContactRosterItem::WhiteboardFeature);
}
roster_->applyOnItems(SetAvailableFeatures(jid, features));
}
}
}
diff --git a/Swift/Controllers/Roster/RosterController.h b/Swift/Controllers/Roster/RosterController.h
index 5b26fc7..d0c7024 100644
--- a/Swift/Controllers/Roster/RosterController.h
+++ b/Swift/Controllers/Roster/RosterController.h
@@ -1,118 +1,123 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <string>
#include <set>
#include <boost/shared_ptr.hpp>
#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swift/Controllers/UIEvents/UIEvent.h>
#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
#include <Swift/Controllers/Roster/RosterGroupExpandinessPersister.h>
namespace Swift {
class IQRouter;
class Roster;
class XMPPRoster;
class XMPPRosterItem;
class MainWindow;
class MainWindowFactory;
class OfflineRosterFilter;
class NickResolver;
class PresenceOracle;
class SubscriptionManager;
class EventController;
class SubscriptionRequestEvent;
class UIEventStream;
class IQRouter;
class SettingsProvider;
class NickManager;
class EntityCapsProvider;
class FileTransferManager;
class ClientBlockListManager;
class RosterVCardProvider;
class RosterController {
public:
RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter_, SettingsProvider* settings, EntityCapsProvider* entityCapsProvider, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager);
~RosterController();
void showRosterWindow();
+ void setJID(const JID& jid) { myJID_ = jid; }
MainWindow* getWindow() {return mainWindow_;}
boost::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
boost::signal<void ()> onSignOutRequest;
+ void handleOwnVCardChanged(VCard::ref vcard);
void handleAvatarChanged(const JID& jid);
+ void handlePresenceChanged(Presence::ref presence);
void setEnabled(bool enabled);
boost::optional<XMPPRosterItem> getItem(const JID&) const;
std::set<std::string> getGroups() const;
void setContactGroups(const JID& jid, const std::vector<std::string>& groups);
void updateItem(const XMPPRosterItem&);
void initBlockingCommand();
private:
void handleOnJIDAdded(const JID &jid);
void handleRosterCleared();
void handleOnJIDRemoved(const JID &jid);
void handleOnJIDUpdated(const JID &jid, const std::string& oldName, const std::vector<std::string>& oldGroups);
void handleStartChatRequest(const JID& contact);
void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText);
void handleShowOfflineToggled(bool state);
void handleIncomingPresence(boost::shared_ptr<Presence> newPresence);
void handleSubscriptionRequest(const JID& jid, const std::string& message);
void handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event);
void handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event);
void handleUIEvent(boost::shared_ptr<UIEvent> event);
void handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload);
void applyAllPresenceTo(const JID& jid);
void handleEditProfileRequest();
void handleOnCapsChanged(const JID& jid);
void handleSettingChanged(const std::string& settingPath);
void handleBlockingStateChanged();
void handleBlockingItemAdded(const JID& jid);
void handleBlockingItemRemoved(const JID& jid);
JID myJID_;
XMPPRoster* xmppRoster_;
MainWindowFactory* mainWindowFactory_;
MainWindow* mainWindow_;
Roster* roster_;
OfflineRosterFilter* offlineFilter_;
+ VCardManager* vcardManager_;
AvatarManager* avatarManager_;
NickManager* nickManager_;
NickResolver* nickResolver_;
PresenceOracle* presenceOracle_;
SubscriptionManager* subscriptionManager_;
EventController* eventController_;
RosterGroupExpandinessPersister* expandiness_;
IQRouter* iqRouter_;
SettingsProvider* settings_;
UIEventStream* uiEventStream_;
EntityCapsProvider* entityCapsManager_;
FileTransferOverview* ftOverview_;
ClientBlockListManager* clientBlockListManager_;
RosterVCardProvider* rosterVCardProvider_;
+ boost::shared_ptr<ContactRosterItem> ownContact_;
boost::bsignals::scoped_connection blockingOnStateChangedConnection_;
boost::bsignals::scoped_connection blockingOnItemAddedConnection_;
boost::bsignals::scoped_connection blockingOnItemRemovedConnection_;
boost::bsignals::scoped_connection changeStatusConnection_;
boost::bsignals::scoped_connection signOutConnection_;
boost::bsignals::scoped_connection uiEventConnection_;
};
}
diff --git a/Swift/Controllers/UIInterfaces/MainWindow.h b/Swift/Controllers/UIInterfaces/MainWindow.h
index c85106f..82750bf 100644
--- a/Swift/Controllers/UIInterfaces/MainWindow.h
+++ b/Swift/Controllers/UIInterfaces/MainWindow.h
@@ -1,51 +1,53 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <string>
#include <boost/shared_ptr.hpp>
#include <Swiften/JID/JID.h>
#include <Swiften/Elements/StatusShow.h>
#include <Swiften/Elements/DiscoItems.h>
#include <Swiften/TLS/Certificate.h>
#include <Swiften/Base/boost_bsignals.h>
+#include <Swift/Controllers/Roster/ContactRosterItem.h>
namespace Swift {
class Roster;
class MainWindow {
public:
MainWindow(bool candelete = true) : canDelete_(candelete) {}
virtual ~MainWindow() {}
bool canDelete() const {
return canDelete_;
}
virtual void setMyNick(const std::string& name) = 0;
virtual void setMyJID(const JID& jid) = 0;
virtual void setMyAvatarPath(const std::string& path) = 0;
virtual void setMyStatusText(const std::string& status) = 0;
virtual void setMyStatusType(StatusShow::Type type) = 0;
+ virtual void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) = 0;
/** Must be able to cope with NULL to clear the roster */
virtual void setRosterModel(Roster* roster) = 0;
virtual void setConnecting() = 0;
virtual void setBlockingCommandAvailable(bool isAvailable) = 0;
virtual void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands) = 0;
virtual void setStreamEncryptionStatus(bool tlsInPlaceAndValid) = 0;
virtual void openCertificateDialog(const std::vector<Certificate::ref>& chain) = 0;
boost::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
boost::signal<void ()> onSignOutRequest;
boost::signal<void ()> onShowCertificateRequest;
private:
bool canDelete_;
};
}
diff --git a/Swift/Controllers/UnitTest/MockMainWindow.h b/Swift/Controllers/UnitTest/MockMainWindow.h
index ff3fa4d..b56f352 100644
--- a/Swift/Controllers/UnitTest/MockMainWindow.h
+++ b/Swift/Controllers/UnitTest/MockMainWindow.h
@@ -1,31 +1,32 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
namespace Swift {
class Roster;
class MockMainWindow : public MainWindow {
public:
MockMainWindow() : roster(NULL) {}
virtual ~MockMainWindow() {}
virtual void setRosterModel(Roster* roster) {this->roster = roster;}
virtual void setMyNick(const std::string& /*name*/) {}
virtual void setMyJID(const JID& /*jid*/) {}
virtual void setMyAvatarPath(const std::string& /*path*/) {}
virtual void setMyStatusText(const std::string& /*status*/) {}
virtual void setMyStatusType(StatusShow::Type /*type*/) {}
+ virtual void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> /*contact*/) {}
virtual void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& /*commands*/) {}
virtual void setConnecting() {}
virtual void setStreamEncryptionStatus(bool /*tlsInPlaceAndValid*/) {}
virtual void openCertificateDialog(const std::vector<Certificate::ref>& /*chain*/) {}
virtual void setBlockingCommandAvailable(bool /*isAvailable*/) {}
Roster* roster;
};
}
diff --git a/Swift/QtUI/QtMainWindow.cpp b/Swift/QtUI/QtMainWindow.cpp
index 1acc519..31a8234 100644
--- a/Swift/QtUI/QtMainWindow.cpp
+++ b/Swift/QtUI/QtMainWindow.cpp
@@ -1,398 +1,402 @@
/*
* Copyright (c) 2010-2011 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swift/QtUI/QtMainWindow.h>
#include <boost/optional.hpp>
#include <boost/bind.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <QBoxLayout>
#include <QComboBox>
#include <QLineEdit>
#include <QListWidget>
#include <QListWidgetItem>
#include <QPushButton>
#include <QMenuBar>
#include <QToolBar>
#include <QAction>
#include <QTabWidget>
#include <Swiften/Base/Platform.h>
#include <Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestHistoryUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h>
#include <Swift/Controllers/UIEvents/JoinMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestAdHocUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestBlockListDialogUIEvent.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swift/QtUI/Roster/QtFilterWidget.h>
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtTabWidget.h>
#include <Swift/QtUI/QtSettingsProvider.h>
#include <Swift/QtUI/QtLoginWindow.h>
#include <Swift/QtUI/Roster/QtRosterWidget.h>
#include <Swift/QtUI/QtUISettingConstants.h>
#if defined(SWIFTEN_PLATFORM_MACOSX)
#include <Swift/QtUI/CocoaUIHelpers.h>
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
#include <Swift/QtUI/WinUIHelpers.h>
#else
#include <Swift/QtUI/QtCertificateViewerDialog.h>
#endif
namespace Swift {
QtMainWindow::QtMainWindow(SettingsProvider* settings, UIEventStream* uiEventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist) : QWidget(), MainWindow(false), loginMenus_(loginMenus) {
uiEventStream_ = uiEventStream;
settings_ = settings;
setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this);
mainLayout->setContentsMargins(0,0,0,0);
mainLayout->setSpacing(0);
meView_ = new QtRosterHeader(settings, statusCache, this);
mainLayout->addWidget(meView_);
connect(meView_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleStatusChanged(StatusShow::Type, const QString&)));
connect(meView_, SIGNAL(onEditProfileRequest()), this, SLOT(handleEditProfileRequest()));
connect(meView_, SIGNAL(onShowCertificateInfo()), this, SLOT(handleShowCertificateInfo()));
tabs_ = new QtTabWidget(this);
#if QT_VERSION >= 0x040500
tabs_->setDocumentMode(true);
#endif
tabs_->setTabPosition(QTabWidget::South);
mainLayout->addWidget(tabs_);
contactsTabWidget_ = new QWidget(this);
contactsTabWidget_->setContentsMargins(0, 0, 0, 0);
QBoxLayout *contactTabLayout = new QBoxLayout(QBoxLayout::TopToBottom, contactsTabWidget_);
contactsTabWidget_->setLayout(contactTabLayout);
contactTabLayout->setSpacing(0);
contactTabLayout->setContentsMargins(0, 0, 0, 0);
treeWidget_ = new QtRosterWidget(uiEventStream_, settings_, this);
contactTabLayout->addWidget(treeWidget_);
new QtFilterWidget(this, treeWidget_, uiEventStream_, contactTabLayout);
tabs_->addTab(contactsTabWidget_, tr("&Contacts"));
eventWindow_ = new QtEventWindow(uiEventStream_);
connect(eventWindow_, SIGNAL(onNewEventCountUpdated(int)), this, SLOT(handleEventCountUpdated(int)));
chatListWindow_ = new QtChatListWindow(uiEventStream_, settings_);
connect(chatListWindow_, SIGNAL(onCountUpdated(int)), this, SLOT(handleChatCountUpdated(int)));
tabs_->addTab(chatListWindow_, tr("C&hats"));
tabs_->addTab(eventWindow_, tr("&Notices"));
tabs_->setCurrentIndex(settings_->getSetting(QtUISettingConstants::CURRENT_ROSTER_TAB));
connect(tabs_, SIGNAL(currentChanged(int)), this, SLOT(handleTabChanged(int)));
tabBarCombo_ = NULL;
if (settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
tabs_->tabBar()->hide();
tabBarCombo_ = new QComboBox(this);
tabBarCombo_->setAccessibleName("Current View");
tabBarCombo_->addItem(tr("Contacts"));
tabBarCombo_->addItem(tr("Chats"));
tabBarCombo_->addItem(tr("Notices"));
tabBarCombo_->setCurrentIndex(tabs_->currentIndex());
mainLayout->addWidget(tabBarCombo_);
connect(tabBarCombo_, SIGNAL(currentIndexChanged(int)), tabs_, SLOT(setCurrentIndex(int)));
}
this->setLayout(mainLayout);
QMenu* viewMenu = new QMenu(tr("&View"), this);
menus_.push_back(viewMenu);
compactRosterAction_ = new QAction(tr("&Compact Roster"), this);
compactRosterAction_->setCheckable(true);
compactRosterAction_->setChecked(false);
connect(compactRosterAction_, SIGNAL(toggled(bool)), SLOT(handleCompactRosterToggled(bool)));
viewMenu->addAction(compactRosterAction_);
handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
showOfflineAction_ = new QAction(tr("&Show offline contacts"), this);
showOfflineAction_->setCheckable(true);
showOfflineAction_->setChecked(false);
connect(showOfflineAction_, SIGNAL(toggled(bool)), SLOT(handleShowOfflineToggled(bool)));
viewMenu->addAction(showOfflineAction_);
handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
if (emoticonsExist) {
showEmoticonsAction_ = new QAction(tr("&Show Emoticons"), this);
showEmoticonsAction_->setCheckable(true);
showEmoticonsAction_->setChecked(false);
connect(showEmoticonsAction_, SIGNAL(toggled(bool)), SLOT(handleShowEmoticonsToggled(bool)));
viewMenu->addAction(showEmoticonsAction_);
handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
}
//QAction* compactRosterAction_ = new QAction(tr("&Compact Roster"), this);
//compactRosterAction_->setCheckable(true);
//compactRosterAction_->setChecked(false);
//connect(compactRosterAction_, SIGNAL(toggled(bool)), uiPreferences_, SLOT(setCompactRosters(bool)));
//viewMenu->addAction(compactRosterAction_);
QMenu* actionsMenu = new QMenu(tr("&Actions"), this);
menus_.push_back(actionsMenu);
QAction* editProfileAction = new QAction(tr("Edit &Profile…"), this);
connect(editProfileAction, SIGNAL(triggered()), SLOT(handleEditProfileAction()));
actionsMenu->addAction(editProfileAction);
QAction* joinMUCAction = new QAction(tr("Enter &Room…"), this);
connect(joinMUCAction, SIGNAL(triggered()), SLOT(handleJoinMUCAction()));
actionsMenu->addAction(joinMUCAction);
#ifdef SWIFT_EXPERIMENTAL_HISTORY
QAction* viewLogsAction = new QAction(tr("&View History…"), this);
connect(viewLogsAction, SIGNAL(triggered()), SLOT(handleViewLogsAction()));
actionsMenu->addAction(viewLogsAction);
#endif
openBlockingListEditor_ = new QAction(tr("Edit &Blocking List…"), this);
connect(openBlockingListEditor_, SIGNAL(triggered()), SLOT(handleEditBlockingList()));
actionsMenu->addAction(openBlockingListEditor_);
openBlockingListEditor_->setVisible(false);
addUserAction_ = new QAction(tr("&Add Contact…"), this);
addUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
addUserAction_->setShortcutContext(Qt::ApplicationShortcut);
connect(addUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleAddUserActionTriggered(bool)));
actionsMenu->addAction(addUserAction_);
editUserAction_ = new QAction(tr("&Edit Selected Contact…"), this);
connect(editUserAction_, SIGNAL(triggered(bool)), treeWidget_, SLOT(handleEditUserActionTriggered(bool)));
actionsMenu->addAction(editUserAction_);
editUserAction_->setEnabled(false);
chatUserAction_ = new QAction(tr("Start &Chat…"), this);
chatUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N));
chatUserAction_->setShortcutContext(Qt::ApplicationShortcut);
connect(chatUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleChatUserActionTriggered(bool)));
actionsMenu->addAction(chatUserAction_);
serverAdHocMenu_ = new QMenu(tr("Run Server Command"), this);
actionsMenu->addMenu(serverAdHocMenu_);
actionsMenu->addSeparator();
QAction* signOutAction = new QAction(tr("&Sign Out"), this);
connect(signOutAction, SIGNAL(triggered()), SLOT(handleSignOutAction()));
actionsMenu->addAction(signOutAction);
toggleRequestDeliveryReceipts_ = new QAction(tr("&Request Delivery Receipts"), this);
toggleRequestDeliveryReceipts_->setCheckable(true);
toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
connect(toggleRequestDeliveryReceipts_, SIGNAL(toggled(bool)), SLOT(handleToggleRequestDeliveryReceipts(bool)));
QList< QAction* > generalMenuActions = loginMenus_.generalMenu->actions();
loginMenus_.generalMenu->insertAction(generalMenuActions.at(generalMenuActions.count()-2),toggleRequestDeliveryReceipts_);
treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QAction::setEnabled, editUserAction_, _1));
setAvailableAdHocCommands(std::vector<DiscoItems::Item>());
QAction* adHocAction = new QAction(tr("Collecting commands..."), this);
adHocAction->setEnabled(false);
serverAdHocMenu_->addAction(adHocAction);
serverAdHocCommandActions_.append(adHocAction);
settings_->onSettingChanged.connect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
}
QtMainWindow::~QtMainWindow() {
settings_->onSettingChanged.disconnect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
}
void QtMainWindow::handleTabChanged(int index) {
settings_->storeSetting(QtUISettingConstants::CURRENT_ROSTER_TAB, index);
}
void QtMainWindow::handleToggleRequestDeliveryReceipts(bool enabled) {
settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, enabled);
}
void QtMainWindow::handleShowCertificateInfo() {
onShowCertificateRequest();
}
void QtMainWindow::handleEditBlockingList() {
uiEventStream_->send(boost::make_shared<RequestBlockListDialogUIEvent>());
}
QtEventWindow* QtMainWindow::getEventWindow() {
return eventWindow_;
}
QtChatListWindow* QtMainWindow::getChatListWindow() {
return chatListWindow_;
}
void QtMainWindow::setRosterModel(Roster* roster) {
treeWidget_->setRosterModel(roster);
}
void QtMainWindow::handleEditProfileRequest() {
uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
}
void QtMainWindow::handleEventCountUpdated(int count) {
QColor eventTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
int eventIndex = 2;
tabs_->tabBar()->setTabTextColor(eventIndex, eventTabColor);
QString text = tr("&Notices");
if (count > 0) {
text += QString(" (%1)").arg(count);
}
tabs_->setTabText(eventIndex, text);
}
void QtMainWindow::handleChatCountUpdated(int count) {
QColor chatTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
int chatIndex = 1;
tabs_->tabBar()->setTabTextColor(chatIndex, chatTabColor);
QString text = tr("&Chats");
if (count > 0) {
text += QString(" (%1)").arg(count);
}
tabs_->setTabText(chatIndex, text);
}
void QtMainWindow::handleAddUserActionTriggered(bool /*checked*/) {
boost::shared_ptr<UIEvent> event(new RequestAddUserDialogUIEvent());
uiEventStream_->send(event);
}
void QtMainWindow::handleChatUserActionTriggered(bool /*checked*/) {
boost::shared_ptr<UIEvent> event(new RequestChatWithUserDialogUIEvent());
uiEventStream_->send(event);
}
void QtMainWindow::handleSignOutAction() {
loginMenus_.generalMenu->removeAction(toggleRequestDeliveryReceipts_);
onSignOutRequest();
}
void QtMainWindow::handleEditProfileAction() {
uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
}
void QtMainWindow::handleJoinMUCAction() {
uiEventStream_->send(boost::make_shared<RequestJoinMUCUIEvent>());
}
void QtMainWindow::handleViewLogsAction() {
uiEventStream_->send(boost::make_shared<RequestHistoryUIEvent>());
}
void QtMainWindow::handleStatusChanged(StatusShow::Type showType, const QString &statusMessage) {
onChangeStatusRequest(showType, Q2PSTRING(statusMessage));
}
void QtMainWindow::handleSettingChanged(const std::string& settingPath) {
if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
}
if (settingPath == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
}
if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
}
if (settingPath == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
}
void QtMainWindow::handleCompactRosterToggled(bool state) {
settings_->storeSetting(QtUISettingConstants::COMPACT_ROSTER, state);
compactRosterAction_->setChecked(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
void QtMainWindow::handleShowOfflineToggled(bool state) {
settings_->storeSetting(SettingConstants::SHOW_OFFLINE, state);
showOfflineAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
}
void QtMainWindow::handleShowEmoticonsToggled(bool state) {
settings_->storeSetting(QtUISettingConstants::SHOW_EMOTICONS, state);
showEmoticonsAction_->setChecked(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
}
void QtMainWindow::setMyNick(const std::string& nick) {
meView_->setNick(P2QSTRING(nick));
}
void QtMainWindow::setMyJID(const JID& jid) {
meView_->setJID(P2QSTRING(jid.toBare().toString()));
}
void QtMainWindow::setMyAvatarPath(const std::string& path) {
meView_->setAvatar(P2QSTRING(path));
}
void QtMainWindow::setMyStatusText(const std::string& status) {
meView_->setStatusText(P2QSTRING(status));
}
void QtMainWindow::setMyStatusType(StatusShow::Type type) {
meView_->setStatusType(type);
}
+void QtMainWindow::setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) {
+ meView_->setContactRosterItem(contact);
+}
+
void QtMainWindow::setConnecting() {
meView_->setConnecting();
}
void QtMainWindow::setStreamEncryptionStatus(bool tlsInPlaceAndValid) {
meView_->setStreamEncryptionStatus(tlsInPlaceAndValid);
}
void QtMainWindow::openCertificateDialog(const std::vector<Certificate::ref>& chain) {
openCertificateDialog(chain, this);
}
void QtMainWindow::openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent) {
#if defined(SWIFTEN_PLATFORM_MACOSX)
CocoaUIHelpers::displayCertificateChainAsSheet(parent, chain);
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
WinUIHelpers::displayCertificateChainAsSheet(parent, chain);
#else
QtCertificateViewerDialog::displayCertificateChainAsSheet(parent, chain);
#endif
}
void QtMainWindow::handleAdHocActionTriggered(bool /*checked*/) {
QAction* action = qobject_cast<QAction*>(sender());
assert(action);
DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)];
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestAdHocUIEvent(command)));
}
void QtMainWindow::setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands) {
serverAdHocCommands_ = commands;
foreach (QAction* action, serverAdHocCommandActions_) {
delete action;
}
serverAdHocMenu_->clear();
serverAdHocCommandActions_.clear();
foreach (DiscoItems::Item command, commands) {
QAction* action = new QAction(P2QSTRING(command.getName()), this);
connect(action, SIGNAL(triggered(bool)), this, SLOT(handleAdHocActionTriggered(bool)));
serverAdHocMenu_->addAction(action);
serverAdHocCommandActions_.append(action);
}
if (serverAdHocCommandActions_.isEmpty()) {
QAction* action = new QAction(tr("No Available Commands"), this);
action->setEnabled(false);
serverAdHocMenu_->addAction(action);
serverAdHocCommandActions_.append(action);
}
}
void QtMainWindow::setBlockingCommandAvailable(bool isAvailable) {
openBlockingListEditor_->setVisible(isAvailable);
}
}
diff --git a/Swift/QtUI/QtMainWindow.h b/Swift/QtUI/QtMainWindow.h
index c489a9e..f1f6900 100644
--- a/Swift/QtUI/QtMainWindow.h
+++ b/Swift/QtUI/QtMainWindow.h
@@ -1,105 +1,106 @@
/*
* Copyright (c) 2010-2011 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <vector>
#include <QWidget>
#include <QMenu>
#include <QList>
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
#include <Swift/QtUI/QtRosterHeader.h>
#include <Swift/QtUI/EventViewer/QtEventWindow.h>
#include <Swift/QtUI/ChatList/QtChatListWindow.h>
#include <Swift/QtUI/QtLoginWindow.h>
class QComboBox;
class QLineEdit;
class QPushButton;
class QToolBar;
class QAction;
class QMenu;
class QTabWidget;
namespace Swift {
class QtRosterWidget;
class TreeWidget;
class UIEventStream;
class QtTabWidget;
class SettingsProvider;
class QtUIPreferences;
class StatusCache;
class QtMainWindow : public QWidget, public MainWindow {
Q_OBJECT
public:
QtMainWindow(SettingsProvider*, UIEventStream* eventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist);
virtual ~QtMainWindow();
std::vector<QMenu*> getMenus() {return menus_;}
void setMyNick(const std::string& name);
void setMyJID(const JID& jid);
void setMyAvatarPath(const std::string& path);
void setMyStatusText(const std::string& status);
void setMyStatusType(StatusShow::Type type);
+ void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
void setConnecting();
void setStreamEncryptionStatus(bool tlsInPlaceAndValid);
void openCertificateDialog(const std::vector<Certificate::ref>& chain);
static void openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent);
QtEventWindow* getEventWindow();
QtChatListWindow* getChatListWindow();
void setRosterModel(Roster* roster);
void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands);
void setBlockingCommandAvailable(bool isAvailable);
private slots:
void handleStatusChanged(StatusShow::Type showType, const QString &statusMessage);
void handleSettingChanged(const std::string& settingPath);
void handleCompactRosterToggled(bool);
void handleShowOfflineToggled(bool);
void handleShowEmoticonsToggled(bool);
void handleJoinMUCAction();
void handleViewLogsAction();
void handleSignOutAction();
void handleEditProfileAction();
void handleAddUserActionTriggered(bool checked);
void handleChatUserActionTriggered(bool checked);
void handleAdHocActionTriggered(bool checked);
void handleEventCountUpdated(int count);
void handleChatCountUpdated(int count);
void handleEditProfileRequest();
void handleTabChanged(int index);
void handleToggleRequestDeliveryReceipts(bool enabled);
void handleShowCertificateInfo();
void handleEditBlockingList();
private:
SettingsProvider* settings_;
QtLoginWindow::QtMenus loginMenus_;
std::vector<QMenu*> menus_;
QtRosterWidget* treeWidget_;
QtRosterHeader* meView_;
QAction* addUserAction_;
QAction* editUserAction_;
QAction* chatUserAction_;
QAction* showOfflineAction_;
QAction* compactRosterAction_;
QAction* showEmoticonsAction_;
QAction* openBlockingListEditor_;
QAction* toggleRequestDeliveryReceipts_;
QMenu* serverAdHocMenu_;
QtTabWidget* tabs_;
QComboBox* tabBarCombo_;
QWidget* contactsTabWidget_;
QWidget* eventsTabWidget_;
QtEventWindow* eventWindow_;
QtChatListWindow* chatListWindow_;
UIEventStream* uiEventStream_;
std::vector<DiscoItems::Item> serverAdHocCommands_;
QList<QAction*> serverAdHocCommandActions_;
};
}
diff --git a/Swift/QtUI/QtRosterHeader.cpp b/Swift/QtUI/QtRosterHeader.cpp
index 2c8f244..69a0ef6 100644
--- a/Swift/QtUI/QtRosterHeader.cpp
+++ b/Swift/QtUI/QtRosterHeader.cpp
@@ -1,116 +1,134 @@
/*
* Copyright (c) 2010-2014 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "QtRosterHeader.h"
-#include <QHBoxLayout>
-#include <QVBoxLayout>
+#include <QBitmap>
+#include <qdebug.h>
#include <QFileInfo>
+#include <QHBoxLayout>
+#include <QHelpEvent>
#include <QIcon>
-#include <QSizePolicy>
-#include <qdebug.h>
#include <QMouseEvent>
#include <QPainter>
-#include <QBitmap>
+#include <QSizePolicy>
+#include <QToolTip>
+#include <QVBoxLayout>
#include "QtStatusWidget.h"
#include <Swift/QtUI/QtElidingLabel.h>
#include <Swift/QtUI/QtClickableLabel.h>
#include <Swift/QtUI/QtNameWidget.h>
+#include <Swift/QtUI/Roster/RosterTooltip.h>
#include "QtScaledAvatarCache.h"
namespace Swift {
QtRosterHeader::QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent) : QWidget(parent), statusEdit_(NULL) {
QHBoxLayout* topLayout = new QHBoxLayout();
topLayout->setSpacing(3);
topLayout->setContentsMargins(4,4,4,4);
setLayout(topLayout);
setMinimumHeight(50);
setMaximumHeight(50);
avatarLabel_ = new QtClickableLabel(this);
avatarLabel_->setMinimumSize(avatarSize_, avatarSize_);
avatarLabel_->setMaximumSize(avatarSize_, avatarSize_);
avatarLabel_->setAlignment(Qt::AlignCenter);
setAvatar(":/icons/avatar.png");
avatarLabel_->setScaledContents(false);
topLayout->addWidget(avatarLabel_);
connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
QVBoxLayout* rightLayout = new QVBoxLayout();
rightLayout->setSpacing(4);
rightLayout->setContentsMargins(4,0,0,0);
topLayout->addLayout(rightLayout);
QHBoxLayout* nameAndSecurityLayout = new QHBoxLayout();
nameAndSecurityLayout->setContentsMargins(4,0,0,0);
nameWidget_ = new QtNameWidget(settings, this);
connect(nameWidget_, SIGNAL(onChangeNickRequest()), this, SIGNAL(onEditProfileRequest()));
nameAndSecurityLayout->addWidget(nameWidget_);
securityInfoButton_ = new QToolButton(this);
securityInfoButton_->setStyleSheet("QToolButton { border: none; } QToolButton:hover { border: 1px solid #bebebe; } QToolButton:pressed { border: 1px solid #757575; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777777, stop: 1 #d4d4d4);}");
//securityInfoButton_->setAutoRaise(true);
securityInfoButton_->setIcon(QIcon(":/icons/lock.png"));
securityInfoButton_->setToolTip(tr("Connection is secured"));
connect(securityInfoButton_, SIGNAL(clicked()), this, SIGNAL(onShowCertificateInfo()));
nameAndSecurityLayout->addWidget(securityInfoButton_);
rightLayout->addLayout(nameAndSecurityLayout);
statusWidget_ = new QtStatusWidget(statusCache, this);
connect(statusWidget_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleChangeStatusRequest(StatusShow::Type, const QString&)));
rightLayout->addWidget(statusWidget_);
show();
}
void QtRosterHeader::handleChangeStatusRequest(StatusShow::Type type, const QString& text) {
emit onChangeStatusRequest(type, text);
}
void QtRosterHeader::setStatusText(const QString& statusMessage) {
statusWidget_->setStatusText(statusMessage);
}
void QtRosterHeader::setStatusType(StatusShow::Type type) {
statusWidget_->setStatusType(type);
}
void QtRosterHeader::setConnecting() {
statusWidget_->setConnecting();
}
void QtRosterHeader::setStreamEncryptionStatus(bool tlsInPlace) {
securityInfoButton_->setVisible(tlsInPlace);
}
+bool QtRosterHeader::event(QEvent* event) {
+ if (event->type() == QEvent::ToolTip) {
+ QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
+ QtScaledAvatarCache scaledAvatarCache(avatarSize_);
+ QString text = RosterTooltip::buildDetailedTooltip(contact_.get(), &scaledAvatarCache);
+ QToolTip::showText(helpEvent->globalPos(), text);
+ return true;
+ }
+ return QWidget::event(event);
+}
+
void QtRosterHeader::setAvatar(const QString& path) {
QString scaledAvatarPath = QtScaledAvatarCache(avatarSize_).getScaledAvatarPath(path);
QPixmap avatar;
if (QFileInfo(scaledAvatarPath).exists()) {
avatar.load(scaledAvatarPath);
}
else {
avatar = QPixmap(":/icons/avatar.png").scaled(avatarSize_, avatarSize_, Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
avatarLabel_->setPixmap(avatar);
}
void QtRosterHeader::setNick(const QString& nick) {
nameWidget_->setNick(nick);
}
+void QtRosterHeader::setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) {
+ contact_ = contact;
+}
+
void QtRosterHeader::setJID(const QString& jid) {
nameWidget_->setJID(jid);
}
const int QtRosterHeader::avatarSize_ = 40;
}
diff --git a/Swift/QtUI/QtRosterHeader.h b/Swift/QtUI/QtRosterHeader.h
index ad19178..eafbc02 100644
--- a/Swift/QtUI/QtRosterHeader.h
+++ b/Swift/QtUI/QtRosterHeader.h
@@ -1,58 +1,64 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <QWidget>
#include <QLabel>
#include <QPixmap>
#include <QSize>
#include <QToolButton>
#include <string>
-#include "Swiften/Elements/StatusShow.h"
+#include <Swiften/Elements/StatusShow.h>
+#include <Swiften/Elements/VCard.h>
+#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include "QtTextEdit.h"
class QHBoxLayout;
namespace Swift {
class QtClickableLabel;
class QtStatusWidget;
class QtNameWidget;
class SettingsProvider;
class StatusCache;
class QtRosterHeader : public QWidget {
Q_OBJECT
public:
QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = NULL);
void setAvatar(const QString& path);
void setJID(const QString& jid);
void setNick(const QString& nick);
+ void setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
void setStatusText(const QString& statusMessage);
void setStatusType(StatusShow::Type type);
void setConnecting();
void setStreamEncryptionStatus(bool tlsInPlace);
+ private:
+ bool event(QEvent* event);
signals:
void onChangeStatusRequest(StatusShow::Type showType, const QString &statusMessage);
void onEditProfileRequest();
void onShowCertificateInfo();
private slots:
void handleChangeStatusRequest(StatusShow::Type type, const QString &statusMessage);
private:
QString name_;
QtClickableLabel* avatarLabel_;
QtNameWidget* nameWidget_;
QtTextEdit* statusEdit_;
QtStatusWidget* statusWidget_;
QToolButton* securityInfoButton_;
static const int avatarSize_;
+ boost::shared_ptr<ContactRosterItem> contact_;
};
}