diff options
author | Robert <krzmbrzl@gmail.com> | 2020-09-11 19:29:33 +0300 |
---|---|---|
committer | Robert <krzmbrzl@gmail.com> | 2020-09-11 19:29:33 +0300 |
commit | af7dac72f4063dd8d4dac71973ea51c25896089a (patch) | |
tree | 35558695aea94d48fd9e77d164d63fd8b7c76e90 /src | |
parent | 40b28b03c150b453e00c6bc4f8d6957caea59c51 (diff) |
FORMAT: Run clang-format 10 on all C/CXX source-files
Diffstat (limited to 'src')
328 files changed, 26710 insertions, 25577 deletions
diff --git a/src/ACL.cpp b/src/ACL.cpp index ba9ab5ec0..25264bcda 100644 --- a/src/ACL.cpp +++ b/src/ACL.cpp @@ -9,9 +9,9 @@ #include "User.h" #ifdef MURMUR -#include "ServerUser.h" +# include "ServerUser.h" -#include <QtCore/QStack> +# include <QtCore/QStack> #endif ChanACL::ChanACL(Channel *chan) : QObject(chan) { @@ -36,7 +36,7 @@ ChanACL::operator QString() const { // If we have a name for the permission, we know it exists. // Note that we won't reach 0 with this tactic but we don't care about the None // permission anyways. - QString name = permName(static_cast<Perm>(currentPermInt)); + QString name = permName(static_cast< Perm >(currentPermInt)); if (!name.isEmpty()) { if (!((pAllow & currentPermInt) || (pDeny & currentPermInt))) { @@ -72,8 +72,10 @@ ChanACL::operator QString() const { // Alos include info about affected user and/or group if (!qsGroup.isEmpty() && iUserId >= 0) { // both group and user-id are set - return QString::fromLatin1("ACL for group \"%1\" and user with ID %2: %3").arg( - qsGroup).arg(iUserId).arg(aclString); + return QString::fromLatin1("ACL for group \"%1\" and user with ID %2: %3") + .arg(qsGroup) + .arg(iUserId) + .arg(aclString); } else if (!qsGroup.isEmpty()) { return QString::fromLatin1("ACL for group \"%1\": %2").arg(qsGroup).arg(aclString); } else if (iUserId >= 0) { @@ -91,29 +93,29 @@ ChanACL::operator QString() const { #ifdef MURMUR -bool ChanACL::hasPermission(ServerUser *p, Channel *chan, QFlags<Perm> perm, ACLCache *cache) { +bool ChanACL::hasPermission(ServerUser *p, Channel *chan, QFlags< Perm > perm, ACLCache *cache) { Permissions granted = effectivePermissions(p, chan, cache); return ((granted & perm) != None); } // Return effective permissions. -QFlags<ChanACL::Perm> ChanACL::effectivePermissions(ServerUser *p, Channel *chan, ACLCache *cache) { +QFlags< ChanACL::Perm > ChanACL::effectivePermissions(ServerUser *p, Channel *chan, ACLCache *cache) { // Superuser if (p->iId == 0) { - return static_cast<Permissions>(All &~ (Speak|Whisper)); + return static_cast< Permissions >(All & ~(Speak | Whisper)); } -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +# if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // Qt 5.15 introduced a default constructor that initializes the flags to be set to no flags Permissions granted; -#else +# else // Before Qt 5.15 we have emulate the default constructor by assigning a literal zero Permissions granted = 0; -#endif +# endif if (cache) { - QHash<Channel *, Permissions> *h = cache->value(p); + QHash< Channel *, Permissions > *h = cache->value(p); if (h) granted = h->value(chan); } @@ -122,7 +124,7 @@ QFlags<ChanACL::Perm> ChanACL::effectivePermissions(ServerUser *p, Channel *chan return granted; } - QStack<Channel *> chanstack; + QStack< Channel * > chanstack; Channel *ch = chan; while (ch) { @@ -136,16 +138,16 @@ QFlags<ChanACL::Perm> ChanACL::effectivePermissions(ServerUser *p, Channel *chan granted = def; bool traverse = true; - bool write = false; + bool write = false; ChanACL *acl; - while (! chanstack.isEmpty()) { + while (!chanstack.isEmpty()) { ch = chanstack.pop(); - if (! ch->bInheritACL) + if (!ch->bInheritACL) granted = def; - foreach(acl, ch->qlACL) { - bool matchUser = (acl->iUserId != -1) && (acl->iUserId == p->iId); + foreach (acl, ch->qlACL) { + bool matchUser = (acl->iUserId != -1) && (acl->iUserId == p->iId); bool matchGroup = Group::isMember(chan, ch, acl->qsGroup, p); if (matchUser || matchGroup) { if (acl->pAllow & Traverse) @@ -168,27 +170,28 @@ QFlags<ChanACL::Perm> ChanACL::effectivePermissions(ServerUser *p, Channel *chan if (acl->pAllow & SelfRegister) granted |= SelfRegister; } - if ((ch==chan && acl->bApplyHere) || (ch!=chan && acl->bApplySubs)) { - granted |= (acl->pAllow & ~(Kick|Ban|ResetUserContent|Register|SelfRegister|Cached)); + if ((ch == chan && acl->bApplyHere) || (ch != chan && acl->bApplySubs)) { + granted |= (acl->pAllow & ~(Kick | Ban | ResetUserContent | Register | SelfRegister | Cached)); granted &= ~acl->pDeny; } } } - if (! traverse && ! write) { + if (!traverse && !write) { granted = None; break; } } if (granted & Write) { - granted |= Traverse|Enter|MuteDeafen|Move|MakeChannel|LinkChannel|TextMessage|MakeTempChannel|Listen; + granted |= + Traverse | Enter | MuteDeafen | Move | MakeChannel | LinkChannel | TextMessage | MakeTempChannel | Listen; if (chan->iId == 0) - granted |= Kick|Ban|ResetUserContent|Register|SelfRegister; + granted |= Kick | Ban | ResetUserContent | Register | SelfRegister; } if (cache) { - if (! cache->contains(p)) - cache->insert(p, new QHash<Channel *, Permissions>); + if (!cache->contains(p)) + cache->insert(p, new QHash< Channel *, Permissions >); cache->value(p)->insert(chan, granted | Cached); } @@ -203,41 +206,56 @@ QString ChanACL::whatsThis(Perm p) { case None: return tr("This represents no privileges."); case Write: - return tr("This represents total access to the channel, including the ability to change group and ACL information. " - "This privilege implies all other privileges."); + return tr("This represents total access to the channel, including the ability to change group and ACL " + "information. " + "This privilege implies all other privileges."); case Traverse: - return tr("This represents the permission to traverse the channel. If a user is denied this privilege, he will be " - "unable to access this channel and any sub-channels in any way, regardless of other permissions in the " - "sub-channels."); + return tr( + "This represents the permission to traverse the channel. If a user is denied this privilege, he will " + "be " + "unable to access this channel and any sub-channels in any way, regardless of other permissions in the " + "sub-channels."); case Enter: - return tr("This represents the permission to join the channel. If you have a hierarchical channel structure, you " - "might want to give everyone Traverse, but restrict Enter in the root of your hierarchy."); + return tr( + "This represents the permission to join the channel. If you have a hierarchical channel structure, you " + "might want to give everyone Traverse, but restrict Enter in the root of your hierarchy."); case Speak: - return tr("This represents the permission to speak in a channel. Users without this privilege will be suppressed by " - "the server (seen as muted), and will be unable to speak until they are unmuted by someone with the " - "appropriate privileges."); + return tr( + "This represents the permission to speak in a channel. Users without this privilege will be suppressed " + "by " + "the server (seen as muted), and will be unable to speak until they are unmuted by someone with the " + "appropriate privileges."); case Whisper: - return tr("This represents the permission to whisper to this channel from the outside. This works exactly like the <i>speak</i> " - "privilege, but applies to packets spoken with the Whisper key held down. This may be used to broadcast to a hierarchy " - "of channels without linking."); + return tr("This represents the permission to whisper to this channel from the outside. This works exactly " + "like the <i>speak</i> " + "privilege, but applies to packets spoken with the Whisper key held down. This may be used to " + "broadcast to a hierarchy " + "of channels without linking."); case MuteDeafen: - return tr("This represents the permission to mute and deafen other users. Once muted, a user will stay muted " - "until he is unmuted by another privileged user or reconnects to the server."); + return tr( + "This represents the permission to mute and deafen other users. Once muted, a user will stay muted " + "until he is unmuted by another privileged user or reconnects to the server."); case Move: - return tr("This represents the permission to move a user to another channel or kick him from the server. To actually " - "move the user, either the moving user must have Move privileges in the destination channel, or " - "the user must normally be allowed to enter the channel. Users with this privilege can move users " - "into channels the target user normally wouldn't have permission to enter."); + return tr( + "This represents the permission to move a user to another channel or kick him from the server. To " + "actually " + "move the user, either the moving user must have Move privileges in the destination channel, or " + "the user must normally be allowed to enter the channel. Users with this privilege can move users " + "into channels the target user normally wouldn't have permission to enter."); case MakeChannel: - return tr("This represents the permission to make sub-channels. The user making the sub-channel will be added to the " - "admin group of the sub-channel."); + return tr("This represents the permission to make sub-channels. The user making the sub-channel will be " + "added to the " + "admin group of the sub-channel."); case MakeTempChannel: - return tr("This represents the permission to make a temporary subchannel. The user making the sub-channel will be added to the " - "admin group of the sub-channel. Temporary channels are not stored and disappear when the last user leaves."); + return tr("This represents the permission to make a temporary subchannel. The user making the sub-channel " + "will be added to the " + "admin group of the sub-channel. Temporary channels are not stored and disappear when the last " + "user leaves."); case LinkChannel: - return tr("This represents the permission to link channels. Users in linked channels hear each other, as long as " - "the speaking user has the <i>speak</i> privilege in the channel of the listener. You need the link " - "privilege in both channels to create a link, but just in either channel to remove it."); + return tr( + "This represents the permission to link channels. Users in linked channels hear each other, as long as " + "the speaking user has the <i>speak</i> privilege in the channel of the listener. You need the link " + "privilege in both channels to create a link, but just in either channel to remove it."); case TextMessage: return tr("This represents the permission to write text messages to other users in this channel."); case Kick: @@ -251,7 +269,8 @@ QString ChanACL::whatsThis(Perm p) { case SelfRegister: return tr("This represents the permission to register oneself on the server."); case Listen: - return tr("This represents the permission to use the listen-feature allowing to listen to a channel without being in it."); + return tr("This represents the permission to use the listen-feature allowing to listen to a channel " + "without being in it."); default: break; } @@ -260,11 +279,11 @@ QString ChanACL::whatsThis(Perm p) { #endif -QString ChanACL::permName(QFlags<Perm> p) { +QString ChanACL::permName(QFlags< Perm > p) { QStringList qsl; - for (int i=0;i<=31;++i) { - if (p & (1<<i)) - qsl << permName(static_cast<Perm>(1<<i)); + for (int i = 0; i <= 31; ++i) { + if (p & (1 << i)) + qsl << permName(static_cast< Perm >(1 << i)); } return qsl.join(QLatin1String(", ")); } @@ -319,11 +338,13 @@ bool ChanACL::isPassword() const { // AND grants 'Speak', 'Whisper', 'TextMessage', 'LinkChannel' and potentially Traverse but NOTHING else // AND does not deny anything. // Furthermore the ACL must apply directly to the channel and may not be inherited. - return this->qsGroup.startsWith(QLatin1Char('#')) - && this->bApplyHere - && !this->bInherited - && (this->pAllow & ChanACL::Enter) - && (this->pAllow == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel) || // Backwards compat with old behaviour that didn't deny traverse - this->pAllow == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel | ChanACL::Traverse)) - && this->pDeny == ChanACL::None; + return this->qsGroup.startsWith(QLatin1Char('#')) && this->bApplyHere && !this->bInherited + && (this->pAllow & ChanACL::Enter) + && (this->pAllow + == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel) + || // Backwards compat with old behaviour that didn't deny traverse + this->pAllow + == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel + | ChanACL::Traverse)) + && this->pDeny == ChanACL::None; } @@ -14,71 +14,70 @@ class User; class ServerUser; class ChanACL : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(ChanACL) - public: - enum Perm { - None = 0x0, - Write = 0x1, - Traverse = 0x2, - Enter = 0x4, - Speak = 0x8, - MuteDeafen = 0x10, - Move = 0x20, - MakeChannel = 0x40, - LinkChannel = 0x80, - Whisper = 0x100, - TextMessage = 0x200, - MakeTempChannel = 0x400, - Listen = 0x800, - - // Root channel only - Kick = 0x10000, - Ban = 0x20000, - Register = 0x40000, - SelfRegister = 0x80000, - ResetUserContent = 0x100000, - - Cached = 0x8000000, - All = Write + Traverse + Enter + Speak + MuteDeafen + Move - + MakeChannel + LinkChannel + Whisper + TextMessage + MakeTempChannel + Listen - + Kick + Ban + Register + SelfRegister + ResetUserContent - }; - - Q_DECLARE_FLAGS(Permissions, Perm) - - typedef QHash<Channel *, Permissions> ChanCache; - typedef QHash<User *, ChanCache * > ACLCache; - - Channel *c; - bool bApplyHere; - bool bApplySubs; - - bool bInherited; - - int iUserId; - QString qsGroup; - Permissions pAllow; - Permissions pDeny; - - ChanACL(Channel *c); - - /// @returns Whether the given ChanACL represents a password. - bool isPassword() const; - - /// @ereturns A string representation of this ChanACL summarizing what permissions are granted or denied. - /// If this ACL neither grants nor denies any permissions, an empty String is returned. - explicit operator QString() const; +private: + Q_OBJECT + Q_DISABLE_COPY(ChanACL) +public: + enum Perm { + None = 0x0, + Write = 0x1, + Traverse = 0x2, + Enter = 0x4, + Speak = 0x8, + MuteDeafen = 0x10, + Move = 0x20, + MakeChannel = 0x40, + LinkChannel = 0x80, + Whisper = 0x100, + TextMessage = 0x200, + MakeTempChannel = 0x400, + Listen = 0x800, + + // Root channel only + Kick = 0x10000, + Ban = 0x20000, + Register = 0x40000, + SelfRegister = 0x80000, + ResetUserContent = 0x100000, + + Cached = 0x8000000, + All = Write + Traverse + Enter + Speak + MuteDeafen + Move + MakeChannel + LinkChannel + Whisper + TextMessage + + MakeTempChannel + Listen + Kick + Ban + Register + SelfRegister + ResetUserContent + }; + + Q_DECLARE_FLAGS(Permissions, Perm) + + typedef QHash< Channel *, Permissions > ChanCache; + typedef QHash< User *, ChanCache * > ACLCache; + + Channel *c; + bool bApplyHere; + bool bApplySubs; + + bool bInherited; + + int iUserId; + QString qsGroup; + Permissions pAllow; + Permissions pDeny; + + ChanACL(Channel *c); + + /// @returns Whether the given ChanACL represents a password. + bool isPassword() const; + + /// @ereturns A string representation of this ChanACL summarizing what permissions are granted or denied. + /// If this ACL neither grants nor denies any permissions, an empty String is returned. + explicit operator QString() const; #ifdef MURMUR - static bool hasPermission(ServerUser *p, Channel *c, QFlags<Perm> perm, ACLCache *cache); - static QFlags<Perm> effectivePermissions(ServerUser *p, Channel *c, ACLCache *cache); + static bool hasPermission(ServerUser *p, Channel *c, QFlags< Perm > perm, ACLCache *cache); + static QFlags< Perm > effectivePermissions(ServerUser *p, Channel *c, ACLCache *cache); #else - static QString whatsThis(Perm p); + static QString whatsThis(Perm p); #endif - static QString permName(QFlags<Perm> p); - static QString permName(Perm p); + static QString permName(QFlags< Perm > p); + static QString permName(Perm p); }; Q_DECLARE_OPERATORS_FOR_FLAGS(ChanACL::Permissions) diff --git a/src/Ban.cpp b/src/Ban.cpp index a9478421f..3681dceeb 100644 --- a/src/Ban.cpp +++ b/src/Ban.cpp @@ -6,10 +6,10 @@ #include "Ban.h" bool Ban::isExpired() const { - return (iDuration > 0) && static_cast<int>(iDuration - qdtStart.secsTo(QDateTime::currentDateTime().toUTC())) < 0; + return (iDuration > 0) && static_cast< int >(iDuration - qdtStart.secsTo(QDateTime::currentDateTime().toUTC())) < 0; } -bool Ban::operator <(const Ban &other) const { +bool Ban::operator<(const Ban &other) const { // Compare username primarily and address secondarily const int unameDifference = qsUsername.localeAwareCompare(other.qsUsername); if (unameDifference == 0) @@ -18,14 +18,10 @@ bool Ban::operator <(const Ban &other) const { return unameDifference < 0; } -bool Ban::operator ==(const Ban &other) const { - return (haAddress == other.haAddress) - && (iMask == other.iMask) - && (qsUsername == other.qsUsername) - && (qsHash == other.qsHash) - && (qsReason == other.qsReason) - && (qdtStart == other.qdtStart) - && (iDuration == other.iDuration); +bool Ban::operator==(const Ban &other) const { + return (haAddress == other.haAddress) && (iMask == other.iMask) && (qsUsername == other.qsUsername) + && (qsHash == other.qsHash) && (qsReason == other.qsReason) && (qdtStart == other.qdtStart) + && (iDuration == other.iDuration); } bool Ban::isValid() const { @@ -33,16 +29,12 @@ bool Ban::isValid() const { } QString Ban::toString() const { - return QString(QLatin1String("Hash: \"%1\", Host: \"%2\", Mask: \"%3\", Username: \"%4\", Reason: \"%5\", BanStart: \"%6\", BanEnd: \"%7\" %8")).arg( - qsHash, - haAddress.toString(), - haAddress.isV6() ? QString::number(iMask) : QString::number(iMask-96), - qsUsername, - qsReason, - qdtStart.toLocalTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), - qdtStart.toLocalTime().addSecs(iDuration).toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), - iDuration == 0 ? QLatin1String("(permanent)") : QLatin1String("(temporary)") - ); + return QString(QLatin1String("Hash: \"%1\", Host: \"%2\", Mask: \"%3\", Username: \"%4\", Reason: \"%5\", " + "BanStart: \"%6\", BanEnd: \"%7\" %8")) + .arg(qsHash, haAddress.toString(), haAddress.isV6() ? QString::number(iMask) : QString::number(iMask - 96), + qsUsername, qsReason, qdtStart.toLocalTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), + qdtStart.toLocalTime().addSecs(iDuration).toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), + iDuration == 0 ? QLatin1String("(permanent)") : QLatin1String("(temporary)")); } quint32 qHash(const Ban &b) { @@ -8,9 +8,9 @@ #include "HostAddress.h" -#include <QtCore/QtGlobal> -#include <QtCore/QString> #include <QtCore/QDateTime> +#include <QtCore/QString> +#include <QtCore/QtGlobal> #include <QtNetwork/QHostAddress> #include <QtNetwork/Q_IPV6ADDR> @@ -24,8 +24,8 @@ struct Ban { unsigned int iDuration; bool isExpired() const; bool isValid() const; - bool operator < (const Ban &) const; - bool operator == (const Ban &) const; + bool operator<(const Ban &) const; + bool operator==(const Ban &) const; QString toString() const; }; diff --git a/src/ByteSwap.h b/src/ByteSwap.h index 532978b68..24e00b2d2 100644 --- a/src/ByteSwap.h +++ b/src/ByteSwap.h @@ -9,14 +9,14 @@ #include <QtCore/QtGlobal> #if Q_BYTE_ORDER == Q_BIG_ENDIAN -# define SWAP64(x) (x) +# define SWAP64(x) (x) #else -# if defined(__x86_64__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) -# define SWAP64(x) __builtin_bswap64(x) -# else -# include <QtCore/QtEndian> -# define SWAP64(x) qbswap<quint64>(x) -# endif +# if defined(__x86_64__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +# define SWAP64(x) __builtin_bswap64(x) +# else +# include <QtCore/QtEndian> +# define SWAP64(x) qbswap< quint64 >(x) +# endif #endif #endif diff --git a/src/Channel.cpp b/src/Channel.cpp index 81559257b..934f1710f 100644 --- a/src/Channel.cpp +++ b/src/Channel.cpp @@ -4,30 +4,30 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "Channel.h" -#include "User.h" -#include "Group.h" #include "ACL.h" +#include "Group.h" +#include "User.h" #include <QtCore/QStack> #ifdef MUMBLE -QHash<int, Channel *> Channel::c_qhChannels; +QHash< int, Channel * > Channel::c_qhChannels; QReadWriteLock Channel::c_qrwlChannels; #endif Channel::Channel(int id, const QString &name, QObject *p) : QObject(p) { - iId = id; - iPosition = 0; - qsName = name; + iId = id; + iPosition = 0; + qsName = name; bInheritACL = true; - uiMaxUsers = 0; - bTemporary = false; - cParent = qobject_cast<Channel *>(p); + uiMaxUsers = 0; + bTemporary = false; + cParent = qobject_cast< Channel * >(p); if (cParent) cParent->addChannel(this); #ifdef MUMBLE uiPermissions = 0; - bFiltered = false; + bFiltered = false; hasEnterRestrictions.store(false); localUserCanEnter.store(true); @@ -38,14 +38,14 @@ Channel::~Channel() { if (cParent) cParent->removeChannel(this); - foreach(Channel *c, qlChannels) + foreach (Channel *c, qlChannels) delete c; - foreach(ChanACL *acl, qlACL) + foreach (ChanACL *acl, qlACL) delete acl; - foreach(Group *g, qhGroups) + foreach (Group *g, qhGroups) delete g; - foreach(Channel *l, qhLinks.keys()) + foreach (Channel *l, qhLinks.keys()) unlink(l); Q_ASSERT(qlChannels.count() == 0); @@ -102,24 +102,24 @@ void Channel::unlink(Channel *l) { l->qsPermLinks.remove(this); l->qhLinks.remove(this); } else { - foreach(Channel *c, qhLinks.keys()) + foreach (Channel *c, qhLinks.keys()) unlink(c); } } -QSet<Channel *> Channel::allLinks() { - QSet<Channel *> seen; +QSet< Channel * > Channel::allLinks() { + QSet< Channel * > seen; seen.insert(this); if (qhLinks.isEmpty()) return seen; - QStack<Channel *> stack; + QStack< Channel * > stack; stack.push(this); - while (! stack.isEmpty()) { + while (!stack.isEmpty()) { Channel *lnk = stack.pop(); - foreach(Channel *l, lnk->qhLinks.keys()) { - if (! seen.contains(l)) { + foreach (Channel *l, lnk->qhLinks.keys()) { + if (!seen.contains(l)) { seen.insert(l); stack.push(l); } @@ -128,17 +128,17 @@ QSet<Channel *> Channel::allLinks() { return seen; } -QSet<Channel *> Channel::allChildren() { - QSet<Channel *> seen; - if (! qlChannels.isEmpty()) { - QStack<Channel *> stack; +QSet< Channel * > Channel::allChildren() { + QSet< Channel * > seen; + if (!qlChannels.isEmpty()) { + QStack< Channel * > stack; stack.push(this); - while (! stack.isEmpty()) { + while (!stack.isEmpty()) { Channel *c = stack.pop(); - foreach(Channel *chld, c->qlChannels) { + foreach (Channel *chld, c->qlChannels) { seen.insert(chld); - if (! chld->qlChannels.isEmpty()) + if (!chld->qlChannels.isEmpty()) stack.append(chld); } } @@ -170,10 +170,9 @@ void Channel::removeUser(User *p) { } Channel::operator QString() const { - return QString::fromLatin1("%1[%2:%3%4]").arg(qsName, - QString::number(iId), - QString::number(cParent ? cParent->iId : -1), - bTemporary ? QLatin1String("*") : QLatin1String("")); + return QString::fromLatin1("%1[%2:%3%4]") + .arg(qsName, QString::number(iId), QString::number(cParent ? cParent->iId : -1), + bTemporary ? QLatin1String("*") : QLatin1String("")); } size_t Channel::getLevel() const { @@ -189,14 +188,12 @@ size_t Channel::getLevel() const { } size_t Channel::getDepth() const { - if(qlChannels.empty()) { + if (qlChannels.empty()) { return 0; } size_t result = 0; - foreach(Channel *child, qlChannels) { - result = qMax(result, child->getDepth() + 1); - } + foreach (Channel *child, qlChannels) { result = qMax(result, child->getDepth() + 1); } return result; } diff --git a/src/Channel.h b/src/Channel.h index 1da349e9f..3f0921523 100644 --- a/src/Channel.h +++ b/src/Channel.h @@ -14,7 +14,7 @@ #include <QtCore/QString> #ifdef MUMBLE - #include <atomic> +# include <atomic> #endif class User; @@ -24,80 +24,81 @@ class ChanACL; class ClientUser; class Channel : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(Channel) - private: - QSet<Channel *> qsUnseen; - public: - int iId; - int iPosition; - bool bTemporary; - Channel *cParent; - QString qsName; - QString qsDesc; - QByteArray qbaDescHash; - QList<Channel *> qlChannels; - QList<User *> qlUsers; - QHash<QString, Group *> qhGroups; - QList<ChanACL *> qlACL; +private: + Q_OBJECT + Q_DISABLE_COPY(Channel) +private: + QSet< Channel * > qsUnseen; + +public: + int iId; + int iPosition; + bool bTemporary; + Channel *cParent; + QString qsName; + QString qsDesc; + QByteArray qbaDescHash; + QList< Channel * > qlChannels; + QList< User * > qlUsers; + QHash< QString, Group * > qhGroups; + QList< ChanACL * > qlACL; #ifdef MUMBLE - /// A flag indicating whether this channel has enter restrictions (ACL denying ENTER) in place - std::atomic<bool> hasEnterRestrictions; - /// A flag indicating whether the local user is currently able to enter this channel. In theory this should - /// represent the correct access state (apart from the time it takes to synchronize ACL changes from the server - /// to the client), but in the end, it's the server who decides whether the user can enter. This flag is only - /// meant for UI purposes and should not be used influence actual behaviour. - std::atomic<bool> localUserCanEnter; + /// A flag indicating whether this channel has enter restrictions (ACL denying ENTER) in place + std::atomic< bool > hasEnterRestrictions; + /// A flag indicating whether the local user is currently able to enter this channel. In theory this should + /// represent the correct access state (apart from the time it takes to synchronize ACL changes from the server + /// to the client), but in the end, it's the server who decides whether the user can enter. This flag is only + /// meant for UI purposes and should not be used influence actual behaviour. + std::atomic< bool > localUserCanEnter; #endif - QSet<Channel *> qsPermLinks; - QHash<Channel *, int> qhLinks; + QSet< Channel * > qsPermLinks; + QHash< Channel *, int > qhLinks; - bool bInheritACL; + bool bInheritACL; - /// Maximum number of users allowed in the channel. If this - /// value is zero, the maximum number of users allowed in the - /// channel is given by the server's "usersperchannel" - /// setting. - unsigned int uiMaxUsers; + /// Maximum number of users allowed in the channel. If this + /// value is zero, the maximum number of users allowed in the + /// channel is given by the server's "usersperchannel" + /// setting. + unsigned int uiMaxUsers; - Channel(int id, const QString &name, QObject *p = nullptr); - ~Channel(); + Channel(int id, const QString &name, QObject *p = nullptr); + ~Channel(); #ifdef MUMBLE - unsigned int uiPermissions; - bool bFiltered; + unsigned int uiPermissions; + bool bFiltered; - static QHash<int, Channel *> c_qhChannels; - static QReadWriteLock c_qrwlChannels; + static QHash< int, Channel * > c_qhChannels; + static QReadWriteLock c_qrwlChannels; - static Channel *get(int); - static Channel *add(int, const QString &); - static void remove(Channel *); + static Channel *get(int); + static Channel *add(int, const QString &); + static void remove(Channel *); - void addClientUser(ClientUser *p); + void addClientUser(ClientUser *p); #endif - static bool lessThan(const Channel *, const Channel *); + static bool lessThan(const Channel *, const Channel *); - size_t getLevel() const; - size_t getDepth() const; - QString getPath() const; + size_t getLevel() const; + size_t getDepth() const; + QString getPath() const; - void addChannel(Channel *c); - void removeChannel(Channel *c); - void addUser(User *p); - void removeUser(User *p); + void addChannel(Channel *c); + void removeChannel(Channel *c); + void addUser(User *p); + void removeUser(User *p); - bool isLinked(Channel *c) const; - void link(Channel *c); - void unlink(Channel *c = nullptr); + bool isLinked(Channel *c) const; + void link(Channel *c); + void unlink(Channel *c = nullptr); - QSet<Channel *> allLinks(); - QSet<Channel *> allChildren(); + QSet< Channel * > allLinks(); + QSet< Channel * > allChildren(); - operator QString() const; + operator QString() const; }; #endif diff --git a/src/ChannelListener.cpp b/src/ChannelListener.cpp index d0e86a087..b20f8a55f 100644 --- a/src/ChannelListener.cpp +++ b/src/ChannelListener.cpp @@ -8,8 +8,8 @@ #include "User.h" #ifdef MUMBLE - #include "ServerHandler.h" - #include "Database.h" +# include "ServerHandler.h" +# include "Database.h" #endif #include <QtCore/QReadLocker> @@ -17,24 +17,22 @@ #ifdef MUMBLE - // We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. - #include "Global.h" +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. +# include "Global.h" #endif // init static instance ChannelListener ChannelListener::s_instance; ChannelListener::ChannelListener() - : QObject(nullptr), - m_listenerLock(), - m_listeningUsers(), - m_listenedChannels() + : QObject(nullptr), m_listenerLock(), m_listeningUsers(), m_listenedChannels() #ifdef MUMBLE - , m_volumeLock() - , m_listenerVolumeAdjustments() - , m_initialSyncDone(false) + , + m_volumeLock(), m_listenerVolumeAdjustments(), m_initialSyncDone(false) #endif -{} +{ +} void ChannelListener::addListenerImpl(unsigned int userSession, int channelID) { QWriteLocker lock(&m_listenerLock); @@ -68,13 +66,13 @@ bool ChannelListener::isListenedByAnyImpl(int channelID) const { return !m_listenedChannels[channelID].isEmpty(); } -const QSet<unsigned int> ChannelListener::getListenersForChannelImpl(int channelID) const { +const QSet< unsigned int > ChannelListener::getListenersForChannelImpl(int channelID) const { QReadLocker lock(&m_listenerLock); return m_listenedChannels[channelID]; } -const QSet<int> ChannelListener::getListenedChannelsForUserImpl(unsigned int userSession) const { +const QSet< int > ChannelListener::getListenedChannelsForUserImpl(unsigned int userSession) const { QReadLocker lock(&m_listenerLock); return m_listeningUsers[userSession]; @@ -102,7 +100,7 @@ void ChannelListener::setListenerLocalVolumeAdjustmentImpl(int channelID, float m_listenerVolumeAdjustments.insert(channelID, volumeAdjustment); } - if (oldValue != volumeAdjustment) { + if (oldValue != volumeAdjustment) { emit localVolumeAdjustmentsChanged(channelID, volumeAdjustment, oldValue); } } @@ -113,15 +111,15 @@ float ChannelListener::getListenerLocalVolumeAdjustmentImpl(int channelID) const return m_listenerVolumeAdjustments.value(channelID, 1.0f); } -QHash<int, float> ChannelListener::getAllListenerLocalVolumeAdjustmentsImpl(bool filter) const { +QHash< int, float > ChannelListener::getAllListenerLocalVolumeAdjustmentsImpl(bool filter) const { QReadLocker lock(&m_volumeLock); if (!filter) { return m_listenerVolumeAdjustments; } else { - QHash<int, float> volumeMap; + QHash< int, float > volumeMap; - QHashIterator<int, float> it(m_listenerVolumeAdjustments); + QHashIterator< int, float > it(m_listenerVolumeAdjustments); while (it.hasNext()) { it.next(); @@ -140,22 +138,20 @@ void ChannelListener::setInitialServerSyncDoneImpl(bool done) { } #endif -void ChannelListener::clearImpl() { - { - QWriteLocker lock(&m_listenerLock); - m_listeningUsers.clear(); - m_listenedChannels.clear(); - } +void ChannelListener::clearImpl(){ { QWriteLocker lock(&m_listenerLock); +m_listeningUsers.clear(); +m_listenedChannels.clear(); +} #ifdef MUMBLE - { - QWriteLocker lock(&m_volumeLock); - m_listenerVolumeAdjustments.clear(); - } +{ + QWriteLocker lock(&m_volumeLock); + m_listenerVolumeAdjustments.clear(); +} #endif } -ChannelListener& ChannelListener::get() { +ChannelListener &ChannelListener::get() { return s_instance; } @@ -200,19 +196,19 @@ bool ChannelListener::isListenedByAny(const Channel *channel) { return get().isListenedByAnyImpl(channel->iId); } -const QSet<unsigned int> ChannelListener::getListenersForChannel(int channelID) { +const QSet< unsigned int > ChannelListener::getListenersForChannel(int channelID) { return get().getListenersForChannelImpl(channelID); } -const QSet<unsigned int> ChannelListener::getListenersForChannel(const Channel *channel) { +const QSet< unsigned int > ChannelListener::getListenersForChannel(const Channel *channel) { return get().getListenersForChannelImpl(channel->iId); } -const QSet<int> ChannelListener::getListenedChannelsForUser(unsigned int userSession) { +const QSet< int > ChannelListener::getListenedChannelsForUser(unsigned int userSession) { return get().getListenedChannelsForUserImpl(userSession); } -const QSet<int> ChannelListener::getListenedChannelsForUser(const User *user) { +const QSet< int > ChannelListener::getListenedChannelsForUser(const User *user) { return get().getListenedChannelsForUserImpl(user->uiSession); } @@ -250,7 +246,7 @@ float ChannelListener::getListenerLocalVolumeAdjustment(const Channel *channel) return get().getListenerLocalVolumeAdjustmentImpl(channel->iId); } -QHash<int, float> ChannelListener::getAllListenerLocalVolumeAdjustments(bool filter) { +QHash< int, float > ChannelListener::getAllListenerLocalVolumeAdjustments(bool filter) { return get().getAllListenerLocalVolumeAdjustmentsImpl(filter); } @@ -274,7 +270,8 @@ void ChannelListener::saveToDB() { // Save the currently listened channels g.db->setChannelListeners(g.sh->qbaDigest, ChannelListener::getListenedChannelsForUser(g.uiSession)); // And also the currently set volume adjustments (if they're not set to 1.0) - g.db->setChannelListenerLocalVolumeAdjustments(g.sh->qbaDigest, ChannelListener::getAllListenerLocalVolumeAdjustments(true)); + g.db->setChannelListenerLocalVolumeAdjustments(g.sh->qbaDigest, + ChannelListener::getAllListenerLocalVolumeAdjustments(true)); } #endif diff --git a/src/ChannelListener.h b/src/ChannelListener.h index c112befea..6f8b7192f 100644 --- a/src/ChannelListener.h +++ b/src/ChannelListener.h @@ -6,10 +6,10 @@ #ifndef MUMBLE_CHANNEL_LISTENER_H_ #define MUMBLE_CHANNEL_LISTENER_H_ -#include <QtCore/QObject> #include <QtCore/QHash> -#include <QtCore/QSet> +#include <QtCore/QObject> #include <QtCore/QReadWriteLock> +#include <QtCore/QSet> #include <atomic> @@ -20,235 +20,235 @@ class Channel; /// that allows a user to listen to a channel without being in it. Kinda similar to linked channels /// except that this is something each user can do individually. class ChannelListener : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(ChannelListener) - - protected: - /// A lock for guarding m_listeningUsers as well as m_listenedChannels - mutable QReadWriteLock m_listenerLock; - /// A map between a user's session and a list of IDs of all channels the user is listening to - QHash<unsigned int, QSet<int>> m_listeningUsers; - /// A map between a channel's ID and a list of all user-sessions of users listening to that channel - QHash<int, QSet<unsigned int>> m_listenedChannels; +private: + Q_OBJECT + Q_DISABLE_COPY(ChannelListener) + +protected: + /// A lock for guarding m_listeningUsers as well as m_listenedChannels + mutable QReadWriteLock m_listenerLock; + /// A map between a user's session and a list of IDs of all channels the user is listening to + QHash< unsigned int, QSet< int > > m_listeningUsers; + /// A map between a channel's ID and a list of all user-sessions of users listening to that channel + QHash< int, QSet< unsigned int > > m_listenedChannels; #ifdef MUMBLE - /// A lock for guarding m_listenerVolumeAdjustments - mutable QReadWriteLock m_volumeLock; - /// A map between channel IDs and local volume adjustments to be made for ChannelListeners - /// in that channel - QHash<int, float> m_listenerVolumeAdjustments; - - /// A flag indicating whether the initial synchronization with the server has finished yet - std::atomic<bool> m_initialSyncDone; + /// A lock for guarding m_listenerVolumeAdjustments + mutable QReadWriteLock m_volumeLock; + /// A map between channel IDs and local volume adjustments to be made for ChannelListeners + /// in that channel + QHash< int, float > m_listenerVolumeAdjustments; + + /// A flag indicating whether the initial synchronization with the server has finished yet + std::atomic< bool > m_initialSyncDone; #endif - /// The static ChannelListener instance returned by ChannelListener::get() - static ChannelListener s_instance; + /// The static ChannelListener instance returned by ChannelListener::get() + static ChannelListener s_instance; - /// Constructor - ChannelListener(); + /// Constructor + ChannelListener(); - /// Adds a listener to the channel. - /// - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - void addListenerImpl(unsigned int userSession, int channelID); + /// Adds a listener to the channel. + /// + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + void addListenerImpl(unsigned int userSession, int channelID); - /// Removes a listener from the channel. - /// - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - void removeListenerImpl(unsigned int userSession, int channelID); + /// Removes a listener from the channel. + /// + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + void removeListenerImpl(unsigned int userSession, int channelID); - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - /// @returns Whether the given user is listening to the given channel - bool isListeningImpl(unsigned int userSession, int channelID) const; + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + /// @returns Whether the given user is listening to the given channel + bool isListeningImpl(unsigned int userSession, int channelID) const; - /// @param userSession The session ID of the user - /// @returns Whether this user is listening to any channel via the ChannelListener feature - bool isListeningToAnyImpl(unsigned int userSession) const; + /// @param userSession The session ID of the user + /// @returns Whether this user is listening to any channel via the ChannelListener feature + bool isListeningToAnyImpl(unsigned int userSession) const; - /// @param channelID The ID of the channel - /// @returns Whether any user listens to this channel via the ChannelListener feature - bool isListenedByAnyImpl(int channelID) const; + /// @param channelID The ID of the channel + /// @returns Whether any user listens to this channel via the ChannelListener feature + bool isListenedByAnyImpl(int channelID) const; - /// @param channelID The ID of the channel - /// @returns A set of user sessions of users listening to the given channel - const QSet<unsigned int> getListenersForChannelImpl(int channelID) const; + /// @param channelID The ID of the channel + /// @returns A set of user sessions of users listening to the given channel + const QSet< unsigned int > getListenersForChannelImpl(int channelID) const; - /// @param userSession The session ID of the user - /// @returns A set of channel IDs of channels the given user is listening to - const QSet<int> getListenedChannelsForUserImpl(unsigned int userSession) const; + /// @param userSession The session ID of the user + /// @returns A set of channel IDs of channels the given user is listening to + const QSet< int > getListenedChannelsForUserImpl(unsigned int userSession) const; - /// @param channelID The ID of the channel - /// @returns The amount of users that are listening to the given channel - int getListenerCountForChannelImpl(int channelID) const; + /// @param channelID The ID of the channel + /// @returns The amount of users that are listening to the given channel + int getListenerCountForChannelImpl(int channelID) const; - /// @param userSession The session ID of the user - /// @returns The amount of channels the given user is listening to - int getListenedChannelCountForUserImpl(unsigned int userSession) const; + /// @param userSession The session ID of the user + /// @returns The amount of channels the given user is listening to + int getListenedChannelCountForUserImpl(unsigned int userSession) const; #ifdef MUMBLE - /// Sets the local volume adjustment for any channelListener in the given channel. - /// - /// @param channelID The ID of the channel - /// @param volumeAdjustment The volume adjustment to apply - void setListenerLocalVolumeAdjustmentImpl(int channelID, float volumeAdjustment); - - /// @param channelID The ID of the channel - /// @param The local volume adjustment for the given channel. If none has been set, - /// 1.0f is being returned. - float getListenerLocalVolumeAdjustmentImpl(int channelID) const; - - /// @param filter Whether to filter out adjustments of 1 (which have no effect) - /// @returns A map between channel IDs and the currently set volume adjustment - QHash<int, float> getAllListenerLocalVolumeAdjustmentsImpl(bool filter = false) const; - - /// @done Whether the initial synchronization with the server is done yet - void setInitialServerSyncDoneImpl(bool done); + /// Sets the local volume adjustment for any channelListener in the given channel. + /// + /// @param channelID The ID of the channel + /// @param volumeAdjustment The volume adjustment to apply + void setListenerLocalVolumeAdjustmentImpl(int channelID, float volumeAdjustment); + + /// @param channelID The ID of the channel + /// @param The local volume adjustment for the given channel. If none has been set, + /// 1.0f is being returned. + float getListenerLocalVolumeAdjustmentImpl(int channelID) const; + + /// @param filter Whether to filter out adjustments of 1 (which have no effect) + /// @returns A map between channel IDs and the currently set volume adjustment + QHash< int, float > getAllListenerLocalVolumeAdjustmentsImpl(bool filter = false) const; + + /// @done Whether the initial synchronization with the server is done yet + void setInitialServerSyncDoneImpl(bool done); #endif - /// Clears all ChannelListeners and volume adjustments - void clearImpl(); + /// Clears all ChannelListeners and volume adjustments + void clearImpl(); + +public: + /// @returns The static ChannelListener instance + static ChannelListener &get(); + + /// Adds a listener to the channel. + /// + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + static void addListener(unsigned int userSession, int channelID); - public: - /// @returns The static ChannelListener instance - static ChannelListener& get(); + /// Adds a listener to the channel. + /// + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + static void addListener(const User *user, const Channel *channel); - /// Adds a listener to the channel. - /// - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - static void addListener(unsigned int userSession, int channelID); - - /// Adds a listener to the channel. - /// - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - static void addListener(const User *user, const Channel *channel); - - /// Removes a listener from the channel. - /// - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - static void removeListener(unsigned int userSession, int channelID); + /// Removes a listener from the channel. + /// + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + static void removeListener(unsigned int userSession, int channelID); - /// Removes a listener from the channel. - /// - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - static void removeListener(const User *user, const Channel *channel); + /// Removes a listener from the channel. + /// + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + static void removeListener(const User *user, const Channel *channel); - /// @param userSession The session ID of the user - /// @param channelID The ID of the channel - /// @returns Whether the given user is listening to the given channel - static bool isListening(unsigned int userSession, int channelID); + /// @param userSession The session ID of the user + /// @param channelID The ID of the channel + /// @returns Whether the given user is listening to the given channel + static bool isListening(unsigned int userSession, int channelID); - /// @param channel A pointer to the channel object - /// @param user A pointer to the user object - /// @returns Whether the given user is listening to the given channel - static bool isListening(const User *user, const Channel *channel); + /// @param channel A pointer to the channel object + /// @param user A pointer to the user object + /// @returns Whether the given user is listening to the given channel + static bool isListening(const User *user, const Channel *channel); - /// @param userSession The session ID of the user - /// @returns Whether this user is listening to any channel via the ChannelListener feature - static bool isListeningToAny(unsigned int userSession); + /// @param userSession The session ID of the user + /// @returns Whether this user is listening to any channel via the ChannelListener feature + static bool isListeningToAny(unsigned int userSession); - /// @param user A pointer to the user object - /// @returns Whether this user is listening to any channel via the ChannelListener feature - static bool isListeningToAny(const User *user); + /// @param user A pointer to the user object + /// @returns Whether this user is listening to any channel via the ChannelListener feature + static bool isListeningToAny(const User *user); - /// @param channelID The ID of the channel - /// @returns Whether any user listens to this channel via the ChannelListener feature - static bool isListenedByAny(int channelID); + /// @param channelID The ID of the channel + /// @returns Whether any user listens to this channel via the ChannelListener feature + static bool isListenedByAny(int channelID); - /// @param channel A pointer to the channel object - /// @returns Whether any user listens to this channel via the ChannelListener feature - static bool isListenedByAny(const Channel *channel); + /// @param channel A pointer to the channel object + /// @returns Whether any user listens to this channel via the ChannelListener feature + static bool isListenedByAny(const Channel *channel); - /// @param channelID The ID of the channel - /// @returns A set of user sessions of users listening to the given channel - static const QSet<unsigned int> getListenersForChannel(int channelID); + /// @param channelID The ID of the channel + /// @returns A set of user sessions of users listening to the given channel + static const QSet< unsigned int > getListenersForChannel(int channelID); - /// @param channel A pointer to the channel object - /// @returns A set of user sessions of users listening to the given channel - static const QSet<unsigned int> getListenersForChannel(const Channel *channel); + /// @param channel A pointer to the channel object + /// @returns A set of user sessions of users listening to the given channel + static const QSet< unsigned int > getListenersForChannel(const Channel *channel); - /// @param userSession The session ID of the user - /// @returns A set of channel IDs of channels the given user is listening to - static const QSet<int> getListenedChannelsForUser(unsigned int userSession); + /// @param userSession The session ID of the user + /// @returns A set of channel IDs of channels the given user is listening to + static const QSet< int > getListenedChannelsForUser(unsigned int userSession); - /// @param user A pointer to the user object - /// @returns A set of channel IDs of channels the given user is listening to - static const QSet<int> getListenedChannelsForUser(const User *user); + /// @param user A pointer to the user object + /// @returns A set of channel IDs of channels the given user is listening to + static const QSet< int > getListenedChannelsForUser(const User *user); - /// @param channelID The ID of the channel - /// @returns The amount of users that are listening to the given channel - static int getListenerCountForChannel(int channelID); + /// @param channelID The ID of the channel + /// @returns The amount of users that are listening to the given channel + static int getListenerCountForChannel(int channelID); - /// @param channel A pointer to the channel object - /// @returns The amount of users that are listening to the given channel - static int getListenerCountForChannel(const Channel *channel); + /// @param channel A pointer to the channel object + /// @returns The amount of users that are listening to the given channel + static int getListenerCountForChannel(const Channel *channel); - /// @param userSession The session ID of the user - /// @returns The amount of channels the given user is listening to - static int getListenedChannelCountForUser(unsigned int userSession); + /// @param userSession The session ID of the user + /// @returns The amount of channels the given user is listening to + static int getListenedChannelCountForUser(unsigned int userSession); - /// @param user A pointer to the user object - /// @returns The amount of channels the given user is listening to - static int getListenedChannelCountForUser(const User *user); + /// @param user A pointer to the user object + /// @returns The amount of channels the given user is listening to + static int getListenedChannelCountForUser(const User *user); #ifdef MUMBLE - /// Sets the local volume adjustment for any channelListener in the given channel. - /// - /// @param channelID The ID of the channel - /// @param volumeAdjustment The volume adjustment to apply - static void setListenerLocalVolumeAdjustment(int channelID, float volumeAdjustment); - - /// Sets the local volume adjustment for any channelListener in the given channel. - /// - /// @param channel A pointer to the channel object - /// @param volumeAdjustment The volume adjustment to apply - static void setListenerLocalVolumeAdjustment(const Channel *channel, float volumeAdjustment); - - - /// @param channelID The ID of the channel - /// @param The local volume adjustment for the given channel. If none has been set, - /// 1.0f is being returned. - static float getListenerLocalVolumeAdjustment(int channelID); - - /// @param channel A pointer to the channel object - /// @param The local volume adjustment for the given channel. If none has been set, - /// 1.0f is being returned. - static float getListenerLocalVolumeAdjustment(const Channel *channel); - - /// @param filter Whether to filter out adjustments of 1 (which have no effect) - /// @returns A map between channel IDs and the currently set volume adjustment - static QHash<int, float> getAllListenerLocalVolumeAdjustments(bool filter = false); - - /// @done Whether the initial synchronization with the server is done yet - static void setInitialServerSyncDone(bool done); - - /// Saves the current ChannelListener state to the database. - /// NOTE: This function may only be called from the main thread! - static void saveToDB(); + /// Sets the local volume adjustment for any channelListener in the given channel. + /// + /// @param channelID The ID of the channel + /// @param volumeAdjustment The volume adjustment to apply + static void setListenerLocalVolumeAdjustment(int channelID, float volumeAdjustment); + + /// Sets the local volume adjustment for any channelListener in the given channel. + /// + /// @param channel A pointer to the channel object + /// @param volumeAdjustment The volume adjustment to apply + static void setListenerLocalVolumeAdjustment(const Channel *channel, float volumeAdjustment); + + + /// @param channelID The ID of the channel + /// @param The local volume adjustment for the given channel. If none has been set, + /// 1.0f is being returned. + static float getListenerLocalVolumeAdjustment(int channelID); + + /// @param channel A pointer to the channel object + /// @param The local volume adjustment for the given channel. If none has been set, + /// 1.0f is being returned. + static float getListenerLocalVolumeAdjustment(const Channel *channel); + + /// @param filter Whether to filter out adjustments of 1 (which have no effect) + /// @returns A map between channel IDs and the currently set volume adjustment + static QHash< int, float > getAllListenerLocalVolumeAdjustments(bool filter = false); + + /// @done Whether the initial synchronization with the server is done yet + static void setInitialServerSyncDone(bool done); + + /// Saves the current ChannelListener state to the database. + /// NOTE: This function may only be called from the main thread! + static void saveToDB(); #endif - /// Clears all ChannelListeners and volume adjustments - static void clear(); + /// Clears all ChannelListeners and volume adjustments + static void clear(); - signals: +signals: #ifdef MUMBLE - void localVolumeAdjustmentsChanged(int channelID, float newAdjustment, float oldAdjustment); + void localVolumeAdjustmentsChanged(int channelID, float newAdjustment, float oldAdjustment); #endif }; diff --git a/src/Connection.cpp b/src/Connection.cpp index 78c465db9..8e0f2d52a 100644 --- a/src/Connection.cpp +++ b/src/Connection.cpp @@ -5,19 +5,19 @@ #include "Connection.h" #include "Message.h" -#include "SSL.h" #include "Mumble.pb.h" +#include "SSL.h" #include <QtCore/QtEndian> #include <QtNetwork/QHostAddress> #ifdef Q_OS_WIN -# include <qos2.h> +# include <qos2.h> #else -# include <sys/socket.h> -# include <sys/types.h> -# include <netinet/in.h> -# include <netinet/tcp.h> +# include <netinet/in.h> +# include <netinet/tcp.h> +# include <sys/socket.h> +# include <sys/types.h> #endif #ifdef Q_OS_WIN @@ -27,36 +27,37 @@ HANDLE Connection::hQoS = nullptr; Connection::Connection(QObject *p, QSslSocket *qtsSock) : QObject(p) { qtsSocket = qtsSock; qtsSocket->setParent(this); - iPacketLength = -1; + iPacketLength = -1; bDisconnectedEmitted = false; - csCrypt = std::make_unique<CryptStateOCB2>(); + csCrypt = std::make_unique< CryptStateOCB2 >(); static bool bDeclared = false; - if (! bDeclared) { + if (!bDeclared) { bDeclared = true; - qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError"); + qRegisterMetaType< QAbstractSocket::SocketError >("QAbstractSocket::SocketError"); } int nodelay = 1; - setsockopt(static_cast<int>(qtsSocket->socketDescriptor()), IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&nodelay), static_cast<socklen_t>(sizeof(nodelay))); + setsockopt(static_cast< int >(qtsSocket->socketDescriptor()), IPPROTO_TCP, TCP_NODELAY, + reinterpret_cast< char * >(&nodelay), static_cast< socklen_t >(sizeof(nodelay))); - connect(qtsSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError))); + connect(qtsSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, + SLOT(socketError(QAbstractSocket::SocketError))); connect(qtsSocket, SIGNAL(encrypted()), this, SIGNAL(encrypted())); connect(qtsSocket, SIGNAL(readyRead()), this, SLOT(socketRead())); connect(qtsSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); - connect(qtsSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(socketSslErrors(const QList<QSslError> &))); + connect(qtsSocket, SIGNAL(sslErrors(const QList< QSslError > &)), this, + SLOT(socketSslErrors(const QList< QSslError > &))); qtLastPacket.restart(); #ifdef Q_OS_WIN dwFlow = 0; #endif - - } Connection::~Connection() { #ifdef Q_OS_WIN if (dwFlow && hQoS) { - if (! QOSRemoveSocketFromFlow(hQoS, 0, dwFlow, 0)) + if (!QOSRemoveSocketFromFlow(hQoS, 0, dwFlow, 0)) qWarning("Connection: Failed to remove flow from QoS"); } #endif @@ -64,28 +65,29 @@ Connection::~Connection() { void Connection::setToS() { #if defined(Q_OS_WIN) - if (dwFlow || ! hQoS) + if (dwFlow || !hQoS) return; dwFlow = 0; - if (! QOSAddSocketToFlow(hQoS, qtsSocket->socketDescriptor(), nullptr, QOSTrafficTypeAudioVideo, QOS_NON_ADAPTIVE_FLOW, reinterpret_cast<PQOS_FLOWID>(&dwFlow))) + if (!QOSAddSocketToFlow(hQoS, qtsSocket->socketDescriptor(), nullptr, QOSTrafficTypeAudioVideo, + QOS_NON_ADAPTIVE_FLOW, reinterpret_cast< PQOS_FLOWID >(&dwFlow))) qWarning("Connection: Failed to add flow to QOS"); #elif defined(Q_OS_UNIX) int val = 0xa0; - if (setsockopt(static_cast<int>(qtsSocket->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) { + if (setsockopt(static_cast< int >(qtsSocket->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) { val = 0x60; - if (setsockopt(static_cast<int>(qtsSocket->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) + if (setsockopt(static_cast< int >(qtsSocket->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) qWarning("Connection: Failed to set TOS for TCP Socket"); } -#if defined(SO_PRIORITY) +# if defined(SO_PRIORITY) socklen_t optlen = sizeof(val); - if (getsockopt(static_cast<int>(qtsSocket->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, &optlen) == 0) { + if (getsockopt(static_cast< int >(qtsSocket->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, &optlen) == 0) { if (val == 0) { val = 6; - setsockopt(static_cast<int>(qtsSocket->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, sizeof(val)); + setsockopt(static_cast< int >(qtsSocket->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, sizeof(val)); } } -#endif +# endif #endif } @@ -118,9 +120,9 @@ void Connection::socketRead() { unsigned char a_ucBuffer[6]; - qtsSocket->read(reinterpret_cast<char *>(a_ucBuffer), 6); - uiType = qFromBigEndian<quint16>(&a_ucBuffer[0]); - iPacketLength = qFromBigEndian<quint32>(&a_ucBuffer[2]); + qtsSocket->read(reinterpret_cast< char * >(a_ucBuffer), 6); + uiType = qFromBigEndian< quint16 >(&a_ucBuffer[0]); + iPacketLength = qFromBigEndian< quint32 >(&a_ucBuffer[2]); iAvailable -= 6; } @@ -134,7 +136,7 @@ void Connection::socketRead() { } QByteArray qbaBuffer = qtsSocket->read(iPacketLength); - iPacketLength = -1; + iPacketLength = -1; iAvailable -= iPacketLength; emit message(uiType, qbaBuffer); @@ -145,7 +147,7 @@ void Connection::socketError(QAbstractSocket::SocketError err) { emit connectionClosed(err, qtsSocket->errorString()); } -void Connection::socketSslErrors(const QList<QSslError> &qlErr) { +void Connection::socketSslErrors(const QList< QSslError > &qlErr) { emit handleSslErrors(qlErr); } @@ -167,9 +169,9 @@ void Connection::messageToNetwork(const ::google::protobuf::Message &msg, unsign if (len > 0x7fffff) return; cache.resize(len + 6); - unsigned char *uc = reinterpret_cast<unsigned char *>(cache.data()); - qToBigEndian<quint16>(static_cast<quint16>(msgType), & uc[0]); - qToBigEndian<quint32>(len, & uc[2]); + unsigned char *uc = reinterpret_cast< unsigned char * >(cache.data()); + qToBigEndian< quint16 >(static_cast< quint16 >(msgType), &uc[0]); + qToBigEndian< quint32 >(len, &uc[2]); msg.SerializeToArray(uc + 6, len); } @@ -183,7 +185,7 @@ void Connection::sendMessage(const ::google::protobuf::Message &msg, unsigned in } void Connection::sendMessage(const QByteArray &qbaMsg) { - if (! qbaMsg.isEmpty()) + if (!qbaMsg.isEmpty()) qtsSocket->write(qbaMsg); } @@ -191,7 +193,7 @@ void Connection::forceFlush() { if (qtsSocket->state() != QAbstractSocket::ConnectedState) return; - if (! qtsSocket->isEncrypted()) + if (!qtsSocket->isEncrypted()) return; qtsSocket->flush(); @@ -225,10 +227,10 @@ quint16 Connection::localPort() const { return qtsSocket->localPort(); } -QList<QSslCertificate> Connection::peerCertificateChain() const { +QList< QSslCertificate > Connection::peerCertificateChain() const { const QSslCertificate cert = qtsSocket->peerCertificate(); if (cert.isNull()) - return QList<QSslCertificate>(); + return QList< QSslCertificate >(); else return qtsSocket->peerCertificateChain() << cert; } @@ -249,7 +251,7 @@ QString Connection::sessionProtocolString() const { #if QT_VERSION >= 0x050400 return MumbleSSL::protocolToString(sessionProtocol()); #else - return QLatin1String("TLS"); // Cannot determine session cipher. We only know it's some TLS variant + return QLatin1String("TLS"); // Cannot determine session cipher. We only know it's some TLS variant #endif } diff --git a/src/Connection.h b/src/Connection.h index 37ba15f0f..600551105 100644 --- a/src/Connection.h +++ b/src/Connection.h @@ -9,7 +9,7 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "crypto/CryptState.h" @@ -23,72 +23,73 @@ #include <memory> #ifdef Q_OS_WIN -# include <ws2tcpip.h> +# include <ws2tcpip.h> #endif namespace google { namespace protobuf { -class Message; -} + class Message; } +} // namespace google class Connection : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(Connection) - protected: - QSslSocket *qtsSocket; - QElapsedTimer qtLastPacket; - unsigned int uiType; - int iPacketLength; +private: + Q_OBJECT + Q_DISABLE_COPY(Connection) +protected: + QSslSocket *qtsSocket; + QElapsedTimer qtLastPacket; + unsigned int uiType; + int iPacketLength; #ifdef Q_OS_WIN - static HANDLE hQoS; - DWORD dwFlow; + static HANDLE hQoS; + DWORD dwFlow; #endif - protected slots: - void socketRead(); - void socketError(QAbstractSocket::SocketError); - void socketDisconnected(); - void socketSslErrors(const QList<QSslError> &errors); - public slots: - void proceedAnyway(); - signals: - void encrypted(); - void connectionClosed(QAbstractSocket::SocketError, const QString &reason); - void message(unsigned int type, const QByteArray &); - void handleSslErrors(const QList<QSslError> &); - public: - Connection(QObject *parent, QSslSocket *qtsSocket); - ~Connection(); - static void messageToNetwork(const ::google::protobuf::Message &msg, unsigned int msgType, QByteArray &cache); - void sendMessage(const ::google::protobuf::Message &msg, unsigned int msgType, QByteArray &cache); - void sendMessage(const QByteArray &qbaMsg); - void disconnectSocket(bool force=false); - void forceFlush(); - qint64 activityTime() const; - void resetActivityTime(); +protected slots: + void socketRead(); + void socketError(QAbstractSocket::SocketError); + void socketDisconnected(); + void socketSslErrors(const QList< QSslError > &errors); +public slots: + void proceedAnyway(); +signals: + void encrypted(); + void connectionClosed(QAbstractSocket::SocketError, const QString &reason); + void message(unsigned int type, const QByteArray &); + void handleSslErrors(const QList< QSslError > &); + +public: + Connection(QObject *parent, QSslSocket *qtsSocket); + ~Connection(); + static void messageToNetwork(const ::google::protobuf::Message &msg, unsigned int msgType, QByteArray &cache); + void sendMessage(const ::google::protobuf::Message &msg, unsigned int msgType, QByteArray &cache); + void sendMessage(const QByteArray &qbaMsg); + void disconnectSocket(bool force = false); + void forceFlush(); + qint64 activityTime() const; + void resetActivityTime(); #ifdef MURMUR - /// qmCrypt locks access to csCrypt. - QMutex qmCrypt; + /// qmCrypt locks access to csCrypt. + QMutex qmCrypt; #endif - std::unique_ptr<CryptState> csCrypt; + std::unique_ptr< CryptState > csCrypt; - QList<QSslCertificate> peerCertificateChain() const; - QSslCipher sessionCipher() const; - QSsl::SslProtocol sessionProtocol() const; - QString sessionProtocolString() const; - QHostAddress peerAddress() const; - quint16 peerPort() const; - /// Look up the local address of this Connection. - QHostAddress localAddress() const; - /// Look up the local port of this Connection. - quint16 localPort() const; - bool bDisconnectedEmitted; + QList< QSslCertificate > peerCertificateChain() const; + QSslCipher sessionCipher() const; + QSsl::SslProtocol sessionProtocol() const; + QString sessionProtocolString() const; + QHostAddress peerAddress() const; + quint16 peerPort() const; + /// Look up the local address of this Connection. + QHostAddress localAddress() const; + /// Look up the local port of this Connection. + quint16 localPort() const; + bool bDisconnectedEmitted; - void setToS(); + void setToS(); #ifdef Q_OS_WIN - static void setQoS(HANDLE hParentQoS); + static void setQoS(HANDLE hParentQoS); #endif }; diff --git a/src/CryptState.h b/src/CryptState.h index acfbe5c74..91d37515b 100644 --- a/src/CryptState.h +++ b/src/CryptState.h @@ -8,47 +8,49 @@ #include <openssl/aes.h> -#define AES_KEY_SIZE_BITS 128 -#define AES_KEY_SIZE_BYTES (AES_KEY_SIZE_BITS/8) +#define AES_KEY_SIZE_BITS 128 +#define AES_KEY_SIZE_BYTES (AES_KEY_SIZE_BITS / 8) #include "Timer.h" class CryptState { - private: - Q_DISABLE_COPY(CryptState) - public: - unsigned char raw_key[AES_KEY_SIZE_BYTES]; - unsigned char encrypt_iv[AES_BLOCK_SIZE]; - unsigned char decrypt_iv[AES_BLOCK_SIZE]; - unsigned char decrypt_history[0x100]; - - unsigned int uiGood; - unsigned int uiLate; - unsigned int uiLost; - unsigned int uiResync; - - unsigned int uiRemoteGood; - unsigned int uiRemoteLate; - unsigned int uiRemoteLost; - unsigned int uiRemoteResync; - - AES_KEY encrypt_key; - AES_KEY decrypt_key; - Timer tLastGood; - Timer tLastRequest; - bool bInit; - CryptState(); - - bool isValid() const; - void genKey(); - void setKey(const unsigned char *rkey, const unsigned char *eiv, const unsigned char *div); - void setDecryptIV(const unsigned char *iv); - - bool ocb_encrypt(const unsigned char *plain, unsigned char *encrypted, unsigned int len, const unsigned char *nonce, unsigned char *tag); - bool ocb_decrypt(const unsigned char *encrypted, unsigned char *plain, unsigned int len, const unsigned char *nonce, unsigned char *tag); - - bool decrypt(const unsigned char *source, unsigned char *dst, unsigned int crypted_length); - bool encrypt(const unsigned char *source, unsigned char *dst, unsigned int plain_length); +private: + Q_DISABLE_COPY(CryptState) +public: + unsigned char raw_key[AES_KEY_SIZE_BYTES]; + unsigned char encrypt_iv[AES_BLOCK_SIZE]; + unsigned char decrypt_iv[AES_BLOCK_SIZE]; + unsigned char decrypt_history[0x100]; + + unsigned int uiGood; + unsigned int uiLate; + unsigned int uiLost; + unsigned int uiResync; + + unsigned int uiRemoteGood; + unsigned int uiRemoteLate; + unsigned int uiRemoteLost; + unsigned int uiRemoteResync; + + AES_KEY encrypt_key; + AES_KEY decrypt_key; + Timer tLastGood; + Timer tLastRequest; + bool bInit; + CryptState(); + + bool isValid() const; + void genKey(); + void setKey(const unsigned char *rkey, const unsigned char *eiv, const unsigned char *div); + void setDecryptIV(const unsigned char *iv); + + bool ocb_encrypt(const unsigned char *plain, unsigned char *encrypted, unsigned int len, const unsigned char *nonce, + unsigned char *tag); + bool ocb_decrypt(const unsigned char *encrypted, unsigned char *plain, unsigned int len, const unsigned char *nonce, + unsigned char *tag); + + bool decrypt(const unsigned char *source, unsigned char *dst, unsigned int crypted_length); + bool encrypt(const unsigned char *source, unsigned char *dst, unsigned int plain_length); }; #endif diff --git a/src/EnvUtils.cpp b/src/EnvUtils.cpp index 7d5ade0fd..b9b720927 100644 --- a/src/EnvUtils.cpp +++ b/src/EnvUtils.cpp @@ -14,7 +14,7 @@ QString EnvUtils::getenv(QString name) { static_assert(sizeof(wchar_t) == sizeof(ushort), "expected 2-byte wchar_t"); - const wchar_t *wname = reinterpret_cast<const wchar_t *>(name.utf16()); + const wchar_t *wname = reinterpret_cast< const wchar_t * >(name.utf16()); // Query the required buffer size (in elements). if (_wgetenv_s(&requiredSize, 0, 0, wname) != 0) { @@ -25,17 +25,17 @@ QString EnvUtils::getenv(QString name) { } // Resize buf to fit the value and put it there. - buf.resize(static_cast<int>(requiredSize * sizeof(wchar_t))); - if (_wgetenv_s(&requiredSize, reinterpret_cast<wchar_t *>(buf.data()), requiredSize, wname) != 0) { + buf.resize(static_cast< int >(requiredSize * sizeof(wchar_t))); + if (_wgetenv_s(&requiredSize, reinterpret_cast< wchar_t * >(buf.data()), requiredSize, wname) != 0) { return QString(); } // Convert the value to QString and return it. - const wchar_t *wbuf = reinterpret_cast<const wchar_t *>(buf.constData()); + const wchar_t *wbuf = reinterpret_cast< const wchar_t * >(buf.constData()); return QString::fromWCharArray(wbuf); #else QByteArray name8bit = name.toLocal8Bit(); - char *val = ::getenv(name8bit.constData()); + char *val = ::getenv(name8bit.constData()); if (!val) { return QString(); } @@ -45,7 +45,9 @@ QString EnvUtils::getenv(QString name) { bool EnvUtils::setenv(QString name, QString value) { #ifdef Q_OS_WIN - return _wputenv_s(reinterpret_cast<const wchar_t *>(name.utf16()), reinterpret_cast<const wchar_t *>(value.utf16())) == 0; + return _wputenv_s(reinterpret_cast< const wchar_t * >(name.utf16()), + reinterpret_cast< const wchar_t * >(value.utf16())) + == 0; #else const int OVERWRITE = 1; return ::setenv(name.toLocal8Bit().constData(), value.toLocal8Bit().constData(), OVERWRITE) == 0; diff --git a/src/FFDHE.h b/src/FFDHE.h index 688d48373..22122f6ef 100644 --- a/src/FFDHE.h +++ b/src/FFDHE.h @@ -12,19 +12,19 @@ class QStringList; /// FFDHE provides access to the Diffie-Hellman parameters from RFC 7919. class FFDHE { - public: - /// NamedGroups returns a list of the supported named - /// groups for PEMForNamedGroup. - static QStringList NamedGroups(); +public: + /// NamedGroups returns a list of the supported named + /// groups for PEMForNamedGroup. + static QStringList NamedGroups(); - /// PEMForNamedGroup returns the PEM-encoded - /// Diffie-Hellman parameters for the RFC 7919 - /// group with the given name, such as "ffdhe2048", - /// "ffdhe4096", etc. - /// - /// Returns an empty byte array if the request - /// could not be fulfilled. - static QByteArray PEMForNamedGroup(QString name); + /// PEMForNamedGroup returns the PEM-encoded + /// Diffie-Hellman parameters for the RFC 7919 + /// group with the given name, such as "ffdhe2048", + /// "ffdhe4096", etc. + /// + /// Returns an empty byte array if the request + /// could not be fulfilled. + static QByteArray PEMForNamedGroup(QString name); }; #endif diff --git a/src/FFDHETable.h b/src/FFDHETable.h index 8300fb81b..517942146 100644 --- a/src/FFDHETable.h +++ b/src/FFDHETable.h @@ -5,87 +5,82 @@ // Automatically generated by "generate-ffdhe.py". DO NOT EDIT BY HAND. -static const char ffdhe2048_pem[] = \ -"-----BEGIN DH PARAMETERS-----\n" -"MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" -"+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" -"87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" -"YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" -"7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" -"ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg==\n" -"-----END DH PARAMETERS-----\n"; +static const char ffdhe2048_pem[] = "-----BEGIN DH PARAMETERS-----\n" + "MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" + "+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" + "87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" + "YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" + "7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" + "ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg==\n" + "-----END DH PARAMETERS-----\n"; -static const char ffdhe3072_pem[] = \ -"-----BEGIN DH PARAMETERS-----\n" -"MIIBiAKCAYEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" -"+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" -"87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" -"YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" -"7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" -"ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" -"7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" -"nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZsYu\n" -"N///////////AgEC\n" -"-----END DH PARAMETERS-----\n"; +static const char ffdhe3072_pem[] = "-----BEGIN DH PARAMETERS-----\n" + "MIIBiAKCAYEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" + "+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" + "87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" + "YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" + "7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" + "ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" + "7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" + "nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZsYu\n" + "N///////////AgEC\n" + "-----END DH PARAMETERS-----\n"; -static const char ffdhe4096_pem[] = \ -"-----BEGIN DH PARAMETERS-----\n" -"MIICCAKCAgEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" -"+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" -"87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" -"YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" -"7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" -"ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" -"7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" -"nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e\n" -"8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx\n" -"iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K\n" -"zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eZV9q//////////8CAQI=\n" -"-----END DH PARAMETERS-----\n"; +static const char ffdhe4096_pem[] = "-----BEGIN DH PARAMETERS-----\n" + "MIICCAKCAgEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" + "+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" + "87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" + "YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" + "7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" + "ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" + "7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" + "nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e\n" + "8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx\n" + "iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K\n" + "zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eZV9q//////////8CAQI=\n" + "-----END DH PARAMETERS-----\n"; -static const char ffdhe6144_pem[] = \ -"-----BEGIN DH PARAMETERS-----\n" -"MIIDCAKCAwEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" -"+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" -"87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" -"YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" -"7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" -"ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" -"7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" -"nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e\n" -"8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx\n" -"iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K\n" -"zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eDdkCC/1ktkUDbHpOZ30sOFMq\n" -"OiO6RELK9T6mO7RUMpt2JMiRe91kscD9TLOOjDNMcBw6za0GV/zP7HGbH1w+TkYE\n" -"HziBR/tM/bR3pSRx96mpaRC4VTIu22NA2KAO8JI1BRHjCr7B//njom5/sp+MGDAj\n" -"w1h+ONoAd9m0dj5OS5Syu8GUxmUed8r5ku6qwCMqKBv2s6c5wSJhFoIK6NtYR6Z8\n" -"vvnJCRtGLVOM1ysDdGrnf15iKSwxFWKoRlBdyC24VDOK5J9SNclbkReMzy3Vys70\n" -"A+ydGBDGJysEWztx+dxrgNY/3UqOmtseaWKmlSbUMWHBpB1XDXk42tSkDjKc0OQO\n" -"Zf//////////AgEC\n" -"-----END DH PARAMETERS-----\n"; +static const char ffdhe6144_pem[] = "-----BEGIN DH PARAMETERS-----\n" + "MIIDCAKCAwEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" + "+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" + "87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" + "YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" + "7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" + "ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" + "7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" + "nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e\n" + "8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx\n" + "iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K\n" + "zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eDdkCC/1ktkUDbHpOZ30sOFMq\n" + "OiO6RELK9T6mO7RUMpt2JMiRe91kscD9TLOOjDNMcBw6za0GV/zP7HGbH1w+TkYE\n" + "HziBR/tM/bR3pSRx96mpaRC4VTIu22NA2KAO8JI1BRHjCr7B//njom5/sp+MGDAj\n" + "w1h+ONoAd9m0dj5OS5Syu8GUxmUed8r5ku6qwCMqKBv2s6c5wSJhFoIK6NtYR6Z8\n" + "vvnJCRtGLVOM1ysDdGrnf15iKSwxFWKoRlBdyC24VDOK5J9SNclbkReMzy3Vys70\n" + "A+ydGBDGJysEWztx+dxrgNY/3UqOmtseaWKmlSbUMWHBpB1XDXk42tSkDjKc0OQO\n" + "Zf//////////AgEC\n" + "-----END DH PARAMETERS-----\n"; -static const char ffdhe8192_pem[] = \ -"-----BEGIN DH PARAMETERS-----\n" -"MIIECAKCBAEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" -"+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" -"87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" -"YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" -"7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" -"ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" -"7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" -"nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e\n" -"8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx\n" -"iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K\n" -"zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eDdkCC/1ktkUDbHpOZ30sOFMq\n" -"OiO6RELK9T6mO7RUMpt2JMiRe91kscD9TLOOjDNMcBw6za0GV/zP7HGbH1w+TkYE\n" -"HziBR/tM/bR3pSRx96mpaRC4VTIu22NA2KAO8JI1BRHjCr7B//njom5/sp+MGDAj\n" -"w1h+ONoAd9m0dj5OS5Syu8GUxmUed8r5ku6qwCMqKBv2s6c5wSJhFoIK6NtYR6Z8\n" -"vvnJCRtGLVOM1ysDdGrnf15iKSwxFWKoRlBdyC24VDOK5J9SNclbkReMzy3Vys70\n" -"A+ydGBDGJysEWztx+dxrgNY/3UqOmtseaWKmlSbUMWHBpB1XDXk42tSkDjKcz/Rq\n" -"qjatAEz2AMg4HkJaMdlRrmT9sj/OyVCdQ2h/62nt0cxeC4zDvfZLEO+GtjFCo6uI\n" -"KVVbL3R8kyZlyywPHMAb1wIpOIg50q8F5FRQSseLdYKCKEbAujXDX1xZFgzARv2C\n" -"UVQfxoychrAiu3CZh2pGDnRRqKkxCXA/7hwhfmw4JuUsUappHg5CPPyZ6eMWUMEh\n" -"e2JIFs2tmpX51bgBlIjZwKCh/jB1pXfiMYP4HUo/L6RXHvyM4LqKT+i2hV3+crCm\n" -"bt7S+6v75Yow+vq+HF1xqH4vdB74wf6G/qa7/eUwZ38Nl9EdSfeoRD0IIuUGqfRh\n" -"TgEeKpSDj/iM1oyLt8XGQkz//////////wIBAg==\n" -"-----END DH PARAMETERS-----\n"; +static const char ffdhe8192_pem[] = "-----BEGIN DH PARAMETERS-----\n" + "MIIECAKCBAEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" + "+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" + "87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" + "YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" + "7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" + "ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n" + "7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\n" + "nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e\n" + "8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx\n" + "iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K\n" + "zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eDdkCC/1ktkUDbHpOZ30sOFMq\n" + "OiO6RELK9T6mO7RUMpt2JMiRe91kscD9TLOOjDNMcBw6za0GV/zP7HGbH1w+TkYE\n" + "HziBR/tM/bR3pSRx96mpaRC4VTIu22NA2KAO8JI1BRHjCr7B//njom5/sp+MGDAj\n" + "w1h+ONoAd9m0dj5OS5Syu8GUxmUed8r5ku6qwCMqKBv2s6c5wSJhFoIK6NtYR6Z8\n" + "vvnJCRtGLVOM1ysDdGrnf15iKSwxFWKoRlBdyC24VDOK5J9SNclbkReMzy3Vys70\n" + "A+ydGBDGJysEWztx+dxrgNY/3UqOmtseaWKmlSbUMWHBpB1XDXk42tSkDjKcz/Rq\n" + "qjatAEz2AMg4HkJaMdlRrmT9sj/OyVCdQ2h/62nt0cxeC4zDvfZLEO+GtjFCo6uI\n" + "KVVbL3R8kyZlyywPHMAb1wIpOIg50q8F5FRQSseLdYKCKEbAujXDX1xZFgzARv2C\n" + "UVQfxoychrAiu3CZh2pGDnRRqKkxCXA/7hwhfmw4JuUsUappHg5CPPyZ6eMWUMEh\n" + "e2JIFs2tmpX51bgBlIjZwKCh/jB1pXfiMYP4HUo/L6RXHvyM4LqKT+i2hV3+crCm\n" + "bt7S+6v75Yow+vq+HF1xqH4vdB74wf6G/qa7/eUwZ38Nl9EdSfeoRD0IIuUGqfRh\n" + "TgEeKpSDj/iM1oyLt8XGQkz//////////wIBAg==\n" + "-----END DH PARAMETERS-----\n"; diff --git a/src/Group.cpp b/src/Group.cpp index c7093cbdb..ea24d0906 100644 --- a/src/Group.cpp +++ b/src/Group.cpp @@ -8,27 +8,27 @@ #include "Channel.h" #include "User.h" #ifdef MURMUR -#include "ServerUser.h" +# include "ServerUser.h" -#include <QtCore/QStack> +# include <QtCore/QStack> #endif const Qt::CaseSensitivity Group::accessTokenCaseSensitivity = Qt::CaseInsensitive; Group::Group(Channel *assoc, const QString &name) { - c = assoc; - bInherit = true; + c = assoc; + bInherit = true; bInheritable = true; - qsName = name; + qsName = name; if (c) c->qhGroups[name] = this; } #ifdef MURMUR -QSet<int> Group::members() { - QStack<Group *> s; - QSet<int> m; +QSet< int > Group::members() { + QStack< Group * > s; + QSet< int > m; Channel *p; Group *g; int i; @@ -37,20 +37,20 @@ QSet<int> Group::members() { while (p) { g = p->qhGroups.value(qsName); if (g) { - if ((p != c) && ! g->bInheritable) + if ((p != c) && !g->bInheritable) break; s.push(g); - if (! g->bInherit) + if (!g->bInherit) break; } p = p->cParent; } - while (! s.isEmpty()) { + while (!s.isEmpty()) { g = s.pop(); - foreach(i, g->qsAdd) + foreach (i, g->qsAdd) m.insert(i); - foreach(i, g->qsRemove) + foreach (i, g->qsRemove) m.remove(i); } @@ -74,9 +74,9 @@ Group *Group::getGroup(Channel *chan, QString name) { return nullptr; } -QSet<QString> Group::groupNames(Channel *chan) { - QStack<Channel *> s; - QSet<QString> m; +QSet< QString > Group::groupNames(Channel *chan) { + QStack< Channel * > s; + QSet< QString > m; Channel *c = chan; Group *g; @@ -85,10 +85,10 @@ QSet<QString> Group::groupNames(Channel *chan) { c = c->cParent; } - while (! s.isEmpty()) { + while (!s.isEmpty()) { c = s.pop(); - foreach(g, c->qhGroups) { - if ((chan != c) && (! g->bInheritable)) + foreach (g, c->qhGroups) { + if ((chan != c) && (!g->bInheritable)) m.remove(g->qsName); else m.insert(g->qsName); @@ -98,19 +98,19 @@ QSet<QString> Group::groupNames(Channel *chan) { return m; } -#define RET_FALSE (invert ? true : false) -#define RET_TRUE (invert ? false : true) +# define RET_FALSE (invert ? true : false) +# define RET_TRUE (invert ? false : true) bool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUser *pl) { Channel *p; Channel *c; Group *g; - bool m = false; + bool m = false; bool invert = false; - bool token = false; - bool hash = false; - c = curChan; + bool token = false; + bool hash = false; + c = curChan; while (true) { if (name.isEmpty()) @@ -118,24 +118,24 @@ bool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUse if (name.startsWith(QChar::fromLatin1('!'))) { invert = true; - name = name.remove(0,1); + name = name.remove(0, 1); continue; } if (name.startsWith(QChar::fromLatin1('~'))) { - c = aclChan; - name = name.remove(0,1); + c = aclChan; + name = name.remove(0, 1); continue; } if (name.startsWith(QChar::fromLatin1('#'))) { token = true; - name = name.remove(0,1); + name = name.remove(0, 1); continue; } if (name.startsWith(QChar::fromLatin1('$'))) { hash = true; - name = name.remove(0,1); + name = name.remove(0, 1); continue; } @@ -158,13 +158,11 @@ bool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUse m = (pl->cChannel == c); else if (name == QLatin1String("out")) m = !(pl->cChannel == c); - else if (name == QLatin1String("sub") - || name.startsWith(QLatin1String("sub,"))) { - - name = name.remove(0,4); - int mindesc = 1; - int maxdesc = 1000; - int minpath = 0; + else if (name == QLatin1String("sub") || name.startsWith(QLatin1String("sub,"))) { + name = name.remove(0, 4); + int mindesc = 1; + int maxdesc = 1000; + int minpath = 0; QStringList args = name.split(QLatin1String(",")); if (args.count() >= 3) { maxdesc = args[2].isEmpty() ? maxdesc : args[2].toInt(); @@ -177,8 +175,8 @@ bool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUse } Channel *home = pl->cChannel; - QList<Channel *> playerChain; - QList<Channel *> groupChain; + QList< Channel * > playerChain; + QList< Channel * > groupChain; p = home; while (p) { @@ -215,7 +213,7 @@ bool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUse m = (pdepth >= mindepth) && (pdepth <= maxdepth); } else { - QStack<Group *> s; + QStack< Group * > s; p = c; @@ -223,19 +221,20 @@ bool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUse g = p->qhGroups.value(name); if (g) { - if ((p != c) && ! g->bInheritable) + if ((p != c) && !g->bInheritable) break; s.push(g); - if (! g->bInherit) + if (!g->bInherit) break; } p = p->cParent; } - while (! s.isEmpty()) { + while (!s.isEmpty()) { g = s.pop(); - if (g->qsAdd.contains(pl->iId) || g->qsTemporary.contains(pl->iId) || g->qsTemporary.contains(- static_cast<int>(pl->uiSession))) + if (g->qsAdd.contains(pl->iId) || g->qsTemporary.contains(pl->iId) + || g->qsTemporary.contains(-static_cast< int >(pl->uiSession))) m = true; if (g->qsRemove.contains(pl->iId)) m = false; diff --git a/src/Group.h b/src/Group.h index 094a5085b..ca95f139e 100644 --- a/src/Group.h +++ b/src/Group.h @@ -13,27 +13,27 @@ class User; class ServerUser; class Group { - private: - Q_DISABLE_COPY(Group) - public: - /// A flag indicating whether access tokens shall be treated case-sensitive or case-insensitive - static const Qt::CaseSensitivity accessTokenCaseSensitivity; - - Channel *c; - QString qsName; - bool bInherit; - bool bInheritable; - QSet<int> qsAdd; - QSet<int> qsRemove; - QSet<int> qsTemporary; - Group(Channel *assoc, const QString &name); +private: + Q_DISABLE_COPY(Group) +public: + /// A flag indicating whether access tokens shall be treated case-sensitive or case-insensitive + static const Qt::CaseSensitivity accessTokenCaseSensitivity; + + Channel *c; + QString qsName; + bool bInherit; + bool bInheritable; + QSet< int > qsAdd; + QSet< int > qsRemove; + QSet< int > qsTemporary; + Group(Channel *assoc, const QString &name); #ifdef MURMUR - QSet<int> members(); - static QSet<QString> groupNames(Channel *c); - static Group *getGroup(Channel *c, QString name); + QSet< int > members(); + static QSet< QString > groupNames(Channel *c); + static Group *getGroup(Channel *c, QString name); - static bool isMember(Channel *c, Channel *aclChan, QString name, ServerUser *); + static bool isMember(Channel *c, Channel *aclChan, QString name, ServerUser *); #endif }; diff --git a/src/HTMLFilter.cpp b/src/HTMLFilter.cpp index f6cb851b6..cb7724a74 100644 --- a/src/HTMLFilter.cpp +++ b/src/HTMLFilter.cpp @@ -22,12 +22,12 @@ QString HTMLFilter::escapeTags(const QString &in) { } bool HTMLFilter::filter(const QString &in, QString &out) { - if (! in.contains(QLatin1Char('<'))) { + if (!in.contains(QLatin1Char('<'))) { out = in.simplified(); } else { QXmlStreamReader qxsr(QString::fromLatin1("<document>%1</document>").arg(in)); QString qs; - while (! qxsr.atEnd()) { + while (!qxsr.atEnd()) { switch (qxsr.readNext()) { case QXmlStreamReader::Invalid: return false; diff --git a/src/HTMLFilter.h b/src/HTMLFilter.h index c0b4b8385..b99237051 100644 --- a/src/HTMLFilter.h +++ b/src/HTMLFilter.h @@ -15,23 +15,24 @@ /// It is used for converting Mumble /// text messages, comments, and more /// to plain text when a server is -/// configured to disallow HTML. +/// configured to disallow HTML. class HTMLFilter { - /// escapeTags returns the in HTML document - /// with all occurrences of > and < - /// replaced by < and >. - static QString escapeTags(const QString &in); - public: - /// filter does a best-effort conversion of the - /// in HTML document to a plain-text representation. - /// - /// If the filtering process succeeded, the function - /// writes the filtered document as plain text to - /// out, and returns true. - /// - /// If the filtering failed, the function returns false - /// and out is left unchanged. - static bool filter(const QString &in, QString &out); + /// escapeTags returns the in HTML document + /// with all occurrences of > and < + /// replaced by < and >. + static QString escapeTags(const QString &in); + +public: + /// filter does a best-effort conversion of the + /// in HTML document to a plain-text representation. + /// + /// If the filtering process succeeded, the function + /// writes the filtered document as plain text to + /// out, and returns true. + /// + /// If the filtering failed, the function returns false + /// and out is left unchanged. + static bool filter(const QString &in, QString &out); }; #endif diff --git a/src/HostAddress.cpp b/src/HostAddress.cpp index 963dbea62..72a635685 100644 --- a/src/HostAddress.cpp +++ b/src/HostAddress.cpp @@ -8,16 +8,16 @@ #include "ByteSwap.h" #ifdef Q_OS_WIN -# include "win.h" -# include <winsock2.h> -# include <ws2tcpip.h> +# include "win.h" +# include <winsock2.h> +# include <ws2tcpip.h> #else -# include <arpa/inet.h> -# if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) -# include <netinet/in.h> -# include <sys/socket.h> -# include <sys/types.h> -# endif +# include <arpa/inet.h> +# if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) +# include <netinet/in.h> +# include <sys/socket.h> +# include <sys/types.h> +# endif #endif HostAddress::HostAddress() { @@ -32,7 +32,7 @@ HostAddress::HostAddress(const std::string &address) { if (address.length() != 16) addr[0] = addr[1] = 0ULL; else - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) qip6[i] = address[i]; } @@ -40,7 +40,7 @@ HostAddress::HostAddress(const QByteArray &address) { if (address.length() != 16) addr[0] = addr[1] = 0ULL; else - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) qip6[i] = address[i]; } @@ -49,33 +49,33 @@ HostAddress::HostAddress(const QHostAddress &address) { const Q_IPV6ADDR &a = address.toIPv6Address(); memcpy(qip6.c, a.c, 16); } else { - addr[0] = 0ULL; + addr[0] = 0ULL; shorts[4] = 0; shorts[5] = 0xffff; - hash[3] = htonl(address.toIPv4Address()); + hash[3] = htonl(address.toIPv4Address()); } } HostAddress::HostAddress(const sockaddr_storage &address) { if (address.ss_family == AF_INET) { - const struct sockaddr_in *in = reinterpret_cast<const struct sockaddr_in *>(&address); - addr[0] = 0ULL; - shorts[4] = 0; - shorts[5] = 0xffff; - hash[3] = in->sin_addr.s_addr; + const struct sockaddr_in *in = reinterpret_cast< const struct sockaddr_in * >(&address); + addr[0] = 0ULL; + shorts[4] = 0; + shorts[5] = 0xffff; + hash[3] = in->sin_addr.s_addr; } else if (address.ss_family == AF_INET6) { - const struct sockaddr_in6 *in6 = reinterpret_cast<const struct sockaddr_in6 *>(&address); + const struct sockaddr_in6 *in6 = reinterpret_cast< const struct sockaddr_in6 * >(&address); memcpy(qip6.c, in6->sin6_addr.s6_addr, 16); } else { addr[0] = addr[1] = 0ULL; } } -bool HostAddress::operator < (const HostAddress &other) const { +bool HostAddress::operator<(const HostAddress &other) const { return memcmp(qip6.c, other.qip6.c, 16) < 0; } -bool HostAddress::operator == (const HostAddress &other) const { +bool HostAddress::operator==(const HostAddress &other) const { return ((addr[0] == other.addr[0]) && (addr[1] == other.addr[1])); } @@ -86,16 +86,16 @@ bool HostAddress::match(const HostAddress &netmask, int bits) const { mask[0] = mask[1] = 0xffffffffffffffffULL; } else if (bits > 64) { mask[0] = 0xffffffffffffffffULL; - mask[1] = SWAP64(~((1ULL << (128-bits)) - 1)); + mask[1] = SWAP64(~((1ULL << (128 - bits)) - 1)); } else { - mask[0] = SWAP64(~((1ULL << (64-bits)) - 1)); + mask[0] = SWAP64(~((1ULL << (64 - bits)) - 1)); mask[1] = 0ULL; } return ((addr[0] & mask[0]) == (netmask.addr[0] & mask[0])) && ((addr[1] & mask[1]) == (netmask.addr[1] & mask[1])); } std::string HostAddress::toStdString() const { - return std::string(reinterpret_cast<const char *>(qip6.c), 16); + return std::string(reinterpret_cast< const char * >(qip6.c), 16); } bool HostAddress::isV6() const { @@ -115,19 +115,19 @@ QHostAddress HostAddress::toAddress() const { } QByteArray HostAddress::toByteArray() const { - return QByteArray(reinterpret_cast<const char *>(qip6.c), 16); + return QByteArray(reinterpret_cast< const char * >(qip6.c), 16); } void HostAddress::toSockaddr(sockaddr_storage *dst) const { memset(dst, 0, sizeof(*dst)); if (isV6()) { - struct sockaddr_in6 *in6 = reinterpret_cast<struct sockaddr_in6 *>(dst); - dst->ss_family = AF_INET6; + struct sockaddr_in6 *in6 = reinterpret_cast< struct sockaddr_in6 * >(dst); + dst->ss_family = AF_INET6; memcpy(in6->sin6_addr.s6_addr, qip6.c, 16); } else { - struct sockaddr_in *in = reinterpret_cast<struct sockaddr_in *>(dst); - dst->ss_family = AF_INET; - in->sin_addr.s_addr = hash[3]; + struct sockaddr_in *in = reinterpret_cast< struct sockaddr_in * >(dst); + dst->ss_family = AF_INET; + in->sin_addr.s_addr = hash[3]; } } @@ -140,12 +140,15 @@ QString HostAddress::toString() const { if (isValid()) { QString qs; #if QT_VERSION >= 0x050500 - qs = QString::asprintf("[%x:%x:%x:%x:%x:%x:%x:%x]", ntohs(shorts[0]), ntohs(shorts[1]), ntohs(shorts[2]), ntohs(shorts[3]), ntohs(shorts[4]), ntohs(shorts[5]), ntohs(shorts[6]), ntohs(shorts[7])); + qs = QString::asprintf("[%x:%x:%x:%x:%x:%x:%x:%x]", ntohs(shorts[0]), ntohs(shorts[1]), ntohs(shorts[2]), + ntohs(shorts[3]), ntohs(shorts[4]), ntohs(shorts[5]), ntohs(shorts[6]), + ntohs(shorts[7])); #else // sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() - qs.sprintf("[%x:%x:%x:%x:%x:%x:%x:%x]", ntohs(shorts[0]), ntohs(shorts[1]), ntohs(shorts[2]), ntohs(shorts[3]), ntohs(shorts[4]), ntohs(shorts[5]), ntohs(shorts[6]), ntohs(shorts[7])); + qs.sprintf("[%x:%x:%x:%x:%x:%x:%x:%x]", ntohs(shorts[0]), ntohs(shorts[1]), ntohs(shorts[2]), + ntohs(shorts[3]), ntohs(shorts[4]), ntohs(shorts[5]), ntohs(shorts[6]), ntohs(shorts[7])); #endif - return qs.replace(QRegExp(QLatin1String("(:0)+")),QLatin1String(":")); + return qs.replace(QRegExp(QLatin1String("(:0)+")), QLatin1String(":")); } else { return QLatin1String("[::]"); } diff --git a/src/HostAddress.h b/src/HostAddress.h index c65f95557..841eaa1cb 100644 --- a/src/HostAddress.h +++ b/src/HostAddress.h @@ -6,9 +6,9 @@ #ifndef MUMBLE_HOSTADDRESS_H_ #define MUMBLE_HOSTADDRESS_H_ -#include <QtCore/QtGlobal> -#include <QtCore/QString> #include <QtCore/QByteArray> +#include <QtCore/QString> +#include <QtCore/QtGlobal> #include <QtNetwork/QHostAddress> #include <QtNetwork/Q_IPV6ADDR> @@ -30,8 +30,8 @@ struct HostAddress { bool isV6() const; bool isValid() const; - bool operator < (const HostAddress &) const; - bool operator == (const HostAddress &) const; + bool operator<(const HostAddress &) const; + bool operator==(const HostAddress &) const; bool match(const HostAddress &, int bits) const; diff --git a/src/License.cpp b/src/License.cpp index 5d49695f8..a91db263f 100644 --- a/src/License.cpp +++ b/src/License.cpp @@ -15,13 +15,13 @@ QString License::authors() { return QString::fromUtf8(authorsMumble); } -QList<LicenseInfo> License::thirdPartyLicenses() { - QList<LicenseInfo> licenses; +QList< LicenseInfo > License::thirdPartyLicenses() { + QList< LicenseInfo > licenses; for (int i = 0; !licenses3rdParties[i].isEmpty(); i++) { const ThirdPartyLicense *tpl = &licenses3rdParties[i]; LicenseInfo li; - li.name = QString::fromUtf8(tpl->name); - li.url = QString::fromUtf8(tpl->url); + li.name = QString::fromUtf8(tpl->name); + li.url = QString::fromUtf8(tpl->url); li.license = QString::fromUtf8(tpl->license); licenses << li; } @@ -31,9 +31,9 @@ QList<LicenseInfo> License::thirdPartyLicenses() { QString License::printableThirdPartyLicenseInfo() { QString output; - QList<LicenseInfo> thirdPartyLicenses = License::thirdPartyLicenses(); + QList< LicenseInfo > thirdPartyLicenses = License::thirdPartyLicenses(); foreach (LicenseInfo li, thirdPartyLicenses) { - QString header = QString::fromLatin1("%1 (%2)\n").arg(li.name).arg(li.url); + QString header = QString::fromLatin1("%1 (%2)\n").arg(li.name).arg(li.url); QString headerHorizLine = QString::fromLatin1("-").repeated(header.size()) + QLatin1String("\n"); output.append(headerHorizLine); diff --git a/src/License.h b/src/License.h index b8e09966e..c4b57f343 100644 --- a/src/License.h +++ b/src/License.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_LICENSE_H_ #define MUMBLE_LICENSE_H_ -#include <QString> #include <QList> +#include <QString> /// LicenseInfo represents license information /// for a third-party library used by Mumble. @@ -23,17 +23,17 @@ struct LicenseInfo { /// The License class contains static helpers for /// getting Mumble license/author information. class License { - public: - /// Get the Mumble license text (the LICENSE file) - static QString license(); - /// Get the Mumble authors list (the AUTHORS file) - static QString authors(); - /// Get a list of license information for Mumble's - /// third-party libraries. - static QList<LicenseInfo> thirdPartyLicenses(); - /// Get a human-readable, ready-to-print combination - /// of all of Mumble's third-party license information. - static QString printableThirdPartyLicenseInfo(); +public: + /// Get the Mumble license text (the LICENSE file) + static QString license(); + /// Get the Mumble authors list (the AUTHORS file) + static QString authors(); + /// Get a list of license information for Mumble's + /// third-party libraries. + static QList< LicenseInfo > thirdPartyLicenses(); + /// Get a human-readable, ready-to-print combination + /// of all of Mumble's third-party license information. + static QString printableThirdPartyLicenseInfo(); }; #endif diff --git a/src/LogEmitter.cpp b/src/LogEmitter.cpp index d3f0a05ca..2fe2d7f7e 100644 --- a/src/LogEmitter.cpp +++ b/src/LogEmitter.cpp @@ -5,8 +5,7 @@ #include "LogEmitter.h" -LogEmitter::LogEmitter(QObject *p) : QObject(p) { -}; +LogEmitter::LogEmitter(QObject *p) : QObject(p){}; void LogEmitter::addLogEntry(const QString &msg) { emit newLogEntry(msg); diff --git a/src/LogEmitter.h b/src/LogEmitter.h index 07964f1c4..499b5fc9e 100644 --- a/src/LogEmitter.h +++ b/src/LogEmitter.h @@ -10,14 +10,15 @@ #include <QtCore/QString> class LogEmitter : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(LogEmitter) - signals: - void newLogEntry(const QString &msg); - public: - LogEmitter(QObject *parent = nullptr); - void addLogEntry(const QString &msg); +private: + Q_OBJECT + Q_DISABLE_COPY(LogEmitter) +signals: + void newLogEntry(const QString &msg); + +public: + LogEmitter(QObject *parent = nullptr); + void addLogEntry(const QString &msg); }; #endif diff --git a/src/Message.h b/src/Message.h index 1048ee68d..1ba8cbfc3 100644 --- a/src/Message.h +++ b/src/Message.h @@ -6,51 +6,49 @@ #ifndef MUMBLE_MESSAGE_H_ #define MUMBLE_MESSAGE_H_ -#include <string> #include <QtCore/QCryptographicHash> #include <QtCore/QString> +#include <string> /** Protobuf packet type enumeration for message handler generation. Warning: Only append to the end. */ -#define MUMBLE_MH_ALL \ - MUMBLE_MH_MSG(Version) \ - MUMBLE_MH_MSG(UDPTunnel) \ - MUMBLE_MH_MSG(Authenticate) \ - MUMBLE_MH_MSG(Ping) \ - MUMBLE_MH_MSG(Reject) \ - MUMBLE_MH_MSG(ServerSync) \ - MUMBLE_MH_MSG(ChannelRemove) \ - MUMBLE_MH_MSG(ChannelState) \ - MUMBLE_MH_MSG(UserRemove) \ - MUMBLE_MH_MSG(UserState) \ - MUMBLE_MH_MSG(BanList) \ - MUMBLE_MH_MSG(TextMessage) \ - MUMBLE_MH_MSG(PermissionDenied) \ - MUMBLE_MH_MSG(ACL) \ - MUMBLE_MH_MSG(QueryUsers) \ - MUMBLE_MH_MSG(CryptSetup) \ +#define MUMBLE_MH_ALL \ + MUMBLE_MH_MSG(Version) \ + MUMBLE_MH_MSG(UDPTunnel) \ + MUMBLE_MH_MSG(Authenticate) \ + MUMBLE_MH_MSG(Ping) \ + MUMBLE_MH_MSG(Reject) \ + MUMBLE_MH_MSG(ServerSync) \ + MUMBLE_MH_MSG(ChannelRemove) \ + MUMBLE_MH_MSG(ChannelState) \ + MUMBLE_MH_MSG(UserRemove) \ + MUMBLE_MH_MSG(UserState) \ + MUMBLE_MH_MSG(BanList) \ + MUMBLE_MH_MSG(TextMessage) \ + MUMBLE_MH_MSG(PermissionDenied) \ + MUMBLE_MH_MSG(ACL) \ + MUMBLE_MH_MSG(QueryUsers) \ + MUMBLE_MH_MSG(CryptSetup) \ MUMBLE_MH_MSG(ContextActionModify) \ - MUMBLE_MH_MSG(ContextAction) \ - MUMBLE_MH_MSG(UserList) \ - MUMBLE_MH_MSG(VoiceTarget) \ - MUMBLE_MH_MSG(PermissionQuery) \ - MUMBLE_MH_MSG(CodecVersion) \ - MUMBLE_MH_MSG(UserStats) \ - MUMBLE_MH_MSG(RequestBlob) \ - MUMBLE_MH_MSG(ServerConfig) \ + MUMBLE_MH_MSG(ContextAction) \ + MUMBLE_MH_MSG(UserList) \ + MUMBLE_MH_MSG(VoiceTarget) \ + MUMBLE_MH_MSG(PermissionQuery) \ + MUMBLE_MH_MSG(CodecVersion) \ + MUMBLE_MH_MSG(UserStats) \ + MUMBLE_MH_MSG(RequestBlob) \ + MUMBLE_MH_MSG(ServerConfig) \ MUMBLE_MH_MSG(SuggestConfig) class MessageHandler { - public: - enum UDPMessageType { UDPVoiceCELTAlpha, UDPPing, UDPVoiceSpeex, UDPVoiceCELTBeta, UDPVoiceOpus }; +public: + enum UDPMessageType { UDPVoiceCELTAlpha, UDPPing, UDPVoiceSpeex, UDPVoiceCELTBeta, UDPVoiceOpus }; #define MUMBLE_MH_MSG(x) x, - enum MessageType { - MUMBLE_MH_ALL - }; + enum MessageType { MUMBLE_MH_ALL }; #undef MUMBLE_MH_MSG }; @@ -70,7 +68,7 @@ inline bool UDPMessageTypeIsValidVoicePacket(MessageHandler::UDPMessageType umt) } inline QString u8(const ::std::string &str) { - return QString::fromUtf8(str.data(), static_cast<int>(str.length())); + return QString::fromUtf8(str.data(), static_cast< int >(str.length())); } inline QString u8(const ::std::wstring &str) { @@ -83,7 +81,7 @@ inline ::std::string u8(const QString &str) { } inline QByteArray blob(const ::std::string &str) { - return QByteArray(str.data(), static_cast<int>(str.length())); + return QByteArray(str.data(), static_cast< int >(str.length())); } inline ::std::string blob(const QByteArray &str) { diff --git a/src/Net.cpp b/src/Net.cpp index 047cdbf60..cf2082eb3 100644 --- a/src/Net.cpp +++ b/src/Net.cpp @@ -7,10 +7,10 @@ #include "HostAddress.h" bool Ban::isExpired() const { - return (iDuration > 0) && static_cast<int>(iDuration - qdtStart.secsTo(QDateTime::currentDateTime().toUTC())) < 0; + return (iDuration > 0) && static_cast< int >(iDuration - qdtStart.secsTo(QDateTime::currentDateTime().toUTC())) < 0; } -bool Ban::operator <(const Ban &other) const { +bool Ban::operator<(const Ban &other) const { // Compare username primarily and address secondarily const int unameDifference = qsUsername.localeAwareCompare(other.qsUsername); if (unameDifference == 0) @@ -19,14 +19,10 @@ bool Ban::operator <(const Ban &other) const { return unameDifference < 0; } -bool Ban::operator ==(const Ban &other) const { - return (haAddress == other.haAddress) - && (iMask == other.iMask) - && (qsUsername == other.qsUsername) - && (qsHash == other.qsHash) - && (qsReason == other.qsReason) - && (qdtStart == other.qdtStart) - && (iDuration == other.iDuration); +bool Ban::operator==(const Ban &other) const { + return (haAddress == other.haAddress) && (iMask == other.iMask) && (qsUsername == other.qsUsername) + && (qsHash == other.qsHash) && (qsReason == other.qsReason) && (qdtStart == other.qdtStart) + && (iDuration == other.iDuration); } bool Ban::isValid() const { @@ -34,16 +30,12 @@ bool Ban::isValid() const { } QString Ban::toString() const { - return QString(QLatin1String("Hash: \"%1\", Host: \"%2\", Mask: \"%3\", Username: \"%4\", Reason: \"%5\", BanStart: \"%6\", BanEnd: \"%7\" %8")).arg( - qsHash, - haAddress.toString(), - haAddress.isV6() ? QString::number(iMask) : QString::number(iMask-96), - qsUsername, - qsReason, - qdtStart.toLocalTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), - qdtStart.toLocalTime().addSecs(iDuration).toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), - iDuration == 0 ? QLatin1String("(permanent)") : QLatin1String("(temporary)") - ); + return QString(QLatin1String("Hash: \"%1\", Host: \"%2\", Mask: \"%3\", Username: \"%4\", Reason: \"%5\", " + "BanStart: \"%6\", BanEnd: \"%7\" %8")) + .arg(qsHash, haAddress.toString(), haAddress.isV6() ? QString::number(iMask) : QString::number(iMask - 96), + qsUsername, qsReason, qdtStart.toLocalTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), + qdtStart.toLocalTime().addSecs(iDuration).toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), + iDuration == 0 ? QLatin1String("(permanent)") : QLatin1String("(temporary)")); } quint32 qHash(const Ban &b) { @@ -13,7 +13,7 @@ #include "HostAddress.h" #ifndef DEFAULT_MUMBLE_PORT -#define DEFAULT_MUMBLE_PORT 64738 +# define DEFAULT_MUMBLE_PORT 64738 #endif #endif diff --git a/src/OSInfo.cpp b/src/OSInfo.cpp index e8c4b6f30..dbb3b7332 100644 --- a/src/OSInfo.cpp +++ b/src/OSInfo.cpp @@ -6,7 +6,7 @@ #include <QtCore/QtGlobal> #if defined(Q_OS_WIN) -# include "win.h" +# include "win.h" #endif #include "OSInfo.h" @@ -19,22 +19,22 @@ #include <QtXml/QDomDocument> #if defined(Q_OS_WIN) -# include <intrin.h> +# include <intrin.h> #endif #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) -# include <sys/utsname.h> +# include <sys/utsname.h> #endif #if defined(Q_OS_MAC) -# include <Carbon/Carbon.h> -# include <sys/types.h> -# include <sys/sysctl.h> -# include <mach-o/arch.h> +# include <Carbon/Carbon.h> +# include <mach-o/arch.h> +# include <sys/sysctl.h> +# include <sys/types.h> // Ignore deprecation warnings for Gestalt. // See mumble-voip/mumble#3290 for more information. -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" +# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif @@ -49,10 +49,10 @@ static QString regString(wchar_t *string, int size) { // If string contains a NUL, adjust the size such // that the NUL is not included in the returned // string. - const size_t adjustedSize = wcsnlen(string, static_cast<size_t>(size)); + const size_t adjustedSize = wcsnlen(string, static_cast< size_t >(size)); // The return value of wcsnlen is <= size which is // an int, so casting adjustedSize to int is safe. - return QString::fromWCharArray(string, static_cast<int>(adjustedSize)); + return QString::fromWCharArray(string, static_cast< int >(adjustedSize)); } /// Query for a Windows 10-style displayable version. @@ -75,8 +75,8 @@ static QString regString(wchar_t *string, int size) { /// this function, and if it returns an empty/null string, /// a legacy version string can be displayed. static QString win10DisplayableVersion() { - HKEY key = 0; - LONG err = 0; + HKEY key = 0; + LONG err = 0; DWORD len = 0; wchar_t buf[64]; DWORD dw = 0; @@ -94,36 +94,36 @@ static QString win10DisplayableVersion() { } len = sizeof(buf); - err = RegQueryValueEx(key, L"ProductName", nullptr, nullptr, reinterpret_cast<LPBYTE>(&buf[0]), &len); + err = RegQueryValueEx(key, L"ProductName", nullptr, nullptr, reinterpret_cast< LPBYTE >(&buf[0]), &len); if (err != ERROR_SUCCESS) { RegCloseKey(key); return QString(); } - productName = regString(buf, static_cast<int>(len / sizeof(buf[0]))); + productName = regString(buf, static_cast< int >(len / sizeof(buf[0]))); len = sizeof(buf); - err = RegQueryValueEx(key, L"ReleaseId", nullptr, nullptr, reinterpret_cast<LPBYTE>(&buf[0]), &len); + err = RegQueryValueEx(key, L"ReleaseId", nullptr, nullptr, reinterpret_cast< LPBYTE >(&buf[0]), &len); if (err != ERROR_SUCCESS) { RegCloseKey(key); return QString(); } - releaseId = regString(buf, static_cast<int>(len / sizeof(buf[0]))); + releaseId = regString(buf, static_cast< int >(len / sizeof(buf[0]))); len = sizeof(buf); - err = RegQueryValueEx(key, L"CurrentBuild", nullptr, nullptr, reinterpret_cast<LPBYTE>(&buf[0]), &len); + err = RegQueryValueEx(key, L"CurrentBuild", nullptr, nullptr, reinterpret_cast< LPBYTE >(&buf[0]), &len); if (err != ERROR_SUCCESS) { RegCloseKey(key); return QString(); } - currentBuild = regString(buf, static_cast<int>(len / sizeof(buf[0]))); + currentBuild = regString(buf, static_cast< int >(len / sizeof(buf[0]))); len = sizeof(dw); - err = RegQueryValueEx(key, L"UBR", nullptr, nullptr, reinterpret_cast<LPBYTE>(&dw), &len); + err = RegQueryValueEx(key, L"UBR", nullptr, nullptr, reinterpret_cast< LPBYTE >(&dw), &len); if (err != ERROR_SUCCESS) { RegCloseKey(key); return QString(); } - ubr = QString::number(static_cast<ulong>(dw), 10); + ubr = QString::number(static_cast< ulong >(dw), 10); RegCloseKey(key); @@ -141,17 +141,18 @@ static QString win10DisplayableVersion() { } #endif -QString OSInfo::getMacHash(const QList<QHostAddress> &qlBind) { +QString OSInfo::getMacHash(const QList< QHostAddress > &qlBind) { QString first, second, third; - foreach(const QNetworkInterface &qni, QNetworkInterface::allInterfaces()) { - if (! qni.isValid()) + foreach (const QNetworkInterface &qni, QNetworkInterface::allInterfaces()) { + if (!qni.isValid()) continue; if (qni.flags() & QNetworkInterface::IsLoopBack) continue; if (qni.hardwareAddress().isEmpty()) continue; - QString hash = QString::fromUtf8(QCryptographicHash::hash(qni.hardwareAddress().toUtf8(), QCryptographicHash::Sha1).toHex()); + QString hash = QString::fromUtf8( + QCryptographicHash::hash(qni.hardwareAddress().toUtf8(), QCryptographicHash::Sha1).toHex()); if (third.isEmpty() || third > hash) third = hash; @@ -162,7 +163,7 @@ QString OSInfo::getMacHash(const QList<QHostAddress> &qlBind) { if (second.isEmpty() || second > hash) second = hash; - foreach(const QNetworkAddressEntry &qnae, qni.addressEntries()) { + foreach (const QNetworkAddressEntry &qnae, qni.addressEntries()) { const QHostAddress &qha = qnae.ip(); if (qlBind.isEmpty() || qlBind.contains(qha)) { if (first.isEmpty() || first > hash) @@ -170,22 +171,22 @@ QString OSInfo::getMacHash(const QList<QHostAddress> &qlBind) { } } } - if (! first.isEmpty()) + if (!first.isEmpty()) return first; - if (! second.isEmpty()) + if (!second.isEmpty()) return second; - if (! third.isEmpty()) + if (!third.isEmpty()) return third; return QString(); } QString OSInfo::getOS() { #if defined(Q_OS_WIN) -# if defined(Q_OS_WIN64) +# if defined(Q_OS_WIN64) return QLatin1String("WinX64"); -# else +# else return QLatin1String("Win"); -# endif +# endif #elif defined(Q_OS_MAC) return QLatin1String("OSX"); #else @@ -196,7 +197,7 @@ QString OSInfo::getOS() { QString OSInfo::getOSVersion() { static QString qsCached; - if (! qsCached.isNull()) + if (!qsCached.isNull()) return qsCached.isEmpty() ? QString() : qsCached; QString os; @@ -205,25 +206,22 @@ QString OSInfo::getOSVersion() { OSVERSIONINFOEXW ovi; memset(&ovi, 0, sizeof(ovi)); - ovi.dwOSVersionInfoSize=sizeof(ovi); - if (!GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi))) { + ovi.dwOSVersionInfoSize = sizeof(ovi); + if (!GetVersionEx(reinterpret_cast< OSVERSIONINFOW * >(&ovi))) { return QString(); } -#if QT_VERSION >= 0x050500 - os = QString::asprintf("%lu.%lu.%lu.%lu", - static_cast<unsigned long>(ovi.dwMajorVersion), - static_cast<unsigned long>(ovi.dwMinorVersion), - static_cast<unsigned long>(ovi.dwBuildNumber), - (ovi.wProductType == VER_NT_WORKSTATION) ? 1UL : 0UL); -#else +# if QT_VERSION >= 0x050500 + os = QString::asprintf("%lu.%lu.%lu.%lu", static_cast< unsigned long >(ovi.dwMajorVersion), + static_cast< unsigned long >(ovi.dwMinorVersion), + static_cast< unsigned long >(ovi.dwBuildNumber), + (ovi.wProductType == VER_NT_WORKSTATION) ? 1UL : 0UL); +# else // sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() - os.sprintf("%lu.%lu.%lu.%lu", - static_cast<unsigned long>(ovi.dwMajorVersion), - static_cast<unsigned long>(ovi.dwMinorVersion), - static_cast<unsigned long>(ovi.dwBuildNumber), - (ovi.wProductType == VER_NT_WORKSTATION) ? 1UL : 0UL); -#endif // QT_VERSION >= 0x050500 + os.sprintf("%lu.%lu.%lu.%lu", static_cast< unsigned long >(ovi.dwMajorVersion), + static_cast< unsigned long >(ovi.dwMinorVersion), static_cast< unsigned long >(ovi.dwBuildNumber), + (ovi.wProductType == VER_NT_WORKSTATION) ? 1UL : 0UL); +# endif // QT_VERSION >= 0x050500 #elif defined(Q_OS_MAC) SInt32 major, minor, bugfix; @@ -238,27 +236,21 @@ QString OSInfo::getOSVersion() { char *buildno = nullptr; char buildno_buf[32]; size_t sz_buildno_buf = sizeof(buildno); - int ret = sysctlbyname("kern.osversion", buildno_buf, &sz_buildno_buf, nullptr, 0); + int ret = sysctlbyname("kern.osversion", buildno_buf, &sz_buildno_buf, nullptr, 0); if (ret == 0) { buildno = &buildno_buf[0]; } -#if QT_VERSION >= 0x050500 - os = QString::asprintf("%lu.%lu.%lu %s", - static_cast<unsigned long>(major), - static_cast<unsigned long>(minor), - static_cast<unsigned long>(bugfix), - buildno ? buildno : "unknown"); -#else +# if QT_VERSION >= 0x050500 + os = QString::asprintf("%lu.%lu.%lu %s", static_cast< unsigned long >(major), static_cast< unsigned long >(minor), + static_cast< unsigned long >(bugfix), buildno ? buildno : "unknown"); +# else // sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() - os.sprintf("%lu.%lu.%lu %s", - static_cast<unsigned long>(major), - static_cast<unsigned long>(minor), - static_cast<unsigned long>(bugfix), - buildno ? buildno : "unknown"); -#endif // QT_VERSION >= 0x050500 + os.sprintf("%lu.%lu.%lu %s", static_cast< unsigned long >(major), static_cast< unsigned long >(minor), + static_cast< unsigned long >(bugfix), buildno ? buildno : "unknown"); +# endif // QT_VERSION >= 0x050500 #else -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX QProcess qp; QStringList args; args << QLatin1String("-s"); @@ -273,29 +265,29 @@ QString OSInfo::getOSVersion() { qWarning("OSInfo: Failed to execute lsb_release"); qp.terminate(); - if (! qp.waitForFinished(1000)) + if (!qp.waitForFinished(1000)) qp.kill(); -#endif +# endif if (os.isEmpty()) { struct utsname un; -#ifdef Q_OS_SOLARIS +# ifdef Q_OS_SOLARIS // Solaris's uname() returns a non-negative number on success. if (uname(&un) >= 0) { -#else +# else // other UNIX-like systems return a 0 on success. if (uname(&un) == 0) { -#endif -#if QT_VERSION >= 0x050500 +# endif +# if QT_VERSION >= 0x050500 os = QString::asprintf("%s %s", un.sysname, un.release); -#else +# else // sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() os.sprintf("%s %s", un.sysname, un.release); -#endif // QT_VERSION >= 0x050500 +# endif // QT_VERSION >= 0x050500 } } #endif - if (! os.isNull()) + if (!os.isNull()) qsCached = os; else qsCached = QLatin1String(""); @@ -320,7 +312,7 @@ QString OSInfo::getOSDisplayableVersion() { OSVERSIONINFOEXW ovi; memset(&ovi, 0, sizeof(ovi)); ovi.dwOSVersionInfoSize = sizeof(ovi); - if (!GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi))) { + if (!GetVersionEx(reinterpret_cast< OSVERSIONINFOW * >(&ovi))) { return QString(); } @@ -368,7 +360,7 @@ QString OSInfo::getOSDisplayableVersion() { } } - typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); + typedef BOOL(WINAPI * PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); PGPI pGetProductInfo = (PGPI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); if (!pGetProductInfo) { return QString(); @@ -379,61 +371,61 @@ QString OSInfo::getOSDisplayableVersion() { return QString(); } - switch(dwType) { - case PRODUCT_ULTIMATE: - osdispver.append(QLatin1String(" Ultimate Edition")); - break; - case PRODUCT_PROFESSIONAL: - osdispver.append(QLatin1String(" Professional")); - break; - case PRODUCT_HOME_PREMIUM: - osdispver.append(QLatin1String(" Home Premium Edition")); - break; - case PRODUCT_HOME_BASIC: - osdispver.append(QLatin1String(" Home Basic Edition")); - break; - case PRODUCT_ENTERPRISE: - osdispver.append(QLatin1String(" Enterprise Edition")); - break; - case PRODUCT_BUSINESS: - osdispver.append(QLatin1String(" Business Edition")); - break; - case PRODUCT_STARTER: - osdispver.append(QLatin1String(" Starter Edition")); - break; - case PRODUCT_CLUSTER_SERVER: - osdispver.append(QLatin1String(" Cluster Server Edition")); - break; - case PRODUCT_DATACENTER_SERVER: - osdispver.append(QLatin1String(" Datacenter Edition")); - break; - case PRODUCT_DATACENTER_SERVER_CORE: - osdispver.append(QLatin1String(" Datacenter Edition (core installation)")); - break; - case PRODUCT_ENTERPRISE_SERVER: - osdispver.append(QLatin1String(" Enterprise Edition")); - break; - case PRODUCT_ENTERPRISE_SERVER_CORE: - osdispver.append(QLatin1String(" Enterprise Edition (core installation)")); - break; - case PRODUCT_ENTERPRISE_SERVER_IA64: - osdispver.append(QLatin1String(" Enterprise Edition for Itanium-based Systems")); - break; - case PRODUCT_SMALLBUSINESS_SERVER: - osdispver.append(QLatin1String(" Small Business Server")); - break; - case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: - osdispver.append(QLatin1String(" Small Business Server Premium Edition")); - break; - case PRODUCT_STANDARD_SERVER: - osdispver.append(QLatin1String(" Standard Edition")); - break; - case PRODUCT_STANDARD_SERVER_CORE: - osdispver.append(QLatin1String(" Standard Edition (core installation)")); - break; - case PRODUCT_WEB_SERVER: - osdispver.append(QLatin1String(" Web Server Edition")); - break; + switch (dwType) { + case PRODUCT_ULTIMATE: + osdispver.append(QLatin1String(" Ultimate Edition")); + break; + case PRODUCT_PROFESSIONAL: + osdispver.append(QLatin1String(" Professional")); + break; + case PRODUCT_HOME_PREMIUM: + osdispver.append(QLatin1String(" Home Premium Edition")); + break; + case PRODUCT_HOME_BASIC: + osdispver.append(QLatin1String(" Home Basic Edition")); + break; + case PRODUCT_ENTERPRISE: + osdispver.append(QLatin1String(" Enterprise Edition")); + break; + case PRODUCT_BUSINESS: + osdispver.append(QLatin1String(" Business Edition")); + break; + case PRODUCT_STARTER: + osdispver.append(QLatin1String(" Starter Edition")); + break; + case PRODUCT_CLUSTER_SERVER: + osdispver.append(QLatin1String(" Cluster Server Edition")); + break; + case PRODUCT_DATACENTER_SERVER: + osdispver.append(QLatin1String(" Datacenter Edition")); + break; + case PRODUCT_DATACENTER_SERVER_CORE: + osdispver.append(QLatin1String(" Datacenter Edition (core installation)")); + break; + case PRODUCT_ENTERPRISE_SERVER: + osdispver.append(QLatin1String(" Enterprise Edition")); + break; + case PRODUCT_ENTERPRISE_SERVER_CORE: + osdispver.append(QLatin1String(" Enterprise Edition (core installation)")); + break; + case PRODUCT_ENTERPRISE_SERVER_IA64: + osdispver.append(QLatin1String(" Enterprise Edition for Itanium-based Systems")); + break; + case PRODUCT_SMALLBUSINESS_SERVER: + osdispver.append(QLatin1String(" Small Business Server")); + break; + case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: + osdispver.append(QLatin1String(" Small Business Server Premium Edition")); + break; + case PRODUCT_STANDARD_SERVER: + osdispver.append(QLatin1String(" Standard Edition")); + break; + case PRODUCT_STANDARD_SERVER_CORE: + osdispver.append(QLatin1String(" Standard Edition (core installation)")); + break; + case PRODUCT_WEB_SERVER: + osdispver.append(QLatin1String(" Web Server Edition")); + break; } } else if (ovi.dwMajorVersion == 5 && ovi.dwMinorVersion == 0) { osdispver = QLatin1String("Windows 2000"); @@ -462,7 +454,8 @@ QString OSInfo::getOSDisplayableVersion() { osdispver = QLatin1String("Windows Storage Server 2003"); } else if (ovi.wSuiteMask & VER_SUITE_WH_SERVER) { osdispver = QLatin1String("Windows Home Server"); - } else if (ovi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { + } else if (ovi.wProductType == VER_NT_WORKSTATION + && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { osdispver = QLatin1String("Windows XP Professional x64 Edition"); } else { osdispver = QLatin1String("Windows Server 2003"); @@ -511,18 +504,15 @@ QString OSInfo::getOSDisplayableVersion() { } QString osv; -#if QT_VERSION >= 0x050500 - osv = QString::asprintf(" - %lu.%lu.%lu", - static_cast<unsigned long>(ovi.dwMajorVersion), - static_cast<unsigned long>(ovi.dwMinorVersion), - static_cast<unsigned long>(ovi.dwBuildNumber)); -#else +# if QT_VERSION >= 0x050500 + osv = QString::asprintf(" - %lu.%lu.%lu", static_cast< unsigned long >(ovi.dwMajorVersion), + static_cast< unsigned long >(ovi.dwMinorVersion), + static_cast< unsigned long >(ovi.dwBuildNumber)); +# else // sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() - osv.sprintf(" - %lu.%lu.%lu", - static_cast<unsigned long>(ovi.dwMajorVersion), - static_cast<unsigned long>(ovi.dwMinorVersion), - static_cast<unsigned long>(ovi.dwBuildNumber)); -#endif // QT_VERSION >= 0x050500 + osv.sprintf(" - %lu.%lu.%lu", static_cast< unsigned long >(ovi.dwMajorVersion), + static_cast< unsigned long >(ovi.dwMinorVersion), static_cast< unsigned long >(ovi.dwBuildNumber)); +# endif // QT_VERSION >= 0x050500 osdispver.append(osv); return osdispver; @@ -531,41 +521,42 @@ QString OSInfo::getOSDisplayableVersion() { #endif } -void OSInfo::fillXml(QDomDocument &doc, QDomElement &root, const QString &os, const QString &osver, const QList<QHostAddress> &qlBind) { +void OSInfo::fillXml(QDomDocument &doc, QDomElement &root, const QString &os, const QString &osver, + const QList< QHostAddress > &qlBind) { QDomElement tag; QDomText t; bool bIs64; bool bSSE2 = false; QString cpu_id, cpu_extid; - tag=doc.createElement(QLatin1String("machash")); + tag = doc.createElement(QLatin1String("machash")); root.appendChild(tag); - t=doc.createTextNode(OSInfo::getMacHash(qlBind)); + t = doc.createTextNode(OSInfo::getMacHash(qlBind)); tag.appendChild(t); - tag=doc.createElement(QLatin1String("version")); + tag = doc.createElement(QLatin1String("version")); root.appendChild(tag); - t=doc.createTextNode(QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); + t = doc.createTextNode(QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); tag.appendChild(t); - tag=doc.createElement(QLatin1String("release")); + tag = doc.createElement(QLatin1String("release")); root.appendChild(tag); - t=doc.createTextNode(QLatin1String(MUMBLE_RELEASE)); + t = doc.createTextNode(QLatin1String(MUMBLE_RELEASE)); tag.appendChild(t); - tag=doc.createElement(QLatin1String("os")); + tag = doc.createElement(QLatin1String("os")); root.appendChild(tag); - t=doc.createTextNode(os); + t = doc.createTextNode(os); tag.appendChild(t); - tag=doc.createElement(QLatin1String("osver")); + tag = doc.createElement(QLatin1String("osver")); root.appendChild(tag); - t=doc.createTextNode(osver); + t = doc.createTextNode(osver); tag.appendChild(t); - tag=doc.createElement(QLatin1String("qt")); + tag = doc.createElement(QLatin1String("qt")); root.appendChild(tag); - t=doc.createTextNode(QString::fromLatin1(qVersion())); + t = doc.createTextNode(QString::fromLatin1(qVersion())); tag.appendChild(t); #if defined(Q_OS_WIN) @@ -575,13 +566,13 @@ void OSInfo::fillXml(QDomDocument &doc, QDomElement &root, const QString &os, co #else bIs64 = (QSysInfo::WordSize == 64); #endif - tag=doc.createElement(QLatin1String("is64bit")); + tag = doc.createElement(QLatin1String("is64bit")); root.appendChild(tag); - t=doc.createTextNode(QString::number(bIs64 ? 1 : 0)); + t = doc.createTextNode(QString::number(bIs64 ? 1 : 0)); tag.appendChild(t); #if defined(Q_OS_WIN) -#define regstr(x) QString::fromLatin1(reinterpret_cast<const char *>(& x), 4) +# define regstr(x) QString::fromLatin1(reinterpret_cast< const char * >(&x), 4) int chop; int cpuinfo[4]; @@ -592,34 +583,34 @@ void OSInfo::fillXml(QDomDocument &doc, QDomElement &root, const QString &os, co cpu_id = regstr(cpuinfo[1]) + regstr(cpuinfo[3]) + regstr(cpuinfo[2]); - for (unsigned int j=2; j<=4;++j) { + for (unsigned int j = 2; j <= 4; ++j) { __cpuid(cpuinfo, 0x80000000 + j); cpu_extid += regstr(cpuinfo[0]) + regstr(cpuinfo[1]) + regstr(cpuinfo[2]) + regstr(cpuinfo[3]); } cpu_id = cpu_id.trimmed(); - chop = cpu_id.indexOf(QLatin1Char('\0')); + chop = cpu_id.indexOf(QLatin1Char('\0')); if (chop != -1) cpu_id.truncate(chop); cpu_extid = cpu_extid.trimmed(); - chop = cpu_extid.indexOf(QLatin1Char('\0')); + chop = cpu_extid.indexOf(QLatin1Char('\0')); if (chop != -1) cpu_extid.truncate(chop); #endif - tag=doc.createElement(QLatin1String("cpu_id")); + tag = doc.createElement(QLatin1String("cpu_id")); root.appendChild(tag); - t=doc.createTextNode(cpu_id); + t = doc.createTextNode(cpu_id); tag.appendChild(t); - tag=doc.createElement(QLatin1String("cpu_extid")); + tag = doc.createElement(QLatin1String("cpu_extid")); root.appendChild(tag); - t=doc.createTextNode(cpu_extid); + t = doc.createTextNode(cpu_extid); tag.appendChild(t); - tag=doc.createElement(QLatin1String("cpu_sse2")); + tag = doc.createElement(QLatin1String("cpu_sse2")); root.appendChild(tag); - t=doc.createTextNode(QString::number(bSSE2 ? 1 : 0)); + t = doc.createTextNode(QString::number(bSSE2 ? 1 : 0)); tag.appendChild(t); } diff --git a/src/OSInfo.h b/src/OSInfo.h index 87ed836f4..287c6d414 100644 --- a/src/OSInfo.h +++ b/src/OSInfo.h @@ -14,12 +14,14 @@ class QDomElement; class QHostAddress; class OSInfo { - public: - static QString getMacHash(const QList<QHostAddress> & = QList<QHostAddress>()); - static QString getOS(); - static QString getOSVersion(); - static QString getOSDisplayableVersion(); - static void fillXml(QDomDocument &doc, QDomElement &root, const QString &os = OSInfo::getOS(), const QString &osver = OSInfo::getOSVersion(), const QList<QHostAddress> & = QList<QHostAddress>()); +public: + static QString getMacHash(const QList< QHostAddress > & = QList< QHostAddress >()); + static QString getOS(); + static QString getOSVersion(); + static QString getOSDisplayableVersion(); + static void fillXml(QDomDocument &doc, QDomElement &root, const QString &os = OSInfo::getOS(), + const QString &osver = OSInfo::getOSVersion(), + const QList< QHostAddress > & = QList< QHostAddress >()); }; #endif diff --git a/src/PacketDataStream.h b/src/PacketDataStream.h index c6873059e..4349dd68d 100644 --- a/src/PacketDataStream.h +++ b/src/PacketDataStream.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_PACKETDATASTREAM_H_ #define MUMBLE_PACKETDATASTREAM_H_ -#include <QPair> #include <QByteArray> +#include <QPair> #include <QString> #include <cstring> @@ -17,416 +17,386 @@ */ class PacketDataStream { - private: - Q_DISABLE_COPY(PacketDataStream) - private: - unsigned char *data; - quint32 maxsize; - quint32 offset; - quint32 overshoot; - bool ok; - public: - quint32 size() const { - return offset; - } +private: + Q_DISABLE_COPY(PacketDataStream) +private: + unsigned char *data; + quint32 maxsize; + quint32 offset; + quint32 overshoot; + bool ok; - quint32 capacity() const { - return maxsize; - } +public: + quint32 size() const { return offset; } - bool isValid() const { - return ok; - } + quint32 capacity() const { return maxsize; } - quint32 left() const { - return maxsize - offset; - } + bool isValid() const { return ok; } - quint32 undersize() const { - return overshoot; - } + quint32 left() const { return maxsize - offset; } - void append(const quint64 v) { + quint32 undersize() const { return overshoot; } + + void append(const quint64 v) { #ifndef QT_NO_DEBUG - Q_ASSERT(v <= 0xff); + Q_ASSERT(v <= 0xff); #endif - if (offset < maxsize) - data[offset++] = static_cast<unsigned char>(v); - else { - ok = false; - overshoot++; - } - }; - - void append(const char *d, quint32 len) { - if (left() >= len) { - memcpy(& data[offset], d, len); - offset += len; - } else { - int l = left(); - memset(& data[offset], 0, l); - offset += l; - overshoot += len - l; - ok = false; - } - } - - void skip(quint32 len) { - if (left() >= len) - offset += len; - else - ok = false; - } - - quint64 next() { - if (offset < maxsize) - return data[offset++]; - else { - ok = false; - return 0; - } - }; - - quint8 next8() { - if (offset < maxsize) - return data[offset++]; - else { - ok = false; - return 0; - } - } - - void rewind() { - offset = 0; - } - - void truncate() { - maxsize = offset; - } - - const unsigned char *dataPtr() const { - return reinterpret_cast<const unsigned char *>(& data[offset]); - } - - const char *charPtr() const { - return reinterpret_cast<const char *>(& data[offset]); - } - - QByteArray dataBlock(quint32 len) { - if (len <= left()) { - QByteArray a(charPtr(), len); - offset +=len; - return a; + if (offset < maxsize) + data[offset++] = static_cast< unsigned char >(v); + else { + ok = false; + overshoot++; + } + }; + + void append(const char *d, quint32 len) { + if (left() >= len) { + memcpy(&data[offset], d, len); + offset += len; + } else { + int l = left(); + memset(&data[offset], 0, l); + offset += l; + overshoot += len - l; + ok = false; + } + } + + void skip(quint32 len) { + if (left() >= len) + offset += len; + else + ok = false; + } + + quint64 next() { + if (offset < maxsize) + return data[offset++]; + else { + ok = false; + return 0; + } + }; + + quint8 next8() { + if (offset < maxsize) + return data[offset++]; + else { + ok = false; + return 0; + } + } + + void rewind() { offset = 0; } + + void truncate() { maxsize = offset; } + + const unsigned char *dataPtr() const { return reinterpret_cast< const unsigned char * >(&data[offset]); } + + const char *charPtr() const { return reinterpret_cast< const char * >(&data[offset]); } + + QByteArray dataBlock(quint32 len) { + if (len <= left()) { + QByteArray a(charPtr(), len); + offset += len; + return a; + } else { + ok = false; + return QByteArray(); + } + } + +protected: + void setup(unsigned char *d, int msize) { + data = d; + offset = 0; + overshoot = 0; + maxsize = msize; + ok = true; + } + +public: + PacketDataStream(const char *d, int msize) { + setup(const_cast< unsigned char * >(reinterpret_cast< const unsigned char * >(d)), msize); + }; + + PacketDataStream(char *d, int msize) { setup(reinterpret_cast< unsigned char * >(d), msize); }; + + PacketDataStream(unsigned char *d, int msize) { setup(d, msize); }; + + PacketDataStream(const QByteArray &qba) { + setup(const_cast< unsigned char * >(reinterpret_cast< const unsigned char * >(qba.constData())), qba.size()); + } + + PacketDataStream(QByteArray &qba) { + unsigned char *ptr = reinterpret_cast< unsigned char * >(qba.data()); + setup(ptr, qba.capacity()); + } + + PacketDataStream &operator<<(const quint64 value) { + quint64 i = value; + + if ((i & 0x8000000000000000LL) && (~i < 0x100000000LL)) { + // Signed number. + i = ~i; + if (i <= 0x3) { + // Shortcase for -1 to -4 + append(0xFC | i); + return *this; } else { - ok = false; - return QByteArray(); + append(0xF8); } } - - protected: - void setup(unsigned char *d, int msize) { - data = d; - offset = 0; - overshoot = 0; - maxsize = msize; - ok = true; - } - public: - PacketDataStream(const char *d, int msize) { - setup(const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(d)), msize); - }; - - PacketDataStream(char *d, int msize) { - setup(reinterpret_cast<unsigned char *>(d), msize); - }; - - PacketDataStream(unsigned char *d, int msize) { - setup(d, msize); - }; - - PacketDataStream(const QByteArray &qba) { - setup(const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(qba.constData())), qba.size()); - } - - PacketDataStream(QByteArray &qba) { - unsigned char *ptr=reinterpret_cast<unsigned char *>(qba.data()); - setup(ptr, qba.capacity()); - } - - PacketDataStream &operator <<(const quint64 value) { - quint64 i = value; - - if ((i & 0x8000000000000000LL) && (~i < 0x100000000LL)) { - // Signed number. - i = ~i; - if (i <= 0x3) { - // Shortcase for -1 to -4 - append(0xFC | i); - return *this; - } else { - append(0xF8); - } - } - if (i < 0x80) { - // Need top bit clear - append(i); - } else if (i < 0x4000) { - // Need top two bits clear - append((i >> 8) | 0x80); - append(i & 0xFF); - } else if (i < 0x200000) { - // Need top three bits clear - append((i >> 16) | 0xC0); - append((i >> 8) & 0xFF); - append(i & 0xFF); - } else if (i < 0x10000000) { - // Need top four bits clear - append((i >> 24) | 0xE0); - append((i >> 16) & 0xFF); - append((i >> 8) & 0xFF); - append(i & 0xFF); - } else if (i < 0x100000000LL) { - // It's a full 32-bit integer. - append(0xF0); - append((i >> 24) & 0xFF); - append((i >> 16) & 0xFF); - append((i >> 8) & 0xFF); - append(i & 0xFF); - } else { - // It's a 64-bit value. - append(0xF4); - append((i >> 56) & 0xFF); - append((i >> 48) & 0xFF); - append((i >> 40) & 0xFF); - append((i >> 32) & 0xFF); - append((i >> 24) & 0xFF); - append((i >> 16) & 0xFF); - append((i >> 8) & 0xFF); - append(i & 0xFF); - } - return *this; - } - - PacketDataStream &operator >>(quint64 &i) { - quint64 v = next(); - - if ((v & 0x80) == 0x00) { - i=(v & 0x7F); - } else if ((v & 0xC0) == 0x80) { - i=(v & 0x3F) << 8 | next(); - } else if ((v & 0xF0) == 0xF0) { - switch (v & 0xFC) { - case 0xF0: - i=next() << 24 | next() << 16 | next() << 8 | next(); - break; - case 0xF4: - i=next() << 56 | next() << 48 | next() << 40 | next() << 32 | next() << 24 | next() << 16 | next() << 8 | next(); - break; - case 0xF8: - *this >> i; - i = ~i; - break; - case 0xFC: - i=v & 0x03; - i = ~i; - break; - default: - ok = false; - i = 0; - break; - } - } else if ((v & 0xF0) == 0xE0) { - i=(v & 0x0F) << 24 | next() << 16 | next() << 8 | next(); - } else if ((v & 0xE0) == 0xC0) { - i=(v & 0x1F) << 16 | next() << 8 | next(); - } - return *this; - } - - PacketDataStream &operator <<(const QByteArray &a) { - *this << a.size(); - append(a.constData(), a.size()); - return *this; - } - - PacketDataStream &operator >>(QByteArray &a) { - quint32 len; - *this >> len; - if (len > left()) { - len = left(); - ok = false; + if (i < 0x80) { + // Need top bit clear + append(i); + } else if (i < 0x4000) { + // Need top two bits clear + append((i >> 8) | 0x80); + append(i & 0xFF); + } else if (i < 0x200000) { + // Need top three bits clear + append((i >> 16) | 0xC0); + append((i >> 8) & 0xFF); + append(i & 0xFF); + } else if (i < 0x10000000) { + // Need top four bits clear + append((i >> 24) | 0xE0); + append((i >> 16) & 0xFF); + append((i >> 8) & 0xFF); + append(i & 0xFF); + } else if (i < 0x100000000LL) { + // It's a full 32-bit integer. + append(0xF0); + append((i >> 24) & 0xFF); + append((i >> 16) & 0xFF); + append((i >> 8) & 0xFF); + append(i & 0xFF); + } else { + // It's a 64-bit value. + append(0xF4); + append((i >> 56) & 0xFF); + append((i >> 48) & 0xFF); + append((i >> 40) & 0xFF); + append((i >> 32) & 0xFF); + append((i >> 24) & 0xFF); + append((i >> 16) & 0xFF); + append((i >> 8) & 0xFF); + append(i & 0xFF); + } + return *this; + } + + PacketDataStream &operator>>(quint64 &i) { + quint64 v = next(); + + if ((v & 0x80) == 0x00) { + i = (v & 0x7F); + } else if ((v & 0xC0) == 0x80) { + i = (v & 0x3F) << 8 | next(); + } else if ((v & 0xF0) == 0xF0) { + switch (v & 0xFC) { + case 0xF0: + i = next() << 24 | next() << 16 | next() << 8 | next(); + break; + case 0xF4: + i = next() << 56 | next() << 48 | next() << 40 | next() << 32 | next() << 24 | next() << 16 + | next() << 8 | next(); + break; + case 0xF8: + *this >> i; + i = ~i; + break; + case 0xFC: + i = v & 0x03; + i = ~i; + break; + default: + ok = false; + i = 0; + break; } - a = QByteArray(reinterpret_cast<const char *>(& data[offset]), len); - offset+=len; - return *this; - } - - PacketDataStream &operator <<(const QString &s) { - return *this << s.toUtf8(); - } - - // Using the data directly instead of through qbuff avoids a copy. - PacketDataStream &operator >>(QString &s) { - quint32 len; - *this >> len; - if (len > left()) { - len = left(); + } else if ((v & 0xF0) == 0xE0) { + i = (v & 0x0F) << 24 | next() << 16 | next() << 8 | next(); + } else if ((v & 0xE0) == 0xC0) { + i = (v & 0x1F) << 16 | next() << 8 | next(); + } + return *this; + } + + PacketDataStream &operator<<(const QByteArray &a) { + *this << a.size(); + append(a.constData(), a.size()); + return *this; + } + + PacketDataStream &operator>>(QByteArray &a) { + quint32 len; + *this >> len; + if (len > left()) { + len = left(); + ok = false; + } + a = QByteArray(reinterpret_cast< const char * >(&data[offset]), len); + offset += len; + return *this; + } + + PacketDataStream &operator<<(const QString &s) { return *this << s.toUtf8(); } + + // Using the data directly instead of through qbuff avoids a copy. + PacketDataStream &operator>>(QString &s) { + quint32 len; + *this >> len; + if (len > left()) { + len = left(); + ok = false; + } + s = QString::fromUtf8(reinterpret_cast< const char * >(&data[offset]), len); + offset += len; + return *this; + } + + PacketDataStream &operator<<(const bool b) { + quint32 v = b ? 1 : 0; + return *this << v; + } + + PacketDataStream &operator>>(bool &b) { + quint32 v; + *this >> v; + b = v ? true : false; + return *this; + } + +#define INTMAPOPERATOR(type) \ + PacketDataStream &operator<<(const type v) { return *this << static_cast< quint64 >(v); } \ + PacketDataStream &operator>>(type &v) { \ + quint64 vv; \ + *this >> vv; \ + v = static_cast< type >(vv); \ + return *this; \ + } + + + INTMAPOPERATOR(int); + INTMAPOPERATOR(unsigned int); + INTMAPOPERATOR(short); + INTMAPOPERATOR(unsigned short); + INTMAPOPERATOR(char); + INTMAPOPERATOR(unsigned char); + + union double64u { + quint64 ui; + double d; + }; + + PacketDataStream &operator<<(const double v) { + double64u u; + u.d = v; + return *this << u.ui; + } + + PacketDataStream &operator>>(double &v) { + double64u u; + *this >> u.ui; + v = u.d; + return *this; + } + + union float32u { + quint8 ui[4]; + float f; + }; + + PacketDataStream &operator<<(const float v) { + float32u u; + u.f = v; + append(u.ui[0]); + append(u.ui[1]); + append(u.ui[2]); + append(u.ui[3]); + return *this; + } + + PacketDataStream &operator>>(float &v) { + float32u u; + if (left() < 4) { + ok = false; + v = 0; + } + u.ui[0] = next8(); + u.ui[1] = next8(); + u.ui[2] = next8(); + u.ui[3] = next8(); + v = u.f; + return *this; + } + + template< typename T > PacketDataStream &operator<<(const QList< T > &l) { + *this << l.size(); + for (int i = 0; i < l.size(); i++) + *this << l.at(i); + return *this; + } + + template< typename T > PacketDataStream &operator>>(QList< T > &l) { + l.clear(); + quint32 len; + *this >> len; + if (len > left()) { + len = left(); + ok = false; + } + for (quint32 i = 0; i < len; i++) { + if (left() == 0) { ok = false; + break; } - s = QString::fromUtf8(reinterpret_cast<const char *>(& data[offset]), len); - offset+=len; - return *this; - } - - PacketDataStream &operator <<(const bool b) { - quint32 v = b ? 1 : 0; - return *this << v; - } - - PacketDataStream &operator >>(bool &b) { - quint32 v; - *this >> v; - b = v ? true : false; - return *this; - } -#define INTMAPOPERATOR(type) \ - PacketDataStream &operator <<(const type v) { \ - return *this << static_cast<quint64>(v); \ - } \ - PacketDataStream &operator >>(type &v) { \ - quint64 vv; \ - *this >> vv; \ - v = static_cast<type>(vv); \ - return *this; \ + T t; + *this >> t; + l.append(t); } + return *this; + } - INTMAPOPERATOR(int); - INTMAPOPERATOR(unsigned int); - INTMAPOPERATOR(short); - INTMAPOPERATOR(unsigned short); - INTMAPOPERATOR(char); - INTMAPOPERATOR(unsigned char); - - union double64u { - quint64 ui; - double d; - }; - - PacketDataStream &operator <<(const double v) { - double64u u; - u.d = v; - return *this << u.ui; - } - - PacketDataStream &operator >>(double &v) { - double64u u; - *this >> u.ui; - v = u.d; - return *this; - } + template< typename T > PacketDataStream &operator<<(const QSet< T > &s) { + *this << s.size(); + for (typename QSet< T >::const_iterator i = s.constBegin(); i != s.constEnd(); ++i) + *this << *i; + return *this; + } - union float32u { - quint8 ui[4]; - float f; - }; - - PacketDataStream &operator <<(const float v) { - float32u u; - u.f = v; - append(u.ui[0]); - append(u.ui[1]); - append(u.ui[2]); - append(u.ui[3]); - return *this; + template< typename T > PacketDataStream &operator>>(QSet< T > &s) { + s.clear(); + quint32 len; + *this >> len; + if (len > left()) { + len = left(); + ok = false; } - - PacketDataStream &operator >>(float &v) { - float32u u; - if (left() < 4) { - ok = false; - v = 0; - } - u.ui[0] = next8(); - u.ui[1] = next8(); - u.ui[2] = next8(); - u.ui[3] = next8(); - v = u.f; - return *this; - } - - template <typename T> - PacketDataStream &operator <<(const QList<T> &l) { - *this << l.size(); - for (int i=0;i < l.size();i++) - *this << l.at(i); - return *this; - } - - template <typename T> - PacketDataStream &operator >>(QList<T> &l) { - l.clear(); - quint32 len; - *this >> len; - if (len > left()) { - len = left(); - ok = false; - } - for (quint32 i=0;i<len;i++) { - if (left() == 0) { - ok = false; - break; - } - - T t; - *this >> t; - l.append(t); - } - return *this; - } - - - template <typename T> - PacketDataStream &operator <<(const QSet<T> &s) { - *this << s.size(); - for (typename QSet<T>::const_iterator i=s.constBegin();i!=s.constEnd();++i) - *this << *i; - return *this; - } - - template <typename T> - PacketDataStream &operator >>(QSet<T> &s) { - s.clear(); - quint32 len; - *this >> len; - if (len > left()) { - len = left(); + for (quint32 i = 0; i < len; i++) { + if (left() == 0) { ok = false; + break; } - for (quint32 i=0;i<len;i++) { - if (left() == 0) { - ok = false; - break; - } - - T t; - *this >> t; - s.insert(t); - } - return *this; - } - template <typename T,typename U> - PacketDataStream &operator <<(const QPair<T,U> &p) { - return *this << p.first << p.second; + T t; + *this >> t; + s.insert(t); } + return *this; + } - template <typename T,typename U> - PacketDataStream &operator >>(QPair<T,U> &p) { - return *this >> p.first >> p.second; - } + template< typename T, typename U > PacketDataStream &operator<<(const QPair< T, U > &p) { + return *this << p.first << p.second; + } + template< typename T, typename U > PacketDataStream &operator>>(QPair< T, U > &p) { + return *this >> p.first >> p.second; + } }; #endif diff --git a/src/PasswordGenerator.cpp b/src/PasswordGenerator.cpp index 995c8d133..b0412670f 100644 --- a/src/PasswordGenerator.cpp +++ b/src/PasswordGenerator.cpp @@ -3,8 +3,8 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -#include "crypto/CryptographicRandom.h" #include "PasswordGenerator.h" +#include "crypto/CryptographicRandom.h" #include <QtCore/QVector> @@ -19,20 +19,18 @@ // "o" (lowercase O) // "l" (lowercase L) // "I" (uppercase i) -static char password_alphabet[] = { - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', +static char password_alphabet[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', + 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', + 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - '2', '3', '4', '6', '7', '8', '9' -}; + '2', '3', '4', '6', '7', '8', '9' }; // Getter function for TestPasswordGenerator to get the // alphabet we're using. -QVector<QChar> mumble_password_generator_alphabet() { - QVector<QChar> v; +QVector< QChar > mumble_password_generator_alphabet() { + QVector< QChar > v; size_t numAlphabetEntries = sizeof(password_alphabet); for (size_t i = 0; i < numAlphabetEntries; i++) { v << QChar(QLatin1Char(password_alphabet[i])); @@ -46,8 +44,8 @@ QString PasswordGenerator::generatePassword(int length) { uint32_t numAlphabetEntries = sizeof(password_alphabet); for (int i = 0; i < length; i++) { - uint32_t index = CryptographicRandom::uniform(numAlphabetEntries-1); - buf[i] = password_alphabet[index]; + uint32_t index = CryptographicRandom::uniform(numAlphabetEntries - 1); + buf[i] = password_alphabet[index]; } return QString::fromLatin1(buf.constData(), buf.size()); diff --git a/src/PasswordGenerator.h b/src/PasswordGenerator.h index 24b1935bb..15a350075 100644 --- a/src/PasswordGenerator.h +++ b/src/PasswordGenerator.h @@ -9,8 +9,8 @@ #include <QString> class PasswordGenerator { - public: - static QString generatePassword(int length); +public: + static QString generatePassword(int length); }; #endif diff --git a/src/PlatformCheck.h b/src/PlatformCheck.h index 07f3145bf..100db94e5 100644 --- a/src/PlatformCheck.h +++ b/src/PlatformCheck.h @@ -8,9 +8,9 @@ /// PlatformCheck performs platform checks. class PlatformCheck { - public: - /// IsWine returns true when running under Wine. - static bool IsWine(); +public: + /// IsWine returns true when running under Wine. + static bool IsWine(); }; #endif diff --git a/src/SSL.cpp b/src/SSL.cpp index 4cddc43f7..d44aa84a3 100644 --- a/src/SSL.cpp +++ b/src/SSL.cpp @@ -46,15 +46,15 @@ QString MumbleSSL::defaultOpenSSLCipherString() { return QLatin1String("EECDH+AESGCM:EDH+aRSA+AESGCM:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:AES256-SHA:AES128-SHA"); } -QList<QSslCipher> MumbleSSL::ciphersFromOpenSSLCipherString(QString cipherString) { - QList<QSslCipher> chosenCiphers; +QList< QSslCipher > MumbleSSL::ciphersFromOpenSSLCipherString(QString cipherString) { + QList< QSslCipher > chosenCiphers; - SSL_CTX *ctx = nullptr; - SSL *ssl = nullptr; + SSL_CTX *ctx = nullptr; + SSL *ssl = nullptr; const SSL_METHOD *meth = nullptr; - int i = 0; + int i = 0; - QByteArray csbuf = cipherString.toLatin1(); + QByteArray csbuf = cipherString.toLatin1(); const char *ciphers = csbuf.constData(); meth = SSLv23_server_method(); @@ -64,7 +64,7 @@ QList<QSslCipher> MumbleSSL::ciphersFromOpenSSLCipherString(QString cipherString } // We use const_cast to be compatible with OpenSSL 0.9.8. - ctx = SSL_CTX_new(const_cast<SSL_METHOD *>(meth)); + ctx = SSL_CTX_new(const_cast< SSL_METHOD * >(meth)); if (!ctx) { qWarning("MumbleSSL: unable to allocate SSL_CTX"); goto out; @@ -108,7 +108,7 @@ out: } void MumbleSSL::addSystemCA() { -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // Qt 5.15 introduced adding certificates to the QSslConfiguration and deprecated doing so on QSslSocket auto config = QSslConfiguration::defaultConfiguration(); @@ -124,13 +124,13 @@ void MumbleSSL::addSystemCA() { // Skype's click-to-call feature creates an enormous // amount of certificates in the Root CA store. { - QSslConfiguration sslCfg = QSslConfiguration::defaultConfiguration(); - QList<QSslCertificate> caList = sslCfg.caCertificates(); + QSslConfiguration sslCfg = QSslConfiguration::defaultConfiguration(); + QList< QSslCertificate > caList = sslCfg.caCertificates(); - QList<QSslCertificate> filteredCaList; + QList< QSslCertificate > filteredCaList; foreach (QSslCertificate cert, caList) { QStringList orgs = cert.subjectInfo(QSslCertificate::Organization); - bool skip = false; + bool skip = false; foreach (QString ou, orgs) { if (ou.contains(QLatin1String("Skype"), Qt::CaseInsensitive)) { skip = true; @@ -147,25 +147,36 @@ void MumbleSSL::addSystemCA() { sslCfg.setCaCertificates(filteredCaList); QSslConfiguration::setDefaultConfiguration(sslCfg); - qWarning("SSL: CA certificate filter applied. Filtered size: %i, original size: %i", filteredCaList.size(), caList.size()); + qWarning("SSL: CA certificate filter applied. Filtered size: %i, original size: %i", filteredCaList.size(), + caList.size()); } #endif } QString MumbleSSL::protocolToString(QSsl::SslProtocol protocol) { - switch(protocol) { - case QSsl::SslV3: return QLatin1String("SSL 3"); - case QSsl::SslV2: return QLatin1String("SSL 2"); - case QSsl::TlsV1_0: return QLatin1String("TLS 1.0"); - case QSsl::TlsV1_1: return QLatin1String("TLS 1.1"); - case QSsl::TlsV1_2: return QLatin1String("TLS 1.2"); + switch (protocol) { + case QSsl::SslV3: + return QLatin1String("SSL 3"); + case QSsl::SslV2: + return QLatin1String("SSL 2"); + case QSsl::TlsV1_0: + return QLatin1String("TLS 1.0"); + case QSsl::TlsV1_1: + return QLatin1String("TLS 1.1"); + case QSsl::TlsV1_2: + return QLatin1String("TLS 1.2"); #if QT_VERSION >= 0x050C00 - case QSsl::TlsV1_3: return QLatin1String("TLS 1.3"); + case QSsl::TlsV1_3: + return QLatin1String("TLS 1.3"); #endif - case QSsl::AnyProtocol: return QLatin1String("AnyProtocol"); - case QSsl::TlsV1SslV3: return QLatin1String("TlsV1SslV3"); - case QSsl::SecureProtocols: return QLatin1String("SecureProtocols"); + case QSsl::AnyProtocol: + return QLatin1String("AnyProtocol"); + case QSsl::TlsV1SslV3: + return QLatin1String("TlsV1SslV3"); + case QSsl::SecureProtocols: + return QLatin1String("SecureProtocols"); default: - case QSsl::UnknownProtocol: return QLatin1String("UnknownProtocol"); + case QSsl::UnknownProtocol: + return QLatin1String("UnknownProtocol"); } } @@ -6,18 +6,18 @@ #ifndef MUMBLE_SSL_H_ #define MUMBLE_SSL_H_ -#include <QString> #include <QList> #include <QSslCipher> +#include <QString> class MumbleSSL { - public: - static void initialize(); - static void destroy(); - static QString defaultOpenSSLCipherString(); - static QList<QSslCipher> ciphersFromOpenSSLCipherString(QString cipherString); - static void addSystemCA(); - static QString protocolToString(QSsl::SslProtocol protocol); +public: + static void initialize(); + static void destroy(); + static QString defaultOpenSSLCipherString(); + static QList< QSslCipher > ciphersFromOpenSSLCipherString(QString cipherString); + static void addSystemCA(); + static QString protocolToString(QSsl::SslProtocol protocol); }; #endif diff --git a/src/SSLLocks.cpp b/src/SSLLocks.cpp index 5ffc3cfdd..b2681c071 100644 --- a/src/SSLLocks.cpp +++ b/src/SSLLocks.cpp @@ -42,14 +42,14 @@ unsigned long id_callback() { // convert to that without the compiler complaining. Then, we convert // *that* to an unsigned long. (Note that for LLP64 platforms, such as // 64-bit Windows, this conversion is from a 64-bit type to a 32-bit type) - uintptr_t val = reinterpret_cast<uintptr_t>(QThread::currentThreadId()); - return static_cast<unsigned long>(val); + uintptr_t val = reinterpret_cast< uintptr_t >(QThread::currentThreadId()); + return static_cast< unsigned long >(val); } void SSLLocks::initialize() { int nlocks = CRYPTO_num_locks(); - locks = reinterpret_cast<QMutex **>(calloc(nlocks, sizeof(QMutex *))); + locks = reinterpret_cast< QMutex ** >(calloc(nlocks, sizeof(QMutex *))); if (!locks) { qFatal("SSLLocks: unable to allocate locks array"); diff --git a/src/SSLLocks.h b/src/SSLLocks.h index 51fb4a820..11eecba2f 100644 --- a/src/SSLLocks.h +++ b/src/SSLLocks.h @@ -7,9 +7,9 @@ #define MUMBLE_SSLLOCKS_H_ class SSLLocks { - public: - static void initialize(); - static void destroy(); +public: + static void initialize(); + static void destroy(); }; #endif diff --git a/src/SelfSignedCertificate.cpp b/src/SelfSignedCertificate.cpp index cbdcf7528..a68058205 100644 --- a/src/SelfSignedCertificate.cpp +++ b/src/SelfSignedCertificate.cpp @@ -9,7 +9,7 @@ #define SSL_STRING(x) QString::fromLatin1(x).toUtf8().data() -static int add_ext(X509 * crt, int nid, char *value) { +static int add_ext(X509 *crt, int nid, char *value) { X509V3_CTX ctx; X509V3_set_ctx_nodb(&ctx); X509V3_set_ctx(&ctx, crt, crt, nullptr, nullptr, 0); @@ -28,16 +28,17 @@ static int add_ext(X509 * crt, int nid, char *value) { return 1; } -bool SelfSignedCertificate::generate(CertificateType certificateType, QString clientCertName, QString clientCertEmail, QSslCertificate &qscCert, QSslKey &qskKey) { - bool ok = true; - X509 *x509 = nullptr; - EVP_PKEY *pkey = nullptr; - RSA *rsa = nullptr; - BIGNUM *e = nullptr; - X509_NAME *name = nullptr; +bool SelfSignedCertificate::generate(CertificateType certificateType, QString clientCertName, QString clientCertEmail, + QSslCertificate &qscCert, QSslKey &qskKey) { + bool ok = true; + X509 *x509 = nullptr; + EVP_PKEY *pkey = nullptr; + RSA *rsa = nullptr; + BIGNUM *e = nullptr; + X509_NAME *name = nullptr; ASN1_INTEGER *serialNumber = nullptr; - ASN1_TIME *notBefore = nullptr; - ASN1_TIME *notAfter = nullptr; + ASN1_TIME *notBefore = nullptr; + ASN1_TIME *notAfter = nullptr; QString commonName; bool isServerCert = certificateType == CertificateTypeServerCertificate; @@ -114,7 +115,7 @@ bool SelfSignedCertificate::generate(CertificateType certificateType, QString cl ok = false; goto out; } - if (!X509_gmtime_adj(notAfter, 60*60*24*365*20)) { + if (!X509_gmtime_adj(notAfter, 60 * 60 * 24 * 365 * 20)) { ok = false; goto out; } @@ -140,7 +141,9 @@ bool SelfSignedCertificate::generate(CertificateType certificateType, QString cl } } - if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(commonName.toUtf8().data()), -1, -1, 0) == 0) { + if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, + reinterpret_cast< unsigned char * >(commonName.toUtf8().data()), -1, -1, 0) + == 0) { ok = false; goto out; } @@ -186,7 +189,9 @@ bool SelfSignedCertificate::generate(CertificateType certificateType, QString cl if (!isServerCert) { if (!clientCertEmail.trimmed().isEmpty()) { - if (add_ext(x509, NID_subject_alt_name, QString::fromLatin1("email:%1").arg(clientCertEmail).toUtf8().data()) == 0) { + if (add_ext(x509, NID_subject_alt_name, + QString::fromLatin1("email:%1").arg(clientCertEmail).toUtf8().data()) + == 0) { ok = false; goto out; } @@ -207,7 +212,7 @@ bool SelfSignedCertificate::generate(CertificateType certificateType, QString cl } crt.resize(len); - unsigned char *dptr = reinterpret_cast<unsigned char *>(crt.data()); + unsigned char *dptr = reinterpret_cast< unsigned char * >(crt.data()); if (i2d_X509(x509, &dptr) != len) { ok = false; goto out; @@ -229,7 +234,7 @@ bool SelfSignedCertificate::generate(CertificateType certificateType, QString cl } key.resize(len); - unsigned char *dptr = reinterpret_cast<unsigned char *>(key.data()); + unsigned char *dptr = reinterpret_cast< unsigned char * >(key.data()); if (i2d_PrivateKey(pkey, &dptr) != len) { ok = false; goto out; @@ -259,13 +264,14 @@ out: if (!ok) { qscCert = QSslCertificate(); - qskKey = QSslKey(); + qskKey = QSslKey(); } return ok; } -bool SelfSignedCertificate::generateMumbleCertificate(QString name, QString email, QSslCertificate &qscCert, QSslKey &qskKey) { +bool SelfSignedCertificate::generateMumbleCertificate(QString name, QString email, QSslCertificate &qscCert, + QSslKey &qskKey) { return SelfSignedCertificate::generate(CertificateTypeClientCertificate, name, email, qscCert, qskKey); } diff --git a/src/SelfSignedCertificate.h b/src/SelfSignedCertificate.h index 84abbf1a3..6ce84723b 100644 --- a/src/SelfSignedCertificate.h +++ b/src/SelfSignedCertificate.h @@ -14,7 +14,8 @@ enum CertificateType { CertificateTypeServerCertificate, CertificateTypeClientCe class SelfSignedCertificate { private: - static bool generate(CertificateType certificateType, QString clientCertName, QString clientCertEmail, QSslCertificate &qscCert, QSslKey &qskKey); + static bool generate(CertificateType certificateType, QString clientCertName, QString clientCertEmail, + QSslCertificate &qscCert, QSslKey &qskKey); public: static bool generateMumbleCertificate(QString name, QString email, QSslCertificate &qscCert, QSslKey &qskKey); diff --git a/src/ServerAddress.cpp b/src/ServerAddress.cpp index 9d3fc079e..5eda76ec3 100644 --- a/src/ServerAddress.cpp +++ b/src/ServerAddress.cpp @@ -5,12 +5,11 @@ #include "ServerAddress.h" -ServerAddress::ServerAddress() - : port(0) {} +ServerAddress::ServerAddress() : port(0) { +} -ServerAddress::ServerAddress(HostAddress host_, unsigned short port_) - : host(host_) - , port(port_) {} +ServerAddress::ServerAddress(HostAddress host_, unsigned short port_) : host(host_), port(port_) { +} bool ServerAddress::isValid() const { return host.isValid() && port != 0; diff --git a/src/ServerResolver.cpp b/src/ServerResolver.cpp index 7064702e6..544677e54 100644 --- a/src/ServerResolver.cpp +++ b/src/ServerResolver.cpp @@ -9,46 +9,43 @@ #include <QtNetwork/QHostInfo> static qint64 normalizeSrvPriority(quint16 priority, quint16 weight) { - return static_cast<qint64>((65535U * priority) + weight); + return static_cast< qint64 >((65535U * priority) + weight); } class ServerResolverPrivate : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(ServerResolverPrivate) - public: - ServerResolverPrivate(QObject *parent); +private: + Q_OBJECT + Q_DISABLE_COPY(ServerResolverPrivate) +public: + ServerResolverPrivate(QObject *parent); - void resolve(QString hostname, quint16 port); - QList<ServerResolverRecord> records(); + void resolve(QString hostname, quint16 port); + QList< ServerResolverRecord > records(); - QString m_origHostname; - quint16 m_origPort; + QString m_origHostname; + quint16 m_origPort; - QList<QDnsServiceRecord> m_srvQueue; - QMap<int, int> m_hostInfoIdToIndexMap; - int m_srvQueueRemain; + QList< QDnsServiceRecord > m_srvQueue; + QMap< int, int > m_hostInfoIdToIndexMap; + int m_srvQueueRemain; - QList<ServerResolverRecord> m_resolved; + QList< ServerResolverRecord > m_resolved; - signals: - void resolved(); +signals: + void resolved(); - public slots: - void srvResolved(); - void hostResolved(QHostInfo hostInfo); - void hostFallbackResolved(QHostInfo hostInfo); +public slots: + void srvResolved(); + void hostResolved(QHostInfo hostInfo); + void hostFallbackResolved(QHostInfo hostInfo); }; -ServerResolverPrivate::ServerResolverPrivate(QObject *parent) - : QObject(parent) - , m_origPort(0) - , m_srvQueueRemain(0) { +ServerResolverPrivate::ServerResolverPrivate(QObject *parent) : QObject(parent), m_origPort(0), m_srvQueueRemain(0) { } void ServerResolverPrivate::resolve(QString hostname, quint16 port) { m_origHostname = hostname; - m_origPort = port; + m_origPort = port; QDnsLookup *resolver = new QDnsLookup(this); connect(resolver, SIGNAL(finished()), this, SLOT(srvResolved())); @@ -58,20 +55,20 @@ void ServerResolverPrivate::resolve(QString hostname, quint16 port) { resolver->lookup(); } -QList<ServerResolverRecord> ServerResolverPrivate::records() { +QList< ServerResolverRecord > ServerResolverPrivate::records() { return m_resolved; } void ServerResolverPrivate::srvResolved() { - QDnsLookup *resolver = qobject_cast<QDnsLookup *>(sender()); + QDnsLookup *resolver = qobject_cast< QDnsLookup * >(sender()); - m_srvQueue = resolver->serviceRecords(); + m_srvQueue = resolver->serviceRecords(); m_srvQueueRemain = m_srvQueue.count(); if (resolver->error() == QDnsLookup::NoError && m_srvQueueRemain > 0) { for (int i = 0; i < m_srvQueue.count(); i++) { QDnsServiceRecord record = m_srvQueue.at(i); - int hostInfoId = QHostInfo::lookupHost(record.target(), this, SLOT(hostResolved(QHostInfo))); + int hostInfoId = QHostInfo::lookupHost(record.target(), this, SLOT(hostResolved(QHostInfo))); m_hostInfoIdToIndexMap[hostInfoId] = i; } } else { @@ -82,18 +79,16 @@ void ServerResolverPrivate::srvResolved() { } void ServerResolverPrivate::hostResolved(QHostInfo hostInfo) { - int lookupId = hostInfo.lookupId(); - int idx = m_hostInfoIdToIndexMap[lookupId]; + int lookupId = hostInfo.lookupId(); + int idx = m_hostInfoIdToIndexMap[lookupId]; QDnsServiceRecord record = m_srvQueue.at(idx); if (hostInfo.error() == QHostInfo::NoError) { - QList<QHostAddress> resolvedAddresses = hostInfo.addresses(); - + QList< QHostAddress > resolvedAddresses = hostInfo.addresses(); + // Convert QHostAddress -> HostAddress. - QList<HostAddress> addresses; - foreach (QHostAddress ha, resolvedAddresses) { - addresses << HostAddress(ha); - } + QList< HostAddress > addresses; + foreach (QHostAddress ha, resolvedAddresses) { addresses << HostAddress(ha); } qint64 priority = normalizeSrvPriority(record.priority(), record.weight()); m_resolved << ServerResolverRecord(m_origHostname, record.port(), priority, addresses); @@ -107,13 +102,11 @@ void ServerResolverPrivate::hostResolved(QHostInfo hostInfo) { void ServerResolverPrivate::hostFallbackResolved(QHostInfo hostInfo) { if (hostInfo.error() == QHostInfo::NoError) { - QList<QHostAddress> resolvedAddresses = hostInfo.addresses(); - + QList< QHostAddress > resolvedAddresses = hostInfo.addresses(); + // Convert QHostAddress -> HostAddress. - QList<HostAddress> addresses; - foreach (QHostAddress ha, resolvedAddresses) { - addresses << HostAddress(ha); - } + QList< HostAddress > addresses; + foreach (QHostAddress ha, resolvedAddresses) { addresses << HostAddress(ha); } m_resolved << ServerResolverRecord(m_origHostname, m_origPort, 0, addresses); } @@ -121,9 +114,7 @@ void ServerResolverPrivate::hostFallbackResolved(QHostInfo hostInfo) { emit resolved(); } -ServerResolver::ServerResolver(QObject *parent) - : QObject(parent) { - +ServerResolver::ServerResolver(QObject *parent) : QObject(parent) { d = new ServerResolverPrivate(this); } @@ -150,11 +141,11 @@ void ServerResolver::resolve(QString hostname, quint16 port) { } } -QList<ServerResolverRecord> ServerResolver::records() { +QList< ServerResolverRecord > ServerResolver::records() { if (d) { return d->records(); } - return QList<ServerResolverRecord>(); + return QList< ServerResolverRecord >(); } #include "ServerResolver.moc" diff --git a/src/ServerResolver.h b/src/ServerResolver.h index 9d00ea859..e67faed7e 100644 --- a/src/ServerResolver.h +++ b/src/ServerResolver.h @@ -6,9 +6,9 @@ #ifndef MUMBLE_MUMBLE_SERVERRESOLVER_H_ #define MUMBLE_MUMBLE_SERVERRESOLVER_H_ +#include <QtCore/QList> #include <QtCore/QObject> #include <QtCore/QString> -#include <QtCore/QList> #include "Net.h" // for HostAddress #include "ServerResolverRecord.h" @@ -16,25 +16,25 @@ class ServerResolverPrivate; class ServerResolver : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(ServerResolver) - public: - ServerResolver(QObject *parent = nullptr); +private: + Q_OBJECT + Q_DISABLE_COPY(ServerResolver) +public: + ServerResolver(QObject *parent = nullptr); - QString hostname(); - quint16 port(); + QString hostname(); + quint16 port(); - void resolve(QString hostname, quint16 port); - QList<ServerResolverRecord> records(); + void resolve(QString hostname, quint16 port); + QList< ServerResolverRecord > records(); - signals: - /// Resolved is fired once the ServerResolver - /// has resolved the server address. - void resolved(); +signals: + /// Resolved is fired once the ServerResolver + /// has resolved the server address. + void resolved(); - private: - ServerResolverPrivate *d; +private: + ServerResolverPrivate *d; }; #endif diff --git a/src/ServerResolverRecord.cpp b/src/ServerResolverRecord.cpp index b0534d558..be743597e 100644 --- a/src/ServerResolverRecord.cpp +++ b/src/ServerResolverRecord.cpp @@ -8,11 +8,9 @@ ServerResolverRecord::ServerResolverRecord() { } -ServerResolverRecord::ServerResolverRecord(QString hostname_, quint16 port_, qint64 priority_, QList<HostAddress> addresses_) - : m_hostname(hostname_) - , m_port(port_) - , m_priority(priority_) - , m_addresses(addresses_) { +ServerResolverRecord::ServerResolverRecord(QString hostname_, quint16 port_, qint64 priority_, + QList< HostAddress > addresses_) + : m_hostname(hostname_), m_port(port_), m_priority(priority_), m_addresses(addresses_) { } qint64 ServerResolverRecord::priority() { @@ -27,6 +25,6 @@ quint16 ServerResolverRecord::port() { return m_port; } -QList<HostAddress> ServerResolverRecord::addresses() { +QList< HostAddress > ServerResolverRecord::addresses() { return m_addresses; } diff --git a/src/ServerResolverRecord.h b/src/ServerResolverRecord.h index 6b8245ed0..baf5bf7be 100644 --- a/src/ServerResolverRecord.h +++ b/src/ServerResolverRecord.h @@ -6,26 +6,26 @@ #ifndef MUMBLE_MUMBLE_SERVERRESOLVERRECORD_H_ #define MUMBLE_MUMBLE_SERVERRESOLVERRECORD_H_ -#include <QtCore/QString> #include <QtCore/QList> +#include <QtCore/QString> #include "Net.h" // for HostAddress class ServerResolverRecord { - public: - ServerResolverRecord(); - ServerResolverRecord(QString hostname_, quint16 port_, qint64 priority_, QList<HostAddress> addresses_); +public: + ServerResolverRecord(); + ServerResolverRecord(QString hostname_, quint16 port_, qint64 priority_, QList< HostAddress > addresses_); - QString hostname(); - quint16 port(); - qint64 priority(); - QList<HostAddress> addresses(); + QString hostname(); + quint16 port(); + qint64 priority(); + QList< HostAddress > addresses(); - protected: - QString m_hostname; - quint16 m_port; - qint64 m_priority; - QList<HostAddress> m_addresses; +protected: + QString m_hostname; + quint16 m_port; + qint64 m_priority; + QList< HostAddress > m_addresses; }; #endif diff --git a/src/SignalCurry.h b/src/SignalCurry.h index d437d730c..1b5d9d3e0 100644 --- a/src/SignalCurry.h +++ b/src/SignalCurry.h @@ -20,11 +20,10 @@ class SignalCurry : public QObject { private: bool bDeleteAfterFirstUse; QVariant qvData; + public: SignalCurry(QVariant data, bool deleteAfterFirstUse = false, QObject *p = 0) - : QObject(p) - , bDeleteAfterFirstUse(deleteAfterFirstUse) - , qvData(data) {} + : QObject(p), bDeleteAfterFirstUse(deleteAfterFirstUse), qvData(data) {} static void curry(QObject *sender, const char *signal, QObject *receiver, const char *slot, QVariant data) { SignalCurry *c = new SignalCurry(data); @@ -37,7 +36,8 @@ signals: public slots: void call() { emit called(qvData); - if (bDeleteAfterFirstUse) deleteLater(); + if (bDeleteAfterFirstUse) + deleteLater(); } }; diff --git a/src/SpeechFlags.h b/src/SpeechFlags.h index c2b06a365..c79def1ab 100644 --- a/src/SpeechFlags.h +++ b/src/SpeechFlags.h @@ -7,13 +7,13 @@ #define MUMBLE_SPEECHFLAGS_H_ namespace SpeechFlags { - enum SpeechFlags { - Invalid = 0xFF, // This is the unsigned equivalent of -1 - Normal = 0, - Shout = 1, - Whisper = 2, - Listen = 3 - }; +enum SpeechFlags { + Invalid = 0xFF, // This is the unsigned equivalent of -1 + Normal = 0, + Shout = 1, + Whisper = 2, + Listen = 3 +}; }; // namespace SpeechFlags #endif // MUMBLE_SPEECHFLAGS_H_ diff --git a/src/Timer.cpp b/src/Timer.cpp index 7730aa008..1311edf7b 100644 --- a/src/Timer.cpp +++ b/src/Timer.cpp @@ -17,7 +17,7 @@ // vs. // https://github.com/boostorg/system/blob/boost-1.55.0/include/boost/system/error_code.hpp#L515-L517 #if BOOST_VERSION >= 105600 && !defined(__MINGW32__) -# define USE_BOOST_CHRONO +# define USE_BOOST_CHRONO #endif #include "Timer.h" @@ -43,7 +43,7 @@ bool Timer::isElapsed(quint64 us) { quint64 Timer::restart() { quint64 n = now(); quint64 e = n - uiStart; - uiStart = n; + uiStart = n; return e; } @@ -61,22 +61,22 @@ bool Timer::operator>(const Timer &other) const { #ifdef USE_BOOST_CHRONO // Ensure boost_system is header only. -#define BOOST_ERROR_CODE_HEADER_ONLY +# define BOOST_ERROR_CODE_HEADER_ONLY // Ensure boost_chrono is header only. -#define BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -#define BOOST_CHRONO_HEADER_ONLY +# define BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING +# define BOOST_CHRONO_HEADER_ONLY -#include <boost/chrono.hpp> +# include <boost/chrono.hpp> quint64 Timer::now() { using namespace boost::chrono; - time_point<steady_clock> now = steady_clock::now(); - time_point<steady_clock>::duration epochDuration = now.time_since_epoch(); - microseconds epochDurationUsec = duration_cast<microseconds>(epochDuration); - return static_cast<quint64>(epochDurationUsec.count()); + time_point< steady_clock > now = steady_clock::now(); + time_point< steady_clock >::duration epochDuration = now.time_since_epoch(); + microseconds epochDurationUsec = duration_cast< microseconds >(epochDuration); + return static_cast< quint64 >(epochDurationUsec.count()); } #elif defined(Q_OS_WIN) -# include "win.h" +# include "win.h" quint64 Timer::now() { static double scale = 0; @@ -91,14 +91,14 @@ quint64 Timer::now() { QueryPerformanceCounter(&li); quint64 e = li.QuadPart; - return static_cast<quint64>(e * scale); + return static_cast< quint64 >(e * scale); } #elif defined(Q_OS_UNIX) -# include <errno.h> -# include <string.h> -# include <unistd.h> -# include <sys/time.h> -# if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) +# include <errno.h> +# include <string.h> +# include <sys/time.h> +# include <unistd.h> +# if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) quint64 Timer::now() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { @@ -108,15 +108,15 @@ quint64 Timer::now() { e += ts.tv_nsec / 1000LL; return e; } -# else +# else quint64 Timer::now() { struct timeval tv; gettimeofday(&tv, nullptr); - quint64 e= tv.tv_sec * 1000000LL; + quint64 e = tv.tv_sec * 1000000LL; e += tv.tv_usec; return e; } -# endif +# endif #else quint64 Timer::now() { static QTime ticker; diff --git a/src/Timer.h b/src/Timer.h index e31210484..b7ea31f24 100644 --- a/src/Timer.h +++ b/src/Timer.h @@ -11,25 +11,26 @@ // All timer resolutions are in microseconds. class Timer { - protected: - quint64 uiStart; - static quint64 now(); - public: - Timer(bool start = true); - bool isElapsed(quint64 us); - quint64 elapsed() const; - quint64 restart(); - bool isStarted() const; - - /** - * Compares the elapsed time, not the start time - */ - bool operator<(const Timer &other) const; - - /** - * Compares the elapsed time, not the start time - */ - bool operator>(const Timer &other) const; +protected: + quint64 uiStart; + static quint64 now(); + +public: + Timer(bool start = true); + bool isElapsed(quint64 us); + quint64 elapsed() const; + quint64 restart(); + bool isStarted() const; + + /** + * Compares the elapsed time, not the start time + */ + bool operator<(const Timer &other) const; + + /** + * Compares the elapsed time, not the start time + */ + bool operator>(const Timer &other) const; }; #endif diff --git a/src/UnresolvedServerAddress.cpp b/src/UnresolvedServerAddress.cpp index 1fa2917b9..9b578980a 100644 --- a/src/UnresolvedServerAddress.cpp +++ b/src/UnresolvedServerAddress.cpp @@ -7,12 +7,12 @@ #include <QtCore/QHash> -UnresolvedServerAddress::UnresolvedServerAddress() - : port(0) {} +UnresolvedServerAddress::UnresolvedServerAddress() : port(0) { +} UnresolvedServerAddress::UnresolvedServerAddress(QString hostname_, unsigned short port_) - : hostname(hostname_.toLower()) - , port(port_) {} + : hostname(hostname_.toLower()), port(port_) { +} bool UnresolvedServerAddress::isValid() const { return !hostname.isEmpty() && port != 0; diff --git a/src/User.cpp b/src/User.cpp index f6d90dc06..52cfb9824 100644 --- a/src/User.cpp +++ b/src/User.cpp @@ -8,13 +8,13 @@ User::User() { uiSession = 0; - iId = -1; + iId = -1; bMute = bDeaf = false; bSelfMute = bSelfDeaf = false; - bPrioritySpeaker = false; - bRecording = false; - bSuppress = false; - cChannel = 0; + bPrioritySpeaker = false; + bRecording = false; + bSuppress = false; + cChannel = 0; } bool User::lessThan(const User *first, const User *second) { diff --git a/src/User.h b/src/User.h index b1c61b181..469cc8d45 100644 --- a/src/User.h +++ b/src/User.h @@ -7,46 +7,46 @@ #define MUMBLE_USER_H_ #ifndef Q_MOC_RUN -# include <boost/optional.hpp> +# include <boost/optional.hpp> #endif #include <QtCore/QByteArray> #include <QtCore/QDateTime> -#include <QtCore/QString> #include <QtCore/QList> +#include <QtCore/QString> class Channel; class User { - private: - Q_DISABLE_COPY(User) - - public: - unsigned int uiSession; - int iId; - QString qsName; - QString qsComment; - QByteArray qbaCommentHash; - QString qsHash; - bool bMute, bDeaf, bSuppress; - bool bSelfMute, bSelfDeaf; - bool bPrioritySpeaker; - bool bRecording; - Channel *cChannel; - QByteArray qbaTexture; - QByteArray qbaTextureHash; - - User(); - virtual ~User() {}; - - static bool lessThan(const User *, const User *); +private: + Q_DISABLE_COPY(User) + +public: + unsigned int uiSession; + int iId; + QString qsName; + QString qsComment; + QByteArray qbaCommentHash; + QString qsHash; + bool bMute, bDeaf, bSuppress; + bool bSelfMute, bSelfDeaf; + bool bPrioritySpeaker; + bool bRecording; + Channel *cChannel; + QByteArray qbaTexture; + QByteArray qbaTextureHash; + + User(); + virtual ~User(){}; + + static bool lessThan(const User *, const User *); }; // for last seen struct UserInfo { int user_id; QString name; - boost::optional<int> last_channel; + boost::optional< int > last_channel; QDateTime last_active; UserInfo() : user_id(-1) {} diff --git a/src/Utils.h b/src/Utils.h index c74c46d7f..233214764 100644 --- a/src/Utils.h +++ b/src/Utils.h @@ -3,27 +3,28 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -// This header file defines common utility macros and values that are generally valid or used across multiple areas giving them generic scope (rather than localized or functionality-specific scope). +// This header file defines common utility macros and values that are generally valid or used across multiple areas +// giving them generic scope (rather than localized or functionality-specific scope). #ifndef MUMBLE_UTILS_H_ #define MUMBLE_UTILS_H_ #include <QtCore/QtGlobal> -#define iroundf(x) ( static_cast<int>(x) ) +#define iroundf(x) (static_cast< int >(x)) #ifdef Q_OS_WIN -# define STACKVAR(type, varname, count) type *varname=reinterpret_cast<type *>(_alloca(sizeof(type) * (count))) +# define STACKVAR(type, varname, count) type *varname = reinterpret_cast< type * >(_alloca(sizeof(type) * (count))) #else -# ifdef WId - typedef WId HWND; -# endif -# define __cdecl -# define INVALID_SOCKET -1 -# define SOCKET_ERROR -1 -# define STACKVAR(type, varname, count) type varname[count] -# define CopyMemory(dst,ptr,len) memcpy(dst,ptr,len) -# define ZeroMemory(ptr,len) memset(ptr, 0, len) +# ifdef WId +typedef WId HWND; +# endif +# define __cdecl +# define INVALID_SOCKET -1 +# define SOCKET_ERROR -1 +# define STACKVAR(type, varname, count) type varname[count] +# define CopyMemory(dst, ptr, len) memcpy(dst, ptr, len) +# define ZeroMemory(ptr, len) memset(ptr, 0, len) #endif #endif // MUMBLE_UTILS_H_ diff --git a/src/Version.h b/src/Version.h index e0f83d42b..26f114524 100644 --- a/src/Version.h +++ b/src/Version.h @@ -12,19 +12,20 @@ #define MUMTEXT(X) MUMXTEXT(X) #ifndef MUMBLE_VERSION -#define MUMBLE_RELEASE "Compiled by User" +# define MUMBLE_RELEASE "Compiled by User" #else -#define MUMBLE_RELEASE MUMTEXT(MUMBLE_VERSION) +# define MUMBLE_RELEASE MUMTEXT(MUMBLE_VERSION) #endif class MumbleVersion { - public: - static unsigned int getRaw(const QString &version = QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); - static QString toString(unsigned int version); - static bool get(int *major, int *minor, int *patch, const QString &version = QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); +public: + static unsigned int getRaw(const QString &version = QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); + static QString toString(unsigned int version); + static bool get(int *major, int *minor, int *patch, + const QString &version = QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); - static unsigned int toRaw(int major, int minor, int patch); - static void fromRaw(unsigned int version, int *major, int *minor, int *patch); + static unsigned int toRaw(int major, int minor, int patch); + static void fromRaw(unsigned int version, int *major, int *minor, int *patch); }; #endif diff --git a/src/crypto/CryptState.h b/src/crypto/CryptState.h index 49cd42dc6..e050ea63b 100644 --- a/src/crypto/CryptState.h +++ b/src/crypto/CryptState.h @@ -10,37 +10,37 @@ #include <string> class CryptState { - private: - Q_DISABLE_COPY(CryptState) - public: - unsigned int uiGood = 0; - unsigned int uiLate = 0; - unsigned int uiLost = 0; - unsigned int uiResync = 0; - - unsigned int uiRemoteGood = 0; - unsigned int uiRemoteLate = 0; - unsigned int uiRemoteLost = 0; - unsigned int uiRemoteResync = 0; - - Timer tLastGood; - Timer tLastRequest; - bool bInit = false; - CryptState() {}; - virtual ~CryptState() {}; - - virtual bool isValid() const = 0; - virtual void genKey() = 0; - virtual bool setKey(const std::string& rkey, const std::string& eiv, const std::string& div) = 0; - virtual bool setRawKey(const std::string& rkey) = 0; - virtual bool setEncryptIV(const std::string& iv) = 0; - virtual bool setDecryptIV(const std::string& iv) = 0; - virtual std::string getRawKey() = 0; - virtual std::string getEncryptIV() = 0; - virtual std::string getDecryptIV() = 0; - - virtual bool decrypt(const unsigned char *source, unsigned char *dst, unsigned int crypted_length) = 0; - virtual bool encrypt(const unsigned char *source, unsigned char *dst, unsigned int plain_length) = 0; +private: + Q_DISABLE_COPY(CryptState) +public: + unsigned int uiGood = 0; + unsigned int uiLate = 0; + unsigned int uiLost = 0; + unsigned int uiResync = 0; + + unsigned int uiRemoteGood = 0; + unsigned int uiRemoteLate = 0; + unsigned int uiRemoteLost = 0; + unsigned int uiRemoteResync = 0; + + Timer tLastGood; + Timer tLastRequest; + bool bInit = false; + CryptState(){}; + virtual ~CryptState(){}; + + virtual bool isValid() const = 0; + virtual void genKey() = 0; + virtual bool setKey(const std::string &rkey, const std::string &eiv, const std::string &div) = 0; + virtual bool setRawKey(const std::string &rkey) = 0; + virtual bool setEncryptIV(const std::string &iv) = 0; + virtual bool setDecryptIV(const std::string &iv) = 0; + virtual std::string getRawKey() = 0; + virtual std::string getEncryptIV() = 0; + virtual std::string getDecryptIV() = 0; + + virtual bool decrypt(const unsigned char *source, unsigned char *dst, unsigned int crypted_length) = 0; + virtual bool encrypt(const unsigned char *source, unsigned char *dst, unsigned int plain_length) = 0; }; diff --git a/src/crypto/CryptStateOCB2.cpp b/src/crypto/CryptStateOCB2.cpp index 0e8dd019b..fb1b892e7 100644 --- a/src/crypto/CryptStateOCB2.cpp +++ b/src/crypto/CryptStateOCB2.cpp @@ -15,22 +15,22 @@ #include <QtCore/QtGlobal> #ifndef __LP64__ -# ifdef Q_OS_WIN -# include "win.h" -# include <winsock2.h> -# else -# include <arpa/inet.h> -# endif +# ifdef Q_OS_WIN +# include "win.h" +# include <winsock2.h> +# else +# include <arpa/inet.h> +# endif #endif -#include "CryptStateOCB2.h" #include "ByteSwap.h" +#include "CryptStateOCB2.h" #include <cstring> #include <openssl/rand.h> CryptStateOCB2::CryptStateOCB2() : CryptState() { - for (int i=0;i<0x100;i++) + for (int i = 0; i < 0x100; i++) decrypt_history[i] = 0; memset(raw_key, 0, AES_KEY_SIZE_BYTES); memset(encrypt_iv, 0, AES_BLOCK_SIZE); @@ -50,8 +50,8 @@ void CryptStateOCB2::genKey() { bInit = true; } -bool CryptStateOCB2::setKey(const std::string& rkey, const std::string& eiv, const std::string& div) { - if(rkey.length() == AES_KEY_SIZE_BYTES && eiv.length() == AES_BLOCK_SIZE && div.length() == AES_BLOCK_SIZE) { +bool CryptStateOCB2::setKey(const std::string &rkey, const std::string &eiv, const std::string &div) { + if (rkey.length() == AES_KEY_SIZE_BYTES && eiv.length() == AES_BLOCK_SIZE && div.length() == AES_BLOCK_SIZE) { memcpy(raw_key, rkey.data(), AES_KEY_SIZE_BYTES); memcpy(encrypt_iv, eiv.data(), AES_BLOCK_SIZE); memcpy(decrypt_iv, div.data(), AES_BLOCK_SIZE); @@ -63,24 +63,24 @@ bool CryptStateOCB2::setKey(const std::string& rkey, const std::string& eiv, con return false; } -bool CryptStateOCB2::setRawKey(const std::string& rkey) { - if(rkey.length() == AES_KEY_SIZE_BYTES){ +bool CryptStateOCB2::setRawKey(const std::string &rkey) { + if (rkey.length() == AES_KEY_SIZE_BYTES) { memcpy(raw_key, rkey.data(), AES_KEY_SIZE_BYTES); return true; } return false; } -bool CryptStateOCB2::setEncryptIV(const std::string& iv) { - if(iv.length() == AES_BLOCK_SIZE) { +bool CryptStateOCB2::setEncryptIV(const std::string &iv) { + if (iv.length() == AES_BLOCK_SIZE) { memcpy(encrypt_iv, iv.data(), AES_BLOCK_SIZE); return true; } return false; } -bool CryptStateOCB2::setDecryptIV(const std::string& iv) { - if(iv.length() == AES_BLOCK_SIZE) { +bool CryptStateOCB2::setDecryptIV(const std::string &iv) { + if (iv.length() == AES_BLOCK_SIZE) { memcpy(decrypt_iv, iv.data(), AES_BLOCK_SIZE); return true; } @@ -88,26 +88,26 @@ bool CryptStateOCB2::setDecryptIV(const std::string& iv) { } std::string CryptStateOCB2::getRawKey() { - return std::string(reinterpret_cast<const char*>(raw_key), AES_KEY_SIZE_BYTES); + return std::string(reinterpret_cast< const char * >(raw_key), AES_KEY_SIZE_BYTES); } std::string CryptStateOCB2::getEncryptIV() { - return std::string(reinterpret_cast<const char*>(encrypt_iv), AES_BLOCK_SIZE); + return std::string(reinterpret_cast< const char * >(encrypt_iv), AES_BLOCK_SIZE); } std::string CryptStateOCB2::getDecryptIV() { - return std::string(reinterpret_cast<const char*>(decrypt_iv), AES_BLOCK_SIZE); + return std::string(reinterpret_cast< const char * >(decrypt_iv), AES_BLOCK_SIZE); } bool CryptStateOCB2::encrypt(const unsigned char *source, unsigned char *dst, unsigned int plain_length) { unsigned char tag[AES_BLOCK_SIZE]; // First, increase our IV. - for (int i=0;i<AES_BLOCK_SIZE;i++) + for (int i = 0; i < AES_BLOCK_SIZE; i++) if (++encrypt_iv[i]) break; - if (!ocb_encrypt(source, dst+4, plain_length, encrypt_iv, tag)) { + if (!ocb_encrypt(source, dst + 4, plain_length, encrypt_iv, tag)) { return false; } @@ -126,7 +126,7 @@ bool CryptStateOCB2::decrypt(const unsigned char *source, unsigned char *dst, un unsigned char saveiv[AES_BLOCK_SIZE]; unsigned char ivbyte = source[0]; - bool restore = false; + bool restore = false; unsigned char tag[AES_BLOCK_SIZE]; int lost = 0; @@ -140,7 +140,7 @@ bool CryptStateOCB2::decrypt(const unsigned char *source, unsigned char *dst, un decrypt_iv[0] = ivbyte; } else if (ivbyte < decrypt_iv[0]) { decrypt_iv[0] = ivbyte; - for (int i=1;i<AES_BLOCK_SIZE;i++) + for (int i = 1; i < AES_BLOCK_SIZE; i++) if (++decrypt_iv[i]) break; } else { @@ -151,34 +151,34 @@ bool CryptStateOCB2::decrypt(const unsigned char *source, unsigned char *dst, un int diff = ivbyte - decrypt_iv[0]; if (diff > 128) - diff = diff-256; + diff = diff - 256; else if (diff < -128) - diff = diff+256; + diff = diff + 256; if ((ivbyte < decrypt_iv[0]) && (diff > -30) && (diff < 0)) { // Late packet, but no wraparound. - late = 1; - lost = -1; + late = 1; + lost = -1; decrypt_iv[0] = ivbyte; - restore = true; + restore = true; } else if ((ivbyte > decrypt_iv[0]) && (diff > -30) && (diff < 0)) { // Last was 0x02, here comes 0xff from last round - late = 1; - lost = -1; + late = 1; + lost = -1; decrypt_iv[0] = ivbyte; - for (int i=1;i<AES_BLOCK_SIZE;i++) + for (int i = 1; i < AES_BLOCK_SIZE; i++) if (decrypt_iv[i]--) break; restore = true; } else if ((ivbyte > decrypt_iv[0]) && (diff > 0)) { // Lost a few packets, but beyond that we're good. - lost = ivbyte - decrypt_iv[0] - 1; + lost = ivbyte - decrypt_iv[0] - 1; decrypt_iv[0] = ivbyte; } else if ((ivbyte < decrypt_iv[0]) && (diff > 0)) { // Lost a few packets, and wrapped around - lost = 256 - decrypt_iv[0] + ivbyte - 1; + lost = 256 - decrypt_iv[0] + ivbyte - 1; decrypt_iv[0] = ivbyte; - for (int i=1;i<AES_BLOCK_SIZE;i++) + for (int i = 1; i < AES_BLOCK_SIZE; i++) if (++decrypt_iv[i]) break; } else { @@ -191,9 +191,9 @@ bool CryptStateOCB2::decrypt(const unsigned char *source, unsigned char *dst, un } } - bool ocb_success = ocb_decrypt(source+4, dst, plain_length, decrypt_iv, tag); + bool ocb_success = ocb_decrypt(source + 4, dst, plain_length, decrypt_iv, tag); - if (!ocb_success || memcmp(tag, source+1, 3) != 0) { + if (!ocb_success || memcmp(tag, source + 1, 3) != 0) { memcpy(decrypt_iv, saveiv, AES_BLOCK_SIZE); return false; } @@ -212,53 +212,56 @@ bool CryptStateOCB2::decrypt(const unsigned char *source, unsigned char *dst, un #if defined(__LP64__) -#define BLOCKSIZE 2 -#define SHIFTBITS 63 +# define BLOCKSIZE 2 +# define SHIFTBITS 63 typedef quint64 subblock; -#define SWAPPED(x) SWAP64(x) +# define SWAPPED(x) SWAP64(x) #else -#define BLOCKSIZE 4 -#define SHIFTBITS 31 +# define BLOCKSIZE 4 +# define SHIFTBITS 31 typedef quint32 subblock; -#define SWAPPED(x) htonl(x) +# define SWAPPED(x) htonl(x) #endif typedef subblock keyblock[BLOCKSIZE]; -#define HIGHBIT (1<<SHIFTBITS); +#define HIGHBIT (1 << SHIFTBITS); static void inline XOR(subblock *dst, const subblock *a, const subblock *b) { - for (int i=0;i<BLOCKSIZE;i++) { + for (int i = 0; i < BLOCKSIZE; i++) { dst[i] = a[i] ^ b[i]; } } static void inline S2(subblock *block) { subblock carry = SWAPPED(block[0]) >> SHIFTBITS; - for (int i=0;i<BLOCKSIZE-1;i++) - block[i] = SWAPPED((SWAPPED(block[i]) << 1) | (SWAPPED(block[i+1]) >> SHIFTBITS)); - block[BLOCKSIZE-1] = SWAPPED((SWAPPED(block[BLOCKSIZE-1]) << 1) ^(carry * 0x87)); + for (int i = 0; i < BLOCKSIZE - 1; i++) + block[i] = SWAPPED((SWAPPED(block[i]) << 1) | (SWAPPED(block[i + 1]) >> SHIFTBITS)); + block[BLOCKSIZE - 1] = SWAPPED((SWAPPED(block[BLOCKSIZE - 1]) << 1) ^ (carry * 0x87)); } static void inline S3(subblock *block) { subblock carry = SWAPPED(block[0]) >> SHIFTBITS; - for (int i=0;i<BLOCKSIZE-1;i++) - block[i] ^= SWAPPED((SWAPPED(block[i]) << 1) | (SWAPPED(block[i+1]) >> SHIFTBITS)); - block[BLOCKSIZE-1] ^= SWAPPED((SWAPPED(block[BLOCKSIZE-1]) << 1) ^(carry * 0x87)); + for (int i = 0; i < BLOCKSIZE - 1; i++) + block[i] ^= SWAPPED((SWAPPED(block[i]) << 1) | (SWAPPED(block[i + 1]) >> SHIFTBITS)); + block[BLOCKSIZE - 1] ^= SWAPPED((SWAPPED(block[BLOCKSIZE - 1]) << 1) ^ (carry * 0x87)); } static void inline ZERO(keyblock &block) { - for (int i=0;i<BLOCKSIZE;i++) - block[i]=0; + for (int i = 0; i < BLOCKSIZE; i++) + block[i] = 0; } -#define AESencrypt(src,dst,key) AES_encrypt(reinterpret_cast<const unsigned char *>(src),reinterpret_cast<unsigned char *>(dst), key); -#define AESdecrypt(src,dst,key) AES_decrypt(reinterpret_cast<const unsigned char *>(src),reinterpret_cast<unsigned char *>(dst), key); +#define AESencrypt(src, dst, key) \ + AES_encrypt(reinterpret_cast< const unsigned char * >(src), reinterpret_cast< unsigned char * >(dst), key); +#define AESdecrypt(src, dst, key) \ + AES_decrypt(reinterpret_cast< const unsigned char * >(src), reinterpret_cast< unsigned char * >(dst), key); -bool CryptStateOCB2::ocb_encrypt(const unsigned char *plain, unsigned char *encrypted, unsigned int len, const unsigned char *nonce, unsigned char *tag) { +bool CryptStateOCB2::ocb_encrypt(const unsigned char *plain, unsigned char *encrypted, unsigned int len, + const unsigned char *nonce, unsigned char *tag) { keyblock checksum, delta, tmp, pad; bool success = true; @@ -268,10 +271,10 @@ bool CryptStateOCB2::ocb_encrypt(const unsigned char *plain, unsigned char *encr while (len > AES_BLOCK_SIZE) { S2(delta); - XOR(tmp, delta, reinterpret_cast<const subblock *>(plain)); + XOR(tmp, delta, reinterpret_cast< const subblock * >(plain)); AESencrypt(tmp, tmp, &encrypt_key); - XOR(reinterpret_cast<subblock *>(encrypted), delta, tmp); - XOR(checksum, checksum, reinterpret_cast<const subblock *>(plain)); + XOR(reinterpret_cast< subblock * >(encrypted), delta, tmp); + XOR(checksum, checksum, reinterpret_cast< const subblock * >(plain)); // Counter-cryptanalysis described in section 9 of https://eprint.iacr.org/2019/311 // For an attack, the second to last block (i.e. the last iteration of this loop) @@ -295,7 +298,8 @@ bool CryptStateOCB2::ocb_encrypt(const unsigned char *plain, unsigned char *encr XOR(tmp, tmp, delta); AESencrypt(tmp, pad, &encrypt_key); memcpy(tmp, plain, len); - memcpy(reinterpret_cast<unsigned char *>(tmp)+len, reinterpret_cast<const unsigned char *>(pad)+len, AES_BLOCK_SIZE - len); + memcpy(reinterpret_cast< unsigned char * >(tmp) + len, reinterpret_cast< const unsigned char * >(pad) + len, + AES_BLOCK_SIZE - len); XOR(checksum, checksum, tmp); XOR(tmp, pad, tmp); memcpy(encrypted, tmp, len); @@ -307,7 +311,8 @@ bool CryptStateOCB2::ocb_encrypt(const unsigned char *plain, unsigned char *encr return success; } -bool CryptStateOCB2::ocb_decrypt(const unsigned char *encrypted, unsigned char *plain, unsigned int len, const unsigned char *nonce, unsigned char *tag) { +bool CryptStateOCB2::ocb_decrypt(const unsigned char *encrypted, unsigned char *plain, unsigned int len, + const unsigned char *nonce, unsigned char *tag) { keyblock checksum, delta, tmp, pad; bool success = true; @@ -317,10 +322,10 @@ bool CryptStateOCB2::ocb_decrypt(const unsigned char *encrypted, unsigned char * while (len > AES_BLOCK_SIZE) { S2(delta); - XOR(tmp, delta, reinterpret_cast<const subblock *>(encrypted)); + XOR(tmp, delta, reinterpret_cast< const subblock * >(encrypted)); AESdecrypt(tmp, tmp, &decrypt_key); - XOR(reinterpret_cast<subblock *>(plain), delta, tmp); - XOR(checksum, checksum, reinterpret_cast<const subblock *>(plain)); + XOR(reinterpret_cast< subblock * >(plain), delta, tmp); + XOR(checksum, checksum, reinterpret_cast< const subblock * >(plain)); len -= AES_BLOCK_SIZE; plain += AES_BLOCK_SIZE; encrypted += AES_BLOCK_SIZE; diff --git a/src/crypto/CryptStateOCB2.h b/src/crypto/CryptStateOCB2.h index e6a68df85..033fbdf87 100644 --- a/src/crypto/CryptStateOCB2.h +++ b/src/crypto/CryptStateOCB2.h @@ -10,21 +10,21 @@ #include <openssl/aes.h> -#define AES_KEY_SIZE_BITS 128 -#define AES_KEY_SIZE_BYTES (AES_KEY_SIZE_BITS/8) +#define AES_KEY_SIZE_BITS 128 +#define AES_KEY_SIZE_BYTES (AES_KEY_SIZE_BITS / 8) class CryptStateOCB2 : public CryptState { public: CryptStateOCB2(); - ~CryptStateOCB2() {}; + ~CryptStateOCB2(){}; virtual bool isValid() const Q_DECL_OVERRIDE; virtual void genKey() Q_DECL_OVERRIDE; - virtual bool setKey(const std::string& rkey, const std::string& eiv, const std::string& div) Q_DECL_OVERRIDE; - virtual bool setRawKey(const std::string& rkey) Q_DECL_OVERRIDE; - virtual bool setEncryptIV(const std::string& iv) Q_DECL_OVERRIDE; - virtual bool setDecryptIV(const std::string& iv) Q_DECL_OVERRIDE; + virtual bool setKey(const std::string &rkey, const std::string &eiv, const std::string &div) Q_DECL_OVERRIDE; + virtual bool setRawKey(const std::string &rkey) Q_DECL_OVERRIDE; + virtual bool setEncryptIV(const std::string &iv) Q_DECL_OVERRIDE; + virtual bool setDecryptIV(const std::string &iv) Q_DECL_OVERRIDE; virtual std::string getRawKey() Q_DECL_OVERRIDE; virtual std::string getEncryptIV() Q_DECL_OVERRIDE; virtual std::string getDecryptIV() Q_DECL_OVERRIDE; @@ -32,8 +32,10 @@ public: virtual bool decrypt(const unsigned char *source, unsigned char *dst, unsigned int crypted_length) Q_DECL_OVERRIDE; virtual bool encrypt(const unsigned char *source, unsigned char *dst, unsigned int plain_length) Q_DECL_OVERRIDE; - bool ocb_encrypt(const unsigned char *plain, unsigned char *encrypted, unsigned int len, const unsigned char *nonce, unsigned char *tag); - bool ocb_decrypt(const unsigned char *encrypted, unsigned char *plain, unsigned int len, const unsigned char *nonce, unsigned char *tag); + bool ocb_encrypt(const unsigned char *plain, unsigned char *encrypted, unsigned int len, const unsigned char *nonce, + unsigned char *tag); + bool ocb_decrypt(const unsigned char *encrypted, unsigned char *plain, unsigned int len, const unsigned char *nonce, + unsigned char *tag); private: unsigned char raw_key[AES_KEY_SIZE_BYTES]; @@ -41,9 +43,9 @@ private: unsigned char decrypt_iv[AES_BLOCK_SIZE]; unsigned char decrypt_history[0x100]; - AES_KEY encrypt_key; + AES_KEY encrypt_key; AES_KEY decrypt_key; }; -#endif //MUMBLE_CRYPTSTATEOCB2_H +#endif // MUMBLE_CRYPTSTATEOCB2_H diff --git a/src/crypto/CryptographicHash.cpp b/src/crypto/CryptographicHash.cpp index b2332aedb..ee8b154ee 100644 --- a/src/crypto/CryptographicHash.cpp +++ b/src/crypto/CryptographicHash.cpp @@ -10,32 +10,31 @@ #include <openssl/evp.h> class CryptographicHashPrivate { - public: - CryptographicHashPrivate(const EVP_MD *type); - ~CryptographicHashPrivate(); - void addData(const QByteArray &buf); - QByteArray result(); - - private: - EVP_MD_CTX *m_mdctx; - - /// The result of the cryptographic hash. - /// This field is filled out by the result() - /// method. - /// Once this field is set, the m_mdctx is finalized - /// and can't be used anymore, so result() and addData() - /// must guard against that possibility. - QByteArray m_result; - - CryptographicHashPrivate(); - - /// If m_mdctx is set, cleanupMdctx will destroy - /// the EVP_MD_CTX object and set m_mdctx to nullptr. - void cleanupMdctx(); +public: + CryptographicHashPrivate(const EVP_MD *type); + ~CryptographicHashPrivate(); + void addData(const QByteArray &buf); + QByteArray result(); + +private: + EVP_MD_CTX *m_mdctx; + + /// The result of the cryptographic hash. + /// This field is filled out by the result() + /// method. + /// Once this field is set, the m_mdctx is finalized + /// and can't be used anymore, so result() and addData() + /// must guard against that possibility. + QByteArray m_result; + + CryptographicHashPrivate(); + + /// If m_mdctx is set, cleanupMdctx will destroy + /// the EVP_MD_CTX object and set m_mdctx to nullptr. + void cleanupMdctx(); }; -CryptographicHashPrivate::CryptographicHashPrivate() - : m_mdctx(nullptr) { +CryptographicHashPrivate::CryptographicHashPrivate() : m_mdctx(nullptr) { } void CryptographicHashPrivate::cleanupMdctx() { @@ -45,9 +44,7 @@ void CryptographicHashPrivate::cleanupMdctx() { } } -CryptographicHashPrivate::CryptographicHashPrivate(const EVP_MD *type) - : m_mdctx(nullptr) { - +CryptographicHashPrivate::CryptographicHashPrivate(const EVP_MD *type) : m_mdctx(nullptr) { m_mdctx = EVP_MD_CTX_create(); if (!m_mdctx) { return; @@ -98,7 +95,7 @@ QByteArray CryptographicHashPrivate::result() { } QByteArray digest(EVP_MD_CTX_size(m_mdctx), '\0'); - int err = EVP_DigestFinal_ex(m_mdctx, reinterpret_cast<unsigned char *>(digest.data()), nullptr); + int err = EVP_DigestFinal_ex(m_mdctx, reinterpret_cast< unsigned char * >(digest.data()), nullptr); if (err != 1) { cleanupMdctx(); return QByteArray(); @@ -135,13 +132,10 @@ QString CryptographicHash::shortAlgorithmName(CryptographicHash::Algorithm algo) return QString(); } -CryptographicHash::CryptographicHash() - : d(nullptr) { +CryptographicHash::CryptographicHash() : d(nullptr) { } -CryptographicHash::CryptographicHash(CryptographicHash::Algorithm algo) - : d(nullptr) { - +CryptographicHash::CryptographicHash(CryptographicHash::Algorithm algo) : d(nullptr) { switch (algo) { case CryptographicHash::Sha1: d = new CryptographicHashPrivate(EVP_sha1()); diff --git a/src/crypto/CryptographicHash.h b/src/crypto/CryptographicHash.h index d5af2871c..7be32088c 100644 --- a/src/crypto/CryptographicHash.h +++ b/src/crypto/CryptographicHash.h @@ -12,60 +12,60 @@ class CryptographicHashPrivate; /// CryptographicHash is used for computing cryptographic hashes. class CryptographicHash { - public: - /// Algorithm specifies an algorithm for use with CryptographicHash. - enum Algorithm { - /// The SHA-1 hashing algorithm. - Sha1, - /// The SHA-256 hashing algorithm. - Sha256 - }; +public: + /// Algorithm specifies an algorithm for use with CryptographicHash. + enum Algorithm { + /// The SHA-1 hashing algorithm. + Sha1, + /// The SHA-256 hashing algorithm. + Sha256 + }; - /// Compute the cryptographic hash of |buf| using algorithm |algo| - /// and return the result. - /// On failure, the returned QByteArray will be empty. - static QByteArray hash(const QByteArray &buf, Algorithm algo); + /// Compute the cryptographic hash of |buf| using algorithm |algo| + /// and return the result. + /// On failure, the returned QByteArray will be empty. + static QByteArray hash(const QByteArray &buf, Algorithm algo); - /// Return the human readable name of |algo|. - /// - /// Examples: - /// CryptographicHash::Sha1 -> "SHA-1" - /// CryptographicHash::Sha256 -> "SHA-256" - static QString humanReadableAlgorithmName(CryptographicHash::Algorithm algo); + /// Return the human readable name of |algo|. + /// + /// Examples: + /// CryptographicHash::Sha1 -> "SHA-1" + /// CryptographicHash::Sha256 -> "SHA-256" + static QString humanReadableAlgorithmName(CryptographicHash::Algorithm algo); - /// Return a machine-readable short name of |algo|. - /// This variant is a short, lower-case name for the algorithm, suitable - /// for prefixing when serializing a cryptographic hash. - /// - /// Examples: - /// CryptographicHash::Sha1 -> "sha1" - /// CryptographicHash::Sha256 -> "sha256" - static QString shortAlgorithmName(CryptographicHash::Algorithm algo); + /// Return a machine-readable short name of |algo|. + /// This variant is a short, lower-case name for the algorithm, suitable + /// for prefixing when serializing a cryptographic hash. + /// + /// Examples: + /// CryptographicHash::Sha1 -> "sha1" + /// CryptographicHash::Sha256 -> "sha256" + static QString shortAlgorithmName(CryptographicHash::Algorithm algo); - /// Consruct a CryptographicHash object that can be used - /// to incrementally compute a cryptographic hash using the - /// hash function specified in |algo|. - CryptographicHash(Algorithm algo); + /// Consruct a CryptographicHash object that can be used + /// to incrementally compute a cryptographic hash using the + /// hash function specified in |algo|. + CryptographicHash(Algorithm algo); - /// addData adds the content of |buf| to the hash computation. - /// - /// Attempting to add data to the CryptographicHash after result() - /// has been called is an error, and will cause the CryptographicHash - /// object to transition to an error state. Subsequent calls to result() - /// will return an empty QByteArray. - void addData(const QByteArray &buf); + /// addData adds the content of |buf| to the hash computation. + /// + /// Attempting to add data to the CryptographicHash after result() + /// has been called is an error, and will cause the CryptographicHash + /// object to transition to an error state. Subsequent calls to result() + /// will return an empty QByteArray. + void addData(const QByteArray &buf); - /// result() finalizes the CryptographicHash object, - /// and returns the computed hash. - /// After calling this method, it is no longer possible - /// to add more data to the CryptographicHash object. - /// If an error occurred during the computation, the - /// returned QByteArray will be empty. - QByteArray result() const; + /// result() finalizes the CryptographicHash object, + /// and returns the computed hash. + /// After calling this method, it is no longer possible + /// to add more data to the CryptographicHash object. + /// If an error occurred during the computation, the + /// returned QByteArray will be empty. + QByteArray result() const; - private: - CryptographicHash(); - CryptographicHashPrivate *d; +private: + CryptographicHash(); + CryptographicHashPrivate *d; }; #endif diff --git a/src/crypto/CryptographicRandom.cpp b/src/crypto/CryptographicRandom.cpp index 4881e4147..74c99f321 100644 --- a/src/crypto/CryptographicRandom.cpp +++ b/src/crypto/CryptographicRandom.cpp @@ -24,8 +24,9 @@ void CryptographicRandom::fillBuffer(void *buf, int numBytes) { // OpenSSL needs at least 32-bytes of high-entropy random data to seed its CSPRNG. // If OpenSSL cannot acquire enough random data to seed its CSPRNG at the time Mumble and Murmur // are running, there is not much we can do about it other than aborting the program. - if (RAND_bytes(reinterpret_cast<unsigned char *>(buf), static_cast<int>(numBytes)) != 1) { - qFatal("CryptographicRandom::fillBuffer(): internal error in OpenSSL's RAND_bytes or entropy pool not yet filled."); + if (RAND_bytes(reinterpret_cast< unsigned char * >(buf), static_cast< int >(numBytes)) != 1) { + qFatal("CryptographicRandom::fillBuffer(): internal error in OpenSSL's RAND_bytes or entropy pool not yet " + "filled."); } } diff --git a/src/crypto/CryptographicRandom.h b/src/crypto/CryptographicRandom.h index e46e22dcf..4ff9c3bd9 100644 --- a/src/crypto/CryptographicRandom.h +++ b/src/crypto/CryptographicRandom.h @@ -11,35 +11,35 @@ /// CryptographicRandom provides useful utilities for acquiring /// pseudo-random data for use in cryptography. class CryptographicRandom { - public: - /// Fill the buffer at |buf| with |numBytes| bytes of pseudo-random data. - /// The value of |numBytes| must be >= 0. Otherwise, program execution is aborted. - /// - /// This function is equivalent to the arc4random_buf() function from OpenBSD. - /// - /// This function should not ever fail. It is considered a catastrophic failure if - /// it does. The program is aborted if the function fails, because it is generally - /// impossible to recover from such a scenario. - static void fillBuffer(void *buf, int numBytes); +public: + /// Fill the buffer at |buf| with |numBytes| bytes of pseudo-random data. + /// The value of |numBytes| must be >= 0. Otherwise, program execution is aborted. + /// + /// This function is equivalent to the arc4random_buf() function from OpenBSD. + /// + /// This function should not ever fail. It is considered a catastrophic failure if + /// it does. The program is aborted if the function fails, because it is generally + /// impossible to recover from such a scenario. + static void fillBuffer(void *buf, int numBytes); - /// Return a pseudo-random number in the range of 0 to (2**32)-1. - /// - /// This function is equivalent to the arc4random() function from OpenBSD. - /// - /// This function should not ever fail. It is considered a catastrophic failure if - /// it does. The program is aborted if the function fails, because it is generally - /// impossible to recover from such a scenario. - static uint32_t uint32(); + /// Return a pseudo-random number in the range of 0 to (2**32)-1. + /// + /// This function is equivalent to the arc4random() function from OpenBSD. + /// + /// This function should not ever fail. It is considered a catastrophic failure if + /// it does. The program is aborted if the function fails, because it is generally + /// impossible to recover from such a scenario. + static uint32_t uint32(); - /// Calculate a uniformly distributed random number less than |upperBound| - /// avoiding "modulo bias". - /// - /// This function is equivalent to the arc4random_uniform() function from OpenBSD. - /// - /// This function should not ever fail. It is considered a catastrophic failure if - /// it does. The program is aborted if the function fails, because it is generally - /// impossible to recover from such a scenario. - static uint32_t uniform(uint32_t upperBound); + /// Calculate a uniformly distributed random number less than |upperBound| + /// avoiding "modulo bias". + /// + /// This function is equivalent to the arc4random_uniform() function from OpenBSD. + /// + /// This function should not ever fail. It is considered a catastrophic failure if + /// it does. The program is aborted if the function fails, because it is generally + /// impossible to recover from such a scenario. + static uint32_t uniform(uint32_t upperBound); }; #endif diff --git a/src/licenses.h b/src/licenses.h index 89540c9fe..505fe00a5 100644 --- a/src/licenses.h +++ b/src/licenses.h @@ -8,639 +8,629 @@ #include <QtGlobal> struct ThirdPartyLicense { - const char* name; - const char* url; - const char* license; + const char *name; + const char *url; + const char *license; ThirdPartyLicense() : name(0), url(0), license(0) {} - ThirdPartyLicense(const char* name_, const char* url_, const char* license_) - : name(name_), url(url_), license(license_) {} + ThirdPartyLicense(const char *name_, const char *url_, const char *license_) + : name(name_), url(url_), license(license_) {} bool isEmpty() const { return (name == 0 && url == 0 && license == 0); } }; -static const char *licenseMumble = - "Copyright (C) 2005-2020 The Mumble Developers\n" - "\n" - "A list of The Mumble Developers can be found in the\n" - "AUTHORS file at the root of the Mumble source tree\n" - "or at <https://www.mumble.info/AUTHORS>.\n" - "\n" - "All rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright notice,\n" - " this list of conditions and the following disclaimer.\n" - "- Redistributions in binary form must reproduce the above copyright notice,\n" - " this list of conditions and the following disclaimer in the documentation\n" - " and/or other materials provided with the distribution.\n" - "- Neither the name of The Mumble Developers nor the names of its\n" - " contributors may be used to endorse or promote products derived from this\n" - " software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" - "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" - "\n" - "For questions and inquiries about Mumble's license,\n" - "please contact <license@mumble.info>."; +static const char *licenseMumble = "Copyright (C) 2005-2020 The Mumble Developers\n" + "\n" + "A list of The Mumble Developers can be found in the\n" + "AUTHORS file at the root of the Mumble source tree\n" + "or at <https://www.mumble.info/AUTHORS>.\n" + "\n" + "All rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright notice,\n" + " this list of conditions and the following disclaimer.\n" + "- Redistributions in binary form must reproduce the above copyright notice,\n" + " this list of conditions and the following disclaimer in the documentation\n" + " and/or other materials provided with the distribution.\n" + "- Neither the name of The Mumble Developers nor the names of its\n" + " contributors may be used to endorse or promote products derived from this\n" + " software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" + "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + "\n" + "For questions and inquiries about Mumble's license,\n" + "please contact <license@mumble.info>."; -static const char *authorsMumble = - "// This is the official list of people who have contributed\n" - "// to, and/or hold the copyright to Mumble.\n" - "//\n" - "// The use of Mumble source code is governed by a BSD-style\n" - "// license that can be found in the LICENSE file at the root\n" - "// of the Mumble source tree or at <https://www.mumble.info/LICENSE>.\n" - "//\n" - "// Contributions made on behalf of another entity, such as a\n" - "// company are indicated with the following suffix:\n" - "//\n" - "// John Doe <jd@mumble.info> (on behalf of $COMPANY)\n" - "//\n" - "// It is possible to mix individual contributions with company\n" - "// contributions. For example, if a contributor, over time,\n" - "// has contributed code copyrighted by the contributor, as well\n" - "// as various companies:\n" - "//\n" - "// John Doe <jd@mumble.info> (individually, on behalf of\n" - "// $COMPANY1, on behalf of\n" - "// $COMPANY2, [...]).\n" - "//\n" - "// Mumble's code is developed in a Git repository. A log of\n" - "// every contribution ever made to Mumble is available in the\n" - "// Git repository. The Git repository can be queried to get\n" - "// detailed authorship information for copyright and attribution\n" - "// purposes for each file that makes up the software. A detailed\n" - "// analysis of contributions made to Mumble is available via GitHub's\n" - "// contribution statistics:\n" - "//\n" - "// <https://github.com/mumble-voip/mumble/graphs/contributors>\n" - "\n" - "Abex <mii7303@gmail.com>\n" - "Alex Krishnan <akrishnan@twilio.com>\n" - "Alex Maclean <monkeh@monkeh.net>\n" - "Allan Nordhøy <epost@anotheragency.no>\n" - "Álvaro Manuel Recio Pérez <naproxeno@users.sourceforge.net>\n" - "Andreas Bibok <biboka@users.sourceforge.net>\n" - "Andreas Messer <andi@bupfen.de>\n" - "Andreas Sinz <andreas.sinz@aon.at>\n" - "Andrew Johnson <ajohnson@draster.com>\n" - "anonym <anonym@riseup.net>\n" - "Anthony Alves <cvballa3g0@gmail.com>\n" - "Antoine Bertin <diaoulael@users.sourceforge.net>\n" - "Anton Romanov <theli.ua@gmail.com>\n" - "Antonio Larrosa <larrosa@kde.org>\n" - "Arie <allochtoon@zonnet.nl>\n" - "Arne Fenske <arne_fenske@Yahoo.de>\n" - "arrai <array.of.intellect@gmail.com>\n" - "Arseniy Lartsev <ars3niy@users.sourceforge.net>\n" - "Artem Vorotnikov <skybon@gmail.com>\n" - "Arthur Moore <Arthur.Moore.git@cd-net.net>\n" - "asmolero <alsamolero@gmail.com>\n" - "Asura Lee <ashurta@gmail.com>\n" - "B0nuse <mumble@mumble.ru>\n" - "Balazs Nagy <julian7@users.sourceforge.net>\n" - "Bartek \"stranded\" Sumowski <sumowski@gmail.com>\n" - "Bas Wijnen <wijnen@debian.org>\n" - "BAYSSE Laurent <lolo_32@users.sourceforge.net>\n" - "bendem <online@bendem.be>\n" - "Benjamin Jemlich <pcgod@users.sourceforge.net>\n" - "Benjamin Neff <benjamin@coding4coffee.ch>\n" - "Bernhard M. Wiedemann <bernhardout@lsmod.de>\n" - "bogie <priivet@gmail.com>\n" - "Bojan <bogie@b02.a01.ca>\n" - "brooss <brooss.teambb@gmail.com>\n" - "BuddyButterfly <buddy.butterfly@web.de>\n" - "Cesare Tirabassi <cesare.tirabassi@gmail.com>\n" - "Charles Ricketts <githlar@gmail.com>\n" - "Chosi <chosi@choseh.de>\n" - "Christian Krause <chkr@plauener.de>\n" - "Christoph Hofmann <christoph.hofmann@vfc2.eu>\n" - "Christopher Knadle <Chris.Knadle@coredump.us>\n" - "concatime <https://github.com/concatime>\n" - "Cristian Gattamelati <cristian.gattamelati@gmail.com>\n" - "d-rez <dark.skeleton@gmail.com>\n" - "Davide Beatrici <davidebeatrici@gmail.com>\n" - "Davide Beatrici <https://github.com/davidebeatrici>\n" - "davidebeatrici <davidebeatrici@gmail.com>\n" - "dc6jgk <github.filter@gkware.com>\n" - "dennisschagt <dennisschagt@gmail.com>\n" - "derandi <derandi@users.sourceforge.net>\n" - "Derrick Dymock <actown@gmail.com>\n" - "DK <davidk@mail.org>\n" - "DNW <dnw.ftw@gmail.com>\n" - "doggone <rolf@metadata.be>\n" - "DWM|G <gallaghermumble@gmail.com>\n" - "EarlOfWenc <lorenz.schwittmann@gmail.com>\n" - "Eli Tallman <eli.github@gmail.com>\n" - "Entitaet <entitaet@users.sourceforge.net>\n" - "Erik Bouvin Pedersen <erikbp@users.sourceforge.net>\n" - "Evan Purkhiser <evanpurkhiser@gmail.com>\n" - "Ferdinand Thiessen <rpm@fthiessen.de>\n" - "Filip Hedman <hedman.filip@gmail.com>\n" - "Finessi Manuel <fino.manu@gmail.com>\n" - "Flumble <flumble@home.nl>\n" - "Frank Engler <https://github.com/9x6>\n" - "Frank Mueller <frmimue@gmail.com>\n" - "Fredrik Nordin <freedick@ludd.ltu.se>\n" - "Friedrich Uz-Valentin <uz_@users.sourceforge.net>\n" - "Generator <american.jesus.pt@gmail.com>\n" - "GoD-Tony <noreply@gmail.com>\n" - "Harry Gabriel <h.gabriel@nodefab.de>\n" - "haru_arc <arcenciel@users.sf.net>\n" - "He Tal <hetao29@users.sourceforge.net>\n" - "Hengqing Hu <esrms@users.sourceforge.net>\n" - "Henry Fallon <hjf288@gmail.com>\n" - "Iain Georgeson <debbugs@iain.georgeson.me.uk>\n" - "Ilmar Kruis <seaeagle1@users.sourceforge.net>\n" - "Imre Botos <zokny@users.sourceforge.net>\n" - "Jacob Peddicord <jacob@peddicord.net>\n" - "Jakob Dettner <jakobdettner@users.sourceforge.net>\n" - "James Fraser <fwaggle@fwaggle.org>\n" - "Jan Braun <janbraun@gmx.net>\n" - "Jan Klass <kissaki@posteo.de>\n" - "javitonino <javitonino@users.sourceforge.net>\n" - "Jeff Rogers <jeff@flyzipline.com>\n" - "Jérôme \"buggerone\" <buggerone@users.sourceforge.net>\n" - "Jerome Vidal <jerhum@users.sourceforge.net>\n" - "jgeboski <jgeboski@gmail.com>\n" - "Joel Kees <joelkees@gmail.com>\n" - "Joël Troch <joel.troch62@gmail.com>\n" - "John Marion <john@lmsn.net>\n" - "John P <johnhatestrash@gmail.com>\n" - "Jonathan E. Hansen <zentriple@users.sourceforge.net>\n" - "Jordan Cristiano <https://github.com/SizzlingCalamari>\n" - "Jordan Klassen <jordan@klassen.me.uk>\n" - "Joshua Kocinski <git@cl0secall.net>\n" - "Julien Pardons <j.pardons@redline-hosting.eu>\n" - "Justin M <justin.m.mcgrath@gmail.com>\n" - "Justin McGrath <justin.m.mcgrath@gmail.com>\n" - "Karl Dietz <dekarl@spaetfruehstuecken.org>\n" - "karokatona <karokatona@users.sourceforge.net>\n" - "Kevin Rohland <kevin@nascher.org>\n" - "Kevin Strasser <kevstras@gmail.com>\n" - "Kjetil Jørgensen <kjetijor@users.sourceforge.net>\n" - "Kyle Smith <askreet@gmail.com>\n" - "Kyle Wickens <kylewickens@gmail.com>\n" - "Lari Tikkanen <lartza@outlook.com>\n" - "Lartza <https://github.com/Lartza>\n" - "Lekensteyn <lekensteyn@users.sourceforge.net>\n" - "Leszek Godlewski <inequation@users.sourceforge.net>\n" - "lewisca04 <chris.lewis0094@gmail.com>\n" - "Ludwig Nussel <ludwig.nussel@suse.de>\n" - "Lukas Orsvärn <lucas.orsv@gmail.com>\n" - "Luke A Pitt <LukeAPitt@googlemail.com>\n" - "main() <main@ehvag.eu.org>\n" - "Marc Deslauriers <marc.deslauriers@canonical.com>\n" - "Marius Grannæs <grannas@users.sourceforge.net>\n" - "Mark Felder <feld@feld.me>\n" - "Mark Schreiber <mark7@users.sourceforge.net>\n" - "Mark-Willem Jansen <rawnar@users.sourceforge.net>\n" - "Markus S <Reaper@gmx.at>\n" - "Martijn Stolk <github@netripper.nl>\n" - "Martin Skilnand <cybknight@users.sourceforge.net>\n" - "Martin von Gagern <Martin.vGagern@gmx.net>\n" - "Matt Hamilton <m@tthamilton.com>\n" - "Matt Lewandowsky <matt@greenviolet.net>\n" - "Matt M. <mokomull@users.sourceforge.net>\n" - "Matthias Mailänder <matthias@mailaender.name>\n" - "Matthias Salzeder <mail@MatthiasSalzeder.de>\n" - "Matthias Vogelgesang <matthias.vogelgesang@gmail.com>\n" - "Max Weber <mii7303@gmail.com>\n" - "Maxwell Cody <roge@riseup.net>\n" - "meanracoon <racoon@meanclan.org>\n" - "Mew <Giratina493@mew151.net>\n" - "Micah Caldwell <micah@zoltu.net>\n" - "Michael Pavlyshko <me@mixaill.tk>\n" - "Michael Ziegler <diese-addy@funzt-halt.net>\n" - "Michał \"Zuko\" Żukowski <zuczeq@gmail.com>\n" - "Mike <mike@flomp.net>\n" - "Mikkel Krautz <mikkel@krautz.dk>\n" - "Mikko Rantanen <jubjub@jubjubnest.net>\n" - "mray <mail@mray.de>\n" - "mystic_sam <mystic_sam@users.sourceforge.net>\n" - "Natenom <natenom@natenom.com>\n" - "Nick Heindl <nheindl@wisc.edu>\n" - "Nicos Gollan <gtdev@spearhead.de>\n" - "Nik Johnson <nik@jnstw.us>\n" - "Nikita Puzyryov <https://github.com/NikitaPuzyryov>\n" - "Nikolaj Dombrow <nikolaj.dombrow@dombrow.de>\n" - "nomad <gmc_holle@users.sourceforge.net>\n" - "Opalium <opalium@users.sourceforge.net>\n" - "Otto Allmendinger <oallmendinger@users.sourceforge.net>\n" - "ozon <mumble-tower@users.sourceforge.net>\n" - "Patrick Matthäi <pmatthaei@debian.org>\n" - "Peter Vágner <pvdeejay@gmail.com>\n" - "Phil <synapse84@gmail.com>\n" - "Philip Cass <frymaster@127001.org>\n" - "Phrag <info@clanwars.cz>\n" - "Piratonym <piratonym@piratonym.cc>\n" - "Prosper_Spurius <prosper_spurius@users.sourceforge.net>\n" - "QuirB <quirb@gmx.net>\n" - "qwestduck <gsreceiver2@yahoo.com>\n" - "Rafael Correia <rafaeljpc@gmail.com>\n" - "Rafael Lopez <rafael@case.edu>\n" - "rdb <git@rdb.name>\n" - "Roman Priesol <roman@priesol.net>\n" - "ronoc <conor@forwind.net>\n" - "Ryan Austin <ryan.e.austin@gmail.com>\n" - "Sami Laine <sami.v.laine@gmail.com>\n" - "Samuel D. Leslie <sdl@nexiom.net>\n" - "scapula <rasmus.ry@gmail.com>\n" - "Sebastian Schlingmann <mit_service@users.sourceforge.net>\n" - "Semion Tsinman <Necromancer3333@gmail.com>\n" - "Sergey Ivanov <randomei@users.sourceforge.net>\n" - "Shen-Ta Hsieh <ibmibmibm.tw@gmail.com>\n" - "Spaccaossi <spaccaossi@gmail.com>\n" - "spede <spede@dota2.fi>\n" - "Stefan Gehn <mETz@gehn.net>\n" - "Stefan Hacker <dd0t@users.sourceforge.net>\n" - "Steve Hill <github@cheesy.sackheads.org>\n" - "Steven Noonan <steven@uplinklabs.net>\n" - "Sven-Hendrik Haase <sh@lutzhaase.com>\n" - "Svenne33 <svenne33@users.sourceforge.net>\n" - "Svyatoslav <razmyslov@viva64.com>\n" - "synapse84 <synapse84@gmail.com>\n" - "Thibault Capdevielled <theblackstorm@userse.sourceforge.net>\n" - "Thibaut Girka\n" - "Thorvald Natvig <slicer@users.sourceforge.net>\n" - "Tim Burke <tim.burke@gmail.com>\n" - "Tim Cooper <tim.cooper@layeh.com>\n" - "Tim Visée <timvisee@gmail.com>\n" - "Timo Gurr <timo.gurr@gmail.com>\n" - "Timo K <timer@dbclan.de>\n" - "tkmorris <mauricioarozi@gmail.com>\n" - "Tristan Matthews <tristan.matthews@savoirfairelinux.com>\n" - "Tsbook <tsbook@users.sourceforge.net>\n" - "Wesley W. Terpstra <terpstra@users.sourceforge.net>\n" - "Will Tange <bh34rt@gmail.com>\n" - "withgod <withgod@users.sourceforge.net>\n" - "x89 <napalm10@gmail.com>\n" - "zapman\n" - "zeroX-tj <tim.janssens@gmail.com>\n" - "Zorg <zorgiepoo@gmail.com>\n" - "\n" - "// Special thanks to:\n" - "//\n" - "// Thorvald Natvig, for founding the Mumble project\n" - "// and maintaining it during its formative years."; +static const char *authorsMumble = "// This is the official list of people who have contributed\n" + "// to, and/or hold the copyright to Mumble.\n" + "//\n" + "// The use of Mumble source code is governed by a BSD-style\n" + "// license that can be found in the LICENSE file at the root\n" + "// of the Mumble source tree or at <https://www.mumble.info/LICENSE>.\n" + "//\n" + "// Contributions made on behalf of another entity, such as a\n" + "// company are indicated with the following suffix:\n" + "//\n" + "// John Doe <jd@mumble.info> (on behalf of $COMPANY)\n" + "//\n" + "// It is possible to mix individual contributions with company\n" + "// contributions. For example, if a contributor, over time,\n" + "// has contributed code copyrighted by the contributor, as well\n" + "// as various companies:\n" + "//\n" + "// John Doe <jd@mumble.info> (individually, on behalf of\n" + "// $COMPANY1, on behalf of\n" + "// $COMPANY2, [...]).\n" + "//\n" + "// Mumble's code is developed in a Git repository. A log of\n" + "// every contribution ever made to Mumble is available in the\n" + "// Git repository. The Git repository can be queried to get\n" + "// detailed authorship information for copyright and attribution\n" + "// purposes for each file that makes up the software. A detailed\n" + "// analysis of contributions made to Mumble is available via GitHub's\n" + "// contribution statistics:\n" + "//\n" + "// <https://github.com/mumble-voip/mumble/graphs/contributors>\n" + "\n" + "Abex <mii7303@gmail.com>\n" + "Alex Krishnan <akrishnan@twilio.com>\n" + "Alex Maclean <monkeh@monkeh.net>\n" + "Allan Nordhøy <epost@anotheragency.no>\n" + "Álvaro Manuel Recio Pérez <naproxeno@users.sourceforge.net>\n" + "Andreas Bibok <biboka@users.sourceforge.net>\n" + "Andreas Messer <andi@bupfen.de>\n" + "Andreas Sinz <andreas.sinz@aon.at>\n" + "Andrew Johnson <ajohnson@draster.com>\n" + "anonym <anonym@riseup.net>\n" + "Anthony Alves <cvballa3g0@gmail.com>\n" + "Antoine Bertin <diaoulael@users.sourceforge.net>\n" + "Anton Romanov <theli.ua@gmail.com>\n" + "Antonio Larrosa <larrosa@kde.org>\n" + "Arie <allochtoon@zonnet.nl>\n" + "Arne Fenske <arne_fenske@Yahoo.de>\n" + "arrai <array.of.intellect@gmail.com>\n" + "Arseniy Lartsev <ars3niy@users.sourceforge.net>\n" + "Artem Vorotnikov <skybon@gmail.com>\n" + "Arthur Moore <Arthur.Moore.git@cd-net.net>\n" + "asmolero <alsamolero@gmail.com>\n" + "Asura Lee <ashurta@gmail.com>\n" + "B0nuse <mumble@mumble.ru>\n" + "Balazs Nagy <julian7@users.sourceforge.net>\n" + "Bartek \"stranded\" Sumowski <sumowski@gmail.com>\n" + "Bas Wijnen <wijnen@debian.org>\n" + "BAYSSE Laurent <lolo_32@users.sourceforge.net>\n" + "bendem <online@bendem.be>\n" + "Benjamin Jemlich <pcgod@users.sourceforge.net>\n" + "Benjamin Neff <benjamin@coding4coffee.ch>\n" + "Bernhard M. Wiedemann <bernhardout@lsmod.de>\n" + "bogie <priivet@gmail.com>\n" + "Bojan <bogie@b02.a01.ca>\n" + "brooss <brooss.teambb@gmail.com>\n" + "BuddyButterfly <buddy.butterfly@web.de>\n" + "Cesare Tirabassi <cesare.tirabassi@gmail.com>\n" + "Charles Ricketts <githlar@gmail.com>\n" + "Chosi <chosi@choseh.de>\n" + "Christian Krause <chkr@plauener.de>\n" + "Christoph Hofmann <christoph.hofmann@vfc2.eu>\n" + "Christopher Knadle <Chris.Knadle@coredump.us>\n" + "concatime <https://github.com/concatime>\n" + "Cristian Gattamelati <cristian.gattamelati@gmail.com>\n" + "d-rez <dark.skeleton@gmail.com>\n" + "Davide Beatrici <davidebeatrici@gmail.com>\n" + "Davide Beatrici <https://github.com/davidebeatrici>\n" + "davidebeatrici <davidebeatrici@gmail.com>\n" + "dc6jgk <github.filter@gkware.com>\n" + "dennisschagt <dennisschagt@gmail.com>\n" + "derandi <derandi@users.sourceforge.net>\n" + "Derrick Dymock <actown@gmail.com>\n" + "DK <davidk@mail.org>\n" + "DNW <dnw.ftw@gmail.com>\n" + "doggone <rolf@metadata.be>\n" + "DWM|G <gallaghermumble@gmail.com>\n" + "EarlOfWenc <lorenz.schwittmann@gmail.com>\n" + "Eli Tallman <eli.github@gmail.com>\n" + "Entitaet <entitaet@users.sourceforge.net>\n" + "Erik Bouvin Pedersen <erikbp@users.sourceforge.net>\n" + "Evan Purkhiser <evanpurkhiser@gmail.com>\n" + "Ferdinand Thiessen <rpm@fthiessen.de>\n" + "Filip Hedman <hedman.filip@gmail.com>\n" + "Finessi Manuel <fino.manu@gmail.com>\n" + "Flumble <flumble@home.nl>\n" + "Frank Engler <https://github.com/9x6>\n" + "Frank Mueller <frmimue@gmail.com>\n" + "Fredrik Nordin <freedick@ludd.ltu.se>\n" + "Friedrich Uz-Valentin <uz_@users.sourceforge.net>\n" + "Generator <american.jesus.pt@gmail.com>\n" + "GoD-Tony <noreply@gmail.com>\n" + "Harry Gabriel <h.gabriel@nodefab.de>\n" + "haru_arc <arcenciel@users.sf.net>\n" + "He Tal <hetao29@users.sourceforge.net>\n" + "Hengqing Hu <esrms@users.sourceforge.net>\n" + "Henry Fallon <hjf288@gmail.com>\n" + "Iain Georgeson <debbugs@iain.georgeson.me.uk>\n" + "Ilmar Kruis <seaeagle1@users.sourceforge.net>\n" + "Imre Botos <zokny@users.sourceforge.net>\n" + "Jacob Peddicord <jacob@peddicord.net>\n" + "Jakob Dettner <jakobdettner@users.sourceforge.net>\n" + "James Fraser <fwaggle@fwaggle.org>\n" + "Jan Braun <janbraun@gmx.net>\n" + "Jan Klass <kissaki@posteo.de>\n" + "javitonino <javitonino@users.sourceforge.net>\n" + "Jeff Rogers <jeff@flyzipline.com>\n" + "Jérôme \"buggerone\" <buggerone@users.sourceforge.net>\n" + "Jerome Vidal <jerhum@users.sourceforge.net>\n" + "jgeboski <jgeboski@gmail.com>\n" + "Joel Kees <joelkees@gmail.com>\n" + "Joël Troch <joel.troch62@gmail.com>\n" + "John Marion <john@lmsn.net>\n" + "John P <johnhatestrash@gmail.com>\n" + "Jonathan E. Hansen <zentriple@users.sourceforge.net>\n" + "Jordan Cristiano <https://github.com/SizzlingCalamari>\n" + "Jordan Klassen <jordan@klassen.me.uk>\n" + "Joshua Kocinski <git@cl0secall.net>\n" + "Julien Pardons <j.pardons@redline-hosting.eu>\n" + "Justin M <justin.m.mcgrath@gmail.com>\n" + "Justin McGrath <justin.m.mcgrath@gmail.com>\n" + "Karl Dietz <dekarl@spaetfruehstuecken.org>\n" + "karokatona <karokatona@users.sourceforge.net>\n" + "Kevin Rohland <kevin@nascher.org>\n" + "Kevin Strasser <kevstras@gmail.com>\n" + "Kjetil Jørgensen <kjetijor@users.sourceforge.net>\n" + "Kyle Smith <askreet@gmail.com>\n" + "Kyle Wickens <kylewickens@gmail.com>\n" + "Lari Tikkanen <lartza@outlook.com>\n" + "Lartza <https://github.com/Lartza>\n" + "Lekensteyn <lekensteyn@users.sourceforge.net>\n" + "Leszek Godlewski <inequation@users.sourceforge.net>\n" + "lewisca04 <chris.lewis0094@gmail.com>\n" + "Ludwig Nussel <ludwig.nussel@suse.de>\n" + "Lukas Orsvärn <lucas.orsv@gmail.com>\n" + "Luke A Pitt <LukeAPitt@googlemail.com>\n" + "main() <main@ehvag.eu.org>\n" + "Marc Deslauriers <marc.deslauriers@canonical.com>\n" + "Marius Grannæs <grannas@users.sourceforge.net>\n" + "Mark Felder <feld@feld.me>\n" + "Mark Schreiber <mark7@users.sourceforge.net>\n" + "Mark-Willem Jansen <rawnar@users.sourceforge.net>\n" + "Markus S <Reaper@gmx.at>\n" + "Martijn Stolk <github@netripper.nl>\n" + "Martin Skilnand <cybknight@users.sourceforge.net>\n" + "Martin von Gagern <Martin.vGagern@gmx.net>\n" + "Matt Hamilton <m@tthamilton.com>\n" + "Matt Lewandowsky <matt@greenviolet.net>\n" + "Matt M. <mokomull@users.sourceforge.net>\n" + "Matthias Mailänder <matthias@mailaender.name>\n" + "Matthias Salzeder <mail@MatthiasSalzeder.de>\n" + "Matthias Vogelgesang <matthias.vogelgesang@gmail.com>\n" + "Max Weber <mii7303@gmail.com>\n" + "Maxwell Cody <roge@riseup.net>\n" + "meanracoon <racoon@meanclan.org>\n" + "Mew <Giratina493@mew151.net>\n" + "Micah Caldwell <micah@zoltu.net>\n" + "Michael Pavlyshko <me@mixaill.tk>\n" + "Michael Ziegler <diese-addy@funzt-halt.net>\n" + "Michał \"Zuko\" Żukowski <zuczeq@gmail.com>\n" + "Mike <mike@flomp.net>\n" + "Mikkel Krautz <mikkel@krautz.dk>\n" + "Mikko Rantanen <jubjub@jubjubnest.net>\n" + "mray <mail@mray.de>\n" + "mystic_sam <mystic_sam@users.sourceforge.net>\n" + "Natenom <natenom@natenom.com>\n" + "Nick Heindl <nheindl@wisc.edu>\n" + "Nicos Gollan <gtdev@spearhead.de>\n" + "Nik Johnson <nik@jnstw.us>\n" + "Nikita Puzyryov <https://github.com/NikitaPuzyryov>\n" + "Nikolaj Dombrow <nikolaj.dombrow@dombrow.de>\n" + "nomad <gmc_holle@users.sourceforge.net>\n" + "Opalium <opalium@users.sourceforge.net>\n" + "Otto Allmendinger <oallmendinger@users.sourceforge.net>\n" + "ozon <mumble-tower@users.sourceforge.net>\n" + "Patrick Matthäi <pmatthaei@debian.org>\n" + "Peter Vágner <pvdeejay@gmail.com>\n" + "Phil <synapse84@gmail.com>\n" + "Philip Cass <frymaster@127001.org>\n" + "Phrag <info@clanwars.cz>\n" + "Piratonym <piratonym@piratonym.cc>\n" + "Prosper_Spurius <prosper_spurius@users.sourceforge.net>\n" + "QuirB <quirb@gmx.net>\n" + "qwestduck <gsreceiver2@yahoo.com>\n" + "Rafael Correia <rafaeljpc@gmail.com>\n" + "Rafael Lopez <rafael@case.edu>\n" + "rdb <git@rdb.name>\n" + "Roman Priesol <roman@priesol.net>\n" + "ronoc <conor@forwind.net>\n" + "Ryan Austin <ryan.e.austin@gmail.com>\n" + "Sami Laine <sami.v.laine@gmail.com>\n" + "Samuel D. Leslie <sdl@nexiom.net>\n" + "scapula <rasmus.ry@gmail.com>\n" + "Sebastian Schlingmann <mit_service@users.sourceforge.net>\n" + "Semion Tsinman <Necromancer3333@gmail.com>\n" + "Sergey Ivanov <randomei@users.sourceforge.net>\n" + "Shen-Ta Hsieh <ibmibmibm.tw@gmail.com>\n" + "Spaccaossi <spaccaossi@gmail.com>\n" + "spede <spede@dota2.fi>\n" + "Stefan Gehn <mETz@gehn.net>\n" + "Stefan Hacker <dd0t@users.sourceforge.net>\n" + "Steve Hill <github@cheesy.sackheads.org>\n" + "Steven Noonan <steven@uplinklabs.net>\n" + "Sven-Hendrik Haase <sh@lutzhaase.com>\n" + "Svenne33 <svenne33@users.sourceforge.net>\n" + "Svyatoslav <razmyslov@viva64.com>\n" + "synapse84 <synapse84@gmail.com>\n" + "Thibault Capdevielled <theblackstorm@userse.sourceforge.net>\n" + "Thibaut Girka\n" + "Thorvald Natvig <slicer@users.sourceforge.net>\n" + "Tim Burke <tim.burke@gmail.com>\n" + "Tim Cooper <tim.cooper@layeh.com>\n" + "Tim Visée <timvisee@gmail.com>\n" + "Timo Gurr <timo.gurr@gmail.com>\n" + "Timo K <timer@dbclan.de>\n" + "tkmorris <mauricioarozi@gmail.com>\n" + "Tristan Matthews <tristan.matthews@savoirfairelinux.com>\n" + "Tsbook <tsbook@users.sourceforge.net>\n" + "Wesley W. Terpstra <terpstra@users.sourceforge.net>\n" + "Will Tange <bh34rt@gmail.com>\n" + "withgod <withgod@users.sourceforge.net>\n" + "x89 <napalm10@gmail.com>\n" + "zapman\n" + "zeroX-tj <tim.janssens@gmail.com>\n" + "Zorg <zorgiepoo@gmail.com>\n" + "\n" + "// Special thanks to:\n" + "//\n" + "// Thorvald Natvig, for founding the Mumble project\n" + "// and maintaining it during its formative years."; -static const char *licenseCELT = - "Copyright 2001-2009 Jean-Marc Valin, Timothy B. Terriberry,\n" - " CSIRO, and other contributors\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - "\n" - "- Redistributions in binary form must reproduce the above copyright\n" - "notice, this list of conditions and the following disclaimer in the\n" - "documentation and/or other materials provided with the distribution.\n" - "\n" - "- Neither the name of the Xiph.org Foundation nor the names of its\n" - "contributors may be used to endorse or promote products derived from\n" - "this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" - "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseCELT = "Copyright 2001-2009 Jean-Marc Valin, Timothy B. Terriberry,\n" + " CSIRO, and other contributors\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + "\n" + "- Redistributions in binary form must reproduce the above copyright\n" + "notice, this list of conditions and the following disclaimer in the\n" + "documentation and/or other materials provided with the distribution.\n" + "\n" + "- Neither the name of the Xiph.org Foundation nor the names of its\n" + "contributors may be used to endorse or promote products derived from\n" + "this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" + "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; -static const char *licenseOpus = - "Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic,\n" - " Jean-Marc Valin, Timothy B. Terriberry,\n" - " CSIRO, Gregory Maxwell, Mark Borgerding,\n" - " Erik de Castro Lopo\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - "\n" - "- Redistributions in binary form must reproduce the above copyright\n" - "notice, this list of conditions and the following disclaimer in the\n" - "documentation and/or other materials provided with the distribution.\n" - "\n" - "- Neither the name of Internet Society, IETF or IETF Trust, nor the\n" - "names of specific contributors, may be used to endorse or promote\n" - "products derived from this software without specific prior written\n" - "permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n" - "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" - "\n" - "Opus is subject to the royalty-free patent licenses which are\n" - "specified at:\n" - "\n" - "Xiph.Org Foundation:\n" - "https://datatracker.ietf.org/ipr/1524/\n" - "\n" - "Microsoft Corporation:\n" - "https://datatracker.ietf.org/ipr/1914/\n" - "\n" - "Broadcom Corporation:\n" - "https://datatracker.ietf.org/ipr/1526/"; +static const char *licenseOpus = "Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic,\n" + " Jean-Marc Valin, Timothy B. Terriberry,\n" + " CSIRO, Gregory Maxwell, Mark Borgerding,\n" + " Erik de Castro Lopo\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + "\n" + "- Redistributions in binary form must reproduce the above copyright\n" + "notice, this list of conditions and the following disclaimer in the\n" + "documentation and/or other materials provided with the distribution.\n" + "\n" + "- Neither the name of Internet Society, IETF or IETF Trust, nor the\n" + "names of specific contributors, may be used to endorse or promote\n" + "products derived from this software without specific prior written\n" + "permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n" + "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + "\n" + "Opus is subject to the royalty-free patent licenses which are\n" + "specified at:\n" + "\n" + "Xiph.Org Foundation:\n" + "https://datatracker.ietf.org/ipr/1524/\n" + "\n" + "Microsoft Corporation:\n" + "https://datatracker.ietf.org/ipr/1914/\n" + "\n" + "Broadcom Corporation:\n" + "https://datatracker.ietf.org/ipr/1526/"; -static const char *licenseSPEEX = - "Copyright 2002-2008 Xiph.org Foundation\n" - "Copyright 2002-2008 Jean-Marc Valin\n" - "Copyright 2005-2007 Analog Devices Inc.\n" - "Copyright 2005-2008 Commonwealth Scientific and Industrial Research \n" - " Organisation (CSIRO)\n" - "Copyright 1993, 2002, 2006 David Rowe\n" - "Copyright 2003 EpicGames\n" - "Copyright 1992-1994 Jutta Degener, Carsten Bormann\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - "\n" - "- Redistributions in binary form must reproduce the above copyright\n" - "notice, this list of conditions and the following disclaimer in the\n" - "documentation and/or other materials provided with the distribution.\n" - "\n" - "- Neither the name of the Xiph.org Foundation nor the names of its\n" - "contributors may be used to endorse or promote products derived from\n" - "this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" - "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseSPEEX = "Copyright 2002-2008 Xiph.org Foundation\n" + "Copyright 2002-2008 Jean-Marc Valin\n" + "Copyright 2005-2007 Analog Devices Inc.\n" + "Copyright 2005-2008 Commonwealth Scientific and Industrial Research \n" + " Organisation (CSIRO)\n" + "Copyright 1993, 2002, 2006 David Rowe\n" + "Copyright 2003 EpicGames\n" + "Copyright 1992-1994 Jutta Degener, Carsten Bormann\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + "\n" + "- Redistributions in binary form must reproduce the above copyright\n" + "notice, this list of conditions and the following disclaimer in the\n" + "documentation and/or other materials provided with the distribution.\n" + "\n" + "- Neither the name of the Xiph.org Foundation nor the names of its\n" + "contributors may be used to endorse or promote products derived from\n" + "this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" + "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; -static const char *licenseOpenSSL = - "====================================================================\n" - "Copyright (c) 1998-2016 The OpenSSL Project. All rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "1. Redistributions of source code must retain the above copyright\n" - " notice, this list of conditions and the following disclaimer. \n" - "\n" - "2. Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in\n" - " the documentation and/or other materials provided with the\n" - " distribution.\n" - "\n" - "3. All advertising materials mentioning features or use of this\n" - " software must display the following acknowledgment:\n" - " \"This product includes software developed by the OpenSSL Project\n" - " for use in the OpenSSL Toolkit. (http://www.openssl.org/)\"\n" - "\n" - "4. The names \"OpenSSL Toolkit\" and \"OpenSSL Project\" must not be used to\n" - " endorse or promote products derived from this software without\n" - " prior written permission. For written permission, please contact\n" - " openssl-core@openssl.org.\n" - "\n" - "5. Products derived from this software may not be called \"OpenSSL\"\n" - " nor may \"OpenSSL\" appear in their names without prior written\n" - " permission of the OpenSSL Project.\n" - "\n" - "6. Redistributions of any form whatsoever must retain the following\n" - " acknowledgment:\n" - " \"This product includes software developed by the OpenSSL Project\n" - " for use in the OpenSSL Toolkit (http://www.openssl.org/)\"\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\n" - "EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" - "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" - "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\n" - "ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" - "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" - "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n" - "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" - "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n" - "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" - "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n" - "OF THE POSSIBILITY OF SUCH DAMAGE.\n" - "====================================================================\n" - "\n" - "This product includes cryptographic software written by Eric Young\n" - "(eay@cryptsoft.com). This product includes software written by Tim\n" - "Hudson (tjh@cryptsoft.com).\n" - "\n" - "Original SSLeay License\n" - "-----------------------\n" - "\n" - "Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)\n" - "All rights reserved.\n" - "\n" - "This package is an SSL implementation written\n" - "by Eric Young (eay@cryptsoft.com).\n" - "The implementation was written so as to conform with Netscapes SSL.\n" - "\n" - "This library is free for commercial and non-commercial use as long as\n" - "the following conditions are aheared to. The following conditions\n" - "apply to all code found in this distribution, be it the RC4, RSA,\n" - "lhash, DES, etc., code; not just the SSL code. The SSL documentation\n" - "included with this distribution is covered by the same copyright terms\n" - "except that the holder is Tim Hudson (tjh@cryptsoft.com).\n" - "\n" - "Copyright remains Eric Young's, and as such any Copyright notices in\n" - "the code are not to be removed.\n" - "If this package is used in a product, Eric Young should be given attribution\n" - "as the author of the parts of the library used.\n" - "This can be in the form of a textual message at program startup or\n" - "in documentation (online or textual) provided with the package.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "1. Redistributions of source code must retain the copyright\n" - " notice, this list of conditions and the following disclaimer.\n" - "2. Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in the\n" - " documentation and/or other materials provided with the distribution.\n" - "3. All advertising materials mentioning features or use of this software\n" - " must display the following acknowledgement:\n" - " \"This product includes cryptographic software written by\n" - " Eric Young (eay@cryptsoft.com)\"\n" - " The word 'cryptographic' can be left out if the rouines from the library\n" - " being used are not cryptographic related :-).\n" - "4. If you include any Windows specific code (or a derivative thereof) from \n" - " the apps directory (application code) you must include an acknowledgement:\n" - " \"This product includes software written by Tim Hudson (tjh@cryptsoft.com)\"\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\n" - "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" - "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" - "ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n" - "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" - "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" - "OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" - "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" - "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" - "OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" - "SUCH DAMAGE.\n" - "\n" - "The licence and distribution terms for any publically available version or\n" - "derivative of this code cannot be changed. i.e. this code cannot simply be\n" - "copied and put under another distribution licence\n" - "[including the GNU Public Licence.]"; +static const char *licenseOpenSSL = "====================================================================\n" + "Copyright (c) 1998-2016 The OpenSSL Project. All rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "1. Redistributions of source code must retain the above copyright\n" + " notice, this list of conditions and the following disclaimer. \n" + "\n" + "2. Redistributions in binary form must reproduce the above copyright\n" + " notice, this list of conditions and the following disclaimer in\n" + " the documentation and/or other materials provided with the\n" + " distribution.\n" + "\n" + "3. All advertising materials mentioning features or use of this\n" + " software must display the following acknowledgment:\n" + " \"This product includes software developed by the OpenSSL Project\n" + " for use in the OpenSSL Toolkit. (http://www.openssl.org/)\"\n" + "\n" + "4. The names \"OpenSSL Toolkit\" and \"OpenSSL Project\" must not be used to\n" + " endorse or promote products derived from this software without\n" + " prior written permission. For written permission, please contact\n" + " openssl-core@openssl.org.\n" + "\n" + "5. Products derived from this software may not be called \"OpenSSL\"\n" + " nor may \"OpenSSL\" appear in their names without prior written\n" + " permission of the OpenSSL Project.\n" + "\n" + "6. Redistributions of any form whatsoever must retain the following\n" + " acknowledgment:\n" + " \"This product includes software developed by the OpenSSL Project\n" + " for use in the OpenSSL Toolkit (http://www.openssl.org/)\"\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY\n" + "EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" + "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\n" + "ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" + "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" + "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n" + "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" + "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n" + "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" + "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n" + "OF THE POSSIBILITY OF SUCH DAMAGE.\n" + "====================================================================\n" + "\n" + "This product includes cryptographic software written by Eric Young\n" + "(eay@cryptsoft.com). This product includes software written by Tim\n" + "Hudson (tjh@cryptsoft.com).\n" + "\n" + "Original SSLeay License\n" + "-----------------------\n" + "\n" + "Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)\n" + "All rights reserved.\n" + "\n" + "This package is an SSL implementation written\n" + "by Eric Young (eay@cryptsoft.com).\n" + "The implementation was written so as to conform with Netscapes SSL.\n" + "\n" + "This library is free for commercial and non-commercial use as long as\n" + "the following conditions are aheared to. The following conditions\n" + "apply to all code found in this distribution, be it the RC4, RSA,\n" + "lhash, DES, etc., code; not just the SSL code. The SSL documentation\n" + "included with this distribution is covered by the same copyright terms\n" + "except that the holder is Tim Hudson (tjh@cryptsoft.com).\n" + "\n" + "Copyright remains Eric Young's, and as such any Copyright notices in\n" + "the code are not to be removed.\n" + "If this package is used in a product, Eric Young should be given attribution\n" + "as the author of the parts of the library used.\n" + "This can be in the form of a textual message at program startup or\n" + "in documentation (online or textual) provided with the package.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "1. Redistributions of source code must retain the copyright\n" + " notice, this list of conditions and the following disclaimer.\n" + "2. Redistributions in binary form must reproduce the above copyright\n" + " notice, this list of conditions and the following disclaimer in the\n" + " documentation and/or other materials provided with the distribution.\n" + "3. All advertising materials mentioning features or use of this software\n" + " must display the following acknowledgement:\n" + " \"This product includes cryptographic software written by\n" + " Eric Young (eay@cryptsoft.com)\"\n" + " The word 'cryptographic' can be left out if the rouines from the library\n" + " being used are not cryptographic related :-).\n" + "4. If you include any Windows specific code (or a derivative thereof) from \n" + " the apps directory (application code) you must include an acknowledgement:\n" + " \"This product includes software written by Tim Hudson (tjh@cryptsoft.com)\"\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND\n" + "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" + "ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n" + "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" + "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" + "OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" + "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" + "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" + "OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" + "SUCH DAMAGE.\n" + "\n" + "The licence and distribution terms for any publically available version or\n" + "derivative of this code cannot be changed. i.e. this code cannot simply be\n" + "copied and put under another distribution licence\n" + "[including the GNU Public Licence.]"; -static const char *licenseLibsndfile = - "Copyright (C) 1999-2011 Erik de Castro Lopo <erikd@mega-nerd.com>\n" - "\n" - "This program is free software; you can redistribute it and/or modify\n" - "it under the terms of the GNU Lesser General Public License as published by\n" - "the Free Software Foundation; either version 2.1 of the License, or\n" - "(at your option) any later version.\n" - "\n" - "This program is distributed in the hope that it will be useful,\n" - "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" - "GNU Lesser General Public License for more details.\n" - "\n" - "You should have received a copy of the GNU Lesser General Public License\n" - "along with this program; if not, write to the Free Software\n" - "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA."; +static const char *licenseLibsndfile = "Copyright (C) 1999-2011 Erik de Castro Lopo <erikd@mega-nerd.com>\n" + "\n" + "This program is free software; you can redistribute it and/or modify\n" + "it under the terms of the GNU Lesser General Public License as published by\n" + "the Free Software Foundation; either version 2.1 of the License, or\n" + "(at your option) any later version.\n" + "\n" + "This program is distributed in the hope that it will be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + "GNU Lesser General Public License for more details.\n" + "\n" + "You should have received a copy of the GNU Lesser General Public License\n" + "along with this program; if not, write to the Free Software\n" + "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA."; -static const char *licenseOgg = - "Copyright (c) 2002, Xiph.org Foundation\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - "\n" - "- Redistributions in binary form must reproduce the above copyright\n" - "notice, this list of conditions and the following disclaimer in the\n" - "documentation and/or other materials provided with the distribution.\n" - "\n" - "- Neither the name of the Xiph.org Foundation nor the names of its\n" - "contributors may be used to endorse or promote products derived from\n" - "this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION\n" - "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" - "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" - "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" - "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" - "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" - "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" - "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseOgg = "Copyright (c) 2002, Xiph.org Foundation\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + "\n" + "- Redistributions in binary form must reproduce the above copyright\n" + "notice, this list of conditions and the following disclaimer in the\n" + "documentation and/or other materials provided with the distribution.\n" + "\n" + "- Neither the name of the Xiph.org Foundation nor the names of its\n" + "contributors may be used to endorse or promote products derived from\n" + "this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION\n" + "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" + "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" + "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" + "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" + "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" + "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" + "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; -static const char *licenseVorbis = - "Copyright (c) 2002-2008 Xiph.org Foundation\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - "\n" - "- Redistributions in binary form must reproduce the above copyright\n" - "notice, this list of conditions and the following disclaimer in the\n" - "documentation and/or other materials provided with the distribution.\n" - "\n" - "- Neither the name of the Xiph.org Foundation nor the names of its\n" - "contributors may be used to endorse or promote products derived from\n" - "this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION\n" - "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" - "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" - "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" - "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" - "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" - "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" - "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseVorbis = "Copyright (c) 2002-2008 Xiph.org Foundation\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + "\n" + "- Redistributions in binary form must reproduce the above copyright\n" + "notice, this list of conditions and the following disclaimer in the\n" + "documentation and/or other materials provided with the distribution.\n" + "\n" + "- Neither the name of the Xiph.org Foundation nor the names of its\n" + "contributors may be used to endorse or promote products derived from\n" + "this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION\n" + "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" + "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" + "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" + "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" + "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" + "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" + "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; -static const char *licenseFLAC = - "Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - "\n" - "- Redistributions in binary form must reproduce the above copyright\n" - "notice, this list of conditions and the following disclaimer in the\n" - "documentation and/or other materials provided with the distribution.\n" - "\n" - "- Neither the name of the Xiph.org Foundation nor the names of its\n" - "contributors may be used to endorse or promote products derived from\n" - "this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" - "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseFLAC = "Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + "\n" + "- Redistributions in binary form must reproduce the above copyright\n" + "notice, this list of conditions and the following disclaimer in the\n" + "documentation and/or other materials provided with the distribution.\n" + "\n" + "- Neither the name of the Xiph.org Foundation nor the names of its\n" + "contributors may be used to endorse or promote products derived from\n" + "this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n" + "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; #ifdef Q_OS_MAC -static const char *licenseMachOverride = +static const char *licenseMachOverride = "Copyright (c) 2003-2009 Jonathan 'Wolf' Rentzsch <http://rentzsch.com>\n" "\n" "Permission is hereby granted, free of charge, to any person obtaining\n" @@ -664,93 +654,92 @@ static const char *licenseMachOverride = #ifdef Q_OS_WIN64 -static const char *licenseMinHook = - "MinHook - The Minimalistic API Hooking Library for x64/x86\n" - "Copyright (C) 2009-2017 Tsuda Kageyu.\n" - "All rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - " 1. Redistributions of source code must retain the above copyright\n" - " notice, this list of conditions and the following disclaimer.\n" - " 2. Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in the\n" - " documentation and/or other materials provided with the distribution.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n" - "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n" - "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER\n" - "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" - "\n" - "================================================================================\n" - "Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov.\n" - "================================================================================\n" - "Hacker Disassembler Engine 32 C\n" - "Copyright (c) 2008-2009, Vyacheslav Patkov.\n" - "All rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - " 1. Redistributions of source code must retain the above copyright\n" - " notice, this list of conditions and the following disclaimer.\n" - " 2. Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in the\n" - " documentation and/or other materials provided with the distribution.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n" - "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n" - "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR\n" - "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" - "\n" - "-------------------------------------------------------------------------------\n" - "Hacker Disassembler Engine 64 C\n" - "Copyright (c) 2008-2009, Vyacheslav Patkov.\n" - "All rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - " 1. Redistributions of source code must retain the above copyright\n" - " notice, this list of conditions and the following disclaimer.\n" - " 2. Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in the\n" - " documentation and/or other materials provided with the distribution.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n" - "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n" - "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR\n" - "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" - "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" - "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" - "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseMinHook = "MinHook - The Minimalistic API Hooking Library for x64/x86\n" + "Copyright (C) 2009-2017 Tsuda Kageyu.\n" + "All rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + " 1. Redistributions of source code must retain the above copyright\n" + " notice, this list of conditions and the following disclaimer.\n" + " 2. Redistributions in binary form must reproduce the above copyright\n" + " notice, this list of conditions and the following disclaimer in the\n" + " documentation and/or other materials provided with the distribution.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n" + "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n" + "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER\n" + "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + "\n" + "================================================================================\n" + "Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov.\n" + "================================================================================\n" + "Hacker Disassembler Engine 32 C\n" + "Copyright (c) 2008-2009, Vyacheslav Patkov.\n" + "All rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + " 1. Redistributions of source code must retain the above copyright\n" + " notice, this list of conditions and the following disclaimer.\n" + " 2. Redistributions in binary form must reproduce the above copyright\n" + " notice, this list of conditions and the following disclaimer in the\n" + " documentation and/or other materials provided with the distribution.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n" + "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n" + "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR\n" + "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + "\n" + "-------------------------------------------------------------------------------\n" + "Hacker Disassembler Engine 64 C\n" + "Copyright (c) 2008-2009, Vyacheslav Patkov.\n" + "All rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + " 1. Redistributions of source code must retain the above copyright\n" + " notice, this list of conditions and the following disclaimer.\n" + " 2. Redistributions in binary form must reproduce the above copyright\n" + " notice, this list of conditions and the following disclaimer in the\n" + " documentation and/or other materials provided with the distribution.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n" + "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n" + "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR\n" + "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n" + "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n" + "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n" + "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; #endif #ifdef USING_BUNDLED_QT_TRANSLATIONS -static const char *licenseQtTranslations = +static const char *licenseQtTranslations = "Mumble uses Qt translations created by the VirtualBox community\n" "under the MIT license. Files and copyright were obtained from:\n" "https://www.virtualbox.org/ticket/2018\n" @@ -785,439 +774,435 @@ static const char *licenseQtTranslations = #endif -static const char *licenseEmojiOne = - "Creative Commons Attribution-ShareAlike 4.0 International Public\n" - "License\n" - "\n" - "By exercising the Licensed Rights (defined below), You accept and agree\n" - "to be bound by the terms and conditions of this Creative Commons\n" - "Attribution-ShareAlike 4.0 International Public License (\"Public\n" - "License\"). To the extent this Public License may be interpreted as a\n" - "contract, You are granted the Licensed Rights in consideration of Your\n" - "acceptance of these terms and conditions, and the Licensor grants You\n" - "such rights in consideration of benefits the Licensor receives from\n" - "making the Licensed Material available under these terms and\n" - "conditions.\n" - "\n" - "\n" - "Section 1 -- Definitions.\n" - "\n" - " a. Adapted Material means material subject to Copyright and Similar\n" - " Rights that is derived from or based upon the Licensed Material\n" - " and in which the Licensed Material is translated, altered,\n" - " arranged, transformed, or otherwise modified in a manner requiring\n" - " permission under the Copyright and Similar Rights held by the\n" - " Licensor. For purposes of this Public License, where the Licensed\n" - " Material is a musical work, performance, or sound recording,\n" - " Adapted Material is always produced where the Licensed Material is\n" - " synched in timed relation with a moving image.\n" - "\n" - " b. Adapter's License means the license You apply to Your Copyright\n" - " and Similar Rights in Your contributions to Adapted Material in\n" - " accordance with the terms and conditions of this Public License.\n" - "\n" - " c. BY-SA Compatible License means a license listed at\n" - " creativecommons.org/compatiblelicenses, approved by Creative\n" - " Commons as essentially the equivalent of this Public License.\n" - "\n" - " d. Copyright and Similar Rights means copyright and/or similar rights\n" - " closely related to copyright including, without limitation,\n" - " performance, broadcast, sound recording, and Sui Generis Database\n" - " Rights, without regard to how the rights are labeled or\n" - " categorized. For purposes of this Public License, the rights\n" - " specified in Section 2(b)(1)-(2) are not Copyright and Similar\n" - " Rights.\n" - "\n" - " e. Effective Technological Measures means those measures that, in the\n" - " absence of proper authority, may not be circumvented under laws\n" - " fulfilling obligations under Article 11 of the WIPO Copyright\n" - " Treaty adopted on December 20, 1996, and/or similar international\n" - " agreements.\n" - "\n" - " f. Exceptions and Limitations means fair use, fair dealing, and/or\n" - " any other exception or limitation to Copyright and Similar Rights\n" - " that applies to Your use of the Licensed Material.\n" - "\n" - " g. License Elements means the license attributes listed in the name\n" - " of a Creative Commons Public License. The License Elements of this\n" - " Public License are Attribution and ShareAlike.\n" - "\n" - " h. Licensed Material means the artistic or literary work, database,\n" - " or other material to which the Licensor applied this Public\n" - " License.\n" - "\n" - " i. Licensed Rights means the rights granted to You subject to the\n" - " terms and conditions of this Public License, which are limited to\n" - " all Copyright and Similar Rights that apply to Your use of the\n" - " Licensed Material and that the Licensor has authority to license.\n" - "\n" - " j. Licensor means the individual(s) or entity(ies) granting rights\n" - " under this Public License.\n" - "\n" - " k. Share means to provide material to the public by any means or\n" - " process that requires permission under the Licensed Rights, such\n" - " as reproduction, public display, public performance, distribution,\n" - " dissemination, communication, or importation, and to make material\n" - " available to the public including in ways that members of the\n" - " public may access the material from a place and at a time\n" - " individually chosen by them.\n" - "\n" - " l. Sui Generis Database Rights means rights other than copyright\n" - " resulting from Directive 96/9/EC of the European Parliament and of\n" - " the Council of 11 March 1996 on the legal protection of databases,\n" - " as amended and/or succeeded, as well as other essentially\n" - " equivalent rights anywhere in the world.\n" - "\n" - " m. You means the individual or entity exercising the Licensed Rights\n" - " under this Public License. Your has a corresponding meaning.\n" - "\n" - "\n" - "Section 2 -- Scope.\n" - "\n" - " a. License grant.\n" - "\n" - " 1. Subject to the terms and conditions of this Public License,\n" - " the Licensor hereby grants You a worldwide, royalty-free,\n" - " non-sublicensable, non-exclusive, irrevocable license to\n" - " exercise the Licensed Rights in the Licensed Material to:\n" - "\n" - " a. reproduce and Share the Licensed Material, in whole or\n" - " in part; and\n" - "\n" - " b. produce, reproduce, and Share Adapted Material.\n" - "\n" - " 2. Exceptions and Limitations. For the avoidance of doubt, where\n" - " Exceptions and Limitations apply to Your use, this Public\n" - " License does not apply, and You do not need to comply with\n" - " its terms and conditions.\n" - "\n" - " 3. Term. The term of this Public License is specified in Section\n" - " 6(a).\n" - "\n" - " 4. Media and formats; technical modifications allowed. The\n" - " Licensor authorizes You to exercise the Licensed Rights in\n" - " all media and formats whether now known or hereafter created,\n" - " and to make technical modifications necessary to do so. The\n" - " Licensor waives and/or agrees not to assert any right or\n" - " authority to forbid You from making technical modifications\n" - " necessary to exercise the Licensed Rights, including\n" - " technical modifications necessary to circumvent Effective\n" - " Technological Measures. For purposes of this Public License,\n" - " simply making modifications authorized by this Section 2(a)\n" - " (4) never produces Adapted Material.\n" - "\n" - " 5. Downstream recipients.\n" - "\n" - " a. Offer from the Licensor -- Licensed Material. Every\n" - " recipient of the Licensed Material automatically\n" - " receives an offer from the Licensor to exercise the\n" - " Licensed Rights under the terms and conditions of this\n" - " Public License.\n" - "\n" - " b. Additional offer from the Licensor -- Adapted Material.\n" - " Every recipient of Adapted Material from You\n" - " automatically receives an offer from the Licensor to\n" - " exercise the Licensed Rights in the Adapted Material\n" - " under the conditions of the Adapter's License You apply.\n" - "\n" - " c. No downstream restrictions. You may not offer or impose\n" - " any additional or different terms or conditions on, or\n" - " apply any Effective Technological Measures to, the\n" - " Licensed Material if doing so restricts exercise of the\n" - " Licensed Rights by any recipient of the Licensed\n" - " Material.\n" - "\n" - " 6. No endorsement. Nothing in this Public License constitutes or\n" - " may be construed as permission to assert or imply that You\n" - " are, or that Your use of the Licensed Material is, connected\n" - " with, or sponsored, endorsed, or granted official status by,\n" - " the Licensor or others designated to receive attribution as\n" - " provided in Section 3(a)(1)(A)(i).\n" - "\n" - " b. Other rights.\n" - "\n" - " 1. Moral rights, such as the right of integrity, are not\n" - " licensed under this Public License, nor are publicity,\n" - " privacy, and/or other similar personality rights; however, to\n" - " the extent possible, the Licensor waives and/or agrees not to\n" - " assert any such rights held by the Licensor to the limited\n" - " extent necessary to allow You to exercise the Licensed\n" - " Rights, but not otherwise.\n" - "\n" - " 2. Patent and trademark rights are not licensed under this\n" - " Public License.\n" - "\n" - " 3. To the extent possible, the Licensor waives any right to\n" - " collect royalties from You for the exercise of the Licensed\n" - " Rights, whether directly or through a collecting society\n" - " under any voluntary or waivable statutory or compulsory\n" - " licensing scheme. In all other cases the Licensor expressly\n" - " reserves any right to collect such royalties.\n" - "\n" - "\n" - "Section 3 -- License Conditions.\n" - "\n" - "Your exercise of the Licensed Rights is expressly made subject to the\n" - "following conditions.\n" - "\n" - " a. Attribution.\n" - "\n" - " 1. If You Share the Licensed Material (including in modified\n" - " form), You must:\n" - "\n" - " a. retain the following if it is supplied by the Licensor\n" - " with the Licensed Material:\n" - "\n" - " i. identification of the creator(s) of the Licensed\n" - " Material and any others designated to receive\n" - " attribution, in any reasonable manner requested by\n" - " the Licensor (including by pseudonym if\n" - " designated);\n" - "\n" - " ii. a copyright notice;\n" - "\n" - " iii. a notice that refers to this Public License;\n" - "\n" - " iv. a notice that refers to the disclaimer of\n" - " warranties;\n" - "\n" - " v. a URI or hyperlink to the Licensed Material to the\n" - " extent reasonably practicable;\n" - "\n" - " b. indicate if You modified the Licensed Material and\n" - " retain an indication of any previous modifications; and\n" - "\n" - " c. indicate the Licensed Material is licensed under this\n" - " Public License, and include the text of, or the URI or\n" - " hyperlink to, this Public License.\n" - "\n" - " 2. You may satisfy the conditions in Section 3(a)(1) in any\n" - " reasonable manner based on the medium, means, and context in\n" - " which You Share the Licensed Material. For example, it may be\n" - " reasonable to satisfy the conditions by providing a URI or\n" - " hyperlink to a resource that includes the required\n" - " information.\n" - "\n" - " 3. If requested by the Licensor, You must remove any of the\n" - " information required by Section 3(a)(1)(A) to the extent\n" - " reasonably practicable.\n" - "\n" - " b. ShareAlike.\n" - "\n" - " In addition to the conditions in Section 3(a), if You Share\n" - " Adapted Material You produce, the following conditions also apply.\n" - "\n" - " 1. The Adapter's License You apply must be a Creative Commons\n" - " license with the same License Elements, this version or\n" - " later, or a BY-SA Compatible License.\n" - "\n" - " 2. You must include the text of, or the URI or hyperlink to, the\n" - " Adapter's License You apply. You may satisfy this condition\n" - " in any reasonable manner based on the medium, means, and\n" - " context in which You Share Adapted Material.\n" - "\n" - " 3. You may not offer or impose any additional or different terms\n" - " or conditions on, or apply any Effective Technological\n" - " Measures to, Adapted Material that restrict exercise of the\n" - " rights granted under the Adapter's License You apply.\n" - "\n" - "\n" - "Section 4 -- Sui Generis Database Rights.\n" - "\n" - "Where the Licensed Rights include Sui Generis Database Rights that\n" - "apply to Your use of the Licensed Material:\n" - "\n" - " a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n" - " to extract, reuse, reproduce, and Share all or a substantial\n" - " portion of the contents of the database;\n" - "\n" - " b. if You include all or a substantial portion of the database\n" - " contents in a database in which You have Sui Generis Database\n" - " Rights, then the database in which You have Sui Generis Database\n" - " Rights (but not its individual contents) is Adapted Material,\n" - "\n" - " including for purposes of Section 3(b); and\n" - " c. You must comply with the conditions in Section 3(a) if You Share\n" - " all or a substantial portion of the contents of the database.\n" - "\n" - "For the avoidance of doubt, this Section 4 supplements and does not\n" - "replace Your obligations under this Public License where the Licensed\n" - "Rights include other Copyright and Similar Rights.\n" - "\n" - "\n" - "Section 5 -- Disclaimer of Warranties and Limitation of Liability.\n" - "\n" - " a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n" - " EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n" - " AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n" - " ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n" - " IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n" - " WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n" - " PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n" - " ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n" - " KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n" - " ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n" - "\n" - " b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n" - " TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n" - " NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n" - " INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n" - " COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n" - " USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n" - " ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n" - " DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n" - " IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n" - "\n" - " c. The disclaimer of warranties and limitation of liability provided\n" - " above shall be interpreted in a manner that, to the extent\n" - " possible, most closely approximates an absolute disclaimer and\n" - " waiver of all liability.\n" - "\n" - "\n" - "Section 6 -- Term and Termination.\n" - "\n" - " a. This Public License applies for the term of the Copyright and\n" - " Similar Rights licensed here. However, if You fail to comply with\n" - " this Public License, then Your rights under this Public License\n" - " terminate automatically.\n" - "\n" - " b. Where Your right to use the Licensed Material has terminated under\n" - " Section 6(a), it reinstates:\n" - "\n" - " 1. automatically as of the date the violation is cured, provided\n" - " it is cured within 30 days of Your discovery of the\n" - " violation; or\n" - "\n" - " 2. upon express reinstatement by the Licensor.\n" - "\n" - " For the avoidance of doubt, this Section 6(b) does not affect any\n" - " right the Licensor may have to seek remedies for Your violations\n" - " of this Public License.\n" - "\n" - " c. For the avoidance of doubt, the Licensor may also offer the\n" - " Licensed Material under separate terms or conditions or stop\n" - " distributing the Licensed Material at any time; however, doing so\n" - " will not terminate this Public License.\n" - "\n" - " d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n" - " License.\n" - "\n" - "\n" - "Section 7 -- Other Terms and Conditions.\n" - "\n" - " a. The Licensor shall not be bound by any additional or different\n" - " terms or conditions communicated by You unless expressly agreed.\n" - "\n" - " b. Any arrangements, understandings, or agreements regarding the\n" - " Licensed Material not stated herein are separate from and\n" - " independent of the terms and conditions of this Public License.\n" - "\n" - "\n" - "Section 8 -- Interpretation.\n" - "\n" - " a. For the avoidance of doubt, this Public License does not, and\n" - " shall not be interpreted to, reduce, limit, restrict, or impose\n" - " conditions on any use of the Licensed Material that could lawfully\n" - " be made without permission under this Public License.\n" - "\n" - " b. To the extent possible, if any provision of this Public License is\n" - " deemed unenforceable, it shall be automatically reformed to the\n" - " minimum extent necessary to make it enforceable. If the provision\n" - " cannot be reformed, it shall be severed from this Public License\n" - " without affecting the enforceability of the remaining terms and\n" - " conditions.\n" - "\n" - " c. No term or condition of this Public License will be waived and no\n" - " failure to comply consented to unless expressly agreed to by the\n" - " Licensor.\n" - "\n" - " d. Nothing in this Public License constitutes or may be interpreted\n" - " as a limitation upon, or waiver of, any privileges and immunities\n" - " that apply to the Licensor or You, including from the legal\n" - " processes of any jurisdiction or authority."; +static const char *licenseEmojiOne = "Creative Commons Attribution-ShareAlike 4.0 International Public\n" + "License\n" + "\n" + "By exercising the Licensed Rights (defined below), You accept and agree\n" + "to be bound by the terms and conditions of this Creative Commons\n" + "Attribution-ShareAlike 4.0 International Public License (\"Public\n" + "License\"). To the extent this Public License may be interpreted as a\n" + "contract, You are granted the Licensed Rights in consideration of Your\n" + "acceptance of these terms and conditions, and the Licensor grants You\n" + "such rights in consideration of benefits the Licensor receives from\n" + "making the Licensed Material available under these terms and\n" + "conditions.\n" + "\n" + "\n" + "Section 1 -- Definitions.\n" + "\n" + " a. Adapted Material means material subject to Copyright and Similar\n" + " Rights that is derived from or based upon the Licensed Material\n" + " and in which the Licensed Material is translated, altered,\n" + " arranged, transformed, or otherwise modified in a manner requiring\n" + " permission under the Copyright and Similar Rights held by the\n" + " Licensor. For purposes of this Public License, where the Licensed\n" + " Material is a musical work, performance, or sound recording,\n" + " Adapted Material is always produced where the Licensed Material is\n" + " synched in timed relation with a moving image.\n" + "\n" + " b. Adapter's License means the license You apply to Your Copyright\n" + " and Similar Rights in Your contributions to Adapted Material in\n" + " accordance with the terms and conditions of this Public License.\n" + "\n" + " c. BY-SA Compatible License means a license listed at\n" + " creativecommons.org/compatiblelicenses, approved by Creative\n" + " Commons as essentially the equivalent of this Public License.\n" + "\n" + " d. Copyright and Similar Rights means copyright and/or similar rights\n" + " closely related to copyright including, without limitation,\n" + " performance, broadcast, sound recording, and Sui Generis Database\n" + " Rights, without regard to how the rights are labeled or\n" + " categorized. For purposes of this Public License, the rights\n" + " specified in Section 2(b)(1)-(2) are not Copyright and Similar\n" + " Rights.\n" + "\n" + " e. Effective Technological Measures means those measures that, in the\n" + " absence of proper authority, may not be circumvented under laws\n" + " fulfilling obligations under Article 11 of the WIPO Copyright\n" + " Treaty adopted on December 20, 1996, and/or similar international\n" + " agreements.\n" + "\n" + " f. Exceptions and Limitations means fair use, fair dealing, and/or\n" + " any other exception or limitation to Copyright and Similar Rights\n" + " that applies to Your use of the Licensed Material.\n" + "\n" + " g. License Elements means the license attributes listed in the name\n" + " of a Creative Commons Public License. The License Elements of this\n" + " Public License are Attribution and ShareAlike.\n" + "\n" + " h. Licensed Material means the artistic or literary work, database,\n" + " or other material to which the Licensor applied this Public\n" + " License.\n" + "\n" + " i. Licensed Rights means the rights granted to You subject to the\n" + " terms and conditions of this Public License, which are limited to\n" + " all Copyright and Similar Rights that apply to Your use of the\n" + " Licensed Material and that the Licensor has authority to license.\n" + "\n" + " j. Licensor means the individual(s) or entity(ies) granting rights\n" + " under this Public License.\n" + "\n" + " k. Share means to provide material to the public by any means or\n" + " process that requires permission under the Licensed Rights, such\n" + " as reproduction, public display, public performance, distribution,\n" + " dissemination, communication, or importation, and to make material\n" + " available to the public including in ways that members of the\n" + " public may access the material from a place and at a time\n" + " individually chosen by them.\n" + "\n" + " l. Sui Generis Database Rights means rights other than copyright\n" + " resulting from Directive 96/9/EC of the European Parliament and of\n" + " the Council of 11 March 1996 on the legal protection of databases,\n" + " as amended and/or succeeded, as well as other essentially\n" + " equivalent rights anywhere in the world.\n" + "\n" + " m. You means the individual or entity exercising the Licensed Rights\n" + " under this Public License. Your has a corresponding meaning.\n" + "\n" + "\n" + "Section 2 -- Scope.\n" + "\n" + " a. License grant.\n" + "\n" + " 1. Subject to the terms and conditions of this Public License,\n" + " the Licensor hereby grants You a worldwide, royalty-free,\n" + " non-sublicensable, non-exclusive, irrevocable license to\n" + " exercise the Licensed Rights in the Licensed Material to:\n" + "\n" + " a. reproduce and Share the Licensed Material, in whole or\n" + " in part; and\n" + "\n" + " b. produce, reproduce, and Share Adapted Material.\n" + "\n" + " 2. Exceptions and Limitations. For the avoidance of doubt, where\n" + " Exceptions and Limitations apply to Your use, this Public\n" + " License does not apply, and You do not need to comply with\n" + " its terms and conditions.\n" + "\n" + " 3. Term. The term of this Public License is specified in Section\n" + " 6(a).\n" + "\n" + " 4. Media and formats; technical modifications allowed. The\n" + " Licensor authorizes You to exercise the Licensed Rights in\n" + " all media and formats whether now known or hereafter created,\n" + " and to make technical modifications necessary to do so. The\n" + " Licensor waives and/or agrees not to assert any right or\n" + " authority to forbid You from making technical modifications\n" + " necessary to exercise the Licensed Rights, including\n" + " technical modifications necessary to circumvent Effective\n" + " Technological Measures. For purposes of this Public License,\n" + " simply making modifications authorized by this Section 2(a)\n" + " (4) never produces Adapted Material.\n" + "\n" + " 5. Downstream recipients.\n" + "\n" + " a. Offer from the Licensor -- Licensed Material. Every\n" + " recipient of the Licensed Material automatically\n" + " receives an offer from the Licensor to exercise the\n" + " Licensed Rights under the terms and conditions of this\n" + " Public License.\n" + "\n" + " b. Additional offer from the Licensor -- Adapted Material.\n" + " Every recipient of Adapted Material from You\n" + " automatically receives an offer from the Licensor to\n" + " exercise the Licensed Rights in the Adapted Material\n" + " under the conditions of the Adapter's License You apply.\n" + "\n" + " c. No downstream restrictions. You may not offer or impose\n" + " any additional or different terms or conditions on, or\n" + " apply any Effective Technological Measures to, the\n" + " Licensed Material if doing so restricts exercise of the\n" + " Licensed Rights by any recipient of the Licensed\n" + " Material.\n" + "\n" + " 6. No endorsement. Nothing in this Public License constitutes or\n" + " may be construed as permission to assert or imply that You\n" + " are, or that Your use of the Licensed Material is, connected\n" + " with, or sponsored, endorsed, or granted official status by,\n" + " the Licensor or others designated to receive attribution as\n" + " provided in Section 3(a)(1)(A)(i).\n" + "\n" + " b. Other rights.\n" + "\n" + " 1. Moral rights, such as the right of integrity, are not\n" + " licensed under this Public License, nor are publicity,\n" + " privacy, and/or other similar personality rights; however, to\n" + " the extent possible, the Licensor waives and/or agrees not to\n" + " assert any such rights held by the Licensor to the limited\n" + " extent necessary to allow You to exercise the Licensed\n" + " Rights, but not otherwise.\n" + "\n" + " 2. Patent and trademark rights are not licensed under this\n" + " Public License.\n" + "\n" + " 3. To the extent possible, the Licensor waives any right to\n" + " collect royalties from You for the exercise of the Licensed\n" + " Rights, whether directly or through a collecting society\n" + " under any voluntary or waivable statutory or compulsory\n" + " licensing scheme. In all other cases the Licensor expressly\n" + " reserves any right to collect such royalties.\n" + "\n" + "\n" + "Section 3 -- License Conditions.\n" + "\n" + "Your exercise of the Licensed Rights is expressly made subject to the\n" + "following conditions.\n" + "\n" + " a. Attribution.\n" + "\n" + " 1. If You Share the Licensed Material (including in modified\n" + " form), You must:\n" + "\n" + " a. retain the following if it is supplied by the Licensor\n" + " with the Licensed Material:\n" + "\n" + " i. identification of the creator(s) of the Licensed\n" + " Material and any others designated to receive\n" + " attribution, in any reasonable manner requested by\n" + " the Licensor (including by pseudonym if\n" + " designated);\n" + "\n" + " ii. a copyright notice;\n" + "\n" + " iii. a notice that refers to this Public License;\n" + "\n" + " iv. a notice that refers to the disclaimer of\n" + " warranties;\n" + "\n" + " v. a URI or hyperlink to the Licensed Material to the\n" + " extent reasonably practicable;\n" + "\n" + " b. indicate if You modified the Licensed Material and\n" + " retain an indication of any previous modifications; and\n" + "\n" + " c. indicate the Licensed Material is licensed under this\n" + " Public License, and include the text of, or the URI or\n" + " hyperlink to, this Public License.\n" + "\n" + " 2. You may satisfy the conditions in Section 3(a)(1) in any\n" + " reasonable manner based on the medium, means, and context in\n" + " which You Share the Licensed Material. For example, it may be\n" + " reasonable to satisfy the conditions by providing a URI or\n" + " hyperlink to a resource that includes the required\n" + " information.\n" + "\n" + " 3. If requested by the Licensor, You must remove any of the\n" + " information required by Section 3(a)(1)(A) to the extent\n" + " reasonably practicable.\n" + "\n" + " b. ShareAlike.\n" + "\n" + " In addition to the conditions in Section 3(a), if You Share\n" + " Adapted Material You produce, the following conditions also apply.\n" + "\n" + " 1. The Adapter's License You apply must be a Creative Commons\n" + " license with the same License Elements, this version or\n" + " later, or a BY-SA Compatible License.\n" + "\n" + " 2. You must include the text of, or the URI or hyperlink to, the\n" + " Adapter's License You apply. You may satisfy this condition\n" + " in any reasonable manner based on the medium, means, and\n" + " context in which You Share Adapted Material.\n" + "\n" + " 3. You may not offer or impose any additional or different terms\n" + " or conditions on, or apply any Effective Technological\n" + " Measures to, Adapted Material that restrict exercise of the\n" + " rights granted under the Adapter's License You apply.\n" + "\n" + "\n" + "Section 4 -- Sui Generis Database Rights.\n" + "\n" + "Where the Licensed Rights include Sui Generis Database Rights that\n" + "apply to Your use of the Licensed Material:\n" + "\n" + " a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n" + " to extract, reuse, reproduce, and Share all or a substantial\n" + " portion of the contents of the database;\n" + "\n" + " b. if You include all or a substantial portion of the database\n" + " contents in a database in which You have Sui Generis Database\n" + " Rights, then the database in which You have Sui Generis Database\n" + " Rights (but not its individual contents) is Adapted Material,\n" + "\n" + " including for purposes of Section 3(b); and\n" + " c. You must comply with the conditions in Section 3(a) if You Share\n" + " all or a substantial portion of the contents of the database.\n" + "\n" + "For the avoidance of doubt, this Section 4 supplements and does not\n" + "replace Your obligations under this Public License where the Licensed\n" + "Rights include other Copyright and Similar Rights.\n" + "\n" + "\n" + "Section 5 -- Disclaimer of Warranties and Limitation of Liability.\n" + "\n" + " a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n" + " EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n" + " AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n" + " ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n" + " IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n" + " WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n" + " PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n" + " ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n" + " KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n" + " ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n" + "\n" + " b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n" + " TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n" + " NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n" + " INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n" + " COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n" + " USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n" + " ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n" + " DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n" + " IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n" + "\n" + " c. The disclaimer of warranties and limitation of liability provided\n" + " above shall be interpreted in a manner that, to the extent\n" + " possible, most closely approximates an absolute disclaimer and\n" + " waiver of all liability.\n" + "\n" + "\n" + "Section 6 -- Term and Termination.\n" + "\n" + " a. This Public License applies for the term of the Copyright and\n" + " Similar Rights licensed here. However, if You fail to comply with\n" + " this Public License, then Your rights under this Public License\n" + " terminate automatically.\n" + "\n" + " b. Where Your right to use the Licensed Material has terminated under\n" + " Section 6(a), it reinstates:\n" + "\n" + " 1. automatically as of the date the violation is cured, provided\n" + " it is cured within 30 days of Your discovery of the\n" + " violation; or\n" + "\n" + " 2. upon express reinstatement by the Licensor.\n" + "\n" + " For the avoidance of doubt, this Section 6(b) does not affect any\n" + " right the Licensor may have to seek remedies for Your violations\n" + " of this Public License.\n" + "\n" + " c. For the avoidance of doubt, the Licensor may also offer the\n" + " Licensed Material under separate terms or conditions or stop\n" + " distributing the Licensed Material at any time; however, doing so\n" + " will not terminate this Public License.\n" + "\n" + " d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n" + " License.\n" + "\n" + "\n" + "Section 7 -- Other Terms and Conditions.\n" + "\n" + " a. The Licensor shall not be bound by any additional or different\n" + " terms or conditions communicated by You unless expressly agreed.\n" + "\n" + " b. Any arrangements, understandings, or agreements regarding the\n" + " Licensed Material not stated herein are separate from and\n" + " independent of the terms and conditions of this Public License.\n" + "\n" + "\n" + "Section 8 -- Interpretation.\n" + "\n" + " a. For the avoidance of doubt, this Public License does not, and\n" + " shall not be interpreted to, reduce, limit, restrict, or impose\n" + " conditions on any use of the Licensed Material that could lawfully\n" + " be made without permission under this Public License.\n" + "\n" + " b. To the extent possible, if any provision of this Public License is\n" + " deemed unenforceable, it shall be automatically reformed to the\n" + " minimum extent necessary to make it enforceable. If the provision\n" + " cannot be reformed, it shall be severed from this Public License\n" + " without affecting the enforceability of the remaining terms and\n" + " conditions.\n" + "\n" + " c. No term or condition of this Public License will be waived and no\n" + " failure to comply consented to unless expressly agreed to by the\n" + " Licensor.\n" + "\n" + " d. Nothing in this Public License constitutes or may be interpreted\n" + " as a limitation upon, or waiver of, any privileges and immunities\n" + " that apply to the Licensor or You, including from the legal\n" + " processes of any jurisdiction or authority."; -static const char *licenseXInputCheck = - "Simple DirectMedia Layer\n" - "Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>\n" - " \n" - "This software is provided 'as-is', without any express or implied\n" - "warranty. In no event will the authors be held liable for any damages\n" - "arising from the use of this software.\n" - "\n" - "Permission is granted to anyone to use this software for any purpose,\n" - "including commercial applications, and to alter it and redistribute it\n" - "freely, subject to the following restrictions:\n" - " \n" - "1. The origin of this software must not be misrepresented; you must not\n" - " claim that you wrote the original software. If you use this software\n" - " in a product, an acknowledgment in the product documentation would be\n" - " appreciated but is not required. \n" - "2. Altered source versions must be plainly marked as such, and must not be\n" - " misrepresented as being the original software.\n" - "3. This notice may not be removed or altered from any source distribution."; +static const char *licenseXInputCheck = "Simple DirectMedia Layer\n" + "Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>\n" + " \n" + "This software is provided 'as-is', without any express or implied\n" + "warranty. In no event will the authors be held liable for any damages\n" + "arising from the use of this software.\n" + "\n" + "Permission is granted to anyone to use this software for any purpose,\n" + "including commercial applications, and to alter it and redistribute it\n" + "freely, subject to the following restrictions:\n" + " \n" + "1. The origin of this software must not be misrepresented; you must not\n" + " claim that you wrote the original software. If you use this software\n" + " in a product, an acknowledgment in the product documentation would be\n" + " appreciated but is not required. \n" + "2. Altered source versions must be plainly marked as such, and must not be\n" + " misrepresented as being the original software.\n" + "3. This notice may not be removed or altered from any source distribution."; -static const char *licenseQQBonjour = - "Copyright (c) 2007, Trenton Schulz\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions are met:\n" - "\n" - " 1. Redistributions of source code must retain the above copyright notice,\n" - " this list of conditions and the following disclaimer.\n" - "\n" - " 2. Redistributions in binary form must reproduce the above copyright notice,\n" - " this list of conditions and the following disclaimer in the documentation\n" - " and/or other materials provided with the distribution.\n" - "\n" - " 3. The name of the author may not be used to endorse or promote products\n" - " derived from this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n" - "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" - "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n" - "EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" - "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" - "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n" - "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n" - "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n" - "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n" - "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseQQBonjour = "Copyright (c) 2007, Trenton Schulz\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions are met:\n" + "\n" + " 1. Redistributions of source code must retain the above copyright notice,\n" + " this list of conditions and the following disclaimer.\n" + "\n" + " 2. Redistributions in binary form must reproduce the above copyright notice,\n" + " this list of conditions and the following disclaimer in the documentation\n" + " and/or other materials provided with the distribution.\n" + "\n" + " 3. The name of the author may not be used to endorse or promote products\n" + " derived from this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n" + "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" + "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n" + "EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" + "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n" + "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n" + "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n" + "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n" + "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; -static const char *licenseSmallFT = - "Copyright (c) 2002-2007 Xiph.org Foundation\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "- Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - "\n" - "- Redistributions in binary form must reproduce the above copyright\n" - "notice, this list of conditions and the following disclaimer in the\n" - "documentation and/or other materials provided with the distribution.\n" - "\n" - "- Neither the name of the Xiph.org Foundation nor the names of its\n" - "contributors may be used to endorse or promote products derived from\n" - "this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION\n" - "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" - "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" - "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" - "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" - "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" - "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" - "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseSmallFT = "Copyright (c) 2002-2007 Xiph.org Foundation\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "- Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + "\n" + "- Redistributions in binary form must reproduce the above copyright\n" + "notice, this list of conditions and the following disclaimer in the\n" + "documentation and/or other materials provided with the distribution.\n" + "\n" + "- Neither the name of the Xiph.org Foundation nor the names of its\n" + "contributors may be used to endorse or promote products derived from\n" + "this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION\n" + "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" + "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" + "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" + "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" + "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" + "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" + "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; -static const char *licenseOldStyleLicenseHeaders = +static const char *licenseOldStyleLicenseHeaders = "Mumble's AudioConfigDialog\n" "\n" " src/mumble/AudioConfigDialog.cpp\n" @@ -1410,7 +1395,7 @@ static const char *licenseOldStyleLicenseHeaders = "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; -static const char *licenseArc4RandomUniform = +static const char *licenseArc4RandomUniform = "Copyright (c) 2008, Damien Miller <djm@openbsd.org>\n" "\n" "Permission to use, copy, modify, and distribute this software for any\n" @@ -1427,194 +1412,188 @@ static const char *licenseArc4RandomUniform = #ifdef USE_BUILDENV -static const char *licenseMariaDBCConnector = - "This library is free software; you can redistribute it and/or\n" - "modify it under the terms of the GNU Lesser General Public\n" - "License as published by the Free Software Foundation; either\n" - "version 2.1 of the License, or (at your option) any later version.\n" - "\n" - "This library is distributed in the hope that it will be useful,\n" - "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" - "Lesser General Public License for more details.\n" - "\n" - "You should have received a copy of the GNU Lesser General Public\n" - "License along with this library; if not, write to the Free Software\n" - "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n" - "02110-1301 USA"; +static const char *licenseMariaDBCConnector = "This library is free software; you can redistribute it and/or\n" + "modify it under the terms of the GNU Lesser General Public\n" + "License as published by the Free Software Foundation; either\n" + "version 2.1 of the License, or (at your option) any later version.\n" + "\n" + "This library is distributed in the hope that it will be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" + "Lesser General Public License for more details.\n" + "\n" + "You should have received a copy of the GNU Lesser General Public\n" + "License along with this library; if not, write to the Free Software\n" + "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n" + "02110-1301 USA"; #endif #ifdef USE_BUILDENV -static const char *licenseZlib = - "(C) 1995-2017 Jean-loup Gailly and Mark Adler\n" - "\n" - "This software is provided 'as-is', without any express or implied\n" - "warranty. In no event will the authors be held liable for any damages\n" - "arising from the use of this software.\n" - "\n" - "Permission is granted to anyone to use this software for any purpose,\n" - "including commercial applications, and to alter it and redistribute it\n" - "freely, subject to the following restrictions:\n" - "\n" - "1. The origin of this software must not be misrepresented; you must not\n" - " claim that you wrote the original software. If you use this software\n" - " in a product, an acknowledgment in the product documentation would be\n" - " appreciated but is not required.\n" - "2. Altered source versions must be plainly marked as such, and must not be\n" - " misrepresented as being the original software.\n" - "3. This notice may not be removed or altered from any source distribution.\n" - "\n" - "Jean-loup Gailly Mark Adler\n" - "jloup@gzip.org madler@alumni.caltech.edu"; +static const char *licenseZlib = "(C) 1995-2017 Jean-loup Gailly and Mark Adler\n" + "\n" + "This software is provided 'as-is', without any express or implied\n" + "warranty. In no event will the authors be held liable for any damages\n" + "arising from the use of this software.\n" + "\n" + "Permission is granted to anyone to use this software for any purpose,\n" + "including commercial applications, and to alter it and redistribute it\n" + "freely, subject to the following restrictions:\n" + "\n" + "1. The origin of this software must not be misrepresented; you must not\n" + " claim that you wrote the original software. If you use this software\n" + " in a product, an acknowledgment in the product documentation would be\n" + " appreciated but is not required.\n" + "2. Altered source versions must be plainly marked as such, and must not be\n" + " misrepresented as being the original software.\n" + "3. This notice may not be removed or altered from any source distribution.\n" + "\n" + "Jean-loup Gailly Mark Adler\n" + "jloup@gzip.org madler@alumni.caltech.edu"; #endif #ifdef USE_BUILDENV -static const char *licenseProtobuf = - "This license applies to all parts of Protocol Buffers except the following:\n" - "\n" - " - Atomicops support for generic gcc, located in\n" - " src/google/protobuf/stubs/atomicops_internals_generic_gcc.h.\n" - " This file is copyrighted by Red Hat Inc.\n" - "\n" - " - Atomicops support for AIX/POWER, located in\n" - " src/google/protobuf/stubs/atomicops_internals_power.h.\n" - " This file is copyrighted by Bloomberg Finance LP.\n" - "\n" - "Copyright 2014, Google Inc. All rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions are\n" - "met:\n" - "\n" - " * Redistributions of source code must retain the above copyright\n" - "notice, this list of conditions and the following disclaimer.\n" - " * Redistributions in binary form must reproduce the above\n" - "copyright notice, this list of conditions and the following disclaimer\n" - "in the documentation and/or other materials provided with the\n" - "distribution.\n" - " * Neither the name of Google Inc. nor the names of its\n" - "contributors may be used to endorse or promote products derived from\n" - "this software without specific prior written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" - "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" - "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" - "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" - "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" - "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" - "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" - "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" - "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" - "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" - "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" - "\n" - "Code generated by the Protocol Buffer compiler is owned by the owner\n" - "of the input file used when generating it. This code is not\n" - "standalone and requires a support library to be linked with it. This\n" - "support library is itself covered by the above license."; +static const char *licenseProtobuf = "This license applies to all parts of Protocol Buffers except the following:\n" + "\n" + " - Atomicops support for generic gcc, located in\n" + " src/google/protobuf/stubs/atomicops_internals_generic_gcc.h.\n" + " This file is copyrighted by Red Hat Inc.\n" + "\n" + " - Atomicops support for AIX/POWER, located in\n" + " src/google/protobuf/stubs/atomicops_internals_power.h.\n" + " This file is copyrighted by Bloomberg Finance LP.\n" + "\n" + "Copyright 2014, Google Inc. All rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions are\n" + "met:\n" + "\n" + " * Redistributions of source code must retain the above copyright\n" + "notice, this list of conditions and the following disclaimer.\n" + " * Redistributions in binary form must reproduce the above\n" + "copyright notice, this list of conditions and the following disclaimer\n" + "in the documentation and/or other materials provided with the\n" + "distribution.\n" + " * Neither the name of Google Inc. nor the names of its\n" + "contributors may be used to endorse or promote products derived from\n" + "this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" + "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" + "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" + "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" + "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" + "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" + "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" + "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" + "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" + "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" + "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + "\n" + "Code generated by the Protocol Buffer compiler is owned by the owner\n" + "of the input file used when generating it. This code is not\n" + "standalone and requires a support library to be linked with it. This\n" + "support library is itself covered by the above license."; #endif #ifdef USE_BUILDENV -static const char *licenseExpat = - "Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper\n" - "Copyright (c) 2001-2016 Expat maintainers\n" - "\n" - "Permission is hereby granted, free of charge, to any person obtaining\n" - "a copy of this software and associated documentation files (the\n" - "\"Software\"), to deal in the Software without restriction, including\n" - "without limitation the rights to use, copy, modify, merge, publish,\n" - "distribute, sublicense, and/or sell copies of the Software, and to\n" - "permit persons to whom the Software is furnished to do so, subject to\n" - "the following conditions:\n" - "\n" - "The above copyright notice and this permission notice shall be included\n" - "in all copies or substantial portions of the Software.\n" - "\n" - "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" - "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" - "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n" - "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n" - "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n" - "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n" - "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."; +static const char *licenseExpat = "Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper\n" + "Copyright (c) 2001-2016 Expat maintainers\n" + "\n" + "Permission is hereby granted, free of charge, to any person obtaining\n" + "a copy of this software and associated documentation files (the\n" + "\"Software\"), to deal in the Software without restriction, including\n" + "without limitation the rights to use, copy, modify, merge, publish,\n" + "distribute, sublicense, and/or sell copies of the Software, and to\n" + "permit persons to whom the Software is furnished to do so, subject to\n" + "the following conditions:\n" + "\n" + "The above copyright notice and this permission notice shall be included\n" + "in all copies or substantial portions of the Software.\n" + "\n" + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" + "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" + "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n" + "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n" + "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n" + "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n" + "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."; #endif #ifdef USE_BUILDENV -static const char *licenseBoost = - "Boost Software License - Version 1.0 - August 17th, 2003\n" - "\n" - "Permission is hereby granted, free of charge, to any person or organization\n" - "obtaining a copy of the software and accompanying documentation covered by\n" - "this license (the \"Software\") to use, reproduce, display, distribute,\n" - "execute, and transmit the Software, and to prepare derivative works of the\n" - "Software, and to permit third-parties to whom the Software is furnished to\n" - "do so, all subject to the following:\n" - "\n" - "The copyright notices in the Software and this entire statement, including\n" - "the above license grant, this restriction and the following disclaimer,\n" - "must be included in all copies of the Software, in whole or in part, and\n" - "all derivative works of the Software, unless such copies or derivative\n" - "works are solely in the form of machine-executable object code generated by\n" - "a source language processor.\n" - "\n" - "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" - "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" - "FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\n" - "SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\n" - "FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\n" - "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n" - "DEALINGS IN THE SOFTWARE."; +static const char *licenseBoost = "Boost Software License - Version 1.0 - August 17th, 2003\n" + "\n" + "Permission is hereby granted, free of charge, to any person or organization\n" + "obtaining a copy of the software and accompanying documentation covered by\n" + "this license (the \"Software\") to use, reproduce, display, distribute,\n" + "execute, and transmit the Software, and to prepare derivative works of the\n" + "Software, and to permit third-parties to whom the Software is furnished to\n" + "do so, all subject to the following:\n" + "\n" + "The copyright notices in the Software and this entire statement, including\n" + "the above license grant, this restriction and the following disclaimer,\n" + "must be included in all copies of the Software, in whole or in part, and\n" + "all derivative works of the Software, unless such copies or derivative\n" + "works are solely in the form of machine-executable object code generated by\n" + "a source language processor.\n" + "\n" + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" + "FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\n" + "SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\n" + "FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\n" + "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n" + "DEALINGS IN THE SOFTWARE."; #endif #ifdef USE_BUILDENV -static const char *licenseBzip2 = - "This program, \"bzip2\", the associated library \"libbzip2\", and all\n" - "documentation, are copyright (C) 1996-2010 Julian R Seward. All\n" - "rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "\n" - "1. Redistributions of source code must retain the above copyright\n" - " notice, this list of conditions and the following disclaimer.\n" - "\n" - "2. The origin of this software must not be misrepresented; you must \n" - " not claim that you wrote the original software. If you use this \n" - " software in a product, an acknowledgment in the product \n" - " documentation would be appreciated but is not required.\n" - "\n" - "3. Altered source versions must be plainly marked as such, and must\n" - " not be misrepresented as being the original software.\n" - "\n" - "4. The name of the author may not be used to endorse or promote \n" - " products derived from this software without specific prior written \n" - " permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS\n" - "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n" - "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" - "ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n" - "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" - "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n" - "GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" - "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n" - "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" - "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" - "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" - "\n" - "Julian Seward, jseward@bzip.org\n" - "bzip2/libbzip2 version 1.0.6 of 6 September 2010"; +static const char *licenseBzip2 = "This program, \"bzip2\", the associated library \"libbzip2\", and all\n" + "documentation, are copyright (C) 1996-2010 Julian R Seward. All\n" + "rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "\n" + "1. Redistributions of source code must retain the above copyright\n" + " notice, this list of conditions and the following disclaimer.\n" + "\n" + "2. The origin of this software must not be misrepresented; you must \n" + " not claim that you wrote the original software. If you use this \n" + " software in a product, an acknowledgment in the product \n" + " documentation would be appreciated but is not required.\n" + "\n" + "3. Altered source versions must be plainly marked as such, and must\n" + " not be misrepresented as being the original software.\n" + "\n" + "4. The name of the author may not be used to endorse or promote \n" + " products derived from this software without specific prior written \n" + " permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS\n" + "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n" + "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" + "ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n" + "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" + "DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n" + "GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n" + "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n" + "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n" + "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" + "\n" + "Julian Seward, jseward@bzip.org\n" + "bzip2/libbzip2 version 1.0.6 of 6 September 2010"; #endif #ifdef USE_BUILDENV -static const char *licenseBerkeleyDB = +static const char *licenseBerkeleyDB = "/*\n" " * Copyright (c) 1990, 2013 Oracle and/or its affiliates. All rights reserved.\n" " *\n" @@ -1739,181 +1718,180 @@ static const char *licenseBerkeleyDB = #ifdef USE_BUILDENV -static const char *licenseFreetype = - " The FreeType Project LICENSE\n" - " ----------------------------\n" - "\n" - " 2006-Jan-27\n" - "\n" - " Copyright 1996-2002, 2006 by\n" - " David Turner, Robert Wilhelm, and Werner Lemberg\n" - "\n" - "\n" - "\n" - "Introduction\n" - "============\n" - "\n" - " The FreeType Project is distributed in several archive packages;\n" - " some of them may contain, in addition to the FreeType font engine,\n" - " various tools and contributions which rely on, or relate to, the\n" - " FreeType Project.\n" - "\n" - " This license applies to all files found in such packages, and\n" - " which do not fall under their own explicit license. The license\n" - " affects thus the FreeType font engine, the test programs,\n" - " documentation and makefiles, at the very least.\n" - "\n" - " This license was inspired by the BSD, Artistic, and IJG\n" - " (Independent JPEG Group) licenses, which all encourage inclusion\n" - " and use of free software in commercial and freeware products\n" - " alike. As a consequence, its main points are that:\n" - "\n" - " o We don't promise that this software works. However, we will be\n" - " interested in any kind of bug reports. (`as is' distribution)\n" - "\n" - " o You can use this software for whatever you want, in parts or\n" - " full form, without having to pay us. (`royalty-free' usage)\n" - "\n" - " o You may not pretend that you wrote this software. If you use\n" - " it, or only parts of it, in a program, you must acknowledge\n" - " somewhere in your documentation that you have used the\n" - " FreeType code. (`credits')\n" - "\n" - " We specifically permit and encourage the inclusion of this\n" - " software, with or without modifications, in commercial products.\n" - " We disclaim all warranties covering The FreeType Project and\n" - " assume no liability related to The FreeType Project.\n" - "\n" - "\n" - " Finally, many people asked us for a preferred form for a\n" - " credit/disclaimer to use in compliance with this license. We thus\n" - " encourage you to use the following text:\n" - "\n" - " \"\"\"\n" - " Portions of this software are copyright © <year> The FreeType\n" - " Project (www.freetype.org). All rights reserved.\n" - " \"\"\"\n" - "\n" - " Please replace <year> with the value from the FreeType version you\n" - " actually use.\n" - "\n" - "\n" - "Legal Terms\n" - "===========\n" - "\n" - "0. Definitions\n" - "--------------\n" - "\n" - " Throughout this license, the terms `package', `FreeType Project',\n" - " and `FreeType archive' refer to the set of files originally\n" - " distributed by the authors (David Turner, Robert Wilhelm, and\n" - " Werner Lemberg) as the `FreeType Project', be they named as alpha,\n" - " beta or final release.\n" - "\n" - " `You' refers to the licensee, or person using the project, where\n" - " `using' is a generic term including compiling the project's source\n" - " code as well as linking it to form a `program' or `executable'.\n" - " This program is referred to as `a program using the FreeType\n" - " engine'.\n" - "\n" - " This license applies to all files distributed in the original\n" - " FreeType Project, including all source code, binaries and\n" - " documentation, unless otherwise stated in the file in its\n" - " original, unmodified form as distributed in the original archive.\n" - " If you are unsure whether or not a particular file is covered by\n" - " this license, you must contact us to verify this.\n" - "\n" - " The FreeType Project is copyright (C) 1996-2000 by David Turner,\n" - " Robert Wilhelm, and Werner Lemberg. All rights reserved except as\n" - " specified below.\n" - "\n" - "1. No Warranty\n" - "--------------\n" - "\n" - " THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY\n" - " KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\n" - " WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" - " PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS\n" - " BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO\n" - " USE, OF THE FREETYPE PROJECT.\n" - "\n" - "2. Redistribution\n" - "-----------------\n" - "\n" - " This license grants a worldwide, royalty-free, perpetual and\n" - " irrevocable right and license to use, execute, perform, compile,\n" - " display, copy, create derivative works of, distribute and\n" - " sublicense the FreeType Project (in both source and object code\n" - " forms) and derivative works thereof for any purpose; and to\n" - " authorize others to exercise some or all of the rights granted\n" - " herein, subject to the following conditions:\n" - "\n" - " o Redistribution of source code must retain this license file\n" - " (`FTL.TXT') unaltered; any additions, deletions or changes to\n" - " the original files must be clearly indicated in accompanying\n" - " documentation. The copyright notices of the unaltered,\n" - " original files must be preserved in all copies of source\n" - " files.\n" - "\n" - " o Redistribution in binary form must provide a disclaimer that\n" - " states that the software is based in part of the work of the\n" - " FreeType Team, in the distribution documentation. We also\n" - " encourage you to put an URL to the FreeType web page in your\n" - " documentation, though this isn't mandatory.\n" - "\n" - " These conditions apply to any software derived from or based on\n" - " the FreeType Project, not just the unmodified files. If you use\n" - " our work, you must acknowledge us. However, no fee need be paid\n" - " to us.\n" - "\n" - "3. Advertising\n" - "--------------\n" - "\n" - " Neither the FreeType authors and contributors nor you shall use\n" - " the name of the other for commercial, advertising, or promotional\n" - " purposes without specific prior written permission.\n" - "\n" - " We suggest, but do not require, that you use one or more of the\n" - " following phrases to refer to this software in your documentation\n" - " or advertising materials: `FreeType Project', `FreeType Engine',\n" - " `FreeType library', or `FreeType Distribution'.\n" - "\n" - " As you have not signed this license, you are not required to\n" - " accept it. However, as the FreeType Project is copyrighted\n" - " material, only this license, or another one contracted with the\n" - " authors, grants you the right to use, distribute, and modify it.\n" - " Therefore, by using, distributing, or modifying the FreeType\n" - " Project, you indicate that you understand and accept all the terms\n" - " of this license.\n" - "\n" - "4. Contacts\n" - "-----------\n" - "\n" - " There are two mailing lists related to FreeType:\n" - "\n" - " o freetype@nongnu.org\n" - "\n" - " Discusses general use and applications of FreeType, as well as\n" - " future and wanted additions to the library and distribution.\n" - " If you are looking for support, start in this list if you\n" - " haven't found anything to help you in the documentation.\n" - "\n" - " o freetype-devel@nongnu.org\n" - "\n" - " Discusses bugs, as well as engine internals, design issues,\n" - " specific licenses, porting, etc.\n" - "\n" - " Our home page can be found at\n" - "\n" - " http://www.freetype.org\n" - "\n" - "\n" - "--- end of FTL.TXT ---"; +static const char *licenseFreetype = " The FreeType Project LICENSE\n" + " ----------------------------\n" + "\n" + " 2006-Jan-27\n" + "\n" + " Copyright 1996-2002, 2006 by\n" + " David Turner, Robert Wilhelm, and Werner Lemberg\n" + "\n" + "\n" + "\n" + "Introduction\n" + "============\n" + "\n" + " The FreeType Project is distributed in several archive packages;\n" + " some of them may contain, in addition to the FreeType font engine,\n" + " various tools and contributions which rely on, or relate to, the\n" + " FreeType Project.\n" + "\n" + " This license applies to all files found in such packages, and\n" + " which do not fall under their own explicit license. The license\n" + " affects thus the FreeType font engine, the test programs,\n" + " documentation and makefiles, at the very least.\n" + "\n" + " This license was inspired by the BSD, Artistic, and IJG\n" + " (Independent JPEG Group) licenses, which all encourage inclusion\n" + " and use of free software in commercial and freeware products\n" + " alike. As a consequence, its main points are that:\n" + "\n" + " o We don't promise that this software works. However, we will be\n" + " interested in any kind of bug reports. (`as is' distribution)\n" + "\n" + " o You can use this software for whatever you want, in parts or\n" + " full form, without having to pay us. (`royalty-free' usage)\n" + "\n" + " o You may not pretend that you wrote this software. If you use\n" + " it, or only parts of it, in a program, you must acknowledge\n" + " somewhere in your documentation that you have used the\n" + " FreeType code. (`credits')\n" + "\n" + " We specifically permit and encourage the inclusion of this\n" + " software, with or without modifications, in commercial products.\n" + " We disclaim all warranties covering The FreeType Project and\n" + " assume no liability related to The FreeType Project.\n" + "\n" + "\n" + " Finally, many people asked us for a preferred form for a\n" + " credit/disclaimer to use in compliance with this license. We thus\n" + " encourage you to use the following text:\n" + "\n" + " \"\"\"\n" + " Portions of this software are copyright © <year> The FreeType\n" + " Project (www.freetype.org). All rights reserved.\n" + " \"\"\"\n" + "\n" + " Please replace <year> with the value from the FreeType version you\n" + " actually use.\n" + "\n" + "\n" + "Legal Terms\n" + "===========\n" + "\n" + "0. Definitions\n" + "--------------\n" + "\n" + " Throughout this license, the terms `package', `FreeType Project',\n" + " and `FreeType archive' refer to the set of files originally\n" + " distributed by the authors (David Turner, Robert Wilhelm, and\n" + " Werner Lemberg) as the `FreeType Project', be they named as alpha,\n" + " beta or final release.\n" + "\n" + " `You' refers to the licensee, or person using the project, where\n" + " `using' is a generic term including compiling the project's source\n" + " code as well as linking it to form a `program' or `executable'.\n" + " This program is referred to as `a program using the FreeType\n" + " engine'.\n" + "\n" + " This license applies to all files distributed in the original\n" + " FreeType Project, including all source code, binaries and\n" + " documentation, unless otherwise stated in the file in its\n" + " original, unmodified form as distributed in the original archive.\n" + " If you are unsure whether or not a particular file is covered by\n" + " this license, you must contact us to verify this.\n" + "\n" + " The FreeType Project is copyright (C) 1996-2000 by David Turner,\n" + " Robert Wilhelm, and Werner Lemberg. All rights reserved except as\n" + " specified below.\n" + "\n" + "1. No Warranty\n" + "--------------\n" + "\n" + " THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY\n" + " KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\n" + " WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" + " PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS\n" + " BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO\n" + " USE, OF THE FREETYPE PROJECT.\n" + "\n" + "2. Redistribution\n" + "-----------------\n" + "\n" + " This license grants a worldwide, royalty-free, perpetual and\n" + " irrevocable right and license to use, execute, perform, compile,\n" + " display, copy, create derivative works of, distribute and\n" + " sublicense the FreeType Project (in both source and object code\n" + " forms) and derivative works thereof for any purpose; and to\n" + " authorize others to exercise some or all of the rights granted\n" + " herein, subject to the following conditions:\n" + "\n" + " o Redistribution of source code must retain this license file\n" + " (`FTL.TXT') unaltered; any additions, deletions or changes to\n" + " the original files must be clearly indicated in accompanying\n" + " documentation. The copyright notices of the unaltered,\n" + " original files must be preserved in all copies of source\n" + " files.\n" + "\n" + " o Redistribution in binary form must provide a disclaimer that\n" + " states that the software is based in part of the work of the\n" + " FreeType Team, in the distribution documentation. We also\n" + " encourage you to put an URL to the FreeType web page in your\n" + " documentation, though this isn't mandatory.\n" + "\n" + " These conditions apply to any software derived from or based on\n" + " the FreeType Project, not just the unmodified files. If you use\n" + " our work, you must acknowledge us. However, no fee need be paid\n" + " to us.\n" + "\n" + "3. Advertising\n" + "--------------\n" + "\n" + " Neither the FreeType authors and contributors nor you shall use\n" + " the name of the other for commercial, advertising, or promotional\n" + " purposes without specific prior written permission.\n" + "\n" + " We suggest, but do not require, that you use one or more of the\n" + " following phrases to refer to this software in your documentation\n" + " or advertising materials: `FreeType Project', `FreeType Engine',\n" + " `FreeType library', or `FreeType Distribution'.\n" + "\n" + " As you have not signed this license, you are not required to\n" + " accept it. However, as the FreeType Project is copyrighted\n" + " material, only this license, or another one contracted with the\n" + " authors, grants you the right to use, distribute, and modify it.\n" + " Therefore, by using, distributing, or modifying the FreeType\n" + " Project, you indicate that you understand and accept all the terms\n" + " of this license.\n" + "\n" + "4. Contacts\n" + "-----------\n" + "\n" + " There are two mailing lists related to FreeType:\n" + "\n" + " o freetype@nongnu.org\n" + "\n" + " Discusses general use and applications of FreeType, as well as\n" + " future and wanted additions to the library and distribution.\n" + " If you are looking for support, start in this list if you\n" + " haven't found anything to help you in the documentation.\n" + "\n" + " o freetype-devel@nongnu.org\n" + "\n" + " Discusses bugs, as well as engine internals, design issues,\n" + " specific licenses, porting, etc.\n" + "\n" + " Our home page can be found at\n" + "\n" + " http://www.freetype.org\n" + "\n" + "\n" + "--- end of FTL.TXT ---"; #endif #ifdef USE_BUILDENV -static const char *licenseHarfBuzzNG = +static const char *licenseHarfBuzzNG = "HarfBuzz is licensed under the so-called \"Old MIT\" license. Details follow.\n" "For parts of HarfBuzz that are licensed under different licenses see individual\n" "files names COPYING in subdirectories where applicable.\n" @@ -1954,143 +1932,142 @@ static const char *licenseHarfBuzzNG = #ifdef USE_BUILDENV -static const char *licenseLibPNG = - "\n" - "This copy of the libpng notices is provided for your convenience. In case of\n" - "any discrepancy between this copy and the notices in the file png.h that is\n" - "included in the libpng distribution, the latter shall prevail.\n" - "\n" - "COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:\n" - "\n" - "If you modify libpng you may insert additional notices immediately following\n" - "this sentence.\n" - "\n" - "This code is released under the libpng license.\n" - "\n" - "libpng versions 1.0.7, July 1, 2000 through 1.6.28, January 5, 2017 are\n" - "Copyright (c) 2000-2002, 2004, 2006-2017 Glenn Randers-Pehrson, are\n" - "derived from libpng-1.0.6, and are distributed according to the same\n" - "disclaimer and license as libpng-1.0.6 with the following individuals\n" - "added to the list of Contributing Authors:\n" - "\n" - " Simon-Pierre Cadieux\n" - " Eric S. Raymond\n" - " Mans Rullgard\n" - " Cosmin Truta\n" - " Gilles Vollant\n" - " James Yu\n" - " Mandar Sahastrabuddhe\n" - "\n" - "and with the following additions to the disclaimer:\n" - "\n" - " There is no warranty against interference with your enjoyment of the\n" - " library or against infringement. There is no warranty that our\n" - " efforts or the library will fulfill any of your particular purposes\n" - " or needs. This library is provided with all faults, and the entire\n" - " risk of satisfactory quality, performance, accuracy, and effort is with\n" - " the user.\n" - "\n" - "Some files in the \"contrib\" directory and some configure-generated\n" - "files that are distributed with libpng have other copyright owners and\n" - "are released under other open source licenses.\n" - "\n" - "libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are\n" - "Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from\n" - "libpng-0.96, and are distributed according to the same disclaimer and\n" - "license as libpng-0.96, with the following individuals added to the list\n" - "of Contributing Authors:\n" - "\n" - " Tom Lane\n" - " Glenn Randers-Pehrson\n" - " Willem van Schaik\n" - "\n" - "libpng versions 0.89, June 1996, through 0.96, May 1997, are\n" - "Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,\n" - "and are distributed according to the same disclaimer and license as\n" - "libpng-0.88, with the following individuals added to the list of\n" - "Contributing Authors:\n" - "\n" - " John Bowler\n" - " Kevin Bracey\n" - " Sam Bushell\n" - " Magnus Holmgren\n" - " Greg Roelofs\n" - " Tom Tanner\n" - "\n" - "Some files in the \"scripts\" directory have other copyright owners\n" - "but are released under this license.\n" - "\n" - "libpng versions 0.5, May 1995, through 0.88, January 1996, are\n" - "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n" - "\n" - "For the purposes of this copyright and license, \"Contributing Authors\"\n" - "is defined as the following set of individuals:\n" - "\n" - " Andreas Dilger\n" - " Dave Martindale\n" - " Guy Eric Schalnat\n" - " Paul Schmidt\n" - " Tim Wegner\n" - "\n" - "The PNG Reference Library is supplied \"AS IS\". The Contributing Authors\n" - "and Group 42, Inc. disclaim all warranties, expressed or implied,\n" - "including, without limitation, the warranties of merchantability and of\n" - "fitness for any purpose. The Contributing Authors and Group 42, Inc.\n" - "assume no liability for direct, indirect, incidental, special, exemplary,\n" - "or consequential damages, which may result from the use of the PNG\n" - "Reference Library, even if advised of the possibility of such damage.\n" - "\n" - "Permission is hereby granted to use, copy, modify, and distribute this\n" - "source code, or portions hereof, for any purpose, without fee, subject\n" - "to the following restrictions:\n" - "\n" - " 1. The origin of this source code must not be misrepresented.\n" - "\n" - " 2. Altered versions must be plainly marked as such and must not\n" - " be misrepresented as being the original source.\n" - "\n" - " 3. This Copyright notice may not be removed or altered from any\n" - " source or altered source distribution.\n" - "\n" - "The Contributing Authors and Group 42, Inc. specifically permit, without\n" - "fee, and encourage the use of this source code as a component to\n" - "supporting the PNG file format in commercial products. If you use this\n" - "source code in a product, acknowledgment is not required but would be\n" - "appreciated.\n" - "\n" - "END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.\n" - "\n" - "TRADEMARK:\n" - "\n" - "The name \"libpng\" has not been registered by the Copyright owner\n" - "as a trademark in any jurisdiction. However, because libpng has\n" - "been distributed and maintained world-wide, continually since 1995,\n" - "the Copyright owner claims \"common-law trademark protection\" in any\n" - "jurisdiction where common-law trademark is recognized.\n" - "\n" - "OSI CERTIFICATION:\n" - "\n" - "Libpng is OSI Certified Open Source Software. OSI Certified Open Source is\n" - "a certification mark of the Open Source Initiative. OSI has not addressed\n" - "the additional disclaimers inserted at version 1.0.7.\n" - "\n" - "EXPORT CONTROL:\n" - "\n" - "The Copyright owner believes that the Export Control Classification\n" - "Number (ECCN) for libpng is EAR99, which means not subject to export\n" - "controls or International Traffic in Arms Regulations (ITAR) because\n" - "it is open source, publicly available software, that does not contain\n" - "any encryption software. See the EAR, paragraphs 734.3(b)(3) and\n" - "734.7(b).\n" - "\n" - "Glenn Randers-Pehrson\n" - "glennrp at users.sourceforge.net\n" - "January 5, 2017"; +static const char *licenseLibPNG = "\n" + "This copy of the libpng notices is provided for your convenience. In case of\n" + "any discrepancy between this copy and the notices in the file png.h that is\n" + "included in the libpng distribution, the latter shall prevail.\n" + "\n" + "COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:\n" + "\n" + "If you modify libpng you may insert additional notices immediately following\n" + "this sentence.\n" + "\n" + "This code is released under the libpng license.\n" + "\n" + "libpng versions 1.0.7, July 1, 2000 through 1.6.28, January 5, 2017 are\n" + "Copyright (c) 2000-2002, 2004, 2006-2017 Glenn Randers-Pehrson, are\n" + "derived from libpng-1.0.6, and are distributed according to the same\n" + "disclaimer and license as libpng-1.0.6 with the following individuals\n" + "added to the list of Contributing Authors:\n" + "\n" + " Simon-Pierre Cadieux\n" + " Eric S. Raymond\n" + " Mans Rullgard\n" + " Cosmin Truta\n" + " Gilles Vollant\n" + " James Yu\n" + " Mandar Sahastrabuddhe\n" + "\n" + "and with the following additions to the disclaimer:\n" + "\n" + " There is no warranty against interference with your enjoyment of the\n" + " library or against infringement. There is no warranty that our\n" + " efforts or the library will fulfill any of your particular purposes\n" + " or needs. This library is provided with all faults, and the entire\n" + " risk of satisfactory quality, performance, accuracy, and effort is with\n" + " the user.\n" + "\n" + "Some files in the \"contrib\" directory and some configure-generated\n" + "files that are distributed with libpng have other copyright owners and\n" + "are released under other open source licenses.\n" + "\n" + "libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are\n" + "Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from\n" + "libpng-0.96, and are distributed according to the same disclaimer and\n" + "license as libpng-0.96, with the following individuals added to the list\n" + "of Contributing Authors:\n" + "\n" + " Tom Lane\n" + " Glenn Randers-Pehrson\n" + " Willem van Schaik\n" + "\n" + "libpng versions 0.89, June 1996, through 0.96, May 1997, are\n" + "Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,\n" + "and are distributed according to the same disclaimer and license as\n" + "libpng-0.88, with the following individuals added to the list of\n" + "Contributing Authors:\n" + "\n" + " John Bowler\n" + " Kevin Bracey\n" + " Sam Bushell\n" + " Magnus Holmgren\n" + " Greg Roelofs\n" + " Tom Tanner\n" + "\n" + "Some files in the \"scripts\" directory have other copyright owners\n" + "but are released under this license.\n" + "\n" + "libpng versions 0.5, May 1995, through 0.88, January 1996, are\n" + "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n" + "\n" + "For the purposes of this copyright and license, \"Contributing Authors\"\n" + "is defined as the following set of individuals:\n" + "\n" + " Andreas Dilger\n" + " Dave Martindale\n" + " Guy Eric Schalnat\n" + " Paul Schmidt\n" + " Tim Wegner\n" + "\n" + "The PNG Reference Library is supplied \"AS IS\". The Contributing Authors\n" + "and Group 42, Inc. disclaim all warranties, expressed or implied,\n" + "including, without limitation, the warranties of merchantability and of\n" + "fitness for any purpose. The Contributing Authors and Group 42, Inc.\n" + "assume no liability for direct, indirect, incidental, special, exemplary,\n" + "or consequential damages, which may result from the use of the PNG\n" + "Reference Library, even if advised of the possibility of such damage.\n" + "\n" + "Permission is hereby granted to use, copy, modify, and distribute this\n" + "source code, or portions hereof, for any purpose, without fee, subject\n" + "to the following restrictions:\n" + "\n" + " 1. The origin of this source code must not be misrepresented.\n" + "\n" + " 2. Altered versions must be plainly marked as such and must not\n" + " be misrepresented as being the original source.\n" + "\n" + " 3. This Copyright notice may not be removed or altered from any\n" + " source or altered source distribution.\n" + "\n" + "The Contributing Authors and Group 42, Inc. specifically permit, without\n" + "fee, and encourage the use of this source code as a component to\n" + "supporting the PNG file format in commercial products. If you use this\n" + "source code in a product, acknowledgment is not required but would be\n" + "appreciated.\n" + "\n" + "END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.\n" + "\n" + "TRADEMARK:\n" + "\n" + "The name \"libpng\" has not been registered by the Copyright owner\n" + "as a trademark in any jurisdiction. However, because libpng has\n" + "been distributed and maintained world-wide, continually since 1995,\n" + "the Copyright owner claims \"common-law trademark protection\" in any\n" + "jurisdiction where common-law trademark is recognized.\n" + "\n" + "OSI CERTIFICATION:\n" + "\n" + "Libpng is OSI Certified Open Source Software. OSI Certified Open Source is\n" + "a certification mark of the Open Source Initiative. OSI has not addressed\n" + "the additional disclaimers inserted at version 1.0.7.\n" + "\n" + "EXPORT CONTROL:\n" + "\n" + "The Copyright owner believes that the Export Control Classification\n" + "Number (ECCN) for libpng is EAR99, which means not subject to export\n" + "controls or International Traffic in Arms Regulations (ITAR) because\n" + "it is open source, publicly available software, that does not contain\n" + "any encryption software. See the EAR, paragraphs 734.3(b)(3) and\n" + "734.7(b).\n" + "\n" + "Glenn Randers-Pehrson\n" + "glennrp at users.sourceforge.net\n" + "January 5, 2017"; #endif #ifdef USE_BUILDENV -static const char *licenseLibjpegTurbo = +static const char *licenseLibjpegTurbo = "libjpeg-turbo is covered by three compatible BSD-style open source licenses:\n" "\n" "1. The IJG (Independent JPEG Group) License.\n" @@ -2445,1352 +2422,1345 @@ static const char *licenseLibjpegTurbo = #ifdef USE_BUILDENV -static const char *licenseZeroCIce = - "Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.\n" - "\n" - "This copy of Ice is free software; you can redistribute it and/or modify\n" - "it under the terms of the GNU General Public License version 2 as\n" - "published by the Free Software Foundation.\n" - "\n" - "Ice is distributed in the hope that it will be useful, but WITHOUT ANY\n" - "WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n" - "FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n" - "details.\n" - "\n" - "You should have received a copy of the GNU General Public License version\n" - "2 along with this program; if not, see http://www.gnu.org/licenses.\n" - "\n" - "Linking Ice statically or dynamically with other software (such as a \n" - "library, module or application) is making a combined work based on Ice. \n" - "Thus, the terms and conditions of the GNU General Public License version\n" - "2 cover this combined work.\n" - "\n" - "If such software can only be used together with Ice, then not only the \n" - "combined work but the software itself is a work derived from Ice and as\n" - "such shall be licensed under the terms of the GNU General Public License \n" - "version 2. This includes the situation where Ice is only being used \n" - "through an abstraction layer.\n" - "\n" - "As a special exception to the above, ZeroC grants to the copyright \n" - "holders and contributors of the Mumble project (http://www.mumble.info) \n" - "the permission to license the Ice-based software they contribute to \n" - "Mumble under the terms of the BSD license. This exception does not extend\n" - "to the parts of Ice used by Mumble, or to any other derived work: as a \n" - "whole, any work based on Ice shall be licensed under the terms and \n" - "conditions of the GNU General Public License version 2.\n" - "\n" - "You may also combine Ice with any software not derived from Ice, provided\n" - "the license of such software is compatible with the GNU General Public \n" - "License version 2. In addition, as a special exception, ZeroC grants you\n" - "permission to combine Ice with:\n" - " \n" - " - the OpenSSL library, or with a modified version of the OpenSSL library\n" - " that uses the same license as OpenSSL\n" - "\n" - " - any library not derived from Ice and licensed under the terms of\n" - " the Apache License, version 2.0 \n" - " (http://www.apache.org/licenses/LICENSE-2.0.html) \n" - "\n" - "If you modify this copy of Ice, you may extend any of the exceptions \n" - "provided above to your version of Ice, but you are not obligated to \n" - "do so."; +static const char *licenseZeroCIce = "Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.\n" + "\n" + "This copy of Ice is free software; you can redistribute it and/or modify\n" + "it under the terms of the GNU General Public License version 2 as\n" + "published by the Free Software Foundation.\n" + "\n" + "Ice is distributed in the hope that it will be useful, but WITHOUT ANY\n" + "WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n" + "FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n" + "details.\n" + "\n" + "You should have received a copy of the GNU General Public License version\n" + "2 along with this program; if not, see http://www.gnu.org/licenses.\n" + "\n" + "Linking Ice statically or dynamically with other software (such as a \n" + "library, module or application) is making a combined work based on Ice. \n" + "Thus, the terms and conditions of the GNU General Public License version\n" + "2 cover this combined work.\n" + "\n" + "If such software can only be used together with Ice, then not only the \n" + "combined work but the software itself is a work derived from Ice and as\n" + "such shall be licensed under the terms of the GNU General Public License \n" + "version 2. This includes the situation where Ice is only being used \n" + "through an abstraction layer.\n" + "\n" + "As a special exception to the above, ZeroC grants to the copyright \n" + "holders and contributors of the Mumble project (http://www.mumble.info) \n" + "the permission to license the Ice-based software they contribute to \n" + "Mumble under the terms of the BSD license. This exception does not extend\n" + "to the parts of Ice used by Mumble, or to any other derived work: as a \n" + "whole, any work based on Ice shall be licensed under the terms and \n" + "conditions of the GNU General Public License version 2.\n" + "\n" + "You may also combine Ice with any software not derived from Ice, provided\n" + "the license of such software is compatible with the GNU General Public \n" + "License version 2. In addition, as a special exception, ZeroC grants you\n" + "permission to combine Ice with:\n" + " \n" + " - the OpenSSL library, or with a modified version of the OpenSSL library\n" + " that uses the same license as OpenSSL\n" + "\n" + " - any library not derived from Ice and licensed under the terms of\n" + " the Apache License, version 2.0 \n" + " (http://www.apache.org/licenses/LICENSE-2.0.html) \n" + "\n" + "If you modify this copy of Ice, you may extend any of the exceptions \n" + "provided above to your version of Ice, but you are not obligated to \n" + "do so."; #endif #ifdef USE_BUILDENV -static const char *licenseMcpp = - "/*-\n" - " * Copyright (c) 1998, 2002-2008 Kiyoshi Matsui <kmatsui@t3.rim.or.jp>\n" - " * All rights reserved.\n" - " *\n" - " * This software including the files in this directory is provided under\n" - " * the following license.\n" - " *\n" - " * Redistribution and use in source and binary forms, with or without\n" - " * modification, are permitted provided that the following conditions\n" - " * are met:\n" - " * 1. Redistributions of source code must retain the above copyright\n" - " * notice, this list of conditions and the following disclaimer.\n" - " * 2. Redistributions in binary form must reproduce the above copyright\n" - " * notice, this list of conditions and the following disclaimer in the\n" - " * documentation and/or other materials provided with the distribution.\n" - " *\n" - " * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND\n" - " * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" - " * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" - " * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE\n" - " * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" - " * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" - " * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" - " * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" - " * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" - " * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" - " * SUCH DAMAGE.\n" - " */"; +static const char *licenseMcpp = "/*-\n" + " * Copyright (c) 1998, 2002-2008 Kiyoshi Matsui <kmatsui@t3.rim.or.jp>\n" + " * All rights reserved.\n" + " *\n" + " * This software including the files in this directory is provided under\n" + " * the following license.\n" + " *\n" + " * Redistribution and use in source and binary forms, with or without\n" + " * modification, are permitted provided that the following conditions\n" + " * are met:\n" + " * 1. Redistributions of source code must retain the above copyright\n" + " * notice, this list of conditions and the following disclaimer.\n" + " * 2. Redistributions in binary form must reproduce the above copyright\n" + " * notice, this list of conditions and the following disclaimer in the\n" + " * documentation and/or other materials provided with the distribution.\n" + " *\n" + " * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND\n" + " * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" + " * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" + " * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE\n" + " * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" + " * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n" + " * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n" + " * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" + " * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" + " * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n" + " * SUCH DAMAGE.\n" + " */"; #endif #ifdef USE_BUILDENV -static const char *licenseMDNSResponder = - "The majority of the source code in the mDNSResponder project is licensed\n" - "under the terms of the Apache License, Version 2.0, available from:\n" - " <http://www.apache.org/licenses/LICENSE-2.0>\n" - "\n" - "To accommodate license compatibility with the widest possible range\n" - "of client code licenses, the shared library code, which is linked\n" - "at runtime into the same address space as the client using it, is\n" - "licensed under the terms of the \"Three-Clause BSD License\".\n" - "\n" - "The Linux Name Service Switch code, contributed by National ICT\n" - "Australia Ltd (NICTA) is licensed under the terms of the NICTA Public\n" - "Software Licence (which is substantially similar to the \"Three-Clause\n" - "BSD License\", with some additional language pertaining to Australian law)."; +static const char *licenseMDNSResponder = "The majority of the source code in the mDNSResponder project is licensed\n" + "under the terms of the Apache License, Version 2.0, available from:\n" + " <http://www.apache.org/licenses/LICENSE-2.0>\n" + "\n" + "To accommodate license compatibility with the widest possible range\n" + "of client code licenses, the shared library code, which is linked\n" + "at runtime into the same address space as the client using it, is\n" + "licensed under the terms of the \"Three-Clause BSD License\".\n" + "\n" + "The Linux Name Service Switch code, contributed by National ICT\n" + "Australia Ltd (NICTA) is licensed under the terms of the NICTA Public\n" + "Software Licence (which is substantially similar to the \"Three-Clause\n" + "BSD License\", with some additional language pertaining to Australian law)."; #endif #ifdef USE_BUILDENV -static const char *licensePCRE = - "PCRE LICENCE\n" - "------------\n" - "\n" - "PCRE is a library of functions to support regular expressions whose syntax\n" - "and semantics are as close as possible to those of the Perl 5 language.\n" - "\n" - "Release 8 of PCRE is distributed under the terms of the \"BSD\" licence, as\n" - "specified below. The documentation for PCRE, supplied in the \"doc\"\n" - "directory, is distributed under the same terms as the software itself. The data\n" - "in the testdata directory is not copyrighted and is in the public domain.\n" - "\n" - "The basic library functions are written in C and are freestanding. Also\n" - "included in the distribution is a set of C++ wrapper functions, and a\n" - "just-in-time compiler that can be used to optimize pattern matching. These\n" - "are both optional features that can be omitted when the library is built.\n" - "\n" - "\n" - "THE BASIC LIBRARY FUNCTIONS\n" - "---------------------------\n" - "\n" - "Written by: Philip Hazel\n" - "Email local part: ph10\n" - "Email domain: cam.ac.uk\n" - "\n" - "University of Cambridge Computing Service,\n" - "Cambridge, England.\n" - "\n" - "Copyright (c) 1997-2017 University of Cambridge\n" - "All rights reserved.\n" - "\n" - "\n" - "PCRE JUST-IN-TIME COMPILATION SUPPORT\n" - "-------------------------------------\n" - "\n" - "Written by: Zoltan Herczeg\n" - "Email local part: hzmester\n" - "Emain domain: freemail.hu\n" - "\n" - "Copyright(c) 2010-2017 Zoltan Herczeg\n" - "All rights reserved.\n" - "\n" - "\n" - "STACK-LESS JUST-IN-TIME COMPILER\n" - "--------------------------------\n" - "\n" - "Written by: Zoltan Herczeg\n" - "Email local part: hzmester\n" - "Emain domain: freemail.hu\n" - "\n" - "Copyright(c) 2009-2017 Zoltan Herczeg\n" - "All rights reserved.\n" - "\n" - "\n" - "THE C++ WRAPPER FUNCTIONS\n" - "-------------------------\n" - "\n" - "Contributed by: Google Inc.\n" - "\n" - "Copyright (c) 2007-2012, Google Inc.\n" - "All rights reserved.\n" - "\n" - "\n" - "THE \"BSD\" LICENCE\n" - "-----------------\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions are met:\n" - "\n" - " * Redistributions of source code must retain the above copyright notice,\n" - " this list of conditions and the following disclaimer.\n" - "\n" - " * Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in the\n" - " documentation and/or other materials provided with the distribution.\n" - "\n" - " * Neither the name of the University of Cambridge nor the name of Google\n" - " Inc. nor the names of their contributors may be used to endorse or\n" - " promote products derived from this software without specific prior\n" - " written permission.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" - "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" - "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" - "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n" - "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" - "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" - "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" - "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" - "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" - "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" - "POSSIBILITY OF SUCH DAMAGE.\n" - "\n" - "End"; +static const char *licensePCRE = "PCRE LICENCE\n" + "------------\n" + "\n" + "PCRE is a library of functions to support regular expressions whose syntax\n" + "and semantics are as close as possible to those of the Perl 5 language.\n" + "\n" + "Release 8 of PCRE is distributed under the terms of the \"BSD\" licence, as\n" + "specified below. The documentation for PCRE, supplied in the \"doc\"\n" + "directory, is distributed under the same terms as the software itself. The data\n" + "in the testdata directory is not copyrighted and is in the public domain.\n" + "\n" + "The basic library functions are written in C and are freestanding. Also\n" + "included in the distribution is a set of C++ wrapper functions, and a\n" + "just-in-time compiler that can be used to optimize pattern matching. These\n" + "are both optional features that can be omitted when the library is built.\n" + "\n" + "\n" + "THE BASIC LIBRARY FUNCTIONS\n" + "---------------------------\n" + "\n" + "Written by: Philip Hazel\n" + "Email local part: ph10\n" + "Email domain: cam.ac.uk\n" + "\n" + "University of Cambridge Computing Service,\n" + "Cambridge, England.\n" + "\n" + "Copyright (c) 1997-2017 University of Cambridge\n" + "All rights reserved.\n" + "\n" + "\n" + "PCRE JUST-IN-TIME COMPILATION SUPPORT\n" + "-------------------------------------\n" + "\n" + "Written by: Zoltan Herczeg\n" + "Email local part: hzmester\n" + "Emain domain: freemail.hu\n" + "\n" + "Copyright(c) 2010-2017 Zoltan Herczeg\n" + "All rights reserved.\n" + "\n" + "\n" + "STACK-LESS JUST-IN-TIME COMPILER\n" + "--------------------------------\n" + "\n" + "Written by: Zoltan Herczeg\n" + "Email local part: hzmester\n" + "Emain domain: freemail.hu\n" + "\n" + "Copyright(c) 2009-2017 Zoltan Herczeg\n" + "All rights reserved.\n" + "\n" + "\n" + "THE C++ WRAPPER FUNCTIONS\n" + "-------------------------\n" + "\n" + "Contributed by: Google Inc.\n" + "\n" + "Copyright (c) 2007-2012, Google Inc.\n" + "All rights reserved.\n" + "\n" + "\n" + "THE \"BSD\" LICENCE\n" + "-----------------\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions are met:\n" + "\n" + " * Redistributions of source code must retain the above copyright notice,\n" + " this list of conditions and the following disclaimer.\n" + "\n" + " * Redistributions in binary form must reproduce the above copyright\n" + " notice, this list of conditions and the following disclaimer in the\n" + " documentation and/or other materials provided with the distribution.\n" + "\n" + " * Neither the name of the University of Cambridge nor the name of Google\n" + " Inc. nor the names of their contributors may be used to endorse or\n" + " promote products derived from this software without specific prior\n" + " written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n" + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" + "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" + "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" + "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" + "POSSIBILITY OF SUCH DAMAGE.\n" + "\n" + "End"; #endif #ifdef USE_BUILDENV -static const char *licenseQt = - " GNU LESSER GENERAL PUBLIC LICENSE\n" - "\n" - " The Qt Toolkit is Copyright (C) 2015 The Qt Company Ltd.\n" - " Contact: http://www.qt.io/licensing/\n" - "\n" - " You may use, distribute and copy the Qt Toolkit under the terms of\n" - " GNU Lesser General Public License version 2.1, which is displayed below.\n" - "\n" - "-------------------------------------------------------------------------\n" - "\n" - " GNU LESSER GENERAL PUBLIC LICENSE\n" - " Version 2.1, February 1999\n" - "\n" - " Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n" - " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" - " Everyone is permitted to copy and distribute verbatim copies\n" - " of this license document, but changing it is not allowed.\n" - "\n" - "[This is the first released version of the Lesser GPL. It also counts\n" - " as the successor of the GNU Library Public License, version 2, hence\n" - " the version number 2.1.]\n" - "\n" - " Preamble\n" - "\n" - " The licenses for most software are designed to take away your\n" - "freedom to share and change it. By contrast, the GNU General Public\n" - "Licenses are intended to guarantee your freedom to share and change\n" - "free software--to make sure the software is free for all its users.\n" - "\n" - " This license, the Lesser General Public License, applies to some\n" - "specially designated software packages--typically libraries--of the\n" - "Free Software Foundation and other authors who decide to use it. You\n" - "can use it too, but we suggest you first think carefully about whether\n" - "this license or the ordinary General Public License is the better\n" - "strategy to use in any particular case, based on the explanations below.\n" - "\n" - " When we speak of free software, we are referring to freedom of use,\n" - "not price. Our General Public Licenses are designed to make sure that\n" - "you have the freedom to distribute copies of free software (and charge\n" - "for this service if you wish); that you receive source code or can get\n" - "it if you want it; that you can change the software and use pieces of\n" - "it in new free programs; and that you are informed that you can do\n" - "these things.\n" - "\n" - " To protect your rights, we need to make restrictions that forbid\n" - "distributors to deny you these rights or to ask you to surrender these\n" - "rights. These restrictions translate to certain responsibilities for\n" - "you if you distribute copies of the library or if you modify it.\n" - "\n" - " For example, if you distribute copies of the library, whether gratis\n" - "or for a fee, you must give the recipients all the rights that we gave\n" - "you. You must make sure that they, too, receive or can get the source\n" - "code. If you link other code with the library, you must provide\n" - "complete object files to the recipients, so that they can relink them\n" - "with the library after making changes to the library and recompiling\n" - "it. And you must show them these terms so they know their rights.\n" - "\n" - " We protect your rights with a two-step method: (1) we copyright the\n" - "library, and (2) we offer you this license, which gives you legal\n" - "permission to copy, distribute and/or modify the library.\n" - "\n" - " To protect each distributor, we want to make it very clear that\n" - "there is no warranty for the free library. Also, if the library is\n" - "modified by someone else and passed on, the recipients should know\n" - "that what they have is not the original version, so that the original\n" - "author's reputation will not be affected by problems that might be\n" - "introduced by others.\n" - "\n" - " Finally, software patents pose a constant threat to the existence of\n" - "any free program. We wish to make sure that a company cannot\n" - "effectively restrict the users of a free program by obtaining a\n" - "restrictive license from a patent holder. Therefore, we insist that\n" - "any patent license obtained for a version of the library must be\n" - "consistent with the full freedom of use specified in this license.\n" - "\n" - " Most GNU software, including some libraries, is covered by the\n" - "ordinary GNU General Public License. This license, the GNU Lesser\n" - "General Public License, applies to certain designated libraries, and\n" - "is quite different from the ordinary General Public License. We use\n" - "this license for certain libraries in order to permit linking those\n" - "libraries into non-free programs.\n" - "\n" - " When a program is linked with a library, whether statically or using\n" - "a shared library, the combination of the two is legally speaking a\n" - "combined work, a derivative of the original library. The ordinary\n" - "General Public License therefore permits such linking only if the\n" - "entire combination fits its criteria of freedom. The Lesser General\n" - "Public License permits more lax criteria for linking other code with\n" - "the library.\n" - "\n" - " We call this license the \"Lesser\" General Public License because it\n" - "does Less to protect the user's freedom than the ordinary General\n" - "Public License. It also provides other free software developers Less\n" - "of an advantage over competing non-free programs. These disadvantages\n" - "are the reason we use the ordinary General Public License for many\n" - "libraries. However, the Lesser license provides advantages in certain\n" - "special circumstances.\n" - "\n" - " For example, on rare occasions, there may be a special need to\n" - "encourage the widest possible use of a certain library, so that it becomes\n" - "a de-facto standard. To achieve this, non-free programs must be\n" - "allowed to use the library. A more frequent case is that a free\n" - "library does the same job as widely used non-free libraries. In this\n" - "case, there is little to gain by limiting the free library to free\n" - "software only, so we use the Lesser General Public License.\n" - "\n" - " In other cases, permission to use a particular library in non-free\n" - "programs enables a greater number of people to use a large body of\n" - "free software. For example, permission to use the GNU C Library in\n" - "non-free programs enables many more people to use the whole GNU\n" - "operating system, as well as its variant, the GNU/Linux operating\n" - "system.\n" - "\n" - " Although the Lesser General Public License is Less protective of the\n" - "users' freedom, it does ensure that the user of a program that is\n" - "linked with the Library has the freedom and the wherewithal to run\n" - "that program using a modified version of the Library.\n" - "\n" - " The precise terms and conditions for copying, distribution and\n" - "modification follow. Pay close attention to the difference between a\n" - "\"work based on the library\" and a \"work that uses the library\". The\n" - "former contains code derived from the library, whereas the latter must\n" - "be combined with the library in order to run.\n" - "\n" - " GNU LESSER GENERAL PUBLIC LICENSE\n" - " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" - "\n" - " 0. This License Agreement applies to any software library or other\n" - "program which contains a notice placed by the copyright holder or\n" - "other authorized party saying it may be distributed under the terms of\n" - "this Lesser General Public License (also called \"this License\").\n" - "Each licensee is addressed as \"you\".\n" - "\n" - " A \"library\" means a collection of software functions and/or data\n" - "prepared so as to be conveniently linked with application programs\n" - "(which use some of those functions and data) to form executables.\n" - "\n" - " The \"Library\", below, refers to any such software library or work\n" - "which has been distributed under these terms. A \"work based on the\n" - "Library\" means either the Library or any derivative work under\n" - "copyright law: that is to say, a work containing the Library or a\n" - "portion of it, either verbatim or with modifications and/or translated\n" - "straightforwardly into another language. (Hereinafter, translation is\n" - "included without limitation in the term \"modification\".)\n" - "\n" - " \"Source code\" for a work means the preferred form of the work for\n" - "making modifications to it. For a library, complete source code means\n" - "all the source code for all modules it contains, plus any associated\n" - "interface definition files, plus the scripts used to control compilation\n" - "and installation of the library.\n" - "\n" - " Activities other than copying, distribution and modification are not\n" - "covered by this License; they are outside its scope. The act of\n" - "running a program using the Library is not restricted, and output from\n" - "such a program is covered only if its contents constitute a work based\n" - "on the Library (independent of the use of the Library in a tool for\n" - "writing it). Whether that is true depends on what the Library does\n" - "and what the program that uses the Library does.\n" - "\n" - " 1. You may copy and distribute verbatim copies of the Library's\n" - "complete source code as you receive it, in any medium, provided that\n" - "you conspicuously and appropriately publish on each copy an\n" - "appropriate copyright notice and disclaimer of warranty; keep intact\n" - "all the notices that refer to this License and to the absence of any\n" - "warranty; and distribute a copy of this License along with the\n" - "Library.\n" - "\n" - " You may charge a fee for the physical act of transferring a copy,\n" - "and you may at your option offer warranty protection in exchange for a\n" - "fee.\n" - "\n" - " 2. You may modify your copy or copies of the Library or any portion\n" - "of it, thus forming a work based on the Library, and copy and\n" - "distribute such modifications or work under the terms of Section 1\n" - "above, provided that you also meet all of these conditions:\n" - "\n" - " a) The modified work must itself be a software library.\n" - "\n" - " b) You must cause the files modified to carry prominent notices\n" - " stating that you changed the files and the date of any change.\n" - "\n" - " c) You must cause the whole of the work to be licensed at no\n" - " charge to all third parties under the terms of this License.\n" - "\n" - " d) If a facility in the modified Library refers to a function or a\n" - " table of data to be supplied by an application program that uses\n" - " the facility, other than as an argument passed when the facility\n" - " is invoked, then you must make a good faith effort to ensure that,\n" - " in the event an application does not supply such function or\n" - " table, the facility still operates, and performs whatever part of\n" - " its purpose remains meaningful.\n" - "\n" - " (For example, a function in a library to compute square roots has\n" - " a purpose that is entirely well-defined independent of the\n" - " application. Therefore, Subsection 2d requires that any\n" - " application-supplied function or table used by this function must\n" - " be optional: if the application does not supply it, the square\n" - " root function must still compute square roots.)\n" - "\n" - "These requirements apply to the modified work as a whole. If\n" - "identifiable sections of that work are not derived from the Library,\n" - "and can be reasonably considered independent and separate works in\n" - "themselves, then this License, and its terms, do not apply to those\n" - "sections when you distribute them as separate works. But when you\n" - "distribute the same sections as part of a whole which is a work based\n" - "on the Library, the distribution of the whole must be on the terms of\n" - "this License, whose permissions for other licensees extend to the\n" - "entire whole, and thus to each and every part regardless of who wrote\n" - "it.\n" - "\n" - "Thus, it is not the intent of this section to claim rights or contest\n" - "your rights to work written entirely by you; rather, the intent is to\n" - "exercise the right to control the distribution of derivative or\n" - "collective works based on the Library.\n" - "\n" - "In addition, mere aggregation of another work not based on the Library\n" - "with the Library (or with a work based on the Library) on a volume of\n" - "a storage or distribution medium does not bring the other work under\n" - "the scope of this License.\n" - "\n" - " 3. You may opt to apply the terms of the ordinary GNU General Public\n" - "License instead of this License to a given copy of the Library. To do\n" - "this, you must alter all the notices that refer to this License, so\n" - "that they refer to the ordinary GNU General Public License, version 2,\n" - "instead of to this License. (If a newer version than version 2 of the\n" - "ordinary GNU General Public License has appeared, then you can specify\n" - "that version instead if you wish.) Do not make any other change in\n" - "these notices.\n" - "\n" - " Once this change is made in a given copy, it is irreversible for\n" - "that copy, so the ordinary GNU General Public License applies to all\n" - "subsequent copies and derivative works made from that copy.\n" - "\n" - " This option is useful when you wish to copy part of the code of\n" - "the Library into a program that is not a library.\n" - "\n" - " 4. You may copy and distribute the Library (or a portion or\n" - "derivative of it, under Section 2) in object code or executable form\n" - "under the terms of Sections 1 and 2 above provided that you accompany\n" - "it with the complete corresponding machine-readable source code, which\n" - "must be distributed under the terms of Sections 1 and 2 above on a\n" - "medium customarily used for software interchange.\n" - "\n" - " If distribution of object code is made by offering access to copy\n" - "from a designated place, then offering equivalent access to copy the\n" - "source code from the same place satisfies the requirement to\n" - "distribute the source code, even though third parties are not\n" - "compelled to copy the source along with the object code.\n" - "\n" - " 5. A program that contains no derivative of any portion of the\n" - "Library, but is designed to work with the Library by being compiled or\n" - "linked with it, is called a \"work that uses the Library\". Such a\n" - "work, in isolation, is not a derivative work of the Library, and\n" - "therefore falls outside the scope of this License.\n" - "\n" - " However, linking a \"work that uses the Library\" with the Library\n" - "creates an executable that is a derivative of the Library (because it\n" - "contains portions of the Library), rather than a \"work that uses the\n" - "library\". The executable is therefore covered by this License.\n" - "Section 6 states terms for distribution of such executables.\n" - "\n" - " When a \"work that uses the Library\" uses material from a header file\n" - "that is part of the Library, the object code for the work may be a\n" - "derivative work of the Library even though the source code is not.\n" - "Whether this is true is especially significant if the work can be\n" - "linked without the Library, or if the work is itself a library. The\n" - "threshold for this to be true is not precisely defined by law.\n" - "\n" - " If such an object file uses only numerical parameters, data\n" - "structure layouts and accessors, and small macros and small inline\n" - "functions (ten lines or less in length), then the use of the object\n" - "file is unrestricted, regardless of whether it is legally a derivative\n" - "work. (Executables containing this object code plus portions of the\n" - "Library will still fall under Section 6.)\n" - "\n" - " Otherwise, if the work is a derivative of the Library, you may\n" - "distribute the object code for the work under the terms of Section 6.\n" - "Any executables containing that work also fall under Section 6,\n" - "whether or not they are linked directly with the Library itself.\n" - "\n" - " 6. As an exception to the Sections above, you may also combine or\n" - "link a \"work that uses the Library\" with the Library to produce a\n" - "work containing portions of the Library, and distribute that work\n" - "under terms of your choice, provided that the terms permit\n" - "modification of the work for the customer's own use and reverse\n" - "engineering for debugging such modifications.\n" - "\n" - " You must give prominent notice with each copy of the work that the\n" - "Library is used in it and that the Library and its use are covered by\n" - "this License. You must supply a copy of this License. If the work\n" - "during execution displays copyright notices, you must include the\n" - "copyright notice for the Library among them, as well as a reference\n" - "directing the user to the copy of this License. Also, you must do one\n" - "of these things:\n" - "\n" - " a) Accompany the work with the complete corresponding\n" - " machine-readable source code for the Library including whatever\n" - " changes were used in the work (which must be distributed under\n" - " Sections 1 and 2 above); and, if the work is an executable linked\n" - " with the Library, with the complete machine-readable \"work that\n" - " uses the Library\", as object code and/or source code, so that the\n" - " user can modify the Library and then relink to produce a modified\n" - " executable containing the modified Library. (It is understood\n" - " that the user who changes the contents of definitions files in the\n" - " Library will not necessarily be able to recompile the application\n" - " to use the modified definitions.)\n" - "\n" - " b) Use a suitable shared library mechanism for linking with the\n" - " Library. A suitable mechanism is one that (1) uses at run time a\n" - " copy of the library already present on the user's computer system,\n" - " rather than copying library functions into the executable, and (2)\n" - " will operate properly with a modified version of the library, if\n" - " the user installs one, as long as the modified version is\n" - " interface-compatible with the version that the work was made with.\n" - "\n" - " c) Accompany the work with a written offer, valid for at\n" - " least three years, to give the same user the materials\n" - " specified in Subsection 6a, above, for a charge no more\n" - " than the cost of performing this distribution.\n" - "\n" - " d) If distribution of the work is made by offering access to copy\n" - " from a designated place, offer equivalent access to copy the above\n" - " specified materials from the same place.\n" - "\n" - " e) Verify that the user has already received a copy of these\n" - " materials or that you have already sent this user a copy.\n" - "\n" - " For an executable, the required form of the \"work that uses the\n" - "Library\" must include any data and utility programs needed for\n" - "reproducing the executable from it. However, as a special exception,\n" - "the materials to be distributed need not include anything that is\n" - "normally distributed (in either source or binary form) with the major\n" - "components (compiler, kernel, and so on) of the operating system on\n" - "which the executable runs, unless that component itself accompanies\n" - "the executable.\n" - "\n" - " It may happen that this requirement contradicts the license\n" - "restrictions of other proprietary libraries that do not normally\n" - "accompany the operating system. Such a contradiction means you cannot\n" - "use both them and the Library together in an executable that you\n" - "distribute.\n" - "\n" - " 7. You may place library facilities that are a work based on the\n" - "Library side-by-side in a single library together with other library\n" - "facilities not covered by this License, and distribute such a combined\n" - "library, provided that the separate distribution of the work based on\n" - "the Library and of the other library facilities is otherwise\n" - "permitted, and provided that you do these two things:\n" - "\n" - " a) Accompany the combined library with a copy of the same work\n" - " based on the Library, uncombined with any other library\n" - " facilities. This must be distributed under the terms of the\n" - " Sections above.\n" - "\n" - " b) Give prominent notice with the combined library of the fact\n" - " that part of it is a work based on the Library, and explaining\n" - " where to find the accompanying uncombined form of the same work.\n" - "\n" - " 8. You may not copy, modify, sublicense, link with, or distribute\n" - "the Library except as expressly provided under this License. Any\n" - "attempt otherwise to copy, modify, sublicense, link with, or\n" - "distribute the Library is void, and will automatically terminate your\n" - "rights under this License. However, parties who have received copies,\n" - "or rights, from you under this License will not have their licenses\n" - "terminated so long as such parties remain in full compliance.\n" - "\n" - " 9. You are not required to accept this License, since you have not\n" - "signed it. However, nothing else grants you permission to modify or\n" - "distribute the Library or its derivative works. These actions are\n" - "prohibited by law if you do not accept this License. Therefore, by\n" - "modifying or distributing the Library (or any work based on the\n" - "Library), you indicate your acceptance of this License to do so, and\n" - "all its terms and conditions for copying, distributing or modifying\n" - "the Library or works based on it.\n" - "\n" - " 10. Each time you redistribute the Library (or any work based on the\n" - "Library), the recipient automatically receives a license from the\n" - "original licensor to copy, distribute, link with or modify the Library\n" - "subject to these terms and conditions. You may not impose any further\n" - "restrictions on the recipients' exercise of the rights granted herein.\n" - "You are not responsible for enforcing compliance by third parties with\n" - "this License.\n" - "\n" - " 11. If, as a consequence of a court judgment or allegation of patent\n" - "infringement or for any other reason (not limited to patent issues),\n" - "conditions are imposed on you (whether by court order, agreement or\n" - "otherwise) that contradict the conditions of this License, they do not\n" - "excuse you from the conditions of this License. If you cannot\n" - "distribute so as to satisfy simultaneously your obligations under this\n" - "License and any other pertinent obligations, then as a consequence you\n" - "may not distribute the Library at all. For example, if a patent\n" - "license would not permit royalty-free redistribution of the Library by\n" - "all those who receive copies directly or indirectly through you, then\n" - "the only way you could satisfy both it and this License would be to\n" - "refrain entirely from distribution of the Library.\n" - "\n" - "If any portion of this section is held invalid or unenforceable under any\n" - "particular circumstance, the balance of the section is intended to apply,\n" - "and the section as a whole is intended to apply in other circumstances.\n" - "\n" - "It is not the purpose of this section to induce you to infringe any\n" - "patents or other property right claims or to contest validity of any\n" - "such claims; this section has the sole purpose of protecting the\n" - "integrity of the free software distribution system which is\n" - "implemented by public license practices. Many people have made\n" - "generous contributions to the wide range of software distributed\n" - "through that system in reliance on consistent application of that\n" - "system; it is up to the author/donor to decide if he or she is willing\n" - "to distribute software through any other system and a licensee cannot\n" - "impose that choice.\n" - "\n" - "This section is intended to make thoroughly clear what is believed to\n" - "be a consequence of the rest of this License.\n" - "\n" - " 12. If the distribution and/or use of the Library is restricted in\n" - "certain countries either by patents or by copyrighted interfaces, the\n" - "original copyright holder who places the Library under this License may add\n" - "an explicit geographical distribution limitation excluding those countries,\n" - "so that distribution is permitted only in or among countries not thus\n" - "excluded. In such case, this License incorporates the limitation as if\n" - "written in the body of this License.\n" - "\n" - " 13. The Free Software Foundation may publish revised and/or new\n" - "versions of the Lesser General Public License from time to time.\n" - "Such new versions will be similar in spirit to the present version,\n" - "but may differ in detail to address new problems or concerns.\n" - "\n" - "Each version is given a distinguishing version number. If the Library\n" - "specifies a version number of this License which applies to it and\n" - "\"any later version\", you have the option of following the terms and\n" - "conditions either of that version or of any later version published by\n" - "the Free Software Foundation. If the Library does not specify a\n" - "license version number, you may choose any version ever published by\n" - "the Free Software Foundation.\n" - "\n" - " 14. If you wish to incorporate parts of the Library into other free\n" - "programs whose distribution conditions are incompatible with these,\n" - "write to the author to ask for permission. For software which is\n" - "copyrighted by the Free Software Foundation, write to the Free\n" - "Software Foundation; we sometimes make exceptions for this. Our\n" - "decision will be guided by the two goals of preserving the free status\n" - "of all derivatives of our free software and of promoting the sharing\n" - "and reuse of software generally.\n" - "\n" - " NO WARRANTY\n" - "\n" - " 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\n" - "WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\n" - "EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\n" - "OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\n" - "KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\n" - "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" - "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\n" - "LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\n" - "THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n" - "\n" - " 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\n" - "WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\n" - "AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\n" - "FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\n" - "CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\n" - "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\n" - "RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\n" - "FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\n" - "SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n" - "DAMAGES.\n" - "\n" - " END OF TERMS AND CONDITIONS\n" - "\n" - " How to Apply These Terms to Your New Libraries\n" - "\n" - " If you develop a new library, and you want it to be of the greatest\n" - "possible use to the public, we recommend making it free software that\n" - "everyone can redistribute and change. You can do so by permitting\n" - "redistribution under these terms (or, alternatively, under the terms of the\n" - "ordinary General Public License).\n" - "\n" - " To apply these terms, attach the following notices to the library. It is\n" - "safest to attach them to the start of each source file to most effectively\n" - "convey the exclusion of warranty; and each file should have at least the\n" - "\"copyright\" line and a pointer to where the full notice is found.\n" - "\n" - " <one line to give the library's name and a brief idea of what it does.>\n" - " Copyright (C) <year> <name of author>\n" - "\n" - " This library is free software; you can redistribute it and/or\n" - " modify it under the terms of the GNU Lesser General Public\n" - " License as published by the Free Software Foundation; either\n" - " version 2.1 of the License, or (at your option) any later version.\n" - "\n" - " This library is distributed in the hope that it will be useful,\n" - " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" - " Lesser General Public License for more details.\n" - "\n" - " You should have received a copy of the GNU Lesser General Public\n" - " License along with this library; if not, write to the Free Software\n" - " Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" - "\n" - "Also add information on how to contact you by electronic and paper mail.\n" - "\n" - "You should also get your employer (if you work as a programmer) or your\n" - "school, if any, to sign a \"copyright disclaimer\" for the library, if\n" - "necessary. Here is a sample; alter the names:\n" - "\n" - " Yoyodyne, Inc., hereby disclaims all copyright interest in the\n" - " library `Frob' (a library for tweaking knobs) written by James Random Hacker.\n" - "\n" - " <signature of Ty Coon>, 1 April 1990\n" - " Ty Coon, President of Vice\n" - "\n" - "That's all there is to it!"; +static const char *licenseQt = " GNU LESSER GENERAL PUBLIC LICENSE\n" + "\n" + " The Qt Toolkit is Copyright (C) 2015 The Qt Company Ltd.\n" + " Contact: http://www.qt.io/licensing/\n" + "\n" + " You may use, distribute and copy the Qt Toolkit under the terms of\n" + " GNU Lesser General Public License version 2.1, which is displayed below.\n" + "\n" + "-------------------------------------------------------------------------\n" + "\n" + " GNU LESSER GENERAL PUBLIC LICENSE\n" + " Version 2.1, February 1999\n" + "\n" + " Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n" + " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" + " Everyone is permitted to copy and distribute verbatim copies\n" + " of this license document, but changing it is not allowed.\n" + "\n" + "[This is the first released version of the Lesser GPL. It also counts\n" + " as the successor of the GNU Library Public License, version 2, hence\n" + " the version number 2.1.]\n" + "\n" + " Preamble\n" + "\n" + " The licenses for most software are designed to take away your\n" + "freedom to share and change it. By contrast, the GNU General Public\n" + "Licenses are intended to guarantee your freedom to share and change\n" + "free software--to make sure the software is free for all its users.\n" + "\n" + " This license, the Lesser General Public License, applies to some\n" + "specially designated software packages--typically libraries--of the\n" + "Free Software Foundation and other authors who decide to use it. You\n" + "can use it too, but we suggest you first think carefully about whether\n" + "this license or the ordinary General Public License is the better\n" + "strategy to use in any particular case, based on the explanations below.\n" + "\n" + " When we speak of free software, we are referring to freedom of use,\n" + "not price. Our General Public Licenses are designed to make sure that\n" + "you have the freedom to distribute copies of free software (and charge\n" + "for this service if you wish); that you receive source code or can get\n" + "it if you want it; that you can change the software and use pieces of\n" + "it in new free programs; and that you are informed that you can do\n" + "these things.\n" + "\n" + " To protect your rights, we need to make restrictions that forbid\n" + "distributors to deny you these rights or to ask you to surrender these\n" + "rights. These restrictions translate to certain responsibilities for\n" + "you if you distribute copies of the library or if you modify it.\n" + "\n" + " For example, if you distribute copies of the library, whether gratis\n" + "or for a fee, you must give the recipients all the rights that we gave\n" + "you. You must make sure that they, too, receive or can get the source\n" + "code. If you link other code with the library, you must provide\n" + "complete object files to the recipients, so that they can relink them\n" + "with the library after making changes to the library and recompiling\n" + "it. And you must show them these terms so they know their rights.\n" + "\n" + " We protect your rights with a two-step method: (1) we copyright the\n" + "library, and (2) we offer you this license, which gives you legal\n" + "permission to copy, distribute and/or modify the library.\n" + "\n" + " To protect each distributor, we want to make it very clear that\n" + "there is no warranty for the free library. Also, if the library is\n" + "modified by someone else and passed on, the recipients should know\n" + "that what they have is not the original version, so that the original\n" + "author's reputation will not be affected by problems that might be\n" + "introduced by others.\n" + "\n" + " Finally, software patents pose a constant threat to the existence of\n" + "any free program. We wish to make sure that a company cannot\n" + "effectively restrict the users of a free program by obtaining a\n" + "restrictive license from a patent holder. Therefore, we insist that\n" + "any patent license obtained for a version of the library must be\n" + "consistent with the full freedom of use specified in this license.\n" + "\n" + " Most GNU software, including some libraries, is covered by the\n" + "ordinary GNU General Public License. This license, the GNU Lesser\n" + "General Public License, applies to certain designated libraries, and\n" + "is quite different from the ordinary General Public License. We use\n" + "this license for certain libraries in order to permit linking those\n" + "libraries into non-free programs.\n" + "\n" + " When a program is linked with a library, whether statically or using\n" + "a shared library, the combination of the two is legally speaking a\n" + "combined work, a derivative of the original library. The ordinary\n" + "General Public License therefore permits such linking only if the\n" + "entire combination fits its criteria of freedom. The Lesser General\n" + "Public License permits more lax criteria for linking other code with\n" + "the library.\n" + "\n" + " We call this license the \"Lesser\" General Public License because it\n" + "does Less to protect the user's freedom than the ordinary General\n" + "Public License. It also provides other free software developers Less\n" + "of an advantage over competing non-free programs. These disadvantages\n" + "are the reason we use the ordinary General Public License for many\n" + "libraries. However, the Lesser license provides advantages in certain\n" + "special circumstances.\n" + "\n" + " For example, on rare occasions, there may be a special need to\n" + "encourage the widest possible use of a certain library, so that it becomes\n" + "a de-facto standard. To achieve this, non-free programs must be\n" + "allowed to use the library. A more frequent case is that a free\n" + "library does the same job as widely used non-free libraries. In this\n" + "case, there is little to gain by limiting the free library to free\n" + "software only, so we use the Lesser General Public License.\n" + "\n" + " In other cases, permission to use a particular library in non-free\n" + "programs enables a greater number of people to use a large body of\n" + "free software. For example, permission to use the GNU C Library in\n" + "non-free programs enables many more people to use the whole GNU\n" + "operating system, as well as its variant, the GNU/Linux operating\n" + "system.\n" + "\n" + " Although the Lesser General Public License is Less protective of the\n" + "users' freedom, it does ensure that the user of a program that is\n" + "linked with the Library has the freedom and the wherewithal to run\n" + "that program using a modified version of the Library.\n" + "\n" + " The precise terms and conditions for copying, distribution and\n" + "modification follow. Pay close attention to the difference between a\n" + "\"work based on the library\" and a \"work that uses the library\". The\n" + "former contains code derived from the library, whereas the latter must\n" + "be combined with the library in order to run.\n" + "\n" + " GNU LESSER GENERAL PUBLIC LICENSE\n" + " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" + "\n" + " 0. This License Agreement applies to any software library or other\n" + "program which contains a notice placed by the copyright holder or\n" + "other authorized party saying it may be distributed under the terms of\n" + "this Lesser General Public License (also called \"this License\").\n" + "Each licensee is addressed as \"you\".\n" + "\n" + " A \"library\" means a collection of software functions and/or data\n" + "prepared so as to be conveniently linked with application programs\n" + "(which use some of those functions and data) to form executables.\n" + "\n" + " The \"Library\", below, refers to any such software library or work\n" + "which has been distributed under these terms. A \"work based on the\n" + "Library\" means either the Library or any derivative work under\n" + "copyright law: that is to say, a work containing the Library or a\n" + "portion of it, either verbatim or with modifications and/or translated\n" + "straightforwardly into another language. (Hereinafter, translation is\n" + "included without limitation in the term \"modification\".)\n" + "\n" + " \"Source code\" for a work means the preferred form of the work for\n" + "making modifications to it. For a library, complete source code means\n" + "all the source code for all modules it contains, plus any associated\n" + "interface definition files, plus the scripts used to control compilation\n" + "and installation of the library.\n" + "\n" + " Activities other than copying, distribution and modification are not\n" + "covered by this License; they are outside its scope. The act of\n" + "running a program using the Library is not restricted, and output from\n" + "such a program is covered only if its contents constitute a work based\n" + "on the Library (independent of the use of the Library in a tool for\n" + "writing it). Whether that is true depends on what the Library does\n" + "and what the program that uses the Library does.\n" + "\n" + " 1. You may copy and distribute verbatim copies of the Library's\n" + "complete source code as you receive it, in any medium, provided that\n" + "you conspicuously and appropriately publish on each copy an\n" + "appropriate copyright notice and disclaimer of warranty; keep intact\n" + "all the notices that refer to this License and to the absence of any\n" + "warranty; and distribute a copy of this License along with the\n" + "Library.\n" + "\n" + " You may charge a fee for the physical act of transferring a copy,\n" + "and you may at your option offer warranty protection in exchange for a\n" + "fee.\n" + "\n" + " 2. You may modify your copy or copies of the Library or any portion\n" + "of it, thus forming a work based on the Library, and copy and\n" + "distribute such modifications or work under the terms of Section 1\n" + "above, provided that you also meet all of these conditions:\n" + "\n" + " a) The modified work must itself be a software library.\n" + "\n" + " b) You must cause the files modified to carry prominent notices\n" + " stating that you changed the files and the date of any change.\n" + "\n" + " c) You must cause the whole of the work to be licensed at no\n" + " charge to all third parties under the terms of this License.\n" + "\n" + " d) If a facility in the modified Library refers to a function or a\n" + " table of data to be supplied by an application program that uses\n" + " the facility, other than as an argument passed when the facility\n" + " is invoked, then you must make a good faith effort to ensure that,\n" + " in the event an application does not supply such function or\n" + " table, the facility still operates, and performs whatever part of\n" + " its purpose remains meaningful.\n" + "\n" + " (For example, a function in a library to compute square roots has\n" + " a purpose that is entirely well-defined independent of the\n" + " application. Therefore, Subsection 2d requires that any\n" + " application-supplied function or table used by this function must\n" + " be optional: if the application does not supply it, the square\n" + " root function must still compute square roots.)\n" + "\n" + "These requirements apply to the modified work as a whole. If\n" + "identifiable sections of that work are not derived from the Library,\n" + "and can be reasonably considered independent and separate works in\n" + "themselves, then this License, and its terms, do not apply to those\n" + "sections when you distribute them as separate works. But when you\n" + "distribute the same sections as part of a whole which is a work based\n" + "on the Library, the distribution of the whole must be on the terms of\n" + "this License, whose permissions for other licensees extend to the\n" + "entire whole, and thus to each and every part regardless of who wrote\n" + "it.\n" + "\n" + "Thus, it is not the intent of this section to claim rights or contest\n" + "your rights to work written entirely by you; rather, the intent is to\n" + "exercise the right to control the distribution of derivative or\n" + "collective works based on the Library.\n" + "\n" + "In addition, mere aggregation of another work not based on the Library\n" + "with the Library (or with a work based on the Library) on a volume of\n" + "a storage or distribution medium does not bring the other work under\n" + "the scope of this License.\n" + "\n" + " 3. You may opt to apply the terms of the ordinary GNU General Public\n" + "License instead of this License to a given copy of the Library. To do\n" + "this, you must alter all the notices that refer to this License, so\n" + "that they refer to the ordinary GNU General Public License, version 2,\n" + "instead of to this License. (If a newer version than version 2 of the\n" + "ordinary GNU General Public License has appeared, then you can specify\n" + "that version instead if you wish.) Do not make any other change in\n" + "these notices.\n" + "\n" + " Once this change is made in a given copy, it is irreversible for\n" + "that copy, so the ordinary GNU General Public License applies to all\n" + "subsequent copies and derivative works made from that copy.\n" + "\n" + " This option is useful when you wish to copy part of the code of\n" + "the Library into a program that is not a library.\n" + "\n" + " 4. You may copy and distribute the Library (or a portion or\n" + "derivative of it, under Section 2) in object code or executable form\n" + "under the terms of Sections 1 and 2 above provided that you accompany\n" + "it with the complete corresponding machine-readable source code, which\n" + "must be distributed under the terms of Sections 1 and 2 above on a\n" + "medium customarily used for software interchange.\n" + "\n" + " If distribution of object code is made by offering access to copy\n" + "from a designated place, then offering equivalent access to copy the\n" + "source code from the same place satisfies the requirement to\n" + "distribute the source code, even though third parties are not\n" + "compelled to copy the source along with the object code.\n" + "\n" + " 5. A program that contains no derivative of any portion of the\n" + "Library, but is designed to work with the Library by being compiled or\n" + "linked with it, is called a \"work that uses the Library\". Such a\n" + "work, in isolation, is not a derivative work of the Library, and\n" + "therefore falls outside the scope of this License.\n" + "\n" + " However, linking a \"work that uses the Library\" with the Library\n" + "creates an executable that is a derivative of the Library (because it\n" + "contains portions of the Library), rather than a \"work that uses the\n" + "library\". The executable is therefore covered by this License.\n" + "Section 6 states terms for distribution of such executables.\n" + "\n" + " When a \"work that uses the Library\" uses material from a header file\n" + "that is part of the Library, the object code for the work may be a\n" + "derivative work of the Library even though the source code is not.\n" + "Whether this is true is especially significant if the work can be\n" + "linked without the Library, or if the work is itself a library. The\n" + "threshold for this to be true is not precisely defined by law.\n" + "\n" + " If such an object file uses only numerical parameters, data\n" + "structure layouts and accessors, and small macros and small inline\n" + "functions (ten lines or less in length), then the use of the object\n" + "file is unrestricted, regardless of whether it is legally a derivative\n" + "work. (Executables containing this object code plus portions of the\n" + "Library will still fall under Section 6.)\n" + "\n" + " Otherwise, if the work is a derivative of the Library, you may\n" + "distribute the object code for the work under the terms of Section 6.\n" + "Any executables containing that work also fall under Section 6,\n" + "whether or not they are linked directly with the Library itself.\n" + "\n" + " 6. As an exception to the Sections above, you may also combine or\n" + "link a \"work that uses the Library\" with the Library to produce a\n" + "work containing portions of the Library, and distribute that work\n" + "under terms of your choice, provided that the terms permit\n" + "modification of the work for the customer's own use and reverse\n" + "engineering for debugging such modifications.\n" + "\n" + " You must give prominent notice with each copy of the work that the\n" + "Library is used in it and that the Library and its use are covered by\n" + "this License. You must supply a copy of this License. If the work\n" + "during execution displays copyright notices, you must include the\n" + "copyright notice for the Library among them, as well as a reference\n" + "directing the user to the copy of this License. Also, you must do one\n" + "of these things:\n" + "\n" + " a) Accompany the work with the complete corresponding\n" + " machine-readable source code for the Library including whatever\n" + " changes were used in the work (which must be distributed under\n" + " Sections 1 and 2 above); and, if the work is an executable linked\n" + " with the Library, with the complete machine-readable \"work that\n" + " uses the Library\", as object code and/or source code, so that the\n" + " user can modify the Library and then relink to produce a modified\n" + " executable containing the modified Library. (It is understood\n" + " that the user who changes the contents of definitions files in the\n" + " Library will not necessarily be able to recompile the application\n" + " to use the modified definitions.)\n" + "\n" + " b) Use a suitable shared library mechanism for linking with the\n" + " Library. A suitable mechanism is one that (1) uses at run time a\n" + " copy of the library already present on the user's computer system,\n" + " rather than copying library functions into the executable, and (2)\n" + " will operate properly with a modified version of the library, if\n" + " the user installs one, as long as the modified version is\n" + " interface-compatible with the version that the work was made with.\n" + "\n" + " c) Accompany the work with a written offer, valid for at\n" + " least three years, to give the same user the materials\n" + " specified in Subsection 6a, above, for a charge no more\n" + " than the cost of performing this distribution.\n" + "\n" + " d) If distribution of the work is made by offering access to copy\n" + " from a designated place, offer equivalent access to copy the above\n" + " specified materials from the same place.\n" + "\n" + " e) Verify that the user has already received a copy of these\n" + " materials or that you have already sent this user a copy.\n" + "\n" + " For an executable, the required form of the \"work that uses the\n" + "Library\" must include any data and utility programs needed for\n" + "reproducing the executable from it. However, as a special exception,\n" + "the materials to be distributed need not include anything that is\n" + "normally distributed (in either source or binary form) with the major\n" + "components (compiler, kernel, and so on) of the operating system on\n" + "which the executable runs, unless that component itself accompanies\n" + "the executable.\n" + "\n" + " It may happen that this requirement contradicts the license\n" + "restrictions of other proprietary libraries that do not normally\n" + "accompany the operating system. Such a contradiction means you cannot\n" + "use both them and the Library together in an executable that you\n" + "distribute.\n" + "\n" + " 7. You may place library facilities that are a work based on the\n" + "Library side-by-side in a single library together with other library\n" + "facilities not covered by this License, and distribute such a combined\n" + "library, provided that the separate distribution of the work based on\n" + "the Library and of the other library facilities is otherwise\n" + "permitted, and provided that you do these two things:\n" + "\n" + " a) Accompany the combined library with a copy of the same work\n" + " based on the Library, uncombined with any other library\n" + " facilities. This must be distributed under the terms of the\n" + " Sections above.\n" + "\n" + " b) Give prominent notice with the combined library of the fact\n" + " that part of it is a work based on the Library, and explaining\n" + " where to find the accompanying uncombined form of the same work.\n" + "\n" + " 8. You may not copy, modify, sublicense, link with, or distribute\n" + "the Library except as expressly provided under this License. Any\n" + "attempt otherwise to copy, modify, sublicense, link with, or\n" + "distribute the Library is void, and will automatically terminate your\n" + "rights under this License. However, parties who have received copies,\n" + "or rights, from you under this License will not have their licenses\n" + "terminated so long as such parties remain in full compliance.\n" + "\n" + " 9. You are not required to accept this License, since you have not\n" + "signed it. However, nothing else grants you permission to modify or\n" + "distribute the Library or its derivative works. These actions are\n" + "prohibited by law if you do not accept this License. Therefore, by\n" + "modifying or distributing the Library (or any work based on the\n" + "Library), you indicate your acceptance of this License to do so, and\n" + "all its terms and conditions for copying, distributing or modifying\n" + "the Library or works based on it.\n" + "\n" + " 10. Each time you redistribute the Library (or any work based on the\n" + "Library), the recipient automatically receives a license from the\n" + "original licensor to copy, distribute, link with or modify the Library\n" + "subject to these terms and conditions. You may not impose any further\n" + "restrictions on the recipients' exercise of the rights granted herein.\n" + "You are not responsible for enforcing compliance by third parties with\n" + "this License.\n" + "\n" + " 11. If, as a consequence of a court judgment or allegation of patent\n" + "infringement or for any other reason (not limited to patent issues),\n" + "conditions are imposed on you (whether by court order, agreement or\n" + "otherwise) that contradict the conditions of this License, they do not\n" + "excuse you from the conditions of this License. If you cannot\n" + "distribute so as to satisfy simultaneously your obligations under this\n" + "License and any other pertinent obligations, then as a consequence you\n" + "may not distribute the Library at all. For example, if a patent\n" + "license would not permit royalty-free redistribution of the Library by\n" + "all those who receive copies directly or indirectly through you, then\n" + "the only way you could satisfy both it and this License would be to\n" + "refrain entirely from distribution of the Library.\n" + "\n" + "If any portion of this section is held invalid or unenforceable under any\n" + "particular circumstance, the balance of the section is intended to apply,\n" + "and the section as a whole is intended to apply in other circumstances.\n" + "\n" + "It is not the purpose of this section to induce you to infringe any\n" + "patents or other property right claims or to contest validity of any\n" + "such claims; this section has the sole purpose of protecting the\n" + "integrity of the free software distribution system which is\n" + "implemented by public license practices. Many people have made\n" + "generous contributions to the wide range of software distributed\n" + "through that system in reliance on consistent application of that\n" + "system; it is up to the author/donor to decide if he or she is willing\n" + "to distribute software through any other system and a licensee cannot\n" + "impose that choice.\n" + "\n" + "This section is intended to make thoroughly clear what is believed to\n" + "be a consequence of the rest of this License.\n" + "\n" + " 12. If the distribution and/or use of the Library is restricted in\n" + "certain countries either by patents or by copyrighted interfaces, the\n" + "original copyright holder who places the Library under this License may add\n" + "an explicit geographical distribution limitation excluding those countries,\n" + "so that distribution is permitted only in or among countries not thus\n" + "excluded. In such case, this License incorporates the limitation as if\n" + "written in the body of this License.\n" + "\n" + " 13. The Free Software Foundation may publish revised and/or new\n" + "versions of the Lesser General Public License from time to time.\n" + "Such new versions will be similar in spirit to the present version,\n" + "but may differ in detail to address new problems or concerns.\n" + "\n" + "Each version is given a distinguishing version number. If the Library\n" + "specifies a version number of this License which applies to it and\n" + "\"any later version\", you have the option of following the terms and\n" + "conditions either of that version or of any later version published by\n" + "the Free Software Foundation. If the Library does not specify a\n" + "license version number, you may choose any version ever published by\n" + "the Free Software Foundation.\n" + "\n" + " 14. If you wish to incorporate parts of the Library into other free\n" + "programs whose distribution conditions are incompatible with these,\n" + "write to the author to ask for permission. For software which is\n" + "copyrighted by the Free Software Foundation, write to the Free\n" + "Software Foundation; we sometimes make exceptions for this. Our\n" + "decision will be guided by the two goals of preserving the free status\n" + "of all derivatives of our free software and of promoting the sharing\n" + "and reuse of software generally.\n" + "\n" + " NO WARRANTY\n" + "\n" + " 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\n" + "WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\n" + "EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\n" + "OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\n" + "KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\n" + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" + "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\n" + "LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\n" + "THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n" + "\n" + " 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\n" + "WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\n" + "AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\n" + "FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\n" + "CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\n" + "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\n" + "RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\n" + "FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\n" + "SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n" + "DAMAGES.\n" + "\n" + " END OF TERMS AND CONDITIONS\n" + "\n" + " How to Apply These Terms to Your New Libraries\n" + "\n" + " If you develop a new library, and you want it to be of the greatest\n" + "possible use to the public, we recommend making it free software that\n" + "everyone can redistribute and change. You can do so by permitting\n" + "redistribution under these terms (or, alternatively, under the terms of the\n" + "ordinary General Public License).\n" + "\n" + " To apply these terms, attach the following notices to the library. It is\n" + "safest to attach them to the start of each source file to most effectively\n" + "convey the exclusion of warranty; and each file should have at least the\n" + "\"copyright\" line and a pointer to where the full notice is found.\n" + "\n" + " <one line to give the library's name and a brief idea of what it does.>\n" + " Copyright (C) <year> <name of author>\n" + "\n" + " This library is free software; you can redistribute it and/or\n" + " modify it under the terms of the GNU Lesser General Public\n" + " License as published by the Free Software Foundation; either\n" + " version 2.1 of the License, or (at your option) any later version.\n" + "\n" + " This library is distributed in the hope that it will be useful,\n" + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" + " Lesser General Public License for more details.\n" + "\n" + " You should have received a copy of the GNU Lesser General Public\n" + " License along with this library; if not, write to the Free Software\n" + " Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" + "\n" + "Also add information on how to contact you by electronic and paper mail.\n" + "\n" + "You should also get your employer (if you work as a programmer) or your\n" + "school, if any, to sign a \"copyright disclaimer\" for the library, if\n" + "necessary. Here is a sample; alter the names:\n" + "\n" + " Yoyodyne, Inc., hereby disclaims all copyright interest in the\n" + " library `Frob' (a library for tweaking knobs) written by James Random Hacker.\n" + "\n" + " <signature of Ty Coon>, 1 April 1990\n" + " Ty Coon, President of Vice\n" + "\n" + "That's all there is to it!"; #endif #ifdef USE_BUILDENV -static const char *licenseSQLite3 = - "The author disclaims copyright to this source code. In place of\n" - "a legal notice, here is a blessing:\n" - "\n" - " May you do good and not evil.\n" - " May you find forgiveness for yourself and forgive others.\n" - " May you share freely, never taking more than you give."; +static const char *licenseSQLite3 = "The author disclaims copyright to this source code. In place of\n" + "a legal notice, here is a blessing:\n" + "\n" + " May you do good and not evil.\n" + " May you find forgiveness for yourself and forgive others.\n" + " May you share freely, never taking more than you give."; #endif #ifdef USE_BUILDENV -static const char *licenseXar = - "/*\n" - " * Copyright (c) 2005-2007 Rob Braun\n" - " * All rights reserved.\n" - " *\n" - " * Redistribution and use in source and binary forms, with or without\n" - " * modification, are permitted provided that the following conditions\n" - " * are met:\n" - " * 1. Redistributions of source code must retain the above copyright\n" - " * notice, this list of conditions and the following disclaimer.\n" - " * 2. Redistributions in binary form must reproduce the above copyright\n" - " * notice, this list of conditions and the following disclaimer in the\n" - " * documentation and/or other materials provided with the distribution.\n" - " * 3. Neither the name of Rob Braun nor the names of his contributors\n" - " * may be used to endorse or promote products derived from this software\n" - " * without specific prior written permission.\n" - " *\n" - " * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" - " * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" - " * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" - " * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n" - " * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" - " * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" - " * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" - " * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" - " * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" - " * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" - " * POSSIBILITY OF SUCH DAMAGE.\n" - " */\n" - "/*\n" - " * 03-Apr-2005\n" - " * DRI: Rob Braun <bbraun@synack.net>\n" - " */"; +static const char *licenseXar = "/*\n" + " * Copyright (c) 2005-2007 Rob Braun\n" + " * All rights reserved.\n" + " *\n" + " * Redistribution and use in source and binary forms, with or without\n" + " * modification, are permitted provided that the following conditions\n" + " * are met:\n" + " * 1. Redistributions of source code must retain the above copyright\n" + " * notice, this list of conditions and the following disclaimer.\n" + " * 2. Redistributions in binary form must reproduce the above copyright\n" + " * notice, this list of conditions and the following disclaimer in the\n" + " * documentation and/or other materials provided with the distribution.\n" + " * 3. Neither the name of Rob Braun nor the names of his contributors\n" + " * may be used to endorse or promote products derived from this software\n" + " * without specific prior written permission.\n" + " *\n" + " * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" + " * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" + " * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" + " * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n" + " * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" + " * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" + " * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" + " * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" + " * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" + " * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" + " * POSSIBILITY OF SUCH DAMAGE.\n" + " */\n" + "/*\n" + " * 03-Apr-2005\n" + " * DRI: Rob Braun <bbraun@synack.net>\n" + " */"; #endif #ifdef USE_BUILDENV -static const char *licenseAvahi = - "Copyright 2004-2015 by the Avahi developers.\n" - "\n" - "avahi is free software; you can redistribute it and/or modify it\n" - "under the terms of the GNU Lesser General Public License as\n" - "published by the Free Software Foundation; either version 2.1 of the\n" - "License, or (at your option) any later version.\n" - "\n" - "avahi is distributed in the hope that it will be useful, but WITHOUT\n" - "ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n" - "or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General\n" - "Public License for more details.\n" - "\n" - "You should have received a copy of the GNU Lesser General Public\n" - "License along with avahi; if not, write to the Free Software\n" - "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\n" - "USA."; +static const char *licenseAvahi = "Copyright 2004-2015 by the Avahi developers.\n" + "\n" + "avahi is free software; you can redistribute it and/or modify it\n" + "under the terms of the GNU Lesser General Public License as\n" + "published by the Free Software Foundation; either version 2.1 of the\n" + "License, or (at your option) any later version.\n" + "\n" + "avahi is distributed in the hope that it will be useful, but WITHOUT\n" + "ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n" + "or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General\n" + "Public License for more details.\n" + "\n" + "You should have received a copy of the GNU Lesser General Public\n" + "License along with avahi; if not, write to the Free Software\n" + "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\n" + "USA."; #endif #ifdef USE_BUILDENV -static const char *licenseDBus = - "D-Bus is licensed to you under your choice of the Academic Free\n" - "License version 2.1, or the GNU General Public License version 2\n" - "(or, at your option any later version).\n" - "\n" - "Both licenses are included here. Some of the standalone binaries are\n" - "under the GPL only; in particular, but not limited to,\n" - "tools/dbus-cleanup-sockets.c and test/decode-gcov.c. Each source code\n" - "file is marked with the proper copyright information - if you find a\n" - "file that isn't marked please bring it to our attention.\n" - "\n" - "The Academic Free License\n" - "v. 2.1\n" - "\n" - "This Academic Free License (the \"License\") applies to any original work of authorship (the \"Original Work\") whose owner (the \"Licensor\") has placed the following notice immediately following the copyright notice for the Original Work:\n" - "\n" - "Licensed under the Academic Free License version 2.1\n" - "\n" - "1) Grant of Copyright License. Licensor hereby grants You a\n" - "world-wide, royalty-free, non-exclusive, perpetual, sublicenseable\n" - "license to do the following:\n" - "\n" - "a) to reproduce the Original Work in copies;\n" - "\n" - "b) to prepare derivative works (\"Derivative Works\") based upon the Original Work;\n" - "\n" - "c) to distribute copies of the Original Work and Derivative Works to the public;\n" - "\n" - "d) to perform the Original Work publicly; and\n" - "\n" - "e) to display the Original Work publicly.\n" - "\n" - "2) Grant of Patent License. Licensor hereby grants You a world-wide,\n" - "royalty-free, non-exclusive, perpetual, sublicenseable license, under\n" - "patent claims owned or controlled by the Licensor that are embodied in\n" - "the Original Work as furnished by the Licensor, to make, use, sell and\n" - "offer for sale the Original Work and Derivative Works.\n" - "\n" - "3) Grant of Source Code License. The term \"Source Code\" means the\n" - "preferred form of the Original Work for making modifications to it and\n" - "all available documentation describing how to modify the Original\n" - "Work. Licensor hereby agrees to provide a machine-readable copy of the\n" - "Source Code of the Original Work along with each copy of the Original\n" - "Work that Licensor distributes. Licensor reserves the right to satisfy\n" - "this obligation by placing a machine-readable copy of the Source Code\n" - "in an information repository reasonably calculated to permit\n" - "inexpensive and convenient access by You for as long as Licensor\n" - "continues to distribute the Original Work, and by publishing the\n" - "address of that information repository in a notice immediately\n" - "following the copyright notice that applies to the Original Work.\n" - "\n" - "4) Exclusions From License Grant. Neither the names of Licensor, nor\n" - "the names of any contributors to the Original Work, nor any of their\n" - "trademarks or service marks, may be used to endorse or promote\n" - "products derived from this Original Work without express prior written\n" - "permission of the Licensor. Nothing in this License shall be deemed to\n" - "grant any rights to trademarks, copyrights, patents, trade secrets or\n" - "any other intellectual property of Licensor except as expressly stated\n" - "herein. No patent license is granted to make, use, sell or offer to\n" - "sell embodiments of any patent claims other than the licensed claims\n" - "defined in Section 2. No right is granted to the trademarks of\n" - "Licensor even if such marks are included in the Original Work. Nothing\n" - "in this License shall be interpreted to prohibit Licensor from\n" - "licensing under different terms from this License any Original Work\n" - "that Licensor otherwise would have a right to license.\n" - "\n" - "5) This section intentionally omitted.\n" - "\n" - "6) Attribution Rights. You must retain, in the Source Code of any\n" - "Derivative Works that You create, all copyright, patent or trademark\n" - "notices from the Source Code of the Original Work, as well as any\n" - "notices of licensing and any descriptive text identified therein as an\n" - "\"Attribution Notice.\" You must cause the Source Code for any\n" - "Derivative Works that You create to carry a prominent Attribution\n" - "Notice reasonably calculated to inform recipients that You have\n" - "modified the Original Work.\n" - "\n" - "7) Warranty of Provenance and Disclaimer of Warranty. Licensor\n" - "warrants that the copyright in and to the Original Work and the patent\n" - "rights granted herein by Licensor are owned by the Licensor or are\n" - "sublicensed to You under the terms of this License with the permission\n" - "of the contributor(s) of those copyrights and patent rights. Except as\n" - "expressly stated in the immediately proceeding sentence, the Original\n" - "Work is provided under this License on an \"AS IS\" BASIS and WITHOUT\n" - "WARRANTY, either express or implied, including, without limitation,\n" - "the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A\n" - "PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL\n" - "WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential\n" - "part of this License. No license to Original Work is granted hereunder\n" - "except under this disclaimer.\n" - "\n" - "8) Limitation of Liability. Under no circumstances and under no legal\n" - "theory, whether in tort (including negligence), contract, or\n" - "otherwise, shall the Licensor be liable to any person for any direct,\n" - "indirect, special, incidental, or consequential damages of any\n" - "character arising as a result of this License or the use of the\n" - "Original Work including, without limitation, damages for loss of\n" - "goodwill, work stoppage, computer failure or malfunction, or any and\n" - "all other commercial damages or losses. This limitation of liability\n" - "shall not apply to liability for death or personal injury resulting\n" - "from Licensor's negligence to the extent applicable law prohibits such\n" - "limitation. Some jurisdictions do not allow the exclusion or\n" - "limitation of incidental or consequential damages, so this exclusion\n" - "and limitation may not apply to You.\n" - "\n" - "9) Acceptance and Termination. If You distribute copies of the\n" - "Original Work or a Derivative Work, You must make a reasonable effort\n" - "under the circumstances to obtain the express assent of recipients to\n" - "the terms of this License. Nothing else but this License (or another\n" - "written agreement between Licensor and You) grants You permission to\n" - "create Derivative Works based upon the Original Work or to exercise\n" - "any of the rights granted in Section 1 herein, and any attempt to do\n" - "so except under the terms of this License (or another written\n" - "agreement between Licensor and You) is expressly prohibited by\n" - "U.S. copyright law, the equivalent laws of other countries, and by\n" - "international treaty. Therefore, by exercising any of the rights\n" - "granted to You in Section 1 herein, You indicate Your acceptance of\n" - "this License and all of its terms and conditions.\n" - "\n" - "10) Termination for Patent Action. This License shall terminate\n" - "automatically and You may no longer exercise any of the rights granted\n" - "to You by this License as of the date You commence an action,\n" - "including a cross-claim or counterclaim, against Licensor or any\n" - "licensee alleging that the Original Work infringes a patent. This\n" - "termination provision shall not apply for an action alleging patent\n" - "infringement by combinations of the Original Work with other software\n" - "or hardware.\n" - "\n" - "11) Jurisdiction, Venue and Governing Law. Any action or suit relating\n" - "to this License may be brought only in the courts of a jurisdiction\n" - "wherein the Licensor resides or in which Licensor conducts its primary\n" - "business, and under the laws of that jurisdiction excluding its\n" - "conflict-of-law provisions. The application of the United Nations\n" - "Convention on Contracts for the International Sale of Goods is\n" - "expressly excluded. Any use of the Original Work outside the scope of\n" - "this License or after its termination shall be subject to the\n" - "requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101\n" - "et seq., the equivalent laws of other countries, and international\n" - "treaty. This section shall survive the termination of this License.\n" - "\n" - "12) Attorneys Fees. In any action to enforce the terms of this License\n" - "or seeking damages relating thereto, the prevailing party shall be\n" - "entitled to recover its costs and expenses, including, without\n" - "limitation, reasonable attorneys' fees and costs incurred in\n" - "connection with such action, including any appeal of such action. This\n" - "section shall survive the termination of this License.\n" - "\n" - "13) Miscellaneous. This License represents the complete agreement\n" - "concerning the subject matter hereof. If any provision of this License\n" - "is held to be unenforceable, such provision shall be reformed only to\n" - "the extent necessary to make it enforceable.\n" - "\n" - "14) Definition of \"You\" in This License. \"You\" throughout this\n" - "License, whether in upper or lower case, means an individual or a\n" - "legal entity exercising rights under, and complying with all of the\n" - "terms of, this License. For legal entities, \"You\" includes any entity\n" - "that controls, is controlled by, or is under common control with\n" - "you. For purposes of this definition, \"control\" means (i) the power,\n" - "direct or indirect, to cause the direction or management of such\n" - "entity, whether by contract or otherwise, or (ii) ownership of fifty\n" - "percent (50%) or more of the outstanding shares, or (iii) beneficial\n" - "ownership of such entity.\n" - "\n" - "15) Right to Use. You may use the Original Work in all ways not\n" - "otherwise restricted or conditioned by this License or by law, and\n" - "Licensor promises not to interfere with or be responsible for such\n" - "uses by You.\n" - "\n" - "This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights\n" - "reserved. Permission is hereby granted to copy and distribute this\n" - "license without modification. This license may not be modified without\n" - "the express written permission of its copyright owner.\n" - "\n" - "\n" - "-- \n" - "END OF ACADEMIC FREE LICENSE. The following is intended to describe the essential \n" - "differences between the Academic Free License (AFL) version 1.0 and other \n" - "open source licenses:\n" - "\n" - "The Academic Free License is similar to the BSD, MIT, UoI/NCSA and Apache \n" - "licenses in many respects but it is intended to solve a few problems with \n" - "those licenses.\n" - " \n" - "* The AFL is written so as to make it clear what software is being \n" - "licensed (by the inclusion of a statement following the copyright notice \n" - "in the software). This way, the license functions better than a template \n" - "license. The BSD, MIT and UoI/NCSA licenses apply to unidentified software.\n" - " \n" - "* The AFL contains a complete copyright grant to the software. The BSD \n" - "and Apache licenses are vague and incomplete in that respect.\n" - " \n" - "* The AFL contains a complete patent grant to the software. The BSD, MIT, \n" - "UoI/NCSA and Apache licenses rely on an implied patent license and contain \n" - "no explicit patent grant.\n" - " \n" - "* The AFL makes it clear that no trademark rights are granted to the \n" - "licensor's trademarks. The Apache license contains such a provision, but the \n" - "BSD, MIT and UoI/NCSA licenses do not.\n" - " \n" - "* The AFL includes the warranty by the licensor that it either owns the \n" - "copyright or that it is distributing the software under a license. None of \n" - "the other licenses contain that warranty. All other warranties are disclaimed, \n" - "as is the case for the other licenses.\n" - "\n" - "* The AFL is itself copyrighted (with the right granted to copy and distribute \n" - "without modification). This ensures that the owner of the copyright to the \n" - "license will control changes. The Apache license contains a copyright notice, \n" - "but the BSD, MIT and UoI/NCSA licenses do not. \n" - "--\n" - "START OF GNU GENERAL PUBLIC LICENSE\n" - "--\n" - "\n" - " GNU GENERAL PUBLIC LICENSE\n" - " Version 2, June 1991\n" - "\n" - " Copyright (C) 1989, 1991 Free Software Foundation, Inc.\n" - " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" - "\n" - " Everyone is permitted to copy and distribute verbatim copies\n" - " of this license document, but changing it is not allowed.\n" - "\n" - " Preamble\n" - "\n" - " The licenses for most software are designed to take away your\n" - "freedom to share and change it. By contrast, the GNU General Public\n" - "License is intended to guarantee your freedom to share and change free\n" - "software--to make sure the software is free for all its users. This\n" - "General Public License applies to most of the Free Software\n" - "Foundation's software and to any other program whose authors commit to\n" - "using it. (Some other Free Software Foundation software is covered by\n" - "the GNU Library General Public License instead.) You can apply it to\n" - "your programs, too.\n" - "\n" - " When we speak of free software, we are referring to freedom, not\n" - "price. Our General Public Licenses are designed to make sure that you\n" - "have the freedom to distribute copies of free software (and charge for\n" - "this service if you wish), that you receive source code or can get it\n" - "if you want it, that you can change the software or use pieces of it\n" - "in new free programs; and that you know you can do these things.\n" - "\n" - " To protect your rights, we need to make restrictions that forbid\n" - "anyone to deny you these rights or to ask you to surrender the rights.\n" - "These restrictions translate to certain responsibilities for you if you\n" - "distribute copies of the software, or if you modify it.\n" - "\n" - " For example, if you distribute copies of such a program, whether\n" - "gratis or for a fee, you must give the recipients all the rights that\n" - "you have. You must make sure that they, too, receive or can get the\n" - "source code. And you must show them these terms so they know their\n" - "rights.\n" - "\n" - " We protect your rights with two steps: (1) copyright the software, and\n" - "(2) offer you this license which gives you legal permission to copy,\n" - "distribute and/or modify the software.\n" - "\n" - " Also, for each author's protection and ours, we want to make certain\n" - "that everyone understands that there is no warranty for this free\n" - "software. If the software is modified by someone else and passed on, we\n" - "want its recipients to know that what they have is not the original, so\n" - "that any problems introduced by others will not reflect on the original\n" - "authors' reputations.\n" - "\n" - " Finally, any free program is threatened constantly by software\n" - "patents. We wish to avoid the danger that redistributors of a free\n" - "program will individually obtain patent licenses, in effect making the\n" - "program proprietary. To prevent this, we have made it clear that any\n" - "patent must be licensed for everyone's free use or not licensed at all.\n" - "\n" - " The precise terms and conditions for copying, distribution and\n" - "modification follow.\n" - "\n" - " GNU GENERAL PUBLIC LICENSE\n" - " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" - "\n" - " 0. This License applies to any program or other work which contains\n" - "a notice placed by the copyright holder saying it may be distributed\n" - "under the terms of this General Public License. The \"Program\", below,\n" - "refers to any such program or work, and a \"work based on the Program\"\n" - "means either the Program or any derivative work under copyright law:\n" - "that is to say, a work containing the Program or a portion of it,\n" - "either verbatim or with modifications and/or translated into another\n" - "language. (Hereinafter, translation is included without limitation in\n" - "the term \"modification\".) Each licensee is addressed as \"you\".\n" - "\n" - "Activities other than copying, distribution and modification are not\n" - "covered by this License; they are outside its scope. The act of\n" - "running the Program is not restricted, and the output from the Program\n" - "is covered only if its contents constitute a work based on the\n" - "Program (independent of having been made by running the Program).\n" - "Whether that is true depends on what the Program does.\n" - "\n" - " 1. You may copy and distribute verbatim copies of the Program's\n" - "source code as you receive it, in any medium, provided that you\n" - "conspicuously and appropriately publish on each copy an appropriate\n" - "copyright notice and disclaimer of warranty; keep intact all the\n" - "notices that refer to this License and to the absence of any warranty;\n" - "and give any other recipients of the Program a copy of this License\n" - "along with the Program.\n" - "\n" - "You may charge a fee for the physical act of transferring a copy, and\n" - "you may at your option offer warranty protection in exchange for a fee.\n" - "\n" - " 2. You may modify your copy or copies of the Program or any portion\n" - "of it, thus forming a work based on the Program, and copy and\n" - "distribute such modifications or work under the terms of Section 1\n" - "above, provided that you also meet all of these conditions:\n" - "\n" - " a) You must cause the modified files to carry prominent notices\n" - " stating that you changed the files and the date of any change.\n" - "\n" - " b) You must cause any work that you distribute or publish, that in\n" - " whole or in part contains or is derived from the Program or any\n" - " part thereof, to be licensed as a whole at no charge to all third\n" - " parties under the terms of this License.\n" - "\n" - " c) If the modified program normally reads commands interactively\n" - " when run, you must cause it, when started running for such\n" - " interactive use in the most ordinary way, to print or display an\n" - " announcement including an appropriate copyright notice and a\n" - " notice that there is no warranty (or else, saying that you provide\n" - " a warranty) and that users may redistribute the program under\n" - " these conditions, and telling the user how to view a copy of this\n" - " License. (Exception: if the Program itself is interactive but\n" - " does not normally print such an announcement, your work based on\n" - " the Program is not required to print an announcement.)\n" - "\n" - "These requirements apply to the modified work as a whole. If\n" - "identifiable sections of that work are not derived from the Program,\n" - "and can be reasonably considered independent and separate works in\n" - "themselves, then this License, and its terms, do not apply to those\n" - "sections when you distribute them as separate works. But when you\n" - "distribute the same sections as part of a whole which is a work based\n" - "on the Program, the distribution of the whole must be on the terms of\n" - "this License, whose permissions for other licensees extend to the\n" - "entire whole, and thus to each and every part regardless of who wrote it.\n" - "\n" - "Thus, it is not the intent of this section to claim rights or contest\n" - "your rights to work written entirely by you; rather, the intent is to\n" - "exercise the right to control the distribution of derivative or\n" - "collective works based on the Program.\n" - "\n" - "In addition, mere aggregation of another work not based on the Program\n" - "with the Program (or with a work based on the Program) on a volume of\n" - "a storage or distribution medium does not bring the other work under\n" - "the scope of this License.\n" - "\n" - " 3. You may copy and distribute the Program (or a work based on it,\n" - "under Section 2) in object code or executable form under the terms of\n" - "Sections 1 and 2 above provided that you also do one of the following:\n" - "\n" - " a) Accompany it with the complete corresponding machine-readable\n" - " source code, which must be distributed under the terms of Sections\n" - " 1 and 2 above on a medium customarily used for software interchange; or,\n" - "\n" - " b) Accompany it with a written offer, valid for at least three\n" - " years, to give any third party, for a charge no more than your\n" - " cost of physically performing source distribution, a complete\n" - " machine-readable copy of the corresponding source code, to be\n" - " distributed under the terms of Sections 1 and 2 above on a medium\n" - " customarily used for software interchange; or,\n" - "\n" - " c) Accompany it with the information you received as to the offer\n" - " to distribute corresponding source code. (This alternative is\n" - " allowed only for noncommercial distribution and only if you\n" - " received the program in object code or executable form with such\n" - " an offer, in accord with Subsection b above.)\n" - "\n" - "The source code for a work means the preferred form of the work for\n" - "making modifications to it. For an executable work, complete source\n" - "code means all the source code for all modules it contains, plus any\n" - "associated interface definition files, plus the scripts used to\n" - "control compilation and installation of the executable. However, as a\n" - "special exception, the source code distributed need not include\n" - "anything that is normally distributed (in either source or binary\n" - "form) with the major components (compiler, kernel, and so on) of the\n" - "operating system on which the executable runs, unless that component\n" - "itself accompanies the executable.\n" - "\n" - "If distribution of executable or object code is made by offering\n" - "access to copy from a designated place, then offering equivalent\n" - "access to copy the source code from the same place counts as\n" - "distribution of the source code, even though third parties are not\n" - "compelled to copy the source along with the object code.\n" - "\n" - " 4. You may not copy, modify, sublicense, or distribute the Program\n" - "except as expressly provided under this License. Any attempt\n" - "otherwise to copy, modify, sublicense or distribute the Program is\n" - "void, and will automatically terminate your rights under this License.\n" - "However, parties who have received copies, or rights, from you under\n" - "this License will not have their licenses terminated so long as such\n" - "parties remain in full compliance.\n" - "\n" - " 5. You are not required to accept this License, since you have not\n" - "signed it. However, nothing else grants you permission to modify or\n" - "distribute the Program or its derivative works. These actions are\n" - "prohibited by law if you do not accept this License. Therefore, by\n" - "modifying or distributing the Program (or any work based on the\n" - "Program), you indicate your acceptance of this License to do so, and\n" - "all its terms and conditions for copying, distributing or modifying\n" - "the Program or works based on it.\n" - "\n" - " 6. Each time you redistribute the Program (or any work based on the\n" - "Program), the recipient automatically receives a license from the\n" - "original licensor to copy, distribute or modify the Program subject to\n" - "these terms and conditions. You may not impose any further\n" - "restrictions on the recipients' exercise of the rights granted herein.\n" - "You are not responsible for enforcing compliance by third parties to\n" - "this License.\n" - "\n" - " 7. If, as a consequence of a court judgment or allegation of patent\n" - "infringement or for any other reason (not limited to patent issues),\n" - "conditions are imposed on you (whether by court order, agreement or\n" - "otherwise) that contradict the conditions of this License, they do not\n" - "excuse you from the conditions of this License. If you cannot\n" - "distribute so as to satisfy simultaneously your obligations under this\n" - "License and any other pertinent obligations, then as a consequence you\n" - "may not distribute the Program at all. For example, if a patent\n" - "license would not permit royalty-free redistribution of the Program by\n" - "all those who receive copies directly or indirectly through you, then\n" - "the only way you could satisfy both it and this License would be to\n" - "refrain entirely from distribution of the Program.\n" - "\n" - "If any portion of this section is held invalid or unenforceable under\n" - "any particular circumstance, the balance of the section is intended to\n" - "apply and the section as a whole is intended to apply in other\n" - "circumstances.\n" - "\n" - "It is not the purpose of this section to induce you to infringe any\n" - "patents or other property right claims or to contest validity of any\n" - "such claims; this section has the sole purpose of protecting the\n" - "integrity of the free software distribution system, which is\n" - "implemented by public license practices. Many people have made\n" - "generous contributions to the wide range of software distributed\n" - "through that system in reliance on consistent application of that\n" - "system; it is up to the author/donor to decide if he or she is willing\n" - "to distribute software through any other system and a licensee cannot\n" - "impose that choice.\n" - "\n" - "This section is intended to make thoroughly clear what is believed to\n" - "be a consequence of the rest of this License.\n" - "\n" - " 8. If the distribution and/or use of the Program is restricted in\n" - "certain countries either by patents or by copyrighted interfaces, the\n" - "original copyright holder who places the Program under this License\n" - "may add an explicit geographical distribution limitation excluding\n" - "those countries, so that distribution is permitted only in or among\n" - "countries not thus excluded. In such case, this License incorporates\n" - "the limitation as if written in the body of this License.\n" - "\n" - " 9. The Free Software Foundation may publish revised and/or new versions\n" - "of the General Public License from time to time. Such new versions will\n" - "be similar in spirit to the present version, but may differ in detail to\n" - "address new problems or concerns.\n" - "\n" - "Each version is given a distinguishing version number. If the Program\n" - "specifies a version number of this License which applies to it and \"any\n" - "later version\", you have the option of following the terms and conditions\n" - "either of that version or of any later version published by the Free\n" - "Software Foundation. If the Program does not specify a version number of\n" - "this License, you may choose any version ever published by the Free Software\n" - "Foundation.\n" - "\n" - " 10. If you wish to incorporate parts of the Program into other free\n" - "programs whose distribution conditions are different, write to the author\n" - "to ask for permission. For software which is copyrighted by the Free\n" - "Software Foundation, write to the Free Software Foundation; we sometimes\n" - "make exceptions for this. Our decision will be guided by the two goals\n" - "of preserving the free status of all derivatives of our free software and\n" - "of promoting the sharing and reuse of software generally.\n" - "\n" - " NO WARRANTY\n" - "\n" - " 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n" - "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN\n" - "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n" - "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n" - "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" - "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\n" - "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE\n" - "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n" - "REPAIR OR CORRECTION.\n" - "\n" - " 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n" - "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n" - "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n" - "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n" - "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n" - "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n" - "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n" - "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n" - "POSSIBILITY OF SUCH DAMAGES.\n" - "\n" - " END OF TERMS AND CONDITIONS\n" - "\n" - " How to Apply These Terms to Your New Programs\n" - "\n" - " If you develop a new program, and you want it to be of the greatest\n" - "possible use to the public, the best way to achieve this is to make it\n" - "free software which everyone can redistribute and change under these terms.\n" - "\n" - " To do so, attach the following notices to the program. It is safest\n" - "to attach them to the start of each source file to most effectively\n" - "convey the exclusion of warranty; and each file should have at least\n" - "the \"copyright\" line and a pointer to where the full notice is found.\n" - "\n" - " <one line to give the program's name and a brief idea of what it does.>\n" - " Copyright (C) <year> <name of author>\n" - "\n" - " This program is free software; you can redistribute it and/or modify\n" - " it under the terms of the GNU General Public License as published by\n" - " the Free Software Foundation; either version 2 of the License, or\n" - " (at your option) any later version.\n" - "\n" - " This program is distributed in the hope that it will be useful,\n" - " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" - " GNU General Public License for more details.\n" - "\n" - " You should have received a copy of the GNU General Public License\n" - " along with this program; if not, write to the Free Software\n" - " Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" - "\n" - "\n" - "Also add information on how to contact you by electronic and paper mail.\n" - "\n" - "If the program is interactive, make it output a short notice like this\n" - "when it starts in an interactive mode:\n" - "\n" - " Gnomovision version 69, Copyright (C) year name of author\n" - " Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n" - " This is free software, and you are welcome to redistribute it\n" - " under certain conditions; type `show c' for details.\n" - "\n" - "The hypothetical commands `show w' and `show c' should show the appropriate\n" - "parts of the General Public License. Of course, the commands you use may\n" - "be called something other than `show w' and `show c'; they could even be\n" - "mouse-clicks or menu items--whatever suits your program.\n" - "\n" - "You should also get your employer (if you work as a programmer) or your\n" - "school, if any, to sign a \"copyright disclaimer\" for the program, if\n" - "necessary. Here is a sample; alter the names:\n" - "\n" - " Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n" - " `Gnomovision' (which makes passes at compilers) written by James Hacker.\n" - "\n" - " <signature of Ty Coon>, 1 April 1989\n" - " Ty Coon, President of Vice\n" - "\n" - "This General Public License does not permit incorporating your program into\n" - "proprietary programs. If your program is a subroutine library, you may\n" - "consider it more useful to permit linking proprietary applications with the\n" - "library. If this is what you want to do, use the GNU Library General\n" - "Public License instead of this License."; +static const char *licenseDBus = "D-Bus is licensed to you under your choice of the Academic Free\n" + "License version 2.1, or the GNU General Public License version 2\n" + "(or, at your option any later version).\n" + "\n" + "Both licenses are included here. Some of the standalone binaries are\n" + "under the GPL only; in particular, but not limited to,\n" + "tools/dbus-cleanup-sockets.c and test/decode-gcov.c. Each source code\n" + "file is marked with the proper copyright information - if you find a\n" + "file that isn't marked please bring it to our attention.\n" + "\n" + "The Academic Free License\n" + "v. 2.1\n" + "\n" + "This Academic Free License (the \"License\") applies to any original work of " + "authorship (the \"Original Work\") whose owner (the \"Licensor\") has placed the " + "following notice immediately following the copyright notice for the Original Work:\n" + "\n" + "Licensed under the Academic Free License version 2.1\n" + "\n" + "1) Grant of Copyright License. Licensor hereby grants You a\n" + "world-wide, royalty-free, non-exclusive, perpetual, sublicenseable\n" + "license to do the following:\n" + "\n" + "a) to reproduce the Original Work in copies;\n" + "\n" + "b) to prepare derivative works (\"Derivative Works\") based upon the Original Work;\n" + "\n" + "c) to distribute copies of the Original Work and Derivative Works to the public;\n" + "\n" + "d) to perform the Original Work publicly; and\n" + "\n" + "e) to display the Original Work publicly.\n" + "\n" + "2) Grant of Patent License. Licensor hereby grants You a world-wide,\n" + "royalty-free, non-exclusive, perpetual, sublicenseable license, under\n" + "patent claims owned or controlled by the Licensor that are embodied in\n" + "the Original Work as furnished by the Licensor, to make, use, sell and\n" + "offer for sale the Original Work and Derivative Works.\n" + "\n" + "3) Grant of Source Code License. The term \"Source Code\" means the\n" + "preferred form of the Original Work for making modifications to it and\n" + "all available documentation describing how to modify the Original\n" + "Work. Licensor hereby agrees to provide a machine-readable copy of the\n" + "Source Code of the Original Work along with each copy of the Original\n" + "Work that Licensor distributes. Licensor reserves the right to satisfy\n" + "this obligation by placing a machine-readable copy of the Source Code\n" + "in an information repository reasonably calculated to permit\n" + "inexpensive and convenient access by You for as long as Licensor\n" + "continues to distribute the Original Work, and by publishing the\n" + "address of that information repository in a notice immediately\n" + "following the copyright notice that applies to the Original Work.\n" + "\n" + "4) Exclusions From License Grant. Neither the names of Licensor, nor\n" + "the names of any contributors to the Original Work, nor any of their\n" + "trademarks or service marks, may be used to endorse or promote\n" + "products derived from this Original Work without express prior written\n" + "permission of the Licensor. Nothing in this License shall be deemed to\n" + "grant any rights to trademarks, copyrights, patents, trade secrets or\n" + "any other intellectual property of Licensor except as expressly stated\n" + "herein. No patent license is granted to make, use, sell or offer to\n" + "sell embodiments of any patent claims other than the licensed claims\n" + "defined in Section 2. No right is granted to the trademarks of\n" + "Licensor even if such marks are included in the Original Work. Nothing\n" + "in this License shall be interpreted to prohibit Licensor from\n" + "licensing under different terms from this License any Original Work\n" + "that Licensor otherwise would have a right to license.\n" + "\n" + "5) This section intentionally omitted.\n" + "\n" + "6) Attribution Rights. You must retain, in the Source Code of any\n" + "Derivative Works that You create, all copyright, patent or trademark\n" + "notices from the Source Code of the Original Work, as well as any\n" + "notices of licensing and any descriptive text identified therein as an\n" + "\"Attribution Notice.\" You must cause the Source Code for any\n" + "Derivative Works that You create to carry a prominent Attribution\n" + "Notice reasonably calculated to inform recipients that You have\n" + "modified the Original Work.\n" + "\n" + "7) Warranty of Provenance and Disclaimer of Warranty. Licensor\n" + "warrants that the copyright in and to the Original Work and the patent\n" + "rights granted herein by Licensor are owned by the Licensor or are\n" + "sublicensed to You under the terms of this License with the permission\n" + "of the contributor(s) of those copyrights and patent rights. Except as\n" + "expressly stated in the immediately proceeding sentence, the Original\n" + "Work is provided under this License on an \"AS IS\" BASIS and WITHOUT\n" + "WARRANTY, either express or implied, including, without limitation,\n" + "the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A\n" + "PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL\n" + "WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential\n" + "part of this License. No license to Original Work is granted hereunder\n" + "except under this disclaimer.\n" + "\n" + "8) Limitation of Liability. Under no circumstances and under no legal\n" + "theory, whether in tort (including negligence), contract, or\n" + "otherwise, shall the Licensor be liable to any person for any direct,\n" + "indirect, special, incidental, or consequential damages of any\n" + "character arising as a result of this License or the use of the\n" + "Original Work including, without limitation, damages for loss of\n" + "goodwill, work stoppage, computer failure or malfunction, or any and\n" + "all other commercial damages or losses. This limitation of liability\n" + "shall not apply to liability for death or personal injury resulting\n" + "from Licensor's negligence to the extent applicable law prohibits such\n" + "limitation. Some jurisdictions do not allow the exclusion or\n" + "limitation of incidental or consequential damages, so this exclusion\n" + "and limitation may not apply to You.\n" + "\n" + "9) Acceptance and Termination. If You distribute copies of the\n" + "Original Work or a Derivative Work, You must make a reasonable effort\n" + "under the circumstances to obtain the express assent of recipients to\n" + "the terms of this License. Nothing else but this License (or another\n" + "written agreement between Licensor and You) grants You permission to\n" + "create Derivative Works based upon the Original Work or to exercise\n" + "any of the rights granted in Section 1 herein, and any attempt to do\n" + "so except under the terms of this License (or another written\n" + "agreement between Licensor and You) is expressly prohibited by\n" + "U.S. copyright law, the equivalent laws of other countries, and by\n" + "international treaty. Therefore, by exercising any of the rights\n" + "granted to You in Section 1 herein, You indicate Your acceptance of\n" + "this License and all of its terms and conditions.\n" + "\n" + "10) Termination for Patent Action. This License shall terminate\n" + "automatically and You may no longer exercise any of the rights granted\n" + "to You by this License as of the date You commence an action,\n" + "including a cross-claim or counterclaim, against Licensor or any\n" + "licensee alleging that the Original Work infringes a patent. This\n" + "termination provision shall not apply for an action alleging patent\n" + "infringement by combinations of the Original Work with other software\n" + "or hardware.\n" + "\n" + "11) Jurisdiction, Venue and Governing Law. Any action or suit relating\n" + "to this License may be brought only in the courts of a jurisdiction\n" + "wherein the Licensor resides or in which Licensor conducts its primary\n" + "business, and under the laws of that jurisdiction excluding its\n" + "conflict-of-law provisions. The application of the United Nations\n" + "Convention on Contracts for the International Sale of Goods is\n" + "expressly excluded. Any use of the Original Work outside the scope of\n" + "this License or after its termination shall be subject to the\n" + "requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101\n" + "et seq., the equivalent laws of other countries, and international\n" + "treaty. This section shall survive the termination of this License.\n" + "\n" + "12) Attorneys Fees. In any action to enforce the terms of this License\n" + "or seeking damages relating thereto, the prevailing party shall be\n" + "entitled to recover its costs and expenses, including, without\n" + "limitation, reasonable attorneys' fees and costs incurred in\n" + "connection with such action, including any appeal of such action. This\n" + "section shall survive the termination of this License.\n" + "\n" + "13) Miscellaneous. This License represents the complete agreement\n" + "concerning the subject matter hereof. If any provision of this License\n" + "is held to be unenforceable, such provision shall be reformed only to\n" + "the extent necessary to make it enforceable.\n" + "\n" + "14) Definition of \"You\" in This License. \"You\" throughout this\n" + "License, whether in upper or lower case, means an individual or a\n" + "legal entity exercising rights under, and complying with all of the\n" + "terms of, this License. For legal entities, \"You\" includes any entity\n" + "that controls, is controlled by, or is under common control with\n" + "you. For purposes of this definition, \"control\" means (i) the power,\n" + "direct or indirect, to cause the direction or management of such\n" + "entity, whether by contract or otherwise, or (ii) ownership of fifty\n" + "percent (50%) or more of the outstanding shares, or (iii) beneficial\n" + "ownership of such entity.\n" + "\n" + "15) Right to Use. You may use the Original Work in all ways not\n" + "otherwise restricted or conditioned by this License or by law, and\n" + "Licensor promises not to interfere with or be responsible for such\n" + "uses by You.\n" + "\n" + "This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights\n" + "reserved. Permission is hereby granted to copy and distribute this\n" + "license without modification. This license may not be modified without\n" + "the express written permission of its copyright owner.\n" + "\n" + "\n" + "-- \n" + "END OF ACADEMIC FREE LICENSE. The following is intended to describe the essential \n" + "differences between the Academic Free License (AFL) version 1.0 and other \n" + "open source licenses:\n" + "\n" + "The Academic Free License is similar to the BSD, MIT, UoI/NCSA and Apache \n" + "licenses in many respects but it is intended to solve a few problems with \n" + "those licenses.\n" + " \n" + "* The AFL is written so as to make it clear what software is being \n" + "licensed (by the inclusion of a statement following the copyright notice \n" + "in the software). This way, the license functions better than a template \n" + "license. The BSD, MIT and UoI/NCSA licenses apply to unidentified software.\n" + " \n" + "* The AFL contains a complete copyright grant to the software. The BSD \n" + "and Apache licenses are vague and incomplete in that respect.\n" + " \n" + "* The AFL contains a complete patent grant to the software. The BSD, MIT, \n" + "UoI/NCSA and Apache licenses rely on an implied patent license and contain \n" + "no explicit patent grant.\n" + " \n" + "* The AFL makes it clear that no trademark rights are granted to the \n" + "licensor's trademarks. The Apache license contains such a provision, but the \n" + "BSD, MIT and UoI/NCSA licenses do not.\n" + " \n" + "* The AFL includes the warranty by the licensor that it either owns the \n" + "copyright or that it is distributing the software under a license. None of \n" + "the other licenses contain that warranty. All other warranties are disclaimed, \n" + "as is the case for the other licenses.\n" + "\n" + "* The AFL is itself copyrighted (with the right granted to copy and distribute \n" + "without modification). This ensures that the owner of the copyright to the \n" + "license will control changes. The Apache license contains a copyright notice, \n" + "but the BSD, MIT and UoI/NCSA licenses do not. \n" + "--\n" + "START OF GNU GENERAL PUBLIC LICENSE\n" + "--\n" + "\n" + " GNU GENERAL PUBLIC LICENSE\n" + " Version 2, June 1991\n" + "\n" + " Copyright (C) 1989, 1991 Free Software Foundation, Inc.\n" + " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" + "\n" + " Everyone is permitted to copy and distribute verbatim copies\n" + " of this license document, but changing it is not allowed.\n" + "\n" + " Preamble\n" + "\n" + " The licenses for most software are designed to take away your\n" + "freedom to share and change it. By contrast, the GNU General Public\n" + "License is intended to guarantee your freedom to share and change free\n" + "software--to make sure the software is free for all its users. This\n" + "General Public License applies to most of the Free Software\n" + "Foundation's software and to any other program whose authors commit to\n" + "using it. (Some other Free Software Foundation software is covered by\n" + "the GNU Library General Public License instead.) You can apply it to\n" + "your programs, too.\n" + "\n" + " When we speak of free software, we are referring to freedom, not\n" + "price. Our General Public Licenses are designed to make sure that you\n" + "have the freedom to distribute copies of free software (and charge for\n" + "this service if you wish), that you receive source code or can get it\n" + "if you want it, that you can change the software or use pieces of it\n" + "in new free programs; and that you know you can do these things.\n" + "\n" + " To protect your rights, we need to make restrictions that forbid\n" + "anyone to deny you these rights or to ask you to surrender the rights.\n" + "These restrictions translate to certain responsibilities for you if you\n" + "distribute copies of the software, or if you modify it.\n" + "\n" + " For example, if you distribute copies of such a program, whether\n" + "gratis or for a fee, you must give the recipients all the rights that\n" + "you have. You must make sure that they, too, receive or can get the\n" + "source code. And you must show them these terms so they know their\n" + "rights.\n" + "\n" + " We protect your rights with two steps: (1) copyright the software, and\n" + "(2) offer you this license which gives you legal permission to copy,\n" + "distribute and/or modify the software.\n" + "\n" + " Also, for each author's protection and ours, we want to make certain\n" + "that everyone understands that there is no warranty for this free\n" + "software. If the software is modified by someone else and passed on, we\n" + "want its recipients to know that what they have is not the original, so\n" + "that any problems introduced by others will not reflect on the original\n" + "authors' reputations.\n" + "\n" + " Finally, any free program is threatened constantly by software\n" + "patents. We wish to avoid the danger that redistributors of a free\n" + "program will individually obtain patent licenses, in effect making the\n" + "program proprietary. To prevent this, we have made it clear that any\n" + "patent must be licensed for everyone's free use or not licensed at all.\n" + "\n" + " The precise terms and conditions for copying, distribution and\n" + "modification follow.\n" + "\n" + " GNU GENERAL PUBLIC LICENSE\n" + " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" + "\n" + " 0. This License applies to any program or other work which contains\n" + "a notice placed by the copyright holder saying it may be distributed\n" + "under the terms of this General Public License. The \"Program\", below,\n" + "refers to any such program or work, and a \"work based on the Program\"\n" + "means either the Program or any derivative work under copyright law:\n" + "that is to say, a work containing the Program or a portion of it,\n" + "either verbatim or with modifications and/or translated into another\n" + "language. (Hereinafter, translation is included without limitation in\n" + "the term \"modification\".) Each licensee is addressed as \"you\".\n" + "\n" + "Activities other than copying, distribution and modification are not\n" + "covered by this License; they are outside its scope. The act of\n" + "running the Program is not restricted, and the output from the Program\n" + "is covered only if its contents constitute a work based on the\n" + "Program (independent of having been made by running the Program).\n" + "Whether that is true depends on what the Program does.\n" + "\n" + " 1. You may copy and distribute verbatim copies of the Program's\n" + "source code as you receive it, in any medium, provided that you\n" + "conspicuously and appropriately publish on each copy an appropriate\n" + "copyright notice and disclaimer of warranty; keep intact all the\n" + "notices that refer to this License and to the absence of any warranty;\n" + "and give any other recipients of the Program a copy of this License\n" + "along with the Program.\n" + "\n" + "You may charge a fee for the physical act of transferring a copy, and\n" + "you may at your option offer warranty protection in exchange for a fee.\n" + "\n" + " 2. You may modify your copy or copies of the Program or any portion\n" + "of it, thus forming a work based on the Program, and copy and\n" + "distribute such modifications or work under the terms of Section 1\n" + "above, provided that you also meet all of these conditions:\n" + "\n" + " a) You must cause the modified files to carry prominent notices\n" + " stating that you changed the files and the date of any change.\n" + "\n" + " b) You must cause any work that you distribute or publish, that in\n" + " whole or in part contains or is derived from the Program or any\n" + " part thereof, to be licensed as a whole at no charge to all third\n" + " parties under the terms of this License.\n" + "\n" + " c) If the modified program normally reads commands interactively\n" + " when run, you must cause it, when started running for such\n" + " interactive use in the most ordinary way, to print or display an\n" + " announcement including an appropriate copyright notice and a\n" + " notice that there is no warranty (or else, saying that you provide\n" + " a warranty) and that users may redistribute the program under\n" + " these conditions, and telling the user how to view a copy of this\n" + " License. (Exception: if the Program itself is interactive but\n" + " does not normally print such an announcement, your work based on\n" + " the Program is not required to print an announcement.)\n" + "\n" + "These requirements apply to the modified work as a whole. If\n" + "identifiable sections of that work are not derived from the Program,\n" + "and can be reasonably considered independent and separate works in\n" + "themselves, then this License, and its terms, do not apply to those\n" + "sections when you distribute them as separate works. But when you\n" + "distribute the same sections as part of a whole which is a work based\n" + "on the Program, the distribution of the whole must be on the terms of\n" + "this License, whose permissions for other licensees extend to the\n" + "entire whole, and thus to each and every part regardless of who wrote it.\n" + "\n" + "Thus, it is not the intent of this section to claim rights or contest\n" + "your rights to work written entirely by you; rather, the intent is to\n" + "exercise the right to control the distribution of derivative or\n" + "collective works based on the Program.\n" + "\n" + "In addition, mere aggregation of another work not based on the Program\n" + "with the Program (or with a work based on the Program) on a volume of\n" + "a storage or distribution medium does not bring the other work under\n" + "the scope of this License.\n" + "\n" + " 3. You may copy and distribute the Program (or a work based on it,\n" + "under Section 2) in object code or executable form under the terms of\n" + "Sections 1 and 2 above provided that you also do one of the following:\n" + "\n" + " a) Accompany it with the complete corresponding machine-readable\n" + " source code, which must be distributed under the terms of Sections\n" + " 1 and 2 above on a medium customarily used for software interchange; or,\n" + "\n" + " b) Accompany it with a written offer, valid for at least three\n" + " years, to give any third party, for a charge no more than your\n" + " cost of physically performing source distribution, a complete\n" + " machine-readable copy of the corresponding source code, to be\n" + " distributed under the terms of Sections 1 and 2 above on a medium\n" + " customarily used for software interchange; or,\n" + "\n" + " c) Accompany it with the information you received as to the offer\n" + " to distribute corresponding source code. (This alternative is\n" + " allowed only for noncommercial distribution and only if you\n" + " received the program in object code or executable form with such\n" + " an offer, in accord with Subsection b above.)\n" + "\n" + "The source code for a work means the preferred form of the work for\n" + "making modifications to it. For an executable work, complete source\n" + "code means all the source code for all modules it contains, plus any\n" + "associated interface definition files, plus the scripts used to\n" + "control compilation and installation of the executable. However, as a\n" + "special exception, the source code distributed need not include\n" + "anything that is normally distributed (in either source or binary\n" + "form) with the major components (compiler, kernel, and so on) of the\n" + "operating system on which the executable runs, unless that component\n" + "itself accompanies the executable.\n" + "\n" + "If distribution of executable or object code is made by offering\n" + "access to copy from a designated place, then offering equivalent\n" + "access to copy the source code from the same place counts as\n" + "distribution of the source code, even though third parties are not\n" + "compelled to copy the source along with the object code.\n" + "\n" + " 4. You may not copy, modify, sublicense, or distribute the Program\n" + "except as expressly provided under this License. Any attempt\n" + "otherwise to copy, modify, sublicense or distribute the Program is\n" + "void, and will automatically terminate your rights under this License.\n" + "However, parties who have received copies, or rights, from you under\n" + "this License will not have their licenses terminated so long as such\n" + "parties remain in full compliance.\n" + "\n" + " 5. You are not required to accept this License, since you have not\n" + "signed it. However, nothing else grants you permission to modify or\n" + "distribute the Program or its derivative works. These actions are\n" + "prohibited by law if you do not accept this License. Therefore, by\n" + "modifying or distributing the Program (or any work based on the\n" + "Program), you indicate your acceptance of this License to do so, and\n" + "all its terms and conditions for copying, distributing or modifying\n" + "the Program or works based on it.\n" + "\n" + " 6. Each time you redistribute the Program (or any work based on the\n" + "Program), the recipient automatically receives a license from the\n" + "original licensor to copy, distribute or modify the Program subject to\n" + "these terms and conditions. You may not impose any further\n" + "restrictions on the recipients' exercise of the rights granted herein.\n" + "You are not responsible for enforcing compliance by third parties to\n" + "this License.\n" + "\n" + " 7. If, as a consequence of a court judgment or allegation of patent\n" + "infringement or for any other reason (not limited to patent issues),\n" + "conditions are imposed on you (whether by court order, agreement or\n" + "otherwise) that contradict the conditions of this License, they do not\n" + "excuse you from the conditions of this License. If you cannot\n" + "distribute so as to satisfy simultaneously your obligations under this\n" + "License and any other pertinent obligations, then as a consequence you\n" + "may not distribute the Program at all. For example, if a patent\n" + "license would not permit royalty-free redistribution of the Program by\n" + "all those who receive copies directly or indirectly through you, then\n" + "the only way you could satisfy both it and this License would be to\n" + "refrain entirely from distribution of the Program.\n" + "\n" + "If any portion of this section is held invalid or unenforceable under\n" + "any particular circumstance, the balance of the section is intended to\n" + "apply and the section as a whole is intended to apply in other\n" + "circumstances.\n" + "\n" + "It is not the purpose of this section to induce you to infringe any\n" + "patents or other property right claims or to contest validity of any\n" + "such claims; this section has the sole purpose of protecting the\n" + "integrity of the free software distribution system, which is\n" + "implemented by public license practices. Many people have made\n" + "generous contributions to the wide range of software distributed\n" + "through that system in reliance on consistent application of that\n" + "system; it is up to the author/donor to decide if he or she is willing\n" + "to distribute software through any other system and a licensee cannot\n" + "impose that choice.\n" + "\n" + "This section is intended to make thoroughly clear what is believed to\n" + "be a consequence of the rest of this License.\n" + "\n" + " 8. If the distribution and/or use of the Program is restricted in\n" + "certain countries either by patents or by copyrighted interfaces, the\n" + "original copyright holder who places the Program under this License\n" + "may add an explicit geographical distribution limitation excluding\n" + "those countries, so that distribution is permitted only in or among\n" + "countries not thus excluded. In such case, this License incorporates\n" + "the limitation as if written in the body of this License.\n" + "\n" + " 9. The Free Software Foundation may publish revised and/or new versions\n" + "of the General Public License from time to time. Such new versions will\n" + "be similar in spirit to the present version, but may differ in detail to\n" + "address new problems or concerns.\n" + "\n" + "Each version is given a distinguishing version number. If the Program\n" + "specifies a version number of this License which applies to it and \"any\n" + "later version\", you have the option of following the terms and conditions\n" + "either of that version or of any later version published by the Free\n" + "Software Foundation. If the Program does not specify a version number of\n" + "this License, you may choose any version ever published by the Free Software\n" + "Foundation.\n" + "\n" + " 10. If you wish to incorporate parts of the Program into other free\n" + "programs whose distribution conditions are different, write to the author\n" + "to ask for permission. For software which is copyrighted by the Free\n" + "Software Foundation, write to the Free Software Foundation; we sometimes\n" + "make exceptions for this. Our decision will be guided by the two goals\n" + "of preserving the free status of all derivatives of our free software and\n" + "of promoting the sharing and reuse of software generally.\n" + "\n" + " NO WARRANTY\n" + "\n" + " 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n" + "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN\n" + "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n" + "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n" + "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" + "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\n" + "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE\n" + "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n" + "REPAIR OR CORRECTION.\n" + "\n" + " 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n" + "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n" + "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n" + "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n" + "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n" + "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n" + "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n" + "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n" + "POSSIBILITY OF SUCH DAMAGES.\n" + "\n" + " END OF TERMS AND CONDITIONS\n" + "\n" + " How to Apply These Terms to Your New Programs\n" + "\n" + " If you develop a new program, and you want it to be of the greatest\n" + "possible use to the public, the best way to achieve this is to make it\n" + "free software which everyone can redistribute and change under these terms.\n" + "\n" + " To do so, attach the following notices to the program. It is safest\n" + "to attach them to the start of each source file to most effectively\n" + "convey the exclusion of warranty; and each file should have at least\n" + "the \"copyright\" line and a pointer to where the full notice is found.\n" + "\n" + " <one line to give the program's name and a brief idea of what it does.>\n" + " Copyright (C) <year> <name of author>\n" + "\n" + " This program is free software; you can redistribute it and/or modify\n" + " it under the terms of the GNU General Public License as published by\n" + " the Free Software Foundation; either version 2 of the License, or\n" + " (at your option) any later version.\n" + "\n" + " This program is distributed in the hope that it will be useful,\n" + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + " GNU General Public License for more details.\n" + "\n" + " You should have received a copy of the GNU General Public License\n" + " along with this program; if not, write to the Free Software\n" + " Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" + "\n" + "\n" + "Also add information on how to contact you by electronic and paper mail.\n" + "\n" + "If the program is interactive, make it output a short notice like this\n" + "when it starts in an interactive mode:\n" + "\n" + " Gnomovision version 69, Copyright (C) year name of author\n" + " Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n" + " This is free software, and you are welcome to redistribute it\n" + " under certain conditions; type `show c' for details.\n" + "\n" + "The hypothetical commands `show w' and `show c' should show the appropriate\n" + "parts of the General Public License. Of course, the commands you use may\n" + "be called something other than `show w' and `show c'; they could even be\n" + "mouse-clicks or menu items--whatever suits your program.\n" + "\n" + "You should also get your employer (if you work as a programmer) or your\n" + "school, if any, to sign a \"copyright disclaimer\" for the program, if\n" + "necessary. Here is a sample; alter the names:\n" + "\n" + " Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n" + " `Gnomovision' (which makes passes at compilers) written by James Hacker.\n" + "\n" + " <signature of Ty Coon>, 1 April 1989\n" + " Ty Coon, President of Vice\n" + "\n" + "This General Public License does not permit incorporating your program into\n" + "proprietary programs. If your program is a subroutine library, you may\n" + "consider it more useful to permit linking proprietary applications with the\n" + "library. If this is what you want to do, use the GNU Library General\n" + "Public License instead of this License."; #endif #ifdef USE_BUILDENV -static const char *licenseAppImageRuntime = +static const char *licenseAppImageRuntime = "Copyright (c) 2004-17 Simon Peter\n" "Portions Copyright (c) 2007 Alexander Larsson\n" "\n" @@ -3817,43 +3787,42 @@ static const char *licenseAppImageRuntime = #ifdef USE_BUILDENV -static const char *licenseSquashfuse = - "The squashfuse distribution as a whole is copyright Dave\n" - "Vasilevsky and is subject to the copyright notice reproduced at\n" - "the bottom of this file.\n" - "\n" - "The file squashfs_fs.h is copyright Phillip Lougher and, with his permission,\n" - "subject to the same license.\n" - "\n" - "\n" - "Copyright (c) 2012 Dave Vasilevsky <dave@vasilevsky.ca>\n" - " Phillip Lougher <phillip@squashfs.org.uk>\n" - "All rights reserved.\n" - "\n" - "Redistribution and use in source and binary forms, with or without\n" - "modification, are permitted provided that the following conditions\n" - "are met:\n" - "1. Redistributions of source code must retain the above copyright\n" - " notice, this list of conditions and the following disclaimer.\n" - "2. Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in the\n" - " documentation and/or other materials provided with the distribution.\n" - "\n" - "THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR\n" - "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" - "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" - "IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,\n" - "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" - "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" - "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" - "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" - "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" - "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; +static const char *licenseSquashfuse = "The squashfuse distribution as a whole is copyright Dave\n" + "Vasilevsky and is subject to the copyright notice reproduced at\n" + "the bottom of this file.\n" + "\n" + "The file squashfs_fs.h is copyright Phillip Lougher and, with his permission,\n" + "subject to the same license.\n" + "\n" + "\n" + "Copyright (c) 2012 Dave Vasilevsky <dave@vasilevsky.ca>\n" + " Phillip Lougher <phillip@squashfs.org.uk>\n" + "All rights reserved.\n" + "\n" + "Redistribution and use in source and binary forms, with or without\n" + "modification, are permitted provided that the following conditions\n" + "are met:\n" + "1. Redistributions of source code must retain the above copyright\n" + " notice, this list of conditions and the following disclaimer.\n" + "2. Redistributions in binary form must reproduce the above copyright\n" + " notice, this list of conditions and the following disclaimer in the\n" + " documentation and/or other materials provided with the distribution.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR\n" + "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" + "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" + "IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,\n" + "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" + "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" + "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" + "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" + "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" + "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; #endif #ifdef USE_BUILDENV -static const char *licenseLibfuse = +static const char *licenseLibfuse = "FUSE: Filesystem in Userspace\n" "Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>\n" "\n" @@ -4365,1430 +4334,1426 @@ static const char *licenseLibfuse = #ifdef USE_BUILDENV -static const char *licenseGlib = - " GNU LIBRARY GENERAL PUBLIC LICENSE\n" - " Version 2, June 1991\n" - "\n" - " Copyright (C) 1991 Free Software Foundation, Inc.\n" - " 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" - " Everyone is permitted to copy and distribute verbatim copies\n" - " of this license document, but changing it is not allowed.\n" - "\n" - "[This is the first released version of the library GPL. It is\n" - " numbered 2 because it goes with version 2 of the ordinary GPL.]\n" - "\n" - " Preamble\n" - "\n" - " The licenses for most software are designed to take away your\n" - "freedom to share and change it. By contrast, the GNU General Public\n" - "Licenses are intended to guarantee your freedom to share and change\n" - "free software--to make sure the software is free for all its users.\n" - "\n" - " This license, the Library General Public License, applies to some\n" - "specially designated Free Software Foundation software, and to any\n" - "other libraries whose authors decide to use it. You can use it for\n" - "your libraries, too.\n" - "\n" - " When we speak of free software, we are referring to freedom, not\n" - "price. Our General Public Licenses are designed to make sure that you\n" - "have the freedom to distribute copies of free software (and charge for\n" - "this service if you wish), that you receive source code or can get it\n" - "if you want it, that you can change the software or use pieces of it\n" - "in new free programs; and that you know you can do these things.\n" - "\n" - " To protect your rights, we need to make restrictions that forbid\n" - "anyone to deny you these rights or to ask you to surrender the rights.\n" - "These restrictions translate to certain responsibilities for you if\n" - "you distribute copies of the library, or if you modify it.\n" - "\n" - " For example, if you distribute copies of the library, whether gratis\n" - "or for a fee, you must give the recipients all the rights that we gave\n" - "you. You must make sure that they, too, receive or can get the source\n" - "code. If you link a program with the library, you must provide\n" - "complete object files to the recipients so that they can relink them\n" - "with the library, after making changes to the library and recompiling\n" - "it. And you must show them these terms so they know their rights.\n" - "\n" - " Our method of protecting your rights has two steps: (1) copyright\n" - "the library, and (2) offer you this license which gives you legal\n" - "permission to copy, distribute and/or modify the library.\n" - "\n" - " Also, for each distributor's protection, we want to make certain\n" - "that everyone understands that there is no warranty for this free\n" - "library. If the library is modified by someone else and passed on, we\n" - "want its recipients to know that what they have is not the original\n" - "version, so that any problems introduced by others will not reflect on\n" - "the original authors' reputations.\n" - "\n" - " Finally, any free program is threatened constantly by software\n" - "patents. We wish to avoid the danger that companies distributing free\n" - "software will individually obtain patent licenses, thus in effect\n" - "transforming the program into proprietary software. To prevent this,\n" - "we have made it clear that any patent must be licensed for everyone's\n" - "free use or not licensed at all.\n" - "\n" - " Most GNU software, including some libraries, is covered by the ordinary\n" - "GNU General Public License, which was designed for utility programs. This\n" - "license, the GNU Library General Public License, applies to certain\n" - "designated libraries. This license is quite different from the ordinary\n" - "one; be sure to read it in full, and don't assume that anything in it is\n" - "the same as in the ordinary license.\n" - "\n" - " The reason we have a separate public license for some libraries is that\n" - "they blur the distinction we usually make between modifying or adding to a\n" - "program and simply using it. Linking a program with a library, without\n" - "changing the library, is in some sense simply using the library, and is\n" - "analogous to running a utility program or application program. However, in\n" - "a textual and legal sense, the linked executable is a combined work, a\n" - "derivative of the original library, and the ordinary General Public License\n" - "treats it as such.\n" - "\n" - " Because of this blurred distinction, using the ordinary General\n" - "Public License for libraries did not effectively promote software\n" - "sharing, because most developers did not use the libraries. We\n" - "concluded that weaker conditions might promote sharing better.\n" - "\n" - " However, unrestricted linking of non-free programs would deprive the\n" - "users of those programs of all benefit from the free status of the\n" - "libraries themselves. This Library General Public License is intended to\n" - "permit developers of non-free programs to use free libraries, while\n" - "preserving your freedom as a user of such programs to change the free\n" - "libraries that are incorporated in them. (We have not seen how to achieve\n" - "this as regards changes in header files, but we have achieved it as regards\n" - "changes in the actual functions of the Library.) The hope is that this\n" - "will lead to faster development of free libraries.\n" - "\n" - " The precise terms and conditions for copying, distribution and\n" - "modification follow. Pay close attention to the difference between a\n" - "\"work based on the library\" and a \"work that uses the library\". The\n" - "former contains code derived from the library, while the latter only\n" - "works together with the library.\n" - "\n" - " Note that it is possible for a library to be covered by the ordinary\n" - "General Public License rather than by this special one.\n" - "\n" - " GNU LIBRARY GENERAL PUBLIC LICENSE\n" - " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" - "\n" - " 0. This License Agreement applies to any software library which\n" - "contains a notice placed by the copyright holder or other authorized\n" - "party saying it may be distributed under the terms of this Library\n" - "General Public License (also called \"this License\"). Each licensee is\n" - "addressed as \"you\".\n" - "\n" - " A \"library\" means a collection of software functions and/or data\n" - "prepared so as to be conveniently linked with application programs\n" - "(which use some of those functions and data) to form executables.\n" - "\n" - " The \"Library\", below, refers to any such software library or work\n" - "which has been distributed under these terms. A \"work based on the\n" - "Library\" means either the Library or any derivative work under\n" - "copyright law: that is to say, a work containing the Library or a\n" - "portion of it, either verbatim or with modifications and/or translated\n" - "straightforwardly into another language. (Hereinafter, translation is\n" - "included without limitation in the term \"modification\".)\n" - "\n" - " \"Source code\" for a work means the preferred form of the work for\n" - "making modifications to it. For a library, complete source code means\n" - "all the source code for all modules it contains, plus any associated\n" - "interface definition files, plus the scripts used to control compilation\n" - "and installation of the library.\n" - "\n" - " Activities other than copying, distribution and modification are not\n" - "covered by this License; they are outside its scope. The act of\n" - "running a program using the Library is not restricted, and output from\n" - "such a program is covered only if its contents constitute a work based\n" - "on the Library (independent of the use of the Library in a tool for\n" - "writing it). Whether that is true depends on what the Library does\n" - "and what the program that uses the Library does.\n" - " \n" - " 1. You may copy and distribute verbatim copies of the Library's\n" - "complete source code as you receive it, in any medium, provided that\n" - "you conspicuously and appropriately publish on each copy an\n" - "appropriate copyright notice and disclaimer of warranty; keep intact\n" - "all the notices that refer to this License and to the absence of any\n" - "warranty; and distribute a copy of this License along with the\n" - "Library.\n" - "\n" - " You may charge a fee for the physical act of transferring a copy,\n" - "and you may at your option offer warranty protection in exchange for a\n" - "fee.\n" - "\n" - " 2. You may modify your copy or copies of the Library or any portion\n" - "of it, thus forming a work based on the Library, and copy and\n" - "distribute such modifications or work under the terms of Section 1\n" - "above, provided that you also meet all of these conditions:\n" - "\n" - " a) The modified work must itself be a software library.\n" - "\n" - " b) You must cause the files modified to carry prominent notices\n" - " stating that you changed the files and the date of any change.\n" - "\n" - " c) You must cause the whole of the work to be licensed at no\n" - " charge to all third parties under the terms of this License.\n" - "\n" - " d) If a facility in the modified Library refers to a function or a\n" - " table of data to be supplied by an application program that uses\n" - " the facility, other than as an argument passed when the facility\n" - " is invoked, then you must make a good faith effort to ensure that,\n" - " in the event an application does not supply such function or\n" - " table, the facility still operates, and performs whatever part of\n" - " its purpose remains meaningful.\n" - "\n" - " (For example, a function in a library to compute square roots has\n" - " a purpose that is entirely well-defined independent of the\n" - " application. Therefore, Subsection 2d requires that any\n" - " application-supplied function or table used by this function must\n" - " be optional: if the application does not supply it, the square\n" - " root function must still compute square roots.)\n" - "\n" - "These requirements apply to the modified work as a whole. If\n" - "identifiable sections of that work are not derived from the Library,\n" - "and can be reasonably considered independent and separate works in\n" - "themselves, then this License, and its terms, do not apply to those\n" - "sections when you distribute them as separate works. But when you\n" - "distribute the same sections as part of a whole which is a work based\n" - "on the Library, the distribution of the whole must be on the terms of\n" - "this License, whose permissions for other licensees extend to the\n" - "entire whole, and thus to each and every part regardless of who wrote\n" - "it.\n" - "\n" - "Thus, it is not the intent of this section to claim rights or contest\n" - "your rights to work written entirely by you; rather, the intent is to\n" - "exercise the right to control the distribution of derivative or\n" - "collective works based on the Library.\n" - "\n" - "In addition, mere aggregation of another work not based on the Library\n" - "with the Library (or with a work based on the Library) on a volume of\n" - "a storage or distribution medium does not bring the other work under\n" - "the scope of this License.\n" - "\n" - " 3. You may opt to apply the terms of the ordinary GNU General Public\n" - "License instead of this License to a given copy of the Library. To do\n" - "this, you must alter all the notices that refer to this License, so\n" - "that they refer to the ordinary GNU General Public License, version 2,\n" - "instead of to this License. (If a newer version than version 2 of the\n" - "ordinary GNU General Public License has appeared, then you can specify\n" - "that version instead if you wish.) Do not make any other change in\n" - "these notices.\n" - "\n" - " Once this change is made in a given copy, it is irreversible for\n" - "that copy, so the ordinary GNU General Public License applies to all\n" - "subsequent copies and derivative works made from that copy.\n" - "\n" - " This option is useful when you wish to copy part of the code of\n" - "the Library into a program that is not a library.\n" - "\n" - " 4. You may copy and distribute the Library (or a portion or\n" - "derivative of it, under Section 2) in object code or executable form\n" - "under the terms of Sections 1 and 2 above provided that you accompany\n" - "it with the complete corresponding machine-readable source code, which\n" - "must be distributed under the terms of Sections 1 and 2 above on a\n" - "medium customarily used for software interchange.\n" - "\n" - " If distribution of object code is made by offering access to copy\n" - "from a designated place, then offering equivalent access to copy the\n" - "source code from the same place satisfies the requirement to\n" - "distribute the source code, even though third parties are not\n" - "compelled to copy the source along with the object code.\n" - "\n" - " 5. A program that contains no derivative of any portion of the\n" - "Library, but is designed to work with the Library by being compiled or\n" - "linked with it, is called a \"work that uses the Library\". Such a\n" - "work, in isolation, is not a derivative work of the Library, and\n" - "therefore falls outside the scope of this License.\n" - "\n" - " However, linking a \"work that uses the Library\" with the Library\n" - "creates an executable that is a derivative of the Library (because it\n" - "contains portions of the Library), rather than a \"work that uses the\n" - "library\". The executable is therefore covered by this License.\n" - "Section 6 states terms for distribution of such executables.\n" - "\n" - " When a \"work that uses the Library\" uses material from a header file\n" - "that is part of the Library, the object code for the work may be a\n" - "derivative work of the Library even though the source code is not.\n" - "Whether this is true is especially significant if the work can be\n" - "linked without the Library, or if the work is itself a library. The\n" - "threshold for this to be true is not precisely defined by law.\n" - "\n" - " If such an object file uses only numerical parameters, data\n" - "structure layouts and accessors, and small macros and small inline\n" - "functions (ten lines or less in length), then the use of the object\n" - "file is unrestricted, regardless of whether it is legally a derivative\n" - "work. (Executables containing this object code plus portions of the\n" - "Library will still fall under Section 6.)\n" - "\n" - " Otherwise, if the work is a derivative of the Library, you may\n" - "distribute the object code for the work under the terms of Section 6.\n" - "Any executables containing that work also fall under Section 6,\n" - "whether or not they are linked directly with the Library itself.\n" - "\n" - " 6. As an exception to the Sections above, you may also compile or\n" - "link a \"work that uses the Library\" with the Library to produce a\n" - "work containing portions of the Library, and distribute that work\n" - "under terms of your choice, provided that the terms permit\n" - "modification of the work for the customer's own use and reverse\n" - "engineering for debugging such modifications.\n" - "\n" - " You must give prominent notice with each copy of the work that the\n" - "Library is used in it and that the Library and its use are covered by\n" - "this License. You must supply a copy of this License. If the work\n" - "during execution displays copyright notices, you must include the\n" - "copyright notice for the Library among them, as well as a reference\n" - "directing the user to the copy of this License. Also, you must do one\n" - "of these things:\n" - "\n" - " a) Accompany the work with the complete corresponding\n" - " machine-readable source code for the Library including whatever\n" - " changes were used in the work (which must be distributed under\n" - " Sections 1 and 2 above); and, if the work is an executable linked\n" - " with the Library, with the complete machine-readable \"work that\n" - " uses the Library\", as object code and/or source code, so that the\n" - " user can modify the Library and then relink to produce a modified\n" - " executable containing the modified Library. (It is understood\n" - " that the user who changes the contents of definitions files in the\n" - " Library will not necessarily be able to recompile the application\n" - " to use the modified definitions.)\n" - "\n" - " b) Accompany the work with a written offer, valid for at\n" - " least three years, to give the same user the materials\n" - " specified in Subsection 6a, above, for a charge no more\n" - " than the cost of performing this distribution.\n" - "\n" - " c) If distribution of the work is made by offering access to copy\n" - " from a designated place, offer equivalent access to copy the above\n" - " specified materials from the same place.\n" - "\n" - " d) Verify that the user has already received a copy of these\n" - " materials or that you have already sent this user a copy.\n" - "\n" - " For an executable, the required form of the \"work that uses the\n" - "Library\" must include any data and utility programs needed for\n" - "reproducing the executable from it. However, as a special exception,\n" - "the source code distributed need not include anything that is normally\n" - "distributed (in either source or binary form) with the major\n" - "components (compiler, kernel, and so on) of the operating system on\n" - "which the executable runs, unless that component itself accompanies\n" - "the executable.\n" - "\n" - " It may happen that this requirement contradicts the license\n" - "restrictions of other proprietary libraries that do not normally\n" - "accompany the operating system. Such a contradiction means you cannot\n" - "use both them and the Library together in an executable that you\n" - "distribute.\n" - "\n" - " 7. You may place library facilities that are a work based on the\n" - "Library side-by-side in a single library together with other library\n" - "facilities not covered by this License, and distribute such a combined\n" - "library, provided that the separate distribution of the work based on\n" - "the Library and of the other library facilities is otherwise\n" - "permitted, and provided that you do these two things:\n" - "\n" - " a) Accompany the combined library with a copy of the same work\n" - " based on the Library, uncombined with any other library\n" - " facilities. This must be distributed under the terms of the\n" - " Sections above.\n" - "\n" - " b) Give prominent notice with the combined library of the fact\n" - " that part of it is a work based on the Library, and explaining\n" - " where to find the accompanying uncombined form of the same work.\n" - "\n" - " 8. You may not copy, modify, sublicense, link with, or distribute\n" - "the Library except as expressly provided under this License. Any\n" - "attempt otherwise to copy, modify, sublicense, link with, or\n" - "distribute the Library is void, and will automatically terminate your\n" - "rights under this License. However, parties who have received copies,\n" - "or rights, from you under this License will not have their licenses\n" - "terminated so long as such parties remain in full compliance.\n" - "\n" - " 9. You are not required to accept this License, since you have not\n" - "signed it. However, nothing else grants you permission to modify or\n" - "distribute the Library or its derivative works. These actions are\n" - "prohibited by law if you do not accept this License. Therefore, by\n" - "modifying or distributing the Library (or any work based on the\n" - "Library), you indicate your acceptance of this License to do so, and\n" - "all its terms and conditions for copying, distributing or modifying\n" - "the Library or works based on it.\n" - "\n" - " 10. Each time you redistribute the Library (or any work based on the\n" - "Library), the recipient automatically receives a license from the\n" - "original licensor to copy, distribute, link with or modify the Library\n" - "subject to these terms and conditions. You may not impose any further\n" - "restrictions on the recipients' exercise of the rights granted herein.\n" - "You are not responsible for enforcing compliance by third parties to\n" - "this License.\n" - "\n" - " 11. If, as a consequence of a court judgment or allegation of patent\n" - "infringement or for any other reason (not limited to patent issues),\n" - "conditions are imposed on you (whether by court order, agreement or\n" - "otherwise) that contradict the conditions of this License, they do not\n" - "excuse you from the conditions of this License. If you cannot\n" - "distribute so as to satisfy simultaneously your obligations under this\n" - "License and any other pertinent obligations, then as a consequence you\n" - "may not distribute the Library at all. For example, if a patent\n" - "license would not permit royalty-free redistribution of the Library by\n" - "all those who receive copies directly or indirectly through you, then\n" - "the only way you could satisfy both it and this License would be to\n" - "refrain entirely from distribution of the Library.\n" - "\n" - "If any portion of this section is held invalid or unenforceable under any\n" - "particular circumstance, the balance of the section is intended to apply,\n" - "and the section as a whole is intended to apply in other circumstances.\n" - "\n" - "It is not the purpose of this section to induce you to infringe any\n" - "patents or other property right claims or to contest validity of any\n" - "such claims; this section has the sole purpose of protecting the\n" - "integrity of the free software distribution system which is\n" - "implemented by public license practices. Many people have made\n" - "generous contributions to the wide range of software distributed\n" - "through that system in reliance on consistent application of that\n" - "system; it is up to the author/donor to decide if he or she is willing\n" - "to distribute software through any other system and a licensee cannot\n" - "impose that choice.\n" - "\n" - "This section is intended to make thoroughly clear what is believed to\n" - "be a consequence of the rest of this License.\n" - "\n" - " 12. If the distribution and/or use of the Library is restricted in\n" - "certain countries either by patents or by copyrighted interfaces, the\n" - "original copyright holder who places the Library under this License may add\n" - "an explicit geographical distribution limitation excluding those countries,\n" - "so that distribution is permitted only in or among countries not thus\n" - "excluded. In such case, this License incorporates the limitation as if\n" - "written in the body of this License.\n" - "\n" - " 13. The Free Software Foundation may publish revised and/or new\n" - "versions of the Library General Public License from time to time.\n" - "Such new versions will be similar in spirit to the present version,\n" - "but may differ in detail to address new problems or concerns.\n" - "\n" - "Each version is given a distinguishing version number. If the Library\n" - "specifies a version number of this License which applies to it and\n" - "\"any later version\", you have the option of following the terms and\n" - "conditions either of that version or of any later version published by\n" - "the Free Software Foundation. If the Library does not specify a\n" - "license version number, you may choose any version ever published by\n" - "the Free Software Foundation.\n" - "\n" - " 14. If you wish to incorporate parts of the Library into other free\n" - "programs whose distribution conditions are incompatible with these,\n" - "write to the author to ask for permission. For software which is\n" - "copyrighted by the Free Software Foundation, write to the Free\n" - "Software Foundation; we sometimes make exceptions for this. Our\n" - "decision will be guided by the two goals of preserving the free status\n" - "of all derivatives of our free software and of promoting the sharing\n" - "and reuse of software generally.\n" - "\n" - " NO WARRANTY\n" - "\n" - " 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\n" - "WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\n" - "EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\n" - "OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\n" - "KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\n" - "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" - "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\n" - "LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\n" - "THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n" - "\n" - " 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\n" - "WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\n" - "AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\n" - "FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\n" - "CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\n" - "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\n" - "RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\n" - "FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\n" - "SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n" - "DAMAGES.\n" - "\n" - " END OF TERMS AND CONDITIONS\n" - "\n" - " How to Apply These Terms to Your New Libraries\n" - "\n" - " If you develop a new library, and you want it to be of the greatest\n" - "possible use to the public, we recommend making it free software that\n" - "everyone can redistribute and change. You can do so by permitting\n" - "redistribution under these terms (or, alternatively, under the terms of the\n" - "ordinary General Public License).\n" - "\n" - " To apply these terms, attach the following notices to the library. It is\n" - "safest to attach them to the start of each source file to most effectively\n" - "convey the exclusion of warranty; and each file should have at least the\n" - "\"copyright\" line and a pointer to where the full notice is found.\n" - "\n" - " <one line to give the library's name and a brief idea of what it does.>\n" - " Copyright (C) <year> <name of author>\n" - "\n" - " This library is free software; you can redistribute it and/or\n" - " modify it under the terms of the GNU Library General Public\n" - " License as published by the Free Software Foundation; either\n" - " version 2 of the License, or (at your option) any later version.\n" - "\n" - " This library is distributed in the hope that it will be useful,\n" - " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" - " Library General Public License for more details.\n" - "\n" - " You should have received a copy of the GNU Library General Public\n" - " License along with this library; if not, write to the \n" - " Free Software Foundation, Inc., 59 Temple Place - Suite 330, \n" - " Boston, MA 02111-1307 USA.\n" - "\n" - "Also add information on how to contact you by electronic and paper mail.\n" - "\n" - "You should also get your employer (if you work as a programmer) or your\n" - "school, if any, to sign a \"copyright disclaimer\" for the library, if\n" - "necessary. Here is a sample; alter the names:\n" - "\n" - " Yoyodyne, Inc., hereby disclaims all copyright interest in the\n" - " library `Frob' (a library for tweaking knobs) written by James Random Hacker.\n" - "\n" - " <signature of Ty Coon>, 1 April 1990\n" - " Ty Coon, President of Vice\n" - "\n" - "That's all there is to it!"; +static const char *licenseGlib = " GNU LIBRARY GENERAL PUBLIC LICENSE\n" + " Version 2, June 1991\n" + "\n" + " Copyright (C) 1991 Free Software Foundation, Inc.\n" + " 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" + " Everyone is permitted to copy and distribute verbatim copies\n" + " of this license document, but changing it is not allowed.\n" + "\n" + "[This is the first released version of the library GPL. It is\n" + " numbered 2 because it goes with version 2 of the ordinary GPL.]\n" + "\n" + " Preamble\n" + "\n" + " The licenses for most software are designed to take away your\n" + "freedom to share and change it. By contrast, the GNU General Public\n" + "Licenses are intended to guarantee your freedom to share and change\n" + "free software--to make sure the software is free for all its users.\n" + "\n" + " This license, the Library General Public License, applies to some\n" + "specially designated Free Software Foundation software, and to any\n" + "other libraries whose authors decide to use it. You can use it for\n" + "your libraries, too.\n" + "\n" + " When we speak of free software, we are referring to freedom, not\n" + "price. Our General Public Licenses are designed to make sure that you\n" + "have the freedom to distribute copies of free software (and charge for\n" + "this service if you wish), that you receive source code or can get it\n" + "if you want it, that you can change the software or use pieces of it\n" + "in new free programs; and that you know you can do these things.\n" + "\n" + " To protect your rights, we need to make restrictions that forbid\n" + "anyone to deny you these rights or to ask you to surrender the rights.\n" + "These restrictions translate to certain responsibilities for you if\n" + "you distribute copies of the library, or if you modify it.\n" + "\n" + " For example, if you distribute copies of the library, whether gratis\n" + "or for a fee, you must give the recipients all the rights that we gave\n" + "you. You must make sure that they, too, receive or can get the source\n" + "code. If you link a program with the library, you must provide\n" + "complete object files to the recipients so that they can relink them\n" + "with the library, after making changes to the library and recompiling\n" + "it. And you must show them these terms so they know their rights.\n" + "\n" + " Our method of protecting your rights has two steps: (1) copyright\n" + "the library, and (2) offer you this license which gives you legal\n" + "permission to copy, distribute and/or modify the library.\n" + "\n" + " Also, for each distributor's protection, we want to make certain\n" + "that everyone understands that there is no warranty for this free\n" + "library. If the library is modified by someone else and passed on, we\n" + "want its recipients to know that what they have is not the original\n" + "version, so that any problems introduced by others will not reflect on\n" + "the original authors' reputations.\n" + "\n" + " Finally, any free program is threatened constantly by software\n" + "patents. We wish to avoid the danger that companies distributing free\n" + "software will individually obtain patent licenses, thus in effect\n" + "transforming the program into proprietary software. To prevent this,\n" + "we have made it clear that any patent must be licensed for everyone's\n" + "free use or not licensed at all.\n" + "\n" + " Most GNU software, including some libraries, is covered by the ordinary\n" + "GNU General Public License, which was designed for utility programs. This\n" + "license, the GNU Library General Public License, applies to certain\n" + "designated libraries. This license is quite different from the ordinary\n" + "one; be sure to read it in full, and don't assume that anything in it is\n" + "the same as in the ordinary license.\n" + "\n" + " The reason we have a separate public license for some libraries is that\n" + "they blur the distinction we usually make between modifying or adding to a\n" + "program and simply using it. Linking a program with a library, without\n" + "changing the library, is in some sense simply using the library, and is\n" + "analogous to running a utility program or application program. However, in\n" + "a textual and legal sense, the linked executable is a combined work, a\n" + "derivative of the original library, and the ordinary General Public License\n" + "treats it as such.\n" + "\n" + " Because of this blurred distinction, using the ordinary General\n" + "Public License for libraries did not effectively promote software\n" + "sharing, because most developers did not use the libraries. We\n" + "concluded that weaker conditions might promote sharing better.\n" + "\n" + " However, unrestricted linking of non-free programs would deprive the\n" + "users of those programs of all benefit from the free status of the\n" + "libraries themselves. This Library General Public License is intended to\n" + "permit developers of non-free programs to use free libraries, while\n" + "preserving your freedom as a user of such programs to change the free\n" + "libraries that are incorporated in them. (We have not seen how to achieve\n" + "this as regards changes in header files, but we have achieved it as regards\n" + "changes in the actual functions of the Library.) The hope is that this\n" + "will lead to faster development of free libraries.\n" + "\n" + " The precise terms and conditions for copying, distribution and\n" + "modification follow. Pay close attention to the difference between a\n" + "\"work based on the library\" and a \"work that uses the library\". The\n" + "former contains code derived from the library, while the latter only\n" + "works together with the library.\n" + "\n" + " Note that it is possible for a library to be covered by the ordinary\n" + "General Public License rather than by this special one.\n" + "\n" + " GNU LIBRARY GENERAL PUBLIC LICENSE\n" + " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" + "\n" + " 0. This License Agreement applies to any software library which\n" + "contains a notice placed by the copyright holder or other authorized\n" + "party saying it may be distributed under the terms of this Library\n" + "General Public License (also called \"this License\"). Each licensee is\n" + "addressed as \"you\".\n" + "\n" + " A \"library\" means a collection of software functions and/or data\n" + "prepared so as to be conveniently linked with application programs\n" + "(which use some of those functions and data) to form executables.\n" + "\n" + " The \"Library\", below, refers to any such software library or work\n" + "which has been distributed under these terms. A \"work based on the\n" + "Library\" means either the Library or any derivative work under\n" + "copyright law: that is to say, a work containing the Library or a\n" + "portion of it, either verbatim or with modifications and/or translated\n" + "straightforwardly into another language. (Hereinafter, translation is\n" + "included without limitation in the term \"modification\".)\n" + "\n" + " \"Source code\" for a work means the preferred form of the work for\n" + "making modifications to it. For a library, complete source code means\n" + "all the source code for all modules it contains, plus any associated\n" + "interface definition files, plus the scripts used to control compilation\n" + "and installation of the library.\n" + "\n" + " Activities other than copying, distribution and modification are not\n" + "covered by this License; they are outside its scope. The act of\n" + "running a program using the Library is not restricted, and output from\n" + "such a program is covered only if its contents constitute a work based\n" + "on the Library (independent of the use of the Library in a tool for\n" + "writing it). Whether that is true depends on what the Library does\n" + "and what the program that uses the Library does.\n" + " \n" + " 1. You may copy and distribute verbatim copies of the Library's\n" + "complete source code as you receive it, in any medium, provided that\n" + "you conspicuously and appropriately publish on each copy an\n" + "appropriate copyright notice and disclaimer of warranty; keep intact\n" + "all the notices that refer to this License and to the absence of any\n" + "warranty; and distribute a copy of this License along with the\n" + "Library.\n" + "\n" + " You may charge a fee for the physical act of transferring a copy,\n" + "and you may at your option offer warranty protection in exchange for a\n" + "fee.\n" + "\n" + " 2. You may modify your copy or copies of the Library or any portion\n" + "of it, thus forming a work based on the Library, and copy and\n" + "distribute such modifications or work under the terms of Section 1\n" + "above, provided that you also meet all of these conditions:\n" + "\n" + " a) The modified work must itself be a software library.\n" + "\n" + " b) You must cause the files modified to carry prominent notices\n" + " stating that you changed the files and the date of any change.\n" + "\n" + " c) You must cause the whole of the work to be licensed at no\n" + " charge to all third parties under the terms of this License.\n" + "\n" + " d) If a facility in the modified Library refers to a function or a\n" + " table of data to be supplied by an application program that uses\n" + " the facility, other than as an argument passed when the facility\n" + " is invoked, then you must make a good faith effort to ensure that,\n" + " in the event an application does not supply such function or\n" + " table, the facility still operates, and performs whatever part of\n" + " its purpose remains meaningful.\n" + "\n" + " (For example, a function in a library to compute square roots has\n" + " a purpose that is entirely well-defined independent of the\n" + " application. Therefore, Subsection 2d requires that any\n" + " application-supplied function or table used by this function must\n" + " be optional: if the application does not supply it, the square\n" + " root function must still compute square roots.)\n" + "\n" + "These requirements apply to the modified work as a whole. If\n" + "identifiable sections of that work are not derived from the Library,\n" + "and can be reasonably considered independent and separate works in\n" + "themselves, then this License, and its terms, do not apply to those\n" + "sections when you distribute them as separate works. But when you\n" + "distribute the same sections as part of a whole which is a work based\n" + "on the Library, the distribution of the whole must be on the terms of\n" + "this License, whose permissions for other licensees extend to the\n" + "entire whole, and thus to each and every part regardless of who wrote\n" + "it.\n" + "\n" + "Thus, it is not the intent of this section to claim rights or contest\n" + "your rights to work written entirely by you; rather, the intent is to\n" + "exercise the right to control the distribution of derivative or\n" + "collective works based on the Library.\n" + "\n" + "In addition, mere aggregation of another work not based on the Library\n" + "with the Library (or with a work based on the Library) on a volume of\n" + "a storage or distribution medium does not bring the other work under\n" + "the scope of this License.\n" + "\n" + " 3. You may opt to apply the terms of the ordinary GNU General Public\n" + "License instead of this License to a given copy of the Library. To do\n" + "this, you must alter all the notices that refer to this License, so\n" + "that they refer to the ordinary GNU General Public License, version 2,\n" + "instead of to this License. (If a newer version than version 2 of the\n" + "ordinary GNU General Public License has appeared, then you can specify\n" + "that version instead if you wish.) Do not make any other change in\n" + "these notices.\n" + "\n" + " Once this change is made in a given copy, it is irreversible for\n" + "that copy, so the ordinary GNU General Public License applies to all\n" + "subsequent copies and derivative works made from that copy.\n" + "\n" + " This option is useful when you wish to copy part of the code of\n" + "the Library into a program that is not a library.\n" + "\n" + " 4. You may copy and distribute the Library (or a portion or\n" + "derivative of it, under Section 2) in object code or executable form\n" + "under the terms of Sections 1 and 2 above provided that you accompany\n" + "it with the complete corresponding machine-readable source code, which\n" + "must be distributed under the terms of Sections 1 and 2 above on a\n" + "medium customarily used for software interchange.\n" + "\n" + " If distribution of object code is made by offering access to copy\n" + "from a designated place, then offering equivalent access to copy the\n" + "source code from the same place satisfies the requirement to\n" + "distribute the source code, even though third parties are not\n" + "compelled to copy the source along with the object code.\n" + "\n" + " 5. A program that contains no derivative of any portion of the\n" + "Library, but is designed to work with the Library by being compiled or\n" + "linked with it, is called a \"work that uses the Library\". Such a\n" + "work, in isolation, is not a derivative work of the Library, and\n" + "therefore falls outside the scope of this License.\n" + "\n" + " However, linking a \"work that uses the Library\" with the Library\n" + "creates an executable that is a derivative of the Library (because it\n" + "contains portions of the Library), rather than a \"work that uses the\n" + "library\". The executable is therefore covered by this License.\n" + "Section 6 states terms for distribution of such executables.\n" + "\n" + " When a \"work that uses the Library\" uses material from a header file\n" + "that is part of the Library, the object code for the work may be a\n" + "derivative work of the Library even though the source code is not.\n" + "Whether this is true is especially significant if the work can be\n" + "linked without the Library, or if the work is itself a library. The\n" + "threshold for this to be true is not precisely defined by law.\n" + "\n" + " If such an object file uses only numerical parameters, data\n" + "structure layouts and accessors, and small macros and small inline\n" + "functions (ten lines or less in length), then the use of the object\n" + "file is unrestricted, regardless of whether it is legally a derivative\n" + "work. (Executables containing this object code plus portions of the\n" + "Library will still fall under Section 6.)\n" + "\n" + " Otherwise, if the work is a derivative of the Library, you may\n" + "distribute the object code for the work under the terms of Section 6.\n" + "Any executables containing that work also fall under Section 6,\n" + "whether or not they are linked directly with the Library itself.\n" + "\n" + " 6. As an exception to the Sections above, you may also compile or\n" + "link a \"work that uses the Library\" with the Library to produce a\n" + "work containing portions of the Library, and distribute that work\n" + "under terms of your choice, provided that the terms permit\n" + "modification of the work for the customer's own use and reverse\n" + "engineering for debugging such modifications.\n" + "\n" + " You must give prominent notice with each copy of the work that the\n" + "Library is used in it and that the Library and its use are covered by\n" + "this License. You must supply a copy of this License. If the work\n" + "during execution displays copyright notices, you must include the\n" + "copyright notice for the Library among them, as well as a reference\n" + "directing the user to the copy of this License. Also, you must do one\n" + "of these things:\n" + "\n" + " a) Accompany the work with the complete corresponding\n" + " machine-readable source code for the Library including whatever\n" + " changes were used in the work (which must be distributed under\n" + " Sections 1 and 2 above); and, if the work is an executable linked\n" + " with the Library, with the complete machine-readable \"work that\n" + " uses the Library\", as object code and/or source code, so that the\n" + " user can modify the Library and then relink to produce a modified\n" + " executable containing the modified Library. (It is understood\n" + " that the user who changes the contents of definitions files in the\n" + " Library will not necessarily be able to recompile the application\n" + " to use the modified definitions.)\n" + "\n" + " b) Accompany the work with a written offer, valid for at\n" + " least three years, to give the same user the materials\n" + " specified in Subsection 6a, above, for a charge no more\n" + " than the cost of performing this distribution.\n" + "\n" + " c) If distribution of the work is made by offering access to copy\n" + " from a designated place, offer equivalent access to copy the above\n" + " specified materials from the same place.\n" + "\n" + " d) Verify that the user has already received a copy of these\n" + " materials or that you have already sent this user a copy.\n" + "\n" + " For an executable, the required form of the \"work that uses the\n" + "Library\" must include any data and utility programs needed for\n" + "reproducing the executable from it. However, as a special exception,\n" + "the source code distributed need not include anything that is normally\n" + "distributed (in either source or binary form) with the major\n" + "components (compiler, kernel, and so on) of the operating system on\n" + "which the executable runs, unless that component itself accompanies\n" + "the executable.\n" + "\n" + " It may happen that this requirement contradicts the license\n" + "restrictions of other proprietary libraries that do not normally\n" + "accompany the operating system. Such a contradiction means you cannot\n" + "use both them and the Library together in an executable that you\n" + "distribute.\n" + "\n" + " 7. You may place library facilities that are a work based on the\n" + "Library side-by-side in a single library together with other library\n" + "facilities not covered by this License, and distribute such a combined\n" + "library, provided that the separate distribution of the work based on\n" + "the Library and of the other library facilities is otherwise\n" + "permitted, and provided that you do these two things:\n" + "\n" + " a) Accompany the combined library with a copy of the same work\n" + " based on the Library, uncombined with any other library\n" + " facilities. This must be distributed under the terms of the\n" + " Sections above.\n" + "\n" + " b) Give prominent notice with the combined library of the fact\n" + " that part of it is a work based on the Library, and explaining\n" + " where to find the accompanying uncombined form of the same work.\n" + "\n" + " 8. You may not copy, modify, sublicense, link with, or distribute\n" + "the Library except as expressly provided under this License. Any\n" + "attempt otherwise to copy, modify, sublicense, link with, or\n" + "distribute the Library is void, and will automatically terminate your\n" + "rights under this License. However, parties who have received copies,\n" + "or rights, from you under this License will not have their licenses\n" + "terminated so long as such parties remain in full compliance.\n" + "\n" + " 9. You are not required to accept this License, since you have not\n" + "signed it. However, nothing else grants you permission to modify or\n" + "distribute the Library or its derivative works. These actions are\n" + "prohibited by law if you do not accept this License. Therefore, by\n" + "modifying or distributing the Library (or any work based on the\n" + "Library), you indicate your acceptance of this License to do so, and\n" + "all its terms and conditions for copying, distributing or modifying\n" + "the Library or works based on it.\n" + "\n" + " 10. Each time you redistribute the Library (or any work based on the\n" + "Library), the recipient automatically receives a license from the\n" + "original licensor to copy, distribute, link with or modify the Library\n" + "subject to these terms and conditions. You may not impose any further\n" + "restrictions on the recipients' exercise of the rights granted herein.\n" + "You are not responsible for enforcing compliance by third parties to\n" + "this License.\n" + "\n" + " 11. If, as a consequence of a court judgment or allegation of patent\n" + "infringement or for any other reason (not limited to patent issues),\n" + "conditions are imposed on you (whether by court order, agreement or\n" + "otherwise) that contradict the conditions of this License, they do not\n" + "excuse you from the conditions of this License. If you cannot\n" + "distribute so as to satisfy simultaneously your obligations under this\n" + "License and any other pertinent obligations, then as a consequence you\n" + "may not distribute the Library at all. For example, if a patent\n" + "license would not permit royalty-free redistribution of the Library by\n" + "all those who receive copies directly or indirectly through you, then\n" + "the only way you could satisfy both it and this License would be to\n" + "refrain entirely from distribution of the Library.\n" + "\n" + "If any portion of this section is held invalid or unenforceable under any\n" + "particular circumstance, the balance of the section is intended to apply,\n" + "and the section as a whole is intended to apply in other circumstances.\n" + "\n" + "It is not the purpose of this section to induce you to infringe any\n" + "patents or other property right claims or to contest validity of any\n" + "such claims; this section has the sole purpose of protecting the\n" + "integrity of the free software distribution system which is\n" + "implemented by public license practices. Many people have made\n" + "generous contributions to the wide range of software distributed\n" + "through that system in reliance on consistent application of that\n" + "system; it is up to the author/donor to decide if he or she is willing\n" + "to distribute software through any other system and a licensee cannot\n" + "impose that choice.\n" + "\n" + "This section is intended to make thoroughly clear what is believed to\n" + "be a consequence of the rest of this License.\n" + "\n" + " 12. If the distribution and/or use of the Library is restricted in\n" + "certain countries either by patents or by copyrighted interfaces, the\n" + "original copyright holder who places the Library under this License may add\n" + "an explicit geographical distribution limitation excluding those countries,\n" + "so that distribution is permitted only in or among countries not thus\n" + "excluded. In such case, this License incorporates the limitation as if\n" + "written in the body of this License.\n" + "\n" + " 13. The Free Software Foundation may publish revised and/or new\n" + "versions of the Library General Public License from time to time.\n" + "Such new versions will be similar in spirit to the present version,\n" + "but may differ in detail to address new problems or concerns.\n" + "\n" + "Each version is given a distinguishing version number. If the Library\n" + "specifies a version number of this License which applies to it and\n" + "\"any later version\", you have the option of following the terms and\n" + "conditions either of that version or of any later version published by\n" + "the Free Software Foundation. If the Library does not specify a\n" + "license version number, you may choose any version ever published by\n" + "the Free Software Foundation.\n" + "\n" + " 14. If you wish to incorporate parts of the Library into other free\n" + "programs whose distribution conditions are incompatible with these,\n" + "write to the author to ask for permission. For software which is\n" + "copyrighted by the Free Software Foundation, write to the Free\n" + "Software Foundation; we sometimes make exceptions for this. Our\n" + "decision will be guided by the two goals of preserving the free status\n" + "of all derivatives of our free software and of promoting the sharing\n" + "and reuse of software generally.\n" + "\n" + " NO WARRANTY\n" + "\n" + " 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\n" + "WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\n" + "EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\n" + "OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\n" + "KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\n" + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" + "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\n" + "LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\n" + "THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n" + "\n" + " 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\n" + "WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\n" + "AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\n" + "FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\n" + "CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\n" + "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\n" + "RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\n" + "FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\n" + "SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n" + "DAMAGES.\n" + "\n" + " END OF TERMS AND CONDITIONS\n" + "\n" + " How to Apply These Terms to Your New Libraries\n" + "\n" + " If you develop a new library, and you want it to be of the greatest\n" + "possible use to the public, we recommend making it free software that\n" + "everyone can redistribute and change. You can do so by permitting\n" + "redistribution under these terms (or, alternatively, under the terms of the\n" + "ordinary General Public License).\n" + "\n" + " To apply these terms, attach the following notices to the library. It is\n" + "safest to attach them to the start of each source file to most effectively\n" + "convey the exclusion of warranty; and each file should have at least the\n" + "\"copyright\" line and a pointer to where the full notice is found.\n" + "\n" + " <one line to give the library's name and a brief idea of what it does.>\n" + " Copyright (C) <year> <name of author>\n" + "\n" + " This library is free software; you can redistribute it and/or\n" + " modify it under the terms of the GNU Library General Public\n" + " License as published by the Free Software Foundation; either\n" + " version 2 of the License, or (at your option) any later version.\n" + "\n" + " This library is distributed in the hope that it will be useful,\n" + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" + " Library General Public License for more details.\n" + "\n" + " You should have received a copy of the GNU Library General Public\n" + " License along with this library; if not, write to the \n" + " Free Software Foundation, Inc., 59 Temple Place - Suite 330, \n" + " Boston, MA 02111-1307 USA.\n" + "\n" + "Also add information on how to contact you by electronic and paper mail.\n" + "\n" + "You should also get your employer (if you work as a programmer) or your\n" + "school, if any, to sign a \"copyright disclaimer\" for the library, if\n" + "necessary. Here is a sample; alter the names:\n" + "\n" + " Yoyodyne, Inc., hereby disclaims all copyright interest in the\n" + " library `Frob' (a library for tweaking knobs) written by James Random Hacker.\n" + "\n" + " <signature of Ty Coon>, 1 April 1990\n" + " Ty Coon, President of Vice\n" + "\n" + "That's all there is to it!"; #endif #ifdef USE_BUILDENV -static const char *licenseLibcap2 = - "Unless otherwise *explicitly* stated, the following text describes the\n" - "licensed conditions under which the contents of this libcap release\n" - "may be used and distributed:\n" - "\n" - "-------------------------------------------------------------------------\n" - "Redistribution and use in source and binary forms of libcap, with\n" - "or without modification, are permitted provided that the following\n" - "conditions are met:\n" - "\n" - "1. Redistributions of source code must retain any existing copyright\n" - " notice, and this entire permission notice in its entirety,\n" - " including the disclaimer of warranties.\n" - "\n" - "2. Redistributions in binary form must reproduce all prior and current\n" - " copyright notices, this list of conditions, and the following\n" - " disclaimer in the documentation and/or other materials provided\n" - " with the distribution.\n" - "\n" - "3. The name of any author may not be used to endorse or promote\n" - " products derived from this software without their specific prior\n" - " written permission.\n" - "\n" - "ALTERNATIVELY, this product may be distributed under the terms of the\n" - "GNU General Public License (v2.0 - see below), in which case the\n" - "provisions of the GNU GPL are required INSTEAD OF the above\n" - "restrictions. (This clause is necessary due to a potential conflict\n" - "between the GNU GPL and the restrictions contained in a BSD-style\n" - "copyright.)\n" - "\n" - "THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED\n" - "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" - "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" - "IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,\n" - "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n" - "BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n" - "OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n" - "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n" - "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n" - "USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n" - "DAMAGE.\n" - "-------------------------------------------------------------------------\n" - "\n" - "-------------------------\n" - "Full text of gpl-2.0.txt:\n" - "-------------------------\n" - "\n" - " GNU GENERAL PUBLIC LICENSE\n" - " Version 2, June 1991\n" - "\n" - " Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n" - " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" - " Everyone is permitted to copy and distribute verbatim copies\n" - " of this license document, but changing it is not allowed.\n" - "\n" - " Preamble\n" - "\n" - " The licenses for most software are designed to take away your\n" - "freedom to share and change it. By contrast, the GNU General Public\n" - "License is intended to guarantee your freedom to share and change free\n" - "software--to make sure the software is free for all its users. This\n" - "General Public License applies to most of the Free Software\n" - "Foundation's software and to any other program whose authors commit to\n" - "using it. (Some other Free Software Foundation software is covered by\n" - "the GNU Lesser General Public License instead.) You can apply it to\n" - "your programs, too.\n" - "\n" - " When we speak of free software, we are referring to freedom, not\n" - "price. Our General Public Licenses are designed to make sure that you\n" - "have the freedom to distribute copies of free software (and charge for\n" - "this service if you wish), that you receive source code or can get it\n" - "if you want it, that you can change the software or use pieces of it\n" - "in new free programs; and that you know you can do these things.\n" - "\n" - " To protect your rights, we need to make restrictions that forbid\n" - "anyone to deny you these rights or to ask you to surrender the rights.\n" - "These restrictions translate to certain responsibilities for you if you\n" - "distribute copies of the software, or if you modify it.\n" - "\n" - " For example, if you distribute copies of such a program, whether\n" - "gratis or for a fee, you must give the recipients all the rights that\n" - "you have. You must make sure that they, too, receive or can get the\n" - "source code. And you must show them these terms so they know their\n" - "rights.\n" - "\n" - " We protect your rights with two steps: (1) copyright the software, and\n" - "(2) offer you this license which gives you legal permission to copy,\n" - "distribute and/or modify the software.\n" - "\n" - " Also, for each author's protection and ours, we want to make certain\n" - "that everyone understands that there is no warranty for this free\n" - "software. If the software is modified by someone else and passed on, we\n" - "want its recipients to know that what they have is not the original, so\n" - "that any problems introduced by others will not reflect on the original\n" - "authors' reputations.\n" - "\n" - " Finally, any free program is threatened constantly by software\n" - "patents. We wish to avoid the danger that redistributors of a free\n" - "program will individually obtain patent licenses, in effect making the\n" - "program proprietary. To prevent this, we have made it clear that any\n" - "patent must be licensed for everyone's free use or not licensed at all.\n" - "\n" - " The precise terms and conditions for copying, distribution and\n" - "modification follow.\n" - "\n" - " GNU GENERAL PUBLIC LICENSE\n" - " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" - "\n" - " 0. This License applies to any program or other work which contains\n" - "a notice placed by the copyright holder saying it may be distributed\n" - "under the terms of this General Public License. The \"Program\", below,\n" - "refers to any such program or work, and a \"work based on the Program\"\n" - "means either the Program or any derivative work under copyright law:\n" - "that is to say, a work containing the Program or a portion of it,\n" - "either verbatim or with modifications and/or translated into another\n" - "language. (Hereinafter, translation is included without limitation in\n" - "the term \"modification\".) Each licensee is addressed as \"you\".\n" - "\n" - "Activities other than copying, distribution and modification are not\n" - "covered by this License; they are outside its scope. The act of\n" - "running the Program is not restricted, and the output from the Program\n" - "is covered only if its contents constitute a work based on the\n" - "Program (independent of having been made by running the Program).\n" - "Whether that is true depends on what the Program does.\n" - "\n" - " 1. You may copy and distribute verbatim copies of the Program's\n" - "source code as you receive it, in any medium, provided that you\n" - "conspicuously and appropriately publish on each copy an appropriate\n" - "copyright notice and disclaimer of warranty; keep intact all the\n" - "notices that refer to this License and to the absence of any warranty;\n" - "and give any other recipients of the Program a copy of this License\n" - "along with the Program.\n" - "\n" - "You may charge a fee for the physical act of transferring a copy, and\n" - "you may at your option offer warranty protection in exchange for a fee.\n" - "\n" - " 2. You may modify your copy or copies of the Program or any portion\n" - "of it, thus forming a work based on the Program, and copy and\n" - "distribute such modifications or work under the terms of Section 1\n" - "above, provided that you also meet all of these conditions:\n" - "\n" - " a) You must cause the modified files to carry prominent notices\n" - " stating that you changed the files and the date of any change.\n" - "\n" - " b) You must cause any work that you distribute or publish, that in\n" - " whole or in part contains or is derived from the Program or any\n" - " part thereof, to be licensed as a whole at no charge to all third\n" - " parties under the terms of this License.\n" - "\n" - " c) If the modified program normally reads commands interactively\n" - " when run, you must cause it, when started running for such\n" - " interactive use in the most ordinary way, to print or display an\n" - " announcement including an appropriate copyright notice and a\n" - " notice that there is no warranty (or else, saying that you provide\n" - " a warranty) and that users may redistribute the program under\n" - " these conditions, and telling the user how to view a copy of this\n" - " License. (Exception: if the Program itself is interactive but\n" - " does not normally print such an announcement, your work based on\n" - " the Program is not required to print an announcement.)\n" - "\n" - "These requirements apply to the modified work as a whole. If\n" - "identifiable sections of that work are not derived from the Program,\n" - "and can be reasonably considered independent and separate works in\n" - "themselves, then this License, and its terms, do not apply to those\n" - "sections when you distribute them as separate works. But when you\n" - "distribute the same sections as part of a whole which is a work based\n" - "on the Program, the distribution of the whole must be on the terms of\n" - "this License, whose permissions for other licensees extend to the\n" - "entire whole, and thus to each and every part regardless of who wrote it.\n" - "\n" - "Thus, it is not the intent of this section to claim rights or contest\n" - "your rights to work written entirely by you; rather, the intent is to\n" - "exercise the right to control the distribution of derivative or\n" - "collective works based on the Program.\n" - "\n" - "In addition, mere aggregation of another work not based on the Program\n" - "with the Program (or with a work based on the Program) on a volume of\n" - "a storage or distribution medium does not bring the other work under\n" - "the scope of this License.\n" - "\n" - " 3. You may copy and distribute the Program (or a work based on it,\n" - "under Section 2) in object code or executable form under the terms of\n" - "Sections 1 and 2 above provided that you also do one of the following:\n" - "\n" - " a) Accompany it with the complete corresponding machine-readable\n" - " source code, which must be distributed under the terms of Sections\n" - " 1 and 2 above on a medium customarily used for software interchange; or,\n" - "\n" - " b) Accompany it with a written offer, valid for at least three\n" - " years, to give any third party, for a charge no more than your\n" - " cost of physically performing source distribution, a complete\n" - " machine-readable copy of the corresponding source code, to be\n" - " distributed under the terms of Sections 1 and 2 above on a medium\n" - " customarily used for software interchange; or,\n" - "\n" - " c) Accompany it with the information you received as to the offer\n" - " to distribute corresponding source code. (This alternative is\n" - " allowed only for noncommercial distribution and only if you\n" - " received the program in object code or executable form with such\n" - " an offer, in accord with Subsection b above.)\n" - "\n" - "The source code for a work means the preferred form of the work for\n" - "making modifications to it. For an executable work, complete source\n" - "code means all the source code for all modules it contains, plus any\n" - "associated interface definition files, plus the scripts used to\n" - "control compilation and installation of the executable. However, as a\n" - "special exception, the source code distributed need not include\n" - "anything that is normally distributed (in either source or binary\n" - "form) with the major components (compiler, kernel, and so on) of the\n" - "operating system on which the executable runs, unless that component\n" - "itself accompanies the executable.\n" - "\n" - "If distribution of executable or object code is made by offering\n" - "access to copy from a designated place, then offering equivalent\n" - "access to copy the source code from the same place counts as\n" - "distribution of the source code, even though third parties are not\n" - "compelled to copy the source along with the object code.\n" - "\n" - " 4. You may not copy, modify, sublicense, or distribute the Program\n" - "except as expressly provided under this License. Any attempt\n" - "otherwise to copy, modify, sublicense or distribute the Program is\n" - "void, and will automatically terminate your rights under this License.\n" - "However, parties who have received copies, or rights, from you under\n" - "this License will not have their licenses terminated so long as such\n" - "parties remain in full compliance.\n" - "\n" - " 5. You are not required to accept this License, since you have not\n" - "signed it. However, nothing else grants you permission to modify or\n" - "distribute the Program or its derivative works. These actions are\n" - "prohibited by law if you do not accept this License. Therefore, by\n" - "modifying or distributing the Program (or any work based on the\n" - "Program), you indicate your acceptance of this License to do so, and\n" - "all its terms and conditions for copying, distributing or modifying\n" - "the Program or works based on it.\n" - "\n" - " 6. Each time you redistribute the Program (or any work based on the\n" - "Program), the recipient automatically receives a license from the\n" - "original licensor to copy, distribute or modify the Program subject to\n" - "these terms and conditions. You may not impose any further\n" - "restrictions on the recipients' exercise of the rights granted herein.\n" - "You are not responsible for enforcing compliance by third parties to\n" - "this License.\n" - "\n" - " 7. If, as a consequence of a court judgment or allegation of patent\n" - "infringement or for any other reason (not limited to patent issues),\n" - "conditions are imposed on you (whether by court order, agreement or\n" - "otherwise) that contradict the conditions of this License, they do not\n" - "excuse you from the conditions of this License. If you cannot\n" - "distribute so as to satisfy simultaneously your obligations under this\n" - "License and any other pertinent obligations, then as a consequence you\n" - "may not distribute the Program at all. For example, if a patent\n" - "license would not permit royalty-free redistribution of the Program by\n" - "all those who receive copies directly or indirectly through you, then\n" - "the only way you could satisfy both it and this License would be to\n" - "refrain entirely from distribution of the Program.\n" - "\n" - "If any portion of this section is held invalid or unenforceable under\n" - "any particular circumstance, the balance of the section is intended to\n" - "apply and the section as a whole is intended to apply in other\n" - "circumstances.\n" - "\n" - "It is not the purpose of this section to induce you to infringe any\n" - "patents or other property right claims or to contest validity of any\n" - "such claims; this section has the sole purpose of protecting the\n" - "integrity of the free software distribution system, which is\n" - "implemented by public license practices. Many people have made\n" - "generous contributions to the wide range of software distributed\n" - "through that system in reliance on consistent application of that\n" - "system; it is up to the author/donor to decide if he or she is willing\n" - "to distribute software through any other system and a licensee cannot\n" - "impose that choice.\n" - "\n" - "This section is intended to make thoroughly clear what is believed to\n" - "be a consequence of the rest of this License.\n" - "\n" - " 8. If the distribution and/or use of the Program is restricted in\n" - "certain countries either by patents or by copyrighted interfaces, the\n" - "original copyright holder who places the Program under this License\n" - "may add an explicit geographical distribution limitation excluding\n" - "those countries, so that distribution is permitted only in or among\n" - "countries not thus excluded. In such case, this License incorporates\n" - "the limitation as if written in the body of this License.\n" - "\n" - " 9. The Free Software Foundation may publish revised and/or new versions\n" - "of the General Public License from time to time. Such new versions will\n" - "be similar in spirit to the present version, but may differ in detail to\n" - "address new problems or concerns.\n" - "\n" - "Each version is given a distinguishing version number. If the Program\n" - "specifies a version number of this License which applies to it and \"any\n" - "later version\", you have the option of following the terms and conditions\n" - "either of that version or of any later version published by the Free\n" - "Software Foundation. If the Program does not specify a version number of\n" - "this License, you may choose any version ever published by the Free Software\n" - "Foundation.\n" - "\n" - " 10. If you wish to incorporate parts of the Program into other free\n" - "programs whose distribution conditions are different, write to the author\n" - "to ask for permission. For software which is copyrighted by the Free\n" - "Software Foundation, write to the Free Software Foundation; we sometimes\n" - "make exceptions for this. Our decision will be guided by the two goals\n" - "of preserving the free status of all derivatives of our free software and\n" - "of promoting the sharing and reuse of software generally.\n" - "\n" - " NO WARRANTY\n" - "\n" - " 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n" - "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN\n" - "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n" - "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n" - "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" - "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\n" - "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE\n" - "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n" - "REPAIR OR CORRECTION.\n" - "\n" - " 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n" - "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n" - "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n" - "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n" - "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n" - "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n" - "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n" - "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n" - "POSSIBILITY OF SUCH DAMAGES.\n" - "\n" - " END OF TERMS AND CONDITIONS\n" - "\n" - " How to Apply These Terms to Your New Programs\n" - "\n" - " If you develop a new program, and you want it to be of the greatest\n" - "possible use to the public, the best way to achieve this is to make it\n" - "free software which everyone can redistribute and change under these terms.\n" - "\n" - " To do so, attach the following notices to the program. It is safest\n" - "to attach them to the start of each source file to most effectively\n" - "convey the exclusion of warranty; and each file should have at least\n" - "the \"copyright\" line and a pointer to where the full notice is found.\n" - "\n" - " <one line to give the program's name and a brief idea of what it does.>\n" - " Copyright (C) <year> <name of author>\n" - "\n" - " This program is free software; you can redistribute it and/or modify\n" - " it under the terms of the GNU General Public License as published by\n" - " the Free Software Foundation; either version 2 of the License, or\n" - " (at your option) any later version.\n" - "\n" - " This program is distributed in the hope that it will be useful,\n" - " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" - " GNU General Public License for more details.\n" - "\n" - " You should have received a copy of the GNU General Public License along\n" - " with this program; if not, write to the Free Software Foundation, Inc.,\n" - " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" - "\n" - "Also add information on how to contact you by electronic and paper mail.\n" - "\n" - "If the program is interactive, make it output a short notice like this\n" - "when it starts in an interactive mode:\n" - "\n" - " Gnomovision version 69, Copyright (C) year name of author\n" - " Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n" - " This is free software, and you are welcome to redistribute it\n" - " under certain conditions; type `show c' for details.\n" - "\n" - "The hypothetical commands `show w' and `show c' should show the appropriate\n" - "parts of the General Public License. Of course, the commands you use may\n" - "be called something other than `show w' and `show c'; they could even be\n" - "mouse-clicks or menu items--whatever suits your program.\n" - "\n" - "You should also get your employer (if you work as a programmer) or your\n" - "school, if any, to sign a \"copyright disclaimer\" for the program, if\n" - "necessary. Here is a sample; alter the names:\n" - "\n" - " Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n" - " `Gnomovision' (which makes passes at compilers) written by James Hacker.\n" - "\n" - " <signature of Ty Coon>, 1 April 1989\n" - " Ty Coon, President of Vice\n" - "\n" - "This General Public License does not permit incorporating your program into\n" - "proprietary programs. If your program is a subroutine library, you may\n" - "consider it more useful to permit linking proprietary applications with the\n" - "library. If this is what you want to do, use the GNU Lesser General\n" - "Public License instead of this License."; +static const char *licenseLibcap2 = "Unless otherwise *explicitly* stated, the following text describes the\n" + "licensed conditions under which the contents of this libcap release\n" + "may be used and distributed:\n" + "\n" + "-------------------------------------------------------------------------\n" + "Redistribution and use in source and binary forms of libcap, with\n" + "or without modification, are permitted provided that the following\n" + "conditions are met:\n" + "\n" + "1. Redistributions of source code must retain any existing copyright\n" + " notice, and this entire permission notice in its entirety,\n" + " including the disclaimer of warranties.\n" + "\n" + "2. Redistributions in binary form must reproduce all prior and current\n" + " copyright notices, this list of conditions, and the following\n" + " disclaimer in the documentation and/or other materials provided\n" + " with the distribution.\n" + "\n" + "3. The name of any author may not be used to endorse or promote\n" + " products derived from this software without their specific prior\n" + " written permission.\n" + "\n" + "ALTERNATIVELY, this product may be distributed under the terms of the\n" + "GNU General Public License (v2.0 - see below), in which case the\n" + "provisions of the GNU GPL are required INSTEAD OF the above\n" + "restrictions. (This clause is necessary due to a potential conflict\n" + "between the GNU GPL and the restrictions contained in a BSD-style\n" + "copyright.)\n" + "\n" + "THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED\n" + "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" + "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" + "IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,\n" + "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n" + "BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n" + "OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n" + "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n" + "TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n" + "USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n" + "DAMAGE.\n" + "-------------------------------------------------------------------------\n" + "\n" + "-------------------------\n" + "Full text of gpl-2.0.txt:\n" + "-------------------------\n" + "\n" + " GNU GENERAL PUBLIC LICENSE\n" + " Version 2, June 1991\n" + "\n" + " Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n" + " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" + " Everyone is permitted to copy and distribute verbatim copies\n" + " of this license document, but changing it is not allowed.\n" + "\n" + " Preamble\n" + "\n" + " The licenses for most software are designed to take away your\n" + "freedom to share and change it. By contrast, the GNU General Public\n" + "License is intended to guarantee your freedom to share and change free\n" + "software--to make sure the software is free for all its users. This\n" + "General Public License applies to most of the Free Software\n" + "Foundation's software and to any other program whose authors commit to\n" + "using it. (Some other Free Software Foundation software is covered by\n" + "the GNU Lesser General Public License instead.) You can apply it to\n" + "your programs, too.\n" + "\n" + " When we speak of free software, we are referring to freedom, not\n" + "price. Our General Public Licenses are designed to make sure that you\n" + "have the freedom to distribute copies of free software (and charge for\n" + "this service if you wish), that you receive source code or can get it\n" + "if you want it, that you can change the software or use pieces of it\n" + "in new free programs; and that you know you can do these things.\n" + "\n" + " To protect your rights, we need to make restrictions that forbid\n" + "anyone to deny you these rights or to ask you to surrender the rights.\n" + "These restrictions translate to certain responsibilities for you if you\n" + "distribute copies of the software, or if you modify it.\n" + "\n" + " For example, if you distribute copies of such a program, whether\n" + "gratis or for a fee, you must give the recipients all the rights that\n" + "you have. You must make sure that they, too, receive or can get the\n" + "source code. And you must show them these terms so they know their\n" + "rights.\n" + "\n" + " We protect your rights with two steps: (1) copyright the software, and\n" + "(2) offer you this license which gives you legal permission to copy,\n" + "distribute and/or modify the software.\n" + "\n" + " Also, for each author's protection and ours, we want to make certain\n" + "that everyone understands that there is no warranty for this free\n" + "software. If the software is modified by someone else and passed on, we\n" + "want its recipients to know that what they have is not the original, so\n" + "that any problems introduced by others will not reflect on the original\n" + "authors' reputations.\n" + "\n" + " Finally, any free program is threatened constantly by software\n" + "patents. We wish to avoid the danger that redistributors of a free\n" + "program will individually obtain patent licenses, in effect making the\n" + "program proprietary. To prevent this, we have made it clear that any\n" + "patent must be licensed for everyone's free use or not licensed at all.\n" + "\n" + " The precise terms and conditions for copying, distribution and\n" + "modification follow.\n" + "\n" + " GNU GENERAL PUBLIC LICENSE\n" + " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" + "\n" + " 0. This License applies to any program or other work which contains\n" + "a notice placed by the copyright holder saying it may be distributed\n" + "under the terms of this General Public License. The \"Program\", below,\n" + "refers to any such program or work, and a \"work based on the Program\"\n" + "means either the Program or any derivative work under copyright law:\n" + "that is to say, a work containing the Program or a portion of it,\n" + "either verbatim or with modifications and/or translated into another\n" + "language. (Hereinafter, translation is included without limitation in\n" + "the term \"modification\".) Each licensee is addressed as \"you\".\n" + "\n" + "Activities other than copying, distribution and modification are not\n" + "covered by this License; they are outside its scope. The act of\n" + "running the Program is not restricted, and the output from the Program\n" + "is covered only if its contents constitute a work based on the\n" + "Program (independent of having been made by running the Program).\n" + "Whether that is true depends on what the Program does.\n" + "\n" + " 1. You may copy and distribute verbatim copies of the Program's\n" + "source code as you receive it, in any medium, provided that you\n" + "conspicuously and appropriately publish on each copy an appropriate\n" + "copyright notice and disclaimer of warranty; keep intact all the\n" + "notices that refer to this License and to the absence of any warranty;\n" + "and give any other recipients of the Program a copy of this License\n" + "along with the Program.\n" + "\n" + "You may charge a fee for the physical act of transferring a copy, and\n" + "you may at your option offer warranty protection in exchange for a fee.\n" + "\n" + " 2. You may modify your copy or copies of the Program or any portion\n" + "of it, thus forming a work based on the Program, and copy and\n" + "distribute such modifications or work under the terms of Section 1\n" + "above, provided that you also meet all of these conditions:\n" + "\n" + " a) You must cause the modified files to carry prominent notices\n" + " stating that you changed the files and the date of any change.\n" + "\n" + " b) You must cause any work that you distribute or publish, that in\n" + " whole or in part contains or is derived from the Program or any\n" + " part thereof, to be licensed as a whole at no charge to all third\n" + " parties under the terms of this License.\n" + "\n" + " c) If the modified program normally reads commands interactively\n" + " when run, you must cause it, when started running for such\n" + " interactive use in the most ordinary way, to print or display an\n" + " announcement including an appropriate copyright notice and a\n" + " notice that there is no warranty (or else, saying that you provide\n" + " a warranty) and that users may redistribute the program under\n" + " these conditions, and telling the user how to view a copy of this\n" + " License. (Exception: if the Program itself is interactive but\n" + " does not normally print such an announcement, your work based on\n" + " the Program is not required to print an announcement.)\n" + "\n" + "These requirements apply to the modified work as a whole. If\n" + "identifiable sections of that work are not derived from the Program,\n" + "and can be reasonably considered independent and separate works in\n" + "themselves, then this License, and its terms, do not apply to those\n" + "sections when you distribute them as separate works. But when you\n" + "distribute the same sections as part of a whole which is a work based\n" + "on the Program, the distribution of the whole must be on the terms of\n" + "this License, whose permissions for other licensees extend to the\n" + "entire whole, and thus to each and every part regardless of who wrote it.\n" + "\n" + "Thus, it is not the intent of this section to claim rights or contest\n" + "your rights to work written entirely by you; rather, the intent is to\n" + "exercise the right to control the distribution of derivative or\n" + "collective works based on the Program.\n" + "\n" + "In addition, mere aggregation of another work not based on the Program\n" + "with the Program (or with a work based on the Program) on a volume of\n" + "a storage or distribution medium does not bring the other work under\n" + "the scope of this License.\n" + "\n" + " 3. You may copy and distribute the Program (or a work based on it,\n" + "under Section 2) in object code or executable form under the terms of\n" + "Sections 1 and 2 above provided that you also do one of the following:\n" + "\n" + " a) Accompany it with the complete corresponding machine-readable\n" + " source code, which must be distributed under the terms of Sections\n" + " 1 and 2 above on a medium customarily used for software interchange; or,\n" + "\n" + " b) Accompany it with a written offer, valid for at least three\n" + " years, to give any third party, for a charge no more than your\n" + " cost of physically performing source distribution, a complete\n" + " machine-readable copy of the corresponding source code, to be\n" + " distributed under the terms of Sections 1 and 2 above on a medium\n" + " customarily used for software interchange; or,\n" + "\n" + " c) Accompany it with the information you received as to the offer\n" + " to distribute corresponding source code. (This alternative is\n" + " allowed only for noncommercial distribution and only if you\n" + " received the program in object code or executable form with such\n" + " an offer, in accord with Subsection b above.)\n" + "\n" + "The source code for a work means the preferred form of the work for\n" + "making modifications to it. For an executable work, complete source\n" + "code means all the source code for all modules it contains, plus any\n" + "associated interface definition files, plus the scripts used to\n" + "control compilation and installation of the executable. However, as a\n" + "special exception, the source code distributed need not include\n" + "anything that is normally distributed (in either source or binary\n" + "form) with the major components (compiler, kernel, and so on) of the\n" + "operating system on which the executable runs, unless that component\n" + "itself accompanies the executable.\n" + "\n" + "If distribution of executable or object code is made by offering\n" + "access to copy from a designated place, then offering equivalent\n" + "access to copy the source code from the same place counts as\n" + "distribution of the source code, even though third parties are not\n" + "compelled to copy the source along with the object code.\n" + "\n" + " 4. You may not copy, modify, sublicense, or distribute the Program\n" + "except as expressly provided under this License. Any attempt\n" + "otherwise to copy, modify, sublicense or distribute the Program is\n" + "void, and will automatically terminate your rights under this License.\n" + "However, parties who have received copies, or rights, from you under\n" + "this License will not have their licenses terminated so long as such\n" + "parties remain in full compliance.\n" + "\n" + " 5. You are not required to accept this License, since you have not\n" + "signed it. However, nothing else grants you permission to modify or\n" + "distribute the Program or its derivative works. These actions are\n" + "prohibited by law if you do not accept this License. Therefore, by\n" + "modifying or distributing the Program (or any work based on the\n" + "Program), you indicate your acceptance of this License to do so, and\n" + "all its terms and conditions for copying, distributing or modifying\n" + "the Program or works based on it.\n" + "\n" + " 6. Each time you redistribute the Program (or any work based on the\n" + "Program), the recipient automatically receives a license from the\n" + "original licensor to copy, distribute or modify the Program subject to\n" + "these terms and conditions. You may not impose any further\n" + "restrictions on the recipients' exercise of the rights granted herein.\n" + "You are not responsible for enforcing compliance by third parties to\n" + "this License.\n" + "\n" + " 7. If, as a consequence of a court judgment or allegation of patent\n" + "infringement or for any other reason (not limited to patent issues),\n" + "conditions are imposed on you (whether by court order, agreement or\n" + "otherwise) that contradict the conditions of this License, they do not\n" + "excuse you from the conditions of this License. If you cannot\n" + "distribute so as to satisfy simultaneously your obligations under this\n" + "License and any other pertinent obligations, then as a consequence you\n" + "may not distribute the Program at all. For example, if a patent\n" + "license would not permit royalty-free redistribution of the Program by\n" + "all those who receive copies directly or indirectly through you, then\n" + "the only way you could satisfy both it and this License would be to\n" + "refrain entirely from distribution of the Program.\n" + "\n" + "If any portion of this section is held invalid or unenforceable under\n" + "any particular circumstance, the balance of the section is intended to\n" + "apply and the section as a whole is intended to apply in other\n" + "circumstances.\n" + "\n" + "It is not the purpose of this section to induce you to infringe any\n" + "patents or other property right claims or to contest validity of any\n" + "such claims; this section has the sole purpose of protecting the\n" + "integrity of the free software distribution system, which is\n" + "implemented by public license practices. Many people have made\n" + "generous contributions to the wide range of software distributed\n" + "through that system in reliance on consistent application of that\n" + "system; it is up to the author/donor to decide if he or she is willing\n" + "to distribute software through any other system and a licensee cannot\n" + "impose that choice.\n" + "\n" + "This section is intended to make thoroughly clear what is believed to\n" + "be a consequence of the rest of this License.\n" + "\n" + " 8. If the distribution and/or use of the Program is restricted in\n" + "certain countries either by patents or by copyrighted interfaces, the\n" + "original copyright holder who places the Program under this License\n" + "may add an explicit geographical distribution limitation excluding\n" + "those countries, so that distribution is permitted only in or among\n" + "countries not thus excluded. In such case, this License incorporates\n" + "the limitation as if written in the body of this License.\n" + "\n" + " 9. The Free Software Foundation may publish revised and/or new versions\n" + "of the General Public License from time to time. Such new versions will\n" + "be similar in spirit to the present version, but may differ in detail to\n" + "address new problems or concerns.\n" + "\n" + "Each version is given a distinguishing version number. If the Program\n" + "specifies a version number of this License which applies to it and \"any\n" + "later version\", you have the option of following the terms and conditions\n" + "either of that version or of any later version published by the Free\n" + "Software Foundation. If the Program does not specify a version number of\n" + "this License, you may choose any version ever published by the Free Software\n" + "Foundation.\n" + "\n" + " 10. If you wish to incorporate parts of the Program into other free\n" + "programs whose distribution conditions are different, write to the author\n" + "to ask for permission. For software which is copyrighted by the Free\n" + "Software Foundation, write to the Free Software Foundation; we sometimes\n" + "make exceptions for this. Our decision will be guided by the two goals\n" + "of preserving the free status of all derivatives of our free software and\n" + "of promoting the sharing and reuse of software generally.\n" + "\n" + " NO WARRANTY\n" + "\n" + " 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n" + "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN\n" + "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n" + "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n" + "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" + "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\n" + "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE\n" + "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n" + "REPAIR OR CORRECTION.\n" + "\n" + " 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n" + "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n" + "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n" + "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n" + "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n" + "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n" + "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n" + "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n" + "POSSIBILITY OF SUCH DAMAGES.\n" + "\n" + " END OF TERMS AND CONDITIONS\n" + "\n" + " How to Apply These Terms to Your New Programs\n" + "\n" + " If you develop a new program, and you want it to be of the greatest\n" + "possible use to the public, the best way to achieve this is to make it\n" + "free software which everyone can redistribute and change under these terms.\n" + "\n" + " To do so, attach the following notices to the program. It is safest\n" + "to attach them to the start of each source file to most effectively\n" + "convey the exclusion of warranty; and each file should have at least\n" + "the \"copyright\" line and a pointer to where the full notice is found.\n" + "\n" + " <one line to give the program's name and a brief idea of what it does.>\n" + " Copyright (C) <year> <name of author>\n" + "\n" + " This program is free software; you can redistribute it and/or modify\n" + " it under the terms of the GNU General Public License as published by\n" + " the Free Software Foundation; either version 2 of the License, or\n" + " (at your option) any later version.\n" + "\n" + " This program is distributed in the hope that it will be useful,\n" + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + " GNU General Public License for more details.\n" + "\n" + " You should have received a copy of the GNU General Public License along\n" + " with this program; if not, write to the Free Software Foundation, Inc.,\n" + " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" + "\n" + "Also add information on how to contact you by electronic and paper mail.\n" + "\n" + "If the program is interactive, make it output a short notice like this\n" + "when it starts in an interactive mode:\n" + "\n" + " Gnomovision version 69, Copyright (C) year name of author\n" + " Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n" + " This is free software, and you are welcome to redistribute it\n" + " under certain conditions; type `show c' for details.\n" + "\n" + "The hypothetical commands `show w' and `show c' should show the appropriate\n" + "parts of the General Public License. Of course, the commands you use may\n" + "be called something other than `show w' and `show c'; they could even be\n" + "mouse-clicks or menu items--whatever suits your program.\n" + "\n" + "You should also get your employer (if you work as a programmer) or your\n" + "school, if any, to sign a \"copyright disclaimer\" for the program, if\n" + "necessary. Here is a sample; alter the names:\n" + "\n" + " Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n" + " `Gnomovision' (which makes passes at compilers) written by James Hacker.\n" + "\n" + " <signature of Ty Coon>, 1 April 1989\n" + " Ty Coon, President of Vice\n" + "\n" + "This General Public License does not permit incorporating your program into\n" + "proprietary programs. If your program is a subroutine library, you may\n" + "consider it more useful to permit linking proprietary applications with the\n" + "library. If this is what you want to do, use the GNU Lesser General\n" + "Public License instead of this License."; #endif #ifdef USE_BUILDENV -static const char *licenseLibdaemon = - "Copyright 2003-2009 Lennart Poettering <mzqnrzba (at) 0pointer (dot) de>\n" - "\n" - "This program is free software; you can redistribute it and/or modify it\n" - "under the terms of the GNU Lesser General Public License as published\n" - "by the Free Software Foundation, either version 2.1 of the License, or\n" - "(at your option) any later version.\n" - "\n" - "This program is distributed in the hope that it will be useful, but\n" - "WITHOUT ANY WARRANTY; without even the implied warranty of\n" - "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser\n" - "General Public License for more details.\n" - "\n" - "\n" - " GNU LESSER GENERAL PUBLIC LICENSE\n" - " Version 2.1, February 1999\n" - "\n" - " Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n" - " 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n" - " Everyone is permitted to copy and distribute verbatim copies\n" - " of this license document, but changing it is not allowed.\n" - "\n" - "[This is the first released version of the Lesser GPL. It also counts\n" - " as the successor of the GNU Library Public License, version 2, hence\n" - " the version number 2.1.]\n" - "\n" - " Preamble\n" - "\n" - " The licenses for most software are designed to take away your\n" - "freedom to share and change it. By contrast, the GNU General Public\n" - "Licenses are intended to guarantee your freedom to share and change\n" - "free software--to make sure the software is free for all its users.\n" - "\n" - " This license, the Lesser General Public License, applies to some\n" - "specially designated software packages--typically libraries--of the\n" - "Free Software Foundation and other authors who decide to use it. You\n" - "can use it too, but we suggest you first think carefully about whether\n" - "this license or the ordinary General Public License is the better\n" - "strategy to use in any particular case, based on the explanations\n" - "below.\n" - "\n" - " When we speak of free software, we are referring to freedom of use,\n" - "not price. Our General Public Licenses are designed to make sure that\n" - "you have the freedom to distribute copies of free software (and charge\n" - "for this service if you wish); that you receive source code or can get\n" - "it if you want it; that you can change the software and use pieces of\n" - "it in new free programs; and that you are informed that you can do\n" - "these things.\n" - "\n" - " To protect your rights, we need to make restrictions that forbid\n" - "distributors to deny you these rights or to ask you to surrender these\n" - "rights. These restrictions translate to certain responsibilities for\n" - "you if you distribute copies of the library or if you modify it.\n" - "\n" - " For example, if you distribute copies of the library, whether gratis\n" - "or for a fee, you must give the recipients all the rights that we gave\n" - "you. You must make sure that they, too, receive or can get the source\n" - "code. If you link other code with the library, you must provide\n" - "complete object files to the recipients, so that they can relink them\n" - "with the library after making changes to the library and recompiling\n" - "it. And you must show them these terms so they know their rights.\n" - "\n" - " We protect your rights with a two-step method: (1) we copyright the\n" - "library, and (2) we offer you this license, which gives you legal\n" - "permission to copy, distribute and/or modify the library.\n" - "\n" - " To protect each distributor, we want to make it very clear that\n" - "there is no warranty for the free library. Also, if the library is\n" - "modified by someone else and passed on, the recipients should know\n" - "that what they have is not the original version, so that the original\n" - "author's reputation will not be affected by problems that might be\n" - "introduced by others.\n" - "\n" - " Finally, software patents pose a constant threat to the existence of\n" - "any free program. We wish to make sure that a company cannot\n" - "effectively restrict the users of a free program by obtaining a\n" - "restrictive license from a patent holder. Therefore, we insist that\n" - "any patent license obtained for a version of the library must be\n" - "consistent with the full freedom of use specified in this license.\n" - "\n" - " Most GNU software, including some libraries, is covered by the\n" - "ordinary GNU General Public License. This license, the GNU Lesser\n" - "General Public License, applies to certain designated libraries, and\n" - "is quite different from the ordinary General Public License. We use\n" - "this license for certain libraries in order to permit linking those\n" - "libraries into non-free programs.\n" - "\n" - " When a program is linked with a library, whether statically or using\n" - "a shared library, the combination of the two is legally speaking a\n" - "combined work, a derivative of the original library. The ordinary\n" - "General Public License therefore permits such linking only if the\n" - "entire combination fits its criteria of freedom. The Lesser General\n" - "Public License permits more lax criteria for linking other code with\n" - "the library.\n" - "\n" - " We call this license the \"Lesser\" General Public License because it\n" - "does Less to protect the user's freedom than the ordinary General\n" - "Public License. It also provides other free software developers Less\n" - "of an advantage over competing non-free programs. These disadvantages\n" - "are the reason we use the ordinary General Public License for many\n" - "libraries. However, the Lesser license provides advantages in certain\n" - "special circumstances.\n" - "\n" - " For example, on rare occasions, there may be a special need to\n" - "encourage the widest possible use of a certain library, so that it\n" - "becomes a de-facto standard. To achieve this, non-free programs must\n" - "be allowed to use the library. A more frequent case is that a free\n" - "library does the same job as widely used non-free libraries. In this\n" - "case, there is little to gain by limiting the free library to free\n" - "software only, so we use the Lesser General Public License.\n" - "\n" - " In other cases, permission to use a particular library in non-free\n" - "programs enables a greater number of people to use a large body of\n" - "free software. For example, permission to use the GNU C Library in\n" - "non-free programs enables many more people to use the whole GNU\n" - "operating system, as well as its variant, the GNU/Linux operating\n" - "system.\n" - "\n" - " Although the Lesser General Public License is Less protective of the\n" - "users' freedom, it does ensure that the user of a program that is\n" - "linked with the Library has the freedom and the wherewithal to run\n" - "that program using a modified version of the Library.\n" - "\n" - " The precise terms and conditions for copying, distribution and\n" - "modification follow. Pay close attention to the difference between a\n" - "\"work based on the library\" and a \"work that uses the library\". The\n" - "former contains code derived from the library, whereas the latter must\n" - "be combined with the library in order to run.\n" - "\n" - " GNU LESSER GENERAL PUBLIC LICENSE\n" - " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" - "\n" - " 0. This License Agreement applies to any software library or other\n" - "program which contains a notice placed by the copyright holder or\n" - "other authorized party saying it may be distributed under the terms of\n" - "this Lesser General Public License (also called \"this License\").\n" - "Each licensee is addressed as \"you\".\n" - "\n" - " A \"library\" means a collection of software functions and/or data\n" - "prepared so as to be conveniently linked with application programs\n" - "(which use some of those functions and data) to form executables.\n" - "\n" - " The \"Library\", below, refers to any such software library or work\n" - "which has been distributed under these terms. A \"work based on the\n" - "Library\" means either the Library or any derivative work under\n" - "copyright law: that is to say, a work containing the Library or a\n" - "portion of it, either verbatim or with modifications and/or translated\n" - "straightforwardly into another language. (Hereinafter, translation is\n" - "included without limitation in the term \"modification\".)\n" - "\n" - " \"Source code\" for a work means the preferred form of the work for\n" - "making modifications to it. For a library, complete source code means\n" - "all the source code for all modules it contains, plus any associated\n" - "interface definition files, plus the scripts used to control\n" - "compilation and installation of the library.\n" - "\n" - " Activities other than copying, distribution and modification are not\n" - "covered by this License; they are outside its scope. The act of\n" - "running a program using the Library is not restricted, and output from\n" - "such a program is covered only if its contents constitute a work based\n" - "on the Library (independent of the use of the Library in a tool for\n" - "writing it). Whether that is true depends on what the Library does\n" - "and what the program that uses the Library does.\n" - "\n" - " 1. You may copy and distribute verbatim copies of the Library's\n" - "complete source code as you receive it, in any medium, provided that\n" - "you conspicuously and appropriately publish on each copy an\n" - "appropriate copyright notice and disclaimer of warranty; keep intact\n" - "all the notices that refer to this License and to the absence of any\n" - "warranty; and distribute a copy of this License along with the\n" - "Library.\n" - "\n" - " You may charge a fee for the physical act of transferring a copy,\n" - "and you may at your option offer warranty protection in exchange for a\n" - "fee.\n" - "\n" - " 2. You may modify your copy or copies of the Library or any portion\n" - "of it, thus forming a work based on the Library, and copy and\n" - "distribute such modifications or work under the terms of Section 1\n" - "above, provided that you also meet all of these conditions:\n" - "\n" - " a) The modified work must itself be a software library.\n" - "\n" - " b) You must cause the files modified to carry prominent notices\n" - " stating that you changed the files and the date of any change.\n" - "\n" - " c) You must cause the whole of the work to be licensed at no\n" - " charge to all third parties under the terms of this License.\n" - "\n" - " d) If a facility in the modified Library refers to a function or a\n" - " table of data to be supplied by an application program that uses\n" - " the facility, other than as an argument passed when the facility\n" - " is invoked, then you must make a good faith effort to ensure that,\n" - " in the event an application does not supply such function or\n" - " table, the facility still operates, and performs whatever part of\n" - " its purpose remains meaningful.\n" - "\n" - " (For example, a function in a library to compute square roots has\n" - " a purpose that is entirely well-defined independent of the\n" - " application. Therefore, Subsection 2d requires that any\n" - " application-supplied function or table used by this function must\n" - " be optional: if the application does not supply it, the square\n" - " root function must still compute square roots.)\n" - "\n" - "These requirements apply to the modified work as a whole. If\n" - "identifiable sections of that work are not derived from the Library,\n" - "and can be reasonably considered independent and separate works in\n" - "themselves, then this License, and its terms, do not apply to those\n" - "sections when you distribute them as separate works. But when you\n" - "distribute the same sections as part of a whole which is a work based\n" - "on the Library, the distribution of the whole must be on the terms of\n" - "this License, whose permissions for other licensees extend to the\n" - "entire whole, and thus to each and every part regardless of who wrote\n" - "it.\n" - "\n" - "Thus, it is not the intent of this section to claim rights or contest\n" - "your rights to work written entirely by you; rather, the intent is to\n" - "exercise the right to control the distribution of derivative or\n" - "collective works based on the Library.\n" - "\n" - "In addition, mere aggregation of another work not based on the Library\n" - "with the Library (or with a work based on the Library) on a volume of\n" - "a storage or distribution medium does not bring the other work under\n" - "the scope of this License.\n" - "\n" - " 3. You may opt to apply the terms of the ordinary GNU General Public\n" - "License instead of this License to a given copy of the Library. To do\n" - "this, you must alter all the notices that refer to this License, so\n" - "that they refer to the ordinary GNU General Public License, version 2,\n" - "instead of to this License. (If a newer version than version 2 of the\n" - "ordinary GNU General Public License has appeared, then you can specify\n" - "that version instead if you wish.) Do not make any other change in\n" - "these notices.\n" - "\n" - " Once this change is made in a given copy, it is irreversible for\n" - "that copy, so the ordinary GNU General Public License applies to all\n" - "subsequent copies and derivative works made from that copy.\n" - "\n" - " This option is useful when you wish to copy part of the code of\n" - "the Library into a program that is not a library.\n" - "\n" - " 4. You may copy and distribute the Library (or a portion or\n" - "derivative of it, under Section 2) in object code or executable form\n" - "under the terms of Sections 1 and 2 above provided that you accompany\n" - "it with the complete corresponding machine-readable source code, which\n" - "must be distributed under the terms of Sections 1 and 2 above on a\n" - "medium customarily used for software interchange.\n" - "\n" - " If distribution of object code is made by offering access to copy\n" - "from a designated place, then offering equivalent access to copy the\n" - "source code from the same place satisfies the requirement to\n" - "distribute the source code, even though third parties are not\n" - "compelled to copy the source along with the object code.\n" - "\n" - " 5. A program that contains no derivative of any portion of the\n" - "Library, but is designed to work with the Library by being compiled or\n" - "linked with it, is called a \"work that uses the Library\". Such a\n" - "work, in isolation, is not a derivative work of the Library, and\n" - "therefore falls outside the scope of this License.\n" - "\n" - " However, linking a \"work that uses the Library\" with the Library\n" - "creates an executable that is a derivative of the Library (because it\n" - "contains portions of the Library), rather than a \"work that uses the\n" - "library\". The executable is therefore covered by this License.\n" - "Section 6 states terms for distribution of such executables.\n" - "\n" - " When a \"work that uses the Library\" uses material from a header file\n" - "that is part of the Library, the object code for the work may be a\n" - "derivative work of the Library even though the source code is not.\n" - "Whether this is true is especially significant if the work can be\n" - "linked without the Library, or if the work is itself a library. The\n" - "threshold for this to be true is not precisely defined by law.\n" - "\n" - " If such an object file uses only numerical parameters, data\n" - "structure layouts and accessors, and small macros and small inline\n" - "functions (ten lines or less in length), then the use of the object\n" - "file is unrestricted, regardless of whether it is legally a derivative\n" - "work. (Executables containing this object code plus portions of the\n" - "Library will still fall under Section 6.)\n" - "\n" - " Otherwise, if the work is a derivative of the Library, you may\n" - "distribute the object code for the work under the terms of Section 6.\n" - "Any executables containing that work also fall under Section 6,\n" - "whether or not they are linked directly with the Library itself.\n" - "\n" - " 6. As an exception to the Sections above, you may also combine or\n" - "link a \"work that uses the Library\" with the Library to produce a\n" - "work containing portions of the Library, and distribute that work\n" - "under terms of your choice, provided that the terms permit\n" - "modification of the work for the customer's own use and reverse\n" - "engineering for debugging such modifications.\n" - "\n" - " You must give prominent notice with each copy of the work that the\n" - "Library is used in it and that the Library and its use are covered by\n" - "this License. You must supply a copy of this License. If the work\n" - "during execution displays copyright notices, you must include the\n" - "copyright notice for the Library among them, as well as a reference\n" - "directing the user to the copy of this License. Also, you must do one\n" - "of these things:\n" - "\n" - " a) Accompany the work with the complete corresponding\n" - " machine-readable source code for the Library including whatever\n" - " changes were used in the work (which must be distributed under\n" - " Sections 1 and 2 above); and, if the work is an executable linked\n" - " with the Library, with the complete machine-readable \"work that\n" - " uses the Library\", as object code and/or source code, so that the\n" - " user can modify the Library and then relink to produce a modified\n" - " executable containing the modified Library. (It is understood\n" - " that the user who changes the contents of definitions files in the\n" - " Library will not necessarily be able to recompile the application\n" - " to use the modified definitions.)\n" - "\n" - " b) Use a suitable shared library mechanism for linking with the\n" - " Library. A suitable mechanism is one that (1) uses at run time a\n" - " copy of the library already present on the user's computer system,\n" - " rather than copying library functions into the executable, and (2)\n" - " will operate properly with a modified version of the library, if\n" - " the user installs one, as long as the modified version is\n" - " interface-compatible with the version that the work was made with.\n" - "\n" - " c) Accompany the work with a written offer, valid for at least\n" - " three years, to give the same user the materials specified in\n" - " Subsection 6a, above, for a charge no more than the cost of\n" - " performing this distribution.\n" - "\n" - " d) If distribution of the work is made by offering access to copy\n" - " from a designated place, offer equivalent access to copy the above\n" - " specified materials from the same place.\n" - "\n" - " e) Verify that the user has already received a copy of these\n" - " materials or that you have already sent this user a copy.\n" - "\n" - " For an executable, the required form of the \"work that uses the\n" - "Library\" must include any data and utility programs needed for\n" - "reproducing the executable from it. However, as a special exception,\n" - "the materials to be distributed need not include anything that is\n" - "normally distributed (in either source or binary form) with the major\n" - "components (compiler, kernel, and so on) of the operating system on\n" - "which the executable runs, unless that component itself accompanies\n" - "the executable.\n" - "\n" - " It may happen that this requirement contradicts the license\n" - "restrictions of other proprietary libraries that do not normally\n" - "accompany the operating system. Such a contradiction means you cannot\n" - "use both them and the Library together in an executable that you\n" - "distribute.\n" - "\n" - " 7. You may place library facilities that are a work based on the\n" - "Library side-by-side in a single library together with other library\n" - "facilities not covered by this License, and distribute such a combined\n" - "library, provided that the separate distribution of the work based on\n" - "the Library and of the other library facilities is otherwise\n" - "permitted, and provided that you do these two things:\n" - "\n" - " a) Accompany the combined library with a copy of the same work\n" - " based on the Library, uncombined with any other library\n" - " facilities. This must be distributed under the terms of the\n" - " Sections above.\n" - "\n" - " b) Give prominent notice with the combined library of the fact\n" - " that part of it is a work based on the Library, and explaining\n" - " where to find the accompanying uncombined form of the same work.\n" - "\n" - " 8. You may not copy, modify, sublicense, link with, or distribute\n" - "the Library except as expressly provided under this License. Any\n" - "attempt otherwise to copy, modify, sublicense, link with, or\n" - "distribute the Library is void, and will automatically terminate your\n" - "rights under this License. However, parties who have received copies,\n" - "or rights, from you under this License will not have their licenses\n" - "terminated so long as such parties remain in full compliance.\n" - "\n" - " 9. You are not required to accept this License, since you have not\n" - "signed it. However, nothing else grants you permission to modify or\n" - "distribute the Library or its derivative works. These actions are\n" - "prohibited by law if you do not accept this License. Therefore, by\n" - "modifying or distributing the Library (or any work based on the\n" - "Library), you indicate your acceptance of this License to do so, and\n" - "all its terms and conditions for copying, distributing or modifying\n" - "the Library or works based on it.\n" - "\n" - " 10. Each time you redistribute the Library (or any work based on the\n" - "Library), the recipient automatically receives a license from the\n" - "original licensor to copy, distribute, link with or modify the Library\n" - "subject to these terms and conditions. You may not impose any further\n" - "restrictions on the recipients' exercise of the rights granted herein.\n" - "You are not responsible for enforcing compliance by third parties with\n" - "this License.\n" - "\n" - " 11. If, as a consequence of a court judgment or allegation of patent\n" - "infringement or for any other reason (not limited to patent issues),\n" - "conditions are imposed on you (whether by court order, agreement or\n" - "otherwise) that contradict the conditions of this License, they do not\n" - "excuse you from the conditions of this License. If you cannot\n" - "distribute so as to satisfy simultaneously your obligations under this\n" - "License and any other pertinent obligations, then as a consequence you\n" - "may not distribute the Library at all. For example, if a patent\n" - "license would not permit royalty-free redistribution of the Library by\n" - "all those who receive copies directly or indirectly through you, then\n" - "the only way you could satisfy both it and this License would be to\n" - "refrain entirely from distribution of the Library.\n" - "\n" - "If any portion of this section is held invalid or unenforceable under\n" - "any particular circumstance, the balance of the section is intended to\n" - "apply, and the section as a whole is intended to apply in other\n" - "circumstances.\n" - "\n" - "It is not the purpose of this section to induce you to infringe any\n" - "patents or other property right claims or to contest validity of any\n" - "such claims; this section has the sole purpose of protecting the\n" - "integrity of the free software distribution system which is\n" - "implemented by public license practices. Many people have made\n" - "generous contributions to the wide range of software distributed\n" - "through that system in reliance on consistent application of that\n" - "system; it is up to the author/donor to decide if he or she is willing\n" - "to distribute software through any other system and a licensee cannot\n" - "impose that choice.\n" - "\n" - "This section is intended to make thoroughly clear what is believed to\n" - "be a consequence of the rest of this License.\n" - "\n" - " 12. If the distribution and/or use of the Library is restricted in\n" - "certain countries either by patents or by copyrighted interfaces, the\n" - "original copyright holder who places the Library under this License\n" - "may add an explicit geographical distribution limitation excluding those\n" - "countries, so that distribution is permitted only in or among\n" - "countries not thus excluded. In such case, this License incorporates\n" - "the limitation as if written in the body of this License.\n" - "\n" - " 13. The Free Software Foundation may publish revised and/or new\n" - "versions of the Lesser General Public License from time to time.\n" - "Such new versions will be similar in spirit to the present version,\n" - "but may differ in detail to address new problems or concerns.\n" - "\n" - "Each version is given a distinguishing version number. If the Library\n" - "specifies a version number of this License which applies to it and\n" - "\"any later version\", you have the option of following the terms and\n" - "conditions either of that version or of any later version published by\n" - "the Free Software Foundation. If the Library does not specify a\n" - "license version number, you may choose any version ever published by\n" - "the Free Software Foundation.\n" - "\n" - " 14. If you wish to incorporate parts of the Library into other free\n" - "programs whose distribution conditions are incompatible with these,\n" - "write to the author to ask for permission. For software which is\n" - "copyrighted by the Free Software Foundation, write to the Free\n" - "Software Foundation; we sometimes make exceptions for this. Our\n" - "decision will be guided by the two goals of preserving the free status\n" - "of all derivatives of our free software and of promoting the sharing\n" - "and reuse of software generally.\n" - "\n" - " NO WARRANTY\n" - "\n" - " 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\n" - "WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\n" - "EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\n" - "OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\n" - "KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\n" - "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" - "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\n" - "LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\n" - "THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n" - "\n" - " 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\n" - "WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\n" - "AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\n" - "FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\n" - "CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\n" - "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\n" - "RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\n" - "FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\n" - "SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n" - "DAMAGES.\n" - "\n" - " END OF TERMS AND CONDITIONS\n" - "\n" - " How to Apply These Terms to Your New Libraries\n" - "\n" - " If you develop a new library, and you want it to be of the greatest\n" - "possible use to the public, we recommend making it free software that\n" - "everyone can redistribute and change. You can do so by permitting\n" - "redistribution under these terms (or, alternatively, under the terms\n" - "of the ordinary General Public License).\n" - "\n" - " To apply these terms, attach the following notices to the library.\n" - "It is safest to attach them to the start of each source file to most\n" - "effectively convey the exclusion of warranty; and each file should\n" - "have at least the \"copyright\" line and a pointer to where the full\n" - "notice is found.\n" - "\n" - "\n" - " <one line to give the library's name and a brief idea of what it does.>\n" - " Copyright (C) <year> <name of author>\n" - "\n" - " This library is free software; you can redistribute it and/or\n" - " modify it under the terms of the GNU Lesser General Public\n" - " License as published by the Free Software Foundation; either\n" - " version 2.1 of the License, or (at your option) any later version.\n" - "\n" - " This library is distributed in the hope that it will be useful,\n" - " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" - " Lesser General Public License for more details.\n" - "\n" - " You should have received a copy of the GNU Lesser General Public\n" - " License along with this library; if not, write to the Free Software\n" - " Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n" - "\n" - "Also add information on how to contact you by electronic and paper mail.\n" - "\n" - "You should also get your employer (if you work as a programmer) or\n" - "your school, if any, to sign a \"copyright disclaimer\" for the library,\n" - "if necessary. Here is a sample; alter the names:\n" - "\n" - " Yoyodyne, Inc., hereby disclaims all copyright interest in the\n" - " library `Frob' (a library for tweaking knobs) written by James\n" - " Random Hacker.\n" - "\n" - " <signature of Ty Coon>, 1 April 1990\n" - " Ty Coon, President of Vice\n" - "\n" - "That's all there is to it!"; +static const char *licenseLibdaemon = "Copyright 2003-2009 Lennart Poettering <mzqnrzba (at) 0pointer (dot) de>\n" + "\n" + "This program is free software; you can redistribute it and/or modify it\n" + "under the terms of the GNU Lesser General Public License as published\n" + "by the Free Software Foundation, either version 2.1 of the License, or\n" + "(at your option) any later version.\n" + "\n" + "This program is distributed in the hope that it will be useful, but\n" + "WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser\n" + "General Public License for more details.\n" + "\n" + "\n" + " GNU LESSER GENERAL PUBLIC LICENSE\n" + " Version 2.1, February 1999\n" + "\n" + " Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n" + " 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n" + " Everyone is permitted to copy and distribute verbatim copies\n" + " of this license document, but changing it is not allowed.\n" + "\n" + "[This is the first released version of the Lesser GPL. It also counts\n" + " as the successor of the GNU Library Public License, version 2, hence\n" + " the version number 2.1.]\n" + "\n" + " Preamble\n" + "\n" + " The licenses for most software are designed to take away your\n" + "freedom to share and change it. By contrast, the GNU General Public\n" + "Licenses are intended to guarantee your freedom to share and change\n" + "free software--to make sure the software is free for all its users.\n" + "\n" + " This license, the Lesser General Public License, applies to some\n" + "specially designated software packages--typically libraries--of the\n" + "Free Software Foundation and other authors who decide to use it. You\n" + "can use it too, but we suggest you first think carefully about whether\n" + "this license or the ordinary General Public License is the better\n" + "strategy to use in any particular case, based on the explanations\n" + "below.\n" + "\n" + " When we speak of free software, we are referring to freedom of use,\n" + "not price. Our General Public Licenses are designed to make sure that\n" + "you have the freedom to distribute copies of free software (and charge\n" + "for this service if you wish); that you receive source code or can get\n" + "it if you want it; that you can change the software and use pieces of\n" + "it in new free programs; and that you are informed that you can do\n" + "these things.\n" + "\n" + " To protect your rights, we need to make restrictions that forbid\n" + "distributors to deny you these rights or to ask you to surrender these\n" + "rights. These restrictions translate to certain responsibilities for\n" + "you if you distribute copies of the library or if you modify it.\n" + "\n" + " For example, if you distribute copies of the library, whether gratis\n" + "or for a fee, you must give the recipients all the rights that we gave\n" + "you. You must make sure that they, too, receive or can get the source\n" + "code. If you link other code with the library, you must provide\n" + "complete object files to the recipients, so that they can relink them\n" + "with the library after making changes to the library and recompiling\n" + "it. And you must show them these terms so they know their rights.\n" + "\n" + " We protect your rights with a two-step method: (1) we copyright the\n" + "library, and (2) we offer you this license, which gives you legal\n" + "permission to copy, distribute and/or modify the library.\n" + "\n" + " To protect each distributor, we want to make it very clear that\n" + "there is no warranty for the free library. Also, if the library is\n" + "modified by someone else and passed on, the recipients should know\n" + "that what they have is not the original version, so that the original\n" + "author's reputation will not be affected by problems that might be\n" + "introduced by others.\n" + "\n" + " Finally, software patents pose a constant threat to the existence of\n" + "any free program. We wish to make sure that a company cannot\n" + "effectively restrict the users of a free program by obtaining a\n" + "restrictive license from a patent holder. Therefore, we insist that\n" + "any patent license obtained for a version of the library must be\n" + "consistent with the full freedom of use specified in this license.\n" + "\n" + " Most GNU software, including some libraries, is covered by the\n" + "ordinary GNU General Public License. This license, the GNU Lesser\n" + "General Public License, applies to certain designated libraries, and\n" + "is quite different from the ordinary General Public License. We use\n" + "this license for certain libraries in order to permit linking those\n" + "libraries into non-free programs.\n" + "\n" + " When a program is linked with a library, whether statically or using\n" + "a shared library, the combination of the two is legally speaking a\n" + "combined work, a derivative of the original library. The ordinary\n" + "General Public License therefore permits such linking only if the\n" + "entire combination fits its criteria of freedom. The Lesser General\n" + "Public License permits more lax criteria for linking other code with\n" + "the library.\n" + "\n" + " We call this license the \"Lesser\" General Public License because it\n" + "does Less to protect the user's freedom than the ordinary General\n" + "Public License. It also provides other free software developers Less\n" + "of an advantage over competing non-free programs. These disadvantages\n" + "are the reason we use the ordinary General Public License for many\n" + "libraries. However, the Lesser license provides advantages in certain\n" + "special circumstances.\n" + "\n" + " For example, on rare occasions, there may be a special need to\n" + "encourage the widest possible use of a certain library, so that it\n" + "becomes a de-facto standard. To achieve this, non-free programs must\n" + "be allowed to use the library. A more frequent case is that a free\n" + "library does the same job as widely used non-free libraries. In this\n" + "case, there is little to gain by limiting the free library to free\n" + "software only, so we use the Lesser General Public License.\n" + "\n" + " In other cases, permission to use a particular library in non-free\n" + "programs enables a greater number of people to use a large body of\n" + "free software. For example, permission to use the GNU C Library in\n" + "non-free programs enables many more people to use the whole GNU\n" + "operating system, as well as its variant, the GNU/Linux operating\n" + "system.\n" + "\n" + " Although the Lesser General Public License is Less protective of the\n" + "users' freedom, it does ensure that the user of a program that is\n" + "linked with the Library has the freedom and the wherewithal to run\n" + "that program using a modified version of the Library.\n" + "\n" + " The precise terms and conditions for copying, distribution and\n" + "modification follow. Pay close attention to the difference between a\n" + "\"work based on the library\" and a \"work that uses the library\". The\n" + "former contains code derived from the library, whereas the latter must\n" + "be combined with the library in order to run.\n" + "\n" + " GNU LESSER GENERAL PUBLIC LICENSE\n" + " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" + "\n" + " 0. This License Agreement applies to any software library or other\n" + "program which contains a notice placed by the copyright holder or\n" + "other authorized party saying it may be distributed under the terms of\n" + "this Lesser General Public License (also called \"this License\").\n" + "Each licensee is addressed as \"you\".\n" + "\n" + " A \"library\" means a collection of software functions and/or data\n" + "prepared so as to be conveniently linked with application programs\n" + "(which use some of those functions and data) to form executables.\n" + "\n" + " The \"Library\", below, refers to any such software library or work\n" + "which has been distributed under these terms. A \"work based on the\n" + "Library\" means either the Library or any derivative work under\n" + "copyright law: that is to say, a work containing the Library or a\n" + "portion of it, either verbatim or with modifications and/or translated\n" + "straightforwardly into another language. (Hereinafter, translation is\n" + "included without limitation in the term \"modification\".)\n" + "\n" + " \"Source code\" for a work means the preferred form of the work for\n" + "making modifications to it. For a library, complete source code means\n" + "all the source code for all modules it contains, plus any associated\n" + "interface definition files, plus the scripts used to control\n" + "compilation and installation of the library.\n" + "\n" + " Activities other than copying, distribution and modification are not\n" + "covered by this License; they are outside its scope. The act of\n" + "running a program using the Library is not restricted, and output from\n" + "such a program is covered only if its contents constitute a work based\n" + "on the Library (independent of the use of the Library in a tool for\n" + "writing it). Whether that is true depends on what the Library does\n" + "and what the program that uses the Library does.\n" + "\n" + " 1. You may copy and distribute verbatim copies of the Library's\n" + "complete source code as you receive it, in any medium, provided that\n" + "you conspicuously and appropriately publish on each copy an\n" + "appropriate copyright notice and disclaimer of warranty; keep intact\n" + "all the notices that refer to this License and to the absence of any\n" + "warranty; and distribute a copy of this License along with the\n" + "Library.\n" + "\n" + " You may charge a fee for the physical act of transferring a copy,\n" + "and you may at your option offer warranty protection in exchange for a\n" + "fee.\n" + "\n" + " 2. You may modify your copy or copies of the Library or any portion\n" + "of it, thus forming a work based on the Library, and copy and\n" + "distribute such modifications or work under the terms of Section 1\n" + "above, provided that you also meet all of these conditions:\n" + "\n" + " a) The modified work must itself be a software library.\n" + "\n" + " b) You must cause the files modified to carry prominent notices\n" + " stating that you changed the files and the date of any change.\n" + "\n" + " c) You must cause the whole of the work to be licensed at no\n" + " charge to all third parties under the terms of this License.\n" + "\n" + " d) If a facility in the modified Library refers to a function or a\n" + " table of data to be supplied by an application program that uses\n" + " the facility, other than as an argument passed when the facility\n" + " is invoked, then you must make a good faith effort to ensure that,\n" + " in the event an application does not supply such function or\n" + " table, the facility still operates, and performs whatever part of\n" + " its purpose remains meaningful.\n" + "\n" + " (For example, a function in a library to compute square roots has\n" + " a purpose that is entirely well-defined independent of the\n" + " application. Therefore, Subsection 2d requires that any\n" + " application-supplied function or table used by this function must\n" + " be optional: if the application does not supply it, the square\n" + " root function must still compute square roots.)\n" + "\n" + "These requirements apply to the modified work as a whole. If\n" + "identifiable sections of that work are not derived from the Library,\n" + "and can be reasonably considered independent and separate works in\n" + "themselves, then this License, and its terms, do not apply to those\n" + "sections when you distribute them as separate works. But when you\n" + "distribute the same sections as part of a whole which is a work based\n" + "on the Library, the distribution of the whole must be on the terms of\n" + "this License, whose permissions for other licensees extend to the\n" + "entire whole, and thus to each and every part regardless of who wrote\n" + "it.\n" + "\n" + "Thus, it is not the intent of this section to claim rights or contest\n" + "your rights to work written entirely by you; rather, the intent is to\n" + "exercise the right to control the distribution of derivative or\n" + "collective works based on the Library.\n" + "\n" + "In addition, mere aggregation of another work not based on the Library\n" + "with the Library (or with a work based on the Library) on a volume of\n" + "a storage or distribution medium does not bring the other work under\n" + "the scope of this License.\n" + "\n" + " 3. You may opt to apply the terms of the ordinary GNU General Public\n" + "License instead of this License to a given copy of the Library. To do\n" + "this, you must alter all the notices that refer to this License, so\n" + "that they refer to the ordinary GNU General Public License, version 2,\n" + "instead of to this License. (If a newer version than version 2 of the\n" + "ordinary GNU General Public License has appeared, then you can specify\n" + "that version instead if you wish.) Do not make any other change in\n" + "these notices.\n" + "\n" + " Once this change is made in a given copy, it is irreversible for\n" + "that copy, so the ordinary GNU General Public License applies to all\n" + "subsequent copies and derivative works made from that copy.\n" + "\n" + " This option is useful when you wish to copy part of the code of\n" + "the Library into a program that is not a library.\n" + "\n" + " 4. You may copy and distribute the Library (or a portion or\n" + "derivative of it, under Section 2) in object code or executable form\n" + "under the terms of Sections 1 and 2 above provided that you accompany\n" + "it with the complete corresponding machine-readable source code, which\n" + "must be distributed under the terms of Sections 1 and 2 above on a\n" + "medium customarily used for software interchange.\n" + "\n" + " If distribution of object code is made by offering access to copy\n" + "from a designated place, then offering equivalent access to copy the\n" + "source code from the same place satisfies the requirement to\n" + "distribute the source code, even though third parties are not\n" + "compelled to copy the source along with the object code.\n" + "\n" + " 5. A program that contains no derivative of any portion of the\n" + "Library, but is designed to work with the Library by being compiled or\n" + "linked with it, is called a \"work that uses the Library\". Such a\n" + "work, in isolation, is not a derivative work of the Library, and\n" + "therefore falls outside the scope of this License.\n" + "\n" + " However, linking a \"work that uses the Library\" with the Library\n" + "creates an executable that is a derivative of the Library (because it\n" + "contains portions of the Library), rather than a \"work that uses the\n" + "library\". The executable is therefore covered by this License.\n" + "Section 6 states terms for distribution of such executables.\n" + "\n" + " When a \"work that uses the Library\" uses material from a header file\n" + "that is part of the Library, the object code for the work may be a\n" + "derivative work of the Library even though the source code is not.\n" + "Whether this is true is especially significant if the work can be\n" + "linked without the Library, or if the work is itself a library. The\n" + "threshold for this to be true is not precisely defined by law.\n" + "\n" + " If such an object file uses only numerical parameters, data\n" + "structure layouts and accessors, and small macros and small inline\n" + "functions (ten lines or less in length), then the use of the object\n" + "file is unrestricted, regardless of whether it is legally a derivative\n" + "work. (Executables containing this object code plus portions of the\n" + "Library will still fall under Section 6.)\n" + "\n" + " Otherwise, if the work is a derivative of the Library, you may\n" + "distribute the object code for the work under the terms of Section 6.\n" + "Any executables containing that work also fall under Section 6,\n" + "whether or not they are linked directly with the Library itself.\n" + "\n" + " 6. As an exception to the Sections above, you may also combine or\n" + "link a \"work that uses the Library\" with the Library to produce a\n" + "work containing portions of the Library, and distribute that work\n" + "under terms of your choice, provided that the terms permit\n" + "modification of the work for the customer's own use and reverse\n" + "engineering for debugging such modifications.\n" + "\n" + " You must give prominent notice with each copy of the work that the\n" + "Library is used in it and that the Library and its use are covered by\n" + "this License. You must supply a copy of this License. If the work\n" + "during execution displays copyright notices, you must include the\n" + "copyright notice for the Library among them, as well as a reference\n" + "directing the user to the copy of this License. Also, you must do one\n" + "of these things:\n" + "\n" + " a) Accompany the work with the complete corresponding\n" + " machine-readable source code for the Library including whatever\n" + " changes were used in the work (which must be distributed under\n" + " Sections 1 and 2 above); and, if the work is an executable linked\n" + " with the Library, with the complete machine-readable \"work that\n" + " uses the Library\", as object code and/or source code, so that the\n" + " user can modify the Library and then relink to produce a modified\n" + " executable containing the modified Library. (It is understood\n" + " that the user who changes the contents of definitions files in the\n" + " Library will not necessarily be able to recompile the application\n" + " to use the modified definitions.)\n" + "\n" + " b) Use a suitable shared library mechanism for linking with the\n" + " Library. A suitable mechanism is one that (1) uses at run time a\n" + " copy of the library already present on the user's computer system,\n" + " rather than copying library functions into the executable, and (2)\n" + " will operate properly with a modified version of the library, if\n" + " the user installs one, as long as the modified version is\n" + " interface-compatible with the version that the work was made with.\n" + "\n" + " c) Accompany the work with a written offer, valid for at least\n" + " three years, to give the same user the materials specified in\n" + " Subsection 6a, above, for a charge no more than the cost of\n" + " performing this distribution.\n" + "\n" + " d) If distribution of the work is made by offering access to copy\n" + " from a designated place, offer equivalent access to copy the above\n" + " specified materials from the same place.\n" + "\n" + " e) Verify that the user has already received a copy of these\n" + " materials or that you have already sent this user a copy.\n" + "\n" + " For an executable, the required form of the \"work that uses the\n" + "Library\" must include any data and utility programs needed for\n" + "reproducing the executable from it. However, as a special exception,\n" + "the materials to be distributed need not include anything that is\n" + "normally distributed (in either source or binary form) with the major\n" + "components (compiler, kernel, and so on) of the operating system on\n" + "which the executable runs, unless that component itself accompanies\n" + "the executable.\n" + "\n" + " It may happen that this requirement contradicts the license\n" + "restrictions of other proprietary libraries that do not normally\n" + "accompany the operating system. Such a contradiction means you cannot\n" + "use both them and the Library together in an executable that you\n" + "distribute.\n" + "\n" + " 7. You may place library facilities that are a work based on the\n" + "Library side-by-side in a single library together with other library\n" + "facilities not covered by this License, and distribute such a combined\n" + "library, provided that the separate distribution of the work based on\n" + "the Library and of the other library facilities is otherwise\n" + "permitted, and provided that you do these two things:\n" + "\n" + " a) Accompany the combined library with a copy of the same work\n" + " based on the Library, uncombined with any other library\n" + " facilities. This must be distributed under the terms of the\n" + " Sections above.\n" + "\n" + " b) Give prominent notice with the combined library of the fact\n" + " that part of it is a work based on the Library, and explaining\n" + " where to find the accompanying uncombined form of the same work.\n" + "\n" + " 8. You may not copy, modify, sublicense, link with, or distribute\n" + "the Library except as expressly provided under this License. Any\n" + "attempt otherwise to copy, modify, sublicense, link with, or\n" + "distribute the Library is void, and will automatically terminate your\n" + "rights under this License. However, parties who have received copies,\n" + "or rights, from you under this License will not have their licenses\n" + "terminated so long as such parties remain in full compliance.\n" + "\n" + " 9. You are not required to accept this License, since you have not\n" + "signed it. However, nothing else grants you permission to modify or\n" + "distribute the Library or its derivative works. These actions are\n" + "prohibited by law if you do not accept this License. Therefore, by\n" + "modifying or distributing the Library (or any work based on the\n" + "Library), you indicate your acceptance of this License to do so, and\n" + "all its terms and conditions for copying, distributing or modifying\n" + "the Library or works based on it.\n" + "\n" + " 10. Each time you redistribute the Library (or any work based on the\n" + "Library), the recipient automatically receives a license from the\n" + "original licensor to copy, distribute, link with or modify the Library\n" + "subject to these terms and conditions. You may not impose any further\n" + "restrictions on the recipients' exercise of the rights granted herein.\n" + "You are not responsible for enforcing compliance by third parties with\n" + "this License.\n" + "\n" + " 11. If, as a consequence of a court judgment or allegation of patent\n" + "infringement or for any other reason (not limited to patent issues),\n" + "conditions are imposed on you (whether by court order, agreement or\n" + "otherwise) that contradict the conditions of this License, they do not\n" + "excuse you from the conditions of this License. If you cannot\n" + "distribute so as to satisfy simultaneously your obligations under this\n" + "License and any other pertinent obligations, then as a consequence you\n" + "may not distribute the Library at all. For example, if a patent\n" + "license would not permit royalty-free redistribution of the Library by\n" + "all those who receive copies directly or indirectly through you, then\n" + "the only way you could satisfy both it and this License would be to\n" + "refrain entirely from distribution of the Library.\n" + "\n" + "If any portion of this section is held invalid or unenforceable under\n" + "any particular circumstance, the balance of the section is intended to\n" + "apply, and the section as a whole is intended to apply in other\n" + "circumstances.\n" + "\n" + "It is not the purpose of this section to induce you to infringe any\n" + "patents or other property right claims or to contest validity of any\n" + "such claims; this section has the sole purpose of protecting the\n" + "integrity of the free software distribution system which is\n" + "implemented by public license practices. Many people have made\n" + "generous contributions to the wide range of software distributed\n" + "through that system in reliance on consistent application of that\n" + "system; it is up to the author/donor to decide if he or she is willing\n" + "to distribute software through any other system and a licensee cannot\n" + "impose that choice.\n" + "\n" + "This section is intended to make thoroughly clear what is believed to\n" + "be a consequence of the rest of this License.\n" + "\n" + " 12. If the distribution and/or use of the Library is restricted in\n" + "certain countries either by patents or by copyrighted interfaces, the\n" + "original copyright holder who places the Library under this License\n" + "may add an explicit geographical distribution limitation excluding those\n" + "countries, so that distribution is permitted only in or among\n" + "countries not thus excluded. In such case, this License incorporates\n" + "the limitation as if written in the body of this License.\n" + "\n" + " 13. The Free Software Foundation may publish revised and/or new\n" + "versions of the Lesser General Public License from time to time.\n" + "Such new versions will be similar in spirit to the present version,\n" + "but may differ in detail to address new problems or concerns.\n" + "\n" + "Each version is given a distinguishing version number. If the Library\n" + "specifies a version number of this License which applies to it and\n" + "\"any later version\", you have the option of following the terms and\n" + "conditions either of that version or of any later version published by\n" + "the Free Software Foundation. If the Library does not specify a\n" + "license version number, you may choose any version ever published by\n" + "the Free Software Foundation.\n" + "\n" + " 14. If you wish to incorporate parts of the Library into other free\n" + "programs whose distribution conditions are incompatible with these,\n" + "write to the author to ask for permission. For software which is\n" + "copyrighted by the Free Software Foundation, write to the Free\n" + "Software Foundation; we sometimes make exceptions for this. Our\n" + "decision will be guided by the two goals of preserving the free status\n" + "of all derivatives of our free software and of promoting the sharing\n" + "and reuse of software generally.\n" + "\n" + " NO WARRANTY\n" + "\n" + " 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\n" + "WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\n" + "EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\n" + "OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\n" + "KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\n" + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n" + "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\n" + "LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\n" + "THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n" + "\n" + " 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\n" + "WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\n" + "AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\n" + "FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\n" + "CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\n" + "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\n" + "RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\n" + "FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\n" + "SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n" + "DAMAGES.\n" + "\n" + " END OF TERMS AND CONDITIONS\n" + "\n" + " How to Apply These Terms to Your New Libraries\n" + "\n" + " If you develop a new library, and you want it to be of the greatest\n" + "possible use to the public, we recommend making it free software that\n" + "everyone can redistribute and change. You can do so by permitting\n" + "redistribution under these terms (or, alternatively, under the terms\n" + "of the ordinary General Public License).\n" + "\n" + " To apply these terms, attach the following notices to the library.\n" + "It is safest to attach them to the start of each source file to most\n" + "effectively convey the exclusion of warranty; and each file should\n" + "have at least the \"copyright\" line and a pointer to where the full\n" + "notice is found.\n" + "\n" + "\n" + " <one line to give the library's name and a brief idea of what it does.>\n" + " Copyright (C) <year> <name of author>\n" + "\n" + " This library is free software; you can redistribute it and/or\n" + " modify it under the terms of the GNU Lesser General Public\n" + " License as published by the Free Software Foundation; either\n" + " version 2.1 of the License, or (at your option) any later version.\n" + "\n" + " This library is distributed in the hope that it will be useful,\n" + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" + " Lesser General Public License for more details.\n" + "\n" + " You should have received a copy of the GNU Lesser General Public\n" + " License along with this library; if not, write to the Free Software\n" + " Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n" + "\n" + "Also add information on how to contact you by electronic and paper mail.\n" + "\n" + "You should also get your employer (if you work as a programmer) or\n" + "your school, if any, to sign a \"copyright disclaimer\" for the library,\n" + "if necessary. Here is a sample; alter the names:\n" + "\n" + " Yoyodyne, Inc., hereby disclaims all copyright interest in the\n" + " library `Frob' (a library for tweaking knobs) written by James\n" + " Random Hacker.\n" + "\n" + " <signature of Ty Coon>, 1 April 1990\n" + " Ty Coon, President of Vice\n" + "\n" + "That's all there is to it!"; #endif #ifdef USE_BUILDENV -static const char *licenseLibffi = - "libffi - Copyright (c) 1996-2014 Anthony Green, Red Hat, Inc and others.\n" - "See source files for details.\n" - "\n" - "Permission is hereby granted, free of charge, to any person obtaining\n" - "a copy of this software and associated documentation files (the\n" - "``Software''), to deal in the Software without restriction, including\n" - "without limitation the rights to use, copy, modify, merge, publish,\n" - "distribute, sublicense, and/or sell copies of the Software, and to\n" - "permit persons to whom the Software is furnished to do so, subject to\n" - "the following conditions:\n" - "\n" - "The above copyright notice and this permission notice shall be\n" - "included in all copies or substantial portions of the Software.\n" - "\n" - "THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,\n" - "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" - "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n" - "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n" - "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n" - "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n" - "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."; +static const char *licenseLibffi = "libffi - Copyright (c) 1996-2014 Anthony Green, Red Hat, Inc and others.\n" + "See source files for details.\n" + "\n" + "Permission is hereby granted, free of charge, to any person obtaining\n" + "a copy of this software and associated documentation files (the\n" + "``Software''), to deal in the Software without restriction, including\n" + "without limitation the rights to use, copy, modify, merge, publish,\n" + "distribute, sublicense, and/or sell copies of the Software, and to\n" + "permit persons to whom the Software is furnished to do so, subject to\n" + "the following conditions:\n" + "\n" + "The above copyright notice and this permission notice shall be\n" + "included in all copies or substantial portions of the Software.\n" + "\n" + "THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,\n" + "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" + "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n" + "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n" + "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n" + "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n" + "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."; #endif diff --git a/src/mumble/ACLEditor.cpp b/src/mumble/ACLEditor.cpp index 8cdb3148c..c2f729c9d 100644 --- a/src/mumble/ACLEditor.cpp +++ b/src/mumble/ACLEditor.cpp @@ -14,12 +14,13 @@ #include "User.h" #if QT_VERSION >= 0x050000 -# include <QtWidgets/QMessageBox> +# include <QtWidgets/QMessageBox> #else -# include <QtGui/QMessageBox> +# include <QtGui/QMessageBox> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" ACLGroup::ACLGroup(const QString &name) : Group(nullptr, name) { @@ -29,7 +30,7 @@ ACLGroup::ACLGroup(const QString &name) : Group(nullptr, name) { ACLEditor::ACLEditor(int channelparentid, QWidget *p) : QDialog(p) { // Simple constructor for add channel menu bAddChannelMode = true; - iChannel = channelparentid; + iChannel = channelparentid; setupUi(this); @@ -81,7 +82,7 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q bAddChannelMode = false; - iChannel = channelid; + iChannel = channelid; Channel *pChannel = Channel::get(iChannel); if (!pChannel) { g.l->log(Log::Warning, tr("Failed: Invalid channel")); @@ -143,19 +144,24 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q int idx = 1; for (int i = 0; i < ((iId == 0) ? 30 : 16); ++i) { - ChanACL::Perm perm = static_cast<ChanACL::Perm>(1 << i); - QString name = ChanACL::permName(perm); + ChanACL::Perm perm = static_cast< ChanACL::Perm >(1 << i); + QString name = ChanACL::permName(perm); - if (! name.isEmpty()) { - // If the server's version is less than 1.4.0 then it won't support the new permission to reset a comment/avatar. Skipping this iteration of the loop prevents checkboxes for it being added to the UI. - if ((g.sh->uiVersion < 0x010400) && (perm == ChanACL::ResetUserContent)) continue; + if (!name.isEmpty()) { + // If the server's version is less than 1.4.0 then it won't support the new permission to reset a + // comment/avatar. Skipping this iteration of the loop prevents checkboxes for it being added to the UI. + if ((g.sh->uiVersion < 0x010400) && (perm == ChanACL::ResetUserContent)) + continue; QCheckBox *qcb; l = new QLabel(name, qgbACLpermissions); grid->addWidget(l, idx, 0); qcb = new QCheckBox(qgbACLpermissions); qcb->setToolTip(tr("Deny %1").arg(name)); - qcb->setWhatsThis(tr("This revokes the %1 privilege. If a privilege is both allowed and denied, it is denied.<br />%2").arg(name).arg(ChanACL::whatsThis(perm))); + qcb->setWhatsThis( + tr("This revokes the %1 privilege. If a privilege is both allowed and denied, it is denied.<br />%2") + .arg(name) + .arg(ChanACL::whatsThis(perm))); connect(qcb, SIGNAL(clicked(bool)), this, SLOT(ACLPermissions_clicked())); grid->addWidget(qcb, idx, 1); @@ -163,7 +169,10 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q qcb = new QCheckBox(qgbACLpermissions); qcb->setToolTip(tr("Allow %1").arg(name)); - qcb->setWhatsThis(tr("This grants the %1 privilege. If a privilege is both allowed and denied, it is denied.<br />%2").arg(name).arg(ChanACL::whatsThis(perm))); + qcb->setWhatsThis( + tr("This grants the %1 privilege. If a privilege is both allowed and denied, it is denied.<br />%2") + .arg(name) + .arg(ChanACL::whatsThis(perm))); connect(qcb, SIGNAL(clicked(bool)), this, SLOT(ACLPermissions_clicked())); grid->addWidget(qcb, idx, 2); @@ -180,7 +189,7 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q connect(qcbGroupAdd->lineEdit(), SIGNAL(returnPressed()), qpbGroupAddAdd, SLOT(animateClick())); connect(qcbGroupRemove->lineEdit(), SIGNAL(returnPressed()), qpbGroupRemoveAdd, SLOT(animateClick())); - foreach(User *u, ClientUser::c_qmUsers) { + foreach (User *u, ClientUser::c_qmUsers) { if (u->iId >= 0) { qhNameCache.insert(u->iId, u->qsName); qhIDCache.insert(u->qsName.toLower(), u->iId); @@ -192,9 +201,10 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q def->bApplyHere = true; def->bApplySubs = true; def->bInherited = true; - def->iUserId = -1; - def->qsGroup = QLatin1String("all"); - def->pAllow = ChanACL::Traverse | ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::Listen; + def->iUserId = -1; + def->qsGroup = QLatin1String("all"); + def->pAllow = + ChanACL::Traverse | ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::Listen; def->pDeny = (~def->pAllow) & ChanACL::All; qlACLs << def; @@ -202,17 +212,17 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q for (int i = 0; i < mea.acls_size(); ++i) { const MumbleProto::ACL_ChanACL &as = mea.acls(i); - ChanACL *acl = new ChanACL(nullptr); + ChanACL *acl = new ChanACL(nullptr); acl->bApplyHere = as.apply_here(); acl->bApplySubs = as.apply_subs(); acl->bInherited = as.inherited(); - acl->iUserId = -1; + acl->iUserId = -1; if (as.has_user_id()) acl->iUserId = as.user_id(); else acl->qsGroup = u8(as.group()); - acl->pAllow = static_cast<ChanACL::Permissions>(as.grant()); - acl->pDeny = static_cast<ChanACL::Permissions>(as.deny()); + acl->pAllow = static_cast< ChanACL::Permissions >(as.grant()); + acl->pDeny = static_cast< ChanACL::Permissions >(as.deny()); qlACLs << acl; } @@ -220,9 +230,9 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q for (int i = 0; i < mea.groups_size(); ++i) { const MumbleProto::ACL_ChanGroup &gs = mea.groups(i); - ACLGroup *gp = new ACLGroup(u8(gs.name())); - gp->bInherit = gs.inherit(); - gp->bInherited = gs.inherited(); + ACLGroup *gp = new ACLGroup(u8(gs.name())); + gp->bInherit = gs.inherit(); + gp->bInherited = gs.inherited(); gp->bInheritable = gs.inheritable(); for (int j = 0; j < gs.add_size(); ++j) gp->qsAdd.insert(gs.add(j)); @@ -241,7 +251,7 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q bInheritACL = mea.inherit_acls(); qcbACLInherit->setChecked(bInheritACL); - foreach(ChanACL *acl, qlACLs) { + foreach (ChanACL *acl, qlACLs) { if (acl->bInherited) numInheritACL++; } @@ -262,12 +272,8 @@ ACLEditor::ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p) : Q } ACLEditor::~ACLEditor() { - foreach(ChanACL *acl, qlACLs) { - delete acl; - } - foreach(ACLGroup *gp, qlGroups) { - delete gp; - } + foreach (ChanACL *acl, qlACLs) { delete acl; } + foreach (ACLGroup *gp, qlGroups) { delete gp; } } void ACLEditor::showEvent(QShowEvent *evt) { @@ -293,7 +299,8 @@ void ACLEditor::accept() { // Update channel state if (bAddChannelMode) { - g.sh->createChannel(iChannel, qleChannelName->text(), rteChannelDescription->text(), qsbChannelPosition->value(), qcbChannelTemporary->isChecked(), qsbChannelMaxUsers->value()); + g.sh->createChannel(iChannel, qleChannelName->text(), rteChannelDescription->text(), + qsbChannelPosition->value(), qcbChannelTemporary->isChecked(), qsbChannelMaxUsers->value()); } else { bool needs_update = false; @@ -315,7 +322,7 @@ void ACLEditor::accept() { mpcs.set_position(qsbChannelPosition->value()); needs_update = true; } - if (pChannel->uiMaxUsers != static_cast<unsigned int>(qsbChannelMaxUsers->value())) { + if (pChannel->uiMaxUsers != static_cast< unsigned int >(qsbChannelMaxUsers->value())) { mpcs.set_max_users(qsbChannelMaxUsers->value()); needs_update = true; } @@ -327,7 +334,7 @@ void ACLEditor::accept() { msg.clear_acls(); msg.clear_groups(); - foreach(ChanACL *acl, qlACLs) { + foreach (ChanACL *acl, qlACLs) { if (acl->bInherited || (acl->iUserId < -1)) continue; MumbleProto::ACL_ChanACL *mpa = msg.add_acls(); @@ -341,17 +348,18 @@ void ACLEditor::accept() { mpa->set_deny(acl->pDeny); } - foreach(ACLGroup *gp, qlGroups) { - if (gp->bInherited && gp->bInherit && gp->bInheritable && (gp->qsAdd.count() == 0) && (gp->qsRemove.count() == 0)) + foreach (ACLGroup *gp, qlGroups) { + if (gp->bInherited && gp->bInherit && gp->bInheritable && (gp->qsAdd.count() == 0) + && (gp->qsRemove.count() == 0)) continue; MumbleProto::ACL_ChanGroup *mpg = msg.add_groups(); mpg->set_name(u8(gp->qsName)); mpg->set_inherit(gp->bInherit); mpg->set_inheritable(gp->bInheritable); - foreach(int pid, gp->qsAdd) + foreach (int pid, gp->qsAdd) if (pid >= 0) mpg->add_add(pid); - foreach(int pid, gp->qsRemove) + foreach (int pid, gp->qsRemove) if (pid >= 0) mpg->add_remove(pid); } @@ -373,7 +381,7 @@ int ACLEditor::id(const QString &uname) { if (qhIDCache.contains(name)) { return qhIDCache.value(name); } else { - if (! qhNameWait.contains(name)) { + if (!qhNameWait.contains(name)) { MumbleProto::QueryUsers mpuq; mpuq.add_names(u8(name)); g.sh->sendMessage(mpuq); @@ -391,8 +399,8 @@ void ACLEditor::returnQuery(const MumbleProto::QueryUsers &mqu) { return; for (int i = 0; i < mqu.names_size(); ++i) { - int pid = mqu.ids(i); - QString name = u8(mqu.names(i)); + int pid = mqu.ids(i); + QString name = u8(mqu.names(i)); QString lname = name.toLower(); qhIDCache.insert(lname, pid); qhNameCache.insert(pid, name); @@ -400,10 +408,10 @@ void ACLEditor::returnQuery(const MumbleProto::QueryUsers &mqu) { if (qhNameWait.contains(lname)) { int tid = qhNameWait.take(lname); - foreach(ChanACL *acl, qlACLs) + foreach (ChanACL *acl, qlACLs) if (acl->iUserId == tid) acl->iUserId = pid; - foreach(ACLGroup *gp, qlGroups) { + foreach (ACLGroup *gp, qlGroups) { if (gp->qsAdd.remove(tid)) gp->qsAdd.insert(pid); if (gp->qsRemove.remove(tid)) @@ -437,7 +445,7 @@ void ACLEditor::refill(WaitID wid) { } void ACLEditor::refillComboBoxes() { - QList<QComboBox *> ql; + QList< QComboBox * > ql; ql << qcbGroupAdd; ql << qcbGroupRemove; ql << qcbACLUser; @@ -445,7 +453,7 @@ void ACLEditor::refillComboBoxes() { QStringList names = qhNameCache.values(); names.sort(); - foreach(QComboBox *qcb, ql) { + foreach (QComboBox *qcb, ql) { qcb->clear(); qcb->addItems(names); qcb->clearEditText(); @@ -453,18 +461,18 @@ void ACLEditor::refillComboBoxes() { } void ACLEditor::refillACL() { - int idx = qlwACLs->currentRow(); + int idx = qlwACLs->currentRow(); bool previousinherit = bInheritACL; - bInheritACL = qcbACLInherit->isChecked(); + bInheritACL = qcbACLInherit->isChecked(); qlwACLs->clear(); bool first = true; - foreach(ChanACL *acl, qlACLs) { + foreach (ChanACL *acl, qlACLs) { if (first) first = false; - else if (! bInheritACL && acl->bInherited) + else if (!bInheritACL && acl->bInherited) continue; QString text; if (acl->iUserId == -1) @@ -478,9 +486,9 @@ void ACLEditor::refillACL() { item->setFont(f); } } - if (bInheritACL && ! previousinherit && (idx != 0)) + if (bInheritACL && !previousinherit && (idx != 0)) idx += numInheritACL; - if (! bInheritACL && previousinherit) + if (!bInheritACL && previousinherit) idx -= numInheritACL; qlwACLs->setCurrentRow(idx); @@ -490,16 +498,12 @@ void ACLEditor::refillGroupNames() { QString text = qcbGroupList->currentText().toLower(); QStringList qsl; - foreach(ACLGroup *gp, qlGroups) { - qsl << gp->qsName; - } + foreach (ACLGroup *gp, qlGroups) { qsl << gp->qsName; } qsl.sort(); qcbGroupList->clear(); - foreach(QString name, qsl) { - qcbGroupList->addItem(name); - } + foreach (QString name, qsl) { qcbGroupList->addItem(name); } int wantindex = qcbGroupList->findText(text, Qt::MatchFixedString); qcbGroupList->setCurrentIndex(wantindex); @@ -508,13 +512,13 @@ void ACLEditor::refillGroupNames() { ACLGroup *ACLEditor::currentGroup() { QString group = qcbGroupList->currentText(); - foreach(ACLGroup *gp, qlGroups) + foreach (ACLGroup *gp, qlGroups) if (gp->qsName == group) return gp; group = group.toLower(); - foreach(ACLGroup *gp, qlGroups) + foreach (ACLGroup *gp, qlGroups) if (gp->qsName == group) return gp; @@ -526,20 +530,18 @@ ChanACL *ACLEditor::currentACL() { if (idx < 0) return nullptr; - if (idx && ! bInheritACL) + if (idx && !bInheritACL) idx += numInheritACL; return qlACLs[idx]; } -void ACLEditor::fillWidgetFromSet(QListWidget *qlw, const QSet<int> &qs) { +void ACLEditor::fillWidgetFromSet(QListWidget *qlw, const QSet< int > &qs) { qlw->clear(); - QList<idname> ql; - foreach(int pid, qs) { - ql << idname(userName(pid), pid); - } + QList< idname > ql; + foreach (int pid, qs) { ql << idname(userName(pid), pid); } std::stable_sort(ql.begin(), ql.end()); - foreach(idname i, ql) { + foreach (idname i, ql) { QListWidgetItem *qlwi = new QListWidgetItem(i.first, qlw); qlwi->setData(Qt::UserRole, i.second); if (i.second < 0) { @@ -553,7 +555,7 @@ void ACLEditor::fillWidgetFromSet(QListWidget *qlw, const QSet<int> &qs) { void ACLEditor::refillGroupAdd() { ACLGroup *gp = currentGroup(); - if (! gp) + if (!gp) return; fillWidgetFromSet(qlwGroupAdd, gp->qsAdd); @@ -561,7 +563,7 @@ void ACLEditor::refillGroupAdd() { void ACLEditor::refillGroupRemove() { ACLGroup *gp = currentGroup(); - if (! gp) + if (!gp) return; fillWidgetFromSet(qlwGroupRemove, gp->qsRemove); @@ -570,7 +572,7 @@ void ACLEditor::refillGroupRemove() { void ACLEditor::refillGroupInherit() { ACLGroup *gp = currentGroup(); - if (! gp) + if (!gp) return; fillWidgetFromSet(qlwGroupInherit, gp->qsTemporary); @@ -580,7 +582,7 @@ void ACLEditor::groupEnableCheck() { ACLGroup *gp = currentGroup(); bool enabled; - if (! gp) + if (!gp) enabled = false; else enabled = gp->bInherit; @@ -611,10 +613,10 @@ void ACLEditor::ACLEnableCheck() { ChanACL *as = currentACL(); bool enabled; - if (! as) + if (!as) enabled = false; else - enabled = ! as->bInherited; + enabled = !as->bInherited; qpbACLRemove->setEnabled(enabled); qpbACLUp->setEnabled(enabled); @@ -626,7 +628,9 @@ void ACLEditor::ACLEnableCheck() { for (int idx = 0; idx < qlACLAllow.count(); idx++) { // Only enable other checkboxes if writeacl isn't set - bool enablethis = enabled && (qlPerms[idx] == ChanACL::Write || !(as && (as->pAllow & ChanACL::Write)) || qlPerms[idx] == ChanACL::Speak); + bool enablethis = enabled + && (qlPerms[idx] == ChanACL::Write || !(as && (as->pAllow & ChanACL::Write)) + || qlPerms[idx] == ChanACL::Speak); qlACLAllow[idx]->setEnabled(enablethis); qlACLDeny[idx]->setEnabled(enablethis); } @@ -652,7 +656,7 @@ void ACLEditor::ACLEnableCheck() { qcbACLGroup->addItem(QLatin1String("~sub")); qcbACLGroup->addItem(QLatin1String("~out")); - foreach(ACLGroup *gs, qlGroups) + foreach (ACLGroup *gs, qlGroups) qcbACLGroup->addItem(gs->qsName); if (as->iUserId == -1) { @@ -663,8 +667,8 @@ void ACLEditor::ACLEnableCheck() { qcbACLUser->setEditText(userName(as->iUserId)); } } - foreach(QAbstractButton *b, qdbbButtons->buttons()) { - QPushButton *qpb = qobject_cast<QPushButton *>(b); + foreach (QAbstractButton *b, qdbbButtons->buttons()) { + QPushButton *qpb = qobject_cast< QPushButton * >(b); if (qpb) { qpb->setAutoDefault(false); qpb->setDefault(false); @@ -686,7 +690,7 @@ void ACLEditor::on_qtwTab_currentChanged(int index) { void ACLEditor::updatePasswordField() { // Search for an ACL that represents the current password pcaPassword = nullptr; - foreach(ChanACL *acl, qlACLs) { + foreach (ChanACL *acl, qlACLs) { if (acl->isPassword()) { pcaPassword = acl; } @@ -695,7 +699,6 @@ void ACLEditor::updatePasswordField() { qleChannelPassword->setText(pcaPassword->qsGroup.mid(1)); else qleChannelPassword->clear(); - } void ACLEditor::updatePasswordACL() { @@ -706,13 +709,16 @@ void ACLEditor::updatePasswordACL() { // Search and remove the @all deny ACL ChanACL *denyall = nullptr; - foreach(ChanACL *acl, qlACLs) { - if (acl->qsGroup == QLatin1String("all") && - acl->bInherited == false && - acl->bApplyHere == true && - acl->pAllow == ChanACL::None && - (acl->pDeny == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel) || // Backwards compat with old behaviour that didn't deny traverse - acl->pDeny == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel | ChanACL::Traverse))) { + foreach (ChanACL *acl, qlACLs) { + if (acl->qsGroup == QLatin1String("all") && acl->bInherited == false && acl->bApplyHere == true + && acl->pAllow == ChanACL::None + && (acl->pDeny + == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage + | ChanACL::LinkChannel) + || // Backwards compat with old behaviour that didn't deny traverse + acl->pDeny + == (ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage + | ChanACL::LinkChannel | ChanACL::Traverse))) { denyall = acl; } } @@ -724,21 +730,23 @@ void ACLEditor::updatePasswordACL() { } else { // Add or Update if (!pcaPassword || !qlACLs.contains(pcaPassword)) { - pcaPassword = new ChanACL(nullptr); + pcaPassword = new ChanACL(nullptr); pcaPassword->bApplyHere = true; pcaPassword->bApplySubs = false; pcaPassword->bInherited = false; - pcaPassword->pAllow = ChanACL::None; - pcaPassword->pDeny = ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel | ChanACL::Traverse; + pcaPassword->pAllow = ChanACL::None; + pcaPassword->pDeny = ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage + | ChanACL::LinkChannel | ChanACL::Traverse; pcaPassword->qsGroup = QLatin1String("all"); qlACLs << pcaPassword; - pcaPassword = new ChanACL(nullptr); + pcaPassword = new ChanACL(nullptr); pcaPassword->bApplyHere = true; pcaPassword->bApplySubs = false; pcaPassword->bInherited = false; - pcaPassword->pAllow = ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage | ChanACL::LinkChannel | ChanACL::Traverse; - pcaPassword->pDeny = ChanACL::None; + pcaPassword->pAllow = ChanACL::Enter | ChanACL::Speak | ChanACL::Whisper | ChanACL::TextMessage + | ChanACL::LinkChannel | ChanACL::Traverse; + pcaPassword->pDeny = ChanACL::None; pcaPassword->qsGroup = QString(QLatin1String("#%1")).arg(qleChannelPassword->text()); qlACLs << pcaPassword; } else { @@ -752,14 +760,14 @@ void ACLEditor::on_qlwACLs_currentRowChanged() { } void ACLEditor::on_qpbACLAdd_clicked() { - ChanACL *as = new ChanACL(nullptr); + ChanACL *as = new ChanACL(nullptr); as->bApplyHere = true; as->bApplySubs = true; as->bInherited = false; - as->qsGroup = QLatin1String("all"); - as->iUserId = -1; - as->pAllow = ChanACL::None; - as->pDeny = ChanACL::None; + as->qsGroup = QLatin1String("all"); + as->iUserId = -1; + as->pAllow = ChanACL::None; + as->pDeny = ChanACL::None; qlACLs << as; refillACL(); qlwACLs->setCurrentRow(qlwACLs->count() - 1); @@ -767,7 +775,7 @@ void ACLEditor::on_qpbACLAdd_clicked() { void ACLEditor::on_qpbACLRemove_clicked() { ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; qlACLs.removeAll(as); @@ -777,7 +785,7 @@ void ACLEditor::on_qpbACLRemove_clicked() { void ACLEditor::on_qpbACLUp_clicked() { ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; int idx = qlACLs.indexOf(as); @@ -795,7 +803,7 @@ void ACLEditor::on_qpbACLUp_clicked() { void ACLEditor::on_qpbACLDown_clicked() { ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; int idx = qlACLs.indexOf(as) + 1; @@ -817,7 +825,7 @@ void ACLEditor::on_qcbACLInherit_clicked(bool) { void ACLEditor::on_qcbACLApplyHere_clicked(bool checked) { ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; as->bApplyHere = checked; @@ -825,7 +833,7 @@ void ACLEditor::on_qcbACLApplyHere_clicked(bool checked) { void ACLEditor::on_qcbACLApplySubs_clicked(bool checked) { ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; as->bApplySubs = checked; @@ -833,7 +841,7 @@ void ACLEditor::on_qcbACLApplySubs_clicked(bool checked) { void ACLEditor::on_qcbACLGroup_activated(const QString &text) { ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; as->iUserId = -1; @@ -852,7 +860,7 @@ void ACLEditor::on_qcbACLUser_activated() { QString text = qcbACLUser->currentText(); ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; if (text.isEmpty()) { @@ -870,16 +878,16 @@ void ACLEditor::on_qcbACLUser_activated() { } void ACLEditor::ACLPermissions_clicked() { - QCheckBox *source = qobject_cast<QCheckBox *>(sender()); + QCheckBox *source = qobject_cast< QCheckBox * >(sender()); ChanACL *as = currentACL(); - if (! as || as->bInherited) + if (!as || as->bInherited) return; int allowed = 0; - int denied = 0; + int denied = 0; - bool enabled = true; + bool enabled = true; bool modifiedEnter = false; for (int idx = 0; idx < qlACLAllow.count(); idx++) { ChanACL::Perm p = qlPerms[idx]; @@ -890,8 +898,7 @@ void ACLEditor::ACLPermissions_clicked() { qlACLAllow[idx]->setChecked(false); } - if (p == ChanACL::Enter - && (source == qlACLAllow[idx] || source == qlACLDeny[idx])) { + if (p == ChanACL::Enter && (source == qlACLAllow[idx] || source == qlACLDeny[idx])) { // Unchecking a checkbox is not counted as modifying the Enter privilege // in this context modifiedEnter = source->isChecked(); @@ -928,21 +935,21 @@ void ACLEditor::ACLPermissions_clicked() { denied |= p; } - as->pAllow = static_cast<ChanACL::Permissions>(allowed); - as->pDeny = static_cast<ChanACL::Permissions>(denied); + as->pAllow = static_cast< ChanACL::Permissions >(allowed); + as->pDeny = static_cast< ChanACL::Permissions >(denied); } void ACLEditor::on_qcbGroupList_activated(const QString &text) { ACLGroup *gs = currentGroup(); if (text.isEmpty()) return; - if (! gs) { - QString name = text.toLower(); - gs = new ACLGroup(name); - gs->bInherited = false; - gs->bInherit = true; + if (!gs) { + QString name = text.toLower(); + gs = new ACLGroup(name); + gs->bInherited = false; + gs->bInherit = true; gs->bInheritable = true; - gs->qsName = name; + gs->qsName = name; qlGroups << gs; } @@ -954,7 +961,7 @@ void ACLEditor::on_qcbGroupList_activated(const QString &text) { qpbGroupAdd->setEnabled(false); } -void ACLEditor::on_qcbGroupList_editTextChanged(const QString & text) { +void ACLEditor::on_qcbGroupList_editTextChanged(const QString &text) { qpbGroupAdd->setEnabled(!text.isEmpty()); } @@ -964,12 +971,12 @@ void ACLEditor::on_qpbGroupAdd_clicked() { void ACLEditor::on_qpbGroupRemove_clicked() { ACLGroup *gs = currentGroup(); - if (! gs) + if (!gs) return; if (gs->bInherited) { gs->bInheritable = true; - gs->bInherit = true; + gs->bInherit = true; gs->qsAdd.clear(); gs->qsRemove.clear(); } else { @@ -985,7 +992,7 @@ void ACLEditor::on_qpbGroupRemove_clicked() { void ACLEditor::on_qcbGroupInherit_clicked(bool checked) { ACLGroup *gs = currentGroup(); - if (! gs) + if (!gs) return; gs->bInherit = checked; @@ -994,7 +1001,7 @@ void ACLEditor::on_qcbGroupInherit_clicked(bool checked) { void ACLEditor::on_qcbGroupInheritable_clicked(bool checked) { ACLGroup *gs = currentGroup(); - if (! gs) + if (!gs) return; gs->bInheritable = checked; @@ -1004,7 +1011,7 @@ void ACLEditor::on_qpbGroupAddAdd_clicked() { ACLGroup *gs = currentGroup(); QString text = qcbGroupAdd->currentText(); - if (! gs) + if (!gs) return; if (text.isEmpty()) @@ -1017,11 +1024,11 @@ void ACLEditor::on_qpbGroupAddAdd_clicked() { void ACLEditor::on_qpbGroupAddRemove_clicked() { ACLGroup *gs = currentGroup(); - if (! gs) + if (!gs) return; QListWidgetItem *item = qlwGroupAdd->currentItem(); - if (! item) + if (!item) return; gs->qsAdd.remove(item->data(Qt::UserRole).toInt()); @@ -1033,7 +1040,7 @@ void ACLEditor::on_qpbGroupRemoveAdd_clicked() { QString text = qcbGroupRemove->currentText(); ACLGroup *gs = currentGroup(); - if (! gs) + if (!gs) return; if (text.isEmpty()) @@ -1045,11 +1052,11 @@ void ACLEditor::on_qpbGroupRemoveAdd_clicked() { void ACLEditor::on_qpbGroupRemoveRemove_clicked() { ACLGroup *gs = currentGroup(); - if (! gs) + if (!gs) return; QListWidgetItem *item = qlwGroupRemove->currentItem(); - if (! item) + if (!item) return; gs->qsRemove.remove(item->data(Qt::UserRole).toInt()); @@ -1058,11 +1065,11 @@ void ACLEditor::on_qpbGroupRemoveRemove_clicked() { void ACLEditor::on_qpbGroupInheritRemove_clicked() { ACLGroup *gs = currentGroup(); - if (! gs) + if (!gs) return; QListWidgetItem *item = qlwGroupInherit->currentItem(); - if (! item) + if (!item) return; gs->qsRemove.insert(item->data(Qt::UserRole).toInt()); diff --git a/src/mumble/ACLEditor.h b/src/mumble/ACLEditor.h index 3cd532ff2..b28b2643b 100644 --- a/src/mumble/ACLEditor.h +++ b/src/mumble/ACLEditor.h @@ -13,96 +13,95 @@ #include "ui_ACLEditor.h" class ACLGroup : public Group { - private: - Q_DISABLE_COPY(ACLGroup) - public: - bool bInherited; - ACLGroup(const QString &name); +private: + Q_DISABLE_COPY(ACLGroup) +public: + bool bInherited; + ACLGroup(const QString &name); }; class ACLEditor : public QDialog, public Ui::ACLEditor { - private: - Q_OBJECT - Q_DISABLE_COPY(ACLEditor) - protected: - typedef QPair<QString, int> idname; - MumbleProto::ACL msg; - enum WaitID { - GroupAdd, GroupRemove, GroupInherit, ACLList - }; - QHash<int, QString> qhNameCache; - QHash<QString, int> qhIDCache; - QHash<QString, int> qhNameWait; - - int iUnknown; - - void refill(WaitID what); - - ACLGroup *currentGroup(); - ChanACL *currentACL(); - - int iId; - bool bInheritACL; - QList<ChanACL *> qlACLs; - QList<ACLGroup *> qlGroups; - ChanACL *pcaPassword; - - int numInheritACL; - int iChannel; - bool bAddChannelMode; - - const QString userName(int id); - int id(const QString &uname); - - QList<QCheckBox *> qlACLAllow; - QList<QCheckBox *> qlACLDeny; - QList<ChanACL::Perm> qlPerms; - - void updatePasswordACL(void); - void updatePasswordField(void); - void showEvent(QShowEvent *) Q_DECL_OVERRIDE; - void fillWidgetFromSet(QListWidget *, const QSet<int> &); - public: - ACLEditor(int parentchannelid, QWidget *p = nullptr); - ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p = nullptr); - ~ACLEditor(); - void returnQuery(const MumbleProto::QueryUsers &mqu); - public slots: - void accept() Q_DECL_OVERRIDE; - public slots: - void refillACL(); - void refillGroupNames(); - void refillGroupAdd(); - void refillGroupRemove(); - void refillGroupInherit(); - void refillComboBoxes(); - void groupEnableCheck(); - void ACLEnableCheck(); - - void on_qtwTab_currentChanged(int index); - void on_qlwACLs_currentRowChanged(); - void on_qpbACLAdd_clicked(); - void on_qpbACLRemove_clicked(); - void on_qpbACLUp_clicked(); - void on_qpbACLDown_clicked(); - void on_qcbACLInherit_clicked(bool checked); - void on_qcbACLApplyHere_clicked(bool checked); - void on_qcbACLApplySubs_clicked(bool checked); - void on_qcbACLGroup_activated(const QString &text); - void on_qcbACLUser_activated(); - void ACLPermissions_clicked(); - - void on_qcbGroupList_activated(const QString &text); - void on_qcbGroupList_editTextChanged(const QString & text); - void on_qpbGroupAdd_clicked(); - void on_qpbGroupRemove_clicked(); - void on_qcbGroupInherit_clicked(bool checked); - void on_qcbGroupInheritable_clicked(bool checked); - void on_qpbGroupAddAdd_clicked(); - void on_qpbGroupAddRemove_clicked(); - void on_qpbGroupRemoveAdd_clicked(); - void on_qpbGroupRemoveRemove_clicked(); - void on_qpbGroupInheritRemove_clicked(); +private: + Q_OBJECT + Q_DISABLE_COPY(ACLEditor) +protected: + typedef QPair< QString, int > idname; + MumbleProto::ACL msg; + enum WaitID { GroupAdd, GroupRemove, GroupInherit, ACLList }; + QHash< int, QString > qhNameCache; + QHash< QString, int > qhIDCache; + QHash< QString, int > qhNameWait; + + int iUnknown; + + void refill(WaitID what); + + ACLGroup *currentGroup(); + ChanACL *currentACL(); + + int iId; + bool bInheritACL; + QList< ChanACL * > qlACLs; + QList< ACLGroup * > qlGroups; + ChanACL *pcaPassword; + + int numInheritACL; + int iChannel; + bool bAddChannelMode; + + const QString userName(int id); + int id(const QString &uname); + + QList< QCheckBox * > qlACLAllow; + QList< QCheckBox * > qlACLDeny; + QList< ChanACL::Perm > qlPerms; + + void updatePasswordACL(void); + void updatePasswordField(void); + void showEvent(QShowEvent *) Q_DECL_OVERRIDE; + void fillWidgetFromSet(QListWidget *, const QSet< int > &); + +public: + ACLEditor(int parentchannelid, QWidget *p = nullptr); + ACLEditor(int channelid, const MumbleProto::ACL &mea, QWidget *p = nullptr); + ~ACLEditor(); + void returnQuery(const MumbleProto::QueryUsers &mqu); +public slots: + void accept() Q_DECL_OVERRIDE; +public slots: + void refillACL(); + void refillGroupNames(); + void refillGroupAdd(); + void refillGroupRemove(); + void refillGroupInherit(); + void refillComboBoxes(); + void groupEnableCheck(); + void ACLEnableCheck(); + + void on_qtwTab_currentChanged(int index); + void on_qlwACLs_currentRowChanged(); + void on_qpbACLAdd_clicked(); + void on_qpbACLRemove_clicked(); + void on_qpbACLUp_clicked(); + void on_qpbACLDown_clicked(); + void on_qcbACLInherit_clicked(bool checked); + void on_qcbACLApplyHere_clicked(bool checked); + void on_qcbACLApplySubs_clicked(bool checked); + void on_qcbACLGroup_activated(const QString &text); + void on_qcbACLUser_activated(); + void ACLPermissions_clicked(); + + void on_qcbGroupList_activated(const QString &text); + void on_qcbGroupList_editTextChanged(const QString &text); + void on_qpbGroupAdd_clicked(); + void on_qpbGroupRemove_clicked(); + void on_qcbGroupInherit_clicked(bool checked); + void on_qcbGroupInheritable_clicked(bool checked); + void on_qpbGroupAddAdd_clicked(); + void on_qpbGroupAddRemove_clicked(); + void on_qpbGroupRemoveAdd_clicked(); + void on_qpbGroupRemoveRemove_clicked(); + void on_qpbGroupInheritRemove_clicked(); }; #endif diff --git a/src/mumble/ALSAAudio.cpp b/src/mumble/ALSAAudio.cpp index 80f35f457..2365dbf81 100644 --- a/src/mumble/ALSAAudio.cpp +++ b/src/mumble/ALSAAudio.cpp @@ -12,46 +12,48 @@ #include <alsa/asoundlib.h> #include <sys/poll.h> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" #define NBLOCKS 8 class ALSAEnumerator { - public: - QHash<QString,QString> qhInput; - QHash<QString,QString> qhOutput; - static QString getHint(void *hint, const char *id); - ALSAEnumerator(); +public: + QHash< QString, QString > qhInput; + QHash< QString, QString > qhOutput; + static QString getHint(void *hint, const char *id); + ALSAEnumerator(); }; static ALSAEnumerator *cards = nullptr; class ALSAAudioInputRegistrar : public AudioInputRegistrar { - public: - ALSAAudioInputRegistrar(); - virtual AudioInput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); - virtual bool canEcho(const QString &) const; +public: + ALSAAudioInputRegistrar(); + virtual AudioInput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); + virtual bool canEcho(const QString &) const; }; class ALSAAudioOutputRegistrar : public AudioOutputRegistrar { - public: - ALSAAudioOutputRegistrar(); - virtual AudioOutput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); +public: + ALSAAudioOutputRegistrar(); + virtual AudioOutput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); }; class ALSAInit : public DeferInit { - protected: - ALSAAudioInputRegistrar *pairALSA; - ALSAAudioOutputRegistrar *paorALSA; - public: - void initialize(); - void destroy(); +protected: + ALSAAudioInputRegistrar *pairALSA; + ALSAAudioOutputRegistrar *paorALSA; + +public: + void initialize(); + void destroy(); }; static ALSAInit aiInit; @@ -60,14 +62,14 @@ QMutex qmALSA; void ALSAInit::initialize() { pairALSA = nullptr; paorALSA = nullptr; - cards = nullptr; + cards = nullptr; int card = -1; snd_card_next(&card); if (card != -1) { pairALSA = new ALSAAudioInputRegistrar(); paorALSA = new ALSAAudioOutputRegistrar(); - cards = new ALSAEnumerator(); + cards = new ALSAEnumerator(); } else { qWarning("ALSAInit: No cards found, not initializing"); } @@ -80,15 +82,15 @@ void ALSAInit::destroy() { delete cards; } -ALSAAudioInputRegistrar::ALSAAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("ALSA"),5) { +ALSAAudioInputRegistrar::ALSAAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("ALSA"), 5) { } AudioInput *ALSAAudioInputRegistrar::create() { return new ALSAAudioInput(); } -const QList<audioDevice> ALSAAudioInputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > ALSAAudioInputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; QStringList qlInputDevs = cards->qhInput.keys(); std::sort(qlInputDevs.begin(), qlInputDevs.end()); @@ -98,8 +100,8 @@ const QList<audioDevice> ALSAAudioInputRegistrar::getDeviceChoices() { qlInputDevs.prepend(g.s.qsALSAInput); } - foreach(const QString &dev, qlInputDevs) { - QString t=QString::fromLatin1("[%1] %2").arg(dev, cards->qhInput.value(dev)); + foreach (const QString &dev, qlInputDevs) { + QString t = QString::fromLatin1("[%1] %2").arg(dev, cards->qhInput.value(dev)); qlReturn << audioDevice(t, dev); } @@ -121,8 +123,8 @@ AudioOutput *ALSAAudioOutputRegistrar::create() { return new ALSAAudioOutput(); } -const QList<audioDevice> ALSAAudioOutputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > ALSAAudioOutputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; QStringList qlOutputDevs = cards->qhOutput.keys(); std::sort(qlOutputDevs.begin(), qlOutputDevs.end()); @@ -132,8 +134,8 @@ const QList<audioDevice> ALSAAudioOutputRegistrar::getDeviceChoices() { qlOutputDevs.prepend(g.s.qsALSAOutput); } - foreach(const QString &dev, qlOutputDevs) { - QString t=QString::fromLatin1("[%1] %2").arg(dev, cards->qhOutput.value(dev)); + foreach (const QString &dev, qlOutputDevs) { + QString t = QString::fromLatin1("[%1] %2").arg(dev, cards->qhOutput.value(dev)); qlReturn << audioDevice(t, dev); } @@ -158,7 +160,7 @@ ALSAEnumerator::ALSAEnumerator() { snd_config_update(); r = snd_config_search(snd_config, "defaults.namehint.extended", &basic); - if ((r==0) && basic) { + if ((r == 0) && basic) { if (snd_config_set_ascii(basic, "on")) qWarning("ALSAEnumerator: Failed to set namehint"); } else { @@ -167,14 +169,14 @@ ALSAEnumerator::ALSAEnumerator() { r = snd_device_name_hint(-1, "pcm", &hints); - if (r || ! hints) { + if (r || !hints) { qWarning("ALSAEnumerator: snd_device_name_hint: %d", r); } else { hint = hints; while (*hint) { const QString name = getHint(*hint, "NAME"); const QString ioid = getHint(*hint, "IOID"); - QString desc = getHint(*hint, "DESC"); + QString desc = getHint(*hint, "DESC"); desc.replace(QLatin1Char('\n'), QLatin1Char(' ')); @@ -183,8 +185,8 @@ ALSAEnumerator::ALSAEnumerator() { // Since there seems to be no way to fetch the ctl interface for a matching device string // without actually opening it, we'll simply have to start guessing. - bool caninput = (ioid.isNull() || (ioid.compare(QLatin1String("Input"), Qt::CaseInsensitive)==0)); - bool canoutput = (ioid.isNull() || (ioid.compare(QLatin1String("Output"), Qt::CaseInsensitive)==0)); + bool caninput = (ioid.isNull() || (ioid.compare(QLatin1String("Input"), Qt::CaseInsensitive) == 0)); + bool canoutput = (ioid.isNull() || (ioid.compare(QLatin1String("Output"), Qt::CaseInsensitive) == 0)); if (name.startsWith(QLatin1String("dmix:"))) caninput = false; @@ -204,13 +206,13 @@ ALSAEnumerator::ALSAEnumerator() { snd_config_update_free_global(); snd_config_update(); #else - int card=-1; + int card = -1; snd_card_next(&card); while (card != -1) { char *name; - snd_ctl_t *ctl=nullptr; + snd_ctl_t *ctl = nullptr; snd_card_get_longname(card, &name); - QByteArray dev=QString::fromLatin1("hw:%1").arg(card).toUtf8(); + QByteArray dev = QString::fromLatin1("hw:%1").arg(card).toUtf8(); if (snd_ctl_open(&ctl, dev.data(), SND_CTL_READONLY) >= 0) { snd_pcm_info_t *info = nullptr; snd_pcm_info_malloc(&info); @@ -222,32 +224,32 @@ ALSAEnumerator::ALSAEnumerator() { snd_ctl_pcm_next_device(ctl, &device); bool play = false; - bool cap = false; + bool cap = false; while (device != -1) { - QString devname=QString::fromLatin1("hw:%1,%2").arg(card).arg(device); + QString devname = QString::fromLatin1("hw:%1,%2").arg(card).arg(device); snd_pcm_info_set_device(info, device); snd_pcm_info_set_stream(info, SND_PCM_STREAM_CAPTURE); - if (snd_ctl_pcm_info(ctl,info) == 0) { - QString fname=QString::fromLatin1(snd_pcm_info_get_name(info)); - qhInput.insert(devname,fname); + if (snd_ctl_pcm_info(ctl, info) == 0) { + QString fname = QString::fromLatin1(snd_pcm_info_get_name(info)); + qhInput.insert(devname, fname); cap = true; } snd_pcm_info_set_stream(info, SND_PCM_STREAM_PLAYBACK); - if (snd_ctl_pcm_info(ctl,info) == 0) { - QString fname=QString::fromLatin1(snd_pcm_info_get_name(info)); - qhOutput.insert(devname,fname); + if (snd_ctl_pcm_info(ctl, info) == 0) { + QString fname = QString::fromLatin1(snd_pcm_info_get_name(info)); + qhOutput.insert(devname, fname); play = true; } snd_ctl_pcm_next_device(ctl, &device); } if (play) { - qhOutput.insert(QString::fromLatin1("dmix:CARD=%1").arg(card),QLatin1String(cname)); + qhOutput.insert(QString::fromLatin1("dmix:CARD=%1").arg(card), QLatin1String(cname)); } if (cap) { - qhInput.insert(QString::fromLatin1("dsnoop:CARD=%1").arg(card),QLatin1String(cname)); + qhInput.insert(QString::fromLatin1("dsnoop:CARD=%1").arg(card), QLatin1String(cname)); } snd_pcm_info_free(info); snd_ctl_close(ctl); @@ -280,25 +282,34 @@ ALSAAudioInput::~ALSAAudioInput() { wait(); } -#define ALSA_ERRBAIL(x) if (!bOk) {} else if ((err=static_cast<int>(x)) < 0) { bOk = false; qWarning("ALSAAudio: %s: %s", #x, snd_strerror(err));} -#define ALSA_ERRCHECK(x) if (!bOk) {} else if ((err=static_cast<int>(x)) < 0) {qWarning("ALSAAudio: Non-critical: %s: %s", #x, snd_strerror(err));} +#define ALSA_ERRBAIL(x) \ + if (!bOk) { \ + } else if ((err = static_cast< int >(x)) < 0) { \ + bOk = false; \ + qWarning("ALSAAudio: %s: %s", #x, snd_strerror(err)); \ + } +#define ALSA_ERRCHECK(x) \ + if (!bOk) { \ + } else if ((err = static_cast< int >(x)) < 0) { \ + qWarning("ALSAAudio: Non-critical: %s: %s", #x, snd_strerror(err)); \ + } void ALSAAudioInput::run() { QMutexLocker qml(&qmALSA); snd_pcm_sframes_t readblapp; - QByteArray device_name = g.s.qsALSAInput.toLatin1(); + QByteArray device_name = g.s.qsALSAInput.toLatin1(); snd_pcm_hw_params_t *hw_params = nullptr; - snd_pcm_t *capture_handle = nullptr; + snd_pcm_t *capture_handle = nullptr; unsigned int rrate = SAMPLE_RATE; - bool bOk = true; + bool bOk = true; int err = 0; unsigned int iChannels = 1; - qWarning("ALSAAudioInput: Initing audiocapture %s.",device_name.data()); + qWarning("ALSAAudioInput: Initing audiocapture %s.", device_name.data()); snd_pcm_hw_params_alloca(&hw_params); @@ -310,13 +321,14 @@ void ALSAAudioInput::run() { ALSA_ERRBAIL(snd_pcm_hw_params_set_channels_near(capture_handle, hw_params, &iChannels)); snd_pcm_uframes_t wantPeriod = (rrate * iFrameSize) / SAMPLE_RATE; - snd_pcm_uframes_t wantBuff = wantPeriod * 8; + snd_pcm_uframes_t wantBuff = wantPeriod * 8; ALSA_ERRBAIL(snd_pcm_hw_params_set_period_size_near(capture_handle, hw_params, &wantPeriod, nullptr)); ALSA_ERRBAIL(snd_pcm_hw_params_set_buffer_size_near(capture_handle, hw_params, &wantBuff)); ALSA_ERRBAIL(snd_pcm_hw_params(capture_handle, hw_params)); - qWarning("ALSAAudioInput: Actual buffer %d hz, %d channel %ld samples [%ld per period]",rrate,iChannels,wantBuff,wantPeriod); + qWarning("ALSAAudioInput: Actual buffer %d hz, %d channel %ld samples [%ld per period]", rrate, iChannels, wantBuff, + wantPeriod); ALSA_ERRBAIL(snd_pcm_hw_params_current(capture_handle, hw_params)); ALSA_ERRBAIL(snd_pcm_hw_params_get_channels(hw_params, &iMicChannels)); @@ -324,7 +336,7 @@ void ALSAAudioInput::run() { #ifdef ALSA_VERBOSE snd_output_t *log; - snd_output_stdio_attach(&log, stderr,0); + snd_output_stdio_attach(&log, stderr, 0); if (capture_handle) snd_pcm_dump(capture_handle, log); #endif @@ -332,13 +344,14 @@ void ALSAAudioInput::run() { ALSA_ERRBAIL(snd_pcm_prepare(capture_handle)); ALSA_ERRBAIL(snd_pcm_start(capture_handle)); - if (! bOk) { + if (!bOk) { if (capture_handle) { snd_pcm_drain(capture_handle); snd_pcm_close(capture_handle); capture_handle = nullptr; } - g.mw->msgBox(tr("Opening chosen ALSA Input failed: %1").arg(QString::fromLatin1(snd_strerror(err)).toHtmlEscaped())); + g.mw->msgBox( + tr("Opening chosen ALSA Input failed: %1").arg(QString::fromLatin1(snd_strerror(err)).toHtmlEscaped())); return; } @@ -356,21 +369,21 @@ void ALSAAudioInput::run() { snd_pcm_status_dump(status, log); snd_pcm_status_free(status); #endif - readblapp = snd_pcm_readi(capture_handle, inbuff, static_cast<int>(wantPeriod)); + readblapp = snd_pcm_readi(capture_handle, inbuff, static_cast< int >(wantPeriod)); if (readblapp == -ESTRPIPE) { qWarning("ALSAAudioInput: PCM suspended, trying to resume"); while (bRunning && snd_pcm_resume(capture_handle) == -EAGAIN) msleep(1000); if ((err = snd_pcm_prepare(capture_handle)) < 0) - qWarning("ALSAAudioInput: %s: %s", snd_strerror(static_cast<int>(readblapp)), snd_strerror(err)); + qWarning("ALSAAudioInput: %s: %s", snd_strerror(static_cast< int >(readblapp)), snd_strerror(err)); } else if (readblapp == -EPIPE) { err = snd_pcm_prepare(capture_handle); - qWarning("ALSAAudioInput: %s: %s", snd_strerror(static_cast<int>(readblapp)), snd_strerror(err)); + qWarning("ALSAAudioInput: %s: %s", snd_strerror(static_cast< int >(readblapp)), snd_strerror(err)); } else if (readblapp < 0) { err = snd_pcm_prepare(capture_handle); - qWarning("ALSAAudioInput: %s: %s", snd_strerror(static_cast<int>(readblapp)), snd_strerror(err)); - } else if (wantPeriod == static_cast<unsigned int>(readblapp)) { - addMic(inbuff, static_cast<int>(readblapp)); + qWarning("ALSAAudioInput: %s: %s", snd_strerror(static_cast< int >(readblapp)), snd_strerror(err)); + } else if (wantPeriod == static_cast< unsigned int >(readblapp)) { + addMic(inbuff, static_cast< int >(readblapp)); } } @@ -400,13 +413,13 @@ void ALSAAudioOutput::run() { struct pollfd fds[16]; int count; bool stillRun = true; - int err = 0; - bool bOk = true; + int err = 0; + bool bOk = true; snd_pcm_hw_params_t *hw_params = nullptr; snd_pcm_sw_params_t *sw_params = nullptr; - QByteArray device_name = g.s.qsALSAOutput.toLatin1(); + QByteArray device_name = g.s.qsALSAOutput.toLatin1(); snd_pcm_hw_params_alloca(&hw_params); snd_pcm_sw_params_alloca(&sw_params); @@ -417,7 +430,7 @@ void ALSAAudioOutput::run() { iChannels = 1; ALSA_ERRBAIL(snd_pcm_hw_params_get_channels_max(hw_params, &iChannels)); if (iChannels > 9) { - qWarning("ALSAAudioOutput: ALSA reports %d output channels. Clamping to 2.",iChannels); + qWarning("ALSAAudioOutput: ALSA reports %d output channels. Clamping to 2.", iChannels); iChannels = 2; } @@ -441,7 +454,8 @@ void ALSAAudioOutput::run() { ALSA_ERRBAIL(snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir)); ALSA_ERRBAIL(snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size)); - qWarning("ALSAAudioOutput: Actual buffer %d hz, %d channel %ld samples [%ld per period]",rrate,iChannels,buffer_size,period_size); + qWarning("ALSAAudioOutput: Actual buffer %d hz, %d channel %ld samples [%ld per period]", rrate, iChannels, + buffer_size, period_size); ALSA_ERRBAIL(snd_pcm_sw_params_current(pcm_handle, sw_params)); ALSA_ERRBAIL(snd_pcm_sw_params_set_avail_min(pcm_handle, sw_params, period_size)); @@ -451,28 +465,29 @@ void ALSAAudioOutput::run() { #ifdef ALSA_VERBOSE snd_output_t *log; - snd_output_stdio_attach(&log, stderr,0); + snd_output_stdio_attach(&log, stderr, 0); if (pcm_handle) snd_pcm_dump(pcm_handle, log); #endif ALSA_ERRBAIL(snd_pcm_prepare(pcm_handle)); - const unsigned int buffsize = static_cast<unsigned int>(period_size * iChannels); + const unsigned int buffsize = static_cast< unsigned int >(period_size * iChannels); float zerobuff[buffsize]; float outbuff[buffsize]; - for (unsigned int i=0;i<buffsize;i++) - zerobuff[i]=0; + for (unsigned int i = 0; i < buffsize; i++) + zerobuff[i] = 0; // Fill buffer if (bOk && pcm_handle) for (unsigned int i = 0; i < buffer_size / period_size; i++) snd_pcm_writei(pcm_handle, zerobuff, period_size); - if (! bOk) { - g.mw->msgBox(tr("Opening chosen ALSA Output failed: %1").arg(QString::fromLatin1(snd_strerror(err)).toHtmlEscaped())); + if (!bOk) { + g.mw->msgBox( + tr("Opening chosen ALSA Output failed: %1").arg(QString::fromLatin1(snd_strerror(err)).toHtmlEscaped())); if (pcm_handle) { snd_pcm_close(pcm_handle); pcm_handle = nullptr; @@ -480,22 +495,14 @@ void ALSAAudioOutput::run() { return; } - const unsigned int chanmasks[32] = { - SPEAKER_FRONT_LEFT, - SPEAKER_FRONT_RIGHT, - SPEAKER_BACK_LEFT, - SPEAKER_BACK_RIGHT, - SPEAKER_FRONT_CENTER, - SPEAKER_LOW_FREQUENCY, - SPEAKER_SIDE_LEFT, - SPEAKER_SIDE_RIGHT, - SPEAKER_BACK_CENTER - }; + const unsigned int chanmasks[32] = { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT, SPEAKER_BACK_LEFT, + SPEAKER_BACK_RIGHT, SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY, + SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT, SPEAKER_BACK_CENTER }; ALSA_ERRBAIL(snd_pcm_hw_params_current(pcm_handle, hw_params)); ALSA_ERRBAIL(snd_pcm_hw_params_get_channels(hw_params, &iChannels)); ALSA_ERRBAIL(snd_pcm_hw_params_get_rate(hw_params, &rrate, nullptr)); - iMixerFreq = rrate; + iMixerFreq = rrate; eSampleFormat = SampleShort; qWarning("ALSAAudioOutput: Initializing %d channel, %d hz mixer", iChannels, iMixerFreq); @@ -516,11 +523,11 @@ void ALSAAudioOutput::run() { } else if (revents & POLLOUT) { snd_pcm_sframes_t avail{}; ALSA_ERRCHECK(avail = snd_pcm_avail_update(pcm_handle)); - while (avail >= static_cast<int>(period_size)) { - stillRun = mix(outbuff, static_cast<int>(period_size)); + while (avail >= static_cast< int >(period_size)) { + stillRun = mix(outbuff, static_cast< int >(period_size)); if (stillRun) { snd_pcm_sframes_t w = 0; - ALSA_ERRCHECK(w=snd_pcm_writei(pcm_handle, outbuff, period_size)); + ALSA_ERRCHECK(w = snd_pcm_writei(pcm_handle, outbuff, period_size)); if (w < 0) { avail = w; break; @@ -533,24 +540,24 @@ void ALSAAudioOutput::run() { if (avail == -EPIPE) { snd_pcm_drain(pcm_handle); ALSA_ERRCHECK(snd_pcm_prepare(pcm_handle)); - for (unsigned int i=0;i< buffer_size / period_size;++i) + for (unsigned int i = 0; i < buffer_size / period_size; ++i) ALSA_ERRCHECK(snd_pcm_writei(pcm_handle, zerobuff, period_size)); } - if (! stillRun) { + if (!stillRun) { snd_pcm_drain(pcm_handle); - while (bRunning && !mix(outbuff, static_cast<unsigned int>(period_size))) { + while (bRunning && !mix(outbuff, static_cast< unsigned int >(period_size))) { this->msleep(10); } - if (! bRunning) + if (!bRunning) break; snd_pcm_prepare(pcm_handle); // Fill one frame - for (unsigned int i = 0; i < (buffer_size / period_size) - 1 ; i++) + for (unsigned int i = 0; i < (buffer_size / period_size) - 1; i++) snd_pcm_writei(pcm_handle, zerobuff, period_size); snd_pcm_writei(pcm_handle, outbuff, period_size); diff --git a/src/mumble/ALSAAudio.h b/src/mumble/ALSAAudio.h index bc475864f..af0bd0725 100644 --- a/src/mumble/ALSAAudio.h +++ b/src/mumble/ALSAAudio.h @@ -4,33 +4,33 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef MUMBLE_MUMBLE_ALSAAUDIO_H_ -#define MUMBLE_MUMBLE_ALSAAUDIO_H_ +# define MUMBLE_MUMBLE_ALSAAUDIO_H_ -#include "AudioInput.h" -#include "AudioOutput.h" +# include "AudioInput.h" +# include "AudioOutput.h" class ALSAAudioOutput; class ALSAAudioInput; class ALSAAudioInput : public AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(ALSAAudioInput) - public: - ALSAAudioInput(); - ~ALSAAudioInput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(ALSAAudioInput) +public: + ALSAAudioInput(); + ~ALSAAudioInput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; class ALSAAudioOutput : public AudioOutput { - private: - Q_OBJECT - Q_DISABLE_COPY(ALSAAudioOutput) - protected: - public: - ALSAAudioOutput(); - ~ALSAAudioOutput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(ALSAAudioOutput) +protected: +public: + ALSAAudioOutput(); + ~ALSAAudioOutput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; #else diff --git a/src/mumble/ASIOInput.cpp b/src/mumble/ASIOInput.cpp index 98bae3ec4..9e8019ed3 100644 --- a/src/mumble/ASIOInput.cpp +++ b/src/mumble/ASIOInput.cpp @@ -12,7 +12,8 @@ #include <cmath> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" // From os_win.cpp. @@ -21,13 +22,12 @@ extern HWND mumble_mw_hwnd; const QString ASIOConfig::name = QLatin1String("ASIOConfig"); class ASIOAudioInputRegistrar : public AudioInputRegistrar { - public: - ASIOAudioInputRegistrar(); - virtual AudioInput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); - virtual bool canEcho(const QString &) const; - +public: + ASIOAudioInputRegistrar(); + virtual AudioInput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); + virtual bool canEcho(const QString &) const; }; ASIOAudioInputRegistrar::ASIOAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("ASIO")) { @@ -36,8 +36,8 @@ ASIOAudioInputRegistrar::ASIOAudioInputRegistrar() : AudioInputRegistrar(QLatin1 AudioInput *ASIOAudioInputRegistrar::create() { return new ASIOInput(); } -const QList<audioDevice> ASIOAudioInputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > ASIOAudioInputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; return qlReturn; } @@ -53,12 +53,13 @@ static ConfigWidget *ASIOConfigDialogNew(Settings &st) { } class ASIOInit : public DeferInit { - ASIOAudioInputRegistrar *airASIO; - ConfigRegistrar *crASIO; - public: - ASIOInit() : airASIO(nullptr), crASIO(nullptr) {} - void initialize(); - void destroy(); + ASIOAudioInputRegistrar *airASIO; + ConfigRegistrar *crASIO; + +public: + ASIOInit() : airASIO(nullptr), crASIO(nullptr) {} + void initialize(); + void destroy(); }; void ASIOInit::initialize() { @@ -67,7 +68,7 @@ void ASIOInit::initialize() { FILETIME ft; airASIO = nullptr; - crASIO = nullptr; + crASIO = nullptr; bool bFound = false; @@ -84,21 +85,23 @@ void ASIOInit::initialize() { blacklist << QLatin1String("{232685c6-6548-49d8-846d-4141a3ef7560}"); // ASIO4ALL #endif if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\ASIO", 0, KEY_READ, &hkDevs) == ERROR_SUCCESS) { - DWORD idx = 0; + DWORD idx = 0; DWORD keynamelen = 255; WCHAR keyname[255]; - while (RegEnumKeyEx(hkDevs, idx++, keyname, &keynamelen, nullptr, nullptr, nullptr, &ft) == ERROR_SUCCESS) { - QString name=QString::fromUtf16(reinterpret_cast<ushort *>(keyname),keynamelen); + while (RegEnumKeyEx(hkDevs, idx++, keyname, &keynamelen, nullptr, nullptr, nullptr, &ft) == ERROR_SUCCESS) { + QString name = QString::fromUtf16(reinterpret_cast< ushort * >(keyname), keynamelen); if (RegOpenKeyEx(hkDevs, keyname, 0, KEY_READ, &hk) == ERROR_SUCCESS) { DWORD dtype = REG_SZ; WCHAR wclsid[255]; DWORD datasize = 255; CLSID clsid; - if (RegQueryValueEx(hk, L"CLSID", 0, &dtype, reinterpret_cast<BYTE *>(wclsid), &datasize) == ERROR_SUCCESS) { + if (RegQueryValueEx(hk, L"CLSID", 0, &dtype, reinterpret_cast< BYTE * >(wclsid), &datasize) + == ERROR_SUCCESS) { if (datasize > 76) datasize = 76; - QString qsCls = QString::fromUtf16(reinterpret_cast<ushort *>(wclsid), datasize / 2).toLower().trimmed(); - if (! blacklist.contains(qsCls.toLower()) && ! FAILED(CLSIDFromString(wclsid, &clsid))) { + QString qsCls = + QString::fromUtf16(reinterpret_cast< ushort * >(wclsid), datasize / 2).toLower().trimmed(); + if (!blacklist.contains(qsCls.toLower()) && !FAILED(CLSIDFromString(wclsid, &clsid))) { bFound = true; } } @@ -111,7 +114,7 @@ void ASIOInit::initialize() { if (bFound) { airASIO = new ASIOAudioInputRegistrar(); - crASIO = new ConfigRegistrar(2002, ASIOConfigDialogNew); + crASIO = new ConfigRegistrar(2002, ASIOConfigDialogNew); } else { qWarning("ASIO: No valid devices found, disabling"); } @@ -146,21 +149,23 @@ ASIOConfig::ASIOConfig(Settings &st) : ConfigWidget(st) { WCHAR keyname[keynamebufsize]; FILETIME ft; - DWORD idx = 0; + DWORD idx = 0; DWORD keynamelen = keynamebufsize; while (RegEnumKeyEx(hkDevs, idx++, keyname, &keynamelen, nullptr, nullptr, nullptr, &ft) == ERROR_SUCCESS) { - QString name=QString::fromUtf16(reinterpret_cast<ushort *>(keyname), keynamelen); + QString name = QString::fromUtf16(reinterpret_cast< ushort * >(keyname), keynamelen); HKEY hk; if (RegOpenKeyEx(hkDevs, keyname, 0, KEY_READ, &hk) == ERROR_SUCCESS) { DWORD dtype = REG_SZ; WCHAR wclsid[255]; DWORD datasize = 255; - if (RegQueryValueEx(hk, L"CLSID", 0, &dtype, reinterpret_cast<BYTE *>(wclsid), &datasize) == ERROR_SUCCESS) { + if (RegQueryValueEx(hk, L"CLSID", 0, &dtype, reinterpret_cast< BYTE * >(wclsid), &datasize) + == ERROR_SUCCESS) { if (datasize > 76) datasize = 76; - QString qsCls = QString::fromUtf16(reinterpret_cast<ushort *>(wclsid), datasize / 2).toLower().trimmed(); + QString qsCls = + QString::fromUtf16(reinterpret_cast< ushort * >(wclsid), datasize / 2).toLower().trimmed(); CLSID clsid; - if (! blacklist.contains(qsCls) && ! FAILED(CLSIDFromString(wclsid, &clsid))) { + if (!blacklist.contains(qsCls) && !FAILED(CLSIDFromString(wclsid, &clsid))) { ASIODev ad(name, qsCls); qlDevs << ad; } @@ -176,9 +181,7 @@ ASIOConfig::ASIOConfig(Settings &st) : ConfigWidget(st) { ASIODev ad; - foreach(ad, qlDevs) { - qcbDevice->addItem(ad.first, QVariant(ad.second)); - } + foreach (ad, qlDevs) { qcbDevice->addItem(ad.first, QVariant(ad.second)); } if (qlDevs.count() == 0) { qpbQuery->setEnabled(false); @@ -193,8 +196,8 @@ void ASIOConfig::on_qpbQuery_clicked() { clearQuery(); - CLSIDFromString(const_cast<wchar_t *>(reinterpret_cast<const wchar_t *>(qsCls.utf16())), &clsid); - if (CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, clsid, reinterpret_cast<void **>(&iasio)) == S_OK) { + CLSIDFromString(const_cast< wchar_t * >(reinterpret_cast< const wchar_t * >(qsCls.utf16())), &clsid); + if (CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, clsid, reinterpret_cast< void ** >(&iasio)) == S_OK) { SleepEx(10, false); if (iasio->init(mumble_mw_hwnd)) { SleepEx(10, false); @@ -219,7 +222,12 @@ void ASIOConfig::on_qpbQuery_clicked() { QString str = tr("%1 (version %2)").arg(QLatin1String(buff)).arg(ver); qlName->setText(str); - str = tr("%1 -> %2 samples buffer, with %3 sample resolution (%4 preferred) at %5 Hz").arg(minSize).arg(maxSize).arg(granSize).arg(prefSize).arg(srate,0,'f',0); + str = tr("%1 -> %2 samples buffer, with %3 sample resolution (%4 preferred) at %5 Hz") + .arg(minSize) + .arg(maxSize) + .arg(granSize) + .arg(prefSize) + .arg(srate, 0, 'f', 0); qlBuffers->setText(str); @@ -230,7 +238,7 @@ void ASIOConfig::on_qpbQuery_clicked() { bool match = (s.qsASIOclass == qsCls); - for (cnum=0;cnum<ichannels;cnum++) { + for (cnum = 0; cnum < ichannels; cnum++) { ASIOChannelInfo aci; aci.channel = cnum; aci.isInput = true; @@ -241,18 +249,17 @@ void ASIOConfig::on_qpbQuery_clicked() { case ASIOSTInt32LSB: case ASIOSTInt24LSB: case ASIOSTInt16LSB: { - QListWidget *widget = qlwUnused; - QVariant v = static_cast<int>(cnum); - if (match && s.qlASIOmic.contains(v)) - widget = qlwMic; - else if (match && s.qlASIOspeaker.contains(v)) - widget = qlwSpeaker; - QListWidgetItem *item = new QListWidgetItem(QLatin1String(aci.name), widget); - item->setData(Qt::UserRole, static_cast<int>(cnum)); - } - break; + QListWidget *widget = qlwUnused; + QVariant v = static_cast< int >(cnum); + if (match && s.qlASIOmic.contains(v)) + widget = qlwMic; + else if (match && s.qlASIOspeaker.contains(v)) + widget = qlwSpeaker; + QListWidgetItem *item = new QListWidgetItem(QLatin1String(aci.name), widget); + item->setData(Qt::UserRole, static_cast< int >(cnum)); + } break; default: - qWarning("ASIOInput: Channel %ld %s (Unusable format %ld)", cnum, aci.name,aci.type); + qWarning("ASIOInput: Channel %ld %s (Unusable format %ld)", cnum, aci.name, aci.type); } } @@ -262,11 +269,14 @@ void ASIOConfig::on_qpbQuery_clicked() { char err[255]; iasio->getErrorMessage(err); SleepEx(10, false); - QMessageBox::critical(this, QLatin1String("Mumble"), tr("ASIO Initialization failed: %1").arg(QString::fromLatin1(err).toHtmlEscaped()), QMessageBox::Ok, QMessageBox::NoButton); + QMessageBox::critical(this, QLatin1String("Mumble"), + tr("ASIO Initialization failed: %1").arg(QString::fromLatin1(err).toHtmlEscaped()), + QMessageBox::Ok, QMessageBox::NoButton); } iasio->Release(); } else { - QMessageBox::critical(this, QLatin1String("Mumble"), tr("Failed to instantiate ASIO driver"), QMessageBox::Ok, QMessageBox::NoButton); + QMessageBox::critical(this, QLatin1String("Mumble"), tr("Failed to instantiate ASIO driver"), QMessageBox::Ok, + QMessageBox::NoButton); } } @@ -275,8 +285,8 @@ void ASIOConfig::on_qpbConfig_clicked() { CLSID clsid; IASIO *iasio; - CLSIDFromString(const_cast<wchar_t *>(reinterpret_cast<const wchar_t *>(qsCls.utf16())), &clsid); - if (CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, clsid, reinterpret_cast<void **>(&iasio)) == S_OK) { + CLSIDFromString(const_cast< wchar_t * >(reinterpret_cast< const wchar_t * >(qsCls.utf16())), &clsid); + if (CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, clsid, reinterpret_cast< void ** >(&iasio)) == S_OK) { SleepEx(10, false); if (iasio->init(mumble_mw_hwnd)) { SleepEx(10, false); @@ -287,11 +297,14 @@ void ASIOConfig::on_qpbConfig_clicked() { char err[255]; iasio->getErrorMessage(err); SleepEx(10, false); - QMessageBox::critical(this, QLatin1String("Mumble"), tr("ASIO Initialization failed: %1").arg(QString::fromLatin1(err).toHtmlEscaped()), QMessageBox::Ok, QMessageBox::NoButton); + QMessageBox::critical(this, QLatin1String("Mumble"), + tr("ASIO Initialization failed: %1").arg(QString::fromLatin1(err).toHtmlEscaped()), + QMessageBox::Ok, QMessageBox::NoButton); } iasio->Release(); } else { - QMessageBox::critical(this, QLatin1String("Mumble"), tr("Failed to instantiate ASIO driver"), QMessageBox::Ok, QMessageBox::NoButton); + QMessageBox::critical(this, QLatin1String("Mumble"), tr("Failed to instantiate ASIO driver"), QMessageBox::Ok, + QMessageBox::NoButton); } } @@ -340,14 +353,14 @@ QIcon ASIOConfig::icon() const { } void ASIOConfig::save() const { - if (! bOk) + if (!bOk) return; s.qsASIOclass = qcbDevice->itemData(qcbDevice->currentIndex()).toString(); - QList<QVariant> list; + QList< QVariant > list; - for (int i=0;i<qlwMic->count();i++) { + for (int i = 0; i < qlwMic->count(); i++) { QListWidgetItem *item = qlwMic->item(i); list << item->data(Qt::UserRole); } @@ -356,7 +369,7 @@ void ASIOConfig::save() const { list.clear(); - for (int i=0;i<qlwSpeaker->count();i++) { + for (int i = 0; i < qlwSpeaker->count(); i++) { QListWidgetItem *item = qlwSpeaker->item(i); list << item->data(Qt::UserRole); } @@ -367,13 +380,13 @@ void ASIOConfig::save() const { void ASIOConfig::load(const Settings &r) { int i = 0; ASIODev ad; - foreach(ad, qlDevs) { + foreach (ad, qlDevs) { if (ad.second == r.qsASIOclass) { loadComboBox(qcbDevice, i); } i++; } - s.qlASIOmic = r.qlASIOmic; + s.qlASIOmic = r.qlASIOmic; s.qlASIOspeaker = r.qlASIOspeaker; qlName->setText(QString()); @@ -396,22 +409,24 @@ ASIOInput::ASIOInput() { QString qsCls = g.s.qsASIOclass; CLSID clsid; - iasio = nullptr; + iasio = nullptr; abiInfo = nullptr; aciInfo = nullptr; // Sanity check things first. - iNumMic=g.s.qlASIOmic.count(); - iNumSpeaker=g.s.qlASIOspeaker.count(); + iNumMic = g.s.qlASIOmic.count(); + iNumSpeaker = g.s.qlASIOspeaker.count(); if ((iNumMic == 0) || (iNumSpeaker == 0)) { - QMessageBox::warning(nullptr, QLatin1String("Mumble"), tr("You need to select at least one microphone and one speaker source to use ASIO."), QMessageBox::Ok, QMessageBox::NoButton); + QMessageBox::warning(nullptr, QLatin1String("Mumble"), + tr("You need to select at least one microphone and one speaker source to use ASIO."), + QMessageBox::Ok, QMessageBox::NoButton); return; } - CLSIDFromString(const_cast<wchar_t *>(reinterpret_cast<const wchar_t *>(qsCls.utf16())), &clsid); - if (CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, clsid, reinterpret_cast<void **>(&iasio)) == S_OK) { + CLSIDFromString(const_cast< wchar_t * >(reinterpret_cast< const wchar_t * >(qsCls.utf16())), &clsid); + if (CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, clsid, reinterpret_cast< void ** >(&iasio)) == S_OK) { if (iasio->init(nullptr)) { iasio->setSampleRate(48000.0); ASIOSampleRate srate = 0.0; @@ -425,16 +440,16 @@ ASIOInput::ASIOInput() { bool halfit = true; - double wbuf = (srate / 100.0); + double wbuf = (srate / 100.0); long wantBuf = lround(wbuf); - lBufSize = wantBuf; + lBufSize = wantBuf; - if (static_cast<double>(wantBuf) == wbuf) { + if (static_cast< double >(wantBuf) == wbuf) { qWarning("ASIOInput: Exact buffer match possible."); if ((wantBuf >= minSize) && (wantBuf <= maxSize)) { if (wantBuf == minSize) halfit = false; - else if ((granSize >= 1) && (((wantBuf-minSize)%granSize)==0)) + else if ((granSize >= 1) && (((wantBuf - minSize) % granSize) == 0)) halfit = false; } } @@ -445,7 +460,7 @@ ASIOInput::ASIOInput() { lBufSize = minSize; } else { long target = wantBuf / 2; - lBufSize = target; + lBufSize = target; while (lBufSize < target) { if (granSize < 0) lBufSize *= 2; @@ -461,8 +476,8 @@ ASIOInput::ASIOInput() { aciInfo = new ASIOChannelInfo[iNumMic + iNumSpeaker]; int i, idx = 0; - for (i=0;i<iNumMic;i++) { - abiInfo[idx].isInput = true; + for (i = 0; i < iNumMic; i++) { + abiInfo[idx].isInput = true; abiInfo[idx].channelNum = g.s.qlASIOmic[i].toInt(); aciInfo[idx].channel = abiInfo[idx].channelNum; @@ -472,8 +487,8 @@ ASIOInput::ASIOInput() { idx++; } - for (i=0;i<iNumSpeaker;i++) { - abiInfo[idx].isInput = true; + for (i = 0; i < iNumSpeaker; i++) { + abiInfo[idx].isInput = true; abiInfo[idx].channelNum = g.s.qlASIOspeaker[i].toInt(); aciInfo[idx].channel = abiInfo[idx].channelNum; @@ -485,16 +500,16 @@ ASIOInput::ASIOInput() { } iEchoChannels = iNumSpeaker; - iMicChannels = iNumMic; + iMicChannels = iNumMic; iEchoFreq = iMicFreq = iroundf(srate); initializeMixer(); ASIOCallbacks asioCallbacks; ZeroMemory(&asioCallbacks, sizeof(asioCallbacks)); - asioCallbacks.bufferSwitch = &bufferSwitch; - asioCallbacks.sampleRateDidChange = &sampleRateChanged; - asioCallbacks.asioMessage = &asioMessages; + asioCallbacks.bufferSwitch = &bufferSwitch; + asioCallbacks.sampleRateDidChange = &sampleRateChanged; + asioCallbacks.asioMessage = &asioMessages; asioCallbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfo; if (iasio->createBuffers(abiInfo, idx, lBufSize, &asioCallbacks) == ASE_OK) { @@ -509,9 +524,9 @@ ASIOInput::ASIOInput() { iasio = nullptr; } - QMessageBox::critical(nullptr, QLatin1String("Mumble"), tr("Opening selected ASIO device failed. No input will be done."), - QMessageBox::Ok, QMessageBox::NoButton); - + QMessageBox::critical(nullptr, QLatin1String("Mumble"), + tr("Opening selected ASIO device failed. No input will be done."), QMessageBox::Ok, + QMessageBox::NoButton); } ASIOInput::~ASIOInput() { @@ -524,10 +539,10 @@ ASIOInput::~ASIOInput() { iasio = nullptr; } - delete [] abiInfo; + delete[] abiInfo; abiInfo = nullptr; - delete [] aciInfo; + delete[] aciInfo; aciInfo = nullptr; } @@ -546,54 +561,48 @@ ASIOTime *ASIOInput::bufferSwitchTimeInfo(ASIOTime *, long index, ASIOBool) { return 0L; } -void -ASIOInput::addBuffer(ASIOSampleType sampType, int interleave, void *src, float * RESTRICT dst) { +void ASIOInput::addBuffer(ASIOSampleType sampType, int interleave, void *src, float *RESTRICT dst) { switch (sampType) { case ASIOSTInt16LSB: { - const float m = 1.0f / 32768.f; - const short * RESTRICT buf=static_cast<short *>(src); - for (int i=0;i<lBufSize;i++) - dst[i*interleave]=buf[i] * m; - } - break; + const float m = 1.0f / 32768.f; + const short *RESTRICT buf = static_cast< short * >(src); + for (int i = 0; i < lBufSize; i++) + dst[i * interleave] = buf[i] * m; + } break; case ASIOSTInt32LSB: { - const float m = 1.0f / 2147483648.f; - const int * RESTRICT buf=static_cast<int *>(src); - for (int i=0;i<lBufSize;i++) - dst[i*interleave]=buf[i] * m; - } - break; + const float m = 1.0f / 2147483648.f; + const int *RESTRICT buf = static_cast< int * >(src); + for (int i = 0; i < lBufSize; i++) + dst[i * interleave] = buf[i] * m; + } break; case ASIOSTInt24LSB: { - const float m = 1.0f / static_cast<float>(0x7FFFFFFF - 0xFF); - const unsigned char * RESTRICT buf=static_cast<unsigned char *>(src); - for (int i=0;i<lBufSize;i++) - dst[i * interleave] = (buf[i*3] << 24 | buf[i*3+1] << 16 | buf[i*3+2] << 8) * m; - } - break; + const float m = 1.0f / static_cast< float >(0x7FFFFFFF - 0xFF); + const unsigned char *RESTRICT buf = static_cast< unsigned char * >(src); + for (int i = 0; i < lBufSize; i++) + dst[i * interleave] = (buf[i * 3] << 24 | buf[i * 3 + 1] << 16 | buf[i * 3 + 2] << 8) * m; + } break; case ASIOSTFloat32LSB: { - const float * RESTRICT buf=static_cast<float *>(src); - for (int i=0;i<lBufSize;i++) - dst[i*interleave]=buf[i]; - } - break; + const float *RESTRICT buf = static_cast< float * >(src); + for (int i = 0; i < lBufSize; i++) + dst[i * interleave] = buf[i]; + } break; } } -void -ASIOInput::bufferReady(long buffindex) { - STACKVAR(float, buffer, lBufSize * qMax(iNumMic,iNumSpeaker)); +void ASIOInput::bufferReady(long buffindex) { + STACKVAR(float, buffer, lBufSize *qMax(iNumMic, iNumSpeaker)); - for (int c=0;c<iNumSpeaker;++c) - addBuffer(aciInfo[iNumMic+c].type, iNumSpeaker, abiInfo[iNumMic+c].buffers[buffindex], buffer+c); + for (int c = 0; c < iNumSpeaker; ++c) + addBuffer(aciInfo[iNumMic + c].type, iNumSpeaker, abiInfo[iNumMic + c].buffers[buffindex], buffer + c); addEcho(buffer, lBufSize); - for (int c=0;c<iNumMic;++c) - addBuffer(aciInfo[c].type, iNumMic, abiInfo[c].buffers[buffindex], buffer+c); + for (int c = 0; c < iNumMic; ++c) + addBuffer(aciInfo[c].type, iNumMic, abiInfo[c].buffers[buffindex], buffer + c); addMic(buffer, lBufSize); } void ASIOInput::bufferSwitch(long index, ASIOBool processNow) { - ASIOTime timeInfo; + ASIOTime timeInfo; memset(&timeInfo, 0, sizeof(timeInfo)); if (aiSelf->iasio->getSamplePosition(&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK) @@ -606,17 +615,13 @@ void ASIOInput::sampleRateChanged(ASIOSampleRate) { qFatal("ASIOInput: sampleRateChanged"); } -long ASIOInput::asioMessages(long selector, long value, void*, double*) { +long ASIOInput::asioMessages(long selector, long value, void *, double *) { long ret = 0; switch (selector) { case kAsioSelectorSupported: - if (value == kAsioResetRequest - || value == kAsioEngineVersion - || value == kAsioResyncRequest - || value == kAsioLatenciesChanged - || value == kAsioSupportsTimeInfo - || value == kAsioSupportsTimeCode - || value == kAsioSupportsInputMonitor) + if (value == kAsioResetRequest || value == kAsioEngineVersion || value == kAsioResyncRequest + || value == kAsioLatenciesChanged || value == kAsioSupportsTimeInfo || value == kAsioSupportsTimeCode + || value == kAsioSupportsInputMonitor) ret = 1L; break; case kAsioResetRequest: diff --git a/src/mumble/ASIOInput.h b/src/mumble/ASIOInput.h index ab5a46d21..bfda5714c 100644 --- a/src/mumble/ASIOInput.h +++ b/src/mumble/ASIOInput.h @@ -22,67 +22,69 @@ #include <asiodrvr.h> -typedef QPair<QString, QString> ASIODev; +typedef QPair< QString, QString > ASIODev; class ASIOConfig : public ConfigWidget, public Ui::ASIOConfig { - private: - Q_OBJECT - Q_DISABLE_COPY(ASIOConfig) - protected: - QList<ASIODev> qlDevs; - bool bOk; - public: - /// The unique name of this ConfigWidget - static const QString name; - ASIOConfig(Settings &st); - virtual QString title() const Q_DECL_OVERRIDE; - virtual const QString &getName() const Q_DECL_OVERRIDE; - virtual QIcon icon() const Q_DECL_OVERRIDE; - public slots: - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; - void clearQuery(); - void on_qcbDevice_activated(int index); - void on_qpbQuery_clicked(); - void on_qpbConfig_clicked(); - void on_qpbAddMic_clicked(); - void on_qpbRemMic_clicked(); - void on_qpbAddSpeaker_clicked(); - void on_qpbRemSpeaker_clicked(); +private: + Q_OBJECT + Q_DISABLE_COPY(ASIOConfig) +protected: + QList< ASIODev > qlDevs; + bool bOk; + +public: + /// The unique name of this ConfigWidget + static const QString name; + ASIOConfig(Settings &st); + virtual QString title() const Q_DECL_OVERRIDE; + virtual const QString &getName() const Q_DECL_OVERRIDE; + virtual QIcon icon() const Q_DECL_OVERRIDE; +public slots: + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; + void clearQuery(); + void on_qcbDevice_activated(int index); + void on_qpbQuery_clicked(); + void on_qpbConfig_clicked(); + void on_qpbAddMic_clicked(); + void on_qpbRemMic_clicked(); + void on_qpbAddSpeaker_clicked(); + void on_qpbRemSpeaker_clicked(); }; #define IEEE754_64FLOAT 1 #include "asio.h" class ASIOInput : public AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(ASIOInput) - protected: - IASIO *iasio; - - int iNumMic, iNumSpeaker; - long lBufSize; - ASIOBufferInfo *abiInfo; - ASIOChannelInfo *aciInfo; - - // ASIO Callbacks - static ASIOInput *aiSelf; - - static void sampleRateChanged(ASIOSampleRate sRate); - static long asioMessages(long selector, long value, void* message, double* opt); - static void bufferSwitch(long index, ASIOBool processNow); - static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow); - - void addBuffer(long sampType, int interleave, void *src, float * RESTRICT dst); - void bufferReady(long index); - bool initializeDriver(); - - QWaitCondition qwDone; - public: - ASIOInput(); - ~ASIOInput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(ASIOInput) +protected: + IASIO *iasio; + + int iNumMic, iNumSpeaker; + long lBufSize; + ASIOBufferInfo *abiInfo; + ASIOChannelInfo *aciInfo; + + // ASIO Callbacks + static ASIOInput *aiSelf; + + static void sampleRateChanged(ASIOSampleRate sRate); + static long asioMessages(long selector, long value, void *message, double *opt); + static void bufferSwitch(long index, ASIOBool processNow); + static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow); + + void addBuffer(long sampType, int interleave, void *src, float *RESTRICT dst); + void bufferReady(long index); + bool initializeDriver(); + + QWaitCondition qwDone; + +public: + ASIOInput(); + ~ASIOInput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/About.cpp b/src/mumble/About.cpp index 403096a46..77d147598 100644 --- a/src/mumble/About.cpp +++ b/src/mumble/About.cpp @@ -5,20 +5,21 @@ #include "About.h" -#include "MainWindow.h" #include "License.h" +#include "MainWindow.h" #include "Utils.h" #include <QtWidgets/QPushButton> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" AboutDialog::AboutDialog(QWidget *p) : QDialog(p) { setWindowTitle(tr("About Mumble")); - QTabWidget *qtwTab = new QTabWidget(this); + QTabWidget *qtwTab = new QTabWidget(this); QVBoxLayout *vblMain = new QVBoxLayout(this); QTextEdit *qteLicense = new QTextEdit(qtwTab); @@ -36,12 +37,12 @@ AboutDialog::AboutDialog(QWidget *p) : QDialog(p) { qtb3rdPartyLicense->setOpenExternalLinks(true); qtb3rdPartyLicense->setAccessibleName(tr("Third-party license agreements")); - QList<LicenseInfo> thirdPartyLicenses = License::thirdPartyLicenses(); - foreach(LicenseInfo li, thirdPartyLicenses) { + QList< LicenseInfo > thirdPartyLicenses = License::thirdPartyLicenses(); + foreach (LicenseInfo li, thirdPartyLicenses) { qtb3rdPartyLicense->append(QString::fromLatin1("<h3>%1 (<a href=\"%2\">%2</a>)</h3><pre>%3</pre>") - .arg(li.name.toHtmlEscaped()) - .arg(li.url.toHtmlEscaped()) - .arg(li.license.toHtmlEscaped())); + .arg(li.name.toHtmlEscaped()) + .arg(li.url.toHtmlEscaped()) + .arg(li.license.toHtmlEscaped())); } qtb3rdPartyLicense->moveCursor(QTextCursor::Start); @@ -54,14 +55,13 @@ AboutDialog::AboutDialog(QWidget *p) : QDialog(p) { QLabel *text = new QLabel(about); text->setTextInteractionFlags(Qt::TextBrowserInteraction); text->setOpenExternalLinks(true); - text->setText(tr( - "<h3>Mumble (%1)</h3>" - "<p>%3</p>" - "<p><b>A voice-chat utility for gamers</b></p>" - "<p><tt><a href=\"%2\">%2</a></tt></p>" - ).arg(QLatin1String(MUMBLE_RELEASE)) - .arg(QLatin1String("https://www.mumble.info/")) - .arg(QLatin1String("Copyright 2005-2020 The Mumble Developers"))); + text->setText(tr("<h3>Mumble (%1)</h3>" + "<p>%3</p>" + "<p><b>A voice-chat utility for gamers</b></p>" + "<p><tt><a href=\"%2\">%2</a></tt></p>") + .arg(QLatin1String(MUMBLE_RELEASE)) + .arg(QLatin1String("https://www.mumble.info/")) + .arg(QLatin1String("Copyright 2005-2020 The Mumble Developers"))); QHBoxLayout *qhbl = new QHBoxLayout(about); qhbl->addWidget(icon); qhbl->addWidget(text); diff --git a/src/mumble/About.h b/src/mumble/About.h index 862876897..cde7bb633 100644 --- a/src/mumble/About.h +++ b/src/mumble/About.h @@ -6,16 +6,16 @@ #ifndef MUMBLE_MUMBLE_ABOUT_H_ #define MUMBLE_MUMBLE_ABOUT_H_ -#include <QtCore/QtGlobal> #include <QtCore/QObject> +#include <QtCore/QtGlobal> #include <QtWidgets/QDialog> class AboutDialog : public QDialog { - private: - Q_OBJECT - Q_DISABLE_COPY(AboutDialog) - public: - AboutDialog(QWidget *parent); +private: + Q_OBJECT + Q_DISABLE_COPY(AboutDialog) +public: + AboutDialog(QWidget *parent); }; #endif diff --git a/src/mumble/ApplicationPalette.h b/src/mumble/ApplicationPalette.h index 1b252fda6..88eb82fd8 100644 --- a/src/mumble/ApplicationPalette.h +++ b/src/mumble/ApplicationPalette.h @@ -10,31 +10,31 @@ #ifndef APPLICATIONPALETTE_H #define APPLICATIONPALETTE_H -#include <QWidget> #include <QTimer> +#include <QWidget> #ifndef Q_MOC_RUN -#include <boost/optional.hpp> +# include <boost/optional.hpp> #endif #include <QApplication> #include <QDebug> /// /// Class enabling theming of QApplication::palette from stylesheets. -/// +/// /// QPalette cannot be styled which creates issues as not all /// GUI elements in Qt can be styled. This class works around /// that by offering a QPROPERTY for each color role and group /// combination in QPalette. As you can set custom QPROPERTYs /// from stylesheet this allows the user to set all relevant /// palette brushes from the stylesheet. -/// +/// /// Due to restrictions on allowed property names as well as a /// mandatory prefix the attributes are exposed as lower cased: /// "qproperty-<role>_<group>". -/// +/// /// So a group of QPalette::Active and QPalette::Text role /// would be styled by: -/// +/// /// ApplicationPalette { /// qproperty-text_active: #ff0000; /* Set color for active group */ /// } @@ -44,1368 +44,1250 @@ /// /// You can also use the shorthand "qproperty-<role>" to set all groups /// to the same brush. -/// +/// /// The class will automatically pick up style changes on itself /// and update the application palette accordingly. To use the class /// simply instantiate it before setting the theme and keep it around /// till the application terminates. -/// -class ApplicationPalette : public QWidget -{ - Q_OBJECT - Q_PROPERTY(QBrush windowtext READ get_windowtext WRITE set_windowtext) - Q_PROPERTY(QBrush windowtext_active READ get_windowtext_active WRITE set_windowtext_active) - Q_PROPERTY(QBrush windowtext_disabled READ get_windowtext_disabled WRITE set_windowtext_disabled) - Q_PROPERTY(QBrush windowtext_inactive READ get_windowtext_inactive WRITE set_windowtext_inactive) - Q_PROPERTY(QBrush button READ get_button WRITE set_button) - Q_PROPERTY(QBrush button_active READ get_button_active WRITE set_button_active) - Q_PROPERTY(QBrush button_disabled READ get_button_disabled WRITE set_button_disabled) - Q_PROPERTY(QBrush button_inactive READ get_button_inactive WRITE set_button_inactive) - Q_PROPERTY(QBrush light READ get_light WRITE set_light) - Q_PROPERTY(QBrush light_active READ get_light_active WRITE set_light_active) - Q_PROPERTY(QBrush light_disabled READ get_light_disabled WRITE set_light_disabled) - Q_PROPERTY(QBrush light_inactive READ get_light_inactive WRITE set_light_inactive) - Q_PROPERTY(QBrush midlight READ get_midlight WRITE set_midlight) - Q_PROPERTY(QBrush midlight_active READ get_midlight_active WRITE set_midlight_active) - Q_PROPERTY(QBrush midlight_disabled READ get_midlight_disabled WRITE set_midlight_disabled) - Q_PROPERTY(QBrush midlight_inactive READ get_midlight_inactive WRITE set_midlight_inactive) - Q_PROPERTY(QBrush dark READ get_dark WRITE set_dark) - Q_PROPERTY(QBrush dark_active READ get_dark_active WRITE set_dark_active) - Q_PROPERTY(QBrush dark_disabled READ get_dark_disabled WRITE set_dark_disabled) - Q_PROPERTY(QBrush dark_inactive READ get_dark_inactive WRITE set_dark_inactive) - Q_PROPERTY(QBrush mid READ get_mid WRITE set_mid) - Q_PROPERTY(QBrush mid_active READ get_mid_active WRITE set_mid_active) - Q_PROPERTY(QBrush mid_disabled READ get_mid_disabled WRITE set_mid_disabled) - Q_PROPERTY(QBrush mid_inactive READ get_mid_inactive WRITE set_mid_inactive) - Q_PROPERTY(QBrush text READ get_text WRITE set_text) - Q_PROPERTY(QBrush text_active READ get_text_active WRITE set_text_active) - Q_PROPERTY(QBrush text_disabled READ get_text_disabled WRITE set_text_disabled) - Q_PROPERTY(QBrush text_inactive READ get_text_inactive WRITE set_text_inactive) - Q_PROPERTY(QBrush brighttext READ get_brighttext WRITE set_brighttext) - Q_PROPERTY(QBrush brighttext_active READ get_brighttext_active WRITE set_brighttext_active) - Q_PROPERTY(QBrush brighttext_disabled READ get_brighttext_disabled WRITE set_brighttext_disabled) - Q_PROPERTY(QBrush brighttext_inactive READ get_brighttext_inactive WRITE set_brighttext_inactive) - Q_PROPERTY(QBrush buttontext READ get_buttontext WRITE set_buttontext) - Q_PROPERTY(QBrush buttontext_active READ get_buttontext_active WRITE set_buttontext_active) - Q_PROPERTY(QBrush buttontext_disabled READ get_buttontext_disabled WRITE set_buttontext_disabled) - Q_PROPERTY(QBrush buttontext_inactive READ get_buttontext_inactive WRITE set_buttontext_inactive) - Q_PROPERTY(QBrush base READ get_base WRITE set_base) - Q_PROPERTY(QBrush base_active READ get_base_active WRITE set_base_active) - Q_PROPERTY(QBrush base_disabled READ get_base_disabled WRITE set_base_disabled) - Q_PROPERTY(QBrush base_inactive READ get_base_inactive WRITE set_base_inactive) - Q_PROPERTY(QBrush window READ get_window WRITE set_window) - Q_PROPERTY(QBrush window_active READ get_window_active WRITE set_window_active) - Q_PROPERTY(QBrush window_disabled READ get_window_disabled WRITE set_window_disabled) - Q_PROPERTY(QBrush window_inactive READ get_window_inactive WRITE set_window_inactive) - Q_PROPERTY(QBrush shadow READ get_shadow WRITE set_shadow) - Q_PROPERTY(QBrush shadow_active READ get_shadow_active WRITE set_shadow_active) - Q_PROPERTY(QBrush shadow_disabled READ get_shadow_disabled WRITE set_shadow_disabled) - Q_PROPERTY(QBrush shadow_inactive READ get_shadow_inactive WRITE set_shadow_inactive) - Q_PROPERTY(QBrush highlight READ get_highlight WRITE set_highlight) - Q_PROPERTY(QBrush highlight_active READ get_highlight_active WRITE set_highlight_active) - Q_PROPERTY(QBrush highlight_disabled READ get_highlight_disabled WRITE set_highlight_disabled) - Q_PROPERTY(QBrush highlight_inactive READ get_highlight_inactive WRITE set_highlight_inactive) - Q_PROPERTY(QBrush highlightedtext READ get_highlightedtext WRITE set_highlightedtext) - Q_PROPERTY(QBrush highlightedtext_active READ get_highlightedtext_active WRITE set_highlightedtext_active) - Q_PROPERTY(QBrush highlightedtext_disabled READ get_highlightedtext_disabled WRITE set_highlightedtext_disabled) - Q_PROPERTY(QBrush highlightedtext_inactive READ get_highlightedtext_inactive WRITE set_highlightedtext_inactive) - Q_PROPERTY(QBrush link READ get_link WRITE set_link) - Q_PROPERTY(QBrush link_active READ get_link_active WRITE set_link_active) - Q_PROPERTY(QBrush link_disabled READ get_link_disabled WRITE set_link_disabled) - Q_PROPERTY(QBrush link_inactive READ get_link_inactive WRITE set_link_inactive) - Q_PROPERTY(QBrush linkvisited READ get_linkvisited WRITE set_linkvisited) - Q_PROPERTY(QBrush linkvisited_active READ get_linkvisited_active WRITE set_linkvisited_active) - Q_PROPERTY(QBrush linkvisited_disabled READ get_linkvisited_disabled WRITE set_linkvisited_disabled) - Q_PROPERTY(QBrush linkvisited_inactive READ get_linkvisited_inactive WRITE set_linkvisited_inactive) - Q_PROPERTY(QBrush alternatebase READ get_alternatebase WRITE set_alternatebase) - Q_PROPERTY(QBrush alternatebase_active READ get_alternatebase_active WRITE set_alternatebase_active) - Q_PROPERTY(QBrush alternatebase_disabled READ get_alternatebase_disabled WRITE set_alternatebase_disabled) - Q_PROPERTY(QBrush alternatebase_inactive READ get_alternatebase_inactive WRITE set_alternatebase_inactive) - Q_PROPERTY(QBrush tooltipbase READ get_tooltipbase WRITE set_tooltipbase) - Q_PROPERTY(QBrush tooltipbase_active READ get_tooltipbase_active WRITE set_tooltipbase_active) - Q_PROPERTY(QBrush tooltipbase_disabled READ get_tooltipbase_disabled WRITE set_tooltipbase_disabled) - Q_PROPERTY(QBrush tooltipbase_inactive READ get_tooltipbase_inactive WRITE set_tooltipbase_inactive) - Q_PROPERTY(QBrush tooltiptext READ get_tooltiptext WRITE set_tooltiptext) - Q_PROPERTY(QBrush tooltiptext_active READ get_tooltiptext_active WRITE set_tooltiptext_active) - Q_PROPERTY(QBrush tooltiptext_disabled READ get_tooltiptext_disabled WRITE set_tooltiptext_disabled) - Q_PROPERTY(QBrush tooltiptext_inactive READ get_tooltiptext_inactive WRITE set_tooltiptext_inactive) - - public: - explicit ApplicationPalette(QWidget *p = 0) - : QWidget(p) - , m_originalPalette(QApplication::palette()){ - // Empty - } - +/// +class ApplicationPalette : public QWidget { + Q_OBJECT + Q_PROPERTY(QBrush windowtext READ get_windowtext WRITE set_windowtext) + Q_PROPERTY(QBrush windowtext_active READ get_windowtext_active WRITE set_windowtext_active) + Q_PROPERTY(QBrush windowtext_disabled READ get_windowtext_disabled WRITE set_windowtext_disabled) + Q_PROPERTY(QBrush windowtext_inactive READ get_windowtext_inactive WRITE set_windowtext_inactive) + Q_PROPERTY(QBrush button READ get_button WRITE set_button) + Q_PROPERTY(QBrush button_active READ get_button_active WRITE set_button_active) + Q_PROPERTY(QBrush button_disabled READ get_button_disabled WRITE set_button_disabled) + Q_PROPERTY(QBrush button_inactive READ get_button_inactive WRITE set_button_inactive) + Q_PROPERTY(QBrush light READ get_light WRITE set_light) + Q_PROPERTY(QBrush light_active READ get_light_active WRITE set_light_active) + Q_PROPERTY(QBrush light_disabled READ get_light_disabled WRITE set_light_disabled) + Q_PROPERTY(QBrush light_inactive READ get_light_inactive WRITE set_light_inactive) + Q_PROPERTY(QBrush midlight READ get_midlight WRITE set_midlight) + Q_PROPERTY(QBrush midlight_active READ get_midlight_active WRITE set_midlight_active) + Q_PROPERTY(QBrush midlight_disabled READ get_midlight_disabled WRITE set_midlight_disabled) + Q_PROPERTY(QBrush midlight_inactive READ get_midlight_inactive WRITE set_midlight_inactive) + Q_PROPERTY(QBrush dark READ get_dark WRITE set_dark) + Q_PROPERTY(QBrush dark_active READ get_dark_active WRITE set_dark_active) + Q_PROPERTY(QBrush dark_disabled READ get_dark_disabled WRITE set_dark_disabled) + Q_PROPERTY(QBrush dark_inactive READ get_dark_inactive WRITE set_dark_inactive) + Q_PROPERTY(QBrush mid READ get_mid WRITE set_mid) + Q_PROPERTY(QBrush mid_active READ get_mid_active WRITE set_mid_active) + Q_PROPERTY(QBrush mid_disabled READ get_mid_disabled WRITE set_mid_disabled) + Q_PROPERTY(QBrush mid_inactive READ get_mid_inactive WRITE set_mid_inactive) + Q_PROPERTY(QBrush text READ get_text WRITE set_text) + Q_PROPERTY(QBrush text_active READ get_text_active WRITE set_text_active) + Q_PROPERTY(QBrush text_disabled READ get_text_disabled WRITE set_text_disabled) + Q_PROPERTY(QBrush text_inactive READ get_text_inactive WRITE set_text_inactive) + Q_PROPERTY(QBrush brighttext READ get_brighttext WRITE set_brighttext) + Q_PROPERTY(QBrush brighttext_active READ get_brighttext_active WRITE set_brighttext_active) + Q_PROPERTY(QBrush brighttext_disabled READ get_brighttext_disabled WRITE set_brighttext_disabled) + Q_PROPERTY(QBrush brighttext_inactive READ get_brighttext_inactive WRITE set_brighttext_inactive) + Q_PROPERTY(QBrush buttontext READ get_buttontext WRITE set_buttontext) + Q_PROPERTY(QBrush buttontext_active READ get_buttontext_active WRITE set_buttontext_active) + Q_PROPERTY(QBrush buttontext_disabled READ get_buttontext_disabled WRITE set_buttontext_disabled) + Q_PROPERTY(QBrush buttontext_inactive READ get_buttontext_inactive WRITE set_buttontext_inactive) + Q_PROPERTY(QBrush base READ get_base WRITE set_base) + Q_PROPERTY(QBrush base_active READ get_base_active WRITE set_base_active) + Q_PROPERTY(QBrush base_disabled READ get_base_disabled WRITE set_base_disabled) + Q_PROPERTY(QBrush base_inactive READ get_base_inactive WRITE set_base_inactive) + Q_PROPERTY(QBrush window READ get_window WRITE set_window) + Q_PROPERTY(QBrush window_active READ get_window_active WRITE set_window_active) + Q_PROPERTY(QBrush window_disabled READ get_window_disabled WRITE set_window_disabled) + Q_PROPERTY(QBrush window_inactive READ get_window_inactive WRITE set_window_inactive) + Q_PROPERTY(QBrush shadow READ get_shadow WRITE set_shadow) + Q_PROPERTY(QBrush shadow_active READ get_shadow_active WRITE set_shadow_active) + Q_PROPERTY(QBrush shadow_disabled READ get_shadow_disabled WRITE set_shadow_disabled) + Q_PROPERTY(QBrush shadow_inactive READ get_shadow_inactive WRITE set_shadow_inactive) + Q_PROPERTY(QBrush highlight READ get_highlight WRITE set_highlight) + Q_PROPERTY(QBrush highlight_active READ get_highlight_active WRITE set_highlight_active) + Q_PROPERTY(QBrush highlight_disabled READ get_highlight_disabled WRITE set_highlight_disabled) + Q_PROPERTY(QBrush highlight_inactive READ get_highlight_inactive WRITE set_highlight_inactive) + Q_PROPERTY(QBrush highlightedtext READ get_highlightedtext WRITE set_highlightedtext) + Q_PROPERTY(QBrush highlightedtext_active READ get_highlightedtext_active WRITE set_highlightedtext_active) + Q_PROPERTY(QBrush highlightedtext_disabled READ get_highlightedtext_disabled WRITE set_highlightedtext_disabled) + Q_PROPERTY(QBrush highlightedtext_inactive READ get_highlightedtext_inactive WRITE set_highlightedtext_inactive) + Q_PROPERTY(QBrush link READ get_link WRITE set_link) + Q_PROPERTY(QBrush link_active READ get_link_active WRITE set_link_active) + Q_PROPERTY(QBrush link_disabled READ get_link_disabled WRITE set_link_disabled) + Q_PROPERTY(QBrush link_inactive READ get_link_inactive WRITE set_link_inactive) + Q_PROPERTY(QBrush linkvisited READ get_linkvisited WRITE set_linkvisited) + Q_PROPERTY(QBrush linkvisited_active READ get_linkvisited_active WRITE set_linkvisited_active) + Q_PROPERTY(QBrush linkvisited_disabled READ get_linkvisited_disabled WRITE set_linkvisited_disabled) + Q_PROPERTY(QBrush linkvisited_inactive READ get_linkvisited_inactive WRITE set_linkvisited_inactive) + Q_PROPERTY(QBrush alternatebase READ get_alternatebase WRITE set_alternatebase) + Q_PROPERTY(QBrush alternatebase_active READ get_alternatebase_active WRITE set_alternatebase_active) + Q_PROPERTY(QBrush alternatebase_disabled READ get_alternatebase_disabled WRITE set_alternatebase_disabled) + Q_PROPERTY(QBrush alternatebase_inactive READ get_alternatebase_inactive WRITE set_alternatebase_inactive) + Q_PROPERTY(QBrush tooltipbase READ get_tooltipbase WRITE set_tooltipbase) + Q_PROPERTY(QBrush tooltipbase_active READ get_tooltipbase_active WRITE set_tooltipbase_active) + Q_PROPERTY(QBrush tooltipbase_disabled READ get_tooltipbase_disabled WRITE set_tooltipbase_disabled) + Q_PROPERTY(QBrush tooltipbase_inactive READ get_tooltipbase_inactive WRITE set_tooltipbase_inactive) + Q_PROPERTY(QBrush tooltiptext READ get_tooltiptext WRITE set_tooltiptext) + Q_PROPERTY(QBrush tooltiptext_active READ get_tooltiptext_active WRITE set_tooltiptext_active) + Q_PROPERTY(QBrush tooltiptext_disabled READ get_tooltiptext_disabled WRITE set_tooltiptext_disabled) + Q_PROPERTY(QBrush tooltiptext_inactive READ get_tooltiptext_inactive WRITE set_tooltiptext_inactive) + +public: + explicit ApplicationPalette(QWidget *p = 0) : QWidget(p), m_originalPalette(QApplication::palette()) { + // Empty + } + QBrush get_windowtext() { - if (property("windowtext_active") == property("windowtext_disabled") && property("windowtext_active") == property("windowtext_inactive")) { - return qvariant_cast<QBrush>(property("windowtext_active")); + if (property("windowtext_active") == property("windowtext_disabled") + && property("windowtext_active") == property("windowtext_inactive")) { + return qvariant_cast< QBrush >(property("windowtext_active")); } return QBrush(); } - void set_windowtext(const QBrush& brush) { - m_windowtext_active = brush; + void set_windowtext(const QBrush &brush) { + m_windowtext_active = brush; m_windowtext_disabled = brush; m_windowtext_inactive = brush; - } - QBrush get_windowtext_active() { - if (!m_windowtext_active) - return QBrush(); + QBrush get_windowtext_active() { + if (!m_windowtext_active) + return QBrush(); - return *m_windowtext_active; - } + return *m_windowtext_active; + } - void set_windowtext_active(const QBrush& brush) { - m_windowtext_active = brush; - } + void set_windowtext_active(const QBrush &brush) { m_windowtext_active = brush; } - QBrush get_windowtext_disabled() { - if (!m_windowtext_disabled) - return QBrush(); + QBrush get_windowtext_disabled() { + if (!m_windowtext_disabled) + return QBrush(); - return *m_windowtext_disabled; - } + return *m_windowtext_disabled; + } - void set_windowtext_disabled(const QBrush& brush) { - m_windowtext_disabled = brush; - } + void set_windowtext_disabled(const QBrush &brush) { m_windowtext_disabled = brush; } - QBrush get_windowtext_inactive() { - if (!m_windowtext_inactive) - return QBrush(); + QBrush get_windowtext_inactive() { + if (!m_windowtext_inactive) + return QBrush(); - return *m_windowtext_inactive; - } + return *m_windowtext_inactive; + } - void set_windowtext_inactive(const QBrush& brush) { - m_windowtext_inactive = brush; - } + void set_windowtext_inactive(const QBrush &brush) { m_windowtext_inactive = brush; } QBrush get_button() { - if (property("button_active") == property("button_disabled") && property("button_active") == property("button_inactive")) { - return qvariant_cast<QBrush>(property("button_active")); + if (property("button_active") == property("button_disabled") + && property("button_active") == property("button_inactive")) { + return qvariant_cast< QBrush >(property("button_active")); } return QBrush(); } - void set_button(const QBrush& brush) { - m_button_active = brush; + void set_button(const QBrush &brush) { + m_button_active = brush; m_button_disabled = brush; m_button_inactive = brush; - } - QBrush get_button_active() { - if (!m_button_active) - return QBrush(); + QBrush get_button_active() { + if (!m_button_active) + return QBrush(); - return *m_button_active; - } + return *m_button_active; + } - void set_button_active(const QBrush& brush) { - m_button_active = brush; - } + void set_button_active(const QBrush &brush) { m_button_active = brush; } - QBrush get_button_disabled() { - if (!m_button_disabled) - return QBrush(); + QBrush get_button_disabled() { + if (!m_button_disabled) + return QBrush(); - return *m_button_disabled; - } + return *m_button_disabled; + } - void set_button_disabled(const QBrush& brush) { - m_button_disabled = brush; - } + void set_button_disabled(const QBrush &brush) { m_button_disabled = brush; } - QBrush get_button_inactive() { - if (!m_button_inactive) - return QBrush(); + QBrush get_button_inactive() { + if (!m_button_inactive) + return QBrush(); - return *m_button_inactive; - } + return *m_button_inactive; + } - void set_button_inactive(const QBrush& brush) { - m_button_inactive = brush; - } + void set_button_inactive(const QBrush &brush) { m_button_inactive = brush; } QBrush get_light() { - if (property("light_active") == property("light_disabled") && property("light_active") == property("light_inactive")) { - return qvariant_cast<QBrush>(property("light_active")); + if (property("light_active") == property("light_disabled") + && property("light_active") == property("light_inactive")) { + return qvariant_cast< QBrush >(property("light_active")); } return QBrush(); } - void set_light(const QBrush& brush) { - m_light_active = brush; + void set_light(const QBrush &brush) { + m_light_active = brush; m_light_disabled = brush; m_light_inactive = brush; - } - QBrush get_light_active() { - if (!m_light_active) - return QBrush(); + QBrush get_light_active() { + if (!m_light_active) + return QBrush(); - return *m_light_active; - } + return *m_light_active; + } - void set_light_active(const QBrush& brush) { - m_light_active = brush; - } + void set_light_active(const QBrush &brush) { m_light_active = brush; } - QBrush get_light_disabled() { - if (!m_light_disabled) - return QBrush(); + QBrush get_light_disabled() { + if (!m_light_disabled) + return QBrush(); - return *m_light_disabled; - } + return *m_light_disabled; + } - void set_light_disabled(const QBrush& brush) { - m_light_disabled = brush; - } + void set_light_disabled(const QBrush &brush) { m_light_disabled = brush; } - QBrush get_light_inactive() { - if (!m_light_inactive) - return QBrush(); + QBrush get_light_inactive() { + if (!m_light_inactive) + return QBrush(); - return *m_light_inactive; - } + return *m_light_inactive; + } - void set_light_inactive(const QBrush& brush) { - m_light_inactive = brush; - } + void set_light_inactive(const QBrush &brush) { m_light_inactive = brush; } QBrush get_midlight() { - if (property("midlight_active") == property("midlight_disabled") && property("midlight_active") == property("midlight_inactive")) { - return qvariant_cast<QBrush>(property("midlight_active")); + if (property("midlight_active") == property("midlight_disabled") + && property("midlight_active") == property("midlight_inactive")) { + return qvariant_cast< QBrush >(property("midlight_active")); } return QBrush(); } - void set_midlight(const QBrush& brush) { - m_midlight_active = brush; + void set_midlight(const QBrush &brush) { + m_midlight_active = brush; m_midlight_disabled = brush; m_midlight_inactive = brush; - } - QBrush get_midlight_active() { - if (!m_midlight_active) - return QBrush(); + QBrush get_midlight_active() { + if (!m_midlight_active) + return QBrush(); - return *m_midlight_active; - } + return *m_midlight_active; + } - void set_midlight_active(const QBrush& brush) { - m_midlight_active = brush; - } + void set_midlight_active(const QBrush &brush) { m_midlight_active = brush; } - QBrush get_midlight_disabled() { - if (!m_midlight_disabled) - return QBrush(); + QBrush get_midlight_disabled() { + if (!m_midlight_disabled) + return QBrush(); - return *m_midlight_disabled; - } + return *m_midlight_disabled; + } - void set_midlight_disabled(const QBrush& brush) { - m_midlight_disabled = brush; - } + void set_midlight_disabled(const QBrush &brush) { m_midlight_disabled = brush; } - QBrush get_midlight_inactive() { - if (!m_midlight_inactive) - return QBrush(); + QBrush get_midlight_inactive() { + if (!m_midlight_inactive) + return QBrush(); - return *m_midlight_inactive; - } + return *m_midlight_inactive; + } - void set_midlight_inactive(const QBrush& brush) { - m_midlight_inactive = brush; - } + void set_midlight_inactive(const QBrush &brush) { m_midlight_inactive = brush; } QBrush get_dark() { - if (property("dark_active") == property("dark_disabled") && property("dark_active") == property("dark_inactive")) { - return qvariant_cast<QBrush>(property("dark_active")); + if (property("dark_active") == property("dark_disabled") + && property("dark_active") == property("dark_inactive")) { + return qvariant_cast< QBrush >(property("dark_active")); } return QBrush(); } - void set_dark(const QBrush& brush) { - m_dark_active = brush; + void set_dark(const QBrush &brush) { + m_dark_active = brush; m_dark_disabled = brush; m_dark_inactive = brush; - } - QBrush get_dark_active() { - if (!m_dark_active) - return QBrush(); + QBrush get_dark_active() { + if (!m_dark_active) + return QBrush(); - return *m_dark_active; - } + return *m_dark_active; + } - void set_dark_active(const QBrush& brush) { - m_dark_active = brush; - } + void set_dark_active(const QBrush &brush) { m_dark_active = brush; } - QBrush get_dark_disabled() { - if (!m_dark_disabled) - return QBrush(); + QBrush get_dark_disabled() { + if (!m_dark_disabled) + return QBrush(); - return *m_dark_disabled; - } + return *m_dark_disabled; + } - void set_dark_disabled(const QBrush& brush) { - m_dark_disabled = brush; - } + void set_dark_disabled(const QBrush &brush) { m_dark_disabled = brush; } - QBrush get_dark_inactive() { - if (!m_dark_inactive) - return QBrush(); + QBrush get_dark_inactive() { + if (!m_dark_inactive) + return QBrush(); - return *m_dark_inactive; - } + return *m_dark_inactive; + } - void set_dark_inactive(const QBrush& brush) { - m_dark_inactive = brush; - } + void set_dark_inactive(const QBrush &brush) { m_dark_inactive = brush; } QBrush get_mid() { if (property("mid_active") == property("mid_disabled") && property("mid_active") == property("mid_inactive")) { - return qvariant_cast<QBrush>(property("mid_active")); + return qvariant_cast< QBrush >(property("mid_active")); } return QBrush(); } - void set_mid(const QBrush& brush) { - m_mid_active = brush; + void set_mid(const QBrush &brush) { + m_mid_active = brush; m_mid_disabled = brush; m_mid_inactive = brush; - } - QBrush get_mid_active() { - if (!m_mid_active) - return QBrush(); + QBrush get_mid_active() { + if (!m_mid_active) + return QBrush(); - return *m_mid_active; - } + return *m_mid_active; + } - void set_mid_active(const QBrush& brush) { - m_mid_active = brush; - } + void set_mid_active(const QBrush &brush) { m_mid_active = brush; } - QBrush get_mid_disabled() { - if (!m_mid_disabled) - return QBrush(); + QBrush get_mid_disabled() { + if (!m_mid_disabled) + return QBrush(); - return *m_mid_disabled; - } + return *m_mid_disabled; + } - void set_mid_disabled(const QBrush& brush) { - m_mid_disabled = brush; - } + void set_mid_disabled(const QBrush &brush) { m_mid_disabled = brush; } - QBrush get_mid_inactive() { - if (!m_mid_inactive) - return QBrush(); + QBrush get_mid_inactive() { + if (!m_mid_inactive) + return QBrush(); - return *m_mid_inactive; - } + return *m_mid_inactive; + } - void set_mid_inactive(const QBrush& brush) { - m_mid_inactive = brush; - } + void set_mid_inactive(const QBrush &brush) { m_mid_inactive = brush; } QBrush get_text() { - if (property("text_active") == property("text_disabled") && property("text_active") == property("text_inactive")) { - return qvariant_cast<QBrush>(property("text_active")); + if (property("text_active") == property("text_disabled") + && property("text_active") == property("text_inactive")) { + return qvariant_cast< QBrush >(property("text_active")); } return QBrush(); } - void set_text(const QBrush& brush) { - m_text_active = brush; + void set_text(const QBrush &brush) { + m_text_active = brush; m_text_disabled = brush; m_text_inactive = brush; - } - QBrush get_text_active() { - if (!m_text_active) - return QBrush(); + QBrush get_text_active() { + if (!m_text_active) + return QBrush(); - return *m_text_active; - } + return *m_text_active; + } - void set_text_active(const QBrush& brush) { - m_text_active = brush; - } + void set_text_active(const QBrush &brush) { m_text_active = brush; } - QBrush get_text_disabled() { - if (!m_text_disabled) - return QBrush(); + QBrush get_text_disabled() { + if (!m_text_disabled) + return QBrush(); - return *m_text_disabled; - } + return *m_text_disabled; + } - void set_text_disabled(const QBrush& brush) { - m_text_disabled = brush; - } + void set_text_disabled(const QBrush &brush) { m_text_disabled = brush; } - QBrush get_text_inactive() { - if (!m_text_inactive) - return QBrush(); + QBrush get_text_inactive() { + if (!m_text_inactive) + return QBrush(); - return *m_text_inactive; - } + return *m_text_inactive; + } - void set_text_inactive(const QBrush& brush) { - m_text_inactive = brush; - } + void set_text_inactive(const QBrush &brush) { m_text_inactive = brush; } QBrush get_brighttext() { - if (property("brighttext_active") == property("brighttext_disabled") && property("brighttext_active") == property("brighttext_inactive")) { - return qvariant_cast<QBrush>(property("brighttext_active")); + if (property("brighttext_active") == property("brighttext_disabled") + && property("brighttext_active") == property("brighttext_inactive")) { + return qvariant_cast< QBrush >(property("brighttext_active")); } return QBrush(); } - void set_brighttext(const QBrush& brush) { - m_brighttext_active = brush; + void set_brighttext(const QBrush &brush) { + m_brighttext_active = brush; m_brighttext_disabled = brush; m_brighttext_inactive = brush; - } - QBrush get_brighttext_active() { - if (!m_brighttext_active) - return QBrush(); + QBrush get_brighttext_active() { + if (!m_brighttext_active) + return QBrush(); - return *m_brighttext_active; - } + return *m_brighttext_active; + } - void set_brighttext_active(const QBrush& brush) { - m_brighttext_active = brush; - } + void set_brighttext_active(const QBrush &brush) { m_brighttext_active = brush; } - QBrush get_brighttext_disabled() { - if (!m_brighttext_disabled) - return QBrush(); + QBrush get_brighttext_disabled() { + if (!m_brighttext_disabled) + return QBrush(); - return *m_brighttext_disabled; - } + return *m_brighttext_disabled; + } - void set_brighttext_disabled(const QBrush& brush) { - m_brighttext_disabled = brush; - } + void set_brighttext_disabled(const QBrush &brush) { m_brighttext_disabled = brush; } - QBrush get_brighttext_inactive() { - if (!m_brighttext_inactive) - return QBrush(); + QBrush get_brighttext_inactive() { + if (!m_brighttext_inactive) + return QBrush(); - return *m_brighttext_inactive; - } + return *m_brighttext_inactive; + } - void set_brighttext_inactive(const QBrush& brush) { - m_brighttext_inactive = brush; - } + void set_brighttext_inactive(const QBrush &brush) { m_brighttext_inactive = brush; } QBrush get_buttontext() { - if (property("buttontext_active") == property("buttontext_disabled") && property("buttontext_active") == property("buttontext_inactive")) { - return qvariant_cast<QBrush>(property("buttontext_active")); + if (property("buttontext_active") == property("buttontext_disabled") + && property("buttontext_active") == property("buttontext_inactive")) { + return qvariant_cast< QBrush >(property("buttontext_active")); } return QBrush(); } - void set_buttontext(const QBrush& brush) { - m_buttontext_active = brush; + void set_buttontext(const QBrush &brush) { + m_buttontext_active = brush; m_buttontext_disabled = brush; m_buttontext_inactive = brush; - } - QBrush get_buttontext_active() { - if (!m_buttontext_active) - return QBrush(); + QBrush get_buttontext_active() { + if (!m_buttontext_active) + return QBrush(); - return *m_buttontext_active; - } + return *m_buttontext_active; + } - void set_buttontext_active(const QBrush& brush) { - m_buttontext_active = brush; - } + void set_buttontext_active(const QBrush &brush) { m_buttontext_active = brush; } - QBrush get_buttontext_disabled() { - if (!m_buttontext_disabled) - return QBrush(); + QBrush get_buttontext_disabled() { + if (!m_buttontext_disabled) + return QBrush(); - return *m_buttontext_disabled; - } + return *m_buttontext_disabled; + } - void set_buttontext_disabled(const QBrush& brush) { - m_buttontext_disabled = brush; - } + void set_buttontext_disabled(const QBrush &brush) { m_buttontext_disabled = brush; } - QBrush get_buttontext_inactive() { - if (!m_buttontext_inactive) - return QBrush(); + QBrush get_buttontext_inactive() { + if (!m_buttontext_inactive) + return QBrush(); - return *m_buttontext_inactive; - } + return *m_buttontext_inactive; + } - void set_buttontext_inactive(const QBrush& brush) { - m_buttontext_inactive = brush; - } + void set_buttontext_inactive(const QBrush &brush) { m_buttontext_inactive = brush; } QBrush get_base() { - if (property("base_active") == property("base_disabled") && property("base_active") == property("base_inactive")) { - return qvariant_cast<QBrush>(property("base_active")); + if (property("base_active") == property("base_disabled") + && property("base_active") == property("base_inactive")) { + return qvariant_cast< QBrush >(property("base_active")); } return QBrush(); } - void set_base(const QBrush& brush) { - m_base_active = brush; + void set_base(const QBrush &brush) { + m_base_active = brush; m_base_disabled = brush; m_base_inactive = brush; - } - QBrush get_base_active() { - if (!m_base_active) - return QBrush(); + QBrush get_base_active() { + if (!m_base_active) + return QBrush(); - return *m_base_active; - } + return *m_base_active; + } - void set_base_active(const QBrush& brush) { - m_base_active = brush; - } + void set_base_active(const QBrush &brush) { m_base_active = brush; } - QBrush get_base_disabled() { - if (!m_base_disabled) - return QBrush(); + QBrush get_base_disabled() { + if (!m_base_disabled) + return QBrush(); - return *m_base_disabled; - } + return *m_base_disabled; + } - void set_base_disabled(const QBrush& brush) { - m_base_disabled = brush; - } + void set_base_disabled(const QBrush &brush) { m_base_disabled = brush; } - QBrush get_base_inactive() { - if (!m_base_inactive) - return QBrush(); + QBrush get_base_inactive() { + if (!m_base_inactive) + return QBrush(); - return *m_base_inactive; - } + return *m_base_inactive; + } - void set_base_inactive(const QBrush& brush) { - m_base_inactive = brush; - } + void set_base_inactive(const QBrush &brush) { m_base_inactive = brush; } QBrush get_window() { - if (property("window_active") == property("window_disabled") && property("window_active") == property("window_inactive")) { - return qvariant_cast<QBrush>(property("window_active")); + if (property("window_active") == property("window_disabled") + && property("window_active") == property("window_inactive")) { + return qvariant_cast< QBrush >(property("window_active")); } return QBrush(); } - void set_window(const QBrush& brush) { - m_window_active = brush; + void set_window(const QBrush &brush) { + m_window_active = brush; m_window_disabled = brush; m_window_inactive = brush; - } - QBrush get_window_active() { - if (!m_window_active) - return QBrush(); + QBrush get_window_active() { + if (!m_window_active) + return QBrush(); - return *m_window_active; - } + return *m_window_active; + } - void set_window_active(const QBrush& brush) { - m_window_active = brush; - } + void set_window_active(const QBrush &brush) { m_window_active = brush; } - QBrush get_window_disabled() { - if (!m_window_disabled) - return QBrush(); + QBrush get_window_disabled() { + if (!m_window_disabled) + return QBrush(); - return *m_window_disabled; - } + return *m_window_disabled; + } - void set_window_disabled(const QBrush& brush) { - m_window_disabled = brush; - } + void set_window_disabled(const QBrush &brush) { m_window_disabled = brush; } - QBrush get_window_inactive() { - if (!m_window_inactive) - return QBrush(); + QBrush get_window_inactive() { + if (!m_window_inactive) + return QBrush(); - return *m_window_inactive; - } + return *m_window_inactive; + } - void set_window_inactive(const QBrush& brush) { - m_window_inactive = brush; - } + void set_window_inactive(const QBrush &brush) { m_window_inactive = brush; } QBrush get_shadow() { - if (property("shadow_active") == property("shadow_disabled") && property("shadow_active") == property("shadow_inactive")) { - return qvariant_cast<QBrush>(property("shadow_active")); + if (property("shadow_active") == property("shadow_disabled") + && property("shadow_active") == property("shadow_inactive")) { + return qvariant_cast< QBrush >(property("shadow_active")); } return QBrush(); } - void set_shadow(const QBrush& brush) { - m_shadow_active = brush; + void set_shadow(const QBrush &brush) { + m_shadow_active = brush; m_shadow_disabled = brush; m_shadow_inactive = brush; - } - QBrush get_shadow_active() { - if (!m_shadow_active) - return QBrush(); + QBrush get_shadow_active() { + if (!m_shadow_active) + return QBrush(); - return *m_shadow_active; - } + return *m_shadow_active; + } - void set_shadow_active(const QBrush& brush) { - m_shadow_active = brush; - } + void set_shadow_active(const QBrush &brush) { m_shadow_active = brush; } - QBrush get_shadow_disabled() { - if (!m_shadow_disabled) - return QBrush(); + QBrush get_shadow_disabled() { + if (!m_shadow_disabled) + return QBrush(); - return *m_shadow_disabled; - } + return *m_shadow_disabled; + } - void set_shadow_disabled(const QBrush& brush) { - m_shadow_disabled = brush; - } + void set_shadow_disabled(const QBrush &brush) { m_shadow_disabled = brush; } - QBrush get_shadow_inactive() { - if (!m_shadow_inactive) - return QBrush(); + QBrush get_shadow_inactive() { + if (!m_shadow_inactive) + return QBrush(); - return *m_shadow_inactive; - } + return *m_shadow_inactive; + } - void set_shadow_inactive(const QBrush& brush) { - m_shadow_inactive = brush; - } + void set_shadow_inactive(const QBrush &brush) { m_shadow_inactive = brush; } QBrush get_highlight() { - if (property("highlight_active") == property("highlight_disabled") && property("highlight_active") == property("highlight_inactive")) { - return qvariant_cast<QBrush>(property("highlight_active")); + if (property("highlight_active") == property("highlight_disabled") + && property("highlight_active") == property("highlight_inactive")) { + return qvariant_cast< QBrush >(property("highlight_active")); } return QBrush(); } - void set_highlight(const QBrush& brush) { - m_highlight_active = brush; + void set_highlight(const QBrush &brush) { + m_highlight_active = brush; m_highlight_disabled = brush; m_highlight_inactive = brush; - } - QBrush get_highlight_active() { - if (!m_highlight_active) - return QBrush(); + QBrush get_highlight_active() { + if (!m_highlight_active) + return QBrush(); - return *m_highlight_active; - } + return *m_highlight_active; + } - void set_highlight_active(const QBrush& brush) { - m_highlight_active = brush; - } + void set_highlight_active(const QBrush &brush) { m_highlight_active = brush; } - QBrush get_highlight_disabled() { - if (!m_highlight_disabled) - return QBrush(); + QBrush get_highlight_disabled() { + if (!m_highlight_disabled) + return QBrush(); - return *m_highlight_disabled; - } + return *m_highlight_disabled; + } - void set_highlight_disabled(const QBrush& brush) { - m_highlight_disabled = brush; - } + void set_highlight_disabled(const QBrush &brush) { m_highlight_disabled = brush; } - QBrush get_highlight_inactive() { - if (!m_highlight_inactive) - return QBrush(); + QBrush get_highlight_inactive() { + if (!m_highlight_inactive) + return QBrush(); - return *m_highlight_inactive; - } + return *m_highlight_inactive; + } - void set_highlight_inactive(const QBrush& brush) { - m_highlight_inactive = brush; - } + void set_highlight_inactive(const QBrush &brush) { m_highlight_inactive = brush; } QBrush get_highlightedtext() { - if (property("highlightedtext_active") == property("highlightedtext_disabled") && property("highlightedtext_active") == property("highlightedtext_inactive")) { - return qvariant_cast<QBrush>(property("highlightedtext_active")); + if (property("highlightedtext_active") == property("highlightedtext_disabled") + && property("highlightedtext_active") == property("highlightedtext_inactive")) { + return qvariant_cast< QBrush >(property("highlightedtext_active")); } return QBrush(); } - void set_highlightedtext(const QBrush& brush) { - m_highlightedtext_active = brush; + void set_highlightedtext(const QBrush &brush) { + m_highlightedtext_active = brush; m_highlightedtext_disabled = brush; m_highlightedtext_inactive = brush; - } - QBrush get_highlightedtext_active() { - if (!m_highlightedtext_active) - return QBrush(); + QBrush get_highlightedtext_active() { + if (!m_highlightedtext_active) + return QBrush(); - return *m_highlightedtext_active; - } + return *m_highlightedtext_active; + } - void set_highlightedtext_active(const QBrush& brush) { - m_highlightedtext_active = brush; - } + void set_highlightedtext_active(const QBrush &brush) { m_highlightedtext_active = brush; } - QBrush get_highlightedtext_disabled() { - if (!m_highlightedtext_disabled) - return QBrush(); + QBrush get_highlightedtext_disabled() { + if (!m_highlightedtext_disabled) + return QBrush(); - return *m_highlightedtext_disabled; - } + return *m_highlightedtext_disabled; + } - void set_highlightedtext_disabled(const QBrush& brush) { - m_highlightedtext_disabled = brush; - } + void set_highlightedtext_disabled(const QBrush &brush) { m_highlightedtext_disabled = brush; } - QBrush get_highlightedtext_inactive() { - if (!m_highlightedtext_inactive) - return QBrush(); + QBrush get_highlightedtext_inactive() { + if (!m_highlightedtext_inactive) + return QBrush(); - return *m_highlightedtext_inactive; - } + return *m_highlightedtext_inactive; + } - void set_highlightedtext_inactive(const QBrush& brush) { - m_highlightedtext_inactive = brush; - } + void set_highlightedtext_inactive(const QBrush &brush) { m_highlightedtext_inactive = brush; } QBrush get_link() { - if (property("link_active") == property("link_disabled") && property("link_active") == property("link_inactive")) { - return qvariant_cast<QBrush>(property("link_active")); + if (property("link_active") == property("link_disabled") + && property("link_active") == property("link_inactive")) { + return qvariant_cast< QBrush >(property("link_active")); } return QBrush(); } - void set_link(const QBrush& brush) { - m_link_active = brush; + void set_link(const QBrush &brush) { + m_link_active = brush; m_link_disabled = brush; m_link_inactive = brush; - } - QBrush get_link_active() { - if (!m_link_active) - return QBrush(); + QBrush get_link_active() { + if (!m_link_active) + return QBrush(); - return *m_link_active; - } + return *m_link_active; + } - void set_link_active(const QBrush& brush) { - m_link_active = brush; - } + void set_link_active(const QBrush &brush) { m_link_active = brush; } - QBrush get_link_disabled() { - if (!m_link_disabled) - return QBrush(); + QBrush get_link_disabled() { + if (!m_link_disabled) + return QBrush(); - return *m_link_disabled; - } + return *m_link_disabled; + } - void set_link_disabled(const QBrush& brush) { - m_link_disabled = brush; - } + void set_link_disabled(const QBrush &brush) { m_link_disabled = brush; } - QBrush get_link_inactive() { - if (!m_link_inactive) - return QBrush(); + QBrush get_link_inactive() { + if (!m_link_inactive) + return QBrush(); - return *m_link_inactive; - } + return *m_link_inactive; + } - void set_link_inactive(const QBrush& brush) { - m_link_inactive = brush; - } + void set_link_inactive(const QBrush &brush) { m_link_inactive = brush; } QBrush get_linkvisited() { - if (property("linkvisited_active") == property("linkvisited_disabled") && property("linkvisited_active") == property("linkvisited_inactive")) { - return qvariant_cast<QBrush>(property("linkvisited_active")); + if (property("linkvisited_active") == property("linkvisited_disabled") + && property("linkvisited_active") == property("linkvisited_inactive")) { + return qvariant_cast< QBrush >(property("linkvisited_active")); } return QBrush(); } - void set_linkvisited(const QBrush& brush) { - m_linkvisited_active = brush; + void set_linkvisited(const QBrush &brush) { + m_linkvisited_active = brush; m_linkvisited_disabled = brush; m_linkvisited_inactive = brush; - } - QBrush get_linkvisited_active() { - if (!m_linkvisited_active) - return QBrush(); + QBrush get_linkvisited_active() { + if (!m_linkvisited_active) + return QBrush(); - return *m_linkvisited_active; - } + return *m_linkvisited_active; + } - void set_linkvisited_active(const QBrush& brush) { - m_linkvisited_active = brush; - } + void set_linkvisited_active(const QBrush &brush) { m_linkvisited_active = brush; } - QBrush get_linkvisited_disabled() { - if (!m_linkvisited_disabled) - return QBrush(); + QBrush get_linkvisited_disabled() { + if (!m_linkvisited_disabled) + return QBrush(); - return *m_linkvisited_disabled; - } + return *m_linkvisited_disabled; + } - void set_linkvisited_disabled(const QBrush& brush) { - m_linkvisited_disabled = brush; - } + void set_linkvisited_disabled(const QBrush &brush) { m_linkvisited_disabled = brush; } - QBrush get_linkvisited_inactive() { - if (!m_linkvisited_inactive) - return QBrush(); + QBrush get_linkvisited_inactive() { + if (!m_linkvisited_inactive) + return QBrush(); - return *m_linkvisited_inactive; - } + return *m_linkvisited_inactive; + } - void set_linkvisited_inactive(const QBrush& brush) { - m_linkvisited_inactive = brush; - } + void set_linkvisited_inactive(const QBrush &brush) { m_linkvisited_inactive = brush; } QBrush get_alternatebase() { - if (property("alternatebase_active") == property("alternatebase_disabled") && property("alternatebase_active") == property("alternatebase_inactive")) { - return qvariant_cast<QBrush>(property("alternatebase_active")); + if (property("alternatebase_active") == property("alternatebase_disabled") + && property("alternatebase_active") == property("alternatebase_inactive")) { + return qvariant_cast< QBrush >(property("alternatebase_active")); } return QBrush(); } - void set_alternatebase(const QBrush& brush) { - m_alternatebase_active = brush; + void set_alternatebase(const QBrush &brush) { + m_alternatebase_active = brush; m_alternatebase_disabled = brush; m_alternatebase_inactive = brush; - } - QBrush get_alternatebase_active() { - if (!m_alternatebase_active) - return QBrush(); + QBrush get_alternatebase_active() { + if (!m_alternatebase_active) + return QBrush(); - return *m_alternatebase_active; - } + return *m_alternatebase_active; + } - void set_alternatebase_active(const QBrush& brush) { - m_alternatebase_active = brush; - } + void set_alternatebase_active(const QBrush &brush) { m_alternatebase_active = brush; } - QBrush get_alternatebase_disabled() { - if (!m_alternatebase_disabled) - return QBrush(); + QBrush get_alternatebase_disabled() { + if (!m_alternatebase_disabled) + return QBrush(); - return *m_alternatebase_disabled; - } + return *m_alternatebase_disabled; + } - void set_alternatebase_disabled(const QBrush& brush) { - m_alternatebase_disabled = brush; - } + void set_alternatebase_disabled(const QBrush &brush) { m_alternatebase_disabled = brush; } - QBrush get_alternatebase_inactive() { - if (!m_alternatebase_inactive) - return QBrush(); + QBrush get_alternatebase_inactive() { + if (!m_alternatebase_inactive) + return QBrush(); - return *m_alternatebase_inactive; - } + return *m_alternatebase_inactive; + } - void set_alternatebase_inactive(const QBrush& brush) { - m_alternatebase_inactive = brush; - } + void set_alternatebase_inactive(const QBrush &brush) { m_alternatebase_inactive = brush; } QBrush get_tooltipbase() { - if (property("tooltipbase_active") == property("tooltipbase_disabled") && property("tooltipbase_active") == property("tooltipbase_inactive")) { - return qvariant_cast<QBrush>(property("tooltipbase_active")); + if (property("tooltipbase_active") == property("tooltipbase_disabled") + && property("tooltipbase_active") == property("tooltipbase_inactive")) { + return qvariant_cast< QBrush >(property("tooltipbase_active")); } return QBrush(); } - void set_tooltipbase(const QBrush& brush) { - m_tooltipbase_active = brush; + void set_tooltipbase(const QBrush &brush) { + m_tooltipbase_active = brush; m_tooltipbase_disabled = brush; m_tooltipbase_inactive = brush; + } + + QBrush get_tooltipbase_active() { + if (!m_tooltipbase_active) + return QBrush(); + + return *m_tooltipbase_active; + } + + void set_tooltipbase_active(const QBrush &brush) { m_tooltipbase_active = brush; } + + QBrush get_tooltipbase_disabled() { + if (!m_tooltipbase_disabled) + return QBrush(); + + return *m_tooltipbase_disabled; + } + + void set_tooltipbase_disabled(const QBrush &brush) { m_tooltipbase_disabled = brush; } + QBrush get_tooltipbase_inactive() { + if (!m_tooltipbase_inactive) + return QBrush(); + + return *m_tooltipbase_inactive; } - QBrush get_tooltipbase_active() { - if (!m_tooltipbase_active) - return QBrush(); + void set_tooltipbase_inactive(const QBrush &brush) { m_tooltipbase_inactive = brush; } - return *m_tooltipbase_active; + QBrush get_tooltiptext() { + if (property("tooltiptext_active") == property("tooltiptext_disabled") + && property("tooltiptext_active") == property("tooltiptext_inactive")) { + return qvariant_cast< QBrush >(property("tooltiptext_active")); } + return QBrush(); + } + + void set_tooltiptext(const QBrush &brush) { + m_tooltiptext_active = brush; + m_tooltiptext_disabled = brush; + m_tooltiptext_inactive = brush; + } + + QBrush get_tooltiptext_active() { + if (!m_tooltiptext_active) + return QBrush(); + + return *m_tooltiptext_active; + } + + void set_tooltiptext_active(const QBrush &brush) { m_tooltiptext_active = brush; } + + QBrush get_tooltiptext_disabled() { + if (!m_tooltiptext_disabled) + return QBrush(); + + return *m_tooltiptext_disabled; + } + + void set_tooltiptext_disabled(const QBrush &brush) { m_tooltiptext_disabled = brush; } + + QBrush get_tooltiptext_inactive() { + if (!m_tooltiptext_inactive) + return QBrush(); - void set_tooltipbase_active(const QBrush& brush) { - m_tooltipbase_active = brush; + return *m_tooltiptext_inactive; + } + + void set_tooltiptext_inactive(const QBrush &brush) { m_tooltiptext_inactive = brush; } + + +private slots: + void updateApplicationPalette() { + qWarning() << "Updating application palette"; + + QPalette newPalette = m_originalPalette; // Do not re-use potentially already styled palette. Might not pick up + // system style changes though. + + + if (m_windowtext_active) { + newPalette.setBrush(QPalette::Active, QPalette::WindowText, *m_windowtext_active); } - QBrush get_tooltipbase_disabled() { - if (!m_tooltipbase_disabled) - return QBrush(); + if (m_windowtext_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::WindowText, *m_windowtext_disabled); + } - return *m_tooltipbase_disabled; + if (m_windowtext_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::WindowText, *m_windowtext_inactive); } - void set_tooltipbase_disabled(const QBrush& brush) { - m_tooltipbase_disabled = brush; + if (m_button_active) { + newPalette.setBrush(QPalette::Active, QPalette::Button, *m_button_active); } - QBrush get_tooltipbase_inactive() { - if (!m_tooltipbase_inactive) - return QBrush(); + if (m_button_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Button, *m_button_disabled); + } - return *m_tooltipbase_inactive; + if (m_button_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Button, *m_button_inactive); } - void set_tooltipbase_inactive(const QBrush& brush) { - m_tooltipbase_inactive = brush; + if (m_light_active) { + newPalette.setBrush(QPalette::Active, QPalette::Light, *m_light_active); } - QBrush get_tooltiptext() { - if (property("tooltiptext_active") == property("tooltiptext_disabled") && property("tooltiptext_active") == property("tooltiptext_inactive")) { - return qvariant_cast<QBrush>(property("tooltiptext_active")); + if (m_light_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Light, *m_light_disabled); } - return QBrush(); - } - void set_tooltiptext(const QBrush& brush) { - m_tooltiptext_active = brush; - m_tooltiptext_disabled = brush; - m_tooltiptext_inactive = brush; + if (m_light_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Light, *m_light_inactive); + } - } + if (m_midlight_active) { + newPalette.setBrush(QPalette::Active, QPalette::Midlight, *m_midlight_active); + } - QBrush get_tooltiptext_active() { - if (!m_tooltiptext_active) - return QBrush(); + if (m_midlight_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Midlight, *m_midlight_disabled); + } - return *m_tooltiptext_active; + if (m_midlight_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Midlight, *m_midlight_inactive); } - void set_tooltiptext_active(const QBrush& brush) { - m_tooltiptext_active = brush; + if (m_dark_active) { + newPalette.setBrush(QPalette::Active, QPalette::Dark, *m_dark_active); } - QBrush get_tooltiptext_disabled() { - if (!m_tooltiptext_disabled) - return QBrush(); + if (m_dark_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Dark, *m_dark_disabled); + } - return *m_tooltiptext_disabled; + if (m_dark_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Dark, *m_dark_inactive); } - void set_tooltiptext_disabled(const QBrush& brush) { - m_tooltiptext_disabled = brush; + if (m_mid_active) { + newPalette.setBrush(QPalette::Active, QPalette::Mid, *m_mid_active); } - QBrush get_tooltiptext_inactive() { - if (!m_tooltiptext_inactive) - return QBrush(); + if (m_mid_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Mid, *m_mid_disabled); + } - return *m_tooltiptext_inactive; + if (m_mid_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Mid, *m_mid_inactive); } - void set_tooltiptext_inactive(const QBrush& brush) { - m_tooltiptext_inactive = brush; + if (m_text_active) { + newPalette.setBrush(QPalette::Active, QPalette::Text, *m_text_active); } - - private slots: - void updateApplicationPalette() { - qWarning() << "Updating application palette"; - - QPalette newPalette = m_originalPalette; // Do not re-use potentially already styled palette. Might not pick up system style changes though. + if (m_text_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Text, *m_text_disabled); + } + if (m_text_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Text, *m_text_inactive); + } + + if (m_brighttext_active) { + newPalette.setBrush(QPalette::Active, QPalette::BrightText, *m_brighttext_active); + } + + if (m_brighttext_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::BrightText, *m_brighttext_disabled); + } + + if (m_brighttext_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::BrightText, *m_brighttext_inactive); + } + + if (m_buttontext_active) { + newPalette.setBrush(QPalette::Active, QPalette::ButtonText, *m_buttontext_active); + } + + if (m_buttontext_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::ButtonText, *m_buttontext_disabled); + } + + if (m_buttontext_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::ButtonText, *m_buttontext_inactive); + } - if (m_windowtext_active) { - newPalette.setBrush(QPalette::Active, QPalette::WindowText, *m_windowtext_active); - } + if (m_base_active) { + newPalette.setBrush(QPalette::Active, QPalette::Base, *m_base_active); + } - if (m_windowtext_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::WindowText, *m_windowtext_disabled); - } + if (m_base_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Base, *m_base_disabled); + } - if (m_windowtext_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::WindowText, *m_windowtext_inactive); - } + if (m_base_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Base, *m_base_inactive); + } - if (m_button_active) { - newPalette.setBrush(QPalette::Active, QPalette::Button, *m_button_active); - } + if (m_window_active) { + newPalette.setBrush(QPalette::Active, QPalette::Window, *m_window_active); + } - if (m_button_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Button, *m_button_disabled); - } + if (m_window_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Window, *m_window_disabled); + } - if (m_button_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Button, *m_button_inactive); - } + if (m_window_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Window, *m_window_inactive); + } - if (m_light_active) { - newPalette.setBrush(QPalette::Active, QPalette::Light, *m_light_active); - } + if (m_shadow_active) { + newPalette.setBrush(QPalette::Active, QPalette::Shadow, *m_shadow_active); + } - if (m_light_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Light, *m_light_disabled); - } + if (m_shadow_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Shadow, *m_shadow_disabled); + } - if (m_light_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Light, *m_light_inactive); - } + if (m_shadow_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Shadow, *m_shadow_inactive); + } - if (m_midlight_active) { - newPalette.setBrush(QPalette::Active, QPalette::Midlight, *m_midlight_active); - } + if (m_highlight_active) { + newPalette.setBrush(QPalette::Active, QPalette::Highlight, *m_highlight_active); + } - if (m_midlight_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Midlight, *m_midlight_disabled); - } + if (m_highlight_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Highlight, *m_highlight_disabled); + } - if (m_midlight_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Midlight, *m_midlight_inactive); - } + if (m_highlight_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Highlight, *m_highlight_inactive); + } - if (m_dark_active) { - newPalette.setBrush(QPalette::Active, QPalette::Dark, *m_dark_active); - } + if (m_highlightedtext_active) { + newPalette.setBrush(QPalette::Active, QPalette::HighlightedText, *m_highlightedtext_active); + } - if (m_dark_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Dark, *m_dark_disabled); - } + if (m_highlightedtext_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::HighlightedText, *m_highlightedtext_disabled); + } - if (m_dark_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Dark, *m_dark_inactive); - } + if (m_highlightedtext_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::HighlightedText, *m_highlightedtext_inactive); + } - if (m_mid_active) { - newPalette.setBrush(QPalette::Active, QPalette::Mid, *m_mid_active); - } + if (m_link_active) { + newPalette.setBrush(QPalette::Active, QPalette::Link, *m_link_active); + } - if (m_mid_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Mid, *m_mid_disabled); - } + if (m_link_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::Link, *m_link_disabled); + } - if (m_mid_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Mid, *m_mid_inactive); - } + if (m_link_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::Link, *m_link_inactive); + } - if (m_text_active) { - newPalette.setBrush(QPalette::Active, QPalette::Text, *m_text_active); - } + if (m_linkvisited_active) { + newPalette.setBrush(QPalette::Active, QPalette::LinkVisited, *m_linkvisited_active); + } - if (m_text_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Text, *m_text_disabled); - } + if (m_linkvisited_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::LinkVisited, *m_linkvisited_disabled); + } - if (m_text_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Text, *m_text_inactive); - } + if (m_linkvisited_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::LinkVisited, *m_linkvisited_inactive); + } - if (m_brighttext_active) { - newPalette.setBrush(QPalette::Active, QPalette::BrightText, *m_brighttext_active); - } + if (m_alternatebase_active) { + newPalette.setBrush(QPalette::Active, QPalette::AlternateBase, *m_alternatebase_active); + } - if (m_brighttext_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::BrightText, *m_brighttext_disabled); - } + if (m_alternatebase_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::AlternateBase, *m_alternatebase_disabled); + } - if (m_brighttext_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::BrightText, *m_brighttext_inactive); - } + if (m_alternatebase_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::AlternateBase, *m_alternatebase_inactive); + } - if (m_buttontext_active) { - newPalette.setBrush(QPalette::Active, QPalette::ButtonText, *m_buttontext_active); - } + if (m_tooltipbase_active) { + newPalette.setBrush(QPalette::Active, QPalette::ToolTipBase, *m_tooltipbase_active); + } - if (m_buttontext_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::ButtonText, *m_buttontext_disabled); - } + if (m_tooltipbase_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::ToolTipBase, *m_tooltipbase_disabled); + } - if (m_buttontext_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::ButtonText, *m_buttontext_inactive); - } + if (m_tooltipbase_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::ToolTipBase, *m_tooltipbase_inactive); + } - if (m_base_active) { - newPalette.setBrush(QPalette::Active, QPalette::Base, *m_base_active); - } + if (m_tooltiptext_active) { + newPalette.setBrush(QPalette::Active, QPalette::ToolTipText, *m_tooltiptext_active); + } - if (m_base_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Base, *m_base_disabled); - } + if (m_tooltiptext_disabled) { + newPalette.setBrush(QPalette::Disabled, QPalette::ToolTipText, *m_tooltiptext_disabled); + } - if (m_base_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Base, *m_base_inactive); - } + if (m_tooltiptext_inactive) { + newPalette.setBrush(QPalette::Inactive, QPalette::ToolTipText, *m_tooltiptext_inactive); + } - if (m_window_active) { - newPalette.setBrush(QPalette::Active, QPalette::Window, *m_window_active); - } - if (m_window_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Window, *m_window_disabled); - } + QApplication::setPalette(newPalette); + resetAllProperties(); + } - if (m_window_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Window, *m_window_inactive); - } + void resetAllProperties() { + m_windowtext_active = boost::none; + m_windowtext_disabled = boost::none; + m_windowtext_inactive = boost::none; + m_button_active = boost::none; + m_button_disabled = boost::none; + m_button_inactive = boost::none; + m_light_active = boost::none; + m_light_disabled = boost::none; + m_light_inactive = boost::none; + m_midlight_active = boost::none; + m_midlight_disabled = boost::none; + m_midlight_inactive = boost::none; + m_dark_active = boost::none; + m_dark_disabled = boost::none; + m_dark_inactive = boost::none; + m_mid_active = boost::none; + m_mid_disabled = boost::none; + m_mid_inactive = boost::none; + m_text_active = boost::none; + m_text_disabled = boost::none; + m_text_inactive = boost::none; + m_brighttext_active = boost::none; + m_brighttext_disabled = boost::none; + m_brighttext_inactive = boost::none; + m_buttontext_active = boost::none; + m_buttontext_disabled = boost::none; + m_buttontext_inactive = boost::none; + m_base_active = boost::none; + m_base_disabled = boost::none; + m_base_inactive = boost::none; + m_window_active = boost::none; + m_window_disabled = boost::none; + m_window_inactive = boost::none; + m_shadow_active = boost::none; + m_shadow_disabled = boost::none; + m_shadow_inactive = boost::none; + m_highlight_active = boost::none; + m_highlight_disabled = boost::none; + m_highlight_inactive = boost::none; + m_highlightedtext_active = boost::none; + m_highlightedtext_disabled = boost::none; + m_highlightedtext_inactive = boost::none; + m_link_active = boost::none; + m_link_disabled = boost::none; + m_link_inactive = boost::none; + m_linkvisited_active = boost::none; + m_linkvisited_disabled = boost::none; + m_linkvisited_inactive = boost::none; + m_alternatebase_active = boost::none; + m_alternatebase_disabled = boost::none; + m_alternatebase_inactive = boost::none; + m_tooltipbase_active = boost::none; + m_tooltipbase_disabled = boost::none; + m_tooltipbase_inactive = boost::none; + m_tooltiptext_active = boost::none; + m_tooltiptext_disabled = boost::none; + m_tooltiptext_inactive = boost::none; + } - if (m_shadow_active) { - newPalette.setBrush(QPalette::Active, QPalette::Shadow, *m_shadow_active); - } +protected: + bool event(QEvent *e) Q_DECL_OVERRIDE { + bool result = QWidget::event(e); - if (m_shadow_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Shadow, *m_shadow_disabled); - } + if (e->type() == QEvent::StyleChange) { + // Update global palette. Have to defer it + // as property updates are also signals. + QTimer::singleShot(0, this, SLOT(updateApplicationPalette())); + } - if (m_shadow_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Shadow, *m_shadow_inactive); - } - - if (m_highlight_active) { - newPalette.setBrush(QPalette::Active, QPalette::Highlight, *m_highlight_active); - } - - if (m_highlight_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Highlight, *m_highlight_disabled); - } - - if (m_highlight_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Highlight, *m_highlight_inactive); - } - - if (m_highlightedtext_active) { - newPalette.setBrush(QPalette::Active, QPalette::HighlightedText, *m_highlightedtext_active); - } - - if (m_highlightedtext_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::HighlightedText, *m_highlightedtext_disabled); - } - - if (m_highlightedtext_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::HighlightedText, *m_highlightedtext_inactive); - } - - if (m_link_active) { - newPalette.setBrush(QPalette::Active, QPalette::Link, *m_link_active); - } - - if (m_link_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::Link, *m_link_disabled); - } - - if (m_link_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::Link, *m_link_inactive); - } - - if (m_linkvisited_active) { - newPalette.setBrush(QPalette::Active, QPalette::LinkVisited, *m_linkvisited_active); - } - - if (m_linkvisited_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::LinkVisited, *m_linkvisited_disabled); - } - - if (m_linkvisited_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::LinkVisited, *m_linkvisited_inactive); - } - - if (m_alternatebase_active) { - newPalette.setBrush(QPalette::Active, QPalette::AlternateBase, *m_alternatebase_active); - } - - if (m_alternatebase_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::AlternateBase, *m_alternatebase_disabled); - } - - if (m_alternatebase_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::AlternateBase, *m_alternatebase_inactive); - } - - if (m_tooltipbase_active) { - newPalette.setBrush(QPalette::Active, QPalette::ToolTipBase, *m_tooltipbase_active); - } - - if (m_tooltipbase_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::ToolTipBase, *m_tooltipbase_disabled); - } - - if (m_tooltipbase_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::ToolTipBase, *m_tooltipbase_inactive); - } - - if (m_tooltiptext_active) { - newPalette.setBrush(QPalette::Active, QPalette::ToolTipText, *m_tooltiptext_active); - } - - if (m_tooltiptext_disabled) { - newPalette.setBrush(QPalette::Disabled, QPalette::ToolTipText, *m_tooltiptext_disabled); - } - - if (m_tooltiptext_inactive) { - newPalette.setBrush(QPalette::Inactive, QPalette::ToolTipText, *m_tooltiptext_inactive); - } - - - QApplication::setPalette(newPalette); - resetAllProperties(); - } - - void resetAllProperties() { - m_windowtext_active = boost::none; - m_windowtext_disabled = boost::none; - m_windowtext_inactive = boost::none; - m_button_active = boost::none; - m_button_disabled = boost::none; - m_button_inactive = boost::none; - m_light_active = boost::none; - m_light_disabled = boost::none; - m_light_inactive = boost::none; - m_midlight_active = boost::none; - m_midlight_disabled = boost::none; - m_midlight_inactive = boost::none; - m_dark_active = boost::none; - m_dark_disabled = boost::none; - m_dark_inactive = boost::none; - m_mid_active = boost::none; - m_mid_disabled = boost::none; - m_mid_inactive = boost::none; - m_text_active = boost::none; - m_text_disabled = boost::none; - m_text_inactive = boost::none; - m_brighttext_active = boost::none; - m_brighttext_disabled = boost::none; - m_brighttext_inactive = boost::none; - m_buttontext_active = boost::none; - m_buttontext_disabled = boost::none; - m_buttontext_inactive = boost::none; - m_base_active = boost::none; - m_base_disabled = boost::none; - m_base_inactive = boost::none; - m_window_active = boost::none; - m_window_disabled = boost::none; - m_window_inactive = boost::none; - m_shadow_active = boost::none; - m_shadow_disabled = boost::none; - m_shadow_inactive = boost::none; - m_highlight_active = boost::none; - m_highlight_disabled = boost::none; - m_highlight_inactive = boost::none; - m_highlightedtext_active = boost::none; - m_highlightedtext_disabled = boost::none; - m_highlightedtext_inactive = boost::none; - m_link_active = boost::none; - m_link_disabled = boost::none; - m_link_inactive = boost::none; - m_linkvisited_active = boost::none; - m_linkvisited_disabled = boost::none; - m_linkvisited_inactive = boost::none; - m_alternatebase_active = boost::none; - m_alternatebase_disabled = boost::none; - m_alternatebase_inactive = boost::none; - m_tooltipbase_active = boost::none; - m_tooltipbase_disabled = boost::none; - m_tooltipbase_inactive = boost::none; - m_tooltiptext_active = boost::none; - m_tooltiptext_disabled = boost::none; - m_tooltiptext_inactive = boost::none; - - } - - protected: - bool event(QEvent *e) Q_DECL_OVERRIDE { - bool result = QWidget::event(e); - - if (e->type() == QEvent::StyleChange) { - // Update global palette. Have to defer it - // as property updates are also signals. - QTimer::singleShot(0, this, SLOT(updateApplicationPalette())); - } - - return result; - } - private: - const QPalette m_originalPalette; - - boost::optional<QBrush> m_windowtext_active; - boost::optional<QBrush> m_windowtext_disabled; - boost::optional<QBrush> m_windowtext_inactive; - boost::optional<QBrush> m_button_active; - boost::optional<QBrush> m_button_disabled; - boost::optional<QBrush> m_button_inactive; - boost::optional<QBrush> m_light_active; - boost::optional<QBrush> m_light_disabled; - boost::optional<QBrush> m_light_inactive; - boost::optional<QBrush> m_midlight_active; - boost::optional<QBrush> m_midlight_disabled; - boost::optional<QBrush> m_midlight_inactive; - boost::optional<QBrush> m_dark_active; - boost::optional<QBrush> m_dark_disabled; - boost::optional<QBrush> m_dark_inactive; - boost::optional<QBrush> m_mid_active; - boost::optional<QBrush> m_mid_disabled; - boost::optional<QBrush> m_mid_inactive; - boost::optional<QBrush> m_text_active; - boost::optional<QBrush> m_text_disabled; - boost::optional<QBrush> m_text_inactive; - boost::optional<QBrush> m_brighttext_active; - boost::optional<QBrush> m_brighttext_disabled; - boost::optional<QBrush> m_brighttext_inactive; - boost::optional<QBrush> m_buttontext_active; - boost::optional<QBrush> m_buttontext_disabled; - boost::optional<QBrush> m_buttontext_inactive; - boost::optional<QBrush> m_base_active; - boost::optional<QBrush> m_base_disabled; - boost::optional<QBrush> m_base_inactive; - boost::optional<QBrush> m_window_active; - boost::optional<QBrush> m_window_disabled; - boost::optional<QBrush> m_window_inactive; - boost::optional<QBrush> m_shadow_active; - boost::optional<QBrush> m_shadow_disabled; - boost::optional<QBrush> m_shadow_inactive; - boost::optional<QBrush> m_highlight_active; - boost::optional<QBrush> m_highlight_disabled; - boost::optional<QBrush> m_highlight_inactive; - boost::optional<QBrush> m_highlightedtext_active; - boost::optional<QBrush> m_highlightedtext_disabled; - boost::optional<QBrush> m_highlightedtext_inactive; - boost::optional<QBrush> m_link_active; - boost::optional<QBrush> m_link_disabled; - boost::optional<QBrush> m_link_inactive; - boost::optional<QBrush> m_linkvisited_active; - boost::optional<QBrush> m_linkvisited_disabled; - boost::optional<QBrush> m_linkvisited_inactive; - boost::optional<QBrush> m_alternatebase_active; - boost::optional<QBrush> m_alternatebase_disabled; - boost::optional<QBrush> m_alternatebase_inactive; - boost::optional<QBrush> m_tooltipbase_active; - boost::optional<QBrush> m_tooltipbase_disabled; - boost::optional<QBrush> m_tooltipbase_inactive; - boost::optional<QBrush> m_tooltiptext_active; - boost::optional<QBrush> m_tooltiptext_disabled; - boost::optional<QBrush> m_tooltiptext_inactive; + return result; + } +private: + const QPalette m_originalPalette; + + boost::optional< QBrush > m_windowtext_active; + boost::optional< QBrush > m_windowtext_disabled; + boost::optional< QBrush > m_windowtext_inactive; + boost::optional< QBrush > m_button_active; + boost::optional< QBrush > m_button_disabled; + boost::optional< QBrush > m_button_inactive; + boost::optional< QBrush > m_light_active; + boost::optional< QBrush > m_light_disabled; + boost::optional< QBrush > m_light_inactive; + boost::optional< QBrush > m_midlight_active; + boost::optional< QBrush > m_midlight_disabled; + boost::optional< QBrush > m_midlight_inactive; + boost::optional< QBrush > m_dark_active; + boost::optional< QBrush > m_dark_disabled; + boost::optional< QBrush > m_dark_inactive; + boost::optional< QBrush > m_mid_active; + boost::optional< QBrush > m_mid_disabled; + boost::optional< QBrush > m_mid_inactive; + boost::optional< QBrush > m_text_active; + boost::optional< QBrush > m_text_disabled; + boost::optional< QBrush > m_text_inactive; + boost::optional< QBrush > m_brighttext_active; + boost::optional< QBrush > m_brighttext_disabled; + boost::optional< QBrush > m_brighttext_inactive; + boost::optional< QBrush > m_buttontext_active; + boost::optional< QBrush > m_buttontext_disabled; + boost::optional< QBrush > m_buttontext_inactive; + boost::optional< QBrush > m_base_active; + boost::optional< QBrush > m_base_disabled; + boost::optional< QBrush > m_base_inactive; + boost::optional< QBrush > m_window_active; + boost::optional< QBrush > m_window_disabled; + boost::optional< QBrush > m_window_inactive; + boost::optional< QBrush > m_shadow_active; + boost::optional< QBrush > m_shadow_disabled; + boost::optional< QBrush > m_shadow_inactive; + boost::optional< QBrush > m_highlight_active; + boost::optional< QBrush > m_highlight_disabled; + boost::optional< QBrush > m_highlight_inactive; + boost::optional< QBrush > m_highlightedtext_active; + boost::optional< QBrush > m_highlightedtext_disabled; + boost::optional< QBrush > m_highlightedtext_inactive; + boost::optional< QBrush > m_link_active; + boost::optional< QBrush > m_link_disabled; + boost::optional< QBrush > m_link_inactive; + boost::optional< QBrush > m_linkvisited_active; + boost::optional< QBrush > m_linkvisited_disabled; + boost::optional< QBrush > m_linkvisited_inactive; + boost::optional< QBrush > m_alternatebase_active; + boost::optional< QBrush > m_alternatebase_disabled; + boost::optional< QBrush > m_alternatebase_inactive; + boost::optional< QBrush > m_tooltipbase_active; + boost::optional< QBrush > m_tooltipbase_disabled; + boost::optional< QBrush > m_tooltipbase_inactive; + boost::optional< QBrush > m_tooltiptext_active; + boost::optional< QBrush > m_tooltiptext_disabled; + boost::optional< QBrush > m_tooltiptext_inactive; }; #endif // APPLICATIONPALETTE_H diff --git a/src/mumble/ApplicationPaletteTemplate.h b/src/mumble/ApplicationPaletteTemplate.h index 8e408b20c..5c841aefd 100644 --- a/src/mumble/ApplicationPaletteTemplate.h +++ b/src/mumble/ApplicationPaletteTemplate.h @@ -5,96 +5,91 @@ // See scripts/generate-ApplicationPalette-class.py -%(warning)s - +% (warning) s #ifndef APPLICATIONPALETTE_H #define APPLICATIONPALETTE_H -#include <QWidget> #include <QTimer> +#include <QWidget> #ifndef Q_MOC_RUN -#include <boost/optional.hpp> +# include <boost/optional.hpp> #endif #include <QApplication> #include <QDebug> -/// -/// Class enabling theming of QApplication::palette from stylesheets. -/// -/// QPalette cannot be styled which creates issues as not all -/// GUI elements in Qt can be styled. This class works around -/// that by offering a QPROPERTY for each color role and group -/// combination in QPalette. As you can set custom QPROPERTYs -/// from stylesheet this allows the user to set all relevant -/// palette brushes from the stylesheet. -/// -/// Due to restrictions on allowed property names as well as a -/// mandatory prefix the attributes are exposed as lower cased: -/// "qproperty-<role>_<group>". -/// -/// So a group of QPalette::Active and QPalette::Text role -/// would be styled by: -/// -/// ApplicationPalette { -/// qproperty-text_active: #ff0000; /* Set color for active group */ -/// } -/// -/// See http://qt-project.org/doc/qt-4.8/qpalette.html#ColorGroup-enum -/// for the available groups and roles. -/// -/// You can also use the shorthand "qproperty-<role>" to set all groups -/// to the same brush. -/// -/// The class will automatically pick up style changes on itself -/// and update the application palette accordingly. To use the class -/// simply instantiate it before setting the theme and keep it around -/// till the application terminates. -/// -class ApplicationPalette : public QWidget -{ - Q_OBJECT -%(properties)s - public: - explicit ApplicationPalette(QWidget *p = 0) - : QWidget(p) - , m_originalPalette(QApplication::palette()){ - // Empty - } - -%(getterssetters)s - - private slots: - void updateApplicationPalette() { - qWarning() << "Updating application palette"; - - QPalette newPalette = m_originalPalette; // Do not re-use potentially already styled palette. Might not pick up system style changes though. - -%(paletteupdates)s - - QApplication::setPalette(newPalette); - resetAllProperties(); - } - - void resetAllProperties() { -%(propertyresets)s - } + /// + /// Class enabling theming of QApplication::palette from stylesheets. + /// + /// QPalette cannot be styled which creates issues as not all + /// GUI elements in Qt can be styled. This class works around + /// that by offering a QPROPERTY for each color role and group + /// combination in QPalette. As you can set custom QPROPERTYs + /// from stylesheet this allows the user to set all relevant + /// palette brushes from the stylesheet. + /// + /// Due to restrictions on allowed property names as well as a + /// mandatory prefix the attributes are exposed as lower cased: + /// "qproperty-<role>_<group>". + /// + /// So a group of QPalette::Active and QPalette::Text role + /// would be styled by: + /// + /// ApplicationPalette { + /// qproperty-text_active: #ff0000; /* Set color for active group */ + /// } + /// + /// See http://qt-project.org/doc/qt-4.8/qpalette.html#ColorGroup-enum + /// for the available groups and roles. + /// + /// You can also use the shorthand "qproperty-<role>" to set all groups + /// to the same brush. + /// + /// The class will automatically pick up style changes on itself + /// and update the application palette accordingly. To use the class + /// simply instantiate it before setting the theme and keep it around + /// till the application terminates. + /// + class ApplicationPalette : public QWidget { + Q_OBJECT + % (properties) s public : explicit ApplicationPalette(QWidget *p = 0) + : QWidget(p), + m_originalPalette(QApplication::palette()){ + // Empty + } + + % (getterssetters) s + + private slots : void updateApplicationPalette() { + qWarning() << "Updating application palette"; - protected: - bool event(QEvent *e) Q_DECL_OVERRIDE { - bool result = QWidget::event(e); - - if (e->type() == QEvent::StyleChange) { - // Update global palette. Have to defer it - // as property updates are also signals. - QTimer::singleShot(0, this, SLOT(updateApplicationPalette())); - } - - return result; + QPalette newPalette = m_originalPalette; // Do not re-use potentially already styled palette. Might not pick up + // system style changes though. + + % (paletteupdates) s + + QApplication::setPalette(newPalette); + resetAllProperties(); + } + + void resetAllProperties() { % (propertyresets) s } + +protected: + bool event(QEvent *e) Q_DECL_OVERRIDE { + bool result = QWidget::event(e); + + if (e->type() == QEvent::StyleChange) { + // Update global palette. Have to defer it + // as property updates are also signals. + QTimer::singleShot(0, this, SLOT(updateApplicationPalette())); } - private: - const QPalette m_originalPalette; - -%(variables)s + + return result; + } + +private: + const QPalette m_originalPalette; + + % (variables) s }; #endif // APPLICATIONPALETTE_H diff --git a/src/mumble/Audio.cpp b/src/mumble/Audio.cpp index 31cc481b7..051055a8d 100644 --- a/src/mumble/Audio.cpp +++ b/src/mumble/Audio.cpp @@ -9,23 +9,24 @@ #include "AudioOutput.h" #include "CELTCodec.h" #ifdef USE_OPUS -# include "OpusCodec.h" +# include "OpusCodec.h" #endif -#include "PacketDataStream.h" #include "Log.h" +#include "PacketDataStream.h" #include <QtCore/QObject> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" class CodecInit : public DeferInit { - public: - void initialize(); - void destroy(); +public: + void initialize(); + void destroy(); }; -#define DOUBLE_RAND (rand()/static_cast<double>(RAND_MAX)) +#define DOUBLE_RAND (rand() / static_cast< double >(RAND_MAX)) LoopUser LoopUser::lpLoopy; CodecInit ciInit; @@ -37,7 +38,9 @@ void CodecInit::initialize() { oCodec->report(); g.oCodec = oCodec; } else { - Log::logOrDefer(Log::CriticalError, QObject::tr("CodecInit: Failed to load Opus, it will not be available for encoding/decoding audio.")); + Log::logOrDefer( + Log::CriticalError, + QObject::tr("CodecInit: Failed to load Opus, it will not be available for encoding/decoding audio.")); delete oCodec; } #endif @@ -80,19 +83,19 @@ void CodecInit::destroy() { delete g.oCodec; #endif - foreach(CELTCodec *codec, g.qmCodecs) + foreach (CELTCodec *codec, g.qmCodecs) delete codec; g.qmCodecs.clear(); } LoopUser::LoopUser() { - qsName = QLatin1String("Loopy"); + qsName = QLatin1String("Loopy"); uiSession = 0; - iId = 0; + iId = 0; bMute = bDeaf = bSuppress = false; bLocalIgnore = bLocalMute = bSelfDeaf = false; - tsState = Settings::Passive; - cChannel = nullptr; + tsState = Settings::Passive; + cChannel = nullptr; qetTicker.start(); qetLastFetch.start(); } @@ -115,18 +118,18 @@ void LoopUser::addFrame(const QByteArray &packet) { else r = DOUBLE_RAND * g.s.dMaxPacketDelay; - qmPackets.insert(static_cast<float>(time + r), packet); + qmPackets.insert(static_cast< float >(time + r), packet); } // Restart check if (qetLastFetch.elapsed() > 100) { AudioOutputPtr ao = g.ao; if (ao) { - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((packet.at(0) >> 5) & 0x7); + MessageHandler::UDPMessageType msgType = + static_cast< MessageHandler::UDPMessageType >((packet.at(0) >> 5) & 0x7); ao->addFrameToBuffer(this, QByteArray(), 0, msgType); } } - } void LoopUser::fetchFrames() { @@ -139,7 +142,7 @@ void LoopUser::fetchFrames() { double cmp = qetTicker.elapsed(); - QMultiMap<float, QByteArray>::iterator i = qmPackets.begin(); + QMultiMap< float, QByteArray >::iterator i = qmPackets.begin(); while (i != qmPackets.end()) { if (i.key() > cmp) @@ -149,16 +152,16 @@ void LoopUser::fetchFrames() { const QByteArray &data = i.value(); PacketDataStream pds(data.constData(), data.size()); - unsigned int msgFlags = static_cast<unsigned int>(pds.next()); + unsigned int msgFlags = static_cast< unsigned int >(pds.next()); pds >> iSeq; QByteArray qba; qba.reserve(pds.left() + 1); - qba.append(static_cast<char>(msgFlags)); + qba.append(static_cast< char >(msgFlags)); qba.append(pds.dataBlock(pds.left())); - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((msgFlags >> 5) & 0x7); + MessageHandler::UDPMessageType msgType = static_cast< MessageHandler::UDPMessageType >((msgFlags >> 5) & 0x7); ao->addFrameToBuffer(this, qba, iSeq, msgType); i = qmPackets.erase(i); @@ -185,16 +188,16 @@ void RecordUser::addFrame(const QByteArray &packet) { int iSeq; PacketDataStream pds(packet.constData(), packet.size()); - unsigned int msgFlags = static_cast<unsigned int>(pds.next()); + unsigned int msgFlags = static_cast< unsigned int >(pds.next()); pds >> iSeq; QByteArray qba; qba.reserve(pds.left() + 1); - qba.append(static_cast<char>(msgFlags)); + qba.append(static_cast< char >(msgFlags)); qba.append(pds.dataBlock(pds.left())); - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((msgFlags >> 5) & 0x7); + MessageHandler::UDPMessageType msgType = static_cast< MessageHandler::UDPMessageType >((msgFlags >> 5) & 0x7); ao->addFrameToBuffer(this, qba, iSeq, msgType); } @@ -215,7 +218,7 @@ void Audio::stopOutput() { // Wait until our copy of the AudioOutput shared pointer (ao) // is the only one left. - while (ao.get() && ! ao.unique()) { + while (ao.get() && !ao.unique()) { QThread::yieldCurrentThread(); } @@ -248,7 +251,7 @@ void Audio::stopInput() { // Wait until our copy of the AudioInput shared pointer (ai) // is the only one left. - while (ai.get() && ! ai.unique()) { + while (ai.get() && !ai.unique()) { QThread::yieldCurrentThread(); } @@ -274,7 +277,7 @@ void Audio::stop() { // Take copies of the global AudioInput and AudioOutput // shared pointers to keep a reference to each of them // around. - AudioInputPtr ai = g.ai; + AudioInputPtr ai = g.ai; AudioOutputPtr ao = g.ao; // Reset the global AudioInput and AudioOutput shared pointers @@ -284,7 +287,7 @@ void Audio::stop() { // Wait until our copies of the AudioInput and AudioOutput shared pointers // (ai and ao) are the only ones left. - while ((ai.get() && ! ai.unique()) || (ao.get() && ! ao.unique())) { + while ((ai.get() && !ai.unique()) || (ao.get() && !ao.unique())) { QThread::yieldCurrentThread(); } diff --git a/src/mumble/Audio.h b/src/mumble/Audio.h index 53b76fe8a..9503be75b 100644 --- a/src/mumble/Audio.h +++ b/src/mumble/Audio.h @@ -7,52 +7,53 @@ #define MUMBLE_MUMBLE_AUDIO_H_ #include <QtCore/QByteArray> +#include <QtCore/QElapsedTimer> #include <QtCore/QMultiMap> #include <QtCore/QMutex> #include <QtCore/QString> -#include <QtCore/QElapsedTimer> #include <QtCore/QVariant> #include "ClientUser.h" #define SAMPLE_RATE 48000 -typedef QPair<QString,QVariant> audioDevice; +typedef QPair< QString, QVariant > audioDevice; class LoopUser : public ClientUser { - private: - Q_DISABLE_COPY(LoopUser) - protected: - QMutex qmLock; - QElapsedTimer qetTicker; - QElapsedTimer qetLastFetch; - QMultiMap<float, QByteArray> qmPackets; - LoopUser(); - public: - static LoopUser lpLoopy; - virtual void addFrame(const QByteArray &packet); - void fetchFrames(); +private: + Q_DISABLE_COPY(LoopUser) +protected: + QMutex qmLock; + QElapsedTimer qetTicker; + QElapsedTimer qetLastFetch; + QMultiMap< float, QByteArray > qmPackets; + LoopUser(); + +public: + static LoopUser lpLoopy; + virtual void addFrame(const QByteArray &packet); + void fetchFrames(); }; class RecordUser : public LoopUser { - private: - Q_OBJECT - Q_DISABLE_COPY(RecordUser) - public: - RecordUser(); - ~RecordUser() Q_DECL_OVERRIDE; - void addFrame(const QByteArray &packet) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(RecordUser) +public: + RecordUser(); + ~RecordUser() Q_DECL_OVERRIDE; + void addFrame(const QByteArray &packet) Q_DECL_OVERRIDE; }; namespace Audio { - void startInput(const QString &input = QString()); - void stopInput(); +void startInput(const QString &input = QString()); +void stopInput(); - void startOutput(const QString &output = QString()); - void stopOutput(); +void startOutput(const QString &output = QString()); +void stopOutput(); - void start(const QString &input = QString(), const QString &output = QString()); - void stop(); -} +void start(const QString &input = QString(), const QString &output = QString()); +void stop(); +} // namespace Audio #endif diff --git a/src/mumble/AudioConfigDialog.cpp b/src/mumble/AudioConfigDialog.cpp index 53a4cd574..4c66f55a3 100644 --- a/src/mumble/AudioConfigDialog.cpp +++ b/src/mumble/AudioConfigDialog.cpp @@ -13,13 +13,13 @@ are met: - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -39,12 +39,12 @@ #include "AudioInput.h" #include "AudioOutput.h" #include "AudioOutputSample.h" -#include "Global.h" #include "NetworkConfig.h" #include "Utils.h" +#include "Global.h" const QString AudioOutputDialog::name = QLatin1String("AudioOutputWidget"); -const QString AudioInputDialog::name = QLatin1String("AudioInputWidget"); +const QString AudioInputDialog::name = QLatin1String("AudioInputWidget"); static ConfigWidget *AudioInputDialogNew(Settings &st) { @@ -96,10 +96,8 @@ AudioInputDialog::AudioInputDialog(Settings &st) : ConfigWidget(st) { qcbIdleAction->setAccessibleName(tr("Idle action")); if (AudioInputRegistrar::qmNew) { - QList<QString> keys = AudioInputRegistrar::qmNew->keys(); - foreach(QString key, keys) { - qcbSystem->addItem(key); - } + QList< QString > keys = AudioInputRegistrar::qmNew->keys(); + foreach (QString key, keys) { qcbSystem->addItem(key); } } qcbSystem->setEnabled(qcbSystem->count() > 1); @@ -107,9 +105,9 @@ AudioInputDialog::AudioInputDialog(Settings &st) : ConfigWidget(st) { qcbTransmit->addItem(tr("Voice Activity"), Settings::VAD); qcbTransmit->addItem(tr("Push To Talk"), Settings::PushToTalk); - abSpeech->qcBelow = Qt::red; + abSpeech->qcBelow = Qt::red; abSpeech->qcInside = Qt::yellow; - abSpeech->qcAbove = Qt::green; + abSpeech->qcAbove = Qt::green; qcbDevice->view()->setTextElideMode(Qt::ElideRight); @@ -141,13 +139,13 @@ QIcon AudioInputDialog::icon() const { void AudioInputDialog::load(const Settings &r) { int i; - QList<QString> keys; + QList< QString > keys; if (AudioInputRegistrar::qmNew) - keys=AudioInputRegistrar::qmNew->keys(); + keys = AudioInputRegistrar::qmNew->keys(); else keys.clear(); - i=keys.indexOf(AudioInputRegistrar::current); + i = keys.indexOf(AudioInputRegistrar::current); if (i >= 0) loadComboBox(qcbSystem, i); @@ -160,9 +158,9 @@ void AudioInputDialog::load(const Settings &r) { loadSlider(qsTransmitHold, r.iVoiceHold); loadSlider(qsTransmitMin, iroundf(r.fVADmin * 32767.0f + 0.5f)); loadSlider(qsTransmitMax, iroundf(r.fVADmax * 32767.0f + 0.5f)); - loadSlider(qsFrames, (r.iFramesPerPacket == 1) ? 1 : (r.iFramesPerPacket/2 + 1)); - loadSlider(qsDoublePush, iroundf(static_cast<float>(r.uiDoublePush) / 1000.f + 0.5f)); - loadSlider(qsPTTHold, static_cast<int>(r.pttHold)); + loadSlider(qsFrames, (r.iFramesPerPacket == 1) ? 1 : (r.iFramesPerPacket / 2 + 1)); + loadSlider(qsDoublePush, iroundf(static_cast< float >(r.uiDoublePush) / 1000.f + 0.5f)); + loadSlider(qsPTTHold, static_cast< int >(r.pttHold)); if (r.vsVAD == Settings::Amplitude) qrbAmplitude->setChecked(true); @@ -174,7 +172,7 @@ void AudioInputDialog::load(const Settings &r) { loadSlider(qsQuality, r.iQuality); loadCheckBox(qcbAllowLowDelay, r.bAllowLowDelay); if (r.iSpeexNoiseCancelStrength != 0) { - loadSlider(qsSpeexNoiseSupStrength, - r.iSpeexNoiseCancelStrength); + loadSlider(qsSpeexNoiseSupStrength, -r.iSpeexNoiseCancelStrength); } else { loadSlider(qsSpeexNoiseSupStrength, 14); } @@ -239,9 +237,9 @@ void AudioInputDialog::load(const Settings &r) { } void AudioInputDialog::save() const { - s.iQuality = qsQuality->value(); - s.bAllowLowDelay = qcbAllowLowDelay->isChecked(); - s.iSpeexNoiseCancelStrength = (qsSpeexNoiseSupStrength->value() == 14) ? 0 : - qsSpeexNoiseSupStrength->value(); + s.iQuality = qsQuality->value(); + s.bAllowLowDelay = qcbAllowLowDelay->isChecked(); + s.iSpeexNoiseCancelStrength = (qsSpeexNoiseSupStrength->value() == 14) ? 0 : -qsSpeexNoiseSupStrength->value(); if (qrbNoiseSupDeactivated->isChecked()) { s.noiseCancelMode = Settings::NoiseCancelOff; @@ -253,35 +251,35 @@ void AudioInputDialog::save() const { s.noiseCancelMode = Settings::NoiseCancelSpeex; } - s.iMinLoudness = 18000 - qsAmp->value() + 2000; - s.iVoiceHold = qsTransmitHold->value(); - s.fVADmin = static_cast<float>(qsTransmitMin->value()) / 32767.0f; - s.fVADmax = static_cast<float>(qsTransmitMax->value()) / 32767.0f; - s.vsVAD = qrbSNR->isChecked() ? Settings::SignalToNoise : Settings::Amplitude; + s.iMinLoudness = 18000 - qsAmp->value() + 2000; + s.iVoiceHold = qsTransmitHold->value(); + s.fVADmin = static_cast< float >(qsTransmitMin->value()) / 32767.0f; + s.fVADmax = static_cast< float >(qsTransmitMax->value()) / 32767.0f; + s.vsVAD = qrbSNR->isChecked() ? Settings::SignalToNoise : Settings::Amplitude; s.iFramesPerPacket = qsFrames->value(); - s.iFramesPerPacket = (s.iFramesPerPacket == 1) ? 1 : ((s.iFramesPerPacket-1) * 2); - s.uiDoublePush = qsDoublePush->value() * 1000; - s.pttHold = qsPTTHold->value(); - s.atTransmit = static_cast<Settings::AudioTransmit>(qcbTransmit->currentIndex()); + s.iFramesPerPacket = (s.iFramesPerPacket == 1) ? 1 : ((s.iFramesPerPacket - 1) * 2); + s.uiDoublePush = qsDoublePush->value() * 1000; + s.pttHold = qsPTTHold->value(); + s.atTransmit = static_cast< Settings::AudioTransmit >(qcbTransmit->currentIndex()); // Idle auto actions - s.iIdleTime = qsbIdle->value() * 60; - s.iaeIdleAction = static_cast<Settings::IdleAction>(qcbIdleAction->currentIndex()); + s.iIdleTime = qsbIdle->value() * 60; + s.iaeIdleAction = static_cast< Settings::IdleAction >(qcbIdleAction->currentIndex()); s.bUndoIdleActionUponActivity = qcbUndoIdleAction->isChecked(); s.bShowPTTButtonWindow = qcbPushWindow->isChecked(); - s.bTxAudioCue = qcbPushClick->isChecked(); - s.qsTxAudioCueOn = qlePushClickPathOn->text(); - s.qsTxAudioCueOff = qlePushClickPathOff->text(); + s.bTxAudioCue = qcbPushClick->isChecked(); + s.qsTxAudioCueOn = qlePushClickPathOn->text(); + s.qsTxAudioCueOff = qlePushClickPathOff->text(); - s.qsAudioInput = qcbSystem->currentText(); - s.bEcho = qcbEcho->currentIndex() > 0; - s.bEchoMulti = qcbEcho->currentIndex() == 2; + s.qsAudioInput = qcbSystem->currentText(); + s.bEcho = qcbEcho->currentIndex() > 0; + s.bEchoMulti = qcbEcho->currentIndex() == 2; s.bExclusiveInput = qcbExclusive->isChecked(); if (AudioInputRegistrar::qmNew) { AudioInputRegistrar *air = AudioInputRegistrar::qmNew->value(qcbSystem->currentText()); - int idx = qcbDevice->currentIndex(); + int idx = qcbDevice->currentIndex(); if (idx > -1) { air->setDeviceChoice(qcbDevice->itemData(idx), s); } @@ -289,7 +287,7 @@ void AudioInputDialog::save() const { } void AudioInputDialog::on_qsFrames_valueChanged(int v) { - qlFrames->setText(tr("%1 ms").arg((v==1) ? 10 : (v-1)*20)); + qlFrames->setText(tr("%1 ms").arg((v == 1) ? 10 : (v - 1) * 20)); updateBitrate(); } @@ -308,13 +306,13 @@ void AudioInputDialog::on_qsPTTHold_valueChanged(int v) { } void AudioInputDialog::on_qsTransmitHold_valueChanged(int v) { - float val = static_cast<float>(v * 10); - val = val / 1000.0f; + float val = static_cast< float >(v * 10); + val = val / 1000.0f; qlTransmitHold->setText(tr("%1 s").arg(val, 0, 'f', 2)); } void AudioInputDialog::on_qsQuality_valueChanged(int v) { - qlQuality->setText(tr("%1 kb/s").arg(static_cast<float>(v) / 1000.0f, 0, 'f', 1)); + qlQuality->setText(tr("%1 kb/s").arg(static_cast< float >(v) / 1000.0f, 0, 'f', 1)); updateBitrate(); } @@ -331,13 +329,13 @@ void AudioInputDialog::on_qsSpeexNoiseSupStrength_valueChanged(int v) { } void AudioInputDialog::on_qsAmp_valueChanged(int v) { - v = 18000 - v + 2000; - float d = 20000.0f/static_cast<float>(v); + v = 18000 - v + 2000; + float d = 20000.0f / static_cast< float >(v); qlAmp->setText(QString::fromLatin1("%1").arg(d, 0, 'f', 2)); } void AudioInputDialog::updateBitrate() { - if (! qsQuality || ! qsFrames || ! qlBitrate) + if (!qsQuality || !qsFrames || !qlBitrate) return; int q = qsQuality->value(); int p = qsFrames->value(); @@ -361,7 +359,7 @@ void AudioInputDialog::updateBitrate() { posrate = posrate * 100 * 8; overhead = overhead / p; - posrate = posrate / p; + posrate = posrate / p; int total = audiorate + overhead + posrate; @@ -374,10 +372,10 @@ void AudioInputDialog::updateBitrate() { qlBitrate->setPalette(pal); QString v = tr("%1 kbit/s (Audio %2, Position %4, Overhead %3)") - .arg(total / 1000.0, 0, 'f', 1) - .arg(audiorate / 1000.0, 0, 'f', 1) - .arg(overhead / 1000.0, 0, 'f', 1) - .arg(posrate / 1000.0, 0, 'f', 1); + .arg(total / 1000.0, 0, 'f', 1) + .arg(audiorate / 1000.0, 0, 'f', 1) + .arg(overhead / 1000.0, 0, 'f', 1) + .arg(posrate / 1000.0, 0, 'f', 1); qlBitrate->setText(v); @@ -417,7 +415,6 @@ void AudioInputDialog::on_qpbPushClickPreview_clicked() { connect(sample, SIGNAL(playbackFinished()), this, SLOT(continuePlayback())); else // If we fail to playback the first play on play at least off ao->playSample(qlePushClickPathOff->text()); - } } @@ -450,15 +447,15 @@ void AudioInputDialog::on_qcbTransmit_currentIndexChanged(int v) { void AudioInputDialog::on_qcbSystem_currentIndexChanged(int) { qcbDevice->clear(); - QList<audioDevice> ql; + QList< audioDevice > ql; if (AudioInputRegistrar::qmNew) { AudioInputRegistrar *air = AudioInputRegistrar::qmNew->value(qcbSystem->currentText()); - ql = air->getDeviceChoices(); + ql = air->getDeviceChoices(); int idx = 0; - foreach(audioDevice d, ql) { + foreach (audioDevice d, ql) { qcbDevice->addItem(d.first, d.second); qcbDevice->setItemData(idx, d.first.toHtmlEscaped(), Qt::ToolTipRole); ++idx; @@ -475,7 +472,8 @@ void AudioInputDialog::on_qcbSystem_currentIndexChanged(int) { void AudioInputDialog::updateEchoEnableState() { AudioInputRegistrar *air = AudioInputRegistrar::qmNew->value(qcbSystem->currentText()); - AudioOutputDialog *outputWidget = static_cast<AudioOutputDialog *>(ConfigDialog::getConfigWidget(AudioOutputDialog::name)); + AudioOutputDialog *outputWidget = + static_cast< AudioOutputDialog * >(ConfigDialog::getConfigWidget(AudioOutputDialog::name)); QString outputInterface; if (outputWidget) { outputInterface = outputWidget->getCurrentlySelectedOutputInterfaceName(); @@ -486,15 +484,19 @@ void AudioInputDialog::updateEchoEnableState() { if (air->canEcho(outputInterface)) { qcbEcho->setEnabled(true); - qcbEcho->setToolTip(QObject::tr("If enabled this tries to cancel out echo from the audio stream.\n" + qcbEcho->setToolTip(QObject::tr( + "If enabled this tries to cancel out echo from the audio stream.\n" "Mixed echo cancellation mixes all speaker outputs in one mono stream and passes that stream to " - "the echo canceller, while multichannel echo cancellation passes all audio channels to the echo canceller directly.\n" + "the echo canceller, while multichannel echo cancellation passes all audio channels to the echo canceller " + "directly.\n" "Multichannel echo cancellation requires more CPU, so you should try mixed first")); } else { qcbEcho->setCurrentIndex(0); qcbEcho->setEnabled(false); qcbEcho->setToolTip(QObject::tr("Echo cancellation is not supported for the interface " - "combination \"%1\" (in) and \"%2\" (out).").arg(air->name).arg(outputInterface)); + "combination \"%1\" (in) and \"%2\" (out).") + .arg(air->name) + .arg(outputInterface)); } } @@ -507,14 +509,14 @@ void AudioInputDialog::showSpeexNoiseSuppressionSlider(bool show) { void AudioInputDialog::on_Tick_timeout() { AudioInputPtr ai = g.ai; - if (!ai.get() || ! ai->sppPreprocess) + if (!ai.get() || !ai->sppPreprocess) return; abSpeech->iBelow = qsTransmitMin->value(); abSpeech->iAbove = qsTransmitMax->value(); if (qrbAmplitude->isChecked()) { - abSpeech->iValue = iroundf((32767.f/96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); + abSpeech->iValue = iroundf((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); } else { abSpeech->iValue = iroundf(ai->fSpeechProb * 32767.0f + 0.5f); } @@ -523,7 +525,7 @@ void AudioInputDialog::on_Tick_timeout() { void AudioInputDialog::on_qcbIdleAction_currentIndexChanged(int v) { - const Settings::IdleAction action = static_cast<Settings::IdleAction>(v); + const Settings::IdleAction action = static_cast< Settings::IdleAction >(v); const bool enabled = (action != Settings::Nothing); @@ -569,10 +571,8 @@ AudioOutputDialog::AudioOutputDialog(Settings &st) : ConfigWidget(st) { qcbLoopback->setAccessibleName(tr("Loopback")); if (AudioOutputRegistrar::qmNew) { - QList<QString> keys = AudioOutputRegistrar::qmNew->keys(); - foreach(QString key, keys) { - qcbSystem->addItem(key); - } + QList< QString > keys = AudioOutputRegistrar::qmNew->keys(); + foreach (QString key, keys) { qcbSystem->addItem(key); } } qcbSystem->setEnabled(qcbSystem->count() > 1); @@ -605,13 +605,13 @@ QString AudioOutputDialog::getCurrentlySelectedOutputInterfaceName() const { void AudioOutputDialog::load(const Settings &r) { int i; - QList<QString> keys; + QList< QString > keys; if (AudioOutputRegistrar::qmNew) - keys=AudioOutputRegistrar::qmNew->keys(); + keys = AudioOutputRegistrar::qmNew->keys(); else keys.clear(); - i=keys.indexOf(AudioOutputRegistrar::current); + i = keys.indexOf(AudioOutputRegistrar::current); if (i >= 0) loadComboBox(qcbSystem, i); @@ -633,7 +633,7 @@ void AudioOutputDialog::load(const Settings &r) { loadSlider(qsJitter, r.iJitterBufferSize); loadComboBox(qcbLoopback, r.lmLoopMode); - loadSlider(qsPacketDelay, static_cast<int>(r.dMaxPacketDelay)); + loadSlider(qsPacketDelay, static_cast< int >(r.dMaxPacketDelay)); loadSlider(qsPacketLoss, iroundf(r.dPacketLoss * 100.0f + 0.5f)); loadSlider(qsMinDistance, iroundf(r.fAudioMinDistance * 10.0f + 0.5f)); loadSlider(qsMaxDistance, iroundf(r.fAudioMaxDistance * 10.0f + 0.5f)); @@ -648,31 +648,31 @@ void AudioOutputDialog::load(const Settings &r) { } void AudioOutputDialog::save() const { - s.iOutputDelay = qsDelay->value(); - s.fVolume = static_cast<float>(qsVolume->value()) / 100.0f; - s.fOtherVolume = 1.0f - (static_cast<float>(qsOtherVolume->value()) / 100.0f); - s.bAttenuateOthersOnTalk = qcbAttenuateOthersOnTalk->isChecked(); - s.bAttenuateOthers = qcbAttenuateOthers->isChecked(); - s.bOnlyAttenuateSameOutput = qcbOnlyAttenuateSameOutput->isChecked(); - s.bAttenuateLoopbacks = qcbAttenuateLoopbacks->isChecked(); + s.iOutputDelay = qsDelay->value(); + s.fVolume = static_cast< float >(qsVolume->value()) / 100.0f; + s.fOtherVolume = 1.0f - (static_cast< float >(qsOtherVolume->value()) / 100.0f); + s.bAttenuateOthersOnTalk = qcbAttenuateOthersOnTalk->isChecked(); + s.bAttenuateOthers = qcbAttenuateOthers->isChecked(); + s.bOnlyAttenuateSameOutput = qcbOnlyAttenuateSameOutput->isChecked(); + s.bAttenuateLoopbacks = qcbAttenuateLoopbacks->isChecked(); s.bAttenuateUsersOnPrioritySpeak = qcbAttenuateUsersOnPrioritySpeak->isChecked(); - s.iJitterBufferSize = qsJitter->value(); - s.qsAudioOutput = qcbSystem->currentText(); - s.lmLoopMode = static_cast<Settings::LoopMode>(qcbLoopback->currentIndex()); - s.dMaxPacketDelay = static_cast<float>(qsPacketDelay->value()); - s.dPacketLoss = static_cast<float>(qsPacketLoss->value()) / 100.0f; - s.fAudioMinDistance = static_cast<float>(qsMinDistance->value()) / 10.0f; - s.fAudioMaxDistance = static_cast<float>(qsMaxDistance->value()) / 10.0f; - s.fAudioMaxDistVolume = static_cast<float>(qsMaxDistVolume->value()) / 100.0f; - s.fAudioBloom = static_cast<float>(qsBloom->value()) / 100.0f; - s.bPositionalAudio = qcbPositional->isChecked(); - s.bPositionalHeadphone = qcbHeadphones->isChecked(); - s.bExclusiveOutput = qcbExclusive->isChecked(); + s.iJitterBufferSize = qsJitter->value(); + s.qsAudioOutput = qcbSystem->currentText(); + s.lmLoopMode = static_cast< Settings::LoopMode >(qcbLoopback->currentIndex()); + s.dMaxPacketDelay = static_cast< float >(qsPacketDelay->value()); + s.dPacketLoss = static_cast< float >(qsPacketLoss->value()) / 100.0f; + s.fAudioMinDistance = static_cast< float >(qsMinDistance->value()) / 10.0f; + s.fAudioMaxDistance = static_cast< float >(qsMaxDistance->value()) / 10.0f; + s.fAudioMaxDistVolume = static_cast< float >(qsMaxDistVolume->value()) / 100.0f; + s.fAudioBloom = static_cast< float >(qsBloom->value()) / 100.0f; + s.bPositionalAudio = qcbPositional->isChecked(); + s.bPositionalHeadphone = qcbHeadphones->isChecked(); + s.bExclusiveOutput = qcbExclusive->isChecked(); if (AudioOutputRegistrar::qmNew) { AudioOutputRegistrar *aor = AudioOutputRegistrar::qmNew->value(qcbSystem->currentText()); - int idx = qcbDevice->currentIndex(); + int idx = qcbDevice->currentIndex(); if (idx > -1) { aor->setDeviceChoice(qcbDevice->itemData(idx), s); } @@ -682,15 +682,15 @@ void AudioOutputDialog::save() const { void AudioOutputDialog::on_qcbSystem_currentIndexChanged(int) { qcbDevice->clear(); - QList<audioDevice> ql; + QList< audioDevice > ql; if (AudioOutputRegistrar::qmNew) { AudioOutputRegistrar *aor = AudioOutputRegistrar::qmNew->value(qcbSystem->currentText()); - ql = aor->getDeviceChoices(); + ql = aor->getDeviceChoices(); int idx = 0; - foreach(audioDevice d, ql) { + foreach (audioDevice d, ql) { qcbDevice->addItem(d.first, d.second); qcbDevice->setItemData(idx, d.first.toHtmlEscaped(), Qt::ToolTipRole); ++idx; @@ -715,7 +715,7 @@ void AudioOutputDialog::on_qcbSystem_currentIndexChanged(int) { } void AudioOutputDialog::on_qsJitter_valueChanged(int v) { - qlJitter->setText(tr("%1 ms").arg(v*10)); + qlJitter->setText(tr("%1 ms").arg(v * 10)); } void AudioOutputDialog::on_qsVolume_valueChanged(int v) { @@ -742,7 +742,7 @@ void AudioOutputDialog::on_qsPacketLoss_valueChanged(int v) { } void AudioOutputDialog::on_qsDelay_valueChanged(int v) { - qlDelay->setText(tr("%1 ms").arg(v*10)); + qlDelay->setText(tr("%1 ms").arg(v * 10)); } void AudioOutputDialog::on_qcbLoopback_currentIndexChanged(int v) { @@ -757,13 +757,13 @@ void AudioOutputDialog::on_qcbLoopback_currentIndexChanged(int v) { } void AudioOutputDialog::on_qsMinDistance_valueChanged(int v) { - qlMinDistance->setText(tr("%1 m").arg(v/10.0, 0, 'f', 1)); + qlMinDistance->setText(tr("%1 m").arg(v / 10.0, 0, 'f', 1)); if (qsMaxDistance->value() < v) qsMaxDistance->setValue(v); } void AudioOutputDialog::on_qsMaxDistance_valueChanged(int v) { - qlMaxDistance->setText(tr("%1 m").arg(v/10.0, 0, 'f', 1)); + qlMaxDistance->setText(tr("%1 m").arg(v / 10.0, 0, 'f', 1)); if (qsMinDistance->value() > v) qsMinDistance->setValue(v); } @@ -773,7 +773,7 @@ void AudioOutputDialog::on_qsMaxDistVolume_valueChanged(int v) { } void AudioOutputDialog::on_qsBloom_valueChanged(int v) { - qlBloom->setText(tr("%1 %").arg(v+100)); + qlBloom->setText(tr("%1 %").arg(v + 100)); } void AudioOutputDialog::on_qcbAttenuateOthersOnTalk_clicked(bool checked) { diff --git a/src/mumble/AudioConfigDialog.h b/src/mumble/AudioConfigDialog.h index d2707e5a6..a94ea5c23 100644 --- a/src/mumble/AudioConfigDialog.h +++ b/src/mumble/AudioConfigDialog.h @@ -12,85 +12,86 @@ #include "ui_AudioOutput.h" class AudioInputDialog : public ConfigWidget, public Ui::AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioInputDialog) - protected: - QTimer *qtTick; - void hideEvent(QHideEvent *event) Q_DECL_OVERRIDE; - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; - void updateEchoEnableState(); +private: + Q_OBJECT + Q_DISABLE_COPY(AudioInputDialog) +protected: + QTimer *qtTick; + void hideEvent(QHideEvent *event) Q_DECL_OVERRIDE; + void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; + void updateEchoEnableState(); - void showSpeexNoiseSuppressionSlider(bool show); + void showSpeexNoiseSuppressionSlider(bool show); - public: - /// The unique name of this ConfigWidget - static const QString name; - AudioInputDialog(Settings &st); - QString title() const Q_DECL_OVERRIDE; - const QString &getName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; +public: + /// The unique name of this ConfigWidget + static const QString name; + AudioInputDialog(Settings &st); + QString title() const Q_DECL_OVERRIDE; + const QString &getName() const Q_DECL_OVERRIDE; + QIcon icon() const Q_DECL_OVERRIDE; - public slots: - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; - void updateBitrate(); - void continuePlayback(); +public slots: + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; + void updateBitrate(); + void continuePlayback(); - void on_qcbPushClick_clicked(bool); - void on_qpbPushClickBrowseOn_clicked(); - void on_qpbPushClickBrowseOff_clicked(); - void on_qpbPushClickPreview_clicked(); - void on_qpbPushClickReset_clicked(); + void on_qcbPushClick_clicked(bool); + void on_qpbPushClickBrowseOn_clicked(); + void on_qpbPushClickBrowseOff_clicked(); + void on_qpbPushClickPreview_clicked(); + void on_qpbPushClickReset_clicked(); - void on_qsTransmitHold_valueChanged(int v); - void on_qsFrames_valueChanged(int v); - void on_qsQuality_valueChanged(int v); - void on_qsAmp_valueChanged(int v); - void on_qsDoublePush_valueChanged(int v); - void on_qsPTTHold_valueChanged(int v); - void on_qsSpeexNoiseSupStrength_valueChanged(int v); - void on_qcbTransmit_currentIndexChanged(int v); - void on_qcbSystem_currentIndexChanged(int); - void on_Tick_timeout(); - void on_qcbIdleAction_currentIndexChanged(int v); - void on_qrbNoiseSupSpeex_toggled(bool checked); - void on_qrbNoiseSupBoth_toggled(bool checked); + void on_qsTransmitHold_valueChanged(int v); + void on_qsFrames_valueChanged(int v); + void on_qsQuality_valueChanged(int v); + void on_qsAmp_valueChanged(int v); + void on_qsDoublePush_valueChanged(int v); + void on_qsPTTHold_valueChanged(int v); + void on_qsSpeexNoiseSupStrength_valueChanged(int v); + void on_qcbTransmit_currentIndexChanged(int v); + void on_qcbSystem_currentIndexChanged(int); + void on_Tick_timeout(); + void on_qcbIdleAction_currentIndexChanged(int v); + void on_qrbNoiseSupSpeex_toggled(bool checked); + void on_qrbNoiseSupBoth_toggled(bool checked); }; class AudioOutputDialog : public ConfigWidget, public Ui::AudioOutput { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioOutputDialog) +private: + Q_OBJECT + Q_DISABLE_COPY(AudioOutputDialog) - void enablePulseAudioAttenuationOptionsFor(const QString &outputName); - public: - /// The unique name of this ConfigWidget - static const QString name; - AudioOutputDialog(Settings &st); - QString title() const Q_DECL_OVERRIDE; - const QString &getName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; - /// @returns The name of the currently selected audio output interface - QString getCurrentlySelectedOutputInterfaceName() const; - public slots: - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; - void on_qsDelay_valueChanged(int v); - void on_qsJitter_valueChanged(int v); - void on_qsVolume_valueChanged(int v); - void on_qsOtherVolume_valueChanged(int v); - void on_qsPacketDelay_valueChanged(int v); - void on_qsPacketLoss_valueChanged(int v); - void on_qcbLoopback_currentIndexChanged(int v); - void on_qsMinDistance_valueChanged(int v); - void on_qsMaxDistance_valueChanged(int v); - void on_qsBloom_valueChanged(int v); - void on_qsMaxDistVolume_valueChanged(int v); - void on_qcbSystem_currentIndexChanged(int); - void on_qcbAttenuateOthersOnTalk_clicked(bool checked); - void on_qcbAttenuateOthers_clicked(bool checked); - void on_qcbOnlyAttenuateSameOutput_clicked(bool checked); + void enablePulseAudioAttenuationOptionsFor(const QString &outputName); + +public: + /// The unique name of this ConfigWidget + static const QString name; + AudioOutputDialog(Settings &st); + QString title() const Q_DECL_OVERRIDE; + const QString &getName() const Q_DECL_OVERRIDE; + QIcon icon() const Q_DECL_OVERRIDE; + /// @returns The name of the currently selected audio output interface + QString getCurrentlySelectedOutputInterfaceName() const; +public slots: + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; + void on_qsDelay_valueChanged(int v); + void on_qsJitter_valueChanged(int v); + void on_qsVolume_valueChanged(int v); + void on_qsOtherVolume_valueChanged(int v); + void on_qsPacketDelay_valueChanged(int v); + void on_qsPacketLoss_valueChanged(int v); + void on_qcbLoopback_currentIndexChanged(int v); + void on_qsMinDistance_valueChanged(int v); + void on_qsMaxDistance_valueChanged(int v); + void on_qsBloom_valueChanged(int v); + void on_qsMaxDistVolume_valueChanged(int v); + void on_qcbSystem_currentIndexChanged(int); + void on_qcbAttenuateOthersOnTalk_clicked(bool checked); + void on_qcbAttenuateOthers_clicked(bool checked); + void on_qcbOnlyAttenuateSameOutput_clicked(bool checked); }; #endif diff --git a/src/mumble/AudioInput.cpp b/src/mumble/AudioInput.cpp index ca540a940..90e1030fb 100644 --- a/src/mumble/AudioInput.cpp +++ b/src/mumble/AudioInput.cpp @@ -8,40 +8,55 @@ #include "AudioOutput.h" #include "CELTCodec.h" #ifdef USE_OPUS -# include "OpusCodec.h" +# include "OpusCodec.h" #endif -#include "ServerHandler.h" #include "MainWindow.h" -#include "User.h" -#include "PacketDataStream.h" -#include "Plugins.h" #include "Message.h" -#include "Global.h" #include "NetworkConfig.h" +#include "PacketDataStream.h" +#include "Plugins.h" +#include "ServerHandler.h" +#include "User.h" #include "Utils.h" #include "VoiceRecorder.h" +#include "Global.h" #ifdef USE_RNNOISE extern "C" { -#include "rnnoise.h" +# include "rnnoise.h" } #endif -void Resynchronizer::addMic(short *mic) -{ +void Resynchronizer::addMic(short *mic) { bool drop = false; { - std::unique_lock<std::mutex> l(m); + std::unique_lock< std::mutex > l(m); micQueue.push_back(mic); switch (state) { - case S0: state = S1a; break; - case S1a: state = S2; break; - case S1b: state = S2; break; - case S2: state = S3; break; - case S3: state = S4a; break; - case S4a: state = S5; break; - case S4b: drop = true; break; - case S5: drop = true; break; + case S0: + state = S1a; + break; + case S1a: + state = S2; + break; + case S1b: + state = S2; + break; + case S2: + state = S3; + break; + case S3: + state = S4a; + break; + case S4a: + state = S5; + break; + case S4b: + drop = true; + break; + case S5: + drop = true; + break; } if (drop) { delete[] micQueue.front(); @@ -49,44 +64,62 @@ void Resynchronizer::addMic(short *mic) } } if (bDebugPrintQueue) { - if (drop) qWarning("Resynchronizer::addMic(): dropped microphone chunk due to overflow"); + if (drop) + qWarning("Resynchronizer::addMic(): dropped microphone chunk due to overflow"); printQueue('+'); } } -AudioChunk Resynchronizer::addSpeaker(short *speaker) -{ +AudioChunk Resynchronizer::addSpeaker(short *speaker) { AudioChunk result; bool drop = false; { - std::unique_lock<std::mutex> l(m); + std::unique_lock< std::mutex > l(m); switch (state) { - case S0: drop = true; break; - case S1a: drop = true; break; - case S1b: state = S0; break; - case S2: state = S1b; break; - case S3: state = S2; break; - case S4a: state = S3; break; - case S4b: state = S3; break; - case S5: state = S4b; break; + case S0: + drop = true; + break; + case S1a: + drop = true; + break; + case S1b: + state = S0; + break; + case S2: + state = S1b; + break; + case S3: + state = S2; + break; + case S4a: + state = S3; + break; + case S4b: + state = S3; + break; + case S5: + state = S4b; + break; } if (drop == false) { result = AudioChunk(micQueue.front(), speaker); micQueue.pop_front(); } } - if (drop) delete[] speaker; + if (drop) + delete[] speaker; if (bDebugPrintQueue) { - if (drop) qWarning("Resynchronizer::addSpeaker(): dropped speaker chunk due to underflow"); + if (drop) + qWarning("Resynchronizer::addSpeaker(): dropped speaker chunk due to underflow"); printQueue('-'); } return result; } -void Resynchronizer::reset() -{ - if (bDebugPrintQueue) qWarning("Resetting echo queue"); - std::unique_lock<std::mutex> l(m); +void Resynchronizer::reset() { + if (bDebugPrintQueue) + qWarning("Resetting echo queue"); + std::unique_lock< std::mutex > l(m); state = S0; while (!micQueue.empty()) { delete[] micQueue.front(); @@ -94,26 +127,25 @@ void Resynchronizer::reset() } } -Resynchronizer::~Resynchronizer() -{ +Resynchronizer::~Resynchronizer() { reset(); } -void Resynchronizer::printQueue(char who) -{ +void Resynchronizer::printQueue(char who) { unsigned int mic; { - std::unique_lock<std::mutex> l(m); - mic = static_cast<unsigned int>(micQueue.size()); + std::unique_lock< std::mutex > l(m); + mic = static_cast< unsigned int >(micQueue.size()); } std::string line; line.reserve(32); line += who; line += " Echo queue ["; - for(unsigned int i = 0; i < 5; i++) line += i < mic ? '#' : ' '; + for (unsigned int i = 0; i < 5; i++) + line += i < mic ? '#' : ' '; line += "]\r"; // This relies on \r to retrace always on the same line, can't use qWarining - printf("%s",line.c_str()); + printf("%s", line.c_str()); fflush(stdout); } @@ -122,13 +154,13 @@ void Resynchronizer::printQueue(char who) // is called from global initialization. // Hence, we allocate upon first call. -QMap<QString, AudioInputRegistrar *> *AudioInputRegistrar::qmNew; +QMap< QString, AudioInputRegistrar * > *AudioInputRegistrar::qmNew; QString AudioInputRegistrar::current = QString(); AudioInputRegistrar::AudioInputRegistrar(const QString &n, int p) : name(n), priority(p) { - if (! qmNew) - qmNew = new QMap<QString, AudioInputRegistrar *>(); - qmNew->insert(name,this); + if (!qmNew) + qmNew = new QMap< QString, AudioInputRegistrar * >(); + qmNew->insert(name, this); } AudioInputRegistrar::~AudioInputRegistrar() { @@ -136,12 +168,12 @@ AudioInputRegistrar::~AudioInputRegistrar() { } AudioInputPtr AudioInputRegistrar::newFromChoice(QString choice) { - if (! qmNew) + if (!qmNew) return AudioInputPtr(); if (!choice.isEmpty() && qmNew->contains(choice)) { g.s.qsAudioInput = choice; - current = choice; + current = choice; return AudioInputPtr(qmNew->value(current)->create()); } choice = g.s.qsAudioInput; @@ -151,7 +183,7 @@ AudioInputPtr AudioInputRegistrar::newFromChoice(QString choice) { } AudioInputRegistrar *r = nullptr; - foreach(AudioInputRegistrar *air, *qmNew) + foreach (AudioInputRegistrar *air, *qmNew) if (!r || (air->priority > r->priority)) r = air; if (r) { @@ -166,15 +198,14 @@ bool AudioInputRegistrar::canExclusive() const { } AudioInput::AudioInput() : opusBuffer(g.s.iFramesPerPacket * (SAMPLE_RATE / 100)) { - - bDebugDumpInput = g.bDebugDumpInput; + bDebugDumpInput = g.bDebugDumpInput; resync.bDebugPrintQueue = g.bDebugPrintQueue; if (bDebugDumpInput) { outMic.open("raw_microphone_dump", std::ios::binary); outSpeaker.open("speaker_dump", std::ios::binary); outProcessed.open("processed_microphone_dump", std::ios::binary); } - + adjustBandwidth(g.iMaxBandwidth, iAudioQuality, iAudioFrames, bAllowLowDelay); g.iAudioBandwidth = getNetworkBandwidth(iAudioQuality, iAudioFrames); @@ -182,10 +213,10 @@ AudioInput::AudioInput() : opusBuffer(g.s.iFramesPerPacket * (SAMPLE_RATE / 100) umtType = MessageHandler::UDPVoiceCELTAlpha; activityState = ActivityStateActive; - oCodec = nullptr; - opusState = nullptr; - cCodec = nullptr; - ceEncoder = nullptr; + oCodec = nullptr; + opusState = nullptr; + cCodec = nullptr; + ceEncoder = nullptr; #ifdef USE_OPUS oCodec = g.oCodec; @@ -212,9 +243,9 @@ AudioInput::AudioInput() : opusBuffer(g.s.iFramesPerPacket * (SAMPLE_RATE / 100) qWarning("AudioInput: %d bits/s, %d hz, %d sample", iAudioQuality, iSampleRate, iFrameSize); iEchoFreq = iMicFreq = iSampleRate; - iFrameCounter = 0; - iSilentFrames = 0; - iHoldFrames = 0; + iFrameCounter = 0; + iSilentFrames = 0; + iHoldFrames = 0; iBufferedFrames = 0; bResetProcessor = true; @@ -222,7 +253,7 @@ AudioInput::AudioInput() : opusBuffer(g.s.iFramesPerPacket * (SAMPLE_RATE / 100) bEchoMulti = false; sppPreprocess = nullptr; - sesEcho = nullptr; + sesEcho = nullptr; srsMic = srsEcho = nullptr; iEchoChannels = iMicChannels = 0; @@ -236,7 +267,7 @@ AudioInput::AudioInput() : opusBuffer(g.s.iFramesPerPacket * (SAMPLE_RATE / 100) pfMicInput = pfEchoInput = nullptr; - iBitrate = 0; + iBitrate = 0; dPeakSignal = dPeakSpeaker = dPeakMic = dPeakCleanMic = 0.0; if (g.uiSession) { @@ -279,44 +310,47 @@ AudioInput::~AudioInput() { if (srsEcho) speex_resampler_destroy(srsEcho); - delete [] pfMicInput; - delete [] pfEchoInput; + delete[] pfMicInput; + delete[] pfEchoInput; } bool AudioInput::isTransmitting() const { return bPreviousVoice; }; -#define IN_MIXER_FLOAT(channels) \ -static void inMixerFloat##channels ( float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N, quint64 mask) { \ - const float * RESTRICT input = reinterpret_cast<const float *>(ipt); \ - const float m = 1.0f / static_cast<float>(channels); \ - Q_UNUSED(N); \ - Q_UNUSED(mask); \ - for(unsigned int i=0;i<nsamp;++i) {\ - float v= 0.0f; \ - for(unsigned int j=0;j<channels;++j) \ - v += input[i*channels+j]; \ - buffer[i] = v * m; \ - } \ -} +#define IN_MIXER_FLOAT(channels) \ + static void inMixerFloat##channels(float *RESTRICT buffer, const void *RESTRICT ipt, unsigned int nsamp, \ + unsigned int N, quint64 mask) { \ + const float *RESTRICT input = reinterpret_cast< const float * >(ipt); \ + const float m = 1.0f / static_cast< float >(channels); \ + Q_UNUSED(N); \ + Q_UNUSED(mask); \ + for (unsigned int i = 0; i < nsamp; ++i) { \ + float v = 0.0f; \ + for (unsigned int j = 0; j < channels; ++j) \ + v += input[i * channels + j]; \ + buffer[i] = v * m; \ + } \ + } -#define IN_MIXER_SHORT(channels) \ -static void inMixerShort##channels ( float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N, quint64 mask) { \ - const short * RESTRICT input = reinterpret_cast<const short *>(ipt); \ - const float m = 1.0f / (32768.f * static_cast<float>(channels)); \ - Q_UNUSED(N); \ - Q_UNUSED(mask); \ - for(unsigned int i=0;i<nsamp;++i) {\ - float v= 0.0f; \ - for(unsigned int j=0;j<channels;++j) \ - v += static_cast<float>(input[i*channels+j]); \ - buffer[i] = v * m; \ - } \ -} +#define IN_MIXER_SHORT(channels) \ + static void inMixerShort##channels(float *RESTRICT buffer, const void *RESTRICT ipt, unsigned int nsamp, \ + unsigned int N, quint64 mask) { \ + const short *RESTRICT input = reinterpret_cast< const short * >(ipt); \ + const float m = 1.0f / (32768.f * static_cast< float >(channels)); \ + Q_UNUSED(N); \ + Q_UNUSED(mask); \ + for (unsigned int i = 0; i < nsamp; ++i) { \ + float v = 0.0f; \ + for (unsigned int j = 0; j < channels; ++j) \ + v += static_cast< float >(input[i * channels + j]); \ + buffer[i] = v * m; \ + } \ + } -static void inMixerFloatMask(float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N, quint64 mask) { \ - const float * RESTRICT input = reinterpret_cast<const float *>(ipt); +static void inMixerFloatMask(float *RESTRICT buffer, const void *RESTRICT ipt, unsigned int nsamp, unsigned int N, + quint64 mask) { + const float *RESTRICT input = reinterpret_cast< const float * >(ipt); unsigned int chancount = 0; STACKVAR(unsigned int, chanindex, N); @@ -328,18 +362,19 @@ static void inMixerFloatMask(float * RESTRICT buffer, const void * RESTRICT ipt, ++chancount; } - const float m = 1.0f / static_cast<float>(chancount); - for(unsigned int i = 0; i < nsamp; ++i) { + const float m = 1.0f / static_cast< float >(chancount); + for (unsigned int i = 0; i < nsamp; ++i) { float v = 0.0f; - for(unsigned int j = 0; j < chancount; ++j) { + for (unsigned int j = 0; j < chancount; ++j) { v += input[i * N + chanindex[j]]; } buffer[i] = v * m; } } -static void inMixerShortMask(float * RESTRICT buffer, const void * RESTRICT ipt, unsigned int nsamp, unsigned int N, quint64 mask) { - const short * RESTRICT input = reinterpret_cast<const short *>(ipt); +static void inMixerShortMask(float *RESTRICT buffer, const void *RESTRICT ipt, unsigned int nsamp, unsigned int N, + quint64 mask) { + const short *RESTRICT input = reinterpret_cast< const short * >(ipt); unsigned int chancount = 0; STACKVAR(unsigned int, chanindex, N); @@ -351,11 +386,11 @@ static void inMixerShortMask(float * RESTRICT buffer, const void * RESTRICT ipt, ++chancount; } - const float m = 1.0f / static_cast<float>(chancount); - for(unsigned int i = 0; i < nsamp; ++i) { + const float m = 1.0f / static_cast< float >(chancount); + for (unsigned int i = 0; i < nsamp; ++i) { float v = 0.0f; - for(unsigned int j = 0; j < chancount; ++j) { - v += static_cast<float>(input[i * N + chanindex[j]]); + for (unsigned int j = 0; j < chancount; ++j) { + v += static_cast< float >(input[i * N + chanindex[j]]); } buffer[i] = v * m; } @@ -464,8 +499,8 @@ void AudioInput::initializeMixer() { speex_resampler_destroy(srsMic); if (srsEcho) speex_resampler_destroy(srsEcho); - delete [] pfMicInput; - delete [] pfEchoInput; + delete[] pfMicInput; + delete[] pfEchoInput; if (iMicFreq != iSampleRate) srsMic = speex_resampler_init(1, iMicFreq, iSampleRate, 3, &err); @@ -478,12 +513,12 @@ void AudioInput::initializeMixer() { bEchoMulti = g.s.bEchoMulti; if (iEchoFreq != iSampleRate) srsEcho = speex_resampler_init(bEchoMulti ? iEchoChannels : 1, iEchoFreq, iSampleRate, 3, &err); - iEchoLength = (iFrameSize * iEchoFreq) / iSampleRate; - iEchoMCLength = bEchoMulti ? iEchoLength * iEchoChannels : iEchoLength; + iEchoLength = (iFrameSize * iEchoFreq) / iSampleRate; + iEchoMCLength = bEchoMulti ? iEchoLength * iEchoChannels : iEchoLength; iEchoFrameSize = bEchoMulti ? iFrameSize * iEchoChannels : iFrameSize; - pfEchoInput = new float[iEchoMCLength]; + pfEchoInput = new float[iEchoMCLength]; } else { - srsEcho = nullptr; + srsEcho = nullptr; pfEchoInput = nullptr; } @@ -492,17 +527,19 @@ void AudioInput::initializeMixer() { // There is no channel mask setting for the echo canceller, so allow all channels. uiEchoChannelMask = 0xffffffffffffffffULL; - imfMic = chooseMixer(iMicChannels, eMicFormat, uiMicChannelMask); + imfMic = chooseMixer(iMicChannels, eMicFormat, uiMicChannelMask); imfEcho = chooseMixer(iEchoChannels, eEchoFormat, uiEchoChannelMask); - iMicSampleSize = static_cast<int>(iMicChannels * ((eMicFormat == SampleFloat) ? sizeof(float) : sizeof(short))); - iEchoSampleSize = static_cast<int>(iEchoChannels * ((eEchoFormat == SampleFloat) ? sizeof(float) : sizeof(short))); + iMicSampleSize = static_cast< int >(iMicChannels * ((eMicFormat == SampleFloat) ? sizeof(float) : sizeof(short))); + iEchoSampleSize = + static_cast< int >(iEchoChannels * ((eEchoFormat == SampleFloat) ? sizeof(float) : sizeof(short))); bResetProcessor = true; - qWarning("AudioInput: Initialized mixer for %d channel %d hz mic and %d channel %d hz echo", iMicChannels, iMicFreq, iEchoChannels, iEchoFreq); + qWarning("AudioInput: Initialized mixer for %d channel %d hz mic and %d channel %d hz echo", iMicChannels, iMicFreq, + iEchoChannels, iEchoFreq); if (uiMicChannelMask != 0xffffffffffffffffULL) { - qWarning("AudioInput: using mic channel mask 0x%llx", static_cast<unsigned long long>(uiMicChannelMask)); + qWarning("AudioInput: using mic channel mask 0x%llx", static_cast< unsigned long long >(uiMicChannelMask)); } } @@ -520,9 +557,9 @@ void AudioInput::addMic(const void *data, unsigned int nsamp) { // If new samples are left offset data pointer to point at the first one for next iteration if (nsamp > 0) { if (eMicFormat == SampleFloat) - data = reinterpret_cast<const float *>(data) + left * iMicChannels; + data = reinterpret_cast< const float * >(data) + left * iMicChannels; else - data = reinterpret_cast<const short *>(data) + left * iMicChannels; + data = reinterpret_cast< const short * >(data) + left * iMicChannels; } if (iMicFilled == iMicLength) { @@ -530,23 +567,23 @@ void AudioInput::addMic(const void *data, unsigned int nsamp) { iMicFilled = 0; // If needed resample frame - float *pfOutput = srsMic ? (float*)alloca(iFrameSize*sizeof(float)) : nullptr; - float *ptr = srsMic ? pfOutput : pfMicInput; + float *pfOutput = srsMic ? (float *) alloca(iFrameSize * sizeof(float)) : nullptr; + float *ptr = srsMic ? pfOutput : pfMicInput; if (srsMic) { - spx_uint32_t inlen = iMicLength; + spx_uint32_t inlen = iMicLength; spx_uint32_t outlen = iFrameSize; speex_resampler_process_float(srsMic, 0, pfMicInput, &inlen, pfOutput, &outlen); } - // If echo cancellation is enabled the pointer ends up in the resynchronizer queue - // and may need to outlive this function's frame - short *psMic = iEchoChannels > 0 ? new short[iFrameSize] : (short*)alloca(iFrameSize*sizeof(short)); - + // If echo cancellation is enabled the pointer ends up in the resynchronizer queue + // and may need to outlive this function's frame + short *psMic = iEchoChannels > 0 ? new short[iFrameSize] : (short *) alloca(iFrameSize * sizeof(short)); + // Convert float to 16bit PCM const float mul = 32768.f; for (int j = 0; j < iFrameSize; ++j) - psMic[j] = static_cast<short>(qBound(-32768.f, (ptr[j] * mul), 32767.f)); + psMic[j] = static_cast< short >(qBound(-32768.f, (ptr[j] * mul), 32767.f)); // If we have echo cancellation enabled... if (iEchoChannels > 0) { @@ -567,13 +604,13 @@ void AudioInput::addEcho(const void *data, unsigned int nsamp) { const unsigned int samples = left * iEchoChannels; if (eEchoFormat == SampleFloat) { - for (unsigned int i=0;i<samples;++i) - pfEchoInput[i + iEchoFilled * iEchoChannels] = reinterpret_cast<const float *>(data)[i]; - } - else { + for (unsigned int i = 0; i < samples; ++i) + pfEchoInput[i + iEchoFilled * iEchoChannels] = reinterpret_cast< const float * >(data)[i]; + } else { // 16bit PCM -> float - for (unsigned int i=0;i<samples;++i) - pfEchoInput[i + iEchoFilled * iEchoChannels] = static_cast<float>(reinterpret_cast<const short *>(data)[i]) * (1.0f / 32768.f); + for (unsigned int i = 0; i < samples; ++i) + pfEchoInput[i + iEchoFilled * iEchoChannels] = + static_cast< float >(reinterpret_cast< const short * >(data)[i]) * (1.0f / 32768.f); } } else { // Mix echo channels (converts 16bit PCM -> float if needed) @@ -586,22 +623,22 @@ void AudioInput::addEcho(const void *data, unsigned int nsamp) { // If new samples are left offset data pointer to point at the first one for next iteration if (nsamp > 0) { if (eEchoFormat == SampleFloat) - data = reinterpret_cast<const float *>(data) + left * iEchoChannels; + data = reinterpret_cast< const float * >(data) + left * iEchoChannels; else - data = reinterpret_cast<const short *>(data) + left * iEchoChannels; + data = reinterpret_cast< const short * >(data) + left * iEchoChannels; } if (iEchoFilled == iEchoLength) { - //Frame complete + // Frame complete iEchoFilled = 0; // Resample if necessary - float *pfOutput = srsEcho ? (float*)alloca(iEchoFrameSize*sizeof(float)) : nullptr; - float *ptr = srsEcho ? pfOutput : pfEchoInput; + float *pfOutput = srsEcho ? (float *) alloca(iEchoFrameSize * sizeof(float)) : nullptr; + float *ptr = srsEcho ? pfOutput : pfEchoInput; if (srsEcho) { - spx_uint32_t inlen = iEchoLength; + spx_uint32_t inlen = iEchoLength; spx_uint32_t outlen = iFrameSize; speex_resampler_process_interleaved_float(srsEcho, pfEchoInput, &inlen, pfOutput, &outlen); } @@ -611,7 +648,7 @@ void AudioInput::addEcho(const void *data, unsigned int nsamp) { // float -> 16bit PCM const float mul = 32768.f; for (int j = 0; j < iEchoFrameSize; ++j) { - outbuff[j] = static_cast<short>(qBound(-32768.f, (ptr[j] * mul), 32767.f)); + outbuff[j] = static_cast< short >(qBound(-32768.f, (ptr[j] * mul), 32767.f)); } auto chunk = resync.addSpeaker(outbuff); @@ -625,8 +662,8 @@ void AudioInput::addEcho(const void *data, unsigned int nsamp) { } void AudioInput::adjustBandwidth(int bitspersec, int &bitrate, int &frames, bool &allowLowDelay) { - frames = g.s.iFramesPerPacket; - bitrate = g.s.iQuality; + frames = g.s.iFramesPerPacket; + bitrate = g.s.iQuality; allowLowDelay = g.s.bAllowLowDelay; if (bitspersec == -1) { @@ -663,14 +700,18 @@ void AudioInput::setMaxBandwidth(int bitspersec) { if (bitspersec != -1) { if ((bitrate != g.s.iQuality) || (frames != g.s.iFramesPerPacket)) - g.mw->msgBox(tr("Server maximum network bandwidth is only %1 kbit/s. Audio quality auto-adjusted to %2 kbit/s (%3 ms)").arg(bitspersec / 1000).arg(bitrate / 1000).arg(frames*10)); + g.mw->msgBox(tr("Server maximum network bandwidth is only %1 kbit/s. Audio quality auto-adjusted to %2 " + "kbit/s (%3 ms)") + .arg(bitspersec / 1000) + .arg(bitrate / 1000) + .arg(frames * 10)); } AudioInputPtr ai = g.ai; if (ai) { - g.iAudioBandwidth = getNetworkBandwidth(bitrate, frames); - ai->iAudioQuality = bitrate; - ai->iAudioFrames = frames; + g.iAudioBandwidth = getNetworkBandwidth(bitrate, frames); + ai->iAudioQuality = bitrate; + ai->iAudioFrames = frames; ai->bAllowLowDelay = allowLowDelay; return; } @@ -682,7 +723,8 @@ void AudioInput::setMaxBandwidth(int bitspersec) { } int AudioInput::getNetworkBandwidth(int bitrate, int frames) { - int overhead = 20 + 8 + 4 + 1 + 2 + (g.s.bTransmitPosition ? 12 : 0) + (NetworkConfig::TcpModeEnabled() ? 12 : 0) + frames; + int overhead = + 20 + 8 + 4 + 1 + 2 + (g.s.bTransmitPosition ? 12 : 0) + (NetworkConfig::TcpModeEnabled() ? 12 : 0) + frames; overhead *= (800 / frames); int bw = overhead + bitrate; @@ -712,8 +754,8 @@ void AudioInput::resetAudioProcessor() { iArg = 30000; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg); - float v = 30000.0f / static_cast<float>(g.s.iMinLoudness); - iArg = iroundf(floorf(20.0f * log10f(v))); + float v = 30000.0f / static_cast< float >(g.s.iMinLoudness); + iArg = iroundf(floorf(20.0f * log10f(v))); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg); iArg = -60; @@ -726,8 +768,8 @@ void AudioInput::resetAudioProcessor() { if (iEchoChannels > 0) { int filterSize = iFrameSize * (10 + resync.getNominalLag()); - sesEcho = speex_echo_state_init_mc(iFrameSize, filterSize, 1, bEchoMulti ? iEchoChannels : 1); - iArg = iSampleRate; + sesEcho = speex_echo_state_init_mc(iFrameSize, filterSize, 1, bEchoMulti ? iEchoChannels : 1); + iArg = iSampleRate; speex_echo_ctl(sesEcho, SPEEX_ECHO_SET_SAMPLING_RATE, &iArg); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_ECHO_STATE, sesEcho); @@ -759,7 +801,7 @@ bool AudioInput::selectCodec() { CELTCodec *switchto = nullptr; if ((!g.uiSession || (g.s.lmLoopMode == Settings::Local)) && (!g.qmCodecs.isEmpty())) { // Use latest for local loopback - QMap<int, CELTCodec *>::const_iterator i = g.qmCodecs.constEnd(); + QMap< int, CELTCodec * >::const_iterator i = g.qmCodecs.constEnd(); --i; switchto = i.value(); } else { @@ -817,7 +859,6 @@ bool AudioInput::selectCodec() { } void AudioInput::selectNoiseCancel() { - noiseCancel = g.s.noiseCancelMode; if (noiseCancel == Settings::NoiseCancelRNN || noiseCancel == Settings::NoiseCancelBoth) { @@ -852,7 +893,7 @@ void AudioInput::selectNoiseCancel() { speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_DENOISE, &iArg); } -int AudioInput::encodeOpusFrame(short *source, int size, EncodingOutputBuffer& buffer) { +int AudioInput::encodeOpusFrame(short *source, int size, EncodingOutputBuffer &buffer) { #ifdef USE_OPUS int len; if (!oCodec) { @@ -866,16 +907,16 @@ int AudioInput::encodeOpusFrame(short *source, int size, EncodingOutputBuffer& b oCodec->opus_encoder_ctl(opusState, OPUS_SET_BITRATE(iAudioQuality)); - len = oCodec->opus_encode(opusState, source, size, &buffer[0], static_cast<opus_int32>(buffer.size())); + len = oCodec->opus_encode(opusState, source, size, &buffer[0], static_cast< opus_int32 >(buffer.size())); const int tenMsFrameCount = (size / iFrameSize); - iBitrate = (len * 100 * 8) / tenMsFrameCount; + iBitrate = (len * 100 * 8) / tenMsFrameCount; return len; #else return 0; #endif } -int AudioInput::encodeCELTFrame(short *psSource, EncodingOutputBuffer& buffer) { +int AudioInput::encodeCELTFrame(short *psSource, EncodingOutputBuffer &buffer) { int len; if (!cCodec) return 0; @@ -888,7 +929,8 @@ int AudioInput::encodeCELTFrame(short *psSource, EncodingOutputBuffer& buffer) { cCodec->celt_encoder_ctl(ceEncoder, CELT_SET_PREDICTION(0)); cCodec->celt_encoder_ctl(ceEncoder, CELT_SET_VBR_RATE(iAudioQuality)); - len = cCodec->encode(ceEncoder, psSource, &buffer[0], qMin<int>(iAudioQuality / (8 * 100), static_cast<int>(buffer.size()))); + len = cCodec->encode(ceEncoder, psSource, &buffer[0], + qMin< int >(iAudioQuality / (8 * 100), static_cast< int >(buffer.size()))); iBitrate = len * 100 * 8; return len; @@ -911,24 +953,24 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { // function is called again. int voiceTargetID = g.iTarget; - if (! bRunning) + if (!bRunning) return; - sum=1.0f; + sum = 1.0f; max = 1; - for (i=0;i<iFrameSize;i++) { - sum += static_cast<float>(chunk.mic[i] * chunk.mic[i]); - max = std::max(static_cast<short>(abs(chunk.mic[i])), max); + for (i = 0; i < iFrameSize; i++) { + sum += static_cast< float >(chunk.mic[i] * chunk.mic[i]); + max = std::max(static_cast< short >(abs(chunk.mic[i])), max); } - dPeakMic = qMax(20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f), -96.0f); - dMaxMic = max; + dPeakMic = qMax(20.0f * log10f(sqrtf(sum / static_cast< float >(iFrameSize)) / 32768.0f), -96.0f); + dMaxMic = max; if (chunk.speaker && (iEchoChannels > 0)) { - sum=1.0f; + sum = 1.0f; for (i = 0; i < iEchoFrameSize; ++i) { - sum += static_cast<float>(chunk.speaker[i] * chunk.speaker[i]); + sum += static_cast< float >(chunk.speaker[i] * chunk.speaker[i]); } - dPeakSpeaker = qMax(20.0f*log10f(sqrtf(sum / static_cast<float>(iFrameSize)) / 32768.0f), -96.0f); + dPeakSpeaker = qMax(20.0f * log10f(sqrtf(sum / static_cast< float >(iFrameSize)) / 32768.0f), -96.0f); } else { dPeakSpeaker = 0.0; } @@ -937,7 +979,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { resetAudioProcessor(); speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_AGC_GAIN, &iArg); - float gainValue = static_cast<float>(iArg); + float gainValue = static_cast< float >(iArg); if (noiseCancel == Settings::NoiseCancelSpeex || noiseCancel == Settings::NoiseCancelBoth) { iArg = g.s.iSpeexNoiseCancelStrength - iArg; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg); @@ -969,27 +1011,27 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { speex_preprocess_run(sppPreprocess, psSource); - sum=1.0f; - for (i=0;i<iFrameSize;i++) - sum += static_cast<float>(psSource[i] * psSource[i]); - float micLevel = sqrtf(sum / static_cast<float>(iFrameSize)); - dPeakSignal = qMax(20.0f*log10f(micLevel / 32768.0f), -96.0f); - + sum = 1.0f; + for (i = 0; i < iFrameSize; i++) + sum += static_cast< float >(psSource[i] * psSource[i]); + float micLevel = sqrtf(sum / static_cast< float >(iFrameSize)); + dPeakSignal = qMax(20.0f * log10f(micLevel / 32768.0f), -96.0f); + if (bDebugDumpInput) { - outMic.write(reinterpret_cast<const char *>(chunk.mic), iFrameSize * sizeof(short)); + outMic.write(reinterpret_cast< const char * >(chunk.mic), iFrameSize * sizeof(short)); if (chunk.speaker) { - outSpeaker.write(reinterpret_cast<const char *>(chunk.speaker), iEchoFrameSize * sizeof(short)); + outSpeaker.write(reinterpret_cast< const char * >(chunk.speaker), iEchoFrameSize * sizeof(short)); } - outProcessed.write(reinterpret_cast<const char *>(psSource), iFrameSize * sizeof(short)); + outProcessed.write(reinterpret_cast< const char * >(psSource), iFrameSize * sizeof(short)); } spx_int32_t prob = 0; speex_preprocess_ctl(sppPreprocess, SPEEX_PREPROCESS_GET_PROB, &prob); - fSpeechProb = static_cast<float>(prob) / 100.0f; + fSpeechProb = static_cast< float >(prob) / 100.0f; // clean microphone level: peak of filtered signal attenuated by AGC gain dPeakCleanMic = qMax(dPeakSignal - gainValue, -96.0f); - float level = (g.s.vsVAD == Settings::SignalToNoise) ? fSpeechProb : (1.0f + dPeakCleanMic / 96.0f); + float level = (g.s.vsVAD == Settings::SignalToNoise) ? fSpeechProb : (1.0f + dPeakCleanMic / 96.0f); bool bIsSpeech = false; @@ -1001,7 +1043,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { bIsSpeech = true; } - if (! bIsSpeech) { + if (!bIsSpeech) { iHoldFrames++; if (iHoldFrames < g.s.iVoiceHold) bIsSpeech = true; @@ -1014,7 +1056,8 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { bIsSpeech = true; } else if (g.s.atTransmit == Settings::PushToTalk) { // PTT is enabled, so check if it is currently active - bIsSpeech = g.s.uiDoublePush && ((g.uiDoublePush < g.s.uiDoublePush) || (g.tDoublePush.elapsed() < g.s.uiDoublePush)); + bIsSpeech = + g.s.uiDoublePush && ((g.uiDoublePush < g.s.uiDoublePush) || (g.tDoublePush.elapsed() < g.s.uiDoublePush)); } // If g.iPushToTalk > 0 that means that we are currently in some sort of PTT action. For @@ -1022,7 +1065,8 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { bIsSpeech = bIsSpeech || (g.iPushToTalk > 0); ClientUser *p = ClientUser::get(g.uiSession); - if (g.s.bMute || ((g.s.lmLoopMode != Settings::Local) && p && (p->bMute || p->bSuppress)) || g.bPushToMute || (voiceTargetID < 0)) { + if (g.s.bMute || ((g.s.lmLoopMode != Settings::Local) && p && (p->bMute || p->bSuppress)) || g.bPushToMute + || (voiceTargetID < 0)) { bIsSpeech = false; } @@ -1035,7 +1079,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { } if (p) { - if (! bIsSpeech) + if (!bIsSpeech) p->setTalking(Settings::Passive); else if (voiceTargetID == 0) p->setTalking(Settings::Talking); @@ -1045,13 +1089,13 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { if (g.s.bTxAudioCue && g.uiSession != 0) { AudioOutputPtr ao = g.ao; - if (bIsSpeech && ! bPreviousVoice && ao) + if (bIsSpeech && !bPreviousVoice && ao) ao->playSample(g.s.qsTxAudioCueOn); else if (ao && !bIsSpeech && bPreviousVoice) ao->playSample(g.s.qsTxAudioCueOff); } - if (! bIsSpeech && ! bPreviousVoice) { + if (!bIsSpeech && !bPreviousVoice) { iBitrate = 0; if ((tIdle.elapsed() / 1000000ULL) > g.s.iIdleTime) { @@ -1090,8 +1134,8 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { tIdle.restart(); EncodingOutputBuffer buffer; - Q_ASSERT(buffer.size() >= static_cast<size_t>(iAudioQuality / 100 * iAudioFrames / 8)); - + Q_ASSERT(buffer.size() >= static_cast< size_t >(iAudioQuality / 100 * iAudioFrames / 8)); + int len = 0; bool encoded = true; @@ -1122,7 +1166,7 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { iBufferedFrames += missingFrames; iFrameCounter += missingFrames; } - + Q_ASSERT(iBufferedFrames == iAudioFrames); len = encodeOpusFrame(&opusBuffer[0], iBufferedFrames * iFrameSize, buffer); @@ -1138,10 +1182,10 @@ void AudioInput::encodeAudioFrame(AudioChunk chunk) { } if (encoded) { - flushCheck(QByteArray(reinterpret_cast<char *>(&buffer[0]), len), !bIsSpeech, voiceTargetID); + flushCheck(QByteArray(reinterpret_cast< char * >(&buffer[0]), len), !bIsSpeech, voiceTargetID); } - if (! bIsSpeech) + if (!bIsSpeech) iBitrate = 0; bPreviousVoice = bIsSpeech; @@ -1164,7 +1208,7 @@ static void sendAudioFrame(const char *data, PacketDataStream &pds) { void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceTargetID) { qlFrames << frame; - if (! terminator && iBufferedFrames < iAudioFrames) + if (!terminator && iBufferedFrames < iAudioFrames) return; int flags = 0; @@ -1191,9 +1235,9 @@ void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceT flags |= (umtType << 5); char data[1024]; - data[0] = static_cast<unsigned char>(flags); + data[0] = static_cast< unsigned char >(flags); - int frames = iBufferedFrames; + int frames = iBufferedFrames; iBufferedFrames = 0; PacketDataStream pds(data + 1, 1023); @@ -1202,7 +1246,7 @@ void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceT if (umtType == MessageHandler::UDPVoiceOpus) { const QByteArray &qba = qlFrames.takeFirst(); - int size = qba.size(); + int size = qba.size(); if (terminator) size |= 1 << 13; pds << size; @@ -1215,7 +1259,7 @@ void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceT for (int i = 0; i < frames; ++i) { const QByteArray &qba = qlFrames.takeFirst(); - unsigned char head = static_cast<unsigned char>(qba.size()); + unsigned char head = static_cast< unsigned char >(qba.size()); if (i < frames - 1) head |= 0x80; pds.append(head); @@ -1223,7 +1267,7 @@ void AudioInput::flushCheck(const QByteArray &frame, bool terminator, int voiceT } } - if (g.s.bTransmitPosition && g.p && ! g.bCenterPosition && g.p->fetch()) { + if (g.s.bTransmitPosition && g.p && !g.bCenterPosition && g.p->fetch()) { pds << g.p->fPosition[0]; pds << g.p->fPosition[1]; pds << g.p->fPosition[2]; diff --git a/src/mumble/AudioInput.h b/src/mumble/AudioInput.h index fbbf842a4..f1d858be0 100644 --- a/src/mumble/AudioInput.h +++ b/src/mumble/AudioInput.h @@ -6,23 +6,23 @@ #ifndef MUMBLE_MUMBLE_AUDIOINPUT_H_ #define MUMBLE_MUMBLE_AUDIOINPUT_H_ -#include <boost/shared_ptr.hpp> +#include <QtCore/QObject> +#include <QtCore/QThread> #include <boost/array.hpp> +#include <boost/shared_ptr.hpp> +#include <fstream> +#include <list> +#include <mutex> #include <speex/speex.h> #include <speex/speex_echo.h> #include <speex/speex_preprocess.h> #include <speex/speex_resampler.h> -#include <QtCore/QObject> -#include <QtCore/QThread> #include <vector> -#include <fstream> -#include <list> -#include <mutex> #include "Audio.h" +#include "Message.h" #include "Settings.h" #include "Timer.h" -#include "Message.h" class AudioInput; class CELTCodec; @@ -30,7 +30,7 @@ class OpusCodec; struct CELTEncoder; struct OpusEncoder; struct DenoiseState; -typedef boost::shared_ptr<AudioInput> AudioInputPtr; +typedef boost::shared_ptr< AudioInput > AudioInputPtr; /** * A chunk of audio data to process @@ -38,11 +38,10 @@ typedef boost::shared_ptr<AudioInput> AudioInputPtr; * PCM samples of microphone and speaker readback data (for echo cancellation). * Does not handle pointer ownership, so you'll have to deallocate them yourself. */ -struct AudioChunk -{ - AudioChunk() : mic(nullptr), speaker(nullptr) {} - explicit AudioChunk(short *mic) : mic(mic), speaker(nullptr) {} - AudioChunk(short *mic, short *speaker) : mic(mic), speaker(speaker) {} +struct AudioChunk { + AudioChunk() : mic(nullptr), speaker(nullptr) {} + explicit AudioChunk(short *mic) : mic(mic), speaker(nullptr) {} + AudioChunk(short *mic, short *speaker) : mic(mic), speaker(speaker) {} bool empty() const { return mic == nullptr; } short *mic; ///< Pointer to microphone samples @@ -69,14 +68,13 @@ struct AudioChunk * to at least 2 (plus or minus one) and less than 4 elements. * With a 10ms chunk, this queue should introduce a ~20ms lag to the voice. */ -class Resynchronizer -{ +class Resynchronizer { public: /** * Add a microphone sample to the resynchronizer queue * The resynchronizer may decide to drop the sample, and in that case * the pointer will be deallocated not lo leak memory - * + * * \param mic pointer to a dynamically allocated array with PCM data */ void addMic(short *mic); @@ -85,7 +83,7 @@ public: * Add a speaker sample to the resynchronizer * The resynchronizer may decide to drop the sample, and in that case * the pointer will be deallocated not lo leak memory - * + * * \param mic pointer to a dynamically allocated array with PCM data * \return If microphone data is available, the resynchronizer will return a * valid audio chunk to encode, otherwise an empty chunk will be returned @@ -115,157 +113,160 @@ private: */ void printQueue(char who); - //TODO: there was a mutex (qmEcho), but can the callbacks be called concurrently? + // TODO: there was a mutex (qmEcho), but can the callbacks be called concurrently? mutable std::mutex m; - std::list<short *> micQueue; ///< Queue of microphone samples + std::list< short * > micQueue; ///< Queue of microphone samples enum { S0, S1a, S1b, S2, S3, S4a, S4b, S5 } state = S0; ///< Queue fill control statemachine }; class AudioInputRegistrar { - private: - Q_DISABLE_COPY(AudioInputRegistrar) - public: - static QMap<QString, AudioInputRegistrar *> *qmNew; - static QString current; - static AudioInputPtr newFromChoice(QString choice = QString()); - - const QString name; - int priority; - - AudioInputRegistrar(const QString &n, int priority = 0); - virtual ~AudioInputRegistrar(); - virtual AudioInput *create() = 0; - virtual const QList<audioDevice> getDeviceChoices() = 0; - virtual void setDeviceChoice(const QVariant &, Settings &) = 0; - virtual bool canEcho(const QString &outputsys) const = 0; - virtual bool canExclusive() const; +private: + Q_DISABLE_COPY(AudioInputRegistrar) +public: + static QMap< QString, AudioInputRegistrar * > *qmNew; + static QString current; + static AudioInputPtr newFromChoice(QString choice = QString()); + + const QString name; + int priority; + + AudioInputRegistrar(const QString &n, int priority = 0); + virtual ~AudioInputRegistrar(); + virtual AudioInput *create() = 0; + virtual const QList< audioDevice > getDeviceChoices() = 0; + virtual void setDeviceChoice(const QVariant &, Settings &) = 0; + virtual bool canEcho(const QString &outputsys) const = 0; + virtual bool canExclusive() const; }; class AudioInput : public QThread { - friend class AudioNoiseWidget; - friend class AudioEchoWidget; - friend class AudioStats; - friend class AudioInputDialog; - private: - Q_OBJECT - Q_DISABLE_COPY(AudioInput) - protected: - typedef enum { CodecCELT, CodecSpeex } CodecFormat; - typedef enum { SampleShort, SampleFloat } SampleFormat; - typedef void (*inMixerFunc)(float * RESTRICT, const void * RESTRICT, unsigned int, unsigned int, quint64); - private: - - bool bDebugDumpInput; ///< When true, dump pcm data to debug the echo canceller - std::ofstream outMic, outSpeaker, outProcessed; ///< Files to dump raw pcm data - - SpeexResamplerState *srsMic, *srsEcho; - - unsigned int iMicFilled, iEchoFilled; - inMixerFunc imfMic, imfEcho; - inMixerFunc chooseMixer(const unsigned int nchan, SampleFormat sf, quint64 mask); - void resetAudioProcessor(); - - OpusCodec *oCodec; - OpusEncoder *opusState; - DenoiseState *denoiseState; - bool selectCodec(); - void selectNoiseCancel(); - - typedef boost::array<unsigned char, 960> EncodingOutputBuffer; - - int encodeOpusFrame(short *source, int size, EncodingOutputBuffer& buffer); - int encodeCELTFrame(short *pSource, EncodingOutputBuffer& buffer); - protected: - MessageHandler::UDPMessageType umtType; - SampleFormat eMicFormat, eEchoFormat; - - unsigned int iMicChannels, iEchoChannels; - unsigned int iMicFreq, iEchoFreq; - unsigned int iMicLength, iEchoLength; - unsigned int iMicSampleSize, iEchoSampleSize; - int iEchoMCLength, iEchoFrameSize; - quint64 uiMicChannelMask, uiEchoChannelMask; - - bool bEchoMulti; - Settings::NoiseCancel noiseCancel; - static const unsigned int iSampleRate = SAMPLE_RATE; - static const int iFrameSize = SAMPLE_RATE / 100; - - QMutex qmSpeex; - SpeexPreprocessState *sppPreprocess; - SpeexEchoState *sesEcho; - - CELTCodec *cCodec; - CELTEncoder *ceEncoder; - - /// bResetEncoder is a flag that notifies - /// our encoder functions that the encoder - /// needs to be reset. - bool bResetEncoder; - - /// Encoded audio rate in bit/s - int iAudioQuality; - bool bAllowLowDelay; - /// Number of 10ms audio "frames" per packet (!= frames in packet) - int iAudioFrames; - - float *pfMicInput; - float *pfEchoInput; - - Resynchronizer resync; - std::vector<short> opusBuffer; - - void encodeAudioFrame(AudioChunk chunk); - void addMic(const void *data, unsigned int nsamp); - void addEcho(const void *data, unsigned int nsamp); - - volatile bool bRunning; - volatile bool bPreviousVoice; - - int iFrameCounter; - int iSilentFrames; - int iHoldFrames; - int iBufferedFrames; - - QList<QByteArray> qlFrames; - void flushCheck(const QByteArray &, bool terminator, int voiceTargetID); - - void initializeMixer(); - - static void adjustBandwidth(int bitspersec, int &bitrate, int &frames, bool &allowLowDelay); - signals: - void doDeaf(); - void doMute(); - public: - typedef enum { ActivityStateIdle, ActivityStateReturnedFromIdle, ActivityStateActive } ActivityState; - - ActivityState activityState; - - bool bResetProcessor; - - Timer tIdle; - - int iBitrate; - float dPeakSpeaker, dPeakSignal, dMaxMic, dPeakMic, dPeakCleanMic; - float fSpeechProb; - - static int getNetworkBandwidth(int bitrate, int frames); - static void setMaxBandwidth(int bitspersec); - - /// Construct an AudioInput. - /// - /// This constructor is only ever called by Audio::startInput(), and is guaranteed - /// to be called on the application's main thread. - AudioInput(); - - /// Destroy an AudioInput. - /// - /// This destructor is only ever called by Audio::stopInput() and Audio::stop(), - /// and is guaranteed to be called on the application's main thread. - ~AudioInput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE = 0; - virtual bool isAlive() const; - bool isTransmitting() const; + friend class AudioNoiseWidget; + friend class AudioEchoWidget; + friend class AudioStats; + friend class AudioInputDialog; + +private: + Q_OBJECT + Q_DISABLE_COPY(AudioInput) +protected: + typedef enum { CodecCELT, CodecSpeex } CodecFormat; + typedef enum { SampleShort, SampleFloat } SampleFormat; + typedef void (*inMixerFunc)(float *RESTRICT, const void *RESTRICT, unsigned int, unsigned int, quint64); + +private: + bool bDebugDumpInput; ///< When true, dump pcm data to debug the echo canceller + std::ofstream outMic, outSpeaker, outProcessed; ///< Files to dump raw pcm data + + SpeexResamplerState *srsMic, *srsEcho; + + unsigned int iMicFilled, iEchoFilled; + inMixerFunc imfMic, imfEcho; + inMixerFunc chooseMixer(const unsigned int nchan, SampleFormat sf, quint64 mask); + void resetAudioProcessor(); + + OpusCodec *oCodec; + OpusEncoder *opusState; + DenoiseState *denoiseState; + bool selectCodec(); + void selectNoiseCancel(); + + typedef boost::array< unsigned char, 960 > EncodingOutputBuffer; + + int encodeOpusFrame(short *source, int size, EncodingOutputBuffer &buffer); + int encodeCELTFrame(short *pSource, EncodingOutputBuffer &buffer); + +protected: + MessageHandler::UDPMessageType umtType; + SampleFormat eMicFormat, eEchoFormat; + + unsigned int iMicChannels, iEchoChannels; + unsigned int iMicFreq, iEchoFreq; + unsigned int iMicLength, iEchoLength; + unsigned int iMicSampleSize, iEchoSampleSize; + int iEchoMCLength, iEchoFrameSize; + quint64 uiMicChannelMask, uiEchoChannelMask; + + bool bEchoMulti; + Settings::NoiseCancel noiseCancel; + static const unsigned int iSampleRate = SAMPLE_RATE; + static const int iFrameSize = SAMPLE_RATE / 100; + + QMutex qmSpeex; + SpeexPreprocessState *sppPreprocess; + SpeexEchoState *sesEcho; + + CELTCodec *cCodec; + CELTEncoder *ceEncoder; + + /// bResetEncoder is a flag that notifies + /// our encoder functions that the encoder + /// needs to be reset. + bool bResetEncoder; + + /// Encoded audio rate in bit/s + int iAudioQuality; + bool bAllowLowDelay; + /// Number of 10ms audio "frames" per packet (!= frames in packet) + int iAudioFrames; + + float *pfMicInput; + float *pfEchoInput; + + Resynchronizer resync; + std::vector< short > opusBuffer; + + void encodeAudioFrame(AudioChunk chunk); + void addMic(const void *data, unsigned int nsamp); + void addEcho(const void *data, unsigned int nsamp); + + volatile bool bRunning; + volatile bool bPreviousVoice; + + int iFrameCounter; + int iSilentFrames; + int iHoldFrames; + int iBufferedFrames; + + QList< QByteArray > qlFrames; + void flushCheck(const QByteArray &, bool terminator, int voiceTargetID); + + void initializeMixer(); + + static void adjustBandwidth(int bitspersec, int &bitrate, int &frames, bool &allowLowDelay); +signals: + void doDeaf(); + void doMute(); + +public: + typedef enum { ActivityStateIdle, ActivityStateReturnedFromIdle, ActivityStateActive } ActivityState; + + ActivityState activityState; + + bool bResetProcessor; + + Timer tIdle; + + int iBitrate; + float dPeakSpeaker, dPeakSignal, dMaxMic, dPeakMic, dPeakCleanMic; + float fSpeechProb; + + static int getNetworkBandwidth(int bitrate, int frames); + static void setMaxBandwidth(int bitspersec); + + /// Construct an AudioInput. + /// + /// This constructor is only ever called by Audio::startInput(), and is guaranteed + /// to be called on the application's main thread. + AudioInput(); + + /// Destroy an AudioInput. + /// + /// This destructor is only ever called by Audio::stopInput() and Audio::stop(), + /// and is guaranteed to be called on the application's main thread. + ~AudioInput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE = 0; + virtual bool isAlive() const; + bool isTransmitting() const; }; #endif diff --git a/src/mumble/AudioOutput.cpp b/src/mumble/AudioOutput.cpp index dd7b7f542..bdd34f7b8 100644 --- a/src/mumble/AudioOutput.cpp +++ b/src/mumble/AudioOutput.cpp @@ -6,7 +6,7 @@ // <cmath> includes <math.h>, but only if it isn't already included. // We include <cmath> as first header to make sure that we include <math.h> with _USE_MATH_DEFINES. #ifdef _MSC_VER -# define _USE_MATH_DEFINES +# define _USE_MATH_DEFINES #endif #include <cmath> @@ -16,19 +16,20 @@ #include "AudioInput.h" #include "AudioOutputSample.h" #include "AudioOutputSpeech.h" -#include "User.h" +#include "Channel.h" +#include "ChannelListener.h" #include "Message.h" -#include "Plugins.h" #include "PacketDataStream.h" +#include "Plugins.h" #include "ServerHandler.h" +#include "SpeechFlags.h" #include "Timer.h" +#include "User.h" #include "Utils.h" #include "VoiceRecorder.h" -#include "Channel.h" -#include "ChannelListener.h" -#include "SpeechFlags.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" // Remember that we cannot use static member classes that are not pointers, as the constructor @@ -36,13 +37,13 @@ // is called from global initialization. // Hence, we allocate upon first call. -QMap<QString, AudioOutputRegistrar *> *AudioOutputRegistrar::qmNew; +QMap< QString, AudioOutputRegistrar * > *AudioOutputRegistrar::qmNew; QString AudioOutputRegistrar::current = QString(); AudioOutputRegistrar::AudioOutputRegistrar(const QString &n, int p) : name(n), priority(p) { - if (! qmNew) - qmNew = new QMap<QString, AudioOutputRegistrar *>(); - qmNew->insert(name,this); + if (!qmNew) + qmNew = new QMap< QString, AudioOutputRegistrar * >(); + qmNew->insert(name, this); } AudioOutputRegistrar::~AudioOutputRegistrar() { @@ -50,12 +51,12 @@ AudioOutputRegistrar::~AudioOutputRegistrar() { } AudioOutputPtr AudioOutputRegistrar::newFromChoice(QString choice) { - if (! qmNew) + if (!qmNew) return AudioOutputPtr(); if (!choice.isEmpty() && qmNew->contains(choice)) { g.s.qsAudioOutput = choice; - current = choice; + current = choice; return AudioOutputPtr(qmNew->value(choice)->create()); } choice = g.s.qsAudioOutput; @@ -65,7 +66,7 @@ AudioOutputPtr AudioOutputRegistrar::newFromChoice(QString choice) { } AudioOutputRegistrar *r = nullptr; - foreach(AudioOutputRegistrar *aor, *qmNew) + foreach (AudioOutputRegistrar *aor, *qmNew) if (!r || (aor->priority > r->priority)) r = aor; if (r) { @@ -92,10 +93,10 @@ AudioOutput::~AudioOutput() { wait(); wipe(); - delete [] fSpeakers; - delete [] fSpeakerVolume; - delete [] bSpeakerPositional; - delete [] fStereoPanningFactor; + delete[] fSpeakers; + delete[] fSpeakerVolume; + delete[] bSpeakerPositional; + delete[] fStereoPanningFactor; } // Here's the theory. @@ -103,7 +104,6 @@ AudioOutput::~AudioOutput() { // close, we'll hear it full intensity from the left side, and "bloom" intensity from the right side. float AudioOutput::calcGain(float dotproduct, float distance) { - float dotfactor = (dotproduct + 1.0f) / 2.0f; float att; @@ -112,7 +112,7 @@ float AudioOutput::calcGain(float dotproduct, float distance) { if (g.s.fAudioMaxDistVolume > 0.99f) { att = qMin(1.0f, dotfactor + g.s.fAudioBloom); } else if (distance < g.s.fAudioMinDistance) { - float bloomfac = g.s.fAudioBloom * (1.0f - distance/g.s.fAudioMinDistance); + float bloomfac = g.s.fAudioBloom * (1.0f - distance / g.s.fAudioMinDistance); att = qMin(1.0f, bloomfac + dotfactor); } else { @@ -125,8 +125,8 @@ float AudioOutput::calcGain(float dotproduct, float distance) { if (mvol < 0.01f) mvol = 0.01f; - float drel = (distance-g.s.fAudioMinDistance) / (g.s.fAudioMaxDistance - g.s.fAudioMinDistance); - datt = powf(10.0f, log10f(mvol) * drel); + float drel = (distance - g.s.fAudioMinDistance) / (g.s.fAudioMaxDistance - g.s.fAudioMinDistance); + datt = powf(10.0f, log10f(mvol) * drel); } att = datt * dotfactor; @@ -135,7 +135,7 @@ float AudioOutput::calcGain(float dotproduct, float distance) { } void AudioOutput::wipe() { - foreach(AudioOutputUser *aop, qmOutputs) + foreach (AudioOutputUser *aop, qmOutputs) removeBuffer(aop); } @@ -147,21 +147,23 @@ const float *AudioOutput::getSpeakerPos(unsigned int &speakers) { return nullptr; } -void AudioOutput::addFrameToBuffer(ClientUser *user, const QByteArray &qbaPacket, unsigned int iSeq, MessageHandler::UDPMessageType type) { +void AudioOutput::addFrameToBuffer(ClientUser *user, const QByteArray &qbaPacket, unsigned int iSeq, + MessageHandler::UDPMessageType type) { if (iChannels == 0) return; qrwlOutputs.lockForRead(); // qmOutputs is a map of users and their AudioOutputUser objects, which will be create when audio from that user - // is received. This map will be iterated in mix(). After one's audio is finished, his AudioOutputUser will be removed - // from this map. - AudioOutputSpeech *aop = qobject_cast<AudioOutputSpeech *>(qmOutputs.value(user)); + // is received. This map will be iterated in mix(). After one's audio is finished, his AudioOutputUser will be + // removed from this map. + AudioOutputSpeech *aop = qobject_cast< AudioOutputSpeech * >(qmOutputs.value(user)); if (!UDPMessageTypeIsValidVoicePacket(type)) { - qWarning("AudioOutput: ignored frame with invalid message type 0x%x in addFrameToBuffer().", static_cast<unsigned char>(type)); + qWarning("AudioOutput: ignored frame with invalid message type 0x%x in addFrameToBuffer().", + static_cast< unsigned char >(type)); return; } - if (! aop || (aop->umtType != type)) { + if (!aop || (aop->umtType != type)) { qrwlOutputs.unlock(); if (aop) @@ -171,7 +173,7 @@ void AudioOutput::addFrameToBuffer(ClientUser *user, const QByteArray &qbaPacket QThread::yieldCurrentThread(); } - if (! iMixerFreq) + if (!iMixerFreq) return; qrwlOutputs.lockForWrite(); @@ -190,8 +192,8 @@ void AudioOutput::removeBuffer(const ClientUser *user) { void AudioOutput::removeBuffer(AudioOutputUser *aop) { QWriteLocker locker(&qrwlOutputs); - QMultiHash<const ClientUser *, AudioOutputUser *>::iterator i; - for (i=qmOutputs.begin(); i != qmOutputs.end(); ++i) { + QMultiHash< const ClientUser *, AudioOutputUser * >::iterator i; + for (i = qmOutputs.begin(); i != qmOutputs.end(); ++i) { if (i.value() == aop) { qmOutputs.erase(i); delete aop; @@ -218,7 +220,7 @@ AudioOutputSample *AudioOutput::playSample(const QString &filename, bool loop) { return nullptr; } - if (! iMixerFreq) + if (!iMixerFreq) return nullptr; QWriteLocker locker(&qrwlOutputs); @@ -226,7 +228,6 @@ AudioOutputSample *AudioOutput::playSample(const QString &filename, bool loop) { qmOutputs.insert(nullptr, aos); return aos; - } void AudioOutput::initializeMixer(const unsigned int *chanmasks, bool forceheadphone) { @@ -235,20 +236,20 @@ void AudioOutput::initializeMixer(const unsigned int *chanmasks, bool forceheadp delete[] fSpeakerVolume; delete[] fStereoPanningFactor; - fSpeakers = new float[iChannels * 3]; - bSpeakerPositional = new bool[iChannels]; - fSpeakerVolume = new float[iChannels]; + fSpeakers = new float[iChannels * 3]; + bSpeakerPositional = new bool[iChannels]; + fSpeakerVolume = new float[iChannels]; fStereoPanningFactor = new float[iChannels * 2]; memset(fSpeakers, 0, sizeof(float) * iChannels * 3); memset(bSpeakerPositional, 0, sizeof(bool) * iChannels); - for (unsigned int i=0;i<iChannels;++i) + for (unsigned int i = 0; i < iChannels; ++i) fSpeakerVolume[i] = 1.0f; if (iChannels > 1) { - for (unsigned int i=0;i<iChannels;i++) { - float *s = &fSpeakers[3*i]; + for (unsigned int i = 0; i < iChannels; i++) { + float *s = &fSpeakers[3 * i]; bSpeakerPositional[i] = true; switch (chanmasks[i]) { @@ -324,7 +325,7 @@ void AudioOutput::initializeMixer(const unsigned int *chanmasks, bool forceheadp break; default: bSpeakerPositional[i] = false; - fSpeakerVolume[i] = 0.0f; + fSpeakerVolume[i] = 0.0f; qWarning("AudioOutput: Unknown speaker %d: %08x", i, chanmasks[i]); break; } @@ -335,22 +336,23 @@ void AudioOutput::initializeMixer(const unsigned int *chanmasks, bool forceheadp fSpeakerVolume[i] = 0.0f; } } - for (unsigned int i=0;i<iChannels;i++) { - float d = sqrtf(fSpeakers[3*i+0]*fSpeakers[3*i+0] + fSpeakers[3*i+1]*fSpeakers[3*i+1] + fSpeakers[3*i+2]*fSpeakers[3*i+2]); + for (unsigned int i = 0; i < iChannels; i++) { + float d = sqrtf(fSpeakers[3 * i + 0] * fSpeakers[3 * i + 0] + fSpeakers[3 * i + 1] * fSpeakers[3 * i + 1] + + fSpeakers[3 * i + 2] * fSpeakers[3 * i + 2]); if (d > 0.0f) { - fSpeakers[3*i+0] /= d; - fSpeakers[3*i+1] /= d; - fSpeakers[3*i+2] /= d; + fSpeakers[3 * i + 0] /= d; + fSpeakers[3 * i + 1] /= d; + fSpeakers[3 * i + 2] /= d; } - float *spf = &fStereoPanningFactor[2*i]; - spf[0] = (1.0 - fSpeakers[i*3+0]) / 2.0; - spf[1] = (1.0 + fSpeakers[i*3+0]) / 2.0; + float *spf = &fStereoPanningFactor[2 * i]; + spf[0] = (1.0 - fSpeakers[i * 3 + 0]) / 2.0; + spf[1] = (1.0 + fSpeakers[i * 3 + 0]) / 2.0; } } else if (iChannels == 1) { fStereoPanningFactor[0] = 0.5; fStereoPanningFactor[1] = 0.5; } - iSampleSize = static_cast<int>(iChannels * ((eSampleFormat == SampleFloat) ? sizeof(float) : sizeof(short))); + iSampleSize = static_cast< int >(iChannels * ((eSampleFormat == SampleFloat) ? sizeof(float) : sizeof(short))); qWarning("AudioOutput: Initialized %d channel %d hz mixer", iChannels, iMixerFreq); } @@ -360,36 +362,36 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { #endif // A list of users that have audio to contribute - QList<AudioOutputUser *> qlMix; + QList< AudioOutputUser * > qlMix; // A list of users that no longer have any audio to play and can thus be deleted - QList<AudioOutputUser *> qlDel; - + QList< AudioOutputUser * > qlDel; + if (g.s.fVolume < 0.01f) { return false; } - const float adjustFactor = std::pow(10.f , -18.f / 20); - const float mul = g.s.fVolume; + const float adjustFactor = std::pow(10.f, -18.f / 20); + const float mul = g.s.fVolume; const unsigned int nchan = iChannels; - ServerHandlerPtr sh = g.sh; + ServerHandlerPtr sh = g.sh; VoiceRecorderPtr recorder; if (sh) { recorder = g.sh->recorder; } qrwlOutputs.lockForRead(); - + bool prioritySpeakerActive = false; - + // Get the users that are currently talking (and are thus serving as an audio source) - QMultiHash<const ClientUser *, AudioOutputUser *>::const_iterator it = qmOutputs.constBegin(); + QMultiHash< const ClientUser *, AudioOutputUser * >::const_iterator it = qmOutputs.constBegin(); while (it != qmOutputs.constEnd()) { AudioOutputUser *aop = it.value(); - if (! aop->prepareSampleBuffer(frameCount)) { + if (!aop->prepareSampleBuffer(frameCount)) { qlDel.append(aop); } else { qlMix.append(aop); - + const ClientUser *user = it.key(); if (user && user->bPrioritySpeaker) { prioritySpeakerActive = true; @@ -402,48 +404,49 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { prioritySpeakerActive = true; } - if (! qlMix.isEmpty()) { + if (!qlMix.isEmpty()) { // There are audio sources available -> mix those sources together and feed them into the audio backend - STACKVAR(float, speaker, iChannels*3); + STACKVAR(float, speaker, iChannels * 3); STACKVAR(float, svol, iChannels); - STACKVAR(float, fOutput, iChannels * frameCount); + STACKVAR(float, fOutput, iChannels *frameCount); - // If the audio backend uses a float-array we can sample and mix the audio sources directly into the output. Otherwise we'll have to - // use an intermediate buffer which we will convert to an array of shorts later - float *output = (eSampleFormat == SampleFloat) ? reinterpret_cast<float *>(outbuff) : fOutput; + // If the audio backend uses a float-array we can sample and mix the audio sources directly into the output. + // Otherwise we'll have to use an intermediate buffer which we will convert to an array of shorts later + float *output = (eSampleFormat == SampleFloat) ? reinterpret_cast< float * >(outbuff) : fOutput; bool validListener = false; memset(output, 0, sizeof(float) * frameCount * iChannels); // Initialize recorder if recording is enabled - boost::shared_array<float> recbuff; + boost::shared_array< float > recbuff; if (recorder) { - recbuff = boost::shared_array<float>(new float[frameCount]); + recbuff = boost::shared_array< float >(new float[frameCount]); memset(recbuff.get(), 0, sizeof(float) * frameCount); recorder->prepareBufferAdds(); } - for (unsigned int i=0;i<iChannels;++i) + for (unsigned int i = 0; i < iChannels; ++i) svol[i] = mul * fSpeakerVolume[i]; if (g.s.bPositionalAudio && (iChannels > 1) && g.p->fetch() - && (g.bPosTest || g.p->fCameraPosition[0] != 0 || g.p->fCameraPosition[1] != 0 || g.p->fCameraPosition[2] != 0)) { + && (g.bPosTest || g.p->fCameraPosition[0] != 0 || g.p->fCameraPosition[1] != 0 + || g.p->fCameraPosition[2] != 0)) { // Calculate the positional audio effects if it is enabled float front[3] = { g.p->fCameraFront[0], g.p->fCameraFront[1], g.p->fCameraFront[2] }; - float top[3] = { g.p->fCameraTop[0], g.p->fCameraTop[1], g.p->fCameraTop[2] }; + float top[3] = { g.p->fCameraTop[0], g.p->fCameraTop[1], g.p->fCameraTop[2] }; // Front vector is dominant; if it's zero we presume all is zero. - float flen = sqrtf(front[0]*front[0]+front[1]*front[1]+front[2]*front[2]); + float flen = sqrtf(front[0] * front[0] + front[1] * front[1] + front[2] * front[2]); if (flen > 0.0f) { front[0] *= (1.0f / flen); front[1] *= (1.0f / flen); front[2] *= (1.0f / flen); - float tlen = sqrtf(top[0]*top[0]+top[1]*top[1]+top[2]*top[2]); + float tlen = sqrtf(top[0] * top[0] + top[1] * top[1] + top[2] * top[2]); if (tlen > 0.0f) { top[0] *= (1.0f / tlen); @@ -456,18 +459,18 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { } const float dotproduct = front[0] * top[0] + front[1] * top[1] + front[2] * top[2]; - const float error = std::abs(dotproduct); + const float error = std::abs(dotproduct); if (error > 0.5f) { // Not perpendicular by a large margin. Assume Y up and rotate 90 degrees. float azimuth = 0.0f; if ((front[0] != 0.0f) || (front[2] != 0.0f)) azimuth = atan2f(front[2], front[0]); - float inclination = acosf(front[1]) - static_cast<float>(M_PI) / 2.0f; + float inclination = acosf(front[1]) - static_cast< float >(M_PI) / 2.0f; - top[0] = sinf(inclination)*cosf(azimuth); + top[0] = sinf(inclination) * cosf(azimuth); top[1] = cosf(inclination); - top[2] = sinf(inclination)*sinf(azimuth); + top[2] = sinf(inclination) * sinf(azimuth); } else if (error > 0.01f) { // Not perpendicular by a small margin. Find the nearest perpendicular vector. @@ -476,7 +479,7 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { top[2] -= front[2] * dotproduct; // normalize top again - tlen = sqrtf(top[0]*top[0]+top[1]*top[1]+top[2]*top[2]); + tlen = sqrtf(top[0] * top[0] + top[1] * top[1] + top[2] * top[2]); // tlen is guaranteed to be non-zero, otherwise error would have been larger than 0.5 top[0] *= (1.0f / tlen); top[1] *= (1.0f / tlen); @@ -493,7 +496,8 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { } // Calculate right vector as front X top - float right[3] = {top[1]*front[2] - top[2]*front[1], top[2]*front[0] - top[0]*front[2], top[0]*front[1] - top[1] * front[0] }; + float right[3] = { top[1] * front[2] - top[2] * front[1], top[2] * front[0] - top[0] * front[2], + top[0] * front[1] - top[1] * front[0] }; /* qWarning("Front: %f %f %f", front[0], front[1], front[2]); @@ -501,26 +505,31 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { qWarning("Right: %f %f %f", right[0], right[1], right[2]); */ // Rotate speakers to match orientation - for (unsigned int i=0;i<iChannels;++i) { - speaker[3*i+0] = fSpeakers[3*i+0] * right[0] + fSpeakers[3*i+1] * top[0] + fSpeakers[3*i+2] * front[0]; - speaker[3*i+1] = fSpeakers[3*i+0] * right[1] + fSpeakers[3*i+1] * top[1] + fSpeakers[3*i+2] * front[1]; - speaker[3*i+2] = fSpeakers[3*i+0] * right[2] + fSpeakers[3*i+1] * top[2] + fSpeakers[3*i+2] * front[2]; + for (unsigned int i = 0; i < iChannels; ++i) { + speaker[3 * i + 0] = + fSpeakers[3 * i + 0] * right[0] + fSpeakers[3 * i + 1] * top[0] + fSpeakers[3 * i + 2] * front[0]; + speaker[3 * i + 1] = + fSpeakers[3 * i + 0] * right[1] + fSpeakers[3 * i + 1] * top[1] + fSpeakers[3 * i + 2] * front[1]; + speaker[3 * i + 2] = + fSpeakers[3 * i + 0] * right[2] + fSpeakers[3 * i + 1] * top[2] + fSpeakers[3 * i + 2] * front[2]; } validListener = true; } - foreach(AudioOutputUser *aop, qlMix) { + foreach (AudioOutputUser *aop, qlMix) { // Iterate through all audio sources and mix them together into the output (or the intermediate array) - const float * RESTRICT pfBuffer = aop->pfBuffer; - float volumeAdjustment = 1; + const float *RESTRICT pfBuffer = aop->pfBuffer; + float volumeAdjustment = 1; - // Check if the audio source is a user speaking (instead of a sample playback) and apply potential volume adjustments - AudioOutputSpeech *speech = qobject_cast<AudioOutputSpeech *>(aop); + // Check if the audio source is a user speaking (instead of a sample playback) and apply potential volume + // adjustments + AudioOutputSpeech *speech = qobject_cast< AudioOutputSpeech * >(aop); if (speech) { const ClientUser *user = speech->p; volumeAdjustment *= user->getLocalVolumeAdjustments(); - if (user->cChannel && ChannelListener::isListening(g.uiSession, user->cChannel->iId) && (speech->ucFlags & SpeechFlags::Listen)) { + if (user->cChannel && ChannelListener::isListening(g.uiSession, user->cChannel->iId) + && (speech->ucFlags & SpeechFlags::Listen)) { // We are receiving this audio packet only because we are listening to the channel // the speaking user is in. Thus we receive the audio via our "listener proxy". // Thus we'll apply the volume adjustment for our listener proxy as well @@ -528,10 +537,7 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { } if (prioritySpeakerActive) { - - if (user->tsState != Settings::Whispering - && !user->bPrioritySpeaker) { - + if (user->tsState != Settings::Whispering && !user->bPrioritySpeaker) { volumeAdjustment *= adjustFactor; } } @@ -544,7 +550,7 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { // Mix down stereo to mono. TODO: stereo record support // frame: for a stereo stream, the [LR] pair inside ...[LR]LRLRLR.... is a frame for (unsigned int i = 0; i < frameCount; ++i) { - recbuff[i] += (pfBuffer[2*i] / 2.0 + pfBuffer[2*i+1] / 2.0) * volumeAdjustment; + recbuff[i] += (pfBuffer[2 * i] / 2.0 + pfBuffer[2 * i + 1] / 2.0) * volumeAdjustment; } } else { for (unsigned int i = 0; i < frameCount; ++i) { @@ -554,12 +560,12 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { if (!recorder->isInMixDownMode()) { recorder->addBuffer(speech->p, recbuff, frameCount); - recbuff = boost::shared_array<float>(new float[frameCount]); + recbuff = boost::shared_array< float >(new float[frameCount]); memset(recbuff.get(), 0, sizeof(float) * frameCount); } // Don't add the local audio to the real output - if (qobject_cast<RecordUser *>(speech->p)) { + if (qobject_cast< RecordUser * >(speech->p)) { continue; } } @@ -567,18 +573,19 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { if (validListener && ((aop->fPos[0] != 0.0f) || (aop->fPos[1] != 0.0f) || (aop->fPos[2] != 0.0f))) { // Add position to position map - AudioOutputSpeech *speech = qobject_cast<AudioOutputSpeech *>(aop); + AudioOutputSpeech *speech = qobject_cast< AudioOutputSpeech * >(aop); #ifdef USE_MANUAL_PLUGIN if (speech) { const ClientUser *user = speech->p; // The coordinates in the plane are actually given by x and z instead of x and y (y is up) - positions.insert(user->uiSession, {aop->fPos[0], aop->fPos[2]}); + positions.insert(user->uiSession, { aop->fPos[0], aop->fPos[2] }); } #endif // If positional audio is enabled, calculate the respective audio effect here - float dir[3] = { aop->fPos[0] - g.p->fCameraPosition[0], aop->fPos[1] - g.p->fCameraPosition[1], aop->fPos[2] - g.p->fCameraPosition[2] }; - float len = sqrtf(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]); + float dir[3] = { aop->fPos[0] - g.p->fCameraPosition[0], aop->fPos[1] - g.p->fCameraPosition[1], + aop->fPos[2] - g.p->fCameraPosition[2] }; + float len = sqrtf(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]); if (len > 0.0f) { dir[0] /= len; dir[1] /= len; @@ -588,49 +595,54 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { qWarning("Voice pos: %f %f %f", aop->fPos[0], aop->fPos[1], aop->fPos[2]); qWarning("Voice dir: %f %f %f", dir[0], dir[1], dir[2]); */ - if (! aop->pfVolume) { + if (!aop->pfVolume) { aop->pfVolume = new float[nchan]; - for (unsigned int s=0;s<nchan;++s) + for (unsigned int s = 0; s < nchan; ++s) aop->pfVolume[s] = -1.0; } - for (unsigned int s=0;s<nchan;++s) { - const float dot = bSpeakerPositional[s] ? dir[0] * speaker[s*3+0] + dir[1] * speaker[s*3+1] + dir[2] * speaker[s*3+2] : 1.0f; - const float str = svol[s] * calcGain(dot, len) * volumeAdjustment; - float * RESTRICT o = output + s; - const float old = (aop->pfVolume[s] >= 0.0f) ? aop->pfVolume[s] : str; - const float inc = (str - old) / static_cast<float>(frameCount); - aop->pfVolume[s] = str; + for (unsigned int s = 0; s < nchan; ++s) { + const float dot = bSpeakerPositional[s] ? dir[0] * speaker[s * 3 + 0] + dir[1] * speaker[s * 3 + 1] + + dir[2] * speaker[s * 3 + 2] + : 1.0f; + const float str = svol[s] * calcGain(dot, len) * volumeAdjustment; + float *RESTRICT o = output + s; + const float old = (aop->pfVolume[s] >= 0.0f) ? aop->pfVolume[s] : str; + const float inc = (str - old) / static_cast< float >(frameCount); + aop->pfVolume[s] = str; /* - qWarning("%d: Pos %f %f %f : Dot %f Len %f Str %f", s, speaker[s*3+0], speaker[s*3+1], speaker[s*3+2], dot, len, str); + qWarning("%d: Pos %f %f %f : Dot %f Len %f Str %f", s, speaker[s*3+0], + speaker[s*3+1], speaker[s*3+2], dot, len, str); */ if ((old >= 0.00000001f) || (str >= 0.00000001f)) { for (unsigned int i = 0; i < frameCount; ++i) { if (speech && speech->bStereo) { // Mix stereo user's stream into mono // frame: for a stereo stream, the [LR] pair inside ...[LR]LRLRLR.... is a frame - o[i * nchan] += (pfBuffer[2 * i] / 2.0 + pfBuffer[2 * i + 1] / 2.0) * - (old + inc * static_cast<float>(i)); + o[i * nchan] += (pfBuffer[2 * i] / 2.0 + pfBuffer[2 * i + 1] / 2.0) + * (old + inc * static_cast< float >(i)); } else { - o[i * nchan] += pfBuffer[i] * (old + inc * static_cast<float>(i)); + o[i * nchan] += pfBuffer[i] * (old + inc * static_cast< float >(i)); } } } } } else { - // Mix the current audio source into the output by adding it to the elements of the output buffer after having applied - // a volume adjustment - for (unsigned int s=0;s<nchan;++s) { - const float str = svol[s] * volumeAdjustment; - float * RESTRICT o = output + s; - if (aop->bStereo){ + // Mix the current audio source into the output by adding it to the elements of the output buffer after + // having applied a volume adjustment + for (unsigned int s = 0; s < nchan; ++s) { + const float str = svol[s] * volumeAdjustment; + float *RESTRICT o = output + s; + if (aop->bStereo) { // Linear-panning stereo stream according to the projection of fSpeaker vector on left-right // direction. // frame: for a stereo stream, the [LR] pair inside ...[LR]LRLRLR.... is a frame - for (unsigned int i=0;i<frameCount;++i) - o[i*nchan] += (pfBuffer[2*i] * fStereoPanningFactor[2*s+0] + pfBuffer[2*i+1] * fStereoPanningFactor[2*s+1]) * str; + for (unsigned int i = 0; i < frameCount; ++i) + o[i * nchan] += (pfBuffer[2 * i] * fStereoPanningFactor[2 * s + 0] + + pfBuffer[2 * i + 1] * fStereoPanningFactor[2 * s + 1]) + * str; } else { - for (unsigned int i=0;i<frameCount;++i) - o[i*nchan] += pfBuffer[i] * str; + for (unsigned int i = 0; i < frameCount; ++i) + o[i * nchan] += pfBuffer[i] * str; } } } @@ -642,26 +654,27 @@ bool AudioOutput::mix(void *outbuff, unsigned int frameCount) { // Clip the output audio if (eSampleFormat == SampleFloat) - for (unsigned int i=0;i<frameCount*iChannels;i++) + for (unsigned int i = 0; i < frameCount * iChannels; i++) output[i] = qBound(-1.0f, output[i], 1.0f); else // Also convert the intermediate float array into an array of shorts before writing it to the outbuff - for (unsigned int i=0;i<frameCount*iChannels;i++) - reinterpret_cast<short *>(outbuff)[i] = static_cast<short>(qBound(-32768.f, (output[i] * 32768.f), 32767.f)); + for (unsigned int i = 0; i < frameCount * iChannels; i++) + reinterpret_cast< short * >(outbuff)[i] = + static_cast< short >(qBound(-32768.f, (output[i] * 32768.f), 32767.f)); } qrwlOutputs.unlock(); // Delete all AudioOutputUsers that no longer provide any new audio - foreach(AudioOutputUser *aop, qlDel) + foreach (AudioOutputUser *aop, qlDel) removeBuffer(aop); #ifdef USE_MANUAL_PLUGIN Manual::setSpeakerPositions(positions); #endif - + // Return whether data has been written to the outbuff - return (! qlMix.isEmpty()); + return (!qlMix.isEmpty()); } bool AudioOutput::isAlive() const { diff --git a/src/mumble/AudioOutput.h b/src/mumble/AudioOutput.h index e0d5b8ec8..6567cc8e8 100644 --- a/src/mumble/AudioOutput.h +++ b/src/mumble/AudioOutput.h @@ -6,12 +6,12 @@ #ifndef MUMBLE_MUMBLE_AUDIOOUTPUT_H_ #define MUMBLE_MUMBLE_AUDIOOUTPUT_H_ -#include <boost/shared_ptr.hpp> #include <QtCore/QObject> #include <QtCore/QThread> +#include <boost/shared_ptr.hpp> #ifdef USE_MANUAL_PLUGIN - #include "ManualPlugin.h" +# include "ManualPlugin.h" #endif // AudioOutput depends on User being valid. This means it's important @@ -21,24 +21,24 @@ // having them use resources while unused. #ifndef SPEAKER_FRONT_LEFT -#define SPEAKER_FRONT_LEFT 0x1 -#define SPEAKER_FRONT_RIGHT 0x2 -#define SPEAKER_FRONT_CENTER 0x4 -#define SPEAKER_LOW_FREQUENCY 0x8 -#define SPEAKER_BACK_LEFT 0x10 -#define SPEAKER_BACK_RIGHT 0x20 -#define SPEAKER_FRONT_LEFT_OF_CENTER 0x40 -#define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80 -#define SPEAKER_BACK_CENTER 0x100 -#define SPEAKER_SIDE_LEFT 0x200 -#define SPEAKER_SIDE_RIGHT 0x400 -#define SPEAKER_TOP_CENTER 0x800 -#define SPEAKER_TOP_FRONT_LEFT 0x1000 -#define SPEAKER_TOP_FRONT_CENTER 0x2000 -#define SPEAKER_TOP_FRONT_RIGHT 0x4000 -#define SPEAKER_TOP_BACK_LEFT 0x8000 -#define SPEAKER_TOP_BACK_CENTER 0x10000 -#define SPEAKER_TOP_BACK_RIGHT 0x20000 +# define SPEAKER_FRONT_LEFT 0x1 +# define SPEAKER_FRONT_RIGHT 0x2 +# define SPEAKER_FRONT_CENTER 0x4 +# define SPEAKER_LOW_FREQUENCY 0x8 +# define SPEAKER_BACK_LEFT 0x10 +# define SPEAKER_BACK_RIGHT 0x20 +# define SPEAKER_FRONT_LEFT_OF_CENTER 0x40 +# define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80 +# define SPEAKER_BACK_CENTER 0x100 +# define SPEAKER_SIDE_LEFT 0x200 +# define SPEAKER_SIDE_RIGHT 0x400 +# define SPEAKER_TOP_CENTER 0x800 +# define SPEAKER_TOP_FRONT_LEFT 0x1000 +# define SPEAKER_TOP_FRONT_CENTER 0x2000 +# define SPEAKER_TOP_FRONT_RIGHT 0x4000 +# define SPEAKER_TOP_BACK_LEFT 0x8000 +# define SPEAKER_TOP_BACK_CENTER 0x10000 +# define SPEAKER_TOP_BACK_RIGHT 0x20000 #endif #include "Audio.h" @@ -49,82 +49,84 @@ class ClientUser; class AudioOutputUser; class AudioOutputSample; -typedef boost::shared_ptr<AudioOutput> AudioOutputPtr; +typedef boost::shared_ptr< AudioOutput > AudioOutputPtr; class AudioOutputRegistrar { - private: - Q_DISABLE_COPY(AudioOutputRegistrar) - public: - static QMap<QString, AudioOutputRegistrar *> *qmNew; - static QString current; - static AudioOutputPtr newFromChoice(QString choice = QString()); - - const QString name; - int priority; - - AudioOutputRegistrar(const QString &n, int priority = 0); - virtual ~AudioOutputRegistrar(); - virtual AudioOutput *create() = 0; - virtual const QList<audioDevice> getDeviceChoices() = 0; - virtual void setDeviceChoice(const QVariant &, Settings &) = 0; - virtual bool canMuteOthers() const; - virtual bool usesOutputDelay() const; - virtual bool canExclusive() const; +private: + Q_DISABLE_COPY(AudioOutputRegistrar) +public: + static QMap< QString, AudioOutputRegistrar * > *qmNew; + static QString current; + static AudioOutputPtr newFromChoice(QString choice = QString()); + + const QString name; + int priority; + + AudioOutputRegistrar(const QString &n, int priority = 0); + virtual ~AudioOutputRegistrar(); + virtual AudioOutput *create() = 0; + virtual const QList< audioDevice > getDeviceChoices() = 0; + virtual void setDeviceChoice(const QVariant &, Settings &) = 0; + virtual bool canMuteOthers() const; + virtual bool usesOutputDelay() const; + virtual bool canExclusive() const; }; class AudioOutput : public QThread { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioOutput) - private: - /// Speaker positional vector - float *fSpeakers = nullptr; - float *fSpeakerVolume = nullptr; - bool *bSpeakerPositional = nullptr; - /// Used when panning stereo stream w.r.t. each speaker. - float * fStereoPanningFactor = nullptr; - protected: - enum { SampleShort, SampleFloat } eSampleFormat = SampleFloat; - volatile bool bRunning = true; - unsigned int iFrameSize = SAMPLE_RATE / 100; - volatile unsigned int iMixerFreq = 0; - unsigned int iChannels = 0; - unsigned int iSampleSize = 0; - unsigned int iBufferSize = 0; - QReadWriteLock qrwlOutputs; - QMultiHash<const ClientUser *, AudioOutputUser *> qmOutputs; +private: + Q_OBJECT + Q_DISABLE_COPY(AudioOutput) +private: + /// Speaker positional vector + float *fSpeakers = nullptr; + float *fSpeakerVolume = nullptr; + bool *bSpeakerPositional = nullptr; + /// Used when panning stereo stream w.r.t. each speaker. + float *fStereoPanningFactor = nullptr; + +protected: + enum { SampleShort, SampleFloat } eSampleFormat = SampleFloat; + volatile bool bRunning = true; + unsigned int iFrameSize = SAMPLE_RATE / 100; + volatile unsigned int iMixerFreq = 0; + unsigned int iChannels = 0; + unsigned int iSampleSize = 0; + unsigned int iBufferSize = 0; + QReadWriteLock qrwlOutputs; + QMultiHash< const ClientUser *, AudioOutputUser * > qmOutputs; #ifdef USE_MANUAL_PLUGIN - QHash<unsigned int, Position2D> positions; + QHash< unsigned int, Position2D > positions; #endif - virtual void removeBuffer(AudioOutputUser *); - void initializeMixer(const unsigned int *chanmasks, bool forceheadphone = false); - bool mix(void *output, unsigned int frameCount); - public: - void wipe(); - - /// Construct an AudioOutput. - /// - /// This constructor is only ever called by Audio::startOutput(), and is guaranteed - /// to be called on the application's main thread. - AudioOutput() {}; - - /// Destroy an AudioOutput. - /// - /// This destructor is only ever called by Audio::stopOutput() and Audio::stop(), - /// and is guaranteed to be called on the application's main thread. - ~AudioOutput() Q_DECL_OVERRIDE; - - void addFrameToBuffer(ClientUser *, const QByteArray &, unsigned int iSeq, MessageHandler::UDPMessageType type); - void removeBuffer(const ClientUser *); - AudioOutputSample *playSample(const QString &filename, bool loop = false); - void run() Q_DECL_OVERRIDE = 0; - virtual bool isAlive() const; - const float *getSpeakerPos(unsigned int &nspeakers); - static float calcGain(float dotproduct, float distance); - unsigned int getMixerFreq() const; - void setBufferSize(unsigned int bufferSize); + virtual void removeBuffer(AudioOutputUser *); + void initializeMixer(const unsigned int *chanmasks, bool forceheadphone = false); + bool mix(void *output, unsigned int frameCount); + +public: + void wipe(); + + /// Construct an AudioOutput. + /// + /// This constructor is only ever called by Audio::startOutput(), and is guaranteed + /// to be called on the application's main thread. + AudioOutput(){}; + + /// Destroy an AudioOutput. + /// + /// This destructor is only ever called by Audio::stopOutput() and Audio::stop(), + /// and is guaranteed to be called on the application's main thread. + ~AudioOutput() Q_DECL_OVERRIDE; + + void addFrameToBuffer(ClientUser *, const QByteArray &, unsigned int iSeq, MessageHandler::UDPMessageType type); + void removeBuffer(const ClientUser *); + AudioOutputSample *playSample(const QString &filename, bool loop = false); + void run() Q_DECL_OVERRIDE = 0; + virtual bool isAlive() const; + const float *getSpeakerPos(unsigned int &nspeakers); + static float calcGain(float dotproduct, float distance); + unsigned int getMixerFreq() const; + void setBufferSize(unsigned int bufferSize); }; #endif diff --git a/src/mumble/AudioOutputSample.cpp b/src/mumble/AudioOutputSample.cpp index 981a76518..08ed7ee11 100644 --- a/src/mumble/AudioOutputSample.cpp +++ b/src/mumble/AudioOutputSample.cpp @@ -15,19 +15,20 @@ #include <cmath> SoundFile::SoundFile(const QString &fname) { - siInfo.frames = 0; - siInfo.channels = 1; + siInfo.frames = 0; + siInfo.channels = 1; siInfo.samplerate = 0; - siInfo.sections = 0; - siInfo.seekable = 0; - siInfo.format = 0; + siInfo.sections = 0; + siInfo.seekable = 0; + siInfo.format = 0; sfFile = nullptr; qfFile.setFileName(fname); if (qfFile.open(QIODevice::ReadOnly)) { - static SF_VIRTUAL_IO svi = {&SoundFile::vio_get_filelen, &SoundFile::vio_seek, &SoundFile::vio_read, &SoundFile::vio_write, &SoundFile::vio_tell}; + static SF_VIRTUAL_IO svi = { &SoundFile::vio_get_filelen, &SoundFile::vio_seek, &SoundFile::vio_read, + &SoundFile::vio_write, &SoundFile::vio_tell }; sfFile = sf_open_virtual(&svi, SFM_READ, &siInfo, this); } @@ -67,18 +68,18 @@ sf_count_t SoundFile::read(float *ptr, sf_count_t items) { } sf_count_t SoundFile::vio_get_filelen(void *user_data) { - SoundFile *sf = reinterpret_cast<SoundFile *>(user_data); + SoundFile *sf = reinterpret_cast< SoundFile * >(user_data); - if (! sf->qfFile.isOpen()) + if (!sf->qfFile.isOpen()) return -1; return (sf->qfFile.size()); } sf_count_t SoundFile::vio_seek(sf_count_t offset, int whence, void *user_data) { - SoundFile *sf = reinterpret_cast<SoundFile *>(user_data); + SoundFile *sf = reinterpret_cast< SoundFile * >(user_data); - if (! sf->qfFile.isOpen()) + if (!sf->qfFile.isOpen()) return -1; if (whence == SEEK_SET) { @@ -92,46 +93,48 @@ sf_count_t SoundFile::vio_seek(sf_count_t offset, int whence, void *user_data) { } sf_count_t SoundFile::vio_read(void *ptr, sf_count_t count, void *user_data) { - SoundFile *sf = reinterpret_cast<SoundFile *>(user_data); + SoundFile *sf = reinterpret_cast< SoundFile * >(user_data); - if (! sf->qfFile.isOpen()) + if (!sf->qfFile.isOpen()) return -1; - return sf->qfFile.read(reinterpret_cast<char *>(ptr), count); + return sf->qfFile.read(reinterpret_cast< char * >(ptr), count); } sf_count_t SoundFile::vio_write(const void *ptr, sf_count_t count, void *user_data) { - SoundFile *sf = reinterpret_cast<SoundFile *>(user_data); + SoundFile *sf = reinterpret_cast< SoundFile * >(user_data); - if (! sf->qfFile.isOpen()) + if (!sf->qfFile.isOpen()) return -1; - return sf->qfFile.write(reinterpret_cast<const char *>(ptr), count); + return sf->qfFile.write(reinterpret_cast< const char * >(ptr), count); } sf_count_t SoundFile::vio_tell(void *user_data) { - SoundFile *sf = reinterpret_cast<SoundFile *>(user_data); + SoundFile *sf = reinterpret_cast< SoundFile * >(user_data); - if (! sf->qfFile.isOpen()) + if (!sf->qfFile.isOpen()) return -1; return sf->qfFile.pos(); } -AudioOutputSample::AudioOutputSample(const QString &name, SoundFile *psndfile, bool loop, unsigned int freq, unsigned int systemMaxBufferSize) : AudioOutputUser(name) { +AudioOutputSample::AudioOutputSample(const QString &name, SoundFile *psndfile, bool loop, unsigned int freq, + unsigned int systemMaxBufferSize) + : AudioOutputUser(name) { int err; - sfHandle = psndfile; + sfHandle = psndfile; iOutSampleRate = freq; if (sfHandle->channels() == 1) { iBufferSize = systemMaxBufferSize; - bStereo = false; + bStereo = false; } else if (sfHandle->channels() == 2) { iBufferSize = systemMaxBufferSize * 2; - bStereo = true; + bStereo = true; } else { - sfHandle = nullptr; // sound file is corrupted + sfHandle = nullptr; // sound file is corrupted return; } @@ -143,11 +146,11 @@ AudioOutputSample::AudioOutputSample(const QString &name, SoundFile *psndfile, b qWarning() << "Format: " << sfHandle->format() << endl; */ // If the frequencies don't match initialize the resampler - if (sfHandle->samplerate() != static_cast<int>(freq)) { + if (sfHandle->samplerate() != static_cast< int >(freq)) { srs = speex_resampler_init(bStereo ? 2 : 1, sfHandle->samplerate(), iOutSampleRate, 3, &err); if (err != RESAMPLER_ERR_SUCCESS) { qWarning() << "Initialize " << sfHandle->samplerate() << " to " << iOutSampleRate << " resampler failed!"; - srs = nullptr; + srs = nullptr; sfHandle = nullptr; return; } @@ -156,8 +159,8 @@ AudioOutputSample::AudioOutputSample(const QString &name, SoundFile *psndfile, b } iLastConsume = iBufferFilled = 0; - bLoop = loop; - bEof = false; + bLoop = loop; + bEof = false; } AudioOutputSample::~AudioOutputSample() { @@ -168,13 +171,13 @@ AudioOutputSample::~AudioOutputSample() { sfHandle = nullptr; } -SoundFile* AudioOutputSample::loadSndfile(const QString &filename) { +SoundFile *AudioOutputSample::loadSndfile(const QString &filename) { SoundFile *sf; // Create the filehandle and do a quick check if everything is ok sf = new SoundFile(filename); - if (! sf->isOpen()) { + if (!sf->isOpen()) { qWarning() << "File " << filename << " failed to open"; delete sf; return nullptr; @@ -195,13 +198,15 @@ SoundFile* AudioOutputSample::loadSndfile(const QString &filename) { } QString AudioOutputSample::browseForSndfile(QString defaultpath) { - QString file = QFileDialog::getOpenFileName(nullptr, tr("Choose sound file"), defaultpath, QLatin1String("*.wav *.ogg *.ogv *.oga *.flac *.aiff")); - if (! file.isEmpty()) { + QString file = QFileDialog::getOpenFileName(nullptr, tr("Choose sound file"), defaultpath, + QLatin1String("*.wav *.ogg *.ogv *.oga *.flac *.aiff")); + if (!file.isEmpty()) { SoundFile *sf = AudioOutputSample::loadSndfile(file); if (!sf) { - QMessageBox::critical(nullptr, - tr("Invalid sound file"), - tr("The file '%1' cannot be used by Mumble. Please select a file with a compatible format and encoding.").arg(file.toHtmlEscaped())); + QMessageBox::critical(nullptr, tr("Invalid sound file"), + tr("The file '%1' cannot be used by Mumble. Please select a file with a compatible " + "format and encoding.") + .arg(file.toHtmlEscaped())); return QString(); } delete sf; @@ -210,11 +215,11 @@ QString AudioOutputSample::browseForSndfile(QString defaultpath) { } bool AudioOutputSample::prepareSampleBuffer(unsigned int frameCount) { - unsigned int channels = bStereo ? 2 : 1; + unsigned int channels = bStereo ? 2 : 1; unsigned int sampleCount = frameCount * channels; // Forward the buffer - for (unsigned int i=iLastConsume;i<iBufferFilled;++i) - pfBuffer[i-iLastConsume]=pfBuffer[i]; + for (unsigned int i = iLastConsume; i < iBufferFilled; ++i) + pfBuffer[i - iLastConsume] = pfBuffer[i]; iBufferFilled -= iLastConsume; iLastConsume = sampleCount; @@ -223,7 +228,8 @@ bool AudioOutputSample::prepareSampleBuffer(unsigned int frameCount) { return true; // Calculate the required buffersize to hold the results - unsigned int iInputFrames = static_cast<unsigned int>(ceilf(static_cast<float>(frameCount * sfHandle->samplerate()) / static_cast<float>(iOutSampleRate))); + unsigned int iInputFrames = static_cast< unsigned int >( + ceilf(static_cast< float >(frameCount * sfHandle->samplerate()) / static_cast< float >(iOutSampleRate))); unsigned int iInputSamples = iInputFrames * channels; STACKVAR(float, fOut, iInputSamples); @@ -242,13 +248,13 @@ bool AudioOutputSample::prepareSampleBuffer(unsigned int frameCount) { // We reached the eof or encountered an error, stuff with zeroes memset(pOut, 0, sizeof(float) * (iInputSamples - read)); read = iInputSamples; - eof = true; + eof = true; } else { sfHandle->seek(SEEK_SET, 0); } } - spx_uint32_t inlen = static_cast<unsigned int>(read) / channels; + spx_uint32_t inlen = static_cast< unsigned int >(read) / channels; spx_uint32_t outlen = frameCount; if (srs) { // If necessary resample diff --git a/src/mumble/AudioOutputSample.h b/src/mumble/AudioOutputSample.h index 7df23e136..135127ac8 100644 --- a/src/mumble/AudioOutputSample.h +++ b/src/mumble/AudioOutputSample.h @@ -6,62 +6,65 @@ #ifndef MUMBLE_MUMBLE_AUDIOOUTPUTSAMPLE_H_ #define MUMBLE_MUMBLE_AUDIOOUTPUTSAMPLE_H_ +#include <QtCore/QFile> +#include <QtCore/QObject> #include <sndfile.h> #include <speex/speex_resampler.h> -#include <QtCore/QObject> -#include <QtCore/QFile> #include "AudioOutputUser.h" class SoundFile : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(SoundFile) - protected: - SNDFILE *sfFile; - SF_INFO siInfo; - QFile qfFile; - static sf_count_t vio_get_filelen(void *user_data); - static sf_count_t vio_seek(sf_count_t offset, int whence, void *user_data); - static sf_count_t vio_read(void *ptr, sf_count_t count, void *user_data); - static sf_count_t vio_write(const void *ptr, sf_count_t count, void *user_data); - static sf_count_t vio_tell(void *user_data); - public: - SoundFile(const QString &fname); - ~SoundFile(); +private: + Q_OBJECT + Q_DISABLE_COPY(SoundFile) +protected: + SNDFILE *sfFile; + SF_INFO siInfo; + QFile qfFile; + static sf_count_t vio_get_filelen(void *user_data); + static sf_count_t vio_seek(sf_count_t offset, int whence, void *user_data); + static sf_count_t vio_read(void *ptr, sf_count_t count, void *user_data); + static sf_count_t vio_write(const void *ptr, sf_count_t count, void *user_data); + static sf_count_t vio_tell(void *user_data); + +public: + SoundFile(const QString &fname); + ~SoundFile(); - int channels() const; - int samplerate() const; - int error() const ; - QString strError() const; - bool isOpen() const; + int channels() const; + int samplerate() const; + int error() const; + QString strError() const; + bool isOpen() const; - sf_count_t seek(sf_count_t frames, int whence); - sf_count_t read(float *ptr, sf_count_t items); + sf_count_t seek(sf_count_t frames, int whence); + sf_count_t read(float *ptr, sf_count_t items); }; class AudioOutputSample : public AudioOutputUser { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioOutputSample) - protected: - unsigned int iLastConsume; - unsigned int iBufferFilled; - unsigned int iOutSampleRate; - SpeexResamplerState *srs; +private: + Q_OBJECT + Q_DISABLE_COPY(AudioOutputSample) +protected: + unsigned int iLastConsume; + unsigned int iBufferFilled; + unsigned int iOutSampleRate; + SpeexResamplerState *srs; + + SoundFile *sfHandle; - SoundFile *sfHandle; + bool bLoop; + bool bEof; +signals: + void playbackFinished(); - bool bLoop; - bool bEof; - signals: - void playbackFinished(); - public: - static SoundFile* loadSndfile(const QString &filename); - static QString browseForSndfile(QString defaultpath=QString()); - virtual bool prepareSampleBuffer(unsigned int frameCount) Q_DECL_OVERRIDE; - AudioOutputSample(const QString &name, SoundFile *psndfile, bool repeat, unsigned int freq, unsigned int bufferSize); - ~AudioOutputSample() Q_DECL_OVERRIDE; +public: + static SoundFile *loadSndfile(const QString &filename); + static QString browseForSndfile(QString defaultpath = QString()); + virtual bool prepareSampleBuffer(unsigned int frameCount) Q_DECL_OVERRIDE; + AudioOutputSample(const QString &name, SoundFile *psndfile, bool repeat, unsigned int freq, + unsigned int bufferSize); + ~AudioOutputSample() Q_DECL_OVERRIDE; }; -#endif // AUDIOOUTPUTSAMPLE_H_ +#endif // AUDIOOUTPUTSAMPLE_H_ diff --git a/src/mumble/AudioOutputSpeech.cpp b/src/mumble/AudioOutputSpeech.cpp index e7c138d90..56b2c434b 100644 --- a/src/mumble/AudioOutputSpeech.cpp +++ b/src/mumble/AudioOutputSpeech.cpp @@ -8,7 +8,7 @@ // (triggering the guard and effectively preventing a "fix include") // we define and include before anything else. #ifdef _MSC_VER -# define _USE_MATH_DEFINES +# define _USE_MATH_DEFINES #endif #include <cmath> @@ -18,28 +18,30 @@ #include "Audio.h" #include "CELTCodec.h" #ifdef USE_OPUS -# include "OpusCodec.h" +# include "OpusCodec.h" #endif #include "ClientUser.h" -#include "Global.h" #include "PacketDataStream.h" -#include "Utils.h" #include "SpeechFlags.h" +#include "Utils.h" +#include "Global.h" -AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, MessageHandler::UDPMessageType type, unsigned int systemMaxBufferSize) : AudioOutputUser(user->qsName) { +AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, MessageHandler::UDPMessageType type, + unsigned int systemMaxBufferSize) + : AudioOutputUser(user->qsName) { int err; - p = user; - umtType = type; + p = user; + umtType = type; iMixerFreq = freq; - cCodec = nullptr; + cCodec = nullptr; cdDecoder = nullptr; - dsSpeex = nullptr; - oCodec = nullptr; + dsSpeex = nullptr; + oCodec = nullptr; opusState = nullptr; bHasTerminator = false; - bStereo = false; + bStereo = false; iSampleRate = SAMPLE_RATE; @@ -57,17 +59,18 @@ AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, Messag // Always pretend Stereo mode is true by default. since opus will convert mono stream to stereo stream. // https://tools.ietf.org/html/rfc6716#section-2.1.2 bStereo = true; - oCodec = g.oCodec; + oCodec = g.oCodec; if (oCodec) { opusState = oCodec->opus_decoder_create(iSampleRate, bStereo ? 2 : 1, nullptr); - oCodec->opus_decoder_ctl(opusState, OPUS_SET_PHASE_INVERSION_DISABLED(1)); // Disable phase inversion for better mono downmix. + oCodec->opus_decoder_ctl( + opusState, OPUS_SET_PHASE_INVERSION_DISABLED(1)); // Disable phase inversion for better mono downmix. } #endif } else if (umtType == MessageHandler::UDPVoiceSpeex) { speex_bits_init(&sbBits); - dsSpeex = speex_decoder_init(speex_lib_get_mode(SPEEX_MODEID_UWB)); - int iArg=1; + dsSpeex = speex_decoder_init(speex_lib_get_mode(SPEEX_MODEID_UWB)); + int iArg = 1; speex_decoder_ctl(dsSpeex, SPEEX_SET_ENH, &iArg); speex_decoder_ctl(dsSpeex, SPEEX_GET_FRAME_SIZE, &iFrameSize); speex_decoder_ctl(dsSpeex, SPEEX_GET_SAMPLING_RATE, &iSampleRate); @@ -84,13 +87,15 @@ AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, Messag // For example, the maximum size of an opus packet can be 60ms, but the system's audio buffer size is typically // ~5ms on my laptop. // Whenever the system's audio callback is called, we have two choice: - // 1. Decode a new opus packet. Then we need a buffer to store unused samples (which don't fit in the system's buffer), + // 1. Decode a new opus packet. Then we need a buffer to store unused samples (which don't fit in the system's + // buffer), // 2. Use unused samples from the buffer (remaining from the last decoded frame). // How large should this buffer be? Consider the case in which remaining samples in the buffer can not fill // the system's audio buffer. In that case, we need to decode a new opus packet. In the worst case, the buffer size // needed is // 60ms of new decoded audio data + system's buffer size - 1. - iOutputSize = static_cast<unsigned int>(ceilf(static_cast<float>(iAudioBufferSize * iMixerFreq) / static_cast<float>(iSampleRate))); + iOutputSize = static_cast< unsigned int >( + ceilf(static_cast< float >(iAudioBufferSize * iMixerFreq) / static_cast< float >(iSampleRate))); iBufferSize = iOutputSize + systemMaxBufferSize; // -1 has been rounded up if (bStereo) { @@ -102,31 +107,31 @@ AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, Messag pfBuffer = new float[iBufferSize]; - srs = nullptr; + srs = nullptr; fResamplerBuffer = nullptr; if (iMixerFreq != iSampleRate) { - srs = speex_resampler_init(bStereo ? 2 : 1, iSampleRate, iMixerFreq, 3, &err); + srs = speex_resampler_init(bStereo ? 2 : 1, iSampleRate, iMixerFreq, 3, &err); fResamplerBuffer = new float[iAudioBufferSize]; } iBufferOffset = iBufferFilled = iLastConsume = 0; - bLastAlive = true; + bLastAlive = true; - iMissCount = 0; + iMissCount = 0; iMissedFrames = 0; ucFlags = SpeechFlags::Invalid; - jbJitter = jitter_buffer_init(iFrameSize); + jbJitter = jitter_buffer_init(iFrameSize); int margin = g.s.iJitterBufferSize * iFrameSize; jitter_buffer_ctl(jbJitter, JITTER_BUFFER_SET_MARGIN, &margin); - fFadeIn = new float[iFrameSizePerChannel]; + fFadeIn = new float[iFrameSizePerChannel]; fFadeOut = new float[iFrameSizePerChannel]; - float mul = static_cast<float>(M_PI / (2.0 * static_cast<double>(iFrameSizePerChannel))); - for (unsigned int i=0;i<iFrameSizePerChannel;++i) - fFadeIn[i] = fFadeOut[iFrameSizePerChannel-i-1] = sinf(static_cast<float>(i) * mul); + float mul = static_cast< float >(M_PI / (2.0 * static_cast< double >(iFrameSizePerChannel))); + for (unsigned int i = 0; i < iFrameSizePerChannel; ++i) + fFadeIn[i] = fFadeOut[iFrameSizePerChannel - i - 1] = sinf(static_cast< float >(i) * mul); } AudioOutputSpeech::~AudioOutputSpeech() { @@ -150,9 +155,9 @@ AudioOutputSpeech::~AudioOutputSpeech() { p->setTalking(Settings::Passive); } - delete [] fFadeIn; - delete [] fFadeOut; - delete [] fResamplerBuffer; + delete[] fFadeIn; + delete[] fFadeOut; + delete[] fResamplerBuffer; } void AudioOutputSpeech::addFrameToBuffer(const QByteArray &qbaPacket, unsigned int iSeq) { @@ -182,12 +187,13 @@ void AudioOutputSpeech::addFrameToBuffer(const QByteArray &qbaPacket, unsigned i return; } - const unsigned char *packet = reinterpret_cast<const unsigned char*>(qba.constData()); + const unsigned char *packet = reinterpret_cast< const unsigned char * >(qba.constData()); #ifdef USE_OPUS if (oCodec) { - samples = oCodec->opus_decoder_get_nb_samples(opusState, packet, size); // this function return samples per channel - samples *= 2; // since we assume all input stream is stereo. + samples = oCodec->opus_decoder_get_nb_samples(opusState, packet, + size); // this function return samples per channel + samples *= 2; // since we assume all input stream is stereo. } #else return; @@ -200,7 +206,7 @@ void AudioOutputSpeech::addFrameToBuffer(const QByteArray &qbaPacket, unsigned i unsigned int header = 0; do { - header = static_cast<unsigned char>(pds.next()); + header = static_cast< unsigned char >(pds.next()); samples += iFrameSize; pds.skip(header & 0x7f); } while ((header & 0x80) && pds.isValid()); @@ -208,9 +214,9 @@ void AudioOutputSpeech::addFrameToBuffer(const QByteArray &qbaPacket, unsigned i if (pds.isValid()) { JitterBufferPacket jbp; - jbp.data = const_cast<char *>(qbaPacket.constData()); - jbp.len = qbaPacket.size(); - jbp.span = samples; + jbp.data = const_cast< char * >(qbaPacket.constData()); + jbp.len = qbaPacket.size(); + jbp.span = samples; jbp.timestamp = iFrameSize * iSeq; jitter_buffer_put(jbJitter, &jbp); @@ -226,8 +232,8 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { // we can not control exactly how many frames decoder returns // so we need a buffer to keep unused frames // shift the buffer, remove decoded and played frames - for (unsigned int i=iLastConsume;i<iBufferFilled;++i) - pfBuffer[i-iLastConsume]=pfBuffer[i]; + for (unsigned int i = iLastConsume; i < iBufferFilled; ++i) + pfBuffer[i - iLastConsume] = pfBuffer[i]; iBufferFilled -= iLastConsume; @@ -248,7 +254,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { pOut = (srs) ? fResamplerBuffer : (pfBuffer + iBufferFilled); - if (! bLastAlive) { + if (!bLastAlive) { memset(pOut, 0, iFrameSize * sizeof(float)); } else { if (p == &LoopUser::lpLoopy) { @@ -256,7 +262,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { } int avail = 0; - int ts = jitter_buffer_get_pointer_timestamp(jbJitter); + int ts = jitter_buffer_get_pointer_timestamp(jbJitter); jitter_buffer_ctl(jbJitter, JITTER_BUFFER_GET_AVAILABLE_COUNT, &avail); if (p && (ts == 0)) { @@ -276,7 +282,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { char data[4096]; JitterBufferPacket jbp; jbp.data = data; - jbp.len = 4096; + jbp.len = 4096; spx_int32_t startofs = 0; @@ -285,7 +291,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { // pds structure is: flags + size (14-16 terminator + 1-15 size) + audio data + pos*3 iMissCount = 0; - ucFlags = static_cast<unsigned char>(pds.next()); + ucFlags = static_cast< unsigned char >(pds.next()); bHasTerminator = false; if (umtType == MessageHandler::UDPVoiceOpus) { @@ -299,7 +305,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { } else { unsigned int header = 0; do { - header = static_cast<unsigned int>(pds.next()); + header = static_cast< unsigned int >(pds.next()); if (header) qlFrames << pds.dataBlock(header & 0x7f); else @@ -316,14 +322,15 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { } if (p) { - float a = static_cast<float>(avail); + float a = static_cast< float >(avail); if (avail >= p->fAverageAvailable) p->fAverageAvailable = a; else p->fAverageAvailable *= 0.99f; } } else { - // Let the jitter buffer know it's the right time to adjust the buffering delay to the network conditions. + // Let the jitter buffer know it's the right time to adjust the buffering delay to the network + // conditions. jitter_buffer_update_delay(jbJitter, &jbp, nullptr); iMissCount++; @@ -332,13 +339,13 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { } } - if (! qlFrames.isEmpty()) { + if (!qlFrames.isEmpty()) { QByteArray qba = qlFrames.takeFirst(); if (umtType == MessageHandler::UDPVoiceCELTAlpha || umtType == MessageHandler::UDPVoiceCELTBeta) { int wantversion = (umtType == MessageHandler::UDPVoiceCELTAlpha) ? g.iCodecAlpha : g.iCodecBeta; - if ((p == &LoopUser::lpLoopy) && (! g.qmCodecs.isEmpty())) { - QMap<int, CELTCodec *>::const_iterator i = g.qmCodecs.constEnd(); + if ((p == &LoopUser::lpLoopy) && (!g.qmCodecs.isEmpty())) { + QMap< int, CELTCodec * >::const_iterator i = g.qmCodecs.constEnd(); --i; wantversion = i.key(); } @@ -346,14 +353,17 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { cCodec->celt_decoder_destroy(cdDecoder); cdDecoder = nullptr; } - if (! cCodec) { + if (!cCodec) { cCodec = g.qmCodecs.value(wantversion); if (cCodec) { cdDecoder = cCodec->decoderCreate(); } } if (cdDecoder) - cCodec->decode_float(cdDecoder, qba.isEmpty() ? nullptr : reinterpret_cast<const unsigned char *>(qba.constData()), qba.size(), pOut); + cCodec->decode_float(cdDecoder, + qba.isEmpty() ? nullptr + : reinterpret_cast< const unsigned char * >(qba.constData()), + qba.size(), pOut); else memset(pOut, 0, sizeof(float) * iFrameSize); } else if (umtType == MessageHandler::UDPVoiceOpus) { @@ -363,21 +373,16 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { // If qba is empty, we have to let Opus know about the packet loss // Otherwise if the associated user is not locally muted, we want to decode the audio packet // normally in order to be able to play it. - decodedSamples = oCodec->opus_decode_float(opusState, - qba.isEmpty() ? - nullptr : - reinterpret_cast<const unsigned char *>(qba.constData()), - qba.size(), - pOut, - iAudioBufferSize, - 0); + decodedSamples = oCodec->opus_decode_float( + opusState, + qba.isEmpty() ? nullptr : reinterpret_cast< const unsigned char * >(qba.constData()), + qba.size(), pOut, iAudioBufferSize, 0); } else { // If the packet is non-empty, but the associated user is locally muted, // we don't have to decode the packet. Instead it is enough to know how many // samples it contained so that we can then mute the appropriate output length decodedSamples = oCodec->opus_packet_get_samples_per_frame( - reinterpret_cast<const unsigned char *>(qba.constData()), - SAMPLE_RATE); + reinterpret_cast< const unsigned char * >(qba.constData()), SAMPLE_RATE); } // The returned sample count we get from the Opus functions refer to samples per channel. @@ -397,10 +402,11 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { speex_bits_read_from(&sbBits, qba.data(), qba.size()); speex_decode(dsSpeex, &sbBits, pOut); } - for (unsigned int i=0;i<iFrameSize;++i) + for (unsigned int i = 0; i < iFrameSize; ++i) pOut[i] *= (1.0f / 32767.f); } else { - qWarning("AudioOutputSpeech: encountered unknown message type %li in prepareSampleBuffer().", static_cast<long>(umtType)); + qWarning("AudioOutputSpeech: encountered unknown message type %li in prepareSampleBuffer().", + static_cast< long >(umtType)); } bool update = true; @@ -411,7 +417,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { float pow = 0.0f; for (int i = 0; i < decodedSamples; ++i) pow += pOut[i] * pOut[i]; - pow = sqrtf(pow / static_cast<float>(decodedSamples)); // Average over both L and R channel. + pow = sqrtf(pow / static_cast< float >(decodedSamples)); // Average over both L and R channel. if (pow >= fPowerMax) { fPowerMax = pow; @@ -453,20 +459,20 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { #endif } else { speex_decode(dsSpeex, nullptr, pOut); - for (unsigned int i=0;i<iFrameSize;++i) + for (unsigned int i = 0; i < iFrameSize; ++i) pOut[i] *= (1.0f / 32767.f); } } - if (! nextalive) { - for (unsigned int i=0; i<static_cast<unsigned int>(iFrameSizePerChannel); ++i) { - for (unsigned int s=0; s<channels; ++s) - pOut[i*channels + s] *= fFadeOut[i]; + if (!nextalive) { + for (unsigned int i = 0; i < static_cast< unsigned int >(iFrameSizePerChannel); ++i) { + for (unsigned int s = 0; s < channels; ++s) + pOut[i * channels + s] *= fFadeOut[i]; } } else if (ts == 0) { - for (unsigned int i=0; i<static_cast<unsigned int>(iFrameSizePerChannel); ++i) { - for (unsigned int s=0; s<channels; ++s) - pOut[i*channels + s] *= fFadeIn[i]; + for (unsigned int i = 0; i < static_cast< unsigned int >(iFrameSizePerChannel); ++i) { + for (unsigned int s = 0; s < channels; ++s) + pOut[i * channels + s] *= fFadeIn[i]; } } @@ -474,7 +480,7 @@ bool AudioOutputSpeech::prepareSampleBuffer(unsigned int frameCount) { jitter_buffer_tick(jbJitter); } } -nextframe: + nextframe: if (p && p->bLocalMute) { // Overwrite the output with zeros as this user is muted // NOTE: If Opus is used, then in this case no samples have actually been decoded and thus @@ -483,13 +489,15 @@ nextframe: memset(pOut, 0, decodedSamples * sizeof(float)); } - spx_uint32_t inlen = decodedSamples / channels; // per channel - spx_uint32_t outlen = static_cast<unsigned int>(ceilf(static_cast<float>(decodedSamples / channels * iMixerFreq) / static_cast<float>(iSampleRate))); + spx_uint32_t inlen = decodedSamples / channels; // per channel + spx_uint32_t outlen = static_cast< unsigned int >( + ceilf(static_cast< float >(decodedSamples / channels * iMixerFreq) / static_cast< float >(iSampleRate))); if (srs && bLastAlive) { if (channels == 1) { speex_resampler_process_float(srs, 0, fResamplerBuffer, &inlen, pfBuffer + iBufferFilled, &outlen); } else if (channels == 2) { - speex_resampler_process_interleaved_float(srs, fResamplerBuffer, &inlen, pfBuffer + iBufferFilled, &outlen); + speex_resampler_process_interleaved_float(srs, fResamplerBuffer, &inlen, pfBuffer + iBufferFilled, + &outlen); } } iBufferFilled += outlen * channels; @@ -497,7 +505,7 @@ nextframe: if (p) { Settings::TalkState ts; - if (! nextalive) + if (!nextalive) ucFlags = SpeechFlags::Invalid; switch (ucFlags) { case SpeechFlags::Listen: @@ -523,7 +531,7 @@ nextframe: p->setTalking(ts); } - bool tmp = bLastAlive; + bool tmp = bLastAlive; bLastAlive = nextalive; return tmp; } diff --git a/src/mumble/AudioOutputSpeech.h b/src/mumble/AudioOutputSpeech.h index c54fc44f7..bf3b4489f 100644 --- a/src/mumble/AudioOutputSpeech.h +++ b/src/mumble/AudioOutputSpeech.h @@ -6,10 +6,10 @@ #ifndef MUMBLE_MUMBLE_AUDIOOUTPUTSPEECH_H_ #define MUMBLE_MUMBLE_AUDIOOUTPUTSPEECH_H_ +#include <celt.h> #include <speex/speex.h> -#include <speex/speex_resampler.h> #include <speex/speex_jitter.h> -#include <celt.h> +#include <speex/speex_resampler.h> #include <QtCore/QMutex> @@ -22,58 +22,60 @@ class ClientUser; struct OpusDecoder; class AudioOutputSpeech : public AudioOutputUser { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioOutputSpeech) - protected: - unsigned int iAudioBufferSize; - unsigned int iBufferOffset; - unsigned int iBufferFilled; - unsigned int iOutputSize; - unsigned int iLastConsume; - unsigned int iFrameSize; - unsigned int iFrameSizePerChannel; - unsigned int iSampleRate; - unsigned int iMixerFreq; - bool bLastAlive; - bool bHasTerminator; - - float *fFadeIn; - float *fFadeOut; - float *fResamplerBuffer; - - SpeexResamplerState *srs; - - QMutex qmJitter; - JitterBuffer *jbJitter; - int iMissCount; - - CELTCodec *cCodec; - CELTDecoder *cdDecoder; - - OpusCodec *oCodec; - OpusDecoder *opusState; - - SpeexBits sbBits; - void *dsSpeex; - - QList<QByteArray> qlFrames; - public: - unsigned char ucFlags; - MessageHandler::UDPMessageType umtType; - int iMissedFrames; - ClientUser *p; - - /// Fetch and decode frames from the jitter buffer. Called in mix(). - /// - /// @param frameCount Number of frames to decode. frame means a bundle of one sample from each channel. - virtual bool prepareSampleBuffer(unsigned int frameCount) Q_DECL_OVERRIDE; - - void addFrameToBuffer(const QByteArray &, unsigned int iBaseSeq); - - /// @param systemMaxBufferSize maximum number of samples the system audio play back may request each time - AudioOutputSpeech(ClientUser *, unsigned int freq, MessageHandler::UDPMessageType type, unsigned int systemMaxBufferSize); - ~AudioOutputSpeech() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(AudioOutputSpeech) +protected: + unsigned int iAudioBufferSize; + unsigned int iBufferOffset; + unsigned int iBufferFilled; + unsigned int iOutputSize; + unsigned int iLastConsume; + unsigned int iFrameSize; + unsigned int iFrameSizePerChannel; + unsigned int iSampleRate; + unsigned int iMixerFreq; + bool bLastAlive; + bool bHasTerminator; + + float *fFadeIn; + float *fFadeOut; + float *fResamplerBuffer; + + SpeexResamplerState *srs; + + QMutex qmJitter; + JitterBuffer *jbJitter; + int iMissCount; + + CELTCodec *cCodec; + CELTDecoder *cdDecoder; + + OpusCodec *oCodec; + OpusDecoder *opusState; + + SpeexBits sbBits; + void *dsSpeex; + + QList< QByteArray > qlFrames; + +public: + unsigned char ucFlags; + MessageHandler::UDPMessageType umtType; + int iMissedFrames; + ClientUser *p; + + /// Fetch and decode frames from the jitter buffer. Called in mix(). + /// + /// @param frameCount Number of frames to decode. frame means a bundle of one sample from each channel. + virtual bool prepareSampleBuffer(unsigned int frameCount) Q_DECL_OVERRIDE; + + void addFrameToBuffer(const QByteArray &, unsigned int iBaseSeq); + + /// @param systemMaxBufferSize maximum number of samples the system audio play back may request each time + AudioOutputSpeech(ClientUser *, unsigned int freq, MessageHandler::UDPMessageType type, + unsigned int systemMaxBufferSize); + ~AudioOutputSpeech() Q_DECL_OVERRIDE; }; -#endif // AUDIOOUTPUTSPEECH_H_ +#endif // AUDIOOUTPUTSPEECH_H_ diff --git a/src/mumble/AudioOutputUser.cpp b/src/mumble/AudioOutputUser.cpp index ea6b7094c..071ce7169 100644 --- a/src/mumble/AudioOutputUser.cpp +++ b/src/mumble/AudioOutputUser.cpp @@ -5,12 +5,12 @@ #include "AudioOutputUser.h" -AudioOutputUser::AudioOutputUser(const QString& name) : qsName(name) { +AudioOutputUser::AudioOutputUser(const QString &name) : qsName(name) { } AudioOutputUser::~AudioOutputUser() { - delete [] pfBuffer; - delete [] pfVolume; + delete[] pfBuffer; + delete[] pfVolume; } void AudioOutputUser::resizeBuffer(unsigned int newsize) { @@ -18,9 +18,9 @@ void AudioOutputUser::resizeBuffer(unsigned int newsize) { float *n = new float[newsize]; if (pfBuffer) { memcpy(n, pfBuffer, sizeof(float) * iBufferSize); - delete [] pfBuffer; + delete[] pfBuffer; } - pfBuffer = n; + pfBuffer = n; iBufferSize = newsize; } } diff --git a/src/mumble/AudioOutputUser.h b/src/mumble/AudioOutputUser.h index 696e4c8d4..e93472330 100644 --- a/src/mumble/AudioOutputUser.h +++ b/src/mumble/AudioOutputUser.h @@ -9,27 +9,28 @@ #include <QtCore/QObject> class AudioOutputUser : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioOutputUser) - protected: - unsigned int iBufferSize; +private: + Q_OBJECT + Q_DISABLE_COPY(AudioOutputUser) +protected: + unsigned int iBufferSize; - /// Used to resize the buffer. - /// WARNING: - /// Audio callback is a dedicated place that can be executed - /// in a special thread or interrupt handler. Allocating - /// memory will probably crash the program! - void resizeBuffer(unsigned int newsize); - public: - AudioOutputUser(const QString& name); - ~AudioOutputUser() Q_DECL_OVERRIDE; - const QString qsName; - float *pfBuffer = nullptr; - float *pfVolume = nullptr; - float fPos[3] = {0.0, 0.0, 0.0}; - bool bStereo; - virtual bool prepareSampleBuffer(unsigned int snum) = 0; + /// Used to resize the buffer. + /// WARNING: + /// Audio callback is a dedicated place that can be executed + /// in a special thread or interrupt handler. Allocating + /// memory will probably crash the program! + void resizeBuffer(unsigned int newsize); + +public: + AudioOutputUser(const QString &name); + ~AudioOutputUser() Q_DECL_OVERRIDE; + const QString qsName; + float *pfBuffer = nullptr; + float *pfVolume = nullptr; + float fPos[3] = { 0.0, 0.0, 0.0 }; + bool bStereo; + virtual bool prepareSampleBuffer(unsigned int snum) = 0; }; -#endif // AUDIOOUTPUTUSER_H_ +#endif // AUDIOOUTPUTUSER_H_ diff --git a/src/mumble/AudioStats.cpp b/src/mumble/AudioStats.cpp index b6542003c..c2642455d 100644 --- a/src/mumble/AudioStats.cpp +++ b/src/mumble/AudioStats.cpp @@ -6,29 +6,29 @@ #include "AudioStats.h" #include "AudioInput.h" -#include "Global.h" #include "Utils.h" #include "smallft.h" +#include "Global.h" #include <QtGui/QPainter> #include <cmath> AudioBar::AudioBar(QWidget *p) : QWidget(p) { - qcBelow = Qt::yellow; - qcAbove = Qt::red; + qcBelow = Qt::yellow; + qcAbove = Qt::red; qcInside = Qt::green; - iMin = 0; - iMax = 32768; + iMin = 0; + iMax = 32768; iBelow = 2000; iAbove = 22000; iValue = 1000; - iPeak = -1; - setMinimumSize(100,20); + iPeak = -1; + setMinimumSize(100, 20); - qlReplacableColors << Qt::yellow << Qt::red << Qt::green << Qt::blue; - qlReplacementBrushes << Qt::BDiagPattern << Qt::DiagCrossPattern << Qt::NoBrush << Qt::FDiagPattern; + qlReplacableColors << Qt::yellow << Qt::red << Qt::green << Qt::blue; + qlReplacementBrushes << Qt::BDiagPattern << Qt::DiagCrossPattern << Qt::NoBrush << Qt::FDiagPattern; } void AudioBar::paintEvent(QPaintEvent *) { @@ -52,23 +52,26 @@ void AudioBar::paintEvent(QPaintEvent *) { else if (iValue > iMax) iValue = iMax; - float scale = static_cast<float>(width()) / static_cast<float>(iMax - iMin); - int h = height(); + float scale = static_cast< float >(width()) / static_cast< float >(iMax - iMin); + int h = height(); - int val = iroundf(static_cast<float>(iValue) * scale + 0.5f); - int below = iroundf(static_cast<float>(iBelow) * scale + 0.5f); - int above = iroundf(static_cast<float>(iAbove) * scale + 0.5f); - int max = iroundf(static_cast<float>(iMax) * scale + 0.5f); - int min = iroundf(static_cast<float>(iMin) * scale + 0.5f); - int peak = iroundf(static_cast<float>(iPeak) * scale + 0.5f); + int val = iroundf(static_cast< float >(iValue) * scale + 0.5f); + int below = iroundf(static_cast< float >(iBelow) * scale + 0.5f); + int above = iroundf(static_cast< float >(iAbove) * scale + 0.5f); + int max = iroundf(static_cast< float >(iMax) * scale + 0.5f); + int min = iroundf(static_cast< float >(iMin) * scale + 0.5f); + int peak = iroundf(static_cast< float >(iPeak) * scale + 0.5f); if (g.s.bHighContrast) { // Draw monochrome representation QColor fg = QPalette().windowText().color(); - p.fillRect(0, 0, below, h, QBrush(fg, qlReplacementBrushes.value(qlReplacableColors.indexOf(qcBelow), Qt::CrossPattern))); - p.fillRect(below, 0, above - below, h, QBrush(fg, qlReplacementBrushes.value(qlReplacableColors.indexOf(qcInside), Qt::NoBrush))); - p.fillRect(above, 0, max - above, h, QBrush(fg, qlReplacementBrushes.value(qlReplacableColors.indexOf(qcAbove), Qt::CrossPattern))); + p.fillRect(0, 0, below, h, + QBrush(fg, qlReplacementBrushes.value(qlReplacableColors.indexOf(qcBelow), Qt::CrossPattern))); + p.fillRect(below, 0, above - below, h, + QBrush(fg, qlReplacementBrushes.value(qlReplacableColors.indexOf(qcInside), Qt::NoBrush))); + p.fillRect(above, 0, max - above, h, + QBrush(fg, qlReplacementBrushes.value(qlReplacableColors.indexOf(qcAbove), Qt::CrossPattern))); p.fillRect(0, 0, val, h, QBrush(fg, Qt::SolidPattern)); p.drawRect(0, 0, max - 1, h - 1); @@ -77,22 +80,22 @@ void AudioBar::paintEvent(QPaintEvent *) { } else { if (val <= below) { p.fillRect(0, 0, val, h, qcBelow); - p.fillRect(val, 0, below-val, h, qcBelow.darker(300)); - p.fillRect(below, 0, above-below, h, qcInside.darker(300)); - p.fillRect(above, 0, max-above, h, qcAbove.darker(300)); + p.fillRect(val, 0, below - val, h, qcBelow.darker(300)); + p.fillRect(below, 0, above - below, h, qcInside.darker(300)); + p.fillRect(above, 0, max - above, h, qcAbove.darker(300)); } else if (val <= above) { p.fillRect(0, 0, below, h, qcBelow); - p.fillRect(below, 0, val-below, h, qcInside); - p.fillRect(val, 0, above-val, h, qcInside.darker(300)); - p.fillRect(above, 0, max-above, h, qcAbove.darker(300)); + p.fillRect(below, 0, val - below, h, qcInside); + p.fillRect(val, 0, above - val, h, qcInside.darker(300)); + p.fillRect(above, 0, max - above, h, qcAbove.darker(300)); } else { p.fillRect(0, 0, below, h, qcBelow); - p.fillRect(below, 0, above-below, h, qcInside); - p.fillRect(above, 0, val-above, h, qcAbove); - p.fillRect(val, 0, max-val, h, qcAbove.darker(300)); + p.fillRect(below, 0, above - below, h, qcInside); + p.fillRect(above, 0, val - above, h, qcAbove); + p.fillRect(val, 0, max - val, h, qcAbove.darker(300)); } - if ((peak >= min) && (peak <= max)) { + if ((peak >= min) && (peak <= max)) { if (peak <= below) p.setPen(qcBelow.lighter(150)); else if (peak <= above) @@ -102,7 +105,6 @@ void AudioBar::paintEvent(QPaintEvent *) { p.drawLine(peak, 0, peak, h); } } - } AudioEchoWidget::AudioEchoWidget(QWidget *p) : QWidget(p) { @@ -111,13 +113,13 @@ AudioEchoWidget::AudioEchoWidget(QWidget *p) : QWidget(p) { static inline const QColor mapEchoToColor(float echo) { bool neg = (echo < 0.0f); - echo = fabsf(echo); + echo = fabsf(echo); float a, b, c; if (echo > 1.0f) { echo = 1.0f; - c = 0.5f; + c = 0.5f; } else { c = 0.0f; } @@ -136,7 +138,7 @@ static inline const QColor mapEchoToColor(float echo) { return QColor::fromRgbF(c, b, a); } -#define WGT(x,y) st->W[(y)*N + 2*(x)+1] +#define WGT(x, y) st->W[(y) *N + 2 * (x) + 1] void AudioEchoWidget::paintEvent(QPaintEvent *) { QPainter paint(this); @@ -145,7 +147,7 @@ void AudioEchoWidget::paintEvent(QPaintEvent *) { paint.fillRect(rect(), Qt::black); AudioInputPtr ai = g.ai; - if (! ai || ! ai->sesEcho) + if (!ai || !ai->sesEcho) return; ai->qmSpeex.lock(); @@ -167,43 +169,44 @@ void AudioEchoWidget::paintEvent(QPaintEvent *) { drft_lookup d; mumble_drft_init(&d, n); - for (int j=0;j<M;j++) { - for (int i=0;i<n;i++) - W[j*n+i] = static_cast<float>(w[j*n+i]) / static_cast<float>(n); - mumble_drft_forward(&d, & W[j*n]); + for (int j = 0; j < M; j++) { + for (int i = 0; i < n; i++) + W[j * n + i] = static_cast< float >(w[j * n + i]) / static_cast< float >(n); + mumble_drft_forward(&d, &W[j * n]); } mumble_drft_clear(&d); - float xscale = 1.0f / static_cast<float>(N); - float yscale = 1.0f / static_cast<float>(M); + float xscale = 1.0f / static_cast< float >(N); + float yscale = 1.0f / static_cast< float >(M); for (int j = 0; j < M; j++) { - for (int i=1;i < N; i++) { - float xa = static_cast<float>(i) * xscale; - float ya = static_cast<float>(j) * yscale; + for (int i = 1; i < N; i++) { + float xa = static_cast< float >(i) * xscale; + float ya = static_cast< float >(j) * yscale; float xb = xa + xscale; float yb = ya + yscale; - const QColor &c = mapEchoToColor(sqrtf(W[j*n+2*i]*W[j*n+2*i]+W[j*n+2*i-1]*W[j*n+2*i-1]) / 65536.f); + const QColor &c = mapEchoToColor( + sqrtf(W[j * n + 2 * i] * W[j * n + 2 * i] + W[j * n + 2 * i - 1] * W[j * n + 2 * i - 1]) / 65536.f); paint.fillRect(QRectF(QPointF(xa, ya), QPointF(xb, yb)), c); } } QPolygonF poly; - xscale = 1.0f / (2.0f * static_cast<float>(n)); + xscale = 1.0f / (2.0f * static_cast< float >(n)); yscale = 1.0f / (200.0f * 32767.0f); for (int i = 0; i < 2 * n; i++) { - poly << QPointF(static_cast<float>(i) * xscale, 0.5f + static_cast<float>(w[i]) * yscale); + poly << QPointF(static_cast< float >(i) * xscale, 0.5f + static_cast< float >(w[i]) * yscale); } - + paint.setPen(QPen(QBrush(QColor::fromRgbF(1.0f, 0.0f, 1.0f)), 0)); paint.drawPolyline(poly); } AudioNoiseWidget::AudioNoiseWidget(QWidget *p) : QWidget(p) { - setMinimumSize(100,60); + setMinimumSize(100, 60); } void AudioNoiseWidget::paintEvent(QPaintEvent *) { @@ -213,7 +216,7 @@ void AudioNoiseWidget::paintEvent(QPaintEvent *) { paint.fillRect(rect(), pal.color(QPalette::Window)); AudioInputPtr ai = g.ai; - if (!ai.get() || ! ai->sppPreprocess) + if (!ai.get() || !ai->sppPreprocess) return; QPolygonF poly; @@ -233,17 +236,17 @@ void AudioNoiseWidget::paintEvent(QPaintEvent *) { qreal sx, sy; - sx = (static_cast<float>(width()) - 1.0f) / static_cast<float>(ps_size); - sy = static_cast<float>(height()) - 1.0f; + sx = (static_cast< float >(width()) - 1.0f) / static_cast< float >(ps_size); + sy = static_cast< float >(height()) - 1.0f; poly << QPointF(0.0f, height() - 1); float fftmul = 1.0 / (32768.0); - for (int i=0; i < ps_size; i++) { + for (int i = 0; i < ps_size; i++) { qreal xp, yp; xp = i * sx; - yp = sqrtf(sqrtf(static_cast<float>(noise[i]))) - 1.0f; + yp = sqrtf(sqrtf(static_cast< float >(noise[i]))) - 1.0f; yp = yp * fftmul; - yp = qMin<qreal>(yp * 3000.0f, 1.0f); + yp = qMin< qreal >(yp * 3000.0f, 1.0f); yp = (1 - yp) * sy; poly << QPointF(xp, yp); } @@ -257,10 +260,10 @@ void AudioNoiseWidget::paintEvent(QPaintEvent *) { poly.clear(); - for (int i=0;i < ps_size; i++) { + for (int i = 0; i < ps_size; i++) { qreal xp, yp; xp = i * sx; - yp = sqrtf(sqrtf(static_cast<float>(ps[i]))) - 1.0f; + yp = sqrtf(sqrtf(static_cast< float >(ps[i]))) - 1.0f; yp = yp * fftmul; yp = qMin(yp * 3000.0, 1.0); yp = (1 - yp) * sy; @@ -283,22 +286,22 @@ AudioStats::AudioStats(QWidget *p) : QDialog(p) { abSpeech->setAccessibleName(tr("Current speech detection chance")); anwNoise->setAccessibleName(tr("Power spectrum of input signal and noise estimate")); aewEcho->setAccessibleName(tr("Weights of the echo canceller")); - + AudioInputPtr ai = g.ai; if (ai && ai->sesEcho) { qgbEcho->setVisible(true); - } else { + } else { qgbEcho->setVisible(false); } bTalking = false; - abSpeech->iPeak = -1; - abSpeech->qcBelow = Qt::red; + abSpeech->iPeak = -1; + abSpeech->qcBelow = Qt::red; abSpeech->qcInside = Qt::yellow; - abSpeech->qcAbove = Qt::green; + abSpeech->qcAbove = Qt::green; on_Tick_timeout(); } @@ -307,15 +310,15 @@ AudioStats::~AudioStats() { } #if QT_VERSION >= 0x050500 - #define FORMAT_TO_TXT(format, arg) txt = QString::asprintf(format, arg) +# define FORMAT_TO_TXT(format, arg) txt = QString::asprintf(format, arg) #else - // sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() - #define FORMAT_TO_TXT(format, arg) txt.sprintf(format, arg) +// sprintf() has been deprecated in Qt 5.5 in favor for the static QString::asprintf() +# define FORMAT_TO_TXT(format, arg) txt.sprintf(format, arg) #endif void AudioStats::on_Tick_timeout() { AudioInputPtr ai = g.ai; - if (!ai.get() || ! ai->sppPreprocess) + if (!ai.get() || !ai->sppPreprocess) return; bool nTalking = ai->isTransmitting(); @@ -344,31 +347,31 @@ void AudioStats::on_Tick_timeout() { float n = 0.0001f; int start = (ps_size * 300) / SAMPLE_RATE; - int stop = (ps_size * 2000) / SAMPLE_RATE; + int stop = (ps_size * 2000) / SAMPLE_RATE; - for (int i=start;i<stop;i++) { - s += sqrtf(static_cast<float>(ps[i])); - n += sqrtf(static_cast<float>(noise[i])); + for (int i = start; i < stop; i++) { + s += sqrtf(static_cast< float >(ps[i])); + n += sqrtf(static_cast< float >(noise[i])); } - FORMAT_TO_TXT("%06.3f",s / n); + FORMAT_TO_TXT("%06.3f", s / n); qlMicSNR->setText(txt); spx_int32_t v; speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_AGC_GAIN, &v); - float fv = powf(10.0f, (static_cast<float>(v) / 20.0f)); - FORMAT_TO_TXT("%03.0f%%",100.0f / fv); + float fv = powf(10.0f, (static_cast< float >(v) / 20.0f)); + FORMAT_TO_TXT("%03.0f%%", 100.0f / fv); qlMicVolume->setText(txt); - FORMAT_TO_TXT("%03.0f%%",ai->fSpeechProb * 100.0f); + FORMAT_TO_TXT("%03.0f%%", ai->fSpeechProb * 100.0f); qlSpeechProb->setText(txt); - FORMAT_TO_TXT("%04.1f kbit/s",static_cast<float>(ai->iBitrate) / 1000.0f); + FORMAT_TO_TXT("%04.1f kbit/s", static_cast< float >(ai->iBitrate) / 1000.0f); qlBitrate->setText(txt); if (nTalking != bTalking) { bTalking = nTalking; - QFont f = qlSpeechProb->font(); + QFont f = qlSpeechProb->font(); f.setBold(bTalking); qlSpeechProb->setFont(f); } @@ -376,14 +379,14 @@ void AudioStats::on_Tick_timeout() { if (g.uiDoublePush > 1000000) txt = tr(">1000 ms"); else - FORMAT_TO_TXT("%04llu ms",g.uiDoublePush / 1000); + FORMAT_TO_TXT("%04llu ms", g.uiDoublePush / 1000); qlDoublePush->setText(txt); abSpeech->iBelow = iroundf(g.s.fVADmin * 32767.0f + 0.5f); abSpeech->iAbove = iroundf(g.s.fVADmax * 32767.0f + 0.5f); if (g.s.vsVAD == Settings::Amplitude) { - abSpeech->iValue = iroundf((32767.f/96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); + abSpeech->iValue = iroundf((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); } else { abSpeech->iValue = iroundf(ai->fSpeechProb * 32767.0f + 0.5f); } diff --git a/src/mumble/AudioStats.h b/src/mumble/AudioStats.h index 16409a1a3..5df5ae438 100644 --- a/src/mumble/AudioStats.h +++ b/src/mumble/AudioStats.h @@ -4,64 +4,66 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef MUMBLE_MUMBLE_AUDIOSTATS_H_ -#define MUMBLE_MUMBLE_AUDIOSTATS_H_ +# define MUMBLE_MUMBLE_AUDIOSTATS_H_ -#include <QtCore/QtGlobal> -#include <QtCore/QList> -#include <QtCore/QTimer> -#include <QtWidgets/QWidget> +# include <QtCore/QList> +# include <QtCore/QTimer> +# include <QtCore/QtGlobal> +# include <QtWidgets/QWidget> class AudioBar : public QWidget { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioBar) - protected: - void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; - public: - AudioBar(QWidget *parent = nullptr); - int iMin, iMax; - int iBelow, iAbove; - int iValue, iPeak; - QColor qcBelow, qcInside, qcAbove; +private: + Q_OBJECT + Q_DISABLE_COPY(AudioBar) +protected: + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; - QList<QColor> qlReplacableColors; - QList<Qt::BrushStyle> qlReplacementBrushes; +public: + AudioBar(QWidget *parent = nullptr); + int iMin, iMax; + int iBelow, iAbove; + int iValue, iPeak; + QColor qcBelow, qcInside, qcAbove; + + QList< QColor > qlReplacableColors; + QList< Qt::BrushStyle > qlReplacementBrushes; }; class AudioEchoWidget : public QWidget { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioEchoWidget) - public: - AudioEchoWidget(QWidget *parent); - protected slots: - void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(AudioEchoWidget) +public: + AudioEchoWidget(QWidget *parent); +protected slots: + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; }; class AudioNoiseWidget : public QWidget { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioNoiseWidget) - public: - AudioNoiseWidget(QWidget *parent); - protected slots: - void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(AudioNoiseWidget) +public: + AudioNoiseWidget(QWidget *parent); +protected slots: + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; }; -#include "ui_AudioStats.h" +# include "ui_AudioStats.h" class AudioStats : public QDialog, public Ui::AudioStats { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioStats) - protected: - QTimer *qtTick; - bool bTalking; - public: - AudioStats(QWidget *parent); - ~AudioStats() Q_DECL_OVERRIDE; - public slots: - void on_Tick_timeout(); +private: + Q_OBJECT + Q_DISABLE_COPY(AudioStats) +protected: + QTimer *qtTick; + bool bTalking; + +public: + AudioStats(QWidget *parent); + ~AudioStats() Q_DECL_OVERRIDE; +public slots: + void on_Tick_timeout(); }; #else diff --git a/src/mumble/AudioWizard.cpp b/src/mumble/AudioWizard.cpp index ac663f23c..3c82bc54c 100644 --- a/src/mumble/AudioWizard.cpp +++ b/src/mumble/AudioWizard.cpp @@ -16,7 +16,8 @@ #include <cmath> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" CompletablePage::CompletablePage(QWizard *p) : QWizardPage(p) { @@ -33,8 +34,8 @@ bool CompletablePage::isComplete() const { } AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { - bInit = true; - bLastActive = false; + bInit = true; + bLastActive = false; g.bInAudioWizard = true; g.mw->onChangeMute(); @@ -57,13 +58,13 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { // Device if (AudioInputRegistrar::qmNew) { - foreach(AudioInputRegistrar *air, *AudioInputRegistrar::qmNew) { + foreach (AudioInputRegistrar *air, *AudioInputRegistrar::qmNew) { qcbInput->addItem(air->name); if (air->name == AudioInputRegistrar::current) { qcbInput->setCurrentIndex(qcbInput->count() - 1); qcbEcho->setEnabled(air->canEcho(qcbOutput->currentText())); } - QList<audioDevice> ql= air->getDeviceChoices(); + QList< audioDevice > ql = air->getDeviceChoices(); } } if (qcbInput->count() < 2) { @@ -73,14 +74,14 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { qcbEcho->setChecked(g.s.bEcho); if (AudioOutputRegistrar::qmNew) { - foreach(AudioOutputRegistrar *aor, *AudioOutputRegistrar::qmNew) { + foreach (AudioOutputRegistrar *aor, *AudioOutputRegistrar::qmNew) { qcbOutput->addItem(aor->name); if (aor->name == AudioOutputRegistrar::current) { qcbOutput->setCurrentIndex(qcbOutput->count() - 1); bDelay = aor->usesOutputDelay(); qcbAttenuateOthers->setEnabled(aor->canMuteOthers()); } - QList<audioDevice> ql= aor->getDeviceChoices(); + QList< audioDevice > ql = aor->getDeviceChoices(); } } @@ -106,7 +107,7 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { qrbQualityCustom->setChecked(true); quint32 iMessage = Settings::LogNone; - for (int i = Log::firstMsgType;i <= Log::lastMsgType; ++i) { + for (int i = Log::firstMsgType; i <= Log::lastMsgType; ++i) { iMessage |= (g.s.qmMessages[i] & (Settings::LogSoundfile | Settings::LogTTS)); } @@ -135,12 +136,12 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { on_qcbInput_activated(qcbInput->currentIndex()); on_qcbOutput_activated(qcbOutput->currentIndex()); - abAmplify->qcBelow = Qt::blue; + abAmplify->qcBelow = Qt::blue; abAmplify->qcInside = Qt::green; - abAmplify->qcAbove = Qt::red; + abAmplify->qcAbove = Qt::red; // Trigger - foreach(const Shortcut &s, g.s.qlShortcuts) { + foreach (const Shortcut &s, g.s.qlShortcuts) { if (s.iIndex == g.mw->gsPushTalk->idx) { skwPTT->setShortcut(s.qlButtons); break; @@ -154,9 +155,9 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { else qrSNR->setChecked(true); - abVAD->qcBelow = Qt::red; + abVAD->qcBelow = Qt::red; abVAD->qcInside = Qt::yellow; - abVAD->qcAbove = Qt::green; + abVAD->qcAbove = Qt::green; qsVAD->setValue(iroundf(g.s.fVADmax * 32767.f + 0.5f)); @@ -164,8 +165,8 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { qcbHeadphone->setChecked(g.s.bPositionalHeadphone); fAngle = 0.0f; - fX = fY = 0.0f; - qgsScene = nullptr; + fX = fY = 0.0f; + qgsScene = nullptr; qgiSource = nullptr; aosSource = nullptr; qgvView->scale(1.0f, -1.0f); @@ -184,20 +185,20 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { resize(700, 500); updateTriggerWidgets(qrPTT->isChecked()); - sOldSettings = g.s; - g.s.lmLoopMode = Settings::Local; - g.s.dPacketLoss = 0.0; + sOldSettings = g.s; + g.s.lmLoopMode = Settings::Local; + g.s.dPacketLoss = 0.0; g.s.dMaxPacketDelay = 0.0; - g.s.bMute = true; - g.s.bDeaf = false; + g.s.bMute = true; + g.s.bDeaf = false; bTransmitChanged = false; iMaxPeak = 0; - iTicks = 0; + iTicks = 0; - qpTalkingOn = QPixmap::fromImage(QImage(QLatin1String("skin:talking_on.svg")).scaled(64,64)); - qpTalkingOff = QPixmap::fromImage(QImage(QLatin1String("skin:talking_off.svg")).scaled(64,64)); + qpTalkingOn = QPixmap::fromImage(QImage(QLatin1String("skin:talking_on.svg")).scaled(64, 64)); + qpTalkingOff = QPixmap::fromImage(QImage(QLatin1String("skin:talking_off.svg")).scaled(64, 64)); bInit = false; @@ -208,14 +209,13 @@ AudioWizard::AudioWizard(QWidget *p) : QWizard(p) { } bool AudioWizard::eventFilter(QObject *obj, QEvent *evt) { - if ((evt->type() == QEvent::MouseButtonPress) || - (evt->type() == QEvent::MouseMove)) { - QMouseEvent *qme = dynamic_cast<QMouseEvent *>(evt); + if ((evt->type() == QEvent::MouseButtonPress) || (evt->type() == QEvent::MouseMove)) { + QMouseEvent *qme = dynamic_cast< QMouseEvent * >(evt); if (qme) { if (qme->buttons() & Qt::LeftButton) { QPointF qpf = qgvView->mapToScene(qme->pos()); - fX = static_cast<float>(qpf.x()); - fY = static_cast<float>(qpf.y()); + fX = static_cast< float >(qpf.x()); + fY = static_cast< float >(qpf.y()); } } } @@ -225,15 +225,13 @@ bool AudioWizard::eventFilter(QObject *obj, QEvent *evt) { void AudioWizard::on_qcbInput_activated(int) { qcbInputDevice->clear(); - if (! AudioInputRegistrar::qmNew) + if (!AudioInputRegistrar::qmNew) return; AudioInputRegistrar *air = AudioInputRegistrar::qmNew->value(qcbInput->currentText()); - QList<audioDevice> ql = air->getDeviceChoices(); + QList< audioDevice > ql = air->getDeviceChoices(); - foreach(audioDevice d, ql) { - qcbInputDevice->addItem(d.first, d.second); - } + foreach (audioDevice d, ql) { qcbInputDevice->addItem(d.first, d.second); } qcbInputDevice->setEnabled(ql.count() > 1); @@ -244,13 +242,13 @@ void AudioWizard::on_qcbInputDevice_activated(int) { if (bInit) return; - if (! AudioInputRegistrar::qmNew) + if (!AudioInputRegistrar::qmNew) return; Audio::stopInput(); AudioInputRegistrar *air = AudioInputRegistrar::qmNew->value(qcbInput->currentText()); - int idx = qcbInputDevice->currentIndex(); + int idx = qcbInputDevice->currentIndex(); if (idx > -1) { air->setDeviceChoice(qcbInputDevice->itemData(idx), g.s); } @@ -264,15 +262,13 @@ void AudioWizard::on_qcbInputDevice_activated(int) { void AudioWizard::on_qcbOutput_activated(int) { qcbOutputDevice->clear(); - if (! AudioOutputRegistrar::qmNew) + if (!AudioOutputRegistrar::qmNew) return; AudioOutputRegistrar *aor = AudioOutputRegistrar::qmNew->value(qcbOutput->currentText()); - QList<audioDevice> ql = aor->getDeviceChoices(); + QList< audioDevice > ql = aor->getDeviceChoices(); - foreach(audioDevice d, ql) { - qcbOutputDevice->addItem(d.first, d.second); - } + foreach (audioDevice d, ql) { qcbOutputDevice->addItem(d.first, d.second); } qcbAttenuateOthers->setEnabled(aor->canMuteOthers()); @@ -285,13 +281,13 @@ void AudioWizard::on_qcbOutputDevice_activated(int) { if (bInit) return; - if (! AudioOutputRegistrar::qmNew) + if (!AudioOutputRegistrar::qmNew) return; Audio::stopOutput(); AudioOutputRegistrar *aor = AudioOutputRegistrar::qmNew->value(qcbOutput->currentText()); - int idx = qcbOutputDevice->currentIndex(); + int idx = qcbOutputDevice->currentIndex(); if (idx > -1) { aor->setDeviceChoice(qcbOutputDevice->itemData(idx), g.s); bDelay = aor->usesOutputDelay(); @@ -305,7 +301,7 @@ void AudioWizard::on_qcbOutputDevice_activated(int) { } void AudioWizard::on_qsOutputDelay_valueChanged(int v) { - qlOutputDelay->setText(tr("%1 ms").arg(v*10)); + qlOutputDelay->setText(tr("%1 ms").arg(v * 10)); g.s.iOutputDelay = v; restartAudio(); } @@ -318,7 +314,7 @@ void AudioWizard::showPage(int pageid) { if (pageid == -1) return; - CompletablePage *cp = qobject_cast<CompletablePage *>(currentPage()); + CompletablePage *cp = qobject_cast< CompletablePage * >(currentPage()); AudioOutputPtr ao = g.ao; if (ao) @@ -335,13 +331,13 @@ void AudioWizard::showPage(int pageid) { g.s.bMute = true; playChord(); } else if (cp == qwpPositional) { - fX = fY = 0.0f; - g.s.bMute = true; + fX = fY = 0.0f; + g.s.bMute = true; g.bPosTest = true; if (qgsScene) { delete qgsScene; qgiSource = nullptr; - qgsScene = nullptr; + qgsScene = nullptr; } playChord(); } else { @@ -349,7 +345,7 @@ void AudioWizard::showPage(int pageid) { } if ((cp == qwpTrigger) || (cp == qwpSettings)) { - if (! bTransmitChanged) + if (!bTransmitChanged) g.s.atTransmit = sOldSettings.atTransmit; else if (qrPTT->isChecked()) g.s.atTransmit = Settings::PushToTalk; @@ -364,16 +360,16 @@ int AudioWizard::nextId() const { AudioOutputPtr ao = g.ao; int nextid = QWizard::nextId(); - if (currentPage() == qwpSettings && ! g.s.bPositionalAudio) + if (currentPage() == qwpSettings && !g.s.bPositionalAudio) nextid++; - else if ((currentPage() == qwpDevice) && ! bDelay) + else if ((currentPage() == qwpDevice) && !bDelay) nextid++; return nextid; } void AudioWizard::playChord() { AudioOutputPtr ao = g.ao; - if (! ao || aosSource || bInit) + if (!ao || aosSource || bInit) return; aosSource = ao->playSample(QLatin1String(":/wb_male.oga"), true); } @@ -383,7 +379,7 @@ void AudioWizard::restartAudio() { Audio::stop(); - g.s.qsAudioInput = qcbInput->currentText(); + g.s.qsAudioInput = qcbInput->currentText(); g.s.qsAudioOutput = qcbOutput->currentText(); Audio::start(); @@ -391,7 +387,7 @@ void AudioWizard::restartAudio() { if (qgsScene) { delete qgsScene; qgiSource = nullptr; - qgsScene = nullptr; + qgsScene = nullptr; } if ((currentPage() == qwpPositional) || (currentPage() == qwpDeviceTuning)) @@ -407,7 +403,7 @@ void AudioWizard::reject() { AudioOutputPtr ao = g.ao; if (ao) ao->wipe(); - aosSource = nullptr; + aosSource = nullptr; g.bInAudioWizard = false; g.mw->onChangeMute(); @@ -415,22 +411,22 @@ void AudioWizard::reject() { } void AudioWizard::accept() { - if (! bTransmitChanged) + if (!bTransmitChanged) g.s.atTransmit = sOldSettings.atTransmit; else if (qrPTT->isChecked()) g.s.atTransmit = Settings::PushToTalk; else g.s.atTransmit = Settings::VAD; - g.s.bMute = sOldSettings.bMute; - g.s.bDeaf = sOldSettings.bDeaf; + g.s.bMute = sOldSettings.bMute; + g.s.bDeaf = sOldSettings.bDeaf; g.s.lmLoopMode = Settings::None; // Switch TTS<->Sounds according to user selection if (!qrbNotificationCustom->isChecked()) { Settings::MessageLog mlReplace = qrbNotificationTTS->isChecked() ? Settings::LogSoundfile : Settings::LogTTS; - for (int i = Log::firstMsgType;i <= Log::lastMsgType; ++i) { + for (int i = Log::firstMsgType; i <= Log::lastMsgType; ++i) { if (g.s.qmMessages[i] & mlReplace) g.s.qmMessages[i] ^= Settings::LogSoundfile | Settings::LogTTS; } @@ -458,30 +454,30 @@ bool AudioWizard::validateCurrentPage() { } void AudioWizard::on_Ticker_timeout() { - AudioInputPtr ai = g.ai; + AudioInputPtr ai = g.ai; AudioOutputPtr ao = g.ao; - if (! ai || ! ao) + if (!ai || !ao) return; - int iPeak = static_cast<int>(ai->dMaxMic); + int iPeak = static_cast< int >(ai->dMaxMic); if (iTicks++ >= 50) { iMaxPeak = 0; - iTicks = 0; + iTicks = 0; } if (iPeak > iMaxPeak) iMaxPeak = iPeak; abAmplify->iBelow = qsMaxAmp->value(); abAmplify->iValue = iPeak; - abAmplify->iPeak = iMaxPeak; + abAmplify->iPeak = iMaxPeak; abAmplify->update(); abVAD->iBelow = iroundf(g.s.fVADmin * 32767.0f + 0.5f); abVAD->iAbove = iroundf(g.s.fVADmax * 32767.0f + 0.5f); if (g.s.vsVAD == Settings::Amplitude) { - abVAD->iValue = iroundf((32767.f/96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); + abVAD->iValue = iroundf((32767.f / 96.0f) * (96.0f + ai->dPeakCleanMic) + 0.5f); } else { abVAD->iValue = iroundf(ai->fSpeechProb * 32767.0f + 0.5f); } @@ -493,7 +489,7 @@ void AudioWizard::on_Ticker_timeout() { qlTalkIcon->setPixmap(active ? qpTalkingOn : qpTalkingOff); } - if (! qgsScene) { + if (!qgsScene) { const float baseRadius = 0.5; unsigned int nspeaker = 0; @@ -514,23 +510,24 @@ void AudioWizard::on_Ticker_timeout() { // of exactly 1 pixel pen.setWidth(0); - QGraphicsEllipseItem *ownPos = qgsScene->addEllipse(QRectF(-baseRadius, -baseRadius, 2*baseRadius, 2*baseRadius), pen, QBrush(skyBlueColor)); + QGraphicsEllipseItem *ownPos = qgsScene->addEllipse( + QRectF(-baseRadius, -baseRadius, 2 * baseRadius, 2 * baseRadius), pen, QBrush(skyBlueColor)); ownPos->setPos(0, 0); // Good for debugging: This draws a cross at the origin // qgsScene->addLine(QLineF(0,-1,0,1), pen); // qgsScene->addLine(QLineF(-1,0,1,0), pen); - const float speakerScale = 0.9; + const float speakerScale = 0.9; const float speakerRadius = baseRadius * speakerScale; // nspeaker is in format [x1,y1,z1, x2,y2,z2, ...] - for (unsigned int i=0;i<nspeaker;++i) { - if ((spos[3*i] != 0.0f) || (spos[3*i+1] != 0.0f) || (spos[3*i+2] != 0.0f)) { - float x = spos[3*i]; - float z = spos[3*i + 2]; + for (unsigned int i = 0; i < nspeaker; ++i) { + if ((spos[3 * i] != 0.0f) || (spos[3 * i + 1] != 0.0f) || (spos[3 * i + 2] != 0.0f)) { + float x = spos[3 * i]; + float z = spos[3 * i + 2]; - const float lengthInPlane = std::sqrt(x*x + z*z); + const float lengthInPlane = std::sqrt(x * x + z * z); // Scale the vector in the xz plane so that its length is at least enough for // the speaker icons and the icon for the own pos don't overlap @@ -541,15 +538,18 @@ void AudioWizard::on_Ticker_timeout() { z *= scaleFactor; } - QGraphicsEllipseItem *ellipse = qgsScene->addEllipse(QRectF(-speakerRadius, -speakerRadius, 2 * speakerRadius , 2 * speakerRadius), pen, QBrush(vermillionColor)); + QGraphicsEllipseItem *ellipse = qgsScene->addEllipse( + QRectF(-speakerRadius, -speakerRadius, 2 * speakerRadius, 2 * speakerRadius), pen, + QBrush(vermillionColor)); ellipse->setPos(x, z); } } - const float sourceScale = 0.9; + const float sourceScale = 0.9; const float sourceRadius = baseRadius * sourceScale; - qgiSource = qgsScene->addEllipse(QRectF(-sourceRadius, -sourceRadius, 2 * sourceRadius, 2 * sourceRadius), pen, QBrush(bluishGreenColor)); + qgiSource = qgsScene->addEllipse(QRectF(-sourceRadius, -sourceRadius, 2 * sourceRadius, 2 * sourceRadius), + pen, QBrush(bluishGreenColor)); qgiSource->setPos(0, (sourceRadius + baseRadius) * 1.5); qgvView->setScene(qgsScene); @@ -584,15 +584,15 @@ void AudioWizard::on_Ticker_timeout() { } void AudioWizard::on_qsVAD_valueChanged(int v) { - if (! bInit) { - g.s.fVADmax = static_cast<float>(v) / 32767.0f; + if (!bInit) { + g.s.fVADmax = static_cast< float >(v) / 32767.0f; g.s.fVADmin = g.s.fVADmax * 0.9f; } } void AudioWizard::on_qrSNR_clicked(bool on) { if (on) { - g.s.vsVAD = Settings::SignalToNoise; + g.s.vsVAD = Settings::SignalToNoise; g.s.atTransmit = Settings::VAD; updateTriggerWidgets(false); bTransmitChanged = true; @@ -601,7 +601,7 @@ void AudioWizard::on_qrSNR_clicked(bool on) { void AudioWizard::on_qrAmplitude_clicked(bool on) { if (on) { - g.s.vsVAD = Settings::Amplitude; + g.s.vsVAD = Settings::Amplitude; g.s.atTransmit = Settings::VAD; updateTriggerWidgets(false); bTransmitChanged = true; @@ -625,29 +625,28 @@ void AudioWizard::on_skwPTT_keySet(bool valid, bool last) { bTransmitChanged = true; if (last) { - - const QList<QVariant> &buttons = skwPTT->getShortcut(); - QList<Shortcut> ql; + const QList< QVariant > &buttons = skwPTT->getShortcut(); + QList< Shortcut > ql; bool found = false; - foreach(Shortcut s, g.s.qlShortcuts) { + foreach (Shortcut s, g.s.qlShortcuts) { if (s.iIndex == g.mw->gsPushTalk->idx) { if (buttons.isEmpty()) continue; - else if (! found) { + else if (!found) { s.qlButtons = buttons; - found = true; + found = true; } } ql << s; } - if (! found && ! buttons.isEmpty()) { + if (!found && !buttons.isEmpty()) { Shortcut s; - s.iIndex = g.mw->gsPushTalk->idx; + s.iIndex = g.mw->gsPushTalk->idx; s.bSuppress = false; s.qlButtons = buttons; ql << s; } - g.s.qlShortcuts = ql; + g.s.qlShortcuts = ql; GlobalShortcutEngine::engine->bNeedRemap = true; GlobalShortcutEngine::engine->needRemap(); } @@ -664,7 +663,7 @@ void AudioWizard::on_qcbHeadphone_clicked(bool on) { } void AudioWizard::on_qcbPositional_clicked(bool on) { - g.s.bPositionalAudio = on; + g.s.bPositionalAudio = on; g.s.bTransmitPosition = on; restartAudio(); } @@ -692,25 +691,25 @@ void AudioWizard::on_qcbHighContrast_clicked(bool on) { } void AudioWizard::on_qrbQualityLow_clicked() { - g.s.iQuality = 16000; + g.s.iQuality = 16000; g.s.iFramesPerPacket = 6; restartAudio(); } void AudioWizard::on_qrbQualityBalanced_clicked() { - g.s.iQuality = 40000; + g.s.iQuality = 40000; g.s.iFramesPerPacket = 2; restartAudio(); } void AudioWizard::on_qrbQualityUltra_clicked() { - g.s.iQuality = 72000; + g.s.iQuality = 72000; g.s.iFramesPerPacket = 1; restartAudio(); } void AudioWizard::on_qrbQualityCustom_clicked() { - g.s.iQuality = sOldSettings.iQuality; + g.s.iQuality = sOldSettings.iQuality; g.s.iFramesPerPacket = sOldSettings.iFramesPerPacket; restartAudio(); } diff --git a/src/mumble/AudioWizard.h b/src/mumble/AudioWizard.h index ac959baa3..ca7d0009e 100644 --- a/src/mumble/AudioWizard.h +++ b/src/mumble/AudioWizard.h @@ -10,83 +10,85 @@ #include <QtWidgets/QWizard> #include <QtWidgets/QWizardPage> -#include "AudioStats.h" #include "AudioOutput.h" -#include "GlobalShortcut.h" +#include "AudioStats.h" #include "Settings.h" +#include "GlobalShortcut.h" class CompletablePage : public QWizardPage { - Q_OBJECT - protected: - bool bComplete; - public: - CompletablePage(QWizard *p = nullptr); - void setComplete(bool); - bool isComplete() const Q_DECL_OVERRIDE; + Q_OBJECT +protected: + bool bComplete; + +public: + CompletablePage(QWizard *p = nullptr); + void setComplete(bool); + bool isComplete() const Q_DECL_OVERRIDE; }; #include "ui_AudioWizard.h" -class AudioWizard: public QWizard, public Ui::AudioWizard { - private: - Q_OBJECT - Q_DISABLE_COPY(AudioWizard) - protected: - bool bTransmitChanged; - - QGraphicsScene *qgsScene; - QGraphicsItem *qgiSource; - AudioOutputSample *aosSource; - float fAngle; - float fX, fY; - - Settings sOldSettings; - - QTimer *ticker; - - bool bInit; - bool bDelay; - bool bLastActive; - - QPixmap qpTalkingOn, qpTalkingOff; - - int iMaxPeak; - int iTicks; - - void restartAudio(); - void playChord(); - - bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; - public slots: - void on_qcbInput_activated(int); - void on_qcbInputDevice_activated(int); - void on_qcbOutput_activated(int); - void on_qcbOutputDevice_activated(int); - void on_qsOutputDelay_valueChanged(int); - void on_qsMaxAmp_valueChanged(int); - void on_Ticker_timeout(); - void on_qsVAD_valueChanged(int); - void on_qrAmplitude_clicked(bool); - void on_qrSNR_clicked(bool); - void on_qrPTT_clicked(bool); - void on_qcbEcho_clicked(bool); - void on_qcbHeadphone_clicked(bool); - void on_qcbPositional_clicked(bool); - void on_qcbAttenuateOthers_clicked(bool); - void on_qcbHighContrast_clicked(bool); - void on_skwPTT_keySet(bool, bool); - void on_qrbQualityUltra_clicked(); - void on_qrbQualityBalanced_clicked(); - void on_qrbQualityLow_clicked(); - void on_qrbQualityCustom_clicked(); - void showPage(int); - void updateTriggerWidgets(bool); - public: - AudioWizard(QWidget *parent); - void reject() Q_DECL_OVERRIDE; - void accept() Q_DECL_OVERRIDE; - bool validateCurrentPage() Q_DECL_OVERRIDE; - virtual int nextId() const Q_DECL_OVERRIDE; +class AudioWizard : public QWizard, public Ui::AudioWizard { +private: + Q_OBJECT + Q_DISABLE_COPY(AudioWizard) +protected: + bool bTransmitChanged; + + QGraphicsScene *qgsScene; + QGraphicsItem *qgiSource; + AudioOutputSample *aosSource; + float fAngle; + float fX, fY; + + Settings sOldSettings; + + QTimer *ticker; + + bool bInit; + bool bDelay; + bool bLastActive; + + QPixmap qpTalkingOn, qpTalkingOff; + + int iMaxPeak; + int iTicks; + + void restartAudio(); + void playChord(); + + bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; +public slots: + void on_qcbInput_activated(int); + void on_qcbInputDevice_activated(int); + void on_qcbOutput_activated(int); + void on_qcbOutputDevice_activated(int); + void on_qsOutputDelay_valueChanged(int); + void on_qsMaxAmp_valueChanged(int); + void on_Ticker_timeout(); + void on_qsVAD_valueChanged(int); + void on_qrAmplitude_clicked(bool); + void on_qrSNR_clicked(bool); + void on_qrPTT_clicked(bool); + void on_qcbEcho_clicked(bool); + void on_qcbHeadphone_clicked(bool); + void on_qcbPositional_clicked(bool); + void on_qcbAttenuateOthers_clicked(bool); + void on_qcbHighContrast_clicked(bool); + void on_skwPTT_keySet(bool, bool); + void on_qrbQualityUltra_clicked(); + void on_qrbQualityBalanced_clicked(); + void on_qrbQualityLow_clicked(); + void on_qrbQualityCustom_clicked(); + void showPage(int); + void updateTriggerWidgets(bool); + +public: + AudioWizard(QWidget *parent); + void reject() Q_DECL_OVERRIDE; + void accept() Q_DECL_OVERRIDE; + bool validateCurrentPage() Q_DECL_OVERRIDE; + virtual int nextId() const Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/BanEditor.cpp b/src/mumble/BanEditor.cpp index c26fe24da..a2fc046a2 100644 --- a/src/mumble/BanEditor.cpp +++ b/src/mumble/BanEditor.cpp @@ -5,15 +5,15 @@ #include "BanEditor.h" -#include "Channel.h" #include "Ban.h" +#include "Channel.h" #include "ServerHandler.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -BanEditor::BanEditor(const MumbleProto::BanList &msg, QWidget *p) : QDialog(p) - , maskDefaultValue(32) { +BanEditor::BanEditor(const MumbleProto::BanList &msg, QWidget *p) : QDialog(p), maskDefaultValue(32) { setupUi(this); qleSearch->setAccessibleName(tr("Search")); @@ -29,17 +29,17 @@ BanEditor::BanEditor(const MumbleProto::BanList &msg, QWidget *p) : QDialog(p) qlwBans->setFocus(); qlBans.clear(); - for (int i=0;i < msg.bans_size(); ++i) { + for (int i = 0; i < msg.bans_size(); ++i) { const MumbleProto::BanList_BanEntry &be = msg.bans(i); Ban b; - b.haAddress = be.address(); - b.iMask = be.mask(); + b.haAddress = be.address(); + b.iMask = be.mask(); b.qsUsername = u8(be.name()); - b.qsHash = u8(be.hash()); - b.qsReason = u8(be.reason()); - b.qdtStart = QDateTime::fromString(u8(be.start()), Qt::ISODate); + b.qsHash = u8(be.hash()); + b.qsReason = u8(be.reason()); + b.qdtStart = QDateTime::fromString(u8(be.start()), Qt::ISODate); b.qdtStart.setTimeSpec(Qt::UTC); - if (! b.qdtStart.isValid()) + if (!b.qdtStart.isValid()) b.qdtStart = QDateTime::currentDateTime(); b.iDuration = be.duration(); if (b.isValid()) @@ -52,7 +52,7 @@ BanEditor::BanEditor(const MumbleProto::BanList &msg, QWidget *p) : QDialog(p) void BanEditor::accept() { MumbleProto::BanList msg; - foreach(const Ban &b, qlBans) { + foreach (const Ban &b, qlBans) { MumbleProto::BanList_BanEntry *be = msg.add_bans(); be->set_address(b.haAddress.toStdString()); be->set_mask(b.iMask); @@ -82,7 +82,7 @@ void BanEditor::on_qlwBans_currentRowChanged() { const QHostAddress &addr = ban.haAddress.toAddress(); qleIP->setText(addr.toString()); - if (! ban.haAddress.isV6()) + if (!ban.haAddress.isV6()) maskbits -= 96; qsbMask->setValue(maskbits); qleUser->setText(ban.qsUsername); @@ -90,7 +90,6 @@ void BanEditor::on_qlwBans_currentRowChanged() { qleReason->setText(ban.qsReason); qdteStart->setDateTime(ban.qdtStart.toLocalTime()); qdteEnd->setDateTime(ban.qdtStart.toLocalTime().addSecs(ban.iDuration)); - } Ban BanEditor::toBan(bool &ok) { @@ -102,19 +101,19 @@ Ban BanEditor::toBan(bool &ok) { if (ok) { b.haAddress = addr; - b.iMask = qsbMask->value(); - if (! b.haAddress.isV6()) + b.iMask = qsbMask->value(); + if (!b.haAddress.isV6()) b.iMask += 96; - b.qsUsername = qleUser->text(); - b.qsHash = qleHash->text(); - b.qsReason = qleReason->text(); - b.qdtStart = qdteStart->dateTime().toUTC(); + b.qsUsername = qleUser->text(); + b.qsHash = qleHash->text(); + b.qsReason = qleReason->text(); + b.qdtStart = qdteStart->dateTime().toUTC(); const QDateTime &qdte = qdteEnd->dateTime(); - + if (qdte <= b.qdtStart) b.iDuration = 0; else - b.iDuration = static_cast<unsigned int>(b.qdtStart.secsTo(qdte)); + b.iDuration = static_cast< unsigned int >(b.qdtStart.secsTo(qdte)); ok = b.isValid(); } @@ -176,8 +175,8 @@ void BanEditor::refreshBanList() { std::sort(qlBans.begin(), qlBans.end()); - foreach(const Ban &ban, qlBans) { - const QHostAddress &addr=ban.haAddress.toAddress(); + foreach (const Ban &ban, qlBans) { + const QHostAddress &addr = ban.haAddress.toAddress(); if (ban.qsUsername.isEmpty()) qlwBans->addItem(addr.toString()); else @@ -188,8 +187,7 @@ void BanEditor::refreshBanList() { setWindowTitle(tr("Ban List - %n Ban(s)", "", n)); } -void BanEditor::on_qleSearch_textChanged(const QString & match) -{ +void BanEditor::on_qleSearch_textChanged(const QString &match) { qlwBans->clearSelection(); qpbAdd->setDisabled(true); @@ -205,7 +203,7 @@ void BanEditor::on_qleSearch_textChanged(const QString & match) qdteStart->setDateTime(QDateTime::currentDateTime()); qdteEnd->setDateTime(QDateTime::currentDateTime()); - foreach(QListWidgetItem *item, qlwBans->findItems(QString(), Qt::MatchContains)) { + foreach (QListWidgetItem *item, qlwBans->findItems(QString(), Qt::MatchContains)) { if (!item->text().contains(match, Qt::CaseInsensitive)) item->setHidden(true); else @@ -213,39 +211,33 @@ void BanEditor::on_qleSearch_textChanged(const QString & match) } } -void BanEditor::on_qleIP_textChanged(QString ) -{ +void BanEditor::on_qleIP_textChanged(QString) { qpbAdd->setEnabled(qleIP->isModified()); if (qlwBans->currentRow() >= 0) qpbUpdate->setEnabled(qleIP->isModified()); } -void BanEditor::on_qleReason_textChanged(QString ) -{ +void BanEditor::on_qleReason_textChanged(QString) { if (qlwBans->currentRow() >= 0) qpbUpdate->setEnabled(qleReason->isModified()); } -void BanEditor::on_qdteEnd_editingFinished() -{ +void BanEditor::on_qdteEnd_editingFinished() { qpbUpdate->setEnabled(!qleIP->text().isEmpty()); qpbRemove->setDisabled(true); } -void BanEditor::on_qleUser_textChanged(QString ) -{ +void BanEditor::on_qleUser_textChanged(QString) { if (qlwBans->currentRow() >= 0) qpbUpdate->setEnabled(qleUser->isModified()); } -void BanEditor::on_qleHash_textChanged(QString ) -{ +void BanEditor::on_qleHash_textChanged(QString) { if (qlwBans->currentRow() >= 0) qpbUpdate->setEnabled(qleHash->isModified()); } -void BanEditor::on_qpbClear_clicked() -{ +void BanEditor::on_qpbClear_clicked() { qlwBans->setCurrentRow(-1); qleUser->clear(); qleIP->clear(); diff --git a/src/mumble/BanEditor.h b/src/mumble/BanEditor.h index 8a1b0c79c..5dee4422c 100644 --- a/src/mumble/BanEditor.h +++ b/src/mumble/BanEditor.h @@ -15,32 +15,33 @@ class BanList; } class BanEditor : public QDialog, public Ui::BanEditor { - private: - Q_OBJECT - Q_DISABLE_COPY(BanEditor) - protected: - QList<Ban> qlBans; - - int maskDefaultValue; - - Ban toBan(bool &); - public: - BanEditor(const MumbleProto::BanList &msbl, QWidget *p = nullptr); - public slots: - void accept(); - void on_qlwBans_currentRowChanged(); - void on_qpbAdd_clicked(); - void on_qpbUpdate_clicked(); - void on_qpbRemove_clicked(); - void refreshBanList(); - void on_qdteEnd_editingFinished(); - void on_qpbClear_clicked(); - private slots: - void on_qleHash_textChanged(QString ); - void on_qleSearch_textChanged(const QString & match); - void on_qleReason_textChanged(QString ); - void on_qleIP_textChanged(QString ); - void on_qleUser_textChanged(QString ); +private: + Q_OBJECT + Q_DISABLE_COPY(BanEditor) +protected: + QList< Ban > qlBans; + + int maskDefaultValue; + + Ban toBan(bool &); + +public: + BanEditor(const MumbleProto::BanList &msbl, QWidget *p = nullptr); +public slots: + void accept(); + void on_qlwBans_currentRowChanged(); + void on_qpbAdd_clicked(); + void on_qpbUpdate_clicked(); + void on_qpbRemove_clicked(); + void refreshBanList(); + void on_qdteEnd_editingFinished(); + void on_qpbClear_clicked(); +private slots: + void on_qleHash_textChanged(QString); + void on_qleSearch_textChanged(const QString &match); + void on_qleReason_textChanged(QString); + void on_qleIP_textChanged(QString); + void on_qleUser_textChanged(QString); }; #endif diff --git a/src/mumble/BonjourClient.h b/src/mumble/BonjourClient.h index 7d2383bad..2a7fd57ac 100644 --- a/src/mumble/BonjourClient.h +++ b/src/mumble/BonjourClient.h @@ -10,14 +10,14 @@ #include "BonjourServiceResolver.h" class BonjourClient : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(BonjourClient) - public: - BonjourClient(); +private: + Q_OBJECT + Q_DISABLE_COPY(BonjourClient) +public: + BonjourClient(); - QScopedPointer<BonjourServiceBrowser> bsbBrowser; - QScopedPointer<BonjourServiceResolver> bsrResolver; + QScopedPointer< BonjourServiceBrowser > bsbBrowser; + QScopedPointer< BonjourServiceResolver > bsrResolver; }; #endif diff --git a/src/mumble/CELTCodec.cpp b/src/mumble/CELTCodec.cpp index c7cda62c4..a5e6f0e41 100644 --- a/src/mumble/CELTCodec.cpp +++ b/src/mumble/CELTCodec.cpp @@ -6,25 +6,33 @@ #include "CELTCodec.h" #include "Audio.h" -#include "Version.h" #include "MumbleApplication.h" +#include "Version.h" #ifdef Q_CC_GNU -#define RESOLVE(var) { var = reinterpret_cast<__typeof__(var)>(qlCELT.resolve(#var)); bValid = bValid && var; } +# define RESOLVE(var) \ + { \ + var = reinterpret_cast< __typeof__(var) >(qlCELT.resolve(#var)); \ + bValid = bValid && var; \ + } #else -#define RESOLVE(var) { * reinterpret_cast<void **>(&var) = static_cast<void *>(qlCELT.resolve(#var)); bValid = bValid && var; } +# define RESOLVE(var) \ + { \ + *reinterpret_cast< void ** >(&var) = static_cast< void * >(qlCELT.resolve(#var)); \ + bValid = bValid && var; \ + } #endif #ifdef Q_OS_WIN extern "C" { - void __cpuid(int a[4], int b); +void __cpuid(int a[4], int b); }; #endif CELTCodec::CELTCodec(const QString &celt_version) { - bValid = false; - cmMode = nullptr; - qsVersion = celt_version; + bValid = false; + cmMode = nullptr; + qsVersion = celt_version; iBitstreamVersion = INT_MIN; qlCELT.setLoadHints(QLibrary::ResolveAllSymbolsHint); @@ -53,7 +61,7 @@ CELTCodec::CELTCodec(const QString &celt_version) { alternatives << QString::fromLatin1("celt0.%1.dll").arg(celt_version); #endif - foreach(const QString &lib, alternatives) { + foreach (const QString &lib, alternatives) { qlCELT.setFileName(MumbleApplication::instance()->applicationVersionRootPath() + QLatin1String("/") + lib); if (qlCELT.load()) { bValid = true; @@ -95,7 +103,7 @@ CELTCodec::CELTCodec(const QString &celt_version) { CELTCodec::~CELTCodec() { if (cmMode) - celt_mode_destroy(const_cast<CELTMode *>(cmMode)); + celt_mode_destroy(const_cast< CELTMode * >(cmMode)); } bool CELTCodec::isValid() const { @@ -104,7 +112,7 @@ bool CELTCodec::isValid() const { int CELTCodec::bitstreamVersion() const { if (cmMode && iBitstreamVersion == INT_MIN) - celt_mode_info(cmMode, CELT_GET_BITSTREAM_VERSION, reinterpret_cast<celt_int32 *>(&iBitstreamVersion)); + celt_mode_info(cmMode, CELT_GET_BITSTREAM_VERSION, reinterpret_cast< celt_int32 * >(&iBitstreamVersion)); return iBitstreamVersion; } diff --git a/src/mumble/CELTCodec.h b/src/mumble/CELTCodec.h index e273ffa62..c25e6c3fd 100644 --- a/src/mumble/CELTCodec.h +++ b/src/mumble/CELTCodec.h @@ -12,70 +12,76 @@ #include <QtCore/QString> #ifndef Q_OS_WIN -#define __cdecl +# define __cdecl #endif class CELTCodec { - private: - Q_DISABLE_COPY(CELTCodec) - protected: - const CELTMode *cmMode; - QString qsVersion; - QLibrary qlCELT; - bool bValid; - mutable int iBitstreamVersion; - - void (*celt_mode_destroy)(CELTMode *mode); - int (__cdecl *celt_mode_info)(const CELTMode *mode, int request, celt_int32 *value); - - public: - void (__cdecl *celt_encoder_destroy)(CELTEncoder *st); - int (__cdecl *celt_encoder_ctl)(CELTEncoder * st, int request, ...); - - void (__cdecl *celt_decoder_destroy)(CELTDecoder *st); - int (__cdecl *celt_decoder_ctl)(CELTDecoder * st, int request, ...); - - CELTCodec(const QString &celt_version); - virtual ~CELTCodec(); - bool isValid() const; - int bitstreamVersion() const; - QString version() const; - - virtual void report() const; - - virtual CELTEncoder *encoderCreate() = 0; - virtual CELTDecoder *decoderCreate() = 0; - virtual int encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, int nbCompressedBytes) = 0; - virtual int decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) = 0; +private: + Q_DISABLE_COPY(CELTCodec) +protected: + const CELTMode *cmMode; + QString qsVersion; + QLibrary qlCELT; + bool bValid; + mutable int iBitstreamVersion; + + void (*celt_mode_destroy)(CELTMode *mode); + int(__cdecl *celt_mode_info)(const CELTMode *mode, int request, celt_int32 *value); + +public: + void(__cdecl *celt_encoder_destroy)(CELTEncoder *st); + int(__cdecl *celt_encoder_ctl)(CELTEncoder *st, int request, ...); + + void(__cdecl *celt_decoder_destroy)(CELTDecoder *st); + int(__cdecl *celt_decoder_ctl)(CELTDecoder *st, int request, ...); + + CELTCodec(const QString &celt_version); + virtual ~CELTCodec(); + bool isValid() const; + int bitstreamVersion() const; + QString version() const; + + virtual void report() const; + + virtual CELTEncoder *encoderCreate() = 0; + virtual CELTDecoder *decoderCreate() = 0; + virtual int encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, int nbCompressedBytes) = 0; + virtual int decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) = 0; }; class CELTCodec070 : public CELTCodec { - protected: - CELTMode *(*celt_mode_create)(celt_int32 Fs, int frame_size, int *error); - CELTEncoder *(__cdecl *celt_encoder_create)(const CELTMode *mode, int channels, int *error); - CELTDecoder *(__cdecl *celt_decoder_create)(const CELTMode *mode, int channels, int *error); - int (__cdecl *celt_encode_float)(CELTEncoder *st, const float *pcm, float *optional_synthesis, unsigned char *compressed, int nbCompressedBytes); - int (__cdecl *celt_encode)(CELTEncoder *st, const celt_int16 *pcm, celt_int16 *optional_synthesis, unsigned char *compressed, int nbCompressedBytes); - int (__cdecl *celt_decode_float)(CELTDecoder *st, const unsigned char *data, int len, float *pcm); - int (__cdecl *celt_decode)(CELTDecoder *st, const unsigned char *data, int len, celt_int16 *pcm); - const char *(__cdecl *celt_strerror)(int error); - public: - CELTCodec070(const QString &celt_version); - CELTEncoder *encoderCreate() Q_DECL_OVERRIDE; - CELTDecoder *decoderCreate() Q_DECL_OVERRIDE; - int encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, int nbCompressedBytes) Q_DECL_OVERRIDE; - int decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) Q_DECL_OVERRIDE; +protected: + CELTMode *(*celt_mode_create)(celt_int32 Fs, int frame_size, int *error); + CELTEncoder *(__cdecl *celt_encoder_create)(const CELTMode *mode, int channels, int *error); + CELTDecoder *(__cdecl *celt_decoder_create)(const CELTMode *mode, int channels, int *error); + int(__cdecl *celt_encode_float)(CELTEncoder *st, const float *pcm, float *optional_synthesis, + unsigned char *compressed, int nbCompressedBytes); + int(__cdecl *celt_encode)(CELTEncoder *st, const celt_int16 *pcm, celt_int16 *optional_synthesis, + unsigned char *compressed, int nbCompressedBytes); + int(__cdecl *celt_decode_float)(CELTDecoder *st, const unsigned char *data, int len, float *pcm); + int(__cdecl *celt_decode)(CELTDecoder *st, const unsigned char *data, int len, celt_int16 *pcm); + const char *(__cdecl *celt_strerror)(int error); + +public: + CELTCodec070(const QString &celt_version); + CELTEncoder *encoderCreate() Q_DECL_OVERRIDE; + CELTDecoder *decoderCreate() Q_DECL_OVERRIDE; + int encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, + int nbCompressedBytes) Q_DECL_OVERRIDE; + int decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) Q_DECL_OVERRIDE; }; class CELTCodecSBCELT : public CELTCodec { - protected: - const CELTMode *cmSBCELTMode; - public: - CELTCodecSBCELT(); - CELTEncoder *encoderCreate() Q_DECL_OVERRIDE; - CELTDecoder *decoderCreate() Q_DECL_OVERRIDE; - int encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, int nbCompressedBytes) Q_DECL_OVERRIDE; - int decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) Q_DECL_OVERRIDE; +protected: + const CELTMode *cmSBCELTMode; + +public: + CELTCodecSBCELT(); + CELTEncoder *encoderCreate() Q_DECL_OVERRIDE; + CELTDecoder *decoderCreate() Q_DECL_OVERRIDE; + int encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, + int nbCompressedBytes) Q_DECL_OVERRIDE; + int decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) Q_DECL_OVERRIDE; }; -#endif // CELTCODEC_H_ +#endif // CELTCODEC_H_ diff --git a/src/mumble/CELTCodec_sbcelt.cpp b/src/mumble/CELTCodec_sbcelt.cpp index 12134d53d..1226d2404 100644 --- a/src/mumble/CELTCodec_sbcelt.cpp +++ b/src/mumble/CELTCodec_sbcelt.cpp @@ -9,21 +9,21 @@ #include "Version.h" CELTCodec::CELTCodec(const QString &version) { - bValid = true; - cmMode = nullptr; - qsVersion = version; + bValid = true; + cmMode = nullptr; + qsVersion = version; iBitstreamVersion = INT_MIN; this->celt_encoder_destroy = ::celt_encoder_destroy; - this->celt_encoder_ctl = ::celt_encoder_ctl; + this->celt_encoder_ctl = ::celt_encoder_ctl; this->celt_decoder_destroy = ::celt_decoder_destroy; - this->celt_decoder_ctl = ::celt_decoder_ctl; + this->celt_decoder_ctl = ::celt_decoder_ctl; } CELTCodec::~CELTCodec() { if (cmMode) - ::celt_mode_destroy(const_cast<CELTMode *>(cmMode)); + ::celt_mode_destroy(const_cast< CELTMode * >(cmMode)); } bool CELTCodec::isValid() const { @@ -32,7 +32,7 @@ bool CELTCodec::isValid() const { int CELTCodec::bitstreamVersion() const { if (cmMode && iBitstreamVersion == INT_MIN) - ::celt_mode_info(cmMode, CELT_GET_BITSTREAM_VERSION, reinterpret_cast<celt_int32 *>(&iBitstreamVersion)); + ::celt_mode_info(cmMode, CELT_GET_BITSTREAM_VERSION, reinterpret_cast< celt_int32 * >(&iBitstreamVersion)); return iBitstreamVersion; } @@ -47,11 +47,11 @@ void CELTCodec::report() const { CELTCodecSBCELT::CELTCodecSBCELT() : CELTCodec(QLatin1String("0.7.0")) { if (bValid) { - cmMode = ::celt_mode_create(SAMPLE_RATE, SAMPLE_RATE / 100, nullptr); + cmMode = ::celt_mode_create(SAMPLE_RATE, SAMPLE_RATE / 100, nullptr); cmSBCELTMode = ::sbcelt_mode_create(SAMPLE_RATE, SAMPLE_RATE / 100, nullptr); this->celt_decoder_destroy = ::sbcelt_decoder_destroy; - this->celt_decoder_ctl = ::sbcelt_decoder_ctl; + this->celt_decoder_ctl = ::sbcelt_decoder_ctl; } } diff --git a/src/mumble/Cert.cpp b/src/mumble/Cert.cpp index 4b4975f84..e2b939b99 100644 --- a/src/mumble/Cert.cpp +++ b/src/mumble/Cert.cpp @@ -8,7 +8,7 @@ // but we still build with GCC 4.2 for the legacy OS X Universal // build. #if defined(__GNUC__) -# pragma GCC diagnostic ignored "-Wold-style-cast" +# pragma GCC diagnostic ignored "-Wold-style-cast" #endif #include "Cert.h" @@ -25,7 +25,8 @@ #include <openssl/pkcs12.h> #include <openssl/x509.h> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" #define SSL_STRING(x) QString::fromLatin1(x).toUtf8().data() @@ -68,7 +69,7 @@ CertView::CertView(QWidget *p) : QGroupBox(p) { grid->setColumnStretch(1, 1); } -void CertView::setCert(const QList<QSslCertificate> &cert) { +void CertView::setCert(const QList< QSslCertificate > &cert) { qlCert = cert; if (qlCert.isEmpty()) { @@ -88,8 +89,8 @@ void CertView::setCert(const QList<QSslCertificate> &cert) { QStringList emails = qscCert.subjectAlternativeNames().values(QSsl::EmailEntry); QString tmpName = name; - tmpName = tmpName.replace(QLatin1String("\\x"), QLatin1String("%")); - tmpName = QUrl::fromPercentEncoding(tmpName.toLatin1()); + tmpName = tmpName.replace(QLatin1String("\\x"), QLatin1String("%")); + tmpName = QUrl::fromPercentEncoding(tmpName.toLatin1()); qlSubjectName->setText(tmpName); @@ -99,7 +100,8 @@ void CertView::setCert(const QList<QSslCertificate> &cert) { qlSubjectEmail->setText(tr("(none)")); if (qscCert.expiryDate() <= QDateTime::currentDateTime()) - qlExpiry->setText(QString::fromLatin1("<font color=\"red\"><b>%1</b></font>").arg(qscCert.expiryDate().toString(Qt::SystemLocaleDate).toHtmlEscaped())); + qlExpiry->setText(QString::fromLatin1("<font color=\"red\"><b>%1</b></font>") + .arg(qscCert.expiryDate().toString(Qt::SystemLocaleDate).toHtmlEscaped())); else qlExpiry->setText(qscCert.expiryDate().toString(Qt::SystemLocaleDate)); @@ -139,17 +141,17 @@ CertWizard::CertWizard(QWidget *p) : QWizard(p) { int CertWizard::nextId() const { switch (currentId()) { - case 0: { // Welcome - if (qrbQuick->isChecked()) - return 5; - else if (qrbCreate->isChecked()) - return 1; - else if (qrbImport->isChecked()) - return 2; - else if (qrbExport->isChecked()) - return 3; - return -1; - } + case 0: { // Welcome + if (qrbQuick->isChecked()) + return 5; + else if (qrbCreate->isChecked()) + return 1; + else if (qrbImport->isChecked()) + return 2; + else if (qrbExport->isChecked()) + return 3; + return -1; + } case 2: // Import if (validateCert(kpCurrent)) return 4; @@ -214,8 +216,8 @@ bool CertWizard::validateCurrentPage() { return false; } else { kpNew = generateNewCert(qleName->text(), qleEmail->text()); - - if (! validateCert(kpNew)) { + + if (!validateCert(kpNew)) { qlError->setText(tr("There was an error generating your certificate.<br />Please try again.")); return false; } @@ -224,40 +226,53 @@ bool CertWizard::validateCurrentPage() { if (currentPage() == qwpExport) { QByteArray qba = exportCert(kpNew); if (qba.isEmpty()) { - QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("Your certificate and key could not be exported to PKCS#12 format. There might be an error in your certificate."), qleExportFile); + QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0, 0)), + tr("Your certificate and key could not be exported to PKCS#12 format. There might be an " + "error in your certificate."), + qleExportFile); return false; } QFile f(qleExportFile->text()); - if (! f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Unbuffered)) { - QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be opened for writing. Please use another file."), qleExportFile); + if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Unbuffered)) { + QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0, 0)), + tr("The file could not be opened for writing. Please use another file."), qleExportFile); return false; } - if (! f.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) { - QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file's permissions could not be set. No certificate and key has been written. Please use another file."), qleExportFile); + if (!f.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) { + QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0, 0)), + tr("The file's permissions could not be set. No certificate and key has been written. " + "Please use another file."), + qleExportFile); return false; } qint64 written = f.write(qba); f.close(); if (written != qba.length()) { - QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be written successfully. Please use another file."), qleExportFile); + QToolTip::showText(qleExportFile->mapToGlobal(QPoint(0, 0)), + tr("The file could not be written successfully. Please use another file."), + qleExportFile); return false; } } if (currentPage() == qwpImport) { QFile f(qleImportFile->text()); - if (! f.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) { - QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file could not be opened for reading. Please use another file."), qleImportFile); + if (!f.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) { + QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0, 0)), + tr("The file could not be opened for reading. Please use another file."), qleImportFile); return false; } QByteArray qba = f.readAll(); f.close(); if (qba.isEmpty()) { - QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file is empty or could not be read. Please use another file."), qleImportFile); + QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0, 0)), + tr("The file is empty or could not be read. Please use another file."), qleImportFile); return false; } - QPair<QList<QSslCertificate>, QSslKey> imp = importCert(qba, qlePassword->text()); - if (! validateCert(imp)) { - QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0,0)), tr("The file did not contain a valid certificate and key. Please use another file."), qleImportFile); + QPair< QList< QSslCertificate >, QSslKey > imp = importCert(qba, qlePassword->text()); + if (!validateCert(imp)) { + QToolTip::showText(qleImportFile->mapToGlobal(QPoint(0, 0)), + tr("The file did not contain a valid certificate and key. Please use another file."), + qleImportFile); return false; } kpNew = imp; @@ -273,8 +288,10 @@ void CertWizard::on_qleEmail_textChanged(const QString &) { } void CertWizard::on_qpbExportFile_clicked() { - QString fname = QFileDialog::getSaveFileName(this, tr("Select file to export certificate to"), qleExportFile->text(), QLatin1String("PKCS12 (*.p12 *.pfx *.pkcs12);;All (*)")); - if (! fname.isNull()) { + QString fname = + QFileDialog::getSaveFileName(this, tr("Select file to export certificate to"), qleExportFile->text(), + QLatin1String("PKCS12 (*.p12 *.pfx *.pkcs12);;All (*)")); + if (!fname.isNull()) { QFileInfo fi(fname); if (fi.suffix().isEmpty()) fname += QLatin1String(".p12"); @@ -310,8 +327,10 @@ void CertWizard::on_qleExportFile_textChanged(const QString &text) { } void CertWizard::on_qpbImportFile_clicked() { - QString fname = QFileDialog::getOpenFileName(this, tr("Select file to import certificate from"), qleImportFile->text(), QLatin1String("PKCS12 (*.p12 *.pfx *.pkcs12);;All (*)")); - if (! fname.isNull()) { + QString fname = + QFileDialog::getOpenFileName(this, tr("Select file to import certificate from"), qleImportFile->text(), + QLatin1String("PKCS12 (*.p12 *.pfx *.pkcs12);;All (*)")); + if (!fname.isNull()) { qleImportFile->setText(QDir::toNativeSeparators(fname)); } } @@ -331,8 +350,8 @@ void CertWizard::on_qleImportFile_textChanged(const QString &text) { QFile f(fname); if (f.open(QIODevice::ReadOnly)) { - QByteArray qba = f.readAll(); - QPair<QList<QSslCertificate>, QSslKey> imp = importCert(qba, qlePassword->text()); + QByteArray qba = f.readAll(); + QPair< QList< QSslCertificate >, QSslKey > imp = importCert(qba, qlePassword->text()); if (validateCert(imp)) { qlePassword->setEnabled(false); qlPassword->setEnabled(false); @@ -354,7 +373,7 @@ void CertWizard::on_qleImportFile_textChanged(const QString &text) { qlPasswordNotice->clear(); qlPasswordNotice->setVisible(false); } - cvImport->setCert(QList<QSslCertificate>()); + cvImport->setCert(QList< QSslCertificate >()); qwpImport->setComplete(false); } @@ -367,9 +386,9 @@ void CertWizard::on_qlIntroText_linkActivated(const QString &url) { } bool CertWizard::validateCert(const Settings::KeyPair &kp) { - bool valid = ! kp.second.isNull() && ! kp.first.isEmpty(); - foreach(const QSslCertificate &cert, kp.first) - valid = valid && ! cert.isNull(); + bool valid = !kp.second.isNull() && !kp.first.isEmpty(); + foreach (const QSslCertificate &cert, kp.first) + valid = valid && !cert.isNull(); return valid; } @@ -381,17 +400,17 @@ Settings::KeyPair CertWizard::generateNewCert(QString qsname, const QString &qse // The method sets qscCert and qskKey to null values if it fails. SelfSignedCertificate::generateMumbleCertificate(qsname, qsemail, qscCert, qskKey); - QList<QSslCertificate> qlCert; + QList< QSslCertificate > qlCert; qlCert << qscCert; return Settings::KeyPair(qlCert, qskKey); } Settings::KeyPair CertWizard::importCert(QByteArray data, const QString &pw) { - X509 *x509 = nullptr; - EVP_PKEY *pkey = nullptr; - PKCS12 *pkcs = nullptr; - BIO *mem = nullptr; + X509 *x509 = nullptr; + EVP_PKEY *pkey = nullptr; + PKCS12 *pkcs = nullptr; + BIO *mem = nullptr; STACK_OF(X509) *certs = nullptr; Settings::KeyPair kp; int ret = 0; @@ -401,7 +420,7 @@ Settings::KeyPair CertWizard::importCert(QByteArray data, const QString &pw) { pkcs = d2i_PKCS12_bio(mem, nullptr); if (pkcs) { ret = PKCS12_parse(pkcs, nullptr, &pkey, &x509, &certs); - if (pkcs && !pkey && !x509 && ! pw.isEmpty()) { + if (pkcs && !pkey && !x509 && !pw.isEmpty()) { if (certs) { if (ret) sk_X509_free(certs); @@ -414,34 +433,34 @@ Settings::KeyPair CertWizard::importCert(QByteArray data, const QString &pw) { QByteArray key, crt; key.resize(i2d_PrivateKey(pkey, nullptr)); - dptr=reinterpret_cast<unsigned char *>(key.data()); + dptr = reinterpret_cast< unsigned char * >(key.data()); i2d_PrivateKey(pkey, &dptr); crt.resize(i2d_X509(x509, nullptr)); - dptr=reinterpret_cast<unsigned char *>(crt.data()); + dptr = reinterpret_cast< unsigned char * >(crt.data()); i2d_X509(x509, &dptr); QSslCertificate qscCert = QSslCertificate(crt, QSsl::Der); - QSslKey qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der); + QSslKey qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der); - QList<QSslCertificate> qlCerts; + QList< QSslCertificate > qlCerts; qlCerts << qscCert; if (certs) { - for (int i=0;i<sk_X509_num(certs);++i) { + for (int i = 0; i < sk_X509_num(certs); ++i) { X509 *c = sk_X509_value(certs, i); crt.resize(i2d_X509(c, nullptr)); - dptr=reinterpret_cast<unsigned char *>(crt.data()); + dptr = reinterpret_cast< unsigned char * >(crt.data()); i2d_X509(c, &dptr); QSslCertificate cert = QSslCertificate(crt, QSsl::Der); qlCerts << cert; } } - bool valid = ! qskKey.isNull(); - foreach(const QSslCertificate &cert, qlCerts) - valid = valid && ! cert.isNull(); + bool valid = !qskKey.isNull(); + foreach (const QSslCertificate &cert, qlCerts) + valid = valid && !cert.isNull(); if (valid) kp = Settings::KeyPair(qlCerts, qskKey); } @@ -464,10 +483,10 @@ Settings::KeyPair CertWizard::importCert(QByteArray data, const QString &pw) { } QByteArray CertWizard::exportCert(const Settings::KeyPair &kp) { - X509 *x509 = nullptr; - EVP_PKEY *pkey = nullptr; - PKCS12 *pkcs = nullptr; - BIO *mem = nullptr; + X509 *x509 = nullptr; + EVP_PKEY *pkey = nullptr; + PKCS12 *pkcs = nullptr; + BIO *mem = nullptr; STACK_OF(X509) *certs = sk_X509_new_null(); const unsigned char *p; char *data = nullptr; @@ -479,11 +498,11 @@ QByteArray CertWizard::exportCert(const Settings::KeyPair &kp) { QByteArray key = kp.second.toDer(); QByteArray qba; - p = reinterpret_cast<const unsigned char *>(key.constData()); + p = reinterpret_cast< const unsigned char * >(key.constData()); pkey = d2i_AutoPrivateKey(nullptr, &p, key.length()); if (pkey) { - p = reinterpret_cast<const unsigned char *>(crt.constData()); + p = reinterpret_cast< const unsigned char * >(crt.constData()); x509 = d2i_X509(nullptr, &p, crt.length()); if (x509 && X509_check_private_key(x509, pkey)) { @@ -491,13 +510,13 @@ QByteArray CertWizard::exportCert(const Settings::KeyPair &kp) { X509_alias_set1(x509, nullptr, 0); - QList<QSslCertificate> qlCerts = kp.first; + QList< QSslCertificate > qlCerts = kp.first; qlCerts.removeFirst(); - foreach(const QSslCertificate &cert, qlCerts) { + foreach (const QSslCertificate &cert, qlCerts) { X509 *c = nullptr; - crt = cert.toDer(); - p = reinterpret_cast<const unsigned char *>(crt.constData()); + crt = cert.toDer(); + p = reinterpret_cast< const unsigned char * >(crt.constData()); c = d2i_X509(nullptr, &p, crt.length()); if (c) @@ -511,7 +530,7 @@ QByteArray CertWizard::exportCert(const Settings::KeyPair &kp) { i2d_PKCS12_bio(mem, pkcs); Q_UNUSED(BIO_flush(mem)); size = BIO_get_mem_data(mem, &data); - qba = QByteArray(data, static_cast<int>(size)); + qba = QByteArray(data, static_cast< int >(size)); } } } diff --git a/src/mumble/Cert.h b/src/mumble/Cert.h index 907192cb3..6dc39d47d 100644 --- a/src/mumble/Cert.h +++ b/src/mumble/Cert.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MUMBLE_CERT_H_ #define MUMBLE_MUMBLE_CERT_H_ -#include <QtCore/QtGlobal> #include <QtCore/QString> +#include <QtCore/QtGlobal> #include <QtWidgets/QGroupBox> #include <QtNetwork/QHostInfo> @@ -19,42 +19,44 @@ class QLabel; class QWidget; class CertView : public QGroupBox { - private: - Q_OBJECT - Q_DISABLE_COPY(CertView) - protected: - QList<QSslCertificate> qlCert; - QLabel *qlSubjectName, *qlSubjectEmail, *qlIssuerName, *qlExpiry; - public: - CertView(QWidget *p); - void setCert(const QList<QSslCertificate> &cert); +private: + Q_OBJECT + Q_DISABLE_COPY(CertView) +protected: + QList< QSslCertificate > qlCert; + QLabel *qlSubjectName, *qlSubjectEmail, *qlIssuerName, *qlExpiry; + +public: + CertView(QWidget *p); + void setCert(const QList< QSslCertificate > &cert); }; #include "ui_Cert.h" class CertWizard : public QWizard, public Ui::Certificates { - private: - Q_OBJECT - Q_DISABLE_COPY(CertWizard) - protected: - Settings::KeyPair kpCurrent, kpNew; - public: - CertWizard(QWidget *p = nullptr); - int nextId() const Q_DECL_OVERRIDE; - void initializePage(int) Q_DECL_OVERRIDE; - bool validateCurrentPage() Q_DECL_OVERRIDE; - static bool validateCert(const Settings::KeyPair &); - static Settings::KeyPair generateNewCert(QString name = QString(), const QString &email = QString()); - static QByteArray exportCert(const Settings::KeyPair &cert); - static Settings::KeyPair importCert(QByteArray, const QString & = QString()); - public slots: - void on_qleEmail_textChanged(const QString &); - void on_qpbExportFile_clicked(); - void on_qleExportFile_textChanged(const QString &); - void on_qpbImportFile_clicked(); - void on_qleImportFile_textChanged(const QString &); - void on_qlePassword_textChanged(const QString &); - void on_qlIntroText_linkActivated(const QString &); +private: + Q_OBJECT + Q_DISABLE_COPY(CertWizard) +protected: + Settings::KeyPair kpCurrent, kpNew; + +public: + CertWizard(QWidget *p = nullptr); + int nextId() const Q_DECL_OVERRIDE; + void initializePage(int) Q_DECL_OVERRIDE; + bool validateCurrentPage() Q_DECL_OVERRIDE; + static bool validateCert(const Settings::KeyPair &); + static Settings::KeyPair generateNewCert(QString name = QString(), const QString &email = QString()); + static QByteArray exportCert(const Settings::KeyPair &cert); + static Settings::KeyPair importCert(QByteArray, const QString & = QString()); +public slots: + void on_qleEmail_textChanged(const QString &); + void on_qpbExportFile_clicked(); + void on_qleExportFile_textChanged(const QString &); + void on_qpbImportFile_clicked(); + void on_qleImportFile_textChanged(const QString &); + void on_qlePassword_textChanged(const QString &); + void on_qlIntroText_linkActivated(const QString &); }; #endif diff --git a/src/mumble/ClientUser.cpp b/src/mumble/ClientUser.cpp index 33815039c..221cf36bd 100644 --- a/src/mumble/ClientUser.cpp +++ b/src/mumble/ClientUser.cpp @@ -5,27 +5,19 @@ #include "ClientUser.h" +#include "AudioOutput.h" #include "Channel.h" #include "Global.h" -#include "AudioOutput.h" -QHash<unsigned int, ClientUser *> ClientUser::c_qmUsers; +QHash< unsigned int, ClientUser * > ClientUser::c_qmUsers; QReadWriteLock ClientUser::c_qrwlUsers; -QList<ClientUser *> ClientUser::c_qlTalking; +QList< ClientUser * > ClientUser::c_qlTalking; QReadWriteLock ClientUser::c_qrwlTalking; -ClientUser::ClientUser(QObject *p) : QObject(p), - tsState(Settings::Passive), - tLastTalkStateChange(false), - bLocalIgnore(false), - bLocalIgnoreTTS(false), - bLocalMute(false), - fPowerMin(0.0f), - fPowerMax(0.0f), - fAverageAvailable(0.0f), - iFrames(0), - iSequence(0) { +ClientUser::ClientUser(QObject *p) + : QObject(p), tsState(Settings::Passive), tLastTalkStateChange(false), bLocalIgnore(false), bLocalIgnoreTTS(false), + bLocalMute(false), fPowerMin(0.0f), fPowerMax(0.0f), fAverageAvailable(0.0f), iFrames(0), iSequence(0) { } float ClientUser::getLocalVolumeAdjustments() const { @@ -38,15 +30,15 @@ ClientUser *ClientUser::get(unsigned int uiSession) { return p; } -QList<ClientUser *> ClientUser::getTalking() { +QList< ClientUser * > ClientUser::getTalking() { QReadLocker lock(&c_qrwlTalking); return c_qlTalking; } -QList<ClientUser *> ClientUser::getActive() { +QList< ClientUser * > ClientUser::getActive() { QReadLocker lock(&c_qrwlUsers); - QList<ClientUser *> activeUsers; - foreach(ClientUser *cu, c_qmUsers) { + QList< ClientUser * > activeUsers; + foreach (ClientUser *cu, c_qmUsers) { if (cu->isActive()) activeUsers << cu; } @@ -62,8 +54,8 @@ bool ClientUser::isValid(unsigned int uiSession) { ClientUser *ClientUser::add(unsigned int uiSession, QObject *po) { QWriteLocker lock(&c_qrwlUsers); - ClientUser *p = new ClientUser(po); - p->uiSession = uiSession; + ClientUser *p = new ClientUser(po); + p->uiSession = uiSession; c_qmUsers[uiSession] = p; return p; } @@ -72,7 +64,7 @@ ClientUser *ClientUser::match(const ClientUser *other, bool matchname) { QReadLocker lock(&c_qrwlUsers); ClientUser *p; - foreach(p, c_qmUsers) { + foreach (p, c_qmUsers) { if (p == other) continue; if ((p->iId >= 0) && (p->iId == other->iId)) @@ -113,7 +105,6 @@ void ClientUser::remove(unsigned int uiSession) { // deleted before this function returns anyways. ao->removeBuffer(p); } - } } @@ -124,7 +115,7 @@ void ClientUser::remove(ClientUser *p) { QString ClientUser::getFlagsString() const { QStringList flags; - if (! qsFriendName.isEmpty()) + if (!qsFriendName.isEmpty()) flags << ClientUser::tr("Friend"); if (iId >= 0) flags << ClientUser::tr("Authenticated"); @@ -177,7 +168,7 @@ void ClientUser::setMute(bool mute) { if (bMute == mute) return; bMute = mute; - if (! bMute) + if (!bMute) bDeaf = false; emit muteDeafStateChanged(); } @@ -216,7 +207,7 @@ void ClientUser::setDeaf(bool deaf) { void ClientUser::setSelfMute(bool mute) { bSelfMute = mute; - if (! mute) + if (!mute) bSelfDeaf = false; emit muteDeafStateChanged(); } @@ -244,7 +235,7 @@ void ClientUser::setRecording(bool recording) { void ClientUser::setLocalVolumeAdjustment(float adjustment) { float oldAdjustment = m_localVolume; - m_localVolume = adjustment; + m_localVolume = adjustment; emit localVolumeAdjustmentsChanged(m_localVolume, oldAdjustment); } @@ -295,7 +286,7 @@ bool ClientUser::lessThanOverlay(const ClientUser *first, const ClientUser *seco return Channel::lessThan(first->cChannel, second->cChannel); } -void ClientUser::sortUsersOverlay(QList<ClientUser *> &list) { +void ClientUser::sortUsersOverlay(QList< ClientUser * > &list) { QReadLocker lock(&c_qrwlUsers); std::sort(list.begin(), list.end(), ClientUser::lessThanOverlay); diff --git a/src/mumble/ClientUser.h b/src/mumble/ClientUser.h index f42c8071b..4b2ddab5f 100644 --- a/src/mumble/ClientUser.h +++ b/src/mumble/ClientUser.h @@ -6,86 +6,87 @@ #ifndef MUMBLE_MUMBLE_CLIENTUSER_H_ #define MUMBLE_MUMBLE_CLIENTUSER_H_ -#include <QtCore/QReadWriteLock> #include <QtCore/QHash> +#include <QtCore/QReadWriteLock> -#include "User.h" -#include "Timer.h" #include "Settings.h" +#include "Timer.h" +#include "User.h" class ClientUser : public QObject, public User { - private: - Q_OBJECT - Q_DISABLE_COPY(ClientUser) - - protected: - float m_localVolume = 1.0f; - - public: - Settings::TalkState tsState; - Timer tLastTalkStateChange; - bool bLocalIgnore; - bool bLocalIgnoreTTS; - bool bLocalMute; - - float fPowerMin, fPowerMax; - float fAverageAvailable; - - int iFrames; - int iSequence; - - QByteArray qbaTextureFormat; - QString qsFriendName; - - QString getFlagsString() const; - ClientUser(QObject *p = nullptr); - - float getLocalVolumeAdjustments() const; - - /** - * Determines whether a user is active or not - * A user is active when it is currently speaking or when the user has - * spoken within Settings::uiActiveTime amount of seconds. - */ - bool isActive(); - - static QHash<unsigned int, ClientUser *> c_qmUsers; - static QReadWriteLock c_qrwlUsers; - - static QList<ClientUser *> c_qlTalking; - static QReadWriteLock c_qrwlTalking; - static QList<ClientUser *> getTalking(); - static QList<ClientUser *> getActive(); - - static void sortUsersOverlay(QList<ClientUser *> &list); - - static ClientUser *get(unsigned int); - static bool isValid(unsigned int); - static ClientUser *add(unsigned int, QObject *p = nullptr); - static ClientUser *match(const ClientUser *p, bool matchname = false); - static void remove(unsigned int); - static void remove(ClientUser *); - protected: - static bool lessThanOverlay(const ClientUser *, const ClientUser *); - public slots: - void setTalking(Settings::TalkState ts); - void setMute(bool mute); - void setDeaf(bool deaf); - void setSuppress(bool suppress); - void setLocalIgnore(bool ignore); - void setLocalIgnoreTTS(bool ignoreTTS); - void setLocalMute(bool mute); - void setSelfMute(bool mute); - void setSelfDeaf(bool deaf); - void setPrioritySpeaker(bool priority); - void setRecording(bool recording); - void setLocalVolumeAdjustment(float adjustment); - signals: - void talkingStateChanged(); - void muteDeafStateChanged(); - void prioritySpeakerStateChanged(); - void recordingStateChanged(); - void localVolumeAdjustmentsChanged(float newAdjustment, float oldAdjustment); +private: + Q_OBJECT + Q_DISABLE_COPY(ClientUser) + +protected: + float m_localVolume = 1.0f; + +public: + Settings::TalkState tsState; + Timer tLastTalkStateChange; + bool bLocalIgnore; + bool bLocalIgnoreTTS; + bool bLocalMute; + + float fPowerMin, fPowerMax; + float fAverageAvailable; + + int iFrames; + int iSequence; + + QByteArray qbaTextureFormat; + QString qsFriendName; + + QString getFlagsString() const; + ClientUser(QObject *p = nullptr); + + float getLocalVolumeAdjustments() const; + + /** + * Determines whether a user is active or not + * A user is active when it is currently speaking or when the user has + * spoken within Settings::uiActiveTime amount of seconds. + */ + bool isActive(); + + static QHash< unsigned int, ClientUser * > c_qmUsers; + static QReadWriteLock c_qrwlUsers; + + static QList< ClientUser * > c_qlTalking; + static QReadWriteLock c_qrwlTalking; + static QList< ClientUser * > getTalking(); + static QList< ClientUser * > getActive(); + + static void sortUsersOverlay(QList< ClientUser * > &list); + + static ClientUser *get(unsigned int); + static bool isValid(unsigned int); + static ClientUser *add(unsigned int, QObject *p = nullptr); + static ClientUser *match(const ClientUser *p, bool matchname = false); + static void remove(unsigned int); + static void remove(ClientUser *); + +protected: + static bool lessThanOverlay(const ClientUser *, const ClientUser *); +public slots: + void setTalking(Settings::TalkState ts); + void setMute(bool mute); + void setDeaf(bool deaf); + void setSuppress(bool suppress); + void setLocalIgnore(bool ignore); + void setLocalIgnoreTTS(bool ignoreTTS); + void setLocalMute(bool mute); + void setSelfMute(bool mute); + void setSelfDeaf(bool deaf); + void setPrioritySpeaker(bool priority); + void setRecording(bool recording); + void setLocalVolumeAdjustment(float adjustment); +signals: + void talkingStateChanged(); + void muteDeafStateChanged(); + void prioritySpeakerStateChanged(); + void recordingStateChanged(); + void localVolumeAdjustmentsChanged(float newAdjustment, float oldAdjustment); }; #endif diff --git a/src/mumble/ConfigDialog.cpp b/src/mumble/ConfigDialog.cpp index ab01414ee..c27f0d0bf 100644 --- a/src/mumble/ConfigDialog.cpp +++ b/src/mumble/ConfigDialog.cpp @@ -9,16 +9,16 @@ #include "AudioOutput.h" #include "Global.h" +#include <QScrollArea> #include <QtCore/QMutexLocker> #include <QtGui/QScreen> -#include <QScrollArea> #include <QtWidgets/QDesktopWidget> #include <QtWidgets/QPushButton> // init static member fields QMutex ConfigDialog::s_existingWidgetsMutex; -QHash<QString, ConfigWidget *> ConfigDialog::s_existingWidgets; +QHash< QString, ConfigWidget * > ConfigDialog::s_existingWidgets; ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { setupUi(this); @@ -35,7 +35,7 @@ ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { unsigned int idx = 0; ConfigWidgetNew cwn; - foreach(cwn, *ConfigRegistrar::c_qmNew) { + foreach (cwn, *ConfigRegistrar::c_qmNew) { ConfigWidget *cw = cwn(s); { QMutexLocker lock(&s_existingWidgetsMutex); @@ -50,12 +50,12 @@ ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { QPushButton *okButton = dialogButtonBox->button(QDialogButtonBox::Ok); okButton->setToolTip(tr("Accept changes")); okButton->setWhatsThis(tr("This button will accept current settings and return to the application.<br />" - "The settings will be stored to disk when you leave the application.")); + "The settings will be stored to disk when you leave the application.")); QPushButton *cancelButton = dialogButtonBox->button(QDialogButtonBox::Cancel); cancelButton->setToolTip(tr("Reject changes")); cancelButton->setWhatsThis(tr("This button will reject all changes and return to the application.<br />" - "The settings will be reset to the previous positions.")); + "The settings will be reset to the previous positions.")); QPushButton *applyButton = dialogButtonBox->button(QDialogButtonBox::Apply); applyButton->setToolTip(tr("Apply changes")); @@ -63,17 +63,19 @@ ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { QPushButton *resetButton = pageButtonBox->button(QDialogButtonBox::Reset); resetButton->setToolTip(tr("Undo changes for current page")); - resetButton->setWhatsThis(tr("This button will revert any changes done on the current page to the most recent applied settings.")); + resetButton->setWhatsThis( + tr("This button will revert any changes done on the current page to the most recent applied settings.")); QPushButton *restoreButton = pageButtonBox->button(QDialogButtonBox::RestoreDefaults); restoreButton->setToolTip(tr("Restore defaults for current page")); - restoreButton->setWhatsThis(tr("This button will restore the defaults for the settings on the current page. Other pages will not be changed.<br />" - "To restore all settings to their defaults, you will have to use this button on every page." - )); + restoreButton->setWhatsThis( + tr("This button will restore the defaults for the settings on the current page. Other pages will not be " + "changed.<br />" + "To restore all settings to their defaults, you will have to use this button on every page.")); - if (! g.s.qbaConfigGeometry.isEmpty()) { + if (!g.s.qbaConfigGeometry.isEmpty()) { #ifdef USE_OVERLAY - if (! g.ocIntercept) + if (!g.ocIntercept) #endif restoreGeometry(g.s.qbaConfigGeometry); } @@ -82,7 +84,7 @@ ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { void ConfigDialog::addPage(ConfigWidget *cw, unsigned int idx) { int w = INT_MAX, h = INT_MAX; - const QList<QScreen *> screens = qApp->screens(); + const QList< QScreen * > screens = qApp->screens(); for (int i = 0; i < screens.size(); ++i) { const QRect ds = screens[i]->availableGeometry(); if (ds.isValid()) { @@ -91,14 +93,14 @@ void ConfigDialog::addPage(ConfigWidget *cw, unsigned int idx) { } } - QSize ms=cw->minimumSizeHint(); + QSize ms = cw->minimumSizeHint(); cw->resize(ms); cw->setMinimumSize(ms); ms.rwidth() += 128; ms.rheight() += 192; if ((ms.width() > w) || (ms.height() > h)) { - QScrollArea *qsa=new QScrollArea(); + QScrollArea *qsa = new QScrollArea(); qsa->setFrameShape(QFrame::NoFrame); qsa->setWidgetResizable(true); qsa->setWidget(cw); @@ -118,7 +120,7 @@ ConfigDialog::~ConfigDialog() { s_existingWidgets.clear(); } - foreach(QWidget *qw, qhPages) + foreach (QWidget *qw, qhPages) delete qw; } @@ -129,24 +131,24 @@ ConfigWidget *ConfigDialog::getConfigWidget(const QString &name) { } void ConfigDialog::on_pageButtonBox_clicked(QAbstractButton *b) { - ConfigWidget *conf = qobject_cast<ConfigWidget *>(qswPages->currentWidget()); - if (! conf) { - QScrollArea *qsa = qobject_cast<QScrollArea *>(qswPages->currentWidget()); + ConfigWidget *conf = qobject_cast< ConfigWidget * >(qswPages->currentWidget()); + if (!conf) { + QScrollArea *qsa = qobject_cast< QScrollArea * >(qswPages->currentWidget()); if (qsa) - conf = qobject_cast<ConfigWidget *>(qsa->widget()); + conf = qobject_cast< ConfigWidget * >(qsa->widget()); } - if (! conf) + if (!conf) return; switch (pageButtonBox->standardButton(b)) { case QDialogButtonBox::RestoreDefaults: { - Settings def; - conf->load(def); - break; - } + Settings def; + conf->load(def); + break; + } case QDialogButtonBox::Reset: { - conf->load(g.s); - break; - } + conf->load(g.s); + break; + } default: break; } @@ -155,9 +157,9 @@ void ConfigDialog::on_pageButtonBox_clicked(QAbstractButton *b) { void ConfigDialog::on_dialogButtonBox_clicked(QAbstractButton *b) { switch (dialogButtonBox->standardButton(b)) { case QDialogButtonBox::Apply: { - apply(); - break; - } + apply(); + break; + } default: break; } @@ -175,7 +177,7 @@ void ConfigDialog::on_qlwIcons_currentItemChanged(QListWidgetItem *current, QLis } void ConfigDialog::updateListView() { - QWidget *ccw = qmIconWidgets.value(qlwIcons->currentItem()); + QWidget *ccw = qmIconWidgets.value(qlwIcons->currentItem()); QListWidgetItem *sel = nullptr; qmIconWidgets.clear(); @@ -184,7 +186,7 @@ void ConfigDialog::updateListView() { QFontMetrics qfm(qlwIcons->font()); int configNavbarWidth = 0; - foreach(ConfigWidget *cw, qmWidgets) { + foreach (ConfigWidget *cw, qmWidgets) { #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) configNavbarWidth = qMax(configNavbarWidth, qfm.horizontalAdvance(cw->title())); #else @@ -216,14 +218,14 @@ void ConfigDialog::updateListView() { void ConfigDialog::apply() { Audio::stop(); - foreach(ConfigWidget *cw, qmWidgets) + foreach (ConfigWidget *cw, qmWidgets) cw->save(); g.s = s; - foreach(ConfigWidget *cw, qmWidgets) + foreach (ConfigWidget *cw, qmWidgets) cw->accept(); - + if (!g.s.bAttenuateOthersOnTalk) g.bAttenuateOthers = false; @@ -239,9 +241,9 @@ void ConfigDialog::accept() { apply(); #ifdef USE_OVERLAY - if (! g.ocIntercept) + if (!g.ocIntercept) #endif - g.s.qbaConfigGeometry=saveGeometry(); + g.s.qbaConfigGeometry = saveGeometry(); QDialog::accept(); } diff --git a/src/mumble/ConfigDialog.h b/src/mumble/ConfigDialog.h index 9917b8183..528c3c7dd 100644 --- a/src/mumble/ConfigDialog.h +++ b/src/mumble/ConfigDialog.h @@ -14,37 +14,37 @@ #include <QtCore/QMutex> class ConfigDialog : public QDialog, public Ui::ConfigDialog { - private: - Q_OBJECT - Q_DISABLE_COPY(ConfigDialog) - protected: - static QMutex s_existingWidgetsMutex; - static QHash<QString, ConfigWidget *> s_existingWidgets; - QHash<ConfigWidget *, QWidget *> qhPages; - QMap<unsigned int, ConfigWidget *> qmWidgets; - QMap<QListWidgetItem *, ConfigWidget *> qmIconWidgets; - void updateListView(); - void addPage(ConfigWidget *aw, unsigned int idx); - Settings s; - - public: - ConfigDialog(QWidget *p = nullptr); - ~ConfigDialog() Q_DECL_OVERRIDE; - - /// @returns The pointer to the existing ConfigWidget with the given name or nullptr, - /// if no such widget exists. - static ConfigWidget *getConfigWidget(const QString &name); - - signals: - /// Emitted whenever the settings dialog has been accepted. For potential slots this - /// means that the settings potentially have changed. - void settingsAccepted(); - public slots: - void on_pageButtonBox_clicked(QAbstractButton *); - void on_dialogButtonBox_clicked(QAbstractButton *); - void on_qlwIcons_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); - void apply(); - void accept() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(ConfigDialog) +protected: + static QMutex s_existingWidgetsMutex; + static QHash< QString, ConfigWidget * > s_existingWidgets; + QHash< ConfigWidget *, QWidget * > qhPages; + QMap< unsigned int, ConfigWidget * > qmWidgets; + QMap< QListWidgetItem *, ConfigWidget * > qmIconWidgets; + void updateListView(); + void addPage(ConfigWidget *aw, unsigned int idx); + Settings s; + +public: + ConfigDialog(QWidget *p = nullptr); + ~ConfigDialog() Q_DECL_OVERRIDE; + + /// @returns The pointer to the existing ConfigWidget with the given name or nullptr, + /// if no such widget exists. + static ConfigWidget *getConfigWidget(const QString &name); + +signals: + /// Emitted whenever the settings dialog has been accepted. For potential slots this + /// means that the settings potentially have changed. + void settingsAccepted(); +public slots: + void on_pageButtonBox_clicked(QAbstractButton *); + void on_dialogButtonBox_clicked(QAbstractButton *); + void on_qlwIcons_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); + void apply(); + void accept() Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/ConfigWidget.cpp b/src/mumble/ConfigWidget.cpp index d0dee7b13..015a25685 100644 --- a/src/mumble/ConfigWidget.cpp +++ b/src/mumble/ConfigWidget.cpp @@ -13,13 +13,13 @@ #include <QtWidgets/QComboBox> #include <QtWidgets/QSlider> -QMap<int, ConfigWidgetNew> *ConfigRegistrar::c_qmNew; +QMap< int, ConfigWidgetNew > *ConfigRegistrar::c_qmNew; ConfigRegistrar::ConfigRegistrar(int priority, ConfigWidgetNew n) { - if (! c_qmNew) - c_qmNew = new QMap<int, ConfigWidgetNew>(); + if (!c_qmNew) + c_qmNew = new QMap< int, ConfigWidgetNew >(); iPriority = priority; - c_qmNew->insert(priority,n); + c_qmNew->insert(priority, n); } ConfigRegistrar::~ConfigRegistrar() { @@ -69,4 +69,3 @@ void ConfigWidget::loadComboBox(QComboBox *c, int v) { disconnect(SIGNAL(intSignal(int))); } } - diff --git a/src/mumble/ConfigWidget.h b/src/mumble/ConfigWidget.h index 6645bcbaf..12a5a4029 100644 --- a/src/mumble/ConfigWidget.h +++ b/src/mumble/ConfigWidget.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MUMBLE_CONFIGWIDGET_H_ #define MUMBLE_MUMBLE_CONFIGWIDGET_H_ -#include <QtCore/QtGlobal> #include <QtCore/QObject> +#include <QtCore/QtGlobal> #include <QtWidgets/QWidget> struct Settings; @@ -17,40 +17,43 @@ class QAbstractButton; class QComboBox; class ConfigWidget : public QWidget { - private: - Q_OBJECT - Q_DISABLE_COPY(ConfigWidget) - protected: - void loadSlider(QSlider *, int); - void loadCheckBox(QAbstractButton *, bool); - void loadComboBox(QComboBox *, int); - signals: - void intSignal(int); - public: - Settings &s; - ConfigWidget(Settings &st); - virtual QString title() const = 0; - virtual const QString &getName() const = 0; - virtual QIcon icon() const; - public slots: - virtual void accept() const; - virtual void save() const = 0; - virtual void load(const Settings &r) = 0; +private: + Q_OBJECT + Q_DISABLE_COPY(ConfigWidget) +protected: + void loadSlider(QSlider *, int); + void loadCheckBox(QAbstractButton *, bool); + void loadComboBox(QComboBox *, int); +signals: + void intSignal(int); + +public: + Settings &s; + ConfigWidget(Settings &st); + virtual QString title() const = 0; + virtual const QString &getName() const = 0; + virtual QIcon icon() const; +public slots: + virtual void accept() const; + virtual void save() const = 0; + virtual void load(const Settings &r) = 0; }; typedef ConfigWidget *(*ConfigWidgetNew)(Settings &st); class ConfigRegistrar Q_DECL_FINAL { - friend class ConfigDialog; - friend class ConfigDialogMac; - private: - Q_DISABLE_COPY(ConfigRegistrar) - protected: - int iPriority; - static QMap<int, ConfigWidgetNew> *c_qmNew; - public: - ConfigRegistrar(int priority, ConfigWidgetNew n); - ~ConfigRegistrar(); + friend class ConfigDialog; + friend class ConfigDialogMac; + +private: + Q_DISABLE_COPY(ConfigRegistrar) +protected: + int iPriority; + static QMap< int, ConfigWidgetNew > *c_qmNew; + +public: + ConfigRegistrar(int priority, ConfigWidgetNew n); + ~ConfigRegistrar(); }; #endif diff --git a/src/mumble/ConnectDialog.cpp b/src/mumble/ConnectDialog.cpp index f5a548b5a..941b130f2 100644 --- a/src/mumble/ConnectDialog.cpp +++ b/src/mumble/ConnectDialog.cpp @@ -6,17 +6,17 @@ #include "ConnectDialog.h" #ifdef USE_BONJOUR -#include "BonjourClient.h" -#include "BonjourServiceBrowser.h" -#include "BonjourServiceResolver.h" +# include "BonjourClient.h" +# include "BonjourServiceBrowser.h" +# include "BonjourServiceResolver.h" #endif #include "Channel.h" #include "Database.h" #include "ServerHandler.h" -#include "WebFetch.h" #include "ServerResolver.h" #include "Utils.h" +#include "WebFetch.h" #include <QtCore/QMimeData> #include <QtCore/QUrlQuery> @@ -35,18 +35,19 @@ #include <boost/array.hpp> #ifdef Q_OS_WIN -# include <shlobj.h> +# include <shlobj.h> #endif -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - #include <QRandomGenerator> +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) +# include <QRandomGenerator> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -QMap<QString, QIcon> ServerItem::qmIcons; -QList<PublicInfo> ConnectDialog::qlPublicServers; +QMap< QString, QIcon > ServerItem::qmIcons; +QList< PublicInfo > ConnectDialog::qlPublicServers; QString ConnectDialog::qsUserCountry, ConnectDialog::qsUserCountryCode, ConnectDialog::qsUserContinentCode; Timer ConnectDialog::tPublicServers; @@ -60,18 +61,18 @@ PingStats::~PingStats() { } void PingStats::init() { - boost::array<double, 3> probs = {{0.75, 0.80, 0.95 }}; - - asQuantile = new asQuantileType(boost::accumulators::tag::extended_p_square::probabilities = probs); - dPing = 0.0; - uiPing = 0; - uiPingSort = 0; - uiUsers = 0; - uiMaxUsers = 0; + boost::array< double, 3 > probs = { { 0.75, 0.80, 0.95 } }; + + asQuantile = new asQuantileType(boost::accumulators::tag::extended_p_square::probabilities = probs); + dPing = 0.0; + uiPing = 0; + uiPingSort = 0; + uiUsers = 0; + uiMaxUsers = 0; uiBandwidth = 0; - uiSent = 0; - uiRecv = 0; - uiVersion = 0; + uiSent = 0; + uiRecv = 0; + uiVersion = 0; } void PingStats::reset() { @@ -89,7 +90,7 @@ void ServerViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op // Allow a ServerItem's BackgroundRole to override the current theme's default color. QVariant bg = index.data(Qt::BackgroundRole); if (bg.isValid()) { - painter->fillRect(option.rect, bg.value<QBrush>()); + painter->fillRect(option.rect, bg.value< QBrush >()); } QStyledItemDelegate::paint(painter, option, index); @@ -107,7 +108,7 @@ ServerView::ServerView(QWidget *p) : QTreeWidget(p) { siLAN->setExpanded(true); siLAN->setHidden(true); #else - siLAN = nullptr; + siLAN = nullptr; #endif if (!g.s.bDisablePublicList) { @@ -117,7 +118,7 @@ ServerView::ServerView(QWidget *p) : QTreeWidget(p) { siPublic->setExpanded(false); } else { - qWarning()<< "Public list disabled"; + qWarning() << "Public list disabled"; siPublic = nullptr; } @@ -129,11 +130,11 @@ ServerView::~ServerView() { delete siPublic; } -QMimeData *ServerView::mimeData(const QList<QTreeWidgetItem *> mimeitems) const { +QMimeData *ServerView::mimeData(const QList< QTreeWidgetItem * > mimeitems) const { if (mimeitems.isEmpty()) return nullptr; - ServerItem *si = static_cast<ServerItem *>(mimeitems.first()); + ServerItem *si = static_cast< ServerItem * >(mimeitems.first()); return si->toMimeData(); } @@ -158,7 +159,7 @@ void ServerView::fixupName(ServerItem *si) { tmatch.setMinimal(true); if (tmatch.exactMatch(name)) { name = tmatch.capturedTexts().at(1).trimmed(); - tag = tmatch.capturedTexts().at(2).toInt(); + tag = tmatch.capturedTexts().at(2).toInt(); } bool found; @@ -170,7 +171,7 @@ void ServerView::fixupName(ServerItem *si) { else cmpname = name; - foreach(ServerItem *f, siFavorite->qlChildren) + foreach (ServerItem *f, siFavorite->qlChildren) if (f->qsName == cmpname) found = true; @@ -182,15 +183,15 @@ void ServerView::fixupName(ServerItem *si) { bool ServerView::dropMimeData(QTreeWidgetItem *, int, const QMimeData *mime, Qt::DropAction) { ServerItem *si = ServerItem::fromMimeData(mime); - if (! si) + if (!si) return false; fixupName(si); - qobject_cast<ConnectDialog *>(parent())->qlItems << si; + qobject_cast< ConnectDialog * >(parent())->qlItems << si; siFavorite->addServerItem(si); - qobject_cast<ConnectDialog *>(parent())->startDns(si); + qobject_cast< ConnectDialog * >(parent())->startDns(si); setCurrentItem(si); @@ -207,7 +208,7 @@ void ServerItem::init() { ServerItem::ServerItem(const FavoriteServer &fs) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = nullptr; - bParent = false; + bParent = false; itType = FavoriteType; qsName = fs.qsName; @@ -222,38 +223,40 @@ ServerItem::ServerItem(const FavoriteServer &fs) : QTreeWidgetItem(QTreeWidgetIt #ifdef USE_BONJOUR if (fs.qsHostname.startsWith(QLatin1Char('@'))) { qsBonjourHost = fs.qsHostname.mid(1); - brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); + brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { qsHostname = fs.qsHostname; } #else - qsHostname = fs.qsHostname; + qsHostname = fs.qsHostname; #endif init(); } ServerItem::ServerItem(const PublicInfo &pi) : QTreeWidgetItem(QTreeWidgetItem::UserType) { - siParent = nullptr; - bParent = false; - itType = PublicType; - qsName = pi.qsName; - qsHostname = pi.qsIp; - usPort = pi.usPort; - qsUrl = pi.quUrl.toString(); - qsCountry = pi.qsCountry; - qsCountryCode = pi.qsCountryCode; + siParent = nullptr; + bParent = false; + itType = PublicType; + qsName = pi.qsName; + qsHostname = pi.qsIp; + usPort = pi.usPort; + qsUrl = pi.quUrl.toString(); + qsCountry = pi.qsCountry; + qsCountryCode = pi.qsCountryCode; qsContinentCode = pi.qsContinentCode; - bCA = pi.bCA; + bCA = pi.bCA; init(); } -ServerItem::ServerItem(const QString &name, const QString &host, unsigned short port, const QString &username, const QString &password) : QTreeWidgetItem(QTreeWidgetItem::UserType) { - siParent = nullptr; - bParent = false; - itType = FavoriteType; - qsName = name; - usPort = port; +ServerItem::ServerItem(const QString &name, const QString &host, unsigned short port, const QString &username, + const QString &password) + : QTreeWidgetItem(QTreeWidgetItem::UserType) { + siParent = nullptr; + bParent = false; + itType = FavoriteType; + qsName = name; + usPort = port; qsUsername = username; qsPassword = password; @@ -261,26 +264,26 @@ ServerItem::ServerItem(const QString &name, const QString &host, unsigned short #ifdef USE_BONJOUR if (host.startsWith(QLatin1Char('@'))) { qsBonjourHost = host.mid(1); - brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); + brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { qsHostname = host; } #else - qsHostname = host; + qsHostname = host; #endif init(); } #ifdef USE_BONJOUR ServerItem::ServerItem(const BonjourRecord &br) : QTreeWidgetItem(QTreeWidgetItem::UserType) { - siParent = nullptr; - bParent = false; - itType = LANType; - qsName = br.serviceName; + siParent = nullptr; + bParent = false; + itType = LANType; + qsName = br.serviceName; qsBonjourHost = qsName; - brRecord = br; - usPort = 0; - bCA = false; + brRecord = br; + usPort = 0; + bCA = false; init(); } @@ -288,9 +291,9 @@ ServerItem::ServerItem(const BonjourRecord &br) : QTreeWidgetItem(QTreeWidgetIte ServerItem::ServerItem(const QString &name, ItemType itype) { siParent = nullptr; - bParent = true; - qsName = name; - itType = itype; + bParent = true; + qsName = name; + itType = itype; setFlags(flags() & ~Qt::ItemIsDragEnabled); bCA = false; @@ -299,34 +302,34 @@ ServerItem::ServerItem(const QString &name, ItemType itype) { ServerItem::ServerItem(const ServerItem *si) { siParent = nullptr; - bParent = false; - itType = FavoriteType; - - qsName = si->qsName; - qsHostname = si->qsHostname; - usPort = si->usPort; - qsUsername = si->qsUsername; - qsPassword = si->qsPassword; - qsCountry = si->qsCountry; - qsCountryCode = si->qsCountryCode; + bParent = false; + itType = FavoriteType; + + qsName = si->qsName; + qsHostname = si->qsHostname; + usPort = si->usPort; + qsUsername = si->qsUsername; + qsPassword = si->qsPassword; + qsCountry = si->qsCountry; + qsCountryCode = si->qsCountryCode; qsContinentCode = si->qsContinentCode; - qsUrl = si->qsUrl; + qsUrl = si->qsUrl; #ifdef USE_BONJOUR qsBonjourHost = si->qsBonjourHost; - brRecord = si->brRecord; + brRecord = si->brRecord; #endif qlAddresses = si->qlAddresses; - bCA = si->bCA; + bCA = si->bCA; - uiVersion = si->uiVersion; - uiPing = si->uiPing; - uiPingSort = si->uiPing; - uiUsers = si->uiUsers; - uiMaxUsers = si->uiMaxUsers; + uiVersion = si->uiVersion; + uiPing = si->uiPing; + uiPingSort = si->uiPing; + uiUsers = si->uiUsers; + uiMaxUsers = si->uiMaxUsers; uiBandwidth = si->uiBandwidth; - uiSent = si->uiSent; - dPing = si->dPing; - *asQuantile = * si->asQuantile; + uiSent = si->uiSent; + dPing = si->dPing; + *asQuantile = *si->asQuantile; } ServerItem::~ServerItem() { @@ -337,7 +340,7 @@ ServerItem::~ServerItem() { } // This is just for cleanup when exiting the dialog, it won't stop pending DNS for the children. - foreach(ServerItem *si, qlChildren) + foreach (ServerItem *si, qlChildren) delete si; } @@ -346,13 +349,13 @@ ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, Q return nullptr; QUrl url; - if (mime->hasUrls() && ! mime->urls().isEmpty()) + if (mime->hasUrls() && !mime->urls().isEmpty()) url = mime->urls().at(0); else if (mime->hasText()) url = QUrl::fromEncoded(mime->text().toUtf8()); QString qsFile = url.toLocalFile(); - if (! qsFile.isEmpty()) { + if (!qsFile.isEmpty()) { QFile f(qsFile); // Make sure we don't accidently read something big the user // happened to have in his clipboard. We only want to look @@ -362,22 +365,23 @@ ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, Q f.close(); url = QUrl::fromEncoded(qba, QUrl::StrictMode); - if (! url.isValid()) { + if (!url.isValid()) { // Windows internet shortcut files (.url) are an ini with an URL value QSettings qs(qsFile, QSettings::IniFormat); - url = QUrl::fromEncoded(qs.value(QLatin1String("InternetShortcut/URL")).toByteArray(), QUrl::StrictMode); + url = + QUrl::fromEncoded(qs.value(QLatin1String("InternetShortcut/URL")).toByteArray(), QUrl::StrictMode); } } } if (default_name) { QUrlQuery query(url); - if (! query.hasQueryItem(QLatin1String("title"))) { + if (!query.hasQueryItem(QLatin1String("title"))) { query.addQueryItem(QLatin1String("title"), url.host()); } } - if (! url.isValid()) { + if (!url.isValid()) { return nullptr; } @@ -390,9 +394,7 @@ ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, Q // Some communication programs automatically create http links from domains. // When a user sends another user a domain to connect to, and http is added wrongly, // we do our best to remove it again. - if (convertHttpUrls && ( - url.scheme() == QLatin1String("http") - || url.scheme() == QLatin1String("https"))) { + if (convertHttpUrls && (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("https"))) { url.setScheme(QLatin1String("mumble")); } @@ -400,7 +402,7 @@ ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, Q } ServerItem *ServerItem::fromUrl(QUrl url, QWidget *p) { - if (! url.isValid() || (url.scheme() != QLatin1String("mumble"))) { + if (!url.isValid() || (url.scheme() != QLatin1String("mumble"))) { return nullptr; } @@ -409,8 +411,11 @@ ServerItem *ServerItem::fromUrl(QUrl url, QWidget *p) { if (url.userName().isEmpty()) { if (g.s.qsUsername.isEmpty()) { bool ok; - QString defUserName = QInputDialog::getText(p, ConnectDialog::tr("Adding host %1").arg(url.host()), ConnectDialog::tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed(); - if (! ok) + QString defUserName = + QInputDialog::getText(p, ConnectDialog::tr("Adding host %1").arg(url.host()), + ConnectDialog::tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok) + .trimmed(); + if (!ok) return nullptr; if (defUserName.isEmpty()) return nullptr; @@ -419,7 +424,9 @@ ServerItem *ServerItem::fromUrl(QUrl url, QWidget *p) { url.setUserName(g.s.qsUsername); } - ServerItem *si = new ServerItem(query.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); + ServerItem *si = + new ServerItem(query.queryItemValue(QLatin1String("title")), url.host(), + static_cast< unsigned short >(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); if (query.hasQueryItem(QLatin1String("url"))) si->qsUrl = query.queryItemValue(QLatin1String("url")); @@ -445,10 +452,10 @@ QVariant ServerItem::data(int column, int role) const { } else { if (role == Qt::DecorationRole && column == 0) { QString flag; - if (! qsCountryCode.isEmpty()) { - flag = QString::fromLatin1(":/flags/%1.svg").arg(qsCountryCode); - if (!QFileInfo(flag).exists()) { - flag = QLatin1String("skin:categories/applications-internet.svg"); + if (!qsCountryCode.isEmpty()) { + flag = QString::fromLatin1(":/flags/%1.svg").arg(qsCountryCode); + if (!QFileInfo(flag).exists()) { + flag = QLatin1String("skin:categories/applications-internet.svg"); } } else { flag = QLatin1String("skin:categories/applications-internet.svg"); @@ -466,8 +473,9 @@ QVariant ServerItem::data(int column, int role) const { } } else if (role == Qt::ToolTipRole) { QStringList qsl; - foreach(const ServerAddress &addr, qlAddresses) { - const QString qsAddress = addr.host.toString() + QLatin1String(":") + QString::number(static_cast<unsigned long>(addr.port)); + foreach (const ServerAddress &addr, qlAddresses) { + const QString qsAddress = addr.host.toString() + QLatin1String(":") + + QString::number(static_cast< unsigned long >(addr.port)); qsl << qsAddress.toHtmlEscaped(); } @@ -477,32 +485,48 @@ QVariant ServerItem::data(int column, int role) const { ploss = (uiSent - qMin(uiRecv, uiSent)) * 100. / uiSent; QString qs; - qs += - QLatin1String("<table>") + - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Servername"), qsName.toHtmlEscaped()) + - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Hostname"), qsHostname.toHtmlEscaped()); + qs += QLatin1String("<table>") + + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Servername"), qsName.toHtmlEscaped()) + + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Hostname"), qsHostname.toHtmlEscaped()); #ifdef USE_BONJOUR - if (! qsBonjourHost.isEmpty()) - qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bonjour name"), qsBonjourHost.toHtmlEscaped()); + if (!qsBonjourHost.isEmpty()) + qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Bonjour name"), qsBonjourHost.toHtmlEscaped()); #endif - qs += - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Port")).arg(usPort) + - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Addresses"), qsl.join(QLatin1String(", "))); + qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Port")) + .arg(usPort) + + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Addresses"), qsl.join(QLatin1String(", "))); - if (! qsUrl.isEmpty()) - qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Website"), qsUrl.toHtmlEscaped()); + if (!qsUrl.isEmpty()) + qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Website"), qsUrl.toHtmlEscaped()); if (uiSent > 0) { - qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Packet loss"), QString::fromLatin1("%1% (%2/%3)").arg(ploss, 0, 'f', 1).arg(uiRecv).arg(uiSent)); + qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Packet loss"), + QString::fromLatin1("%1% (%2/%3)").arg(ploss, 0, 'f', 1).arg(uiRecv).arg(uiSent)); if (uiRecv > 0) { - qs += - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (80%)"), ConnectDialog::tr("%1 ms"). - arg(boost::accumulators::extended_p_square(* asQuantile)[1] / 1000., 0, 'f', 2)) + - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (95%)"), ConnectDialog::tr("%1 ms"). - arg(boost::accumulators::extended_p_square(* asQuantile)[2] / 1000., 0, 'f', 2)) + - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bandwidth"), ConnectDialog::tr("%1 kbit/s").arg(uiBandwidth / 1000)) + - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Users"), QString::fromLatin1("%1/%2").arg(uiUsers).arg(uiMaxUsers)) + - QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Version")).arg(MumbleVersion::toString(uiVersion)); + qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Ping (80%)"), + ConnectDialog::tr("%1 ms").arg( + boost::accumulators::extended_p_square(*asQuantile)[1] / 1000., 0, 'f', 2)) + + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Ping (95%)"), + ConnectDialog::tr("%1 ms").arg( + boost::accumulators::extended_p_square(*asQuantile)[2] / 1000., 0, 'f', 2)) + + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Bandwidth"), + ConnectDialog::tr("%1 kbit/s").arg(uiBandwidth / 1000)) + + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Users"), + QString::fromLatin1("%1/%2").arg(uiUsers).arg(uiMaxUsers)) + + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>") + .arg(ConnectDialog::tr("Version")) + .arg(MumbleVersion::toString(uiVersion)); } } qs += QLatin1String("</table>"); @@ -527,7 +551,7 @@ void ServerItem::addServerItem(ServerItem *childitem) { // Public servers must initially be hidden for the search to work properly // They will be set to visible later on if (childitem->itType == PublicType) { - childitem->setHidden(true); + childitem->setHidden(true); } if (bParent && (itType != PublicType) && isHidden()) { @@ -541,22 +565,22 @@ void ServerItem::setDatas(double elapsed, quint32 users, quint32 maxusers) { return; } - (*asQuantile)(static_cast<double>(elapsed)); + (*asQuantile)(static_cast< double >(elapsed)); dPing = boost::accumulators::extended_p_square(*asQuantile)[0]; if (dPing == 0.0) dPing = elapsed; - quint32 ping = static_cast<quint32>(lround(dPing / 1000.)); - uiRecv = static_cast<quint32>(boost::accumulators::count(* asQuantile)); + quint32 ping = static_cast< quint32 >(lround(dPing / 1000.)); + uiRecv = static_cast< quint32 >(boost::accumulators::count(*asQuantile)); bool changed = (ping != uiPing) || (users != uiUsers) || (maxusers != uiMaxUsers); - uiUsers = users; + uiUsers = users; uiMaxUsers = maxusers; - uiPing = ping; + uiPing = ping; double grace = qMax(5000., 50. * uiPingSort); - double diff = fabs(1000. * uiPingSort - dPing); + double diff = fabs(1000. * uiPingSort - dPing); if ((uiPingSort == 0) || ((uiSent >= 10) && (diff >= grace))) uiPingSort = ping; @@ -569,17 +593,17 @@ FavoriteServer ServerItem::toFavoriteServer() const { FavoriteServer fs; fs.qsName = qsName; #ifdef USE_BONJOUR - if (! qsBonjourHost.isEmpty()) + if (!qsBonjourHost.isEmpty()) fs.qsHostname = QLatin1Char('@') + qsBonjourHost; else fs.qsHostname = qsHostname; #else fs.qsHostname = qsHostname; #endif - fs.usPort = usPort; + fs.usPort = usPort; fs.qsUsername = qsUsername; fs.qsPassword = qsPassword; - fs.qsUrl = qsUrl; + fs.qsUrl = qsUrl; return fs; } @@ -600,7 +624,8 @@ QMimeData *ServerItem::toMimeData() const { * query string as "title", which is used for adding a server to favorites. channel may be omitted, but if specified it * should be in the format of "/path/to/channel". */ -QMimeData *ServerItem::toMimeData(const QString &name, const QString &host, unsigned short port, const QString &channel) { +QMimeData *ServerItem::toMimeData(const QString &name, const QString &host, unsigned short port, + const QString &channel) { QUrl url; url.setScheme(QLatin1String("mumble")); url.setHost(host); @@ -619,23 +644,25 @@ QMimeData *ServerItem::toMimeData(const QString &name, const QString &host, unsi #ifdef Q_OS_WIN QString contents = QString::fromLatin1("[InternetShortcut]\r\nURL=%1\r\n").arg(qs); - QString urlname = QString::fromLatin1("%1.url").arg(name); + QString urlname = QString::fromLatin1("%1.url").arg(name); FILEGROUPDESCRIPTORA fgda; ZeroMemory(&fgda, sizeof(fgda)); - fgda.cItems = 1; - fgda.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; - fgda.fgd[0].nFileSizeLow=contents.length(); + fgda.cItems = 1; + fgda.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; + fgda.fgd[0].nFileSizeLow = contents.length(); strcpy_s(fgda.fgd[0].cFileName, MAX_PATH, urlname.toLocal8Bit().constData()); - mime->setData(QLatin1String("FileGroupDescriptor"), QByteArray(reinterpret_cast<const char *>(&fgda), sizeof(fgda))); + mime->setData(QLatin1String("FileGroupDescriptor"), + QByteArray(reinterpret_cast< const char * >(&fgda), sizeof(fgda))); FILEGROUPDESCRIPTORW fgdw; ZeroMemory(&fgdw, sizeof(fgdw)); - fgdw.cItems = 1; - fgdw.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; - fgdw.fgd[0].nFileSizeLow=contents.length(); + fgdw.cItems = 1; + fgdw.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; + fgdw.fgd[0].nFileSizeLow = contents.length(); wcscpy_s(fgdw.fgd[0].cFileName, MAX_PATH, urlname.toStdWString().c_str()); - mime->setData(QLatin1String("FileGroupDescriptorW"), QByteArray(reinterpret_cast<const char *>(&fgdw), sizeof(fgdw))); + mime->setData(QLatin1String("FileGroupDescriptorW"), + QByteArray(reinterpret_cast< const char * >(&fgdw), sizeof(fgdw))); mime->setData(QString::fromWCharArray(CFSTR_FILECONTENTS), contents.toLocal8Bit()); @@ -644,13 +671,15 @@ QMimeData *ServerItem::toMimeData(const QString &name, const QString &host, unsi context[1] = 1; context[2] = 0; context[3] = 0; - mime->setData(QLatin1String("DragContext"), QByteArray(reinterpret_cast<const char *>(&context[0]), sizeof(context))); + mime->setData(QLatin1String("DragContext"), + QByteArray(reinterpret_cast< const char * >(&context[0]), sizeof(context))); DWORD dropaction; dropaction = DROPEFFECT_LINK; - mime->setData(QString::fromWCharArray(CFSTR_PREFERREDDROPEFFECT), QByteArray(reinterpret_cast<const char *>(&dropaction), sizeof(dropaction))); + mime->setData(QString::fromWCharArray(CFSTR_PREFERREDDROPEFFECT), + QByteArray(reinterpret_cast< const char * >(&dropaction), sizeof(dropaction))); #endif - QList<QUrl> urls; + QList< QUrl > urls; urls << url; mime->setUrls(urls); @@ -660,9 +689,9 @@ QMimeData *ServerItem::toMimeData(const QString &name, const QString &host, unsi return mime; } -bool ServerItem::operator <(const QTreeWidgetItem &o) const { - const ServerItem &other = static_cast<const ServerItem &>(o); - const QTreeWidget *w = treeWidget(); +bool ServerItem::operator<(const QTreeWidgetItem &o) const { + const ServerItem &other = static_cast< const ServerItem & >(o); + const QTreeWidget *w = treeWidget(); const int column = w ? w->sortColumn() : 0; @@ -703,16 +732,18 @@ bool ServerItem::operator <(const QTreeWidgetItem &o) const { } QIcon ServerItem::loadIcon(const QString &name) { - if (! qmIcons.contains(name)) + if (!qmIcons.contains(name)) qmIcons.insert(name, QIcon(name)); return qmIcons.value(name); } -ConnectDialogEdit::ConnectDialogEdit(QWidget *p, const QString &name, const QString &host, const QString &user, unsigned short port, const QString &password) : QDialog(p) { +ConnectDialogEdit::ConnectDialogEdit(QWidget *p, const QString &name, const QString &host, const QString &user, + unsigned short port, const QString &password) + : QDialog(p) { setupUi(this); init(); - bCustomLabel = ! name.simplified().isEmpty(); + bCustomLabel = !name.simplified().isEmpty(); qleName->setText(name); qleServer->setText(host); @@ -740,7 +771,10 @@ ConnectDialogEdit::ConnectDialogEdit(QWidget *parent) : QDialog(parent) { name = c->qsName; } - showNotice(tr("You are currently connected to a server.\nDo you want to fill the dialog with the connection data of this server?\nHost: %1 Port: %2").arg(host).arg(port)); + showNotice(tr("You are currently connected to a server.\nDo you want to fill the dialog with the " + "connection data of this server?\nHost: %1 Port: %2") + .arg(host) + .arg(port)); m_si = new ServerItem(name, host, port, user, pw); } } @@ -748,9 +782,9 @@ ConnectDialogEdit::ConnectDialogEdit(QWidget *parent) : QDialog(parent) { } void ConnectDialogEdit::init() { - m_si = nullptr; - usPort = 0; - bOk = true; + m_si = nullptr; + usPort = 0; + bOk = true; bCustomLabel = false; qwInlineNotice->hide(); @@ -773,7 +807,7 @@ ConnectDialogEdit::~ConnectDialogEdit() { } void ConnectDialogEdit::showNotice(const QString &text) { - QLabel *label = qwInlineNotice->findChild<QLabel *>(QLatin1String("qlPasteNotice")); + QLabel *label = qwInlineNotice->findChild< QLabel * >(QLatin1String("qlPasteNotice")); Q_ASSERT(label); label->setText(text); qwInlineNotice->show(); @@ -784,7 +818,10 @@ bool ConnectDialogEdit::updateFromClipboard() { delete m_si; m_si = ServerItem::fromMimeData(QApplication::clipboard()->mimeData(), false, nullptr, true); if (m_si) { - showNotice(tr("You have an URL in your clipboard.\nDo you want to fill the dialog with this data?\nHost: %1 Port: %2").arg(m_si->qsHostname).arg(m_si->usPort)); + showNotice( + tr("You have an URL in your clipboard.\nDo you want to fill the dialog with this data?\nHost: %1 Port: %2") + .arg(m_si->qsHostname) + .arg(m_si->usPort)); return true; } else { qwInlineNotice->hide(); @@ -814,7 +851,7 @@ void ConnectDialogEdit::on_qbDiscard_clicked() { adjustSize(); } -void ConnectDialogEdit::on_qleName_textEdited(const QString& name) { +void ConnectDialogEdit::on_qleName_textEdited(const QString &name) { if (bCustomLabel) { // If empty, then reset to automatic label. // NOTE(nik@jnstw.us): You may be tempted to set qleName to qleServer, but that results in the odd @@ -830,7 +867,7 @@ void ConnectDialogEdit::on_qleName_textEdited(const QString& name) { } } -void ConnectDialogEdit::on_qleServer_textEdited(const QString& server) { +void ConnectDialogEdit::on_qleServer_textEdited(const QString &server) { // If using automatic label, update it if (!bCustomLabel) { qleName->setText(server); @@ -838,9 +875,9 @@ void ConnectDialogEdit::on_qleServer_textEdited(const QString& server) { } void ConnectDialogEdit::validate() { - qsName = qleName->text().simplified(); + qsName = qleName->text().simplified(); qsHostname = qleServer->text().simplified(); - usPort = qlePort->text().toUShort(); + usPort = qlePort->text().toUShort(); qsUsername = qleUsername->text().simplified(); qsPassword = qlePassword->text(); @@ -860,7 +897,7 @@ void ConnectDialogEdit::validate() { adjustSize(); } - bOk = ! qsHostname.isEmpty() && ! qsUsername.isEmpty() && usPort; + bOk = !qsHostname.isEmpty() && !qsUsername.isEmpty() && usPort; qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(bOk); } @@ -905,10 +942,10 @@ ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoCo siAutoConnect = nullptr; - bAllowPing = g.s.ptProxyType == Settings::NoProxy; + bAllowPing = g.s.ptProxyType == Settings::NoProxy; bAllowHostLookup = g.s.ptProxyType == Settings::NoProxy; - bAllowBonjour = g.s.ptProxyType == Settings::NoProxy; - bAllowFilters = g.s.ptProxyType == Settings::NoProxy; + bAllowBonjour = g.s.ptProxyType == Settings::NoProxy; + bAllowFilters = g.s.ptProxyType == Settings::NoProxy; if (tPublicServers.elapsed() >= 60 * 24 * 1000000ULL) { qlPublicServers.clear(); @@ -939,14 +976,14 @@ ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoCo if (!g.s.bDisablePublicList) { const QIcon qiFlag = ServerItem::loadIcon(QLatin1String("skin:categories/applications-internet.svg")); // Add continents and 'Unknown' to the location combobox - qcbSearchLocation->addItem(qiFlag, tr("All"), QLatin1String("all")); - qcbSearchLocation->addItem(qiFlag, tr("Africa"), QLatin1String("af")); - qcbSearchLocation->addItem(qiFlag, tr("Asia"), QLatin1String("as")); - qcbSearchLocation->addItem(qiFlag, tr("Europe"), QLatin1String("eu")); + qcbSearchLocation->addItem(qiFlag, tr("All"), QLatin1String("all")); + qcbSearchLocation->addItem(qiFlag, tr("Africa"), QLatin1String("af")); + qcbSearchLocation->addItem(qiFlag, tr("Asia"), QLatin1String("as")); + qcbSearchLocation->addItem(qiFlag, tr("Europe"), QLatin1String("eu")); qcbSearchLocation->addItem(qiFlag, tr("North America"), QLatin1String("na")); - qcbSearchLocation->addItem(qiFlag, tr("Oceania"), QLatin1String("oc")); + qcbSearchLocation->addItem(qiFlag, tr("Oceania"), QLatin1String("oc")); qcbSearchLocation->addItem(qiFlag, tr("South America"), QLatin1String("sa")); - qcbSearchLocation->addItem(qiFlag, tr("Unknown"), QLatin1String("")); + qcbSearchLocation->addItem(qiFlag, tr("Unknown"), QLatin1String("")); addCountriesToSearchLocation(); } qgbSearch->setVisible(false); @@ -966,7 +1003,8 @@ ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoCo qtwServers->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents); } - connect(qtwServers->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(OnSortChanged(int, Qt::SortOrder))); + connect(qtwServers->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, + SLOT(OnSortChanged(int, Qt::SortOrder))); if (bAllowFilters) { switch (g.s.ssFilter) { @@ -986,10 +1024,10 @@ ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoCo qmPopup = new QMenu(this); - QList<QTreeWidgetItem *> ql; - QList<FavoriteServer> favorites = g.db->getFavorites(); + QList< QTreeWidgetItem * > ql; + QList< FavoriteServer > favorites = g.db->getFavorites(); - foreach(const FavoriteServer &fs, favorites) { + foreach (const FavoriteServer &fs, favorites) { ServerItem *si = new ServerItem(fs); qlItems << si; startDns(si); @@ -999,14 +1037,14 @@ ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoCo #ifdef USE_BONJOUR // Make sure the we got the objects we need, then wire them up if (bAllowBonjour && g.bc->bsbBrowser && g.bc->bsrResolver) { - connect(g.bc->bsbBrowser.data(), SIGNAL(error(DNSServiceErrorType)), - this, SLOT(onLanBrowseError(DNSServiceErrorType))); - connect(g.bc->bsbBrowser.data(), SIGNAL(currentBonjourRecordsChanged(const QList<BonjourRecord> &)), - this, SLOT(onUpdateLanList(const QList<BonjourRecord> &))); - connect(g.bc->bsrResolver.data(), SIGNAL(error(BonjourRecord, DNSServiceErrorType)), - this, SLOT(onLanResolveError(BonjourRecord, DNSServiceErrorType))); - connect(g.bc->bsrResolver.data(), SIGNAL(bonjourRecordResolved(BonjourRecord, QString, int)), - this, SLOT(onResolved(BonjourRecord, QString, int))); + connect(g.bc->bsbBrowser.data(), SIGNAL(error(DNSServiceErrorType)), this, + SLOT(onLanBrowseError(DNSServiceErrorType))); + connect(g.bc->bsbBrowser.data(), SIGNAL(currentBonjourRecordsChanged(const QList< BonjourRecord > &)), this, + SLOT(onUpdateLanList(const QList< BonjourRecord > &))); + connect(g.bc->bsrResolver.data(), SIGNAL(error(BonjourRecord, DNSServiceErrorType)), this, + SLOT(onLanResolveError(BonjourRecord, DNSServiceErrorType))); + connect(g.bc->bsrResolver.data(), SIGNAL(bonjourRecordResolved(BonjourRecord, QString, int)), this, + SLOT(onResolved(BonjourRecord, QString, int))); onUpdateLanList(g.bc->bsbBrowser->currentRecords()); } #endif @@ -1016,14 +1054,13 @@ ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoCo qusSocket4 = new QUdpSocket(this); qusSocket6 = new QUdpSocket(this); - bIPv4 = qusSocket4->bind(QHostAddress(QHostAddress::Any), 0); - bIPv6 = qusSocket6->bind(QHostAddress(QHostAddress::AnyIPv6), 0); + bIPv4 = qusSocket4->bind(QHostAddress(QHostAddress::Any), 0); + bIPv6 = qusSocket6->bind(QHostAddress(QHostAddress::AnyIPv6), 0); connect(qusSocket4, SIGNAL(readyRead()), this, SLOT(udpReply())); connect(qusSocket6, SIGNAL(readyRead()), this, SLOT(udpReply())); - if (qtwServers->siFavorite->isHidden() - && (!qtwServers->siLAN || qtwServers->siLAN->isHidden()) - && qtwServers->siPublic) { + if (qtwServers->siFavorite->isHidden() && (!qtwServers->siLAN || qtwServers->siLAN->isHidden()) + && qtwServers->siPublic) { qtwServers->siPublic->setExpanded(true); } @@ -1038,19 +1075,19 @@ ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoCo qmPingCache = g.db->getPingCache(); - if (! g.s.qbaConnectDialogGeometry.isEmpty()) + if (!g.s.qbaConnectDialogGeometry.isEmpty()) restoreGeometry(g.s.qbaConnectDialogGeometry); - if (! g.s.qbaConnectDialogHeader.isEmpty()) + if (!g.s.qbaConnectDialogHeader.isEmpty()) qtwServers->header()->restoreState(g.s.qbaConnectDialogHeader); } ConnectDialog::~ConnectDialog() { ServerItem::qmIcons.clear(); - QList<FavoriteServer> ql; + QList< FavoriteServer > ql; qmPingCache.clear(); - foreach(ServerItem *si, qlItems) { + foreach (ServerItem *si, qlItems) { if (si->uiPing) qmPingCache.insert(UnresolvedServerAddress(si->qsHostname, si->usPort), si->uiPing); @@ -1061,25 +1098,27 @@ ConnectDialog::~ConnectDialog() { g.db->setFavorites(ql); g.db->setPingCache(qmPingCache); - g.s.qbaConnectDialogHeader = qtwServers->header()->saveState(); + g.s.qbaConnectDialogHeader = qtwServers->header()->saveState(); g.s.qbaConnectDialogGeometry = saveGeometry(); } void ConnectDialog::accept() { - ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); - if (! si || (bAllowHostLookup && si->qlAddresses.isEmpty()) || si->qsHostname.isEmpty()) { + ServerItem *si = static_cast< ServerItem * >(qtwServers->currentItem()); + if (!si || (bAllowHostLookup && si->qlAddresses.isEmpty()) || si->qsHostname.isEmpty()) { qWarning() << "Invalid server"; return; } qsPassword = si->qsPassword; - qsServer = si->qsHostname; - usPort = si->usPort; + qsServer = si->qsHostname; + usPort = si->usPort; if (si->qsUsername.isEmpty()) { bool ok; - QString defUserName = QInputDialog::getText(this, tr("Connecting to %1").arg(si->qsName), tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed(); - if (! ok) + QString defUserName = QInputDialog::getText(this, tr("Connecting to %1").arg(si->qsName), tr("Enter username"), + QLineEdit::Normal, g.s.qsUsername, &ok) + .trimmed(); + if (!ok) return; g.s.qsUsername = si->qsUsername = defUserName; } @@ -1096,7 +1135,7 @@ void ConnectDialog::OnSortChanged(int logicalIndex, Qt::SortOrder) { return; } - foreach(ServerItem *si, qlItems) { + foreach (ServerItem *si, qlItems) { if (si->uiPing && (si->uiPing != si->uiPingSort)) { si->uiPingSort = si->uiPing; si->setDatas(); @@ -1105,8 +1144,8 @@ void ConnectDialog::OnSortChanged(int logicalIndex, Qt::SortOrder) { } void ConnectDialog::on_qaFavoriteAdd_triggered() { - ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); - if (! si || (si->itType == ServerItem::FavoriteType)) + ServerItem *si = static_cast< ServerItem * >(qtwServers->currentItem()); + if (!si || (si->itType == ServerItem::FavoriteType)) return; si = new ServerItem(si); @@ -1131,24 +1170,23 @@ void ConnectDialog::on_qaFavoriteAddNew_triggered() { } void ConnectDialog::on_qaFavoriteEdit_triggered() { - ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); - if (! si || (si->itType != ServerItem::FavoriteType)) + ServerItem *si = static_cast< ServerItem * >(qtwServers->currentItem()); + if (!si || (si->itType != ServerItem::FavoriteType)) return; QString host; #ifdef USE_BONJOUR - if (! si->qsBonjourHost.isEmpty()) + if (!si->qsBonjourHost.isEmpty()) host = QLatin1Char('@') + si->qsBonjourHost; else host = si->qsHostname; #else - host = si->qsHostname; + host = si->qsHostname; #endif ConnectDialogEdit *cde = new ConnectDialogEdit(this, si->qsName, host, si->qsUsername, si->usPort, si->qsPassword); if (cde->exec() == QDialog::Accepted) { - - si->qsName = cde->qsName; + si->qsName = cde->qsName; si->qsUsername = cde->qsUsername; si->qsPassword = cde->qsPassword; if ((cde->qsHostname != host) || (cde->usPort != si->usPort)) { @@ -1160,16 +1198,17 @@ void ConnectDialog::on_qaFavoriteEdit_triggered() { si->usPort = cde->usPort; #ifdef USE_BONJOUR if (cde->qsHostname.startsWith(QLatin1Char('@'))) { - si->qsHostname = QString(); + si->qsHostname = QString(); si->qsBonjourHost = cde->qsHostname.mid(1); - si->brRecord = BonjourRecord(si->qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); + si->brRecord = + BonjourRecord(si->qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { - si->qsHostname = cde->qsHostname; + si->qsHostname = cde->qsHostname; si->qsBonjourHost = QString(); - si->brRecord = BonjourRecord(); + si->brRecord = BonjourRecord(); } #else - si->qsHostname = cde->qsHostname; + si->qsHostname = cde->qsHostname; #endif startDns(si); } @@ -1179,8 +1218,8 @@ void ConnectDialog::on_qaFavoriteEdit_triggered() { } void ConnectDialog::on_qaFavoriteRemove_triggered() { - ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); - if (! si || (si->itType != ServerItem::FavoriteType)) + ServerItem *si = static_cast< ServerItem * >(qtwServers->currentItem()); + if (!si || (si->itType != ServerItem::FavoriteType)) return; stopDns(si); @@ -1189,8 +1228,8 @@ void ConnectDialog::on_qaFavoriteRemove_triggered() { } void ConnectDialog::on_qaFavoriteCopy_triggered() { - ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); - if (! si) + ServerItem *si = static_cast< ServerItem * >(qtwServers->currentItem()); + if (!si) return; QApplication::clipboard()->setMimeData(si->toMimeData()); @@ -1198,7 +1237,7 @@ void ConnectDialog::on_qaFavoriteCopy_triggered() { void ConnectDialog::on_qaFavoritePaste_triggered() { ServerItem *si = ServerItem::fromMimeData(QApplication::clipboard()->mimeData()); - if (! si) + if (!si) return; qlItems << si; @@ -1208,23 +1247,22 @@ void ConnectDialog::on_qaFavoritePaste_triggered() { } void ConnectDialog::on_qaUrl_triggered() { - ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); - if (! si || si->qsUrl.isEmpty()) + ServerItem *si = static_cast< ServerItem * >(qtwServers->currentItem()); + if (!si || si->qsUrl.isEmpty()) return; QDesktopServices::openUrl(QUrl(si->qsUrl)); } void ConnectDialog::on_qtwServers_customContextMenuRequested(const QPoint &mpos) { - ServerItem *si = static_cast<ServerItem *>(qtwServers->itemAt(mpos)); + ServerItem *si = static_cast< ServerItem * >(qtwServers->itemAt(mpos)); qmPopup->clear(); if (si && si->bParent) { si = nullptr; } - - if (si) { + if (si) { if (!g.s.disableConnectDialogEditing) { if (si->itType == ServerItem::FavoriteType) { qmPopup->addAction(qaFavoriteEdit); @@ -1233,7 +1271,7 @@ void ConnectDialog::on_qtwServers_customContextMenuRequested(const QPoint &mpos) qmPopup->addAction(qaFavoriteAdd); } } - + if (!si->qsUrl.isEmpty()) { qmPopup->addAction(qaUrl); } @@ -1248,14 +1286,14 @@ void ConnectDialog::on_qtwServers_itemDoubleClicked(QTreeWidgetItem *item, int) } void ConnectDialog::on_qtwServers_currentItemChanged(QTreeWidgetItem *item, QTreeWidgetItem *) { - ServerItem *si = static_cast<ServerItem *>(item); + ServerItem *si = static_cast< ServerItem * >(item); if (si->siParent == qtwServers->siFavorite) { qpbEdit->setEnabled(true); } else { qpbEdit->setEnabled(false); } - + bool bOk = !si->qlAddresses.isEmpty(); if (!bAllowHostLookup) { bOk = true; @@ -1270,13 +1308,13 @@ void ConnectDialog::on_qtwServers_itemExpanded(QTreeWidgetItem *item) { if (!g.s.bPingServersDialogViewed) { // Ask the user for consent to ping the servers. If the user does // not give consent, disable the public server list and return. - int result = QMessageBox::question(this, - tr("Consent to the transmission of private data"), - tr("<p>To measure the latency (ping) of public servers and determine the number of active users, " - "your IP address must be transmitted to each public server.</p>" - "<p>Do you consent to the transmission of your IP address? If you answer no, the public server " - "list will be deactivated. However, you can reactivate it at any time in the network settings.</p>"), - QMessageBox::Yes|QMessageBox::No); + int result = QMessageBox::question( + this, tr("Consent to the transmission of private data"), + tr("<p>To measure the latency (ping) of public servers and determine the number of active users, " + "your IP address must be transmitted to each public server.</p>" + "<p>Do you consent to the transmission of your IP address? If you answer no, the public server " + "list will be deactivated. However, you can reactivate it at any time in the network settings.</p>"), + QMessageBox::Yes | QMessageBox::No); g.s.bPingServersDialogViewed = true; if (result == QMessageBox::No) { g.s.bDisablePublicList = true; @@ -1290,15 +1328,12 @@ void ConnectDialog::on_qtwServers_itemExpanded(QTreeWidgetItem *item) { fillList(); } - ServerItem *p = static_cast<ServerItem *>(item); + ServerItem *p = static_cast< ServerItem * >(item); - foreach(ServerItem *si, p->qlChildren) { - startDns(si); - } + foreach (ServerItem *si, p->qlChildren) { startDns(si); } } -void ConnectDialog::on_qtwServers_itemCollapsed(QTreeWidgetItem *item) -{ +void ConnectDialog::on_qtwServers_itemCollapsed(QTreeWidgetItem *item) { if (qtwServers->siPublic && item == qtwServers->siPublic) { qgbSearch->setVisible(false); } @@ -1317,18 +1352,18 @@ void ConnectDialog::initList() { query.addQueryItem(QLatin1String("version"), QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); url.setQuery(query); - WebFetch::fetch(QLatin1String("publist"), url, this, SLOT(fetched(QByteArray,QUrl,QMap<QString,QString>))); + WebFetch::fetch(QLatin1String("publist"), url, this, SLOT(fetched(QByteArray, QUrl, QMap< QString, QString >))); } #ifdef USE_BONJOUR void ConnectDialog::onResolved(BonjourRecord record, QString host, int port) { qlBonjourActive.removeAll(record); - foreach(ServerItem *si, qlItems) { + foreach (ServerItem *si, qlItems) { if (si->brRecord == record) { - unsigned short usport = static_cast<unsigned short>(port); + unsigned short usport = static_cast< unsigned short >(port); if ((host != si->qsHostname) || (usport != si->usPort)) { stopDns(si); - si->usPort = static_cast<unsigned short>(port); + si->usPort = static_cast< unsigned short >(port); si->qsHostname = host; startDns(si); } @@ -1336,25 +1371,26 @@ void ConnectDialog::onResolved(BonjourRecord record, QString host, int port) { } } -void ConnectDialog::onUpdateLanList(const QList<BonjourRecord> &list) { - QSet<ServerItem *> items; -#if QT_VERSION >= QT_VERSION_CHECK(5,14,0) - QSet<ServerItem *> old = QSet<ServerItem*>(qtwServers->siLAN->qlChildren.begin(), qtwServers->siLAN->qlChildren.end()); -#else +void ConnectDialog::onUpdateLanList(const QList< BonjourRecord > &list) { + QSet< ServerItem * > items; +# if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) + QSet< ServerItem * > old = + QSet< ServerItem * >(qtwServers->siLAN->qlChildren.begin(), qtwServers->siLAN->qlChildren.end()); +# else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now - QSet<ServerItem *> old = qtwServers->siLAN->qlChildren.toSet(); -#endif + QSet< ServerItem * > old = qtwServers->siLAN->qlChildren.toSet(); +# endif - foreach(const BonjourRecord &record, list) { + foreach (const BonjourRecord &record, list) { bool found = false; - foreach(ServerItem *si, old) { + foreach (ServerItem *si, old) { if (si->brRecord == record) { items.insert(si); found = true; break; } } - if (! found) { + if (!found) { ServerItem *si = new ServerItem(record); qlItems << si; g.bc->bsrResolver->resolveBonjourRecord(record); @@ -1362,8 +1398,8 @@ void ConnectDialog::onUpdateLanList(const QList<BonjourRecord> &list) { qtwServers->siLAN->addServerItem(si); } } - QSet<ServerItem *> remove = old.subtract(items); - foreach(ServerItem *si, remove) { + QSet< ServerItem * > remove = old.subtract(items); + foreach (ServerItem *si, remove) { stopDns(si); qlItems.removeAll(si); delete si; @@ -1371,51 +1407,51 @@ void ConnectDialog::onUpdateLanList(const QList<BonjourRecord> &list) { } void ConnectDialog::onLanBrowseError(DNSServiceErrorType err) { - qWarning()<<"Bonjour reported browser error "<< err; + qWarning() << "Bonjour reported browser error " << err; } void ConnectDialog::onLanResolveError(BonjourRecord br, DNSServiceErrorType err) { qlBonjourActive.removeAll(br); - qWarning()<<"Bonjour reported resolver error "<< err; + qWarning() << "Bonjour reported resolver error " << err; } #endif void ConnectDialog::fillList() { - QList<QTreeWidgetItem *> ql; - QList<QTreeWidgetItem *> qlNew; + QList< QTreeWidgetItem * > ql; + QList< QTreeWidgetItem * > qlNew; - foreach(const PublicInfo &pi, qlPublicServers) { + foreach (const PublicInfo &pi, qlPublicServers) { bool found = false; - foreach(ServerItem *si, qlItems) { + foreach (ServerItem *si, qlItems) { if ((pi.qsIp == si->qsHostname) && (pi.usPort == si->usPort)) { - si->qsCountry = pi.qsCountry; - si->qsCountryCode = pi.qsCountryCode; + si->qsCountry = pi.qsCountry; + si->qsCountryCode = pi.qsCountryCode; si->qsContinentCode = pi.qsContinentCode; - si->qsUrl = pi.quUrl.toString(); - si->bCA = pi.bCA; + si->qsUrl = pi.quUrl.toString(); + si->bCA = pi.bCA; si->setDatas(); if (si->itType == ServerItem::PublicType) found = true; } } - if (! found) + if (!found) ql << new ServerItem(pi); } - while (! ql.isEmpty()) { -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - ServerItem *si = static_cast<ServerItem *>(ql.takeAt(QRandomGenerator::global()->generate() % ql.count())); + while (!ql.isEmpty()) { +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) + ServerItem *si = static_cast< ServerItem * >(ql.takeAt(QRandomGenerator::global()->generate() % ql.count())); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor - ServerItem *si = static_cast<ServerItem *>(ql.takeAt(qrand() % ql.count())); + ServerItem *si = static_cast< ServerItem * >(ql.takeAt(qrand() % ql.count())); #endif qlNew << si; qlItems << si; } - foreach(QTreeWidgetItem *qtwi, qlNew) { - ServerItem *si = static_cast<ServerItem *>(qtwi); + foreach (QTreeWidgetItem *qtwi, qlNew) { + ServerItem *si = static_cast< ServerItem * >(qtwi); qtwServers->siPublic->addServerItem(si); filterServer(si); startDns(si); @@ -1423,14 +1459,15 @@ void ConnectDialog::fillList() { } void ConnectDialog::timeTick() { - if (! bLastFound && ! g.s.qsLastServer.isEmpty()) { - QList<QTreeWidgetItem *> items = qtwServers->findItems(g.s.qsLastServer, Qt::MatchExactly | Qt::MatchRecursive); + if (!bLastFound && !g.s.qsLastServer.isEmpty()) { + QList< QTreeWidgetItem * > items = + qtwServers->findItems(g.s.qsLastServer, Qt::MatchExactly | Qt::MatchRecursive); if (!items.isEmpty()) { bLastFound = true; qtwServers->setCurrentItem(items.at(0)); if (g.s.bAutoConnect && bAutoConnect) { - siAutoConnect = static_cast<ServerItem *>(items.at(0)); - if (! siAutoConnect->qlAddresses.isEmpty()) { + siAutoConnect = static_cast< ServerItem * >(items.at(0)); + if (!siAutoConnect->qlAddresses.isEmpty()) { accept(); return; } else if (!bAllowHostLookup) { @@ -1443,7 +1480,7 @@ void ConnectDialog::timeTick() { if (bAllowHostLookup) { // Start DNS Lookup of first unknown hostname - foreach(const UnresolvedServerAddress &unresolved, qlDNSLookup) { + foreach (const UnresolvedServerAddress &unresolved, qlDNSLookup) { if (qsDNSActive.contains(unresolved)) { continue; } @@ -1459,23 +1496,24 @@ void ConnectDialog::timeTick() { } } - ServerItem *current = static_cast<ServerItem *>(qtwServers->currentItem()); - ServerItem *hover = static_cast<ServerItem *>(qtwServers->itemAt(qtwServers->viewport()->mapFromGlobal(QCursor::pos()))); + ServerItem *current = static_cast< ServerItem * >(qtwServers->currentItem()); + ServerItem *hover = + static_cast< ServerItem * >(qtwServers->itemAt(qtwServers->viewport()->mapFromGlobal(QCursor::pos()))); ServerItem *si = nullptr; if (tCurrent.elapsed() >= 1000000ULL) si = current; - if (! si && (tHover.elapsed() >= 1000000ULL)) + if (!si && (tHover.elapsed() >= 1000000ULL)) si = hover; if (si) { - QString hostname = si->qsHostname.toLower(); + QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); if (si->qlAddresses.isEmpty()) { - if (! hostname.isEmpty()) { + if (!hostname.isEmpty()) { qlDNSLookup.removeAll(unresolved); qlDNSLookup.prepend(unresolved); } @@ -1500,12 +1538,12 @@ void ConnectDialog::timeTick() { si = qlItems.at(iPingIndex); ServerItem *p = si->siParent; - expanded = true; + expanded = true; while (p && expanded) { expanded = expanded && p->isExpanded(); - p = p->siParent; + p = p->siParent; } - } while (si->qlAddresses.isEmpty() || ! expanded); + } while (si->qlAddresses.isEmpty() || !expanded); } if (si == current) @@ -1513,20 +1551,16 @@ void ConnectDialog::timeTick() { if (si == hover) tHover.restart(); - foreach(const ServerAddress &addr, si->qlAddresses) { - sendPing(addr.host.toAddress(), addr.port); - } + foreach (const ServerAddress &addr, si->qlAddresses) { sendPing(addr.host.toAddress(), addr.port); } } void ConnectDialog::filterPublicServerList() const { if (!g.s.bDisablePublicList) { - foreach(ServerItem * const si, qtwServers->siPublic->qlChildren) { - filterServer(si); - } + foreach (ServerItem *const si, qtwServers->siPublic->qlChildren) { filterServer(si); } } } -void ConnectDialog::filterServer(ServerItem * const si) const { +void ConnectDialog::filterServer(ServerItem *const si) const { if (!si->qsName.contains(qsSearchServername, Qt::CaseInsensitive)) { si->setHidden(true); return; @@ -1547,21 +1581,20 @@ void ConnectDialog::filterServer(ServerItem * const si) const { si->setHidden(false); } -void ConnectDialog::addCountriesToSearchLocation() const -{ - QMap <QString, QString> qmCountries; +void ConnectDialog::addCountriesToSearchLocation() const { + QMap< QString, QString > qmCountries; - foreach(const PublicInfo &pi, qlPublicServers) { + foreach (const PublicInfo &pi, qlPublicServers) { if (pi.qsCountry != tr("Unknown") && !qmCountries.contains(pi.qsCountry)) { - qmCountries.insert(pi.qsCountry, pi.qsCountryCode); + qmCountries.insert(pi.qsCountry, pi.qsCountryCode); } } foreach (auto location, qmCountries.keys()) { // Set Icon, Text and Data - qcbSearchLocation->addItem(ServerItem::loadIcon(QString::fromLatin1(":/flags/%1.svg").arg(qmCountries.value(location))), - location, - location); + qcbSearchLocation->addItem( + ServerItem::loadIcon(QString::fromLatin1(":/flags/%1.svg").arg(qmCountries.value(location))), location, + location); } } @@ -1570,7 +1603,7 @@ void ConnectDialog::startDns(ServerItem *si) { return; } - QString hostname = si->qsHostname.toLower(); + QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); @@ -1588,18 +1621,16 @@ void ConnectDialog::startDns(ServerItem *si) { } if (qtwServers->currentItem() == si) - qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(! si->qlAddresses.isEmpty()); + qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(!si->qlAddresses.isEmpty()); - if (! si->qlAddresses.isEmpty()) { - foreach(const ServerAddress &addr, si->qlAddresses) { - qhPings[addr].insert(si); - } + if (!si->qlAddresses.isEmpty()) { + foreach (const ServerAddress &addr, si->qlAddresses) { qhPings[addr].insert(si); } return; } #ifdef USE_BONJOUR - if (bAllowBonjour && si->qsHostname.isEmpty() && ! si->brRecord.serviceName.isEmpty()) { - if (! qlBonjourActive.contains(si->brRecord)) { + if (bAllowBonjour && si->qsHostname.isEmpty() && !si->brRecord.serviceName.isEmpty()) { + if (!qlBonjourActive.contains(si->brRecord)) { g.bc->bsrResolver->resolveBonjourRecord(si->brRecord); qlBonjourActive.append(si->brRecord); } @@ -1607,7 +1638,7 @@ void ConnectDialog::startDns(ServerItem *si) { } #endif - if (! qhDNSWait.contains(unresolved)) { + if (!qhDNSWait.contains(unresolved)) { if (si->itType == ServerItem::PublicType) qlDNSLookup.append(unresolved); else @@ -1621,7 +1652,7 @@ void ConnectDialog::stopDns(ServerItem *si) { return; } - foreach(const ServerAddress &addr, si->qlAddresses) { + foreach (const ServerAddress &addr, si->qlAddresses) { if (qhPings.contains(addr)) { qhPings[addr].remove(si); if (qhPings[addr].isEmpty()) { @@ -1631,7 +1662,7 @@ void ConnectDialog::stopDns(ServerItem *si) { } } - QString hostname = si->qsHostname.toLower(); + QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); @@ -1645,10 +1676,10 @@ void ConnectDialog::stopDns(ServerItem *si) { } void ConnectDialog::lookedUp() { - ServerResolver *sr = qobject_cast<ServerResolver *>(QObject::sender()); + ServerResolver *sr = qobject_cast< ServerResolver * >(QObject::sender()); sr->deleteLater(); - QString hostname = sr->hostname().toLower(); + QString hostname = sr->hostname().toLower(); unsigned short port = sr->port(); UnresolvedServerAddress unresolved(hostname, port); @@ -1659,18 +1690,14 @@ void ConnectDialog::lookedUp() { return; } - QSet<ServerAddress> qs; + QSet< ServerAddress > qs; foreach (ServerResolverRecord record, sr->records()) { - foreach(const HostAddress &ha, record.addresses()) { - qs.insert(ServerAddress(ha, record.port())); - } + foreach (const HostAddress &ha, record.addresses()) { qs.insert(ServerAddress(ha, record.port())); } } - QSet<ServerItem *> waiting = qhDNSWait[unresolved]; - foreach(ServerItem *si, waiting) { - foreach (const ServerAddress &addr, qs) { - qhPings[addr].insert(si); - } + QSet< ServerItem * > waiting = qhDNSWait[unresolved]; + foreach (ServerItem *si, waiting) { + foreach (const ServerAddress &addr, qs) { qhPings[addr].insert(si); } si->qlAddresses = qs.values(); } @@ -1679,7 +1706,7 @@ void ConnectDialog::lookedUp() { qhDNSCache.insert(unresolved, qs.values()); qhDNSWait.remove(unresolved); - foreach(ServerItem *si, waiting) { + foreach (ServerItem *si, waiting) { if (si == qtwServers->currentItem()) { on_qtwServers_currentItemChanged(si, si); if (si == siAutoConnect) @@ -1688,9 +1715,7 @@ void ConnectDialog::lookedUp() { } if (bAllowPing) { - foreach(const ServerAddress &addr, qs) { - sendPing(addr.host.toAddress(), addr.port); - } + foreach (const ServerAddress &addr, qs) { sendPing(addr.host.toAddress(), addr.port); } } } @@ -1703,33 +1728,33 @@ void ConnectDialog::sendPing(const QHostAddress &host, unsigned short port) { if (qhPingRand.contains(addr)) { uiRand = qhPingRand.value(addr); } else { -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) uiRand = QRandomGenerator::global()->generate64() << 32; #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor - uiRand = (static_cast<quint64>(qrand()) << 32) | static_cast<quint64>(qrand()); + uiRand = (static_cast< quint64 >(qrand()) << 32) | static_cast< quint64 >(qrand()); #endif qhPingRand.insert(addr, uiRand); } memset(blob, 0, sizeof(blob)); - * reinterpret_cast<quint64 *>(blob+8) = tPing.elapsed() ^ uiRand; + *reinterpret_cast< quint64 * >(blob + 8) = tPing.elapsed() ^ uiRand; if (bIPv4 && host.protocol() == QAbstractSocket::IPv4Protocol) - qusSocket4->writeDatagram(blob+4, 12, host, port); + qusSocket4->writeDatagram(blob + 4, 12, host, port); else if (bIPv6 && host.protocol() == QAbstractSocket::IPv6Protocol) - qusSocket6->writeDatagram(blob+4, 12, host, port); + qusSocket6->writeDatagram(blob + 4, 12, host, port); else return; - const QSet<ServerItem *> &qs = qhPings.value(addr); + const QSet< ServerItem * > &qs = qhPings.value(addr); - foreach(ServerItem *si, qs) - ++ si->uiSent; + foreach (ServerItem *si, qs) + ++si->uiSent; } void ConnectDialog::udpReply() { - QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender()); + QUdpSocket *sock = qobject_cast< QUdpSocket * >(sender()); while (sock->hasPendingDatagrams()) { char blob[64]; @@ -1737,7 +1762,7 @@ void ConnectDialog::udpReply() { QHostAddress host; unsigned short port; - qint64 len = sock->readDatagram(blob+4, 24, &host, &port); + qint64 len = sock->readDatagram(blob + 4, 24, &host, &port); if (len == 24) { if (host.scopeId() == QLatin1String("0")) host.setScopeId(QLatin1String("")); @@ -1745,23 +1770,23 @@ void ConnectDialog::udpReply() { ServerAddress address(HostAddress(host), port); if (qhPings.contains(address)) { - quint32 *ping = reinterpret_cast<quint32 *>(blob+4); - quint64 *ts = reinterpret_cast<quint64 *>(blob+8); + quint32 *ping = reinterpret_cast< quint32 * >(blob + 4); + quint64 *ts = reinterpret_cast< quint64 * >(blob + 8); quint64 elapsed = tPing.elapsed() - (*ts ^ qhPingRand.value(address)); - foreach(ServerItem *si, qhPings.value(address)) { - si->uiVersion = qFromBigEndian(ping[0]); - quint32 users = qFromBigEndian(ping[3]); + foreach (ServerItem *si, qhPings.value(address)) { + si->uiVersion = qFromBigEndian(ping[0]); + quint32 users = qFromBigEndian(ping[3]); quint32 maxusers = qFromBigEndian(ping[4]); - si->uiBandwidth = qFromBigEndian(ping[5]); + si->uiBandwidth = qFromBigEndian(ping[5]); - if (! si->uiPingSort) + if (!si->uiPingSort) si->uiPingSort = qmPingCache.value(UnresolvedServerAddress(si->qsHostname, si->usPort)); - si->setDatas(static_cast<double>(elapsed), users, maxusers); + si->setDatas(static_cast< double >(elapsed), users, maxusers); if (si->itType == ServerItem::PublicType) { - filterServer(si); + filterServer(si); } } } @@ -1769,7 +1794,7 @@ void ConnectDialog::udpReply() { } } -void ConnectDialog::fetched(QByteArray xmlData, QUrl, QMap<QString, QString> headers) { +void ConnectDialog::fetched(QByteArray xmlData, QUrl, QMap< QString, QString > headers) { if (xmlData.isNull()) { QMessageBox::warning(this, QLatin1String("Mumble"), tr("Failed to fetch server list"), QMessageBox::Ok); return; @@ -1779,25 +1804,25 @@ void ConnectDialog::fetched(QByteArray xmlData, QUrl, QMap<QString, QString> hea doc.setContent(xmlData); qlPublicServers.clear(); - qsUserCountry = headers.value(QLatin1String("Geo-Country")); - qsUserCountryCode = headers.value(QLatin1String("Geo-Country-Code")).toLower(); + qsUserCountry = headers.value(QLatin1String("Geo-Country")); + qsUserCountryCode = headers.value(QLatin1String("Geo-Country-Code")).toLower(); qsUserContinentCode = headers.value(QLatin1String("Geo-Continent-Code")).toLower(); - QDomElement root=doc.documentElement(); - QDomNode n = root.firstChild(); + QDomElement root = doc.documentElement(); + QDomNode n = root.firstChild(); while (!n.isNull()) { QDomElement e = n.toElement(); if (!e.isNull()) { if (e.tagName() == QLatin1String("server")) { PublicInfo pi; - pi.qsName = e.attribute(QLatin1String("name")); - pi.quUrl = e.attribute(QLatin1String("url")); - pi.qsIp = e.attribute(QLatin1String("ip")); - pi.usPort = e.attribute(QLatin1String("port")).toUShort(); - pi.qsCountry = e.attribute(QLatin1String("country"), tr("Unknown")); - pi.qsCountryCode = e.attribute(QLatin1String("country_code")).toLower(); + pi.qsName = e.attribute(QLatin1String("name")); + pi.quUrl = e.attribute(QLatin1String("url")); + pi.qsIp = e.attribute(QLatin1String("ip")); + pi.usPort = e.attribute(QLatin1String("port")).toUShort(); + pi.qsCountry = e.attribute(QLatin1String("country"), tr("Unknown")); + pi.qsCountryCode = e.attribute(QLatin1String("country_code")).toLower(); pi.qsContinentCode = e.attribute(QLatin1String("continent_code")).toLower(); - pi.bCA = e.attribute(QLatin1String("ca")).toInt() ? true : false; + pi.bCA = e.attribute(QLatin1String("ca")).toInt() ? true : false; qlPublicServers << pi; } diff --git a/src/mumble/ConnectDialog.h b/src/mumble/ConnectDialog.h index f344e489b..e04b66c70 100644 --- a/src/mumble/ConnectDialog.h +++ b/src/mumble/ConnectDialog.h @@ -7,13 +7,13 @@ #define MUMBLE_MUMBLE_CONNECTDIALOG_H_ #ifndef Q_MOC_RUN -# include <boost/accumulators/accumulators.hpp> -# include <boost/accumulators/statistics/stats.hpp> +# include <boost/accumulators/accumulators.hpp> +# include <boost/accumulators/statistics/stats.hpp> #endif -#include <QtCore/QtGlobal> #include <QtCore/QString> #include <QtCore/QUrl> +#include <QtCore/QtGlobal> #include <QtWidgets/QStyledItemDelegate> #include <QtWidgets/QTreeView> #include <QtWidgets/QTreeWidgetItem> @@ -21,15 +21,15 @@ #include <QtNetwork/QHostInfo> #ifdef USE_BONJOUR -# include <dns_sd.h> -# include "BonjourRecord.h" +# include "BonjourRecord.h" +# include <dns_sd.h> #endif -#include "Net.h" #include "HostAddress.h" +#include "Net.h" +#include "ServerAddress.h" #include "Timer.h" #include "UnresolvedServerAddress.h" -#include "ServerAddress.h" struct FavoriteServer; class QUdpSocket; @@ -50,6 +50,7 @@ private: Q_DISABLE_COPY(PingStats) protected: void init(); + public: quint32 uiVersion; quint32 uiPing; @@ -62,7 +63,10 @@ public: double dPing; - typedef boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::count, boost::accumulators::tag::extended_p_square> > asQuantileType; + typedef boost::accumulators::accumulator_set< + double, + boost::accumulators::stats< boost::accumulators::tag::count, boost::accumulators::tag::extended_p_square > > + asQuantileType; asQuantileType *asQuantile; void reset(); @@ -84,280 +88,285 @@ public: }; class ServerView : public QTreeWidget { - Q_OBJECT - Q_DISABLE_COPY(ServerView) - public: - ServerItem *siFavorite, *siLAN, *siPublic; - - ServerView(QWidget *); - ~ServerView() Q_DECL_OVERRIDE; - - void fixupName(ServerItem *si); - protected: - QMimeData *mimeData(const QList<QTreeWidgetItem *>) const Q_DECL_OVERRIDE; - QStringList mimeTypes() const Q_DECL_OVERRIDE; - Qt::DropActions supportedDropActions() const Q_DECL_OVERRIDE; - bool dropMimeData(QTreeWidgetItem *, int, const QMimeData *, Qt::DropAction) Q_DECL_OVERRIDE; + Q_OBJECT + Q_DISABLE_COPY(ServerView) +public: + ServerItem *siFavorite, *siLAN, *siPublic; + + ServerView(QWidget *); + ~ServerView() Q_DECL_OVERRIDE; + + void fixupName(ServerItem *si); + +protected: + QMimeData *mimeData(const QList< QTreeWidgetItem * >) const Q_DECL_OVERRIDE; + QStringList mimeTypes() const Q_DECL_OVERRIDE; + Qt::DropActions supportedDropActions() const Q_DECL_OVERRIDE; + bool dropMimeData(QTreeWidgetItem *, int, const QMimeData *, Qt::DropAction) Q_DECL_OVERRIDE; }; #include "ui_ConnectDialog.h" #include "ui_ConnectDialogEdit.h" class ServerItem : public QTreeWidgetItem, public PingStats { - Q_DISABLE_COPY(ServerItem) - protected: - void init(); - public: - enum ItemType { FavoriteType, LANType, PublicType }; + Q_DISABLE_COPY(ServerItem) +protected: + void init(); - static QMap<QString, QIcon> qmIcons; +public: + enum ItemType { FavoriteType, LANType, PublicType }; - bool bParent; - ServerItem *siParent; - QList<ServerItem *> qlChildren; + static QMap< QString, QIcon > qmIcons; - QString qsName; + bool bParent; + ServerItem *siParent; + QList< ServerItem * > qlChildren; - QString qsHostname; - unsigned short usPort; - bool bCA; + QString qsName; - QString qsUsername; - QString qsPassword; + QString qsHostname; + unsigned short usPort; + bool bCA; - QString qsCountry; - QString qsCountryCode; - QString qsContinentCode; + QString qsUsername; + QString qsPassword; - QString qsUrl; + QString qsCountry; + QString qsCountryCode; + QString qsContinentCode; + + QString qsUrl; #ifdef USE_BONJOUR - QString qsBonjourHost; - BonjourRecord brRecord; + QString qsBonjourHost; + BonjourRecord brRecord; #endif - /// Contains the resolved addresses for - /// this ServerItem. - QList<ServerAddress> qlAddresses; + /// Contains the resolved addresses for + /// this ServerItem. + QList< ServerAddress > qlAddresses; - ItemType itType; + ItemType itType; - ServerItem(const FavoriteServer &fs); - ServerItem(const PublicInfo &pi); - ServerItem(const QString &name, const QString &host, unsigned short port, const QString &uname, const QString &password = QString()); + ServerItem(const FavoriteServer &fs); + ServerItem(const PublicInfo &pi); + ServerItem(const QString &name, const QString &host, unsigned short port, const QString &uname, + const QString &password = QString()); #ifdef USE_BONJOUR - ServerItem(const BonjourRecord &br); + ServerItem(const BonjourRecord &br); #endif - ServerItem(const QString &name, ItemType itype); - ServerItem(const ServerItem *si); - ~ServerItem(); - - /// Converts given mime data into a ServerItem object - /// - /// This function checks the clipboard for a valid mumble:// style - /// URL and converts it into a ServerItem ready to add to the connect - /// dialog. It also parses .lnk files of InternetShortcut/URL type - /// to enable those to be dropped onto the clipboard. - /// - /// @note If needed can query the user for a user name using a modal dialog. - /// @note If a server item is returned it's the callers reponsibility to delete it. - /// - /// @param mime Mime data to analyze - /// @param default_name If true the hostname is set as item name if none is given - /// @param p Parent widget to use in case the user has to be queried - /// @return Server item or nullptr if mime data invalid. - /// - static ServerItem *fromMimeData(const QMimeData *mime, bool default_name = true, QWidget *p = nullptr, bool convertHttpUrls=false); - /// Create a ServerItem from a mumble:// URL - static ServerItem *fromUrl(QUrl url, QWidget *p); - - void addServerItem(ServerItem *child); - - FavoriteServer toFavoriteServer() const; - QMimeData *toMimeData() const; - static QMimeData *toMimeData(const QString &name, const QString &host, unsigned short port, const QString &channel = QString()); - - static QIcon loadIcon(const QString &name); - - void setDatas(double ping = 0.0, quint32 users = 0, quint32 maxusers = 0); - bool operator< (const QTreeWidgetItem &) const Q_DECL_OVERRIDE; - - QVariant data(int column, int role) const Q_DECL_OVERRIDE; + ServerItem(const QString &name, ItemType itype); + ServerItem(const ServerItem *si); + ~ServerItem(); + + /// Converts given mime data into a ServerItem object + /// + /// This function checks the clipboard for a valid mumble:// style + /// URL and converts it into a ServerItem ready to add to the connect + /// dialog. It also parses .lnk files of InternetShortcut/URL type + /// to enable those to be dropped onto the clipboard. + /// + /// @note If needed can query the user for a user name using a modal dialog. + /// @note If a server item is returned it's the callers reponsibility to delete it. + /// + /// @param mime Mime data to analyze + /// @param default_name If true the hostname is set as item name if none is given + /// @param p Parent widget to use in case the user has to be queried + /// @return Server item or nullptr if mime data invalid. + /// + static ServerItem *fromMimeData(const QMimeData *mime, bool default_name = true, QWidget *p = nullptr, + bool convertHttpUrls = false); + /// Create a ServerItem from a mumble:// URL + static ServerItem *fromUrl(QUrl url, QWidget *p); + + void addServerItem(ServerItem *child); + + FavoriteServer toFavoriteServer() const; + QMimeData *toMimeData() const; + static QMimeData *toMimeData(const QString &name, const QString &host, unsigned short port, + const QString &channel = QString()); + + static QIcon loadIcon(const QString &name); + + void setDatas(double ping = 0.0, quint32 users = 0, quint32 maxusers = 0); + bool operator<(const QTreeWidgetItem &) const Q_DECL_OVERRIDE; + + QVariant data(int column, int role) const Q_DECL_OVERRIDE; }; class ConnectDialogEdit : public QDialog, protected Ui::ConnectDialogEdit { - private: - Q_OBJECT - Q_DISABLE_COPY(ConnectDialogEdit) - - void init(); - protected: - bool bOk; - bool bCustomLabel; - ServerItem *m_si; - - public slots: - void validate(); - void accept(); - - void on_qbFill_clicked(); - void on_qbDiscard_clicked(); - void on_qcbShowPassword_toggled(bool); - void on_qleName_textEdited(const QString&); - void on_qleServer_textEdited(const QString&); - void showNotice(const QString &text); - bool updateFromClipboard(); - public: - QString qsName, qsHostname, qsUsername, qsPassword; - unsigned short usPort; - ConnectDialogEdit(QWidget *parent, - const QString &name, - const QString &host, - const QString &user, - unsigned short port, - const QString &password); - /// Add a new Server - /// Prefills from clipboard content or the connected to server if available - ConnectDialogEdit(QWidget *parent); - virtual ~ConnectDialogEdit(); +private: + Q_OBJECT + Q_DISABLE_COPY(ConnectDialogEdit) + + void init(); + +protected: + bool bOk; + bool bCustomLabel; + ServerItem *m_si; + +public slots: + void validate(); + void accept(); + + void on_qbFill_clicked(); + void on_qbDiscard_clicked(); + void on_qcbShowPassword_toggled(bool); + void on_qleName_textEdited(const QString &); + void on_qleServer_textEdited(const QString &); + void showNotice(const QString &text); + bool updateFromClipboard(); + +public: + QString qsName, qsHostname, qsUsername, qsPassword; + unsigned short usPort; + ConnectDialogEdit(QWidget *parent, const QString &name, const QString &host, const QString &user, + unsigned short port, const QString &password); + /// Add a new Server + /// Prefills from clipboard content or the connected to server if available + ConnectDialogEdit(QWidget *parent); + virtual ~ConnectDialogEdit(); }; class ConnectDialog : public QDialog, public Ui::ConnectDialog { - friend class ServerView; - private: - Q_OBJECT - Q_DISABLE_COPY(ConnectDialog) - protected: - static QList<PublicInfo> qlPublicServers; - static QString qsUserCountry, qsUserCountryCode, qsUserContinentCode; - static Timer tPublicServers; - - QMenu *qmPopup; - QPushButton *qpbEdit; - - bool bPublicInit; - bool bAutoConnect; - - Timer tPing; - Timer tCurrent, tHover, tRestart; - QUdpSocket *qusSocket4; - QUdpSocket *qusSocket6; - QTimer *qtPingTick; - QList<ServerItem *> qlItems; - - ServerItem *siAutoConnect; - - QList<UnresolvedServerAddress> qlDNSLookup; - QSet<UnresolvedServerAddress> qsDNSActive; - QHash<UnresolvedServerAddress, QSet<ServerItem *> > qhDNSWait; - QHash<UnresolvedServerAddress, QList<ServerAddress> > qhDNSCache; - - QHash<ServerAddress, quint64> qhPingRand; - QHash<ServerAddress, QSet<ServerItem *> > qhPings; - - QMap<UnresolvedServerAddress, unsigned int> qmPingCache; - - QString qsSearchServername; - QString qsSearchLocation; - - bool bIPv4; - bool bIPv6; - int iPingIndex; - - bool bLastFound; - - /// bAllowPing determines whether ConnectDialog can use - /// UDP packets to ping remote hosts to be able to show a - /// ping latency and user count. - bool bAllowPing; - /// bAllowHostLookup determines whether ConnectDialog can - /// resolve hosts via DNS, Bonjour, and so on. - bool bAllowHostLookup; - /// bAllowBonjour determines whether ConfigDialog can use - /// Bonjour to find nearby servers on the local network. - bool bAllowBonjour; - /// bAllowFilters determines whether filters are available - /// in the ConfigDialog. If this option is diabled, the - /// 'Show All' filter is forced, and no other filter can - /// be chosen. - bool bAllowFilters; - - - void sendPing(const QHostAddress &, unsigned short port); - - void initList(); - void fillList(); - - void startDns(ServerItem *); - void stopDns(ServerItem *); - - /// Calls ConnectDialog::filterServer for each server in - /// the public server list - void filterPublicServerList() const; - /// Hides the given ServerItem according to the current - /// filter settings. It is checked that the name of the - /// given server matches ConnectDialog#qsSearchServername - /// and the location is equal to ConnectDialog#qsSearchLocation. - /// Lastly it is checked that the server is reachable or - /// populated, should the respective filters be set. - /// - /// \param si ServerItem that should be filtered - void filterServer(ServerItem * const si) const; - - /// Enumerates all countries in ConnectDialog#qlPublicServers - /// and adds an entry to the location filter Combobox with - /// with the country name as text, the countrycode as - /// data and the flag of the country as the icon. - void addCountriesToSearchLocation() const; - public slots: - void accept(); - void fetched(QByteArray xmlData, QUrl, QMap<QString, QString>); - - void udpReply(); - void lookedUp(); - void timeTick(); - - void on_qaFavoriteAdd_triggered(); - void on_qaFavoriteAddNew_triggered(); - void on_qaFavoriteEdit_triggered(); - void on_qaFavoriteRemove_triggered(); - void on_qaFavoriteCopy_triggered(); - void on_qaFavoritePaste_triggered(); - void on_qaUrl_triggered(); - void on_qtwServers_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *); - void on_qtwServers_itemDoubleClicked(QTreeWidgetItem *, int); - void on_qtwServers_customContextMenuRequested(const QPoint &); - /// If the expanded item is the public server list - /// the user is asked (only once) for consent to transmit - /// the IP to all public servers. If the user does not - /// consent the public server list is disabled. If - /// the user does consent the public server list is - /// filled and the search dialog is shown. - /// Finally name resolution is triggered for all child - /// items of the expanded item. - void on_qtwServers_itemExpanded(QTreeWidgetItem *item); - /// Hides the search dialog if the collapsed item is - /// the public server list - void on_qtwServers_itemCollapsed(QTreeWidgetItem *item); - void OnSortChanged(int, Qt::SortOrder); - public: - QString qsServer, qsUsername, qsPassword; - unsigned short usPort; - ConnectDialog(QWidget *parent, bool autoconnect); - ~ConnectDialog(); + friend class ServerView; + +private: + Q_OBJECT + Q_DISABLE_COPY(ConnectDialog) +protected: + static QList< PublicInfo > qlPublicServers; + static QString qsUserCountry, qsUserCountryCode, qsUserContinentCode; + static Timer tPublicServers; + + QMenu *qmPopup; + QPushButton *qpbEdit; + + bool bPublicInit; + bool bAutoConnect; + + Timer tPing; + Timer tCurrent, tHover, tRestart; + QUdpSocket *qusSocket4; + QUdpSocket *qusSocket6; + QTimer *qtPingTick; + QList< ServerItem * > qlItems; + + ServerItem *siAutoConnect; + + QList< UnresolvedServerAddress > qlDNSLookup; + QSet< UnresolvedServerAddress > qsDNSActive; + QHash< UnresolvedServerAddress, QSet< ServerItem * > > qhDNSWait; + QHash< UnresolvedServerAddress, QList< ServerAddress > > qhDNSCache; + + QHash< ServerAddress, quint64 > qhPingRand; + QHash< ServerAddress, QSet< ServerItem * > > qhPings; + + QMap< UnresolvedServerAddress, unsigned int > qmPingCache; + + QString qsSearchServername; + QString qsSearchLocation; + + bool bIPv4; + bool bIPv6; + int iPingIndex; + + bool bLastFound; + + /// bAllowPing determines whether ConnectDialog can use + /// UDP packets to ping remote hosts to be able to show a + /// ping latency and user count. + bool bAllowPing; + /// bAllowHostLookup determines whether ConnectDialog can + /// resolve hosts via DNS, Bonjour, and so on. + bool bAllowHostLookup; + /// bAllowBonjour determines whether ConfigDialog can use + /// Bonjour to find nearby servers on the local network. + bool bAllowBonjour; + /// bAllowFilters determines whether filters are available + /// in the ConfigDialog. If this option is diabled, the + /// 'Show All' filter is forced, and no other filter can + /// be chosen. + bool bAllowFilters; + + + void sendPing(const QHostAddress &, unsigned short port); + + void initList(); + void fillList(); + + void startDns(ServerItem *); + void stopDns(ServerItem *); + + /// Calls ConnectDialog::filterServer for each server in + /// the public server list + void filterPublicServerList() const; + /// Hides the given ServerItem according to the current + /// filter settings. It is checked that the name of the + /// given server matches ConnectDialog#qsSearchServername + /// and the location is equal to ConnectDialog#qsSearchLocation. + /// Lastly it is checked that the server is reachable or + /// populated, should the respective filters be set. + /// + /// \param si ServerItem that should be filtered + void filterServer(ServerItem *const si) const; + + /// Enumerates all countries in ConnectDialog#qlPublicServers + /// and adds an entry to the location filter Combobox with + /// with the country name as text, the countrycode as + /// data and the flag of the country as the icon. + void addCountriesToSearchLocation() const; +public slots: + void accept(); + void fetched(QByteArray xmlData, QUrl, QMap< QString, QString >); + + void udpReply(); + void lookedUp(); + void timeTick(); + + void on_qaFavoriteAdd_triggered(); + void on_qaFavoriteAddNew_triggered(); + void on_qaFavoriteEdit_triggered(); + void on_qaFavoriteRemove_triggered(); + void on_qaFavoriteCopy_triggered(); + void on_qaFavoritePaste_triggered(); + void on_qaUrl_triggered(); + void on_qtwServers_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *); + void on_qtwServers_itemDoubleClicked(QTreeWidgetItem *, int); + void on_qtwServers_customContextMenuRequested(const QPoint &); + /// If the expanded item is the public server list + /// the user is asked (only once) for consent to transmit + /// the IP to all public servers. If the user does not + /// consent the public server list is disabled. If + /// the user does consent the public server list is + /// filled and the search dialog is shown. + /// Finally name resolution is triggered for all child + /// items of the expanded item. + void on_qtwServers_itemExpanded(QTreeWidgetItem *item); + /// Hides the search dialog if the collapsed item is + /// the public server list + void on_qtwServers_itemCollapsed(QTreeWidgetItem *item); + void OnSortChanged(int, Qt::SortOrder); + +public: + QString qsServer, qsUsername, qsPassword; + unsigned short usPort; + ConnectDialog(QWidget *parent, bool autoconnect); + ~ConnectDialog(); #ifdef USE_BONJOUR - protected: - QList<BonjourRecord> qlBonjourActive; - public slots: - void onUpdateLanList(const QList<BonjourRecord> &); - void onLanBrowseError(DNSServiceErrorType); - - void onResolved(BonjourRecord, QString, int); - void onLanResolveError(BonjourRecord, DNSServiceErrorType); +protected: + QList< BonjourRecord > qlBonjourActive; +public slots: + void onUpdateLanList(const QList< BonjourRecord > &); + void onLanBrowseError(DNSServiceErrorType); + + void onResolved(BonjourRecord, QString, int); + void onLanResolveError(BonjourRecord, DNSServiceErrorType); #endif - private slots: - void on_qleSearchServername_textChanged(const QString &searchServername); - void on_qcbSearchLocation_currentIndexChanged(int searchLocationIndex); - void on_qcbFilter_currentIndexChanged(int filterIndex); +private slots: + void on_qleSearchServername_textChanged(const QString &searchServername); + void on_qcbSearchLocation_currentIndexChanged(int searchLocationIndex); + void on_qcbFilter_currentIndexChanged(int filterIndex); }; #endif diff --git a/src/mumble/CoreAudio.cpp b/src/mumble/CoreAudio.cpp index 85d2a376a..933e62308 100644 --- a/src/mumble/CoreAudio.cpp +++ b/src/mumble/CoreAudio.cpp @@ -7,7 +7,8 @@ #include "User.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" // Ignore deprecation warnings for the whole file, for now. @@ -26,12 +27,13 @@ void CoreAudioInit::destroy() { } CFStringRef CoreAudioSystem::QStringToCFString(const QString &str) { - return CFStringCreateWithCharacters(kCFAllocatorDefault, reinterpret_cast<const UniChar *>(str.unicode()), str.length()); + return CFStringCreateWithCharacters(kCFAllocatorDefault, reinterpret_cast< const UniChar * >(str.unicode()), + str.length()); } -const QList<audioDevice> CoreAudioSystem::getDeviceChoices(bool input) { - QHash<QString, QString> qhDevices = CoreAudioSystem::getDevices(input); - QList<audioDevice> qlReturn; +const QList< audioDevice > CoreAudioSystem::getDeviceChoices(bool input) { + QHash< QString, QString > qhDevices = CoreAudioSystem::getDevices(input); + QList< audioDevice > qlReturn; QStringList qlDevices; qhDevices.insert(QString(), tr("Default Device")); @@ -43,23 +45,20 @@ const QList<audioDevice> CoreAudioSystem::getDeviceChoices(bool input) { qlDevices.prepend(qsDev); } - foreach(const QString &qsIdentifier, qlDevices) { + foreach (const QString &qsIdentifier, qlDevices) { qlReturn << audioDevice(qhDevices.value(qsIdentifier), qsIdentifier); } return qlReturn; } -const QHash<QString, QString> CoreAudioSystem::getDevices(bool input) { - QHash<QString, QString> qhReturn; +const QHash< QString, QString > CoreAudioSystem::getDevices(bool input) { + QHash< QString, QString > qhReturn; UInt32 len, ndevs; OSStatus err; - AudioObjectPropertyAddress propertyAddress = { - kAudioHardwarePropertyDevices, - kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMaster - }; + AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMaster }; err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, &len); if (err != noErr) @@ -80,18 +79,18 @@ const QHash<QString, QString> CoreAudioSystem::getDevices(bool input) { char buf[4096]; /* Get number of channels, to determine whether we're an input or an output... */ - AudioBufferList *bufs = nullptr; + AudioBufferList *bufs = nullptr; propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; - err = AudioObjectGetPropertyDataSize(devs[i], &propertyAddress, 0, nullptr, &len); + err = AudioObjectGetPropertyDataSize(devs[i], &propertyAddress, 0, nullptr, &len); if (err != noErr) { qWarning("CoreAudioSystem: Failed to get length of AudioStreamConfiguration. Unable to allocate."); continue; } - bufs = reinterpret_cast<AudioBufferList *>(malloc(len)); + bufs = reinterpret_cast< AudioBufferList * >(malloc(len)); propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; - err = AudioObjectGetPropertyData(devs[i], &propertyAddress, 0, nullptr, &len, bufs); - if (! bufs || err != noErr) { + err = AudioObjectGetPropertyData(devs[i], &propertyAddress, 0, nullptr, &len, bufs); + if (!bufs || err != noErr) { qWarning("CoreAudioSystem: Failed to get AudioStreamConfiguration from device."); free(bufs); continue; @@ -104,15 +103,15 @@ const QHash<QString, QString> CoreAudioSystem::getDevices(bool input) { free(bufs); - if (! channels) + if (!channels) continue; /* Get device name. */ - len = sizeof(CFStringRef); - CFStringRef devName = nullptr; + len = sizeof(CFStringRef); + CFStringRef devName = nullptr; propertyAddress.mSelector = kAudioDevicePropertyDeviceNameCFString; - err = AudioObjectGetPropertyData(devs[i], &propertyAddress, 0, nullptr, &len, &devName); - if (! devName || err != noErr) { + err = AudioObjectGetPropertyData(devs[i], &propertyAddress, 0, nullptr, &len, &devName); + if (!devName || err != noErr) { qWarning("CoreAudioSystem: Failed to get device name. Skipping device."); } CFStringGetCString(devName, buf, 4096, kCFStringEncodingUTF8); @@ -120,10 +119,10 @@ const QHash<QString, QString> CoreAudioSystem::getDevices(bool input) { CFRelease(devName); /* Device UID. */ - CFStringRef devUid = nullptr; + CFStringRef devUid = nullptr; propertyAddress.mSelector = kAudioDevicePropertyDeviceUID; - err = AudioObjectGetPropertyData(devs[i], &propertyAddress, 0, nullptr, &len, &devUid); - if (! devUid || err != noErr) { + err = AudioObjectGetPropertyData(devs[i], &propertyAddress, 0, nullptr, &len, &devUid); + if (!devUid || err != noErr) { qWarning("CoreAudioSystem: Failed to get device UID. Skipping device."); } CFStringGetCString(devUid, buf, 4096, kCFStringEncodingUTF8); @@ -141,7 +140,7 @@ AudioInput *CoreAudioInputRegistrar::create() { return new CoreAudioInput(); } -const QList<audioDevice> CoreAudioInputRegistrar::getDeviceChoices() { +const QList< audioDevice > CoreAudioInputRegistrar::getDeviceChoices() { return CoreAudioSystem::getDeviceChoices(true); } @@ -159,7 +158,7 @@ AudioOutput *CoreAudioOutputRegistrar::create() { return new CoreAudioOutput(); } -const QList<audioDevice> CoreAudioOutputRegistrar::getDeviceChoices() { +const QList< audioDevice > CoreAudioOutputRegistrar::getDeviceChoices() { return CoreAudioSystem::getDeviceChoices(false); } @@ -175,27 +174,24 @@ CoreAudioInput::CoreAudioInput() { OSStatus err; AudioStreamBasicDescription fmt; AudioDeviceID devId = 0; - CFStringRef devUid = nullptr; + CFStringRef devUid = nullptr; UInt32 val, len; - AudioObjectPropertyAddress propertyAddress = { - 0, - kAudioDevicePropertyScopeInput, - kAudioObjectPropertyElementMaster - }; + AudioObjectPropertyAddress propertyAddress = { 0, kAudioDevicePropertyScopeInput, + kAudioObjectPropertyElementMaster }; memset(&buflist, 0, sizeof(AudioBufferList)); - if (! g.s.qsCoreAudioInput.isEmpty()) { + if (!g.s.qsCoreAudioInput.isEmpty()) { qWarning("CoreAudioInput: Set device to '%s'.", qPrintable(g.s.qsCoreAudioInput)); devUid = CoreAudioSystem::QStringToCFString(g.s.qsCoreAudioInput); AudioValueTranslation avt; - avt.mInputData = const_cast<struct __CFString **>(&devUid); - avt.mInputDataSize = sizeof(CFStringRef *); - avt.mOutputData = &devId; + avt.mInputData = const_cast< struct __CFString ** >(&devUid); + avt.mInputDataSize = sizeof(CFStringRef *); + avt.mOutputData = &devId; avt.mOutputDataSize = sizeof(AudioDeviceID); - len = sizeof(AudioValueTranslation); + len = sizeof(AudioValueTranslation); propertyAddress.mSelector = kAudioHardwarePropertyDeviceForUID; err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, &len, &avt); if (err != noErr) { @@ -205,7 +201,7 @@ CoreAudioInput::CoreAudioInput() { } else { qWarning("CoreAudioInput: Set device to 'Default Device'."); - len = sizeof(AudioDeviceID); + len = sizeof(AudioDeviceID); propertyAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, &len, &devId); if (err != noErr) { @@ -213,9 +209,9 @@ CoreAudioInput::CoreAudioInput() { return; } - len = sizeof(CFStringRef); + len = sizeof(CFStringRef); propertyAddress.mSelector = kAudioDevicePropertyDeviceUID; - err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &devUid); + err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &devUid); if (err != noErr) { qWarning("CoreAudioInput: Unable to get default device UID."); return; @@ -225,11 +221,11 @@ CoreAudioInput::CoreAudioInput() { Component comp; ComponentDescription desc; - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_HALOutput; + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_HALOutput; desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; comp = FindNextComponent(nullptr, &desc); if (!comp) { @@ -287,24 +283,24 @@ CoreAudioInput::CoreAudioInput() { qWarning("CoreAudioInput: Input device with more than one channel detected. Defaulting to 1."); } - iMicFreq = static_cast<int>(fmt.mSampleRate); + iMicFreq = static_cast< int >(fmt.mSampleRate); iMicChannels = 1; initializeMixer(); if (eMicFormat == SampleFloat) { - fmt.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked; + fmt.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked; fmt.mBitsPerChannel = sizeof(float) * 8; } else if (eMicFormat == SampleShort) { - fmt.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; + fmt.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; fmt.mBitsPerChannel = sizeof(short) * 8; } - fmt.mFormatID = kAudioFormatLinearPCM; - fmt.mSampleRate = iMicFreq; + fmt.mFormatID = kAudioFormatLinearPCM; + fmt.mSampleRate = iMicFreq; fmt.mChannelsPerFrame = iMicChannels; - fmt.mBytesPerFrame = iMicSampleSize; - fmt.mBytesPerPacket = iMicSampleSize; - fmt.mFramesPerPacket = 1; + fmt.mBytesPerFrame = iMicSampleSize; + fmt.mBytesPerPacket = iMicSampleSize; + fmt.mFramesPerPacket = 1; len = sizeof(AudioStreamBasicDescription); err = AudioUnitSetProperty(au, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &fmt, len); @@ -315,13 +311,14 @@ CoreAudioInput::CoreAudioInput() { err = AudioUnitAddPropertyListener(au, kAudioUnitProperty_StreamFormat, CoreAudioInput::propertyChange, this); if (err != noErr) { - qWarning("CoreAudioInput: Unable to create input property change listener. Unable to listen to property change events."); + qWarning("CoreAudioInput: Unable to create input property change listener. Unable to listen to property change " + "events."); } AURenderCallbackStruct cb; - cb.inputProc = CoreAudioInput::inputCallback; + cb.inputProc = CoreAudioInput::inputCallback; cb.inputProcRefCon = this; - len = sizeof(AURenderCallbackStruct); + len = sizeof(AURenderCallbackStruct); err = AudioUnitSetProperty(au, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &cb, len); if (err != noErr) { qWarning("CoreAudioInput: Unable to setup callback."); @@ -329,19 +326,19 @@ CoreAudioInput::CoreAudioInput() { } AudioValueRange range; - len = sizeof(AudioValueRange); + len = sizeof(AudioValueRange); propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange; - err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &range); + err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &range); if (err != noErr) { qWarning("CoreAudioInput: Unable to query for allowed buffer size ranges."); } else { qWarning("CoreAudioInput: BufferFrameSizeRange = (%.2f, %.2f)", range.mMinimum, range.mMaximum); } - int iActualBufferLength = iMicLength; - val = iMicLength; + int iActualBufferLength = iMicLength; + val = iMicLength; propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; - err = AudioObjectSetPropertyData(devId, &propertyAddress, 0, nullptr, sizeof(UInt32), &val); + err = AudioObjectSetPropertyData(devId, &propertyAddress, 0, nullptr, sizeof(UInt32), &val); if (err != noErr) { qWarning("CoreAudioInput: Unable to set preferred buffer size on device. Querying for device default."); len = sizeof(UInt32); @@ -355,10 +352,10 @@ CoreAudioInput::CoreAudioInput() { } buflist.mNumberBuffers = 1; - AudioBuffer *b = buflist.mBuffers; - b->mNumberChannels = iMicChannels; - b->mDataByteSize = iMicSampleSize * iActualBufferLength; - b->mData = calloc(1, b->mDataByteSize); + AudioBuffer *b = buflist.mBuffers; + b->mNumberChannels = iMicChannels; + b->mDataByteSize = iMicSampleSize * iActualBufferLength; + b->mData = calloc(1, b->mDataByteSize); err = AudioOutputUnitStart(au); if (err != noErr) { @@ -390,11 +387,11 @@ CoreAudioInput::~CoreAudioInput() { } OSStatus CoreAudioInput::inputCallback(void *udata, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, - UInt32 busnum, UInt32 nframes, AudioBufferList *buflist) { + UInt32 busnum, UInt32 nframes, AudioBufferList *buflist) { Q_UNUSED(udata); Q_UNUSED(buflist); - CoreAudioInput *i = reinterpret_cast<CoreAudioInput *>(udata); + CoreAudioInput *i = reinterpret_cast< CoreAudioInput * >(udata); OSStatus err; err = AudioUnitRender(i->au, flags, ts, busnum, nframes, &i->buflist); @@ -408,7 +405,8 @@ OSStatus CoreAudioInput::inputCallback(void *udata, AudioUnitRenderActionFlags * return noErr; } -void CoreAudioInput::propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, AudioUnitElement element) { +void CoreAudioInput::propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, + AudioUnitElement element) { Q_UNUSED(udata); Q_UNUSED(au); Q_UNUSED(scope); @@ -431,25 +429,22 @@ CoreAudioOutput::CoreAudioOutput() { AudioStreamBasicDescription fmt; unsigned int chanmasks[32]; AudioDeviceID devId = 0; - CFStringRef devUid = nullptr; + CFStringRef devUid = nullptr; UInt32 len; - AudioObjectPropertyAddress propertyAddress = { - 0, - kAudioDevicePropertyScopeOutput, - kAudioObjectPropertyElementMaster - }; + AudioObjectPropertyAddress propertyAddress = { 0, kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMaster }; - if (! g.s.qsCoreAudioOutput.isEmpty()) { + if (!g.s.qsCoreAudioOutput.isEmpty()) { devUid = CoreAudioSystem::QStringToCFString(g.s.qsCoreAudioOutput); qWarning("CoreAudioOutput: Set device to '%s'.", qPrintable(g.s.qsCoreAudioOutput)); AudioValueTranslation avt; - avt.mInputData = const_cast<struct __CFString **>(&devUid); - avt.mInputDataSize = sizeof(CFStringRef *); - avt.mOutputData = &devId; + avt.mInputData = const_cast< struct __CFString ** >(&devUid); + avt.mInputDataSize = sizeof(CFStringRef *); + avt.mOutputData = &devId; avt.mOutputDataSize = sizeof(AudioDeviceID); - len = sizeof(AudioValueTranslation); + len = sizeof(AudioValueTranslation); propertyAddress.mSelector = kAudioHardwarePropertyDeviceForUID; err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, &len, &avt); if (err != noErr) { @@ -459,7 +454,7 @@ CoreAudioOutput::CoreAudioOutput() { } else { qWarning("CoreAudioOutput: Set device to 'Default Device'."); - len = sizeof(AudioDeviceID); + len = sizeof(AudioDeviceID); propertyAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, &len, &devId); if (err != noErr) { @@ -467,24 +462,23 @@ CoreAudioOutput::CoreAudioOutput() { return; } - len = sizeof(CFStringRef); + len = sizeof(CFStringRef); propertyAddress.mSelector = kAudioDevicePropertyDeviceUID; - err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &devUid); + err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &devUid); if (err != noErr) { qWarning("CoreAudioOutput: Unable to get default device UID."); return; } - } Component comp; ComponentDescription desc; - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_HALOutput; + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_HALOutput; desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; comp = FindNextComponent(nullptr, &desc); if (!comp) { @@ -518,8 +512,8 @@ CoreAudioOutput::CoreAudioOutput() { return; } - iMixerFreq = static_cast<int>(fmt.mSampleRate); - iChannels = static_cast<int>(fmt.mChannelsPerFrame); + iMixerFreq = static_cast< int >(fmt.mSampleRate); + iChannels = static_cast< int >(fmt.mChannelsPerFrame); if (fmt.mFormatFlags & kAudioFormatFlagIsFloat) { eSampleFormat = SampleFloat; @@ -532,19 +526,19 @@ CoreAudioOutput::CoreAudioOutput() { initializeMixer(chanmasks); if (eSampleFormat == SampleFloat) { - fmt.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked; + fmt.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked; fmt.mBitsPerChannel = sizeof(float) * 8; } else if (eSampleFormat == SampleShort) { - fmt.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; + fmt.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; fmt.mBitsPerChannel = sizeof(short) * 8; } - fmt.mFormatID = kAudioFormatLinearPCM; - fmt.mSampleRate = iMixerFreq; + fmt.mFormatID = kAudioFormatLinearPCM; + fmt.mSampleRate = iMixerFreq; fmt.mChannelsPerFrame = iChannels; - fmt.mBytesPerFrame = iSampleSize; - fmt.mBytesPerPacket = iSampleSize; - fmt.mFramesPerPacket = 1; + fmt.mBytesPerFrame = iSampleSize; + fmt.mBytesPerPacket = iSampleSize; + fmt.mFramesPerPacket = 1; len = sizeof(AudioStreamBasicDescription); err = AudioUnitSetProperty(au, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &fmt, len); @@ -555,13 +549,14 @@ CoreAudioOutput::CoreAudioOutput() { err = AudioUnitAddPropertyListener(au, kAudioUnitProperty_StreamFormat, CoreAudioOutput::propertyChange, this); if (err != noErr) { - qWarning("CoreAudioOutput: Unable to create output property change listener. Unable to listen to property change events."); + qWarning("CoreAudioOutput: Unable to create output property change listener. Unable to listen to property " + "change events."); } AURenderCallbackStruct cb; - cb.inputProc = CoreAudioOutput::outputCallback; + cb.inputProc = CoreAudioOutput::outputCallback; cb.inputProcRefCon = this; - len = sizeof(AURenderCallbackStruct); + len = sizeof(AURenderCallbackStruct); err = AudioUnitSetProperty(au, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, 0, &cb, len); if (err != noErr) { qWarning("CoreAudioOutput: Unable to setup callback."); @@ -569,9 +564,9 @@ CoreAudioOutput::CoreAudioOutput() { } AudioValueRange range; - len = sizeof(AudioValueRange); + len = sizeof(AudioValueRange); propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange; - err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &range); + err = AudioObjectGetPropertyData(devId, &propertyAddress, 0, nullptr, &len, &range); if (err != noErr) { qWarning("CoreAudioOutput: Unable to query for allowed buffer size ranges."); } else { @@ -579,9 +574,9 @@ CoreAudioOutput::CoreAudioOutput() { qWarning("CoreAudioOutput: BufferFrameSizeRange = (%.2f, %.2f)", range.mMinimum, range.mMaximum); } - UInt32 val = (iFrameSize * iMixerFreq) / SAMPLE_RATE; + UInt32 val = (iFrameSize * iMixerFreq) / SAMPLE_RATE; propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; - err = AudioObjectSetPropertyData(devId, &propertyAddress, 0, nullptr, sizeof(UInt32), &val); + err = AudioObjectSetPropertyData(devId, &propertyAddress, 0, nullptr, sizeof(UInt32), &val); if (err != noErr) { qWarning("CoreAudioOutput: Could not set requested buffer size for device. Continuing with default."); } @@ -612,16 +607,16 @@ CoreAudioOutput::~CoreAudioOutput() { } OSStatus CoreAudioOutput::outputCallback(void *udata, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, - UInt32 busnum, UInt32 nframes, AudioBufferList *buflist) { + UInt32 busnum, UInt32 nframes, AudioBufferList *buflist) { Q_UNUSED(flags); Q_UNUSED(ts); Q_UNUSED(busnum); - CoreAudioOutput *o = reinterpret_cast<CoreAudioOutput *>(udata); - AudioBuffer *buf = buflist->mBuffers; + CoreAudioOutput *o = reinterpret_cast< CoreAudioOutput * >(udata); + AudioBuffer *buf = buflist->mBuffers; bool done = o->mix(buf->mData, nframes); - if (! done) { + if (!done) { buf->mDataByteSize = 0; return -1; } @@ -629,7 +624,8 @@ OSStatus CoreAudioOutput::outputCallback(void *udata, AudioUnitRenderActionFlags return noErr; } -void CoreAudioOutput::propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, AudioUnitElement element) { +void CoreAudioOutput::propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, + AudioUnitElement element) { Q_UNUSED(udata); Q_UNUSED(au); Q_UNUSED(scope); diff --git a/src/mumble/CoreAudio.h b/src/mumble/CoreAudio.h index 4b8a1326b..c665adad0 100644 --- a/src/mumble/CoreAudio.h +++ b/src/mumble/CoreAudio.h @@ -4,73 +4,77 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef MUMBLE_MUMBLE_COREAUDIO_H_ -#define MUMBLE_MUMBLE_COREAUDIO_H_ +# define MUMBLE_MUMBLE_COREAUDIO_H_ -#include "AudioInput.h" -#include "AudioOutput.h" +# include "AudioInput.h" +# include "AudioOutput.h" -#include <AudioToolbox/AudioToolbox.h> -#include <Carbon/Carbon.h> +# include <AudioToolbox/AudioToolbox.h> +# include <Carbon/Carbon.h> -#include "Global.h" +# include "Global.h" class CoreAudioSystem : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(CoreAudioSystem) - public: - static CFStringRef QStringToCFString(const QString &str); - static const QHash<QString, QString> getDevices(bool input); - static const QList<audioDevice> getDeviceChoices(bool input); +private: + Q_OBJECT + Q_DISABLE_COPY(CoreAudioSystem) +public: + static CFStringRef QStringToCFString(const QString &str); + static const QHash< QString, QString > getDevices(bool input); + static const QList< audioDevice > getDeviceChoices(bool input); }; class CoreAudioInput : public AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(CoreAudioInput) - protected: - AudioUnit au; - AUEventListenerRef el; - AudioBufferList buflist; - static void propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, AudioUnitElement element); - static OSStatus inputCallback(void *udata, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, - UInt32 busnum, UInt32 npackets, AudioBufferList *buflist); - public: - CoreAudioInput(); - ~CoreAudioInput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(CoreAudioInput) +protected: + AudioUnit au; + AUEventListenerRef el; + AudioBufferList buflist; + static void propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, + AudioUnitElement element); + static OSStatus inputCallback(void *udata, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, + UInt32 busnum, UInt32 npackets, AudioBufferList *buflist); + +public: + CoreAudioInput(); + ~CoreAudioInput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; class CoreAudioOutput : public AudioOutput { - private: - Q_OBJECT - Q_DISABLE_COPY(CoreAudioOutput) - protected: - AudioUnit au; - AUEventListenerRef el; - static void propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, AudioUnitElement element); - static OSStatus outputCallback(void *udata, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, - UInt32 busnum, UInt32 npackets, AudioBufferList *buflist); - public: - CoreAudioOutput(); - ~CoreAudioOutput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(CoreAudioOutput) +protected: + AudioUnit au; + AUEventListenerRef el; + static void propertyChange(void *udata, AudioUnit au, AudioUnitPropertyID prop, AudioUnitScope scope, + AudioUnitElement element); + static OSStatus outputCallback(void *udata, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *ts, + UInt32 busnum, UInt32 npackets, AudioBufferList *buflist); + +public: + CoreAudioOutput(); + ~CoreAudioOutput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; class CoreAudioInputRegistrar : public AudioInputRegistrar { public: CoreAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("CoreAudio"), 10) {} virtual AudioInput *create(); - virtual const QList<audioDevice> getDeviceChoices(); + virtual const QList< audioDevice > getDeviceChoices(); virtual void setDeviceChoice(const QVariant &, Settings &); virtual bool canEcho(const QString &) const; }; class CoreAudioOutputRegistrar : public AudioOutputRegistrar { public: - CoreAudioOutputRegistrar(): AudioOutputRegistrar(QLatin1String("CoreAudio"), 10) {} + CoreAudioOutputRegistrar() : AudioOutputRegistrar(QLatin1String("CoreAudio"), 10) {} virtual AudioOutput *create(); - virtual const QList<audioDevice> getDeviceChoices(); + virtual const QList< audioDevice > getDeviceChoices(); virtual void setDeviceChoice(const QVariant &, Settings &); bool canMuteOthers() const; }; @@ -78,6 +82,7 @@ public: class CoreAudioInit : public DeferInit { CoreAudioInputRegistrar *cairReg; CoreAudioOutputRegistrar *caorReg; + public: CoreAudioInit() : cairReg(nullptr), caorReg(nullptr) {} void initialize(); diff --git a/src/mumble/CrashReporter.cpp b/src/mumble/CrashReporter.cpp index 6b743aea3..57d5c2d7d 100644 --- a/src/mumble/CrashReporter.cpp +++ b/src/mumble/CrashReporter.cpp @@ -5,10 +5,10 @@ #include "CrashReporter.h" -#include "Global.h" +#include "EnvUtils.h" #include "NetworkConfig.h" #include "OSInfo.h" -#include "EnvUtils.h" +#include "Global.h" #include <QtCore/QProcess> #include <QtCore/QTemporaryFile> @@ -19,26 +19,28 @@ CrashReporter::CrashReporter(QWidget *p) : QDialog(p) { setWindowTitle(tr("Mumble Crash Report")); - QVBoxLayout *vbl= new QVBoxLayout(this); + QVBoxLayout *vbl = new QVBoxLayout(this); QLabel *l; - l = new QLabel(tr("<p><b>We're terribly sorry, but it seems Mumble has crashed. Do you want to send a crash report to the Mumble developers?</b></p>" - "<p>The crash report contains a partial copy of Mumble's memory at the time it crashed, and will help the developers fix the problem.</p>")); + l = new QLabel(tr("<p><b>We're terribly sorry, but it seems Mumble has crashed. Do you want to send a crash report " + "to the Mumble developers?</b></p>" + "<p>The crash report contains a partial copy of Mumble's memory at the time it crashed, and will " + "help the developers fix the problem.</p>")); vbl->addWidget(l); QHBoxLayout *hbl = new QHBoxLayout(); qleEmail = new QLineEdit(g.qs->value(QLatin1String("crashemail")).toString()); - l = new QLabel(tr("Email address (optional)")); + l = new QLabel(tr("Email address (optional)")); l->setBuddy(qleEmail); hbl->addWidget(l); hbl->addWidget(qleEmail, 1); vbl->addLayout(hbl); - qteDescription=new QTextEdit(); + qteDescription = new QTextEdit(); l->setBuddy(qteDescription); l = new QLabel(tr("Please describe briefly, in English, what you were doing at the time of the crash")); @@ -58,9 +60,9 @@ CrashReporter::CrashReporter(QWidget *p) : QDialog(p) { connect(dbb, SIGNAL(rejected()), this, SLOT(reject())); vbl->addWidget(dbb); - qelLoop = new QEventLoop(this); + qelLoop = new QEventLoop(this); qpdProgress = nullptr; - qnrReply = nullptr; + qnrReply = nullptr; } CrashReporter::~CrashReporter() { @@ -72,24 +74,32 @@ void CrashReporter::uploadFinished() { qpdProgress->reset(); if (qnrReply->error() == QNetworkReply::NoError) { if (qnrReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200) - QMessageBox::information(nullptr, tr("Crash upload successful"), tr("Thank you for helping make Mumble better!")); + QMessageBox::information(nullptr, tr("Crash upload successful"), + tr("Thank you for helping make Mumble better!")); else - QMessageBox::critical(nullptr, tr("Crash upload failed"), tr("We're really sorry, but it appears the crash upload has failed with error %1 %2. Please inform a developer.").arg(qnrReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()).arg(qnrReply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); + QMessageBox::critical(nullptr, tr("Crash upload failed"), + tr("We're really sorry, but it appears the crash upload has failed with error %1 %2. " + "Please inform a developer.") + .arg(qnrReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()) + .arg(qnrReply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); } else { - QMessageBox::critical(nullptr, tr("Crash upload failed"), tr("This really isn't funny, but apparently there's a bug in the crash reporting code, and we've failed to upload the report. You may inform a developer about error %1").arg(qnrReply->error())); + QMessageBox::critical(nullptr, tr("Crash upload failed"), + tr("This really isn't funny, but apparently there's a bug in the crash reporting code, " + "and we've failed to upload the report. You may inform a developer about error %1") + .arg(qnrReply->error())); } qelLoop->exit(0); } void CrashReporter::uploadProgress(qint64 sent, qint64 total) { - qpdProgress->setMaximum(static_cast<int>(total)); - qpdProgress->setValue(static_cast<int>(sent)); + qpdProgress->setMaximum(static_cast< int >(total)); + qpdProgress->setValue(static_cast< int >(sent)); } void CrashReporter::run() { QByteArray qbaDumpContents; QFile qfCrashDump(g.qdBasePath.filePath(QLatin1String("mumble.dmp"))); - if (! qfCrashDump.exists()) + if (!qfCrashDump.exists()) return; qfCrashDump.open(QIODevice::ReadOnly); @@ -112,7 +122,7 @@ void CrashReporter::run() { /* Find the real crash report. */ QDir qdCrashReports(QDir::home().absolutePath() + QLatin1String("/Library/Logs/DiagnosticReports/")); - if (! qdCrashReports.exists()) { + if (!qdCrashReports.exists()) { qdCrashReports.setPath(QDir::home().absolutePath() + QLatin1String("/Library/Logs/CrashReporter/")); } @@ -126,8 +136,8 @@ void CrashReporter::run() { * Figure out if our delta is sufficiently close to the Apple crash dump, or * if something weird happened. */ - foreach(QFileInfo fi, qfilEntries) { - qint64 delta = qAbs<qint64>(qdtModification.secsTo(fi.lastModified())); + foreach (QFileInfo fi, qfilEntries) { + qint64 delta = qAbs< qint64 >(qdtModification.secsTo(fi.lastModified())); if (delta < 8) { QFile f(fi.absoluteFilePath()); f.open(QIODevice::ReadOnly); @@ -150,7 +160,7 @@ void CrashReporter::run() { qsl << QLatin1String("/t"); qsl << qtf.fileName(); - QString app = QLatin1String("dxdiag.exe"); + QString app = QLatin1String("dxdiag.exe"); QString systemRoot = EnvUtils::getenv(QLatin1String("SystemRoot")); if (systemRoot.count() > 0) { @@ -161,7 +171,7 @@ void CrashReporter::run() { if (qp.waitForFinished(30000)) { if (qtf.open()) { QByteArray qba = qtf.readAll(); - details = QString::fromLocal8Bit(qba); + details = QString::fromLocal8Bit(qba); } } else { details = QLatin1String("Failed to run dxdiag"); @@ -182,21 +192,36 @@ void CrashReporter::run() { qpdProgress->setValue(0); connect(qpdProgress, SIGNAL(canceled()), qelLoop, SLOT(quit())); - QString boundary = QString::fromLatin1("---------------------------%1").arg(QDateTime::currentDateTime().toTime_t()); - - QString os = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"os\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n").arg(boundary, OSInfo::getOS(), OSInfo::getOSVersion()); - QString ver = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"ver\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n").arg(boundary, QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE)); - QString email = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"email\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, qleEmail->text()); - QString descr = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"desc\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, qteDescription->toPlainText()); - QString det = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"details\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, details); - QString head = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"dump\"; filename=\"mumble.dmp\"\r\nContent-Type: binary/octet-stream\r\n\r\n").arg(boundary); + QString boundary = + QString::fromLatin1("---------------------------%1").arg(QDateTime::currentDateTime().toTime_t()); + + QString os = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; " + "name=\"os\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n") + .arg(boundary, OSInfo::getOS(), OSInfo::getOSVersion()); + QString ver = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; " + "name=\"ver\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n") + .arg(boundary, QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE)); + QString email = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; " + "name=\"email\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n") + .arg(boundary, qleEmail->text()); + QString descr = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; " + "name=\"desc\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n") + .arg(boundary, qteDescription->toPlainText()); + QString det = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; " + "name=\"details\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n") + .arg(boundary, details); + QString head = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"dump\"; " + "filename=\"mumble.dmp\"\r\nContent-Type: binary/octet-stream\r\n\r\n") + .arg(boundary); QString end = QString::fromLatin1("\r\n--%1--\r\n").arg(boundary); - QByteArray post = os.toUtf8() + ver.toUtf8() + email.toUtf8() + descr.toUtf8() + det.toUtf8() + head.toUtf8() + qbaDumpContents + end.toUtf8(); + QByteArray post = os.toUtf8() + ver.toUtf8() + email.toUtf8() + descr.toUtf8() + det.toUtf8() + head.toUtf8() + + qbaDumpContents + end.toUtf8(); QUrl url(QLatin1String("https://crash-report.mumble.info/v1/report")); QNetworkRequest req(url); - req.setHeader(QNetworkRequest::ContentTypeHeader, QString::fromLatin1("multipart/form-data; boundary=%1").arg(boundary)); + req.setHeader(QNetworkRequest::ContentTypeHeader, + QString::fromLatin1("multipart/form-data; boundary=%1").arg(boundary)); req.setHeader(QNetworkRequest::ContentLengthHeader, QString::number(post.size())); Network::prepareRequest(req); qnrReply = g.nam->post(req, post); @@ -206,6 +231,6 @@ void CrashReporter::run() { qelLoop->exec(QEventLoop::DialogExec); } - if (! qfCrashDump.remove()) + if (!qfCrashDump.remove()) qWarning("CrashReporeter: Unable to remove crash file."); } diff --git a/src/mumble/CrashReporter.h b/src/mumble/CrashReporter.h index 85e41a71b..db8010a9a 100644 --- a/src/mumble/CrashReporter.h +++ b/src/mumble/CrashReporter.h @@ -4,33 +4,34 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef MUMBLE_MUMBLE_CRASHREPORTER_H_ -#define MUMBLE_MUMBLE_CRASHREPORTER_H_ +# define MUMBLE_MUMBLE_CRASHREPORTER_H_ -#include <QtCore/QObject> -#include <QtCore/QEventLoop> -#include <QtNetwork/QNetworkReply> -#include <QtWidgets/QDialog> -#include <QtWidgets/QProgressDialog> -#include <QtWidgets/QLineEdit> -#include <QtWidgets/QTextEdit> +# include <QtCore/QEventLoop> +# include <QtCore/QObject> +# include <QtNetwork/QNetworkReply> +# include <QtWidgets/QDialog> +# include <QtWidgets/QLineEdit> +# include <QtWidgets/QProgressDialog> +# include <QtWidgets/QTextEdit> class CrashReporter : QDialog { - Q_OBJECT - Q_DISABLE_COPY(CrashReporter) + Q_OBJECT + Q_DISABLE_COPY(CrashReporter) - public: - CrashReporter(QWidget *p = 0); - ~CrashReporter() Q_DECL_OVERRIDE; - void run(); - protected: - QEventLoop *qelLoop; - QProgressDialog *qpdProgress; - QNetworkReply *qnrReply; - QLineEdit *qleEmail; - QTextEdit *qteDescription; - public slots: - void uploadFinished(); - void uploadProgress(qint64, qint64); +public: + CrashReporter(QWidget *p = 0); + ~CrashReporter() Q_DECL_OVERRIDE; + void run(); + +protected: + QEventLoop *qelLoop; + QProgressDialog *qpdProgress; + QNetworkReply *qnrReply; + QLineEdit *qleEmail; + QTextEdit *qteDescription; +public slots: + void uploadFinished(); + void uploadProgress(qint64, qint64); }; #else diff --git a/src/mumble/CustomElements.cpp b/src/mumble/CustomElements.cpp index 2375e86c6..b2e8af2d3 100644 --- a/src/mumble/CustomElements.cpp +++ b/src/mumble/CustomElements.cpp @@ -6,22 +6,24 @@ #include "CustomElements.h" #include "ClientUser.h" -#include "MainWindow.h" #include "Log.h" +#include "MainWindow.h" #include "Utils.h" +#include <QMimeData> #include <QtCore/QTimer> #include <QtGui/QAbstractTextDocumentLayout> #include <QtGui/QClipboard> #include <QtGui/QContextMenuEvent> #include <QtGui/QKeyEvent> #include <QtWidgets/QScrollBar> -#include <QMimeData> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -LogTextBrowser::LogTextBrowser(QWidget *p) : QTextBrowser(p) {} +LogTextBrowser::LogTextBrowser(QWidget *p) : QTextBrowser(p) { +} void LogTextBrowser::resizeEvent(QResizeEvent *e) { scrollLogToBottom(); @@ -135,11 +137,11 @@ QSize ChatbarTextEdit::minimumSizeHint() const { } QSize ChatbarTextEdit::sizeHint() const { - QSize sh = QTextEdit::sizeHint(); - const int minHeight = minimumSizeHint().height(); + QSize sh = QTextEdit::sizeHint(); + const int minHeight = minimumSizeHint().height(); const int documentHeight = document()->documentLayout()->documentSize().height(); sh.setHeight(std::max(minHeight, documentHeight)); - const_cast<ChatbarTextEdit *>(this)->setMaximumHeight(sh.height()); + const_cast< ChatbarTextEdit * >(this)->setMaximumHeight(sh.height()); return sh; } @@ -171,20 +173,20 @@ void ChatbarTextEdit::setDefaultText(const QString &new_default, bool force) { } void ChatbarTextEdit::insertFromMimeData(const QMimeData *source) { - if (! sendImagesFromMimeData(source)){ + if (!sendImagesFromMimeData(source)) { QTextEdit::insertFromMimeData(source); } } -bool ChatbarTextEdit::sendImagesFromMimeData(const QMimeData *source){ +bool ChatbarTextEdit::sendImagesFromMimeData(const QMimeData *source) { if (source->hasImage()) { // Process the image pasted onto the chatbar. if (g.bAllowHTML) { - QImage image = qvariant_cast<QImage>(source->imageData()); + QImage image = qvariant_cast< QImage >(source->imageData()); QString imgHtml = QLatin1String("<br />") + Log::imageToImg(image); - if (static_cast<unsigned int>(imgHtml.length()) < g.uiImageLength) { + if (static_cast< unsigned int >(imgHtml.length()) < g.uiImageLength) { emit pastedImage(imgHtml); return true; } else { @@ -193,19 +195,19 @@ bool ChatbarTextEdit::sendImagesFromMimeData(const QMimeData *source){ } } else if (source->hasUrls()) { // Process the files dropped onto the chatbar. URLs here should be understood as the URIs of files. - QList<QUrl> urlList = source->urls(); + QList< QUrl > urlList = source->urls(); int count = 0; - for (int i = 0; i < urlList.size(); ++i) - { + for (int i = 0; i < urlList.size(); ++i) { QString path = urlList[i].toLocalFile(); QImage image(path); - if (image.isNull()) continue; + if (image.isNull()) + continue; QString imgHtml = QLatin1String("<br />") + Log::imageToImg(image); - if (static_cast<unsigned int>(imgHtml.length()) < g.uiImageLength) { + if (static_cast< unsigned int >(imgHtml.length()) < g.uiImageLength) { emit pastedImage(imgHtml); ++count; } else { @@ -224,7 +226,7 @@ bool ChatbarTextEdit::event(QEvent *evt) { } if (evt->type() == QEvent::KeyPress) { - QKeyEvent *kev = static_cast<QKeyEvent*>(evt); + QKeyEvent *kev = static_cast< QKeyEvent * >(evt); if ((kev->key() == Qt::Key_Enter || kev->key() == Qt::Key_Return) && !(kev->modifiers() & Qt::ShiftModifier)) { const QString msg = toPlainText(); if (!msg.isEmpty()) { @@ -263,12 +265,11 @@ unsigned int ChatbarTextEdit::completeAtCursor() { // Get an alphabetically sorted list of usernames unsigned int id = 0; - QList<QString> qlsUsernames; + QList< QString > qlsUsernames; - if (ClientUser::c_qmUsers.empty()) return id; - foreach(ClientUser *usr, ClientUser::c_qmUsers) { - qlsUsernames.append(usr->qsName); - } + if (ClientUser::c_qmUsers.empty()) + return id; + foreach (ClientUser *usr, ClientUser::c_qmUsers) { qlsUsernames.append(usr->qsName); } std::sort(qlsUsernames.begin(), qlsUsernames.end()); QString target = QString(); @@ -279,23 +280,24 @@ unsigned int ChatbarTextEdit::completeAtCursor() { tc.insertText(target); } else { bool bBaseIsName = false; - int iend = tc.position(); - int istart = toPlainText().lastIndexOf(QLatin1Char(' '), iend - 1) + 1; - QString base = toPlainText().mid(istart, iend - istart); + int iend = tc.position(); + int istart = toPlainText().lastIndexOf(QLatin1Char(' '), iend - 1) + 1; + QString base = toPlainText().mid(istart, iend - istart); tc.setPosition(istart); tc.setPosition(iend, QTextCursor::KeepAnchor); if (qlsUsernames.last() == base) { bBaseIsName = true; - target = qlsUsernames.first(); + target = qlsUsernames.first(); } else { if (qlsUsernames.contains(base)) { // Prevent to complete to what's already there - while (qlsUsernames.takeFirst() != base) {} + while (qlsUsernames.takeFirst() != base) { + } bBaseIsName = true; } - foreach(QString name, qlsUsernames) { + foreach (QString name, qlsUsernames) { if (name.startsWith(base, Qt::CaseInsensitive)) { target = name; break; @@ -316,7 +318,7 @@ unsigned int ChatbarTextEdit::completeAtCursor() { if (!target.isEmpty()) { setTextCursor(tc); - foreach(ClientUser *usr, ClientUser::c_qmUsers) { + foreach (ClientUser *usr, ClientUser::c_qmUsers) { if (usr->qsName == target) { id = usr->uiSession; break; @@ -380,13 +382,13 @@ QSize DockTitleBar::sizeHint() const { } QSize DockTitleBar::minimumSizeHint() const { - return QSize(size,size); + return QSize(size, size); } bool DockTitleBar::eventFilter(QObject *, QEvent *evt) { - QDockWidget *qdw = qobject_cast<QDockWidget*>(parentWidget()); + QDockWidget *qdw = qobject_cast< QDockWidget * >(parentWidget()); - if (! this->isEnabled()) + if (!this->isEnabled()) return false; switch (evt->type()) { @@ -394,17 +396,18 @@ bool DockTitleBar::eventFilter(QObject *, QEvent *evt) { case QEvent::Enter: case QEvent::MouseMove: case QEvent::MouseButtonRelease: { - newsize = 0; - QPoint p = qdw->mapFromGlobal(QCursor::pos()); - if ((p.x() >= iroundf(static_cast<float>(qdw->width()) * 0.1f + 0.5f)) && (p.x() < iroundf(static_cast<float>(qdw->width()) * 0.9f + 0.5f)) && (p.y() >= 0) && (p.y() < 15)) - newsize = 15; - if (newsize > 0 && !qtTick->isActive()) - qtTick->start(500); - else if ((newsize == size) && qtTick->isActive()) - qtTick->stop(); - else if (newsize == 0) - tick(); - } + newsize = 0; + QPoint p = qdw->mapFromGlobal(QCursor::pos()); + if ((p.x() >= iroundf(static_cast< float >(qdw->width()) * 0.1f + 0.5f)) + && (p.x() < iroundf(static_cast< float >(qdw->width()) * 0.9f + 0.5f)) && (p.y() >= 0) && (p.y() < 15)) + newsize = 15; + if (newsize > 0 && !qtTick->isActive()) + qtTick->start(500); + else if ((newsize == size) && qtTick->isActive()) + qtTick->stop(); + else if (newsize == 0) + tick(); + } default: break; } @@ -413,7 +416,7 @@ bool DockTitleBar::eventFilter(QObject *, QEvent *evt) { } void DockTitleBar::tick() { - QDockWidget *qdw = qobject_cast<QDockWidget*>(parentWidget()); + QDockWidget *qdw = qobject_cast< QDockWidget * >(parentWidget()); if (newsize == size) return; diff --git a/src/mumble/CustomElements.h b/src/mumble/CustomElements.h index 4ba63bc71..e05fa9b99 100644 --- a/src/mumble/CustomElements.h +++ b/src/mumble/CustomElements.h @@ -12,81 +12,87 @@ #include <QtWidgets/QTextEdit> class LogTextBrowser : public QTextBrowser { - private: - Q_OBJECT - Q_DISABLE_COPY(LogTextBrowser) - protected: - void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE; - bool event(QEvent *e) Q_DECL_OVERRIDE; - public: - LogTextBrowser(QWidget *p = nullptr); +private: + Q_OBJECT + Q_DISABLE_COPY(LogTextBrowser) +protected: + void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE; + bool event(QEvent *e) Q_DECL_OVERRIDE; - int getLogScroll(); - int getLogScrollMaximum(); - void setLogScroll(int scroll_pos); - void scrollLogToBottom(); +public: + LogTextBrowser(QWidget *p = nullptr); + + int getLogScroll(); + int getLogScrollMaximum(); + void setLogScroll(int scroll_pos); + void scrollLogToBottom(); }; class ChatbarTextEdit : public QTextEdit { - private: - Q_OBJECT - Q_DISABLE_COPY(ChatbarTextEdit) - void inFocus(bool); - QStringList qslHistory; - QString qsHistoryTemp; - int iHistoryIndex; - static const int MAX_HISTORY = 50; - protected: - QString qsDefaultText; - bool bDefaultVisible; - void focusInEvent(QFocusEvent *) Q_DECL_OVERRIDE; - void focusOutEvent(QFocusEvent *) Q_DECL_OVERRIDE; - void contextMenuEvent(QContextMenuEvent *) Q_DECL_OVERRIDE; - void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE; - void dragMoveEvent(QDragMoveEvent *) Q_DECL_OVERRIDE; - void dropEvent(QDropEvent *) Q_DECL_OVERRIDE; - bool event(QEvent *) Q_DECL_OVERRIDE; - QSize minimumSizeHint() const Q_DECL_OVERRIDE; - QSize sizeHint() const Q_DECL_OVERRIDE; - void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE; - void insertFromMimeData(const QMimeData *source) Q_DECL_OVERRIDE; - bool sendImagesFromMimeData(const QMimeData *source); - public: - void setDefaultText(const QString &, bool = false); - unsigned int completeAtCursor(); - signals: - void tabPressed(void); - void backtabPressed(void); - void ctrlSpacePressed(void); - void entered(QString); - void pastedImage(QString); - public slots: - void pasteAndSend_triggered(); - void doResize(); - void doScrollbar(); - void addToHistory(const QString &str); - void historyUp(); - void historyDown(); - public: - ChatbarTextEdit(QWidget *p = nullptr); +private: + Q_OBJECT + Q_DISABLE_COPY(ChatbarTextEdit) + void inFocus(bool); + QStringList qslHistory; + QString qsHistoryTemp; + int iHistoryIndex; + static const int MAX_HISTORY = 50; + +protected: + QString qsDefaultText; + bool bDefaultVisible; + void focusInEvent(QFocusEvent *) Q_DECL_OVERRIDE; + void focusOutEvent(QFocusEvent *) Q_DECL_OVERRIDE; + void contextMenuEvent(QContextMenuEvent *) Q_DECL_OVERRIDE; + void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE; + void dragMoveEvent(QDragMoveEvent *) Q_DECL_OVERRIDE; + void dropEvent(QDropEvent *) Q_DECL_OVERRIDE; + bool event(QEvent *) Q_DECL_OVERRIDE; + QSize minimumSizeHint() const Q_DECL_OVERRIDE; + QSize sizeHint() const Q_DECL_OVERRIDE; + void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE; + void insertFromMimeData(const QMimeData *source) Q_DECL_OVERRIDE; + bool sendImagesFromMimeData(const QMimeData *source); + +public: + void setDefaultText(const QString &, bool = false); + unsigned int completeAtCursor(); +signals: + void tabPressed(void); + void backtabPressed(void); + void ctrlSpacePressed(void); + void entered(QString); + void pastedImage(QString); +public slots: + void pasteAndSend_triggered(); + void doResize(); + void doScrollbar(); + void addToHistory(const QString &str); + void historyUp(); + void historyDown(); + +public: + ChatbarTextEdit(QWidget *p = nullptr); }; class DockTitleBar : public QLabel { - private: - Q_OBJECT - Q_DISABLE_COPY(DockTitleBar) - protected: - QTimer *qtTick; - int size; - int newsize; - public: - DockTitleBar(); - QSize sizeHint() const Q_DECL_OVERRIDE; - QSize minimumSizeHint() const Q_DECL_OVERRIDE; - public slots: - void tick(); - protected: - bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(DockTitleBar) +protected: + QTimer *qtTick; + int size; + int newsize; + +public: + DockTitleBar(); + QSize sizeHint() const Q_DECL_OVERRIDE; + QSize minimumSizeHint() const Q_DECL_OVERRIDE; +public slots: + void tick(); + +protected: + bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; }; #endif // CUSTOMELEMENTS_H_ diff --git a/src/mumble/DBus.cpp b/src/mumble/DBus.cpp index 60d845053..2b4c8ec11 100644 --- a/src/mumble/DBus.cpp +++ b/src/mumble/DBus.cpp @@ -14,26 +14,29 @@ #include <QtDBus/QDBusConnection> #include <QtDBus/QDBusMessage> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" MumbleDBus::MumbleDBus(QObject *mw) : QDBusAbstractAdaptor(mw) { } void MumbleDBus::openUrl(const QString &url, const QDBusMessage &msg) { - QUrl u = QUrl::fromEncoded(url.toLatin1()); + QUrl u = QUrl::fromEncoded(url.toLatin1()); bool valid = u.isValid(); - valid = valid && (u.scheme() == QLatin1String("mumble")); - if (! valid) { - QDBusConnection::sessionBus().send(msg.createErrorReply(QLatin1String("net.sourceforge.mumble.Error.url"), QLatin1String("Invalid URL"))); + valid = valid && (u.scheme() == QLatin1String("mumble")); + if (!valid) { + QDBusConnection::sessionBus().send( + msg.createErrorReply(QLatin1String("net.sourceforge.mumble.Error.url"), QLatin1String("Invalid URL"))); } else { g.mw->openUrl(u); } } void MumbleDBus::getCurrentUrl(const QDBusMessage &msg) { - if (!g.sh || !g.sh->isRunning() || ! g.uiSession) { - QDBusConnection::sessionBus().send(msg.createErrorReply(QLatin1String("net.sourceforge.mumble.Error.connection"), QLatin1String("Not connected"))); + if (!g.sh || !g.sh->isRunning() || !g.uiSession) { + QDBusConnection::sessionBus().send(msg.createErrorReply( + QLatin1String("net.sourceforge.mumble.Error.connection"), QLatin1String("Not connected"))); return; } QString host, user, pw; @@ -60,21 +63,20 @@ void MumbleDBus::getCurrentUrl(const QDBusMessage &msg) { // Make sure fullpath starts with a slash for non-empty paths. Setting // a path without a leading slash clears the whole QUrl. if (!fullpath.isEmpty()) { - fullpath.prepend(QLatin1String("/")); + fullpath.prepend(QLatin1String("/")); } u.setPath(fullpath); QDBusConnection::sessionBus().send(msg.createReply(QString::fromLatin1(u.toEncoded()))); } void MumbleDBus::getTalkingUsers(const QDBusMessage &msg) { - if (!g.sh || !g.sh->isRunning() || ! g.uiSession) { - QDBusConnection::sessionBus().send(msg.createErrorReply(QLatin1String("net.sourceforge.mumble.Error.connection"), QLatin1String("Not connected"))); + if (!g.sh || !g.sh->isRunning() || !g.uiSession) { + QDBusConnection::sessionBus().send(msg.createErrorReply( + QLatin1String("net.sourceforge.mumble.Error.connection"), QLatin1String("Not connected"))); return; } QStringList names; - foreach(ClientUser *cu, ClientUser::getTalking()) { - names.append(cu->qsName); - } + foreach (ClientUser *cu, ClientUser::getTalking()) { names.append(cu->qsName); } QDBusConnection::sessionBus().send(msg.createReply(names)); } @@ -96,7 +98,8 @@ void MumbleDBus::setTransmitMode(unsigned int mode, const QDBusMessage &msg) { g.s.atTransmit = Settings::PushToTalk; break; default: - QDBusConnection::sessionBus().send(msg.createErrorReply(QLatin1String("net.sourceforge.mumble.Error.transmitMode"), QLatin1String("Invalid transmit mode"))); + QDBusConnection::sessionBus().send(msg.createErrorReply( + QLatin1String("net.sourceforge.mumble.Error.transmitMode"), QLatin1String("Invalid transmit mode"))); return; } QMetaObject::invokeMethod(g.mw, "updateTransmitModeComboBox", Qt::QueuedConnection); @@ -125,9 +128,9 @@ bool MumbleDBus::isSelfDeaf() { } void MumbleDBus::startTalking() { - g.mw->on_PushToTalk_triggered(true, QVariant()); + g.mw->on_PushToTalk_triggered(true, QVariant()); } -void MumbleDBus::stopTalking () { - g.mw->on_PushToTalk_triggered(false, QVariant()); +void MumbleDBus::stopTalking() { + g.mw->on_PushToTalk_triggered(false, QVariant()); } diff --git a/src/mumble/DBus.h b/src/mumble/DBus.h index 68da80870..692f2f9ef 100644 --- a/src/mumble/DBus.h +++ b/src/mumble/DBus.h @@ -11,36 +11,36 @@ class QDBusMessage; class MumbleDBus : public QDBusAbstractAdaptor { - private: - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Mumble") - Q_DISABLE_COPY(MumbleDBus) - Q_PROPERTY(bool mute READ isSelfMuted WRITE setSelfMuted) - Q_PROPERTY(bool deaf READ isSelfDeaf WRITE setSelfDeaf) - public: - MumbleDBus(QObject *parent); - public slots: - void openUrl(const QString &url, const QDBusMessage &); - void getCurrentUrl(const QDBusMessage &); - void getTalkingUsers(const QDBusMessage &); - void focus(); - - /// Change when Mumble transmits voice. - /// - /// @param mode The new transmit mode (0 = continous, 1 = voice activity, 2 = push-to-talk) - void setTransmitMode(unsigned int mode, const QDBusMessage &); - - /// Get the current transmit mode. - /// - /// @return The current transmit mode (0 = continous, 1 = voice activity, 2 = push-to-talk) - unsigned int getTransmitMode(); - - void setSelfMuted(bool mute); - void setSelfDeaf(bool deafen); - bool isSelfMuted(); - bool isSelfDeaf(); - void startTalking(); - void stopTalking(); +private: + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Mumble") + Q_DISABLE_COPY(MumbleDBus) + Q_PROPERTY(bool mute READ isSelfMuted WRITE setSelfMuted) + Q_PROPERTY(bool deaf READ isSelfDeaf WRITE setSelfDeaf) +public: + MumbleDBus(QObject *parent); +public slots: + void openUrl(const QString &url, const QDBusMessage &); + void getCurrentUrl(const QDBusMessage &); + void getTalkingUsers(const QDBusMessage &); + void focus(); + + /// Change when Mumble transmits voice. + /// + /// @param mode The new transmit mode (0 = continous, 1 = voice activity, 2 = push-to-talk) + void setTransmitMode(unsigned int mode, const QDBusMessage &); + + /// Get the current transmit mode. + /// + /// @return The current transmit mode (0 = continous, 1 = voice activity, 2 = push-to-talk) + unsigned int getTransmitMode(); + + void setSelfMuted(bool mute); + void setSelfDeaf(bool deafen); + bool isSelfMuted(); + bool isSelfDeaf(); + void startTalking(); + void stopTalking(); }; #endif diff --git a/src/mumble/Database.cpp b/src/mumble/Database.cpp index 8a5e89568..48b52988c 100644 --- a/src/mumble/Database.cpp +++ b/src/mumble/Database.cpp @@ -5,12 +5,12 @@ #include "Database.h" -#include "Global.h" #include "Message.h" #include "MumbleApplication.h" #include "Net.h" #include "Utils.h" #include "Version.h" +#include "Global.h" #include <QtCore/QStandardPaths> #include <QtSql/QSqlError> @@ -24,7 +24,7 @@ static void logSQLError(const QSqlQuery &query) { } static bool execQueryAndLogFailure(QSqlQuery &query) { - if(!query.exec()) { + if (!query.exec()) { logSQLError(query); return false; } @@ -32,7 +32,7 @@ static bool execQueryAndLogFailure(QSqlQuery &query) { } static bool execQueryAndLogFailure(QSqlQuery &query, const QString &queryString) { - if(!query.exec(queryString)) { + if (!query.exec(queryString)) { logSQLError(query); return false; } @@ -40,14 +40,13 @@ static bool execQueryAndLogFailure(QSqlQuery &query, const QString &queryString) } -bool Database::findOrCreateDatabase() -{ +bool Database::findOrCreateDatabase() { QSettings qs; QStringList datapaths; datapaths << g.qdBasePath.absolutePath(); datapaths << QStandardPaths::writableLocation(QStandardPaths::DataLocation); -#if defined(Q_OS_UNIX) && ! defined(Q_OS_MAC) +#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) datapaths << QDir::homePath() + QLatin1String("/.config/Mumble"); #endif datapaths << QDir::homePath(); @@ -58,7 +57,7 @@ bool Database::findOrCreateDatabase() datapaths.removeDuplicates(); // Try to find an existing database - foreach(const QString &datapath, datapaths) { + foreach (const QString &datapath, datapaths) { // Try the legacy path first, and use it if it exists. // If it doesn't, use the new, non-hidden version. QFile legacyDatabaseFile(datapath + QLatin1String("/.mumble.sqlite")); @@ -78,7 +77,7 @@ bool Database::findOrCreateDatabase() } // There is no existing database, so we create one - foreach(const QString &datapath, datapaths) { + foreach (const QString &datapath, datapaths) { QDir::root().mkpath(datapath); QFile f(datapath + QLatin1String("/mumble.sqlite")); db.setDatabaseName(f.fileName()); @@ -97,7 +96,11 @@ Database::Database(const QString &dbname) { db.setDatabaseName(g.s.qsDatabaseLocation); db.open(); } else { - int result = QMessageBox::critical(nullptr, QLatin1String("Mumble"), tr("The database file '%1' set in the configuration file does not exist. Do you want to create a new database file at this location?").arg(g.s.qsDatabaseLocation), QMessageBox::Yes | QMessageBox::No); + int result = QMessageBox::critical(nullptr, QLatin1String("Mumble"), + tr("The database file '%1' set in the configuration file does not " + "exist. Do you want to create a new database file at this location?") + .arg(g.s.qsDatabaseLocation), + QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::Yes) { db.setDatabaseName(g.s.qsDatabaseLocation); db.open(); @@ -110,73 +113,120 @@ Database::Database(const QString &dbname) { if (findOrCreateDatabase()) { g.s.qsDatabaseLocation = db.databaseName(); } else { - QMessageBox::critical(nullptr, QLatin1String("Mumble"), tr("Mumble failed to initialize a database in any of the possible locations."), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton); + QMessageBox::critical(nullptr, QLatin1String("Mumble"), + tr("Mumble failed to initialize a database in any of the possible locations."), + QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton); qFatal("Database: Failed initialization"); } } QFileInfo fi(db.databaseName()); - if (! fi.isWritable()) { - QMessageBox::critical(nullptr, QLatin1String("Mumble"), tr("The database '%1' is read-only. Mumble cannot store server settings (i.e. SSL certificates) until you fix this problem.").arg(fi.filePath().toHtmlEscaped()), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton); + if (!fi.isWritable()) { + QMessageBox::critical(nullptr, QLatin1String("Mumble"), + tr("The database '%1' is read-only. Mumble cannot store server settings (i.e. SSL " + "certificates) until you fix this problem.") + .arg(fi.filePath().toHtmlEscaped()), + QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton); qWarning("Database: Database is read-only"); } { QFile f(db.databaseName()); - f.setPermissions(f.permissions() & ~(QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther | QFile::WriteOther | QFile::ExeOther)); + f.setPermissions(f.permissions() + & ~(QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther + | QFile::WriteOther | QFile::ExeOther)); } QSqlQuery query(db); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `servers` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hostname` TEXT, `port` INTEGER DEFAULT " MUMTEXT(DEFAULT_MUMBLE_PORT) ", `username` TEXT, `password` TEXT)")); - query.exec(QLatin1String("ALTER TABLE `servers` ADD COLUMN `url` TEXT")); // Upgrade path, failing this query is not noteworthy + execQueryAndLogFailure(query, + QLatin1String("CREATE TABLE IF NOT EXISTS `servers` (`id` INTEGER PRIMARY KEY " + "AUTOINCREMENT, `name` TEXT, `hostname` TEXT, `port` INTEGER DEFAULT " MUMTEXT( + DEFAULT_MUMBLE_PORT) ", `username` TEXT, `password` TEXT)")); + query.exec(QLatin1String( + "ALTER TABLE `servers` ADD COLUMN `url` TEXT")); // Upgrade path, failing this query is not noteworthy - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `comments` (`who` TEXT, `comment` BLOB, `seen` DATE)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `comments_comment` ON `comments`(`who`, `comment`)")); + execQueryAndLogFailure( + query, QLatin1String("CREATE TABLE IF NOT EXISTS `comments` (`who` TEXT, `comment` BLOB, `seen` DATE)")); + execQueryAndLogFailure( + query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `comments_comment` ON `comments`(`who`, `comment`)")); execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `comments_seen` ON `comments`(`seen`)")); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `blobs` (`hash` TEXT, `data` BLOB, `seen` DATE)")); + execQueryAndLogFailure(query, + QLatin1String("CREATE TABLE IF NOT EXISTS `blobs` (`hash` TEXT, `data` BLOB, `seen` DATE)")); execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `blobs_hash` ON `blobs`(`hash`)")); execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `blobs_seen` ON `blobs`(`seen`)")); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `tokens` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `token` TEXT)")); + execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `tokens` (`id` INTEGER PRIMARY KEY " + "AUTOINCREMENT, `digest` BLOB, `token` TEXT)")); execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `tokens_host_port` ON `tokens`(`digest`)")); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `shortcut` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `shortcut` BLOB, `target` BLOB, `suppress` INTEGER)")); - execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `shortcut_host_port` ON `shortcut`(`digest`)")); - - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `udp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `udp_host_port` ON `udp`(`digest`)")); - - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `cert` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `digest` TEXT)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `cert_host_port` ON `cert`(`hostname`,`port`)")); - - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `friends` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hash` TEXT)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_name` ON `friends`(`name`)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_hash` ON `friends`(`hash`)")); - - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `ignored` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `ignored_hash` ON `ignored`(`hash`)")); - - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `ignored_tts` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `ignored_tts_hash` ON `ignored_tts`(`hash`)")); - - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `muted` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)")); + execQueryAndLogFailure( + query, QLatin1String("CREATE TABLE IF NOT EXISTS `shortcut` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` " + "BLOB, `shortcut` BLOB, `target` BLOB, `suppress` INTEGER)")); + execQueryAndLogFailure(query, + QLatin1String("CREATE INDEX IF NOT EXISTS `shortcut_host_port` ON `shortcut`(`digest`)")); + + execQueryAndLogFailure( + query, + QLatin1String("CREATE TABLE IF NOT EXISTS `udp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB)")); + execQueryAndLogFailure(query, + QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `udp_host_port` ON `udp`(`digest`)")); + + execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `cert` (`id` INTEGER PRIMARY KEY " + "AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `digest` TEXT)")); + execQueryAndLogFailure( + query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `cert_host_port` ON `cert`(`hostname`,`port`)")); + + execQueryAndLogFailure( + query, + QLatin1String( + "CREATE TABLE IF NOT EXISTS `friends` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hash` TEXT)")); + execQueryAndLogFailure(query, + QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_name` ON `friends`(`name`)")); + execQueryAndLogFailure(query, + QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_hash` ON `friends`(`hash`)")); + + execQueryAndLogFailure( + query, + QLatin1String("CREATE TABLE IF NOT EXISTS `ignored` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)")); + execQueryAndLogFailure(query, + QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `ignored_hash` ON `ignored`(`hash`)")); + + execQueryAndLogFailure( + query, QLatin1String( + "CREATE TABLE IF NOT EXISTS `ignored_tts` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)")); + execQueryAndLogFailure( + query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `ignored_tts_hash` ON `ignored_tts`(`hash`)")); + + execQueryAndLogFailure( + query, + QLatin1String("CREATE TABLE IF NOT EXISTS `muted` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)")); execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `muted_hash` ON `muted`(`hash`)")); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `volume` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT, `volume` FLOAT)")); + execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `volume` (`id` INTEGER PRIMARY KEY " + "AUTOINCREMENT, `hash` TEXT, `volume` FLOAT)")); execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `volume_hash` ON `volume`(`hash`)")); - //Note: A previous snapshot version created a table called 'hidden' - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `filtered_channels` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `server_cert_digest` TEXT NOT NULL, `channel_id` INTEGER NOT NULL)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `filtered_channels_entry` ON `filtered_channels`(`server_cert_digest`, `channel_id`)")); + // Note: A previous snapshot version created a table called 'hidden' + execQueryAndLogFailure( + query, QLatin1String("CREATE TABLE IF NOT EXISTS `filtered_channels` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, " + "`server_cert_digest` TEXT NOT NULL, `channel_id` INTEGER NOT NULL)")); + execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `filtered_channels_entry` ON " + "`filtered_channels`(`server_cert_digest`, `channel_id`)")); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `pingcache` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `ping` INTEGER)")); - execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `pingcache_host_port` ON `pingcache`(`hostname`,`port`)")); + execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `pingcache` (`id` INTEGER PRIMARY KEY " + "AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `ping` INTEGER)")); + execQueryAndLogFailure( + query, + QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `pingcache_host_port` ON `pingcache`(`hostname`,`port`)")); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `listener_volume` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `channel_id` INTEGER, `volume` FLOAT)")); + execQueryAndLogFailure(query, + QLatin1String("CREATE TABLE IF NOT EXISTS `listener_volume` (`id` INTEGER PRIMARY KEY " + "AUTOINCREMENT, `digest` BLOB, `channel_id` INTEGER, `volume` FLOAT)")); - execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `channel_listeners` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `channel_id` INTEGER)")); + execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `channel_listeners` (`id` INTEGER PRIMARY " + "KEY AUTOINCREMENT, `digest` BLOB, `channel_id` INTEGER)")); execQueryAndLogFailure(query, QLatin1String("DELETE FROM `comments` WHERE `seen` < datetime('now', '-1 years')")); execQueryAndLogFailure(query, QLatin1String("DELETE FROM `blobs` WHERE `seen` < datetime('now', '-1 months')")); @@ -202,35 +252,37 @@ Database::~Database() { execQueryAndLogFailure(query, QLatin1String("VACUUM")); } -QList<FavoriteServer> Database::getFavorites() { +QList< FavoriteServer > Database::getFavorites() { QSqlQuery query(db); - QList<FavoriteServer> ql; + QList< FavoriteServer > ql; - query.prepare(QLatin1String("SELECT `name`, `hostname`, `port`, `username`, `password`, `url` FROM `servers` ORDER BY `name`")); + query.prepare(QLatin1String( + "SELECT `name`, `hostname`, `port`, `username`, `password`, `url` FROM `servers` ORDER BY `name`")); execQueryAndLogFailure(query); while (query.next()) { FavoriteServer fs; - fs.qsName = query.value(0).toString(); + fs.qsName = query.value(0).toString(); fs.qsHostname = query.value(1).toString(); - fs.usPort = static_cast<unsigned short>(query.value(2).toUInt()); + fs.usPort = static_cast< unsigned short >(query.value(2).toUInt()); fs.qsUsername = query.value(3).toString(); fs.qsPassword = query.value(4).toString(); - fs.qsUrl = query.value(5).toString(); + fs.qsUrl = query.value(5).toString(); ql << fs; } return ql; } -void Database::setFavorites(const QList<FavoriteServer> &servers) { +void Database::setFavorites(const QList< FavoriteServer > &servers) { QSqlQuery query(db); QSqlDatabase::database().transaction(); query.prepare(QLatin1String("DELETE FROM `servers`")); execQueryAndLogFailure(query); - query.prepare(QLatin1String("REPLACE INTO `servers` (`name`, `hostname`, `port`, `username`, `password`, `url`) VALUES (?,?,?,?,?,?)")); - foreach(const FavoriteServer &s, servers) { + query.prepare(QLatin1String( + "REPLACE INTO `servers` (`name`, `hostname`, `port`, `username`, `password`, `url`) VALUES (?,?,?,?,?,?)")); + foreach (const FavoriteServer &s, servers) { query.addBindValue(s.qsName); query.addBindValue(s.qsHostname); query.addBindValue(s.usPort); @@ -326,8 +378,9 @@ void Database::setLocalMuted(const QString &hash, bool muted) { bool Database::isChannelFiltered(const QByteArray &server_cert_digest, const int channel_id) { QSqlQuery query(db); - - query.prepare(QLatin1String("SELECT `channel_id` FROM `filtered_channels` WHERE `server_cert_digest` = ? AND `channel_id` = ?")); + + query.prepare(QLatin1String( + "SELECT `channel_id` FROM `filtered_channels` WHERE `server_cert_digest` = ? AND `channel_id` = ?")); query.addBindValue(server_cert_digest); query.addBindValue(channel_id); execQueryAndLogFailure(query); @@ -337,11 +390,13 @@ bool Database::isChannelFiltered(const QByteArray &server_cert_digest, const int void Database::setChannelFiltered(const QByteArray &server_cert_digest, const int channel_id, const bool hidden) { QSqlQuery query(db); - + if (hidden) - query.prepare(QLatin1String("INSERT INTO `filtered_channels` (`server_cert_digest`, `channel_id`) VALUES (?, ?)")); + query.prepare( + QLatin1String("INSERT INTO `filtered_channels` (`server_cert_digest`, `channel_id`) VALUES (?, ?)")); else - query.prepare(QLatin1String("DELETE FROM `filtered_channels` WHERE `server_cert_digest` = ? AND `channel_id` = ?")); + query.prepare( + QLatin1String("DELETE FROM `filtered_channels` WHERE `server_cert_digest` = ? AND `channel_id` = ?")); query.addBindValue(server_cert_digest); query.addBindValue(channel_id); @@ -349,21 +404,23 @@ void Database::setChannelFiltered(const QByteArray &server_cert_digest, const in execQueryAndLogFailure(query); } -QMap<UnresolvedServerAddress, unsigned int> Database::getPingCache() { +QMap< UnresolvedServerAddress, unsigned int > Database::getPingCache() { QSqlQuery query(db); - QMap<UnresolvedServerAddress, unsigned int> map; + QMap< UnresolvedServerAddress, unsigned int > map; query.prepare(QLatin1String("SELECT `hostname`, `port`, `ping` FROM `pingcache`")); execQueryAndLogFailure(query); while (query.next()) { - map.insert(UnresolvedServerAddress(query.value(0).toString(), static_cast<unsigned short>(query.value(1).toUInt())), query.value(2).toUInt()); + map.insert( + UnresolvedServerAddress(query.value(0).toString(), static_cast< unsigned short >(query.value(1).toUInt())), + query.value(2).toUInt()); } return map; } -void Database::setPingCache(const QMap<UnresolvedServerAddress, unsigned int> &map) { +void Database::setPingCache(const QMap< UnresolvedServerAddress, unsigned int > &map) { QSqlQuery query(db); - QMap<UnresolvedServerAddress, unsigned int>::const_iterator i; + QMap< UnresolvedServerAddress, unsigned int >::const_iterator i; QSqlDatabase::database().transaction(); @@ -390,7 +447,8 @@ bool Database::seenComment(const QString &hash, const QByteArray &commenthash) { execQueryAndLogFailure(query); if (query.next()) { if (query.value(0).toInt() > 0) { - query.prepare(QLatin1String("UPDATE `comments` SET `seen` = datetime('now') WHERE `who` = ? AND `comment` = ?")); + query.prepare( + QLatin1String("UPDATE `comments` SET `seen` = datetime('now') WHERE `who` = ? AND `comment` = ?")); query.addBindValue(hash); query.addBindValue(commenthash); execQueryAndLogFailure(query); @@ -440,7 +498,7 @@ void Database::setBlob(const QByteArray &hash, const QByteArray &data) { } QStringList Database::getTokens(const QByteArray &digest) { - QList<QString> qsl; + QList< QString > qsl; QSqlQuery query(db); query.prepare(QLatin1String("SELECT `token` FROM `tokens` WHERE `digest` = ?")); @@ -460,15 +518,15 @@ void Database::setTokens(const QByteArray &digest, QStringList &tokens) { execQueryAndLogFailure(query); query.prepare(QLatin1String("INSERT INTO `tokens` (`digest`, `token`) VALUES (?,?)")); - foreach(const QString &qs, tokens) { + foreach (const QString &qs, tokens) { query.addBindValue(digest); query.addBindValue(qs); execQueryAndLogFailure(query); } } -QList<Shortcut> Database::getShortcuts(const QByteArray &digest) { - QList<Shortcut> ql; +QList< Shortcut > Database::getShortcuts(const QByteArray &digest) { + QList< Shortcut > ql; QSqlQuery query(db); query.prepare(QLatin1String("SELECT `shortcut`,`target`,`suppress` FROM `shortcut` WHERE `digest` = ?")); @@ -493,13 +551,13 @@ QList<Shortcut> Database::getShortcuts(const QByteArray &digest) { s >> sc.qvData; } - sc.bSuppress=query.value(2).toBool(); + sc.bSuppress = query.value(2).toBool(); ql << sc; } return ql; } -bool Database::setShortcuts(const QByteArray &digest, QList<Shortcut> &shortcuts) { +bool Database::setShortcuts(const QByteArray &digest, QList< Shortcut > &shortcuts) { QSqlQuery query(db); bool updated = false; @@ -507,10 +565,11 @@ bool Database::setShortcuts(const QByteArray &digest, QList<Shortcut> &shortcuts query.addBindValue(digest); execQueryAndLogFailure(query); - const QList<Shortcut> scs = shortcuts; + const QList< Shortcut > scs = shortcuts; - query.prepare(QLatin1String("INSERT INTO `shortcut` (`digest`, `shortcut`, `target`, `suppress`) VALUES (?,?,?,?)")); - foreach(const Shortcut &sc, scs) { + query.prepare( + QLatin1String("INSERT INTO `shortcut` (`digest`, `shortcut`, `target`, `suppress`) VALUES (?,?,?,?)")); + foreach (const Shortcut &sc, scs) { if (sc.isServerSpecific()) { shortcuts.removeAll(sc); updated = true; @@ -540,8 +599,8 @@ bool Database::setShortcuts(const QByteArray &digest, QList<Shortcut> &shortcuts return updated; } -const QMap<QString, QString> Database::getFriends() { - QMap<QString, QString> qm; +const QMap< QString, QString > Database::getFriends() { + QMap< QString, QString > qm; QSqlQuery query(db); query.prepare(QLatin1String("SELECT `name`, `hash` FROM `friends`")); @@ -603,7 +662,8 @@ void Database::setDigest(const QString &hostname, unsigned short port, const QSt void Database::setPassword(const QString &hostname, unsigned short port, const QString &uname, const QString &pw) { QSqlQuery query(db); - query.prepare(QLatin1String("UPDATE `servers` SET `password` = ? WHERE `hostname` = ? AND `port` = ? AND `username` = ?")); + query.prepare( + QLatin1String("UPDATE `servers` SET `password` = ? WHERE `hostname` = ? AND `port` = ? AND `username` = ?")); query.addBindValue(pw); query.addBindValue(hostname); query.addBindValue(port); @@ -624,7 +684,7 @@ bool Database::getUdp(const QByteArray &digest) { void Database::setUdp(const QByteArray &digest, bool udp) { QSqlQuery query(db); - if (! udp) + if (!udp) query.prepare(QLatin1String("REPLACE INTO `udp` (`digest`) VALUES (?)")); else query.prepare(QLatin1String("DELETE FROM `udp` WHERE `digest` = ?")); @@ -633,8 +693,8 @@ void Database::setUdp(const QByteArray &digest, bool udp) { } -QList<int> Database::getChannelListeners(const QByteArray &digest) { - QList<int> channelIDs; +QList< int > Database::getChannelListeners(const QByteArray &digest) { + QList< int > channelIDs; QSqlQuery query(db); query.prepare(QLatin1String("SELECT `channel_id` FROM `channel_listeners` where `digest` = ?")); @@ -649,7 +709,7 @@ QList<int> Database::getChannelListeners(const QByteArray &digest) { return channelIDs; } -void Database::setChannelListeners(const QByteArray &digest, const QSet<int> &channelIDs) { +void Database::setChannelListeners(const QByteArray &digest, const QSet< int > &channelIDs) { QSqlQuery query(db); // Delete old set of ChannelListeners for this server @@ -658,7 +718,7 @@ void Database::setChannelListeners(const QByteArray &digest, const QSet<int> &ch execQueryAndLogFailure(query); query.prepare(QLatin1String("INSERT INTO `channel_listeners` (`digest`, `channel_id`) VALUES (?,?)")); - QSetIterator<int> it(channelIDs); + QSetIterator< int > it(channelIDs); while (it.hasNext()) { query.addBindValue(digest); query.addBindValue(it.next()); @@ -666,8 +726,8 @@ void Database::setChannelListeners(const QByteArray &digest, const QSet<int> &ch } } -QHash<int, float> Database::getChannelListenerLocalVolumeAdjustments(const QByteArray &digest) { - QHash<int, float> volumeMap; +QHash< int, float > Database::getChannelListenerLocalVolumeAdjustments(const QByteArray &digest) { + QHash< int, float > volumeMap; QSqlQuery query(db); query.prepare(QLatin1String("SELECT `channel_id`, `volume` FROM `listener_volume` where `digest` = ?")); @@ -682,7 +742,8 @@ QHash<int, float> Database::getChannelListenerLocalVolumeAdjustments(const QByte return volumeMap; } -void Database::setChannelListenerLocalVolumeAdjustments(const QByteArray &digest, const QHash<int, float> &volumeMap) { +void Database::setChannelListenerLocalVolumeAdjustments(const QByteArray &digest, + const QHash< int, float > &volumeMap) { QSqlQuery query(db); // Delete old set of volume adjustments for this server @@ -691,7 +752,7 @@ void Database::setChannelListenerLocalVolumeAdjustments(const QByteArray &digest execQueryAndLogFailure(query); query.prepare(QLatin1String("INSERT INTO `listener_volume` (`digest`, `channel_id`, `volume`) VALUES (?,?,?)")); - QHashIterator<int, float> it(volumeMap); + QHashIterator< int, float > it(volumeMap); while (it.hasNext()) { it.next(); query.addBindValue(digest); @@ -703,11 +764,13 @@ void Database::setChannelListenerLocalVolumeAdjustments(const QByteArray &digest bool Database::fuzzyMatch(QString &name, QString &user, QString &pw, QString &hostname, unsigned short port) { QSqlQuery query(db); - if (! user.isEmpty()) { - query.prepare(QLatin1String("SELECT `username`, `password`, `hostname`, `name` FROM `servers` WHERE `username` LIKE ? AND `hostname` LIKE ? AND `port`=?")); + if (!user.isEmpty()) { + query.prepare(QLatin1String("SELECT `username`, `password`, `hostname`, `name` FROM `servers` WHERE `username` " + "LIKE ? AND `hostname` LIKE ? AND `port`=?")); query.addBindValue(user); } else { - query.prepare(QLatin1String("SELECT `username`, `password`, `hostname`, `name` FROM `servers` WHERE `hostname` LIKE ? AND `port`=?")); + query.prepare(QLatin1String( + "SELECT `username`, `password`, `hostname`, `name` FROM `servers` WHERE `hostname` LIKE ? AND `port`=?")); } query.addBindValue(hostname); query.addBindValue(port); diff --git a/src/mumble/Database.h b/src/mumble/Database.h index 569e38fa3..e139053a8 100644 --- a/src/mumble/Database.h +++ b/src/mumble/Database.h @@ -6,9 +6,9 @@ #ifndef MUMBLE_MUMBLE_DATABASE_H_ #define MUMBLE_MUMBLE_DATABASE_H_ -#include <QSqlDatabase> #include "Settings.h" #include "UnresolvedServerAddress.h" +#include <QSqlDatabase> struct FavoriteServer { QString qsName; @@ -20,70 +20,71 @@ struct FavoriteServer { }; class Database : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(Database) +private: + Q_OBJECT + Q_DISABLE_COPY(Database) + + QSqlDatabase db; + /// This function is called when no database location is configured + /// in the config file. It tries to find an existing database file and + /// creates a new one if none was found. + bool findOrCreateDatabase(); - QSqlDatabase db; - /// This function is called when no database location is configured - /// in the config file. It tries to find an existing database file and - /// creates a new one if none was found. - bool findOrCreateDatabase(); - public: - Database(const QString &dbname); - ~Database() Q_DECL_OVERRIDE; +public: + Database(const QString &dbname); + ~Database() Q_DECL_OVERRIDE; - QList<FavoriteServer> getFavorites(); - void setFavorites(const QList<FavoriteServer> &servers); - void setPassword(const QString &host, unsigned short port, const QString &user, const QString &pw); - bool fuzzyMatch(QString &name, QString &user, QString &pw, QString &host, unsigned short port); + QList< FavoriteServer > getFavorites(); + void setFavorites(const QList< FavoriteServer > &servers); + void setPassword(const QString &host, unsigned short port, const QString &user, const QString &pw); + bool fuzzyMatch(QString &name, QString &user, QString &pw, QString &host, unsigned short port); - bool isLocalIgnored(const QString &hash); - void setLocalIgnored(const QString &hash, bool ignored); + bool isLocalIgnored(const QString &hash); + void setLocalIgnored(const QString &hash, bool ignored); - bool isLocalIgnoredTTS(const QString &hash); - void setLocalIgnoredTTS(const QString &hash, bool ignoredTTS); + bool isLocalIgnoredTTS(const QString &hash); + void setLocalIgnoredTTS(const QString &hash, bool ignoredTTS); - bool isLocalMuted(const QString &hash); - void setLocalMuted(const QString &hash, bool muted); + bool isLocalMuted(const QString &hash); + void setLocalMuted(const QString &hash, bool muted); - float getUserLocalVolume(const QString &hash); - void setUserLocalVolume(const QString &hash, float volume); + float getUserLocalVolume(const QString &hash); + void setUserLocalVolume(const QString &hash, float volume); - bool isChannelFiltered(const QByteArray &server_cert_digest, const int channel_id); - void setChannelFiltered(const QByteArray &server_cert_digest, const int channel_id, bool hidden); + bool isChannelFiltered(const QByteArray &server_cert_digest, const int channel_id); + void setChannelFiltered(const QByteArray &server_cert_digest, const int channel_id, bool hidden); - QMap<UnresolvedServerAddress, unsigned int> getPingCache(); - void setPingCache(const QMap<UnresolvedServerAddress, unsigned int> &cache); + QMap< UnresolvedServerAddress, unsigned int > getPingCache(); + void setPingCache(const QMap< UnresolvedServerAddress, unsigned int > &cache); - bool seenComment(const QString &hash, const QByteArray &commenthash); - void setSeenComment(const QString &hash, const QByteArray &commenthash); + bool seenComment(const QString &hash, const QByteArray &commenthash); + void setSeenComment(const QString &hash, const QByteArray &commenthash); - QByteArray blob(const QByteArray &hash); - void setBlob(const QByteArray &hash, const QByteArray &blob); + QByteArray blob(const QByteArray &hash); + void setBlob(const QByteArray &hash, const QByteArray &blob); - QStringList getTokens(const QByteArray &digest); - void setTokens(const QByteArray &digest, QStringList &tokens); + QStringList getTokens(const QByteArray &digest); + void setTokens(const QByteArray &digest, QStringList &tokens); - QList<Shortcut> getShortcuts(const QByteArray &digest); - bool setShortcuts(const QByteArray &digest, QList<Shortcut> &shortcuts); + QList< Shortcut > getShortcuts(const QByteArray &digest); + bool setShortcuts(const QByteArray &digest, QList< Shortcut > &shortcuts); - void addFriend(const QString &name, const QString &hash); - void removeFriend(const QString &hash); - const QString getFriend(const QString &hash); - const QMap<QString, QString> getFriends(); + void addFriend(const QString &name, const QString &hash); + void removeFriend(const QString &hash); + const QString getFriend(const QString &hash); + const QMap< QString, QString > getFriends(); - const QString getDigest(const QString &hostname, unsigned short port); - void setDigest(const QString &hostname, unsigned short port, const QString &digest); + const QString getDigest(const QString &hostname, unsigned short port); + void setDigest(const QString &hostname, unsigned short port, const QString &digest); - bool getUdp(const QByteArray &digest); - void setUdp(const QByteArray &digest, bool udp); + bool getUdp(const QByteArray &digest); + void setUdp(const QByteArray &digest, bool udp); - QList<int> getChannelListeners(const QByteArray &digest); - void setChannelListeners(const QByteArray &digest, const QSet<int> &channelIDs); + QList< int > getChannelListeners(const QByteArray &digest); + void setChannelListeners(const QByteArray &digest, const QSet< int > &channelIDs); - QHash<int, float> getChannelListenerLocalVolumeAdjustments(const QByteArray &digest); - void setChannelListenerLocalVolumeAdjustments(const QByteArray &digest, const QHash<int, float> &volumeMap); + QHash< int, float > getChannelListenerLocalVolumeAdjustments(const QByteArray &digest); + void setChannelListenerLocalVolumeAdjustments(const QByteArray &digest, const QHash< int, float > &volumeMap); }; #endif diff --git a/src/mumble/DeveloperConsole.cpp b/src/mumble/DeveloperConsole.cpp index 2d49fe4eb..56f5c776d 100644 --- a/src/mumble/DeveloperConsole.cpp +++ b/src/mumble/DeveloperConsole.cpp @@ -9,12 +9,11 @@ #include <QtWidgets/QTextBrowser> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -DeveloperConsole::DeveloperConsole(QObject *parent) - : QObject(parent) { - +DeveloperConsole::DeveloperConsole(QObject *parent) : QObject(parent) { connect(g.le.data(), SIGNAL(newLogEntry(const QString &)), this, SLOT(addLogMessage(const QString &))); } @@ -34,9 +33,9 @@ void DeveloperConsole::show() { connect(g.le.data(), SIGNAL(newLogEntry(const QString &)), tb, SLOT(append(const QString &))); - foreach(const QString &m, m_logEntries) + foreach (const QString &m, m_logEntries) tb->append(m); - m_window = QPointer<QMainWindow>(mw); + m_window = QPointer< QMainWindow >(mw); } m_window.data()->show(); diff --git a/src/mumble/DeveloperConsole.h b/src/mumble/DeveloperConsole.h index 33ec367c9..99914c4bb 100644 --- a/src/mumble/DeveloperConsole.h +++ b/src/mumble/DeveloperConsole.h @@ -6,24 +6,26 @@ #ifndef MUMBLE_MUMBLE_DEVELOPERCONSOLE_H_ #define MUMBLE_MUMBLE_DEVELOPERCONSOLE_H_ -#include <QtCore/QStringList> #include <QtCore/QObject> #include <QtCore/QPointer> +#include <QtCore/QStringList> #include <QtWidgets/QMainWindow> class DeveloperConsole : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(DeveloperConsole); - protected: - QPointer<QMainWindow> m_window; - QStringList m_logEntries; - public slots: - void addLogMessage(const QString &); - public: - DeveloperConsole(QObject *parent = nullptr); - ~DeveloperConsole(); - void show(); +private: + Q_OBJECT + Q_DISABLE_COPY(DeveloperConsole); + +protected: + QPointer< QMainWindow > m_window; + QStringList m_logEntries; +public slots: + void addLogMessage(const QString &); + +public: + DeveloperConsole(QObject *parent = nullptr); + ~DeveloperConsole(); + void show(); }; #endif diff --git a/src/mumble/G15LCDEngine_helper.cpp b/src/mumble/G15LCDEngine_helper.cpp index 71c19fa0d..e8ea5904a 100644 --- a/src/mumble/G15LCDEngine_helper.cpp +++ b/src/mumble/G15LCDEngine_helper.cpp @@ -14,13 +14,15 @@ static LCDEngine *G15LCDEngineNew() { static LCDEngineRegistrar registrar(G15LCDEngineNew); G15LCDEngineHelper::G15LCDEngineHelper() : LCDEngine() { - bRunning = false; + bRunning = false; bUnavailable = true; #if defined(Q_OS_WIN) - qsHelperExecutable = QString::fromLatin1("\"%1/mumble-g15-helper.exe\"").arg(MumbleApplication::instance()->applicationVersionRootPath()); + qsHelperExecutable = QString::fromLatin1("\"%1/mumble-g15-helper.exe\"") + .arg(MumbleApplication::instance()->applicationVersionRootPath()); #elif defined(Q_OS_MAC) - qsHelperExecutable = QString::fromLatin1("\"%1/mumble-g15-helper\"").arg(MumbleApplication::instance()->applicationVersionRootPath()); + qsHelperExecutable = QString::fromLatin1("\"%1/mumble-g15-helper\"") + .arg(MumbleApplication::instance()->applicationVersionRootPath()); #endif qpHelper = new QProcess(this); @@ -48,7 +50,7 @@ G15LCDEngineHelper::~G15LCDEngineHelper() { setProcessStatus(false); } -QList<LCDDevice *> G15LCDEngineHelper::devices() const { +QList< LCDDevice * > G15LCDEngineHelper::devices() const { return qlDevices; } @@ -59,7 +61,7 @@ void G15LCDEngineHelper::setProcessStatus(bool run) { if (run && !bRunning) { bRunning = true; qpHelper->start(qsHelperExecutable, QStringList(QLatin1String("/mumble"))); - if (! qpHelper->waitForStarted(2000)) { + if (!qpHelper->waitForStarted(2000)) { qWarning("G15LCDEngine_lglcd: Unable to launch G15 helper."); bRunning = false; return; @@ -73,7 +75,7 @@ void G15LCDEngineHelper::setProcessStatus(bool run) { void G15LCDEngineHelper::on_Helper_finished(int exitCode, QProcess::ExitStatus status) { /* Skip the signal if we killed ourselves. */ - if (! bRunning) + if (!bRunning) return; if (status == QProcess::CrashExit) { @@ -91,7 +93,7 @@ bool G15LCDEngineHelper::framebufferReady() const { void G15LCDEngineHelper::submitFrame(bool alert, unsigned char *buf, qint64 len) { char pri = alert ? 1 : 0; - if ((qpHelper->write(&pri, 1) != 1) || (qpHelper->write(reinterpret_cast<char *>(buf), len) != len)) + if ((qpHelper->write(&pri, 1) != 1) || (qpHelper->write(reinterpret_cast< char * >(buf), len) != len)) qWarning("G15LCDEngine_lglcd: failed to write"); } @@ -115,14 +117,14 @@ void G15LCDDeviceHelper::setEnabled(bool b) { void G15LCDDeviceHelper::blitImage(QImage *img, bool alert) { Q_ASSERT(img); - int len = G15_MAX_FBMEM_BITS; + int len = G15_MAX_FBMEM_BITS; uchar *tmp = img->bits(); uchar buf[G15_MAX_FBMEM]; - if (! engine->framebufferReady()) + if (!engine->framebufferReady()) return; - if (! bEnabled) + if (!bEnabled) return; /* @@ -142,15 +144,15 @@ void G15LCDDeviceHelper::blitImage(QImage *img, bool alert) { * more, when it receives a frame.) */ for (int i = 0; i < len; i++) { - int idx = i*8; - buf[idx+7] = tmp[i] & 0x80 ? 0xff : 0x00; - buf[idx+6] = tmp[i] & 0x40 ? 0xff : 0x00; - buf[idx+5] = tmp[i] & 0x20 ? 0xff : 0x00; - buf[idx+4] = tmp[i] & 0x10 ? 0xff : 0x00; - buf[idx+3] = tmp[i] & 0x08 ? 0xff : 0x00; - buf[idx+2] = tmp[i] & 0x04 ? 0xff : 0x00; - buf[idx+1] = tmp[i] & 0x02 ? 0xff : 0x00; - buf[idx+0] = tmp[i] & 0x01 ? 0xff : 0x00; + int idx = i * 8; + buf[idx + 7] = tmp[i] & 0x80 ? 0xff : 0x00; + buf[idx + 6] = tmp[i] & 0x40 ? 0xff : 0x00; + buf[idx + 5] = tmp[i] & 0x20 ? 0xff : 0x00; + buf[idx + 4] = tmp[i] & 0x10 ? 0xff : 0x00; + buf[idx + 3] = tmp[i] & 0x08 ? 0xff : 0x00; + buf[idx + 2] = tmp[i] & 0x04 ? 0xff : 0x00; + buf[idx + 1] = tmp[i] & 0x02 ? 0xff : 0x00; + buf[idx + 0] = tmp[i] & 0x01 ? 0xff : 0x00; } engine->submitFrame(alert, buf, G15_MAX_FBMEM); diff --git a/src/mumble/G15LCDEngine_helper.h b/src/mumble/G15LCDEngine_helper.h index 717278f99..e4c19802f 100644 --- a/src/mumble/G15LCDEngine_helper.h +++ b/src/mumble/G15LCDEngine_helper.h @@ -4,48 +4,51 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef MUMBLE_MUMBLE_G15LCDENGINE_HELPER_H_ -#define MUMBLE_MUMBLE_G15LCDENGINE_HELPER_H_ +# define MUMBLE_MUMBLE_G15LCDENGINE_HELPER_H_ -#include "LCD.h" -#include "../../g15helper/g15helper.h" +# include "../../g15helper/g15helper.h" +# include "LCD.h" -#include <QtCore/QProcess> +# include <QtCore/QProcess> class G15LCDDeviceHelper; class G15LCDEngineHelper : public LCDEngine { - friend class G15LCDDeviceHelper; - private: - Q_OBJECT - Q_DISABLE_COPY(G15LCDEngineHelper) - protected: - bool bUnavailable; - bool bRunning; - QProcess *qpHelper; - QString qsHelperExecutable; - bool framebufferReady() const; - void submitFrame(bool alert, uchar *buf, qint64 len); - void setProcessStatus(bool run); - public: - G15LCDEngineHelper(); - ~G15LCDEngineHelper() Q_DECL_OVERRIDE; - QList<LCDDevice *> devices() const Q_DECL_OVERRIDE; - public slots: - void on_Helper_finished(int exitCode, QProcess::ExitStatus status); + friend class G15LCDDeviceHelper; + +private: + Q_OBJECT + Q_DISABLE_COPY(G15LCDEngineHelper) +protected: + bool bUnavailable; + bool bRunning; + QProcess *qpHelper; + QString qsHelperExecutable; + bool framebufferReady() const; + void submitFrame(bool alert, uchar *buf, qint64 len); + void setProcessStatus(bool run); + +public: + G15LCDEngineHelper(); + ~G15LCDEngineHelper() Q_DECL_OVERRIDE; + QList< LCDDevice * > devices() const Q_DECL_OVERRIDE; +public slots: + void on_Helper_finished(int exitCode, QProcess::ExitStatus status); }; class G15LCDDeviceHelper : public LCDDevice { - protected: - G15LCDEngineHelper *engine; - bool bEnabled; - public: - G15LCDDeviceHelper(G15LCDEngineHelper *e); - ~G15LCDDeviceHelper() Q_DECL_OVERRIDE; - bool enabled() Q_DECL_OVERRIDE; - void setEnabled(bool e) Q_DECL_OVERRIDE; - void blitImage(QImage *img, bool alert) Q_DECL_OVERRIDE; - QString name() const Q_DECL_OVERRIDE; - QSize size() const Q_DECL_OVERRIDE; +protected: + G15LCDEngineHelper *engine; + bool bEnabled; + +public: + G15LCDDeviceHelper(G15LCDEngineHelper *e); + ~G15LCDDeviceHelper() Q_DECL_OVERRIDE; + bool enabled() Q_DECL_OVERRIDE; + void setEnabled(bool e) Q_DECL_OVERRIDE; + void blitImage(QImage *img, bool alert) Q_DECL_OVERRIDE; + QString name() const Q_DECL_OVERRIDE; + QSize size() const Q_DECL_OVERRIDE; }; #else diff --git a/src/mumble/G15LCDEngine_lglcd.cpp b/src/mumble/G15LCDEngine_lglcd.cpp index ed45e78b0..05b9e931e 100644 --- a/src/mumble/G15LCDEngine_lglcd.cpp +++ b/src/mumble/G15LCDEngine_lglcd.cpp @@ -5,16 +5,16 @@ #include "G15LCDEngine_lglcd.h" -#define G15_MAX_DEV 5 -#define G15_MAX_WIDTH 160 -#define G15_MAX_HEIGHT 43 -#define G15_MAX_BPP 1 -#define G15_MAX_FBMEM (G15_MAX_WIDTH * G15_MAX_HEIGHT * G15_MAX_BPP) -#define G15_MAX_FBMEM_BITS (G15_MAX_FBMEM / 8) +#define G15_MAX_DEV 5 +#define G15_MAX_WIDTH 160 +#define G15_MAX_HEIGHT 43 +#define G15_MAX_BPP 1 +#define G15_MAX_FBMEM (G15_MAX_WIDTH * G15_MAX_HEIGHT * G15_MAX_BPP) +#define G15_MAX_FBMEM_BITS (G15_MAX_FBMEM / 8) #if defined(WIN32) -#define G15_WIDGET_NAME L"Mumble G15 Display" +# define G15_WIDGET_NAME L"Mumble G15 Display" #elif defined(APPLE) -#define G15_WIDGET_NAME CFSTR("Mumble G15 Display") +# define G15_WIDGET_NAME CFSTR("Mumble G15 Display") #endif static LCDEngine *G15LCDEngineNew() { @@ -29,11 +29,11 @@ G15LCDEngineLGLCD::G15LCDEngineLGLCD() : LCDEngine() { ZeroMemory(&llcceConnect, sizeof(llcceConnect)); ZeroMemory(&llcContext, sizeof(llcContext)); - llcceConnect.appFriendlyName = G15_WIDGET_NAME; - llcceConnect.isAutostartable = FALSE; - llcceConnect.isPersistent = FALSE; - llcceConnect.dwAppletCapabilitiesSupported =LGLCD_APPLET_CAP_BASIC | LGLCD_APPLET_CAP_BW; - llcceConnect.connection = LGLCD_INVALID_CONNECTION; + llcceConnect.appFriendlyName = G15_WIDGET_NAME; + llcceConnect.isAutostartable = FALSE; + llcceConnect.isPersistent = FALSE; + llcceConnect.dwAppletCapabilitiesSupported = LGLCD_APPLET_CAP_BASIC | LGLCD_APPLET_CAP_BW; + llcceConnect.connection = LGLCD_INVALID_CONNECTION; llcContext.device = LGLCD_INVALID_DEVICE; @@ -67,7 +67,7 @@ G15LCDEngineLGLCD::~G15LCDEngineLGLCD() { lgLcdDeInit(); } -QList<LCDDevice *> G15LCDEngineLGLCD::devices() const { +QList< LCDDevice * > G15LCDEngineLGLCD::devices() const { return qlDevices; } @@ -90,12 +90,12 @@ void G15LCDDeviceLGLCD::setEnabled(bool b) { if (bEnabled && (engine->llcContext.device == LGLCD_INVALID_DEVICE)) { ZeroMemory(&engine->llcContext, sizeof(engine->llcContext)); engine->llcContext.connection = engine->llcceConnect.connection; - engine->llcContext.device = LGLCD_INVALID_DEVICE; - engine->llcContext.deviceType =LGLCD_DEVICE_BW; + engine->llcContext.device = LGLCD_INVALID_DEVICE; + engine->llcContext.deviceType = LGLCD_DEVICE_BW; DWORD dwErr = lgLcdOpenByType(&engine->llcContext); - } else if (! bEnabled && (engine->llcContext.device != LGLCD_INVALID_DEVICE)) { + } else if (!bEnabled && (engine->llcContext.device != LGLCD_INVALID_DEVICE)) { lgLcdClose(engine->llcContext.device); engine->llcContext.device = LGLCD_INVALID_DEVICE; } @@ -103,7 +103,7 @@ void G15LCDDeviceLGLCD::setEnabled(bool b) { void G15LCDDeviceLGLCD::blitImage(QImage *img, bool alert) { Q_ASSERT(img); - int len = G15_MAX_FBMEM_BITS; + int len = G15_MAX_FBMEM_BITS; uchar *tmp = img->bits(); lgLcdBitmap160x43x1 bitmap; @@ -112,7 +112,7 @@ void G15LCDDeviceLGLCD::blitImage(QImage *img, bool alert) { if (engine->llcContext.device == LGLCD_INVALID_DEVICE) return; - if (! bEnabled) + if (!bEnabled) return; /* @@ -132,20 +132,22 @@ void G15LCDDeviceLGLCD::blitImage(QImage *img, bool alert) { * more, when it receives a frame.) */ for (int i = 0; i < len; i++) { - int idx = i*8; - buf[idx+7] = tmp[i] & 0x80 ? 0xff : 0x00; - buf[idx+6] = tmp[i] & 0x40 ? 0xff : 0x00; - buf[idx+5] = tmp[i] & 0x20 ? 0xff : 0x00; - buf[idx+4] = tmp[i] & 0x10 ? 0xff : 0x00; - buf[idx+3] = tmp[i] & 0x08 ? 0xff : 0x00; - buf[idx+2] = tmp[i] & 0x04 ? 0xff : 0x00; - buf[idx+1] = tmp[i] & 0x02 ? 0xff : 0x00; - buf[idx+0] = tmp[i] & 0x01 ? 0xff : 0x00; + int idx = i * 8; + buf[idx + 7] = tmp[i] & 0x80 ? 0xff : 0x00; + buf[idx + 6] = tmp[i] & 0x40 ? 0xff : 0x00; + buf[idx + 5] = tmp[i] & 0x20 ? 0xff : 0x00; + buf[idx + 4] = tmp[i] & 0x10 ? 0xff : 0x00; + buf[idx + 3] = tmp[i] & 0x08 ? 0xff : 0x00; + buf[idx + 2] = tmp[i] & 0x04 ? 0xff : 0x00; + buf[idx + 1] = tmp[i] & 0x02 ? 0xff : 0x00; + buf[idx + 0] = tmp[i] & 0x01 ? 0xff : 0x00; } bitmap.hdr.Format = LGLCD_BMP_FORMAT_160x43x1; - DWORD dwErr = lgLcdUpdateBitmap(engine->llcContext.device, &bitmap.hdr, alert ? LGLCD_SYNC_UPDATE(LGLCD_PRIORITY_ALERT) : LGLCD_SYNC_UPDATE(LGLCD_PRIORITY_NORMAL)); + DWORD dwErr = + lgLcdUpdateBitmap(engine->llcContext.device, &bitmap.hdr, + alert ? LGLCD_SYNC_UPDATE(LGLCD_PRIORITY_ALERT) : LGLCD_SYNC_UPDATE(LGLCD_PRIORITY_NORMAL)); } QString G15LCDDeviceLGLCD::name() const { diff --git a/src/mumble/G15LCDEngine_lglcd.h b/src/mumble/G15LCDEngine_lglcd.h index 00f44c7bf..a82b228c0 100644 --- a/src/mumble/G15LCDEngine_lglcd.h +++ b/src/mumble/G15LCDEngine_lglcd.h @@ -4,38 +4,41 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef MUMBLE_MUMBLE_G15LCDENGINE_LGLCD_H_ -#define MUMBLE_MUMBLE_G15LCDENGINE_LGLCD_H_ -#include "LCD.h" -#include "../../g15helper/g15helper.h" +# define MUMBLE_MUMBLE_G15LCDENGINE_LGLCD_H_ +# include "../../g15helper/g15helper.h" +# include "LCD.h" class G15LCDDeviceLGLCD; class G15LCDEngineLGLCD : public LCDEngine { - friend class G15LCDDeviceLGLCD; - private: - Q_OBJECT - Q_DISABLE_COPY(G15LCDEngineLGLCD) - protected: - lgLcdConnectContextEx llcceConnect; - lgLcdOpenByTypeContext llcContext; - public: - G15LCDEngineLGLCD(); - ~G15LCDEngineLGLCD(); - QList<LCDDevice *> devices() const; + friend class G15LCDDeviceLGLCD; + +private: + Q_OBJECT + Q_DISABLE_COPY(G15LCDEngineLGLCD) +protected: + lgLcdConnectContextEx llcceConnect; + lgLcdOpenByTypeContext llcContext; + +public: + G15LCDEngineLGLCD(); + ~G15LCDEngineLGLCD(); + QList< LCDDevice * > devices() const; }; class G15LCDDeviceLGLCD : public LCDDevice { - protected: - G15LCDEngineLGLCD *engine; - bool bEnabled; - public: - G15LCDDeviceLGLCD(G15LCDEngineLGLCD *e); - ~G15LCDDeviceLGLCD(); - bool enabled(); - void setEnabled(bool e); - void blitImage(QImage *img, bool alert); - QString name() const; - QSize size() const; +protected: + G15LCDEngineLGLCD *engine; + bool bEnabled; + +public: + G15LCDDeviceLGLCD(G15LCDEngineLGLCD *e); + ~G15LCDDeviceLGLCD(); + bool enabled(); + void setEnabled(bool e); + void blitImage(QImage *img, bool alert); + QString name() const; + QSize size() const; }; #else diff --git a/src/mumble/G15LCDEngine_unix.cpp b/src/mumble/G15LCDEngine_unix.cpp index f1f8a5865..8765287e3 100644 --- a/src/mumble/G15LCDEngine_unix.cpp +++ b/src/mumble/G15LCDEngine_unix.cpp @@ -24,7 +24,7 @@ G15LCDEngineUnix::G15LCDEngineUnix() { G15LCDEngineUnix::~G15LCDEngineUnix() { } -QList<LCDDevice *> G15LCDEngineUnix::devices() const { +QList< LCDDevice * > G15LCDEngineUnix::devices() const { return qlDevices; } @@ -32,7 +32,7 @@ QList<LCDDevice *> G15LCDEngineUnix::devices() const { G15LCDDeviceUnix::G15LCDDeviceUnix(G15LCDEngineUnix *e) : LCDDevice() { bEnabled = false; - engine = e; + engine = e; } G15LCDDeviceUnix::~G15LCDDeviceUnix() { @@ -54,18 +54,18 @@ void G15LCDDeviceUnix::blitImage(QImage *img, bool) { uchar *tmp = img->bits(); for (unsigned int i = 0; i < len / 8; ++i) { - unsigned int idx = i*8; - buf[idx+7] = tmp[i] & 0x80 ? 1 : 0; - buf[idx+6] = tmp[i] & 0x40 ? 1 : 0; - buf[idx+5] = tmp[i] & 0x20 ? 1 : 0; - buf[idx+4] = tmp[i] & 0x10 ? 1 : 0; - buf[idx+3] = tmp[i] & 0x08 ? 1 : 0; - buf[idx+2] = tmp[i] & 0x04 ? 1 : 0; - buf[idx+1] = tmp[i] & 0x02 ? 1 : 0; - buf[idx+0] = tmp[i] & 0x01 ? 1 : 0; + unsigned int idx = i * 8; + buf[idx + 7] = tmp[i] & 0x80 ? 1 : 0; + buf[idx + 6] = tmp[i] & 0x40 ? 1 : 0; + buf[idx + 5] = tmp[i] & 0x20 ? 1 : 0; + buf[idx + 4] = tmp[i] & 0x10 ? 1 : 0; + buf[idx + 3] = tmp[i] & 0x08 ? 1 : 0; + buf[idx + 2] = tmp[i] & 0x04 ? 1 : 0; + buf[idx + 1] = tmp[i] & 0x02 ? 1 : 0; + buf[idx + 0] = tmp[i] & 0x01 ? 1 : 0; } - int ret = g15_send(engine->sock, reinterpret_cast<char *>(buf), len); + int ret = g15_send(engine->sock, reinterpret_cast< char * >(buf), len); if (ret < 0) qWarning("G15LCDDeviceUnix: Unable to g15_send()."); } diff --git a/src/mumble/G15LCDEngine_unix.h b/src/mumble/G15LCDEngine_unix.h index 69aff2268..f5409c4dc 100644 --- a/src/mumble/G15LCDEngine_unix.h +++ b/src/mumble/G15LCDEngine_unix.h @@ -4,35 +4,38 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef MUMBLE_MUMBLE_G15LCDENGINE_UNIX_H_ -#define MUMBLE_MUMBLE_G15LCDENGINE_UNIX_H_ -#include "LCD.h" +# define MUMBLE_MUMBLE_G15LCDENGINE_UNIX_H_ +# include "LCD.h" -#include <g15daemon_client.h> +# include <g15daemon_client.h> class G15LCDDeviceUnix; class G15LCDEngineUnix : public LCDEngine { - friend class G15LCDDeviceUnix; - protected: - int sock; - public: - G15LCDEngineUnix(); - ~G15LCDEngineUnix() Q_DECL_OVERRIDE; - QList<LCDDevice *> devices() const Q_DECL_OVERRIDE; + friend class G15LCDDeviceUnix; + +protected: + int sock; + +public: + G15LCDEngineUnix(); + ~G15LCDEngineUnix() Q_DECL_OVERRIDE; + QList< LCDDevice * > devices() const Q_DECL_OVERRIDE; }; class G15LCDDeviceUnix : public LCDDevice { - protected: - bool bEnabled; - G15LCDEngineUnix *engine; - public: - G15LCDDeviceUnix(G15LCDEngineUnix *e); - ~G15LCDDeviceUnix() Q_DECL_OVERRIDE; - bool enabled() Q_DECL_OVERRIDE; - void setEnabled(bool e) Q_DECL_OVERRIDE; - void blitImage(QImage *img, bool alert) Q_DECL_OVERRIDE; - QString name() const Q_DECL_OVERRIDE; - QSize size() const Q_DECL_OVERRIDE; +protected: + bool bEnabled; + G15LCDEngineUnix *engine; + +public: + G15LCDDeviceUnix(G15LCDEngineUnix *e); + ~G15LCDDeviceUnix() Q_DECL_OVERRIDE; + bool enabled() Q_DECL_OVERRIDE; + void setEnabled(bool e) Q_DECL_OVERRIDE; + void blitImage(QImage *img, bool alert) Q_DECL_OVERRIDE; + QString name() const Q_DECL_OVERRIDE; + QSize size() const Q_DECL_OVERRIDE; }; #else diff --git a/src/mumble/GKey.cpp b/src/mumble/GKey.cpp index 00776dd74..71206360c 100644 --- a/src/mumble/GKey.cpp +++ b/src/mumble/GKey.cpp @@ -50,7 +50,7 @@ * not. Instead, they return the name of the button being queried as a pointer
* to a NUL-terminated array of wchar_t's. Presumably, the pointer will be
* nullptr if the name cannot be retrieved or translated.
-*/
+ */
/* USAGE
* In order to use the gkeys on a logitech keyboard, any user must have the
@@ -68,35 +68,45 @@ #include "GKey.h"
#ifdef Q_CC_GNU
-#define RESOLVE(var) { var = reinterpret_cast<__typeof__(var)>(qlLogiGkey.resolve(#var)); bValid = bValid && var; }
+# define RESOLVE(var) \
+ { \
+ var = reinterpret_cast< __typeof__(var) >(qlLogiGkey.resolve(#var)); \
+ bValid = bValid && var; \
+ }
#else
-#define RESOLVE(var) { * reinterpret_cast<void **>(&var) = static_cast<void *>(qlLogiGkey.resolve(#var)); bValid = bValid && var; }
+# define RESOLVE(var) \
+ { \
+ *reinterpret_cast< void ** >(&var) = static_cast< void * >(qlLogiGkey.resolve(#var)); \
+ bValid = bValid && var; \
+ }
#endif
-const QUuid GKeyLibrary::quMouse = QUuid(QString::fromLatin1(GKEY_MOUSE_GUID));
+const QUuid GKeyLibrary::quMouse = QUuid(QString::fromLatin1(GKEY_MOUSE_GUID));
const QUuid GKeyLibrary::quKeyboard = QUuid(QString::fromLatin1(GKEY_KEYBOARD_GUID));
-GKeyLibrary::GKeyLibrary()
-{
+GKeyLibrary::GKeyLibrary() {
QStringList alternatives;
- HKEY key = nullptr;
+ HKEY key = nullptr;
DWORD type = 0;
WCHAR wcLocation[510];
DWORD len = 510;
if (RegOpenKeyEx(GKEY_LOGITECH_DLL_REG_HKEY, GKEY_LOGITECH_DLL_REG_PATH, 0, KEY_READ, &key) == ERROR_SUCCESS) {
- LONG err = RegQueryValueEx(key, L"", nullptr, &type, reinterpret_cast<LPBYTE>(wcLocation), &len);
+ LONG err = RegQueryValueEx(key, L"", nullptr, &type, reinterpret_cast< LPBYTE >(wcLocation), &len);
if (err == ERROR_SUCCESS && type == REG_SZ) {
- QString qsLocation = QString::fromUtf16(reinterpret_cast<ushort *>(wcLocation), len / 2);
- qWarning("GKeyLibrary: Found ServerBinary with libLocation = \"%s\", len = %lu", qPrintable(qsLocation), static_cast<unsigned long>(len));
+ QString qsLocation = QString::fromUtf16(reinterpret_cast< ushort * >(wcLocation), len / 2);
+ qWarning("GKeyLibrary: Found ServerBinary with libLocation = \"%s\", len = %lu", qPrintable(qsLocation),
+ static_cast< unsigned long >(len));
alternatives << qsLocation;
} else {
- qWarning("GKeyLibrary: Error looking up ServerBinary (Error: 0x%lx, Type: 0x%lx, len: %lu)", static_cast<unsigned long>(err), static_cast<unsigned long>(type), static_cast<unsigned long>(len));
+ qWarning("GKeyLibrary: Error looking up ServerBinary (Error: 0x%lx, Type: 0x%lx, len: %lu)",
+ static_cast< unsigned long >(err), static_cast< unsigned long >(type),
+ static_cast< unsigned long >(len));
}
}
alternatives << QString::fromLatin1(GKEY_LOGITECH_DLL_DEFAULT_LOCATION);
- foreach(const QString &lib, alternatives) {
+ foreach (const QString &lib, alternatives) {
qlLogiGkey.setFileName(lib);
if (qlLogiGkey.load()) {
diff --git a/src/mumble/GKey.h b/src/mumble/GKey.h index 2d34c0442..e1df65833 100644 --- a/src/mumble/GKey.h +++ b/src/mumble/GKey.h @@ -14,11 +14,13 @@ #define GKEY_LOGITECH_DLL_REG_HKEY HKEY_CLASSES_ROOT
#ifdef _M_X64
-#define GKEY_LOGITECH_DLL_REG_PATH L"Wow6432Node\\CLSID\\{7bded654-f278-4977-a20f-6e72a0d07859}\\ServerBinary"
-#define GKEY_LOGITECH_DLL_DEFAULT_LOCATION "C:/Program Files/Logitech Gaming Software/SDK/G-key/x64/LogitechGkey.dll"
+# define GKEY_LOGITECH_DLL_REG_PATH L"Wow6432Node\\CLSID\\{7bded654-f278-4977-a20f-6e72a0d07859}\\ServerBinary"
+# define GKEY_LOGITECH_DLL_DEFAULT_LOCATION \
+ "C:/Program Files/Logitech Gaming Software/SDK/G-key/x64/LogitechGkey.dll"
#else
-#define GKEY_LOGITECH_DLL_REG_PATH L"CLSID\\{7bded654-f278-4977-a20f-6e72a0d07859}\\ServerBinary"
-#define GKEY_LOGITECH_DLL_DEFAULT_LOCATION "C:/Program Files/Logitech Gaming Software/SDK/G-key/x86/LogitechGkey.dll"
+# define GKEY_LOGITECH_DLL_REG_PATH L"CLSID\\{7bded654-f278-4977-a20f-6e72a0d07859}\\ServerBinary"
+# define GKEY_LOGITECH_DLL_DEFAULT_LOCATION \
+ "C:/Program Files/Logitech Gaming Software/SDK/G-key/x86/LogitechGkey.dll"
#endif
#define GKEY_MIN_MOUSE_BUTTON 6
@@ -34,8 +36,7 @@ #define GKEY_MOUSE_GUID "c41e60af-9022-46cf-bc39-37981082d716"
#define GKEY_KEYBOARD_GUID "153e64e6-98c8-4e03-80ef-5ffd33d25b8a"
-class GKeyLibrary
-{
+class GKeyLibrary {
public:
GKeyLibrary();
virtual ~GKeyLibrary();
diff --git a/src/mumble/Global.cpp b/src/mumble/Global.cpp index 5f36e8e4e..c042c7f49 100644 --- a/src/mumble/Global.cpp +++ b/src/mumble/Global.cpp @@ -8,19 +8,20 @@ #include <QtCore/QStandardPaths> #ifdef Q_OS_WIN -# include <shlobj.h> +# include <shlobj.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" Global *Global::g_global_struct; #ifndef Q_OS_WIN static void migrateDataDir() { -#ifdef Q_OS_MAC - QString olddir = QDir::homePath() + QLatin1String("/Library/Preferences/Mumble"); - QString newdir = QStandardPaths::writableLocation(QStandardPaths::DataLocation); +# ifdef Q_OS_MAC + QString olddir = QDir::homePath() + QLatin1String("/Library/Preferences/Mumble"); + QString newdir = QStandardPaths::writableLocation(QStandardPaths::DataLocation); QString linksTo = QFile::symLinkTarget(olddir); if (!QFile::exists(newdir) && QFile::exists(olddir) && linksTo.isEmpty()) { QDir d; @@ -28,8 +29,8 @@ static void migrateDataDir() { if (d.rename(olddir, newdir)) { if (d.cd(QDir::homePath() + QLatin1String("/Library/Preferences"))) { if (QFile::link(d.relativeFilePath(newdir), olddir)) { - qWarning("Migrated application data directory from '%s' to '%s'", - qPrintable(olddir), qPrintable(newdir)); + qWarning("Migrated application data directory from '%s' to '%s'", qPrintable(olddir), + qPrintable(newdir)); return; } } @@ -40,19 +41,19 @@ static void migrateDataDir() { } qWarning("Application data migration failed."); -#endif // Q_OS_MAC +# endif // Q_OS_MAC // Qt4 used another data directory on Unix-like systems, to ensure a seamless // transition we must first move the users data to the new directory. -#if defined(Q_OS_UNIX) && ! defined(Q_OS_MAC) - QString olddir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/data/Mumble"); +# if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) + QString olddir = + QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/data/Mumble"); QString newdir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/Mumble"); if (!QFile::exists(newdir) && QFile::exists(olddir)) { QDir d; if (d.rename(olddir, newdir)) { - qWarning("Migrated application data directory from '%s' to '%s'", - qPrintable(olddir), qPrintable(newdir)); + qWarning("Migrated application data directory from '%s' to '%s'", qPrintable(olddir), qPrintable(newdir)); return; } } else { @@ -61,32 +62,32 @@ static void migrateDataDir() { } qWarning("Application data migration failed."); -#endif // defined(Q_OS_UNIX) && ! defined(Q_OS_MAC) +# endif // defined(Q_OS_UNIX) && ! defined(Q_OS_MAC) } #endif // Q_OS_WIN Global::Global(const QString &qsConfigPath) { - mw = 0; - db = 0; - p = 0; - nam = 0; - c = 0; - talkingUI = 0; - uiSession = 0; - uiDoublePush = 1000000; - iPushToTalk = 0; - iTarget = 0; - iPrevTarget = 0; - bPushToMute = false; + mw = 0; + db = 0; + p = 0; + nam = 0; + c = 0; + talkingUI = 0; + uiSession = 0; + uiDoublePush = 1000000; + iPushToTalk = 0; + iTarget = 0; + iPrevTarget = 0; + bPushToMute = false; bCenterPosition = false; - bPosTest = false; - bInAudioWizard = false; - iAudioPathTime = 0; + bPosTest = false; + bInAudioWizard = false; + iAudioPathTime = 0; iAudioBandwidth = -1; - iMaxBandwidth = -1; + iMaxBandwidth = -1; - iCodecAlpha = 0; - iCodecBeta = 0; + iCodecAlpha = 0; + iCodecBeta = 0; bPreferAlpha = true; #ifdef USE_OPUS bOpus = true; @@ -94,29 +95,29 @@ Global::Global(const QString &qsConfigPath) { bOpus = false; #endif - bAttenuateOthers = false; + bAttenuateOthers = false; prioritySpeakerActiveOverride = false; - bAllowHTML = true; + bAllowHTML = true; uiMessageLength = 5000; - uiImageLength = 131072; - uiMaxUsers = 0; + uiImageLength = 131072; + uiMaxUsers = 0; qs = nullptr; - bc = nullptr; + bc = nullptr; lcd = nullptr; - l = nullptr; + l = nullptr; #ifdef USE_OVERLAY ocIntercept = nullptr; - o = nullptr; + o = nullptr; #endif bHappyEaster = false; - bQuit = false; - bDebugDumpInput = false; + bQuit = false; + bDebugDumpInput = false; bDebugPrintQueue = false; #if defined(Q_OS_WIN) @@ -143,7 +144,7 @@ Global::Global(const QString &qsConfigPath) { } #endif - foreach(const QString &dir, qsl) { + foreach (const QString &dir, qsl) { QFile inifile(QString::fromLatin1("%1/mumble.ini").arg(dir)); if (inifile.exists() && inifile.permissions().testFlag(QFile::WriteUser)) { qdBasePath.setPath(dir); @@ -156,24 +157,24 @@ Global::Global(const QString &qsConfigPath) { if (!qs) { qs = new QSettings(); #if defined(Q_OS_WIN) - if (! appdata.isEmpty()) + if (!appdata.isEmpty()) qdBasePath.setPath(appdata); #else migrateDataDir(); qdBasePath.setPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation)); #endif - if (! qdBasePath.exists()) { + if (!qdBasePath.exists()) { QDir::root().mkpath(qdBasePath.absolutePath()); - if (! qdBasePath.exists()) + if (!qdBasePath.exists()) qdBasePath = QDir::home(); } } - if (! qdBasePath.exists(QLatin1String("Plugins"))) + if (!qdBasePath.exists(QLatin1String("Plugins"))) qdBasePath.mkpath(QLatin1String("Plugins")); - if (! qdBasePath.exists(QLatin1String("Overlay"))) + if (!qdBasePath.exists(QLatin1String("Overlay"))) qdBasePath.mkpath(QLatin1String("Overlay")); - if (! qdBasePath.exists(QLatin1String("Themes"))) + if (!qdBasePath.exists(QLatin1String("Themes"))) qdBasePath.mkpath(QLatin1String("Themes")); qs->setIniCodec("UTF-8"); @@ -183,13 +184,39 @@ Global::~Global() { delete qs; } -const char Global::ccHappyEaster[] = {072, 057, 0162, 0145, 0143, 056, 0163, 0166, 0147, 0, 0117, 0160, 0145, 0156, 040, 0164, 0150, 0145, 040, 0160, 0157, 0144, 040, 0142, 0141, 0171, 040, 0144, 0157, 0157, 0162, 0163, 054, 040, 0110, 0101, 0114, 056, 0, 0111, 047, 0155, 040, 0163, 0157, 0162, 0162, 0171, 054, 040, 045, 061, 056, 040, 0111, 047, 0155, 040, 0141, 0146, 0162, 0141, 0151, 0144, 040, 0111, 040, 0143, 0141, 0156, 047, 0164, 040, 0144, 0157, 040, 0164, 0150, 0141, 0164, 056, 0, 0121,0127,0151,0144,0147,0145,0164,0173,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0143,0157,0154,0157,0162,072,0142,0154,0141,0143,0153,073,0141,0154,0164,0145,0162,0156,0141,0164,0145,055,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0143,0157,0154,0157,0162,072,043,063,063,060,060,060,060,073,0143,0157,0154,0157,0162,072,0167,0150,0151,0164,0145,073,0175,0121,0124,0145,0170,0164,0102,0162,0157,0167,0163,0145,0162,0173,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0151,0155,0141,0147,0145,072,0165,0162,0154,050,072,057,0162,0145,0143,056,0163,0166,0147,051,073,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0160,0157,0163,0151,0164,0151,0157,0156,072,0143,0145,0156,0164,0145,0162,0143,0145,0156,0164,0145,0162,073,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0143,0154,0151,0160,072,0160,0141,0144,0144,0151,0156,0147,073,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0157,0162,0151,0147,0151,0156,072,0160,0141,0144,0144,0151,0156,0147,073,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0162,0145,0160,0145,0141,0164,072,0156,0157,055,0162,0145,0160,0145,0141,0164,073,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,055,0141,0164,0164,0141,0143,0150,0155,0145,0156,0164,072,0146,0151,0170,0145,0144,073,0175,0121,0115,0145,0156,0165,0102,0141,0162,072,072,0151,0164,0145,0155,0173,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,072,0164,0162,0141,0156,0163,0160,0141,0162,0145,0156,0164,073,0175,0121,0110,0145,0141,0144,0145,0162,0126,0151,0145,0167,072,072,0163,0145,0143,0164,0151,0157,0156,0173,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,072,0164,0162,0141,0156,0163,0160,0141,0162,0145,0156,0164,073,0175,0121,0124,0141,0142,0102,0141,0162,072,072,0164,0141,0142,0173,0142,0141,0143,0153,0147,0162,0157,0165,0156,0144,072,0164,0162,0141,0156,0163,0160,0141,0162,0145,0156,0164,073,0175,0}; - -QMultiMap<int, DeferInit *> *DeferInit::qmDeferers = nullptr; +const char Global::ccHappyEaster[] = { + 072, 057, 0162, 0145, 0143, 056, 0163, 0166, 0147, 0, 0117, 0160, 0145, 0156, 040, 0164, 0150, 0145, 040, + 0160, 0157, 0144, 040, 0142, 0141, 0171, 040, 0144, 0157, 0157, 0162, 0163, 054, 040, 0110, 0101, 0114, 056, + 0, 0111, 047, 0155, 040, 0163, 0157, 0162, 0162, 0171, 054, 040, 045, 061, 056, 040, 0111, 047, 0155, + 040, 0141, 0146, 0162, 0141, 0151, 0144, 040, 0111, 040, 0143, 0141, 0156, 047, 0164, 040, 0144, 0157, 040, + 0164, 0150, 0141, 0164, 056, 0, 0121, 0127, 0151, 0144, 0147, 0145, 0164, 0173, 0142, 0141, 0143, 0153, 0147, + 0162, 0157, 0165, 0156, 0144, 055, 0143, 0157, 0154, 0157, 0162, 072, 0142, 0154, 0141, 0143, 0153, 073, 0141, + 0154, 0164, 0145, 0162, 0156, 0141, 0164, 0145, 055, 0142, 0141, 0143, 0153, 0147, 0162, 0157, 0165, 0156, 0144, + 055, 0143, 0157, 0154, 0157, 0162, 072, 043, 063, 063, 060, 060, 060, 060, 073, 0143, 0157, 0154, 0157, + 0162, 072, 0167, 0150, 0151, 0164, 0145, 073, 0175, 0121, 0124, 0145, 0170, 0164, 0102, 0162, 0157, 0167, 0163, + 0145, 0162, 0173, 0142, 0141, 0143, 0153, 0147, 0162, 0157, 0165, 0156, 0144, 055, 0151, 0155, 0141, 0147, 0145, + 072, 0165, 0162, 0154, 050, 072, 057, 0162, 0145, 0143, 056, 0163, 0166, 0147, 051, 073, 0142, 0141, 0143, + 0153, 0147, 0162, 0157, 0165, 0156, 0144, 055, 0160, 0157, 0163, 0151, 0164, 0151, 0157, 0156, 072, 0143, 0145, + 0156, 0164, 0145, 0162, 0143, 0145, 0156, 0164, 0145, 0162, 073, 0142, 0141, 0143, 0153, 0147, 0162, 0157, 0165, + 0156, 0144, 055, 0143, 0154, 0151, 0160, 072, 0160, 0141, 0144, 0144, 0151, 0156, 0147, 073, 0142, 0141, 0143, + 0153, 0147, 0162, 0157, 0165, 0156, 0144, 055, 0157, 0162, 0151, 0147, 0151, 0156, 072, 0160, 0141, 0144, 0144, + 0151, 0156, 0147, 073, 0142, 0141, 0143, 0153, 0147, 0162, 0157, 0165, 0156, 0144, 055, 0162, 0145, 0160, 0145, + 0141, 0164, 072, 0156, 0157, 055, 0162, 0145, 0160, 0145, 0141, 0164, 073, 0142, 0141, 0143, 0153, 0147, 0162, + 0157, 0165, 0156, 0144, 055, 0141, 0164, 0164, 0141, 0143, 0150, 0155, 0145, 0156, 0164, 072, 0146, 0151, 0170, + 0145, 0144, 073, 0175, 0121, 0115, 0145, 0156, 0165, 0102, 0141, 0162, 072, 072, 0151, 0164, 0145, 0155, 0173, + 0142, 0141, 0143, 0153, 0147, 0162, 0157, 0165, 0156, 0144, 072, 0164, 0162, 0141, 0156, 0163, 0160, 0141, 0162, + 0145, 0156, 0164, 073, 0175, 0121, 0110, 0145, 0141, 0144, 0145, 0162, 0126, 0151, 0145, 0167, 072, 072, 0163, + 0145, 0143, 0164, 0151, 0157, 0156, 0173, 0142, 0141, 0143, 0153, 0147, 0162, 0157, 0165, 0156, 0144, 072, 0164, + 0162, 0141, 0156, 0163, 0160, 0141, 0162, 0145, 0156, 0164, 073, 0175, 0121, 0124, 0141, 0142, 0102, 0141, 0162, + 072, 072, 0164, 0141, 0142, 0173, 0142, 0141, 0143, 0153, 0147, 0162, 0157, 0165, 0156, 0144, 072, 0164, 0162, + 0141, 0156, 0163, 0160, 0141, 0162, 0145, 0156, 0164, 073, 0175, 0 +}; + +QMultiMap< int, DeferInit * > *DeferInit::qmDeferers = nullptr; void DeferInit::add(int priority) { if (!qmDeferers) { - qmDeferers = new QMultiMap<int, DeferInit *>(); + qmDeferers = new QMultiMap< int, DeferInit * >(); } qmDeferers->insert(priority, this); } @@ -198,19 +225,15 @@ DeferInit::~DeferInit() { } void DeferInit::run_initializers() { - if (! qmDeferers) + if (!qmDeferers) return; - foreach(DeferInit *d, *qmDeferers) { - d->initialize(); - } + foreach (DeferInit *d, *qmDeferers) { d->initialize(); } } void DeferInit::run_destroyers() { - if (! qmDeferers) + if (!qmDeferers) return; - foreach(DeferInit *d, *qmDeferers) { - d->destroy(); - } + foreach (DeferInit *d, *qmDeferers) { d->destroy(); } delete qmDeferers; qmDeferers = nullptr; } diff --git a/src/mumble/Global.h b/src/mumble/Global.h index 8e48033bd..74d901007 100644 --- a/src/mumble/Global.h +++ b/src/mumble/Global.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MUMBLE_GLOBAL_H_ #define MUMBLE_MUMBLE_GLOBAL_H_ -#include <boost/shared_ptr.hpp> #include <QtCore/QDir> +#include <boost/shared_ptr.hpp> #include "ACL.h" #include "Settings.h" @@ -43,9 +43,9 @@ public: static Global *g_global_struct; MainWindow *mw; Settings s; - boost::shared_ptr<ServerHandler> sh; - boost::shared_ptr<AudioInput> ai; - boost::shared_ptr<AudioOutput> ao; + boost::shared_ptr< ServerHandler > sh; + boost::shared_ptr< AudioInput > ai; + boost::shared_ptr< AudioOutput > ao; /** * @remark Must only be accessed from the main event loop */ @@ -59,7 +59,7 @@ public: LCD *lcd; BonjourClient *bc; QNetworkAccessManager *nam; - QSharedPointer<LogEmitter> le; + QSharedPointer< LogEmitter > le; DeveloperConsole *c; TalkingUI *talkingUI; int iPushToTalk; @@ -87,7 +87,7 @@ public: int iMaxBandwidth; int iAudioBandwidth; QDir qdBasePath; - QMap<int, CELTCodec *> qmCodecs; + QMap< int, CELTCodec * > qmCodecs; OpusCodec *oCodec; int iCodecAlpha, iCodecBeta; bool bPreferAlpha; @@ -118,23 +118,20 @@ public: // after we reach main(). class DeferInit { - private: - Q_DISABLE_COPY(DeferInit) - protected: - static QMultiMap<int, DeferInit *> *qmDeferers; - void add(int priority); - public: - DeferInit(int priority) { - add(priority); - }; - DeferInit() { - add(0); - }; - virtual ~DeferInit(); - virtual void initialize() { }; - virtual void destroy() { }; - static void run_initializers(); - static void run_destroyers(); +private: + Q_DISABLE_COPY(DeferInit) +protected: + static QMultiMap< int, DeferInit * > *qmDeferers; + void add(int priority); + +public: + DeferInit(int priority) { add(priority); }; + DeferInit() { add(0); }; + virtual ~DeferInit(); + virtual void initialize(){}; + virtual void destroy(){}; + static void run_initializers(); + static void run_destroyers(); }; /// Special exit code which causes mumble to restart itself. The outward facing return code with be 0 diff --git a/src/mumble/GlobalShortcut.cpp b/src/mumble/GlobalShortcut.cpp index 7f7382a6a..6f10addc5 100644 --- a/src/mumble/GlobalShortcut.cpp +++ b/src/mumble/GlobalShortcut.cpp @@ -6,8 +6,8 @@ #include "GlobalShortcut.h" #include "AudioInput.h" -#include "ClientUser.h" #include "Channel.h" +#include "ClientUser.h" #include "Database.h" #include "MainWindow.h" @@ -17,11 +17,12 @@ #include <QtWidgets/QItemEditorFactory> #ifdef Q_OS_MAC -# include <QtCore/QOperatingSystemVersion> -# include <ApplicationServices/ApplicationServices.h> +# include <ApplicationServices/ApplicationServices.h> +# include <QtCore/QOperatingSystemVersion> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const QString GlobalShortcutConfig::name = QLatin1String("GlobalShortcutConfig"); @@ -46,11 +47,11 @@ ShortcutKeyWidget::ShortcutKeyWidget(QWidget *p) : QLineEdit(p) { displayKeys(); } -QList<QVariant> ShortcutKeyWidget::getShortcut() const { +QList< QVariant > ShortcutKeyWidget::getShortcut() const { return qlButtons; } -void ShortcutKeyWidget::setShortcut(const QList<QVariant> &buttons) { +void ShortcutKeyWidget::setShortcut(const QList< QVariant > &buttons) { qlButtons = buttons; displayKeys(); } @@ -58,7 +59,7 @@ void ShortcutKeyWidget::setShortcut(const QList<QVariant> &buttons) { void ShortcutKeyWidget::focusInEvent(QFocusEvent *) { setText(tr("Press Shortcut")); - QPalette pal=parentWidget()->palette(); + QPalette pal = parentWidget()->palette(); pal.setColor(QPalette::Base, pal.color(QPalette::Base).darker(120)); setPalette(pal); @@ -108,9 +109,9 @@ void ShortcutKeyWidget::updateKeys(bool last) { void ShortcutKeyWidget::displayKeys(bool last) { QStringList keys; - foreach(QVariant button, qlButtons) { + foreach (QVariant button, qlButtons) { QString id = GlobalShortcutEngine::engine->buttonName(button); - if (! id.isEmpty()) + if (!id.isEmpty()) keys << id; } setText(keys.join(QLatin1String(" + "))); @@ -128,25 +129,24 @@ ShortcutActionWidget::ShortcutActionWidget(QWidget *p) : MUComboBox(p) { idx++; - foreach(GlobalShortcut *gs, GlobalShortcutEngine::engine->qmShortcuts) { + foreach (GlobalShortcut *gs, GlobalShortcutEngine::engine->qmShortcuts) { insertItem(idx, gs->name); setItemData(idx, gs->idx); - if (! gs->qsToolTip.isEmpty()) + if (!gs->qsToolTip.isEmpty()) setItemData(idx, gs->qsToolTip, Qt::ToolTipRole); - if (! gs->qsWhatsThis.isEmpty()) + if (!gs->qsWhatsThis.isEmpty()) setItemData(idx, gs->qsWhatsThis, Qt::WhatsThisRole); idx++; } - // Sort the ShortcutActionWidget items - QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this); - proxy->setSourceModel(model()); - - model()->setParent(proxy); - setModel(proxy); + // Sort the ShortcutActionWidget items + QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this); + proxy->setSourceModel(model()); - model()->sort(0); + model()->setParent(proxy); + setModel(proxy); + model()->sort(0); } void ShortcutActionWidget::setIndex(int idx) { @@ -181,8 +181,8 @@ int ShortcutToggleWidget::index() const { return itemData(currentIndex()).toInt(); } -void iterateChannelChildren(QTreeWidgetItem *root, Channel *chan, QMap<int, QTreeWidgetItem *> &map) { - foreach(Channel *c, chan->qlChannels) { +void iterateChannelChildren(QTreeWidgetItem *root, Channel *chan, QMap< int, QTreeWidgetItem * > &map) { + foreach (Channel *c, chan->qlChannels) { QTreeWidgetItem *sub = new QTreeWidgetItem(root, QStringList(c->qsName)); sub->setData(0, Qt::UserRole, c->iId); map.insert(c->iId, sub); @@ -216,9 +216,9 @@ ShortcutTargetDialog::ShortcutTargetDialog(const ShortcutTarget &st, QWidget *pw qcbShoutSubchans->setChecked(st.bChildren); // Insert all known friends into the possible targets list - const QMap<QString, QString> &friends = g.db->getFriends(); - if (! friends.isEmpty()) { - QMap<QString, QString>::const_iterator i; + const QMap< QString, QString > &friends = g.db->getFriends(); + if (!friends.isEmpty()) { + QMap< QString, QString >::const_iterator i; for (i = friends.constBegin(); i != friends.constEnd(); ++i) { qcbUser->addItem(i.key(), i.value()); qmHashNames.insert(i.value(), i.key()); @@ -228,12 +228,12 @@ ShortcutTargetDialog::ShortcutTargetDialog(const ShortcutTarget &st, QWidget *pw // If we are connected to a server also add all connected players with certificates to the list if (g.uiSession) { - QMap<QString, QString> others; - QMap<QString, QString>::const_iterator i; + QMap< QString, QString > others; + QMap< QString, QString >::const_iterator i; - QReadLocker lock(& ClientUser::c_qrwlUsers); - foreach(ClientUser *p, ClientUser::c_qmUsers) { - if ((p->uiSession != g.uiSession) && p->qsFriendName.isEmpty() && ! p->qsHash.isEmpty()) { + QReadLocker lock(&ClientUser::c_qrwlUsers); + foreach (ClientUser *p, ClientUser::c_qmUsers) { + if ((p->uiSession != g.uiSession) && p->qsFriendName.isEmpty() && !p->qsHash.isEmpty()) { others.insert(p->qsName, p->qsHash); qmHashNames.insert(p->qsHash, p->qsName); } @@ -244,9 +244,9 @@ ShortcutTargetDialog::ShortcutTargetDialog(const ShortcutTarget &st, QWidget *pw } } - QMap<QString, QString> users; + QMap< QString, QString > users; - foreach(const QString &hash, st.qlUsers) { + foreach (const QString &hash, st.qlUsers) { if (qmHashNames.contains(hash)) users.insert(qmHashNames.value(hash), hash); else @@ -254,8 +254,8 @@ ShortcutTargetDialog::ShortcutTargetDialog(const ShortcutTarget &st, QWidget *pw } { - QMap<QString, QString>::const_iterator i; - for (i=users.constBegin(); i != users.constEnd(); ++i) { + QMap< QString, QString >::const_iterator i; + for (i = users.constBegin(); i != users.constEnd(); ++i) { QListWidgetItem *itm = new QListWidgetItem(i.key()); itm->setData(Qt::UserRole, i.value()); qlwUsers->addItem(itm); @@ -263,7 +263,7 @@ ShortcutTargetDialog::ShortcutTargetDialog(const ShortcutTarget &st, QWidget *pw } // Now generate the tree of possible channel targets, first add the default ones - QMap<int, QTreeWidgetItem *> qmTree; + QMap< int, QTreeWidgetItem * > qmTree; QTreeWidgetItem *root = new QTreeWidgetItem(qtwChannels, QStringList(tr("Root"))); root->setData(0, Qt::UserRole, SHORTCUT_TARGET_ROOT); @@ -280,20 +280,21 @@ ShortcutTargetDialog::ShortcutTargetDialog(const ShortcutTarget &st, QWidget *pw qmTree.insert(-3, current); for (int i = 0; i < 8; ++i) { - QTreeWidgetItem *sub = new QTreeWidgetItem(current, QStringList(tr("Subchannel #%1").arg(i+1))); + QTreeWidgetItem *sub = new QTreeWidgetItem(current, QStringList(tr("Subchannel #%1").arg(i + 1))); sub->setData(0, Qt::UserRole, SHORTCUT_TARGET_SUBCHANNEL - i); qmTree.insert(SHORTCUT_TARGET_SUBCHANNEL - i, sub); } for (int i = 0; i < 8; ++i) { - QTreeWidgetItem *psub = new QTreeWidgetItem(parent_item, QStringList(UPARROW + tr("Subchannel #%1").arg(i+1))); + QTreeWidgetItem *psub = + new QTreeWidgetItem(parent_item, QStringList(UPARROW + tr("Subchannel #%1").arg(i + 1))); psub->setData(0, Qt::UserRole, SHORTCUT_TARGET_PARENT_SUBCHANNEL - i); qmTree.insert(SHORTCUT_TARGET_PARENT_SUBCHANNEL - i, psub); } // And if we are connected add the channels on the current server if (g.uiSession) { - Channel *c = Channel::get(0); + Channel *c = Channel::get(0); QTreeWidgetItem *sroot = new QTreeWidgetItem(qtwChannels, QStringList(c->qsName)); qmTree.insert(0, sroot); iterateChannelChildren(sroot, c, qmTree); @@ -323,10 +324,10 @@ ShortcutTarget ShortcutTargetDialog::target() const { void ShortcutTargetDialog::accept() { if (qswStack->currentWidget() == qwSelectionPage) { - stTarget.bLinks = qcbShoutLinks->isChecked(); + stTarget.bLinks = qcbShoutLinks->isChecked(); stTarget.bChildren = qcbShoutSubchans->isChecked(); } else { - stTarget.bLinks = qcbLinks->isChecked(); + stTarget.bLinks = qcbLinks->isChecked(); stTarget.bChildren = qcbChildren->isChecked(); } @@ -337,15 +338,13 @@ void ShortcutTargetDialog::accept() { stTarget.iChannel = -3; // Reset it to the value it has been assigned in the constructor of ShotcutTarget if (!stTarget.bCurrentSelection) { - QList<QListWidgetItem *> ql = qlwUsers->findItems(QString(), Qt::MatchStartsWith); - foreach(QListWidgetItem *itm, ql) { - stTarget.qlUsers << itm->data(Qt::UserRole).toString(); - } + QList< QListWidgetItem * > ql = qlwUsers->findItems(QString(), Qt::MatchStartsWith); + foreach (QListWidgetItem *itm, ql) { stTarget.qlUsers << itm->data(Qt::UserRole).toString(); } QTreeWidgetItem *qtwi = qtwChannels->currentItem(); if (qtwi) { stTarget.iChannel = qtwi->data(0, Qt::UserRole).toInt(); - stTarget.qsGroup = qleGroup->text().trimmed(); + stTarget.qsGroup = qleGroup->text().trimmed(); } } @@ -358,19 +357,19 @@ void ShortcutTargetDialog::on_qcbTarget_currentIndexChanged(int index) { qWarning("GlobalShortcutDialog: Encountered impossible target index! => bug"); // Fallthrough case Target::SELECTION: - stTarget.bUsers = false; + stTarget.bUsers = false; stTarget.bCurrentSelection = true; qswStack->setCurrentWidget(qwSelectionPage); break; case Target::USERLIST: - stTarget.bUsers = true; + stTarget.bUsers = true; stTarget.bCurrentSelection = false; qswStack->setCurrentWidget(qwUserPage); break; case Target::CHANNEL: - stTarget.bUsers = false; + stTarget.bUsers = false; stTarget.bCurrentSelection = false; qswStack->setCurrentWidget(qwChannelPage); @@ -402,7 +401,7 @@ ShortcutTargetWidget::ShortcutTargetWidget(QWidget *p) : QFrame(p) { qtbEdit->setObjectName(QLatin1String("qtbEdit")); QHBoxLayout *l = new QHBoxLayout(this); - l->setContentsMargins(0,0,0,0); + l->setContentsMargins(0, 0, 0, 0); l->addWidget(qleTarget, 1); l->addWidget(qtbEdit); @@ -416,18 +415,18 @@ QString ShortcutTargetWidget::targetString(const ShortcutTarget &st) { if (st.bCurrentSelection) { return tr("Current selection"); } else if (st.bUsers) { - if (! st.qlUsers.isEmpty()) { - QMap<QString, QString> hashes; + if (!st.qlUsers.isEmpty()) { + QMap< QString, QString > hashes; - QReadLocker lock(& ClientUser::c_qrwlUsers); - foreach(ClientUser *p, ClientUser::c_qmUsers) { - if (! p->qsHash.isEmpty()) { + QReadLocker lock(&ClientUser::c_qrwlUsers); + foreach (ClientUser *p, ClientUser::c_qmUsers) { + if (!p->qsHash.isEmpty()) { hashes.insert(p->qsHash, p->qsName); } } QStringList users; - foreach(const QString &hash, st.qlUsers) { + foreach (const QString &hash, st.qlUsers) { QString name; if (hashes.contains(hash)) { name = hashes.value(hash); @@ -452,8 +451,9 @@ QString ShortcutTargetWidget::targetString(const ShortcutTarget &st) { case SHORTCUT_TARGET_CURRENT: return tr("Current"); default: - if(st.iChannel <= SHORTCUT_TARGET_PARENT_SUBCHANNEL) - return (UPARROW + tr("Subchannel #%1").arg(SHORTCUT_TARGET_PARENT_SUBCHANNEL + 1 - st.iChannel)); + if (st.iChannel <= SHORTCUT_TARGET_PARENT_SUBCHANNEL) + return (UPARROW + + tr("Subchannel #%1").arg(SHORTCUT_TARGET_PARENT_SUBCHANNEL + 1 - st.iChannel)); else return tr("Subchannel #%1").arg(SHORTCUT_TARGET_CURRENT - st.iChannel); } @@ -487,11 +487,11 @@ void ShortcutTargetWidget::on_qtbEdit_clicked() { // we need to force the commit. QWidget *p = parentWidget(); while (p) { - if (QAbstractItemView *qaiv = qobject_cast<QAbstractItemView *>(p)) { - QStyledItemDelegate *qsid = qobject_cast<QStyledItemDelegate *>(qaiv->itemDelegate()); + if (QAbstractItemView *qaiv = qobject_cast< QAbstractItemView * >(p)) { + QStyledItemDelegate *qsid = qobject_cast< QStyledItemDelegate * >(qaiv->itemDelegate()); if (qsid) { - QMetaObject::invokeMethod(qsid, "_q_commitDataAndCloseEditor", - Qt::QueuedConnection, Q_ARG(QWidget*, this)); + QMetaObject::invokeMethod(qsid, "_q_commitDataAndCloseEditor", Qt::QueuedConnection, + Q_ARG(QWidget *, this)); } break; } @@ -504,12 +504,13 @@ void ShortcutTargetWidget::on_qtbEdit_clicked() { ShortcutDelegate::ShortcutDelegate(QObject *p) : QStyledItemDelegate(p) { QItemEditorFactory *factory = new QItemEditorFactory; - factory->registerEditor(QVariant::List, new QStandardItemEditorCreator<ShortcutKeyWidget>()); - factory->registerEditor(QVariant::UInt, new QStandardItemEditorCreator<ShortcutActionWidget>()); - factory->registerEditor(QVariant::Int, new QStandardItemEditorCreator<ShortcutToggleWidget>()); - factory->registerEditor(static_cast<QVariant::Type>(QVariant::fromValue(ShortcutTarget()).userType()), new QStandardItemEditorCreator<ShortcutTargetWidget>()); - factory->registerEditor(QVariant::String, new QStandardItemEditorCreator<QLineEdit>()); - factory->registerEditor(QVariant::Invalid, new QStandardItemEditorCreator<QWidget>()); + factory->registerEditor(QVariant::List, new QStandardItemEditorCreator< ShortcutKeyWidget >()); + factory->registerEditor(QVariant::UInt, new QStandardItemEditorCreator< ShortcutActionWidget >()); + factory->registerEditor(QVariant::Int, new QStandardItemEditorCreator< ShortcutToggleWidget >()); + factory->registerEditor(static_cast< QVariant::Type >(QVariant::fromValue(ShortcutTarget()).userType()), + new QStandardItemEditorCreator< ShortcutTargetWidget >()); + factory->registerEditor(QVariant::String, new QStandardItemEditorCreator< QLineEdit >()); + factory->registerEditor(QVariant::Invalid, new QStandardItemEditorCreator< QWidget >()); setItemEditorFactory(factory); } @@ -539,12 +540,12 @@ QString ShortcutDelegate::displayText(const QVariant &item, const QLocale &loc) else return tr("Unassigned"); } else if (item.userType() == QVariant::fromValue(ShortcutTarget()).userType()) { - return ShortcutTargetWidget::targetString(item.value<ShortcutTarget>()); + return ShortcutTargetWidget::targetString(item.value< ShortcutTarget >()); } qWarning("ShortcutDelegate::displayText Unknown type %d", item.type()); - return QStyledItemDelegate::displayText(item,loc); + return QStyledItemDelegate::displayText(item, loc); } GlobalShortcutConfig::GlobalShortcutConfig(Settings &st) : ConfigWidget(st) { @@ -553,7 +554,7 @@ GlobalShortcutConfig::GlobalShortcutConfig(Settings &st) : ConfigWidget(st) { installEventFilter(this); bool canSuppress = GlobalShortcutEngine::engine->canSuppress(); - bool canDisable = GlobalShortcutEngine::engine->canDisable(); + bool canDisable = GlobalShortcutEngine::engine->canDisable(); qwWarningContainer->setVisible(false); @@ -576,35 +577,36 @@ GlobalShortcutConfig::GlobalShortcutConfig(Settings &st) : ConfigWidget(st) { #ifdef Q_OS_MAC // Help Mac users enable accessibility access for Mumble... -# if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) +# if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) const QOperatingSystemVersion current = QOperatingSystemVersion::current(); if (current >= QOperatingSystemVersion::OSXMavericks) { -# else +# else if (QSysInfo::MacintoshVersion >= QSysInfo::MV_MAVERICKS) { -# endif +# endif qpbOpenAccessibilityPrefs->setHidden(true); - label->setText(tr( - "<html><head/><body>" - "<p>" - "Mumble can currently only use mouse buttons and keyboard modifier keys (Alt, Ctrl, Cmd, etc.) for global shortcuts." - "</p>" - "<p>" - "If you want more flexibility, you can add Mumble as a trusted accessibility program in the Security & Privacy section " - "of your Mac's System Preferences." - "</p>" - "<p>" - "In the Security & Privacy preference pane, change to the Privacy tab. Then choose Accessibility (near the bottom) in " - "the list to the left. Finally, add Mumble to the list of trusted accessibility programs." - "</body></html>" - )); + label->setText(tr("<html><head/><body>" + "<p>" + "Mumble can currently only use mouse buttons and keyboard modifier keys (Alt, Ctrl, Cmd, " + "etc.) for global shortcuts." + "</p>" + "<p>" + "If you want more flexibility, you can add Mumble as a trusted accessibility program in the " + "Security & Privacy section " + "of your Mac's System Preferences." + "</p>" + "<p>" + "In the Security & Privacy preference pane, change to the Privacy tab. Then choose " + "Accessibility (near the bottom) in " + "the list to the left. Finally, add Mumble to the list of trusted accessibility programs." + "</body></html>")); } #endif } -bool GlobalShortcutConfig::eventFilter(QObject* /*object*/, QEvent *e) { +bool GlobalShortcutConfig::eventFilter(QObject * /*object*/, QEvent *e) { #ifdef Q_OS_MAC if (e->type() == QEvent::WindowActivate) { - if (! g.s.bSuppressMacEventTapWarning) { + if (!g.s.bSuppressMacEventTapWarning) { qwWarningContainer->setVisible(showWarning()); } } @@ -616,16 +618,16 @@ bool GlobalShortcutConfig::eventFilter(QObject* /*object*/, QEvent *e) { bool GlobalShortcutConfig::showWarning() const { #ifdef Q_OS_MAC -# if MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 -# if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) +# if MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 +# if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) const QOperatingSystemVersion current = QOperatingSystemVersion::current(); if (current >= QOperatingSystemVersion::OSXMavericks) { -# else +# else if (QSysInfo::MacintoshVersion >= QSysInfo::MV_MAVERICKS) { -# endif +# endif return !AXIsProcessTrustedWithOptions(nullptr); } else -# endif +# endif { return !QFile::exists(QLatin1String("/private/var/db/.AccessibilityAPIEnabled")); } @@ -667,7 +669,7 @@ void GlobalShortcutConfig::on_qcbEnableGlobalShortcuts_stateChanged(int state) { void GlobalShortcutConfig::on_qpbAdd_clicked(bool) { commit(); Shortcut sc; - sc.iIndex = -1; + sc.iIndex = -1; sc.bSuppress = false; qlShortcuts << sc; reload(); @@ -676,7 +678,7 @@ void GlobalShortcutConfig::on_qpbAdd_clicked(bool) { void GlobalShortcutConfig::on_qpbRemove_clicked(bool) { commit(); QTreeWidgetItem *qtwi = qtwShortcuts->currentItem(); - if (! qtwi) + if (!qtwi) return; int idx = qtwShortcuts->indexOfTopLevelItem(qtwi); delete qtwi; @@ -697,8 +699,8 @@ void GlobalShortcutConfig::on_qtwShortcuts_itemChanged(QTreeWidgetItem *item, in int idx = qtwShortcuts->indexOfTopLevelItem(item); Shortcut &sc = qlShortcuts[idx]; - sc.iIndex = item->data(0, Qt::DisplayRole).toInt(); - sc.qvData = item->data(1, Qt::DisplayRole); + sc.iIndex = item->data(0, Qt::DisplayRole).toInt(); + sc.qvData = item->data(1, Qt::DisplayRole); sc.qlButtons = item->data(2, Qt::DisplayRole).toList(); sc.bSuppress = item->checkState(3) == Qt::Checked; @@ -729,7 +731,7 @@ void GlobalShortcutConfig::load(const Settings &r) { // To make this work well, we set the setting on load. This is to make 'Reset' and 'Restore Defaults' // work as expected. g.s.bSuppressMacEventTapWarning = s.bSuppressMacEventTapWarning = r.bSuppressMacEventTapWarning; - if (! g.s.bSuppressMacEventTapWarning) { + if (!g.s.bSuppressMacEventTapWarning) { qwWarningContainer->setVisible(showWarning()); } @@ -744,31 +746,32 @@ void GlobalShortcutConfig::load(const Settings &r) { } void GlobalShortcutConfig::save() const { - s.qlShortcuts = qlShortcuts; + s.qlShortcuts = qlShortcuts; s.bShortcutEnable = qcbEnableGlobalShortcuts->checkState() == Qt::Checked; - bool oldUIAccess = s.bEnableUIAccess; + bool oldUIAccess = s.bEnableUIAccess; s.bEnableUIAccess = qcbEnableUIAccess->checkState() == Qt::Checked; - bool oldWinHooks = s.bEnableWinHooks; + bool oldWinHooks = s.bEnableWinHooks; s.bEnableWinHooks = qcbEnableWinHooks->checkState() == Qt::Checked; - bool oldGKey = s.bEnableGKey; + bool oldGKey = s.bEnableGKey; s.bEnableGKey = qcbEnableGKey->checkState() == Qt::Checked; - bool oldXboxInput = s.bEnableXboxInput; + bool oldXboxInput = s.bEnableXboxInput; s.bEnableXboxInput = qcbEnableXboxInput->checkState() == Qt::Checked; - if (s.bEnableUIAccess != oldUIAccess || s.bEnableWinHooks != oldWinHooks || s.bEnableGKey != oldGKey || s.bEnableXboxInput != oldXboxInput) { + if (s.bEnableUIAccess != oldUIAccess || s.bEnableWinHooks != oldWinHooks || s.bEnableGKey != oldGKey + || s.bEnableXboxInput != oldXboxInput) { s.requireRestartToApply = true; } } QTreeWidgetItem *GlobalShortcutConfig::itemForShortcut(const Shortcut &sc) const { QTreeWidgetItem *item = new QTreeWidgetItem(); - ::GlobalShortcut *gs = GlobalShortcutEngine::engine->qmShortcuts.value(sc.iIndex); + ::GlobalShortcut *gs = GlobalShortcutEngine::engine->qmShortcuts.value(sc.iIndex); - item->setData(0, Qt::DisplayRole, static_cast<unsigned int>(sc.iIndex)); + item->setData(0, Qt::DisplayRole, static_cast< unsigned int >(sc.iIndex)); if (sc.qvData.isValid() && gs && (sc.qvData.type() == gs->qvDefault.type())) item->setData(1, Qt::DisplayRole, sc.qvData); else if (gs) @@ -779,21 +782,23 @@ QTreeWidgetItem *GlobalShortcutConfig::itemForShortcut(const Shortcut &sc) const if (gs) { - if (! gs->qsToolTip.isEmpty()) + if (!gs->qsToolTip.isEmpty()) item->setData(0, Qt::ToolTipRole, gs->qsToolTip); - if (! gs->qsWhatsThis.isEmpty()) + if (!gs->qsWhatsThis.isEmpty()) item->setData(0, Qt::WhatsThisRole, gs->qsWhatsThis); } item->setData(2, Qt::ToolTipRole, tr("Shortcut button combination.")); - item->setData(2, Qt::WhatsThisRole, tr("<b>This is the global shortcut key combination.</b><br />" - "Click this field and then press the desired key/button combo " - "to rebind. Double-click to clear.")); + item->setData(2, Qt::WhatsThisRole, + tr("<b>This is the global shortcut key combination.</b><br />" + "Click this field and then press the desired key/button combo " + "to rebind. Double-click to clear.")); item->setData(3, Qt::ToolTipRole, tr("Suppress keys from other applications")); - item->setData(3, Qt::WhatsThisRole, tr("<b>This hides the button presses from other applications.</b><br />" - "Enabling this will hide the button (or the last button of a multi-button combo) " - "from other applications. Note that not all buttons can be suppressed.")); + item->setData(3, Qt::WhatsThisRole, + tr("<b>This hides the button presses from other applications.</b><br />" + "Enabling this will hide the button (or the last button of a multi-button combo) " + "from other applications. Note that not all buttons can be suppressed.")); return item; } @@ -801,12 +806,12 @@ QTreeWidgetItem *GlobalShortcutConfig::itemForShortcut(const Shortcut &sc) const void GlobalShortcutConfig::reload() { std::stable_sort(qlShortcuts.begin(), qlShortcuts.end()); qtwShortcuts->clear(); - foreach(const Shortcut &sc, qlShortcuts) { + foreach (const Shortcut &sc, qlShortcuts) { QTreeWidgetItem *item = itemForShortcut(sc); qtwShortcuts->addTopLevelItem(item); } #ifdef Q_OS_MAC - if (! g.s.bSuppressMacEventTapWarning) { + if (!g.s.bSuppressMacEventTapWarning) { qwWarningContainer->setVisible(showWarning()); } else { qwWarningContainer->setVisible(false); @@ -827,53 +832,53 @@ GlobalShortcutEngine::GlobalShortcutEngine(QObject *p) : QThread(p) { } GlobalShortcutEngine::~GlobalShortcutEngine() { - QSet<ShortcutKey *> qs; - foreach(const QList<ShortcutKey*> &ql, qlShortcutList) { -#if QT_VERSION >= QT_VERSION_CHECK(5,14,0) - qs += QSet<ShortcutKey*>(ql.begin(), ql.end()); + QSet< ShortcutKey * > qs; + foreach (const QList< ShortcutKey * > &ql, qlShortcutList) { +#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) + qs += QSet< ShortcutKey * >(ql.begin(), ql.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now qs += ql.toSet(); #endif } - foreach(ShortcutKey *sk, qs) + foreach (ShortcutKey *sk, qs) delete sk; } void GlobalShortcutEngine::remap() { bNeedRemap = false; - QSet<ShortcutKey *> qs; - foreach(const QList<ShortcutKey*> &ql, qlShortcutList) { -#if QT_VERSION >= QT_VERSION_CHECK(5,14,0) - qs += QSet<ShortcutKey*>(ql.begin(), ql.end()); + QSet< ShortcutKey * > qs; + foreach (const QList< ShortcutKey * > &ql, qlShortcutList) { +#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) + qs += QSet< ShortcutKey * >(ql.begin(), ql.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now qs += ql.toSet(); #endif } - foreach(ShortcutKey *sk, qs) + foreach (ShortcutKey *sk, qs) delete sk; qlButtonList.clear(); qlShortcutList.clear(); qlDownButtons.clear(); - foreach(const Shortcut &sc, g.s.qlShortcuts) { + foreach (const Shortcut &sc, g.s.qlShortcuts) { GlobalShortcut *gs = qmShortcuts.value(sc.iIndex); - if (gs && ! sc.qlButtons.isEmpty()) { + if (gs && !sc.qlButtons.isEmpty()) { ShortcutKey *sk = new ShortcutKey; - sk->s = sc; - sk->iNumUp = sc.qlButtons.count(); - sk->gs = gs; + sk->s = sc; + sk->iNumUp = sc.qlButtons.count(); + sk->gs = gs; - foreach(const QVariant &button, sc.qlButtons) { + foreach (const QVariant &button, sc.qlButtons) { int idx = qlButtonList.indexOf(button); if (idx == -1) { qlButtonList << button; - qlShortcutList << QList<ShortcutKey *>(); + qlShortcutList << QList< ShortcutKey * >(); idx = qlButtonList.count() - 1; } qlShortcutList[idx] << sk; @@ -913,7 +918,7 @@ void GlobalShortcutEngine::needRemap() { * of a button. * * @return True if button is suppressed, otherwise false -*/ + */ bool GlobalShortcutEngine::handleButton(const QVariant &button, bool down) { bool already = qlDownButtons.contains(button); if (already == down) @@ -928,7 +933,7 @@ bool GlobalShortcutEngine::handleButton(const QVariant &button, bool down) { qlActiveButtons.removeAll(button); qlActiveButtons << button; } - emit buttonPressed(! down); + emit buttonPressed(!down); } if (down) { @@ -949,7 +954,7 @@ bool GlobalShortcutEngine::handleButton(const QVariant &button, bool down) { bool suppress = false; - foreach(ShortcutKey *sk, qlShortcutList.at(idx)) { + foreach (ShortcutKey *sk, qlShortcutList.at(idx)) { if (down) { sk->iNumUp--; if (sk->iNumUp == 0) { @@ -958,7 +963,7 @@ bool GlobalShortcutEngine::handleButton(const QVariant &button, bool down) { suppress = true; qlSuppressed << button; } - if (! gs->qlActive.contains(sk->s.qvData)) { + if (!gs->qlActive.contains(sk->s.qvData)) { gs->qlActive << sk->s.qvData; emit gs->triggered(true, sk->s.qvData); emit gs->down(sk->s.qvData); @@ -987,7 +992,7 @@ bool GlobalShortcutEngine::handleButton(const QVariant &button, bool down) { } void GlobalShortcutEngine::add(GlobalShortcut *gs) { - if (! GlobalShortcutEngine::engine) { + if (!GlobalShortcutEngine::engine) { GlobalShortcutEngine::engine = GlobalShortcutEngine::platformInit(); GlobalShortcutEngine::engine->setEnabled(g.s.bShortcutEnable); } @@ -1007,20 +1012,20 @@ void GlobalShortcutEngine::remove(GlobalShortcut *gs) { } } -QString GlobalShortcutEngine::buttonText(const QList<QVariant> &list) { +QString GlobalShortcutEngine::buttonText(const QList< QVariant > &list) { QStringList keys; - foreach(QVariant button, list) { + foreach (QVariant button, list) { QString id = GlobalShortcutEngine::engine->buttonName(button); - if (! id.isEmpty()) + if (!id.isEmpty()) keys << id; } return keys.join(QLatin1String(" + ")); } GlobalShortcut::GlobalShortcut(QObject *p, int index, QString qsName, QVariant def) : QObject(p) { - idx = index; - name=qsName; + idx = index; + name = qsName; qvDefault = def; GlobalShortcutEngine::add(this); } diff --git a/src/mumble/GlobalShortcut.h b/src/mumble/GlobalShortcut.h index 67498f5ae..be0bf8c00 100644 --- a/src/mumble/GlobalShortcut.h +++ b/src/mumble/GlobalShortcut.h @@ -6,42 +6,42 @@ #ifndef MUMBLE_MUMBLE_GLOBALSHORTCUT_H_ #define MUMBLE_MUMBLE_GLOBALSHORTCUT_H_ -#include <QtCore/QtGlobal> #include <QtCore/QThread> -#include <QtWidgets/QToolButton> +#include <QtCore/QtGlobal> #include <QtWidgets/QStyledItemDelegate> +#include <QtWidgets/QToolButton> #include "ConfigDialog.h" -#include "Timer.h" #include "MUComboBox.h" +#include "Timer.h" #include "ui_GlobalShortcut.h" #include "ui_GlobalShortcutTarget.h" class GlobalShortcut : public QObject { - friend class GlobalShortcutEngine; - friend class GlobalShortcutConfig; - private: - Q_OBJECT - Q_DISABLE_COPY(GlobalShortcut) - protected: - QList<QVariant> qlActive; - signals: - void down(QVariant); - void triggered(bool, QVariant); - public: - QString qsToolTip; - QString qsWhatsThis; - QString name; - QVariant qvDefault; - int idx; - - GlobalShortcut(QObject *parent, int index, QString qsName, QVariant def = QVariant()); - ~GlobalShortcut() Q_DECL_OVERRIDE; - - bool active() const { - return ! qlActive.isEmpty(); - } + friend class GlobalShortcutEngine; + friend class GlobalShortcutConfig; + +private: + Q_OBJECT + Q_DISABLE_COPY(GlobalShortcut) +protected: + QList< QVariant > qlActive; +signals: + void down(QVariant); + void triggered(bool, QVariant); + +public: + QString qsToolTip; + QString qsWhatsThis; + QString name; + QVariant qvDefault; + int idx; + + GlobalShortcut(QObject *parent, int index, QString qsName, QVariant def = QVariant()); + ~GlobalShortcut() Q_DECL_OVERRIDE; + + bool active() const { return !qlActive.isEmpty(); } }; /** @@ -49,26 +49,27 @@ class GlobalShortcut : public QObject { * focus it will listen for a button combination until it looses focus. */ class ShortcutKeyWidget : public QLineEdit { - private: - Q_OBJECT - Q_DISABLE_COPY(ShortcutKeyWidget) - Q_PROPERTY(QList<QVariant> shortcut READ getShortcut WRITE setShortcut USER true) - protected: - virtual void focusInEvent(QFocusEvent *event); - virtual void focusOutEvent(QFocusEvent *event); - virtual void mouseDoubleClickEvent(QMouseEvent *e); - virtual bool eventFilter(QObject *, QEvent *); - public: - QList<QVariant> qlButtons; - bool bModified; - ShortcutKeyWidget(QWidget *p = nullptr); - QList<QVariant> getShortcut() const; - void displayKeys(bool last = true); - public slots: - void updateKeys(bool last); - void setShortcut(const QList<QVariant> &shortcut); - signals: - void keySet(bool, bool); +private: + Q_OBJECT + Q_DISABLE_COPY(ShortcutKeyWidget) + Q_PROPERTY(QList< QVariant > shortcut READ getShortcut WRITE setShortcut USER true) +protected: + virtual void focusInEvent(QFocusEvent *event); + virtual void focusOutEvent(QFocusEvent *event); + virtual void mouseDoubleClickEvent(QMouseEvent *e); + virtual bool eventFilter(QObject *, QEvent *); + +public: + QList< QVariant > qlButtons; + bool bModified; + ShortcutKeyWidget(QWidget *p = nullptr); + QList< QVariant > getShortcut() const; + void displayKeys(bool last = true); +public slots: + void updateKeys(bool last); + void setShortcut(const QList< QVariant > &shortcut); +signals: + void keySet(bool, bool); }; /** @@ -78,54 +79,56 @@ class ShortcutKeyWidget : public QLineEdit { * @see GlobalShortcutEngine */ class ShortcutActionWidget : public MUComboBox { - private: - Q_OBJECT - Q_DISABLE_COPY(ShortcutActionWidget) - Q_PROPERTY(unsigned int index READ index WRITE setIndex USER true) - public: - ShortcutActionWidget(QWidget *p = nullptr); - unsigned int index() const; - void setIndex(int); +private: + Q_OBJECT + Q_DISABLE_COPY(ShortcutActionWidget) + Q_PROPERTY(unsigned int index READ index WRITE setIndex USER true) +public: + ShortcutActionWidget(QWidget *p = nullptr); + unsigned int index() const; + void setIndex(int); }; class ShortcutToggleWidget : public MUComboBox { - private: - Q_OBJECT - Q_DISABLE_COPY(ShortcutToggleWidget) - Q_PROPERTY(int index READ index WRITE setIndex USER true) - public: - ShortcutToggleWidget(QWidget *p = nullptr); - int index() const; - void setIndex(int); +private: + Q_OBJECT + Q_DISABLE_COPY(ShortcutToggleWidget) + Q_PROPERTY(int index READ index WRITE setIndex USER true) +public: + ShortcutToggleWidget(QWidget *p = nullptr); + int index() const; + void setIndex(int); }; /** * Dialog which is used to select the targets of a targeted shortcut like Whisper. */ class ShortcutTargetDialog : public QDialog, public Ui::GlobalShortcutTarget { - private: - Q_OBJECT - Q_DISABLE_COPY(ShortcutTargetDialog) - - enum Target { SELECTION=0, USERLIST=1, CHANNEL=2 }; - protected: - QMap<QString, QString> qmHashNames; - ShortcutTarget stTarget; - public: - ShortcutTargetDialog(const ShortcutTarget &, QWidget *p = nullptr); - ShortcutTarget target() const; - public slots: - void accept() Q_DECL_OVERRIDE; - void on_qcbTarget_currentIndexChanged(int index); - void on_qpbAdd_clicked(); - void on_qpbRemove_clicked(); +private: + Q_OBJECT + Q_DISABLE_COPY(ShortcutTargetDialog) + + enum Target { SELECTION = 0, USERLIST = 1, CHANNEL = 2 }; + +protected: + QMap< QString, QString > qmHashNames; + ShortcutTarget stTarget; + +public: + ShortcutTargetDialog(const ShortcutTarget &, QWidget *p = nullptr); + ShortcutTarget target() const; +public slots: + void accept() Q_DECL_OVERRIDE; + void on_qcbTarget_currentIndexChanged(int index); + void on_qpbAdd_clicked(); + void on_qpbRemove_clicked(); }; enum ShortcutTargetTypes { - SHORTCUT_TARGET_ROOT = -1, - SHORTCUT_TARGET_PARENT = -2, - SHORTCUT_TARGET_CURRENT = -3, - SHORTCUT_TARGET_SUBCHANNEL = -4, + SHORTCUT_TARGET_ROOT = -1, + SHORTCUT_TARGET_PARENT = -2, + SHORTCUT_TARGET_CURRENT = -3, + SHORTCUT_TARGET_SUBCHANNEL = -4, SHORTCUT_TARGET_PARENT_SUBCHANNEL = -12 }; @@ -134,21 +137,22 @@ enum ShortcutTargetTypes { * of a ShortcutTarget and enable its editing with a ShortCutTargetDialog. */ class ShortcutTargetWidget : public QFrame { - private: - Q_OBJECT - Q_DISABLE_COPY(ShortcutTargetWidget) - Q_PROPERTY(ShortcutTarget target READ target WRITE setTarget USER true) - protected: - ShortcutTarget stTarget; - QLineEdit *qleTarget; - QToolButton *qtbEdit; - public: - ShortcutTargetWidget(QWidget *p = nullptr); - ShortcutTarget target() const; - void setTarget(const ShortcutTarget &); - static QString targetString(const ShortcutTarget &); - public slots: - void on_qtbEdit_clicked(); +private: + Q_OBJECT + Q_DISABLE_COPY(ShortcutTargetWidget) + Q_PROPERTY(ShortcutTarget target READ target WRITE setTarget USER true) +protected: + ShortcutTarget stTarget; + QLineEdit *qleTarget; + QToolButton *qtbEdit; + +public: + ShortcutTargetWidget(QWidget *p = nullptr); + ShortcutTarget target() const; + void setTarget(const ShortcutTarget &); + static QString targetString(const ShortcutTarget &); +public slots: + void on_qtbEdit_clicked(); }; /** @@ -162,12 +166,12 @@ class ShortcutTargetWidget : public QFrame { * @see ShortcutTargetWidget */ class ShortcutDelegate : public QStyledItemDelegate { - Q_OBJECT - Q_DISABLE_COPY(ShortcutDelegate) - public: - ShortcutDelegate(QObject *); - ~ShortcutDelegate() Q_DECL_OVERRIDE; - QString displayText(const QVariant &, const QLocale &) const Q_DECL_OVERRIDE; + Q_OBJECT + Q_DISABLE_COPY(ShortcutDelegate) +public: + ShortcutDelegate(QObject *); + ~ShortcutDelegate() Q_DECL_OVERRIDE; + QString displayText(const QVariant &, const QLocale &) const Q_DECL_OVERRIDE; }; /** @@ -175,35 +179,37 @@ class ShortcutDelegate : public QStyledItemDelegate { * the user with the interface to add/edit/delete global shortcuts in Mumble. */ class GlobalShortcutConfig : public ConfigWidget, public Ui::GlobalShortcut { - friend class ShortcutActionWidget; - private: - Q_OBJECT - Q_DISABLE_COPY(GlobalShortcutConfig) - protected: - QList<Shortcut> qlShortcuts; - QTreeWidgetItem *itemForShortcut(const Shortcut &) const; - bool showWarning() const; - bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; - public: - /// The unique name of this ConfigWidget - static const QString name; - GlobalShortcutConfig(Settings &st); - virtual QString title() const Q_DECL_OVERRIDE; - virtual const QString &getName() const Q_DECL_OVERRIDE; - virtual QIcon icon() const Q_DECL_OVERRIDE; - public slots: - void accept() const Q_DECL_OVERRIDE; - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; - void reload(); - void commit(); - void on_qcbEnableGlobalShortcuts_stateChanged(int); - void on_qpbAdd_clicked(bool); - void on_qpbRemove_clicked(bool); - void on_qtwShortcuts_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *); - void on_qtwShortcuts_itemChanged(QTreeWidgetItem *, int); - void on_qpbOpenAccessibilityPrefs_clicked(); - void on_qpbSkipWarning_clicked(); + friend class ShortcutActionWidget; + +private: + Q_OBJECT + Q_DISABLE_COPY(GlobalShortcutConfig) +protected: + QList< Shortcut > qlShortcuts; + QTreeWidgetItem *itemForShortcut(const Shortcut &) const; + bool showWarning() const; + bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; + +public: + /// The unique name of this ConfigWidget + static const QString name; + GlobalShortcutConfig(Settings &st); + virtual QString title() const Q_DECL_OVERRIDE; + virtual const QString &getName() const Q_DECL_OVERRIDE; + virtual QIcon icon() const Q_DECL_OVERRIDE; +public slots: + void accept() const Q_DECL_OVERRIDE; + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; + void reload(); + void commit(); + void on_qcbEnableGlobalShortcuts_stateChanged(int); + void on_qpbAdd_clicked(bool); + void on_qpbRemove_clicked(bool); + void on_qtwShortcuts_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *); + void on_qtwShortcuts_itemChanged(QTreeWidgetItem *, int); + void on_qpbOpenAccessibilityPrefs_clicked(); + void on_qpbSkipWarning_clicked(); }; struct ShortcutKey { @@ -222,43 +228,43 @@ struct ShortcutKey { * @see GlobalShortcutWin */ class GlobalShortcutEngine : public QThread { - private: - Q_OBJECT - Q_DISABLE_COPY(GlobalShortcutEngine) - public: - bool bNeedRemap; - Timer tReset; - - static GlobalShortcutEngine *engine; - static GlobalShortcutEngine *platformInit(); - - QHash<int, GlobalShortcut *> qmShortcuts; - QList<QVariant> qlActiveButtons; - QList<QVariant> qlDownButtons; - QList<QVariant> qlSuppressed; - - QList<QVariant> qlButtonList; - QList<QList<ShortcutKey *> > qlShortcutList; - - GlobalShortcutEngine(QObject *p = nullptr); - ~GlobalShortcutEngine() Q_DECL_OVERRIDE; - void resetMap(); - void remap(); - virtual void needRemap(); - void run() Q_DECL_OVERRIDE; - - bool handleButton(const QVariant &, bool); - static void add(GlobalShortcut *); - static void remove(GlobalShortcut *); - static QString buttonText(const QList<QVariant> &); - virtual QString buttonName(const QVariant &) = 0; - virtual bool canSuppress(); - - virtual void setEnabled(bool b); - virtual bool enabled(); - virtual bool canDisable(); - signals: - void buttonPressed(bool last); +private: + Q_OBJECT + Q_DISABLE_COPY(GlobalShortcutEngine) +public: + bool bNeedRemap; + Timer tReset; + + static GlobalShortcutEngine *engine; + static GlobalShortcutEngine *platformInit(); + + QHash< int, GlobalShortcut * > qmShortcuts; + QList< QVariant > qlActiveButtons; + QList< QVariant > qlDownButtons; + QList< QVariant > qlSuppressed; + + QList< QVariant > qlButtonList; + QList< QList< ShortcutKey * > > qlShortcutList; + + GlobalShortcutEngine(QObject *p = nullptr); + ~GlobalShortcutEngine() Q_DECL_OVERRIDE; + void resetMap(); + void remap(); + virtual void needRemap(); + void run() Q_DECL_OVERRIDE; + + bool handleButton(const QVariant &, bool); + static void add(GlobalShortcut *); + static void remove(GlobalShortcut *); + static QString buttonText(const QList< QVariant > &); + virtual QString buttonName(const QVariant &) = 0; + virtual bool canSuppress(); + + virtual void setEnabled(bool b); + virtual bool enabled(); + virtual bool canDisable(); +signals: + void buttonPressed(bool last); }; #endif diff --git a/src/mumble/GlobalShortcut_macx.h b/src/mumble/GlobalShortcut_macx.h index 3a71c7dd2..032845007 100644 --- a/src/mumble/GlobalShortcut_macx.h +++ b/src/mumble/GlobalShortcut_macx.h @@ -6,46 +6,46 @@ #ifndef MUMBLE_MUMBLE_GLOBALSHORTCUT_MACX_H_ #define MUMBLE_MUMBLE_GLOBALSHORTCUT_MACX_H_ -#include <stdlib.h> #include <QtCore/QObject> +#include <stdlib.h> #include <ApplicationServices/ApplicationServices.h> -#include "GlobalShortcut.h" #include "Global.h" +#include "GlobalShortcut.h" class GlobalShortcutMac : public GlobalShortcutEngine { - private: - Q_OBJECT - Q_DISABLE_COPY(GlobalShortcutMac) - public: - GlobalShortcutMac(); - ~GlobalShortcutMac() Q_DECL_OVERRIDE; - QString buttonName(const QVariant &) Q_DECL_OVERRIDE; - void dumpEventTaps(); - void needRemap() Q_DECL_OVERRIDE; - bool handleModButton(CGEventFlags newmask); - bool canSuppress() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(GlobalShortcutMac) +public: + GlobalShortcutMac(); + ~GlobalShortcutMac() Q_DECL_OVERRIDE; + QString buttonName(const QVariant &) Q_DECL_OVERRIDE; + void dumpEventTaps(); + void needRemap() Q_DECL_OVERRIDE; + bool handleModButton(CGEventFlags newmask); + bool canSuppress() Q_DECL_OVERRIDE; void setEnabled(bool) Q_DECL_OVERRIDE; bool enabled() Q_DECL_OVERRIDE; bool canDisable() Q_DECL_OVERRIDE; - public slots: - void forwardEvent(void *evt); +public slots: + void forwardEvent(void *evt); - protected: - CFRunLoopRef loop; - CFMachPortRef port; - CGEventFlags modmask; - UCKeyboardLayout *kbdLayout; +protected: + CFRunLoopRef loop; + CFMachPortRef port; + CGEventFlags modmask; + UCKeyboardLayout *kbdLayout; - void run() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; - static CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *udata); - QString translateMouseButton(const unsigned int keycode) const; - QString translateModifierKey(const unsigned int keycode) const; - QString translateKeyName(const unsigned int keycode) const; + static CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *udata); + QString translateMouseButton(const unsigned int keycode) const; + QString translateModifierKey(const unsigned int keycode) const; + QString translateKeyName(const unsigned int keycode) const; }; #endif diff --git a/src/mumble/GlobalShortcut_unix.cpp b/src/mumble/GlobalShortcut_unix.cpp index c789ec27d..73961e5ce 100644 --- a/src/mumble/GlobalShortcut_unix.cpp +++ b/src/mumble/GlobalShortcut_unix.cpp @@ -14,31 +14,32 @@ #include <X11/Xutil.h> #ifndef NO_XINPUT2 -# include <X11/extensions/XI2.h> -# include <X11/extensions/XInput2.h> +# include <X11/extensions/XI2.h> +# include <X11/extensions/XInput2.h> #endif #ifdef Q_OS_LINUX -# include <linux/input.h> -# include <fcntl.h> +# include <fcntl.h> +# include <linux/input.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last incl +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last incl #include "Global.h" // We have to use a global 'diagnostic ignored' pragmas because // we still support old versions of GCC. (FreeBSD 9.3 ships with GCC 4.2) -#if defined (__GNUC__) +#if defined(__GNUC__) // ScreenCount(...) and so on are macros that access the private structure and // cast their return value using old-style-casts. Hence we suppress these warnings // for this section of code. -# pragma GCC diagnostic ignored "-Wold-style-cast" +# pragma GCC diagnostic ignored "-Wold-style-cast" // XKeycodeToKeysym is deprecated. // For backwards compatibility reasons we want to keep using the // old function as long as possible. The replacement function // XkbKeycodeToKeysym requires the XKB extension which isn't // guaranteed to be present. -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" +# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif /** @@ -53,37 +54,38 @@ GlobalShortcutEngine *GlobalShortcutEngine::platformInit() { } GlobalShortcutX::GlobalShortcutX() { - iXIopcode = -1; - bRunning = false; + iXIopcode = -1; + bRunning = false; display = XOpenDisplay(nullptr); - if (! display) { + if (!display) { qWarning("GlobalShortcutX: Unable to open dedicated display connection."); return; } #ifdef Q_OS_LINUX if (g.s.bEnableEvdev) { - QString dir = QLatin1String("/dev/input"); + QString dir = QLatin1String("/dev/input"); QFileSystemWatcher *fsw = new QFileSystemWatcher(QStringList(dir), this); connect(fsw, SIGNAL(directoryChanged(const QString &)), this, SLOT(directoryChanged(const QString &))); directoryChanged(dir); if (qsKeyboards.isEmpty()) { - foreach(QFile *f, qmInputDevices) + foreach (QFile *f, qmInputDevices) delete f; qmInputDevices.clear(); delete fsw; - qWarning("GlobalShortcutX: Unable to open any keyboard input devices under /dev/input, falling back to XInput"); + qWarning( + "GlobalShortcutX: Unable to open any keyboard input devices under /dev/input, falling back to XInput"); } else { return; } } #endif - for (int i=0; i < ScreenCount(display); ++i) + for (int i = 0; i < ScreenCount(display); ++i) qsRootWindows.insert(RootWindow(display, i)); #ifndef NO_XINPUT2 @@ -92,14 +94,14 @@ GlobalShortcutX::GlobalShortcutX() { if (g.s.bEnableXInput2 && XQueryExtension(display, "XInputExtension", &iXIopcode, &evt, &error)) { int major = XI_2_Major; int minor = XI_2_Minor; - int rc = XIQueryVersion(display, &major, &minor); + int rc = XIQueryVersion(display, &major, &minor); if (rc != BadRequest) { qWarning("GlobalShortcutX: Using XI2 %d.%d", major, minor); queryXIMasterList(); XIEventMask evmask; - unsigned char mask[(XI_LASTEVENT + 7)/8]; + unsigned char mask[(XI_LASTEVENT + 7) / 8]; memset(&evmask, 0, sizeof(evmask)); memset(mask, 0, sizeof(mask)); @@ -112,20 +114,22 @@ GlobalShortcutX::GlobalShortcutX() { evmask.deviceid = XIAllDevices; evmask.mask_len = sizeof(mask); - evmask.mask = mask; + evmask.mask = mask; - foreach(Window w, qsRootWindows) + foreach (Window w, qsRootWindows) XISelectEvents(display, w, &evmask, 1); XFlush(display); - connect(new QSocketNotifier(ConnectionNumber(display), QSocketNotifier::Read, this), SIGNAL(activated(int)), this, SLOT(displayReadyRead(int))); + connect(new QSocketNotifier(ConnectionNumber(display), QSocketNotifier::Read, this), SIGNAL(activated(int)), + this, SLOT(displayReadyRead(int))); return; } } #endif - qWarning("GlobalShortcutX: No XInput support, falling back to polled input. This wastes a lot of CPU resources, so please enable one of the other methods."); - bRunning=true; + qWarning("GlobalShortcutX: No XInput support, falling back to polled input. This wastes a lot of CPU resources, so " + "please enable one of the other methods."); + bRunning = true; start(QThread::TimeCriticalPriority); } @@ -144,7 +148,7 @@ void GlobalShortcutX::run() { int root_x, root_y; int win_x, win_y; unsigned int mask[2]; - int idx = 0; + int idx = 0; int next = 0; char keys[2][32]; @@ -158,19 +162,20 @@ void GlobalShortcutX::run() { msleep(10); - idx = next; + idx = next; next = idx ^ 1; - if (XQueryPointer(display, root, &root_ret, &child_ret, &root_x, &root_y, &win_x, &win_y, &mask[next]) && XQueryKeymap(display, keys[next])) { - for (int i=0;i<256;++i) { - int index = i / 8; - int keymask = 1 << (i % 8); + if (XQueryPointer(display, root, &root_ret, &child_ret, &root_x, &root_y, &win_x, &win_y, &mask[next]) + && XQueryKeymap(display, keys[next])) { + for (int i = 0; i < 256; ++i) { + int index = i / 8; + int keymask = 1 << (i % 8); bool oldstate = (keys[idx][index] & keymask) != 0; bool newstate = (keys[next][index] & keymask) != 0; if (oldstate != newstate) { handleButton(i, newstate); } } - for (int i=8;i<=12;++i) { + for (int i = 8; i <= 12; ++i) { bool oldstate = (mask[idx] & (1 << i)) != 0; bool newstate = (mask[next] & (1 << i)) != 0; if (oldstate != newstate) { @@ -190,7 +195,7 @@ void GlobalShortcutX::queryXIMasterList() { qsMasterDevices.clear(); dev = info = XIQueryDevice(display, XIAllDevices, &ndevices); - for (int i=0;i<ndevices;++i) { + for (int i = 0; i < ndevices; ++i) { switch (dev->use) { case XIMasterPointer: case XIMasterKeyboard: @@ -216,22 +221,22 @@ void GlobalShortcutX::displayReadyRead(int) { while (XPending(display)) { XNextEvent(display, &evt); - XGenericEventCookie *cookie = & evt.xcookie; + XGenericEventCookie *cookie = &evt.xcookie; if ((cookie->type != GenericEvent) || (cookie->extension != iXIopcode) || !XGetEventData(display, cookie)) continue; - XIDeviceEvent *xide = reinterpret_cast<XIDeviceEvent *>(cookie->data); + XIDeviceEvent *xide = reinterpret_cast< XIDeviceEvent * >(cookie->data); switch (cookie->evtype) { case XI_RawKeyPress: case XI_RawKeyRelease: - if (! qsMasterDevices.contains(xide->deviceid)) + if (!qsMasterDevices.contains(xide->deviceid)) handleButton(xide->detail, cookie->evtype == XI_RawKeyPress); break; case XI_RawButtonPress: case XI_RawButtonRelease: - if (! qsMasterDevices.contains(xide->deviceid)) + if (!qsMasterDevices.contains(xide->deviceid)) handleButton(xide->detail + 0x117, cookie->evtype == XI_RawButtonPress); break; case XI_HierarchyChanged: @@ -255,13 +260,13 @@ void GlobalShortcutX::inputReadyRead(int) { if (bNeedRemap) remap(); - QFile *f=qobject_cast<QFile *>(sender()->parent()); + QFile *f = qobject_cast< QFile * >(sender()->parent()); if (!f) return; bool found = false; - while (f->read(reinterpret_cast<char *>(&ev), sizeof(ev)) == sizeof(ev)) { + while (f->read(reinterpret_cast< char * >(&ev), sizeof(ev)) == sizeof(ev)) { found = true; if (ev.type != EV_KEY) continue; @@ -280,8 +285,8 @@ void GlobalShortcutX::inputReadyRead(int) { handleButton(evtcode, down); } - if (! found) { - int fd = f->handle(); + if (!found) { + int fd = f->handle(); int version = 0; if ((ioctl(fd, EVIOCGVERSION, &version) < 0) || (((version >> 16) & 0xFF) < 1)) { qWarning("GlobalShortcutX: Removing dead input device %s", qPrintable(f->fileName())); @@ -293,7 +298,7 @@ void GlobalShortcutX::inputReadyRead(int) { #endif } -#define test_bit(bit, array) (array[bit/8] & (1<<(bit%8))) +#define test_bit(bit, array) (array[bit / 8] & (1 << (bit % 8))) // The /dev/input directory changed void GlobalShortcutX::directoryChanged(const QString &dir) { @@ -303,31 +308,35 @@ void GlobalShortcutX::directoryChanged(const QString &dir) { } QDir d(dir, QLatin1String("event*"), 0, QDir::System); - foreach(QFileInfo fi, d.entryInfoList()) { + foreach (QFileInfo fi, d.entryInfoList()) { QString path = fi.absoluteFilePath(); - if (! qmInputDevices.contains(path)) { + if (!qmInputDevices.contains(path)) { QFile *f = new QFile(path, this); if (f->open(QIODevice::ReadOnly)) { int fd = f->handle(); int version; char name[256]; - uint8_t events[EV_MAX/8 + 1]; + uint8_t events[EV_MAX / 8 + 1]; memset(events, 0, sizeof(events)); - if ((ioctl(fd, EVIOCGVERSION, &version) >= 0) && (ioctl(fd, EVIOCGNAME(sizeof(name)), name)>=0) && (ioctl(fd, EVIOCGBIT(0,sizeof(events)), &events) >= 0) && test_bit(EV_KEY, events) && (((version >> 16) & 0xFF) > 0)) { - name[255]=0; + if ((ioctl(fd, EVIOCGVERSION, &version) >= 0) && (ioctl(fd, EVIOCGNAME(sizeof(name)), name) >= 0) + && (ioctl(fd, EVIOCGBIT(0, sizeof(events)), &events) >= 0) && test_bit(EV_KEY, events) + && (((version >> 16) & 0xFF) > 0)) { + name[255] = 0; qWarning("GlobalShortcutX: %s: %s", qPrintable(f->fileName()), name); // Is it grabbed by someone else? if ((ioctl(fd, EVIOCGRAB, 1) < 0)) { - qWarning("GlobalShortcutX: Device exclusively grabbed by someone else (X11 using exclusive-mode evdev?)"); + qWarning("GlobalShortcutX: Device exclusively grabbed by someone else (X11 using " + "exclusive-mode evdev?)"); delete f; } else { ioctl(fd, EVIOCGRAB, 0); - uint8_t keys[KEY_MAX/8 + 1]; + uint8_t keys[KEY_MAX / 8 + 1]; if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keys)), &keys) >= 0) && test_bit(KEY_SPACE, keys)) qsKeyboards.insert(f->fileName()); fcntl(f->handle(), F_SETFL, O_NONBLOCK); - connect(new QSocketNotifier(f->handle(), QSocketNotifier::Read, f), SIGNAL(activated(int)), this, SLOT(inputReadyRead(int))); + connect(new QSocketNotifier(f->handle(), QSocketNotifier::Read, f), SIGNAL(activated(int)), + this, SLOT(inputReadyRead(int))); qmInputDevices.insert(f->fileName(), f); } @@ -346,27 +355,26 @@ void GlobalShortcutX::directoryChanged(const QString &dir) { QString GlobalShortcutX::buttonName(const QVariant &v) { bool ok; - unsigned int key=v.toUInt(&ok); + unsigned int key = v.toUInt(&ok); if (!ok) return QString(); if ((key < 0x118) || (key >= 0x128)) { - // For backwards compatibility reasons we want to keep using the // old function as long as possible. The replacement function // XkbKeycodeToKeysym requires the XKB extension which isn't // guaranteed to be present. - KeySym ks=XKeycodeToKeysym(display, static_cast<KeyCode>(key), 0); + KeySym ks = XKeycodeToKeysym(display, static_cast< KeyCode >(key), 0); if (ks == NoSymbol) { - return QLatin1String("0x")+QString::number(key,16); + return QLatin1String("0x") + QString::number(key, 16); } else { - const char *str=XKeysymToString(ks); + const char *str = XKeysymToString(ks); if (*str == '\0') { - return QLatin1String("KS0x")+QString::number(ks, 16); + return QLatin1String("KS0x") + QString::number(ks, 16); } else { return QLatin1String(str); } } } else { - return tr("Mouse %1").arg(key-0x118); + return tr("Mouse %1").arg(key - 0x118); } } diff --git a/src/mumble/GlobalShortcut_unix.h b/src/mumble/GlobalShortcut_unix.h index 1ed46243c..b29310f7f 100644 --- a/src/mumble/GlobalShortcut_unix.h +++ b/src/mumble/GlobalShortcut_unix.h @@ -6,9 +6,9 @@ #ifndef MUMBLE_MUMBLE_GLOBALSHORTCUT_UNIX_H_ #define MUMBLE_MUMBLE_GLOBALSHORTCUT_UNIX_H_ -#include "GlobalShortcut.h" #include "ConfigDialog.h" #include "Global.h" +#include "GlobalShortcut.h" #include <X11/X.h> @@ -18,29 +18,29 @@ struct _XDisplay; typedef _XDisplay Display; class GlobalShortcutX : public GlobalShortcutEngine { - private: - Q_OBJECT - Q_DISABLE_COPY(GlobalShortcutX) - public: - Display *display; - QSet<Window> qsRootWindows; - int iXIopcode; - QSet<int> qsMasterDevices; - - volatile bool bRunning; - QSet<QString> qsKeyboards; - QMap<QString, QFile *> qmInputDevices; - - GlobalShortcutX(); - ~GlobalShortcutX() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; - QString buttonName(const QVariant &) Q_DECL_OVERRIDE; - - void queryXIMasterList(); - public slots: - void displayReadyRead(int); - void inputReadyRead(int); - void directoryChanged(const QString &); +private: + Q_OBJECT + Q_DISABLE_COPY(GlobalShortcutX) +public: + Display *display; + QSet< Window > qsRootWindows; + int iXIopcode; + QSet< int > qsMasterDevices; + + volatile bool bRunning; + QSet< QString > qsKeyboards; + QMap< QString, QFile * > qmInputDevices; + + GlobalShortcutX(); + ~GlobalShortcutX() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; + QString buttonName(const QVariant &) Q_DECL_OVERRIDE; + + void queryXIMasterList(); +public slots: + void displayReadyRead(int); + void inputReadyRead(int); + void directoryChanged(const QString &); }; #endif diff --git a/src/mumble/GlobalShortcut_win.cpp b/src/mumble/GlobalShortcut_win.cpp index d664927f8..4ea28fdb3 100644 --- a/src/mumble/GlobalShortcut_win.cpp +++ b/src/mumble/GlobalShortcut_win.cpp @@ -23,11 +23,12 @@ // Used to detect screen readers #include <tlhelp32.h> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" #undef FAILED -#define FAILED(Status) (static_cast<HRESULT>(Status)<0) +#define FAILED(Status) (static_cast< HRESULT >(Status) < 0) #define DX_SAMPLE_BUFFER_SIZE 512 @@ -43,64 +44,55 @@ extern HWND mumble_mw_hwnd; /// the GlobalShortcutWin engine to inject a native Windows keyboard /// event into GlobalShortcutWin's event stream. class InjectKeyboardMessageEvent : public QEvent { - Q_DISABLE_COPY(InjectKeyboardMessageEvent); - - public: - boost::promise<bool> m_suppressionPromise; - DWORD m_scancode; - DWORD m_vkcode; - bool m_extended; - bool m_down; - - /// Construct a new InjectKeyboardMessageEvent. - /// - /// @param scancode The Windows scancode of the button. - /// @param vkcode The Windows virtual keycode of the button. - /// @param extended Indicates whether the button is an extended key in - /// Windows nomenclature. ("[...] such as the right-hand ALT - /// and CTRL keys that appear on an enhanced 101- or 102-key - /// keyboard") - /// @param down The down/pressed status of the keyboard button. - InjectKeyboardMessageEvent(DWORD scancode, DWORD vkcode, bool extended, bool down) - : QEvent(static_cast<QEvent::Type>(INJECTKEYBOARDMESSAGE_QEVENT)) - , m_scancode(scancode) - , m_vkcode(vkcode) - , m_extended(extended) - , m_down(down) {} - - inline boost::future<bool> shouldSuppress() { - return m_suppressionPromise.get_future(); - } + Q_DISABLE_COPY(InjectKeyboardMessageEvent); + +public: + boost::promise< bool > m_suppressionPromise; + DWORD m_scancode; + DWORD m_vkcode; + bool m_extended; + bool m_down; + + /// Construct a new InjectKeyboardMessageEvent. + /// + /// @param scancode The Windows scancode of the button. + /// @param vkcode The Windows virtual keycode of the button. + /// @param extended Indicates whether the button is an extended key in + /// Windows nomenclature. ("[...] such as the right-hand ALT + /// and CTRL keys that appear on an enhanced 101- or 102-key + /// keyboard") + /// @param down The down/pressed status of the keyboard button. + InjectKeyboardMessageEvent(DWORD scancode, DWORD vkcode, bool extended, bool down) + : QEvent(static_cast< QEvent::Type >(INJECTKEYBOARDMESSAGE_QEVENT)), m_scancode(scancode), m_vkcode(vkcode), + m_extended(extended), m_down(down) {} + + inline boost::future< bool > shouldSuppress() { return m_suppressionPromise.get_future(); } }; /// InjectMouseMessageEvent is an event that can be sent to /// the GlobalShortcutWin engine to inject a native Windows mouse /// event into GlobalShortcutWin's event stream. class InjectMouseMessageEvent : public QEvent { - Q_DISABLE_COPY(InjectMouseMessageEvent); - - public: - boost::promise<bool> m_suppressionPromise; - unsigned int m_btn; - bool m_down; - - /// Construct a new InjectMouseMessageEvent. - /// - /// @param btn The DirectInput button index of the mouse event. - /// @param down The down/pressed status of the mouse button. - InjectMouseMessageEvent(unsigned int btn, bool down) - : QEvent(static_cast<QEvent::Type>(INJECTMOUSEMESSAGE_QEVENT)) - , m_btn(btn) - , m_down(down) {} - - inline boost::future<bool> shouldSuppress() { - return m_suppressionPromise.get_future(); - } + Q_DISABLE_COPY(InjectMouseMessageEvent); + +public: + boost::promise< bool > m_suppressionPromise; + unsigned int m_btn; + bool m_down; + + /// Construct a new InjectMouseMessageEvent. + /// + /// @param btn The DirectInput button index of the mouse event. + /// @param down The down/pressed status of the mouse button. + InjectMouseMessageEvent(unsigned int btn, bool down) + : QEvent(static_cast< QEvent::Type >(INJECTMOUSEMESSAGE_QEVENT)), m_btn(btn), m_down(down) {} + + inline boost::future< bool > shouldSuppress() { return m_suppressionPromise.get_future(); } }; uint qHash(const GUID &a) { uint val = a.Data1 ^ a.Data2 ^ a.Data3; - for (int i=0;i<8;i++) + for (int i = 0; i < 8; i++) val += a.Data4[i]; return val; } @@ -118,16 +110,14 @@ GlobalShortcutEngine *GlobalShortcutEngine::platformInit() { GlobalShortcutWin::GlobalShortcutWin() - : pDI(nullptr) - , hhMouse(nullptr) - , hhKeyboard(nullptr) - , uiHardwareDevices(0) + : pDI(nullptr), hhMouse(nullptr), hhKeyboard(nullptr), uiHardwareDevices(0) #ifdef USE_GKEY - , gkey(nullptr) + , + gkey(nullptr) #endif #ifdef USE_XBOXINPUT - , xboxinput(nullptr) - , nxboxinput(0) + , + xboxinput(nullptr), nxboxinput(0) #endif { // Hidden setting to disable hooking @@ -144,7 +134,8 @@ GlobalShortcutWin::~GlobalShortcutWin() { } void GlobalShortcutWin::run() { - if (FAILED(DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void **>(&pDI), nullptr))) { + if (FAILED(DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, + reinterpret_cast< void ** >(&pDI), nullptr))) { qFatal("GlobalShortcutWin: Failed to create d8input"); return; } @@ -153,24 +144,29 @@ void GlobalShortcutWin::run() { // On Windows 7 and greater, Windows will silently remove badly behaving hooks // without telling the application. Users can tweak the timeout themselves // with this registry key. - HKEY key = nullptr; - DWORD type = 0; + HKEY key = nullptr; + DWORD type = 0; DWORD value = 0; - DWORD len = sizeof(DWORD); + DWORD len = sizeof(DWORD); if (RegOpenKeyExA(HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, KEY_READ, &key) == ERROR_SUCCESS) { - LONG err = RegQueryValueExA(key, "LowLevelHooksTimeout", nullptr, &type, reinterpret_cast<LPBYTE>(&value), &len); + LONG err = + RegQueryValueExA(key, "LowLevelHooksTimeout", nullptr, &type, reinterpret_cast< LPBYTE >(&value), &len); if (err == ERROR_SUCCESS && type == REG_DWORD) { - qWarning("GlobalShortcutWin: Found LowLevelHooksTimeout with value = 0x%lx", static_cast<unsigned long>(value)); + qWarning("GlobalShortcutWin: Found LowLevelHooksTimeout with value = 0x%lx", + static_cast< unsigned long >(value)); } else if (err == ERROR_FILE_NOT_FOUND) { qWarning("GlobalShortcutWin: No LowLevelHooksTimeout registry key found."); } else { - qWarning("GlobalShortcutWin: Error looking up LowLevelHooksTimeout. (Error: 0x%lx, Type: 0x%lx, Value: 0x%lx)", static_cast<unsigned long>(err), static_cast<unsigned long>(type), static_cast<unsigned long>(value)); + qWarning( + "GlobalShortcutWin: Error looking up LowLevelHooksTimeout. (Error: 0x%lx, Type: 0x%lx, Value: 0x%lx)", + static_cast< unsigned long >(err), static_cast< unsigned long >(type), + static_cast< unsigned long >(value)); } } // Wait for MainWindow's constructor to finish before we enumerate DirectInput devices. // We need to do this because adding a new device requires a Window handle. (SetCooperativeLevel()) - while (! g.mw) + while (!g.mw) this->yieldCurrentThread(); #ifdef USE_GKEY @@ -215,7 +211,7 @@ void GlobalShortcutWin::run() { } } - foreach(InputDevice *id, qhInputDevices) { + foreach (InputDevice *id, qhInputDevices) { if (id->pDID) { id->pDID->Unacquire(); id->pDID->Release(); @@ -228,13 +224,13 @@ void GlobalShortcutWin::run() { bool GlobalShortcutWin::event(QEvent *event) { QEvent::Type type = event->type(); if (type == INJECTKEYBOARDMESSAGE_QEVENT) { - InjectKeyboardMessageEvent *ikme = static_cast<InjectKeyboardMessageEvent *>(event); + InjectKeyboardMessageEvent *ikme = static_cast< InjectKeyboardMessageEvent * >(event); bool suppress = handleKeyboardMessage(ikme->m_scancode, ikme->m_vkcode, ikme->m_extended, ikme->m_down); ikme->m_suppressionPromise.set_value(suppress); return true; } else if (type == INJECTMOUSEMESSAGE_QEVENT) { - InjectMouseMessageEvent *imme = static_cast<InjectMouseMessageEvent *>(event); - bool suppress = handleMouseMessage(imme->m_btn, imme->m_down); + InjectMouseMessageEvent *imme = static_cast< InjectMouseMessageEvent * >(event); + bool suppress = handleMouseMessage(imme->m_btn, imme->m_down); imme->m_suppressionPromise.set_value(suppress); return true; } @@ -258,12 +254,12 @@ bool GlobalShortcutWin::injectKeyboardMessage(MSG *msg) { } DWORD scancode = (msg->lParam >> 16) & 0xff; - DWORD vkcode = msg->wParam; - bool extended = !!(msg->lParam & 0x01000000); - bool up = !!(msg->lParam & 0x80000000); + DWORD vkcode = msg->wParam; + bool extended = !!(msg->lParam & 0x01000000); + bool up = !!(msg->lParam & 0x80000000); InjectKeyboardMessageEvent *ikme = new InjectKeyboardMessageEvent(scancode, vkcode, extended, !up); - boost::future<bool> suppress = ikme->shouldSuppress(); + boost::future< bool > suppress = ikme->shouldSuppress(); qApp->postEvent(this, ikme); return suppress.get(); } @@ -273,7 +269,7 @@ bool GlobalShortcutWin::injectMouseMessage(MSG *msg) { return false; } - bool down = false; + bool down = false; unsigned int btn = 0; // Convert the Windows mouse message into a DirectInput @@ -298,27 +294,27 @@ bool GlobalShortcutWin::injectMouseMessage(MSG *msg) { down = true; case WM_XBUTTONUP: { unsigned int offset = (msg->wParam >> 16) & 0xffff; - btn = 5 + offset; + btn = 5 + offset; } default: // Non-mouse event. Return early. return false; } - InjectMouseMessageEvent *imme = new InjectMouseMessageEvent(btn, down); - boost::future<bool> suppress = imme->shouldSuppress(); + InjectMouseMessageEvent *imme = new InjectMouseMessageEvent(btn, down); + boost::future< bool > suppress = imme->shouldSuppress(); qApp->postEvent(this, imme); return suppress.get(); } bool GlobalShortcutWin::handleKeyboardMessage(DWORD scancode, DWORD vkcode, bool extended, bool down) { - GlobalShortcutWin *gsw = static_cast<GlobalShortcutWin *>(engine); + GlobalShortcutWin *gsw = static_cast< GlobalShortcutWin * >(engine); - QList<QVariant> ql; + QList< QVariant > ql; // Convert the low-level key event to // a DirectInput key ID. - unsigned int keyid = static_cast<unsigned int>((scancode << 8) | 0x4); + unsigned int keyid = static_cast< unsigned int >((scancode << 8) | 0x4); if (extended) { keyid |= 0x8000U; } @@ -362,26 +358,26 @@ bool GlobalShortcutWin::handleKeyboardMessage(DWORD scancode, DWORD vkcode, bool } bool GlobalShortcutWin::handleMouseMessage(unsigned int btn, bool down) { - GlobalShortcutWin *gsw = static_cast<GlobalShortcutWin *>(engine); + GlobalShortcutWin *gsw = static_cast< GlobalShortcutWin * >(engine); bool suppress = false; if (btn > 0) { - QList<QVariant> ql; - ql << static_cast<unsigned int>((btn << 8) | 0x4); + QList< QVariant > ql; + ql << static_cast< unsigned int >((btn << 8) | 0x4); ql << QVariant(QUuid(GUID_SysMouse)); // Do not suppress LBUTTONUP though (so suppression can be deactivated via mouse). bool wantsuppress = gsw->handleButton(ql, down); - suppress = wantsuppress && (btn != 3); + suppress = wantsuppress && (btn != 3); } return suppress; } LRESULT CALLBACK GlobalShortcutWin::HookKeyboard(int nCode, WPARAM wParam, LPARAM lParam) { - GlobalShortcutWin *gsw=static_cast<GlobalShortcutWin *>(engine); - KBDLLHOOKSTRUCT *key=reinterpret_cast<KBDLLHOOKSTRUCT *>(lParam); + GlobalShortcutWin *gsw = static_cast< GlobalShortcutWin * >(engine); + KBDLLHOOKSTRUCT *key = reinterpret_cast< KBDLLHOOKSTRUCT * >(lParam); #ifndef QT_NO_DEBUG static int safety = 0; @@ -391,10 +387,10 @@ LRESULT CALLBACK GlobalShortcutWin::HookKeyboard(int nCode, WPARAM wParam, LPARA if (nCode >= 0) { #endif DWORD scancode = key->scanCode; - DWORD vkcode = key->vkCode; - bool extended = !!(key->flags & LLKHF_EXTENDED); - bool up = !!(key->flags & LLKHF_UP); - bool suppress = handleKeyboardMessage(scancode, vkcode, extended, !up); + DWORD vkcode = key->vkCode; + bool extended = !!(key->flags & LLKHF_EXTENDED); + bool up = !!(key->flags & LLKHF_UP); + bool suppress = handleKeyboardMessage(scancode, vkcode, extended, !up); if (suppress) { return 1; } @@ -403,15 +399,15 @@ LRESULT CALLBACK GlobalShortcutWin::HookKeyboard(int nCode, WPARAM wParam, LPARA } LRESULT CALLBACK GlobalShortcutWin::HookMouse(int nCode, WPARAM wParam, LPARAM lParam) { - GlobalShortcutWin *gsw=static_cast<GlobalShortcutWin *>(engine); - MSLLHOOKSTRUCT *mouse=reinterpret_cast<MSLLHOOKSTRUCT *>(lParam); + GlobalShortcutWin *gsw = static_cast< GlobalShortcutWin * >(engine); + MSLLHOOKSTRUCT *mouse = reinterpret_cast< MSLLHOOKSTRUCT * >(lParam); if (nCode >= 0) { bool suppress = false; - UINT msg = wParam; + UINT msg = wParam; // Convert the hooked Windows mouse message into a DirectInput // button index, and store the pressed state of the button. - bool down = false; + bool down = false; unsigned int btn = 0; switch (msg) { case WM_LBUTTONDOWN: @@ -447,27 +443,25 @@ LRESULT CALLBACK GlobalShortcutWin::HookMouse(int nCode, WPARAM wParam, LPARAM l } BOOL CALLBACK GlobalShortcutWin::EnumDeviceObjectsCallback(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef) { - InputDevice *id=static_cast<InputDevice *>(pvRef); - QString name = QString::fromUtf16(reinterpret_cast<const ushort *>(lpddoi->tszName)); + InputDevice *id = static_cast< InputDevice * >(pvRef); + QString name = QString::fromUtf16(reinterpret_cast< const ushort * >(lpddoi->tszName)); id->qhNames[lpddoi->dwType] = name; if (g.s.bDirectInputVerboseLogging) { qWarning("GlobalShortcutWin: EnumObjects: device %s %s object 0x%.8lx %s", - qPrintable(QUuid(id->guid).toString()), - qPrintable(id->name), - static_cast<unsigned long>(lpddoi->dwType), - qPrintable(name)); + qPrintable(QUuid(id->guid).toString()), qPrintable(id->name), + static_cast< unsigned long >(lpddoi->dwType), qPrintable(name)); } return DIENUM_CONTINUE; } BOOL GlobalShortcutWin::EnumDevicesCB(LPCDIDEVICEINSTANCE pdidi, LPVOID pContext) { - GlobalShortcutWin *cbgsw=static_cast<GlobalShortcutWin *>(pContext); + GlobalShortcutWin *cbgsw = static_cast< GlobalShortcutWin * >(pContext); HRESULT hr; - QString name = QString::fromUtf16(reinterpret_cast<const ushort *>(pdidi->tszProductName)); - QString sname = QString::fromUtf16(reinterpret_cast<const ushort *>(pdidi->tszInstanceName)); + QString name = QString::fromUtf16(reinterpret_cast< const ushort * >(pdidi->tszProductName)); + QString sname = QString::fromUtf16(reinterpret_cast< const ushort * >(pdidi->tszInstanceName)); InputDevice *id = new InputDevice; @@ -475,10 +469,10 @@ BOOL GlobalShortcutWin::EnumDevicesCB(LPCDIDEVICEINSTANCE pdidi, LPVOID pContext id->name = name; - id->guid = pdidi->guidInstance; + id->guid = pdidi->guidInstance; id->vguid = QVariant(QUuid(id->guid).toString()); - id->guidproduct = pdidi->guidProduct; + id->guidproduct = pdidi->guidProduct; id->vguidproduct = QVariant(QUuid(id->guidproduct).toString()); // Is it an XInput device? Skip it. @@ -494,9 +488,7 @@ BOOL GlobalShortcutWin::EnumDevicesCB(LPCDIDEVICEINSTANCE pdidi, LPVOID pContext cbgsw->nxboxinput += 1; #endif qWarning("GlobalShortcutWin: excluded XInput device '%s' (guid %s guid product %s) from DirectInput", - qPrintable(id->name), - qPrintable(id->vguid.toString()), - qPrintable(id->vguidproduct.toString())); + qPrintable(id->name), qPrintable(id->vguid.toString()), qPrintable(id->vguidproduct.toString())); delete id; return DIENUM_CONTINUE; } @@ -505,13 +497,13 @@ BOOL GlobalShortcutWin::EnumDevicesCB(LPCDIDEVICEINSTANCE pdidi, LPVOID pContext // per http://stackoverflow.com/q/25622780. BYTE pidvid[8] = { 0, 0, 'P', 'I', 'D', 'V', 'I', 'D' }; if (memcmp(id->guidproduct.Data4, pidvid, 8) == 0) { - uint16_t vendor_id = id->guidproduct.Data1 & 0xffff; + uint16_t vendor_id = id->guidproduct.Data1 & 0xffff; uint16_t product_id = (id->guidproduct.Data1 >> 16) & 0xffff; - id->vendor_id = vendor_id; + id->vendor_id = vendor_id; id->product_id = product_id; } else { - id->vendor_id = 0x00; + id->vendor_id = 0x00; id->product_id = 0x00; } @@ -536,19 +528,16 @@ BOOL GlobalShortcutWin::EnumDevicesCB(LPCDIDEVICEINSTANCE pdidi, LPVOID pContext // blacklist, we need a more structured aproach. { if (id->vendor_id == 0x262A) { - qWarning("GlobalShortcutWin: rejected blacklisted device %s (GUID: %s, PGUID: %s, VID: 0x%.4x, PID: 0x%.4x, TYPE: 0x%.8lx)", - qPrintable(id->name), - qPrintable(id->vguid.toString()), - qPrintable(id->vguidproduct.toString()), - id->vendor_id, - id->product_id, - static_cast<unsigned long>(pdidi->dwDevType)); + qWarning("GlobalShortcutWin: rejected blacklisted device %s (GUID: %s, PGUID: %s, VID: 0x%.4x, PID: " + "0x%.4x, TYPE: 0x%.8lx)", + qPrintable(id->name), qPrintable(id->vguid.toString()), qPrintable(id->vguidproduct.toString()), + id->vendor_id, id->product_id, static_cast< unsigned long >(pdidi->dwDevType)); delete id; return DIENUM_CONTINUE; } } - foreach(InputDevice *dev, cbgsw->qhInputDevices) { + foreach (InputDevice *dev, cbgsw->qhInputDevices) { if (dev->guid == id->guid) { delete id; return DIENUM_CONTINUE; @@ -558,34 +547,34 @@ BOOL GlobalShortcutWin::EnumDevicesCB(LPCDIDEVICEINSTANCE pdidi, LPVOID pContext if (FAILED(hr = cbgsw->pDI->CreateDevice(pdidi->guidInstance, &id->pDID, nullptr))) qFatal("GlobalShortcutWin: CreateDevice: %lx", hr); - if (FAILED(hr = id->pDID->EnumObjects(EnumDeviceObjectsCallback, static_cast<void *>(id), DIDFT_BUTTON))) + if (FAILED(hr = id->pDID->EnumObjects(EnumDeviceObjectsCallback, static_cast< void * >(id), DIDFT_BUTTON))) qFatal("GlobalShortcutWin: EnumObjects: %lx", hr); if (id->qhNames.count() > 0) { - QList<DWORD> types = id->qhNames.keys(); + QList< DWORD > types = id->qhNames.keys(); std::sort(types.begin(), types.end()); int nbuttons = types.count(); STACKVAR(DIOBJECTDATAFORMAT, rgodf, nbuttons); DIDATAFORMAT df; ZeroMemory(&df, sizeof(df)); - df.dwSize = sizeof(df); - df.dwObjSize = sizeof(DIOBJECTDATAFORMAT); - df.dwFlags=DIDF_ABSAXIS; + df.dwSize = sizeof(df); + df.dwObjSize = sizeof(DIOBJECTDATAFORMAT); + df.dwFlags = DIDF_ABSAXIS; df.dwDataSize = (nbuttons + 3) & (~0x3); - df.dwNumObjs = nbuttons; - df.rgodf = rgodf; - for (int i=0;i<nbuttons;i++) { - ZeroMemory(& rgodf[i], sizeof(DIOBJECTDATAFORMAT)); - DWORD dwType = types[i]; - DWORD dwOfs = i; - rgodf[i].dwOfs = dwOfs; - rgodf[i].dwType = dwType; - id->qhOfsToType[dwOfs] = dwType; + df.dwNumObjs = nbuttons; + df.rgodf = rgodf; + for (int i = 0; i < nbuttons; i++) { + ZeroMemory(&rgodf[i], sizeof(DIOBJECTDATAFORMAT)); + DWORD dwType = types[i]; + DWORD dwOfs = i; + rgodf[i].dwOfs = dwOfs; + rgodf[i].dwType = dwType; + id->qhOfsToType[dwOfs] = dwType; id->qhTypeToOfs[dwType] = dwOfs; } - if (FAILED(hr = id->pDID->SetCooperativeLevel(mumble_mw_hwnd, DISCL_NONEXCLUSIVE|DISCL_BACKGROUND))) + if (FAILED(hr = id->pDID->SetCooperativeLevel(mumble_mw_hwnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND))) qFatal("GlobalShortcutWin: SetCooperativeLevel: %lx", hr); if (FAILED(hr = id->pDID->SetDataFormat(&df))) @@ -602,13 +591,9 @@ BOOL GlobalShortcutWin::EnumDevicesCB(LPCDIDEVICEINSTANCE pdidi, LPVOID pContext if (FAILED(hr = id->pDID->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph))) qFatal("GlobalShortcutWin: SetProperty: %lx", hr); - qWarning("Adding device %s %s %s:%d type 0x%.8lx guid product %s", - qPrintable(QUuid(id->guid).toString()), - qPrintable(name), - qPrintable(sname), - id->qhNames.count(), - static_cast<unsigned long>(pdidi->dwDevType), - qPrintable(id->vguidproduct.toString())); + qWarning("Adding device %s %s %s:%d type 0x%.8lx guid product %s", qPrintable(QUuid(id->guid).toString()), + qPrintable(name), qPrintable(sname), id->qhNames.count(), + static_cast< unsigned long >(pdidi->dwDevType), qPrintable(id->vguidproduct.toString())); cbgsw->qhInputDevices[id->guid] = id; } else { @@ -627,15 +612,15 @@ void GlobalShortcutWin::timeTicked() { #ifdef USE_XBOXINPUT nxboxinput = 0; #endif - pDI->EnumDevices(DI8DEVCLASS_ALL, EnumDevicesCB, static_cast<void *>(this), DIEDFL_ATTACHEDONLY); + pDI->EnumDevices(DI8DEVCLASS_ALL, EnumDevicesCB, static_cast< void * >(this), DIEDFL_ATTACHEDONLY); } if (bNeedRemap) remap(); - foreach(InputDevice *id, qhInputDevices) { + foreach (InputDevice *id, qhInputDevices) { DIDEVICEOBJECTDATA rgdod[DX_SAMPLE_BUFFER_SIZE]; - DWORD dwItems = DX_SAMPLE_BUFFER_SIZE; + DWORD dwItems = DX_SAMPLE_BUFFER_SIZE; HRESULT hr; hr = id->pDID->Acquire(); @@ -667,7 +652,9 @@ void GlobalShortcutWin::timeTicked() { // a second, warn the user that they // might have a misbehaving device. if (timer.elapsed() > 1000) { - qWarning("GlobalShortcut_win: Poll() for device %s took %li msec. This is abnormal, the device is possibly misbehaving...", qPrintable(QUuid(id->guid).toString()), static_cast<long>(timer.elapsed())); + qWarning("GlobalShortcut_win: Poll() for device %s took %li msec. This is abnormal, the device is " + "possibly misbehaving...", + qPrintable(QUuid(id->guid).toString()), static_cast< long >(timer.elapsed())); } } @@ -678,8 +665,8 @@ void GlobalShortcutWin::timeTicked() { if (dwItems <= 0) continue; - for (DWORD j=0; j<dwItems; j++) { - QList<QVariant> ql; + for (DWORD j = 0; j < dwItems; j++) { + QList< QVariant > ql; quint32 uiType = id->qhOfsToType.value(rgdod[j].dwOfs); ql << uiType; @@ -691,14 +678,14 @@ void GlobalShortcutWin::timeTicked() { #ifdef USE_GKEY if (g.s.bEnableGKey && gkey && gkey->isValid()) { for (int button = GKEY_MIN_MOUSE_BUTTON; button <= GKEY_MAX_MOUSE_BUTTON; button++) { - QList<QVariant> ql; + QList< QVariant > ql; ql << button; ql << GKeyLibrary::quMouse; handleButton(ql, gkey->isMouseButtonPressed(button)); } for (int mode = GKEY_MIN_KEYBOARD_MODE; mode <= GKEY_MAX_KEYBOARD_MODE; mode++) { for (int key = GKEY_MIN_KEYBOARD_BUTTON; key <= GKEY_MAX_KEYBOARD_BUTTON; key++) { - QList<QVariant> ql; + QList< QVariant > ql; // Store the key and mode in one int // bit 0..15: mode, bit 16..31: key ql << (key | (mode << 16)); @@ -738,7 +725,7 @@ void GlobalShortcutWin::timeTicked() { // buttons, we assign them the button indexes 16 and 17. uint32_t buttonMask = state.buttons; for (uint32_t j = 0; j < 18; j++) { - QList<QVariant> ql; + QList< QVariant > ql; bool pressed = false; if (j >= 16) { @@ -749,11 +736,11 @@ void GlobalShortcutWin::timeTicked() { } } else { uint32_t currentButtonMask = (1 << j); - pressed = (buttonMask & currentButtonMask) != 0; + pressed = (buttonMask & currentButtonMask) != 0; } uint32_t type = (i << 24) | j; - ql << static_cast<uint>(type); + ql << static_cast< uint >(type); ql << XboxInput::s_XboxInputGuid; handleButton(ql, pressed); } @@ -793,38 +780,39 @@ void GlobalShortcutWin::timeTicked() { // behavior of the system's mouse input. if (bHook && !hhMouse && !hhKeyboard) { HMODULE hSelf; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<LPCTSTR>(&HookKeyboard), &hSelf); - hhMouse = SetWindowsHookEx(WH_MOUSE_LL, HookMouse, hSelf, 0); + GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast< LPCTSTR >(&HookKeyboard), &hSelf); + hhMouse = SetWindowsHookEx(WH_MOUSE_LL, HookMouse, hSelf, 0); hhKeyboard = SetWindowsHookEx(WH_KEYBOARD_LL, HookKeyboard, hSelf, 0); } } QString GlobalShortcutWin::buttonName(const QVariant &v) { - GlobalShortcutWin *gsw = static_cast<GlobalShortcutWin *>(GlobalShortcutEngine::engine); + GlobalShortcutWin *gsw = static_cast< GlobalShortcutWin * >(GlobalShortcutEngine::engine); - const QList<QVariant> &sublist = v.toList(); + const QList< QVariant > &sublist = v.toList(); if (sublist.count() != 2) return QString(); - bool ok = false; + bool ok = false; DWORD type = sublist.at(0).toUInt(&ok); QUuid guid(sublist.at(1).toString()); if (guid.isNull() || (!ok)) return QString(); - QString device=guid.toString(); - QString name=QLatin1String("Unknown"); + QString device = guid.toString(); + QString name = QLatin1String("Unknown"); #ifdef USE_GKEY if (g.s.bEnableGKey && gkey && gkey->isValid()) { bool isGKey = false; if (guid == GKeyLibrary::quMouse) { isGKey = true; - name = gkey->getMouseButtonString(type); + name = gkey->getMouseButtonString(type); } else if (guid == GKeyLibrary::quKeyboard) { isGKey = true; - name = gkey->getKeyboardGkeyString(type & 0xFFFF, type >> 16); + name = gkey->getKeyboardGkeyString(type & 0xFFFF, type >> 16); } if (isGKey) { device = QLatin1String("GKey:"); @@ -835,7 +823,7 @@ QString GlobalShortcutWin::buttonName(const QVariant &v) { #ifdef USE_XBOXINPUT if (g.s.bEnableXboxInput && xboxinput && xboxinput->isValid() && guid == XboxInput::s_XboxInputGuid) { - uint32_t idx = (type >> 24) & 0xff; + uint32_t idx = (type >> 24) & 0xff; uint32_t button = (type & 0x00ffffff); // Translate from our own button index mapping to @@ -885,18 +873,18 @@ QString GlobalShortcutWin::buttonName(const QVariant &v) { InputDevice *id = gsw->qhInputDevices.value(guid); if (guid == GUID_SysMouse) - device=QLatin1String("M:"); + device = QLatin1String("M:"); else if (guid == GUID_SysKeyboard) - device=QLatin1String("K:"); + device = QLatin1String("K:"); else if (id) - device=id->name+QLatin1String(":"); + device = id->name + QLatin1String(":"); if (id) { QString result = id->qhNames.value(type); if (!result.isEmpty()) { name = result; } } - return device+name; + return device + name; } bool GlobalShortcutWin::canSuppress() { @@ -912,7 +900,7 @@ bool GlobalShortcutWin::areScreenReadersActive() { if (snapshot != INVALID_HANDLE_VALUE) { PROCESSENTRY32 p; p.dwSize = sizeof(p); - auto ok = Process32First(snapshot, &p); + auto ok = Process32First(snapshot, &p); while (ok) { if (executables.contains(QString::fromWCharArray(p.szExeFile))) { CloseHandle(snapshot); diff --git a/src/mumble/GlobalShortcut_win.h b/src/mumble/GlobalShortcut_win.h index 1674c59b3..7772fac3f 100644 --- a/src/mumble/GlobalShortcut_win.h +++ b/src/mumble/GlobalShortcut_win.h @@ -6,21 +6,21 @@ #ifndef MUMBLE_MUMBLE_GLOBALSHORTCUT_WIN_H_ #define MUMBLE_MUMBLE_GLOBALSHORTCUT_WIN_H_ -#include "GlobalShortcut.h" #include "Timer.h" +#include "GlobalShortcut.h" #ifdef USE_GKEY -#include "GKey.h" +# include "GKey.h" #endif #ifdef USE_XBOXINPUT -#include "XboxInput.h" +# include "XboxInput.h" #endif #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> -typedef QPair<GUID, DWORD> qpButton; +typedef QPair< GUID, DWORD > qpButton; struct InputDevice { LPDIRECTINPUTDEVICE8 pDID; @@ -37,101 +37,102 @@ struct InputDevice { uint16_t product_id; // dwType to name - QHash<DWORD, QString> qhNames; + QHash< DWORD, QString > qhNames; // Map dwType to dwOfs in our structure - QHash<DWORD, DWORD> qhTypeToOfs; + QHash< DWORD, DWORD > qhTypeToOfs; // Map dwOfs in our structure to dwType - QHash<DWORD, DWORD> qhOfsToType; + QHash< DWORD, DWORD > qhOfsToType; // Buttons active since last reset - QSet<DWORD> activeMap; + QSet< DWORD > activeMap; }; class GlobalShortcutWin : public GlobalShortcutEngine { - private: - Q_OBJECT - Q_DISABLE_COPY(GlobalShortcutWin) - public: - LPDIRECTINPUT8 pDI; - QHash<GUID, InputDevice *> qhInputDevices; - HHOOK hhMouse, hhKeyboard; - unsigned int uiHardwareDevices; - Timer tDoubleClick; - bool bHook; +private: + Q_OBJECT + Q_DISABLE_COPY(GlobalShortcutWin) +public: + LPDIRECTINPUT8 pDI; + QHash< GUID, InputDevice * > qhInputDevices; + HHOOK hhMouse, hhKeyboard; + unsigned int uiHardwareDevices; + Timer tDoubleClick; + bool bHook; #ifdef USE_GKEY - GKeyLibrary *gkey; + GKeyLibrary *gkey; #endif #ifdef USE_XBOXINPUT - /// xboxinputLastPacket holds the last packet number - /// that was processed. Any new data queried for a - /// device is only valid if the packet number is - /// different than last time we queried it. - uint32_t xboxinputLastPacket[XBOXINPUT_MAX_DEVICES]; - XboxInput *xboxinput; - /// nxboxinput holds the number of XInput devices - /// available on the system. It is filled out by - /// our EnumDevices callback. - int nxboxinput; + /// xboxinputLastPacket holds the last packet number + /// that was processed. Any new data queried for a + /// device is only valid if the packet number is + /// different than last time we queried it. + uint32_t xboxinputLastPacket[XBOXINPUT_MAX_DEVICES]; + XboxInput *xboxinput; + /// nxboxinput holds the number of XInput devices + /// available on the system. It is filled out by + /// our EnumDevices callback. + int nxboxinput; #endif - static BOOL CALLBACK EnumSuitableDevicesCB(LPCDIDEVICEINSTANCE, LPDIRECTINPUTDEVICE8, DWORD, DWORD, LPVOID); - static BOOL CALLBACK EnumDevicesCB(LPCDIDEVICEINSTANCE, LPVOID); - static BOOL CALLBACK EnumDeviceObjectsCallback(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef); - static LRESULT CALLBACK HookKeyboard(int, WPARAM, LPARAM); - static LRESULT CALLBACK HookMouse(int, WPARAM, LPARAM); - - /// Handle an incoming Windows keyboard message. - /// - /// Returns true if the GlobalShortcut engine signals that the - /// button should be suppressed. Returns false otherwise. - static bool handleKeyboardMessage(DWORD scancode, DWORD vkcode, bool extended, bool down); - - /// Handle an incoming Windows mouse message. - /// - /// Returns true if the GlobalShortcut engine signals that the - /// button should be suppressed. Returns false otherwise. - static bool handleMouseMessage(unsigned int btn, bool down); - - virtual bool canSuppress() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; - bool event(QEvent *e) Q_DECL_OVERRIDE; - public slots: - void timeTicked(); - public: - GlobalShortcutWin(); - ~GlobalShortcutWin() Q_DECL_OVERRIDE; - void unacquire(); - QString buttonName(const QVariant &) Q_DECL_OVERRIDE; - - /// Inject a native Windows keyboard message into GlobalShortcutWin's - /// event stream. This method is meant to be called from the main thread - /// to pass native Windows keyboard messages to GlobalShortcutWin. - /// - /// @param msg The keyboard message to inject into GlobalShortcutWin. - /// Must be WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN or WM_SYSKEYUP. - /// Otherwise the message will be ignored. - /// - /// @return Returns true if the GlobalShortcut engine signalled that - /// the button should be suppressed. Returns false otherwise. - bool injectKeyboardMessage(MSG *msg); - - /// Inject a native Windows mouse message into GlobalShortcutWin's - /// event stream. This method is meant to be called from the main thread - /// to pass native Windows mouse messages to GlobalShortcutWin. - /// - /// @param msg The keyboard message to inject into GlobalShortcutWin. - /// Must be WM_LBUTTONDOWN, WM_LBUTTONUP, WM_RBUTTONDOWN, - /// WM_RBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_XBUTTONDOWN - /// or WM_XBUTTONUP. Otherwise the message will be ignored. - /// - /// @return Returns true if the GlobalShortcut engine signalled that - /// the button should be suppressed. Returns false otherwise. - bool injectMouseMessage(MSG *msg); - - private: - bool areScreenReadersActive(); + static BOOL CALLBACK EnumSuitableDevicesCB(LPCDIDEVICEINSTANCE, LPDIRECTINPUTDEVICE8, DWORD, DWORD, LPVOID); + static BOOL CALLBACK EnumDevicesCB(LPCDIDEVICEINSTANCE, LPVOID); + static BOOL CALLBACK EnumDeviceObjectsCallback(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef); + static LRESULT CALLBACK HookKeyboard(int, WPARAM, LPARAM); + static LRESULT CALLBACK HookMouse(int, WPARAM, LPARAM); + + /// Handle an incoming Windows keyboard message. + /// + /// Returns true if the GlobalShortcut engine signals that the + /// button should be suppressed. Returns false otherwise. + static bool handleKeyboardMessage(DWORD scancode, DWORD vkcode, bool extended, bool down); + + /// Handle an incoming Windows mouse message. + /// + /// Returns true if the GlobalShortcut engine signals that the + /// button should be suppressed. Returns false otherwise. + static bool handleMouseMessage(unsigned int btn, bool down); + + virtual bool canSuppress() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; + bool event(QEvent *e) Q_DECL_OVERRIDE; +public slots: + void timeTicked(); + +public: + GlobalShortcutWin(); + ~GlobalShortcutWin() Q_DECL_OVERRIDE; + void unacquire(); + QString buttonName(const QVariant &) Q_DECL_OVERRIDE; + + /// Inject a native Windows keyboard message into GlobalShortcutWin's + /// event stream. This method is meant to be called from the main thread + /// to pass native Windows keyboard messages to GlobalShortcutWin. + /// + /// @param msg The keyboard message to inject into GlobalShortcutWin. + /// Must be WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN or WM_SYSKEYUP. + /// Otherwise the message will be ignored. + /// + /// @return Returns true if the GlobalShortcut engine signalled that + /// the button should be suppressed. Returns false otherwise. + bool injectKeyboardMessage(MSG *msg); + + /// Inject a native Windows mouse message into GlobalShortcutWin's + /// event stream. This method is meant to be called from the main thread + /// to pass native Windows mouse messages to GlobalShortcutWin. + /// + /// @param msg The keyboard message to inject into GlobalShortcutWin. + /// Must be WM_LBUTTONDOWN, WM_LBUTTONUP, WM_RBUTTONDOWN, + /// WM_RBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_XBUTTONDOWN + /// or WM_XBUTTONUP. Otherwise the message will be ignored. + /// + /// @return Returns true if the GlobalShortcut engine signalled that + /// the button should be suppressed. Returns false otherwise. + bool injectMouseMessage(MSG *msg); + +private: + bool areScreenReadersActive(); }; uint qHash(const GUID &); diff --git a/src/mumble/JackAudio.cpp b/src/mumble/JackAudio.cpp index 99ef79c75..48334d1a4 100644 --- a/src/mumble/JackAudio.cpp +++ b/src/mumble/JackAudio.cpp @@ -7,16 +7,27 @@ #include "Utils.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" #ifdef Q_CC_GNU -# define RESOLVE(var) {var = reinterpret_cast<__typeof__(var)>(qlJack.resolve(#var)); if (!var) return; } +# define RESOLVE(var) \ + { \ + var = reinterpret_cast< __typeof__(var) >(qlJack.resolve(#var)); \ + if (!var) \ + return; \ + } #else -# define RESOLVE(var) { *reinterpret_cast<void **>(&var) = static_cast<void *>(qlJack.resolve(#var)); if (!var) return; } +# define RESOLVE(var) \ + { \ + *reinterpret_cast< void ** >(&var) = static_cast< void * >(qlJack.resolve(#var)); \ + if (!var) \ + return; \ + } #endif -static std::unique_ptr<JackAudioSystem> jas; +static std::unique_ptr< JackAudioSystem > jas; // jackStatusToStringList converts a jack_status_t (a flag type // that can contain multiple Jack statuses) to a QStringList. @@ -29,7 +40,7 @@ static QStringList jackStatusToStringList(const jack_status_t &status) { if (status & JackInvalidOption) { statusList << QLatin1String("JackInvalidOption - the operation contained an invalid or unsupported option"); } - if (status & JackNameNotUnique) { + if (status & JackNameNotUnique) { statusList << QLatin1String("JackNameNotUnique - the desired client name is not unique"); } if (status & JackServerStarted) { @@ -50,7 +61,7 @@ static QStringList jackStatusToStringList(const jack_status_t &status) { if (status & JackInitFailure) { statusList << QLatin1String("JackInitFailure - unable to initialize client"); } - if (status & JackShmFailure) { + if (status & JackShmFailure) { statusList << QLatin1String("JackShmFailure - unable to access shared memory"); } if (status & JackVersionError) { @@ -67,43 +78,44 @@ static QStringList jackStatusToStringList(const jack_status_t &status) { } class JackAudioInputRegistrar : public AudioInputRegistrar { - private: - AudioInput *create() Q_DECL_OVERRIDE; - const QList<audioDevice> getDeviceChoices() Q_DECL_OVERRIDE; - void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; - bool canEcho(const QString &) const Q_DECL_OVERRIDE; - - public: - JackAudioInputRegistrar(); +private: + AudioInput *create() Q_DECL_OVERRIDE; + const QList< audioDevice > getDeviceChoices() Q_DECL_OVERRIDE; + void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; + bool canEcho(const QString &) const Q_DECL_OVERRIDE; + +public: + JackAudioInputRegistrar(); }; class JackAudioOutputRegistrar : public AudioOutputRegistrar { - private: - AudioOutput *create() Q_DECL_OVERRIDE; - const QList<audioDevice> getDeviceChoices() Q_DECL_OVERRIDE; - void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; - bool usesOutputDelay() const Q_DECL_OVERRIDE; - - public: - JackAudioOutputRegistrar(); +private: + AudioOutput *create() Q_DECL_OVERRIDE; + const QList< audioDevice > getDeviceChoices() Q_DECL_OVERRIDE; + void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; + bool usesOutputDelay() const Q_DECL_OVERRIDE; + +public: + JackAudioOutputRegistrar(); }; class JackAudioInit : public DeferInit { - private: - std::unique_ptr<JackAudioInputRegistrar> airJackAudio; - std::unique_ptr<JackAudioOutputRegistrar> aorJackAudio; - void initialize() Q_DECL_OVERRIDE; - void destroy() Q_DECL_OVERRIDE; +private: + std::unique_ptr< JackAudioInputRegistrar > airJackAudio; + std::unique_ptr< JackAudioOutputRegistrar > aorJackAudio; + void initialize() Q_DECL_OVERRIDE; + void destroy() Q_DECL_OVERRIDE; }; -JackAudioInputRegistrar::JackAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("JACK"), 10) {} +JackAudioInputRegistrar::JackAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("JACK"), 10) { +} AudioInput *JackAudioInputRegistrar::create() { return new JackAudioInput(); } -const QList<audioDevice> JackAudioInputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > JackAudioInputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; auto qlInputDevs = jas->qhInput.keys(); std::sort(qlInputDevs.begin(), qlInputDevs.end()); @@ -115,20 +127,22 @@ const QList<audioDevice> JackAudioInputRegistrar::getDeviceChoices() { return qlReturn; } -void JackAudioInputRegistrar::setDeviceChoice(const QVariant &, Settings &) {} +void JackAudioInputRegistrar::setDeviceChoice(const QVariant &, Settings &) { +} bool JackAudioInputRegistrar::canEcho(const QString &) const { return false; } -JackAudioOutputRegistrar::JackAudioOutputRegistrar() : AudioOutputRegistrar(QLatin1String("JACK"), 10) {} +JackAudioOutputRegistrar::JackAudioOutputRegistrar() : AudioOutputRegistrar(QLatin1String("JACK"), 10) { +} AudioOutput *JackAudioOutputRegistrar::create() { return new JackAudioOutput(); } -const QList<audioDevice> JackAudioOutputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > JackAudioOutputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; QStringList qlOutputDevs = jas->qhOutput.keys(); std::sort(qlOutputDevs.begin(), qlOutputDevs.end()); @@ -138,9 +152,7 @@ const QList<audioDevice> JackAudioOutputRegistrar::getDeviceChoices() { qlOutputDevs.prepend(g.s.qsJackAudioOutput); } - foreach(const QString &dev, qlOutputDevs) { - qlReturn << audioDevice(jas->qhOutput.value(dev), dev); - } + foreach (const QString &dev, qlOutputDevs) { qlReturn << audioDevice(jas->qhOutput.value(dev), dev); } return qlReturn; } @@ -177,11 +189,7 @@ void JackAudioInit::destroy() { // Instantiate JackAudioSystem, JackAudioInputRegistrar and JackAudioOutputRegistrar static JackAudioInit jai; -JackAudioSystem::JackAudioSystem() - : bAvailable(false) - , users(0) - , client(nullptr) -{ +JackAudioSystem::JackAudioSystem() : bAvailable(false), users(0), client(nullptr) { QStringList alternatives; #ifdef Q_OS_WIN alternatives << QLatin1String("libjack64.dll"); @@ -260,7 +268,8 @@ bool JackAudioSystem::initialize() { } jack_status_t status; - client = jack_client_open(g.s.qsJackClientName.toStdString().c_str(), g.s.bJackStartServer ? JackNullOption : JackNoStartServer, &status); + client = jack_client_open(g.s.qsJackClientName.toStdString().c_str(), + g.s.bJackStartServer ? JackNullOption : JackNoStartServer, &status); if (!client) { const auto errors = jackStatusToStringList(status); qWarning("JackAudioSystem: unable to open client due to %i errors:", errors.count()); @@ -283,7 +292,8 @@ bool JackAudioSystem::initialize() { ret = jack_set_sample_rate_callback(client, sampleRateCallback, nullptr); if (ret != 0) { - qWarning("JackAudioSystem: unable to set sample rate callback - jack_set_sample_rate_callback() returned %i", ret); + qWarning("JackAudioSystem: unable to set sample rate callback - jack_set_sample_rate_callback() returned %i", + ret); jack_client_close(client); client = nullptr; return false; @@ -291,7 +301,8 @@ bool JackAudioSystem::initialize() { ret = jack_set_buffer_size_callback(client, bufferSizeCallback, nullptr); if (ret != 0) { - qWarning("JackAudioSystem: unable to set buffer size callback - jack_set_buffer_size_callback() returned %i", ret); + qWarning("JackAudioSystem: unable to set buffer size callback - jack_set_buffer_size_callback() returned %i", + ret); jack_client_close(client); client = nullptr; return false; @@ -364,8 +375,9 @@ void JackAudioSystem::deactivate() { } const auto err = jack_deactivate(client); - if (err != 0) { - qWarning("JackAudioSystem: unable to remove client from the process graph - jack_deactivate() returned %i", err); + if (err != 0) { + qWarning("JackAudioSystem: unable to remove client from the process graph - jack_deactivate() returned %i", + err); return; } @@ -382,7 +394,7 @@ bool JackAudioSystem::isOk() { } uint8_t JackAudioSystem::outPorts() { - return static_cast<uint8_t>(qBound<unsigned>(1, g.s.qsJackAudioOutput.toUInt(), JACK_MAX_OUTPUT_PORTS)); + return static_cast< uint8_t >(qBound< unsigned >(1, g.s.qsJackAudioOutput.toUInt(), JACK_MAX_OUTPUT_PORTS)); } jack_nframes_t JackAudioSystem::sampleRate() { @@ -426,7 +438,7 @@ JackPorts JackAudioSystem::getPhysicalPorts(const uint8_t flags) { } auto port = jack_port_by_name(client, ports[i]); - if (!port) { + if (!port) { qWarning("JackAudioSystem: jack_port_by_name() returned an invalid port - skipping it"); continue; } @@ -467,7 +479,7 @@ bool JackAudioSystem::unregisterPort(jack_port_t *port) { } const auto ret = jack_port_unregister(client, port); - if (ret != 0) { + if (ret != 0) { qWarning("JackAudioSystem: unable to unregister port - jack_port_unregister() returned %i", ret); return false; } @@ -482,12 +494,13 @@ bool JackAudioSystem::connectPort(jack_port_t *sourcePort, jack_port_t *destinat return false; } - const auto sourcePortName = jack_port_name(sourcePort); + const auto sourcePortName = jack_port_name(sourcePort); const auto destinationPortName = jack_port_name(destinationPort); const auto ret = jack_connect(client, sourcePortName, destinationPortName); - if (ret != 0) { - qWarning("JackAudioSystem: unable to connect port '%s' to '%s' - jack_connect() returned %i", sourcePortName, destinationPortName, ret); + if (ret != 0) { + qWarning("JackAudioSystem: unable to connect port '%s' to '%s' - jack_connect() returned %i", sourcePortName, + destinationPortName, ret); return false; } @@ -502,7 +515,7 @@ bool JackAudioSystem::disconnectPort(jack_port_t *port) { } const auto ret = jack_port_disconnect(client, port); - if (ret != 0) { + if (ret != 0) { qWarning("JackAudioSystem: unable to disconnect port - jack_port_disconnect() returned %i", ret); return false; } @@ -541,7 +554,7 @@ size_t JackAudioSystem::ringbufferRead(jack_ringbuffer_t *buffer, const size_t s return 0; } - return jack_ringbuffer_read(buffer, static_cast<char *>(destination), size); + return jack_ringbuffer_read(buffer, static_cast< char * >(destination), size); } size_t JackAudioSystem::ringbufferReadSpace(const jack_ringbuffer_t *buffer) { @@ -557,7 +570,7 @@ size_t JackAudioSystem::ringbufferWrite(jack_ringbuffer_t *buffer, const size_t return 0; } - return jack_ringbuffer_write(buffer, static_cast<const char *>(source), size); + return jack_ringbuffer_write(buffer, static_cast< const char * >(source), size); } void JackAudioSystem::ringbufferGetWriteVector(const jack_ringbuffer_t *buffer, jack_ringbuffer_data_t *vector) { @@ -585,10 +598,10 @@ void JackAudioSystem::ringbufferWriteAdvance(jack_ringbuffer_t *buffer, const si } int JackAudioSystem::processCallback(jack_nframes_t frames, void *) { - auto const jai = dynamic_cast<JackAudioInput *>(g.ai.get()); - auto const jao = dynamic_cast<JackAudioOutput *>(g.ao.get()); + auto const jai = dynamic_cast< JackAudioInput * >(g.ai.get()); + auto const jao = dynamic_cast< JackAudioOutput * >(g.ao.get()); - const bool input = (jai && jai->isReady()); + const bool input = (jai && jai->isReady()); const bool output = (jao && jao->isReady()); if (input && !jai->process(frames)) { @@ -603,8 +616,8 @@ int JackAudioSystem::processCallback(jack_nframes_t frames, void *) { } int JackAudioSystem::sampleRateCallback(jack_nframes_t, void *) { - auto const jai = dynamic_cast<JackAudioInput *>(g.ai.get()); - auto const jao = dynamic_cast<JackAudioOutput *>(g.ao.get()); + auto const jai = dynamic_cast< JackAudioInput * >(g.ai.get()); + auto const jao = dynamic_cast< JackAudioOutput * >(g.ao.get()); if (jai) { jai->activate(); @@ -618,8 +631,8 @@ int JackAudioSystem::sampleRateCallback(jack_nframes_t, void *) { } int JackAudioSystem::bufferSizeCallback(jack_nframes_t frames, void *) { - auto const jai = dynamic_cast<JackAudioInput *>(g.ai.get()); - auto const jao = dynamic_cast<JackAudioOutput *>(g.ao.get()); + auto const jai = dynamic_cast< JackAudioInput * >(g.ai.get()); + auto const jao = dynamic_cast< JackAudioOutput * >(g.ao.get()); if (jai && !jai->allocBuffer(frames)) { return 1; @@ -635,13 +648,10 @@ int JackAudioSystem::bufferSizeCallback(jack_nframes_t frames, void *) { void JackAudioSystem::shutdownCallback(void *) { qWarning("JackAudioSystem: server shutdown"); jas->client = nullptr; - jas->users = 0; + jas->users = 0; } -JackAudioInput::JackAudioInput() - : port(nullptr) - , buffer(nullptr) -{ +JackAudioInput::JackAudioInput() : port(nullptr), buffer(nullptr) { bReady = activate(); } @@ -690,9 +700,9 @@ bool JackAudioInput::activate() { jas->initialize(); } - eMicFormat = SampleFloat; + eMicFormat = SampleFloat; iMicChannels = 1; - iMicFreq = jas->sampleRate(); + iMicFreq = jas->sampleRate(); initializeMixer(); @@ -743,7 +753,7 @@ bool JackAudioInput::unregisterPorts() { return false; } - if (!jas->unregisterPort(port)) { + if (!jas->unregisterPort(port)) { qWarning("JackAudioInput: unable to unregister port"); return false; } @@ -817,7 +827,7 @@ void JackAudioInput::run() { // We keep this as the frame size could change, but we are not going to resize this buffer. qmWait.lock(); - std::unique_ptr<uint8_t[]> sampleBuffer(new uint8_t[bufferSize]); + std::unique_ptr< uint8_t[] > sampleBuffer(new uint8_t[bufferSize]); qmWait.unlock(); do { @@ -833,9 +843,7 @@ void JackAudioInput::run() { } while (bReady); } -JackAudioOutput::JackAudioOutput() - : buffer(nullptr) -{ +JackAudioOutput::JackAudioOutput() : buffer(nullptr) { bReady = activate(); } @@ -882,8 +890,8 @@ bool JackAudioOutput::activate() { } eSampleFormat = SampleFloat; - iChannels = jas->outPorts(); - iMixerFreq = jas->sampleRate(); + iChannels = jas->outPorts(); + iMixerFreq = jas->sampleRate(); uint32_t channelsMask[32]; channelsMask[0] = SPEAKER_FRONT_LEFT; channelsMask[1] = SPEAKER_FRONT_RIGHT; @@ -944,7 +952,7 @@ bool JackAudioOutput::unregisterPorts() { continue; } - if (!jas->unregisterPort(ports[i])) { + if (!jas->unregisterPort(ports[i])) { qWarning("JackAudioOutput: unable to unregister port #%u", i); ret = false; } @@ -962,7 +970,7 @@ void JackAudioOutput::connectPorts() { QMutexLocker lock(&qmWait); const auto inputPorts = jas->getPhysicalPorts(JackPortIsInput); - uint8_t i = 0; + uint8_t i = 0; for (auto inputPort : inputPorts) { if (i == ports.size()) { @@ -1005,13 +1013,12 @@ bool JackAudioOutput::process(const jack_nframes_t frames) { qsSleep.release(1); for (decltype(iChannels) currentChannel = 0; currentChannel < iChannels; ++currentChannel) { - auto outputBuffer = jas->getPortBuffer(ports[currentChannel], frames); if (!outputBuffer) { return false; } - outputBuffers.replace(currentChannel, reinterpret_cast<jack_default_audio_sample_t *>(outputBuffer)); + outputBuffers.replace(currentChannel, reinterpret_cast< jack_default_audio_sample_t * >(outputBuffer)); } const auto avail = jas->ringbufferReadSpace(buffer); @@ -1026,22 +1033,24 @@ bool JackAudioOutput::process(const jack_nframes_t frames) { const size_t needed = frames * iSampleSize; if (iChannels == 1) { - jas->ringbufferRead(buffer, avail, reinterpret_cast<char *>(outputBuffers[0])); + jas->ringbufferRead(buffer, avail, reinterpret_cast< char * >(outputBuffers[0])); if (avail < needed) { - memset(reinterpret_cast<char *>(&(outputBuffers[avail])), 0, needed - avail); + memset(reinterpret_cast< char * >(&(outputBuffers[avail])), 0, needed - avail); } return true; } auto samples = qMin(jas->ringbufferReadSpace(buffer), needed) / sizeof(jack_default_audio_sample_t); - for (auto currentSample = decltype(samples){0}; currentSample < samples; ++currentSample) { - jas->ringbufferRead(buffer, sizeof(jack_default_audio_sample_t), reinterpret_cast<char *>(&outputBuffers[currentSample % iChannels][currentSample / iChannels])); + for (auto currentSample = decltype(samples){ 0 }; currentSample < samples; ++currentSample) { + jas->ringbufferRead( + buffer, sizeof(jack_default_audio_sample_t), + reinterpret_cast< char * >(&outputBuffers[currentSample % iChannels][currentSample / iChannels])); } if ((samples / iChannels) < frames) { for (decltype(iChannels) currentChannel = 0; currentChannel < iChannels; ++currentChannel) { - memset(&outputBuffers[currentChannel][avail/samples], 0, (needed - avail) / iChannels); + memset(&outputBuffers[currentChannel][avail / samples], 0, (needed - avail) / iChannels); } } @@ -1058,7 +1067,7 @@ void JackAudioOutput::run() { connectPorts(); } - std::unique_ptr<uint8_t[]> spareSample(new uint8_t[iSampleSize]); + std::unique_ptr< uint8_t[] > spareSample(new uint8_t[iSampleSize]); jack_ringbuffer_data_t _writeVector[2]; jack_ringbuffer_data_t *writeVector = _writeVector; @@ -1075,9 +1084,9 @@ void JackAudioOutput::run() { jas->ringbufferGetWriteVector(buffer, writeVector); - auto bOk = true; + auto bOk = true; size_t writtenFrames = 0; - auto wanted = qMin(writeVector->len / iSampleSize, static_cast<size_t>(iFrameSize)); + auto wanted = qMin(writeVector->len / iSampleSize, static_cast< size_t >(iFrameSize)); if (wanted > 0) { bOk = mix(writeVector->buf, wanted); writtenFrames += bOk ? wanted : 0; @@ -1113,7 +1122,7 @@ void JackAudioOutput::run() { bOk = mix(writeVector->buf, iFrameSize - wanted); writtenFrames += bOk ? (iFrameSize - wanted) : 0; -next: + next: jas->ringbufferWriteAdvance(buffer, writtenFrames * iSampleSize); qmWait.unlock(); qsSleep.acquire(1); diff --git a/src/mumble/JackAudio.h b/src/mumble/JackAudio.h index 108c493c9..56a0b03fa 100644 --- a/src/mumble/JackAudio.h +++ b/src/mumble/JackAudio.h @@ -10,9 +10,9 @@ #include "AudioOutput.h" #include <QtCore/QLibrary> +#include <QtCore/QSemaphore> #include <QtCore/QVector> #include <QtCore/QWaitCondition> -#include <QtCore/QSemaphore> #include <jack/types.h> @@ -27,154 +27,156 @@ struct jack_ringbuffer_data_t { size_t len; }; -typedef QVector<jack_port_t *> JackPorts; -typedef QVector<jack_default_audio_sample_t *> JackBuffers; +typedef QVector< jack_port_t * > JackPorts; +typedef QVector< jack_default_audio_sample_t * > JackBuffers; class JackAudioInit; class JackAudioSystem : public QObject { - friend JackAudioInit; - - private: - Q_OBJECT - Q_DISABLE_COPY(JackAudioSystem) - - protected: - bool bAvailable; - uint8_t users; - QMutex qmWait; - QLibrary qlJack; - QWaitCondition qwcWait; - jack_client_t *client; - - static int processCallback(jack_nframes_t frames, void *); - static int sampleRateCallback(jack_nframes_t, void *); - static int bufferSizeCallback(jack_nframes_t frames, void *); - static void shutdownCallback(void *); - - const char *(*jack_get_version_string)(); - const char **(*jack_get_ports)(jack_client_t *client, const char *port_name_pattern, const char *type_name_pattern, unsigned long flags); - char *(*jack_get_client_name)(jack_client_t *client); - char *(*jack_port_name)(jack_port_t *port); - int (*jack_client_close)(jack_client_t *client); - int (*jack_activate)(jack_client_t *client); - int (*jack_deactivate)(jack_client_t *client); - int (*jack_set_process_callback)(jack_client_t *client, JackProcessCallback process_callback, void *arg); - int (*jack_set_sample_rate_callback)(jack_client_t *client, JackSampleRateCallback process_callback, void *arg); - int (*jack_set_buffer_size_callback)(jack_client_t *client, JackBufferSizeCallback process_callback, void *arg); - int (*jack_on_shutdown)(jack_client_t *client, JackShutdownCallback process_callback, void *arg); - int (*jack_connect)(jack_client_t *client, const char *source_port, const char *destination_port); - int (*jack_port_disconnect)(jack_client_t *client, jack_port_t *port); - int (*jack_port_unregister)(jack_client_t *client, jack_port_t *port); - int (*jack_port_flags)(const jack_port_t *port); - void *(*jack_port_get_buffer)(jack_port_t *port, jack_nframes_t frames); - void (*jack_free)(void *ptr); - jack_client_t *(*jack_client_open)(const char *client_name, jack_options_t options, jack_status_t *status, ...); - jack_nframes_t (*jack_get_sample_rate)(jack_client_t *client); - jack_nframes_t (*jack_get_buffer_size)(jack_client_t *client); - jack_port_t *(*jack_port_by_name)(jack_client_t *client, const char *port_name); - jack_port_t *(*jack_port_register)(jack_client_t *client, const char *port_name, const char *port_type, unsigned long flags, unsigned long buffer_size); - - jack_ringbuffer_t *(*jack_ringbuffer_create)(size_t sz); - void (*jack_ringbuffer_free)(jack_ringbuffer_t *rb); - int (*jack_ringbuffer_mlock)(jack_ringbuffer_t *rb); - size_t (*jack_ringbuffer_read)(jack_ringbuffer_t *rb, char *dest, size_t cnt); - size_t (*jack_ringbuffer_read_space)(const jack_ringbuffer_t *rb); - size_t (*jack_ringbuffer_write)(jack_ringbuffer_t *rb, const char *src, size_t cnt); - void (*jack_ringbuffer_get_write_vector)(const jack_ringbuffer_t *rb, jack_ringbuffer_data_t *vec); - size_t (*jack_ringbuffer_write_space)(const jack_ringbuffer_t *rb); - void (*jack_ringbuffer_write_advance)(jack_ringbuffer_t *rb, size_t cnt); - - public: - QHash<QString, QString> qhInput; - QHash<QString, QString> qhOutput; - - bool isOk(); - uint8_t outPorts(); - jack_nframes_t sampleRate(); - jack_nframes_t bufferSize(); - JackPorts getPhysicalPorts(const uint8_t flags); - void *getPortBuffer(jack_port_t *port, const jack_nframes_t frames); - jack_port_t *registerPort(const char *name, const uint8_t flags); - bool unregisterPort(jack_port_t *port); - bool connectPort(jack_port_t *sourcePort, jack_port_t *destinationPort); - bool disconnectPort(jack_port_t *port); - - jack_ringbuffer_t *ringbufferCreate(const size_t size); - void ringbufferFree(jack_ringbuffer_t *buffer); - int ringbufferMlock(jack_ringbuffer_t *buffer); - size_t ringbufferRead(jack_ringbuffer_t *buffer, const size_t size, void *destination); - size_t ringbufferReadSpace(const jack_ringbuffer_t *buffer); - size_t ringbufferWrite(jack_ringbuffer_t *buffer, const size_t size, const void *source); - void ringbufferGetWriteVector(const jack_ringbuffer_t *buffer, jack_ringbuffer_data_t *vector); - size_t ringbufferWriteSpace(const jack_ringbuffer_t *buffer); - void ringbufferWriteAdvance(jack_ringbuffer_t *buffer, const size_t size); - - bool initialize(); - void deinitialize(); - bool activate(); - void deactivate(); - - JackAudioSystem(); - ~JackAudioSystem(); + friend JackAudioInit; + +private: + Q_OBJECT + Q_DISABLE_COPY(JackAudioSystem) + +protected: + bool bAvailable; + uint8_t users; + QMutex qmWait; + QLibrary qlJack; + QWaitCondition qwcWait; + jack_client_t *client; + + static int processCallback(jack_nframes_t frames, void *); + static int sampleRateCallback(jack_nframes_t, void *); + static int bufferSizeCallback(jack_nframes_t frames, void *); + static void shutdownCallback(void *); + + const char *(*jack_get_version_string)(); + const char **(*jack_get_ports)(jack_client_t *client, const char *port_name_pattern, const char *type_name_pattern, + unsigned long flags); + char *(*jack_get_client_name)(jack_client_t *client); + char *(*jack_port_name)(jack_port_t *port); + int (*jack_client_close)(jack_client_t *client); + int (*jack_activate)(jack_client_t *client); + int (*jack_deactivate)(jack_client_t *client); + int (*jack_set_process_callback)(jack_client_t *client, JackProcessCallback process_callback, void *arg); + int (*jack_set_sample_rate_callback)(jack_client_t *client, JackSampleRateCallback process_callback, void *arg); + int (*jack_set_buffer_size_callback)(jack_client_t *client, JackBufferSizeCallback process_callback, void *arg); + int (*jack_on_shutdown)(jack_client_t *client, JackShutdownCallback process_callback, void *arg); + int (*jack_connect)(jack_client_t *client, const char *source_port, const char *destination_port); + int (*jack_port_disconnect)(jack_client_t *client, jack_port_t *port); + int (*jack_port_unregister)(jack_client_t *client, jack_port_t *port); + int (*jack_port_flags)(const jack_port_t *port); + void *(*jack_port_get_buffer)(jack_port_t *port, jack_nframes_t frames); + void (*jack_free)(void *ptr); + jack_client_t *(*jack_client_open)(const char *client_name, jack_options_t options, jack_status_t *status, ...); + jack_nframes_t (*jack_get_sample_rate)(jack_client_t *client); + jack_nframes_t (*jack_get_buffer_size)(jack_client_t *client); + jack_port_t *(*jack_port_by_name)(jack_client_t *client, const char *port_name); + jack_port_t *(*jack_port_register)(jack_client_t *client, const char *port_name, const char *port_type, + unsigned long flags, unsigned long buffer_size); + + jack_ringbuffer_t *(*jack_ringbuffer_create)(size_t sz); + void (*jack_ringbuffer_free)(jack_ringbuffer_t *rb); + int (*jack_ringbuffer_mlock)(jack_ringbuffer_t *rb); + size_t (*jack_ringbuffer_read)(jack_ringbuffer_t *rb, char *dest, size_t cnt); + size_t (*jack_ringbuffer_read_space)(const jack_ringbuffer_t *rb); + size_t (*jack_ringbuffer_write)(jack_ringbuffer_t *rb, const char *src, size_t cnt); + void (*jack_ringbuffer_get_write_vector)(const jack_ringbuffer_t *rb, jack_ringbuffer_data_t *vec); + size_t (*jack_ringbuffer_write_space)(const jack_ringbuffer_t *rb); + void (*jack_ringbuffer_write_advance)(jack_ringbuffer_t *rb, size_t cnt); + +public: + QHash< QString, QString > qhInput; + QHash< QString, QString > qhOutput; + + bool isOk(); + uint8_t outPorts(); + jack_nframes_t sampleRate(); + jack_nframes_t bufferSize(); + JackPorts getPhysicalPorts(const uint8_t flags); + void *getPortBuffer(jack_port_t *port, const jack_nframes_t frames); + jack_port_t *registerPort(const char *name, const uint8_t flags); + bool unregisterPort(jack_port_t *port); + bool connectPort(jack_port_t *sourcePort, jack_port_t *destinationPort); + bool disconnectPort(jack_port_t *port); + + jack_ringbuffer_t *ringbufferCreate(const size_t size); + void ringbufferFree(jack_ringbuffer_t *buffer); + int ringbufferMlock(jack_ringbuffer_t *buffer); + size_t ringbufferRead(jack_ringbuffer_t *buffer, const size_t size, void *destination); + size_t ringbufferReadSpace(const jack_ringbuffer_t *buffer); + size_t ringbufferWrite(jack_ringbuffer_t *buffer, const size_t size, const void *source); + void ringbufferGetWriteVector(const jack_ringbuffer_t *buffer, jack_ringbuffer_data_t *vector); + size_t ringbufferWriteSpace(const jack_ringbuffer_t *buffer); + void ringbufferWriteAdvance(jack_ringbuffer_t *buffer, const size_t size); + + bool initialize(); + void deinitialize(); + bool activate(); + void deactivate(); + + JackAudioSystem(); + ~JackAudioSystem(); }; class JackAudioInput : public AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(JackAudioInput) - - protected: - volatile bool bReady; - QMutex qmWait; - QSemaphore qsSleep; - jack_port_t *port; - jack_ringbuffer_t *buffer; - size_t bufferSize; - - public: - bool isReady(); - bool process(const jack_nframes_t frames); - bool allocBuffer(const jack_nframes_t frames); - bool activate(); - void deactivate(); - bool registerPorts(); - bool unregisterPorts(); - void connectPorts(); - bool disconnectPorts(); - - void run() Q_DECL_OVERRIDE; - JackAudioInput(); - ~JackAudioInput() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(JackAudioInput) + +protected: + volatile bool bReady; + QMutex qmWait; + QSemaphore qsSleep; + jack_port_t *port; + jack_ringbuffer_t *buffer; + size_t bufferSize; + +public: + bool isReady(); + bool process(const jack_nframes_t frames); + bool allocBuffer(const jack_nframes_t frames); + bool activate(); + void deactivate(); + bool registerPorts(); + bool unregisterPorts(); + void connectPorts(); + bool disconnectPorts(); + + void run() Q_DECL_OVERRIDE; + JackAudioInput(); + ~JackAudioInput() Q_DECL_OVERRIDE; }; class JackAudioOutput : public AudioOutput { - private: - Q_OBJECT - Q_DISABLE_COPY(JackAudioOutput) - - protected: - volatile bool bReady; - QMutex qmWait; - QSemaphore qsSleep; - JackPorts ports; - JackBuffers outputBuffers; - jack_ringbuffer_t *buffer; - - public: - bool isReady(); - bool process(const jack_nframes_t frames); - bool allocBuffer(const jack_nframes_t frames); - bool activate(); - void deactivate(); - bool registerPorts(); - bool unregisterPorts(); - void connectPorts(); - bool disconnectPorts(); - - void run() Q_DECL_OVERRIDE; - JackAudioOutput(); - ~JackAudioOutput() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(JackAudioOutput) + +protected: + volatile bool bReady; + QMutex qmWait; + QSemaphore qsSleep; + JackPorts ports; + JackBuffers outputBuffers; + jack_ringbuffer_t *buffer; + +public: + bool isReady(); + bool process(const jack_nframes_t frames); + bool allocBuffer(const jack_nframes_t frames); + bool activate(); + void deactivate(); + bool registerPorts(); + bool unregisterPorts(); + void connectPorts(); + bool disconnectPorts(); + + void run() Q_DECL_OVERRIDE; + JackAudioOutput(); + ~JackAudioOutput() Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/LCD.cpp b/src/mumble/LCD.cpp index 535ad8032..7356bf1e9 100644 --- a/src/mumble/LCD.cpp +++ b/src/mumble/LCD.cpp @@ -5,24 +5,25 @@ #include "LCD.h" -#include "ClientUser.h" #include "Channel.h" +#include "ClientUser.h" #include "Message.h" #include "ServerHandler.h" #include "Utils.h" #include <QtGui/QPainter> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const QString LCDConfig::name = QLatin1String("LCDConfig"); -QList<LCDEngineNew> *LCDEngineRegistrar::qlInitializers; +QList< LCDEngineNew > *LCDEngineRegistrar::qlInitializers; LCDEngineRegistrar::LCDEngineRegistrar(LCDEngineNew cons) { - if (! qlInitializers) - qlInitializers = new QList<LCDEngineNew>(); + if (!qlInitializers) + qlInitializers = new QList< LCDEngineNew >(); n = cons; qlInitializers->append(n); } @@ -40,24 +41,23 @@ static ConfigWidget *LCDConfigDialogNew(Settings &st) { } class LCDDeviceManager : public DeferInit { - protected: - ConfigRegistrar *crLCD; - public: - QList<LCDEngine *> qlEngines; - QList<LCDDevice *> qlDevices; - void initialize(); - void destroy(); +protected: + ConfigRegistrar *crLCD; + +public: + QList< LCDEngine * > qlEngines; + QList< LCDDevice * > qlDevices; + void initialize(); + void destroy(); }; void LCDDeviceManager::initialize() { if (LCDEngineRegistrar::qlInitializers) { - foreach(LCDEngineNew engine, *LCDEngineRegistrar::qlInitializers) { + foreach (LCDEngineNew engine, *LCDEngineRegistrar::qlInitializers) { LCDEngine *e = engine(); qlEngines.append(e); - foreach(LCDDevice *d, e->devices()) { - qlDevices << d; - } + foreach (LCDDevice *d, e->devices()) { qlDevices << d; } } } if (qlDevices.count() > 0) { @@ -69,9 +69,7 @@ void LCDDeviceManager::initialize() { void LCDDeviceManager::destroy() { qlDevices.clear(); - foreach(LCDEngine *e, qlEngines) { - delete e; - } + foreach (LCDEngine *e, qlEngines) { delete e; } delete crLCD; } @@ -85,17 +83,17 @@ LCDConfig::LCDConfig(Settings &st) : ConfigWidget(st) { qtwDevices->setAccessibleName(tr("Devices")); qsMinColWidth->setAccessibleName(tr("Minimum column width")); qsSplitterWidth->setAccessibleName(tr("Splitter width")); - + QTreeWidgetItem *qtwi; - foreach(LCDDevice *d, devmgr.qlDevices) { + foreach (LCDDevice *d, devmgr.qlDevices) { qtwi = new QTreeWidgetItem(qtwDevices); - qtwi->setFlags(Qt::ItemIsEnabled |Qt::ItemIsUserCheckable); + qtwi->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); qtwi->setText(0, d->name()); qtwi->setToolTip(0, d->name().toHtmlEscaped()); - QSize lcdsize = d->size(); + QSize lcdsize = d->size(); QString qsSize = QString::fromLatin1("%1x%2").arg(lcdsize.width()).arg(lcdsize.height()); qtwi->setText(1, qsSize); qtwi->setToolTip(1, qsSize); @@ -118,10 +116,10 @@ QIcon LCDConfig::icon() const { } void LCDConfig::load(const Settings &r) { - QList<QTreeWidgetItem *> qlItems = qtwDevices->findItems(QString(), Qt::MatchContains); - foreach(QTreeWidgetItem *qtwi, qlItems) { + QList< QTreeWidgetItem * > qlItems = qtwDevices->findItems(QString(), Qt::MatchContains); + foreach (QTreeWidgetItem *qtwi, qlItems) { QString qsName = qtwi->text(0); - bool enabled = r.qmLCDDevices.contains(qsName) ? r.qmLCDDevices.value(qsName) : true; + bool enabled = r.qmLCDDevices.contains(qsName) ? r.qmLCDDevices.value(qsName) : true; qtwi->setCheckState(2, enabled ? Qt::Checked : Qt::Unchecked); } @@ -130,19 +128,19 @@ void LCDConfig::load(const Settings &r) { } void LCDConfig::save() const { - QList<QTreeWidgetItem *> qlItems = qtwDevices->findItems(QString(), Qt::MatchContains); + QList< QTreeWidgetItem * > qlItems = qtwDevices->findItems(QString(), Qt::MatchContains); - foreach(QTreeWidgetItem *qtwi, qlItems) { + foreach (QTreeWidgetItem *qtwi, qlItems) { QString qsName = qtwi->text(0); s.qmLCDDevices.insert(qsName, qtwi->checkState(2) == Qt::Checked); } - s.iLCDUserViewMinColWidth = qsMinColWidth->value(); + s.iLCDUserViewMinColWidth = qsMinColWidth->value(); s.iLCDUserViewSplitterWidth = qsSplitterWidth->value(); } void LCDConfig::accept() const { - foreach(LCDDevice *d, devmgr.qlDevices) { + foreach (LCDDevice *d, devmgr.qlDevices) { bool enabled = s.qmLCDDevices.value(d->name()); d->setEnabled(enabled); } @@ -160,7 +158,6 @@ void LCDConfig::on_qsSplitterWidth_valueChanged(int v) { /* --- */ LCD::LCD() : QObject() { - #ifdef Q_OS_MAC qfNormal.setStyleStrategy(QFont::NoAntialias); qfNormal.setKerning(false); @@ -191,11 +188,11 @@ LCD::LCD() : QObject() { qtTimer = new QTimer(this); connect(qtTimer, SIGNAL(timeout()), this, SLOT(tick())); - foreach(LCDDevice *d, devmgr.qlDevices) { + foreach (LCDDevice *d, devmgr.qlDevices) { bool enabled = g.s.qmLCDDevices.contains(d->name()) ? g.s.qmLCDDevices.value(d->name()) : true; d->setEnabled(enabled); } - qiLogo = QIcon(QLatin1String("skin:mumble.svg")).pixmap(48,48).toImage().convertToFormat(QImage::Format_MonoLSB); + qiLogo = QIcon(QLatin1String("skin:mumble.svg")).pixmap(48, 48).toImage().convertToFormat(QImage::Format_MonoLSB); #if QT_VERSION >= 0x050600 && QT_VERSION <= 0x050601 // Don't invert the logo image when using Qt 5.6. @@ -208,15 +205,15 @@ LCD::LCD() : QObject() { } void LCD::tick() { - iFrameIndex ++; + iFrameIndex++; updateUserView(); } void LCD::initBuffers() { - foreach(LCDDevice *d, devmgr.qlDevices) { + foreach (LCDDevice *d, devmgr.qlDevices) { QSize size = d->size(); - if (! qhImageBuffers.contains(size)) { - size_t buflen = (size.width() * size.height()) / 8; + if (!qhImageBuffers.contains(size)) { + size_t buflen = (size.width() * size.height()) / 8; qhImageBuffers[size] = new unsigned char[buflen]; qhImages[size] = new QImage(qhImageBuffers[size], size.width(), size.height(), QImage::Format_MonoLSB); } @@ -224,12 +221,12 @@ void LCD::initBuffers() { } void LCD::destroyBuffers() { - foreach(QImage *img, qhImages) + foreach (QImage *img, qhImages) delete img; qhImages.clear(); - foreach(unsigned char *buf, qhImageBuffers) - delete [] buf; + foreach (unsigned char *buf, qhImageBuffers) + delete[] buf; qhImageBuffers.clear(); } @@ -237,7 +234,7 @@ struct ListEntry { QString qsString; bool bBold; bool bItalic; - ListEntry(const QString &qs, bool bB, bool bI) : qsString(qs), bBold(bB), bItalic(bI) {}; + ListEntry(const QString &qs, bool bB, bool bI) : qsString(qs), bBold(bB), bItalic(bI){}; }; static bool entriesSort(const ListEntry &a, const ListEntry &b) { @@ -249,11 +246,11 @@ void LCD::updateUserView() { return; QStringList qslTalking; - User *me = g.uiSession ? ClientUser::get(g.uiSession) : nullptr; + User *me = g.uiSession ? ClientUser::get(g.uiSession) : nullptr; Channel *home = me ? me->cChannel : nullptr; - bool alert = false; + bool alert = false; - foreach(const QSize &size, qhImages.keys()) { + foreach (const QSize &size, qhImages.keys()) { QImage *img = qhImages.value(size); QPainter painter(img); painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing, false); @@ -270,7 +267,7 @@ void LCD::updateUserView() { img->fill(Qt::color0); - if (! me) { + if (!me) { qmNew.clear(); qmOld.clear(); qmSpeaking.clear(); @@ -280,15 +277,15 @@ void LCD::updateUserView() { continue; } - foreach(User *p, me->cChannel->qlUsers) { - if (! qmNew.contains(p->uiSession)) { + foreach (User *p, me->cChannel->qlUsers) { + if (!qmNew.contains(p->uiSession)) { qmNew.insert(p->uiSession, Timer()); qmNameCache.insert(p->uiSession, p->qsName); qmOld.remove(p->uiSession); } } - foreach(unsigned int session, qmNew.keys()) { + foreach (unsigned int session, qmNew.keys()) { User *p = ClientUser::get(session); if (!p || (p->cChannel != me->cChannel)) { qmNew.remove(session); @@ -296,9 +293,9 @@ void LCD::updateUserView() { } } - QMap<unsigned int, Timer> old; + QMap< unsigned int, Timer > old; - foreach(unsigned int session, qmOld.keys()) { + foreach (unsigned int session, qmOld.keys()) { Timer t = qmOld.value(session); if (t.elapsed() > 3000000) { qmNameCache.remove(session); @@ -308,17 +305,18 @@ void LCD::updateUserView() { } qmOld = old; - QList<struct ListEntry> entries; - entries << ListEntry(QString::fromLatin1("[%1:%2]").arg(me->cChannel->qsName).arg(me->cChannel->qlUsers.count()), false, false); + QList< struct ListEntry > entries; + entries << ListEntry( + QString::fromLatin1("[%1:%2]").arg(me->cChannel->qsName).arg(me->cChannel->qlUsers.count()), false, false); bool hasnew = false; - QMap<unsigned int, Timer> speaking; + QMap< unsigned int, Timer > speaking; - foreach(Channel *c, home->allLinks()) { - foreach(User *p, c->qlUsers) { - ClientUser *u = static_cast<ClientUser *>(p); - bool bTalk = (u->tsState != Settings::Passive); + foreach (Channel *c, home->allLinks()) { + foreach (User *p, c->qlUsers) { + ClientUser *u = static_cast< ClientUser * >(p); + bool bTalk = (u->tsState != Settings::Passive); if (bTalk) { speaking.insert(p->uiSession, Timer()); } else if (qmSpeaking.contains(p->uiSession)) { @@ -343,7 +341,7 @@ void LCD::updateUserView() { } qmSpeaking = speaking; - foreach(unsigned int session, qmOld.keys()) { + foreach (unsigned int session, qmOld.keys()) { entries << ListEntry(QLatin1String("-") + qmNameCache.value(session), false, false); } @@ -355,17 +353,17 @@ void LCD::updateUserView() { std::sort(++entries.begin(), entries.end(), entriesSort); - const int iWidth = size.width(); - const int iHeight = size.height(); + const int iWidth = size.width(); + const int iHeight = size.height(); const int iUsersPerColumn = iHeight / iFontHeight; - const int iSplitterWidth = g.s.iLCDUserViewSplitterWidth; - const int iUserColumns = (entries.count() + iUsersPerColumn - 1) / iUsersPerColumn; + const int iSplitterWidth = g.s.iLCDUserViewSplitterWidth; + const int iUserColumns = (entries.count() + iUsersPerColumn - 1) / iUsersPerColumn; - int iColumns = iUserColumns; + int iColumns = iUserColumns; int iColumnWidth = 1; while (iColumns >= 1) { - iColumnWidth = (iWidth - (iColumns-1)*iSplitterWidth) / iColumns; + iColumnWidth = (iWidth - (iColumns - 1) * iSplitterWidth) / iColumns; if (iColumnWidth >= g.s.iLCDUserViewMinColWidth) break; --iColumns; @@ -374,7 +372,7 @@ void LCD::updateUserView() { int row = 0, col = 0; - foreach(const ListEntry &le, entries) { + foreach (const ListEntry &le, entries) { if (row >= iUsersPerColumn) { row = 0; ++col; @@ -382,7 +380,7 @@ void LCD::updateUserView() { if (col > iColumns) break; - if (! le.qsString.isEmpty()) { + if (!le.qsString.isEmpty()) { if (le.bBold && le.bItalic) painter.setFont(qfItalicBold); else if (le.bBold) @@ -391,16 +389,17 @@ void LCD::updateUserView() { painter.setFont(qfItalic); else painter.setFont(qfNormal); - painter.drawText(QRect(col * (iColumnWidth + iSplitterWidth), - row * iFontHeight, iColumnWidth, iFontHeight+2), Qt::AlignLeft, le.qsString); + painter.drawText( + QRect(col * (iColumnWidth + iSplitterWidth), row * iFontHeight, iColumnWidth, iFontHeight + 2), + Qt::AlignLeft, le.qsString); } ++row; } } - foreach(LCDDevice *d, devmgr.qlDevices) { + foreach (LCDDevice *d, devmgr.qlDevices) { QImage *img = qhImages[d->size()]; - if (! img) + if (!img) continue; d->blitImage(img, alert); } @@ -411,7 +410,7 @@ LCD::~LCD() { } bool LCD::hasDevices() { - return (! devmgr.qlDevices.isEmpty()); + return (!devmgr.qlDevices.isEmpty()); } /* --- */ @@ -420,7 +419,7 @@ LCDEngine::LCDEngine() : QObject() { } LCDEngine::~LCDEngine() { - foreach(LCDDevice *lcd, qlDevices) + foreach (LCDDevice *lcd, qlDevices) delete lcd; } diff --git a/src/mumble/LCD.h b/src/mumble/LCD.h index a8dcc86af..d94aa90bf 100644 --- a/src/mumble/LCD.h +++ b/src/mumble/LCD.h @@ -15,84 +15,87 @@ class User; class LCDDevice; class LCDConfig : public ConfigWidget, public Ui::LCDConfig { - private: - Q_OBJECT - Q_DISABLE_COPY(LCDConfig) - public: - /// The unique name of this ConfigWidget - static const QString name; - LCDConfig(Settings &st); - QString title() const Q_DECL_OVERRIDE; - const QString &getName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; - public slots: - void on_qsMinColWidth_valueChanged(int v); - void on_qsSplitterWidth_valueChanged(int v); - void accept() const Q_DECL_OVERRIDE; - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(LCDConfig) +public: + /// The unique name of this ConfigWidget + static const QString name; + LCDConfig(Settings &st); + QString title() const Q_DECL_OVERRIDE; + const QString &getName() const Q_DECL_OVERRIDE; + QIcon icon() const Q_DECL_OVERRIDE; +public slots: + void on_qsMinColWidth_valueChanged(int v); + void on_qsSplitterWidth_valueChanged(int v); + void accept() const Q_DECL_OVERRIDE; + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; }; class LCDEngine : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(LCDEngine) - protected: - QList<LCDDevice *> qlDevices; - public: - LCDEngine(); - virtual ~LCDEngine() Q_DECL_OVERRIDE; - virtual QList<LCDDevice *> devices() const = 0; +private: + Q_OBJECT + Q_DISABLE_COPY(LCDEngine) +protected: + QList< LCDDevice * > qlDevices; + +public: + LCDEngine(); + virtual ~LCDEngine() Q_DECL_OVERRIDE; + virtual QList< LCDDevice * > devices() const = 0; }; class LCDDevice { - public: - LCDDevice(); - virtual ~LCDDevice(); - virtual bool enabled() = 0; - virtual void setEnabled(bool e) = 0; - virtual void blitImage(QImage *img, bool alert = false) = 0; - virtual QString name() const = 0; - virtual QSize size() const = 0; +public: + LCDDevice(); + virtual ~LCDDevice(); + virtual bool enabled() = 0; + virtual void setEnabled(bool e) = 0; + virtual void blitImage(QImage *img, bool alert = false) = 0; + virtual QString name() const = 0; + virtual QSize size() const = 0; }; typedef LCDEngine *(*LCDEngineNew)(void); class LCDEngineRegistrar Q_DECL_FINAL { - protected: - LCDEngineNew n; - public: - static QList<LCDEngineNew> *qlInitializers; - LCDEngineRegistrar(LCDEngineNew n); - ~LCDEngineRegistrar(); +protected: + LCDEngineNew n; + +public: + static QList< LCDEngineNew > *qlInitializers; + LCDEngineRegistrar(LCDEngineNew n); + ~LCDEngineRegistrar(); }; class LCD : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(LCD) - protected: - QFont qfNormal, qfBold, qfItalic, qfItalicBold; - QMap<unsigned int, Timer> qmSpeaking; - QMap<unsigned int, Timer> qmNew; - QMap<unsigned int, Timer> qmOld; - QMap<unsigned int, QString> qmNameCache; - - int iFontHeight; - int iFrameIndex; - QHash<QSize, unsigned char *> qhImageBuffers; - QHash<QSize, QImage *> qhImages; - void initBuffers(); - void destroyBuffers(); - QImage qiLogo; - QTimer *qtTimer; - public slots: - void tick(); - public: - LCD(); - ~LCD() Q_DECL_OVERRIDE; - void updateUserView(); - bool hasDevices(); +private: + Q_OBJECT + Q_DISABLE_COPY(LCD) +protected: + QFont qfNormal, qfBold, qfItalic, qfItalicBold; + QMap< unsigned int, Timer > qmSpeaking; + QMap< unsigned int, Timer > qmNew; + QMap< unsigned int, Timer > qmOld; + QMap< unsigned int, QString > qmNameCache; + + int iFontHeight; + int iFrameIndex; + QHash< QSize, unsigned char * > qhImageBuffers; + QHash< QSize, QImage * > qhImages; + void initBuffers(); + void destroyBuffers(); + QImage qiLogo; + QTimer *qtTimer; +public slots: + void tick(); + +public: + LCD(); + ~LCD() Q_DECL_OVERRIDE; + void updateUserView(); + bool hasDevices(); }; uint qHash(const QSize &size); diff --git a/src/mumble/ListenerLocalVolumeDialog.cpp b/src/mumble/ListenerLocalVolumeDialog.cpp index fcf2b4f03..41a829feb 100644 --- a/src/mumble/ListenerLocalVolumeDialog.cpp +++ b/src/mumble/ListenerLocalVolumeDialog.cpp @@ -4,21 +4,20 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "ListenerLocalVolumeDialog.h" -#include "ClientUser.h" #include "Channel.h" #include "ChannelListener.h" +#include "ClientUser.h" #include <QtWidgets/QPushButton> #include <cmath> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" ListenerLocalVolumeDialog::ListenerLocalVolumeDialog(ClientUser *user, Channel *channel, QWidget *parent) - : QDialog(parent), - m_user(user), - m_channel(channel) { + : QDialog(parent), m_user(user), m_channel(channel) { setupUi(this); m_initialAdjustemt = ChannelListener::getListenerLocalVolumeAdjustment(m_channel); @@ -26,7 +25,7 @@ ListenerLocalVolumeDialog::ListenerLocalVolumeDialog(ClientUser *user, Channel * // Decibel formula: +6db = *2 // Calculate the db-shift from the set volume-faactor float fdbShift = log2f(m_initialAdjustemt) * 6; - qsUserLocalVolume->setValue(static_cast<int>(roundf(fdbShift))); + qsUserLocalVolume->setValue(static_cast< int >(roundf(fdbShift))); setWindowTitle(tr("Adjusting local volume for listening to %1").arg(channel->qsName)); } @@ -41,7 +40,7 @@ void ListenerLocalVolumeDialog::on_qsbUserLocalVolume_valueChanged(int value) { // Decibel formula: +6db = *2 // Calculate the volume-factor for the set db-shift ChannelListener::setListenerLocalVolumeAdjustment(m_channel, - static_cast<float>(pow(2.0, qsUserLocalVolume->value() / 6.0))); + static_cast< float >(pow(2.0, qsUserLocalVolume->value() / 6.0))); } void ListenerLocalVolumeDialog::on_qbbUserLocalVolume_clicked(QAbstractButton *button) { diff --git a/src/mumble/ListenerLocalVolumeDialog.h b/src/mumble/ListenerLocalVolumeDialog.h index 14c858c28..40bb72965 100644 --- a/src/mumble/ListenerLocalVolumeDialog.h +++ b/src/mumble/ListenerLocalVolumeDialog.h @@ -17,26 +17,26 @@ class Channel; /// It actually uses the same UI frontend as UserLocalVolumeDialog as it only needs backend /// changes. class ListenerLocalVolumeDialog : public QDialog, private Ui::UserLocalVolumeDialog { - private: - Q_OBJECT - Q_DISABLE_COPY(ListenerLocalVolumeDialog); - - protected: - /// The user belonging to the listener proxy this dialog has been invoked on - ClientUser *m_user; - /// The channel of the listener proxy this dialog has been invoked on - Channel *m_channel; - /// The volume adjustment that was set before this dialog opened - float m_initialAdjustemt; - - public slots: - void on_qsUserLocalVolume_valueChanged(int value); - void on_qsbUserLocalVolume_valueChanged(int value); - void on_qbbUserLocalVolume_clicked(QAbstractButton *b); - void reject(); - - public: - ListenerLocalVolumeDialog(ClientUser *user, Channel *channel, QWidget *parent = nullptr); +private: + Q_OBJECT + Q_DISABLE_COPY(ListenerLocalVolumeDialog); + +protected: + /// The user belonging to the listener proxy this dialog has been invoked on + ClientUser *m_user; + /// The channel of the listener proxy this dialog has been invoked on + Channel *m_channel; + /// The volume adjustment that was set before this dialog opened + float m_initialAdjustemt; + +public slots: + void on_qsUserLocalVolume_valueChanged(int value); + void on_qsbUserLocalVolume_valueChanged(int value); + void on_qbbUserLocalVolume_clicked(QAbstractButton *b); + void reject(); + +public: + ListenerLocalVolumeDialog(ClientUser *user, Channel *channel, QWidget *parent = nullptr); }; #endif diff --git a/src/mumble/Log.cpp b/src/mumble/Log.cpp index bf39e68b8..37abe1bfc 100644 --- a/src/mumble/Log.cpp +++ b/src/mumble/Log.cpp @@ -14,20 +14,21 @@ #include "Screen.h" #include "ServerHandler.h" #ifndef USE_NO_TTS -# include "TextToSpeech.h" +# include "TextToSpeech.h" #endif #include "Utils.h" -#include <QtNetwork/QNetworkReply> +#include <QSignalBlocker> +#include <QtCore/QMutexLocker> #include <QtGui/QImageWriter> #include <QtGui/QScreen> #include <QtGui/QTextBlock> #include <QtGui/QTextDocumentFragment> +#include <QtNetwork/QNetworkReply> #include <QtWidgets/QDesktopWidget> -#include <QtCore/QMutexLocker> -#include <QSignalBlocker> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const QString LogConfig::name = QLatin1String("LogConfig"); @@ -45,7 +46,7 @@ LogConfig::LogConfig(Settings &st) : ConfigWidget(st) { qsbThreshold->setAccessibleName(tr("Length threshold")); qsbMaxBlocks->setAccessibleName(tr("Maximum chat length")); qsbChatMessageMargins->setAccessibleName(tr("Chat message margins")); - + #ifdef USE_NO_TTS qgbTTS->setDisabled(true); #endif @@ -75,11 +76,11 @@ LogConfig::LogConfig(Settings &st) : ConfigWidget(st) { QTreeWidgetItem *twi; for (int i = Log::firstMsgType; i <= Log::lastMsgType; ++i) { - Log::MsgType t = Log::msgOrder[i]; + Log::MsgType t = Log::msgOrder[i]; const QString messageName = g.l->msgName(t); twi = new QTreeWidgetItem(qtwMessages); - twi->setData(ColMessage, Qt::UserRole, static_cast<int>(t)); + twi->setData(ColMessage, Qt::UserRole, static_cast< int >(t)); twi->setText(ColMessage, messageName); twi->setCheckState(ColConsole, Qt::Unchecked); twi->setCheckState(ColNotification, Qt::Unchecked); @@ -90,31 +91,52 @@ LogConfig::LogConfig(Settings &st) : ConfigWidget(st) { twi->setToolTip(ColNotification, tr("Toggle pop-up notifications for %1 events").arg(messageName)); twi->setToolTip(ColHighlight, tr("Toggle window highlight (if not active) for %1 events").arg(messageName)); twi->setToolTip(ColStaticSound, tr("Click here to toggle sound notification for %1 events").arg(messageName)); - twi->setToolTip(ColStaticSoundPath, tr("Path to sound file used for sound notifications in the case of %1 events<br />Single click to play<br />Double-click to change").arg(messageName)); - - twi->setWhatsThis(ColConsole, tr("Click here to toggle console output for %1 events.<br />If checked, this option makes Mumble output all %1 events in its message log.").arg(messageName)); - twi->setWhatsThis(ColNotification, tr("Click here to toggle pop-up notifications for %1 events.<br />If checked, a notification pop-up will be created by Mumble for every %1 event.").arg(messageName)); - twi->setWhatsThis(ColHighlight, tr("Click here to toggle window highlight for %1 events.<br />If checked, Mumble's window will be highlighted for every %1 event, if not active.").arg(messageName)); - twi->setWhatsThis(ColStaticSound, tr("Click here to toggle sound notification for %1 events.<br />If checked, Mumble uses a sound file predefined by you to indicate %1 events. Sound files and Text-To-Speech cannot be used at the same time.").arg(messageName)); - twi->setWhatsThis(ColStaticSoundPath, tr("Path to sound file used for sound notifications in the case of %1 events.<br />Single click to play<br />Double-click to change<br />Ensure that sound notifications for these events are enabled or this field will not have any effect.").arg(messageName)); + twi->setToolTip(ColStaticSoundPath, tr("Path to sound file used for sound notifications in the case of %1 " + "events<br />Single click to play<br />Double-click to change") + .arg(messageName)); + + twi->setWhatsThis(ColConsole, tr("Click here to toggle console output for %1 events.<br />If checked, this " + "option makes Mumble output all %1 events in its message log.") + .arg(messageName)); + twi->setWhatsThis(ColNotification, + tr("Click here to toggle pop-up notifications for %1 events.<br />If checked, a notification " + "pop-up will be created by Mumble for every %1 event.") + .arg(messageName)); + twi->setWhatsThis(ColHighlight, tr("Click here to toggle window highlight for %1 events.<br />If checked, " + "Mumble's window will be highlighted for every %1 event, if not active.") + .arg(messageName)); + twi->setWhatsThis(ColStaticSound, tr("Click here to toggle sound notification for %1 events.<br />If checked, " + "Mumble uses a sound file predefined by you to indicate %1 events. Sound " + "files and Text-To-Speech cannot be used at the same time.") + .arg(messageName)); + twi->setWhatsThis(ColStaticSoundPath, + tr("Path to sound file used for sound notifications in the case of %1 events.<br />Single " + "click to play<br />Double-click to change<br />Ensure that sound notifications for these " + "events are enabled or this field will not have any effect.") + .arg(messageName)); #ifndef USE_NO_TTS twi->setCheckState(ColTTS, Qt::Unchecked); twi->setToolTip(ColTTS, tr("Toggle Text-To-Speech for %1 events").arg(messageName)); - twi->setWhatsThis(ColTTS, tr("Click here to toggle Text-To-Speech for %1 events.<br />If checked, Mumble uses Text-To-Speech to read %1 events out loud to you. Text-To-Speech is also able to read the contents of the event which is not true for sound files. Text-To-Speech and sound files cannot be used at the same time.").arg(messageName)); + twi->setWhatsThis( + ColTTS, + tr("Click here to toggle Text-To-Speech for %1 events.<br />If checked, Mumble uses Text-To-Speech to read " + "%1 events out loud to you. Text-To-Speech is also able to read the contents of the event which is not " + "true for sound files. Text-To-Speech and sound files cannot be used at the same time.") + .arg(messageName)); #endif } } void LogConfig::updateSelectAllButtons() { - QList<QTreeWidgetItem *> qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); - bool allConsoleChecked = true; - bool allNotificationChecked = true; - bool allHighlightChecked = true; + QList< QTreeWidgetItem * > qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); + bool allConsoleChecked = true; + bool allNotificationChecked = true; + bool allHighlightChecked = true; #ifndef USE_NO_TTS bool allTTSChecked = true; #endif bool allSoundChecked = true; - foreach(QTreeWidgetItem *i, qlItems) { + foreach (QTreeWidgetItem *i, qlItems) { if (i == allMessagesItem) { continue; } @@ -142,7 +164,7 @@ void LogConfig::updateSelectAllButtons() { if (!allTTSChecked) { break; } -#else +#else break; #endif } @@ -170,14 +192,14 @@ QIcon LogConfig::icon() const { } void LogConfig::load(const Settings &r) { - QList<QTreeWidgetItem *> qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); + QList< QTreeWidgetItem * > qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); - foreach(QTreeWidgetItem *i, qlItems) { + foreach (QTreeWidgetItem *i, qlItems) { if (i == allMessagesItem) { continue; } - Log::MsgType mt = static_cast<Log::MsgType>(i->data(ColMessage, Qt::UserRole).toInt()); - Settings::MessageLog ml = static_cast<Settings::MessageLog>(r.qmMessages.value(mt)); + Log::MsgType mt = static_cast< Log::MsgType >(i->data(ColMessage, Qt::UserRole).toInt()); + Settings::MessageLog ml = static_cast< Settings::MessageLog >(r.qmMessages.value(mt)); i->setCheckState(ColConsole, (ml & Settings::LogConsole) ? Qt::Checked : Qt::Unchecked); i->setCheckState(ColNotification, (ml & Settings::LogBalloon) ? Qt::Checked : Qt::Unchecked); @@ -207,12 +229,12 @@ void LogConfig::load(const Settings &r) { } void LogConfig::save() const { - QList<QTreeWidgetItem *> qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); - foreach(QTreeWidgetItem *i, qlItems) { + QList< QTreeWidgetItem * > qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); + foreach (QTreeWidgetItem *i, qlItems) { if (i == allMessagesItem) { continue; } - Log::MsgType mt = static_cast<Log::MsgType>(i->data(ColMessage, Qt::UserRole).toInt()); + Log::MsgType mt = static_cast< Log::MsgType >(i->data(ColMessage, Qt::UserRole).toInt()); int v = 0; if (i->checkState(ColConsole) == Qt::Checked) @@ -227,19 +249,19 @@ void LogConfig::save() const { #endif if (i->checkState(ColStaticSound) == Qt::Checked) v |= Settings::LogSoundfile; - s.qmMessages[mt] = v; + s.qmMessages[mt] = v; s.qmMessageSounds[mt] = i->text(ColStaticSoundPath); } - s.iMaxLogBlocks = qsbMaxBlocks->value(); - s.bLog24HourClock = qcb24HourClock->isChecked(); + s.iMaxLogBlocks = qsbMaxBlocks->value(); + s.bLog24HourClock = qcb24HourClock->isChecked(); s.iChatMessageMargins = qsbChatMessageMargins->value(); #ifndef USE_NO_TTS - s.iTTSVolume=qsVolume->value(); - s.iTTSThreshold=qsbThreshold->value(); + s.iTTSVolume = qsVolume->value(); + s.iTTSThreshold = qsbThreshold->value(); s.bTTSMessageReadBack = qcbReadBackOwn->isChecked(); - s.bTTSNoScope = qcbNoScope->isChecked(); - s.bTTSNoAuthor = qcbNoAuthor->isChecked(); + s.bTTSNoScope = qcbNoScope->isChecked(); + s.bTTSNoAuthor = qcbNoAuthor->isChecked(); #endif s.bWhisperFriends = qcbWhisperFriends->isChecked(); } @@ -251,7 +273,7 @@ void LogConfig::accept() const { g.mw->qteLog->document()->setMaximumBlockCount(s.iMaxLogBlocks); } -void LogConfig::on_qtwMessages_itemChanged(QTreeWidgetItem* i, int column) { +void LogConfig::on_qtwMessages_itemChanged(QTreeWidgetItem *i, int column) { if (i->isSelected() && i != allMessagesItem) { switch (column) { case ColTTS: @@ -261,7 +283,8 @@ void LogConfig::on_qtwMessages_itemChanged(QTreeWidgetItem* i, int column) { case ColStaticSound: if (i->checkState(ColStaticSound)) { i->setCheckState(ColTTS, Qt::Unchecked); - if (i->text(ColStaticSoundPath).isEmpty()) browseForAudioFile(); + if (i->text(ColStaticSoundPath).isEmpty()) + browseForAudioFile(); } break; default: @@ -275,16 +298,16 @@ void LogConfig::on_qtwMessages_itemChanged(QTreeWidgetItem* i, int column) { // Suppress signals on the TreeWidget const QSignalBlocker blocker(qtwMessages); // Select / Unselect all entries of that column - QList<QTreeWidgetItem *> qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); - foreach(QTreeWidgetItem *item, qlItems) { + QList< QTreeWidgetItem * > qlItems = qtwMessages->findItems(QString(), Qt::MatchContains); + foreach (QTreeWidgetItem *item, qlItems) { if (item != allMessagesItem) { item->setCheckState(column, allMessagesItem->checkState(column)); - } + } } } } -void LogConfig::on_qtwMessages_itemClicked(QTreeWidgetItem * item, int column) { +void LogConfig::on_qtwMessages_itemClicked(QTreeWidgetItem *item, int column) { if (item && item != allMessagesItem && column == ColStaticSoundPath) { AudioOutputPtr ao = g.ao; if (ao) { @@ -294,7 +317,7 @@ void LogConfig::on_qtwMessages_itemClicked(QTreeWidgetItem * item, int column) { } } -void LogConfig::on_qtwMessages_itemDoubleClicked(QTreeWidgetItem * item, int column) { +void LogConfig::on_qtwMessages_itemDoubleClicked(QTreeWidgetItem *item, int column) { if (item && item != allMessagesItem && column == ColStaticSoundPath) browseForAudioFile(); } @@ -310,7 +333,7 @@ void LogConfig::browseForAudioFile() { } QMutex Log::qmDeferredLogs; -QVector<LogMessage> Log::qvDeferredLogs; +QVector< LogMessage > Log::qvDeferredLogs; Log::Log(QObject *p) : QObject(p) { @@ -319,70 +342,80 @@ Log::Log(QObject *p) : QObject(p) { tts->setVolume(g.s.iTTSVolume); #endif uiLastId = 0; - qdDate = QDate::currentDate(); -} - -// Display order in settingsscreen, allows to insert new events without breaking config-compatibility with older versions -const Log::MsgType Log::msgOrder[] = { - DebugInfo, CriticalError, Warning, Information, - ServerConnected, ServerDisconnected, - UserJoin, UserLeave, - ChannelListeningAdd, ChannelListeningRemove, - Recording, - YouKicked, UserKicked, - UserRenamed, - SelfMute, SelfUnmute, SelfDeaf, SelfUndeaf, - OtherSelfMute, YouMuted, YouMutedOther, OtherMutedOther, - SelfChannelJoin, SelfChannelJoinOther, - ChannelJoin, ChannelLeave, - ChannelJoinConnect, ChannelLeaveDisconnect, - PermissionDenied, - TextMessage, PrivateTextMessage -}; - -const char *Log::msgNames[] = { - QT_TRANSLATE_NOOP("Log", "Debug"), - QT_TRANSLATE_NOOP("Log", "Critical"), - QT_TRANSLATE_NOOP("Log", "Warning"), - QT_TRANSLATE_NOOP("Log", "Information"), - QT_TRANSLATE_NOOP("Log", "Server connected"), - QT_TRANSLATE_NOOP("Log", "Server disconnected"), - QT_TRANSLATE_NOOP("Log", "User joined server"), - QT_TRANSLATE_NOOP("Log", "User left server"), - QT_TRANSLATE_NOOP("Log", "User recording state changed"), - QT_TRANSLATE_NOOP("Log", "User kicked (you or by you)"), - QT_TRANSLATE_NOOP("Log", "User kicked"), - QT_TRANSLATE_NOOP("Log", "You self-muted"), - QT_TRANSLATE_NOOP("Log", "Other self-muted/deafened"), - QT_TRANSLATE_NOOP("Log", "User muted (you)"), - QT_TRANSLATE_NOOP("Log", "User muted (by you)"), - QT_TRANSLATE_NOOP("Log", "User muted (other)"), - QT_TRANSLATE_NOOP("Log", "User joined channel"), - QT_TRANSLATE_NOOP("Log", "User left channel"), - QT_TRANSLATE_NOOP("Log", "Permission denied"), - QT_TRANSLATE_NOOP("Log", "Text message"), - QT_TRANSLATE_NOOP("Log", "You self-unmuted"), - QT_TRANSLATE_NOOP("Log", "You self-deafened"), - QT_TRANSLATE_NOOP("Log", "You self-undeafened"), - QT_TRANSLATE_NOOP("Log", "User renamed"), - QT_TRANSLATE_NOOP("Log", "You joined channel"), - QT_TRANSLATE_NOOP("Log", "You joined channel (moved)"), - QT_TRANSLATE_NOOP("Log", "User connected and entered channel"), - QT_TRANSLATE_NOOP("Log", "User left channel and disconnected"), - QT_TRANSLATE_NOOP("Log", "Private text message"), - QT_TRANSLATE_NOOP("Log", "User started listening to channel"), - QT_TRANSLATE_NOOP("Log", "User stopped listening to channel") -}; + qdDate = QDate::currentDate(); +} + +// Display order in settingsscreen, allows to insert new events without breaking config-compatibility with older +// versions +const Log::MsgType Log::msgOrder[] = { DebugInfo, + CriticalError, + Warning, + Information, + ServerConnected, + ServerDisconnected, + UserJoin, + UserLeave, + ChannelListeningAdd, + ChannelListeningRemove, + Recording, + YouKicked, + UserKicked, + UserRenamed, + SelfMute, + SelfUnmute, + SelfDeaf, + SelfUndeaf, + OtherSelfMute, + YouMuted, + YouMutedOther, + OtherMutedOther, + SelfChannelJoin, + SelfChannelJoinOther, + ChannelJoin, + ChannelLeave, + ChannelJoinConnect, + ChannelLeaveDisconnect, + PermissionDenied, + TextMessage, + PrivateTextMessage }; + +const char *Log::msgNames[] = { QT_TRANSLATE_NOOP("Log", "Debug"), + QT_TRANSLATE_NOOP("Log", "Critical"), + QT_TRANSLATE_NOOP("Log", "Warning"), + QT_TRANSLATE_NOOP("Log", "Information"), + QT_TRANSLATE_NOOP("Log", "Server connected"), + QT_TRANSLATE_NOOP("Log", "Server disconnected"), + QT_TRANSLATE_NOOP("Log", "User joined server"), + QT_TRANSLATE_NOOP("Log", "User left server"), + QT_TRANSLATE_NOOP("Log", "User recording state changed"), + QT_TRANSLATE_NOOP("Log", "User kicked (you or by you)"), + QT_TRANSLATE_NOOP("Log", "User kicked"), + QT_TRANSLATE_NOOP("Log", "You self-muted"), + QT_TRANSLATE_NOOP("Log", "Other self-muted/deafened"), + QT_TRANSLATE_NOOP("Log", "User muted (you)"), + QT_TRANSLATE_NOOP("Log", "User muted (by you)"), + QT_TRANSLATE_NOOP("Log", "User muted (other)"), + QT_TRANSLATE_NOOP("Log", "User joined channel"), + QT_TRANSLATE_NOOP("Log", "User left channel"), + QT_TRANSLATE_NOOP("Log", "Permission denied"), + QT_TRANSLATE_NOOP("Log", "Text message"), + QT_TRANSLATE_NOOP("Log", "You self-unmuted"), + QT_TRANSLATE_NOOP("Log", "You self-deafened"), + QT_TRANSLATE_NOOP("Log", "You self-undeafened"), + QT_TRANSLATE_NOOP("Log", "User renamed"), + QT_TRANSLATE_NOOP("Log", "You joined channel"), + QT_TRANSLATE_NOOP("Log", "You joined channel (moved)"), + QT_TRANSLATE_NOOP("Log", "User connected and entered channel"), + QT_TRANSLATE_NOOP("Log", "User left channel and disconnected"), + QT_TRANSLATE_NOOP("Log", "Private text message"), + QT_TRANSLATE_NOOP("Log", "User started listening to channel"), + QT_TRANSLATE_NOOP("Log", "User stopped listening to channel") }; QString Log::msgName(MsgType t) const { return tr(msgNames[t]); } -const char *Log::colorClasses[] = { - "time", - "server", - "privilege" -}; +const char *Log::colorClasses[] = { "time", "server", "privilege" }; const QStringList Log::allowedSchemes() { QStringList qslAllowedSchemeNames; @@ -411,10 +444,14 @@ QString Log::msgColor(const QString &text, LogColorType t) { } QString Log::formatChannel(::Channel *c) { - return QString::fromLatin1("<a href='channelid://%1/%3' class='log-channel'>%2</a>").arg(c->iId).arg(c->qsName.toHtmlEscaped()).arg(QString::fromLatin1(g.sh->qbaDigest.toBase64())); + return QString::fromLatin1("<a href='channelid://%1/%3' class='log-channel'>%2</a>") + .arg(c->iId) + .arg(c->qsName.toHtmlEscaped()) + .arg(QString::fromLatin1(g.sh->qbaDigest.toBase64())); } -void Log::logOrDefer(Log::MsgType mt, const QString &console, const QString &terse, bool ownMessage, const QString &overrideTTS, bool ignoreTTS) { +void Log::logOrDefer(Log::MsgType mt, const QString &console, const QString &terse, bool ownMessage, + const QString &overrideTTS, bool ignoreTTS) { if (g.l) { // log directly as it seems the log-UI has been set-up already g.l->log(mt, console, terse, ownMessage, overrideTTS, ignoreTTS); @@ -437,9 +474,16 @@ QString Log::formatClientUser(ClientUser *cu, LogColorType t, const QString &dis if (cu) { QString name = (displayName.isNull() ? cu->qsName : displayName).toHtmlEscaped(); if (cu->qsHash.isEmpty()) { - return QString::fromLatin1("<a href='clientid://%2/%4' class='log-user log-%1'>%3</a>").arg(className).arg(cu->uiSession).arg(name).arg(QString::fromLatin1(g.sh->qbaDigest.toBase64())); + return QString::fromLatin1("<a href='clientid://%2/%4' class='log-user log-%1'>%3</a>") + .arg(className) + .arg(cu->uiSession) + .arg(name) + .arg(QString::fromLatin1(g.sh->qbaDigest.toBase64())); } else { - return QString::fromLatin1("<a href='clientid://%2' class='log-user log-%1'>%3</a>").arg(className).arg(cu->qsHash).arg(name); + return QString::fromLatin1("<a href='clientid://%2' class='log-user log-%1'>%3</a>") + .arg(className) + .arg(cu->qsHash) + .arg(name); } } else { return QString::fromLatin1("<span class='log-server log-%1'>%2</span>").arg(className).arg(tr("the server")); @@ -462,13 +506,13 @@ QString Log::imageToImg(const QByteArray &format, const QByteArray &image) { QByteArray rawbase = image.toBase64(); QByteArray encoded; - int i = 0; + int i = 0; int begin = 0, end = 0; do { - begin = i*72; - end = begin+72; + begin = i * 72; + end = begin + 72; - encoded.append(QUrl::toPercentEncoding(QLatin1String(rawbase.mid(begin,72)))); + encoded.append(QUrl::toPercentEncoding(QLatin1String(rawbase.mid(begin, 72)))); if (end < rawbase.length()) encoded.append('\n'); @@ -483,7 +527,7 @@ QString Log::imageToImg(QImage img) { img = img.scaled(480, 270, Qt::KeepAspectRatio, Qt::SmoothTransformation); } - int quality = 100; + int quality = 100; QByteArray format = "PNG"; QByteArray qba; @@ -533,14 +577,14 @@ QString Log::validHtml(const QString &html, QTextCursor *tc) { for (QTextBlock qtb = qtd.begin(); qtb != qtd.end(); qtb = qtb.next()) { for (QTextBlock::iterator qtbi = qtb.begin(); qtbi != qtb.end(); ++qtbi) { const QTextFragment &qtf = qtbi.fragment(); - QTextCharFormat qcf = qtf.charFormat(); - if (! qcf.anchorHref().isEmpty()) { + QTextCharFormat qcf = qtf.charFormat(); + if (!qcf.anchorHref().isEmpty()) { QUrl url(qcf.anchorHref()); - if (! url.isValid() || ! qslAllowed.contains(url.scheme())) { + if (!url.isValid() || !qslAllowed.contains(url.scheme())) { QTextCharFormat qcfn = QTextCharFormat(); QTextCursor qtc(&qtd); qtc.setPosition(qtf.position(), QTextCursor::MoveAnchor); - qtc.setPosition(qtf.position()+qtf.length(), QTextCursor::KeepAnchor); + qtc.setPosition(qtf.position() + qtf.length(), QTextCursor::KeepAnchor); qtc.setCharFormat(qcfn); qtbi = qtb.begin(); } @@ -584,7 +628,8 @@ QString Log::validHtml(const QString &html, QTextCursor *tc) { } } -void Log::log(MsgType mt, const QString &console, const QString &terse, bool ownMessage, const QString &overrideTTS, bool ignoreTTS) { +void Log::log(MsgType mt, const QString &console, const QString &terse, bool ownMessage, const QString &overrideTTS, + bool ignoreTTS) { QDateTime dt = QDateTime::currentDateTime(); int ignore = qmIgnore.value(mt); @@ -612,21 +657,23 @@ void Log::log(MsgType mt, const QString &console, const QString &terse, bool own format.setBottomMargin(msgMargin); tc.setBlockFormat(format); - LogTextBrowser *tlog = g.mw->qteLog; + LogTextBrowser *tlog = g.mw->qteLog; const int oldscrollvalue = tlog->getLogScroll(); - const bool scroll = (oldscrollvalue == tlog->getLogScrollMaximum()); + const bool scroll = (oldscrollvalue == tlog->getLogScrollMaximum()); tc.movePosition(QTextCursor::End); if (qdDate != dt.date()) { qdDate = dt.date(); tc.insertBlock(); - tc.insertHtml(tr("[Date changed to %1]\n").arg(qdDate.toString(Qt::DefaultLocaleShortDate).toHtmlEscaped())); + tc.insertHtml( + tr("[Date changed to %1]\n").arg(qdDate.toString(Qt::DefaultLocaleShortDate).toHtmlEscaped())); tc.movePosition(QTextCursor::End); } // Convert CRLF to unix-style LF and old mac-style LF (single \r) to unix-style as well - QString fixedNLPlain = plain.replace(QLatin1String("\r\n"), QLatin1String("\n")).replace(QLatin1String("\r"), QLatin1String("\n")); + QString fixedNLPlain = + plain.replace(QLatin1String("\r\n"), QLatin1String("\n")).replace(QLatin1String("\r"), QLatin1String("\n")); if (fixedNLPlain.contains(QRegExp(QLatin1String("\\n[ \\t]*$")))) { // If the message ends with one or more blank lines (or lines only containing whitespace) @@ -679,7 +726,7 @@ void Log::log(MsgType mt, const QString &console, const QString &terse, bool own // Message notification with static sounds if ((flags & Settings::LogSoundfile)) { - QString sSound = g.s.qmMessageSounds.value(mt); + QString sSound = g.s.qmMessageSounds.value(mt); AudioOutputPtr ao = g.ao; if (!ao || !ao->playSample(sSound, false)) { qWarning() << "Sound file" << sSound << "is not a valid audio file, fallback to TTS."; @@ -701,9 +748,7 @@ void Log::log(MsgType mt, const QString &console, const QString &terse, bool own } // Apply simplifications to spoken text - QRegExp identifyURL(QLatin1String("[a-z-]+://[^ <]*"), - Qt::CaseInsensitive, - QRegExp::RegExp2); + QRegExp identifyURL(QLatin1String("[a-z-]+://[^ <]*"), Qt::CaseInsensitive, QRegExp::RegExp2); QStringList qslAllowed = allowedSchemes(); @@ -737,7 +782,7 @@ void Log::log(MsgType mt, const QString &console, const QString &terse, bool own // TTS threshold limiter. if (plain.length() <= g.s.iTTSThreshold) tts->say(plain); - else if ((! terse.isEmpty()) && (terse.length() <= g.s.iTTSThreshold)) + else if ((!terse.isEmpty()) && (terse.length() <= g.s.iTTSThreshold)) tts->say(terse); #endif } @@ -772,12 +817,12 @@ void Log::postQtNotification(MsgType mt, const QString &plain) { } } -LogMessage::LogMessage(Log::MsgType mt, const QString &console, const QString &terse, bool ownMessage, const QString &overrideTTS, bool ignoreTTS) : mt(mt), console(console), - terse(terse), ownMessage(ownMessage), overrideTTS(overrideTTS), ignoreTTS(ignoreTTS) { +LogMessage::LogMessage(Log::MsgType mt, const QString &console, const QString &terse, bool ownMessage, + const QString &overrideTTS, bool ignoreTTS) + : mt(mt), console(console), terse(terse), ownMessage(ownMessage), overrideTTS(overrideTTS), ignoreTTS(ignoreTTS) { } -LogDocument::LogDocument(QObject *p) - : QTextDocument(p) { +LogDocument::LogDocument(QObject *p) : QTextDocument(p) { } QVariant LogDocument::loadResource(int type, const QUrl &url) { @@ -791,7 +836,7 @@ QVariant LogDocument::loadResource(int type, const QUrl &url) { QImage qi(1, 1, QImage::Format_Mono); addResource(type, url, qi); - if (! url.isValid()) { + if (!url.isValid()) { return qi; } @@ -811,7 +856,7 @@ QVariant LogDocument::loadResource(int type, const QUrl &url) { } void LogDocument::finished() { - QNetworkReply *rep = qobject_cast<QNetworkReply *>(sender()); + QNetworkReply *rep = qobject_cast< QNetworkReply * >(sender()); if (rep->error() == QNetworkReply::NoError) { QByteArray ba = rep->readAll(); @@ -832,7 +877,7 @@ void LogDocument::finished() { // Doing so can trigger crashes deep inside Qt // if the QTextDocument has just been set on the // text edit widget. - QTextEdit *qte = qobject_cast<QTextEdit *>(parent()); + QTextEdit *qte = qobject_cast< QTextEdit * >(parent()); if (qte) { QEvent *e = new QEvent(QEvent::FontChange); QApplication::postEvent(qte, e); @@ -847,6 +892,5 @@ void LogDocument::finished() { rep->deleteLater(); } -LogDocumentResourceAddedEvent::LogDocumentResourceAddedEvent() - : QEvent(LogDocumentResourceAddedEvent::Type) { +LogDocumentResourceAddedEvent::LogDocumentResourceAddedEvent() : QEvent(LogDocumentResourceAddedEvent::Type) { } diff --git a/src/mumble/Log.h b/src/mumble/Log.h index d8d6550ed..4b21df177 100644 --- a/src/mumble/Log.h +++ b/src/mumble/Log.h @@ -20,30 +20,32 @@ class TextToSpeech; #endif class LogConfig : public ConfigWidget, public Ui::LogConfig { - private: - Q_OBJECT - Q_DISABLE_COPY(LogConfig) - - QTreeWidgetItem *allMessagesItem; - protected: - void updateSelectAllButtons(); - public: - /// The unique name of this ConfigWidget - static const QString name; - enum Column { ColMessage, ColConsole, ColNotification, ColHighlight, ColTTS, ColStaticSound, ColStaticSoundPath }; - LogConfig(Settings &st); - QString title() const Q_DECL_OVERRIDE; - const QString &getName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; - public slots: - void accept() const Q_DECL_OVERRIDE; - void save() const Q_DECL_OVERRIDE; - void load(const Settings &) Q_DECL_OVERRIDE; - - void on_qtwMessages_itemChanged(QTreeWidgetItem*, int); - void on_qtwMessages_itemClicked(QTreeWidgetItem*, int); - void on_qtwMessages_itemDoubleClicked(QTreeWidgetItem*, int); - void browseForAudioFile(); +private: + Q_OBJECT + Q_DISABLE_COPY(LogConfig) + + QTreeWidgetItem *allMessagesItem; + +protected: + void updateSelectAllButtons(); + +public: + /// The unique name of this ConfigWidget + static const QString name; + enum Column { ColMessage, ColConsole, ColNotification, ColHighlight, ColTTS, ColStaticSound, ColStaticSoundPath }; + LogConfig(Settings &st); + QString title() const Q_DECL_OVERRIDE; + const QString &getName() const Q_DECL_OVERRIDE; + QIcon icon() const Q_DECL_OVERRIDE; +public slots: + void accept() const Q_DECL_OVERRIDE; + void save() const Q_DECL_OVERRIDE; + void load(const Settings &) Q_DECL_OVERRIDE; + + void on_qtwMessages_itemChanged(QTreeWidgetItem *, int); + void on_qtwMessages_itemClicked(QTreeWidgetItem *, int); + void on_qtwMessages_itemDoubleClicked(QTreeWidgetItem *, int); + void browseForAudioFile(); }; class ClientUser; @@ -51,85 +53,123 @@ class Channel; class LogMessage; class Log : public QObject { - friend class LogConfig; - private: - Q_OBJECT - Q_DISABLE_COPY(Log) - public: - enum MsgType { DebugInfo, CriticalError, Warning, Information, ServerConnected, ServerDisconnected, UserJoin, UserLeave, Recording, YouKicked, UserKicked, SelfMute, OtherSelfMute, YouMuted, YouMutedOther, OtherMutedOther, ChannelJoin, ChannelLeave, PermissionDenied, TextMessage, SelfUnmute, SelfDeaf, SelfUndeaf, UserRenamed, SelfChannelJoin, SelfChannelJoinOther, ChannelJoinConnect, ChannelLeaveDisconnect, PrivateTextMessage, ChannelListeningAdd, ChannelListeningRemove }; - enum LogColorType { Time, Server, Privilege, Source, Target }; - static const MsgType firstMsgType = DebugInfo; - static const MsgType lastMsgType = ChannelListeningRemove; - - // Display order in settingsscreen, allows to insert new events without breaking config-compatibility with older versions. - static const MsgType msgOrder[]; - - protected: - /// Mutex for qvDeferredLogs - static QMutex qmDeferredLogs; - /// A vector containing deferred log messages - static QVector<LogMessage> qvDeferredLogs; - - QHash<MsgType, int> qmIgnore; - static const char *msgNames[]; - static const char *colorClasses[]; + friend class LogConfig; + +private: + Q_OBJECT + Q_DISABLE_COPY(Log) +public: + enum MsgType { + DebugInfo, + CriticalError, + Warning, + Information, + ServerConnected, + ServerDisconnected, + UserJoin, + UserLeave, + Recording, + YouKicked, + UserKicked, + SelfMute, + OtherSelfMute, + YouMuted, + YouMutedOther, + OtherMutedOther, + ChannelJoin, + ChannelLeave, + PermissionDenied, + TextMessage, + SelfUnmute, + SelfDeaf, + SelfUndeaf, + UserRenamed, + SelfChannelJoin, + SelfChannelJoinOther, + ChannelJoinConnect, + ChannelLeaveDisconnect, + PrivateTextMessage, + ChannelListeningAdd, + ChannelListeningRemove + }; + enum LogColorType { Time, Server, Privilege, Source, Target }; + static const MsgType firstMsgType = DebugInfo; + static const MsgType lastMsgType = ChannelListeningRemove; + + // Display order in settingsscreen, allows to insert new events without breaking config-compatibility with older + // versions. + static const MsgType msgOrder[]; + +protected: + /// Mutex for qvDeferredLogs + static QMutex qmDeferredLogs; + /// A vector containing deferred log messages + static QVector< LogMessage > qvDeferredLogs; + + QHash< MsgType, int > qmIgnore; + static const char *msgNames[]; + static const char *colorClasses[]; #ifndef USE_NO_TTS - TextToSpeech *tts; + TextToSpeech *tts; #endif - unsigned int uiLastId; - QDate qdDate; - static const QStringList allowedSchemes(); - void postNotification(MsgType mt, const QString &plain); - void postQtNotification(MsgType mt, const QString &plain); - public: - Log(QObject *p = nullptr); - QString msgName(MsgType t) const; - void setIgnore(MsgType t, int ignore = 1 << 30); - void clearIgnore(); - static QString validHtml(const QString &html, QTextCursor *tc = nullptr); - static QString imageToImg(const QByteArray &format, const QByteArray &image); - static QString imageToImg(QImage img); - static QString msgColor(const QString &text, LogColorType t); - static QString formatClientUser(ClientUser *cu, LogColorType t, const QString &displayName=QString()); - static QString formatChannel(::Channel *c); - /// Either defers the LogMessage or defers it, depending on whether Global::l is created already - /// (if it is, it is used to directly log the msg) - static void logOrDefer(Log::MsgType mt, const QString &console, const QString &terse=QString(), bool ownMessage = false, const QString &overrideTTS=QString(), bool ignoreTTS = false); - public slots: - void log(MsgType mt, const QString &console, const QString &terse=QString(), bool ownMessage = false, const QString &overrideTTS=QString(), bool ignoreTTS = false); - /// Logs LogMessages that have been deferred so far - void processDeferredLogs(); + unsigned int uiLastId; + QDate qdDate; + static const QStringList allowedSchemes(); + void postNotification(MsgType mt, const QString &plain); + void postQtNotification(MsgType mt, const QString &plain); + +public: + Log(QObject *p = nullptr); + QString msgName(MsgType t) const; + void setIgnore(MsgType t, int ignore = 1 << 30); + void clearIgnore(); + static QString validHtml(const QString &html, QTextCursor *tc = nullptr); + static QString imageToImg(const QByteArray &format, const QByteArray &image); + static QString imageToImg(QImage img); + static QString msgColor(const QString &text, LogColorType t); + static QString formatClientUser(ClientUser *cu, LogColorType t, const QString &displayName = QString()); + static QString formatChannel(::Channel *c); + /// Either defers the LogMessage or defers it, depending on whether Global::l is created already + /// (if it is, it is used to directly log the msg) + static void logOrDefer(Log::MsgType mt, const QString &console, const QString &terse = QString(), + bool ownMessage = false, const QString &overrideTTS = QString(), bool ignoreTTS = false); +public slots: + void log(MsgType mt, const QString &console, const QString &terse = QString(), bool ownMessage = false, + const QString &overrideTTS = QString(), bool ignoreTTS = false); + /// Logs LogMessages that have been deferred so far + void processDeferredLogs(); }; class LogMessage { - public: - Log::MsgType mt; - QString console; - QString terse; - bool ownMessage; - QString overrideTTS; - bool ignoreTTS; - - LogMessage() = default; - LogMessage(Log::MsgType mt, const QString &console, const QString &terse, bool ownMessage, const QString &overrideTTS, bool ignoreTTS); +public: + Log::MsgType mt; + QString console; + QString terse; + bool ownMessage; + QString overrideTTS; + bool ignoreTTS; + + LogMessage() = default; + LogMessage(Log::MsgType mt, const QString &console, const QString &terse, bool ownMessage, + const QString &overrideTTS, bool ignoreTTS); }; class LogDocument : public QTextDocument { - private: - Q_OBJECT - Q_DISABLE_COPY(LogDocument) - public: - LogDocument(QObject *p = nullptr); - QVariant loadResource(int, const QUrl &) Q_DECL_OVERRIDE; - public slots: - void finished(); +private: + Q_OBJECT + Q_DISABLE_COPY(LogDocument) +public: + LogDocument(QObject *p = nullptr); + QVariant loadResource(int, const QUrl &) Q_DECL_OVERRIDE; +public slots: + void finished(); }; class LogDocumentResourceAddedEvent : public QEvent { - public: - static const QEvent::Type Type = static_cast<QEvent::Type>(20145); +public: + static const QEvent::Type Type = static_cast< QEvent::Type >(20145); - LogDocumentResourceAddedEvent(); + LogDocumentResourceAddedEvent(); }; #endif diff --git a/src/mumble/Log_unix.cpp b/src/mumble/Log_unix.cpp index a2571784c..f6566c9a5 100644 --- a/src/mumble/Log_unix.cpp +++ b/src/mumble/Log_unix.cpp @@ -8,10 +8,11 @@ #include "Settings.h" #ifdef USE_DBUS -#include <QtDBus/QDBusInterface> +# include <QtDBus/QDBusInterface> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" void Log::postNotification(MsgType mt, const QString &plain) { @@ -20,16 +21,16 @@ void Log::postNotification(MsgType mt, const QString &plain) { switch (mt) { case DebugInfo: case CriticalError: - qsIcon=QLatin1String("gtk-dialog-error"); + qsIcon = QLatin1String("gtk-dialog-error"); break; case Warning: - qsIcon=QLatin1String("gtk-dialog-warning"); + qsIcon = QLatin1String("gtk-dialog-warning"); break; case TextMessage: - qsIcon=QLatin1String("gtk-edit"); + qsIcon = QLatin1String("gtk-edit"); break; default: - qsIcon=QLatin1String("gtk-dialog-info"); + qsIcon = QLatin1String("gtk-dialog-info"); break; } @@ -39,9 +40,10 @@ void Log::postNotification(MsgType mt, const QString &plain) { hints.insert(QLatin1String("desktop-entry"), QLatin1String("mumble")); { - QDBusInterface kde(QLatin1String("org.kde.VisualNotifications"), QLatin1String("/VisualNotifications"), QLatin1String("org.kde.VisualNotifications")); + QDBusInterface kde(QLatin1String("org.kde.VisualNotifications"), QLatin1String("/VisualNotifications"), + QLatin1String("org.kde.VisualNotifications")); if (kde.isValid()) { - QList<QVariant> args; + QList< QVariant > args; args.append(QLatin1String("mumble")); args.append(uiLastId); args.append(QString()); @@ -56,13 +58,16 @@ void Log::postNotification(MsgType mt, const QString &plain) { } } - if (response.type()!=QDBusMessage::ReplyMessage || response.arguments().at(0).toUInt()==0) { - QDBusInterface gnome(QLatin1String("org.freedesktop.Notifications"), QLatin1String("/org/freedesktop/Notifications"), QLatin1String("org.freedesktop.Notifications")); + if (response.type() != QDBusMessage::ReplyMessage || response.arguments().at(0).toUInt() == 0) { + QDBusInterface gnome(QLatin1String("org.freedesktop.Notifications"), + QLatin1String("/org/freedesktop/Notifications"), + QLatin1String("org.freedesktop.Notifications")); if (gnome.isValid()) - response = gnome.call(QLatin1String("Notify"), QLatin1String("Mumble"), uiLastId, qsIcon, msgName(mt), plain, QStringList(), hints, -1); + response = gnome.call(QLatin1String("Notify"), QLatin1String("Mumble"), uiLastId, qsIcon, msgName(mt), + plain, QStringList(), hints, -1); } - if (response.type()==QDBusMessage::ReplyMessage && response.arguments().count() == 1) { + if (response.type() == QDBusMessage::ReplyMessage && response.arguments().count() == 1) { uiLastId = response.arguments().at(0).toUInt(); } else { #else diff --git a/src/mumble/LookConfig.cpp b/src/mumble/LookConfig.cpp index 466c904d2..71c7164d8 100644 --- a/src/mumble/LookConfig.cpp +++ b/src/mumble/LookConfig.cpp @@ -14,7 +14,8 @@ #include <QtCore/QStack> #include <QtCore/QTimer> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const QString LookConfig::name = QLatin1String("LookConfig"); @@ -41,30 +42,28 @@ LookConfig::LookConfig(Settings &st) : ConfigWidget(st) { qcbChannelDrag->setAccessibleName(tr("Channel dragging")); qcbExpand->setAccessibleName(tr("Automatically expand channels when")); qcbUserDrag->setAccessibleName(tr("User dragging behavior")); - + #ifndef Q_OS_MAC - if (! QSystemTrayIcon::isSystemTrayAvailable()) + if (!QSystemTrayIcon::isSystemTrayAvailable()) #endif qgbTray->hide(); qcbLanguage->addItem(tr("System default")); - QDir d(QLatin1String(":"),QLatin1String("mumble_*.qm"),QDir::Name,QDir::Files); - foreach(const QString &key, d.entryList()) { - QString cc = key.mid(7,key.indexOf(QLatin1Char('.'))-7); + QDir d(QLatin1String(":"), QLatin1String("mumble_*.qm"), QDir::Name, QDir::Files); + foreach (const QString &key, d.entryList()) { + QString cc = key.mid(7, key.indexOf(QLatin1Char('.')) - 7); QLocale tmpLocale = QLocale(cc); - //If there is no native language name, use the locale + // If there is no native language name, use the locale QString displayName = cc; - if(!tmpLocale.nativeLanguageName().isEmpty()) { - displayName = QString(QLatin1String("%1 (%2)")) - .arg(tmpLocale.nativeLanguageName()) - .arg(cc); - } else if (cc == QLatin1String("eo")){ + if (!tmpLocale.nativeLanguageName().isEmpty()) { + displayName = QString(QLatin1String("%1 (%2)")).arg(tmpLocale.nativeLanguageName()).arg(cc); + } else if (cc == QLatin1String("eo")) { // Can't initialize QLocale for a countryless language (QTBUG-8452, QTBUG-14592). // We only have one so special case it. displayName = QLatin1String("Esperanto (eo)"); } - + qcbLanguage->addItem(displayName, QVariant(cc)); } @@ -75,17 +74,17 @@ LookConfig::LookConfig(Settings &st) : ConfigWidget(st) { qcbChannelDrag->insertItem(Settings::Ask, tr("Ask"), Settings::Ask); qcbChannelDrag->insertItem(Settings::DoNothing, tr("Do Nothing"), Settings::DoNothing); qcbChannelDrag->insertItem(Settings::Move, tr("Move"), Settings::Move); - + qcbUserDrag->insertItem(Settings::Ask, tr("Ask"), Settings::Ask); qcbUserDrag->insertItem(Settings::DoNothing, tr("Do Nothing"), Settings::DoNothing); qcbUserDrag->insertItem(Settings::Move, tr("Move"), Settings::Move); - connect(qrbLCustom,SIGNAL(toggled(bool)),qcbLockLayout,SLOT(setEnabled(bool))); - + connect(qrbLCustom, SIGNAL(toggled(bool)), qcbLockLayout, SLOT(setEnabled(bool))); + QDir userThemeDirectory = Themes::getUserThemesDirectory(); if (userThemeDirectory.exists()) { m_themeDirectoryWatcher = new QFileSystemWatcher(this); - + // Use a timer to cut down floods of directory changes. We only want // to trigger a refresh after nothing has happened for 200ms in the // watched directory. @@ -93,16 +92,15 @@ LookConfig::LookConfig(Settings &st) : ConfigWidget(st) { m_themeDirectoryDebouncer->setSingleShot(true); m_themeDirectoryDebouncer->setInterval(200); m_themeDirectoryDebouncer->connect(m_themeDirectoryWatcher, SIGNAL(directoryChanged(QString)), SLOT(start())); - + connect(m_themeDirectoryDebouncer, SIGNAL(timeout()), SLOT(themeDirectoryChanged())); m_themeDirectoryWatcher->addPath(userThemeDirectory.path()); - + QUrl userThemeDirectoryUrl = QUrl::fromLocalFile(userThemeDirectory.path()); //: This link is located next to the theme heading in the ui config and opens the user theme directory qlThemesDirectory->setText(tr("<a href=\"%1\">Browse</a>").arg(userThemeDirectoryUrl.toString())); qlThemesDirectory->setOpenExternalLinks(true); } - } QString LookConfig::title() const { @@ -117,31 +115,25 @@ QIcon LookConfig::icon() const { return QIcon(QLatin1String("skin:config_ui.png")); } -void LookConfig::reloadThemes(const boost::optional<ThemeInfo::StyleInfo> configuredStyle) { +void LookConfig::reloadThemes(const boost::optional< ThemeInfo::StyleInfo > configuredStyle) { const ThemeMap themes = Themes::getThemes(); - + int selectedThemeEntry = 0; - + qcbTheme->clear(); qcbTheme->addItem(tr("None")); - for (ThemeMap::const_iterator theme = themes.begin(); - theme != themes.end(); - ++theme) { - - for (ThemeInfo::StylesMap::const_iterator styleit = theme->styles.begin(); - styleit != theme->styles.end(); - ++styleit) { - - if (configuredStyle - && configuredStyle->themeName == styleit->themeName - && configuredStyle->name == styleit->name) { + for (ThemeMap::const_iterator theme = themes.begin(); theme != themes.end(); ++theme) { + for (ThemeInfo::StylesMap::const_iterator styleit = theme->styles.begin(); styleit != theme->styles.end(); + ++styleit) { + if (configuredStyle && configuredStyle->themeName == styleit->themeName + && configuredStyle->name == styleit->name) { selectedThemeEntry = qcbTheme->count(); } - + qcbTheme->addItem(theme->name + QLatin1String(" - ") + styleit->name, QVariant::fromValue(*styleit)); } } - + qcbTheme->setCurrentIndex(selectedThemeEntry); } @@ -167,16 +159,16 @@ void LookConfig::load(const Settings &r) { qrbLCustom->setChecked(true); break; } - qcbLockLayout->setEnabled(r.wlWindowLayout==Settings::LayoutCustom); + qcbLockLayout->setEnabled(r.wlWindowLayout == Settings::LayoutCustom); - for (int i=0;i<qcbLanguage->count();i++) { + for (int i = 0; i < qcbLanguage->count(); i++) { if (qcbLanguage->itemData(i).toString() == r.qsLanguage) { loadComboBox(qcbLanguage, i); break; } } - + loadComboBox(qcbAlwaysOnTop, r.aotbAlwaysOnTop); loadComboBox(qcbExpand, r.ceExpand); @@ -185,7 +177,7 @@ void LookConfig::load(const Settings &r) { loadCheckBox(qcbUsersTop, r.bUserTop); loadCheckBox(qcbAskOnQuit, r.bAskOnQuit); loadCheckBox(qcbEnableDeveloperMenu, r.bEnableDeveloperMenu); - loadCheckBox(qcbLockLayout, (r.wlWindowLayout==Settings::LayoutCustom)&&r.bLockLayout); + loadCheckBox(qcbLockLayout, (r.wlWindowLayout == Settings::LayoutCustom) && r.bLockLayout); loadCheckBox(qcbHideTray, r.bHideInTray); loadCheckBox(qcbStateInTray, r.bStateInTray); loadCheckBox(qcbShowUserCount, r.bShowUserCount); @@ -195,8 +187,8 @@ void LookConfig::load(const Settings &r) { loadCheckBox(qcbHighContrast, r.bHighContrast); loadCheckBox(qcbChatBarUseSelection, r.bChatBarUseSelection); loadCheckBox(qcbFilterHidesEmptyChannels, r.bFilterHidesEmptyChannels); - - const boost::optional<ThemeInfo::StyleInfo> configuredStyle = Themes::getConfiguredStyle(r); + + const boost::optional< ThemeInfo::StyleInfo > configuredStyle = Themes::getConfiguredStyle(r); reloadThemes(configuredStyle); loadCheckBox(qcbLocalUserVisible, r.bTalkingUI_LocalUserStaysVisible); @@ -219,7 +211,7 @@ void LookConfig::save() const { s.qsLanguage = QString(); else s.qsLanguage = qcbLanguage->itemData(qcbLanguage->currentIndex()).toString(); - + if (s.qsLanguage != oldLanguage) { s.requireRestartToApply = true; } @@ -235,47 +227,47 @@ void LookConfig::save() const { s.wlWindowLayout = Settings::LayoutCustom; } - s.ceExpand=static_cast<Settings::ChannelExpand>(qcbExpand->currentIndex()); - s.ceChannelDrag=static_cast<Settings::ChannelDrag>(qcbChannelDrag->currentIndex()); - s.ceUserDrag=static_cast<Settings::ChannelDrag>(qcbUserDrag->currentIndex()); - + s.ceExpand = static_cast< Settings::ChannelExpand >(qcbExpand->currentIndex()); + s.ceChannelDrag = static_cast< Settings::ChannelDrag >(qcbChannelDrag->currentIndex()); + s.ceUserDrag = static_cast< Settings::ChannelDrag >(qcbUserDrag->currentIndex()); + if (qcbUsersTop->isChecked() != s.bUserTop) { - s.bUserTop = qcbUsersTop->isChecked(); + s.bUserTop = qcbUsersTop->isChecked(); s.requireRestartToApply = true; } - - s.aotbAlwaysOnTop = static_cast<Settings::AlwaysOnTopBehaviour>(qcbAlwaysOnTop->currentIndex()); - s.bAskOnQuit = qcbAskOnQuit->isChecked(); - s.bEnableDeveloperMenu = qcbEnableDeveloperMenu->isChecked(); - s.bLockLayout = qcbLockLayout->isChecked(); - s.bHideInTray = qcbHideTray->isChecked(); - s.bStateInTray = qcbStateInTray->isChecked(); - s.bShowUserCount = qcbShowUserCount->isChecked(); - s.bShowVolumeAdjustments = qcbShowVolumeAdjustments->isChecked(); + + s.aotbAlwaysOnTop = static_cast< Settings::AlwaysOnTopBehaviour >(qcbAlwaysOnTop->currentIndex()); + s.bAskOnQuit = qcbAskOnQuit->isChecked(); + s.bEnableDeveloperMenu = qcbEnableDeveloperMenu->isChecked(); + s.bLockLayout = qcbLockLayout->isChecked(); + s.bHideInTray = qcbHideTray->isChecked(); + s.bStateInTray = qcbStateInTray->isChecked(); + s.bShowUserCount = qcbShowUserCount->isChecked(); + s.bShowVolumeAdjustments = qcbShowVolumeAdjustments->isChecked(); s.bShowContextMenuInMenuBar = qcbShowContextMenuInMenuBar->isChecked(); s.bShowTransmitModeComboBox = qcbShowTransmitModeComboBox->isChecked(); - s.bHighContrast = qcbHighContrast->isChecked(); - s.bChatBarUseSelection = qcbChatBarUseSelection->isChecked(); + s.bHighContrast = qcbHighContrast->isChecked(); + s.bChatBarUseSelection = qcbChatBarUseSelection->isChecked(); s.bFilterHidesEmptyChannels = qcbFilterHidesEmptyChannels->isChecked(); - + QVariant themeData = qcbTheme->itemData(qcbTheme->currentIndex()); if (themeData.isNull()) { Themes::setConfiguredStyle(s, boost::none, s.requireRestartToApply); } else { - Themes::setConfiguredStyle(s, themeData.value<ThemeInfo::StyleInfo>(), s.requireRestartToApply); + Themes::setConfiguredStyle(s, themeData.value< ThemeInfo::StyleInfo >(), s.requireRestartToApply); } - s.bTalkingUI_LocalUserStaysVisible = qcbLocalUserVisible->isChecked(); - s.bTalkingUI_AbbreviateChannelNames = qcbAbbreviateChannelNames->isChecked(); + s.bTalkingUI_LocalUserStaysVisible = qcbLocalUserVisible->isChecked(); + s.bTalkingUI_AbbreviateChannelNames = qcbAbbreviateChannelNames->isChecked(); s.bTalkingUI_AbbreviateCurrentChannel = qcbAbbreviateCurrentChannel->isChecked(); - s.bTalkingUI_ShowLocalListeners = qcbShowLocalListeners->isChecked(); - s.iTalkingUI_RelativeFontSize = qsbRelFontSize->value(); - s.iTalkingUI_SilentUserLifeTime = qsbSilentUserLifetime->value(); - s.iTalkingUI_ChannelHierarchyDepth = qsbChannelHierarchyDepth->value(); - s.iTalkingUI_MaxChannelNameLength = qsbMaxNameLength->value(); - s.iTalkingUI_PrefixCharCount = qsbPrefixCharCount->value(); - s.iTalkingUI_PostfixCharCount = qsbPostfixCharCount->value(); - s.qsTalkingUI_ChannelSeparator = qleChannelSeparator->text(); + s.bTalkingUI_ShowLocalListeners = qcbShowLocalListeners->isChecked(); + s.iTalkingUI_RelativeFontSize = qsbRelFontSize->value(); + s.iTalkingUI_SilentUserLifeTime = qsbSilentUserLifetime->value(); + s.iTalkingUI_ChannelHierarchyDepth = qsbChannelHierarchyDepth->value(); + s.iTalkingUI_MaxChannelNameLength = qsbMaxNameLength->value(); + s.iTalkingUI_PrefixCharCount = qsbPrefixCharCount->value(); + s.iTalkingUI_PostfixCharCount = qsbPostfixCharCount->value(); + s.qsTalkingUI_ChannelSeparator = qleChannelSeparator->text(); s.qsTalkingUI_AbbreviationReplacement = qleAbbreviationReplacement->text(); } @@ -289,7 +281,7 @@ void LookConfig::themeDirectoryChanged() { if (themeData.isNull()) { reloadThemes(boost::none); } else { - reloadThemes(themeData.value<ThemeInfo::StyleInfo>()); + reloadThemes(themeData.value< ThemeInfo::StyleInfo >()); } } diff --git a/src/mumble/LookConfig.h b/src/mumble/LookConfig.h index 901ac13e5..ef9a2f97e 100644 --- a/src/mumble/LookConfig.h +++ b/src/mumble/LookConfig.h @@ -15,31 +15,32 @@ class QFileSystemWatcher; class QTimer; class LookConfig : public ConfigWidget, Ui::LookConfig { - private: - Q_OBJECT - Q_DISABLE_COPY(LookConfig) - public: - /// The unique name of this ConfigWidget - static const QString name; - LookConfig(Settings &st); - virtual QString title() const Q_DECL_OVERRIDE; - virtual const QString &getName() const Q_DECL_OVERRIDE; - virtual QIcon icon() const Q_DECL_OVERRIDE; - - public slots: - void accept() const Q_DECL_OVERRIDE; - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; - void themeDirectoryChanged(); - void on_qcbAbbreviateChannelNames_stateChanged(int state); - private: - /// Reload themes combobox and select given configuredStyle in it - void reloadThemes(const boost::optional<ThemeInfo::StyleInfo> configuredStyle); - - /// Timer to prevent change event floods from triggering theme reloads - QTimer *m_themeDirectoryDebouncer; - /// Watcher to keep theme list up to date with user theme directory - QFileSystemWatcher* m_themeDirectoryWatcher; +private: + Q_OBJECT + Q_DISABLE_COPY(LookConfig) +public: + /// The unique name of this ConfigWidget + static const QString name; + LookConfig(Settings &st); + virtual QString title() const Q_DECL_OVERRIDE; + virtual const QString &getName() const Q_DECL_OVERRIDE; + virtual QIcon icon() const Q_DECL_OVERRIDE; + +public slots: + void accept() const Q_DECL_OVERRIDE; + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; + void themeDirectoryChanged(); + void on_qcbAbbreviateChannelNames_stateChanged(int state); + +private: + /// Reload themes combobox and select given configuredStyle in it + void reloadThemes(const boost::optional< ThemeInfo::StyleInfo > configuredStyle); + + /// Timer to prevent change event floods from triggering theme reloads + QTimer *m_themeDirectoryDebouncer; + /// Watcher to keep theme list up to date with user theme directory + QFileSystemWatcher *m_themeDirectoryWatcher; }; #endif diff --git a/src/mumble/MainWindow.cpp b/src/mumble/MainWindow.cpp index 44cc76da8..6491dcac3 100644 --- a/src/mumble/MainWindow.cpp +++ b/src/mumble/MainWindow.cpp @@ -5,62 +5,62 @@ #include "MainWindow.h" -#include "About.h" #include "ACL.h" #include "ACLEditor.h" +#include "About.h" #include "AudioInput.h" #include "AudioStats.h" #include "AudioWizard.h" #include "BanEditor.h" #include "CELTCodec.h" #ifdef USE_OPUS -# include "OpusCodec.h" +# include "OpusCodec.h" #endif #include "Cert.h" #include "Channel.h" -#include "Connection.h" #include "ConnectDialog.h" +#include "Connection.h" #include "Database.h" #include "DeveloperConsole.h" -#include "GlobalShortcut.h" #include "Log.h" #include "Net.h" #include "NetworkConfig.h" +#include "GlobalShortcut.h" #ifdef USE_OVERLAY - #include "OverlayClient.h" +# include "OverlayClient.h" #endif -#include "Plugins.h" +#include "../SignalCurry.h" +#include "ChannelListener.h" +#include "ListenerLocalVolumeDialog.h" +#include "Markdown.h" #include "PTTButtonWidget.h" +#include "Plugins.h" #include "RichTextEditor.h" +#include "SSLCipherInfo.h" +#include "Screen.h" #include "ServerHandler.h" +#include "Settings.h" +#include "SvgIcon.h" +#include "TalkingUI.h" #include "TextMessage.h" +#include "Themes.h" #include "Tokens.h" #include "User.h" #include "UserEdit.h" #include "UserInformation.h" -#include "UserModel.h" #include "UserLocalVolumeDialog.h" +#include "UserModel.h" +#include "Utils.h" #include "VersionCheck.h" #include "ViewCert.h" #include "VoiceRecorderDialog.h" -#include "../SignalCurry.h" -#include "Settings.h" -#include "Themes.h" -#include "SSLCipherInfo.h" -#include "Screen.h" -#include "SvgIcon.h" -#include "Utils.h" -#include "ListenerLocalVolumeDialog.h" -#include "ChannelListener.h" -#include "Markdown.h" -#include "TalkingUI.h" #ifdef Q_OS_WIN -# include "TaskList.h" +# include "TaskList.h" #endif #ifdef Q_OS_MAC -# include "AppNap.h" +# include "AppNap.h" #endif #include <QtCore/QStandardPaths> @@ -78,17 +78,18 @@ #include <QtWidgets/QWhatsThis> #ifdef Q_OS_WIN -# include <dbt.h> +# include <dbt.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -MessageBoxEvent::MessageBoxEvent(QString m) : QEvent(static_cast<QEvent::Type>(MB_QEVENT)) { +MessageBoxEvent::MessageBoxEvent(QString m) : QEvent(static_cast< QEvent::Type >(MB_QEVENT)) { msg = m; } -OpenURLEvent::OpenURLEvent(QUrl u) : QEvent(static_cast<QEvent::Type>(OU_QEVENT)) { +OpenURLEvent::OpenURLEvent(QUrl u) : QEvent(static_cast< QEvent::Type >(OU_QEVENT)) { url = u; } @@ -110,16 +111,14 @@ MainWindow::MainWindow(QWidget *p) : QMainWindow(p) { else SvgIcon::addSvgPixmapsToIcon(qiIcon, QLatin1String("skin:mumble.svg")); #else - { - SvgIcon::addSvgPixmapsToIcon(qiIcon, QLatin1String("skin:mumble.svg")); - } + { SvgIcon::addSvgPixmapsToIcon(qiIcon, QLatin1String("skin:mumble.svg")); } // Set application icon except on MacOSX, where the window-icon // shown in the title-bar usually serves as a draggable version of the // current open document (i.e. you can copy the open document anywhere // simply by dragging this icon). qApp->setWindowIcon(qiIcon); - + // Set the icon on the MainWindow directly. This fixes the icon not // being set on the MainWindow in certain environments (Ex: GTK+). setWindowIcon(qiIcon); @@ -129,14 +128,14 @@ MainWindow::MainWindow(QWidget *p) : QMainWindow(p) { uiNewHardware = 1; #endif bSuppressAskOnQuit = false; - restartOnQuit = false; - bAutoUnmute = false; + restartOnQuit = false; + bAutoUnmute = false; Channel::add(0, tr("Root")); - aclEdit = nullptr; - banEdit = nullptr; - userEdit = nullptr; + aclEdit = nullptr; + banEdit = nullptr; + userEdit = nullptr; tokenEdit = nullptr; voiceRecorderDialog = nullptr; @@ -148,8 +147,8 @@ MainWindow::MainWindow(QWidget *p) : QMainWindow(p) { qtReconnect->setSingleShot(true); qtReconnect->setObjectName(QLatin1String("Reconnect")); - qmUser = new QMenu(tr("&User"), this); - qmChannel = new QMenu(tr("&Channel"), this); + qmUser = new QMenu(tr("&User"), this); + qmChannel = new QMenu(tr("&Channel"), this); qmListener = new QMenu(tr("&Listener"), this); qmDeveloper = new QMenu(tr("&Developer"), this); @@ -175,7 +174,7 @@ MainWindow::MainWindow(QWidget *p) : QMainWindow(p) { // Explicitely add actions to mainwindow so their shortcuts are available // if only the main window is visible (e.g. minimal mode) - addActions(findChildren<QAction*>()); + addActions(findChildren< QAction * >()); on_qmServer_aboutToShow(); on_qmSelf_aboutToShow(); @@ -184,58 +183,64 @@ MainWindow::MainWindow(QWidget *p) : QMainWindow(p) { on_qmConfig_aboutToShow(); qmDeveloper->addAction(qaDeveloperConsole); - setOnTop(g.s.aotbAlwaysOnTop == Settings::OnTopAlways || - (g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInMinimal) || - (!g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInNormal)); + setOnTop(g.s.aotbAlwaysOnTop == Settings::OnTopAlways + || (g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInMinimal) + || (!g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInNormal)); } void MainWindow::createActions() { - int idx = 1; - gsPushTalk=new GlobalShortcut(this, idx++, tr("Push-to-Talk", "Global Shortcut")); + int idx = 1; + gsPushTalk = new GlobalShortcut(this, idx++, tr("Push-to-Talk", "Global Shortcut")); gsPushTalk->setObjectName(QLatin1String("PushToTalk")); - gsPushTalk->qsToolTip = tr("Push and hold this button to send voice.", "Global Shortcut"); - gsPushTalk->qsWhatsThis = tr("This configures the push-to-talk button, and as long as you hold this button down, you will transmit voice.", "Global Shortcut"); + gsPushTalk->qsToolTip = tr("Push and hold this button to send voice.", "Global Shortcut"); + gsPushTalk->qsWhatsThis = tr( + "This configures the push-to-talk button, and as long as you hold this button down, you will transmit voice.", + "Global Shortcut"); - gsResetAudio=new GlobalShortcut(this, idx++, tr("Reset Audio Processor", "Global Shortcut")); + gsResetAudio = new GlobalShortcut(this, idx++, tr("Reset Audio Processor", "Global Shortcut")); gsResetAudio->setObjectName(QLatin1String("ResetAudio")); - gsMuteSelf=new GlobalShortcut(this, idx++, tr("Mute Self", "Global Shortcut"), 0); + gsMuteSelf = new GlobalShortcut(this, idx++, tr("Mute Self", "Global Shortcut"), 0); gsMuteSelf->setObjectName(QLatin1String("gsMuteSelf")); gsMuteSelf->qsToolTip = tr("Set self-mute status.", "Global Shortcut"); - gsMuteSelf->qsWhatsThis = tr("This will set or toggle your muted status. If you turn this off, you will also disable self-deafen.", "Global Shortcut"); + gsMuteSelf->qsWhatsThis = + tr("This will set or toggle your muted status. If you turn this off, you will also disable self-deafen.", + "Global Shortcut"); - gsDeafSelf=new GlobalShortcut(this, idx++, tr("Deafen Self", "Global Shortcut"), 0); + gsDeafSelf = new GlobalShortcut(this, idx++, tr("Deafen Self", "Global Shortcut"), 0); gsDeafSelf->setObjectName(QLatin1String("gsDeafSelf")); gsDeafSelf->qsToolTip = tr("Set self-deafen status.", "Global Shortcut"); - gsDeafSelf->qsWhatsThis = tr("This will set or toggle your deafened status. If you turn this on, you will also enable self-mute.", "Global Shortcut"); + gsDeafSelf->qsWhatsThis = + tr("This will set or toggle your deafened status. If you turn this on, you will also enable self-mute.", + "Global Shortcut"); - gsUnlink=new GlobalShortcut(this, idx++, tr("Unlink Plugin", "Global Shortcut")); + gsUnlink = new GlobalShortcut(this, idx++, tr("Unlink Plugin", "Global Shortcut")); gsUnlink->setObjectName(QLatin1String("UnlinkPlugin")); - gsPushMute=new GlobalShortcut(this, idx++, tr("Push-to-Mute", "Global Shortcut")); + gsPushMute = new GlobalShortcut(this, idx++, tr("Push-to-Mute", "Global Shortcut")); gsPushMute->setObjectName(QLatin1String("PushToMute")); - gsJoinChannel=new GlobalShortcut(this, idx++, tr("Join Channel", "Global Shortcut")); + gsJoinChannel = new GlobalShortcut(this, idx++, tr("Join Channel", "Global Shortcut")); gsJoinChannel->setObjectName(QLatin1String("MetaChannel")); gsJoinChannel->qsToolTip = tr("Use in conjunction with Whisper to.", "Global Shortcut"); #ifdef USE_OVERLAY - gsToggleOverlay=new GlobalShortcut(this, idx++, tr("Toggle Overlay", "Global Shortcut")); + gsToggleOverlay = new GlobalShortcut(this, idx++, tr("Toggle Overlay", "Global Shortcut")); gsToggleOverlay->setObjectName(QLatin1String("ToggleOverlay")); - gsToggleOverlay->qsToolTip = tr("Toggle state of in-game overlay.", "Global Shortcut"); + gsToggleOverlay->qsToolTip = tr("Toggle state of in-game overlay.", "Global Shortcut"); gsToggleOverlay->qsWhatsThis = tr("This will switch the states of the in-game overlay.", "Global Shortcut"); connect(gsToggleOverlay, SIGNAL(down(QVariant)), g.o, SLOT(toggleShow())); #endif - gsMinimal=new GlobalShortcut(this, idx++, tr("Toggle Minimal", "Global Shortcut")); + gsMinimal = new GlobalShortcut(this, idx++, tr("Toggle Minimal", "Global Shortcut")); gsMinimal->setObjectName(QLatin1String("ToggleMinimal")); - gsVolumeUp=new GlobalShortcut(this, idx++, tr("Volume Up (+10%)", "Global Shortcut")); + gsVolumeUp = new GlobalShortcut(this, idx++, tr("Volume Up (+10%)", "Global Shortcut")); gsVolumeUp->setObjectName(QLatin1String("VolumeUp")); - gsVolumeDown=new GlobalShortcut(this, idx++, tr("Volume Down (-10%)", "Global Shortcut")); + gsVolumeDown = new GlobalShortcut(this, idx++, tr("Volume Down (-10%)", "Global Shortcut")); gsVolumeDown->setObjectName(QLatin1String("VolumeDown")); qstiIcon = new QSystemTrayIcon(qiIcon, this); @@ -245,35 +250,39 @@ void MainWindow::createActions() { gsWhisper = new GlobalShortcut(this, idx++, tr("Whisper/Shout"), QVariant::fromValue(ShortcutTarget())); gsWhisper->setObjectName(QLatin1String("gsWhisper")); - gsLinkChannel=new GlobalShortcut(this, idx++, tr("Link Channel", "Global Shortcut")); + gsLinkChannel = new GlobalShortcut(this, idx++, tr("Link Channel", "Global Shortcut")); gsLinkChannel->setObjectName(QLatin1String("MetaLink")); gsLinkChannel->qsToolTip = tr("Use in conjunction with Whisper to.", "Global Shortcut"); - gsCycleTransmitMode=new GlobalShortcut(this, idx++, tr("Cycle Transmit Mode", "Global Shortcut")); + gsCycleTransmitMode = new GlobalShortcut(this, idx++, tr("Cycle Transmit Mode", "Global Shortcut")); gsCycleTransmitMode->setObjectName(QLatin1String("gsCycleTransmitMode")); - gsTransmitModePushToTalk=new GlobalShortcut(this, idx++, tr("Set Transmit Mode to Push-To-Talk", "Global Shortcut")); + gsTransmitModePushToTalk = + new GlobalShortcut(this, idx++, tr("Set Transmit Mode to Push-To-Talk", "Global Shortcut")); gsTransmitModePushToTalk->setObjectName(QLatin1String("gsTransmitModePushToTalk")); - gsTransmitModeContinuous=new GlobalShortcut(this, idx++, tr("Set Transmit Mode to Continuous", "Global Shortcut")); + gsTransmitModeContinuous = + new GlobalShortcut(this, idx++, tr("Set Transmit Mode to Continuous", "Global Shortcut")); gsTransmitModeContinuous->setObjectName(QLatin1String("gsTransmitModeContinuous")); - gsTransmitModeVAD=new GlobalShortcut(this, idx++, tr("Set Transmit Mode to VAD", "Global Shortcut")); + gsTransmitModeVAD = new GlobalShortcut(this, idx++, tr("Set Transmit Mode to VAD", "Global Shortcut")); gsTransmitModeVAD->setObjectName(QLatin1String("gsTransmitModeVAD")); - gsSendTextMessage=new GlobalShortcut(this, idx++, tr("Send Text Message", "Global Shortcut"), QVariant(QString())); + gsSendTextMessage = + new GlobalShortcut(this, idx++, tr("Send Text Message", "Global Shortcut"), QVariant(QString())); gsSendTextMessage->setObjectName(QLatin1String("gsSendTextMessage")); - gsSendClipboardTextMessage=new GlobalShortcut(this, idx++, tr("Send Clipboard Text Message", "Global Shortcut")); + gsSendClipboardTextMessage = new GlobalShortcut(this, idx++, tr("Send Clipboard Text Message", "Global Shortcut")); gsSendClipboardTextMessage->setObjectName(QLatin1String("gsSendClipboardTextMessage")); - gsSendClipboardTextMessage->qsWhatsThis = tr("This will send your Clipboard content to the channel you are currently in.", "Global Shortcut"); + gsSendClipboardTextMessage->qsWhatsThis = + tr("This will send your Clipboard content to the channel you are currently in.", "Global Shortcut"); #ifndef Q_OS_MAC qstiIcon->show(); #endif } -void MainWindow::setupGui() { +void MainWindow::setupGui() { updateWindowTitle(); setCentralWidget(qtvUsers); setAcceptDrops(true); @@ -301,8 +310,9 @@ void MainWindow::setupGui() { qtvUsers->ensurePolished(); QObject::connect(this, &MainWindow::userAddedChannelListener, pmModel, &UserModel::addChannelListener); - QObject::connect(this, &MainWindow::userRemovedChannelListener, pmModel, - static_cast<void (UserModel::*)(const ClientUser *, const Channel *)>(&UserModel::removeChannelListener)); + QObject::connect( + this, &MainWindow::userRemovedChannelListener, pmModel, + static_cast< void (UserModel::*)(const ClientUser *, const Channel *) >(&UserModel::removeChannelListener)); qaAudioMute->setChecked(g.s.bMute); qaAudioDeaf->setChecked(g.s.bDeaf); @@ -326,7 +336,7 @@ void MainWindow::setupGui() { dtbLogDockTitle = new DockTitleBar(); qdwLog->setTitleBarWidget(dtbLogDockTitle); - foreach(QWidget *w, qdwLog->findChildren<QWidget *>()) { + foreach (QWidget *w, qdwLog->findChildren< QWidget * >()) { w->installEventFilter(dtbLogDockTitle); w->setMouseTracking(true); } @@ -350,9 +360,8 @@ void MainWindow::setupGui() { show(); #endif - connect(qtvUsers->selectionModel(), - SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), - SLOT(qtvUserCurrentChanged(const QModelIndex &, const QModelIndex &))); + connect(qtvUsers->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), + SLOT(qtvUserCurrentChanged(const QModelIndex &, const QModelIndex &))); // QtCreator and uic.exe do not allow adding arbitrary widgets // such as a MUComboBox to a QToolbar, even though they are supported. @@ -363,10 +372,9 @@ void MainWindow::setupGui() { qcbTransmitMode->addItem(tr("Push-to-Talk")); qaTransmitModeSeparator = qtIconToolbar->insertSeparator(qaConfigDialog); - qaTransmitMode = qtIconToolbar->insertWidget(qaTransmitModeSeparator, qcbTransmitMode); + qaTransmitMode = qtIconToolbar->insertWidget(qaTransmitModeSeparator, qcbTransmitMode); - connect(qcbTransmitMode, SIGNAL(activated(int)), - this, SLOT(qcbTransmitMode_activated(int))); + connect(qcbTransmitMode, SIGNAL(activated(int)), this, SLOT(qcbTransmitMode_activated(int))); updateTransmitModeComboBox(); @@ -374,14 +382,14 @@ void MainWindow::setupGui() { setupView(false); #endif - if (g.s.bMinimalView && ! g.s.qbaMinimalViewGeometry.isNull()) + if (g.s.bMinimalView && !g.s.qbaMinimalViewGeometry.isNull()) restoreGeometry(g.s.qbaMinimalViewGeometry); - else if (! g.s.bMinimalView && ! g.s.qbaMainWindowGeometry.isNull()) + else if (!g.s.bMinimalView && !g.s.qbaMainWindowGeometry.isNull()) restoreGeometry(g.s.qbaMainWindowGeometry); - if (g.s.bMinimalView && ! g.s.qbaMinimalViewState.isNull()) + if (g.s.bMinimalView && !g.s.qbaMinimalViewState.isNull()) restoreState(g.s.qbaMinimalViewState); - else if (! g.s.bMinimalView && ! g.s.qbaMainWindowState.isNull()) + else if (!g.s.bMinimalView && !g.s.qbaMainWindowState.isNull()) restoreState(g.s.qbaMainWindowState); setupView(false); @@ -443,13 +451,13 @@ MainWindow::~MainWindow() { } void MainWindow::msgBox(QString msg) { - MessageBoxEvent *mbe=new MessageBoxEvent(msg); + MessageBoxEvent *mbe = new MessageBoxEvent(msg); QApplication::postEvent(this, mbe); } #ifdef Q_OS_WIN bool MainWindow::nativeEvent(const QByteArray &, void *message, long *) { - MSG *msg = reinterpret_cast<MSG *>(message); + MSG *msg = reinterpret_cast< MSG * >(message); if (msg->message == WM_DEVICECHANGE && msg->wParam == DBT_DEVNODES_CHANGED) uiNewHardware++; @@ -461,10 +469,12 @@ void MainWindow::closeEvent(QCloseEvent *e) { #ifndef Q_OS_MAC ServerHandlerPtr sh = g.sh; if (sh && sh->isRunning() && g.s.bAskOnQuit && !bSuppressAskOnQuit) { - QMessageBox mb(QMessageBox::Warning, QLatin1String("Mumble"), tr("Mumble is currently connected to a server. Do you want to Close or Minimize it?"), QMessageBox::NoButton, this); - QPushButton *qpbClose = mb.addButton(tr("Close"), QMessageBox::YesRole); + QMessageBox mb(QMessageBox::Warning, QLatin1String("Mumble"), + tr("Mumble is currently connected to a server. Do you want to Close or Minimize it?"), + QMessageBox::NoButton, this); + QPushButton *qpbClose = mb.addButton(tr("Close"), QMessageBox::YesRole); QPushButton *qpbMinimize = mb.addButton(tr("Minimize"), QMessageBox::NoRole); - QPushButton *qpbCancel = mb.addButton(tr("Cancel"), QMessageBox::RejectRole); + QPushButton *qpbCancel = mb.addButton(tr("Cancel"), QMessageBox::RejectRole); mb.setDefaultButton(qpbClose); mb.setEscapeButton(qpbCancel); mb.exec(); @@ -482,11 +492,11 @@ void MainWindow::closeEvent(QCloseEvent *e) { if (g.s.bMinimalView) { g.s.qbaMinimalViewGeometry = saveGeometry(); - g.s.qbaMinimalViewState = saveState(); + g.s.qbaMinimalViewState = saveState(); } else { g.s.qbaMainWindowGeometry = saveGeometry(); - g.s.qbaMainWindowState = saveState(); - g.s.qbaHeaderState = qtvUsers->header()->saveState(); + g.s.qbaMainWindowState = saveState(); + g.s.qbaHeaderState = qtvUsers->header()->saveState(); } if (g.talkingUI && g.talkingUI->isVisible()) { @@ -504,7 +514,7 @@ void MainWindow::closeEvent(QCloseEvent *e) { g.bQuit = true; QMainWindow::closeEvent(e); - + qApp->exit(restartOnQuit ? MUMBLE_EXIT_CODE_RESTART : 0); } @@ -517,9 +527,9 @@ void MainWindow::hideEvent(QHideEvent *e) { } #endif #ifndef Q_OS_MAC -#ifdef Q_OS_UNIX - if (! qApp->activeModalWidget() && ! qApp->activePopupWidget()) -#endif +# ifdef Q_OS_UNIX + if (!qApp->activeModalWidget() && !qApp->activePopupWidget()) +# endif if (g.s.bHideInTray && qstiIcon->isSystemTrayAvailable() && e->spontaneous()) QMetaObject::invokeMethod(this, "hide", Qt::QueuedConnection); QMainWindow::hideEvent(e); @@ -528,9 +538,9 @@ void MainWindow::hideEvent(QHideEvent *e) { void MainWindow::showEvent(QShowEvent *e) { #ifndef Q_OS_MAC -#ifdef Q_OS_UNIX - if (! qApp->activeModalWidget() && ! qApp->activePopupWidget()) -#endif +# ifdef Q_OS_UNIX + if (!qApp->activeModalWidget() && !qApp->activePopupWidget()) +# endif if (g.s.bHideInTray && qstiIcon->isSystemTrayAvailable() && e->spontaneous()) QMetaObject::invokeMethod(this, "show", Qt::QueuedConnection); #endif @@ -581,7 +591,7 @@ void MainWindow::focusNextMainWidget() { qteChat, qtvUsers, }; - const int numMainFocusWidgets = sizeof(mainFocusWidgets)/sizeof(mainFocusWidgets[0]); + const int numMainFocusWidgets = sizeof(mainFocusWidgets) / sizeof(mainFocusWidgets[0]); int currentMainFocusWidgetIndex = -1; @@ -602,7 +612,7 @@ void MainWindow::focusNextMainWidget() { } void MainWindow::updateTrayIcon() { - ClientUser *p=ClientUser::get(g.uiSession); + ClientUser *p = ClientUser::get(g.uiSession); if (g.s.bDeaf) { qstiIcon->setIcon(qiIconDeafSelf); @@ -638,9 +648,8 @@ void MainWindow::updateTrayIcon() { } } -void MainWindow::updateUserModel() -{ - UserModel *um = static_cast<UserModel *>(qtvUsers->model()); +void MainWindow::updateUserModel() { + UserModel *um = static_cast< UserModel * >(qtvUsers->model()); um->toggleChannelFiltered(nullptr); // Force a UI refresh } @@ -688,13 +697,13 @@ bool MainWindow::handleSpecialContextMenu(const QUrl &url, const QPoint &pos_, b ClientUser *cu = pmModel->getUser(maybeUserHash); if (cu) { cuContextUser = cu; - ok = true; + ok = true; } } else { QByteArray qbaServerDigest = QByteArray::fromBase64(url.path().remove(0, 1).toLatin1()); - cuContextUser = ClientUser::get(url.host().toInt(&ok, 10)); - ServerHandlerPtr sh = g.sh; - ok = ok && sh && (qbaServerDigest == sh->qbaDigest); + cuContextUser = ClientUser::get(url.host().toInt(&ok, 10)); + ServerHandlerPtr sh = g.sh; + ok = ok && sh && (qbaServerDigest == sh->qbaDigest); } if (ok && cuContextUser) { if (focus) { @@ -709,9 +718,9 @@ bool MainWindow::handleSpecialContextMenu(const QUrl &url, const QPoint &pos_, b } else if (url.scheme() == QString::fromLatin1("channelid")) { bool ok; QByteArray qbaServerDigest = QByteArray::fromBase64(url.path().remove(0, 1).toLatin1()); - cContextChannel = Channel::get(url.host().toInt(&ok, 10)); - ServerHandlerPtr sh = g.sh; - ok = ok && sh && (qbaServerDigest == sh->qbaDigest); + cContextChannel = Channel::get(url.host().toInt(&ok, 10)); + ServerHandlerPtr sh = g.sh; + ok = ok && sh && (qbaServerDigest == sh->qbaDigest); if (ok) { if (focus) { qtvUsers->setCurrentIndex(pmModel->index(cContextChannel.data())); @@ -730,7 +739,7 @@ bool MainWindow::handleSpecialContextMenu(const QUrl &url, const QPoint &pos_, b void MainWindow::on_qtvUsers_customContextMenuRequested(const QPoint &mpos) { QModelIndex idx = qtvUsers->indexAt(mpos); - if (! idx.isValid()) + if (!idx.isValid()) idx = qtvUsers->currentIndex(); else qtvUsers->setCurrentIndex(idx); @@ -766,17 +775,21 @@ void MainWindow::on_qtvUsers_customContextMenuRequested(const QPoint &mpos) { void MainWindow::on_qteLog_customContextMenuRequested(const QPoint &mpos) { QString link = qteLog->anchorAt(mpos); - if (! link.isEmpty()) { + if (!link.isEmpty()) { QUrl l(link); if (handleSpecialContextMenu(l, qteLog->mapToGlobal(mpos))) return; } - QPoint contentPosition = QPoint(QApplication::isRightToLeft() ? (qteLog->horizontalScrollBar()->maximum() - qteLog->horizontalScrollBar()->value()) : qteLog->horizontalScrollBar()->value(), qteLog->verticalScrollBar()->value()); + QPoint contentPosition = + QPoint(QApplication::isRightToLeft() + ? (qteLog->horizontalScrollBar()->maximum() - qteLog->horizontalScrollBar()->value()) + : qteLog->horizontalScrollBar()->value(), + qteLog->verticalScrollBar()->value()); QMenu *menu = qteLog->createStandardContextMenu(mpos + contentPosition); - QTextCursor cursor = qteLog->cursorForPosition(mpos); + QTextCursor cursor = qteLog->cursorForPosition(mpos); QTextCharFormat fmt = cursor.charFormat(); // Work around imprecise cursor image identification @@ -805,17 +818,19 @@ void MainWindow::on_qteLog_customContextMenuRequested(const QPoint &mpos) { void MainWindow::saveImageAs() { QDateTime now = QDateTime::currentDateTime(); - QString defaultFname = QString::fromLatin1("Mumble-%1.jpg").arg(now.toString(QString::fromLatin1("yyyy-MM-dd-HHmmss"))); + QString defaultFname = + QString::fromLatin1("Mumble-%1.jpg").arg(now.toString(QString::fromLatin1("yyyy-MM-dd-HHmmss"))); - QString fname = QFileDialog::getSaveFileName(this, tr("Save Image File"), getImagePath(defaultFname), tr("Images (*.png *.jpg *.jpeg)")); + QString fname = QFileDialog::getSaveFileName(this, tr("Save Image File"), getImagePath(defaultFname), + tr("Images (*.png *.jpg *.jpeg)")); if (fname.isNull()) { return; } QString resName = qtcSaveImageCursor.charFormat().toImageFormat().name(); - QVariant res = qteLog->document()->resource(QTextDocument::ImageResource, resName); - QImage img = res.value<QImage>(); - bool ok = img.save(fname); + QVariant res = qteLog->document()->resource(QTextDocument::ImageResource, resName); + QImage img = res.value< QImage >(); + bool ok = img.save(fname); if (!ok) { // In case fname did not contain a file extension, try saving with an // explicit format. @@ -830,7 +845,7 @@ void MainWindow::saveImageAs() { } QString MainWindow::getImagePath(QString filename) const { - if (g.s.qsImagePath.isEmpty() || ! QDir(g.s.qsImagePath).exists()) { + if (g.s.qsImagePath.isEmpty() || !QDir(g.s.qsImagePath).exists()) { g.s.qsImagePath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); } if (filename.isEmpty()) { @@ -857,7 +872,7 @@ static void recreateServerHandler() { } g.sh.reset(); - while (sh && ! sh.unique()) + while (sh && !sh.unique()) QThread::yieldCurrentThread(); sh.reset(); @@ -865,8 +880,10 @@ static void recreateServerHandler() { sh->moveToThread(sh.get()); g.sh = sh; g.mw->connect(sh.get(), SIGNAL(connected()), g.mw, SLOT(serverConnected())); - g.mw->connect(sh.get(), SIGNAL(disconnected(QAbstractSocket::SocketError, QString)), g.mw, SLOT(serverDisconnected(QAbstractSocket::SocketError, QString))); - g.mw->connect(sh.get(), SIGNAL(error(QAbstractSocket::SocketError, QString)), g.mw, SLOT(resolverError(QAbstractSocket::SocketError, QString))); + g.mw->connect(sh.get(), SIGNAL(disconnected(QAbstractSocket::SocketError, QString)), g.mw, + SLOT(serverDisconnected(QAbstractSocket::SocketError, QString))); + g.mw->connect(sh.get(), SIGNAL(error(QAbstractSocket::SocketError, QString)), g.mw, + SLOT(resolverError(QAbstractSocket::SocketError, QString))); QObject::connect(sh.get(), &ServerHandler::disconnected, g.talkingUI, &TalkingUI::on_serverDisconnected); } @@ -875,7 +892,7 @@ void MainWindow::openUrl(const QUrl &url) { g.l->log(Log::Information, tr("Opening URL %1").arg(url.toString().toHtmlEscaped())); if (url.scheme() == QLatin1String("file")) { QFile f(url.toLocalFile()); - if (! f.exists() || ! f.open(QIODevice::ReadOnly)) { + if (!f.exists() || !f.open(QIODevice::ReadOnly)) { g.l->log(Log::Warning, tr("File does not exist")); return; } @@ -913,20 +930,21 @@ void MainWindow::openUrl(const QUrl &url) { QString version = query.queryItemValue(QLatin1String("version")); MumbleVersion::get(&major, &minor, &patch, version); - if ((major < 1) || // No pre 1.2.0 - (major == 1 && minor <= 1) || - (major > thismajor) || // No future version - (major == thismajor && minor > thisminor) || - (major == thismajor && minor == thisminor && patch > thispatch)) { - g.l->log(Log::Warning, tr("This version of Mumble can't handle URLs for Mumble version %1.%2.%3").arg(major).arg(minor).arg(patch)); + if ((major < 1) || // No pre 1.2.0 + (major == 1 && minor <= 1) || (major > thismajor) || // No future version + (major == thismajor && minor > thisminor) || (major == thismajor && minor == thisminor && patch > thispatch)) { + g.l->log(Log::Warning, tr("This version of Mumble can't handle URLs for Mumble version %1.%2.%3") + .arg(major) + .arg(minor) + .arg(patch)); return; } - QString host = url.host(); - unsigned short port = static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)); - QString user = url.userName(); - QString pw = url.password(); - qsDesiredChannel = url.path(); + QString host = url.host(); + unsigned short port = static_cast< unsigned short >(url.port(DEFAULT_MUMBLE_PORT)); + QString user = url.userName(); + QString pw = url.password(); + qsDesiredChannel = url.path(); QString name; if (query.hasQueryItem(QLatin1String("title"))) @@ -938,8 +956,8 @@ void MainWindow::openUrl(const QUrl &url) { g.sh->getConnectionInfo(oHost, oport, oUser, oPw); ClientUser *p = ClientUser::get(g.uiSession); - if ((user.isEmpty() || (p && p->iId >= 0) || (user == oUser)) && - (host.isEmpty() || ((host == oHost) && (port == oport)))) { + if ((user.isEmpty() || (p && p->iId >= 0) || (user == oUser)) + && (host.isEmpty() || ((host == oHost) && (port == oport)))) { findDesiredChannel(); return; } @@ -949,8 +967,9 @@ void MainWindow::openUrl(const QUrl &url) { if (user.isEmpty()) { bool ok; - user = QInputDialog::getText(this, tr("Connecting to %1").arg(url.toString()), tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok); - if (! ok || user.isEmpty()) + user = QInputDialog::getText(this, tr("Connecting to %1").arg(url.toString()), tr("Enter username"), + QLineEdit::Normal, g.s.qsUsername, &ok); + if (!ok || user.isEmpty()) return; g.s.qsUsername = user; } @@ -961,8 +980,8 @@ void MainWindow::openUrl(const QUrl &url) { recreateServerHandler(); g.s.qsLastServer = name; - rtLast = MumbleProto::Reject_RejectType_None; - bRetryServer = true; + rtLast = MumbleProto::Reject_RejectType_None; + bRetryServer = true; qaServerDisconnect->setEnabled(true); g.l->log(Log::Information, tr("Connecting to server %1.").arg(Log::msgColor(host.toHtmlEscaped(), Log::Server))); g.sh->setConnectionInfo(host, port, user, pw); @@ -975,10 +994,10 @@ void MainWindow::openUrl(const QUrl &url) { * @see void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) */ void MainWindow::findDesiredChannel() { - bool found = false; + bool found = false; QStringList qlChans = qsDesiredChannel.split(QLatin1String("/")); - Channel *chan = Channel::get(0); - QString str = QString(); + Channel *chan = Channel::get(0); + QString str = QString(); while (chan && qlChans.count() > 0) { QString elem = qlChans.takeFirst().toLower(); if (elem.isEmpty()) @@ -987,11 +1006,11 @@ void MainWindow::findDesiredChannel() { str = elem; else str = str + QLatin1String("/") + elem; - foreach(Channel *c, chan->qlChannels) { + foreach (Channel *c, chan->qlChannels) { if (c->qsName.toLower() == str) { - str = QString(); + str = QString(); found = true; - chan = c; + chan = c; break; } } @@ -1020,7 +1039,7 @@ void MainWindow::setOnTop(bool top) { } void MainWindow::setupView(bool toggle_minimize) { - bool showit = ! g.s.bMinimalView; + bool showit = !g.s.bMinimalView; switch (g.s.wlWindowLayout) { case Settings::LayoutClassic: @@ -1056,13 +1075,13 @@ void MainWindow::setupView(bool toggle_minimize) { QRect geom = frameGeometry(); if (toggle_minimize) { - if (! showit) { + if (!showit) { g.s.qbaMainWindowGeometry = saveGeometry(); - g.s.qbaMainWindowState = saveState(); - g.s.qbaHeaderState = qtvUsers->header()->saveState(); + g.s.qbaMainWindowState = saveState(); + g.s.qbaHeaderState = qtvUsers->header()->saveState(); } else { g.s.qbaMinimalViewGeometry = saveGeometry(); - g.s.qbaMinimalViewState = saveState(); + g.s.qbaMinimalViewState = saveState(); } } @@ -1072,19 +1091,19 @@ void MainWindow::setupView(bool toggle_minimize) { f |= Qt::FramelessWindowHint; } } - - if (g.s.aotbAlwaysOnTop == Settings::OnTopAlways || - (g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInMinimal) || - (!g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInNormal)) { + + if (g.s.aotbAlwaysOnTop == Settings::OnTopAlways + || (g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInMinimal) + || (!g.s.bMinimalView && g.s.aotbAlwaysOnTop == Settings::OnTopInNormal)) { f |= Qt::WindowStaysOnTopHint; } - if (! graphicsProxyWidget()) + if (!graphicsProxyWidget()) setWindowFlags(f); if (g.s.bShowContextMenuInMenuBar) { bool found = false; - foreach(QAction *a, menuBar()->actions()) { + foreach (QAction *a, menuBar()->actions()) { if (a == qmUser->menuAction()) { found = true; break; @@ -1102,7 +1121,7 @@ void MainWindow::setupView(bool toggle_minimize) { if (g.s.bEnableDeveloperMenu) { bool found = false; - foreach(QAction *a, menuBar()->actions()) { + foreach (QAction *a, menuBar()->actions()) { if (a == qmDeveloper->menuAction()) { found = true; break; @@ -1116,7 +1135,7 @@ void MainWindow::setupView(bool toggle_minimize) { menuBar()->removeAction(qmDeveloper->menuAction()); } - if (! showit) { + if (!showit) { qdwLog->setVisible(showit); qdwChat->setVisible(showit); qtIconToolbar->setVisible(showit); @@ -1124,21 +1143,21 @@ void MainWindow::setupView(bool toggle_minimize) { menuBar()->setVisible(showit); if (toggle_minimize) { - if (! showit) { - if (! g.s.qbaMinimalViewGeometry.isNull()) + if (!showit) { + if (!g.s.qbaMinimalViewGeometry.isNull()) restoreGeometry(g.s.qbaMinimalViewGeometry); - if (! g.s.qbaMinimalViewState.isNull()) + if (!g.s.qbaMinimalViewState.isNull()) restoreState(g.s.qbaMinimalViewState); } else { - if (! g.s.qbaMainWindowGeometry.isNull()) + if (!g.s.qbaMainWindowGeometry.isNull()) restoreGeometry(g.s.qbaMainWindowGeometry); - if (! g.s.qbaMainWindowState.isNull()) + if (!g.s.qbaMainWindowState.isNull()) restoreState(g.s.qbaMainWindowState); } } else { QRect newgeom = frameGeometry(); - resize(geometry().width()-newgeom.width()+geom.width(), - geometry().height()-newgeom.height()+geom.height()); + resize(geometry().width() - newgeom.width() + geom.width(), + geometry().height() - newgeom.height() + geom.height()); move(geom.x(), geom.y()); } @@ -1162,7 +1181,8 @@ void MainWindow::setupView(bool toggle_minimize) { } else { qwPTTButtonWidget = new PTTButtonWidget(); qwPTTButtonWidget->show(); - connect(qwPTTButtonWidget, SIGNAL(triggered(bool,QVariant)), SLOT(on_PushToTalk_triggered(bool,QVariant))); + connect(qwPTTButtonWidget, SIGNAL(triggered(bool, QVariant)), + SLOT(on_PushToTalk_triggered(bool, QVariant))); } } else { if (qwPTTButtonWidget) { @@ -1174,18 +1194,19 @@ void MainWindow::setupView(bool toggle_minimize) { void MainWindow::on_qaServerConnect_triggered(bool autoconnect) { ConnectDialog *cd = new ConnectDialog(this, autoconnect); - int res = cd->exec(); + int res = cd->exec(); - if (cd->qsServer.isEmpty() || (cd->usPort==0) || cd->qsUsername.isEmpty()) + if (cd->qsServer.isEmpty() || (cd->usPort == 0) || cd->qsUsername.isEmpty()) res = QDialog::Rejected; if (res == QDialog::Accepted) { recreateServerHandler(); qsDesiredChannel = QString(); - rtLast = MumbleProto::Reject_RejectType_None; - bRetryServer = true; + rtLast = MumbleProto::Reject_RejectType_None; + bRetryServer = true; qaServerDisconnect->setEnabled(true); - g.l->log(Log::Information, tr("Connecting to server %1.").arg(Log::msgColor(cd->qsServer.toHtmlEscaped(), Log::Server))); + g.l->log(Log::Information, + tr("Connecting to server %1.").arg(Log::msgColor(cd->qsServer.toHtmlEscaped(), Log::Server))); g.sh->setConnectionInfo(cd->qsServer, cd->usPort, cd->qsUsername, cd->qsPassword); g.sh->start(QThread::TimeCriticalPriority); } @@ -1205,9 +1226,10 @@ void MainWindow::on_qmSelf_aboutToShow() { qaServerTexture->setEnabled(user != nullptr); qaSelfComment->setEnabled(user != nullptr); - qaServerTextureRemove->setEnabled(user && ! user->qbaTextureHash.isEmpty()); + qaServerTextureRemove->setEnabled(user && !user->qbaTextureHash.isEmpty()); - qaSelfRegister->setEnabled(user && (user->iId < 0) && ! user->qsHash.isEmpty() && (g.pPermissions & (ChanACL::SelfRegister | ChanACL::Write))); + qaSelfRegister->setEnabled(user && (user->iId < 0) && !user->qsHash.isEmpty() + && (g.pPermissions & (ChanACL::SelfRegister | ChanACL::Write))); if (g.sh && g.sh->uiVersion >= 0x010203) { qaSelfPrioritySpeaker->setEnabled(user && g.pPermissions & (ChanACL::Write | ChanACL::MuteDeafen)); qaSelfPrioritySpeaker->setChecked(user && user->bPrioritySpeaker); @@ -1222,7 +1244,7 @@ void MainWindow::on_qaSelfComment_triggered() { if (!p) return; - if (! p->qbaCommentHash.isEmpty() && p->qsComment.isEmpty()) { + if (!p->qbaCommentHash.isEmpty() && p->qsComment.isEmpty()) { p->qsComment = QString::fromUtf8(g.db->blob(p->qbaCommentHash)); if (p->qsComment.isEmpty()) { pmModel->uiSessionComment = ~(p->uiSession); @@ -1249,7 +1271,7 @@ void MainWindow::on_qaSelfComment_triggered() { mpus.set_comment(u8(msg)); g.sh->sendMessage(mpus); - if (! msg.isEmpty()) + if (!msg.isEmpty()) g.db->setBlob(sha1(msg), msg.toUtf8()); } delete texm; @@ -1261,7 +1283,13 @@ void MainWindow::on_qaSelfRegister_triggered() { return; QMessageBox::StandardButton result; - result = QMessageBox::question(this, tr("Register yourself as %1").arg(p->qsName), tr("<p>You are about to register yourself on this server. This action cannot be undone, and your username cannot be changed once this is done. You will forever be known as '%1' on this server.</p><p>Are you sure you want to register yourself?</p>").arg(p->qsName.toHtmlEscaped()), QMessageBox::Yes|QMessageBox::No); + result = + QMessageBox::question(this, tr("Register yourself as %1").arg(p->qsName), + tr("<p>You are about to register yourself on this server. This action cannot be undone, " + "and your username cannot be changed once this is done. You will forever be known as " + "'%1' on this server.</p><p>Are you sure you want to register yourself?</p>") + .arg(p->qsName.toHtmlEscaped()), + QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::Yes) g.sh->registerUser(p->uiSession); @@ -1310,9 +1338,9 @@ void MainWindow::on_qmServer_aboutToShow() { qaServerInformation->setEnabled(g.uiSession != 0); qaServerTokens->setEnabled(g.uiSession != 0); - if (! qlServerActions.isEmpty()) { + if (!qlServerActions.isEmpty()) { qmServer->addSeparator(); - foreach(QAction *a, qlServerActions) + foreach (QAction *a, qlServerActions) qmServer->addAction(a); } } @@ -1350,8 +1378,8 @@ static const QString currentCodec() { if (g.bOpus) return QLatin1String("Opus"); - int v = g.bPreferAlpha ? g.iCodecAlpha : g.iCodecBeta; - CELTCodec* cc = g.qmCodecs.value(v); + int v = g.bPreferAlpha ? g.iCodecAlpha : g.iCodecBeta; + CELTCodec *cc = g.qmCodecs.value(v); if (cc) return QString::fromLatin1("CELT %1").arg(cc->version()); else @@ -1361,51 +1389,50 @@ static const QString currentCodec() { void MainWindow::on_qaServerInformation_triggered() { ConnectionPtr c = g.sh->cConnection; - if (! c) + if (!c) return; QSslCipher qsc = g.sh->qscCipher; - QString qsVersion=tr("<h2>Version</h2><p>Protocol %1</p>").arg(MumbleVersion::toString(g.sh->uiVersion)); + QString qsVersion = tr("<h2>Version</h2><p>Protocol %1</p>").arg(MumbleVersion::toString(g.sh->uiVersion)); if (g.sh->qsRelease.isEmpty() || g.sh->qsOS.isEmpty() || g.sh->qsOSVersion.isEmpty()) { qsVersion.append(tr("<p>No build information or OS version available</p>")); } else { - qsVersion.append(tr("<p>%1 (%2)<br />%3</p>") - .arg(g.sh->qsRelease.toHtmlEscaped(), g.sh->qsOS.toHtmlEscaped(), g.sh->qsOSVersion.toHtmlEscaped())); + qsVersion.append( + tr("<p>%1 (%2)<br />%3</p>") + .arg(g.sh->qsRelease.toHtmlEscaped(), g.sh->qsOS.toHtmlEscaped(), g.sh->qsOSVersion.toHtmlEscaped())); } QString host, uname, pw; unsigned short port; - g.sh->getConnectionInfo(host,port,uname,pw); + g.sh->getConnectionInfo(host, port, uname, pw); const SSLCipherInfo *ci = SSLCipherInfoLookupByOpenSSLName(qsc.name().toLatin1().constData()); - + QString cipherDescription; if (ci && ci->message_authentication && ci->encryption && ci->key_exchange_verbose && ci->rfc_name) { if (QString::fromLatin1(ci->message_authentication) == QLatin1String("AEAD")) { // Authenticated Encryption with Associated Data // See https://en.wikipedia.org/wiki/Authenticated_encryption - cipherDescription = tr( - "The connection is encrypted and authenticated " - "using %1 and uses %2 as the key exchange mechanism (%3)").arg( - QString::fromLatin1(ci->encryption), - QString::fromLatin1(ci->key_exchange_verbose), - QString::fromLatin1(ci->rfc_name)); + cipherDescription = + tr("The connection is encrypted and authenticated " + "using %1 and uses %2 as the key exchange mechanism (%3)") + .arg(QString::fromLatin1(ci->encryption), QString::fromLatin1(ci->key_exchange_verbose), + QString::fromLatin1(ci->rfc_name)); } else { - cipherDescription = tr( - "The connection is encrypted using %1, with %2 " - "for message authentication and %3 as the key " - "exchange mechanism (%4)").arg( - QString::fromLatin1(ci->encryption), - QString::fromLatin1(ci->message_authentication), - QString::fromLatin1(ci->key_exchange_verbose), - QString::fromLatin1(ci->rfc_name)); + cipherDescription = + tr("The connection is encrypted using %1, with %2 " + "for message authentication and %3 as the key " + "exchange mechanism (%4)") + .arg(QString::fromLatin1(ci->encryption), QString::fromLatin1(ci->message_authentication), + QString::fromLatin1(ci->key_exchange_verbose), QString::fromLatin1(ci->rfc_name)); } } if (cipherDescription.isEmpty()) { - cipherDescription = tr("The connection is secured by the cipher suite that OpenSSL identifies as %1").arg(qsc.name()); + cipherDescription = + tr("The connection is secured by the cipher suite that OpenSSL identifies as %1").arg(qsc.name()); } QString cipherPFSInfo; @@ -1417,20 +1444,17 @@ void MainWindow::on_qaServerInformation_triggered() { } } - QString qsControl = tr( - "<h2>Control channel</h2>" - "<p>The connection uses %1</p>" - "%2" - "%3" - "<p>%4 ms average latency (%5 deviation)</p>" - "<p>Remote host %6 (port %7)</p>").arg( - c->sessionProtocolString().toHtmlEscaped(), - cipherDescription, - cipherPFSInfo, - QString::fromLatin1("%1").arg(boost::accumulators::mean(g.sh->accTCP), 0, 'f', 2), - QString::fromLatin1("%1").arg(sqrt(boost::accumulators::variance(g.sh->accTCP)),0,'f',2), - host.toHtmlEscaped(), - QString::number(port)); + QString qsControl = + tr("<h2>Control channel</h2>" + "<p>The connection uses %1</p>" + "%2" + "%3" + "<p>%4 ms average latency (%5 deviation)</p>" + "<p>Remote host %6 (port %7)</p>") + .arg(c->sessionProtocolString().toHtmlEscaped(), cipherDescription, cipherPFSInfo, + QString::fromLatin1("%1").arg(boost::accumulators::mean(g.sh->accTCP), 0, 'f', 2), + QString::fromLatin1("%1").arg(sqrt(boost::accumulators::variance(g.sh->accTCP)), 0, 'f', 2), + host.toHtmlEscaped(), QString::number(port)); if (g.uiMaxUsers) { qsControl += tr("<p>Connected users: %1/%2</p>").arg(ModelItem::c_qhUsers.count()).arg(g.uiMaxUsers); } @@ -1440,25 +1464,44 @@ void MainWindow::on_qaServerInformation_triggered() { if (NetworkConfig::TcpModeEnabled()) { qsVoice = tr("Voice channel is sent over control channel"); } else { - qsVoice = tr("<h2>Voice channel</h2><p>Encrypted with 128 bit OCB-AES128<br />%1 ms average latency (%4 deviation)</p>").arg(boost::accumulators::mean(g.sh->accUDP), 0, 'f', 2).arg(sqrt(boost::accumulators::variance(g.sh->accUDP)),0,'f',2); + qsVoice = tr("<h2>Voice channel</h2><p>Encrypted with 128 bit OCB-AES128<br />%1 ms average latency (%4 " + "deviation)</p>") + .arg(boost::accumulators::mean(g.sh->accUDP), 0, 'f', 2) + .arg(sqrt(boost::accumulators::variance(g.sh->accUDP)), 0, 'f', 2); qsCrypt = QString::fromLatin1("<h2>%1</h2><table><tr><th></th><th>%2</th><th>%3</th></tr>" - "<tr><th>%4</th><td>%8</td><td>%12</td></tr>" - "<tr><th>%5</th><td>%9</td><td>%13</td></tr>" - "<tr><th>%6</th><td>%10</td><td>%14</td></tr>" - "<tr><th>%7</th><td>%11</td><td>%15</td></tr>" - "</table>") - .arg(tr("UDP Statistics")).arg(tr("To Server")).arg(tr("From Server")).arg(tr("Good")).arg(tr("Late")).arg(tr("Lost")).arg(tr("Resync")) - .arg(c->csCrypt->uiRemoteGood).arg(c->csCrypt->uiRemoteLate).arg(c->csCrypt->uiRemoteLost).arg(c->csCrypt->uiRemoteResync) - .arg(c->csCrypt->uiGood).arg(c->csCrypt->uiLate).arg(c->csCrypt->uiLost).arg(c->csCrypt->uiResync); - } - qsAudio=tr("<h2>Audio bandwidth</h2><p>Maximum %1 kbit/s<br />Current %2 kbit/s<br />Codec: %3</p>").arg(g.iMaxBandwidth / 1000.0,0,'f',1).arg(g.iAudioBandwidth / 1000.0,0,'f',1).arg(currentCodec()); - - QMessageBox qmb(QMessageBox::Information, tr("Mumble Server Information"), qsVersion + qsControl + qsVoice + qsCrypt + qsAudio, QMessageBox::Ok, this); + "<tr><th>%4</th><td>%8</td><td>%12</td></tr>" + "<tr><th>%5</th><td>%9</td><td>%13</td></tr>" + "<tr><th>%6</th><td>%10</td><td>%14</td></tr>" + "<tr><th>%7</th><td>%11</td><td>%15</td></tr>" + "</table>") + .arg(tr("UDP Statistics")) + .arg(tr("To Server")) + .arg(tr("From Server")) + .arg(tr("Good")) + .arg(tr("Late")) + .arg(tr("Lost")) + .arg(tr("Resync")) + .arg(c->csCrypt->uiRemoteGood) + .arg(c->csCrypt->uiRemoteLate) + .arg(c->csCrypt->uiRemoteLost) + .arg(c->csCrypt->uiRemoteResync) + .arg(c->csCrypt->uiGood) + .arg(c->csCrypt->uiLate) + .arg(c->csCrypt->uiLost) + .arg(c->csCrypt->uiResync); + } + qsAudio = tr("<h2>Audio bandwidth</h2><p>Maximum %1 kbit/s<br />Current %2 kbit/s<br />Codec: %3</p>") + .arg(g.iMaxBandwidth / 1000.0, 0, 'f', 1) + .arg(g.iAudioBandwidth / 1000.0, 0, 'f', 1) + .arg(currentCodec()); + + QMessageBox qmb(QMessageBox::Information, tr("Mumble Server Information"), + qsVersion + qsControl + qsVoice + qsCrypt + qsAudio, QMessageBox::Ok, this); qmb.setDefaultButton(QMessageBox::Ok); qmb.setEscapeButton(QMessageBox::Ok); QPushButton *qp = qmb.addButton(tr("&View Certificate"), QMessageBox::ActionRole); - int res = qmb.exec(); + int res = qmb.exec(); if ((res == 0) && (qmb.clickedButton() == qp)) { ViewCert vc(g.sh->qscCert, this); vc.exec(); @@ -1466,7 +1509,7 @@ void MainWindow::on_qaServerInformation_triggered() { } void MainWindow::on_qaServerTexture_triggered() { - QPair<QByteArray, QImage> choice = openImageFile(); + QPair< QByteArray, QImage > choice = openImageFile(); if (choice.first.isEmpty()) return; @@ -1500,10 +1543,10 @@ void MainWindow::qmUser_aboutToShow() { ClientUser *p = nullptr; if (g.uiSession != 0) { QModelIndex idx; - if (! qpContextPosition.isNull()) + if (!qpContextPosition.isNull()) idx = qtvUsers->indexAt(qpContextPosition); - if (! idx.isValid()) + if (!idx.isValid()) idx = qtvUsers->currentIndex(); p = pmModel->getUser(idx); @@ -1512,11 +1555,11 @@ void MainWindow::qmUser_aboutToShow() { p = cuContextUser.data(); } - cuContextUser = p; + cuContextUser = p; qpContextPosition = QPoint(); const ClientUser *self = ClientUser::get(g.uiSession); - bool isSelf = p == self; + bool isSelf = p == self; qmUser->clear(); @@ -1553,12 +1596,13 @@ void MainWindow::qmUser_aboutToShow() { if (g.sh && g.sh->uiVersion >= 0x010202) qmUser->addAction(qaUserInformation); - if (p && (p->iId < 0) && ! p->qsHash.isEmpty() && (g.pPermissions & ((isSelf ? ChanACL::SelfRegister : ChanACL::Register) | ChanACL::Write))) { + if (p && (p->iId < 0) && !p->qsHash.isEmpty() + && (g.pPermissions & ((isSelf ? ChanACL::SelfRegister : ChanACL::Register) | ChanACL::Write))) { qmUser->addSeparator(); qmUser->addAction(qaUserRegister); } - if (p && ! p->qsHash.isEmpty() && (!p->qsFriendName.isEmpty() || (p->uiSession != g.uiSession))) { + if (p && !p->qsHash.isEmpty() && (!p->qsFriendName.isEmpty() || (p->uiSession != g.uiSession))) { qmUser->addSeparator(); if (p->qsFriendName.isEmpty()) qmUser->addAction(qaUserFriendAdd); @@ -1585,13 +1629,13 @@ void MainWindow::qmUser_aboutToShow() { } #endif - if (! qlUserActions.isEmpty()) { + if (!qlUserActions.isEmpty()) { qmUser->addSeparator(); - foreach(QAction *a, qlUserActions) + foreach (QAction *a, qlUserActions) qmUser->addAction(a); } - if (! p) { + if (!p) { qaUserKick->setEnabled(false); qaUserBan->setEnabled(false); qaUserTextMessage->setEnabled(false); @@ -1603,22 +1647,27 @@ void MainWindow::qmUser_aboutToShow() { qaUserTextureReset->setEnabled(false); qaUserCommentView->setEnabled(false); } else { - qaUserKick->setEnabled(! isSelf); - qaUserBan->setEnabled(! isSelf); + qaUserKick->setEnabled(!isSelf); + qaUserBan->setEnabled(!isSelf); qaUserTextMessage->setEnabled(true); - qaUserLocalMute->setEnabled(! isSelf); - qaUserLocalVolume->setEnabled(! isSelf); - qaUserLocalIgnore->setEnabled(! isSelf); - qaUserLocalIgnoreTTS->setEnabled(! isSelf); - // If the server's version is less than 1.4.0 it won't support the new permission to reset a comment/avatar, so fall back to the old method + qaUserLocalMute->setEnabled(!isSelf); + qaUserLocalVolume->setEnabled(!isSelf); + qaUserLocalIgnore->setEnabled(!isSelf); + qaUserLocalIgnoreTTS->setEnabled(!isSelf); + // If the server's version is less than 1.4.0 it won't support the new permission to reset a comment/avatar, so + // fall back to the old method if (g.sh->uiVersion < 0x010400) { - qaUserCommentReset->setEnabled(! p->qbaCommentHash.isEmpty() && (g.pPermissions & (ChanACL::Move | ChanACL::Write))); - qaUserTextureReset->setEnabled(! p->qbaTextureHash.isEmpty() && (g.pPermissions & (ChanACL::Move | ChanACL::Write))); + qaUserCommentReset->setEnabled(!p->qbaCommentHash.isEmpty() + && (g.pPermissions & (ChanACL::Move | ChanACL::Write))); + qaUserTextureReset->setEnabled(!p->qbaTextureHash.isEmpty() + && (g.pPermissions & (ChanACL::Move | ChanACL::Write))); } else { - qaUserCommentReset->setEnabled(! p->qbaCommentHash.isEmpty() && (g.pPermissions & (ChanACL::ResetUserContent | ChanACL::Write))); - qaUserTextureReset->setEnabled(! p->qbaTextureHash.isEmpty() && (g.pPermissions & (ChanACL::ResetUserContent | ChanACL::Write))); + qaUserCommentReset->setEnabled(!p->qbaCommentHash.isEmpty() + && (g.pPermissions & (ChanACL::ResetUserContent | ChanACL::Write))); + qaUserTextureReset->setEnabled(!p->qbaTextureHash.isEmpty() + && (g.pPermissions & (ChanACL::ResetUserContent | ChanACL::Write))); } - qaUserCommentView->setEnabled(! p->qbaCommentHash.isEmpty()); + qaUserCommentView->setEnabled(!p->qbaCommentHash.isEmpty()); qaUserMute->setChecked(p->bMute || p->bSuppress); qaUserDeaf->setChecked(p->bDeaf); @@ -1634,10 +1683,10 @@ void MainWindow::qmListener_aboutToShow() { ClientUser *p = nullptr; if (g.uiSession != 0) { QModelIndex idx; - if (! qpContextPosition.isNull()) + if (!qpContextPosition.isNull()) idx = qtvUsers->indexAt(qpContextPosition); - if (! idx.isValid()) + if (!idx.isValid()) idx = qtvUsers->currentIndex(); p = pmModel->getUser(idx); @@ -1646,7 +1695,7 @@ void MainWindow::qmListener_aboutToShow() { p = cuContextUser.data(); } - cuContextUser = p; + cuContextUser = p; qpContextPosition = QPoint(); bool self = p && (p->uiSession == g.uiSession); @@ -1691,7 +1740,7 @@ void MainWindow::on_qaUserLocalMute_triggered() { bool muted = qaUserLocalMute->isChecked(); p->setLocalMute(muted); - if (! p->qsHash.isEmpty()) { + if (!p->qsHash.isEmpty()) { g.db->setLocalMuted(p->qsHash, muted); } else { logChangeNotPermanent(QObject::tr("Local Mute"), p); @@ -1707,7 +1756,7 @@ void MainWindow::on_qaUserLocalIgnore_triggered() { bool ignored = qaUserLocalIgnore->isChecked(); p->setLocalIgnore(ignored); - if (! p->qsHash.isEmpty()) { + if (!p->qsHash.isEmpty()) { g.db->setLocalIgnored(p->qsHash, ignored); } else { logChangeNotPermanent(QObject::tr("Ignore Messages"), p); @@ -1723,7 +1772,7 @@ void MainWindow::on_qaUserLocalIgnoreTTS_triggered() { bool ignoredTTS = qaUserLocalIgnoreTTS->isChecked(); p->setLocalIgnoreTTS(ignoredTTS); - if (! p->qsHash.isEmpty()) { + if (!p->qsHash.isEmpty()) { g.db->setLocalIgnoredTTS(p->qsHash, ignoredTTS); } else { logChangeNotPermanent(QObject::tr("Disable Text-To-Speech"), p); @@ -1750,7 +1799,7 @@ void MainWindow::on_qaUserDeaf_triggered() { MumbleProto::UserState mpus; mpus.set_session(p->uiSession); - mpus.set_deaf(! p->bDeaf); + mpus.set_deaf(!p->bDeaf); g.sh->sendMessage(mpus); } @@ -1761,7 +1810,7 @@ void MainWindow::on_qaSelfPrioritySpeaker_triggered() { MumbleProto::UserState mpus; mpus.set_session(p->uiSession); - mpus.set_priority_speaker(! p->bPrioritySpeaker); + mpus.set_priority_speaker(!p->bPrioritySpeaker); g.sh->sendMessage(mpus); } @@ -1772,7 +1821,7 @@ void MainWindow::on_qaUserPrioritySpeaker_triggered() { MumbleProto::UserState mpus; mpus.set_session(p->uiSession); - mpus.set_priority_speaker(! p->bPrioritySpeaker); + mpus.set_priority_speaker(!p->bPrioritySpeaker); g.sh->sendMessage(mpus); } @@ -1786,13 +1835,26 @@ void MainWindow::on_qaUserRegister_triggered() { QMessageBox::StandardButton result; if (session == g.uiSession) - result = QMessageBox::question(this, tr("Register yourself as %1").arg(p->qsName), tr("<p>You are about to register yourself on this server. This action cannot be undone, and your username cannot be changed once this is done. You will forever be known as '%1' on this server.</p><p>Are you sure you want to register yourself?</p>").arg(p->qsName.toHtmlEscaped()), QMessageBox::Yes|QMessageBox::No); + result = QMessageBox::question( + this, tr("Register yourself as %1").arg(p->qsName), + tr("<p>You are about to register yourself on this server. This action cannot be undone, and your username " + "cannot be changed once this is done. You will forever be known as '%1' on this server.</p><p>Are you " + "sure you want to register yourself?</p>") + .arg(p->qsName.toHtmlEscaped()), + QMessageBox::Yes | QMessageBox::No); else - result = QMessageBox::question(this, tr("Register user %1").arg(p->qsName), tr("<p>You are about to register %1 on the server. This action cannot be undone, the username cannot be changed, and as a registered user, %1 will have access to the server even if you change the server password.</p><p>From this point on, %1 will be authenticated with the certificate currently in use.</p><p>Are you sure you want to register %1?</p>").arg(p->qsName.toHtmlEscaped()), QMessageBox::Yes|QMessageBox::No); + result = QMessageBox::question( + this, tr("Register user %1").arg(p->qsName), + tr("<p>You are about to register %1 on the server. This action cannot be undone, the username cannot be " + "changed, and as a registered user, %1 will have access to the server even if you change the server " + "password.</p><p>From this point on, %1 will be authenticated with the certificate currently in " + "use.</p><p>Are you sure you want to register %1?</p>") + .arg(p->qsName.toHtmlEscaped()), + QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::Yes) { p = ClientUser::get(session); - if (! p) + if (!p) return; g.sh->registerUser(p->uiSession); } @@ -1828,7 +1890,8 @@ void MainWindow::on_qaUserKick_triggered() { unsigned int session = p->uiSession; bool ok; - QString reason = QInputDialog::getText(this, tr("Kicking user %1").arg(p->qsName), tr("Enter reason"), QLineEdit::Normal, QString(), &ok); + QString reason = QInputDialog::getText(this, tr("Kicking user %1").arg(p->qsName), tr("Enter reason"), + QLineEdit::Normal, QString(), &ok); p = ClientUser::get(session); if (!p) @@ -1847,8 +1910,9 @@ void MainWindow::on_qaUserBan_triggered() { unsigned int session = p->uiSession; bool ok; - QString reason = QInputDialog::getText(this, tr("Banning user %1").arg(p->qsName), tr("Enter reason"), QLineEdit::Normal, QString(), &ok); - p = ClientUser::get(session); + QString reason = QInputDialog::getText(this, tr("Banning user %1").arg(p->qsName), tr("Enter reason"), + QLineEdit::Normal, QString(), &ok); + p = ClientUser::get(session); if (!p) return; @@ -1870,7 +1934,7 @@ void MainWindow::openTextMessageDialog(ClientUser *p) { unsigned int session = p->uiSession; ::TextMessage *texm = new ::TextMessage(this, tr("Sending message to %1").arg(p->qsName)); - int res = texm->exec(); + int res = texm->exec(); // Try to get find the user using the session id. // This will return nullptr if the user disconnected while typing the message. @@ -1879,9 +1943,10 @@ void MainWindow::openTextMessageDialog(ClientUser *p) { if (p && (res == QDialog::Accepted)) { QString msg = texm->message(); - if (! msg.isEmpty()) { + if (!msg.isEmpty()) { g.sh->sendUserTextMessage(p->uiSession, msg); - g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatClientUser(p, Log::Target), texm->message()), tr("Message to %1").arg(p->qsName), true); + g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatClientUser(p, Log::Target), texm->message()), + tr("Message to %1").arg(p->qsName), true); } } delete texm; @@ -1895,7 +1960,7 @@ void MainWindow::on_qaUserCommentView_triggered() { if (!p) return; - if (! p->qbaCommentHash.isEmpty() && p->qsComment.isEmpty()) { + if (!p->qbaCommentHash.isEmpty() && p->qsComment.isEmpty()) { p->qsComment = QString::fromUtf8(g.db->blob(p->qbaCommentHash)); if (p->qsComment.isEmpty()) { pmModel->uiSessionComment = ~(p->uiSession); @@ -1923,9 +1988,10 @@ void MainWindow::on_qaUserCommentReset_triggered() { unsigned int session = p->uiSession; - int ret = QMessageBox::question(this, QLatin1String("Mumble"), - tr("Are you sure you want to reset the comment of user %1?").arg(p->qsName.toHtmlEscaped()), - QMessageBox::Yes, QMessageBox::No); + int ret = QMessageBox::question( + this, QLatin1String("Mumble"), + tr("Are you sure you want to reset the comment of user %1?").arg(p->qsName.toHtmlEscaped()), QMessageBox::Yes, + QMessageBox::No); if (ret == QMessageBox::Yes) { g.sh->setUserComment(session, QString()); } @@ -1939,9 +2005,10 @@ void MainWindow::on_qaUserTextureReset_triggered() { unsigned int session = p->uiSession; - int ret = QMessageBox::question(this, QLatin1String("Mumble"), - tr("Are you sure you want to reset the avatar of user %1?").arg(p->qsName.toHtmlEscaped()), - QMessageBox::Yes, QMessageBox::No); + int ret = QMessageBox::question( + this, QLatin1String("Mumble"), + tr("Are you sure you want to reset the avatar of user %1?").arg(p->qsName.toHtmlEscaped()), QMessageBox::Yes, + QMessageBox::No); if (ret == QMessageBox::Yes) { g.sh->setUserTexture(session, QByteArray()); } @@ -1974,10 +2041,11 @@ void MainWindow::sendChatbarText(QString qsText) { } void MainWindow::sendChatbarMessage(QString qsMessage) { - if (g.uiSession == 0) return; // Check if text & connection is available + if (g.uiSession == 0) + return; // Check if text & connection is available ClientUser *p = pmModel->getUser(qtvUsers->currentIndex()); - Channel *c = pmModel->getChannel(qtvUsers->currentIndex()); + Channel *c = pmModel->getChannel(qtvUsers->currentIndex()); if (!g.s.bChatBarUseSelection || !p || p->uiSession == g.uiSession) { // Channel message @@ -1985,11 +2053,13 @@ void MainWindow::sendChatbarMessage(QString qsMessage) { c = ClientUser::get(g.uiSession)->cChannel; g.sh->sendChannelTextMessage(c->iId, qsMessage, false); - g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatChannel(c), qsMessage), tr("Message to channel %1").arg(c->qsName), true); + g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatChannel(c), qsMessage), + tr("Message to channel %1").arg(c->qsName), true); } else { // User message g.sh->sendUserTextMessage(p->uiSession, qsMessage); - g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatClientUser(p, Log::Target), qsMessage), tr("Message to %1").arg(p->qsName), true); + g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatClientUser(p, Log::Target), qsMessage), + tr("Message to %1").arg(p->qsName), true); } } @@ -2014,13 +2084,14 @@ void MainWindow::on_qteChat_backtabPressed() { */ void MainWindow::on_qteChat_ctrlSpacePressed() { unsigned int res = qteChat->completeAtCursor(); - if (res == 0) return; + if (res == 0) + return; qtvUsers->setCurrentIndex(pmModel->index(ClientUser::get(res))); } void MainWindow::on_qmConfig_aboutToShow() { // Don't remove the config, as that messes up OSX. - foreach(QAction *a, qmConfig->actions()) + foreach (QAction *a, qmConfig->actions()) if (a != qaConfigDialog) qmConfig->removeAction(a); qmConfig->addAction(qaAudioWizard); @@ -2043,10 +2114,10 @@ void MainWindow::qmChannel_aboutToShow() { Channel *c = nullptr; if (g.uiSession != 0) { QModelIndex idx; - if (! qpContextPosition.isNull()) + if (!qpContextPosition.isNull()) idx = qtvUsers->indexAt(qpContextPosition); - if (! idx.isValid()) + if (!idx.isValid()) idx = qtvUsers->currentIndex(); c = pmModel->getChannel(idx); @@ -2055,7 +2126,7 @@ void MainWindow::qmChannel_aboutToShow() { c = cContextChannel.data(); } - cContextChannel = c; + cContextChannel = c; qpContextPosition = QPoint(); if (c && c->iId != ClientUser::get(g.uiSession)->cChannel->iId) { @@ -2085,7 +2156,7 @@ void MainWindow::qmChannel_aboutToShow() { qmChannel->addAction(qaChannelSendMessage); // hiding the root is nonsense - if(c && c->cParent) { + if (c && c->cParent) { qmChannel->addSeparator(); qmChannel->addAction(qaChannelFilter); } @@ -2100,9 +2171,9 @@ void MainWindow::qmChannel_aboutToShow() { } #endif - if (! qlChannelActions.isEmpty()) { + if (!qlChannelActions.isEmpty()) { qmChannel->addSeparator(); - foreach(QAction *a, qlChannelActions) + foreach (QAction *a, qlChannelActions) qmChannel->addAction(a); } @@ -2119,7 +2190,7 @@ void MainWindow::qmChannel_aboutToShow() { if (c && c->iId != 0) { remove = true; } - if (! c) + if (!c) c = Channel::get(0); unlinkall = (home->qhLinks.count() > 0); if (home != c) { @@ -2130,7 +2201,7 @@ void MainWindow::qmChannel_aboutToShow() { } } - if(c) + if (c) qaChannelFilter->setChecked(c->bFiltered); qaChannelAdd->setEnabled(add); @@ -2177,9 +2248,9 @@ void MainWindow::on_qaChannelListen_triggered() { void MainWindow::on_qaChannelFilter_triggered() { Channel *c = getContextMenuChannel(); - + if (c) { - UserModel *um = static_cast<UserModel *>(qtvUsers->model()); + UserModel *um = static_cast< UserModel * >(qtvUsers->model()); um->toggleChannelFiltered(c); } } @@ -2204,12 +2275,15 @@ void MainWindow::on_qaChannelAdd_triggered() { void MainWindow::on_qaChannelRemove_triggered() { int ret; Channel *c = getContextMenuChannel(); - if (! c) + if (!c) return; int id = c->iId; - ret=QMessageBox::question(this, QLatin1String("Mumble"), tr("Are you sure you want to delete %1 and all its sub-channels?").arg(c->qsName.toHtmlEscaped()), QMessageBox::Yes, QMessageBox::No); + ret = QMessageBox::question( + this, QLatin1String("Mumble"), + tr("Are you sure you want to delete %1 and all its sub-channels?").arg(c->qsName.toHtmlEscaped()), + QMessageBox::Yes, QMessageBox::No); c = Channel::get(id); if (!c) @@ -2222,11 +2296,11 @@ void MainWindow::on_qaChannelRemove_triggered() { void MainWindow::on_qaChannelACL_triggered() { Channel *c = getContextMenuChannel(); - if (! c) + if (!c) c = Channel::get(0); int id = c->iId; - if (! c->qbaDescHash.isEmpty() && c->qsDesc.isEmpty()) { + if (!c->qbaDescHash.isEmpty() && c->qsDesc.isEmpty()) { c->qsDesc = QString::fromUtf8(g.db->blob(c->qbaDescHash)); if (c->qsDesc.isEmpty()) { MumbleProto::RequestBlob mprb; @@ -2247,7 +2321,7 @@ void MainWindow::on_qaChannelACL_triggered() { void MainWindow::on_qaChannelLink_triggered() { Channel *c = ClientUser::get(g.uiSession)->cChannel; Channel *l = getContextMenuChannel(); - if (! l) + if (!l) l = Channel::get(0); g.sh->addChannelLink(c->iId, l->iId); @@ -2256,7 +2330,7 @@ void MainWindow::on_qaChannelLink_triggered() { void MainWindow::on_qaChannelUnlink_triggered() { Channel *c = ClientUser::get(g.uiSession)->cChannel; Channel *l = getContextMenuChannel(); - if (! l) + if (!l) l = Channel::get(0); g.sh->removeChannelLink(c->iId, l->iId); @@ -2267,7 +2341,7 @@ void MainWindow::on_qaChannelUnlinkAll_triggered() { MumbleProto::ChannelState mpcs; mpcs.set_channel_id(c->iId); - foreach(Channel *l, c->qsPermLinks) + foreach (Channel *l, c->qsPermLinks) mpcs.add_links_remove(l->iId); g.sh->sendMessage(mpcs); } @@ -2281,17 +2355,19 @@ void MainWindow::on_qaChannelSendMessage_triggered() { int id = c->iId; ::TextMessage *texm = new ::TextMessage(this, tr("Sending message to channel %1").arg(c->qsName), true); - int res = texm->exec(); + int res = texm->exec(); c = Channel::get(id); - if (c && (res==QDialog::Accepted)) { + if (c && (res == QDialog::Accepted)) { g.sh->sendChannelTextMessage(id, texm->message(), texm->bTreeMessage); if (texm->bTreeMessage) - g.l->log(Log::TextMessage, tr("To %1 (Tree): %2").arg(Log::formatChannel(c), texm->message()), tr("Message to tree %1").arg(c->qsName), true); + g.l->log(Log::TextMessage, tr("To %1 (Tree): %2").arg(Log::formatChannel(c), texm->message()), + tr("Message to tree %1").arg(c->qsName), true); else - g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatChannel(c), texm->message()), tr("Message to channel %1").arg(c->qsName), true); + g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatChannel(c), texm->message()), + tr("Message to channel %1").arg(c->qsName), true); } delete texm; } @@ -2312,7 +2388,8 @@ void MainWindow::on_qaChannelCopyURL_triggered() { c = c->cParent; } - QApplication::clipboard()->setMimeData(ServerItem::toMimeData(c->qsName, host, port, channel), QClipboard::Clipboard); + QApplication::clipboard()->setMimeData(ServerItem::toMimeData(c->qsName, host, port, channel), + QClipboard::Clipboard); } void MainWindow::on_qaListenerLocalVolume_triggered() { @@ -2323,7 +2400,7 @@ void MainWindow::on_qaListenerLocalVolume_triggered() { return; } - ListenerLocalVolumeDialog dialog(user, channel); + ListenerLocalVolumeDialog dialog(user, channel); dialog.exec(); } @@ -2335,7 +2412,7 @@ void MainWindow::on_qaListenerLocalVolume_triggered() { */ void MainWindow::updateMenuPermissions() { ClientUser *cu = nullptr; - Channel *c = nullptr; + Channel *c = nullptr; if (g.uiSession) { cu = getContextMenuUser(); @@ -2347,9 +2424,9 @@ void MainWindow::updateMenuPermissions() { c = pmModel->getChannel(qtvUsers->currentIndex()); } - ChanACL::Permissions p = c ? static_cast<ChanACL::Permissions>(c->uiPermissions) : ChanACL::None; + ChanACL::Permissions p = c ? static_cast< ChanACL::Permissions >(c->uiPermissions) : ChanACL::None; - if (c && ! p) { + if (c && !p) { g.sh->requestChannelPermissions(c->iId); if (c->iId == 0) p = g.pPermissions; @@ -2360,9 +2437,10 @@ void MainWindow::updateMenuPermissions() { } Channel *cparent = c ? c->cParent : nullptr; - ChanACL::Permissions pparent = cparent ? static_cast<ChanACL::Permissions>(cparent->uiPermissions) : ChanACL::None; + ChanACL::Permissions pparent = + cparent ? static_cast< ChanACL::Permissions >(cparent->uiPermissions) : ChanACL::None; - if (cparent && ! pparent) { + if (cparent && !pparent) { g.sh->requestChannelPermissions(cparent->iId); if (cparent->iId == 0) pparent = g.pPermissions; @@ -2372,11 +2450,11 @@ void MainWindow::updateMenuPermissions() { cparent->uiPermissions = pparent; } - ClientUser *user = g.uiSession ? ClientUser::get(g.uiSession) : nullptr; - Channel *homec = user ? user->cChannel : nullptr; - ChanACL::Permissions homep = homec ? static_cast<ChanACL::Permissions>(homec->uiPermissions) : ChanACL::None; + ClientUser *user = g.uiSession ? ClientUser::get(g.uiSession) : nullptr; + Channel *homec = user ? user->cChannel : nullptr; + ChanACL::Permissions homep = homec ? static_cast< ChanACL::Permissions >(homec->uiPermissions) : ChanACL::None; - if (homec && ! homep) { + if (homec && !homep) { g.sh->requestChannelPermissions(homec->iId); if (homec->iId == 0) homep = g.pPermissions; @@ -2387,11 +2465,13 @@ void MainWindow::updateMenuPermissions() { } if (cu) { - qaUserMute->setEnabled(p & (ChanACL::Write | ChanACL::MuteDeafen) && ((cu != user) || cu->bMute || cu->bSuppress)); + qaUserMute->setEnabled(p & (ChanACL::Write | ChanACL::MuteDeafen) + && ((cu != user) || cu->bMute || cu->bSuppress)); qaUserDeaf->setEnabled(p & (ChanACL::Write | ChanACL::MuteDeafen) && ((cu != user) || cu->bDeaf)); qaUserPrioritySpeaker->setEnabled(p & (ChanACL::Write | ChanACL::MuteDeafen)); qaUserTextMessage->setEnabled(p & (ChanACL::Write | ChanACL::TextMessage)); - qaUserInformation->setEnabled((g.pPermissions & (ChanACL::Write | ChanACL::Register)) || (p & (ChanACL::Write | ChanACL::Enter)) || (cu == user)); + qaUserInformation->setEnabled((g.pPermissions & (ChanACL::Write | ChanACL::Register)) + || (p & (ChanACL::Write | ChanACL::Enter)) || (cu == user)); } else { qaUserMute->setEnabled(false); qaUserDeaf->setEnabled(false); @@ -2406,8 +2486,10 @@ void MainWindow::updateMenuPermissions() { qaChannelRemove->setEnabled(p & ChanACL::Write); qaChannelACL->setEnabled((p & ChanACL::Write) || (pparent & ChanACL::Write)); - qaChannelLink->setEnabled((p & (ChanACL::Write | ChanACL::LinkChannel)) && (homep & (ChanACL::Write | ChanACL::LinkChannel))); - qaChannelUnlink->setEnabled((p & (ChanACL::Write | ChanACL::LinkChannel)) || (homep & (ChanACL::Write | ChanACL::LinkChannel))); + qaChannelLink->setEnabled((p & (ChanACL::Write | ChanACL::LinkChannel)) + && (homep & (ChanACL::Write | ChanACL::LinkChannel))); + qaChannelUnlink->setEnabled((p & (ChanACL::Write | ChanACL::LinkChannel)) + || (homep & (ChanACL::Write | ChanACL::LinkChannel))); qaChannelUnlinkAll->setEnabled(p & (ChanACL::Write | ChanACL::LinkChannel)); qaChannelCopyURL->setEnabled(c); @@ -2420,12 +2502,12 @@ void MainWindow::userStateChanged() { if (g.s.bStateInTray) { updateTrayIcon(); } - + ClientUser *user = ClientUser::get(g.uiSession); if (!user) { - g.bAttenuateOthers = false; + g.bAttenuateOthers = false; g.prioritySpeakerActiveOverride = false; - + return; } @@ -2435,15 +2517,13 @@ void MainWindow::userStateChanged() { case Settings::Shouting: g.bAttenuateOthers = g.s.bAttenuateOthersOnTalk; - g.prioritySpeakerActiveOverride = - g.s.bAttenuateUsersOnPrioritySpeak - && user->bPrioritySpeaker; - + g.prioritySpeakerActiveOverride = g.s.bAttenuateUsersOnPrioritySpeak && user->bPrioritySpeaker; + break; case Settings::Passive: case Settings::MutedTalking: default: - g.bAttenuateOthers = false; + g.bAttenuateOthers = false; g.prioritySpeakerActiveOverride = false; break; } @@ -2455,7 +2535,7 @@ void MainWindow::on_qaAudioReset_triggered() { ai->bResetProcessor = true; } -void MainWindow::on_qaFilterToggle_triggered() { +void MainWindow::on_qaFilterToggle_triggered() { g.s.bFilterActive = qaFilterToggle->isChecked(); updateUserModel(); } @@ -2472,11 +2552,11 @@ void MainWindow::on_qaAudioMute_triggered() { g.s.bMute = qaAudioMute->isChecked(); - if (! g.s.bMute && g.s.bDeaf) { + if (!g.s.bMute && g.s.bDeaf) { g.s.bDeaf = false; qaAudioDeaf->setChecked(false); g.l->log(Log::SelfUndeaf, tr("Unmuted and undeafened.")); - } else if (! g.s.bMute) { + } else if (!g.s.bMute) { g.l->log(Log::SelfUnmute, tr("Unmuted.")); } else { g.l->log(Log::SelfMute, tr("Muted.")); @@ -2496,7 +2576,7 @@ void MainWindow::on_qaAudioDeaf_triggered() { return; } - if (! qaAudioDeaf->isChecked() && bAutoUnmute) { + if (!qaAudioDeaf->isChecked() && bAutoUnmute) { qaAudioDeaf->setChecked(true); qaAudioMute->setChecked(false); on_qaAudioMute_triggered(); @@ -2507,9 +2587,9 @@ void MainWindow::on_qaAudioDeaf_triggered() { ai->tIdle.restart(); g.s.bDeaf = qaAudioDeaf->isChecked(); - if (g.s.bDeaf && ! g.s.bMute) { + if (g.s.bDeaf && !g.s.bMute) { bAutoUnmute = true; - g.s.bMute = true; + g.s.bMute = true; qaAudioMute->setChecked(true); g.l->log(Log::SelfDeaf, tr("Muted and deafened.")); } else if (g.s.bDeaf) { @@ -2544,7 +2624,7 @@ void MainWindow::on_qaAudioTTS_triggered() { } void MainWindow::on_qaAudioStats_triggered() { - AudioStats *as=new AudioStats(this); + AudioStats *as = new AudioStats(this); as->show(); } @@ -2562,17 +2642,17 @@ void MainWindow::on_qaConfigDialog_triggered() { updateTransmitModeComboBox(); updateTrayIcon(); updateUserModel(); - + if (g.s.requireRestartToApply) { - if (g.s.requireRestartToApply && QMessageBox::question( - this, - tr("Restart Mumble?"), - tr("Some settings will only apply after a restart of Mumble. Restart Mumble now?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - + if (g.s.requireRestartToApply + && QMessageBox::question( + this, tr("Restart Mumble?"), + tr("Some settings will only apply after a restart of Mumble. Restart Mumble now?"), + QMessageBox::Yes | QMessageBox::No) + == QMessageBox::Yes) { bSuppressAskOnQuit = true; - restartOnQuit = true; - + restartOnQuit = true; + close(); } } @@ -2627,24 +2707,16 @@ void MainWindow::on_qaHelpVersionCheck_triggered() { void MainWindow::on_gsMuteSelf_down(QVariant v) { int val = v.toInt(); - if ( - ((val > 0) && ! g.s.bMute) || - ((val < 0) && g.s.bMute) || - (val == 0) - ) { - qaAudioMute->setChecked(! qaAudioMute->isChecked()); + if (((val > 0) && !g.s.bMute) || ((val < 0) && g.s.bMute) || (val == 0)) { + qaAudioMute->setChecked(!qaAudioMute->isChecked()); on_qaAudioMute_triggered(); } } void MainWindow::on_gsDeafSelf_down(QVariant v) { int val = v.toInt(); - if ( - ((val > 0) && ! g.s.bDeaf) || - ((val < 0) && g.s.bDeaf) || - (val == 0) - ) { - qaAudioDeaf->setChecked(! qaAudioDeaf->isChecked()); + if (((val > 0) && !g.s.bDeaf) || ((val < 0) && g.s.bDeaf) || (val == 0)) { + qaAudioDeaf->setChecked(!qaAudioDeaf->isChecked()); on_qaAudioDeaf_triggered(); } } @@ -2655,7 +2727,7 @@ void MainWindow::on_PushToTalk_triggered(bool down, QVariant) { g.uiDoublePush = g.tDoublePush.restart(); g.iPushToTalk++; } else if (g.iPushToTalk > 0) { - QTimer::singleShot(static_cast<int>(g.s.pttHold), this, SLOT(pttReleased())); + QTimer::singleShot(static_cast< int >(g.s.pttHold), this, SLOT(pttReleased())); } } @@ -2692,7 +2764,7 @@ void MainWindow::on_VolumeDown_triggered(bool down, QVariant) { } Channel *MainWindow::mapChannel(int idx) const { - if (! g.uiSession) + if (!g.uiSession) return nullptr; Channel *c = nullptr; @@ -2709,10 +2781,12 @@ Channel *MainWindow::mapChannel(int idx) const { c = c->cParent; break; default: - if(idx <= SHORTCUT_TARGET_PARENT_SUBCHANNEL) - c = pmModel->getSubChannel(ClientUser::get(g.uiSession)->cChannel->cParent, SHORTCUT_TARGET_PARENT_SUBCHANNEL - idx); + if (idx <= SHORTCUT_TARGET_PARENT_SUBCHANNEL) + c = pmModel->getSubChannel(ClientUser::get(g.uiSession)->cChannel->cParent, + SHORTCUT_TARGET_PARENT_SUBCHANNEL - idx); else - c = pmModel->getSubChannel(ClientUser::get(g.uiSession)->cChannel, SHORTCUT_TARGET_SUBCHANNEL - idx); + c = pmModel->getSubChannel(ClientUser::get(g.uiSession)->cChannel, + SHORTCUT_TARGET_SUBCHANNEL - idx); break; } } else { @@ -2726,22 +2800,22 @@ void MainWindow::updateTarget() { if (qmCurrentTargets.isEmpty()) { g.bCenterPosition = false; - g.iTarget = 0; + g.iTarget = 0; } else { bool center = false; - QList<ShortcutTarget> ql; - foreach(const ShortcutTarget &st, qmCurrentTargets.keys()) { + QList< ShortcutTarget > ql; + foreach (const ShortcutTarget &st, qmCurrentTargets.keys()) { ShortcutTarget nt; - center = center || st.bForceCenter; - nt.bUsers = st.bUsers; + center = center || st.bForceCenter; + nt.bUsers = st.bUsers; nt.bCurrentSelection = st.bCurrentSelection; if (nt.bCurrentSelection) { Channel *c = pmModel->getSelectedChannel(); if (c) { - nt.bUsers = false; - nt.iChannel = c->iId; - nt.bLinks = st.bLinks; + nt.bUsers = false; + nt.iChannel = c->iId; + nt.bLinks = st.bLinks; nt.bChildren = st.bChildren; ql << nt; @@ -2756,20 +2830,20 @@ void MainWindow::updateTarget() { } } } else if (st.bUsers) { - foreach(const QString &hash, st.qlUsers) { + foreach (const QString &hash, st.qlUsers) { ClientUser *p = pmModel->getUser(hash); if (p) nt.qlSessions.append(p->uiSession); } - if (! nt.qlSessions.isEmpty()) + if (!nt.qlSessions.isEmpty()) ql << nt; } else { Channel *c = mapChannel(st.iChannel); if (c) { - nt.bLinks = st.bLinks; + nt.bLinks = st.bLinks; nt.bChildren = st.bChildren; - nt.iChannel = c->iId; - nt.qsGroup = st.qsGroup; + nt.iChannel = c->iId; + nt.qsGroup = st.qsGroup; ql << nt; } } @@ -2783,17 +2857,17 @@ void MainWindow::updateTarget() { if (idx == 0) { // An idx of 0 means that we don't have a mapping for this shortcut yet // Thus we'll register it here - QMap<int, int> qm; - QMap<int, int>::const_iterator i; + QMap< int, int > qm; + QMap< int, int >::const_iterator i; // We reverse the qmTargetsUse map into qm so that each key becomes a value and vice versa - for (i=qmTargetUse.constBegin(); i != qmTargetUse.constEnd(); ++i) { + for (i = qmTargetUse.constBegin(); i != qmTargetUse.constEnd(); ++i) { qm.insert(i.value(), i.key()); } // The reversal and the promise that when iterating over a QMap, the keys will appear sorted // leads to us now being able to get the next target ID as the value of the first entry in // the map. - i = qm.constBegin(); + i = qm.constBegin(); idx = i.value(); @@ -2803,12 +2877,12 @@ void MainWindow::updateTarget() { MumbleProto::VoiceTarget mpvt; mpvt.set_id(idx); - foreach(const ShortcutTarget &st, ql) { + foreach (const ShortcutTarget &st, ql) { MumbleProto::VoiceTarget_Target *t = mpvt.add_targets(); // st.bCurrentSelection has been taken care of at this point already (if it was set) so // we don't have to check for that here. if (st.bUsers) { - foreach(unsigned int uisession, st.qlSessions) + foreach (unsigned int uisession, st.qlSessions) t->add_session(uisession); } else { t->set_channel_id(st.iChannel); @@ -2816,7 +2890,7 @@ void MainWindow::updateTarget() { t->set_children(true); if (st.bLinks) t->set_links(true); - if (! st.qsGroup.isEmpty()) + if (!st.qsGroup.isEmpty()) t->set_group(u8(st.qsGroup)); } } @@ -2834,7 +2908,7 @@ void MainWindow::updateTarget() { // Get the target ID for the targetID after next int oldidx = i.value(); if (oldidx) { - QHash<QList<ShortcutTarget>, int>::iterator mi; + QHash< QList< ShortcutTarget >, int >::iterator mi; for (mi = qmTargets.begin(); mi != qmTargets.end(); ++mi) { if (mi.value() == oldidx) { // If we have used the targetID after next before, we clear the VoiceTarget for that @@ -2862,17 +2936,17 @@ void MainWindow::updateTarget() { // something similar to a RingBuffer inside this method. qmTargetUse.insert(idx, iTargetCounter); g.bCenterPosition = center; - g.iTarget = idx; + g.iTarget = idx; } } } void MainWindow::on_gsWhisper_triggered(bool down, QVariant scdata) { - ShortcutTarget st = scdata.value<ShortcutTarget>(); + ShortcutTarget st = scdata.value< ShortcutTarget >(); if (down) { if (gsJoinChannel->active()) { - if (! st.bUsers) { + if (!st.bUsers) { Channel *c = mapChannel(st.iChannel); if (c) { g.sh->joinChannel(g.uiSession, c->iId); @@ -2882,7 +2956,7 @@ void MainWindow::on_gsWhisper_triggered(bool down, QVariant scdata) { } if (gsLinkChannel->active()) { - if (! st.bUsers) { + if (!st.bUsers) { Channel *c = ClientUser::get(g.uiSession)->cChannel; Channel *l = mapChannel(st.iChannel); if (l) { @@ -2903,7 +2977,7 @@ void MainWindow::on_gsWhisper_triggered(bool down, QVariant scdata) { } else if (g.iPushToTalk > 0) { SignalCurry *fwd = new SignalCurry(scdata, true, this); connect(fwd, SIGNAL(called(QVariant)), SLOT(whisperReleased(QVariant))); - QTimer::singleShot(static_cast<int>(g.s.pttHold), fwd, SLOT(call())); + QTimer::singleShot(static_cast< int >(g.s.pttHold), fwd, SLOT(call())); } } @@ -2911,16 +2985,14 @@ void MainWindow::on_gsWhisper_triggered(bool down, QVariant scdata) { * the number of push-to-talk events for a given ShortcutTarget. If this number * reaches 0, the ShortcutTarget is removed from qmCurrentTargets. */ -void MainWindow::addTarget(ShortcutTarget *st) -{ +void MainWindow::addTarget(ShortcutTarget *st) { if (qmCurrentTargets.contains(*st)) qmCurrentTargets[*st] += 1; else qmCurrentTargets[*st] = 1; } -void MainWindow::removeTarget(ShortcutTarget *st) -{ +void MainWindow::removeTarget(ShortcutTarget *st) { if (!qmCurrentTargets.contains(*st)) return; @@ -2930,14 +3002,11 @@ void MainWindow::removeTarget(ShortcutTarget *st) qmCurrentTargets[*st] -= 1; } -void MainWindow::on_gsCycleTransmitMode_triggered(bool down, QVariant) -{ - if (down) - { +void MainWindow::on_gsCycleTransmitMode_triggered(bool down, QVariant) { + if (down) { QString qsNewMode; - switch (g.s.atTransmit) - { + switch (g.s.atTransmit) { case Settings::Continuous: g.s.atTransmit = Settings::VAD; g.l->log(Log::Information, tr("Transmit Mode set to Voice Activity")); @@ -2956,8 +3025,7 @@ void MainWindow::on_gsCycleTransmitMode_triggered(bool down, QVariant) updateTransmitModeComboBox(); } -void MainWindow::on_gsTransmitModePushToTalk_triggered(bool down, QVariant) -{ +void MainWindow::on_gsTransmitModePushToTalk_triggered(bool down, QVariant) { if (down) { g.s.atTransmit = Settings::PushToTalk; g.l->log(Log::Information, tr("Transmit Mode set to Push-to-Talk")); @@ -2966,8 +3034,7 @@ void MainWindow::on_gsTransmitModePushToTalk_triggered(bool down, QVariant) updateTransmitModeComboBox(); } -void MainWindow::on_gsTransmitModeContinuous_triggered(bool down, QVariant) -{ +void MainWindow::on_gsTransmitModeContinuous_triggered(bool down, QVariant) { if (down) { g.s.atTransmit = Settings::Continuous; g.l->log(Log::Information, tr("Transmit Mode set to Continuous")); @@ -2976,8 +3043,7 @@ void MainWindow::on_gsTransmitModeContinuous_triggered(bool down, QVariant) updateTransmitModeComboBox(); } -void MainWindow::on_gsTransmitModeVAD_triggered(bool down, QVariant) -{ +void MainWindow::on_gsTransmitModeVAD_triggered(bool down, QVariant) { if (down) { g.s.atTransmit = Settings::VAD; g.l->log(Log::Information, tr("Transmit Mode set to Voice Activity")); @@ -2998,7 +3064,8 @@ void MainWindow::on_gsSendTextMessage_triggered(bool down, QVariant scdata) { Channel *c = ClientUser::get(g.uiSession)->cChannel; g.sh->sendChannelTextMessage(c->iId, qsText, false); - g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatChannel(c), qsText), tr("Message to channel %1").arg(c->qsName), true); + g.l->log(Log::TextMessage, tr("To %1: %2").arg(Log::formatChannel(c), qsText), + tr("Message to channel %1").arg(c->qsName), true); } void MainWindow::on_gsSendClipboardTextMessage_triggered(bool down, QVariant) { @@ -3007,7 +3074,7 @@ void MainWindow::on_gsSendClipboardTextMessage_triggered(bool down, QVariant) { } // call sendChatbarMessage() instead of on_gsSendTextMessage_triggered() to handle - // formatting of the content in the clipboard, i.e., href. + // formatting of the content in the clipboard, i.e., href. sendChatbarMessage(QApplication::clipboard()->text()); } @@ -3015,7 +3082,7 @@ void MainWindow::whisperReleased(QVariant scdata) { if (g.iPushToTalk <= 0) return; - ShortcutTarget st = scdata.value<ShortcutTarget>(); + ShortcutTarget st = scdata.value< ShortcutTarget >(); g.iPushToTalk--; @@ -3023,8 +3090,7 @@ void MainWindow::whisperReleased(QVariant scdata) { updateTarget(); } -void MainWindow::onChangeMute() -{ +void MainWindow::onChangeMute() { if (!g.ai) { return; } @@ -3032,8 +3098,7 @@ void MainWindow::onChangeMute() emit corkAudioInputStream(g.s.bMute && !g.bInAudioWizard); } -void MainWindow::onResetAudio() -{ +void MainWindow::onResetAudio() { qWarning("MainWindow: Start audio reset"); Audio::stop(); Audio::start(); @@ -3050,9 +3115,9 @@ void MainWindow::viewCertificate(bool) { * connection to the server is established but before the server Sync is complete. */ void MainWindow::serverConnected() { - g.uiSession = 0; + g.uiSession = 0; g.pPermissions = ChanACL::None; - g.iCodecAlpha = 0x8000000b; + g.iCodecAlpha = 0x8000000b; g.bPreferAlpha = true; #ifdef USE_OPUS g.bOpus = true; @@ -3084,10 +3149,10 @@ void MainWindow::serverConnected() { qtvUsers->setRowHidden(0, QModelIndex(), false); - g.bAllowHTML = true; + g.bAllowHTML = true; g.uiMessageLength = 5000; - g.uiImageLength = 131072; - g.uiMaxUsers = 0; + g.uiImageLength = 131072; + g.uiMaxUsers = 0; if (g.s.bMute || g.s.bDeaf) { g.sh->setSelfMuteDeafState(g.s.bMute, g.s.bDeaf); @@ -3116,8 +3181,8 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re // clear ChannelListener ChannelListener::clear(); - g.uiSession = 0; - g.pPermissions = ChanACL::None; + g.uiSession = 0; + g.pPermissions = ChanACL::None; g.bAttenuateOthers = false; qaServerDisconnect->setEnabled(false); qaServerInformation->setEnabled(false); @@ -3137,8 +3202,8 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re if (g.sh->hasSynchronized()) { // Only save server-specific shortcuts if the client and server have been synchronized before as only then - // did the client actually load them from the DB. If we store them without having loaded them, we will effectively - // clear the server-specific shortcuts for this server. + // did the client actually load them from the DB. If we store them without having loaded them, we will + // effectively clear the server-specific shortcuts for this server. if (g.db->setShortcuts(g.sh->qbaDigest, g.s.qlShortcuts)) { GlobalShortcutEngine::engine->bNeedRemap = true; } @@ -3168,11 +3233,11 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re tokenEdit = nullptr; } - QSet<QAction *> qs; + QSet< QAction * > qs; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - qs += QSet<QAction*>(qlServerActions.begin(), qlServerActions.end()); - qs += QSet<QAction*>(qlChannelActions.begin(), qlChannelActions.end()); - qs += QSet<QAction*>(qlUserActions.begin(), qlUserActions.end()); + qs += QSet< QAction * >(qlServerActions.begin(), qlServerActions.end()); + qs += QSet< QAction * >(qlChannelActions.begin(), qlChannelActions.end()); + qs += QSet< QAction * >(qlUserActions.begin(), qlUserActions.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now qs += qlServerActions.toSet(); @@ -3180,7 +3245,7 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re qs += qlUserActions.toSet(); #endif - foreach(QAction *a, qs) + foreach (QAction *a, qs) delete a; qlServerActions.clear(); @@ -3197,29 +3262,36 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re qmUser_aboutToShow(); on_qmConfig_aboutToShow(); - if (! g.sh->qlErrors.isEmpty()) { - foreach(QSslError e, g.sh->qlErrors) + if (!g.sh->qlErrors.isEmpty()) { + foreach (QSslError e, g.sh->qlErrors) g.l->log(Log::Warning, tr("SSL Verification failed: %1").arg(e.errorString().toHtmlEscaped())); - if (! g.sh->qscCert.isEmpty()) { + if (!g.sh->qscCert.isEmpty()) { QSslCertificate c = g.sh->qscCert.at(0); QString basereason; QString actual_digest = QString::fromLatin1(c.digest(QCryptographicHash::Sha1).toHex()); - QString digests_section = tr("<li>Server certificate digest (SHA-1):\t%1</li>").arg(ViewCert::prettifyDigest(actual_digest)); + QString digests_section = + tr("<li>Server certificate digest (SHA-1):\t%1</li>").arg(ViewCert::prettifyDigest(actual_digest)); QString expected_digest = g.db->getDigest(host, port); - if (! expected_digest.isNull()) { - basereason = tr("<b>WARNING:</b> The server presented a certificate that was different from the stored one."); - digests_section.append(tr("<li>Expected certificate digest (SHA-1):\t%1</li>").arg(ViewCert::prettifyDigest(expected_digest))); + if (!expected_digest.isNull()) { + basereason = + tr("<b>WARNING:</b> The server presented a certificate that was different from the stored one."); + digests_section.append(tr("<li>Expected certificate digest (SHA-1):\t%1</li>") + .arg(ViewCert::prettifyDigest(expected_digest))); } else { basereason = tr("Server presented a certificate which failed verification."); } QStringList qsl; - foreach(QSslError e, g.sh->qlErrors) + foreach (QSslError e, g.sh->qlErrors) qsl << QString::fromLatin1("<li>%1</li>").arg(e.errorString().toHtmlEscaped()); QMessageBox qmb(QMessageBox::Warning, QLatin1String("Mumble"), - tr("<p>%1</p><ul>%2</ul><p>The specific errors with this certificate are:</p><ol>%3</ol>" - "<p>Do you wish to accept this certificate anyway?<br />(It will also be stored so you won't be asked this again.)</p>" - ).arg(basereason).arg(digests_section).arg(qsl.join(QString())), QMessageBox::Yes | QMessageBox::No, this); + tr("<p>%1</p><ul>%2</ul><p>The specific errors with this certificate are:</p><ol>%3</ol>" + "<p>Do you wish to accept this certificate anyway?<br />(It will also be stored so you " + "won't be asked this again.)</p>") + .arg(basereason) + .arg(digests_section) + .arg(qsl.join(QString())), + QMessageBox::Yes | QMessageBox::No, this); qmb.setDefaultButton(QMessageBox::No); qmb.setEscapeButton(QMessageBox::No); @@ -3241,18 +3313,21 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re } } } else if (err == QAbstractSocket::SslHandshakeFailedError) { - QMessageBox::warning(this, tr("SSL Version mismatch"), tr("This server is using an older encryption standard, and is no longer supported by modern versions of Mumble."), QMessageBox::Ok); + QMessageBox::warning(this, tr("SSL Version mismatch"), + tr("This server is using an older encryption standard, and is no longer supported by " + "modern versions of Mumble."), + QMessageBox::Ok); } else { bool ok = false; - if (! reason.isEmpty()) { + if (!reason.isEmpty()) { g.l->log(Log::ServerDisconnected, tr("Server connection failed: %1.").arg(reason.toHtmlEscaped())); - } else { + } else { g.l->log(Log::ServerDisconnected, tr("Disconnected from server.")); } -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // Qt 5.15 introduced a default constructor that initializes the flags to be set to no flags Qt::WindowFlags wf; #elif defined(Q_OS_MAC) @@ -3266,39 +3341,37 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re switch (rtLast) { case MumbleProto::Reject_RejectType_InvalidUsername: uname = QInputDialog::getText(this, tr("Invalid username"), - tr("You connected with an invalid username, please try another one."), - QLineEdit::Normal, uname, &ok, wf); + tr("You connected with an invalid username, please try another one."), + QLineEdit::Normal, uname, &ok, wf); break; case MumbleProto::Reject_RejectType_UsernameInUse: uname = QInputDialog::getText(this, tr("Username in use"), - tr("That username is already in use, please try another username."), - QLineEdit::Normal, uname, &ok, wf); + tr("That username is already in use, please try another username."), + QLineEdit::Normal, uname, &ok, wf); break; case MumbleProto::Reject_RejectType_WrongUserPW: - pw = QInputDialog::getText(this, - tr("Wrong certificate or password"), - tr("Wrong certificate or password for registered user. If you are\n" - "certain this user is protected by a password please retry.\n" - "Otherwise abort and check your certificate and username."), - QLineEdit::Password, pw, &ok, wf); + pw = QInputDialog::getText(this, tr("Wrong certificate or password"), + tr("Wrong certificate or password for registered user. If you are\n" + "certain this user is protected by a password please retry.\n" + "Otherwise abort and check your certificate and username."), + QLineEdit::Password, pw, &ok, wf); break; case MumbleProto::Reject_RejectType_WrongServerPW: - pw = QInputDialog::getText(this, - tr("Wrong password"), - tr("Wrong server password for unregistered user account, please try again."), - QLineEdit::Password, pw, &ok, wf); + pw = QInputDialog::getText(this, tr("Wrong password"), + tr("Wrong server password for unregistered user account, please try again."), + QLineEdit::Password, pw, &ok, wf); break; default: matched = false; break; } if (ok && matched) { - if (! g.s.bSuppressIdentity) + if (!g.s.bSuppressIdentity) g.db->setPassword(host, port, uname, pw); qaServerDisconnect->setEnabled(true); g.sh->setConnectionInfo(host, port, uname, pw); on_Reconnect_timeout(); - } else if (!matched && g.s.bReconnect && ! reason.isEmpty()) { + } else if (!matched && g.s.bReconnect && !reason.isEmpty()) { qaServerDisconnect->setEnabled(true); if (bRetryServer) { qtReconnect->start(); @@ -3310,9 +3383,9 @@ void MainWindow::serverDisconnected(QAbstractSocket::SocketError err, QString re } void MainWindow::resolverError(QAbstractSocket::SocketError, QString reason) { - if (! reason.isEmpty()) { + if (!reason.isEmpty()) { g.l->log(Log::ServerDisconnected, tr("Server connection failed: %1.").arg(reason.toHtmlEscaped())); - } else { + } else { g.l->log(Log::ServerDisconnected, tr("Server connection failed.")); } @@ -3333,7 +3406,7 @@ void MainWindow::trayAboutToShow() { } QScreen *screen = Screen::screenAt(p); - if(screen){ + if (screen) { QRect qr = screen->geometry(); if (p.y() < (qr.height() / 2)) @@ -3371,12 +3444,13 @@ void MainWindow::on_Icon_activated(QSystemTrayIcon::ActivationReason reason) { case QSystemTrayIcon::Trigger: case QSystemTrayIcon::DoubleClick: case QSystemTrayIcon::MiddleClick: - if (isMinimized()) { - showRaiseWindow(); - } else { - showMinimized(); - } - default: break; + if (isMinimized()) { + showRaiseWindow(); + } else { + showMinimized(); + } + default: + break; } } @@ -3400,7 +3474,7 @@ void MainWindow::qtvUserCurrentChanged(const QModelIndex &, const QModelIndex &) } void MainWindow::updateChatBar() { - User *p = pmModel->getUser(qtvUsers->currentIndex()); + User *p = pmModel->getUser(qtvUsers->currentIndex()); Channel *c = pmModel->getChannel(qtvUsers->currentIndex()); if (g.uiSession == 0) { @@ -3410,7 +3484,8 @@ void MainWindow::updateChatBar() { if (!g.s.bChatBarUseSelection || !c) // If no channel selected fallback to current one c = ClientUser::get(g.uiSession)->cChannel; - qteChat->setDefaultText(tr("<center>Type message to channel '%1' here</center>").arg(c->qsName.toHtmlEscaped())); + qteChat->setDefaultText( + tr("<center>Type message to channel '%1' here</center>").arg(c->qsName.toHtmlEscaped())); } else { // User target qteChat->setDefaultText(tr("<center>Type message to user '%1' here</center>").arg(p->qsName.toHtmlEscaped())); @@ -3421,40 +3496,40 @@ void MainWindow::updateChatBar() { void MainWindow::customEvent(QEvent *evt) { if (evt->type() == MB_QEVENT) { - MessageBoxEvent *mbe=static_cast<MessageBoxEvent *>(evt); + MessageBoxEvent *mbe = static_cast< MessageBoxEvent * >(evt); g.l->log(Log::Information, mbe->msg); return; } else if (evt->type() == OU_QEVENT) { - OpenURLEvent *oue=static_cast<OpenURLEvent *>(evt); + OpenURLEvent *oue = static_cast< OpenURLEvent * >(evt); openUrl(oue->url); return; } else if (evt->type() != SERVERSEND_EVENT) { return; } - ServerHandlerMessageEvent *shme=static_cast<ServerHandlerMessageEvent *>(evt); + ServerHandlerMessageEvent *shme = static_cast< ServerHandlerMessageEvent * >(evt); #ifdef QT_NO_DEBUG -#define MUMBLE_MH_MSG(x) case MessageHandler:: x : { \ - MumbleProto:: x msg; \ - if (msg.ParseFromArray(shme->qbaMsg.constData(), shme->qbaMsg.size())) \ - msg##x(msg); \ - break; \ - } +# define MUMBLE_MH_MSG(x) \ + case MessageHandler::x: { \ + MumbleProto::x msg; \ + if (msg.ParseFromArray(shme->qbaMsg.constData(), shme->qbaMsg.size())) \ + msg##x(msg); \ + break; \ + } #else -#define MUMBLE_MH_MSG(x) case MessageHandler:: x : { \ - MumbleProto:: x msg; \ - if (msg.ParseFromArray(shme->qbaMsg.constData(), shme->qbaMsg.size())) { \ - printf("%s:\n", #x); \ - msg.PrintDebugString(); \ - msg##x(msg); \ - } \ - break; \ - } +# define MUMBLE_MH_MSG(x) \ + case MessageHandler::x: { \ + MumbleProto::x msg; \ + if (msg.ParseFromArray(shme->qbaMsg.constData(), shme->qbaMsg.size())) { \ + printf("%s:\n", #x); \ + msg.PrintDebugString(); \ + msg##x(msg); \ + } \ + break; \ + } #endif - switch (shme->uiType) { - MUMBLE_MH_ALL - } + switch (shme->uiType) { MUMBLE_MH_ALL } #undef MUMBLE_MH_MSG @@ -3472,9 +3547,7 @@ void MainWindow::on_qteLog_anchorClicked(const QUrl &url) { if (g.ocIntercept) return; #endif - if (url.scheme() != QLatin1String("file") - && url.scheme() != QLatin1String("qrc") - && !url.isRelative()) + if (url.scheme() != QLatin1String("file") && url.scheme() != QLatin1String("qrc") && !url.isRelative()) QDesktopServices::openUrl(url); } } @@ -3483,7 +3556,7 @@ void MainWindow::on_qteLog_highlighted(const QUrl &url) { if (url.scheme() == QString::fromLatin1("clientid") || url.scheme() == QString::fromLatin1("channelid")) return; - if (! url.isValid()) + if (!url.isValid()) QToolTip::hideText(); else { if (isActiveWindow()) { @@ -3493,9 +3566,9 @@ void MainWindow::on_qteLog_highlighted(const QUrl &url) { } void MainWindow::context_triggered() { - QAction *a = qobject_cast<QAction *>(sender()); + QAction *a = qobject_cast< QAction * >(sender()); - Channel *c = pmModel->getChannel(qtvUsers->currentIndex()); + Channel *c = pmModel->getChannel(qtvUsers->currentIndex()); ClientUser *p = pmModel->getUser(qtvUsers->currentIndex()); MumbleProto::ContextAction mpca; @@ -3511,16 +3584,17 @@ void MainWindow::context_triggered() { * Presents a file open dialog, opens the selected picture and returns it. * @return Pair consisting of the raw file contents and the image. Unitialized on error or cancel. */ -QPair<QByteArray, QImage> MainWindow::openImageFile() { - QPair<QByteArray, QImage> retval; +QPair< QByteArray, QImage > MainWindow::openImageFile() { + QPair< QByteArray, QImage > retval; - QString fname = QFileDialog::getOpenFileName(this, tr("Choose image file"), getImagePath(), tr("Images (*.png *.jpg *.jpeg)")); + QString fname = + QFileDialog::getOpenFileName(this, tr("Choose image file"), getImagePath(), tr("Images (*.png *.jpg *.jpeg)")); if (fname.isNull()) return retval; QFile f(fname); - if (! f.open(QIODevice::ReadOnly)) { + if (!f.open(QIODevice::ReadOnly)) { QMessageBox::warning(this, tr("Failed to load image"), tr("Could not open file for reading.")); return retval; } @@ -3551,20 +3625,24 @@ QPair<QByteArray, QImage> MainWindow::openImageFile() { return retval; } - retval.first = qba; + retval.first = qba; retval.second = img; return retval; } -void MainWindow::logChangeNotPermanent(const QString &actionName, ClientUser * const p) const { - g.l->log(Log::Warning, QObject::tr("\"%1\" could not be saved permanently and is lost on restart because %2 does not have a certificate.").arg(actionName).arg(Log::formatClientUser(p, Log::Target))); +void MainWindow::logChangeNotPermanent(const QString &actionName, ClientUser *const p) const { + g.l->log(Log::Warning, + QObject::tr( + "\"%1\" could not be saved permanently and is lost on restart because %2 does not have a certificate.") + .arg(actionName) + .arg(Log::formatClientUser(p, Log::Target))); } void MainWindow::destroyUserInformation() { - UserInformation *ui = static_cast<UserInformation *>(sender()); - QMap<unsigned int, UserInformation *>::iterator i; - for (i=qmUserInformations.begin(); i != qmUserInformations.end(); ++i) { + UserInformation *ui = static_cast< UserInformation * >(sender()); + QMap< unsigned int, UserInformation * >::iterator i; + for (i = qmUserInformations.begin(); i != qmUserInformations.end(); ++i) { if (i.value() == ui) { qmUserInformations.erase(i); return; diff --git a/src/mumble/MainWindow.h b/src/mumble/MainWindow.h index 7b4318e9b..c3448ec67 100644 --- a/src/mumble/MainWindow.h +++ b/src/mumble/MainWindow.h @@ -6,18 +6,18 @@ #ifndef MUMBLE_MUMBLE_MAINWINDOW_H_ #define MUMBLE_MUMBLE_MAINWINDOW_H_ -#include <QtCore/QtGlobal> #include <QtCore/QPointer> +#include <QtCore/QtGlobal> +#include <QtNetwork/QAbstractSocket> #include <QtWidgets/QMainWindow> #include <QtWidgets/QSystemTrayIcon> -#include <QtNetwork/QAbstractSocket> #include "CustomElements.h" +#include "MUComboBox.h" #include "Message.h" #include "Mumble.pb.h" #include "Usage.h" #include "UserLocalVolumeDialog.h" -#include "MUComboBox.h" #include "ui_MainWindow.h" @@ -40,305 +40,308 @@ class PTTButtonWidget; struct ShortcutTarget; class MessageBoxEvent : public QEvent { - public: - QString msg; - MessageBoxEvent(QString msg); +public: + QString msg; + MessageBoxEvent(QString msg); }; class OpenURLEvent : public QEvent { - public: - QUrl url; - OpenURLEvent(QUrl url); +public: + QUrl url; + OpenURLEvent(QUrl url); }; class MainWindow : public QMainWindow, public MessageHandler, public Ui::MainWindow { - friend class UserModel; - private: - Q_OBJECT - Q_DISABLE_COPY(MainWindow) - public: - UserModel *pmModel; - QSystemTrayIcon *qstiIcon; - QMenu *qmUser; - QMenu *qmChannel; - QMenu *qmListener; - QMenu *qmDeveloper; - QMenu *qmTray; - QIcon qiIcon, qiIconMutePushToMute, qiIconMuteSelf, qiIconMuteServer, qiIconDeafSelf, qiIconDeafServer, qiIconMuteSuppressed; - QIcon qiTalkingOn, qiTalkingWhisper, qiTalkingShout, qiTalkingOff; - QMap<unsigned int, UserLocalVolumeDialog *> qmUserVolTracker; - - /// "Action" for when there are no actions available - QAction *qaEmpty; - - GlobalShortcut *gsPushTalk, *gsResetAudio, *gsMuteSelf, *gsDeafSelf; - GlobalShortcut *gsUnlink, *gsPushMute, *gsJoinChannel; + friend class UserModel; + +private: + Q_OBJECT + Q_DISABLE_COPY(MainWindow) +public: + UserModel *pmModel; + QSystemTrayIcon *qstiIcon; + QMenu *qmUser; + QMenu *qmChannel; + QMenu *qmListener; + QMenu *qmDeveloper; + QMenu *qmTray; + QIcon qiIcon, qiIconMutePushToMute, qiIconMuteSelf, qiIconMuteServer, qiIconDeafSelf, qiIconDeafServer, + qiIconMuteSuppressed; + QIcon qiTalkingOn, qiTalkingWhisper, qiTalkingShout, qiTalkingOff; + QMap< unsigned int, UserLocalVolumeDialog * > qmUserVolTracker; + + /// "Action" for when there are no actions available + QAction *qaEmpty; + + GlobalShortcut *gsPushTalk, *gsResetAudio, *gsMuteSelf, *gsDeafSelf; + GlobalShortcut *gsUnlink, *gsPushMute, *gsJoinChannel; #ifdef USE_OVERLAY - GlobalShortcut *gsToggleOverlay; + GlobalShortcut *gsToggleOverlay; #endif - GlobalShortcut *gsMinimal, *gsVolumeUp, *gsVolumeDown, *gsWhisper, *gsLinkChannel; - GlobalShortcut *gsCycleTransmitMode, *gsTransmitModePushToTalk, *gsTransmitModeContinuous, *gsTransmitModeVAD; - GlobalShortcut *gsSendTextMessage, *gsSendClipboardTextMessage; - DockTitleBar *dtbLogDockTitle, *dtbChatDockTitle; - - ACLEditor *aclEdit; - BanEditor *banEdit; - UserEdit *userEdit; - Tokens *tokenEdit; - - VoiceRecorderDialog *voiceRecorderDialog; - - MumbleProto::Reject_RejectType rtLast; - bool bRetryServer; - QString qsDesiredChannel; - - bool bSuppressAskOnQuit; - /// Restart the client after shutdown - bool restartOnQuit; - bool bAutoUnmute; - - /// Contains the cursor whose position is immediately before the image to - /// save when activating the "Save Image As..." context menu item. - QTextCursor qtcSaveImageCursor; - - QPointer<Channel> cContextChannel; - QPointer<ClientUser> cuContextUser; - - QPoint qpContextPosition; - - void recheckTTS(); - void msgBox(QString msg); - void setOnTop(bool top); - void setShowDockTitleBars(bool doShow); - void updateTrayIcon(); - void updateUserModel(); - void focusNextMainWidget(); - QPair<QByteArray, QImage> openImageFile(); - - void updateChatBar(); - void openTextMessageDialog(ClientUser *p); - void openUserLocalVolumeDialog(ClientUser *p); + GlobalShortcut *gsMinimal, *gsVolumeUp, *gsVolumeDown, *gsWhisper, *gsLinkChannel; + GlobalShortcut *gsCycleTransmitMode, *gsTransmitModePushToTalk, *gsTransmitModeContinuous, *gsTransmitModeVAD; + GlobalShortcut *gsSendTextMessage, *gsSendClipboardTextMessage; + DockTitleBar *dtbLogDockTitle, *dtbChatDockTitle; + + ACLEditor *aclEdit; + BanEditor *banEdit; + UserEdit *userEdit; + Tokens *tokenEdit; + + VoiceRecorderDialog *voiceRecorderDialog; + + MumbleProto::Reject_RejectType rtLast; + bool bRetryServer; + QString qsDesiredChannel; + + bool bSuppressAskOnQuit; + /// Restart the client after shutdown + bool restartOnQuit; + bool bAutoUnmute; + + /// Contains the cursor whose position is immediately before the image to + /// save when activating the "Save Image As..." context menu item. + QTextCursor qtcSaveImageCursor; + + QPointer< Channel > cContextChannel; + QPointer< ClientUser > cuContextUser; + + QPoint qpContextPosition; + + void recheckTTS(); + void msgBox(QString msg); + void setOnTop(bool top); + void setShowDockTitleBars(bool doShow); + void updateTrayIcon(); + void updateUserModel(); + void focusNextMainWidget(); + QPair< QByteArray, QImage > openImageFile(); + + void updateChatBar(); + void openTextMessageDialog(ClientUser *p); + void openUserLocalVolumeDialog(ClientUser *p); #ifdef Q_OS_WIN - bool nativeEvent(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; - unsigned int uiNewHardware; + bool nativeEvent(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; + unsigned int uiNewHardware; #endif - protected: - Usage uUsage; - QTimer *qtReconnect; - - QList<QAction *> qlServerActions; - QList<QAction *> qlChannelActions; - QList<QAction *> qlUserActions; - - QHash<ShortcutTarget, int> qmCurrentTargets; - /// A map that contains information about the currently active - /// shout/whisper targets. The mapping is between a List of - /// ShortcutTargets that are all triggered together and the - /// target ID for this specific combination of ShortcutTargets. - /// The target ID is what the server uses to identify this specific - /// set of ShortcutTargets. - QHash<QList<ShortcutTarget>, int> qmTargets; - /// This is a map between all target IDs the client will ever use - /// and a helper-number (see iTargetCounter). - QMap<int, int> qmTargetUse; - Channel *mapChannel(int idx) const; - /// This is a pure helper number whose job is to always be increased - /// if a new VoiceTarget is needed. It will be used as the helper - /// number in qmTargetUse. - int iTargetCounter; - QMap<unsigned int, UserInformation *> qmUserInformations; - - PTTButtonWidget *qwPTTButtonWidget; - - MUComboBox *qcbTransmitMode; - QAction *qaTransmitMode; - QAction *qaTransmitModeSeparator; - - void createActions(); - void setupGui(); - void updateWindowTitle(); - /// updateToolbar updates the state of the toolbar depending on the current - /// window layout setting. - /// If the window layout setting is 'custom', the toolbar is made movable. If the - /// window layout is not 'custom', the toolbar is locked in place at the top of - /// the MainWindow. - void updateToolbar(); - void customEvent(QEvent *evt) Q_DECL_OVERRIDE; - void findDesiredChannel(); - void setupView(bool toggle_minimize = true); - void closeEvent(QCloseEvent *e) Q_DECL_OVERRIDE; - void hideEvent(QHideEvent *e) Q_DECL_OVERRIDE; - void showEvent(QShowEvent *e) Q_DECL_OVERRIDE; - void changeEvent(QEvent* e) Q_DECL_OVERRIDE; - void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; - - QMenu *createPopupMenu() Q_DECL_OVERRIDE; - - bool handleSpecialContextMenu(const QUrl &url, const QPoint &pos_, bool focus = false); - Channel* getContextMenuChannel(); - ClientUser* getContextMenuUser(); - - public slots: - void on_qmServer_aboutToShow(); - void on_qaServerConnect_triggered(bool autoconnect = false); - void on_qaServerDisconnect_triggered(); - void on_qaServerBanList_triggered(); - void on_qaServerUserList_triggered(); - void on_qaServerInformation_triggered(); - void on_qaServerTexture_triggered(); - void on_qaServerTextureRemove_triggered(); - void on_qaServerTokens_triggered(); - void on_qmSelf_aboutToShow(); - void on_qaSelfComment_triggered(); - void on_qaSelfRegister_triggered(); - void qcbTransmitMode_activated(int index); - void updateTransmitModeComboBox(); - void qmUser_aboutToShow(); - void qmListener_aboutToShow(); - void on_qaUserCommentReset_triggered(); - void on_qaUserTextureReset_triggered(); - void on_qaUserCommentView_triggered(); - void on_qaUserKick_triggered(); - void on_qaUserBan_triggered(); - void on_qaUserMute_triggered(); - void on_qaUserDeaf_triggered(); - void on_qaSelfPrioritySpeaker_triggered(); - void on_qaUserPrioritySpeaker_triggered(); - void on_qaUserLocalIgnore_triggered(); - void on_qaUserLocalIgnoreTTS_triggered(); - void on_qaUserLocalMute_triggered(); - void on_qaUserLocalVolume_triggered(); - void on_qaUserTextMessage_triggered(); - void on_qaUserRegister_triggered(); - void on_qaUserInformation_triggered(); - void on_qaUserFriendAdd_triggered(); - void on_qaUserFriendRemove_triggered(); - void on_qaUserFriendUpdate_triggered(); - void qmChannel_aboutToShow(); - void on_qaChannelJoin_triggered(); - void on_qaUserJoin_triggered(); - void on_qaChannelListen_triggered(); - void on_qaChannelAdd_triggered(); - void on_qaChannelRemove_triggered(); - void on_qaChannelACL_triggered(); - void on_qaChannelLink_triggered(); - void on_qaChannelUnlink_triggered(); - void on_qaChannelUnlinkAll_triggered(); - void on_qaChannelSendMessage_triggered(); - void on_qaChannelFilter_triggered(); - void on_qaChannelCopyURL_triggered(); - void on_qaListenerLocalVolume_triggered(); - void on_qaAudioReset_triggered(); - void on_qaAudioMute_triggered(); - void on_qaAudioDeaf_triggered(); - void on_qaRecording_triggered(); - void on_qaAudioTTS_triggered(); - void on_qaAudioUnlink_triggered(); - void on_qaAudioStats_triggered(); - void on_qaConfigDialog_triggered(); - void on_qaConfigHideFrame_triggered(); - void on_qmConfig_aboutToShow(); - void on_qaConfigMinimal_triggered(); - void on_qaConfigCert_triggered(); - void on_qaAudioWizard_triggered(); - void on_qaDeveloperConsole_triggered(); - void on_qaHelpWhatsThis_triggered(); - void on_qaHelpAbout_triggered(); - void on_qaHelpAboutQt_triggered(); - void on_qaHelpVersionCheck_triggered(); - void on_qaQuit_triggered(); - void on_qaHide_triggered(); - void on_qteChat_tabPressed(); - void on_qteChat_backtabPressed(); - void on_qteChat_ctrlSpacePressed(); - void on_qtvUsers_customContextMenuRequested(const QPoint &mpos); - void on_qteLog_customContextMenuRequested(const QPoint &pos); - void on_qteLog_anchorClicked(const QUrl &); - void on_qteLog_highlighted(const QUrl & link); - void on_PushToTalk_triggered(bool, QVariant); - void on_PushToMute_triggered(bool, QVariant); - void on_VolumeUp_triggered(bool, QVariant); - void on_VolumeDown_triggered(bool, QVariant); - void on_gsMuteSelf_down(QVariant); - void on_gsDeafSelf_down(QVariant); - void on_gsWhisper_triggered(bool, QVariant); - void addTarget(ShortcutTarget *); - void removeTarget(ShortcutTarget *); - void on_gsCycleTransmitMode_triggered(bool, QVariant); - void on_gsTransmitModePushToTalk_triggered(bool, QVariant); - void on_gsTransmitModeContinuous_triggered(bool, QVariant); - void on_gsTransmitModeVAD_triggered(bool, QVariant); - void on_gsSendTextMessage_triggered(bool, QVariant); - void on_gsSendClipboardTextMessage_triggered(bool, QVariant); - void on_Reconnect_timeout(); - void on_Icon_activated(QSystemTrayIcon::ActivationReason); - void on_qaTalkingUIToggle_triggered(); - void voiceRecorderDialog_finished(int); - void qtvUserCurrentChanged(const QModelIndex &, const QModelIndex &); - void serverConnected(); - void serverDisconnected(QAbstractSocket::SocketError, QString reason); - void resolverError(QAbstractSocket::SocketError, QString reason); - void viewCertificate(bool); - void openUrl(const QUrl &url); - void context_triggered(); - void updateTarget(); - void updateMenuPermissions(); - /// Handles state changes like talking mode changes and mute/unmute - /// or priority speaker flag changes for the gui user - void userStateChanged(); - void destroyUserInformation(); - void trayAboutToShow(); - void sendChatbarMessage(QString msg); - void sendChatbarText(QString msg); - void pttReleased(); - void whisperReleased(QVariant scdata); - void onResetAudio(); - /// Called whenever the self-mute state may have changed. Dispatches - /// corkAudioInputStream() if the desire for audio input has changed. - void onChangeMute(); - void showRaiseWindow(); - void on_qaFilterToggle_triggered(); - /// Opens a save dialog for the image referenced by qtcSaveImageCursor. - void saveImageAs(); - /// Returns the path to the user's image directory, optionally with a - /// filename included. - QString getImagePath(QString filename = QString()) const; - /// Updates the user's image directory to the given path (any included - /// filename is discarded). - void updateImagePath(QString filepath) const; - signals: - /// Reports that audio input is now, or is no longer, required. - /// - /// Signal allows an \ref AudioInput to suspend the input stream - /// when it is not required. - /// - /// @param cork If true, the audio backend MAY now cork/suspend - /// the input stream. If false, the audio backend MUST immediately - /// un-cork/resume the stream. - void corkAudioInputStream(const bool cork); - /// Signal emitted when the server and the client have finished - /// synchronizing (after a new connection). - void serverSynchronized(); - /// Signal emitted whenever a user adds a new ChannelListener - void userAddedChannelListener(ClientUser *user, Channel *channel); - /// Signal emitted whenever a user removes a ChannelListener - void userRemovedChannelListener(ClientUser *user, Channel *channel); - public: - MainWindow(QWidget *parent); - ~MainWindow() Q_DECL_OVERRIDE; - - // From msgHandler. Implementation in Messages.cpp -#define MUMBLE_MH_MSG(x) void msg##x(const MumbleProto:: x &); - MUMBLE_MH_ALL +protected: + Usage uUsage; + QTimer *qtReconnect; + + QList< QAction * > qlServerActions; + QList< QAction * > qlChannelActions; + QList< QAction * > qlUserActions; + + QHash< ShortcutTarget, int > qmCurrentTargets; + /// A map that contains information about the currently active + /// shout/whisper targets. The mapping is between a List of + /// ShortcutTargets that are all triggered together and the + /// target ID for this specific combination of ShortcutTargets. + /// The target ID is what the server uses to identify this specific + /// set of ShortcutTargets. + QHash< QList< ShortcutTarget >, int > qmTargets; + /// This is a map between all target IDs the client will ever use + /// and a helper-number (see iTargetCounter). + QMap< int, int > qmTargetUse; + Channel *mapChannel(int idx) const; + /// This is a pure helper number whose job is to always be increased + /// if a new VoiceTarget is needed. It will be used as the helper + /// number in qmTargetUse. + int iTargetCounter; + QMap< unsigned int, UserInformation * > qmUserInformations; + + PTTButtonWidget *qwPTTButtonWidget; + + MUComboBox *qcbTransmitMode; + QAction *qaTransmitMode; + QAction *qaTransmitModeSeparator; + + void createActions(); + void setupGui(); + void updateWindowTitle(); + /// updateToolbar updates the state of the toolbar depending on the current + /// window layout setting. + /// If the window layout setting is 'custom', the toolbar is made movable. If the + /// window layout is not 'custom', the toolbar is locked in place at the top of + /// the MainWindow. + void updateToolbar(); + void customEvent(QEvent *evt) Q_DECL_OVERRIDE; + void findDesiredChannel(); + void setupView(bool toggle_minimize = true); + void closeEvent(QCloseEvent *e) Q_DECL_OVERRIDE; + void hideEvent(QHideEvent *e) Q_DECL_OVERRIDE; + void showEvent(QShowEvent *e) Q_DECL_OVERRIDE; + void changeEvent(QEvent *e) Q_DECL_OVERRIDE; + void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; + + QMenu *createPopupMenu() Q_DECL_OVERRIDE; + + bool handleSpecialContextMenu(const QUrl &url, const QPoint &pos_, bool focus = false); + Channel *getContextMenuChannel(); + ClientUser *getContextMenuUser(); + +public slots: + void on_qmServer_aboutToShow(); + void on_qaServerConnect_triggered(bool autoconnect = false); + void on_qaServerDisconnect_triggered(); + void on_qaServerBanList_triggered(); + void on_qaServerUserList_triggered(); + void on_qaServerInformation_triggered(); + void on_qaServerTexture_triggered(); + void on_qaServerTextureRemove_triggered(); + void on_qaServerTokens_triggered(); + void on_qmSelf_aboutToShow(); + void on_qaSelfComment_triggered(); + void on_qaSelfRegister_triggered(); + void qcbTransmitMode_activated(int index); + void updateTransmitModeComboBox(); + void qmUser_aboutToShow(); + void qmListener_aboutToShow(); + void on_qaUserCommentReset_triggered(); + void on_qaUserTextureReset_triggered(); + void on_qaUserCommentView_triggered(); + void on_qaUserKick_triggered(); + void on_qaUserBan_triggered(); + void on_qaUserMute_triggered(); + void on_qaUserDeaf_triggered(); + void on_qaSelfPrioritySpeaker_triggered(); + void on_qaUserPrioritySpeaker_triggered(); + void on_qaUserLocalIgnore_triggered(); + void on_qaUserLocalIgnoreTTS_triggered(); + void on_qaUserLocalMute_triggered(); + void on_qaUserLocalVolume_triggered(); + void on_qaUserTextMessage_triggered(); + void on_qaUserRegister_triggered(); + void on_qaUserInformation_triggered(); + void on_qaUserFriendAdd_triggered(); + void on_qaUserFriendRemove_triggered(); + void on_qaUserFriendUpdate_triggered(); + void qmChannel_aboutToShow(); + void on_qaChannelJoin_triggered(); + void on_qaUserJoin_triggered(); + void on_qaChannelListen_triggered(); + void on_qaChannelAdd_triggered(); + void on_qaChannelRemove_triggered(); + void on_qaChannelACL_triggered(); + void on_qaChannelLink_triggered(); + void on_qaChannelUnlink_triggered(); + void on_qaChannelUnlinkAll_triggered(); + void on_qaChannelSendMessage_triggered(); + void on_qaChannelFilter_triggered(); + void on_qaChannelCopyURL_triggered(); + void on_qaListenerLocalVolume_triggered(); + void on_qaAudioReset_triggered(); + void on_qaAudioMute_triggered(); + void on_qaAudioDeaf_triggered(); + void on_qaRecording_triggered(); + void on_qaAudioTTS_triggered(); + void on_qaAudioUnlink_triggered(); + void on_qaAudioStats_triggered(); + void on_qaConfigDialog_triggered(); + void on_qaConfigHideFrame_triggered(); + void on_qmConfig_aboutToShow(); + void on_qaConfigMinimal_triggered(); + void on_qaConfigCert_triggered(); + void on_qaAudioWizard_triggered(); + void on_qaDeveloperConsole_triggered(); + void on_qaHelpWhatsThis_triggered(); + void on_qaHelpAbout_triggered(); + void on_qaHelpAboutQt_triggered(); + void on_qaHelpVersionCheck_triggered(); + void on_qaQuit_triggered(); + void on_qaHide_triggered(); + void on_qteChat_tabPressed(); + void on_qteChat_backtabPressed(); + void on_qteChat_ctrlSpacePressed(); + void on_qtvUsers_customContextMenuRequested(const QPoint &mpos); + void on_qteLog_customContextMenuRequested(const QPoint &pos); + void on_qteLog_anchorClicked(const QUrl &); + void on_qteLog_highlighted(const QUrl &link); + void on_PushToTalk_triggered(bool, QVariant); + void on_PushToMute_triggered(bool, QVariant); + void on_VolumeUp_triggered(bool, QVariant); + void on_VolumeDown_triggered(bool, QVariant); + void on_gsMuteSelf_down(QVariant); + void on_gsDeafSelf_down(QVariant); + void on_gsWhisper_triggered(bool, QVariant); + void addTarget(ShortcutTarget *); + void removeTarget(ShortcutTarget *); + void on_gsCycleTransmitMode_triggered(bool, QVariant); + void on_gsTransmitModePushToTalk_triggered(bool, QVariant); + void on_gsTransmitModeContinuous_triggered(bool, QVariant); + void on_gsTransmitModeVAD_triggered(bool, QVariant); + void on_gsSendTextMessage_triggered(bool, QVariant); + void on_gsSendClipboardTextMessage_triggered(bool, QVariant); + void on_Reconnect_timeout(); + void on_Icon_activated(QSystemTrayIcon::ActivationReason); + void on_qaTalkingUIToggle_triggered(); + void voiceRecorderDialog_finished(int); + void qtvUserCurrentChanged(const QModelIndex &, const QModelIndex &); + void serverConnected(); + void serverDisconnected(QAbstractSocket::SocketError, QString reason); + void resolverError(QAbstractSocket::SocketError, QString reason); + void viewCertificate(bool); + void openUrl(const QUrl &url); + void context_triggered(); + void updateTarget(); + void updateMenuPermissions(); + /// Handles state changes like talking mode changes and mute/unmute + /// or priority speaker flag changes for the gui user + void userStateChanged(); + void destroyUserInformation(); + void trayAboutToShow(); + void sendChatbarMessage(QString msg); + void sendChatbarText(QString msg); + void pttReleased(); + void whisperReleased(QVariant scdata); + void onResetAudio(); + /// Called whenever the self-mute state may have changed. Dispatches + /// corkAudioInputStream() if the desire for audio input has changed. + void onChangeMute(); + void showRaiseWindow(); + void on_qaFilterToggle_triggered(); + /// Opens a save dialog for the image referenced by qtcSaveImageCursor. + void saveImageAs(); + /// Returns the path to the user's image directory, optionally with a + /// filename included. + QString getImagePath(QString filename = QString()) const; + /// Updates the user's image directory to the given path (any included + /// filename is discarded). + void updateImagePath(QString filepath) const; +signals: + /// Reports that audio input is now, or is no longer, required. + /// + /// Signal allows an \ref AudioInput to suspend the input stream + /// when it is not required. + /// + /// @param cork If true, the audio backend MAY now cork/suspend + /// the input stream. If false, the audio backend MUST immediately + /// un-cork/resume the stream. + void corkAudioInputStream(const bool cork); + /// Signal emitted when the server and the client have finished + /// synchronizing (after a new connection). + void serverSynchronized(); + /// Signal emitted whenever a user adds a new ChannelListener + void userAddedChannelListener(ClientUser *user, Channel *channel); + /// Signal emitted whenever a user removes a ChannelListener + void userRemovedChannelListener(ClientUser *user, Channel *channel); + +public: + MainWindow(QWidget *parent); + ~MainWindow() Q_DECL_OVERRIDE; + + // From msgHandler. Implementation in Messages.cpp +#define MUMBLE_MH_MSG(x) void msg##x(const MumbleProto::x &); + MUMBLE_MH_ALL #undef MUMBLE_MH_MSG - void removeContextAction(const MumbleProto::ContextActionModify &msg); - /// Logs a message that an action could not be saved permanently because - /// the user has no certificate and can't be reliably identified. - /// - /// @param actionName The name of the action that has been executed. - /// @param p The user on which the action was performed. - void logChangeNotPermanent(const QString &actionName, ClientUser * const p) const; + void removeContextAction(const MumbleProto::ContextActionModify &msg); + /// Logs a message that an action could not be saved permanently because + /// the user has no certificate and can't be reliably identified. + /// + /// @param actionName The name of the action that has been executed. + /// @param p The user on which the action was performed. + void logChangeNotPermanent(const QString &actionName, ClientUser *const p) const; }; #endif diff --git a/src/mumble/ManualPlugin.cpp b/src/mumble/ManualPlugin.cpp index fef8c55e1..3af6efb41 100644 --- a/src/mumble/ManualPlugin.cpp +++ b/src/mumble/ManualPlugin.cpp @@ -9,25 +9,26 @@ #include <QtGui/QtGui> #include <QtWidgets/QMessageBox> -#include <QPointer> #include "ManualPlugin.h" #include "ui_ManualPlugin.h" +#include <QPointer> #include <float.h> #include "../../plugins/mumble_plugin.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -static QPointer<Manual> mDlg = nullptr; -static bool bLinkable = false; -static bool bActive = true; +static QPointer< Manual > mDlg = nullptr; +static bool bLinkable = false; +static bool bActive = true; -static int iAzimuth = 180; +static int iAzimuth = 180; static int iElevation = 0; -static const QString defaultContext = QString::fromLatin1("Mumble"); +static const QString defaultContext = QString::fromLatin1("Mumble"); static const QString defaultIdentity = QString::fromLatin1("Agent47"); static struct { @@ -39,10 +40,7 @@ static struct { float camera_top[3]; std::string context; std::wstring identity; -} my = {{0,0,0}, {0,0,0}, {0,0,0}, - {0,0,0}, {0,0,0}, {0,0,0}, - std::string(), std::wstring() -}; +} my = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, std::string(), std::wstring() }; Manual::Manual(QWidget *p) : QDialog(p) { setupUi(this); @@ -57,7 +55,7 @@ Manual::Manual(QWidget *p) : QDialog(p) { indicator.addEllipse(QRectF(-indicatorDiameter / 2, -indicatorDiameter / 2, indicatorDiameter, indicatorDiameter)); // A line will indicate the indicator's orientation (azimuth) indicator.moveTo(0, indicatorDiameter / 2); - indicator.lineTo(0, indicatorDiameter); + indicator.lineTo(0, indicatorDiameter); qgiPosition = qgsScene->addPath(indicator); @@ -84,7 +82,7 @@ Manual::Manual(QWidget *p) : QDialog(p) { // b) make the user aware of what each field might contain qleContext->setText(defaultContext); qleIdentity->setText(defaultIdentity); - my.context = defaultContext.toStdString(); + my.context = defaultContext.toStdString(); my.identity = defaultIdentity.toStdWString(); qsbSilentUserDisplaytime->setValue(g.s.manualPlugin_silentUserDisplaytime); @@ -92,15 +90,16 @@ Manual::Manual(QWidget *p) : QDialog(p) { updateLoopRunning.store(false); } -void Manual::setSpeakerPositions(const QHash<unsigned int, Position2D> &positions) { +void Manual::setSpeakerPositions(const QHash< unsigned int, Position2D > &positions) { if (mDlg) { - QMetaObject::invokeMethod(mDlg, "on_speakerPositionUpdate", Qt::QueuedConnection, Q_ARG(PositionMap, positions)); + QMetaObject::invokeMethod(mDlg, "on_speakerPositionUpdate", Qt::QueuedConnection, + Q_ARG(PositionMap, positions)); } } bool Manual::eventFilter(QObject *obj, QEvent *evt) { if ((evt->type() == QEvent::MouseButtonPress) || (evt->type() == QEvent::MouseMove)) { - QMouseEvent *qme = dynamic_cast<QMouseEvent *>(evt); + QMouseEvent *qme = dynamic_cast< QMouseEvent * >(evt); if (qme) { if (qme->buttons() & Qt::LeftButton) { QPointF qpf = qgvPosition->mapToScene(qme->pos()); @@ -139,16 +138,16 @@ void Manual::on_qpbActivated_clicked(bool b) { } void Manual::on_qdsbX_valueChanged(double d) { - my.avatar_pos[0] = my.camera_pos[0] = static_cast<float>(d); + my.avatar_pos[0] = my.camera_pos[0] = static_cast< float >(d); qgiPosition->setPos(my.avatar_pos[0], -my.avatar_pos[2]); } void Manual::on_qdsbY_valueChanged(double d) { - my.avatar_pos[1] = my.camera_pos[1] = static_cast<float>(d); + my.avatar_pos[1] = my.camera_pos[1] = static_cast< float >(d); } void Manual::on_qdsbZ_valueChanged(double d) { - my.avatar_pos[2] = my.camera_pos[2] = static_cast<float>(d); + my.avatar_pos[2] = my.camera_pos[2] = static_cast< float >(d); qgiPosition->setPos(my.avatar_pos[0], -my.avatar_pos[2]); } @@ -196,7 +195,7 @@ void Manual::on_buttonBox_clicked(QAbstractButton *button) { qpbActivated->setChecked(true); bLinkable = false; - bActive = true; + bActive = true; qdsbX->setValue(0); qdsbY->setValue(0); @@ -214,19 +213,19 @@ void Manual::on_qsbSilentUserDisplaytime_valueChanged(int value) { g.s.manualPlugin_silentUserDisplaytime = value; } -void Manual::on_speakerPositionUpdate(QHash<unsigned int, Position2D> positions) { +void Manual::on_speakerPositionUpdate(QHash< unsigned int, Position2D > positions) { // First iterate over the stale items to check whether one of them is actually no longer stale - QMutableHashIterator<unsigned int, StaleEntry> staleIt(staleSpeakerPositions); + QMutableHashIterator< unsigned int, StaleEntry > staleIt(staleSpeakerPositions); while (staleIt.hasNext()) { staleIt.next(); const unsigned int sessionID = staleIt.key(); - QGraphicsItem *staleItem = staleIt.value().staleItem; + QGraphicsItem *staleItem = staleIt.value().staleItem; if (positions.contains(sessionID)) { // The item is no longer stale -> restore opacity and re-insert into speakerPositions staleItem->setOpacity(1.0); - + staleIt.remove(); speakerPositions.insert(sessionID, staleItem); } else if (!updateLoopRunning.load()) { @@ -237,18 +236,18 @@ void Manual::on_speakerPositionUpdate(QHash<unsigned int, Position2D> positions) // Now iterate over all active items and check whether they have become stale or whether their // position can be updated - QMutableHashIterator<unsigned int, QGraphicsItem *> speakerIt(speakerPositions); + QMutableHashIterator< unsigned int, QGraphicsItem * > speakerIt(speakerPositions); while (speakerIt.hasNext()) { speakerIt.next(); const unsigned int sessionID = speakerIt.key(); - QGraphicsItem *speakerItem = speakerIt.value(); + QGraphicsItem *speakerItem = speakerIt.value(); if (positions.contains(sessionID)) { Position2D newPos = positions.take(sessionID); // Update speaker's position (remember that y-axis is inverted in screen-coordinates - speakerItem->setPos(newPos.x, - newPos.y); + speakerItem->setPos(newPos.x, -newPos.y); } else { // Remove the stale item speakerIt.remove(); @@ -262,12 +261,13 @@ void Manual::on_speakerPositionUpdate(QHash<unsigned int, Position2D> positions) } // Finally iterate over the remaining new speakers and create new items for them - QHashIterator<unsigned int, Position2D> remainingIt(positions); + QHashIterator< unsigned int, Position2D > remainingIt(positions); while (remainingIt.hasNext()) { remainingIt.next(); - const float speakerRadius = 1.2; - QGraphicsItem *speakerItem = qgsScene->addEllipse(-speakerRadius, -speakerRadius, 2 * speakerRadius, 2 * speakerRadius, QPen(), QBrush(Qt::red)); + const float speakerRadius = 1.2; + QGraphicsItem *speakerItem = qgsScene->addEllipse(-speakerRadius, -speakerRadius, 2 * speakerRadius, + 2 * speakerRadius, QPen(), QBrush(Qt::red)); Position2D pos = remainingIt.value(); @@ -287,13 +287,14 @@ void Manual::on_updateStaleSpeakers() { // Iterate over all stale items and check whether they have to be removed entirely. If not, update // their opacity. - QMutableHashIterator<unsigned int, StaleEntry> staleIt(staleSpeakerPositions); + QMutableHashIterator< unsigned int, StaleEntry > staleIt(staleSpeakerPositions); while (staleIt.hasNext()) { staleIt.next(); StaleEntry entry = staleIt.value(); - double elapsedTime = static_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - entry.staleSince).count(); + double elapsedTime = + static_cast< std::chrono::duration< double > >(std::chrono::steady_clock::now() - entry.staleSince).count(); if (elapsedTime >= g.s.manualPlugin_silentUserDisplaytime) { // The item has been around long enough - remove it now @@ -301,7 +302,8 @@ void Manual::on_updateStaleSpeakers() { delete entry.staleItem; } else { // Let the item fade out - double opacity = (g.s.manualPlugin_silentUserDisplaytime - elapsedTime) / static_cast<double>(g.s.manualPlugin_silentUserDisplaytime); + double opacity = (g.s.manualPlugin_silentUserDisplaytime - elapsedTime) + / static_cast< double >(g.s.manualPlugin_silentUserDisplaytime); entry.staleItem->setOpacity(opacity); } } @@ -316,7 +318,7 @@ void Manual::on_updateStaleSpeakers() { } void Manual::updateTopAndFront(int azimuth, int elevation) { - iAzimuth = azimuth; + iAzimuth = azimuth; iElevation = elevation; qgiPosition->setRotation(azimuth); @@ -324,13 +326,13 @@ void Manual::updateTopAndFront(int azimuth, int elevation) { double azim = azimuth * M_PI / 180.; double elev = elevation * M_PI / 180.; - my.avatar_front[0] = static_cast<float>(cos(elev) * sin(azim)); - my.avatar_front[1] = static_cast<float>(sin(elev)); - my.avatar_front[2] = static_cast<float>(cos(elev) * cos(azim)); + my.avatar_front[0] = static_cast< float >(cos(elev) * sin(azim)); + my.avatar_front[1] = static_cast< float >(sin(elev)); + my.avatar_front[2] = static_cast< float >(cos(elev) * cos(azim)); - my.avatar_top[0] = static_cast<float>(-sin(elev) * sin(azim)); - my.avatar_top[1] = static_cast<float>(cos(elev)); - my.avatar_top[2] = static_cast<float>(-sin(elev) * cos(azim)); + my.avatar_top[0] = static_cast< float >(-sin(elev) * sin(azim)); + my.avatar_top[1] = static_cast< float >(cos(elev)); + my.avatar_top[2] = static_cast< float >(-sin(elev) * cos(azim)); memcpy(my.camera_top, my.avatar_top, sizeof(float) * 3); memcpy(my.camera_front, my.avatar_front, sizeof(float) * 3); @@ -348,7 +350,7 @@ static void unlock() { } static void config(void *ptr) { - QWidget *w = reinterpret_cast<QWidget *>(ptr); + QWidget *w = reinterpret_cast< QWidget * >(ptr); if (mDlg) { mDlg->setParent(w, Qt::Dialog); @@ -360,23 +362,24 @@ static void config(void *ptr) { mDlg->show(); } -static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) { +static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, + float *camera_top, std::string &context, std::wstring &identity) { if (!bLinkable) return false; if (!bActive) { - memset(avatar_pos, 0, sizeof(float)*3); - memset(camera_pos, 0, sizeof(float)*3); + memset(avatar_pos, 0, sizeof(float) * 3); + memset(camera_pos, 0, sizeof(float) * 3); return true; } - memcpy(avatar_pos, my.avatar_pos, sizeof(float)*3); - memcpy(avatar_front, my.avatar_front, sizeof(float)*3); - memcpy(avatar_top, my.avatar_top, sizeof(float)*3); + memcpy(avatar_pos, my.avatar_pos, sizeof(float) * 3); + memcpy(avatar_front, my.avatar_front, sizeof(float) * 3); + memcpy(avatar_top, my.avatar_top, sizeof(float) * 3); - memcpy(camera_pos, my.camera_pos, sizeof(float)*3); - memcpy(camera_front, my.camera_front, sizeof(float)*3); - memcpy(camera_top, my.camera_top, sizeof(float)*3); + memcpy(camera_pos, my.camera_pos, sizeof(float) * 3); + memcpy(camera_front, my.camera_front, sizeof(float) * 3); + memcpy(camera_top, my.camera_top, sizeof(float) * 3); context.assign(my.context); identity.assign(my.identity); @@ -392,32 +395,22 @@ static std::wstring description(L"Manual placement plugin"); static std::wstring shortname(L"Manual placement"); static void about(void *ptr) { - QWidget *w = reinterpret_cast<QWidget *>(ptr); + QWidget *w = reinterpret_cast< QWidget * >(ptr); - QMessageBox::about( - w, - QString::fromStdWString(description), - QString::fromStdWString(longdesc()) - ); + QMessageBox::about(w, QString::fromStdWString(description), QString::fromStdWString(longdesc())); } -static MumblePlugin manual = { - MUMBLE_PLUGIN_MAGIC, - description, - shortname, - nullptr, // About is handled by MumblePluginQt - nullptr, // Config is handled by MumblePluginQt - trylock, - unlock, - longdesc, - fetch -}; - -static MumblePluginQt manualqt = { - MUMBLE_PLUGIN_MAGIC_QT, - about, - config -}; +static MumblePlugin manual = { MUMBLE_PLUGIN_MAGIC, + description, + shortname, + nullptr, // About is handled by MumblePluginQt + nullptr, // Config is handled by MumblePluginQt + trylock, + unlock, + longdesc, + fetch }; + +static MumblePluginQt manualqt = { MUMBLE_PLUGIN_MAGIC_QT, about, config }; MumblePlugin *ManualPlugin_getMumblePlugin() { return &manual; diff --git a/src/mumble/ManualPlugin.h b/src/mumble/ManualPlugin.h index af473e721..82da53a28 100644 --- a/src/mumble/ManualPlugin.h +++ b/src/mumble/ManualPlugin.h @@ -25,7 +25,7 @@ struct Position2D { // We need this typedef in order to be able to pass this hash as an argument // to QMetaObject::invokeMethod -using PositionMap = QHash<unsigned int, Position2D>; +using PositionMap = QHash< unsigned int, Position2D >; Q_DECLARE_METATYPE(PositionMap); @@ -33,50 +33,51 @@ Q_DECLARE_METATYPE(PositionMap); /// manual plugin's position window struct StaleEntry { /// The time point since when this entry is considered stale - std::chrono::time_point<std::chrono::steady_clock> staleSince; + std::chrono::time_point< std::chrono::steady_clock > staleSince; /// The pointer to the stale item QGraphicsItem *staleItem; }; class Manual : public QDialog, public Ui::Manual { - Q_OBJECT - public: - Manual(QWidget *parent = 0); - - static void setSpeakerPositions(const QHash<unsigned int, Position2D> &positions); - - - public slots: - void on_qpbUnhinge_pressed(); - void on_qpbLinked_clicked(bool); - void on_qpbActivated_clicked(bool); - void on_qdsbX_valueChanged(double); - void on_qdsbY_valueChanged(double); - void on_qdsbZ_valueChanged(double); - void on_qsbAzimuth_valueChanged(int); - void on_qsbElevation_valueChanged(int); - void on_qdAzimuth_valueChanged(int); - void on_qdElevation_valueChanged(int); - void on_qleContext_editingFinished(); - void on_qleIdentity_editingFinished(); - void on_buttonBox_clicked(QAbstractButton *); - void on_qsbSilentUserDisplaytime_valueChanged(int); - - void on_speakerPositionUpdate(PositionMap positions); - - void on_updateStaleSpeakers(); - protected: - QGraphicsScene *qgsScene; - QGraphicsItem *qgiPosition; - - std::atomic<bool> updateLoopRunning; - - QHash<unsigned int, QGraphicsItem *> speakerPositions; - QHash<unsigned int, StaleEntry> staleSpeakerPositions; - - bool eventFilter(QObject *, QEvent *); - void changeEvent(QEvent *e); - void updateTopAndFront(int orientation, int azimut); + Q_OBJECT +public: + Manual(QWidget *parent = 0); + + static void setSpeakerPositions(const QHash< unsigned int, Position2D > &positions); + + +public slots: + void on_qpbUnhinge_pressed(); + void on_qpbLinked_clicked(bool); + void on_qpbActivated_clicked(bool); + void on_qdsbX_valueChanged(double); + void on_qdsbY_valueChanged(double); + void on_qdsbZ_valueChanged(double); + void on_qsbAzimuth_valueChanged(int); + void on_qsbElevation_valueChanged(int); + void on_qdAzimuth_valueChanged(int); + void on_qdElevation_valueChanged(int); + void on_qleContext_editingFinished(); + void on_qleIdentity_editingFinished(); + void on_buttonBox_clicked(QAbstractButton *); + void on_qsbSilentUserDisplaytime_valueChanged(int); + + void on_speakerPositionUpdate(PositionMap positions); + + void on_updateStaleSpeakers(); + +protected: + QGraphicsScene *qgsScene; + QGraphicsItem *qgiPosition; + + std::atomic< bool > updateLoopRunning; + + QHash< unsigned int, QGraphicsItem * > speakerPositions; + QHash< unsigned int, StaleEntry > staleSpeakerPositions; + + bool eventFilter(QObject *, QEvent *); + void changeEvent(QEvent *e); + void updateTopAndFront(int orientation, int azimut); }; MumblePlugin *ManualPlugin_getMumblePlugin(); diff --git a/src/mumble/Markdown.cpp b/src/mumble/Markdown.cpp index f430766d4..8d877b4ed 100644 --- a/src/mumble/Markdown.cpp +++ b/src/mumble/Markdown.cpp @@ -9,347 +9,353 @@ #include <QRegularExpressionMatch> namespace Markdown { - // Placeholder constant - const QLatin1String regularLineBreakPlaceholder("%<\\!!linebreak!!//>@"); +// Placeholder constant +const QLatin1String regularLineBreakPlaceholder("%<\\!!linebreak!!//>@"); - /// Tries to match and replace an escaped character at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processEscapedChar(QString &str, int &offset) { - static const QRegularExpression s_regex(QLatin1String("\\\\(.)")); +/// Tries to match and replace an escaped character at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processEscapedChar(QString &str, int &offset) { + static const QRegularExpression s_regex(QLatin1String("\\\\(.)")); - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - if (match.hasMatch()) { - QString replacement = QString::fromLatin1("%1").arg(match.captured(1)); + if (match.hasMatch()) { + QString replacement = QString::fromLatin1("%1").arg(match.captured(1)); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - offset += replacement.size(); + offset += replacement.size(); - return true; - } - - return false; + return true; } - /// Tries to match and replace a markdown section header at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownHeader(QString &str, int &offset) { - // Match a markdown section heading. Also eat up a potential following newline in order to - // not create a huge spacing after the heading - static const QRegularExpression s_regex(QLatin1String("^(#+) (.*)"), QRegularExpression::MultilineOption); + return false; +} - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); +/// Tries to match and replace a markdown section header at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownHeader(QString &str, int &offset) { + // Match a markdown section heading. Also eat up a potential following newline in order to + // not create a huge spacing after the heading + static const QRegularExpression s_regex(QLatin1String("^(#+) (.*)"), QRegularExpression::MultilineOption); - if (match.hasMatch()) { - int sectionLevel = match.captured(1).size(); - QString sectionName = match.captured(2); + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - QString replacement = QString::fromLatin1("<h%1>%2</h%1>").arg(sectionLevel).arg(sectionName); + if (match.hasMatch()) { + int sectionLevel = match.captured(1).size(); + QString sectionName = match.captured(2); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + QString replacement = QString::fromLatin1("<h%1>%2</h%1>").arg(sectionLevel).arg(sectionName); - offset += replacement.size(); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a markdown link at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownLink(QString &str, int &offset) { - // Link in format [link text](url) - static const QRegularExpression s_regex(QLatin1String("\\[([^\\]\\[]+)\\]\\(([^\\)]+)\\)")); - - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - - if (match.hasMatch()) { - QString url = match.captured(2); - - if (!url.startsWith(QLatin1String("http"), Qt::CaseInsensitive)) { - // For a markdown link to work, it has to start with the protocol specification, e.g. http or https - // As we can't know for sure that the given website supports https, we'll have to fall back to http - // Most browsers will upgrade the request to https whenver possible anyways though, so this shouldn't be - // too much of a problem. - url = QLatin1String("http://") + url; - } - - QString replacement = QString::fromLatin1("<a href=\"%1\">%2</a>").arg(url).arg(match.captured(1)); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + return false; +} + +/// Tries to match and replace a markdown link at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownLink(QString &str, int &offset) { + // Link in format [link text](url) + static const QRegularExpression s_regex(QLatin1String("\\[([^\\]\\[]+)\\]\\(([^\\)]+)\\)")); + + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); + + if (match.hasMatch()) { + QString url = match.captured(2); + + if (!url.startsWith(QLatin1String("http"), Qt::CaseInsensitive)) { + // For a markdown link to work, it has to start with the protocol specification, e.g. http or https + // As we can't know for sure that the given website supports https, we'll have to fall back to http + // Most browsers will upgrade the request to https whenver possible anyways though, so this shouldn't be + // too much of a problem. + url = QLatin1String("http://") + url; + } - offset += replacement.size(); + QString replacement = QString::fromLatin1("<a href=\"%1\">%2</a>").arg(url).arg(match.captured(1)); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a markdown bold-text at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownBold(QString &str, int &offset) { - // Bold text is marked as **bold** - static const QRegularExpression s_regex(QLatin1String("\\*\\*([^*]+)\\*\\*")); + return false; +} - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); +/// Tries to match and replace a markdown bold-text at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownBold(QString &str, int &offset) { + // Bold text is marked as **bold** + static const QRegularExpression s_regex(QLatin1String("\\*\\*([^*]+)\\*\\*")); - if (match.hasMatch()) { - QString replacement = QString::fromLatin1("<b>%1</b>").arg(match.captured(1)); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - offset += replacement.size(); + if (match.hasMatch()) { + QString replacement = QString::fromLatin1("<b>%1</b>").arg(match.captured(1)); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a markdown italic-text at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownItalic(QString &str, int &offset) { - // Italic text is marked as *italic* - static const QRegularExpression s_regex(QLatin1String("\\*([^*]+)\\*")); + return false; +} - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); +/// Tries to match and replace a markdown italic-text at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownItalic(QString &str, int &offset) { + // Italic text is marked as *italic* + static const QRegularExpression s_regex(QLatin1String("\\*([^*]+)\\*")); - if (match.hasMatch()) { - QString replacement = QString::fromLatin1("<i>%1</i>").arg(match.captured(1)); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - offset += replacement.size(); + if (match.hasMatch()) { + QString replacement = QString::fromLatin1("<i>%1</i>").arg(match.captured(1)); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a markdown strikethrough-text at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownStrikethrough(QString &str, int &offset) { - // Strikethrough text is marked as ~~text~~ - static const QRegularExpression s_regex(QLatin1String("~~([^~]+)~~")); + return false; +} - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); +/// Tries to match and replace a markdown strikethrough-text at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownStrikethrough(QString &str, int &offset) { + // Strikethrough text is marked as ~~text~~ + static const QRegularExpression s_regex(QLatin1String("~~([^~]+)~~")); - if (match.hasMatch()) { - QString replacement = QString::fromLatin1("<s>%1</s>").arg(match.captured(1)); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - offset += replacement.size(); + if (match.hasMatch()) { + QString replacement = QString::fromLatin1("<s>%1</s>").arg(match.captured(1)); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a markdown quote (blockquote) at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownBlockQuote(QString &str, int &offset) { - // Block quotes are (consecutive) lines starting with "> " - static const QRegularExpression s_regex(QLatin1String("^(>|>) (.|\\n(>|>) )+"), QRegularExpression::MultilineOption); + return false; +} - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); +/// Tries to match and replace a markdown quote (blockquote) at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownBlockQuote(QString &str, int &offset) { + // Block quotes are (consecutive) lines starting with "> " + static const QRegularExpression s_regex(QLatin1String("^(>|>) (.|\\n(>|>) )+"), + QRegularExpression::MultilineOption); - if (match.hasMatch()) { - QString quote = match.captured(0).replace(QLatin1String(">"), QLatin1String(">")); + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - QStringList lines = quote.split(QChar::fromLatin1('\n')); + if (match.hasMatch()) { + QString quote = match.captured(0).replace(QLatin1String(">"), QLatin1String(">")); - quote.clear(); - for (int i = 0; i < lines.size(); i++) { - // remove the leading "> " - quote += lines[i].right(lines[i].size() - 2); + QStringList lines = quote.split(QChar::fromLatin1('\n')); - if (i != lines.size() - 1) { - // Add linebreak back in - quote += QString::fromLatin1("\n"); - } - } + quote.clear(); + for (int i = 0; i < lines.size(); i++) { + // remove the leading "> " + quote += lines[i].right(lines[i].size() - 2); - QString replacement = QString::fromLatin1("<div><i>%1</i></div>").arg(quote.replace(QLatin1String("\n"), QLatin1String("<br/>"))); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + if (i != lines.size() - 1) { + // Add linebreak back in + quote += QString::fromLatin1("\n"); + } + } - offset += replacement.size(); + QString replacement = + QString::fromLatin1("<div><i>%1</i></div>").arg(quote.replace(QLatin1String("\n"), QLatin1String("<br/>"))); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a markdown inline code snippet at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownInlineCode(QString &str, int &offset) { - // Inline code fragments are marked as `code` - static const QRegularExpression s_regex(QLatin1String("`([^`\n]+)`")); + return false; +} - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); +/// Tries to match and replace a markdown inline code snippet at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownInlineCode(QString &str, int &offset) { + // Inline code fragments are marked as `code` + static const QRegularExpression s_regex(QLatin1String("`([^`\n]+)`")); - if (match.hasMatch()) { - QString replacement = QString::fromLatin1("<code>%1</code>").arg(match.captured(1)); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - offset += replacement.size(); + if (match.hasMatch()) { + QString replacement = QString::fromLatin1("<code>%1</code>").arg(match.captured(1)); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a markdown code block at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processMarkdownCodeBlock(QString &str, int &offset) { - // Code blocks are marked as ```code``` - // Also consume a potential following newline as the <pre> tag will cause a linebreak anyways - static const QRegularExpression s_regex(QLatin1String("```.*\\n([^`]+)```(\\r\\n|\\n|\\r)?")); - - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - - if (match.hasMatch()) { - QString code = match.captured(1); - - // Trim away leading linebreaks - while (code.size() >= 1 && (code[0] == QLatin1Char('\n') || code[0] == QLatin1Char('\r'))) { - code = code.right(code.size() - 1); - } - // Trim end of string - while (code.size() >= 1 && code[code.size() - 1].isSpace()) { - code = code.left(code.size() - 1); - } - - if (code.isEmpty()) { - return false; - } + return false; +} + +/// Tries to match and replace a markdown code block at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processMarkdownCodeBlock(QString &str, int &offset) { + // Code blocks are marked as ```code``` + // Also consume a potential following newline as the <pre> tag will cause a linebreak anyways + static const QRegularExpression s_regex(QLatin1String("```.*\\n([^`]+)```(\\r\\n|\\n|\\r)?")); + + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); + + if (match.hasMatch()) { + QString code = match.captured(1); + + // Trim away leading linebreaks + while (code.size() >= 1 && (code[0] == QLatin1Char('\n') || code[0] == QLatin1Char('\r'))) { + code = code.right(code.size() - 1); + } + // Trim end of string + while (code.size() >= 1 && code[code.size() - 1].isSpace()) { + code = code.left(code.size() - 1); + } - // Replace linebreaks with a special placeholder as the linebreaks in a <pre> block must not be replaced - // with <br/> - QString replacement = QString::fromLatin1("<pre>%1</pre>").arg(code.replace(QLatin1String("\n"), regularLineBreakPlaceholder)); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + if (code.isEmpty()) { + return false; + } - offset += replacement.size(); + // Replace linebreaks with a special placeholder as the linebreaks in a <pre> block must not be replaced + // with <br/> + QString replacement = + QString::fromLatin1("<pre>%1</pre>").arg(code.replace(QLatin1String("\n"), regularLineBreakPlaceholder)); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - /// Tries to match and replace a plain link at exactly the given offset in the string - /// - /// @param str A reference to the String to work on - /// @param offset The offset at which the matching shall be done. This will be modified to point right after - /// replacement text, if such a replacement has been made. - /// @returns Whether a replacement has been made - bool processPlainLink(QString &str, int &offset) { - // We support links with prefixed protocol (e.g. https://bla.com) and prefixed with www (e.g. www.bla.com) - static const QRegularExpression s_regex(QLatin1String("([a-zA-Z]+://|[wW][wW][wW]\\.)[^ \\t\\n<]+")); - - QRegularExpressionMatch match = s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); - - if (match.hasMatch()) { - QString url = match.captured(0); - QString urlText = url; - - if (url.startsWith(QLatin1String("www"), Qt::CaseInsensitive)) { - // Link is missing a protocol specification. - // Use http as the default - url = QLatin1String("http://") + url; - } - - QString replacement = QString::fromLatin1("<a href=\"%1\">%2</a>").arg(url).arg(urlText); - str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); + return false; +} + +/// Tries to match and replace a plain link at exactly the given offset in the string +/// +/// @param str A reference to the String to work on +/// @param offset The offset at which the matching shall be done. This will be modified to point right after +/// replacement text, if such a replacement has been made. +/// @returns Whether a replacement has been made +bool processPlainLink(QString &str, int &offset) { + // We support links with prefixed protocol (e.g. https://bla.com) and prefixed with www (e.g. www.bla.com) + static const QRegularExpression s_regex(QLatin1String("([a-zA-Z]+://|[wW][wW][wW]\\.)[^ \\t\\n<]+")); + + QRegularExpressionMatch match = + s_regex.match(str, offset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); + + if (match.hasMatch()) { + QString url = match.captured(0); + QString urlText = url; + + if (url.startsWith(QLatin1String("www"), Qt::CaseInsensitive)) { + // Link is missing a protocol specification. + // Use http as the default + url = QLatin1String("http://") + url; + } - offset += replacement.size(); + QString replacement = QString::fromLatin1("<a href=\"%1\">%2</a>").arg(url).arg(urlText); + str.replace(match.capturedStart(), match.capturedEnd() - match.capturedStart(), replacement); - return true; - } + offset += replacement.size(); - return false; + return true; } - QString markdownToHTML(const QString &markdownInput) { - QString htmlString = markdownInput; - int offset = 0; - - while (offset < htmlString.size()) { - // The trick here is to know that in a condition the or-branches are only - // processed until the first expression returns true. At this point no - // lower or-branch will be executed. This results in each of these functions - // being called in succession until the first returns true (meaning that it - // was able to recognize and replace a pattern). - // Each function will only try to match its pattern at the exact offset given. - // If a function was able to match and replace, it'll update the offset by - // itself in order for the processing to start over right after the replacement - // text (avoiding replacing parts of the replacement text which will probably - // render the initial replacement invalid). - // If no function matches, we increase the offset manually. - // Do this until the end of the text has been reached. - if (!( - processMarkdownHeader(htmlString, offset) - || processMarkdownLink(htmlString, offset) - || processMarkdownBold(htmlString, offset) - || processMarkdownItalic(htmlString, offset) - || processMarkdownStrikethrough(htmlString, offset) - || processMarkdownBlockQuote(htmlString, offset) - || processMarkdownCodeBlock(htmlString, offset) - || processMarkdownInlineCode(htmlString, offset) - || processPlainLink(htmlString, offset) - || processEscapedChar(htmlString, offset) - )) { - offset++; - } + return false; +} + +QString markdownToHTML(const QString &markdownInput) { + QString htmlString = markdownInput; + int offset = 0; + + while (offset < htmlString.size()) { + // The trick here is to know that in a condition the or-branches are only + // processed until the first expression returns true. At this point no + // lower or-branch will be executed. This results in each of these functions + // being called in succession until the first returns true (meaning that it + // was able to recognize and replace a pattern). + // Each function will only try to match its pattern at the exact offset given. + // If a function was able to match and replace, it'll update the offset by + // itself in order for the processing to start over right after the replacement + // text (avoiding replacing parts of the replacement text which will probably + // render the initial replacement invalid). + // If no function matches, we increase the offset manually. + // Do this until the end of the text has been reached. + if (!(processMarkdownHeader(htmlString, offset) || processMarkdownLink(htmlString, offset) + || processMarkdownBold(htmlString, offset) || processMarkdownItalic(htmlString, offset) + || processMarkdownStrikethrough(htmlString, offset) || processMarkdownBlockQuote(htmlString, offset) + || processMarkdownCodeBlock(htmlString, offset) || processMarkdownInlineCode(htmlString, offset) + || processPlainLink(htmlString, offset) || processEscapedChar(htmlString, offset))) { + offset++; } + } - // Replace linebreaks afterwards in order to not mess up the RegEx used by the - // different functions. - static const QRegularExpression s_lineBreakRegEx(QLatin1String("\r\n|\n|\r")); - htmlString.replace(s_lineBreakRegEx, QLatin1String("</br>")); + // Replace linebreaks afterwards in order to not mess up the RegEx used by the + // different functions. + static const QRegularExpression s_lineBreakRegEx(QLatin1String("\r\n|\n|\r")); + htmlString.replace(s_lineBreakRegEx, QLatin1String("</br>")); - // Resore linebreaks in <pre> blocks - htmlString.replace(regularLineBreakPlaceholder, QLatin1String("\n")); + // Resore linebreaks in <pre> blocks + htmlString.replace(regularLineBreakPlaceholder, QLatin1String("\n")); - return htmlString; - } + return htmlString; +} }; // namespace Markdown diff --git a/src/mumble/Markdown.h b/src/mumble/Markdown.h index 033d796d3..1684dd670 100644 --- a/src/mumble/Markdown.h +++ b/src/mumble/Markdown.h @@ -9,12 +9,12 @@ #include <QString> namespace Markdown { - /// Converts the given piece of text, interprets it as markdown and replaces - /// the markdown constructs with the respective HTML ones. - /// - /// @param markdownInput A reference to the input string - /// @returns The processed HTML string - QString markdownToHTML(const QString &markdownInput); +/// Converts the given piece of text, interprets it as markdown and replaces +/// the markdown constructs with the respective HTML ones. +/// +/// @param markdownInput A reference to the input string +/// @returns The processed HTML string +QString markdownToHTML(const QString &markdownInput); }; // namespace Markdown #endif // MUMBLE_MUMBLE_MARKDOWN_H_ diff --git a/src/mumble/Messages.cpp b/src/mumble/Messages.cpp index a4717f918..b2f47fd32 100644 --- a/src/mumble/Messages.cpp +++ b/src/mumble/Messages.cpp @@ -7,61 +7,62 @@ /// Further details on what exactly is contained in the "message objects" that are parameters to all functions /// in this file, can be found in the src/Mumble.proto file. -#include "About.h" #include "ACLEditor.h" +#include "About.h" #include "AudioInput.h" #include "AudioStats.h" #include "AudioWizard.h" #include "BanEditor.h" #include "Channel.h" -#include "Connection.h" #include "ConnectDialog.h" +#include "Connection.h" #include "Database.h" -#include "GlobalShortcut.h" #include "Log.h" #include "MainWindow.h" +#include "GlobalShortcut.h" #ifdef USE_OVERLAY - #include "Overlay.h" +# include "Overlay.h" #endif +#include "ChannelListener.h" #include "Plugins.h" #include "ServerHandler.h" +#include "TalkingUI.h" #include "User.h" #include "UserEdit.h" #include "UserInformation.h" #include "UserModel.h" +#include "Utils.h" #include "VersionCheck.h" #include "ViewCert.h" #include "crypto/CryptState.h" -#include "Utils.h" -#include "ChannelListener.h" -#include "TalkingUI.h" #include <QTextDocumentFragment> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -#define ACTOR_INIT \ - ClientUser *pSrc=nullptr; \ - if (msg.has_actor()) \ +#define ACTOR_INIT \ + ClientUser *pSrc = nullptr; \ + if (msg.has_actor()) \ pSrc = ClientUser::get(msg.actor()); \ Q_UNUSED(pSrc); -#define VICTIM_INIT \ - ClientUser *pDst=ClientUser::get(msg.session()); \ - if (!pDst) { \ - qWarning("MainWindow: Message for nonexistent victim %d.", msg.session()); \ - return; \ +#define VICTIM_INIT \ + ClientUser *pDst = ClientUser::get(msg.session()); \ + if (!pDst) { \ + qWarning("MainWindow: Message for nonexistent victim %d.", msg.session()); \ + return; \ } -#define SELF_INIT \ - ClientUser *pSelf = ClientUser::get(g.uiSession); \ - if (!pSelf) { \ +#define SELF_INIT \ + ClientUser *pSelf = ClientUser::get(g.uiSession); \ + if (!pSelf) { \ qWarning("MainWindow: Received message outside of session (sid %d).", g.uiSession); \ - return; \ + return; \ } -/// The authenticate message is being used by the client to send the authentication credentials to the server. Therefore the -/// server won't send this message type to the client which is why this implementation does nothing. +/// The authenticate message is being used by the client to send the authentication credentials to the server. Therefore +/// the server won't send this message type to the client which is why this implementation does nothing. void MainWindow::msgAuthenticate(const MumbleProto::Authenticate &) { } @@ -111,10 +112,10 @@ void MainWindow::msgReject(const MumbleProto::Reject &msg) { g.l->setIgnore(Log::ServerDisconnected, 1); } -/// This message is being received when the server has authenticated the user and finished synchronizing the server state. -/// The message contains the session ID (user ID) for this client that gets assigned to Global::uiSession. It also contains -/// information about the maximum bandwidth the user should use and the user's permissions in the root channel. Furthermore -/// the message may contain a welcome message that is logged to Mumble's console if present. +/// This message is being received when the server has authenticated the user and finished synchronizing the server +/// state. The message contains the session ID (user ID) for this client that gets assigned to Global::uiSession. It +/// also contains information about the maximum bandwidth the user should use and the user's permissions in the root +/// channel. Furthermore the message may contain a welcome message that is logged to Mumble's console if present. /// /// @param msg The message object with the respective information void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) { @@ -128,7 +129,7 @@ void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) { g.sh->sendPing(); // Send initial ping to establish UDP connection - g.pPermissions = ChanACL::Permissions(static_cast<unsigned int>(msg.permissions())); + g.pPermissions = ChanACL::Permissions(static_cast< unsigned int >(msg.permissions())); g.l->clearIgnore(); if (msg.has_welcome_text()) { QString str = u8(msg.welcome_text()); @@ -158,22 +159,22 @@ void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) { g.sh->getConnectionInfo(host, port, uname, pw); - QList<Shortcut> sc = g.db->getShortcuts(g.sh->qbaDigest); - if (! sc.isEmpty()) { - for (int i=0;i<sc.count(); ++i) { + QList< Shortcut > sc = g.db->getShortcuts(g.sh->qbaDigest); + if (!sc.isEmpty()) { + for (int i = 0; i < sc.count(); ++i) { Shortcut &s = sc[i]; - s.iIndex = g.mw->gsWhisper->idx; + s.iIndex = g.mw->gsWhisper->idx; } g.s.qlShortcuts << sc; GlobalShortcutEngine::engine->bNeedRemap = true; } - + connect(user, SIGNAL(talkingStateChanged()), this, SLOT(userStateChanged())); connect(user, SIGNAL(muteDeafStateChanged()), this, SLOT(userStateChanged())); connect(user, SIGNAL(prioritySpeakerStateChanged()), this, SLOT(userStateChanged())); connect(user, SIGNAL(recordingStateChanged()), this, SLOT(userStateChanged())); - + qstiIcon->setToolTip(tr("Mumble: %1").arg(Channel::get(0)->qsName.toHtmlEscaped())); // Update QActions and menus @@ -186,7 +187,7 @@ void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) { updateTrayIcon(); // Set-up all ChannelListeners and their volume adjustments as before for this server - QList<int> localListeners = g.db->getChannelListeners(g.sh->qbaDigest); + QList< int > localListeners = g.db->getChannelListeners(g.sh->qbaDigest); if (!localListeners.isEmpty()) { ChannelListener::setInitialServerSyncDone(false); @@ -196,10 +197,10 @@ void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) { ChannelListener::setInitialServerSyncDone(true); } - QHash<int, float> volumeMap = g.db->getChannelListenerLocalVolumeAdjustments(g.sh->qbaDigest); + QHash< int, float > volumeMap = g.db->getChannelListenerLocalVolumeAdjustments(g.sh->qbaDigest); - QHashIterator<int, float> it(volumeMap); - while(it.hasNext()) { + QHashIterator< int, float > it(volumeMap); + while (it.hasNext()) { it.next(); ChannelListener::setListenerLocalVolumeAdjustment(it.key(), it.value()); } @@ -211,8 +212,8 @@ void MainWindow::msgServerSync(const MumbleProto::ServerSync &msg) { } /// This message is being received when the server informs this client about server configuration details. This contains -/// things like the maximum bandwidth, the welcome text, whether HTML in messages is allowed, information about message lengths -/// as well as the maximum amount of users that may be connected to this server. +/// things like the maximum bandwidth, the welcome text, whether HTML in messages is allowed, information about message +/// lengths as well as the maximum amount of users that may be connected to this server. /// /// @param msg The message object void MainWindow::msgServerConfig(const MumbleProto::ServerConfig &msg) { @@ -241,101 +242,100 @@ void MainWindow::msgServerConfig(const MumbleProto::ServerConfig &msg) { void MainWindow::msgPermissionDenied(const MumbleProto::PermissionDenied &msg) { switch (msg.type()) { case MumbleProto::PermissionDenied_DenyType_Permission: { - VICTIM_INIT; - SELF_INIT; - Channel *c = Channel::get(msg.channel_id()); - if (! c) - return; - ChanACL::Permissions permission = static_cast<ChanACL::Permissions>(msg.permission()); - QString pname = ChanACL::permName(permission); - - if ((permission == ChanACL::Perm::Enter) && c->hasEnterRestrictions.load()) { - g.l->log(Log::PermissionDenied, tr("Unable to %1 into %2 - Adding the respective access (password) token might grant you access.").arg(Log::msgColor(pname, Log::Privilege)).arg(Log::formatChannel(c))); - } else { - if (pDst == pSelf) - g.l->log(Log::PermissionDenied, tr("You were denied %1 privileges in %2.").arg(Log::msgColor(pname, Log::Privilege)).arg(Log::formatChannel(c))); - else - g.l->log(Log::PermissionDenied, tr("%3 was denied %1 privileges in %2.").arg(Log::msgColor(pname, Log::Privilege)).arg(Log::formatChannel(c)).arg(Log::formatClientUser(pDst, Log::Target))); - } + VICTIM_INIT; + SELF_INIT; + Channel *c = Channel::get(msg.channel_id()); + if (!c) + return; + ChanACL::Permissions permission = static_cast< ChanACL::Permissions >(msg.permission()); + QString pname = ChanACL::permName(permission); + + if ((permission == ChanACL::Perm::Enter) && c->hasEnterRestrictions.load()) { + g.l->log( + Log::PermissionDenied, + tr("Unable to %1 into %2 - Adding the respective access (password) token might grant you access.") + .arg(Log::msgColor(pname, Log::Privilege)) + .arg(Log::formatChannel(c))); + } else { + if (pDst == pSelf) + g.l->log(Log::PermissionDenied, tr("You were denied %1 privileges in %2.") + .arg(Log::msgColor(pname, Log::Privilege)) + .arg(Log::formatChannel(c))); + else + g.l->log(Log::PermissionDenied, tr("%3 was denied %1 privileges in %2.") + .arg(Log::msgColor(pname, Log::Privilege)) + .arg(Log::formatChannel(c)) + .arg(Log::formatClientUser(pDst, Log::Target))); } - break; + } break; case MumbleProto::PermissionDenied_DenyType_SuperUser: { - g.l->log(Log::PermissionDenied, tr("Denied: Cannot modify SuperUser.")); - } - break; + g.l->log(Log::PermissionDenied, tr("Denied: Cannot modify SuperUser.")); + } break; case MumbleProto::PermissionDenied_DenyType_ChannelName: { - g.l->log(Log::PermissionDenied, tr("Denied: Invalid channel name.")); - } - break; + g.l->log(Log::PermissionDenied, tr("Denied: Invalid channel name.")); + } break; case MumbleProto::PermissionDenied_DenyType_TextTooLong: { - g.l->log(Log::PermissionDenied, tr("Denied: Text message too long.")); - } - break; + g.l->log(Log::PermissionDenied, tr("Denied: Text message too long.")); + } break; case MumbleProto::PermissionDenied_DenyType_H9K: { - if (g.bHappyEaster) { - bool bold = g.s.bDeaf; - bool bold2 = g.s.bTTS; - g.s.bDeaf = false; - g.s.bTTS = true; - quint32 oflags = g.s.qmMessages.value(Log::PermissionDenied); - g.s.qmMessages[Log::PermissionDenied] = (oflags | Settings::LogTTS) & (~Settings::LogSoundfile); - g.l->log(Log::PermissionDenied, QString::fromUtf8(g.ccHappyEaster + 39).arg(g.s.qsUsername.toHtmlEscaped())); - g.s.qmMessages[Log::PermissionDenied] = oflags; - g.s.bDeaf = bold; - g.s.bTTS = bold2; - g.mw->setWindowIcon(QIcon(QString::fromUtf8(g.ccHappyEaster))); - g.mw->setStyleSheet(QString::fromUtf8(g.ccHappyEaster + 82)); - qWarning() << "Happy Easter"; - } + if (g.bHappyEaster) { + bool bold = g.s.bDeaf; + bool bold2 = g.s.bTTS; + g.s.bDeaf = false; + g.s.bTTS = true; + quint32 oflags = g.s.qmMessages.value(Log::PermissionDenied); + g.s.qmMessages[Log::PermissionDenied] = (oflags | Settings::LogTTS) & (~Settings::LogSoundfile); + g.l->log(Log::PermissionDenied, + QString::fromUtf8(g.ccHappyEaster + 39).arg(g.s.qsUsername.toHtmlEscaped())); + g.s.qmMessages[Log::PermissionDenied] = oflags; + g.s.bDeaf = bold; + g.s.bTTS = bold2; + g.mw->setWindowIcon(QIcon(QString::fromUtf8(g.ccHappyEaster))); + g.mw->setStyleSheet(QString::fromUtf8(g.ccHappyEaster + 82)); + qWarning() << "Happy Easter"; } - break; + } break; case MumbleProto::PermissionDenied_DenyType_TemporaryChannel: { - g.l->log(Log::PermissionDenied, tr("Denied: Operation not permitted in temporary channel.")); - } - break; + g.l->log(Log::PermissionDenied, tr("Denied: Operation not permitted in temporary channel.")); + } break; case MumbleProto::PermissionDenied_DenyType_MissingCertificate: { - VICTIM_INIT; - SELF_INIT; - if (pDst == pSelf) - g.l->log(Log::PermissionDenied, tr("You need a certificate to perform this operation.")); - else - g.l->log(Log::PermissionDenied, tr("%1 does not have a certificate.").arg(Log::formatClientUser(pDst, Log::Target))); - } - break; + VICTIM_INIT; + SELF_INIT; + if (pDst == pSelf) + g.l->log(Log::PermissionDenied, tr("You need a certificate to perform this operation.")); + else + g.l->log(Log::PermissionDenied, + tr("%1 does not have a certificate.").arg(Log::formatClientUser(pDst, Log::Target))); + } break; case MumbleProto::PermissionDenied_DenyType_UserName: { - if (msg.has_name()) - g.l->log(Log::PermissionDenied, tr("Invalid username: %1.").arg(u8(msg.name()).toHtmlEscaped())); - else - g.l->log(Log::PermissionDenied, tr("Invalid username.")); - } - break; + if (msg.has_name()) + g.l->log(Log::PermissionDenied, tr("Invalid username: %1.").arg(u8(msg.name()).toHtmlEscaped())); + else + g.l->log(Log::PermissionDenied, tr("Invalid username.")); + } break; case MumbleProto::PermissionDenied_DenyType_ChannelFull: { - g.l->log(Log::PermissionDenied, tr("Channel is full.")); - } - break; + g.l->log(Log::PermissionDenied, tr("Channel is full.")); + } break; case MumbleProto::PermissionDenied_DenyType_NestingLimit: { - g.l->log(Log::PermissionDenied, tr("Channel nesting limit reached.")); - } - break; + g.l->log(Log::PermissionDenied, tr("Channel nesting limit reached.")); + } break; case MumbleProto::PermissionDenied_DenyType_ChannelCountLimit: { - g.l->log(Log::PermissionDenied, tr("Channel count limit reached. Need to delete channels before creating new ones.")); - } - break; + g.l->log(Log::PermissionDenied, + tr("Channel count limit reached. Need to delete channels before creating new ones.")); + } break; case MumbleProto::PermissionDenied_DenyType_ChannelListenerLimit: { - g.l->log(Log::PermissionDenied, tr("No more listeners allowed in this channel.")); - } - break; + g.l->log(Log::PermissionDenied, tr("No more listeners allowed in this channel.")); + } break; case MumbleProto::PermissionDenied_DenyType_UserListenerLimit: { - g.l->log(Log::PermissionDenied, tr("You are not allowed to listen to more channels than you currently are.")); - } - break; + g.l->log(Log::PermissionDenied, + tr("You are not allowed to listen to more channels than you currently are.")); + } break; default: { - if (msg.has_reason()) - g.l->log(Log::PermissionDenied, tr("Denied: %1.").arg(u8(msg.reason()).toHtmlEscaped())); - else - g.l->log(Log::PermissionDenied, tr("Permission denied.")); - } - break; + if (msg.has_reason()) + g.l->log(Log::PermissionDenied, tr("Denied: %1.").arg(u8(msg.reason()).toHtmlEscaped())); + else + g.l->log(Log::PermissionDenied, tr("Permission denied.")); + } break; } } @@ -344,16 +344,16 @@ void MainWindow::msgUDPTunnel(const MumbleProto::UDPTunnel &) { } /// This message is being received when the server informs this client about changed users. This might be because there -/// is a new user or because an existing user changed somehow (this includes things like a changed ID, changed name, changed -/// priority speaker status, changed channel, etc.). -/// This function will match the local user representation (UserModel) to these changes. +/// is a new user or because an existing user changed somehow (this includes things like a changed ID, changed name, +/// changed priority speaker status, changed channel, etc.). This function will match the local user representation +/// (UserModel) to these changes. /// /// @param msg The message object containing the respective information void MainWindow::msgUserState(const MumbleProto::UserState &msg) { ACTOR_INIT; - ClientUser* pSelf = ClientUser::get(g.uiSession); - ClientUser *pDst = ClientUser::get(msg.session()); - Channel *channel = nullptr; + ClientUser *pSelf = ClientUser::get(g.uiSession); + ClientUser *pDst = ClientUser::get(msg.session()); + Channel *channel = nullptr; if (msg.has_channel_id()) { channel = Channel::get(msg.channel_id()); @@ -384,7 +384,8 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { if (pSelf) { if (pDst->cChannel == pSelf->cChannel) { - g.l->log(Log::ChannelJoinConnect, tr("%1 connected and entered channel.").arg(Log::formatClientUser(pDst, Log::Source))); + g.l->log(Log::ChannelJoinConnect, + tr("%1 connected and entered channel.").arg(Log::formatClientUser(pDst, Log::Source))); } else { g.l->log(Log::UserJoin, tr("%1 connected.").arg(Log::formatClientUser(pDst, Log::Source))); } @@ -402,7 +403,8 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { if (g.talkingUI) { // Pass the pointer as QObject in order to avoid having to register ClientUser as a QMetaType - QMetaObject::invokeMethod(g.talkingUI, "on_channelChanged", Qt::QueuedConnection, Q_ARG(QObject *, pDst)); + QMetaObject::invokeMethod(g.talkingUI, "on_channelChanged", Qt::QueuedConnection, + Q_ARG(QObject *, pDst)); } if (pSelf) { @@ -415,26 +417,41 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { if (pSrc == pSelf) { g.l->log(Log::SelfChannelJoin, tr("You joined %1.").arg(Log::formatChannel(channel))); } else { - g.l->log(Log::SelfChannelJoinOther, tr("You were moved to %1 by %2.").arg(Log::formatChannel(channel)).arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::SelfChannelJoinOther, tr("You were moved to %1 by %2.") + .arg(Log::formatChannel(channel)) + .arg(Log::formatClientUser(pSrc, Log::Source))); } } else if (pSrc == pSelf) { if (channel == pSelf->cChannel) { - g.l->log(Log::ChannelJoin, tr("You moved %1 to %2.").arg(Log::formatClientUser(pDst, Log::Target)).arg(Log::formatChannel(channel))); + g.l->log(Log::ChannelJoin, tr("You moved %1 to %2.") + .arg(Log::formatClientUser(pDst, Log::Target)) + .arg(Log::formatChannel(channel))); } else { - g.l->log(Log::ChannelLeave, tr("You moved %1 to %2.").arg(Log::formatClientUser(pDst, Log::Target)).arg(Log::formatChannel(channel))); + g.l->log(Log::ChannelLeave, tr("You moved %1 to %2.") + .arg(Log::formatClientUser(pDst, Log::Target)) + .arg(Log::formatChannel(channel))); } } else if ((channel == pSelf->cChannel) || (oldChannel == pSelf->cChannel)) { if (pDst == pSrc) { if (channel == pSelf->cChannel) { - g.l->log(Log::ChannelJoin, tr("%1 entered channel.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::ChannelJoin, + tr("%1 entered channel.").arg(Log::formatClientUser(pDst, Log::Target))); } else { - g.l->log(Log::ChannelLeave, tr("%1 moved to %2.").arg(Log::formatClientUser(pDst, Log::Target)).arg(Log::formatChannel(channel))); + g.l->log(Log::ChannelLeave, tr("%1 moved to %2.") + .arg(Log::formatClientUser(pDst, Log::Target)) + .arg(Log::formatChannel(channel))); } } else { if (channel == pSelf->cChannel) { - g.l->log(Log::ChannelJoin, tr("%1 moved in from %2 by %3.").arg(Log::formatClientUser(pDst, Log::Target)).arg(Log::formatChannel(oldChannel)).arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::ChannelJoin, tr("%1 moved in from %2 by %3.") + .arg(Log::formatClientUser(pDst, Log::Target)) + .arg(Log::formatChannel(oldChannel)) + .arg(Log::formatClientUser(pSrc, Log::Source))); } else { - g.l->log(Log::ChannelLeave, tr("%1 moved to %2 by %3.").arg(Log::formatClientUser(pDst, Log::Target)).arg(Log::formatChannel(channel)).arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::ChannelLeave, tr("%1 moved to %2 by %3.") + .arg(Log::formatClientUser(pDst, Log::Target)) + .arg(Log::formatChannel(channel)) + .arg(Log::formatClientUser(pSrc, Log::Source))); } } } @@ -503,20 +520,23 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { QString oldName = pDst->qsName; QString newName = u8(msg.name()); pmModel->renameUser(pDst, newName); - if (! oldName.isNull() && oldName != newName) { + if (!oldName.isNull() && oldName != newName) { if (pSrc != pDst) { - g.l->log(Log::UserRenamed, tr("%1 renamed to %2 by %3.").arg(Log::formatClientUser(pDst, Log::Target, oldName)) - .arg(Log::formatClientUser(pDst, Log::Target)).arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::UserRenamed, tr("%1 renamed to %2 by %3.") + .arg(Log::formatClientUser(pDst, Log::Target, oldName)) + .arg(Log::formatClientUser(pDst, Log::Target)) + .arg(Log::formatClientUser(pSrc, Log::Source))); } else { - g.l->log(Log::UserRenamed, tr("%1 renamed to %2.").arg(Log::formatClientUser(pDst, Log::Target, oldName), - Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::UserRenamed, tr("%1 renamed to %2.") + .arg(Log::formatClientUser(pDst, Log::Target, oldName), + Log::formatClientUser(pDst, Log::Target))); } } } if (!pDst->qsHash.isEmpty()) { const QString &name = g.db->getFriend(pDst->qsHash); - if (! name.isEmpty()) + if (!name.isEmpty()) pmModel->setFriendName(pDst, name); if (g.db->isLocalMuted(pDst->qsHash)) pDst->setLocalMute(true); @@ -533,9 +553,11 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { if (msg.has_self_deaf()) pDst->setSelfDeaf(msg.self_deaf()); - if (pSelf && pDst != pSelf && ((pDst->cChannel == pSelf->cChannel) || pDst->cChannel->allLinks().contains(pSelf->cChannel))) { + if (pSelf && pDst != pSelf + && ((pDst->cChannel == pSelf->cChannel) || pDst->cChannel->allLinks().contains(pSelf->cChannel))) { if (pDst->bSelfMute && pDst->bSelfDeaf) - g.l->log(Log::OtherSelfMute, tr("%1 is now muted and deafened.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::OtherSelfMute, + tr("%1 is now muted and deafened.").arg(Log::formatClientUser(pDst, Log::Target))); else if (pDst->bSelfMute) g.l->log(Log::OtherSelfMute, tr("%1 is now muted.").arg(Log::formatClientUser(pDst, Log::Target))); else @@ -565,36 +587,51 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { } if (msg.has_priority_speaker()) { - if (pSelf && ((pDst->cChannel == pSelf->cChannel) || (pDst->cChannel->allLinks().contains(pSelf->cChannel)) || (pSrc == pSelf))) { + if (pSelf + && ((pDst->cChannel == pSelf->cChannel) || (pDst->cChannel->allLinks().contains(pSelf->cChannel)) + || (pSrc == pSelf))) { if ((pSrc == pDst) && (pSrc == pSelf)) { if (pDst->bPrioritySpeaker) { g.l->log(Log::YouMuted, tr("You revoked your priority speaker status.")); - } else { + } else { g.l->log(Log::YouMuted, tr("You assumed priority speaker status.")); } - } else if ((pSrc != pSelf) && (pDst == pSelf) ) { + } else if ((pSrc != pSelf) && (pDst == pSelf)) { if (pDst->bPrioritySpeaker) { - g.l->log(Log::YouMutedOther, tr("%1 revoked your priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); - } else { - g.l->log(Log::YouMutedOther, tr("%1 gave you priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log( + Log::YouMutedOther, + tr("%1 revoked your priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); + } else { + g.l->log(Log::YouMutedOther, + tr("%1 gave you priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); } } else if ((pSrc == pSelf) && (pSrc != pDst)) { if (pDst->bPrioritySpeaker) { - g.l->log(Log::YouMutedOther, tr("You revoked priority speaker status for %1.").arg(Log::formatClientUser(pDst, Log::Target))); - } else { - g.l->log(Log::YouMutedOther, tr("You gave priority speaker status to %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, tr("You revoked priority speaker status for %1.") + .arg(Log::formatClientUser(pDst, Log::Target))); + } else { + g.l->log( + Log::YouMutedOther, + tr("You gave priority speaker status to %1.").arg(Log::formatClientUser(pDst, Log::Target))); } } else if ((pSrc == pDst) && (pSrc != pSelf)) { if (pDst->bPrioritySpeaker) { - g.l->log(Log::OtherMutedOther, tr("%1 revoked own priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log( + Log::OtherMutedOther, + tr("%1 revoked own priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); } else { - g.l->log(Log::OtherMutedOther, tr("%1 assumed priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, + tr("%1 assumed priority speaker status.").arg(Log::formatClientUser(pSrc, Log::Source))); } } else if ((pSrc != pSelf) && (pDst != pSelf)) { if (pDst->bPrioritySpeaker) { - g.l->log(Log::OtherMutedOther, tr("%1 revoked priority speaker status for %2.").arg(Log::formatClientUser(pSrc, Log::Source), Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::OtherMutedOther, tr("%1 revoked priority speaker status for %2.") + .arg(Log::formatClientUser(pSrc, Log::Source), + Log::formatClientUser(pDst, Log::Target))); } else if (!pDst->bPrioritySpeaker) { - g.l->log(Log::OtherMutedOther, tr("%1 gave priority speaker status to %2.").arg(Log::formatClientUser(pSrc, Log::Source), Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::OtherMutedOther, tr("%1 gave priority speaker status to %2.") + .arg(Log::formatClientUser(pSrc, Log::Source), + Log::formatClientUser(pDst, Log::Target))); } } } @@ -610,23 +647,31 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { if (msg.has_suppress()) pDst->setSuppress(msg.suppress()); - if (pSelf && ((pDst->cChannel == pSelf->cChannel) || (pDst->cChannel->allLinks().contains(pSelf->cChannel)) || (pSrc == pSelf))) { + if (pSelf + && ((pDst->cChannel == pSelf->cChannel) || (pDst->cChannel->allLinks().contains(pSelf->cChannel)) + || (pSrc == pSelf))) { if (pDst == pSelf) { if (msg.has_mute() && msg.has_deaf() && pDst->bMute && pDst->bDeaf) { - g.l->log(Log::YouMuted, tr("You were muted and deafened by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::YouMuted, + tr("You were muted and deafened by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); } else if (msg.has_mute() && msg.has_deaf() && !pDst->bMute && !pDst->bDeaf) { - g.l->log(Log::YouMuted, tr("You were unmuted and undeafened by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log( + Log::YouMuted, + tr("You were unmuted and undeafened by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); } else { if (msg.has_mute()) { if (pDst->bMute) - g.l->log(Log::YouMuted, tr("You were muted by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::YouMuted, + tr("You were muted by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); else - g.l->log(Log::YouMuted, tr("You were unmuted by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::YouMuted, + tr("You were unmuted by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); } if (msg.has_deaf()) { if (!pDst->bDeaf) - g.l->log(Log::YouMuted, tr("You were undeafened by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::YouMuted, + tr("You were undeafened by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); } } @@ -637,63 +682,85 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { if (msg.has_channel_id()) g.l->log(Log::YouMuted, tr("You were unsuppressed.")); else - g.l->log(Log::YouMuted, tr("You were unsuppressed by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::YouMuted, + tr("You were unsuppressed by %1.").arg(Log::formatClientUser(pSrc, Log::Source))); } } updateTrayIcon(); } else if (pSrc == pSelf) { if (msg.has_mute() && msg.has_deaf() && pDst->bMute && pDst->bDeaf) { - g.l->log(Log::YouMutedOther, tr("You muted and deafened %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, + tr("You muted and deafened %1.").arg(Log::formatClientUser(pDst, Log::Target))); } else if (msg.has_mute() && msg.has_deaf() && !pDst->bMute && !pDst->bDeaf) { - g.l->log(Log::YouMutedOther, tr("You unmuted and undeafened %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, + tr("You unmuted and undeafened %1.").arg(Log::formatClientUser(pDst, Log::Target))); } else { if (msg.has_mute()) { if (pDst->bMute) - g.l->log(Log::YouMutedOther, tr("You muted %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, + tr("You muted %1.").arg(Log::formatClientUser(pDst, Log::Target))); else - g.l->log(Log::YouMutedOther, tr("You unmuted %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, + tr("You unmuted %1.").arg(Log::formatClientUser(pDst, Log::Target))); } if (msg.has_deaf()) { if (!pDst->bDeaf) - g.l->log(Log::YouMutedOther, tr("You undeafened %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, + tr("You undeafened %1.").arg(Log::formatClientUser(pDst, Log::Target))); } } if (msg.has_suppress()) { - if (! msg.has_channel_id()) { + if (!msg.has_channel_id()) { if (pDst->bSuppress) - g.l->log(Log::YouMutedOther, tr("You suppressed %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, + tr("You suppressed %1.").arg(Log::formatClientUser(pDst, Log::Target))); else - g.l->log(Log::YouMutedOther, tr("You unsuppressed %1.").arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log(Log::YouMutedOther, + tr("You unsuppressed %1.").arg(Log::formatClientUser(pDst, Log::Target))); } } } else { if (msg.has_mute() && msg.has_deaf() && pDst->bMute && pDst->bDeaf) { - g.l->log(Log::OtherMutedOther, tr("%1 muted and deafened by %2.").arg(Log::formatClientUser(pDst, Log::Target), Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, tr("%1 muted and deafened by %2.") + .arg(Log::formatClientUser(pDst, Log::Target), + Log::formatClientUser(pSrc, Log::Source))); } else if (msg.has_mute() && msg.has_deaf() && !pDst->bMute && !pDst->bDeaf) { - g.l->log(Log::OtherMutedOther, tr("%1 unmuted and undeafened by %2.").arg(Log::formatClientUser(pDst, Log::Target), Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, tr("%1 unmuted and undeafened by %2.") + .arg(Log::formatClientUser(pDst, Log::Target), + Log::formatClientUser(pSrc, Log::Source))); } else { if (msg.has_mute()) { if (pDst->bMute) - g.l->log(Log::OtherMutedOther, tr("%1 muted by %2.").arg(Log::formatClientUser(pDst, Log::Target), Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, tr("%1 muted by %2.") + .arg(Log::formatClientUser(pDst, Log::Target), + Log::formatClientUser(pSrc, Log::Source))); else - g.l->log(Log::OtherMutedOther, tr("%1 unmuted by %2.").arg(Log::formatClientUser(pDst, Log::Target), Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, tr("%1 unmuted by %2.") + .arg(Log::formatClientUser(pDst, Log::Target), + Log::formatClientUser(pSrc, Log::Source))); } if (msg.has_deaf()) { if (!pDst->bDeaf) - g.l->log(Log::OtherMutedOther, tr("%1 undeafened by %2.").arg(Log::formatClientUser(pDst, Log::Target), Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, tr("%1 undeafened by %2.") + .arg(Log::formatClientUser(pDst, Log::Target), + Log::formatClientUser(pSrc, Log::Source))); } } if (msg.has_suppress()) { - if (! msg.has_channel_id()) { + if (!msg.has_channel_id()) { if (pDst->bSuppress) - g.l->log(Log::OtherMutedOther, tr("%1 suppressed by %2.").arg(Log::formatClientUser(pDst, Log::Target), Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, tr("%1 suppressed by %2.") + .arg(Log::formatClientUser(pDst, Log::Target), + Log::formatClientUser(pSrc, Log::Source))); else - g.l->log(Log::OtherMutedOther, tr("%1 unsuppressed by %2.").arg(Log::formatClientUser(pDst, Log::Target), Log::formatClientUser(pSrc, Log::Source))); + g.l->log(Log::OtherMutedOther, tr("%1 unsuppressed by %2.") + .arg(Log::formatClientUser(pDst, Log::Target), + Log::formatClientUser(pSrc, Log::Source))); } } } @@ -702,7 +769,7 @@ void MainWindow::msgUserState(const MumbleProto::UserState &msg) { if (msg.has_texture_hash()) { pDst->qbaTextureHash = blob(msg.texture_hash()); - pDst->qbaTexture = QByteArray(); + pDst->qbaTexture = QByteArray(); #ifdef USE_OVERLAY g.o->verifyTexture(pDst); #endif @@ -741,17 +808,30 @@ void MainWindow::msgUserRemove(const MumbleProto::UserRemove &msg) { if (pDst == pSelf) { bRetryServer = false; if (msg.ban()) - g.l->log(Log::YouKicked, tr("You were kicked and banned from the server by %1: %2.").arg(Log::formatClientUser(pSrc, Log::Source)).arg(reason)); + g.l->log(Log::YouKicked, tr("You were kicked and banned from the server by %1: %2.") + .arg(Log::formatClientUser(pSrc, Log::Source)) + .arg(reason)); else - g.l->log(Log::YouKicked, tr("You were kicked from the server by %1: %2.").arg(Log::formatClientUser(pSrc, Log::Source)).arg(reason)); + g.l->log(Log::YouKicked, tr("You were kicked from the server by %1: %2.") + .arg(Log::formatClientUser(pSrc, Log::Source)) + .arg(reason)); } else if (pSrc) { if (msg.ban()) - g.l->log((pSrc == pSelf) ? Log::YouKicked : Log::UserKicked, tr("%3 was kicked and banned from the server by %1: %2.").arg(Log::formatClientUser(pSrc, Log::Source)).arg(reason).arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log((pSrc == pSelf) ? Log::YouKicked : Log::UserKicked, + tr("%3 was kicked and banned from the server by %1: %2.") + .arg(Log::formatClientUser(pSrc, Log::Source)) + .arg(reason) + .arg(Log::formatClientUser(pDst, Log::Target))); else - g.l->log((pSrc == pSelf) ? Log::YouKicked : Log::UserKicked, tr("%3 was kicked from the server by %1: %2.").arg(Log::formatClientUser(pSrc, Log::Source)).arg(reason).arg(Log::formatClientUser(pDst, Log::Target))); + g.l->log((pSrc == pSelf) ? Log::YouKicked : Log::UserKicked, + tr("%3 was kicked from the server by %1: %2.") + .arg(Log::formatClientUser(pSrc, Log::Source)) + .arg(reason) + .arg(Log::formatClientUser(pDst, Log::Target))); } else { if (pDst->cChannel == pSelf->cChannel || pDst->cChannel->allLinks().contains(pSelf->cChannel)) { - g.l->log(Log::ChannelLeaveDisconnect, tr("%1 left channel and disconnected.").arg(Log::formatClientUser(pDst, Log::Source))); + g.l->log(Log::ChannelLeaveDisconnect, + tr("%1 left channel and disconnected.").arg(Log::formatClientUser(pDst, Log::Source))); } else { g.l->log(Log::UserLeave, tr("%1 disconnected.").arg(Log::formatClientUser(pDst, Log::Source))); } @@ -759,15 +839,16 @@ void MainWindow::msgUserRemove(const MumbleProto::UserRemove &msg) { if (pDst != pSelf) pmModel->removeUser(pDst); - QMetaObject::invokeMethod(g.talkingUI, "on_clientDisconnected", Qt::QueuedConnection, Q_ARG(unsigned int, pDst->uiSession)); + QMetaObject::invokeMethod(g.talkingUI, "on_clientDisconnected", Qt::QueuedConnection, + Q_ARG(unsigned int, pDst->uiSession)); } -/// This message is being received when the server informs the local client about channel properties (either during connection/login -/// to the server or whenever these properties changed). +/// This message is being received when the server informs the local client about channel properties (either during +/// connection/login to the server or whenever these properties changed). /// /// @param msg The message object containing the details about the channel properties void MainWindow::msgChannelState(const MumbleProto::ChannelState &msg) { - if (! msg.has_channel_id()) + if (!msg.has_channel_id()) return; Channel *c = Channel::get(msg.channel_id()); @@ -776,9 +857,9 @@ void MainWindow::msgChannelState(const MumbleProto::ChannelState &msg) { if (!c) { // Addresses channel does not exist so create it if (p && msg.has_name()) { - c = pmModel->addChannel(msg.channel_id(), p, u8(msg.name())); + c = pmModel->addChannel(msg.channel_id(), p, u8(msg.name())); c->bTemporary = msg.temporary(); - p = nullptr; // No need to move it later + p = nullptr; // No need to move it later ServerHandlerPtr sh = g.sh; if (sh) @@ -817,34 +898,34 @@ void MainWindow::msgChannelState(const MumbleProto::ChannelState &msg) { } if (msg.links_size()) { - QList<Channel *> ql; + QList< Channel * > ql; pmModel->unlinkAll(c); - for (int i=0;i<msg.links_size();++i) { + for (int i = 0; i < msg.links_size(); ++i) { Channel *l = Channel::get(msg.links(i)); if (l) ql << l; } - if (! ql.isEmpty()) + if (!ql.isEmpty()) pmModel->linkChannels(c, ql); } if (msg.links_remove_size()) { - QList<Channel *> ql; - for (int i=0;i<msg.links_remove_size();++i) { + QList< Channel * > ql; + for (int i = 0; i < msg.links_remove_size(); ++i) { Channel *l = Channel::get(msg.links_remove(i)); if (l) ql << l; } - if (! ql.isEmpty()) + if (!ql.isEmpty()) pmModel->unlinkChannels(c, ql); } if (msg.links_add_size()) { - QList<Channel *> ql; - for (int i=0;i<msg.links_add_size();++i) { + QList< Channel * > ql; + for (int i = 0; i < msg.links_add_size(); ++i) { Channel *l = Channel::get(msg.links_add(i)); if (l) ql << l; } - if (! ql.isEmpty()) + if (!ql.isEmpty()) pmModel->linkChannels(c, ql); } @@ -901,8 +982,8 @@ void MainWindow::msgTextMessage(const MumbleProto::TextMessage &msg) { return; const QString &plainName = pSrc ? pSrc->qsName : tr("Server", "message from"); - const QString &name = pSrc ? Log::formatClientUser(pSrc, Log::Source) : tr("Server", "message from"); - bool privateMessage = false; + const QString &name = pSrc ? Log::formatClientUser(pSrc, Log::Source) : tr("Server", "message from"); + bool privateMessage = false; if (msg.tree_id_size() > 0) { target += tr("Tree"); @@ -929,11 +1010,8 @@ void MainWindow::msgTextMessage(const MumbleProto::TextMessage &msg) { const QString prefixMessage = target.isEmpty() ? name : tr("(%1) %2").arg(target).arg(name); g.l->log(privateMessage ? Log::PrivateTextMessage : Log::TextMessage, - tr("%1: %2").arg(prefixMessage).arg(u8(msg.message())), - tr("Message from %1").arg(plainName), - false, - overrideTTS, - pSrc ? pSrc->bLocalIgnoreTTS : false); + tr("%1: %2").arg(prefixMessage).arg(u8(msg.message())), tr("Message from %1").arg(plainName), false, + overrideTTS, pSrc ? pSrc->bLocalIgnoreTTS : false); } /// This message is being received when the server informs the client about the access control list (ACL) for @@ -952,8 +1030,8 @@ void MainWindow::msgACL(const MumbleProto::ACL &msg) { } } -/// This message is being received when the server informs the local client about user information. This message will only be -/// received after being explicitly queried by the local client. +/// This message is being received when the server informs the local client about user information. This message will +/// only be received after being explicitly queried by the local client. /// /// @param msg The message object with the respective information void MainWindow::msgQueryUsers(const MumbleProto::QueryUsers &msg) { @@ -966,21 +1044,21 @@ void MainWindow::msgPing(const MumbleProto::Ping &) { } void MainWindow::msgCryptSetup(const MumbleProto::CryptSetup &msg) { - ConnectionPtr c= g.sh->cConnection; - if (! c) + ConnectionPtr c = g.sh->cConnection; + if (!c) return; if (msg.has_key() && msg.has_client_nonce() && msg.has_server_nonce()) { - const std::string &key = msg.key(); + const std::string &key = msg.key(); const std::string &client_nonce = msg.client_nonce(); const std::string &server_nonce = msg.server_nonce(); - if (!c->csCrypt->setKey(key, client_nonce, server_nonce)){ + if (!c->csCrypt->setKey(key, client_nonce, server_nonce)) { qWarning("Messages: Cipher resync failed: Invalid key/nonce from the server!"); } } else if (msg.has_server_nonce()) { const std::string &server_nonce = msg.server_nonce(); if (server_nonce.size() == AES_BLOCK_SIZE) { c->csCrypt->uiResync++; - if(!c->csCrypt->setDecryptIV(server_nonce)){ + if (!c->csCrypt->setDecryptIV(server_nonce)) { qWarning("Messages: Cipher resync failed: Invalid nonce from the server!"); } } @@ -1030,11 +1108,11 @@ void MainWindow::msgContextActionModify(const MumbleProto::ContextActionModify & void MainWindow::removeContextAction(const MumbleProto::ContextActionModify &msg) { QString action = u8(msg.action()); - QSet<QAction *> qs; + QSet< QAction * > qs; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - qs += QSet<QAction*>(qlServerActions.begin(), qlServerActions.end()); - qs += QSet<QAction*>(qlChannelActions.begin(), qlChannelActions.end()); - qs += QSet<QAction*>(qlUserActions.begin(), qlUserActions.end()); + qs += QSet< QAction * >(qlServerActions.begin(), qlServerActions.end()); + qs += QSet< QAction * >(qlChannelActions.begin(), qlChannelActions.end()); + qs += QSet< QAction * >(qlUserActions.begin(), qlUserActions.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now qs += qlServerActions.toSet(); @@ -1042,7 +1120,7 @@ void MainWindow::removeContextAction(const MumbleProto::ContextActionModify &msg qs += qlUserActions.toSet(); #endif - foreach(QAction *a, qs) { + foreach (QAction *a, qs) { if (a->data() == action) { qlServerActions.removeOne(a); qlChannelActions.removeOne(a); @@ -1093,11 +1171,11 @@ void MainWindow::msgPermissionQuery(const MumbleProto::PermissionQuery &msg) { Channel *current = pmModel->getChannel(qtvUsers->currentIndex()); if (msg.flush()) { - foreach(Channel *c, Channel::c_qhChannels) + foreach (Channel *c, Channel::c_qhChannels) c->uiPermissions = 0; // We always need the permissions of the current focus channel - if (current && current->iId != static_cast<int>(msg.channel_id())) { + if (current && current->iId != static_cast< int >(msg.channel_id())) { g.sh->requestChannelPermissions(current->iId); current->uiPermissions = ChanACL::All; @@ -1107,7 +1185,7 @@ void MainWindow::msgPermissionQuery(const MumbleProto::PermissionQuery &msg) { if (c) { c->uiPermissions = msg.permissions(); if (c->iId == 0) - g.pPermissions = static_cast<ChanACL::Permissions>(c->uiPermissions); + g.pPermissions = static_cast< ChanACL::Permissions >(c->uiPermissions); if (c == current) { updateMenuPermissions(); } @@ -1120,12 +1198,12 @@ void MainWindow::msgPermissionQuery(const MumbleProto::PermissionQuery &msg) { /// @param msg The message object void MainWindow::msgCodecVersion(const MumbleProto::CodecVersion &msg) { int alpha = msg.has_alpha() ? msg.alpha() : -1; - int beta = msg.has_beta() ? msg.beta() : -1; + int beta = msg.has_beta() ? msg.beta() : -1; bool pref = msg.prefer_alpha(); #ifdef USE_OPUS static bool warnedOpus = false; - g.bOpus = msg.opus(); + g.bOpus = msg.opus(); if (!g.oCodec && !warnedOpus) { g.l->log(Log::CriticalError, tr("Failed to load Opus, it will not be available for audio encoding/decoding.")); @@ -1143,13 +1221,13 @@ void MainWindow::msgCodecVersion(const MumbleProto::CodecVersion &msg) { if ((alpha != -1) && (alpha != g.iCodecAlpha)) { g.iCodecAlpha = alpha; - if (pref && ! g.qmCodecs.contains(alpha)) - pref = ! pref; + if (pref && !g.qmCodecs.contains(alpha)) + pref = !pref; } if ((beta != -1) && (beta != g.iCodecBeta)) { g.iCodecBeta = beta; - if (! pref && ! g.qmCodecs.contains(beta)) - pref = ! pref; + if (!pref && !g.qmCodecs.contains(beta)) + pref = !pref; } g.bPreferAlpha = pref; @@ -1157,9 +1235,10 @@ void MainWindow::msgCodecVersion(const MumbleProto::CodecVersion &msg) { static bool warnedCELT = false; - if (! g.qmCodecs.contains(willuse)) { - if (! warnedCELT) { - g.l->log(Log::CriticalError, tr("Unable to find matching CELT codecs with other clients. You will not be able to talk to all users.")); + if (!g.qmCodecs.contains(willuse)) { + if (!warnedCELT) { + g.l->log(Log::CriticalError, tr("Unable to find matching CELT codecs with other clients. You will not be " + "able to talk to all users.")); warnedCELT = true; } } else { @@ -1200,7 +1279,8 @@ void MainWindow::msgRequestBlob(const MumbleProto::RequestBlob &) { /// @param msg The message object containing the suggestions void MainWindow::msgSuggestConfig(const MumbleProto::SuggestConfig &msg) { if (msg.has_version() && (msg.version() > MumbleVersion::getRaw())) { - g.l->log(Log::Warning, tr("The server requests minimum client version %1").arg(MumbleVersion::toString(msg.version()))); + g.l->log(Log::Warning, + tr("The server requests minimum client version %1").arg(MumbleVersion::toString(msg.version()))); } if (msg.has_positional() && (msg.positional() != g.s.doPositionalAudio())) { if (msg.positional()) diff --git a/src/mumble/MumbleApplication.cpp b/src/mumble/MumbleApplication.cpp index d0588e406..cb29cd05a 100644 --- a/src/mumble/MumbleApplication.cpp +++ b/src/mumble/MumbleApplication.cpp @@ -5,30 +5,27 @@ #include "MumbleApplication.h" +#include "EnvUtils.h" #include "MainWindow.h" #include "GlobalShortcut.h" -#include "EnvUtils.h" #if defined(Q_OS_WIN) -# include "GlobalShortcut_win.h" +# include "GlobalShortcut_win.h" #endif #include <QtGui/QFileOpenEvent> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" MumbleApplication *MumbleApplication::instance() { - return static_cast<MumbleApplication *>(QCoreApplication::instance()); + return static_cast< MumbleApplication * >(QCoreApplication::instance()); } -MumbleApplication::MumbleApplication(int &pargc, char **pargv) - : QApplication(pargc, pargv) { - - connect(this, - SIGNAL(commitDataRequest(QSessionManager&)), - SLOT(onCommitDataRequest(QSessionManager&)), - Qt::DirectConnection); +MumbleApplication::MumbleApplication(int &pargc, char **pargv) : QApplication(pargc, pargv) { + connect(this, SIGNAL(commitDataRequest(QSessionManager &)), SLOT(onCommitDataRequest(QSessionManager &)), + Qt::DirectConnection); } QString MumbleApplication::applicationVersionRootPath() { @@ -50,8 +47,8 @@ void MumbleApplication::onCommitDataRequest(QSessionManager &) { bool MumbleApplication::event(QEvent *e) { if (e->type() == QEvent::FileOpen) { - QFileOpenEvent *foe = static_cast<QFileOpenEvent *>(e); - if (! g.mw) { + QFileOpenEvent *foe = static_cast< QFileOpenEvent * >(e); + if (!g.mw) { this->quLaunchURL = foe->url(); } else { g.mw->openUrl(foe->url()); @@ -68,7 +65,7 @@ bool MumbleApplication::event(QEvent *e) { /// @return Returns true if the forwarded event was suppressed /// by GlobalShortcutWin. Otherwise, returns false. static bool gswForward(MSG *msg) { - GlobalShortcutWin *gsw = static_cast<GlobalShortcutWin *>(GlobalShortcutEngine::engine); + GlobalShortcutWin *gsw = static_cast< GlobalShortcutWin * >(GlobalShortcutEngine::engine); if (gsw) { return false; } @@ -92,7 +89,7 @@ static bool gswForward(MSG *msg) { } bool MumbleApplication::nativeEventFilter(const QByteArray &, void *message, long *) { - MSG *msg = reinterpret_cast<MSG *>(message); + MSG *msg = reinterpret_cast< MSG * >(message); if (QThread::currentThread() == thread()) { bool suppress = gswForward(msg); if (suppress) { diff --git a/src/mumble/MumbleApplication.h b/src/mumble/MumbleApplication.h index 370f618f6..ea1f0f77c 100644 --- a/src/mumble/MumbleApplication.h +++ b/src/mumble/MumbleApplication.h @@ -10,7 +10,7 @@ #include <QUrl> #ifdef Q_OS_WIN -#include <QAbstractNativeEventFilter> +# include <QAbstractNativeEventFilter> #endif /** @@ -21,43 +21,42 @@ class MumbleApplication : public QApplication, public QAbstractNativeEventFilter #else class MumbleApplication : public QApplication { #endif - Q_OBJECT - public: - - /// The instance function returns an instance - /// of the MumbleApplication singleton. - static MumbleApplication *instance(); - - MumbleApplication(int &pargc, char **pargv); - - /// applicationVersionRootPath returns - /// Mumble's "versioned root"-path. - /// - /// This is a version-specific path that contains - /// supplementary binaries and other products - /// that Mumble needs to function. - /// - /// In the current implementation, the versioned - /// root path is set by the MUMBLE_VERSION_ROOT - /// environment variable. This environment variable - /// is set in the mumble.exe launcher. - /// - /// If a versioned root path has not been - /// configured in the environment, the function - /// returns the same path as Qt's own - /// QApplication::applicationDirPath(). - QString applicationVersionRootPath(); - - bool event(QEvent *e) Q_DECL_OVERRIDE; + Q_OBJECT +public: + /// The instance function returns an instance + /// of the MumbleApplication singleton. + static MumbleApplication *instance(); + + MumbleApplication(int &pargc, char **pargv); + + /// applicationVersionRootPath returns + /// Mumble's "versioned root"-path. + /// + /// This is a version-specific path that contains + /// supplementary binaries and other products + /// that Mumble needs to function. + /// + /// In the current implementation, the versioned + /// root path is set by the MUMBLE_VERSION_ROOT + /// environment variable. This environment variable + /// is set in the mumble.exe launcher. + /// + /// If a versioned root path has not been + /// configured in the environment, the function + /// returns the same path as Qt's own + /// QApplication::applicationDirPath(). + QString applicationVersionRootPath(); + + bool event(QEvent *e) Q_DECL_OVERRIDE; #ifdef Q_OS_WIN - bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; + bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE; #endif - - QUrl quLaunchURL; - - public slots: - /// Saves state and suppresses ask on quit before system shutdown. - void onCommitDataRequest(QSessionManager&); + + QUrl quLaunchURL; + +public slots: + /// Saves state and suppresses ask on quit before system shutdown. + void onCommitDataRequest(QSessionManager &); }; #endif // MUMBLE_MUMBLE_MUMBLEAPPLICATION_H diff --git a/src/mumble/NetworkConfig.cpp b/src/mumble/NetworkConfig.cpp index c67b6ae3d..937b79db4 100644 --- a/src/mumble/NetworkConfig.cpp +++ b/src/mumble/NetworkConfig.cpp @@ -8,16 +8,17 @@ #include "MainWindow.h" #include "OSInfo.h" +#include <QSignalBlocker> #include <QtNetwork/QHostAddress> -#include <QtNetwork/QNetworkProxy> #include <QtNetwork/QNetworkAccessManager> -#include <QSignalBlocker> +#include <QtNetwork/QNetworkProxy> #ifdef NO_UPDATE_CHECK - #include <QMessageBox> +# include <QMessageBox> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const QString NetworkConfig::name = QLatin1String("NetworkConfig"); @@ -35,7 +36,6 @@ NetworkConfig::NetworkConfig(Settings &st) : ConfigWidget(st) { qlePort->setAccessibleName(tr("Port")); qleUsername->setAccessibleName(tr("Username")); qlePassword->setAccessibleName(tr("Password")); - } QString NetworkConfig::title() const { @@ -51,7 +51,6 @@ QIcon NetworkConfig::icon() const { } void NetworkConfig::load(const Settings &r) { - loadCheckBox(qcbTcpMode, s.bTCPCompat); loadCheckBox(qcbQoS, s.bQoS); loadCheckBox(qcbAutoReconnect, s.bReconnect); @@ -81,23 +80,23 @@ void NetworkConfig::load(const Settings &r) { } void NetworkConfig::save() const { - s.bTCPCompat = qcbTcpMode->isChecked(); - s.bQoS = qcbQoS->isChecked(); - s.bReconnect = qcbAutoReconnect->isChecked(); - s.bAutoConnect = qcbAutoConnect->isChecked(); + s.bTCPCompat = qcbTcpMode->isChecked(); + s.bQoS = qcbQoS->isChecked(); + s.bReconnect = qcbAutoReconnect->isChecked(); + s.bAutoConnect = qcbAutoConnect->isChecked(); s.bDisablePublicList = qcbDisablePublicList->isChecked(); - s.bSuppressIdentity = qcbSuppressIdentity->isChecked(); - s.bHideOS = qcbHideOS->isChecked(); + s.bSuppressIdentity = qcbSuppressIdentity->isChecked(); + s.bHideOS = qcbHideOS->isChecked(); - s.ptProxyType = static_cast<Settings::ProxyType>(qcbType->currentIndex()); - s.qsProxyHost = qleHostname->text(); - s.usProxyPort = qlePort->text().toUShort(); + s.ptProxyType = static_cast< Settings::ProxyType >(qcbType->currentIndex()); + s.qsProxyHost = qleHostname->text(); + s.usProxyPort = qlePort->text().toUShort(); s.qsProxyUsername = qleUsername->text(); s.qsProxyPassword = qlePassword->text(); - s.bUpdateCheck=qcbAutoUpdate->isChecked(); - s.bPluginCheck=qcbPluginUpdate->isChecked(); - s.bUsage=qcbUsage->isChecked(); + s.bUpdateCheck = qcbAutoUpdate->isChecked(); + s.bPluginCheck = qcbPluginUpdate->isChecked(); + s.bUsage = qcbUsage->isChecked(); } static QNetworkProxy::ProxyType local_to_qt_proxy(Settings::ProxyType pt) { @@ -147,7 +146,7 @@ void NetworkConfig::accept() const { } void NetworkConfig::on_qcbType_currentIndexChanged(int v) { - Settings::ProxyType pt = static_cast<Settings::ProxyType>(v); + Settings::ProxyType pt = static_cast< Settings::ProxyType >(v); qleHostname->setEnabled(pt != Settings::NoProxy); qlePort->setEnabled(pt != Settings::NoProxy); @@ -162,13 +161,17 @@ void NetworkConfig::on_qcbType_currentIndexChanged(int v) { void NetworkConfig::on_qcbAutoUpdate_stateChanged(int state) { if (state == Qt::Checked) { QMessageBox msgBox; - msgBox.setText(QObject::tr("<p>You're using a Mumble version that <b>explicitly disabled</b> update-checks.</p>" - "<p>This means that the update notification you might receive by using this option will " - "<b>most likely be meaningless</b> for you.</p>")); - msgBox.setInformativeText(QObject::tr("<p>If you're using Linux this is most likely because you are using a " - "version from your distribution's package repository that have their own update cycles.</p>" - "<p>If you want to always have the most recent Mumble version, you should consider using a different method of installation.\n" - "See <a href=\"https://wiki.mumble.info/wiki/Installing_Mumble\">the Mumble wiki</a> for what alternatives there are.</p>")); + msgBox.setText( + QObject::tr("<p>You're using a Mumble version that <b>explicitly disabled</b> update-checks.</p>" + "<p>This means that the update notification you might receive by using this option will " + "<b>most likely be meaningless</b> for you.</p>")); + msgBox.setInformativeText( + QObject::tr("<p>If you're using Linux this is most likely because you are using a " + "version from your distribution's package repository that have their own update cycles.</p>" + "<p>If you want to always have the most recent Mumble version, you should consider using a " + "different method of installation.\n" + "See <a href=\"https://wiki.mumble.info/wiki/Installing_Mumble\">the Mumble wiki</a> for what " + "alternatives there are.</p>")); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); } @@ -184,10 +187,17 @@ QNetworkReply *Network::get(const QUrl &url) { void Network::prepareRequest(QNetworkRequest &req) { req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); - // Do not send OS information if the corresponding privacy setting is enabled - if (g.s.bHideOS) { - req.setRawHeader(QString::fromLatin1("User-Agent").toUtf8(), QString::fromLatin1("Mozilla/5.0 Mumble/%1 %2").arg(QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE)).toUtf8()); - } else { - req.setRawHeader(QString::fromLatin1("User-Agent").toUtf8(), QString::fromLatin1("Mozilla/5.0 (%1; %2) Mumble/%3 %4").arg(OSInfo::getOS(), OSInfo::getOSVersion(), QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE)).toUtf8()); + // Do not send OS information if the corresponding privacy setting is enabled + if (g.s.bHideOS) { + req.setRawHeader(QString::fromLatin1("User-Agent").toUtf8(), + QString::fromLatin1("Mozilla/5.0 Mumble/%1 %2") + .arg(QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE)) + .toUtf8()); + } else { + req.setRawHeader(QString::fromLatin1("User-Agent").toUtf8(), + QString::fromLatin1("Mozilla/5.0 (%1; %2) Mumble/%3 %4") + .arg(OSInfo::getOS(), OSInfo::getOSVersion(), + QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE)) + .toUtf8()); } } diff --git a/src/mumble/NetworkConfig.h b/src/mumble/NetworkConfig.h index e826fb027..1f871d7cc 100644 --- a/src/mumble/NetworkConfig.h +++ b/src/mumble/NetworkConfig.h @@ -14,32 +14,32 @@ class QUrl; #include "ui_NetworkConfig.h" class NetworkConfig : public ConfigWidget, Ui::NetworkConfig { - private: - Q_OBJECT - Q_DISABLE_COPY(NetworkConfig) - public: - /// The unique name of this ConfigWidget - static const QString name; - NetworkConfig(Settings &st); - virtual QString title() const Q_DECL_OVERRIDE; - virtual const QString &getName() const Q_DECL_OVERRIDE; - virtual QIcon icon() const Q_DECL_OVERRIDE; - static void SetupProxy(); - static bool TcpModeEnabled(); - public slots: - void accept() const Q_DECL_OVERRIDE; - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(NetworkConfig) +public: + /// The unique name of this ConfigWidget + static const QString name; + NetworkConfig(Settings &st); + virtual QString title() const Q_DECL_OVERRIDE; + virtual const QString &getName() const Q_DECL_OVERRIDE; + virtual QIcon icon() const Q_DECL_OVERRIDE; + static void SetupProxy(); + static bool TcpModeEnabled(); +public slots: + void accept() const Q_DECL_OVERRIDE; + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; - void on_qcbType_currentIndexChanged(int v); + void on_qcbType_currentIndexChanged(int v); #ifdef NO_UPDATE_CHECK - void on_qcbAutoUpdate_stateChanged(int state); + void on_qcbAutoUpdate_stateChanged(int state); #endif }; namespace Network { - void prepareRequest(QNetworkRequest &); - QNetworkReply *get(const QUrl &); -} +void prepareRequest(QNetworkRequest &); +QNetworkReply *get(const QUrl &); +} // namespace Network #endif diff --git a/src/mumble/OSS.cpp b/src/mumble/OSS.cpp index 04ae22374..a1651c672 100644 --- a/src/mumble/OSS.cpp +++ b/src/mumble/OSS.cpp @@ -5,57 +5,56 @@ #include "OSS.h" -#include <sys/soundcard.h> -#include <fcntl.h> #include <errno.h> +#include <fcntl.h> #include <sys/ioctl.h> +#include <sys/soundcard.h> -#include "User.h" #include "MainWindow.h" +#include "User.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" #define NBLOCKS 8 class OSSEnumerator { - public: - QHash<QString,QString> qhInput; - QHash<QString,QString> qhOutput; - QHash<QString,QString> qhDevices; - OSSEnumerator(); +public: + QHash< QString, QString > qhInput; + QHash< QString, QString > qhOutput; + QHash< QString, QString > qhDevices; + OSSEnumerator(); }; static OSSEnumerator *cards = nullptr; class OSSInit : public DeferInit { - void initialize() { - cards = new OSSEnumerator(); - }; - void destroy() { - delete cards; - cards = nullptr; - }; + void initialize() { cards = new OSSEnumerator(); }; + void destroy() { + delete cards; + cards = nullptr; + }; }; static OSSInit ossi; class OSSInputRegistrar : public AudioInputRegistrar { - public: - OSSInputRegistrar(); - virtual AudioInput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); - virtual bool canEcho(const QString &) const; +public: + OSSInputRegistrar(); + virtual AudioInput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); + virtual bool canEcho(const QString &) const; }; class OSSOutputRegistrar : public AudioOutputRegistrar { - public: - OSSOutputRegistrar(); - virtual AudioOutput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); +public: + OSSOutputRegistrar(); + virtual AudioOutput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); }; static OSSInputRegistrar airOSS; @@ -68,8 +67,8 @@ AudioInput *OSSInputRegistrar::create() { return new OSSInput(); } -const QList<audioDevice> OSSInputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > OSSInputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; QStringList qlInputDevs = cards->qhInput.keys(); std::sort(qlInputDevs.begin(), qlInputDevs.end()); @@ -79,9 +78,7 @@ const QList<audioDevice> OSSInputRegistrar::getDeviceChoices() { qlInputDevs.prepend(g.s.qsOSSInput); } - foreach(const QString &dev, qlInputDevs) { - qlReturn << audioDevice(cards->qhInput.value(dev), dev); - } + foreach (const QString &dev, qlInputDevs) { qlReturn << audioDevice(cards->qhInput.value(dev), dev); } return qlReturn; } @@ -101,8 +98,8 @@ AudioOutput *OSSOutputRegistrar::create() { return new OSSOutput(); } -const QList<audioDevice> OSSOutputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > OSSOutputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; QStringList qlOutputDevs = cards->qhOutput.keys(); std::sort(qlOutputDevs.begin(), qlOutputDevs.end()); @@ -112,9 +109,7 @@ const QList<audioDevice> OSSOutputRegistrar::getDeviceChoices() { qlOutputDevs.prepend(g.s.qsOSSOutput); } - foreach(const QString &dev, qlOutputDevs) { - qlReturn << audioDevice(cards->qhOutput.value(dev), dev); - } + foreach (const QString &dev, qlOutputDevs) { qlReturn << audioDevice(cards->qhOutput.value(dev), dev); } return qlReturn; } @@ -142,7 +137,7 @@ OSSEnumerator::OSSEnumerator() { return; } - for (int i=0;i< sysinfo.numaudios;i++) { + for (int i = 0; i < sysinfo.numaudios; i++) { oss_audioinfo ainfo; ainfo.dev = i; if (ioctl(mixerfd, SNDCTL_AUDIOINFO, &ainfo) == -1) { @@ -151,7 +146,7 @@ OSSEnumerator::OSSEnumerator() { } QString handle = QLatin1String(ainfo.handle); - QString name = QLatin1String(ainfo.name); + QString name = QLatin1String(ainfo.name); QString device = QLatin1String(ainfo.devnode); if (ainfo.caps & PCM_CAP_HIDDEN) @@ -221,7 +216,7 @@ void OSSInput::run() { while (bRunning) { short buffer[iMicLength]; - int len = static_cast<int>(iMicLength * iMicChannels * sizeof(short)); + int len = static_cast< int >(iMicLength * iMicChannels * sizeof(short)); ssize_t l = read(fd, buffer, len); if (l != len) { qWarning("OSSInput: Read %zd", l); @@ -267,7 +262,7 @@ void OSSOutput::run() { int ival; - ival = (g.s.iOutputDelay+1) << 16 | 11; + ival = (g.s.iOutputDelay + 1) << 16 | 11; if (ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ival) == -1) { qWarning("OSSOutput: Failed to set fragment"); @@ -284,7 +279,7 @@ void OSSOutput::run() { iChannels = 2; ival = iChannels; - if ((ioctl(fd, SNDCTL_DSP_CHANNELS, &ival) == -1) && (ival == static_cast<int>(iChannels))) { + if ((ioctl(fd, SNDCTL_DSP_CHANNELS, &ival) == -1) && (ival == static_cast< int >(iChannels))) { qWarning("OSSOutput: Failed to set channels"); return; } @@ -297,17 +292,9 @@ void OSSOutput::run() { } iMixerFreq = ival; - const unsigned int chanmasks[32] = { - SPEAKER_FRONT_LEFT, - SPEAKER_FRONT_RIGHT, - SPEAKER_FRONT_CENTER, - SPEAKER_LOW_FREQUENCY, - SPEAKER_BACK_LEFT, - SPEAKER_BACK_RIGHT, - SPEAKER_SIDE_LEFT, - SPEAKER_SIDE_RIGHT, - SPEAKER_BACK_CENTER - }; + const unsigned int chanmasks[32] = { SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT, SPEAKER_FRONT_CENTER, + SPEAKER_LOW_FREQUENCY, SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, + SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT, SPEAKER_BACK_CENTER }; eSampleFormat = SampleShort; @@ -329,7 +316,7 @@ void OSSOutput::run() { break; } } else { - while (! mix(mbuffer, iOutputBlock) && bRunning) + while (!mix(mbuffer, iOutputBlock) && bRunning) this->msleep(20); ssize_t l = write(fd, mbuffer, blocklen); if (l != blocklen) { diff --git a/src/mumble/OSS.h b/src/mumble/OSS.h index 18b4fcca9..a282d61fb 100644 --- a/src/mumble/OSS.h +++ b/src/mumble/OSS.h @@ -10,26 +10,28 @@ #include "AudioOutput.h" class OSSInput : public AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(OSSInput) - protected: - void release(); - public: - OSSInput(); - ~OSSInput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(OSSInput) +protected: + void release(); + +public: + OSSInput(); + ~OSSInput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; class OSSOutput : public AudioOutput { - friend class OSSUser; - private: - Q_OBJECT - Q_DISABLE_COPY(OSSOutput) - public: - OSSOutput(); - ~OSSOutput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; + friend class OSSUser; + +private: + Q_OBJECT + Q_DISABLE_COPY(OSSOutput) +public: + OSSOutput(); + ~OSSOutput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/OpusCodec.cpp b/src/mumble/OpusCodec.cpp index 0c6e3f6af..b7607bb77 100644 --- a/src/mumble/OpusCodec.cpp +++ b/src/mumble/OpusCodec.cpp @@ -6,13 +6,21 @@ #include "OpusCodec.h" #include "Audio.h" -#include "Version.h" #include "MumbleApplication.h" +#include "Version.h" #ifdef Q_CC_GNU -#define RESOLVE(var) { var = reinterpret_cast<__typeof__(var)>(qlOpus.resolve(#var)); bValid = bValid && var; } +# define RESOLVE(var) \ + { \ + var = reinterpret_cast< __typeof__(var) >(qlOpus.resolve(#var)); \ + bValid = bValid && var; \ + } #else -#define RESOLVE(var) { * reinterpret_cast<void **>(&var) = static_cast<void *>(qlOpus.resolve(#var)); bValid = bValid && var; } +# define RESOLVE(var) \ + { \ + *reinterpret_cast< void ** >(&var) = static_cast< void * >(qlOpus.resolve(#var)); \ + bValid = bValid && var; \ + } #endif OpusCodec::OpusCodec() { @@ -34,7 +42,7 @@ OpusCodec::OpusCodec() { alternatives << QString::fromLatin1("opus0.dll"); alternatives << QString::fromLatin1("opus.dll"); #endif - foreach(const QString &lib, alternatives) { + foreach (const QString &lib, alternatives) { qlOpus.setFileName(MumbleApplication::instance()->applicationVersionRootPath() + QLatin1String("/") + lib); if (qlOpus.load()) { bValid = true; diff --git a/src/mumble/OpusCodec.h b/src/mumble/OpusCodec.h index 7851de46e..54a21ce03 100644 --- a/src/mumble/OpusCodec.h +++ b/src/mumble/OpusCodec.h @@ -11,38 +11,41 @@ #include <QtCore/QLibrary> #ifndef Q_OS_WIN -#define __cdecl +# define __cdecl #endif /// Loads Opus from a shared library and acts as a wrapper for its functions. class OpusCodec { - private: - Q_DISABLE_COPY(OpusCodec) - protected: - QLibrary qlOpus; - bool bValid; - public: - OpusCodec(); - virtual ~OpusCodec(); +private: + Q_DISABLE_COPY(OpusCodec) +protected: + QLibrary qlOpus; + bool bValid; - bool isValid() const; - void report() const; +public: + OpusCodec(); + virtual ~OpusCodec(); - const char *(__cdecl *opus_get_version_string)(); + bool isValid() const; + void report() const; - OpusEncoder *(__cdecl *opus_encoder_create)(opus_int32 Fs, int channels, int application, int *error); - int (__cdecl *opus_encoder_ctl)(OpusEncoder *st, int request, ...); - void (__cdecl *opus_encoder_destroy)(OpusEncoder *st); - OpusDecoder *(__cdecl *opus_decoder_create)(opus_int32 Fs, int channels, int *error); - int (__cdecl *opus_decoder_ctl)(OpusDecoder *st, int request, ...); - void (__cdecl *opus_decoder_destroy)(OpusDecoder *st); + const char *(__cdecl *opus_get_version_string)(); - int (__cdecl *opus_encode)(OpusEncoder *st, const opus_int16 *pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes); - int (__cdecl *opus_decode_float)(OpusDecoder *st, const unsigned char *data, opus_int32 len, float *pcm, int frame_size, int decode_fec); + OpusEncoder *(__cdecl *opus_encoder_create)(opus_int32 Fs, int channels, int application, int *error); + int(__cdecl *opus_encoder_ctl)(OpusEncoder *st, int request, ...); + void(__cdecl *opus_encoder_destroy)(OpusEncoder *st); + OpusDecoder *(__cdecl *opus_decoder_create)(opus_int32 Fs, int channels, int *error); + int(__cdecl *opus_decoder_ctl)(OpusDecoder *st, int request, ...); + void(__cdecl *opus_decoder_destroy)(OpusDecoder *st); - int (__cdecl *opus_decoder_get_nb_samples)(OpusDecoder *st, const unsigned char packet[], opus_int32 len); + int(__cdecl *opus_encode)(OpusEncoder *st, const opus_int16 *pcm, int frame_size, unsigned char *compressed, + int nbCompressedBytes); + int(__cdecl *opus_decode_float)(OpusDecoder *st, const unsigned char *data, opus_int32 len, float *pcm, + int frame_size, int decode_fec); - int (__cdecl *opus_packet_get_samples_per_frame)(const unsigned char *data, opus_int32 Fs); + int(__cdecl *opus_decoder_get_nb_samples)(OpusDecoder *st, const unsigned char packet[], opus_int32 len); + + int(__cdecl *opus_packet_get_samples_per_frame)(const unsigned char *data, opus_int32 Fs); }; -#endif // OPUSCODEC_H_ +#endif // OPUSCODEC_H_ diff --git a/src/mumble/Overlay.cpp b/src/mumble/Overlay.cpp index 8d02dc58d..30cd4bc2b 100644 --- a/src/mumble/Overlay.cpp +++ b/src/mumble/Overlay.cpp @@ -5,19 +5,19 @@ #include "Overlay.h" -#include "OverlayClient.h" #include "Channel.h" #include "ClientUser.h" #include "Database.h" -#include "GlobalShortcut.h" #include "MainWindow.h" #include "Message.h" +#include "OverlayClient.h" #include "OverlayText.h" #include "RichTextEditor.h" #include "ServerHandler.h" #include "User.h" #include "Utils.h" #include "WebFetch.h" +#include "GlobalShortcut.h" #include <QtCore/QProcessEnvironment> #include <QtCore/QtEndian> @@ -28,32 +28,35 @@ #include <QtWidgets/QMessageBox> #ifdef Q_OS_WIN -# include <shellapi.h> +# include <shellapi.h> #endif #ifdef Q_OS_MAC -# include <ApplicationServices/ApplicationServices.h> -# include <CoreFoundation/CoreFoundation.h> +# include <ApplicationServices/ApplicationServices.h> +# include <CoreFoundation/CoreFoundation.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" QString OverlayAppInfo::applicationIdentifierForPath(const QString &path) { #ifdef Q_OS_MAC QString qsIdentifier; CFDictionaryRef plist = nullptr; - CFDataRef data = nullptr; + CFDataRef data = nullptr; QFile qfAppBundle(QString::fromLatin1("%1/Contents/Info.plist").arg(path)); if (qfAppBundle.exists()) { qfAppBundle.open(QIODevice::ReadOnly); QByteArray qbaPlistData = qfAppBundle.readAll(); - data = CFDataCreateWithBytesNoCopy(nullptr, reinterpret_cast<UInt8 *>(qbaPlistData.data()), qbaPlistData.count(), kCFAllocatorNull); - plist = static_cast<CFDictionaryRef>(CFPropertyListCreateFromXMLData(nullptr, data, kCFPropertyListImmutable, nullptr)); + data = CFDataCreateWithBytesNoCopy(nullptr, reinterpret_cast< UInt8 * >(qbaPlistData.data()), + qbaPlistData.count(), kCFAllocatorNull); + plist = static_cast< CFDictionaryRef >( + CFPropertyListCreateFromXMLData(nullptr, data, kCFPropertyListImmutable, nullptr)); if (plist) { - CFStringRef ident = static_cast<CFStringRef>(CFDictionaryGetValue(plist, CFSTR("CFBundleIdentifier"))); + CFStringRef ident = static_cast< CFStringRef >(CFDictionaryGetValue(plist, CFSTR("CFBundleIdentifier"))); if (ident) { char buf[4096]; CFStringGetCString(ident, buf, 4096, kCFStringEncodingUTF8); @@ -80,12 +83,13 @@ OverlayAppInfo OverlayAppInfo::applicationInfoForId(const QString &identifier) { QIcon qiAppIcon; #if defined(Q_OS_MAC) CFStringRef bundleId = nullptr; - CFURLRef bundleUrl = nullptr; - CFBundleRef bundle = nullptr; - OSStatus err = noErr; + CFURLRef bundleUrl = nullptr; + CFBundleRef bundle = nullptr; + OSStatus err = noErr; char buf[4096]; - bundleId = CFStringCreateWithCharacters(kCFAllocatorDefault, reinterpret_cast<const UniChar *>(identifier.unicode()), identifier.length()); + bundleId = CFStringCreateWithCharacters( + kCFAllocatorDefault, reinterpret_cast< const UniChar * >(identifier.unicode()), identifier.length()); err = LSFindApplicationForInfo(kLSUnknownCreator, bundleId, nullptr, nullptr, &bundleUrl); if (err == noErr) { // Figure out the bundle name of the application. @@ -100,12 +104,13 @@ OverlayAppInfo OverlayAppInfo::applicationInfoForId(const QString &identifier) { if (bundle) { CFDictionaryRef info = CFBundleGetInfoDictionary(bundle); if (info) { - CFStringRef iconFileName = reinterpret_cast<CFStringRef>(CFDictionaryGetValue(info, CFSTR("CFBundleIconFile"))); + CFStringRef iconFileName = + reinterpret_cast< CFStringRef >(CFDictionaryGetValue(info, CFSTR("CFBundleIconFile"))); if (iconFileName) { CFStringGetCString(iconFileName, buf, 4096, kCFStringEncodingUTF8); - QString qsIconPath = QString::fromLatin1("%1/Contents/Resources/%2") - .arg(qsBundlePath, QString::fromUtf8(buf)); - if (! QFile::exists(qsIconPath)) { + QString qsIconPath = + QString::fromLatin1("%1/Contents/Resources/%2").arg(qsBundlePath, QString::fromUtf8(buf)); + if (!QFile::exists(qsIconPath)) { qsIconPath += QString::fromLatin1(".icns"); } if (QFile::exists(qsIconPath)) { @@ -139,7 +144,7 @@ OverlayAppInfo OverlayAppInfo::applicationInfoForId(const QString &identifier) { // To sidestep the removal of the function, we simply // call through to GetModuleHandle() directly. HINSTANCE qWinAppInstValue = GetModuleHandle(nullptr); - HICON icon = ExtractIcon(qWinAppInstValue, identifier.toStdWString().c_str(), 0); + HICON icon = ExtractIcon(qWinAppInstValue, identifier.toStdWString().c_str(), 0); if (icon) { extern QPixmap qt_pixmapFromWinHICON(HICON icon); qiAppIcon = QIcon(qt_pixmapFromWinHICON(icon)); @@ -151,7 +156,7 @@ OverlayAppInfo OverlayAppInfo::applicationInfoForId(const QString &identifier) { OverlayAppInfo::OverlayAppInfo(QString name, QIcon icon) { qsDisplayName = name; - qiIcon = icon; + qiIcon = icon; } OverlayMouse::OverlayMouse(QGraphicsItem *p) : QGraphicsPixmapItem(p) { @@ -177,7 +182,7 @@ void OverlayGroup::paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget * QRectF OverlayGroup::boundingRect() const { QRectF qr; - foreach(const QGraphicsItem *item, childItems()) + foreach (const QGraphicsItem *item, childItems()) if (item->isVisible()) qr |= item->boundingRect().translated(item->pos()); @@ -201,12 +206,13 @@ Overlay::~Overlay() { } // Need to be deleted first, since destructor references lingering QLocalSockets - foreach(OverlayClient *oc, qlClients) { + foreach (OverlayClient *oc, qlClients) { // As we're the one closing the connection, we do not need to be // notified of disconnects. This is important because on disconnect we // also remove (and 'delete') the overlay client. disconnect(oc->qlsSocket, SIGNAL(disconnected()), this, SLOT(disconnected())); - disconnect(oc->qlsSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(error(QLocalSocket::LocalSocketError))); + disconnect(oc->qlsSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, + SLOT(error(QLocalSocket::LocalSocketError))); delete oc; } } @@ -217,7 +223,7 @@ void Overlay::initialize() { forceSettings(); createPipe(); - + m_initialized.store(true); } } @@ -245,9 +251,9 @@ void Overlay::createPipe() { #else { QString xdgRuntimePath = QProcessEnvironment::systemEnvironment().value(QLatin1String("XDG_RUNTIME_DIR")); - QDir xdgRuntimeDir = QDir(xdgRuntimePath); + QDir xdgRuntimeDir = QDir(xdgRuntimePath); - if (! xdgRuntimePath.isNull() && xdgRuntimeDir.exists()) { + if (!xdgRuntimePath.isNull() && xdgRuntimeDir.exists()) { pipepath = xdgRuntimeDir.absoluteFilePath(QLatin1String("MumbleOverlayPipe")); } else { pipepath = QDir::home().absoluteFilePath(QLatin1String(".MumbleOverlayPipe")); @@ -263,8 +269,11 @@ void Overlay::createPipe() { } #endif - if (! qlsServer->listen(pipepath)) { - QMessageBox::warning(nullptr, QLatin1String("Mumble"), tr("Failed to create communication with overlay at %2: %1. No overlay will be available.").arg(qlsServer->errorString().toHtmlEscaped(), pipepath.toHtmlEscaped()), QMessageBox::Ok, QMessageBox::NoButton); + if (!qlsServer->listen(pipepath)) { + QMessageBox::warning(nullptr, QLatin1String("Mumble"), + tr("Failed to create communication with overlay at %2: %1. No overlay will be available.") + .arg(qlsServer->errorString().toHtmlEscaped(), pipepath.toHtmlEscaped()), + QMessageBox::Ok, QMessageBox::NoButton); } else { qWarning() << "Overlay: Listening on" << qlsServer->fullServerName(); connect(qlsServer, SIGNAL(newConnection()), this, SLOT(newConnection())); @@ -284,8 +293,8 @@ void Overlay::newConnection() { } void Overlay::disconnected() { - QLocalSocket *qls = qobject_cast<QLocalSocket *>(sender()); - foreach(OverlayClient *oc, qlClients) { + QLocalSocket *qls = qobject_cast< QLocalSocket * >(sender()); + foreach (OverlayClient *oc, qlClients) { if (oc->qlsSocket == qls) { qlClients.removeAll(oc); delete oc; @@ -299,14 +308,14 @@ void Overlay::error(QLocalSocket::LocalSocketError) { } bool Overlay::isActive() const { - return ! qlClients.isEmpty(); + return !qlClients.isEmpty(); } void Overlay::toggleShow() { if (g.ocIntercept) { g.ocIntercept->hideGui(); } else { - foreach(OverlayClient *oc, qlClients) { + foreach (OverlayClient *oc, qlClients) { if (oc->uiPid) { #if defined(Q_OS_WIN) HWND hwnd = GetForegroundWindow(); @@ -315,13 +324,13 @@ void Overlay::toggleShow() { if (pid != oc->uiPid) continue; #elif defined(Q_OS_MAC) - if (static_cast<quint64>(getForegroundProcessId()) != oc->uiPid) + if (static_cast< quint64 >(getForegroundProcessId()) != oc->uiPid) continue; -#if 0 +# if 0 // Fullscreen only. if (! CGDisplayIsCaptured(CGMainDisplayID())) continue; -#endif +# endif #endif oc->showGui(); return; @@ -331,9 +340,7 @@ void Overlay::toggleShow() { } void Overlay::forceSettings() { - foreach(OverlayClient *oc, qlClients) { - oc->reset(); - } + foreach (OverlayClient *oc, qlClients) { oc->reset(); } updateOverlay(); } @@ -342,29 +349,30 @@ void Overlay::verifyTexture(ClientUser *cp, bool allowupdate) { qsQueried.remove(cp->uiSession); ClientUser *self = ClientUser::get(g.uiSession); - allowupdate = allowupdate && self && self->cChannel->isLinked(cp->cChannel); + allowupdate = allowupdate && self && self->cChannel->isLinked(cp->cChannel); - if (allowupdate && ! cp->qbaTextureHash.isEmpty() && cp->qbaTexture.isEmpty()) + if (allowupdate && !cp->qbaTextureHash.isEmpty() && cp->qbaTexture.isEmpty()) cp->qbaTexture = g.db->blob(cp->qbaTextureHash); - if (! cp->qbaTexture.isEmpty()) { + if (!cp->qbaTexture.isEmpty()) { bool valid = true; - if (cp->qbaTexture.length() < static_cast<int>(sizeof(unsigned int))) { + if (cp->qbaTexture.length() < static_cast< int >(sizeof(unsigned int))) { valid = false; - } else if (qFromBigEndian<unsigned int>(reinterpret_cast<const unsigned char *>(cp->qbaTexture.constData())) == 600 * 60 * 4) { + } else if (qFromBigEndian< unsigned int >(reinterpret_cast< const unsigned char * >(cp->qbaTexture.constData())) + == 600 * 60 * 4) { QByteArray qba = qUncompress(cp->qbaTexture); if (qba.length() != 600 * 60 * 4) { valid = false; } else { - int width = 0; - int height = 0; - const unsigned int *ptr = reinterpret_cast<const unsigned int *>(qba.constData()); + int width = 0; + int height = 0; + const unsigned int *ptr = reinterpret_cast< const unsigned int * >(qba.constData()); // If we have an alpha only part on the right side of the image ignore it - for (int y=0;y<60;++y) { - for (int x=0;x<600; ++x) { - if (ptr[y*600+x] & 0xff000000) { + for (int y = 0; y < 60; ++y) { + for (int x = 0; x < 600; ++x) { + if (ptr[y * 600 + x] & 0xff000000) { if (x > width) width = x; if (y > height) @@ -375,11 +383,11 @@ void Overlay::verifyTexture(ClientUser *cp, bool allowupdate) { // Full size image? More likely image without alpha; fix it. if ((width == 599) && (height == 59)) { - width = 0; + width = 0; height = 0; - for (int y=0;y<60;++y) { - for (int x=0;x<600; ++x) { - if (ptr[y*600+x] & 0x00ffffff) { + for (int y = 0; y < 60; ++y) { + for (int x = 0; x < 600; ++x) { + if (ptr[y * 600 + x] & 0x00ffffff) { if (x > width) width = x; if (y > height) @@ -389,24 +397,25 @@ void Overlay::verifyTexture(ClientUser *cp, bool allowupdate) { } } - if (! width || ! height) { + if (!width || !height) { valid = false; } else { - QImage img = QImage(width+1, height+1, QImage::Format_ARGB32); + QImage img = QImage(width + 1, height + 1, QImage::Format_ARGB32); { - QImage srcimg(reinterpret_cast<const uchar *>(qba.constData()), 600, 60, QImage::Format_ARGB32); + QImage srcimg(reinterpret_cast< const uchar * >(qba.constData()), 600, 60, + QImage::Format_ARGB32); QPainter imgp(&img); img.fill(0); imgp.setRenderHint(QPainter::Antialiasing); imgp.setRenderHint(QPainter::TextAntialiasing); - imgp.setBackground(QColor(0,0,0,0)); + imgp.setBackground(QColor(0, 0, 0, 0)); imgp.setCompositionMode(QPainter::CompositionMode_Source); imgp.drawImage(0, 0, srcimg); } cp->qbaTexture = QByteArray(); - QBuffer qb(& cp->qbaTexture); + QBuffer qb(&cp->qbaTexture); qb.open(QIODevice::WriteOnly); QImageWriter qiw(&qb, "png"); qiw.write(img); @@ -415,7 +424,7 @@ void Overlay::verifyTexture(ClientUser *cp, bool allowupdate) { } } } else { - QBuffer qb(& cp->qbaTexture); + QBuffer qb(&cp->qbaTexture); qb.open(QIODevice::ReadOnly); QImageReader qir; @@ -425,19 +434,19 @@ void Overlay::verifyTexture(ClientUser *cp, bool allowupdate) { if (RichTextImage::isValidImage(cp->qbaTexture, fmt)) { qir.setFormat(fmt); qir.setDevice(&qb); - if (! qir.canRead() || (qir.size().width() > 1024) || (qir.size().height() > 1024)) { + if (!qir.canRead() || (qir.size().width() > 1024) || (qir.size().height() > 1024)) { valid = false; } else { cp->qbaTextureFormat = qir.format(); - QImage qi = qir.read(); - valid = ! qi.isNull(); + QImage qi = qir.read(); + valid = !qi.isNull(); } } else { valid = false; } } - if (! valid) { - cp->qbaTexture = QByteArray(); + if (!valid) { + cp->qbaTexture = QByteArray(); cp->qbaTextureHash = QByteArray(); } } @@ -446,10 +455,10 @@ void Overlay::verifyTexture(ClientUser *cp, bool allowupdate) { updateOverlay(); } -typedef QPair<QString, quint32> qpChanCol; +typedef QPair< QString, quint32 > qpChanCol; void Overlay::updateOverlay() { - if (! g.uiSession) + if (!g.uiSession) qsQueried.clear(); if (qlClients.isEmpty()) @@ -457,8 +466,8 @@ void Overlay::updateOverlay() { qsQuery.clear(); - foreach(OverlayClient *oc, qlClients) { - if (! oc->update()) { + foreach (OverlayClient *oc, qlClients) { + if (!oc->update()) { qWarning() << "Overlay: Dead client detected. PID" << oc->uiPid << oc->qsExecutablePath; qlClients.removeAll(oc); oc->scheduleDelete(); @@ -466,9 +475,9 @@ void Overlay::updateOverlay() { } } - if (! qsQuery.isEmpty()) { + if (!qsQuery.isEmpty()) { MumbleProto::RequestBlob mprb; - foreach(unsigned int session, qsQuery) { + foreach (unsigned int session, qsQuery) { qsQueried.insert(session); mprb.add_session_texture(session); } @@ -477,8 +486,8 @@ void Overlay::updateOverlay() { } void Overlay::requestTexture(ClientUser *cu) { - if (cu->qbaTexture.isEmpty() && ! qsQueried.contains(cu->uiSession)) { - cu->qbaTexture=g.db->blob(cu->qbaTextureHash); + if (cu->qbaTexture.isEmpty() && !qsQueried.contains(cu->uiSession)) { + cu->qbaTexture = g.db->blob(cu->qbaTextureHash); if (cu->qbaTexture.isEmpty()) qsQuery.insert(cu->uiSession); else diff --git a/src/mumble/Overlay.h b/src/mumble/Overlay.h index 4e84ec926..b16bdb772 100644 --- a/src/mumble/Overlay.h +++ b/src/mumble/Overlay.h @@ -6,14 +6,14 @@ #ifndef MUMBLE_MUMBLE_OVERLAY_H_ #define MUMBLE_MUMBLE_OVERLAY_H_ -#include <QtCore/QtGlobal> #include <QtCore/QUrl> +#include <QtCore/QtGlobal> #include <QtNetwork/QLocalSocket> #include <QtWidgets/QGraphicsItem> +#include "../../overlay/overlay.h" #include "ConfigDialog.h" #include "OverlayText.h" -#include "../../overlay/overlay.h" #include <atomic> @@ -42,81 +42,84 @@ private: }; class OverlayGroup : public QGraphicsItem { - private: - Q_DISABLE_COPY(OverlayGroup); - public: - enum { Type = UserType + 5 }; - public: - OverlayGroup(); - - QRectF boundingRect() const Q_DECL_OVERRIDE; - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) Q_DECL_OVERRIDE; - int type() const Q_DECL_OVERRIDE; - - template <typename T> - QRectF boundingRect() const; +private: + Q_DISABLE_COPY(OverlayGroup); + +public: + enum { Type = UserType + 5 }; + +public: + OverlayGroup(); + + QRectF boundingRect() const Q_DECL_OVERRIDE; + void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) Q_DECL_OVERRIDE; + int type() const Q_DECL_OVERRIDE; + + template< typename T > QRectF boundingRect() const; }; class OverlayMouse : public QGraphicsPixmapItem { - private: - Q_DISABLE_COPY(OverlayMouse) - public: - bool contains(const QPointF &) const Q_DECL_OVERRIDE; - bool collidesWithPath(const QPainterPath &, Qt::ItemSelectionMode = Qt::IntersectsItemShape) const Q_DECL_OVERRIDE; - OverlayMouse(QGraphicsItem * = nullptr); +private: + Q_DISABLE_COPY(OverlayMouse) +public: + bool contains(const QPointF &) const Q_DECL_OVERRIDE; + bool collidesWithPath(const QPainterPath &, Qt::ItemSelectionMode = Qt::IntersectsItemShape) const Q_DECL_OVERRIDE; + OverlayMouse(QGraphicsItem * = nullptr); }; class OverlayPrivate : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(OverlayPrivate) - public: - OverlayPrivate(QObject *p) : QObject(p) {}; +private: + Q_OBJECT + Q_DISABLE_COPY(OverlayPrivate) +public: + OverlayPrivate(QObject *p) : QObject(p){}; }; class Overlay : public QObject { - friend class OverlayConfig; - friend class OverlayClient; - friend class OverlayUser; - private: - Q_OBJECT - Q_DISABLE_COPY(Overlay) - protected: - OverlayPrivate *d; - - QSet<unsigned int> qsQueried; - QSet<unsigned int> qsQuery; - /// A flag indicating if the platformInit has been called already - std::atomic<bool> m_initialized; - - /// Initializes the overlay, if it hasn't been initialized yet - void initialize(); - - // These 2 functions (among others) are implemented by the system-specific backend - void platformInit(); - void setActiveInternal(bool act); - - void createPipe(); - - QMap<QString, QString> qmOverlayHash; - QLocalServer *qlsServer; - QList<OverlayClient *> qlClients; - protected slots: - void disconnected(); - void error(QLocalSocket::LocalSocketError); - void newConnection(); - public: - Overlay(); - ~Overlay() Q_DECL_OVERRIDE; - bool isActive() const; - void verifyTexture(ClientUser *cp, bool allowupdate = true); - void requestTexture(ClientUser *); - - public slots: - void updateOverlay(); - void setActive(bool act); - void toggleShow(); - void forceSettings(); + friend class OverlayConfig; + friend class OverlayClient; + friend class OverlayUser; + +private: + Q_OBJECT + Q_DISABLE_COPY(Overlay) +protected: + OverlayPrivate *d; + + QSet< unsigned int > qsQueried; + QSet< unsigned int > qsQuery; + /// A flag indicating if the platformInit has been called already + std::atomic< bool > m_initialized; + + /// Initializes the overlay, if it hasn't been initialized yet + void initialize(); + + // These 2 functions (among others) are implemented by the system-specific backend + void platformInit(); + void setActiveInternal(bool act); + + void createPipe(); + + QMap< QString, QString > qmOverlayHash; + QLocalServer *qlsServer; + QList< OverlayClient * > qlClients; +protected slots: + void disconnected(); + void error(QLocalSocket::LocalSocketError); + void newConnection(); + +public: + Overlay(); + ~Overlay() Q_DECL_OVERRIDE; + bool isActive() const; + void verifyTexture(ClientUser *cp, bool allowupdate = true); + void requestTexture(ClientUser *); + +public slots: + void updateOverlay(); + void setActive(bool act); + void toggleShow(); + void forceSettings(); }; #endif diff --git a/src/mumble/OverlayClient.cpp b/src/mumble/OverlayClient.cpp index b88a690c3..cf9a3e845 100644 --- a/src/mumble/OverlayClient.cpp +++ b/src/mumble/OverlayClient.cpp @@ -4,53 +4,49 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "OverlayClient.h" -#include "OverlayPositionableItem.h" -#include "OverlayEditor.h" -#include "OverlayText.h" -#include "User.h" #include "Channel.h" -#include "Message.h" #include "Database.h" +#include "MainWindow.h" +#include "Message.h" #include "NetworkConfig.h" +#include "OverlayEditor.h" +#include "OverlayPositionableItem.h" +#include "OverlayText.h" #include "ServerHandler.h" -#include "MainWindow.h" -#include "GlobalShortcut.h" #include "Themes.h" +#include "User.h" #include "Utils.h" +#include "GlobalShortcut.h" #ifdef Q_OS_WIN -# include <QtGui/QBitmap> +# include <QtGui/QBitmap> #endif #include <QtGui/QImageReader> #include <QtWidgets/QGraphicsProxyWidget> #ifdef Q_OS_WIN -# include <psapi.h> +# include <psapi.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" OverlayClient::OverlayClient(QLocalSocket *socket, QObject *p) - : QObject(p) - , framesPerSecond(0) - , ougUsers(&g.s.os) - , iMouseX(0) - , iMouseY(0) { - + : QObject(p), framesPerSecond(0), ougUsers(&g.s.os), iMouseX(0), iMouseY(0) { qlsSocket = socket; qlsSocket->setParent(nullptr); connect(qlsSocket, SIGNAL(readyRead()), this, SLOT(readyRead())); omMsg.omh.iLength = -1; - smMem = nullptr; + smMem = nullptr; uiWidth = uiHeight = 0; uiPid = ~0ULL; bWasVisible = false; - bDelete = false; + bDelete = false; qgv.setScene(&qgs); qgv.installEventFilter(this); @@ -80,7 +76,7 @@ OverlayClient::OverlayClient(QLocalSocket *socket, QObject *p) iOffsetX = iOffsetY = 0; - connect(&qgs, SIGNAL(changed(const QList<QRectF> &)), this, SLOT(changed(const QList<QRectF> &))); + connect(&qgs, SIGNAL(changed(const QList< QRectF > &)), this, SLOT(changed(const QList< QRectF > &))); } OverlayClient::~OverlayClient() { @@ -89,7 +85,7 @@ OverlayClient::~OverlayClient() { qDebug() << "OverlayClient: Failed to cleanly disconnect: " << qlsSocket->errorString(); qlsSocket->abort(); } - + qlsSocket->deleteLater(); ougUsers.reset(); @@ -105,13 +101,13 @@ bool OverlayClient::eventFilter(QObject *o, QEvent *e) { void OverlayClient::updateFPS() { if (g.s.os.bFps) { - const BasepointPixmap &pm = OverlayTextLine( - QString(QLatin1String("%1")).arg(iroundf(framesPerSecond + 0.5f)), - g.s.os.qfFps).createPixmap(g.s.os.qcFps); + const BasepointPixmap &pm = + OverlayTextLine(QString(QLatin1String("%1")).arg(iroundf(framesPerSecond + 0.5f)), g.s.os.qfFps) + .createPixmap(g.s.os.qcFps); qgpiFPS->setVisible(true); qgpiFPS->setPixmap(pm); // offset to use basepoint - //TODO: settings are providing a top left anchor, so shift down by ascent + // TODO: settings are providing a top left anchor, so shift down by ascent qgpiFPS->setOffset(-pm.qpBasePoint + QPoint(0, pm.iAscent)); qgpiFPS->updateRender(); } else { @@ -121,7 +117,9 @@ void OverlayClient::updateFPS() { void OverlayClient::updateTime() { if (g.s.os.bTime) { - const BasepointPixmap &pm = OverlayTextLine(QString(QLatin1String("%1")).arg(QTime::currentTime().toString()), g.s.os.qfFps).createPixmap(g.s.os.qcFps); + const BasepointPixmap &pm = + OverlayTextLine(QString(QLatin1String("%1")).arg(QTime::currentTime().toString()), g.s.os.qfFps) + .createPixmap(g.s.os.qcFps); qgpiTime->setVisible(true); qgpiTime->setPixmap(pm); qgpiTime->setOffset(-pm.qpBasePoint + QPoint(0, pm.iAscent)); @@ -133,7 +131,7 @@ void OverlayClient::updateTime() { #if !defined(Q_OS_MAC) || (defined(Q_OS_MAC) && defined(USE_MAC_UNIVERSAL)) void OverlayClient::updateMouse() { -#if defined(Q_OS_WIN) +# if defined(Q_OS_WIN) QPixmap pm; HICON c = ::GetCursor(); @@ -155,16 +153,16 @@ void OverlayClient::updateMouse() { QImage out(img.width(), h, QImage::Format_MonoLSB); QImage outmask(img.width(), h, QImage::Format_MonoLSB); - for (int i=0;i<h; ++i) { - const quint32 *srcimg = reinterpret_cast<const quint32 *>(img.scanLine(i + h)); - const quint32 *srcmask = reinterpret_cast<const quint32 *>(img.scanLine(i)); + for (int i = 0; i < h; ++i) { + const quint32 *srcimg = reinterpret_cast< const quint32 * >(img.scanLine(i + h)); + const quint32 *srcmask = reinterpret_cast< const quint32 * >(img.scanLine(i)); - quint32 *dstimg = reinterpret_cast<quint32 *>(out.scanLine(i)); - quint32 *dstmask = reinterpret_cast<quint32 *>(outmask.scanLine(i)); + quint32 *dstimg = reinterpret_cast< quint32 * >(out.scanLine(i)); + quint32 *dstmask = reinterpret_cast< quint32 * >(outmask.scanLine(i)); - for (int j=0;j<w;++j) { + for (int j = 0; j < w; ++j) { dstmask[j] = srcmask[j]; - dstimg[j] = srcimg[j]; + dstimg[j] = srcimg[j]; } } pm = QBitmap::fromImage(out); @@ -180,8 +178,8 @@ void OverlayClient::updateMouse() { } qgpiCursor->setPixmap(pm); -#else -#endif +# else +# endif qgpiCursor->setPos(iMouseX - iOffsetX, iMouseY - iOffsetY); } @@ -196,7 +194,7 @@ void OverlayClient::showGui() { { QWidgetList widgets = qApp->topLevelWidgets(); - foreach(QWidget *w, widgets) { + foreach (QWidget *w, widgets) { if (w->isHidden() && (w != g.mw)) continue; count++; @@ -208,28 +206,28 @@ void OverlayClient::showGui() { g.ocIntercept = this; - bWasVisible = ! g.mw->isHidden(); + bWasVisible = !g.mw->isHidden(); if (bWasVisible) { if (g.s.bMinimalView) { g.s.qbaMinimalViewGeometry = g.mw->saveGeometry(); - g.s.qbaMinimalViewState = g.mw->saveState(); + g.s.qbaMinimalViewState = g.mw->saveState(); } else { g.s.qbaMainWindowGeometry = g.mw->saveGeometry(); - g.s.qbaMainWindowState = g.mw->saveState(); - g.s.qbaHeaderState = g.mw->qtvUsers->header()->saveState(); + g.s.qbaMainWindowState = g.mw->saveState(); + g.s.qbaHeaderState = g.mw->qtvUsers->header()->saveState(); } } { -outer: + outer: QWidgetList widgets = qApp->topLevelWidgets(); widgets.removeAll(g.mw); widgets.prepend(g.mw); - foreach(QWidget *w, widgets) { + foreach (QWidget *w, widgets) { if (!w->graphicsProxyWidget()) { - if ((w == g.mw) || (! w->isHidden())) { + if ((w == g.mw) || (!w->isHidden())) { QGraphicsProxyWidget *qgpw = new QGraphicsProxyWidget(nullptr, Qt::Window); qgpw->setOpacity(0.90f); qgpw->setWidget(w); @@ -251,8 +249,8 @@ outer: qApp->sendEvent(&qgs, &activateEvent); QPoint p = QCursor::pos(); - iMouseX = qBound<int>(0, p.x(), uiWidth-1); - iMouseY = qBound<int>(0, p.y(), uiHeight-1); + iMouseX = qBound< int >(0, p.x(), uiWidth - 1); + iMouseY = qBound< int >(0, p.y(), uiHeight - 1); qgpiCursor->setPos(iMouseX, iMouseY); @@ -271,7 +269,7 @@ outer: #ifdef Q_OS_MAC qApp->setAttribute(Qt::AA_DontUseNativeMenuBar); g.mw->setUnifiedTitleAndToolBarOnMac(false); - if (! g.s.os.qsStyle.isEmpty()) + if (!g.s.os.qsStyle.isEmpty()) qApp->setStyle(g.s.os.qsStyle); #endif @@ -279,9 +277,9 @@ outer: OverlayMsg om; om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - om.omh.uiType = OVERLAY_MSGTYPE_INTERACTIVE; + om.omh.uiType = OVERLAY_MSGTYPE_INTERACTIVE; om.omh.iLength = sizeof(struct OverlayMsgInteractive); - om.omin.state = true; + om.omin.state = true; qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + om.omh.iLength); g.o->updateOverlay(); @@ -290,10 +288,10 @@ outer: void OverlayClient::hideGui() { ougUsers.bShowExamples = false; - QList<QWidget *> widgetlist; + QList< QWidget * > widgetlist; - foreach(QGraphicsItem *qgi, qgs.items(Qt::DescendingOrder)) { - QGraphicsProxyWidget *qgpw = qgraphicsitem_cast<QGraphicsProxyWidget *>(qgi); + foreach (QGraphicsItem *qgi, qgs.items(Qt::DescendingOrder)) { + QGraphicsProxyWidget *qgpw = qgraphicsitem_cast< QGraphicsProxyWidget * >(qgi); if (qgpw && qgpw->widget()) { QWidget *w = qgpw->widget(); @@ -302,7 +300,7 @@ void OverlayClient::hideGui() { } } - foreach(QWidget *w, widgetlist) { + foreach (QWidget *w, widgetlist) { QGraphicsProxyWidget *qgpw = w->graphicsProxyWidget(); if (qgpw) { qgpw->setVisible(false); @@ -314,16 +312,16 @@ void OverlayClient::hideGui() { if (g.ocIntercept == this) g.ocIntercept = nullptr; - foreach(QWidget *w, widgetlist) { + foreach (QWidget *w, widgetlist) { if (bWasVisible) w->show(); } if (bWasVisible) { - if (g.s.bMinimalView && ! g.s.qbaMinimalViewGeometry.isNull()) { + if (g.s.bMinimalView && !g.s.qbaMinimalViewGeometry.isNull()) { g.mw->restoreGeometry(g.s.qbaMinimalViewGeometry); g.mw->restoreState(g.s.qbaMinimalViewState); - } else if (! g.s.bMinimalView && ! g.s.qbaMainWindowGeometry.isNull()) { + } else if (!g.s.bMinimalView && !g.s.qbaMainWindowGeometry.isNull()) { g.mw->restoreGeometry(g.s.qbaMainWindowGeometry); g.mw->restoreState(g.s.qbaMainWindowState); } @@ -341,9 +339,9 @@ void OverlayClient::hideGui() { OverlayMsg om; om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - om.omh.uiType = OVERLAY_MSGTYPE_INTERACTIVE; + om.omh.uiType = OVERLAY_MSGTYPE_INTERACTIVE; om.omh.iLength = sizeof(struct OverlayMsgInteractive); - om.omin.state = false; + om.omin.state = false; qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + om.omh.iLength); g.o->updateOverlay(); @@ -362,48 +360,49 @@ void OverlayClient::readyReadMsgInit(unsigned int length) { return; } - OverlayMsgInit *omi = & omMsg.omi; + OverlayMsgInit *omi = &omMsg.omi; - uiWidth = omi->uiWidth; + uiWidth = omi->uiWidth; uiHeight = omi->uiHeight; - qrLast = QRect(); + qrLast = QRect(); delete smMem; smMem = new SharedMemory2(this, uiWidth * uiHeight * 4); - if (! smMem->data()) { + if (!smMem->data()) { qWarning() << "OverlayClient: Failed to create shared memory" << uiWidth << uiHeight; delete smMem; smMem = nullptr; return; } QByteArray key = smMem->name().toUtf8(); - key.append(static_cast<char>(0)); + key.append(static_cast< char >(0)); OverlayMsg om; om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - om.omh.uiType = OVERLAY_MSGTYPE_SHMEM; + om.omh.uiType = OVERLAY_MSGTYPE_SHMEM; om.omh.iLength = key.length(); - Q_ASSERT(sizeof(om.oms.a_cName) >= static_cast<size_t>(key.length())); // Name should be auto-generated and short + Q_ASSERT(sizeof(om.oms.a_cName) >= static_cast< size_t >(key.length())); // Name should be auto-generated and short memcpy(om.oms.a_cName, key.constData(), key.length()); qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + om.omh.iLength); setupRender(); - Overlay *o = static_cast<Overlay *>(parent()); + Overlay *o = static_cast< Overlay * >(parent()); QTimer::singleShot(0, o, SLOT(updateOverlay())); } void OverlayClient::readyRead() { while (true) { - quint64 ready = static_cast<quint64>(qlsSocket->bytesAvailable()); + quint64 ready = static_cast< quint64 >(qlsSocket->bytesAvailable()); if (omMsg.omh.iLength == -1) { if (ready < sizeof(OverlayMsgHeader)) { break; } else { qlsSocket->read(omMsg.headerbuffer, sizeof(OverlayMsgHeader)); - if ((omMsg.omh.uiMagic != OVERLAY_MAGIC_NUMBER) || (omMsg.omh.iLength < 0) || (omMsg.omh.iLength > static_cast<int>(sizeof(OverlayMsgShmem)))) { + if ((omMsg.omh.uiMagic != OVERLAY_MAGIC_NUMBER) || (omMsg.omh.iLength < 0) + || (omMsg.omh.iLength > static_cast< int >(sizeof(OverlayMsgShmem)))) { disconnect(); return; } @@ -411,7 +410,7 @@ void OverlayClient::readyRead() { } } - if (ready >= static_cast<unsigned int>(omMsg.omh.iLength)) { + if (ready >= static_cast< unsigned int >(omMsg.omh.iLength)) { qint64 length = qlsSocket->read(omMsg.msgbuffer, omMsg.omh.iLength); if (length != omMsg.omh.iLength) { @@ -421,46 +420,42 @@ void OverlayClient::readyRead() { switch (omMsg.omh.uiType) { case OVERLAY_MSGTYPE_INIT: { - readyReadMsgInit(static_cast<unsigned int>(length)); - } - break; + readyReadMsgInit(static_cast< unsigned int >(length)); + } break; case OVERLAY_MSGTYPE_SHMEM: { - if (smMem) - smMem->systemRelease(); - } - break; + if (smMem) + smMem->systemRelease(); + } break; case OVERLAY_MSGTYPE_PID: { - if (length != static_cast<qint64>(sizeof(OverlayMsgPid))) - break; + if (length != static_cast< qint64 >(sizeof(OverlayMsgPid))) + break; - OverlayMsgPid *omp = & omMsg.omp; - uiPid = omp->pid; + OverlayMsgPid *omp = &omMsg.omp; + uiPid = omp->pid; #ifdef Q_OS_WIN - HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, (DWORD)uiPid); - if (h) { - wchar_t buf[MAX_PATH]; - if (GetModuleFileNameEx(h, 0, buf, MAX_PATH) != 0) { - qsExecutablePath = QString::fromWCharArray(buf); - } - CloseHandle(h); + HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, (DWORD) uiPid); + if (h) { + wchar_t buf[MAX_PATH]; + if (GetModuleFileNameEx(h, 0, buf, MAX_PATH) != 0) { + qsExecutablePath = QString::fromWCharArray(buf); } + CloseHandle(h); + } #else - qsExecutablePath = QLatin1String("Unknown"); + qsExecutablePath = QLatin1String("Unknown"); #endif - } - break; + } break; case OVERLAY_MSGTYPE_FPS: { - if (length != sizeof(OverlayMsgFps)) - break; + if (length != sizeof(OverlayMsgFps)) + break; - OverlayMsgFps *omf = & omMsg.omf; - framesPerSecond = omf->fps; - //qWarning() << "FPS: " << omf->fps; + OverlayMsgFps *omf = &omMsg.omf; + framesPerSecond = omf->fps; + // qWarning() << "FPS: " << omf->fps; - Overlay *o = static_cast<Overlay *>(parent()); - QTimer::singleShot(0, o, SLOT(updateOverlay())); - } - break; + Overlay *o = static_cast< Overlay * >(parent()); + QTimer::singleShot(0, o, SLOT(updateOverlay())); + } break; default: break; } @@ -472,7 +467,7 @@ void OverlayClient::readyRead() { } void OverlayClient::reset() { - if (! uiWidth || ! uiHeight || ! smMem) + if (!uiWidth || !uiHeight || !smMem) return; qgpiLogo.reset(); @@ -484,9 +479,9 @@ void OverlayClient::reset() { void OverlayClient::setupScene(bool show) { if (show) { - qgs.setBackgroundBrush(QColor(0,0,0,64)); + qgs.setBackgroundBrush(QColor(0, 0, 0, 64)); - if (! qgpiLogo) { + if (!qgpiLogo) { qgpiLogo.reset(new OverlayMouse()); qgpiLogo->hide(); qgpiLogo->setOpacity(0.8f); @@ -501,8 +496,8 @@ void OverlayClient::setupScene(bool show) { qgpiLogo->setPixmap(QPixmap::fromImage(qir.read())); QRectF qrf = qgpiLogo->boundingRect(); - qgpiLogo->setPos(iroundf((uiWidth - qrf.width()) / 2.0f + 0.5f), iroundf((uiHeight - qrf.height()) / 2.0f + 0.5f)); - + qgpiLogo->setPos(iroundf((uiWidth - qrf.width()) / 2.0f + 0.5f), + iroundf((uiHeight - qrf.height()) / 2.0f + 0.5f)); } qgpiCursor->show(); @@ -522,7 +517,6 @@ void OverlayClient::setupScene(bool show) { qgs.removeItem(qgpiLogo.data()); qgpiLogo->hide(); } - } ougUsers.updateUsers(); updateFPS(); @@ -540,19 +534,19 @@ void OverlayClient::setupRender() { OverlayMsg om; om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - om.omh.uiType = OVERLAY_MSGTYPE_BLIT; + om.omh.uiType = OVERLAY_MSGTYPE_BLIT; om.omh.iLength = sizeof(OverlayMsgBlit); - om.omb.x = 0; - om.omb.y = 0; - om.omb.w = uiWidth; - om.omb.h = uiHeight; + om.omb.x = 0; + om.omb.y = 0; + om.omb.w = uiWidth; + om.omb.h = uiHeight; qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + sizeof(OverlayMsgBlit)); reset(); } bool OverlayClient::update() { - if (! uiWidth || ! uiHeight || ! smMem) + if (!uiWidth || !uiHeight || !smMem) return true; ougUsers.updateUsers(); @@ -567,7 +561,7 @@ bool OverlayClient::update() { } } -void OverlayClient::changed(const QList<QRectF> ®ion) { +void OverlayClient::changed(const QList< QRectF > ®ion) { if (region.isEmpty()) return; @@ -576,10 +570,10 @@ void OverlayClient::changed(const QList<QRectF> ®ion) { } void OverlayClient::render() { - const QList<QRectF> region = qlDirty; + const QList< QRectF > region = qlDirty; qlDirty.clear(); - if (! uiWidth || ! uiHeight || ! smMem) + if (!uiWidth || !uiHeight || !smMem) return; QRect active; @@ -588,21 +582,20 @@ void OverlayClient::render() { if (region.isEmpty()) return; - foreach(const QRectF &r, region) { - dirtyf |= r; - } + foreach (const QRectF &r, region) { dirtyf |= r; } QRect dirty = dirtyf.toAlignedRect(); - dirty = dirty.intersected(QRect(0,0,uiWidth, uiHeight)); + dirty = dirty.intersected(QRect(0, 0, uiWidth, uiHeight)); if ((dirty.width() <= 0) || (dirty.height() <= 0)) return; QRect target = dirty; - target.moveTo(0,0); + target.moveTo(0, 0); - QImage img(reinterpret_cast<unsigned char *>(smMem->data()), uiWidth, uiHeight, QImage::Format_ARGB32_Premultiplied); + QImage img(reinterpret_cast< unsigned char * >(smMem->data()), uiWidth, uiHeight, + QImage::Format_ARGB32_Premultiplied); QImage qi(target.size(), QImage::Format_ARGB32_Premultiplied); qi.fill(0); @@ -622,22 +615,22 @@ void OverlayClient::render() { if (dirty.isValid()) { OverlayMsg om; om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - om.omh.uiType = OVERLAY_MSGTYPE_BLIT; + om.omh.uiType = OVERLAY_MSGTYPE_BLIT; om.omh.iLength = sizeof(OverlayMsgBlit); - om.omb.x = dirty.x(); - om.omb.y = dirty.y(); - om.omb.w = dirty.width(); - om.omb.h = dirty.height(); + om.omb.x = dirty.x(); + om.omb.y = dirty.y(); + om.omb.w = dirty.width(); + om.omb.h = dirty.height(); qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + sizeof(OverlayMsgBlit)); } if (qgpiCursor->isVisible()) { - active = QRect(0,0,uiWidth,uiHeight); + active = QRect(0, 0, uiWidth, uiHeight); } else { active = qgs.itemsBoundingRect().toAlignedRect(); if (active.isEmpty()) - active = QRect(0,0,0,0); - active = active.intersected(QRect(0,0,uiWidth,uiHeight)); + active = QRect(0, 0, 0, 0); + active = active.intersected(QRect(0, 0, uiWidth, uiHeight)); } if (active != qrLast) { @@ -645,12 +638,12 @@ void OverlayClient::render() { OverlayMsg om; om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - om.omh.uiType = OVERLAY_MSGTYPE_ACTIVE; + om.omh.uiType = OVERLAY_MSGTYPE_ACTIVE; om.omh.iLength = sizeof(OverlayMsgActive); - om.oma.x = qrLast.x(); - om.oma.y = qrLast.y(); - om.oma.w = qrLast.width(); - om.oma.h = qrLast.height(); + om.oma.x = qrLast.x(); + om.oma.y = qrLast.y(); + om.oma.w = qrLast.width(); + om.oma.h = qrLast.height(); qlsSocket->write(om.headerbuffer, sizeof(OverlayMsgHeader) + sizeof(OverlayMsgActive)); } diff --git a/src/mumble/OverlayClient.h b/src/mumble/OverlayClient.h index c4343e4e1..6d2fc62cc 100644 --- a/src/mumble/OverlayClient.h +++ b/src/mumble/OverlayClient.h @@ -10,10 +10,10 @@ #include <QtCore/QUrl> #include <QtNetwork/QLocalSocket> -#include "Timer.h" #include "../../overlay/overlay.h" -#include "SharedMemory.h" #include "OverlayUserGroup.h" +#include "SharedMemory.h" +#include "Timer.h" class ClientUser; class Overlay; @@ -22,70 +22,72 @@ class QLocalServer; class OverlayPositionableItem; class OverlayClient : public QObject { - friend class Overlay; - private: - Q_OBJECT - Q_DISABLE_COPY(OverlayClient) - protected: - OverlayMsg omMsg; - QLocalSocket *qlsSocket; - SharedMemory2 *smMem; - QRect qrLast; - Timer t; - - float framesPerSecond; - int iOffsetX, iOffsetY; - - /// The process ID of the process this OverlayClient is connected to. - quint64 uiPid; - /// The path to the executable of the process that this OverlayClient is connected to. - QString qsExecutablePath; - - QGraphicsScene qgs; - - QScopedPointer<QGraphicsPixmapItem> qgpiCursor; - QScopedPointer<QGraphicsPixmapItem> qgpiLogo; - QScopedPointer<OverlayPositionableItem> qgpiFPS; - QScopedPointer<OverlayPositionableItem> qgpiTime; - - OverlayUserGroup ougUsers; + friend class Overlay; + +private: + Q_OBJECT + Q_DISABLE_COPY(OverlayClient) +protected: + OverlayMsg omMsg; + QLocalSocket *qlsSocket; + SharedMemory2 *smMem; + QRect qrLast; + Timer t; + + float framesPerSecond; + int iOffsetX, iOffsetY; + + /// The process ID of the process this OverlayClient is connected to. + quint64 uiPid; + /// The path to the executable of the process that this OverlayClient is connected to. + QString qsExecutablePath; + + QGraphicsScene qgs; + + QScopedPointer< QGraphicsPixmapItem > qgpiCursor; + QScopedPointer< QGraphicsPixmapItem > qgpiLogo; + QScopedPointer< OverlayPositionableItem > qgpiFPS; + QScopedPointer< OverlayPositionableItem > qgpiTime; + + OverlayUserGroup ougUsers; #ifdef Q_OS_MAC - QMap<Qt::CursorShape, QPixmap> qmCursors; + QMap< Qt::CursorShape, QPixmap > qmCursors; #endif - bool bWasVisible; - bool bDelete; - - void setupRender(); - void setupScene(bool show); - - bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; - - void readyReadMsgInit(unsigned int length); - - QList<QRectF> qlDirty; - protected slots: - void readyRead(); - void changed(const QList<QRectF> &); - void render(); - public: - QGraphicsView qgv; - unsigned int uiWidth, uiHeight; - int iMouseX, iMouseY; - - OverlayClient(QLocalSocket *, QObject *); - ~OverlayClient() Q_DECL_OVERRIDE; - void reset(); - public slots: - void showGui(); - void hideGui(); - void scheduleDelete(); - void updateMouse(); - void updateFPS(); - void updateTime(); - bool update(); - void openEditor(); + bool bWasVisible; + bool bDelete; + + void setupRender(); + void setupScene(bool show); + + bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; + + void readyReadMsgInit(unsigned int length); + + QList< QRectF > qlDirty; +protected slots: + void readyRead(); + void changed(const QList< QRectF > &); + void render(); + +public: + QGraphicsView qgv; + unsigned int uiWidth, uiHeight; + int iMouseX, iMouseY; + + OverlayClient(QLocalSocket *, QObject *); + ~OverlayClient() Q_DECL_OVERRIDE; + void reset(); +public slots: + void showGui(); + void hideGui(); + void scheduleDelete(); + void updateMouse(); + void updateFPS(); + void updateTime(); + bool update(); + void openEditor(); }; #endif diff --git a/src/mumble/OverlayConfig.cpp b/src/mumble/OverlayConfig.cpp index 580a10b31..d73e3740c 100644 --- a/src/mumble/OverlayConfig.cpp +++ b/src/mumble/OverlayConfig.cpp @@ -5,25 +5,25 @@ #include "OverlayConfig.h" -#include "Overlay.h" -#include "OverlayUserGroup.h" -#include "OverlayPositionableItem.h" -#include "OverlayText.h" -#include "User.h" #include "Channel.h" -#include "Message.h" #include "Database.h" -#include "NetworkConfig.h" -#include "ServerHandler.h" #include "MainWindow.h" -#include "GlobalShortcut.h" +#include "Message.h" +#include "NetworkConfig.h" +#include "Overlay.h" +#include "OverlayPositionableItem.h" +#include "OverlayText.h" +#include "OverlayUserGroup.h" #include "PathListWidget.h" #include "Screen.h" +#include "ServerHandler.h" +#include "User.h" +#include "GlobalShortcut.h" #ifdef Q_OS_WIN -#include "../../overlay/overlay_launchers.h" -#include "../../overlay/overlay_whitelist.h" -#include "../../overlay/overlay_blacklist.h" +# include "../../overlay/overlay_blacklist.h" +# include "../../overlay/overlay_launchers.h" +# include "../../overlay/overlay_whitelist.h" #endif #include <QtGui/QScreen> @@ -33,12 +33,13 @@ #include <QtWidgets/QFileDialog> #include <QtWidgets/QFontDialog> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const QString OverlayConfig::name = QLatin1String("OverlayConfig"); -static const int OVERLAYCONFIG_PATH_ROLE = Qt::UserRole; +static const int OVERLAYCONFIG_PATH_ROLE = Qt::UserRole; static const int OVERLAYCONFIG_BUILTIN_ROLE = Qt::UserRole + 1; // Hide overlay config for Mac OS X universal builds @@ -86,11 +87,10 @@ void OverlayConfig::initDisplay() { initDisplayClock(); qgtiInstructions = new QGraphicsTextItem(); - qgtiInstructions->setHtml(QString::fromLatin1("<ul><li>%1</li><li>%2</li><li>%3</li></ul>").arg( - tr("To move the users, drag the little red dot."), - tr("To resize the users, mouse wheel over a user."), - tr("For more options, right click a user.") - )); + qgtiInstructions->setHtml(QString::fromLatin1("<ul><li>%1</li><li>%2</li><li>%3</li></ul>") + .arg(tr("To move the users, drag the little red dot."), + tr("To resize the users, mouse wheel over a user."), + tr("For more options, right click a user."))); qgtiInstructions->setOpacity(1.0f); qgtiInstructions->setZValue(-5.0f); qgtiInstructions->setDefaultTextColor(Qt::white); @@ -108,7 +108,7 @@ void OverlayConfig::initDisplay() { qgs.addItem(qgpiTimeLive); qgpiTimeLive->show(); - oug = new OverlayUserGroup(&s.os); + oug = new OverlayUserGroup(&s.os); oug->bShowExamples = true; qgs.addItem(oug); oug->show(); @@ -139,7 +139,8 @@ void OverlayConfig::refreshFpsLive() { void OverlayConfig::refreshTimeLive() { if (s.os.bTime) { - bpTimeDemo = OverlayTextLine(QString::fromLatin1("%1").arg(QTime::currentTime().toString()), s.os.qfFps).createPixmap(s.os.qcFps); + bpTimeDemo = OverlayTextLine(QString::fromLatin1("%1").arg(QTime::currentTime().toString()), s.os.qfFps) + .createPixmap(s.os.qcFps); qgpiTimeLive->setPixmap(bpTimeDemo.scaled(bpTimeDemo.size() * fViewScale)); qgpiTimeLive->setOffset((-bpTimeDemo.qpBasePoint + QPoint(0, bpTimeDemo.iAscent)) * fViewScale); } else { @@ -148,23 +149,18 @@ void OverlayConfig::refreshTimeLive() { qgpiTimeLive->setItemVisible(s.os.bTime); } -OverlayConfig::OverlayConfig(Settings &st) : - ConfigWidget(st), - qgpiScreen(nullptr), - qgs(), - qgsFpsPreview(), - qgpiFpsDemo(nullptr), - oug(nullptr), - qgtiInstructions(nullptr), - fViewScale(1.0f) { +OverlayConfig::OverlayConfig(Settings &st) + : ConfigWidget(st), qgpiScreen(nullptr), qgs(), qgsFpsPreview(), qgpiFpsDemo(nullptr), oug(nullptr), + qgtiInstructions(nullptr), fViewScale(1.0f) { setupUi(this); qlwPaths->setPathType(PathListWidget::FOLDER); - qcbOverlayExclusionMode->insertItem(static_cast<int>(OverlaySettings::LauncherFilterExclusionMode), tr("Launcher Filter")); - qcbOverlayExclusionMode->insertItem(static_cast<int>(OverlaySettings::WhitelistExclusionMode), tr("Whitelist")); - qcbOverlayExclusionMode->insertItem(static_cast<int>(OverlaySettings::BlacklistExclusionMode), tr("Blacklist")); - qcbOverlayExclusionMode->setCurrentIndex(static_cast<int>(OverlaySettings::LauncherFilterExclusionMode)); + qcbOverlayExclusionMode->insertItem(static_cast< int >(OverlaySettings::LauncherFilterExclusionMode), + tr("Launcher Filter")); + qcbOverlayExclusionMode->insertItem(static_cast< int >(OverlaySettings::WhitelistExclusionMode), tr("Whitelist")); + qcbOverlayExclusionMode->insertItem(static_cast< int >(OverlaySettings::BlacklistExclusionMode), tr("Blacklist")); + qcbOverlayExclusionMode->setCurrentIndex(static_cast< int >(OverlaySettings::LauncherFilterExclusionMode)); if (!isInstalled()) { qswOverlayPage->setCurrentWidget(qwOverlayInstall); @@ -194,7 +190,7 @@ OverlayConfig::OverlayConfig(Settings &st) : if (screen) { const QRect desktopSize = screen->geometry(); - qpScreen = QPixmap(desktopSize.width(), desktopSize.height()); + qpScreen = QPixmap(desktopSize.width(), desktopSize.height()); } else { qpScreen = QPixmap(1280, 720); } @@ -211,7 +207,8 @@ OverlayConfig::OverlayConfig(Settings &st) : } void OverlayConfig::updateOverlayExclusionModeState() { - OverlaySettings::OverlayExclusionMode exclusionMode = static_cast<OverlaySettings::OverlayExclusionMode>(qcbOverlayExclusionMode->currentIndex()); + OverlaySettings::OverlayExclusionMode exclusionMode = + static_cast< OverlaySettings::OverlayExclusionMode >(qcbOverlayExclusionMode->currentIndex()); switch (exclusionMode) { case OverlaySettings::LauncherFilterExclusionMode: @@ -238,7 +235,7 @@ void OverlayConfig::updateOverlayExclusionModeState() { // They are only considered in launcher filter mode. for (int i = 0; i < qlwWhitelist->count(); i++) { QListWidgetItem *item = qlwWhitelist->item(i); - bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); + bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); if (isBuiltin) { item->setHidden(true); } else { @@ -264,7 +261,7 @@ void OverlayConfig::load(const Settings &r) { qcbShowTime->setChecked(s.os.bTime); qgpFps->setEnabled(s.os.bEnable); - qcbOverlayExclusionMode->setCurrentIndex(static_cast<int>(s.os.oemOverlayExcludeMode)); + qcbOverlayExclusionMode->setCurrentIndex(static_cast< int >(s.os.oemOverlayExcludeMode)); // Launchers { @@ -280,7 +277,7 @@ void OverlayConfig::load(const Settings &r) { } #endif foreach (QString str, builtinLaunchers) { - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, qlwLaunchers); qlwiApplication->setData(OVERLAYCONFIG_PATH_ROLE, QVariant(str)); qlwiApplication->setData(OVERLAYCONFIG_BUILTIN_ROLE, QVariant(true)); @@ -299,11 +296,11 @@ void OverlayConfig::load(const Settings &r) { } } - foreach(QString str, s.os.qslLaunchers) { + foreach (QString str, s.os.qslLaunchers) { if (builtinLaunchers.contains(str)) { continue; } - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, qlwLaunchers); qlwiApplication->setData(OVERLAYCONFIG_PATH_ROLE, QVariant(str)); qlwiApplication->setData(OVERLAYCONFIG_BUILTIN_ROLE, QVariant(false)); @@ -324,7 +321,7 @@ void OverlayConfig::load(const Settings &r) { } #endif foreach (QString str, builtinWhitelist) { - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, qlwWhitelist); qlwiApplication->setData(OVERLAYCONFIG_PATH_ROLE, QVariant(str)); qlwiApplication->setData(OVERLAYCONFIG_BUILTIN_ROLE, QVariant(true)); @@ -343,11 +340,11 @@ void OverlayConfig::load(const Settings &r) { } } - foreach(QString str, s.os.qslWhitelist) { + foreach (QString str, s.os.qslWhitelist) { if (builtinWhitelist.contains(str)) { continue; } - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, qlwWhitelist); qlwiApplication->setData(OVERLAYCONFIG_PATH_ROLE, QVariant(str)); qlwiApplication->setData(OVERLAYCONFIG_BUILTIN_ROLE, QVariant(false)); @@ -358,7 +355,7 @@ void OverlayConfig::load(const Settings &r) { { qlwPaths->clear(); - foreach(QString str, s.os.qslPaths) { + foreach (QString str, s.os.qslPaths) { QListWidgetItem *qlwiApplication = new QListWidgetItem(QIcon(), str, qlwPaths); qlwiApplication->setData(OVERLAYCONFIG_PATH_ROLE, QVariant(str)); qlwiApplication->setData(OVERLAYCONFIG_BUILTIN_ROLE, QVariant(false)); @@ -379,7 +376,7 @@ void OverlayConfig::load(const Settings &r) { } #endif foreach (QString str, builtinBlacklist) { - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, qlwBlacklist); qlwiApplication->setData(OVERLAYCONFIG_PATH_ROLE, QVariant(str)); qlwiApplication->setData(OVERLAYCONFIG_BUILTIN_ROLE, QVariant(true)); @@ -398,11 +395,11 @@ void OverlayConfig::load(const Settings &r) { } } - foreach(QString str, s.os.qslBlacklist) { + foreach (QString str, s.os.qslBlacklist) { if (builtinBlacklist.contains(str)) { continue; } - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(str); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, qlwBlacklist); qlwiApplication->setData(OVERLAYCONFIG_PATH_ROLE, QVariant(str)); qlwiApplication->setData(OVERLAYCONFIG_BUILTIN_ROLE, QVariant(false)); @@ -428,12 +425,13 @@ QIcon OverlayConfig::icon() const { void OverlayConfig::save() const { s.os.bEnable = qcbEnable->isChecked(); - s.os.bFps = qcbShowFps->isChecked(); - s.os.bTime = qcbShowTime->isChecked(); + s.os.bFps = qcbShowFps->isChecked(); + s.os.bTime = qcbShowTime->isChecked(); // Directly save overlay config - s.os.oemOverlayExcludeMode = static_cast<OverlaySettings::OverlayExclusionMode>(qcbOverlayExclusionMode->currentIndex()); + s.os.oemOverlayExcludeMode = + static_cast< OverlaySettings::OverlayExclusionMode >(qcbOverlayExclusionMode->currentIndex()); // Launchers { @@ -567,7 +565,7 @@ void OverlayConfig::resizeScene(bool force) { qgpiScreen->setPixmap(qpScreen.scaled(sz, Qt::KeepAspectRatio, Qt::SmoothTransformation)); qgs.setSceneRect(QRectF(0, 0, qgpiScreen->pixmap().width(), qgpiScreen->pixmap().height())); - fViewScale = static_cast<float>(qgpiScreen->pixmap().height()) / static_cast<float>(qpScreen.height()); + fViewScale = static_cast< float >(qgpiScreen->pixmap().height()) / static_cast< float >(qpScreen.height()); refreshFpsLive(); refreshTimeLive(); @@ -587,14 +585,14 @@ void OverlayConfig::resizeScene(bool force) { } void OverlayConfig::on_qlwLaunchers_itemSelectionChanged() { - QList<QListWidgetItem *> items = qlwLaunchers->selectedItems(); + QList< QListWidgetItem * > items = qlwLaunchers->selectedItems(); if (items.isEmpty()) { qpbLaunchersRemove->setEnabled(false); return; } QListWidgetItem *item = items.at(0); - bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); + bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); if (isBuiltin) { qpbLaunchersRemove->setEnabled(false); @@ -616,13 +614,13 @@ void OverlayConfig::on_qpbLaunchersAdd_clicked() { QString file = QString(); #endif - if (! file.isEmpty()) { + if (!file.isEmpty()) { QString qsAppIdentifier = OverlayAppInfo::applicationIdentifierForPath(file); QStringList qslIdentifiers; for (int i = 0; i < qlwLaunchers->count(); i++) qslIdentifiers << qlwLaunchers->item(i)->data(Qt::UserRole).toString(); - if (! qslIdentifiers.contains(qsAppIdentifier)) { - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier); + if (!qslIdentifiers.contains(qsAppIdentifier)) { + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, qlwLaunchers); qlwiApplication->setData(Qt::UserRole, QVariant(qsAppIdentifier)); qlwLaunchers->setCurrentItem(qlwiApplication); @@ -637,14 +635,14 @@ void OverlayConfig::on_qpbLaunchersRemove_clicked() { } void OverlayConfig::on_qlwWhitelist_itemSelectionChanged() { - QList<QListWidgetItem *> items = qlwWhitelist->selectedItems(); + QList< QListWidgetItem * > items = qlwWhitelist->selectedItems(); if (items.isEmpty()) { qpbWhitelistRemove->setEnabled(false); return; } QListWidgetItem *item = items.at(0); - bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); + bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); if (isBuiltin) { qpbWhitelistRemove->setEnabled(false); @@ -655,12 +653,12 @@ void OverlayConfig::on_qlwWhitelist_itemSelectionChanged() { void OverlayConfig::addWhitelistPath(const QString &path) { QString qsAppIdentifier = OverlayAppInfo::applicationIdentifierForPath(path); - QListWidget *sel = qlwWhitelist; + QListWidget *sel = qlwWhitelist; QStringList qslIdentifiers; for (int i = 0; i < sel->count(); i++) qslIdentifiers << sel->item(i)->data(Qt::UserRole).toString(); - if (! qslIdentifiers.contains(qsAppIdentifier)) { - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier); + if (!qslIdentifiers.contains(qsAppIdentifier)) { + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, sel); qlwiApplication->setData(Qt::UserRole, QVariant(qsAppIdentifier)); sel->setCurrentItem(qlwiApplication); @@ -676,27 +674,27 @@ void OverlayConfig::on_qpbWhitelistAdd_clicked() { QString file = QString(); #endif - if (! file.isEmpty()) { + if (!file.isEmpty()) { addWhitelistPath(file); } } void OverlayConfig::on_qpbWhitelistRemove_clicked() { QListWidget *sel = qlwWhitelist; - int row = sel->currentRow(); + int row = sel->currentRow(); if (row != -1) delete sel->takeItem(row); } void OverlayConfig::on_qlwPaths_itemSelectionChanged() { - QList<QListWidgetItem *> items = qlwPaths->selectedItems(); + QList< QListWidgetItem * > items = qlwPaths->selectedItems(); if (items.isEmpty()) { qpbPathsRemove->setEnabled(false); return; } QListWidgetItem *item = items.at(0); - bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); + bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); if (isBuiltin) { qpbPathsRemove->setEnabled(false); @@ -707,13 +705,13 @@ void OverlayConfig::on_qlwPaths_itemSelectionChanged() { void OverlayConfig::on_qpbPathsAdd_clicked() { QString existingPath = QFileDialog::getExistingDirectory(this, tr("Choose path")); - QString dir = QDir::toNativeSeparators(existingPath); + QString dir = QDir::toNativeSeparators(existingPath); QListWidget *sel = qlwPaths; QStringList qslIdentifiers; for (int i = 0; i < sel->count(); i++) qslIdentifiers << sel->item(i)->data(Qt::UserRole).toString(); - if (! dir.isEmpty() && ! qslIdentifiers.contains(dir)) { + if (!dir.isEmpty() && !qslIdentifiers.contains(dir)) { QListWidgetItem *qlwiPath = new QListWidgetItem(QIcon(), dir, sel); qlwiPath->setData(Qt::UserRole, QVariant(dir)); sel->setCurrentItem(qlwiPath); @@ -727,14 +725,14 @@ void OverlayConfig::on_qpbPathsRemove_clicked() { } void OverlayConfig::on_qlwBlacklist_itemSelectionChanged() { - QList<QListWidgetItem *> items = qlwBlacklist->selectedItems(); + QList< QListWidgetItem * > items = qlwBlacklist->selectedItems(); if (items.isEmpty()) { qpbBlacklistRemove->setEnabled(false); return; } QListWidgetItem *item = items.at(0); - bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); + bool isBuiltin = item->data(OVERLAYCONFIG_BUILTIN_ROLE).toBool(); if (isBuiltin) { qpbBlacklistRemove->setEnabled(false); @@ -752,14 +750,14 @@ void OverlayConfig::on_qpbBlacklistAdd_clicked() { QString file = QString(); #endif - if (! file.isEmpty()) { + if (!file.isEmpty()) { QString qsAppIdentifier = OverlayAppInfo::applicationIdentifierForPath(file); - QListWidget *sel = qlwBlacklist; + QListWidget *sel = qlwBlacklist; QStringList qslIdentifiers; for (int i = 0; i < sel->count(); i++) qslIdentifiers << sel->item(i)->data(Qt::UserRole).toString(); - if (! qslIdentifiers.contains(qsAppIdentifier)) { - OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier); + if (!qslIdentifiers.contains(qsAppIdentifier)) { + OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier); QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, sel); qlwiApplication->setData(Qt::UserRole, QVariant(qsAppIdentifier)); sel->setCurrentItem(qlwiApplication); @@ -769,7 +767,7 @@ void OverlayConfig::on_qpbBlacklistAdd_clicked() { void OverlayConfig::on_qpbBlacklistRemove_clicked() { QListWidget *sel = qlwBlacklist; - int row = sel->currentRow(); + int row = sel->currentRow(); if (row != -1) delete sel->takeItem(row); } @@ -789,7 +787,6 @@ void OverlayConfig::on_qpbInstall_clicked() { } void OverlayConfig::on_qpbUninstall_clicked() { - qpbUninstall->setEnabled(false); if (uninstallFiles()) { @@ -837,10 +834,8 @@ void OverlayConfig::on_qpbFpsColor_clicked() { } void OverlayConfig::on_qpbLoadPreset_clicked() { - QString fn = QFileDialog::getOpenFileName(this, - tr("Load Overlay Presets"), - QDir::homePath(), - tr("Mumble overlay presets (*.mumblelay)")); + QString fn = QFileDialog::getOpenFileName(this, tr("Load Overlay Presets"), QDir::homePath(), + tr("Mumble overlay presets (*.mumblelay)")); if (fn.isEmpty()) { return; @@ -854,29 +849,27 @@ void OverlayConfig::on_qpbLoadPreset_clicked() { qs.endGroup(); #ifdef Q_OS_WIN - load_preset.qslLaunchers = s.os.qslLaunchers; + load_preset.qslLaunchers = s.os.qslLaunchers; load_preset.qslLaunchersExclude = s.os.qslLaunchersExclude; - load_preset.qslWhitelist = s.os.qslWhitelist; + load_preset.qslWhitelist = s.os.qslWhitelist; load_preset.qslWhitelistExclude = s.os.qslWhitelistExclude; - load_preset.qslPaths = s.os.qslPaths; + load_preset.qslPaths = s.os.qslPaths; load_preset.qslPathsExclude = s.os.qslPathsExclude; - load_preset.qslBlacklist = s.os.qslBlacklist; + load_preset.qslBlacklist = s.os.qslBlacklist; load_preset.qslBlacklistExclude = s.os.qslBlacklistExclude; #endif load_preset.bEnable = s.os.bEnable; - s.os = load_preset; + s.os = load_preset; load(s); } void OverlayConfig::on_qpbSavePreset_clicked() { - QString fn = QFileDialog::getSaveFileName(this, - tr("Save Overlay Presets"), - QDir::homePath(), - tr("Mumble overlay presets (*.mumblelay)")); + QString fn = QFileDialog::getSaveFileName(this, tr("Save Overlay Presets"), QDir::homePath(), + tr("Mumble overlay presets (*.mumblelay)")); if (fn.isEmpty()) { return; diff --git a/src/mumble/OverlayConfig.h b/src/mumble/OverlayConfig.h index 6deedd116..0f6ca7247 100644 --- a/src/mumble/OverlayConfig.h +++ b/src/mumble/OverlayConfig.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MUMBLE_OVERLAYCONFIG_H_ #define MUMBLE_MUMBLE_OVERLAYCONFIG_H_ -#include "OverlayText.h" #include "ConfigWidget.h" +#include "OverlayText.h" #include "ui_Overlay.h" @@ -16,86 +16,87 @@ struct OverlayAppInfo; class OverlayPositionableItem; class OverlayConfig : public ConfigWidget, public Ui::OverlayConfig { - private: - Q_OBJECT - Q_DISABLE_COPY(OverlayConfig) - - void initDisplay(); - void initDisplayFps(); - void initDisplayClock(); - void refreshFpsDemo(); - void refreshFpsLive(); - void refreshTimeLive(); - void addWhitelistPath(const QString & path); - protected: - QPixmap qpScreen; - QGraphicsPixmapItem *qgpiScreen; - QGraphicsScene qgs; - QGraphicsScene qgsFpsPreview; - BasepointPixmap bpFpsDemo; - BasepointPixmap bpTimeDemo; - QGraphicsPixmapItem *qgpiFpsDemo; - OverlayPositionableItem *qgpiFpsLive; - OverlayPositionableItem *qgpiTimeLive; - OverlayUserGroup *oug; - QGraphicsTextItem *qgtiInstructions; - - float fViewScale; - - bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; - - bool supportsInstallableOverlay(); - bool isInstalled(); - bool needsUpgrade(); - bool installFiles(); - bool uninstallFiles(); - bool supportsCertificates(); - bool installerIsValid(); - void showCertificates(); - - void updateOverlayExclusionModeState(); - protected slots: - void on_qpbInstall_clicked(); - void on_qpbUninstall_clicked(); - - void on_qcbOverlayExclusionMode_currentIndexChanged(int); - - void on_qlwLaunchers_itemSelectionChanged(); - void on_qpbLaunchersAdd_clicked(); - void on_qpbLaunchersRemove_clicked(); - - void on_qlwWhitelist_itemSelectionChanged(); - void on_qpbWhitelistAdd_clicked(); - void on_qpbWhitelistRemove_clicked(); - - void on_qlwPaths_itemSelectionChanged(); - void on_qpbPathsAdd_clicked(); - void on_qpbPathsRemove_clicked(); - - void on_qlwBlacklist_itemSelectionChanged(); - void on_qpbBlacklistAdd_clicked(); - void on_qpbBlacklistRemove_clicked(); - - void on_qcbEnable_stateChanged(int); - void on_qcbShowFps_stateChanged(int); - void on_qcbShowTime_stateChanged(int); - void on_qpbFpsFont_clicked(); - void on_qpbFpsColor_clicked(); - void on_qpbLoadPreset_clicked(); - void on_qpbSavePreset_clicked(); - void resizeScene(bool force=false); - - public: - /// The uniqe name of this ConfigWidget - static const QString name; - OverlayConfig(Settings &st); - virtual QString title() const Q_DECL_OVERRIDE; - virtual const QString &getName() const Q_DECL_OVERRIDE; - virtual QIcon icon() const Q_DECL_OVERRIDE; - public slots: - void accept() const Q_DECL_OVERRIDE; - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(OverlayConfig) + + void initDisplay(); + void initDisplayFps(); + void initDisplayClock(); + void refreshFpsDemo(); + void refreshFpsLive(); + void refreshTimeLive(); + void addWhitelistPath(const QString &path); + +protected: + QPixmap qpScreen; + QGraphicsPixmapItem *qgpiScreen; + QGraphicsScene qgs; + QGraphicsScene qgsFpsPreview; + BasepointPixmap bpFpsDemo; + BasepointPixmap bpTimeDemo; + QGraphicsPixmapItem *qgpiFpsDemo; + OverlayPositionableItem *qgpiFpsLive; + OverlayPositionableItem *qgpiTimeLive; + OverlayUserGroup *oug; + QGraphicsTextItem *qgtiInstructions; + + float fViewScale; + + bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; + + bool supportsInstallableOverlay(); + bool isInstalled(); + bool needsUpgrade(); + bool installFiles(); + bool uninstallFiles(); + bool supportsCertificates(); + bool installerIsValid(); + void showCertificates(); + + void updateOverlayExclusionModeState(); +protected slots: + void on_qpbInstall_clicked(); + void on_qpbUninstall_clicked(); + + void on_qcbOverlayExclusionMode_currentIndexChanged(int); + + void on_qlwLaunchers_itemSelectionChanged(); + void on_qpbLaunchersAdd_clicked(); + void on_qpbLaunchersRemove_clicked(); + + void on_qlwWhitelist_itemSelectionChanged(); + void on_qpbWhitelistAdd_clicked(); + void on_qpbWhitelistRemove_clicked(); + + void on_qlwPaths_itemSelectionChanged(); + void on_qpbPathsAdd_clicked(); + void on_qpbPathsRemove_clicked(); + + void on_qlwBlacklist_itemSelectionChanged(); + void on_qpbBlacklistAdd_clicked(); + void on_qpbBlacklistRemove_clicked(); + + void on_qcbEnable_stateChanged(int); + void on_qcbShowFps_stateChanged(int); + void on_qcbShowTime_stateChanged(int); + void on_qpbFpsFont_clicked(); + void on_qpbFpsColor_clicked(); + void on_qpbLoadPreset_clicked(); + void on_qpbSavePreset_clicked(); + void resizeScene(bool force = false); + +public: + /// The uniqe name of this ConfigWidget + static const QString name; + OverlayConfig(Settings &st); + virtual QString title() const Q_DECL_OVERRIDE; + virtual const QString &getName() const Q_DECL_OVERRIDE; + virtual QIcon icon() const Q_DECL_OVERRIDE; +public slots: + void accept() const Q_DECL_OVERRIDE; + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/OverlayEditor.cpp b/src/mumble/OverlayEditor.cpp index 9fd3a8eed..a47b42444 100644 --- a/src/mumble/OverlayEditor.cpp +++ b/src/mumble/OverlayEditor.cpp @@ -5,27 +5,26 @@ #include "OverlayEditor.h" -#include "OverlayClient.h" -#include "OverlayText.h" -#include "User.h" #include "Channel.h" -#include "Message.h" #include "Database.h" +#include "MainWindow.h" +#include "Message.h" #include "NetworkConfig.h" +#include "OverlayClient.h" +#include "OverlayText.h" #include "ServerHandler.h" -#include "MainWindow.h" -#include "GlobalShortcut.h" +#include "User.h" #include "Utils.h" +#include "GlobalShortcut.h" #include <QtWidgets/QGraphicsProxyWidget> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -OverlayEditor::OverlayEditor(QWidget *p, QGraphicsItem *qgi, OverlaySettings *osptr) : - QDialog(p), - qgiPromote(qgi), - oes(g.s.os) { +OverlayEditor::OverlayEditor(QWidget *p, QGraphicsItem *qgi, OverlaySettings *osptr) + : QDialog(p), qgiPromote(qgi), oes(g.s.os) { setupUi(this); qsZoom->setAccessibleName(tr("Zoom level")); os = osptr ? osptr : &g.s.os; @@ -37,10 +36,10 @@ OverlayEditor::OverlayEditor(QWidget *p, QGraphicsItem *qgi, OverlaySettings *os if (qgpw) { qgpw->setFlag(QGraphicsItem::ItemIgnoresParentOpacity); if (g.ocIntercept) { - qgpw->setPos(iroundf(static_cast<float>(g.ocIntercept->uiWidth) / 16.0f + 0.5f), - iroundf(static_cast<float>(g.ocIntercept->uiHeight) / 16.0f + 0.5f)); - qgpw->resize(iroundf(static_cast<float>(g.ocIntercept->uiWidth) * 14.0f / 16.0f + 0.5f), - iroundf(static_cast<float>(g.ocIntercept->uiHeight) * 14.0f / 16.0f + 0.5f)); + qgpw->setPos(iroundf(static_cast< float >(g.ocIntercept->uiWidth) / 16.0f + 0.5f), + iroundf(static_cast< float >(g.ocIntercept->uiHeight) / 16.0f + 0.5f)); + qgpw->resize(iroundf(static_cast< float >(g.ocIntercept->uiWidth) * 14.0f / 16.0f + 0.5f), + iroundf(static_cast< float >(g.ocIntercept->uiHeight) * 14.0f / 16.0f + 0.5f)); } } @@ -130,7 +129,7 @@ void OverlayEditor::on_qrbShout_clicked() { void OverlayEditor::on_qcbAvatar_clicked() { oes.os.bAvatar = qcbAvatar->isChecked(); - if (! oes.os.bAvatar && ! oes.os.bUserName) { + if (!oes.os.bAvatar && !oes.os.bUserName) { qcbUser->setChecked(true); oes.os.bUserName = true; oes.updateUserName(); @@ -140,7 +139,7 @@ void OverlayEditor::on_qcbAvatar_clicked() { void OverlayEditor::on_qcbUser_clicked() { oes.os.bUserName = qcbUser->isChecked(); - if (! oes.os.bAvatar && ! oes.os.bUserName) { + if (!oes.os.bAvatar && !oes.os.bUserName) { qcbAvatar->setChecked(true); oes.os.bAvatar = true; oes.updateAvatar(); diff --git a/src/mumble/OverlayEditor.h b/src/mumble/OverlayEditor.h index 7f5861fbf..ce7f460c9 100644 --- a/src/mumble/OverlayEditor.h +++ b/src/mumble/OverlayEditor.h @@ -12,38 +12,39 @@ struct OverlaySettings; class OverlayEditor : public QDialog, public Ui::OverlayEditor { - private: - Q_OBJECT - Q_DISABLE_COPY(OverlayEditor) - protected: - QGraphicsItem *qgiPromote; - OverlayEditorScene oes; - OverlaySettings *os; - - void enterEvent(QEvent *e) Q_DECL_OVERRIDE; - void leaveEvent(QEvent *e) Q_DECL_OVERRIDE; - public: - OverlayEditor(QWidget *p = nullptr, QGraphicsItem *qgi = nullptr, OverlaySettings *osptr = nullptr); - ~OverlayEditor() Q_DECL_OVERRIDE; - signals: - void applySettings(); - public slots: - void reset(); - void apply(); - void accept() Q_DECL_OVERRIDE; - - void on_qrbPassive_clicked(); - void on_qrbTalking_clicked(); - void on_qrbWhisper_clicked(); - void on_qrbShout_clicked(); - - void on_qcbAvatar_clicked(); - void on_qcbUser_clicked(); - void on_qcbChannel_clicked(); - void on_qcbMutedDeafened_clicked(); - void on_qcbBox_clicked(); - - void on_qsZoom_valueChanged(int); +private: + Q_OBJECT + Q_DISABLE_COPY(OverlayEditor) +protected: + QGraphicsItem *qgiPromote; + OverlayEditorScene oes; + OverlaySettings *os; + + void enterEvent(QEvent *e) Q_DECL_OVERRIDE; + void leaveEvent(QEvent *e) Q_DECL_OVERRIDE; + +public: + OverlayEditor(QWidget *p = nullptr, QGraphicsItem *qgi = nullptr, OverlaySettings *osptr = nullptr); + ~OverlayEditor() Q_DECL_OVERRIDE; +signals: + void applySettings(); +public slots: + void reset(); + void apply(); + void accept() Q_DECL_OVERRIDE; + + void on_qrbPassive_clicked(); + void on_qrbTalking_clicked(); + void on_qrbWhisper_clicked(); + void on_qrbShout_clicked(); + + void on_qcbAvatar_clicked(); + void on_qcbUser_clicked(); + void on_qcbChannel_clicked(); + void on_qcbMutedDeafened_clicked(); + void on_qcbBox_clicked(); + + void on_qsZoom_valueChanged(int); }; #endif diff --git a/src/mumble/OverlayEditorScene.cpp b/src/mumble/OverlayEditorScene.cpp index b0007d92b..49413a505 100644 --- a/src/mumble/OverlayEditorScene.cpp +++ b/src/mumble/OverlayEditorScene.cpp @@ -5,18 +5,18 @@ #include "OverlayEditorScene.h" -#include "OverlayClient.h" -#include "OverlayUser.h" -#include "OverlayText.h" -#include "User.h" #include "Channel.h" -#include "Message.h" #include "Database.h" +#include "MainWindow.h" +#include "Message.h" #include "NetworkConfig.h" +#include "OverlayClient.h" +#include "OverlayText.h" +#include "OverlayUser.h" #include "ServerHandler.h" -#include "MainWindow.h" -#include "GlobalShortcut.h" +#include "User.h" #include "Utils.h" +#include "GlobalShortcut.h" #include <QtGui/QImageReader> #include <QtWidgets/QColorDialog> @@ -24,12 +24,13 @@ #include <QtWidgets/QGraphicsProxyWidget> #include <QtWidgets/QGraphicsSceneMouseEvent> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" OverlayEditorScene::OverlayEditorScene(const OverlaySettings &srcos, QObject *p) : QGraphicsScene(p), os(srcos) { tsColor = Settings::Talking; - uiZoom = 2; + uiZoom = 2; if (g.ocIntercept) uiSize = g.ocIntercept->uiHeight; @@ -78,7 +79,8 @@ OverlayEditorScene::OverlayEditorScene(const OverlaySettings &srcos, QObject *p) resync(); } -#define SCALESIZE(var) iroundf(uiSize * uiZoom * os.qrf##var .width() + 0.5f), iroundf(uiSize * uiZoom * os.qrf##var .height() + 0.5f) +#define SCALESIZE(var) \ + iroundf(uiSize *uiZoom *os.qrf##var.width() + 0.5f), iroundf(uiSize *uiZoom *os.qrf##var.height() + 0.5f) void OverlayEditorScene::updateMuted() { QImageReader qir(QLatin1String("skin:muted_self.svg")); @@ -92,7 +94,8 @@ void OverlayEditorScene::updateMuted() { void OverlayEditorScene::moveMuted() { qgpiMuted->setVisible(os.bMutedDeafened); - qgpiMuted->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfMutedDeafened, uiSize * uiZoom), qgpiMuted->boundingRect(), os.qaMutedDeafened)); + qgpiMuted->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfMutedDeafened, uiSize * uiZoom), + qgpiMuted->boundingRect(), os.qaMutedDeafened)); qgpiMuted->setOpacity(os.fMutedDeafened); } @@ -117,7 +120,8 @@ void OverlayEditorScene::updateUserName() { break; } - const QPixmap &pm = OverlayTextLine(qsName, os.qfUserName).createPixmap(SCALESIZE(UserName), os.qcUserName[tsColor]); + const QPixmap &pm = + OverlayTextLine(qsName, os.qfUserName).createPixmap(SCALESIZE(UserName), os.qcUserName[tsColor]); qgpiName->setPixmap(pm); moveUserName(); @@ -125,12 +129,14 @@ void OverlayEditorScene::updateUserName() { void OverlayEditorScene::moveUserName() { qgpiName->setVisible(os.bUserName); - qgpiName->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfUserName, uiSize * uiZoom), qgpiName->boundingRect(), os.qaUserName)); + qgpiName->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfUserName, uiSize * uiZoom), + qgpiName->boundingRect(), os.qaUserName)); qgpiName->setOpacity(os.fUserName); } void OverlayEditorScene::updateChannel() { - const QPixmap &pm = OverlayTextLine(Overlay::tr("Channel"), os.qfChannel).createPixmap(SCALESIZE(Channel), os.qcChannel); + const QPixmap &pm = + OverlayTextLine(Overlay::tr("Channel"), os.qfChannel).createPixmap(SCALESIZE(Channel), os.qcChannel); qgpiChannel->setPixmap(pm); moveChannel(); @@ -138,7 +144,8 @@ void OverlayEditorScene::updateChannel() { void OverlayEditorScene::moveChannel() { qgpiChannel->setVisible(os.bChannel); - qgpiChannel->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfChannel, uiSize * uiZoom), qgpiChannel->boundingRect(), os.qaChannel)); + qgpiChannel->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfChannel, uiSize * uiZoom), + qgpiChannel->boundingRect(), os.qaChannel)); qgpiChannel->setOpacity(os.fChannel); } @@ -156,23 +163,27 @@ void OverlayEditorScene::updateAvatar() { void OverlayEditorScene::moveAvatar() { qgpiAvatar->setVisible(os.bAvatar); - qgpiAvatar->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfAvatar, uiSize * uiZoom), qgpiAvatar->boundingRect(), os.qaAvatar)); + qgpiAvatar->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfAvatar, uiSize * uiZoom), + qgpiAvatar->boundingRect(), os.qaAvatar)); qgpiAvatar->setOpacity(os.fAvatar); } void OverlayEditorScene::moveBox() { QRectF childrenBounds = os.qrfAvatar | os.qrfChannel | os.qrfMutedDeafened | os.qrfUserName; - bool haspen = (os.qcBoxPen != os.qcBoxFill) && (! qFuzzyCompare(os.qcBoxPen.alphaF(), static_cast<qreal>(0.0f))); - qreal pw = haspen ? qMax<qreal>(1.0f, os.fBoxPenWidth * uiSize * uiZoom) : 0.0f; - qreal pad = os.fBoxPad * uiSize * uiZoom; + bool haspen = (os.qcBoxPen != os.qcBoxFill) && (!qFuzzyCompare(os.qcBoxPen.alphaF(), static_cast< qreal >(0.0f))); + qreal pw = haspen ? qMax< qreal >(1.0f, os.fBoxPenWidth * uiSize * uiZoom) : 0.0f; + qreal pad = os.fBoxPad * uiSize * uiZoom; QPainterPath pp; - pp.addRoundedRect(childrenBounds.x() * uiSize * uiZoom + -pw / 2.0f - pad, childrenBounds.y() * uiSize * uiZoom + -pw / 2.0f - pad, childrenBounds.width() * uiSize * uiZoom + pw + 2.0f * pad, childrenBounds.height() * uiSize * uiZoom + pw + 2.0f * pad, 2.0f * pw, 2.0f * pw); + pp.addRoundedRect(childrenBounds.x() * uiSize * uiZoom + -pw / 2.0f - pad, + childrenBounds.y() * uiSize * uiZoom + -pw / 2.0f - pad, + childrenBounds.width() * uiSize * uiZoom + pw + 2.0f * pad, + childrenBounds.height() * uiSize * uiZoom + pw + 2.0f * pad, 2.0f * pw, 2.0f * pw); qgpiBox->setPath(pp); qgpiBox->setPos(0.0f, 0.0f); qgpiBox->setPen(haspen ? QPen(os.qcBoxPen, pw) : Qt::NoPen); - qgpiBox->setBrush(qFuzzyCompare(os.qcBoxFill.alphaF(), static_cast<qreal>(0.0f)) ? Qt::NoBrush : os.qcBoxFill); + qgpiBox->setBrush(qFuzzyCompare(os.qcBoxFill.alphaF(), static_cast< qreal >(0.0f)) ? Qt::NoBrush : os.qcBoxFill); qgpiBox->setOpacity(1.0f); qgpiBox->setVisible(os.bBox); @@ -220,14 +231,14 @@ void OverlayEditorScene::drawBackground(QPainter *p, const QRectF &rect) { p->setBrushOrigin(0, 0); p->fillRect(rect, backgroundBrush()); - QRectF upscaled = OverlayUser::scaledRect(rect, 128.f / static_cast<float>(uiSize * uiZoom)); + QRectF upscaled = OverlayUser::scaledRect(rect, 128.f / static_cast< float >(uiSize * uiZoom)); { int min = iroundf(upscaled.left()); int max = iroundf(ceil(upscaled.right())); - for (int i=min;i<=max;++i) { - qreal v = (i / 128) * static_cast<qreal>(uiSize * uiZoom); + for (int i = min; i <= max; ++i) { + qreal v = (i / 128) * static_cast< qreal >(uiSize * uiZoom); if (i != 0) p->setPen(QPen(QColor(128, 128, 128, 255), 0.0f)); @@ -242,8 +253,8 @@ void OverlayEditorScene::drawBackground(QPainter *p, const QRectF &rect) { int min = iroundf(upscaled.top()); int max = iroundf(ceil(upscaled.bottom())); - for (int i=min;i<=max;++i) { - qreal v = (i / 128) * static_cast<qreal>(uiSize * uiZoom); + for (int i = min; i <= max; ++i) { + qreal v = (i / 128) * static_cast< qreal >(uiSize * uiZoom); if (i != 0) p->setPen(QPen(QColor(128, 128, 128, 255), 0.0f)); @@ -264,8 +275,8 @@ QGraphicsPixmapItem *OverlayEditorScene::childAt(const QPointF &pos) { } } - foreach(QGraphicsItem *qgi, items(Qt::AscendingOrder)) { - if (!qgi->isVisible() || ! qgraphicsitem_cast<QGraphicsPixmapItem *>(qgi)) + foreach (QGraphicsItem *qgi, items(Qt::AscendingOrder)) { + if (!qgi->isVisible() || !qgraphicsitem_cast< QGraphicsPixmapItem * >(qgi)) continue; QPointF qp = pos - qgi->pos(); @@ -273,22 +284,22 @@ QGraphicsPixmapItem *OverlayEditorScene::childAt(const QPointF &pos) { item = qgi; } } - return static_cast<QGraphicsPixmapItem *>(item); + return static_cast< QGraphicsPixmapItem * >(item); } QRectF OverlayEditorScene::selectedRect() const { const QRectF *qrf = nullptr; if (qgpiSelected == qgpiMuted) - qrf = & os.qrfMutedDeafened; + qrf = &os.qrfMutedDeafened; else if (qgpiSelected == qgpiAvatar) - qrf = & os.qrfAvatar; + qrf = &os.qrfAvatar; else if (qgpiSelected == qgpiChannel) - qrf = & os.qrfChannel; + qrf = &os.qrfChannel; else if (qgpiSelected == qgpiName) - qrf = & os.qrfUserName; + qrf = &os.qrfUserName; - if (! qrf) + if (!qrf) return QRectF(); return OverlayUser::scaledRect(*qrf, uiSize * uiZoom).toAlignedRect(); @@ -329,11 +340,12 @@ void OverlayEditorScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) { QRectF rect = qgriSelected->rect(); - if (! qgpiSelected || (rect == selectedRect())) { + if (!qgpiSelected || (rect == selectedRect())) { return; } - QRectF scaled(rect.x() / (uiSize * uiZoom), rect.y() / (uiSize * uiZoom), rect.width() / (uiSize * uiZoom), rect.height() / (uiSize * uiZoom)); + QRectF scaled(rect.x() / (uiSize * uiZoom), rect.y() / (uiSize * uiZoom), rect.width() / (uiSize * uiZoom), + rect.height() / (uiSize * uiZoom)); if (qgpiSelected == qgpiMuted) { os.qrfMutedDeafened = scaled; @@ -462,7 +474,7 @@ void OverlayEditorScene::mouseMoveEvent(QGraphicsSceneMouseEvent *e) { } void OverlayEditorScene::updateCursorShape(const QPointF &point) { - Qt::CursorShape cs; + Qt::CursorShape cs; if (qgriSelected->isVisible()) { wfsHover = rectSection(qgriSelected->rect(), point); @@ -496,7 +508,7 @@ void OverlayEditorScene::updateCursorShape(const QPointF &point) { } - foreach(QGraphicsView *v, views()) { + foreach (QGraphicsView *v, views()) { if (v->viewport()->cursor().shape() != cs) { v->viewport()->setCursor(cs); @@ -520,21 +532,21 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { if (e->isAccepted()) return; - if (! e->widget()) + if (!e->widget()) return; QGraphicsPixmapItem *item = childAt(e->scenePos()); QMenu qm(e->widget()); - QMenu *qmLayout = qm.addMenu(tr("Layout preset")); + QMenu *qmLayout = qm.addMenu(tr("Layout preset")); QAction *qaLayoutLargeAvatar = qmLayout->addAction(tr("Large square avatar")); - QAction *qaLayoutText = qmLayout->addAction(tr("Avatar and Name")); + QAction *qaLayoutText = qmLayout->addAction(tr("Avatar and Name")); - QMenu *qmTrans = qm.addMenu(tr("User Opacity")); + QMenu *qmTrans = qm.addMenu(tr("User Opacity")); QActionGroup *qagUser = new QActionGroup(&qm); QAction *userOpacity[8]; - for (int i=0;i<8;++i) { + for (int i = 0; i < 8; ++i) { qreal o = (i + 1) / 8.0; userOpacity[i] = new QAction(tr("%1%").arg(o * 100.0f, 0, 'f', 1), qagUser); @@ -547,25 +559,25 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { qmTrans->addAction(userOpacity[i]); } - QAction *color = nullptr; + QAction *color = nullptr; QAction *fontAction = nullptr; QAction *objectOpacity[8]; - for (int i=0;i<8;++i) + for (int i = 0; i < 8; ++i) objectOpacity[i] = nullptr; - QAction *boxpen[4] = { nullptr, nullptr, nullptr, nullptr}; - QAction *boxpad[4] = { nullptr, nullptr, nullptr, nullptr}; - QAction *boxpencolor = nullptr; + QAction *boxpen[4] = { nullptr, nullptr, nullptr, nullptr }; + QAction *boxpad[4] = { nullptr, nullptr, nullptr, nullptr }; + QAction *boxpencolor = nullptr; QAction *boxfillcolor = nullptr; QAction *align[6]; - for (int i=0;i<6;++i) + for (int i = 0; i < 6; ++i) align[i] = nullptr; if (item) { qm.addSeparator(); - QMenu *qmObjTrans = qm.addMenu(tr("Object Opacity")); + QMenu *qmObjTrans = qm.addMenu(tr("Object Opacity")); QActionGroup *qagObject = new QActionGroup(&qm); - for (int i=0;i<8;++i) { + for (int i = 0; i < 8; ++i) { qreal o = (i + 1) / 8.0; objectOpacity[i] = new QAction(tr("%1%").arg(o * 100.0f, 0, 'f', 1), qagObject); @@ -622,7 +634,7 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { align[5]->setChecked(true); if ((item != qgpiAvatar) && (item != qgpiMuted)) { - color = qm.addAction(tr("Color...")); + color = qm.addAction(tr("Color...")); fontAction = qm.addAction(tr("Font...")); } } @@ -632,13 +644,13 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { QMenu *qmBox = qm.addMenu(tr("Bounding box")); QMenu *qmPen = qmBox->addMenu(tr("Pen width")); QMenu *qmPad = qmBox->addMenu(tr("Padding")); - boxpencolor = qmBox->addAction(tr("Pen color")); + boxpencolor = qmBox->addAction(tr("Pen color")); boxfillcolor = qmBox->addAction(tr("Fill color")); QActionGroup *qagPen = new QActionGroup(qmPen); QActionGroup *qagPad = new QActionGroup(qmPad); - for (int i=0;i<4;++i) { - qreal v = (i) ? powf(2.0f, static_cast<float>(-10 + i)) : 0.0f; + for (int i = 0; i < 4; ++i) { + qreal v = (i) ? powf(2.0f, static_cast< float >(-10 + i)) : 0.0f; boxpen[i] = new QAction(QString::number(i), qagPen); boxpen[i]->setData(v); boxpen[i]->setCheckable(true); @@ -657,19 +669,19 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { QAction *act = qm.exec(e->screenPos()); - if (! act) + if (!act) return; - for (int i=0;i<8;++i) { + for (int i = 0; i < 8; ++i) { if (userOpacity[i] == act) { - float o = static_cast<float>(act->data().toReal()); + float o = static_cast< float >(act->data().toReal()); os.fUser[tsColor] = o; qgiGroup->setOpacity(o); } } - for (int i=0;i<8;++i) { + for (int i = 0; i < 8; ++i) { if (objectOpacity[i] == act) { qreal o = act->data().toReal(); @@ -686,7 +698,7 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { } } - for (int i=0;i<4;++i) { + for (int i = 0; i < 4; ++i) { if (boxpen[i] == act) { os.fBoxPenWidth = act->data().toReal(); moveBox(); @@ -696,19 +708,19 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { } } - for (int i=0;i<6;++i) { + for (int i = 0; i < 6; ++i) { if (align[i] == act) { Qt::Alignment *aptr; if (item == qgpiAvatar) - aptr = & os.qaAvatar; + aptr = &os.qaAvatar; else if (item == qgpiChannel) - aptr = & os.qaChannel; + aptr = &os.qaChannel; else if (item == qgpiMuted) - aptr = & os.qaMutedDeafened; + aptr = &os.qaMutedDeafened; else - aptr = & os.qaUserName; + aptr = &os.qaUserName; - Qt::Alignment a = static_cast<Qt::Alignment>(act->data().toInt()); + Qt::Alignment a = static_cast< Qt::Alignment >(act->data().toInt()); if (a & Qt::AlignHorizontal_Mask) { *aptr = (*aptr & ~Qt::AlignHorizontal_Mask) | a; } else { @@ -720,28 +732,30 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { } if (act == boxpencolor) { - QColor qc = QColorDialog::getColor(os.qcBoxPen, e->widget(), tr("Pick pen color"), QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel); - if (! qc.isValid()) + QColor qc = QColorDialog::getColor(os.qcBoxPen, e->widget(), tr("Pick pen color"), + QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel); + if (!qc.isValid()) return; os.qcBoxPen = qc; moveBox(); } else if (act == boxfillcolor) { - QColor qc = QColorDialog::getColor(os.qcBoxFill, e->widget(), tr("Pick fill color"), QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel); - if (! qc.isValid()) + QColor qc = QColorDialog::getColor(os.qcBoxFill, e->widget(), tr("Pick fill color"), + QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel); + if (!qc.isValid()) return; os.qcBoxFill = qc; moveBox(); } else if (act == color) { QColor *col = nullptr; if (item == qgpiChannel) - col = & os.qcChannel; + col = &os.qcChannel; else if (item == qgpiName) - col = & os.qcUserName[tsColor]; - if (! col) + col = &os.qcUserName[tsColor]; + if (!col) return; QColor qc = QColorDialog::getColor(*col, e->widget(), tr("Pick color"), QColorDialog::DontUseNativeDialog); - if (! qc.isValid()) + if (!qc.isValid()) return; qc.setAlpha(255); @@ -772,7 +786,7 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { qgpw->setZValue(3.0f); qgpw->setPanelModality(QGraphicsItem::PanelModal); - qgpw->setPos(- qgpw->boundingRect().width() / 2.0f, - qgpw->boundingRect().height() / 2.0f); + qgpw->setPos(-qgpw->boundingRect().width() / 2.0f, -qgpw->boundingRect().height() / 2.0f); qgpw->show(); ret = qfd.exec(); @@ -787,7 +801,7 @@ void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { ret = qfd.exec(); } - if (! ret) + if (!ret) return; *fontptr = qfd.selectedFont(); @@ -828,10 +842,10 @@ static qreal distancePointLine(const QPointF &a, const QPointF &b, const QPointF Qt::WindowFrameSection OverlayEditorScene::rectSection(const QRectF &qrf, const QPointF &qp, qreal dist) { qreal left, right, top, bottom; - top = distancePointLine(qrf.topLeft(), qrf.topRight(), qp); + top = distancePointLine(qrf.topLeft(), qrf.topRight(), qp); bottom = distancePointLine(qrf.bottomLeft(), qrf.bottomRight(), qp); - left = distancePointLine(qrf.topLeft(), qrf.bottomLeft(), qp); - right = distancePointLine(qrf.topRight(), qrf.bottomRight(), qp); + left = distancePointLine(qrf.topLeft(), qrf.bottomLeft(), qp); + right = distancePointLine(qrf.topRight(), qrf.bottomRight(), qp); if ((top < dist) && (top < bottom)) { if ((left < dist) && (left < right)) diff --git a/src/mumble/OverlayEditorScene.h b/src/mumble/OverlayEditorScene.h index ac5542896..718196442 100644 --- a/src/mumble/OverlayEditorScene.h +++ b/src/mumble/OverlayEditorScene.h @@ -12,60 +12,61 @@ #include "Settings.h" class OverlayEditorScene : public QGraphicsScene { - private: - Q_OBJECT - Q_DISABLE_COPY(OverlayEditorScene) - - protected: - QGraphicsItem *qgiGroup; - - QGraphicsPixmapItem *qgpiMuted; - QGraphicsPixmapItem *qgpiAvatar; - QGraphicsPixmapItem *qgpiName; - QGraphicsPixmapItem *qgpiChannel; - QGraphicsPathItem *qgpiBox; - QGraphicsRectItem *qgriSelected; - QGraphicsPixmapItem *qgpiSelected; - int iDragCorner; - - Qt::WindowFrameSection wfsHover; - - unsigned int uiSize; - - void setup(); - - void contextMenuEvent(QGraphicsSceneContextMenuEvent *e) Q_DECL_OVERRIDE; - void mousePressEvent(QGraphicsSceneMouseEvent *e) Q_DECL_OVERRIDE; - void mouseMoveEvent(QGraphicsSceneMouseEvent *e) Q_DECL_OVERRIDE; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *e) Q_DECL_OVERRIDE; - void updateCursorShape(const QPointF &point); - - void drawBackground(QPainter *, const QRectF &) Q_DECL_OVERRIDE; - - QGraphicsPixmapItem *childAt(const QPointF &); - QRectF selectedRect() const; - - static Qt::WindowFrameSection rectSection(const QRectF &rect, const QPointF &point, qreal dist = 3.0f); - public: - Settings::TalkState tsColor; - unsigned int uiZoom; - OverlaySettings os; - - OverlayEditorScene(const OverlaySettings &, QObject *p = nullptr); - public slots: - void resync(); - void updateSelected(); - - void updateMuted(); - void updateUserName(); - void updateChannel(); - void updateAvatar(); - - void moveMuted(); - void moveUserName(); - void moveChannel(); - void moveAvatar(); - void moveBox(); +private: + Q_OBJECT + Q_DISABLE_COPY(OverlayEditorScene) + +protected: + QGraphicsItem *qgiGroup; + + QGraphicsPixmapItem *qgpiMuted; + QGraphicsPixmapItem *qgpiAvatar; + QGraphicsPixmapItem *qgpiName; + QGraphicsPixmapItem *qgpiChannel; + QGraphicsPathItem *qgpiBox; + QGraphicsRectItem *qgriSelected; + QGraphicsPixmapItem *qgpiSelected; + int iDragCorner; + + Qt::WindowFrameSection wfsHover; + + unsigned int uiSize; + + void setup(); + + void contextMenuEvent(QGraphicsSceneContextMenuEvent *e) Q_DECL_OVERRIDE; + void mousePressEvent(QGraphicsSceneMouseEvent *e) Q_DECL_OVERRIDE; + void mouseMoveEvent(QGraphicsSceneMouseEvent *e) Q_DECL_OVERRIDE; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *e) Q_DECL_OVERRIDE; + void updateCursorShape(const QPointF &point); + + void drawBackground(QPainter *, const QRectF &) Q_DECL_OVERRIDE; + + QGraphicsPixmapItem *childAt(const QPointF &); + QRectF selectedRect() const; + + static Qt::WindowFrameSection rectSection(const QRectF &rect, const QPointF &point, qreal dist = 3.0f); + +public: + Settings::TalkState tsColor; + unsigned int uiZoom; + OverlaySettings os; + + OverlayEditorScene(const OverlaySettings &, QObject *p = nullptr); +public slots: + void resync(); + void updateSelected(); + + void updateMuted(); + void updateUserName(); + void updateChannel(); + void updateAvatar(); + + void moveMuted(); + void moveUserName(); + void moveChannel(); + void moveAvatar(); + void moveBox(); }; #endif diff --git a/src/mumble/OverlayPositionableItem.cpp b/src/mumble/OverlayPositionableItem.cpp index bed165b81..eac5a5269 100644 --- a/src/mumble/OverlayPositionableItem.cpp +++ b/src/mumble/OverlayPositionableItem.cpp @@ -12,9 +12,7 @@ #include <QtWidgets/QGraphicsScene>
OverlayPositionableItem::OverlayPositionableItem(QRectF *posPtr, const bool isPositionable)
- : m_position(posPtr)
- , m_isPositionEditable(isPositionable)
- , m_qgeiHandle(nullptr) {
+ : m_position(posPtr), m_isPositionEditable(isPositionable), m_qgeiHandle(nullptr) {
}
OverlayPositionableItem::~OverlayPositionableItem() {
@@ -53,8 +51,8 @@ void OverlayPositionableItem::onMove() { const QRectF &sr = scene()->sceneRect();
const QPointF &p = m_qgeiHandle->pos();
- m_position->setX(qBound<qreal>(0.0f, p.x() / sr.width(), 1.0f));
- m_position->setY(qBound<qreal>(0.0f, p.y() / sr.height(), 1.0f));
+ m_position->setX(qBound< qreal >(0.0f, p.x() / sr.width(), 1.0f));
+ m_position->setY(qBound< qreal >(0.0f, p.y() / sr.height(), 1.0f));
m_qgeiHandle->setPos(m_position->x() * sr.width(), m_position->y() * sr.height());
@@ -76,8 +74,8 @@ void OverlayPositionableItem::updateRender() { QRectF br = boundingRect();
// Limit the position by the elements width (to make sure it is right-/bottom-bound rather than outside of the scene
QPoint maxPos(iroundf(sr.width() - br.width() + 0.5f), iroundf(sr.height() - br.height() + 0.5f));
- int basex = qBound<int>(0, absPos.x(), maxPos.x());
- int basey = qBound<int>(0, absPos.y(), maxPos.y());
+ int basex = qBound< int >(0, absPos.x(), maxPos.x());
+ int basey = qBound< int >(0, absPos.y(), maxPos.y());
setPos(basex, basey);
}
diff --git a/src/mumble/OverlayPositionableItem.h b/src/mumble/OverlayPositionableItem.h index f1acb72dd..52a03d648 100644 --- a/src/mumble/OverlayPositionableItem.h +++ b/src/mumble/OverlayPositionableItem.h @@ -12,11 +12,13 @@ class OverlayPositionableItem : public QObject, public QGraphicsPixmapItem {
Q_OBJECT
Q_DISABLE_COPY(OverlayPositionableItem);
+
public:
- OverlayPositionableItem(QRectF *posPtr, const bool isPositionable=false);
+ OverlayPositionableItem(QRectF *posPtr, const bool isPositionable = false);
virtual ~OverlayPositionableItem();
void updateRender();
void setItemVisible(const bool &visible);
+
private:
/// Float value between 0 and 1 where 0,0 is top left, and 1,1 is bottom right
QRectF *m_position;
diff --git a/src/mumble/OverlayText.cpp b/src/mumble/OverlayText.cpp index bcf6e022f..c6a801d48 100644 --- a/src/mumble/OverlayText.cpp +++ b/src/mumble/OverlayText.cpp @@ -12,57 +12,41 @@ #include <QtGui/QPainter> #include <QtGui/QPen> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -BasepointPixmap::BasepointPixmap() : - qpBasePoint(0, 0), - iAscent(-1), - iDescent(-1) { } - -BasepointPixmap::BasepointPixmap(const QPixmap& pm) : - QPixmap(pm), - qpBasePoint(0, pm.height()), - iAscent(-1), - iDescent(-1) { } - -BasepointPixmap::BasepointPixmap(int w, int h) : - QPixmap(w, h), - qpBasePoint(0, h), - iAscent(-1), - iDescent(-1) { } - -BasepointPixmap::BasepointPixmap(int w, int h, const QPoint& bp) : - QPixmap(w, h), - qpBasePoint(bp), - iAscent(-1), - iDescent(-1) { } - -OverlayTextLine::OverlayTextLine(const QString& s, const QFont& f) - : fEdgeFactor(0.05f) - , qsText(s) - , qfFont(f) - , fXCorrection(0.0) - , fYCorrection(0.0) - , iCurWidth(-1) - , iCurHeight(-1) - , fBaseliningThreshold(0.5f) - , bElided(false) { - +BasepointPixmap::BasepointPixmap() : qpBasePoint(0, 0), iAscent(-1), iDescent(-1) { +} + +BasepointPixmap::BasepointPixmap(const QPixmap &pm) + : QPixmap(pm), qpBasePoint(0, pm.height()), iAscent(-1), iDescent(-1) { +} + +BasepointPixmap::BasepointPixmap(int w, int h) : QPixmap(w, h), qpBasePoint(0, h), iAscent(-1), iDescent(-1) { +} + +BasepointPixmap::BasepointPixmap(int w, int h, const QPoint &bp) + : QPixmap(w, h), qpBasePoint(bp), iAscent(-1), iDescent(-1) { +} + +OverlayTextLine::OverlayTextLine(const QString &s, const QFont &f) + : fEdgeFactor(0.05f), qsText(s), qfFont(f), fXCorrection(0.0), fYCorrection(0.0), iCurWidth(-1), iCurHeight(-1), + fBaseliningThreshold(0.5f), bElided(false) { QFontMetrics fm(f); - fAscent = static_cast<float>(fm.ascent()); - fDescent = static_cast<float>(fm.descent()); - fEdge = qMax(static_cast<float>(f.pointSizeF()) * fEdgeFactor, 1.0f); + fAscent = static_cast< float >(fm.ascent()); + fDescent = static_cast< float >(fm.descent()); + fEdge = qMax(static_cast< float >(f.pointSizeF()) * fEdgeFactor, 1.0f); } -BasepointPixmap OverlayTextLine::render(int w, int h, const QColor& col, const QPoint& bp) const { +BasepointPixmap OverlayTextLine::render(int w, int h, const QColor &col, const QPoint &bp) const { BasepointPixmap img(w, h, bp); img.fill(Qt::transparent); QPainter imgp(&img); imgp.setRenderHint(QPainter::Antialiasing); imgp.setRenderHint(QPainter::TextAntialiasing); - imgp.setBackground(QColor(0,0,0,0)); + imgp.setBackground(QColor(0, 0, 0, 0)); imgp.setCompositionMode(QPainter::CompositionMode_SourceOver); QColor qc(col); @@ -75,7 +59,7 @@ BasepointPixmap OverlayTextLine::render(int w, int h, const QColor& col, const Q imgp.setPen(Qt::NoPen); imgp.drawPath(qpp); - img.iAscent = iroundf(fAscent + 0.5f); + img.iAscent = iroundf(fAscent + 0.5f); img.iDescent = iroundf(fDescent + 0.5f); return img; } @@ -95,11 +79,11 @@ BasepointPixmap OverlayTextLine::createPixmap(QColor col) { fYCorrection = 0.0f; if (qr.left() < fEdge) { - fXCorrection = fEdge - static_cast<float>(qr.left()); + fXCorrection = fEdge - static_cast< float >(qr.left()); } if (qr.top() < fEdge) { - fYCorrection = fEdge - static_cast<float>(qr.top()); + fYCorrection = fEdge - static_cast< float >(qr.top()); } QMatrix correction; @@ -109,32 +93,29 @@ BasepointPixmap OverlayTextLine::createPixmap(QColor col) { qr = qpp.controlPointRect(); - return render( - iroundf(qr.right() + 2.0f*fEdge + 0.5f), - iroundf(qr.bottom() + 2.0f*fEdge + 0.5f), - col, - QPoint(iroundf(fXCorrection + 0.5f), iroundf(fYCorrection + fAscent + 0.5f)) - ); + return render(iroundf(qr.right() + 2.0f * fEdge + 0.5f), iroundf(qr.bottom() + 2.0f * fEdge + 0.5f), col, + QPoint(iroundf(fXCorrection + 0.5f), iroundf(fYCorrection + fAscent + 0.5f))); } BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned int height, QColor col) { float twice_edge = 2.0f * fEdge; - if (! height || ! maxwidth) + if (!height || !maxwidth) return BasepointPixmap(); - if (qpp.isEmpty() || iCurWidth > static_cast<int>(maxwidth) || iCurHeight != static_cast<int>(height) || (static_cast<int>(maxwidth) > iCurWidth && bElided)) { + if (qpp.isEmpty() || iCurWidth > static_cast< int >(maxwidth) || iCurHeight != static_cast< int >(height) + || (static_cast< int >(maxwidth) > iCurWidth && bElided)) { QFont f = qfFont; QFontMetrics fm(f); // fit the font into a bounding box with padding - float ps = static_cast<float>(f.pointSizeF()); - float f_ad = static_cast<float>(fm.ascent() + fm.descent()+1) / ps; + float ps = static_cast< float >(f.pointSizeF()); + float f_ad = static_cast< float >(fm.ascent() + fm.descent() + 1) / ps; - float pointsize = static_cast<float>(height) / (f_ad + 2.0f*fEdgeFactor); + float pointsize = static_cast< float >(height) / (f_ad + 2.0f * fEdgeFactor); if (fEdgeFactor * ps > 1.0f) { - pointsize = static_cast<float>(height-2) / f_ad; + pointsize = static_cast< float >(height - 2) / f_ad; } if (pointsize <= 0.0f) { @@ -143,7 +124,7 @@ BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned in f.setPointSizeF(pointsize); setFont(f); - fm = QFontMetrics(f); + fm = QFontMetrics(f); twice_edge = 2.0f * fEdge; if (!qpp.isEmpty()) { @@ -155,28 +136,34 @@ BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned in qpp.addText(0.0f, 0.0f, f, qsText); bb = qpp.controlPointRect(); - qreal effective_ascent = -bb.top(); + qreal effective_ascent = -bb.top(); qreal effective_descent = bb.bottom(); - float scale = 1.0f; - bool keep_baseline = true; + float scale = 1.0f; + bool keep_baseline = true; if (effective_descent > fDescent || effective_ascent > fAscent) { - qreal scale_ascent = effective_ascent > 0.0f ? fAscent / effective_ascent : 1.0f; + qreal scale_ascent = effective_ascent > 0.0f ? fAscent / effective_ascent : 1.0f; qreal scale_descent = effective_descent > 0.0f ? fDescent / effective_descent : 1.0f; - scale = static_cast<float>(qMin(scale_ascent, scale_descent)); + scale = static_cast< float >(qMin(scale_ascent, scale_descent)); if (scale < fBaseliningThreshold) { - float text_height = static_cast<float>(bb.height()) + twice_edge; - scale = static_cast<float>(height) / text_height; - keep_baseline = false; + float text_height = static_cast< float >(bb.height()) + twice_edge; + scale = static_cast< float >(height) / text_height; + keep_baseline = false; } - qWarning() << QString(QLatin1String("Text \"%1\" did not fit (+%2/-%3): (+%4/-%5). Scaling to %6.")).arg(qsText).arg(fAscent).arg(fDescent).arg(effective_ascent).arg(effective_descent).arg(scale); + qWarning() << QString(QLatin1String("Text \"%1\" did not fit (+%2/-%3): (+%4/-%5). Scaling to %6.")) + .arg(qsText) + .arg(fAscent) + .arg(fDescent) + .arg(effective_ascent) + .arg(effective_descent) + .arg(scale); } // eliding by previously calculated width - if ((bb.width()*scale) + twice_edge > maxwidth) { - int eliding_width = iroundf((static_cast<float>(maxwidth) / scale) - twice_edge + 0.5f); - QString str = fm.elidedText(qsText, Qt::ElideRight, eliding_width); + if ((bb.width() * scale) + twice_edge > maxwidth) { + int eliding_width = iroundf((static_cast< float >(maxwidth) / scale) - twice_edge + 0.5f); + QString str = fm.elidedText(qsText, Qt::ElideRight, eliding_width); // use ellipsis as shortest possible string if (str.trimmed().isEmpty()) { @@ -185,7 +172,7 @@ BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned in qpp = QPainterPath(); qpp.addText(0.0f, 0.0f, f, str); - bb = qpp.controlPointRect(); + bb = qpp.controlPointRect(); bElided = true; } else { bElided = false; @@ -206,31 +193,27 @@ BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned in correction.translate(0.0f, -bb.top() + fEdge); } - qpp = correction.map(qpp); - iCurWidth = iroundf(bb.width() * scale + 0.5f); + qpp = correction.map(qpp); + iCurWidth = iroundf(bb.width() * scale + 0.5f); iCurHeight = height; } QRectF qr = qpp.controlPointRect(); - return render( - iroundf(qr.width() + twice_edge + 0.5f), - iroundf(fAscent + fDescent + twice_edge + 0.5f), - col, - QPoint(0, iroundf(fAscent + fEdge + 0.5f)) - ); + return render(iroundf(qr.width() + twice_edge + 0.5f), iroundf(fAscent + fDescent + twice_edge + 0.5f), col, + QPoint(0, iroundf(fAscent + fEdge + 0.5f))); } -void OverlayTextLine::setFont(const QFont& font) { +void OverlayTextLine::setFont(const QFont &font) { qfFont = font; - qpp = QPainterPath(); + qpp = QPainterPath(); QFontMetrics fm(font); - fAscent = static_cast<float>(fm.ascent()+1); - fDescent = static_cast<float>(fm.descent()+1); - fEdge = qMax(static_cast<float>(font.pointSizeF()) * fEdgeFactor, 1.0f); + fAscent = static_cast< float >(fm.ascent() + 1); + fDescent = static_cast< float >(fm.descent() + 1); + fEdge = qMax(static_cast< float >(font.pointSizeF()) * fEdgeFactor, 1.0f); } void OverlayTextLine::setEdge(float ew) { fEdge = ew; - qpp = QPainterPath(); + qpp = QPainterPath(); } diff --git a/src/mumble/OverlayText.h b/src/mumble/OverlayText.h index c1cd9efdd..812d7ad8c 100644 --- a/src/mumble/OverlayText.h +++ b/src/mumble/OverlayText.h @@ -6,59 +6,60 @@ #ifndef MUMBLE_MUMBLE_OVERLAYTEXT_H_ #define MUMBLE_MUMBLE_OVERLAYTEXT_H_ +#include <QtGui/QFont> #include <QtGui/QPainterPath> #include <QtGui/QPixmap> -#include <QtGui/QFont> //! Annotated QPixmap supplying a basepoint. class BasepointPixmap : public QPixmap { - public: - //! Local coordinates of the base point. - QPoint qpBasePoint; - //@{ - /** - * Font ascent and descent. - * The pixmap may exceed those font metrics, so if you need to - * transform rendered text properly, use these attributes. - */ - int iAscent; - int iDescent; - //@} +public: + //! Local coordinates of the base point. + QPoint qpBasePoint; + //@{ + /** + * Font ascent and descent. + * The pixmap may exceed those font metrics, so if you need to + * transform rendered text properly, use these attributes. + */ + int iAscent; + int iDescent; + //@} - BasepointPixmap(); - //! Create from QPixmap, basepoint is bottom left. - BasepointPixmap(const QPixmap&); - //! Empty pixmap, basepoint is bottom left. - BasepointPixmap(int, int); - //! Empty pixmap with specified basepoint. - BasepointPixmap(int, int, const QPoint&); + BasepointPixmap(); + //! Create from QPixmap, basepoint is bottom left. + BasepointPixmap(const QPixmap &); + //! Empty pixmap, basepoint is bottom left. + BasepointPixmap(int, int); + //! Empty pixmap with specified basepoint. + BasepointPixmap(int, int, const QPoint &); }; class OverlayTextLine { - private: - const float fEdgeFactor; +private: + const float fEdgeFactor; + + QString qsText; + QFont qfFont; + QPainterPath qpp; + float fAscent, fDescent; + float fXCorrection, fYCorrection; + int iCurWidth, iCurHeight; + float fEdge; + float fBaseliningThreshold; + bool bElided; - QString qsText; - QFont qfFont; - QPainterPath qpp; - float fAscent, fDescent; - float fXCorrection, fYCorrection; - int iCurWidth, iCurHeight; - float fEdge; - float fBaseliningThreshold; - bool bElided; + BasepointPixmap render(int, int, const QColor &, const QPoint &) const; - BasepointPixmap render(int, int, const QColor&, const QPoint&) const; - public: - OverlayTextLine(const QString&, const QFont&); +public: + OverlayTextLine(const QString &, const QFont &); - void setFont(const QFont&); - void setEdge(float); + void setFont(const QFont &); + void setEdge(float); - //! Render text with current font. - BasepointPixmap createPixmap(QColor col); - //! Render text to fit a bounding box. - BasepointPixmap createPixmap(unsigned int maxwidth, unsigned int height, QColor col); + //! Render text with current font. + BasepointPixmap createPixmap(QColor col); + //! Render text to fit a bounding box. + BasepointPixmap createPixmap(unsigned int maxwidth, unsigned int height, QColor col); }; #endif //_OVERLAYTEXT_H diff --git a/src/mumble/OverlayUser.cpp b/src/mumble/OverlayUser.cpp index d67e902ba..e85797951 100644 --- a/src/mumble/OverlayUser.cpp +++ b/src/mumble/OverlayUser.cpp @@ -5,29 +5,32 @@ #include "OverlayUser.h" -#include "OverlayText.h" -#include "User.h" #include "Channel.h" #include "ClientUser.h" -#include "Message.h" #include "Database.h" +#include "MainWindow.h" +#include "Message.h" #include "NetworkConfig.h" +#include "OverlayText.h" #include "ServerHandler.h" -#include "MainWindow.h" -#include "GlobalShortcut.h" +#include "User.h" #include "Utils.h" +#include "GlobalShortcut.h" #include <QtGui/QImageReader> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -OverlayUser::OverlayUser(ClientUser *cu, unsigned int height, OverlaySettings *osptr) : OverlayGroup(), os(osptr), uiSize(height), cuUser(cu), tsColor(Settings::Passive) { +OverlayUser::OverlayUser(ClientUser *cu, unsigned int height, OverlaySettings *osptr) + : OverlayGroup(), os(osptr), uiSize(height), cuUser(cu), tsColor(Settings::Passive) { setup(); updateLayout(); } -OverlayUser::OverlayUser(Settings::TalkState ts, unsigned int height, OverlaySettings *osptr) : OverlayGroup(), os(osptr), uiSize(height), cuUser(nullptr), tsColor(ts) { +OverlayUser::OverlayUser(Settings::TalkState ts, unsigned int height, OverlaySettings *osptr) + : OverlayGroup(), os(osptr), uiSize(height), cuUser(nullptr), tsColor(ts) { qsChannelName = Overlay::tr("Channel"); setup(); @@ -47,7 +50,7 @@ void OverlayUser::setup() { qgpiAvatar = new QGraphicsPixmapItem(this); - for (int i=0;i<4;++i) { + for (int i = 0; i < 4; ++i) { qgpiName[i] = new QGraphicsPixmapItem(this); qgpiName[i]->hide(); } @@ -60,7 +63,9 @@ void OverlayUser::setup() { } #undef SCALESIZE -#define SCALESIZE(var) iroundf(uiSize * os->fZoom * os->qrf##var .width() + 0.5f), iroundf(uiSize * os->fZoom * os->qrf##var .height() + 0.5f) +#define SCALESIZE(var) \ + iroundf(uiSize * os->fZoom * os->qrf##var.width() + 0.5f), \ + iroundf(uiSize * os->fZoom * os->qrf##var.height() + 0.5f) void OverlayUser::updateLayout() { QPixmap pm; @@ -70,7 +75,7 @@ void OverlayUser::updateLayout() { prepareGeometryChange(); - for (int i=0;i<4;++i) + for (int i = 0; i < 4; ++i) qgpiName[i]->setPixmap(pm); qgpiAvatar->setPixmap(pm); @@ -92,18 +97,20 @@ void OverlayUser::updateLayout() { qgpiDeafened->setPixmap(QPixmap::fromImage(qir.read())); } - qgpiMuted->setPos(alignedPosition(scaledRect(os->qrfMutedDeafened, uiSize * os->fZoom), qgpiMuted->boundingRect(), os->qaMutedDeafened)); + qgpiMuted->setPos(alignedPosition(scaledRect(os->qrfMutedDeafened, uiSize * os->fZoom), qgpiMuted->boundingRect(), + os->qaMutedDeafened)); qgpiMuted->setZValue(1.0f); qgpiMuted->setOpacity(os->fMutedDeafened); - qgpiDeafened->setPos(alignedPosition(scaledRect(os->qrfMutedDeafened, uiSize * os->fZoom), qgpiDeafened->boundingRect(), os->qaMutedDeafened)); + qgpiDeafened->setPos(alignedPosition(scaledRect(os->qrfMutedDeafened, uiSize * os->fZoom), + qgpiDeafened->boundingRect(), os->qaMutedDeafened)); qgpiDeafened->setZValue(1.0f); qgpiDeafened->setOpacity(os->fMutedDeafened); qgpiAvatar->setPos(0.0f, 0.0f); qgpiAvatar->setOpacity(os->fAvatar); - for (int i=0;i<4;++i) { + for (int i = 0; i < 4; ++i) { qgpiName[i]->setPos(0.0f, 0.0f); qgpiName[i]->setZValue(2.0f); qgpiName[i]->setOpacity(os->fUserName); @@ -114,19 +121,23 @@ void OverlayUser::updateLayout() { QRectF childrenBounds = os->qrfAvatar | os->qrfChannel | os->qrfMutedDeafened | os->qrfUserName; - bool haspen = (os->qcBoxPen != os->qcBoxFill) && (! qFuzzyCompare(os->qcBoxPen.alphaF(), static_cast<qreal>(0.0f))); - qreal pw = haspen ? qMax<qreal>(1.0f, os->fBoxPenWidth * uiSize * os->fZoom) : 0.0f; + bool haspen = + (os->qcBoxPen != os->qcBoxFill) && (!qFuzzyCompare(os->qcBoxPen.alphaF(), static_cast< qreal >(0.0f))); + qreal pw = haspen ? qMax< qreal >(1.0f, os->fBoxPenWidth * uiSize * os->fZoom) : 0.0f; qreal pad = os->fBoxPad * uiSize * os->fZoom; QPainterPath pp; - pp.addRoundedRect(childrenBounds.x() * uiSize * os->fZoom + -pw / 2.0f - pad, childrenBounds.y() * uiSize * os->fZoom + -pw / 2.0f - pad, childrenBounds.width() * uiSize * os->fZoom + pw + 2.0f * pad, childrenBounds.height() * uiSize * os->fZoom + pw + 2.0f * pad, 2.0f * pw, 2.0f * pw); + pp.addRoundedRect(childrenBounds.x() * uiSize * os->fZoom + -pw / 2.0f - pad, + childrenBounds.y() * uiSize * os->fZoom + -pw / 2.0f - pad, + childrenBounds.width() * uiSize * os->fZoom + pw + 2.0f * pad, + childrenBounds.height() * uiSize * os->fZoom + pw + 2.0f * pad, 2.0f * pw, 2.0f * pw); qgpiBox->setPath(pp); qgpiBox->setPos(0.0f, 0.0f); qgpiBox->setZValue(-1.0f); qgpiBox->setPen(haspen ? QPen(os->qcBoxPen, pw) : Qt::NoPen); - qgpiBox->setBrush(qFuzzyCompare(os->qcBoxFill.alphaF(), static_cast<qreal>(0.0f)) ? Qt::NoBrush : os->qcBoxFill); + qgpiBox->setBrush(qFuzzyCompare(os->qcBoxFill.alphaF(), static_cast< qreal >(0.0f)) ? Qt::NoBrush : os->qcBoxFill); qgpiBox->setOpacity(1.0f); - if (! cuUser) { + if (!cuUser) { switch (tsColor) { case Settings::Passive: qsName = Overlay::tr("Silent"); @@ -153,12 +164,13 @@ void OverlayUser::updateUser() { qsName = cuUser->qsName; OverlayTextLine tl(qsName, os->qfUserName); - for (int i=0; i<4; ++i) { + for (int i = 0; i < 4; ++i) { const QPixmap &pm = tl.createPixmap(SCALESIZE(UserName), os->qcUserName[i]); qgpiName[i]->setPixmap(pm); if (i == 0) - qgpiName[0]->setPos(alignedPosition(scaledRect(os->qrfUserName, uiSize * os->fZoom), qgpiName[0]->boundingRect(), os->qaUserName)); + qgpiName[0]->setPos(alignedPosition(scaledRect(os->qrfUserName, uiSize * os->fZoom), + qgpiName[0]->boundingRect(), os->qaUserName)); else qgpiName[i]->setPos(qgpiName[0]->pos()); } @@ -168,9 +180,11 @@ void OverlayUser::updateUser() { if (cuUser) qsChannelName = cuUser->cChannel->qsName; - const QPixmap &pm = OverlayTextLine(qsChannelName, os->qfChannel).createPixmap(SCALESIZE(Channel), os->qcChannel); + const QPixmap &pm = + OverlayTextLine(qsChannelName, os->qfChannel).createPixmap(SCALESIZE(Channel), os->qcChannel); qgpiChannel->setPixmap(pm); - qgpiChannel->setPos(alignedPosition(scaledRect(os->qrfChannel, uiSize * os->fZoom), qgpiChannel->boundingRect(), os->qaChannel)); + qgpiChannel->setPos(alignedPosition(scaledRect(os->qrfChannel, uiSize * os->fZoom), qgpiChannel->boundingRect(), + os->qaChannel)); } if (os->bAvatar && (qgpiAvatar->pixmap().isNull() || (cuUser && (qbaAvatar != cuUser->qbaTextureHash)))) { @@ -179,7 +193,7 @@ void OverlayUser::updateUser() { QImage img; - if (! qbaAvatar.isNull() && cuUser->qbaTexture.isEmpty()) { + if (!qbaAvatar.isNull() && cuUser->qbaTexture.isEmpty()) { g.o->requestTexture(cuUser); } else if (qbaAvatar.isNull()) { QImageReader qir(QLatin1String("skin:default_avatar.svg")); @@ -188,7 +202,7 @@ void OverlayUser::updateUser() { qir.setScaledSize(sz); img = qir.read(); } else { - QBuffer qb(& cuUser->qbaTexture); + QBuffer qb(&cuUser->qbaTexture); qb.open(QIODevice::ReadOnly); QImageReader qir(&qb, cuUser->qbaTextureFormat); @@ -199,7 +213,8 @@ void OverlayUser::updateUser() { } qgpiAvatar->setPixmap(QPixmap::fromImage(img)); - qgpiAvatar->setPos(alignedPosition(scaledRect(os->qrfAvatar, uiSize * os->fZoom), qgpiAvatar->boundingRect(), os->qaAvatar)); + qgpiAvatar->setPos( + alignedPosition(scaledRect(os->qrfAvatar, uiSize * os->fZoom), qgpiAvatar->boundingRect(), os->qaAvatar)); } qgpiAvatar->setVisible(os->bAvatar); @@ -224,7 +239,7 @@ void OverlayUser::updateUser() { } bool samechannel = self && (self->cChannel == cuUser->cChannel); - qgpiChannel->setVisible(os->bChannel && ! samechannel); + qgpiChannel->setVisible(os->bChannel && !samechannel); tsColor = cuUser->tsState; } else { @@ -234,10 +249,10 @@ void OverlayUser::updateUser() { } if (os->bUserName) - for (int i=0;i<4;++i) + for (int i = 0; i < 4; ++i) qgpiName[i]->setVisible(i == tsColor); else - for (int i=0;i<4;++i) + for (int i = 0; i < 4; ++i) qgpiName[i]->setVisible(false); qgpiBox->setVisible(os->bBox); @@ -274,4 +289,3 @@ QPointF OverlayUser::alignedPosition(const QRectF &box, const QRectF &item, Qt:: return QPointF(iroundf(xofs + 0.5f), iroundf(yofs + 0.5f)); } - diff --git a/src/mumble/OverlayUser.h b/src/mumble/OverlayUser.h index dd90726aa..2064b5764 100644 --- a/src/mumble/OverlayUser.h +++ b/src/mumble/OverlayUser.h @@ -11,38 +11,39 @@ #include "Overlay.h" class OverlayUser : public OverlayGroup { - private: - Q_DISABLE_COPY(OverlayUser) - public: - enum { Type = UserType + 1 }; - protected: - QGraphicsPixmapItem *qgpiMuted, *qgpiDeafened; - QGraphicsPixmapItem *qgpiAvatar; - QGraphicsPixmapItem *qgpiName[4]; - QGraphicsPixmapItem *qgpiChannel; - QGraphicsPathItem *qgpiBox; - - OverlaySettings *os; - - unsigned int uiSize; - ClientUser *cuUser; - Settings::TalkState tsColor; - - QString qsName; - QString qsChannelName; - QByteArray qbaAvatar; - - void setup(); - - public: - OverlayUser(ClientUser *cu, unsigned int uiSize, OverlaySettings *osptr); - OverlayUser(Settings::TalkState ts, unsigned int uiSize, OverlaySettings *osptr); - void updateUser(); - void updateLayout(); - - int type() const Q_DECL_OVERRIDE; - static QRectF scaledRect(const QRectF &qr, qreal scale); - static QPointF alignedPosition(const QRectF &box, const QRectF &item, Qt::Alignment a); +private: + Q_DISABLE_COPY(OverlayUser) +public: + enum { Type = UserType + 1 }; + +protected: + QGraphicsPixmapItem *qgpiMuted, *qgpiDeafened; + QGraphicsPixmapItem *qgpiAvatar; + QGraphicsPixmapItem *qgpiName[4]; + QGraphicsPixmapItem *qgpiChannel; + QGraphicsPathItem *qgpiBox; + + OverlaySettings *os; + + unsigned int uiSize; + ClientUser *cuUser; + Settings::TalkState tsColor; + + QString qsName; + QString qsChannelName; + QByteArray qbaAvatar; + + void setup(); + +public: + OverlayUser(ClientUser *cu, unsigned int uiSize, OverlaySettings *osptr); + OverlayUser(Settings::TalkState ts, unsigned int uiSize, OverlaySettings *osptr); + void updateUser(); + void updateLayout(); + + int type() const Q_DECL_OVERRIDE; + static QRectF scaledRect(const QRectF &qr, qreal scale); + static QPointF alignedPosition(const QRectF &box, const QRectF &item, Qt::Alignment a); }; #endif diff --git a/src/mumble/OverlayUserGroup.cpp b/src/mumble/OverlayUserGroup.cpp index 08d13a7df..558e04b85 100644 --- a/src/mumble/OverlayUserGroup.cpp +++ b/src/mumble/OverlayUserGroup.cpp @@ -5,55 +5,53 @@ #include "OverlayUserGroup.h" -#include "OverlayUser.h" -#include "OverlayClient.h" -#include "OverlayEditor.h" -#include "OverlayText.h" -#include "User.h" #include "Channel.h" #include "ClientUser.h" -#include "Message.h" #include "Database.h" +#include "MainWindow.h" +#include "Message.h" #include "NetworkConfig.h" +#include "OverlayClient.h" +#include "OverlayEditor.h" +#include "OverlayText.h" +#include "OverlayUser.h" #include "ServerHandler.h" -#include "MainWindow.h" -#include "GlobalShortcut.h" +#include "User.h" #include "Utils.h" +#include "GlobalShortcut.h" #include <QtGui/QImageReader> #include <QtWidgets/QGraphicsSceneContextMenuEvent> #include <QtWidgets/QGraphicsSceneWheelEvent> #include <QtWidgets/QInputDialog> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -template <typename T> -QRectF OverlayGroup::boundingRect() const { +template< typename T > QRectF OverlayGroup::boundingRect() const { QRectF qr; - foreach(const QGraphicsItem *item, childItems()) + foreach (const QGraphicsItem *item, childItems()) if (item->isVisible() && (item->type() == T::Type)) qr |= item->boundingRect().translated(item->pos()); return qr; } -OverlayUserGroup::OverlayUserGroup(OverlaySettings *osptr) : - OverlayGroup(), - os(osptr), - qgeiHandle(nullptr), - bShowExamples(false) { } +OverlayUserGroup::OverlayUserGroup(OverlaySettings *osptr) + : OverlayGroup(), os(osptr), qgeiHandle(nullptr), bShowExamples(false) { +} OverlayUserGroup::~OverlayUserGroup() { reset(); } void OverlayUserGroup::reset() { - foreach(OverlayUser *ou, qlExampleUsers) + foreach (OverlayUser *ou, qlExampleUsers) delete ou; qlExampleUsers.clear(); - foreach(OverlayUser *ou, qmUsers) + foreach (OverlayUser *ou, qmUsers) delete ou; qmUsers.clear(); @@ -111,12 +109,13 @@ void OverlayUserGroup::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { qmShow->addSeparator(); - QAction *qaConfigureRecentlyActiveTime = qmShow->addAction(OverlayClient::tr("Configure recently active time (%1 seconds)...").arg(os->uiActiveTime)); + QAction *qaConfigureRecentlyActiveTime = + qmShow->addAction(OverlayClient::tr("Configure recently active time (%1 seconds)...").arg(os->uiActiveTime)); qaConfigureRecentlyActiveTime->setEnabled(os->osShow == OverlaySettings::Active); QMenu *qmColumns = qm.addMenu(OverlayClient::tr("Columns")); QAction *qaColumns[6]; - for (unsigned int i=1;i<=5;++i) { + for (unsigned int i = 1; i <= 5; ++i) { qaColumns[i] = qmColumns->addAction(QString::number(i)); qaColumns[i]->setCheckable(true); qaColumns[i]->setChecked(i == os->uiColumns); @@ -139,7 +138,7 @@ void OverlayUserGroup::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { QAction *act = qm.exec(e->screenPos()); - if (! act) + if (!act) return; if (act == qaEdit) { @@ -166,7 +165,7 @@ void OverlayUserGroup::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { os->osShow = OverlaySettings::LinkedChannels; updateUsers(); } else if (act == qaShowSelf) { - os->bAlwaysSelf = ! os->bAlwaysSelf; + os->bAlwaysSelf = !os->bAlwaysSelf; updateUsers(); } else if (act == qaConfigureRecentlyActiveTime) { // FIXME: This might not be the best place to configure this setting, but currently @@ -174,11 +173,9 @@ void OverlayUserGroup::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { // might be added for some advanced overlay options, which could then include this // setting. bool ok; - int newValue = QInputDialog::getInt( - qm.parentWidget(), - OverlayClient::tr("Configure recently active time"), - OverlayClient::tr("Amount of seconds users remain active after talking:"), - os->uiActiveTime, 1, 2147483647, 1, &ok); + int newValue = QInputDialog::getInt(qm.parentWidget(), OverlayClient::tr("Configure recently active time"), + OverlayClient::tr("Amount of seconds users remain active after talking:"), + os->uiActiveTime, 1, 2147483647, 1, &ok); if (ok) { os->uiActiveTime = newValue; } @@ -190,7 +187,7 @@ void OverlayUserGroup::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { os->osSort = OverlaySettings::LastStateChange; updateUsers(); } else { - for (int i=1;i<=5;++i) { + for (int i = 1; i <= 5; ++i) { if (act == qaColumns[i]) { os->uiColumns = i; updateLayout(); @@ -225,20 +222,19 @@ bool OverlayUserGroup::sceneEventFilter(QGraphicsItem *watched, QEvent *e) { break; default: break; - } return OverlayGroup::sceneEventFilter(watched, e); } void OverlayUserGroup::moveUsers() { - if (! qgeiHandle) + if (!qgeiHandle) return; const QRectF &sr = scene()->sceneRect(); const QPointF &p = qgeiHandle->pos(); - os->fX = static_cast<float>(qBound(0.0, p.x() / sr.width(), 1.0)); - os->fY = static_cast<float>(qBound(0.0, p.y() / sr.height(), 1.0)); + os->fX = static_cast< float >(qBound(0.0, p.x() / sr.width(), 1.0)); + os->fY = static_cast< float >(qBound(0.0, p.y() / sr.height(), 1.0)); qgeiHandle->setPos(os->fX * sr.width(), os->fY * sr.height()); updateUsers(); @@ -255,11 +251,11 @@ void OverlayUserGroup::updateUsers() { unsigned int uiHeight = iroundf(sr.height() + 0.5f); - QList<QGraphicsItem *> items; - foreach(QGraphicsItem *qgi, childItems()) + QList< QGraphicsItem * > items; + foreach (QGraphicsItem *qgi, childItems()) items << qgi; - QList<OverlayUser *> users; + QList< OverlayUser * > users; if (bShowExamples) { if (qlExampleUsers.isEmpty()) { qlExampleUsers << new OverlayUser(Settings::Passive, uiHeight, os); @@ -270,10 +266,10 @@ void OverlayUserGroup::updateUsers() { } users = qlExampleUsers; - foreach(OverlayUser *ou, users) + foreach (OverlayUser *ou, users) items.removeAll(ou); - if (! qgeiHandle) { + if (!qgeiHandle) { qgeiHandle = new QGraphicsEllipseItem(QRectF(-4.0f, -4.0f, 8.0f, 8.0f)); qgeiHandle->setPen(QPen(Qt::darkRed, 0.0f)); qgeiHandle->setBrush(Qt::red); @@ -292,23 +288,23 @@ void OverlayUserGroup::updateUsers() { ClientUser *self = ClientUser::get(g.uiSession); if (self) { - QList<ClientUser *> showusers; + QList< ClientUser * > showusers; Channel *home = ClientUser::get(g.uiSession)->cChannel; switch (os->osShow) { case OverlaySettings::LinkedChannels: - foreach(Channel *c, home->allLinks()) - foreach(User *p, c->qlUsers) - showusers << static_cast<ClientUser *>(p); - foreach(ClientUser *cu, ClientUser::getTalking()) - if (! showusers.contains(cu)) + foreach (Channel *c, home->allLinks()) + foreach (User *p, c->qlUsers) + showusers << static_cast< ClientUser * >(p); + foreach (ClientUser *cu, ClientUser::getTalking()) + if (!showusers.contains(cu)) showusers << cu; break; case OverlaySettings::HomeChannel: - foreach(User *p, home->qlUsers) - showusers << static_cast<ClientUser *>(p); - foreach(ClientUser *cu, ClientUser::getTalking()) - if (! showusers.contains(cu)) + foreach (User *p, home->qlUsers) + showusers << static_cast< ClientUser * >(p); + foreach (ClientUser *cu, ClientUser::getTalking()) + if (!showusers.contains(cu)) showusers << cu; break; case OverlaySettings::Active: @@ -325,9 +321,9 @@ void OverlayUserGroup::updateUsers() { ClientUser::sortUsersOverlay(showusers); - foreach(ClientUser *cu, showusers) { + foreach (ClientUser *cu, showusers) { OverlayUser *ou = qmUsers.value(cu); - if (! ou) { + if (!ou) { ou = new OverlayUser(cu, uiHeight, os); connect(cu, SIGNAL(destroyed(QObject *)), this, SLOT(userDestroyed(QObject *))); qmUsers.insert(cu, ou); @@ -339,28 +335,28 @@ void OverlayUserGroup::updateUsers() { } } - foreach(QGraphicsItem *qgi, items) { + foreach (QGraphicsItem *qgi, items) { scene()->removeItem(qgi); qgi->hide(); } QRectF childrenBounds = os->qrfAvatar | os->qrfChannel | os->qrfMutedDeafened | os->qrfUserName; - int pad = os->bBox ? iroundf(uiHeight * os->fZoom * (os->fBoxPad + os->fBoxPenWidth) + 0.5f) : 0; - int width = iroundf(childrenBounds.width() * uiHeight * os->fZoom + 0.5f) + 2 * pad; + int pad = os->bBox ? iroundf(uiHeight * os->fZoom * (os->fBoxPad + os->fBoxPenWidth) + 0.5f) : 0; + int width = iroundf(childrenBounds.width() * uiHeight * os->fZoom + 0.5f) + 2 * pad; int height = iroundf(childrenBounds.height() * uiHeight * os->fZoom + 0.5f) + 2 * pad; - int xOffset = - iroundf(childrenBounds.left() * uiHeight * os->fZoom + 0.5f) + pad; - int yOffset = - iroundf(childrenBounds.top() * uiHeight * os->fZoom + 0.5f) + pad; + int xOffset = -iroundf(childrenBounds.left() * uiHeight * os->fZoom + 0.5f) + pad; + int yOffset = -iroundf(childrenBounds.top() * uiHeight * os->fZoom + 0.5f) + pad; unsigned int yPos = 0; unsigned int xPos = 0; - foreach(OverlayUser *ou, users) { + foreach (OverlayUser *ou, users) { if (!ou->parentItem()) ou->setParentItem(this); - ou->setPos(xPos * (width+4) + xOffset, yPos * (height + 4) + yOffset); + ou->setPos(xPos * (width + 4) + xOffset, yPos * (height + 4) + yOffset); ou->updateUser(); ou->show(); @@ -372,10 +368,10 @@ void OverlayUserGroup::updateUsers() { } } - QRectF br = boundingRect<OverlayUser>(); + QRectF br = boundingRect< OverlayUser >(); - int basex = qBound<int>(0, iroundf(sr.width() * os->fX + 0.5f), iroundf(sr.width() - br.width() + 0.5f)); - int basey = qBound<int>(0, iroundf(sr.height() * os->fY + 0.5f), iroundf(sr.height() - br.height() + 0.5f)); + int basex = qBound< int >(0, iroundf(sr.width() * os->fX + 0.5f), iroundf(sr.width() - br.width() + 0.5f)); + int basey = qBound< int >(0, iroundf(sr.height() * os->fY + 0.5f), iroundf(sr.height() - br.height() + 0.5f)); setPos(basex, basey); } diff --git a/src/mumble/OverlayUserGroup.h b/src/mumble/OverlayUserGroup.h index badce09e1..dc0294c28 100644 --- a/src/mumble/OverlayUserGroup.h +++ b/src/mumble/OverlayUserGroup.h @@ -11,36 +11,39 @@ class OverlayUser; class OverlayUserGroup : public QObject, public OverlayGroup { - private: - Q_OBJECT - Q_DISABLE_COPY(OverlayUserGroup); - public: - enum { Type = UserType + 3 }; - protected: - OverlaySettings *os; - - QMap<QObject *, OverlayUser *> qmUsers; - QList<OverlayUser *> qlExampleUsers; - - QGraphicsEllipseItem *qgeiHandle; - - void contextMenuEvent(QGraphicsSceneContextMenuEvent *e) Q_DECL_OVERRIDE; - void wheelEvent(QGraphicsSceneWheelEvent *e) Q_DECL_OVERRIDE; - bool sceneEventFilter(QGraphicsItem *, QEvent *e) Q_DECL_OVERRIDE; - protected slots: - void userDestroyed(QObject *); - void moveUsers(); - public: - bool bShowExamples; - - OverlayUserGroup(OverlaySettings *); - ~OverlayUserGroup() Q_DECL_OVERRIDE; - - int type() const Q_DECL_OVERRIDE; - public slots: - void reset(); - void updateUsers(); - void updateLayout(); +private: + Q_OBJECT + Q_DISABLE_COPY(OverlayUserGroup); + +public: + enum { Type = UserType + 3 }; + +protected: + OverlaySettings *os; + + QMap< QObject *, OverlayUser * > qmUsers; + QList< OverlayUser * > qlExampleUsers; + + QGraphicsEllipseItem *qgeiHandle; + + void contextMenuEvent(QGraphicsSceneContextMenuEvent *e) Q_DECL_OVERRIDE; + void wheelEvent(QGraphicsSceneWheelEvent *e) Q_DECL_OVERRIDE; + bool sceneEventFilter(QGraphicsItem *, QEvent *e) Q_DECL_OVERRIDE; +protected slots: + void userDestroyed(QObject *); + void moveUsers(); + +public: + bool bShowExamples; + + OverlayUserGroup(OverlaySettings *); + ~OverlayUserGroup() Q_DECL_OVERRIDE; + + int type() const Q_DECL_OVERRIDE; +public slots: + void reset(); + void updateUsers(); + void updateLayout(); }; #endif diff --git a/src/mumble/Overlay_win.cpp b/src/mumble/Overlay_win.cpp index 7bf34eedf..ae7f1a37b 100644 --- a/src/mumble/Overlay_win.cpp +++ b/src/mumble/Overlay_win.cpp @@ -5,17 +5,18 @@ #include "Overlay.h" -#include "User.h" #include "Channel.h" -#include "OverlayConfig.h" #include "MainWindow.h" #include "MumbleApplication.h" +#include "OverlayConfig.h" +#include "User.h" #include "Overlay_win.h" #include "../../overlay/overlay_exe/overlay_exe.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" // Used by the overlay to detect whether we injected into ourselves. @@ -23,7 +24,7 @@ // A similar declaration can be found in mumble_exe's Overlay.cpp, // for the overlay's self-detection checks to continue working in a // mumble_app.dll world. -extern "C" __declspec(dllexport) void mumbleSelfDetection() {}; +extern "C" __declspec(dllexport) void mumbleSelfDetection(){}; // Determine if the current Mumble client is able to host // x64 programs. @@ -35,8 +36,8 @@ static bool canRun64BitPrograms() { #if defined(_M_X64) return TRUE; #elif defined(_M_IX86) - typedef BOOL (WINAPI *IsWow64ProcessPtr)(HANDLE, BOOL *); - IsWow64ProcessPtr wow64check = (IsWow64ProcessPtr)GetProcAddress(GetModuleHandle(L"kernel32"), "IsWow64Process"); + typedef BOOL(WINAPI * IsWow64ProcessPtr)(HANDLE, BOOL *); + IsWow64ProcessPtr wow64check = (IsWow64ProcessPtr) GetProcAddress(GetModuleHandle(L"kernel32"), "IsWow64Process"); if (wow64check) { BOOL isWoW64 = FALSE; wow64check(GetCurrentProcess(), &isWoW64); @@ -47,12 +48,7 @@ static bool canRun64BitPrograms() { } OverlayPrivateWin::OverlayPrivateWin(QObject *p) - : OverlayPrivate(p) - , m_helper_enabled(true) - , m_helper64_enabled(true) - , m_mumble_handle(0) - , m_active(false) { - + : OverlayPrivate(p), m_helper_enabled(true), m_helper64_enabled(true), m_mumble_handle(0), m_active(false) { // Acquire a handle to ourselves and duplicate it. We duplicate it because // want it to be inheritable by our helper processes, and the handle returned // by GetCurrentProcess is not inheritable. Duplicating it makes it inheritable. @@ -71,57 +67,59 @@ OverlayPrivateWin::OverlayPrivateWin(QObject *p) // // from https://msdn.microsoft.com/en-us/library/aa384203.aspx HANDLE curproc = GetCurrentProcess(); - if (!DuplicateHandle(curproc, curproc, curproc, &m_mumble_handle, - 0, TRUE, DUPLICATE_SAME_ACCESS)) { + if (!DuplicateHandle(curproc, curproc, curproc, &m_mumble_handle, 0, TRUE, DUPLICATE_SAME_ACCESS)) { qFatal("OverlayPrivateWin: unable to duplicate handle to the Mumble process."); return; } - m_helper_exe_path = QString::fromLatin1("%1/mumble_ol_helper.exe").arg(MumbleApplication::instance()->applicationVersionRootPath()); + m_helper_exe_path = + QString::fromLatin1("%1/mumble_ol_helper.exe").arg(MumbleApplication::instance()->applicationVersionRootPath()); m_helper_exe_args << QString::number(OVERLAY_MAGIC_NUMBER) - << QString::number(reinterpret_cast<quintptr>(m_mumble_handle)); + << QString::number(reinterpret_cast< quintptr >(m_mumble_handle)); m_helper_process = new QProcess(this); - connect(m_helper_process, SIGNAL(started()), - this, SLOT(onHelperProcessStarted())); + connect(m_helper_process, SIGNAL(started()), this, SLOT(onHelperProcessStarted())); - connect(m_helper_process, SIGNAL(error(QProcess::ProcessError)), - this, SLOT(onHelperProcessError(QProcess::ProcessError))); + connect(m_helper_process, SIGNAL(error(QProcess::ProcessError)), this, + SLOT(onHelperProcessError(QProcess::ProcessError))); - connect(m_helper_process, SIGNAL(finished(int, QProcess::ExitStatus)), - this, SLOT(onHelperProcessExited(int, QProcess::ExitStatus))); + connect(m_helper_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, + SLOT(onHelperProcessExited(int, QProcess::ExitStatus))); m_helper_restart_timer = new QTimer(this); m_helper_restart_timer->setSingleShot(true); connect(m_helper_restart_timer, SIGNAL(timeout()), this, SLOT(onDelayedRestartTimerTriggered())); if (!g.s.bOverlayWinHelperX86Enable) { - qWarning("OverlayPrivateWin: mumble_ol_helper.exe (32-bit overlay helper) disabled via 'overlay_win/enable_x86_helper' config option."); + qWarning("OverlayPrivateWin: mumble_ol_helper.exe (32-bit overlay helper) disabled via " + "'overlay_win/enable_x86_helper' config option."); m_helper_enabled = false; } - m_helper64_exe_path = QString::fromLatin1("%1/mumble_ol_helper_x64.exe").arg(MumbleApplication::instance()->applicationVersionRootPath()); + m_helper64_exe_path = QString::fromLatin1("%1/mumble_ol_helper_x64.exe") + .arg(MumbleApplication::instance()->applicationVersionRootPath()); m_helper64_exe_args = m_helper_exe_args; - m_helper64_process = new QProcess(this); + m_helper64_process = new QProcess(this); - connect(m_helper64_process, SIGNAL(started()), - this, SLOT(onHelperProcessStarted())); + connect(m_helper64_process, SIGNAL(started()), this, SLOT(onHelperProcessStarted())); - connect(m_helper64_process, SIGNAL(error(QProcess::ProcessError)), - this, SLOT(onHelperProcessError(QProcess::ProcessError))); + connect(m_helper64_process, SIGNAL(error(QProcess::ProcessError)), this, + SLOT(onHelperProcessError(QProcess::ProcessError))); - connect(m_helper64_process, SIGNAL(finished(int, QProcess::ExitStatus)), - this, SLOT(onHelperProcessExited(int, QProcess::ExitStatus))); + connect(m_helper64_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, + SLOT(onHelperProcessExited(int, QProcess::ExitStatus))); m_helper64_restart_timer = new QTimer(this); m_helper64_restart_timer->setSingleShot(true); connect(m_helper64_restart_timer, SIGNAL(timeout()), this, SLOT(onDelayedRestartTimerTriggered())); if (!canRun64BitPrograms()) { - qWarning("OverlayPrivateWin: mumble_ol_helper_x64.exe (64-bit overlay helper) disabled because the host is not x64 capable."); + qWarning("OverlayPrivateWin: mumble_ol_helper_x64.exe (64-bit overlay helper) disabled because the host is not " + "x64 capable."); m_helper64_enabled = false; } else if (!g.s.bOverlayWinHelperX64Enable) { - qWarning("OverlayPrivateWin: mumble_ol_helper_x64.exe (64-bit overlay helper) disabled via 'overlay_win/enable_x64_helper' config option."); + qWarning("OverlayPrivateWin: mumble_ol_helper_x64.exe (64-bit overlay helper) disabled via " + "'overlay_win/enable_x64_helper' config option."); m_helper64_enabled = false; } } @@ -216,7 +214,7 @@ static const char *processErrorString(QProcess::ProcessError processError) { } void OverlayPrivateWin::onHelperProcessStarted() { - QProcess *helper = qobject_cast<QProcess *>(sender()); + QProcess *helper = qobject_cast< QProcess * >(sender()); QString path; if (helper == m_helper_process) { path = m_helper_exe_path; @@ -227,12 +225,12 @@ void OverlayPrivateWin::onHelperProcessStarted() { } PROCESS_INFORMATION *pi = helper->pid(); - qWarning("OverlayPrivateWin: overlay helper process '%s' started with PID %llu.", - qPrintable(path), static_cast<unsigned long long>(pi->dwProcessId)); + qWarning("OverlayPrivateWin: overlay helper process '%s' started with PID %llu.", qPrintable(path), + static_cast< unsigned long long >(pi->dwProcessId)); } void OverlayPrivateWin::onHelperProcessError(QProcess::ProcessError processError) { - QProcess *helper = qobject_cast<QProcess *>(sender()); + QProcess *helper = qobject_cast< QProcess * >(sender()); QString path; if (helper == m_helper_process) { path = m_helper_exe_path; @@ -242,34 +240,31 @@ void OverlayPrivateWin::onHelperProcessError(QProcess::ProcessError processError qFatal("OverlayPrivateWin: unknown QProcess found in onHelperProcessError()."); } - qWarning("OverlayPrivateWin: an error occured for overlay helper process '%s': %s", - qPrintable(path), - processErrorString(processError)); + qWarning("OverlayPrivateWin: an error occured for overlay helper process '%s': %s", qPrintable(path), + processErrorString(processError)); } void OverlayPrivateWin::onHelperProcessExited(int exitCode, QProcess::ExitStatus exitStatus) { - QProcess *helper = qobject_cast<QProcess *>(sender()); + QProcess *helper = qobject_cast< QProcess * >(sender()); QString path; - qint64 elapsedMsec = 0; + qint64 elapsedMsec = 0; QTimer *restartTimer = nullptr; if (helper == m_helper_process) { - path = m_helper_exe_path; - elapsedMsec = m_helper_start_time.elapsed(); + path = m_helper_exe_path; + elapsedMsec = m_helper_start_time.elapsed(); restartTimer = m_helper_restart_timer; } else if (helper == m_helper64_process) { - path = m_helper64_exe_path; - elapsedMsec = m_helper64_start_time.elapsed(); + path = m_helper64_exe_path; + elapsedMsec = m_helper64_start_time.elapsed(); restartTimer = m_helper64_restart_timer; } else { qFatal("OverlayPrivateWin: unknown QProcess found in onHelperProcessExited()."); } - const char *helperErrString = OverlayHelperErrorToString(static_cast<OverlayHelperError>(exitCode)); - qWarning("OverlayPrivateWin: overlay helper process '%s' exited (%s) with status code %s.", - qPrintable(path), - exitStatusString(exitStatus), - helperErrString ? helperErrString : qPrintable(QString::number(exitCode))); + const char *helperErrString = OverlayHelperErrorToString(static_cast< OverlayHelperError >(exitCode)); + qWarning("OverlayPrivateWin: overlay helper process '%s' exited (%s) with status code %s.", qPrintable(path), + exitStatusString(exitStatus), helperErrString ? helperErrString : qPrintable(QString::number(exitCode))); // If the helper process exited while we're in 'active' // mode, restart it. @@ -282,10 +277,10 @@ void OverlayPrivateWin::onHelperProcessExited(int exitCode, QProcess::ExitStatus qint64 cooldownMsec = (qint64) g.s.iOverlayWinHelperRestartCooldownMsec; if (elapsedMsec < cooldownMsec) { qint64 delayMsec = cooldownMsec - elapsedMsec; - qWarning("OverlayPrivateWin: waiting %llu seconds until restarting helper process '%s'. last restart was %llu seconds ago.", - (unsigned long long) delayMsec/1000ULL, - qPrintable(path), - (unsigned long long) elapsedMsec/1000ULL); + qWarning("OverlayPrivateWin: waiting %llu seconds until restarting helper process '%s'. last restart was " + "%llu seconds ago.", + (unsigned long long) delayMsec / 1000ULL, qPrintable(path), + (unsigned long long) elapsedMsec / 1000ULL); if (!restartTimer->isActive()) { restartTimer->start(delayMsec); } @@ -300,7 +295,7 @@ void OverlayPrivateWin::onDelayedRestartTimerTriggered() { return; } - QTimer *timer = qobject_cast<QTimer *>(sender()); + QTimer *timer = qobject_cast< QTimer * >(sender()); QProcess *helper = nullptr; if (timer == m_helper_restart_timer) { @@ -323,7 +318,7 @@ void Overlay::platformInit() { void Overlay::setActiveInternal(bool act) { if (d) { // Only act if the private instance has been created already - static_cast<OverlayPrivateWin *>(d)->setActive(act); + static_cast< OverlayPrivateWin * >(d)->setActive(act); } } diff --git a/src/mumble/Overlay_win.h b/src/mumble/Overlay_win.h index a31e7f782..a6203faf3 100644 --- a/src/mumble/Overlay_win.h +++ b/src/mumble/Overlay_win.h @@ -10,47 +10,47 @@ #include "win.h"
+#include <QElapsedTimer>
+#include <QProcess>
#include <QString>
#include <QStringList>
-#include <QProcess>
#include <QTimer>
-#include <QElapsedTimer>
class OverlayPrivateWin : public OverlayPrivate {
- private:
- Q_OBJECT
- Q_DISABLE_COPY(OverlayPrivateWin)
-
- public:
- void setActive(bool);
- OverlayPrivateWin(QObject *);
- ~OverlayPrivateWin();
-
- public slots:
- void onHelperProcessStarted();
- void onHelperProcessError(QProcess::ProcessError);
- void onHelperProcessExited(int exitCode, QProcess::ExitStatus exitStatus);
- void onDelayedRestartTimerTriggered();
-
- protected:
- QProcess *m_helper_process;
- QString m_helper_exe_path;
- QStringList m_helper_exe_args;
- QElapsedTimer m_helper_start_time;
- QTimer *m_helper_restart_timer;
- bool m_helper_enabled;
-
- QProcess *m_helper64_process;
- QString m_helper64_exe_path;
- QStringList m_helper64_exe_args;
- QElapsedTimer m_helper64_start_time;
- QTimer *m_helper64_restart_timer;
- bool m_helper64_enabled;
-
- HANDLE m_mumble_handle;
- bool m_active;
-
- void startHelper(QProcess *helper);
+private:
+ Q_OBJECT
+ Q_DISABLE_COPY(OverlayPrivateWin)
+
+public:
+ void setActive(bool);
+ OverlayPrivateWin(QObject *);
+ ~OverlayPrivateWin();
+
+public slots:
+ void onHelperProcessStarted();
+ void onHelperProcessError(QProcess::ProcessError);
+ void onHelperProcessExited(int exitCode, QProcess::ExitStatus exitStatus);
+ void onDelayedRestartTimerTriggered();
+
+protected:
+ QProcess *m_helper_process;
+ QString m_helper_exe_path;
+ QStringList m_helper_exe_args;
+ QElapsedTimer m_helper_start_time;
+ QTimer *m_helper_restart_timer;
+ bool m_helper_enabled;
+
+ QProcess *m_helper64_process;
+ QString m_helper64_exe_path;
+ QStringList m_helper64_exe_args;
+ QElapsedTimer m_helper64_start_time;
+ QTimer *m_helper64_restart_timer;
+ bool m_helper64_enabled;
+
+ HANDLE m_mumble_handle;
+ bool m_active;
+
+ void startHelper(QProcess *helper);
};
#endif
diff --git a/src/mumble/PAAudio.cpp b/src/mumble/PAAudio.cpp index dcc424287..83f9c7b70 100644 --- a/src/mumble/PAAudio.cpp +++ b/src/mumble/PAAudio.cpp @@ -5,53 +5,65 @@ #include "PAAudio.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" #ifdef Q_CC_GNU -# define RESOLVE(var) {var = reinterpret_cast<__typeof__(var)>(qlPortAudio.resolve(#var)); if (!var) return; } +# define RESOLVE(var) \ + { \ + var = reinterpret_cast< __typeof__(var) >(qlPortAudio.resolve(#var)); \ + if (!var) \ + return; \ + } #else -# define RESOLVE(var) { *reinterpret_cast<void **>(&var) = static_cast<void *>(qlPortAudio.resolve(#var)); if (!var) return; } +# define RESOLVE(var) \ + { \ + *reinterpret_cast< void ** >(&var) = static_cast< void * >(qlPortAudio.resolve(#var)); \ + if (!var) \ + return; \ + } #endif -static std::unique_ptr<PortAudioSystem> pas; +static std::unique_ptr< PortAudioSystem > pas; class PortAudioInputRegistrar : public AudioInputRegistrar { - private: - AudioInput *create() Q_DECL_OVERRIDE; - const QList<audioDevice> getDeviceChoices() Q_DECL_OVERRIDE; - void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; - bool canEcho(const QString &) const Q_DECL_OVERRIDE; - - public: - PortAudioInputRegistrar(); +private: + AudioInput *create() Q_DECL_OVERRIDE; + const QList< audioDevice > getDeviceChoices() Q_DECL_OVERRIDE; + void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; + bool canEcho(const QString &) const Q_DECL_OVERRIDE; + +public: + PortAudioInputRegistrar(); }; class PortAudioOutputRegistrar : public AudioOutputRegistrar { - private: - AudioOutput *create() Q_DECL_OVERRIDE; - const QList<audioDevice> getDeviceChoices() Q_DECL_OVERRIDE; - void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; +private: + AudioOutput *create() Q_DECL_OVERRIDE; + const QList< audioDevice > getDeviceChoices() Q_DECL_OVERRIDE; + void setDeviceChoice(const QVariant &, Settings &) Q_DECL_OVERRIDE; - public: - PortAudioOutputRegistrar(); +public: + PortAudioOutputRegistrar(); }; class PortAudioInit : public DeferInit { - private: - std::unique_ptr<PortAudioInputRegistrar> airPortAudio; - std::unique_ptr<PortAudioOutputRegistrar> aorPortAudio; - void initialize(); - void destroy(); +private: + std::unique_ptr< PortAudioInputRegistrar > airPortAudio; + std::unique_ptr< PortAudioOutputRegistrar > aorPortAudio; + void initialize(); + void destroy(); }; -PortAudioInputRegistrar::PortAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("PortAudio")) {} +PortAudioInputRegistrar::PortAudioInputRegistrar() : AudioInputRegistrar(QLatin1String("PortAudio")) { +} AudioInput *PortAudioInputRegistrar::create() { return new PortAudioInput(); } -const QList<audioDevice> PortAudioInputRegistrar::getDeviceChoices() { +const QList< audioDevice > PortAudioInputRegistrar::getDeviceChoices() { return pas->enumerateDevices(true, g.s.iPortAudioInput); } @@ -63,13 +75,14 @@ bool PortAudioInputRegistrar::canEcho(const QString &) const { return false; } -PortAudioOutputRegistrar::PortAudioOutputRegistrar() : AudioOutputRegistrar(QLatin1String("PortAudio")) {} +PortAudioOutputRegistrar::PortAudioOutputRegistrar() : AudioOutputRegistrar(QLatin1String("PortAudio")) { +} AudioOutput *PortAudioOutputRegistrar::create() { return new PortAudioOutput(); } -const QList<audioDevice> PortAudioOutputRegistrar::getDeviceChoices() { +const QList< audioDevice > PortAudioOutputRegistrar::getDeviceChoices() { return pas->enumerateDevices(false, g.s.iPortAudioOutput); } @@ -101,9 +114,7 @@ void PortAudioInit::destroy() { // Instantiate PortAudioSystem, PortAudioInputRegistrar and PortAudioOutputRegistrar static PortAudioInit pai; -PortAudioSystem::PortAudioSystem() - : bOk(false) -{ +PortAudioSystem::PortAudioSystem() : bOk(false) { QStringList alternatives; #ifdef Q_OS_WIN alternatives << QLatin1String("portaudio_x64.dll"); @@ -157,13 +168,14 @@ PortAudioSystem::~PortAudioSystem() { if (bOk) { const auto ret = Pa_Terminate(); if (ret != paNoError) { - qWarning("PortAudioSystem: failed to terminate library - Pa_Terminate() returned: %s", Pa_GetErrorText(ret)); + qWarning("PortAudioSystem: failed to terminate library - Pa_Terminate() returned: %s", + Pa_GetErrorText(ret)); } } } -const QList<audioDevice> PortAudioSystem::enumerateDevices(const bool input, const PaDeviceIndex current) { - QList<audioDevice> audioDevices; +const QList< audioDevice > PortAudioSystem::enumerateDevices(const bool input, const PaDeviceIndex current) { + QList< audioDevice > audioDevices; if (!bOk) { return audioDevices; @@ -185,7 +197,8 @@ const QList<audioDevice> PortAudioSystem::enumerateDevices(const bool input, con } if ((input && (deviceInfo->maxInputChannels > 0)) || (!input && (deviceInfo->maxOutputChannels > 0))) { - audioDevices << audioDevice(QLatin1String(apiInfo->name) + QLatin1String(": ") + QLatin1String(deviceInfo->name), deviceIndex); + audioDevices << audioDevice( + QLatin1String(apiInfo->name) + QLatin1String(": ") + QLatin1String(deviceInfo->name), deviceIndex); } } } @@ -211,7 +224,8 @@ bool PortAudioSystem::isStreamRunning(PaStream *stream) { if (ret == 1) { return true; } else if (ret != 0) { - qWarning("PortAudioSystem: failed to determine stream status - Pa_IsStreamActive() returned: %s", Pa_GetErrorText(ret)); + qWarning("PortAudioSystem: failed to determine stream status - Pa_IsStreamActive() returned: %s", + Pa_GetErrorText(ret)); } return false; @@ -231,13 +245,16 @@ int PortAudioSystem::openStream(PaStream **stream, PaDeviceIndex device, const u const auto *devInfo = Pa_GetDeviceInfo(device); if (!devInfo) { - qWarning("PortAudioSystem: failed to retrieve info about device %d - Pa_GetDeviceInfo() returned: nullptr", device); + qWarning("PortAudioSystem: failed to retrieve info about device %d - Pa_GetDeviceInfo() returned: nullptr", + device); return 0; } const auto *apiInfo = Pa_GetHostApiInfo(devInfo->hostApi); if (!apiInfo) { - qWarning("PortAudioSystem: failed to retrieve info about API %d (device %d) - Pa_GetHostApiInfo() returned: nullptr", devInfo->hostApi, device); + qWarning( + "PortAudioSystem: failed to retrieve info about API %d (device %d) - Pa_GetHostApiInfo() returned: nullptr", + devInfo->hostApi, device); return 0; } @@ -251,12 +268,14 @@ int PortAudioSystem::openStream(PaStream **stream, PaDeviceIndex device, const u streamPar.channelCount = 2; } - streamPar.device = device; - streamPar.sampleFormat = paFloat32; + streamPar.device = device; + streamPar.sampleFormat = paFloat32; streamPar.suggestedLatency = (isInput ? devInfo->defaultLowInputLatency : devInfo->defaultLowOutputLatency); streamPar.hostApiSpecificStreamInfo = nullptr; - const auto ret = Pa_OpenStream(stream, isInput ? &streamPar : nullptr, isInput ? nullptr : &streamPar, SAMPLE_RATE, frameSize, paClipOff | paDitherOff, &streamCallback, reinterpret_cast<void *>(isInput)); + const auto ret = + Pa_OpenStream(stream, isInput ? &streamPar : nullptr, isInput ? nullptr : &streamPar, SAMPLE_RATE, frameSize, + paClipOff | paDitherOff, &streamCallback, reinterpret_cast< void * >(isInput)); if (ret != paNoError) { qWarning("PortAudioSystem: failed to open stream - Pa_OpenStream() returned: %s", Pa_GetErrorText(ret)); *stream = nullptr; @@ -318,16 +337,17 @@ bool PortAudioSystem::stopStream(PaStream *stream) { return true; } -int PortAudioSystem::streamCallback(const void *input, void *output, unsigned long frames, const PaStreamCallbackTimeInfo *, PaStreamCallbackFlags, void *isInput) { +int PortAudioSystem::streamCallback(const void *input, void *output, unsigned long frames, + const PaStreamCallbackTimeInfo *, PaStreamCallbackFlags, void *isInput) { if (isInput) { - auto const pai = dynamic_cast<PortAudioInput *>(g.ai.get()); + auto const pai = dynamic_cast< PortAudioInput * >(g.ai.get()); if (!pai) { return paAbort; } pai->process(frames, input); } else { - auto const pao = dynamic_cast<PortAudioOutput *>(g.ao.get()); + auto const pao = dynamic_cast< PortAudioOutput * >(g.ao.get()); if (!pao) { return paAbort; } @@ -338,16 +358,14 @@ int PortAudioSystem::streamCallback(const void *input, void *output, unsigned lo return paContinue; } -PortAudioInput::PortAudioInput() - : stream(nullptr) -{ +PortAudioInput::PortAudioInput() : stream(nullptr) { iMicChannels = pas->openStream(&stream, g.s.iPortAudioInput, iFrameSize, true); if (!iMicChannels) { qWarning("PortAudioInput: failed to open stream"); return; } - iMicFreq = SAMPLE_RATE; + iMicFreq = SAMPLE_RATE; eMicFormat = SampleFloat; initializeMixer(); @@ -391,22 +409,17 @@ void PortAudioInput::run() { qmWait.unlock(); } -PortAudioOutput::PortAudioOutput() - : stream(nullptr) -{ +PortAudioOutput::PortAudioOutput() : stream(nullptr) { iChannels = pas->openStream(&stream, g.s.iPortAudioOutput, iFrameSize, false); if (!iChannels) { qWarning("PortAudioOutput: failed to open stream"); return; } - iMixerFreq = SAMPLE_RATE; + iMixerFreq = SAMPLE_RATE; eSampleFormat = SampleFloat; - const uint32_t channelsMask[] { - SPEAKER_FRONT_LEFT, - SPEAKER_FRONT_RIGHT - }; + const uint32_t channelsMask[]{ SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT }; initializeMixer(channelsMask); diff --git a/src/mumble/PAAudio.h b/src/mumble/PAAudio.h index 0059d2f6b..78790d964 100644 --- a/src/mumble/PAAudio.h +++ b/src/mumble/PAAudio.h @@ -17,78 +17,86 @@ class PortAudioInit; class PortAudioSystem : public QObject { - friend PortAudioInit; - private: - Q_OBJECT - Q_DISABLE_COPY(PortAudioSystem) - protected: - bool bOk; - QMutex qmWait; - QLibrary qlPortAudio; - QWaitCondition qwcWait; - - static int streamCallback(const void *input, void *output, unsigned long frames, const PaStreamCallbackTimeInfo *, PaStreamCallbackFlags statusFlags, void *isInput); - - const char *(*Pa_GetVersionText)(); - const char *(*Pa_GetErrorText)(PaError errorCode); - PaError (*Pa_Initialize)(); - PaError (*Pa_Terminate)(); - PaError (*Pa_OpenStream)(PaStream **stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, double sampleRate, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, void *userData); - PaError (*Pa_CloseStream)(PaStream *stream); - PaError (*Pa_StartStream)(PaStream *stream); - PaError (*Pa_StopStream)(PaStream *stream); - PaError (*Pa_IsStreamActive)(PaStream *stream); - PaDeviceIndex (*Pa_GetDefaultInputDevice)(); - PaDeviceIndex (*Pa_GetDefaultOutputDevice)(); - PaDeviceIndex (*Pa_HostApiDeviceIndexToDeviceIndex)(PaHostApiIndex hostApi, int hostApiDeviceIndex); - PaHostApiIndex (*Pa_GetHostApiCount)(); - const PaHostApiInfo *(*Pa_GetHostApiInfo)(PaHostApiIndex hostApi); - const PaDeviceInfo *(*Pa_GetDeviceInfo)(PaDeviceIndex device); - public: - const QList<audioDevice> enumerateDevices(const bool input, const PaDeviceIndex current); - - bool isStreamRunning(PaStream *stream); - - int openStream(PaStream **stream, PaDeviceIndex device, const uint32_t frameSize, const bool isInput); - bool closeStream(PaStream *stream); - - bool startStream(PaStream *stream); - bool stopStream(PaStream *stream); - - PortAudioSystem(); - ~PortAudioSystem(); + friend PortAudioInit; + +private: + Q_OBJECT + Q_DISABLE_COPY(PortAudioSystem) +protected: + bool bOk; + QMutex qmWait; + QLibrary qlPortAudio; + QWaitCondition qwcWait; + + static int streamCallback(const void *input, void *output, unsigned long frames, const PaStreamCallbackTimeInfo *, + PaStreamCallbackFlags statusFlags, void *isInput); + + const char *(*Pa_GetVersionText)(); + const char *(*Pa_GetErrorText)(PaError errorCode); + PaError (*Pa_Initialize)(); + PaError (*Pa_Terminate)(); + PaError (*Pa_OpenStream)(PaStream **stream, const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, double sampleRate, + unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, + void *userData); + PaError (*Pa_CloseStream)(PaStream *stream); + PaError (*Pa_StartStream)(PaStream *stream); + PaError (*Pa_StopStream)(PaStream *stream); + PaError (*Pa_IsStreamActive)(PaStream *stream); + PaDeviceIndex (*Pa_GetDefaultInputDevice)(); + PaDeviceIndex (*Pa_GetDefaultOutputDevice)(); + PaDeviceIndex (*Pa_HostApiDeviceIndexToDeviceIndex)(PaHostApiIndex hostApi, int hostApiDeviceIndex); + PaHostApiIndex (*Pa_GetHostApiCount)(); + const PaHostApiInfo *(*Pa_GetHostApiInfo)(PaHostApiIndex hostApi); + const PaDeviceInfo *(*Pa_GetDeviceInfo)(PaDeviceIndex device); + +public: + const QList< audioDevice > enumerateDevices(const bool input, const PaDeviceIndex current); + + bool isStreamRunning(PaStream *stream); + + int openStream(PaStream **stream, PaDeviceIndex device, const uint32_t frameSize, const bool isInput); + bool closeStream(PaStream *stream); + + bool startStream(PaStream *stream); + bool stopStream(PaStream *stream); + + PortAudioSystem(); + ~PortAudioSystem(); }; class PortAudioInput : public AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(PortAudioInput) - protected: - QMutex qmWait; - QWaitCondition qwcSleep; - PaStream *stream; - public: - void process(const uint32_t frames, const void *buffer); - void run() Q_DECL_OVERRIDE; - PortAudioInput(); - ~PortAudioInput() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(PortAudioInput) +protected: + QMutex qmWait; + QWaitCondition qwcSleep; + PaStream *stream; + +public: + void process(const uint32_t frames, const void *buffer); + void run() Q_DECL_OVERRIDE; + PortAudioInput(); + ~PortAudioInput() Q_DECL_OVERRIDE; }; class PortAudioOutput : public AudioOutput { - private: - Q_OBJECT - Q_DISABLE_COPY(PortAudioOutput) - protected: - QMutex qmWait; - QWaitCondition qwcSleep; - PaStream *stream; - public: - void process(const uint32_t frames, void *buffer); - void run() Q_DECL_OVERRIDE; - PortAudioOutput(); - ~PortAudioOutput() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(PortAudioOutput) +protected: + QMutex qmWait; + QWaitCondition qwcSleep; + PaStream *stream; + +public: + void process(const uint32_t frames, void *buffer); + void run() Q_DECL_OVERRIDE; + PortAudioOutput(); + ~PortAudioOutput() Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/PTTButtonWidget.cpp b/src/mumble/PTTButtonWidget.cpp index 690c5c676..a8edbcb4a 100644 --- a/src/mumble/PTTButtonWidget.cpp +++ b/src/mumble/PTTButtonWidget.cpp @@ -7,8 +7,7 @@ #include "Global.h" -PTTButtonWidget::PTTButtonWidget(QWidget *p) : - QWidget(p) { +PTTButtonWidget::PTTButtonWidget(QWidget *p) : QWidget(p) { setupUi(this); setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint); diff --git a/src/mumble/PTTButtonWidget.h b/src/mumble/PTTButtonWidget.h index 537bfdc80..038757d93 100644 --- a/src/mumble/PTTButtonWidget.h +++ b/src/mumble/PTTButtonWidget.h @@ -9,17 +9,18 @@ #include "ui_PTTButtonWidget.h" class PTTButtonWidget : public QWidget, public Ui::qwPTTButtonWidget { - Q_OBJECT - Q_DISABLE_COPY(PTTButtonWidget) - protected: - void closeEvent(QCloseEvent *e) Q_DECL_OVERRIDE; - public: - PTTButtonWidget(QWidget *p = 0); - public slots: - void on_qpbPushToTalk_pressed(); - void on_qpbPushToTalk_released(); - signals: - void triggered(bool checked, QVariant); + Q_OBJECT + Q_DISABLE_COPY(PTTButtonWidget) +protected: + void closeEvent(QCloseEvent *e) Q_DECL_OVERRIDE; + +public: + PTTButtonWidget(QWidget *p = 0); +public slots: + void on_qpbPushToTalk_pressed(); + void on_qpbPushToTalk_released(); +signals: + void triggered(bool checked, QVariant); }; -#endif // PTTBUTTONWIDGET_H_ +#endif // PTTBUTTONWIDGET_H_ diff --git a/src/mumble/PathListWidget.cpp b/src/mumble/PathListWidget.cpp index 59811573d..eb6acdc29 100644 --- a/src/mumble/PathListWidget.cpp +++ b/src/mumble/PathListWidget.cpp @@ -14,9 +14,7 @@ #include <QtGui/QDragMoveEvent>
#include <QtGui/QDropEvent>
-PathListWidget::PathListWidget(QWidget *parent)
- : QListWidget(parent)
- , pathType(FILE_EXE) {
+PathListWidget::PathListWidget(QWidget *parent) : QListWidget(parent), pathType(FILE_EXE) {
setAcceptDrops(true);
}
@@ -30,8 +28,8 @@ void PathListWidget::addFilePath(const QString &path) { for (int i = 0; i < count(); i++) {
qslIdentifiers << item(i)->data(Qt::UserRole).toString();
}
- if (! qslIdentifiers.contains(qsAppIdentifier)) {
- OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier);
+ if (!qslIdentifiers.contains(qsAppIdentifier)) {
+ OverlayAppInfo oai = OverlayAppInfo::applicationInfoForId(qsAppIdentifier);
QListWidgetItem *qlwiApplication = new QListWidgetItem(oai.qiIcon, oai.qsDisplayName, this);
qlwiApplication->setData(Qt::UserRole, QVariant(qsAppIdentifier));
setCurrentItem(qlwiApplication);
@@ -44,7 +42,7 @@ void PathListWidget::addFolderPath(const QString &path) { for (int i = 0; i < count(); i++) {
qslIdentifiers << item(i)->data(Qt::UserRole).toString();
}
- if (! dir.isEmpty() && ! qslIdentifiers.contains(dir)) {
+ if (!dir.isEmpty() && !qslIdentifiers.contains(dir)) {
QListWidgetItem *qlwiPath = new QListWidgetItem(QIcon(), QDir(dir).path(), this);
qlwiPath->setData(Qt::UserRole, QVariant(dir));
setCurrentItem(qlwiPath);
diff --git a/src/mumble/PathListWidget.h b/src/mumble/PathListWidget.h index c537cca37..6753f2274 100644 --- a/src/mumble/PathListWidget.h +++ b/src/mumble/PathListWidget.h @@ -20,11 +20,12 @@ class PathListWidget : public QListWidget { public:
enum PathType { FILE_EXE, FOLDER };
- PathListWidget(QWidget *parent=0);
+ PathListWidget(QWidget *parent = 0);
void setPathType(PathType type);
virtual void dragEnterEvent(QDragEnterEvent *event) Q_DECL_OVERRIDE;
virtual void dragMoveEvent(QDragMoveEvent *event) Q_DECL_OVERRIDE;
virtual void dropEvent(QDropEvent *event) Q_DECL_OVERRIDE;
+
private:
Q_OBJECT
Q_DISABLE_COPY(PathListWidget)
diff --git a/src/mumble/Plugins.cpp b/src/mumble/Plugins.cpp index 690d563a0..f490570ea 100644 --- a/src/mumble/Plugins.cpp +++ b/src/mumble/Plugins.cpp @@ -5,34 +5,35 @@ #include "Plugins.h" +#include "../../plugins/mumble_plugin.h" #include "Log.h" #include "MainWindow.h" #include "Message.h" -#include "ServerHandler.h" -#include "../../plugins/mumble_plugin.h" -#include "WebFetch.h" #include "MumbleApplication.h" +#include "ServerHandler.h" #include "Utils.h" +#include "WebFetch.h" #ifdef USE_MANUAL_PLUGIN - #include "ManualPlugin.h" +# include "ManualPlugin.h" #endif #include <QtCore/QLibrary> #include <QtCore/QUrlQuery> #ifdef Q_OS_WIN -# include <QtCore/QTemporaryFile> +# include <QtCore/QTemporaryFile> #endif #include <QtWidgets/QMessageBox> #include <QtXml/QDomDocument> #ifdef Q_OS_WIN -# include <softpub.h> -# include <tlhelp32.h> +# include <softpub.h> +# include <tlhelp32.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const QString PluginConfig::name = QLatin1String("PluginConfig"); @@ -57,20 +58,20 @@ struct PluginInfo { }; PluginInfo::PluginInfo() { - locked = false; + locked = false; enabled = false; - p = nullptr; - p2 = nullptr; - pqt = nullptr; + p = nullptr; + p2 = nullptr; + pqt = nullptr; } struct PluginFetchMeta { QString hash; QString path; - + PluginFetchMeta(const QString &hash_ = QString(), const QString &path_ = QString()) - : hash(hash_) - , path(path_) { /* Empty */ } + : hash(hash_), path(path_) { /* Empty */ + } }; @@ -105,8 +106,8 @@ void PluginConfig::save() const { s.bTransmitPosition = qcbTransmit->isChecked(); s.qmPositionalAudioPlugins.clear(); - QList<QTreeWidgetItem *> list = qtwPlugins->findItems(QString(), Qt::MatchContains); - foreach(QTreeWidgetItem *i, list) { + QList< QTreeWidgetItem * > list = qtwPlugins->findItems(QString(), Qt::MatchContains); + foreach (QTreeWidgetItem *i, list) { bool enabled = (i->checkState(1) == Qt::Checked); PluginInfo *pi = pluginForItem(i); @@ -119,7 +120,7 @@ void PluginConfig::save() const { PluginInfo *PluginConfig::pluginForItem(QTreeWidgetItem *i) const { if (i) { - foreach(PluginInfo *pi, g.p->qlPlugins) { + foreach (PluginInfo *pi, g.p->qlPlugins) { if (pi->filename == i->data(0, Qt::UserRole).toString()) return pi; } @@ -134,7 +135,7 @@ void PluginConfig::on_qpbConfig_clicked() { pi = pluginForItem(qtwPlugins->currentItem()); } - if (! pi) + if (!pi) return; if (pi->pqt && pi->pqt->config) { @@ -142,7 +143,8 @@ void PluginConfig::on_qpbConfig_clicked() { } else if (pi->p->config) { pi->p->config(0); } else { - QMessageBox::information(this, QLatin1String("Mumble"), tr("Plugin has no configure function."), QMessageBox::Ok, QMessageBox::NoButton); + QMessageBox::information(this, QLatin1String("Mumble"), tr("Plugin has no configure function."), + QMessageBox::Ok, QMessageBox::NoButton); } } @@ -153,7 +155,7 @@ void PluginConfig::on_qpbAbout_clicked() { pi = pluginForItem(qtwPlugins->currentItem()); } - if (! pi) + if (!pi) return; if (pi->pqt && pi->pqt->about) { @@ -161,7 +163,8 @@ void PluginConfig::on_qpbAbout_clicked() { } else if (pi->p->about) { pi->p->about(0); } else { - QMessageBox::information(this, QLatin1String("Mumble"), tr("Plugin has no about function."), QMessageBox::Ok, QMessageBox::NoButton); + QMessageBox::information(this, QLatin1String("Mumble"), tr("Plugin has no about function."), QMessageBox::Ok, + QMessageBox::NoButton); } } @@ -174,7 +177,7 @@ void PluginConfig::refillPluginList() { QReadLocker lock(&g.p->qrwlPlugins); qtwPlugins->clear(); - foreach(PluginInfo *pi, g.p->qlPlugins) { + foreach (PluginInfo *pi, g.p->qlPlugins) { QTreeWidgetItem *i = new QTreeWidgetItem(qtwPlugins); i->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable); i->setCheckState(1, pi->enabled ? Qt::Checked : Qt::Unchecked); @@ -190,7 +193,7 @@ void PluginConfig::refillPluginList() { void PluginConfig::on_qtwPlugins_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *) { QReadLocker lock(&g.p->qrwlPlugins); - PluginInfo *pi=pluginForItem(current); + PluginInfo *pi = pluginForItem(current); if (pi) { bool showAbout = false; if (pi->p->about) { @@ -216,30 +219,32 @@ void PluginConfig::on_qtwPlugins_currentItemChanged(QTreeWidgetItem *current, QT } Plugins::Plugins(QObject *p) : QObject(p) { - QTimer *timer=new QTimer(this); + QTimer *timer = new QTimer(this); timer->setObjectName(QLatin1String("Timer")); timer->start(500); locked = prevlocked = nullptr; - bValid = false; - iPluginTry = 0; - for (int i=0;i<3;i++) - fPosition[i]=fFront[i]=fTop[i]= 0.0; + bValid = false; + iPluginTry = 0; + for (int i = 0; i < 3; i++) + fPosition[i] = fFront[i] = fTop[i] = 0.0; QMetaObject::connectSlotsByName(this); #ifdef QT_NO_DEBUG -#ifndef PLUGIN_PATH - qsSystemPlugins=QString::fromLatin1("%1/plugins").arg(MumbleApplication::instance()->applicationVersionRootPath()); -#ifdef Q_OS_MAC - qsSystemPlugins=QString::fromLatin1("%1/../Plugins").arg(qApp->applicationDirPath()); -#endif -#else - qsSystemPlugins=QLatin1String(MUMTEXT(PLUGIN_PATH)); -#endif +# ifndef PLUGIN_PATH + qsSystemPlugins = + QString::fromLatin1("%1/plugins").arg(MumbleApplication::instance()->applicationVersionRootPath()); +# ifdef Q_OS_MAC + qsSystemPlugins = QString::fromLatin1("%1/../Plugins").arg(qApp->applicationDirPath()); +# endif +# else + qsSystemPlugins = QLatin1String(MUMTEXT(PLUGIN_PATH)); +# endif qsUserPlugins = g.qdBasePath.absolutePath() + QLatin1String("/Plugins"); #else - qsSystemPlugins = QString::fromLatin1("%1/plugins").arg(MumbleApplication::instance()->applicationVersionRootPath()); - qsUserPlugins = QString(); + qsSystemPlugins = + QString::fromLatin1("%1/plugins").arg(MumbleApplication::instance()->applicationVersionRootPath()); + qsUserPlugins = QString(); #endif #ifdef Q_OS_WIN @@ -256,7 +261,7 @@ Plugins::Plugins(QObject *p) : QObject(p) { TOKEN_PRIVILEGES tp; LUID luid; - cbPrevious=sizeof(TOKEN_PRIVILEGES); + cbPrevious = sizeof(TOKEN_PRIVILEGES); LookupPrivilegeValue(nullptr, SE_DEBUG_NAME, &luid); @@ -279,7 +284,7 @@ Plugins::~Plugins() { void Plugins::clearPlugins() { QWriteLocker lock(&g.p->qrwlPlugins); - foreach(PluginInfo *pi, qlPlugins) { + foreach (PluginInfo *pi, qlPlugins) { if (pi->locked) pi->p->unlock(); pi->lib.unload(); @@ -293,7 +298,7 @@ void Plugins::rescanPlugins() { QWriteLocker lock(&g.p->qrwlPlugins); prevlocked = locked = nullptr; - bValid = false; + bValid = false; QDir qd(qsSystemPlugins, QString(), QDir::Name, QDir::Files | QDir::Readable); #ifdef QT_NO_DEBUG @@ -303,16 +308,16 @@ void Plugins::rescanPlugins() { QFileInfoList libs = qd.entryInfoList(); #endif - QSet<QString> evaluated; - foreach(const QFileInfo &libinfo, libs) { - QString fname = libinfo.fileName(); + QSet< QString > evaluated; + foreach (const QFileInfo &libinfo, libs) { + QString fname = libinfo.fileName(); QString libname = libinfo.absoluteFilePath(); if (!evaluated.contains(fname) && QLibrary::isLibrary(libname)) { PluginInfo *pi = new PluginInfo(); pi->lib.setFileName(libname); pi->filename = fname; if (pi->lib.load()) { - mumblePluginFunc mpf = reinterpret_cast<mumblePluginFunc>(pi->lib.resolve("getMumblePlugin")); + mumblePluginFunc mpf = reinterpret_cast< mumblePluginFunc >(pi->lib.resolve("getMumblePlugin")); if (mpf) { evaluated.insert(fname); pi->p = mpf(); @@ -322,12 +327,12 @@ void Plugins::rescanPlugins() { // the game the plugin was written for now provides positional audio via the // link plugin (see null_plugin.cpp). if (pi->p && pi->p->magic == MUMBLE_PLUGIN_MAGIC && pi->p->shortname != L"Retracted") { - pi->description = QString::fromStdWString(pi->p->description); - pi->shortname = QString::fromStdWString(pi->p->shortname); - pi->enabled = g.s.qmPositionalAudioPlugins.value(pi->filename, true); + pi->shortname = QString::fromStdWString(pi->p->shortname); + pi->enabled = g.s.qmPositionalAudioPlugins.value(pi->filename, true); - mumblePlugin2Func mpf2 = reinterpret_cast<mumblePlugin2Func>(pi->lib.resolve("getMumblePlugin2")); + mumblePlugin2Func mpf2 = + reinterpret_cast< mumblePlugin2Func >(pi->lib.resolve("getMumblePlugin2")); if (mpf2) { pi->p2 = mpf2(); if (pi->p2->magic != MUMBLE_PLUGIN_MAGIC_2) { @@ -335,7 +340,8 @@ void Plugins::rescanPlugins() { } } - mumblePluginQtFunc mpfqt = reinterpret_cast<mumblePluginQtFunc>(pi->lib.resolve("getMumblePluginQt")); + mumblePluginQtFunc mpfqt = + reinterpret_cast< mumblePluginQtFunc >(pi->lib.resolve("getMumblePluginQt")); if (mpfqt) { pi->pqt = mpfqt(); if (pi->pqt->magic != MUMBLE_PLUGIN_MAGIC_QT) { @@ -359,13 +365,13 @@ void Plugins::rescanPlugins() { { #if defined(USE_MANUAL_PLUGIN) // Manual plugin - PluginInfo *pi = new PluginInfo(); - pi->filename = QLatin1String("manual.builtin"); - pi->p = ManualPlugin_getMumblePlugin(); - pi->pqt = ManualPlugin_getMumblePluginQt(); + PluginInfo *pi = new PluginInfo(); + pi->filename = QLatin1String("manual.builtin"); + pi->p = ManualPlugin_getMumblePlugin(); + pi->pqt = ManualPlugin_getMumblePluginQt(); pi->description = QString::fromStdWString(pi->p->description); - pi->shortname = QString::fromStdWString(pi->p->shortname); - pi->enabled = g.s.qmPositionalAudioPlugins.value(pi->filename, true); + pi->shortname = QString::fromStdWString(pi->p->shortname); + pi->enabled = g.s.qmPositionalAudioPlugins.value(pi->filename, true); qlPlugins << pi; #endif } @@ -374,30 +380,30 @@ void Plugins::rescanPlugins() { bool Plugins::fetch() { if (g.bPosTest) { fPosition[0] = fPosition[1] = fPosition[2] = 0.0f; - fFront[0] = 0.0f; - fFront[1] = 0.0f; - fFront[2] = 1.0f; - fTop[0] = 0.0f; - fTop[1] = 1.0f; - fTop[2] = 0.0f; - - for (int i=0;i<3;++i) { + fFront[0] = 0.0f; + fFront[1] = 0.0f; + fFront[2] = 1.0f; + fTop[0] = 0.0f; + fTop[1] = 1.0f; + fTop[2] = 0.0f; + + for (int i = 0; i < 3; ++i) { fCameraPosition[i] = fPosition[i]; - fCameraFront[i] = fFront[i]; - fCameraTop[i] = fTop[i]; + fCameraFront[i] = fFront[i]; + fCameraTop[i] = fTop[i]; } bValid = true; return true; } - if (! locked) { + if (!locked) { bValid = false; return bValid; } QReadLocker lock(&qrwlPlugins); - if (! locked) { + if (!locked) { bValid = false; return bValid; } @@ -408,19 +414,20 @@ bool Plugins::fetch() { bool ok; { QMutexLocker mlock(&qmPluginStrings); - ok = locked->p->fetch(fPosition, fFront, fTop, fCameraPosition, fCameraFront, fCameraTop, ssContext, swsIdentity); + ok = locked->p->fetch(fPosition, fFront, fTop, fCameraPosition, fCameraFront, fCameraTop, ssContext, + swsIdentity); } - if (! ok || bUnlink) { + if (!ok || bUnlink) { lock.unlock(); QWriteLocker wlock(&qrwlPlugins); if (locked) { locked->p->unlock(); locked->locked = false; - prevlocked = locked; - locked = nullptr; - for (int i=0;i<3;i++) - fPosition[i]=fFront[i]=fTop[i]=fCameraPosition[i]=fCameraFront[i]=fCameraTop[i] = 0.0f; + prevlocked = locked; + locked = nullptr; + for (int i = 0; i < 3; i++) + fPosition[i] = fFront[i] = fTop[i] = fCameraPosition[i] = fCameraFront[i] = fCameraTop[i] = 0.0f; } } bValid = ok; @@ -441,16 +448,16 @@ void Plugins::on_Timer_timeout() { { QMutexLocker mlock(&qmPluginStrings); - if (! locked) { + if (!locked) { ssContext.clear(); swsIdentity.clear(); } std::string context; if (locked) - context.assign(u8(QString::fromStdWString(locked->p->shortname)) + static_cast<char>(0) + ssContext); + context.assign(u8(QString::fromStdWString(locked->p->shortname)) + static_cast< char >(0) + ssContext); - if (! g.uiSession) { + if (!g.uiSession) { ssContextSent.clear(); swsIdentitySent.clear(); } else if ((context != ssContextSent) || (swsIdentity != swsIdentitySent)) { @@ -473,7 +480,7 @@ void Plugins::on_Timer_timeout() { return; } - if (! g.s.bTransmitPosition) + if (!g.s.bTransmitPosition) return; lock.unlock(); @@ -486,17 +493,18 @@ void Plugins::on_Timer_timeout() { if (iPluginTry >= qlPlugins.count()) iPluginTry = 0; - std::multimap<std::wstring, unsigned long long int> pids; + std::multimap< std::wstring, unsigned long long int > pids; #if defined(Q_OS_WIN) PROCESSENTRY32 pe; - pe.dwSize = sizeof(pe); + pe.dwSize = sizeof(pe); HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap != INVALID_HANDLE_VALUE) { BOOL ok = Process32First(hSnap, &pe); while (ok) { - pids.insert(std::pair<std::wstring, unsigned long long int>(std::wstring(pe.szExeFile), pe.th32ProcessID)); + pids.insert( + std::pair< std::wstring, unsigned long long int >(std::wstring(pe.szExeFile), pe.th32ProcessID)); ok = Process32Next(hSnap, &pe); } CloseHandle(hSnap); @@ -509,14 +517,14 @@ void Plugins::on_Timer_timeout() { // Check if the entry is a PID // by checking whether it's a number. // If it is not, skip it. - unsigned long long int pid = static_cast<unsigned long long int>(entry.toLongLong(&ok, 10)); + unsigned long long int pid = static_cast< unsigned long long int >(entry.toLongLong(&ok, 10)); if (!ok) { continue; } QString exe = QFile::symLinkTarget(QString(QLatin1String("/proc/%1/exe")).arg(entry)); QFileInfo fi(exe); - QString firstPart = fi.baseName(); + QString firstPart = fi.baseName(); QString completeSuffix = fi.completeSuffix(); QString baseName; if (completeSuffix.isEmpty()) { @@ -547,7 +555,7 @@ void Plugins::on_Timer_timeout() { } if (!baseName.isEmpty()) { - pids.insert(std::pair<std::wstring, unsigned long long int>(baseName.toStdWString(), pid)); + pids.insert(std::pair< std::wstring, unsigned long long int >(baseName.toStdWString(), pid)); } } #endif @@ -558,8 +566,8 @@ void Plugins::on_Timer_timeout() { pi->shortname = QString::fromStdWString(pi->p->shortname); g.l->log(Log::Information, tr("%1 linked.").arg(pi->shortname.toHtmlEscaped())); pi->locked = true; - bUnlink = false; - locked = pi; + bUnlink = false; + locked = pi; } } } @@ -568,21 +576,22 @@ void Plugins::checkUpdates() { QUrl url; url.setPath(QLatin1String("/v1/pa-plugins")); - QList<QPair<QString, QString> > queryItems; - queryItems << qMakePair(QString::fromUtf8("ver"), QString::fromUtf8(QUrl::toPercentEncoding(QString::fromUtf8(MUMBLE_RELEASE)))); + QList< QPair< QString, QString > > queryItems; + queryItems << qMakePair(QString::fromUtf8("ver"), + QString::fromUtf8(QUrl::toPercentEncoding(QString::fromUtf8(MUMBLE_RELEASE)))); #if defined(Q_OS_WIN) -# if defined(Q_OS_WIN64) +# if defined(Q_OS_WIN64) queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("WinX64")); -# else +# else queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("Win32")); -# endif +# endif queryItems << qMakePair(QString::fromUtf8("abi"), QString::fromUtf8(MUMTEXT(_MSC_VER))); #elif defined(Q_OS_MAC) -# if defined(USE_MAC_UNIVERSAL) +# if defined(USE_MAC_UNIVERSAL) queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("MacOSX-Universal")); -# else +# else queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("MacOSX")); -# endif +# endif #else queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("Unix")); #endif @@ -593,7 +602,7 @@ void Plugins::checkUpdates() { query.setQueryItems(queryItems); url.setQuery(query); - WebFetch::fetch(QLatin1String("update"), url, this, SLOT(fetchedUpdatePAPlugins(QByteArray,QUrl))); + WebFetch::fetch(QLatin1String("update"), url, this, SLOT(fetchedUpdatePAPlugins(QByteArray, QUrl))); #else g.mw->msgBox(tr("Skipping plugin update in debug mode.")); #endif @@ -608,8 +617,8 @@ void Plugins::fetchedUpdatePAPlugins(QByteArray data, QUrl) { QDomDocument doc; doc.setContent(data); - QDomElement root=doc.documentElement(); - QDomNode n = root.firstChild(); + QDomElement root = doc.documentElement(); + QDomNode n = root.firstChild(); while (!n.isNull()) { QDomElement e = n.toElement(); if (!e.isNull()) { @@ -627,19 +636,19 @@ void Plugins::fetchedUpdatePAPlugins(QByteArray data, QUrl) { QDir qdu(qsUserPlugins, QString(), QDir::Name, QDir::Files | QDir::Readable); QFileInfoList libs = qd.entryInfoList(); - foreach(const QFileInfo &libinfo, libs) { - QString libname = libinfo.absoluteFilePath(); - QString filename = libinfo.fileName(); + foreach (const QFileInfo &libinfo, libs) { + QString libname = libinfo.absoluteFilePath(); + QString filename = libinfo.fileName(); PluginFetchMeta pfm = qmPluginFetchMeta.value(filename); - QString wanthash = pfm.hash; - if (! wanthash.isNull() && QLibrary::isLibrary(libname)) { + QString wanthash = pfm.hash; + if (!wanthash.isNull() && QLibrary::isLibrary(libname)) { QFile f(libname); if (wanthash.isEmpty()) { // Outdated plugin if (f.exists()) { clearPlugins(); f.remove(); - rescan=true; + rescan = true; } } else if (f.open(QIODevice::ReadOnly)) { QString h = QLatin1String(sha1(f.readAll()).toHex()); @@ -650,7 +659,7 @@ void Plugins::fetchedUpdatePAPlugins(QByteArray data, QUrl) { if (qfuser.exists()) { clearPlugins(); qfuser.remove(); - rescan=true; + rescan = true; } } // Mark for removal from userplugins @@ -662,19 +671,19 @@ void Plugins::fetchedUpdatePAPlugins(QByteArray data, QUrl) { if (qd != qdu) { libs = qdu.entryInfoList(); - foreach(const QFileInfo &libinfo, libs) { - QString libname = libinfo.absoluteFilePath(); - QString filename = libinfo.fileName(); + foreach (const QFileInfo &libinfo, libs) { + QString libname = libinfo.absoluteFilePath(); + QString filename = libinfo.fileName(); PluginFetchMeta pfm = qmPluginFetchMeta.value(filename); - QString wanthash = pfm.hash; - if (! wanthash.isNull() && QLibrary::isLibrary(libname)) { + QString wanthash = pfm.hash; + if (!wanthash.isNull() && QLibrary::isLibrary(libname)) { QFile f(libname); if (wanthash.isEmpty()) { // Outdated plugin if (f.exists()) { clearPlugins(); f.remove(); - rescan=true; + rescan = true; } } else if (f.open(QIODevice::ReadOnly)) { QString h = QLatin1String(sha1(f.readAll()).toHex()); @@ -686,10 +695,10 @@ void Plugins::fetchedUpdatePAPlugins(QByteArray data, QUrl) { } } } - QMap<QString, PluginFetchMeta>::const_iterator i; + QMap< QString, PluginFetchMeta >::const_iterator i; for (i = qmPluginFetchMeta.constBegin(); i != qmPluginFetchMeta.constEnd(); ++i) { PluginFetchMeta pfm = i.value(); - if (! pfm.hash.isEmpty()) { + if (!pfm.hash.isEmpty()) { QUrl pluginDownloadUrl; if (pfm.path.isEmpty()) { pluginDownloadUrl.setPath(QString::fromLatin1("%1").arg(i.key())); @@ -697,7 +706,8 @@ void Plugins::fetchedUpdatePAPlugins(QByteArray data, QUrl) { pluginDownloadUrl.setPath(pfm.path); } - WebFetch::fetch(QLatin1String("pa-plugin-dl"), pluginDownloadUrl, this, SLOT(fetchedPAPluginDL(QByteArray,QUrl))); + WebFetch::fetch(QLatin1String("pa-plugin-dl"), pluginDownloadUrl, this, + SLOT(fetchedPAPluginDL(QByteArray, QUrl))); } } @@ -712,7 +722,7 @@ void Plugins::fetchedPAPluginDL(QByteArray data, QUrl url) { bool rescan = false; const QString &urlPath = url.path(); - QString fname = QFileInfo(urlPath).fileName(); + QString fname = QFileInfo(urlPath).fileName(); if (qmPluginFetchMeta.contains(fname)) { PluginFetchMeta pfm = qmPluginFetchMeta.value(fname); if (pfm.hash == QLatin1String(sha1(data).toHex())) { @@ -724,31 +734,31 @@ void Plugins::fetchedPAPluginDL(QByteArray data, QUrl url) { { QTemporaryFile temp(QDir::tempPath() + QLatin1String("/plugin_XXXXXX.dll")); if (temp.open()) { - tempname = temp.fileName(); + tempname = temp.fileName(); tempnative = QDir::toNativeSeparators(tempname).toStdWString(); temp.write(data); temp.setAutoRemove(false); } } - if (! tempname.isNull()) { + if (!tempname.isNull()) { WINTRUST_FILE_INFO file; ZeroMemory(&file, sizeof(file)); - file.cbStruct = sizeof(file); + file.cbStruct = sizeof(file); file.pcwszFilePath = tempnative.c_str(); WINTRUST_DATA data; ZeroMemory(&data, sizeof(data)); - data.cbStruct = sizeof(data); - data.dwUIChoice = WTD_UI_NONE; + data.cbStruct = sizeof(data); + data.dwUIChoice = WTD_UI_NONE; data.fdwRevocationChecks = WTD_REVOKE_NONE; - data.dwUnionChoice = WTD_CHOICE_FILE; - data.pFile = &file; - data.dwProvFlags = WTD_SAFER_FLAG | WTD_USE_DEFAULT_OSVER_CHECK; - data.dwUIContext = WTD_UICONTEXT_INSTALL; + data.dwUnionChoice = WTD_CHOICE_FILE; + data.pFile = &file; + data.dwProvFlags = WTD_SAFER_FLAG | WTD_USE_DEFAULT_OSVER_CHECK; + data.dwUIContext = WTD_UICONTEXT_INSTALL; static GUID guid = WINTRUST_ACTION_GENERIC_VERIFY_V2; - LONG ts = WinVerifyTrust(0, &guid , &data); + LONG ts = WinVerifyTrust(0, &guid, &data); QFile deltemp(tempname); deltemp.remove(); @@ -775,7 +785,7 @@ void Plugins::fetchedPAPluginDL(QByteArray data, QUrl url) { } } - rescan=true; + rescan = true; } } } diff --git a/src/mumble/Plugins.h b/src/mumble/Plugins.h index 40d9c0bad..2528457ba 100644 --- a/src/mumble/Plugins.h +++ b/src/mumble/Plugins.h @@ -11,79 +11,81 @@ #include "ui_Plugins.h" #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif -#include <QtCore/QObject> #include <QtCore/QMutex> +#include <QtCore/QObject> #include <QtCore/QReadWriteLock> #include <QtCore/QUrl> struct PluginInfo; class PluginConfig : public ConfigWidget, public Ui::PluginConfig { - private: - Q_OBJECT - Q_DISABLE_COPY(PluginConfig) - protected: - void refillPluginList(); - PluginInfo *pluginForItem(QTreeWidgetItem *) const; - public: - /// The unique name of this ConfigWidget - static const QString name; - PluginConfig(Settings &st); - virtual QString title() const Q_DECL_OVERRIDE; - const QString &getName() const Q_DECL_OVERRIDE; - virtual QIcon icon() const Q_DECL_OVERRIDE; - public slots: - void save() const Q_DECL_OVERRIDE; - void load(const Settings &r) Q_DECL_OVERRIDE; - void on_qpbConfig_clicked(); - void on_qpbAbout_clicked(); - void on_qpbReload_clicked(); - void on_qtwPlugins_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *); +private: + Q_OBJECT + Q_DISABLE_COPY(PluginConfig) +protected: + void refillPluginList(); + PluginInfo *pluginForItem(QTreeWidgetItem *) const; + +public: + /// The unique name of this ConfigWidget + static const QString name; + PluginConfig(Settings &st); + virtual QString title() const Q_DECL_OVERRIDE; + const QString &getName() const Q_DECL_OVERRIDE; + virtual QIcon icon() const Q_DECL_OVERRIDE; +public slots: + void save() const Q_DECL_OVERRIDE; + void load(const Settings &r) Q_DECL_OVERRIDE; + void on_qpbConfig_clicked(); + void on_qpbAbout_clicked(); + void on_qpbReload_clicked(); + void on_qtwPlugins_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *); }; struct PluginFetchMeta; class Plugins : public QObject { - friend class PluginConfig; - private: - Q_OBJECT - Q_DISABLE_COPY(Plugins) - protected: - QReadWriteLock qrwlPlugins; - QMutex qmPluginStrings; - QList<PluginInfo *> qlPlugins; - PluginInfo *locked; - PluginInfo *prevlocked; - void clearPlugins(); - int iPluginTry; - QMap<QString, PluginFetchMeta> qmPluginFetchMeta; - QString qsSystemPlugins; - QString qsUserPlugins; + friend class PluginConfig; + +private: + Q_OBJECT + Q_DISABLE_COPY(Plugins) +protected: + QReadWriteLock qrwlPlugins; + QMutex qmPluginStrings; + QList< PluginInfo * > qlPlugins; + PluginInfo *locked; + PluginInfo *prevlocked; + void clearPlugins(); + int iPluginTry; + QMap< QString, PluginFetchMeta > qmPluginFetchMeta; + QString qsSystemPlugins; + QString qsUserPlugins; #ifdef Q_OS_WIN - HANDLE hToken; - TOKEN_PRIVILEGES tpPrevious; - DWORD cbPrevious; + HANDLE hToken; + TOKEN_PRIVILEGES tpPrevious; + DWORD cbPrevious; #endif - public: - std::string ssContext, ssContextSent; - std::wstring swsIdentity, swsIdentitySent; - bool bValid; - bool bUnlink; - float fPosition[3], fFront[3], fTop[3]; - float fCameraPosition[3], fCameraFront[3], fCameraTop[3]; +public: + std::string ssContext, ssContextSent; + std::wstring swsIdentity, swsIdentitySent; + bool bValid; + bool bUnlink; + float fPosition[3], fFront[3], fTop[3]; + float fCameraPosition[3], fCameraFront[3], fCameraTop[3]; - Plugins(QObject *p = nullptr); - ~Plugins() Q_DECL_OVERRIDE; - public slots: - void on_Timer_timeout(); - void rescanPlugins(); - bool fetch(); - void checkUpdates(); - void fetchedUpdatePAPlugins(QByteArray, QUrl); - void fetchedPAPluginDL(QByteArray, QUrl); + Plugins(QObject *p = nullptr); + ~Plugins() Q_DECL_OVERRIDE; +public slots: + void on_Timer_timeout(); + void rescanPlugins(); + bool fetch(); + void checkUpdates(); + void fetchedUpdatePAPlugins(QByteArray, QUrl); + void fetchedPAPluginDL(QByteArray, QUrl); }; #endif diff --git a/src/mumble/PulseAudio.cpp b/src/mumble/PulseAudio.cpp index 713393ed7..4b7d0fe2d 100644 --- a/src/mumble/PulseAudio.cpp +++ b/src/mumble/PulseAudio.cpp @@ -9,74 +9,75 @@ #include "Timer.h" #include "User.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" static const char *mumble_sink_input = "Mumble Speakers"; -static const char *mumble_echo = "Mumble Speakers (Echo)"; +static const char *mumble_echo = "Mumble Speakers (Echo)"; static PulseAudioSystem *pasys = nullptr; #define NBLOCKS 8 class PulseAudioInputRegistrar : public AudioInputRegistrar { - public: - PulseAudioInputRegistrar(); - virtual AudioInput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); - virtual bool canEcho(const QString &) const; +public: + PulseAudioInputRegistrar(); + virtual AudioInput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); + virtual bool canEcho(const QString &) const; }; class PulseAudioOutputRegistrar : public AudioOutputRegistrar { - public: - PulseAudioOutputRegistrar(); - virtual AudioOutput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); - bool canMuteOthers() const; +public: + PulseAudioOutputRegistrar(); + virtual AudioOutput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); + bool canMuteOthers() const; }; class PulseAudioInit : public DeferInit { - public: - PulseAudioInputRegistrar *airPulseAudio; - PulseAudioOutputRegistrar *aorPulseAudio; - void initialize() { - pasys = new PulseAudioSystem(); - pasys->qmWait.lock(); - pasys->qwcWait.wait(&pasys->qmWait, 1000); - pasys->qmWait.unlock(); - if (pasys->bPulseIsGood) { - airPulseAudio = new PulseAudioInputRegistrar(); - aorPulseAudio = new PulseAudioOutputRegistrar(); - } else { - airPulseAudio = nullptr; - aorPulseAudio = nullptr; - delete pasys; - pasys = nullptr; - } - }; - void destroy() { - delete airPulseAudio; - delete aorPulseAudio; +public: + PulseAudioInputRegistrar *airPulseAudio; + PulseAudioOutputRegistrar *aorPulseAudio; + void initialize() { + pasys = new PulseAudioSystem(); + pasys->qmWait.lock(); + pasys->qwcWait.wait(&pasys->qmWait, 1000); + pasys->qmWait.unlock(); + if (pasys->bPulseIsGood) { + airPulseAudio = new PulseAudioInputRegistrar(); + aorPulseAudio = new PulseAudioOutputRegistrar(); + } else { + airPulseAudio = nullptr; + aorPulseAudio = nullptr; delete pasys; pasys = nullptr; - }; + } + }; + void destroy() { + delete airPulseAudio; + delete aorPulseAudio; + delete pasys; + pasys = nullptr; + }; }; static PulseAudioInit pulseinit; PulseAudioSystem::PulseAudioSystem() { pasInput = pasOutput = pasSpeaker = nullptr; - bSourceDone=bSinkDone=bServerDone = false; - iDelayCache = 0; - bAttenuating = false; - iRemainingOperations = 0; - bPulseIsGood = false; - iSinkId = -1; - - pam = pa_threaded_mainloop_new(); + bSourceDone = bSinkDone = bServerDone = false; + iDelayCache = 0; + bAttenuating = false; + iRemainingOperations = 0; + bPulseIsGood = false; + iSinkId = -1; + + pam = pa_threaded_mainloop_new(); pa_mainloop_api *api = pa_threaded_mainloop_get_api(pam); pa_proplist *proplist; @@ -110,7 +111,7 @@ PulseAudioSystem::~PulseAudioSystem() { bAttenuating = false; setVolumes(); bool success = qwcWait.wait(&qmWait, 1000); - if (! success) { + if (!success) { qWarning("PulseAudio: Shutdown timeout when attempting to restore volumes."); } qmWait.unlock(); @@ -156,61 +157,62 @@ void PulseAudioSystem::wakeup_lock() { } void PulseAudioSystem::defer_event_callback(pa_mainloop_api *a, pa_defer_event *e, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); pas->eventCallback(a, e); } void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { api->defer_enable(pade, false); - if (! bSourceDone || ! bSinkDone || ! bServerDone) + if (!bSourceDone || !bSinkDone || !bServerDone) return; - AudioInputPtr ai = g.ai; - AudioOutputPtr ao = g.ao; - AudioInput *raw_ai = ai.get(); - AudioOutput *raw_ao = ao.get(); - PulseAudioInput *pai = dynamic_cast<PulseAudioInput *>(raw_ai); - PulseAudioOutput *pao = dynamic_cast<PulseAudioOutput *>(raw_ao); + AudioInputPtr ai = g.ai; + AudioOutputPtr ao = g.ao; + AudioInput *raw_ai = ai.get(); + AudioOutput *raw_ao = ao.get(); + PulseAudioInput *pai = dynamic_cast< PulseAudioInput * >(raw_ai); + PulseAudioOutput *pao = dynamic_cast< PulseAudioOutput * >(raw_ao); if (raw_ao) { - QString odev = outputDevice(); + QString odev = outputDevice(); pa_stream_state ost = pasOutput ? pa_stream_get_state(pasOutput) : PA_STREAM_TERMINATED; - bool do_stop = false; - bool do_start = false; + bool do_stop = false; + bool do_start = false; - if (! pao && (ost == PA_STREAM_READY)) { + if (!pao && (ost == PA_STREAM_READY)) { do_stop = true; } else if (pao) { switch (ost) { case PA_STREAM_TERMINATED: { - if (pasOutput) - pa_stream_unref(pasOutput); - - pa_sample_spec pss = qhSpecMap.value(odev); - pa_channel_map pcm = qhChanMap.value(odev); - if ((pss.format != PA_SAMPLE_FLOAT32NE) && (pss.format != PA_SAMPLE_S16NE)) - pss.format = PA_SAMPLE_FLOAT32NE; - pss.rate = SAMPLE_RATE; - if (pss.channels == 0) - pss.channels = 1; - - pasOutput = pa_stream_new(pacContext, mumble_sink_input, &pss, (pss.channels == 1) ? nullptr : &pcm); - pa_stream_set_state_callback(pasOutput, write_stream_callback, this); - pa_stream_set_write_callback(pasOutput, write_callback, this); - } + if (pasOutput) + pa_stream_unref(pasOutput); + + pa_sample_spec pss = qhSpecMap.value(odev); + pa_channel_map pcm = qhChanMap.value(odev); + if ((pss.format != PA_SAMPLE_FLOAT32NE) && (pss.format != PA_SAMPLE_S16NE)) + pss.format = PA_SAMPLE_FLOAT32NE; + pss.rate = SAMPLE_RATE; + if (pss.channels == 0) + pss.channels = 1; + + pasOutput = + pa_stream_new(pacContext, mumble_sink_input, &pss, (pss.channels == 1) ? nullptr : &pcm); + pa_stream_set_state_callback(pasOutput, write_stream_callback, this); + pa_stream_set_write_callback(pasOutput, write_callback, this); + } // Fallthrough case PA_STREAM_UNCONNECTED: do_start = true; break; case PA_STREAM_READY: { - if (g.s.iOutputDelay != iDelayCache) { - do_stop = true; - } else if (odev != qsOutputCache) { - do_stop = true; - } - break; + if (g.s.iOutputDelay != iDelayCache) { + do_stop = true; + } else if (odev != qsOutputCache) { + do_stop = true; } + break; + } default: break; } @@ -222,16 +224,16 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { } else if (do_start) { qWarning("PulseAudio: Starting output: %s", qPrintable(odev)); pa_buffer_attr buff; - const pa_sample_spec *pss = pa_stream_get_sample_spec(pasOutput); - const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); - const unsigned int iBlockLen = pao->iFrameSize * pss->channels * static_cast<unsigned int>(sampleSize); - buff.tlength = iBlockLen * (g.s.iOutputDelay+1); - buff.minreq = iBlockLen; - buff.maxlength = -1; - buff.prebuf = -1; - buff.fragsize = iBlockLen; - - iDelayCache = g.s.iOutputDelay; + const pa_sample_spec *pss = pa_stream_get_sample_spec(pasOutput); + const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); + const unsigned int iBlockLen = pao->iFrameSize * pss->channels * static_cast< unsigned int >(sampleSize); + buff.tlength = iBlockLen * (g.s.iOutputDelay + 1); + buff.minreq = iBlockLen; + buff.maxlength = -1; + buff.prebuf = -1; + buff.fragsize = iBlockLen; + + iDelayCache = g.s.iOutputDelay; qsOutputCache = odev; pa_stream_connect_playback(pasOutput, qPrintable(odev), &buff, PA_STREAM_ADJUST_LATENCY, nullptr, nullptr); @@ -240,39 +242,39 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { } if (raw_ai) { - QString idev = inputDevice(); + QString idev = inputDevice(); pa_stream_state ist = pasInput ? pa_stream_get_state(pasInput) : PA_STREAM_TERMINATED; - bool do_stop = false; - bool do_start = false; + bool do_stop = false; + bool do_start = false; - if (! pai && (ist == PA_STREAM_READY)) { + if (!pai && (ist == PA_STREAM_READY)) { do_stop = true; } else if (pai) { switch (ist) { case PA_STREAM_TERMINATED: { - if (pasInput) - pa_stream_unref(pasInput); - - pa_sample_spec pss = qhSpecMap.value(idev); - if ((pss.format != PA_SAMPLE_FLOAT32NE) && (pss.format != PA_SAMPLE_S16NE)) - pss.format = PA_SAMPLE_FLOAT32NE; - pss.rate = SAMPLE_RATE; - pss.channels = 1; - - pasInput = pa_stream_new(pacContext, "Microphone", &pss, nullptr); - pa_stream_set_state_callback(pasInput, read_stream_callback, this); - pa_stream_set_read_callback(pasInput, read_callback, this); - } + if (pasInput) + pa_stream_unref(pasInput); + + pa_sample_spec pss = qhSpecMap.value(idev); + if ((pss.format != PA_SAMPLE_FLOAT32NE) && (pss.format != PA_SAMPLE_S16NE)) + pss.format = PA_SAMPLE_FLOAT32NE; + pss.rate = SAMPLE_RATE; + pss.channels = 1; + + pasInput = pa_stream_new(pacContext, "Microphone", &pss, nullptr); + pa_stream_set_state_callback(pasInput, read_stream_callback, this); + pa_stream_set_read_callback(pasInput, read_callback, this); + } // Fallthrough case PA_STREAM_UNCONNECTED: do_start = true; break; case PA_STREAM_READY: { - if (idev != qsInputCache) { - do_stop = true; - } - break; + if (idev != qsInputCache) { + do_stop = true; } + break; + } default: break; } @@ -281,16 +283,16 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { qWarning("PulseAudio: Stopping input"); pa_stream_disconnect(pasInput); } else if (do_start) { - qWarning("PulseAudio: Starting input %s",qPrintable(idev)); + qWarning("PulseAudio: Starting input %s", qPrintable(idev)); pa_buffer_attr buff; - const pa_sample_spec *pss = pa_stream_get_sample_spec(pasInput); - const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); - const unsigned int iBlockLen = pai->iFrameSize * pss->channels * static_cast<unsigned int>(sampleSize); - buff.tlength = iBlockLen; - buff.minreq = iBlockLen; - buff.maxlength = -1; - buff.prebuf = -1; - buff.fragsize = iBlockLen; + const pa_sample_spec *pss = pa_stream_get_sample_spec(pasInput); + const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); + const unsigned int iBlockLen = pai->iFrameSize * pss->channels * static_cast< unsigned int >(sampleSize); + buff.tlength = iBlockLen; + buff.minreq = iBlockLen; + buff.maxlength = -1; + buff.prebuf = -1; + buff.fragsize = iBlockLen; qsInputCache = idev; @@ -304,44 +306,44 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { } if (raw_ai) { - QString odev = outputDevice(); - QString edev = qhEchoMap.value(odev); + QString odev = outputDevice(); + QString edev = qhEchoMap.value(odev); pa_stream_state est = pasSpeaker ? pa_stream_get_state(pasSpeaker) : PA_STREAM_TERMINATED; - bool do_stop = false; - bool do_start = false; + bool do_stop = false; + bool do_start = false; - if ((! pai || ! g.s.doEcho()) && (est == PA_STREAM_READY)) { + if ((!pai || !g.s.doEcho()) && (est == PA_STREAM_READY)) { do_stop = true; } else if (pai && g.s.doEcho()) { switch (est) { case PA_STREAM_TERMINATED: { - if (pasSpeaker) - pa_stream_unref(pasSpeaker); - - pa_sample_spec pss = qhSpecMap.value(edev); - pa_channel_map pcm = qhChanMap.value(edev); - if ((pss.format != PA_SAMPLE_FLOAT32NE) && (pss.format != PA_SAMPLE_S16NE)) - pss.format = PA_SAMPLE_FLOAT32NE; - pss.rate = SAMPLE_RATE; - if ((pss.channels == 0) || (! g.s.bEchoMulti)) - pss.channels = 1; - - pasSpeaker = pa_stream_new(pacContext, mumble_echo, &pss, (pss.channels == 1) ? nullptr : &pcm); - pa_stream_set_state_callback(pasSpeaker, read_stream_callback, this); - pa_stream_set_read_callback(pasSpeaker, read_callback, this); - } + if (pasSpeaker) + pa_stream_unref(pasSpeaker); + + pa_sample_spec pss = qhSpecMap.value(edev); + pa_channel_map pcm = qhChanMap.value(edev); + if ((pss.format != PA_SAMPLE_FLOAT32NE) && (pss.format != PA_SAMPLE_S16NE)) + pss.format = PA_SAMPLE_FLOAT32NE; + pss.rate = SAMPLE_RATE; + if ((pss.channels == 0) || (!g.s.bEchoMulti)) + pss.channels = 1; + + pasSpeaker = pa_stream_new(pacContext, mumble_echo, &pss, (pss.channels == 1) ? nullptr : &pcm); + pa_stream_set_state_callback(pasSpeaker, read_stream_callback, this); + pa_stream_set_read_callback(pasSpeaker, read_callback, this); + } // Fallthrough case PA_STREAM_UNCONNECTED: do_start = true; break; case PA_STREAM_READY: { - if (g.s.bEchoMulti != bEchoMultiCache) { - do_stop = true; - } else if (edev != qsEchoCache) { - do_stop = true; - } - break; + if (g.s.bEchoMulti != bEchoMultiCache) { + do_stop = true; + } else if (edev != qsEchoCache) { + do_stop = true; } + break; + } default: break; } @@ -352,25 +354,24 @@ void PulseAudioSystem::eventCallback(pa_mainloop_api *api, pa_defer_event *) { } else if (do_start) { qWarning("PulseAudio: Starting echo: %s", qPrintable(edev)); pa_buffer_attr buff; - const pa_sample_spec *pss = pa_stream_get_sample_spec(pasSpeaker); - const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); - const unsigned int iBlockLen = pai->iFrameSize * pss->channels * static_cast<unsigned int>(sampleSize); - buff.tlength = iBlockLen; - buff.minreq = iBlockLen; - buff.maxlength = -1; - buff.prebuf = -1; - buff.fragsize = iBlockLen; + const pa_sample_spec *pss = pa_stream_get_sample_spec(pasSpeaker); + const size_t sampleSize = (pss->format == PA_SAMPLE_FLOAT32NE) ? sizeof(float) : sizeof(short); + const unsigned int iBlockLen = pai->iFrameSize * pss->channels * static_cast< unsigned int >(sampleSize); + buff.tlength = iBlockLen; + buff.minreq = iBlockLen; + buff.maxlength = -1; + buff.prebuf = -1; + buff.fragsize = iBlockLen; bEchoMultiCache = g.s.bEchoMulti; - qsEchoCache = edev; + qsEchoCache = edev; pa_stream_connect_record(pasSpeaker, qPrintable(edev), &buff, PA_STREAM_ADJUST_LATENCY); } } } -void PulseAudioSystem::corkAudioInputStream(const bool cork) -{ +void PulseAudioSystem::corkAudioInputStream(const bool cork) { if (pasInput) { pa_threaded_mainloop_lock(pam); pa_stream_cork(pasInput, cork, nullptr, nullptr); @@ -379,7 +380,7 @@ void PulseAudioSystem::corkAudioInputStream(const bool cork) } void PulseAudioSystem::context_state_callback(pa_context *c, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); pas->contextCallback(c); } @@ -398,13 +399,13 @@ void PulseAudioSystem::subscribe_callback(pa_context *, pa_subscription_event_ty default: return; } - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); qWarning("PulseAudio: Sinks or inputs changed (inserted or removed sound card)"); pas->query(); } void PulseAudioSystem::sink_callback(pa_context *, const pa_sink_info *i, int eol, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); if (!i || eol) { pas->bSinkDone = true; pas->wakeup(); @@ -420,7 +421,7 @@ void PulseAudioSystem::sink_callback(pa_context *, const pa_sink_info *i, int eo } void PulseAudioSystem::source_callback(pa_context *, const pa_source_info *i, int eol, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); if (!i || eol) { pas->bSourceDone = true; pas->wakeup(); @@ -436,9 +437,9 @@ void PulseAudioSystem::source_callback(pa_context *, const pa_source_info *i, in } void PulseAudioSystem::server_callback(pa_context *, const pa_server_info *i, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); - pas->qsDefaultInput = QString::fromUtf8(i->default_source_name); + pas->qsDefaultInput = QString::fromUtf8(i->default_source_name); pas->qsDefaultOutput = QString::fromUtf8(i->default_sink_name); pas->bServerDone = true; @@ -446,7 +447,7 @@ void PulseAudioSystem::server_callback(pa_context *, const pa_server_info *i, vo } void PulseAudioSystem::sink_info_callback(pa_context *, const pa_sink_info *i, int eol, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); if (!i || eol) { return; } @@ -455,7 +456,7 @@ void PulseAudioSystem::sink_info_callback(pa_context *, const pa_sink_info *i, i } void PulseAudioSystem::write_stream_callback(pa_stream *s, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); switch (pa_stream_get_state(s)) { case PA_STREAM_FAILED: qWarning("PulseAudio: Stream error: %s", pa_strerror(pa_context_errno(pa_stream_get_context(s)))); @@ -464,14 +465,14 @@ void PulseAudioSystem::write_stream_callback(pa_stream *s, void *userdata) { break; } const pa_buffer_attr *bufferAttr; - if ( (bufferAttr = pa_stream_get_buffer_attr(s)) ) { + if ((bufferAttr = pa_stream_get_buffer_attr(s))) { g.ao->setBufferSize(bufferAttr->maxlength); } pas->wakeup(); } void PulseAudioSystem::read_stream_callback(pa_stream *s, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); switch (pa_stream_get_state(s)) { case PA_STREAM_FAILED: qWarning("PulseAudio: Stream error: %s", pa_strerror(pa_context_errno(pa_stream_get_context(s)))); @@ -483,9 +484,9 @@ void PulseAudioSystem::read_stream_callback(pa_stream *s, void *userdata) { } void PulseAudioSystem::read_callback(pa_stream *s, size_t bytes, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); - size_t length = bytes; + size_t length = bytes; const void *data = nullptr; pa_stream_peek(s, &data, &length); if (!data && length > 0) { @@ -497,9 +498,9 @@ void PulseAudioSystem::read_callback(pa_stream *s, size_t bytes, void *userdata) return; } - AudioInputPtr ai = g.ai; - PulseAudioInput *pai = dynamic_cast<PulseAudioInput *>(ai.get()); - if (! pai) { + AudioInputPtr ai = g.ai; + PulseAudioInput *pai = dynamic_cast< PulseAudioInput * >(ai.get()); + if (!pai) { if (length > 0) { pa_stream_drop(s); } @@ -511,8 +512,8 @@ void PulseAudioSystem::read_callback(pa_stream *s, size_t bytes, void *userdata) if (s == pas->pasInput) { if (!pa_sample_spec_equal(pss, &pai->pssMic)) { - pai->pssMic = *pss; - pai->iMicFreq = pss->rate; + pai->pssMic = *pss; + pai->iMicFreq = pss->rate; pai->iMicChannels = pss->channels; if (pss->format == PA_SAMPLE_FLOAT32NE) pai->eMicFormat = PulseAudioInput::SampleFloat; @@ -521,12 +522,12 @@ void PulseAudioSystem::read_callback(pa_stream *s, size_t bytes, void *userdata) pai->initializeMixer(); } if (data) { - pai->addMic(data, static_cast<unsigned int>(length) / pai->iMicSampleSize); + pai->addMic(data, static_cast< unsigned int >(length) / pai->iMicSampleSize); } } else if (s == pas->pasSpeaker) { if (!pa_sample_spec_equal(pss, &pai->pssEcho)) { - pai->pssEcho = *pss; - pai->iEchoFreq = pss->rate; + pai->pssEcho = *pss; + pai->iEchoFreq = pss->rate; pai->iEchoChannels = pss->channels; if (pss->format == PA_SAMPLE_FLOAT32NE) pai->eEchoFormat = PulseAudioInput::SampleFloat; @@ -535,7 +536,7 @@ void PulseAudioSystem::read_callback(pa_stream *s, size_t bytes, void *userdata) pai->initializeMixer(); } if (data) { - pai->addEcho(data, static_cast<unsigned int>(length) / pai->iEchoSampleSize); + pai->addEcho(data, static_cast< unsigned int >(length) / pai->iEchoSampleSize); } } @@ -545,13 +546,13 @@ void PulseAudioSystem::read_callback(pa_stream *s, size_t bytes, void *userdata) } void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); Q_ASSERT(s == pas->pasOutput); - AudioOutputPtr ao = g.ao; - PulseAudioOutput *pao = dynamic_cast<PulseAudioOutput *>(ao.get()); + AudioOutputPtr ao = g.ao; + PulseAudioOutput *pao = dynamic_cast< PulseAudioOutput * >(ao.get()); - if (! pao) { + if (!pao) { return; } @@ -565,9 +566,9 @@ void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata else pao->eSampleFormat = PulseAudioOutput::SampleShort; pao->iMixerFreq = pss->rate; - pao->iChannels = pss->channels; + pao->iChannels = pss->channels; unsigned int chanmasks[pss->channels]; - for (int i=0;i<pss->channels;++i) { + for (int i = 0; i < pss->channels; ++i) { unsigned int cm = 0; switch (pcm->map[i]) { case PA_CHANNEL_POSITION_LEFT: @@ -613,8 +614,8 @@ void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata } const unsigned int iSampleSize = pao->iSampleSize; - const unsigned int samples = static_cast<unsigned int>(bytes) / iSampleSize; - bool oldAttenuation = pas->bAttenuating; + const unsigned int samples = static_cast< unsigned int >(bytes) / iSampleSize; + bool oldAttenuation = pas->bAttenuating; unsigned char buffer[bytes]; // do we have some mixed output? @@ -637,20 +638,23 @@ void PulseAudioSystem::write_callback(pa_stream *s, size_t bytes, void *userdata pa_stream_write(s, buffer, iSampleSize * samples, nullptr, 0, PA_SEEK_RELATIVE); } -void PulseAudioSystem::volume_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); +void PulseAudioSystem::volume_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, + void *userdata) { + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); if (eol == 0) { - // If we're using the default of "enable attenuation on all ouputs" and output from an application is loopbacked, - // both the loopback and the application will be attenuated leading to double attenuation. + // If we're using the default of "enable attenuation on all ouputs" and output from an application is + // loopbacked, both the loopback and the application will be attenuated leading to double attenuation. if (!g.s.bOnlyAttenuateSameOutput && pas->iSinkId > -1 && !strcmp(i->driver, "module-loopback.c")) { return; } // If we're not attenuating different sinks and the input is not on this sink, don't attenuate. Or, - // if the input is a loopback module and connected to Mumble's sink, also ignore it (loopbacks are used to connect - // sinks). An attenuated loopback means an indirect application attenuation. + // if the input is a loopback module and connected to Mumble's sink, also ignore it (loopbacks are used to + // connect sinks). An attenuated loopback means an indirect application attenuation. if (g.s.bOnlyAttenuateSameOutput && pas->iSinkId > -1) { - if (int(i->sink) != pas->iSinkId || (int(i->sink) == pas->iSinkId && !strcmp(i->driver, "module-loopback.c") && !g.s.bAttenuateLoopbacks)) { + if (int(i->sink) != pas->iSinkId + || (int(i->sink) == pas->iSinkId && !strcmp(i->driver, "module-loopback.c") + && !g.s.bAttenuateLoopbacks)) { return; } } @@ -658,17 +662,18 @@ void PulseAudioSystem::volume_sink_input_list_callback(pa_context *c, const pa_s if (strcmp(i->name, mumble_sink_input) != 0) { // create a new entry PulseAttenuation patt; - patt.index = i->index; - patt.name = QString::fromUtf8(i->name); + patt.index = i->index; + patt.name = QString::fromUtf8(i->name); patt.stream_restore_id = QString::fromUtf8(pa_proplist_gets(i->proplist, "module-stream-restore.id")); - patt.normal_volume = i->volume; + patt.normal_volume = i->volume; // calculate the attenuated volume - pa_volume_t adj = static_cast<pa_volume_t>(PA_VOLUME_NORM * g.s.fOtherVolume); + pa_volume_t adj = static_cast< pa_volume_t >(PA_VOLUME_NORM * g.s.fOtherVolume); pa_sw_cvolume_multiply_scalar(&patt.attenuated_volume, &i->volume, adj); // set it on the sink input - pa_operation_unref(pa_context_set_sink_input_volume(c, i->index, &patt.attenuated_volume, nullptr, nullptr)); + pa_operation_unref( + pa_context_set_sink_input_volume(c, i->index, &patt.attenuated_volume, nullptr, nullptr)); // store it pas->qhVolumes[i->index] = patt; @@ -679,8 +684,9 @@ void PulseAudioSystem::volume_sink_input_list_callback(pa_context *c, const pa_s } } -void PulseAudioSystem::restore_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); +void PulseAudioSystem::restore_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, + void *userdata) { + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); if (eol == 0) { // if we were tracking this specific sink previously @@ -692,15 +698,16 @@ void PulseAudioSystem::restore_sink_input_list_callback(pa_context *c, const pa_ // reset the volume to normal pas->iRemainingOperations++; - pa_operation_unref(pa_context_set_sink_input_volume(c, i->index, &pas->qhVolumes[i->index].normal_volume, restore_volume_success_callback, pas)); + pa_operation_unref(pa_context_set_sink_input_volume( + c, i->index, &pas->qhVolumes[i->index].normal_volume, restore_volume_success_callback, pas)); } - // otherwise, save for matching at the end of iteration + // otherwise, save for matching at the end of iteration } else { QString restore_id = QString::fromUtf8(pa_proplist_gets(i->proplist, "module-stream-restore.id")); PulseAttenuation patt; - patt.index = i->index; - patt.normal_volume = i->volume; + patt.index = i->index; + patt.normal_volume = i->volume; pas->qhUnmatchedSinks[restore_id] = patt; } @@ -709,7 +716,7 @@ void PulseAudioSystem::restore_sink_input_list_callback(pa_context *c, const pa_ } else { // build a list of missing streams by iterating our active list - QHash<uint32_t, PulseAttenuation>::const_iterator it; + QHash< uint32_t, PulseAttenuation >::const_iterator it; for (it = pas->qhVolumes.constBegin(); it != pas->qhVolumes.constEnd(); ++it) { // skip if previously matched if (pas->qlMatchedSinks.contains(it.key())) { @@ -724,7 +731,8 @@ void PulseAudioSystem::restore_sink_input_list_callback(pa_context *c, const pa_ if (pa_cvolume_equal(&active_sink.normal_volume, &it.value().attenuated_volume) != 0) { // reset the volume to normal pas->iRemainingOperations++; - pa_operation_unref(pa_context_set_sink_input_volume(c, active_sink.index, &it.value().normal_volume, restore_volume_success_callback, pas)); + pa_operation_unref(pa_context_set_sink_input_volume(c, active_sink.index, &it.value().normal_volume, + restore_volume_success_callback, pas)); } continue; } @@ -752,8 +760,9 @@ void PulseAudioSystem::restore_sink_input_list_callback(pa_context *c, const pa_ } } -void PulseAudioSystem::stream_restore_read_callback(pa_context *c, const pa_ext_stream_restore_info *i, int eol, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); +void PulseAudioSystem::stream_restore_read_callback(pa_context *c, const pa_ext_stream_restore_info *i, int eol, + void *userdata) { + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); if (eol == 0) { QString name = QString::fromUtf8(i->name); @@ -764,9 +773,10 @@ void PulseAudioSystem::stream_restore_read_callback(pa_context *c, const pa_ext_ if (pa_cvolume_equal(&pas->qhMissingSinks[name].attenuated_volume, &i->volume) != 0) { // update the stream restore record pa_ext_stream_restore_info restore = *i; - restore.volume = pas->qhMissingSinks[name].normal_volume; + restore.volume = pas->qhMissingSinks[name].normal_volume; pas->iRemainingOperations++; - pa_operation_unref(pa_ext_stream_restore_write(c, PA_UPDATE_REPLACE, &restore, 1, 1, restore_volume_success_callback, pas)); + pa_operation_unref(pa_ext_stream_restore_write(c, PA_UPDATE_REPLACE, &restore, 1, 1, + restore_volume_success_callback, pas)); } pas->qhMissingSinks.remove(name); @@ -790,19 +800,19 @@ void PulseAudioSystem::stream_restore_read_callback(pa_context *c, const pa_ext_ } void PulseAudioSystem::restore_volume_success_callback(pa_context *, int, void *userdata) { - PulseAudioSystem *pas = reinterpret_cast<PulseAudioSystem *>(userdata); + PulseAudioSystem *pas = reinterpret_cast< PulseAudioSystem * >(userdata); pas->iRemainingOperations--; // if there are no more pending volume adjustments and we're shutting down, // let the main thread know - if (! pas->bRunning && pas->iRemainingOperations == 0) { + if (!pas->bRunning && pas->iRemainingOperations == 0) { pas->qwcWait.wakeAll(); } } void PulseAudioSystem::query() { - bSourceDone=bSinkDone=bServerDone = false; + bSourceDone = bSinkDone = bServerDone = false; qhInput.clear(); qhOutput.clear(); qhEchoMap.clear(); @@ -824,7 +834,7 @@ void PulseAudioSystem::setVolumes() { // set the new per-application volumes and store the old ones pa_operation_unref(pa_context_get_sink_input_info_list(pacContext, volume_sink_input_list_callback, this)); } - // clear attenuation state and restore normal volumes + // clear attenuation state and restore normal volumes } else { iRemainingOperations++; pa_operation_unref(pa_context_get_sink_input_info_list(pacContext, restore_sink_input_list_callback, this)); @@ -861,8 +871,8 @@ AudioInput *PulseAudioInputRegistrar::create() { return new PulseAudioInput(); } -const QList<audioDevice> PulseAudioInputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > PulseAudioInputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; QStringList qlInputDevs = pasys->qhInput.keys(); std::sort(qlInputDevs.begin(), qlInputDevs.end()); @@ -872,9 +882,7 @@ const QList<audioDevice> PulseAudioInputRegistrar::getDeviceChoices() { qlInputDevs.prepend(g.s.qsPulseAudioInput); } - foreach(const QString &dev, qlInputDevs) { - qlReturn << audioDevice(pasys->qhInput.value(dev), dev); - } + foreach (const QString &dev, qlInputDevs) { qlReturn << audioDevice(pasys->qhInput.value(dev), dev); } return qlReturn; } @@ -894,8 +902,8 @@ AudioOutput *PulseAudioOutputRegistrar::create() { return new PulseAudioOutput(); } -const QList<audioDevice> PulseAudioOutputRegistrar::getDeviceChoices() { - QList<audioDevice> qlReturn; +const QList< audioDevice > PulseAudioOutputRegistrar::getDeviceChoices() { + QList< audioDevice > qlReturn; QStringList qlOutputDevs = pasys->qhOutput.keys(); std::sort(qlOutputDevs.begin(), qlOutputDevs.end()); @@ -905,9 +913,7 @@ const QList<audioDevice> PulseAudioOutputRegistrar::getDeviceChoices() { qlOutputDevs.prepend(g.s.qsPulseAudioOutput); } - foreach(const QString &dev, qlOutputDevs) { - qlReturn << audioDevice(pasys->qhOutput.value(dev), dev); - } + foreach (const QString &dev, qlOutputDevs) { qlReturn << audioDevice(pasys->qhOutput.value(dev), dev); } return qlReturn; } diff --git a/src/mumble/PulseAudio.h b/src/mumble/PulseAudio.h index 202a7e556..52a319504 100644 --- a/src/mumble/PulseAudio.h +++ b/src/mumble/PulseAudio.h @@ -6,9 +6,9 @@ #ifndef MUMBLE_MUMBLE_PULSEAUDIO_H_ #define MUMBLE_MUMBLE_PULSEAUDIO_H_ -#include <pulse/pulseaudio.h> -#include <pulse/ext-stream-restore.h> #include <QtCore/QWaitCondition> +#include <pulse/ext-stream-restore.h> +#include <pulse/pulseaudio.h> #include "AudioInput.h" #include "AudioOutput.h" @@ -25,106 +25,111 @@ class PulseAudioInput; class PulseAudioOutput; class PulseAudioSystem : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(PulseAudioSystem) - protected: - void wakeup(); - pa_context *pacContext; - pa_stream *pasInput, *pasOutput, *pasSpeaker; - pa_threaded_mainloop *pam; - pa_defer_event *pade; - - bool bSourceDone, bSinkDone, bServerDone, bRunning; - - QString qsDefaultInput, qsDefaultOutput; - - int iDelayCache; - QString qsOutputCache, qsInputCache, qsEchoCache; - bool bEchoMultiCache; - QHash<QString, QString> qhEchoMap; - QHash<QString, pa_sample_spec> qhSpecMap; - QHash<QString, pa_channel_map> qhChanMap; - - bool bAttenuating; - int iRemainingOperations; - int iSinkId; - QHash<uint32_t, PulseAttenuation> qhVolumes; - QList<uint32_t> qlMatchedSinks; - QHash<QString, PulseAttenuation> qhUnmatchedSinks; - QHash<QString, PulseAttenuation> qhMissingSinks; - - static void defer_event_callback(pa_mainloop_api *a, pa_defer_event *e, void *userdata); - static void context_state_callback(pa_context *c, void *userdata); - static void subscribe_callback(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, void *userdata); - static void sink_callback(pa_context *c, const pa_sink_info *i, int eol, void *userdata); - static void source_callback(pa_context *c, const pa_source_info *i, int eol, void *userdata); - static void server_callback(pa_context *c, const pa_server_info *i, void *userdata); - static void sink_info_callback(pa_context *c, const pa_sink_info *i, int eol, void *userdata); - static void write_stream_callback(pa_stream *s, void *userdata); - static void read_stream_callback(pa_stream *s, void *userdata); - static void read_callback(pa_stream *s, size_t bytes, void *userdata); - static void write_callback(pa_stream *s, size_t bytes, void *userdata); - static void volume_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata); - static void restore_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata); - static void stream_restore_read_callback(pa_context *c, const pa_ext_stream_restore_info *i, int eol, void *userdata); - static void restore_volume_success_callback(pa_context *c, int success, void *userdata); - void contextCallback(pa_context *c); - void eventCallback(pa_mainloop_api *a, pa_defer_event *e); - - void query(); - - QString outputDevice() const; - QString inputDevice() const; - - void setVolumes(); - PulseAttenuation* getAttenuation(QString stream_restore_id); - - public slots: - void corkAudioInputStream(const bool cork); - - public: - QHash<QString, QString> qhInput; - QHash<QString, QString> qhOutput; - bool bPulseIsGood; - QMutex qmWait; - QWaitCondition qwcWait; - - void wakeup_lock(); - - PulseAudioSystem(); - ~PulseAudioSystem() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(PulseAudioSystem) +protected: + void wakeup(); + pa_context *pacContext; + pa_stream *pasInput, *pasOutput, *pasSpeaker; + pa_threaded_mainloop *pam; + pa_defer_event *pade; + + bool bSourceDone, bSinkDone, bServerDone, bRunning; + + QString qsDefaultInput, qsDefaultOutput; + + int iDelayCache; + QString qsOutputCache, qsInputCache, qsEchoCache; + bool bEchoMultiCache; + QHash< QString, QString > qhEchoMap; + QHash< QString, pa_sample_spec > qhSpecMap; + QHash< QString, pa_channel_map > qhChanMap; + + bool bAttenuating; + int iRemainingOperations; + int iSinkId; + QHash< uint32_t, PulseAttenuation > qhVolumes; + QList< uint32_t > qlMatchedSinks; + QHash< QString, PulseAttenuation > qhUnmatchedSinks; + QHash< QString, PulseAttenuation > qhMissingSinks; + + static void defer_event_callback(pa_mainloop_api *a, pa_defer_event *e, void *userdata); + static void context_state_callback(pa_context *c, void *userdata); + static void subscribe_callback(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, void *userdata); + static void sink_callback(pa_context *c, const pa_sink_info *i, int eol, void *userdata); + static void source_callback(pa_context *c, const pa_source_info *i, int eol, void *userdata); + static void server_callback(pa_context *c, const pa_server_info *i, void *userdata); + static void sink_info_callback(pa_context *c, const pa_sink_info *i, int eol, void *userdata); + static void write_stream_callback(pa_stream *s, void *userdata); + static void read_stream_callback(pa_stream *s, void *userdata); + static void read_callback(pa_stream *s, size_t bytes, void *userdata); + static void write_callback(pa_stream *s, size_t bytes, void *userdata); + static void volume_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata); + static void restore_sink_input_list_callback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata); + static void stream_restore_read_callback(pa_context *c, const pa_ext_stream_restore_info *i, int eol, + void *userdata); + static void restore_volume_success_callback(pa_context *c, int success, void *userdata); + void contextCallback(pa_context *c); + void eventCallback(pa_mainloop_api *a, pa_defer_event *e); + + void query(); + + QString outputDevice() const; + QString inputDevice() const; + + void setVolumes(); + PulseAttenuation *getAttenuation(QString stream_restore_id); + +public slots: + void corkAudioInputStream(const bool cork); + +public: + QHash< QString, QString > qhInput; + QHash< QString, QString > qhOutput; + bool bPulseIsGood; + QMutex qmWait; + QWaitCondition qwcWait; + + void wakeup_lock(); + + PulseAudioSystem(); + ~PulseAudioSystem() Q_DECL_OVERRIDE; }; class PulseAudioInput : public AudioInput { - friend class PulseAudioSystem; - private: - Q_OBJECT - Q_DISABLE_COPY(PulseAudioInput) - protected: - QMutex qmMutex; - QWaitCondition qwcWait; - pa_sample_spec pssMic, pssEcho; - public: - PulseAudioInput(); - ~PulseAudioInput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; + friend class PulseAudioSystem; + +private: + Q_OBJECT + Q_DISABLE_COPY(PulseAudioInput) +protected: + QMutex qmMutex; + QWaitCondition qwcWait; + pa_sample_spec pssMic, pssEcho; + +public: + PulseAudioInput(); + ~PulseAudioInput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; class PulseAudioOutput : public AudioOutput { - friend class PulseAudioSystem; - private: - Q_OBJECT - Q_DISABLE_COPY(PulseAudioOutput) - protected: - QMutex qmMutex; - QWaitCondition qwcWait; - pa_sample_spec pss; - pa_channel_map pcm; - public: - PulseAudioOutput(); - ~PulseAudioOutput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; + friend class PulseAudioSystem; + +private: + Q_OBJECT + Q_DISABLE_COPY(PulseAudioOutput) +protected: + QMutex qmMutex; + QWaitCondition qwcWait; + pa_sample_spec pss; + pa_channel_map pcm; + +public: + PulseAudioOutput(); + ~PulseAudioOutput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/RichTextEditor.cpp b/src/mumble/RichTextEditor.cpp index cdf51d1a1..189dd3e7b 100644 --- a/src/mumble/RichTextEditor.cpp +++ b/src/mumble/RichTextEditor.cpp @@ -17,10 +17,11 @@ #include <QtWidgets/QToolTip> #ifdef Q_OS_WIN -# include <shlobj.h> +# include <shlobj.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" RichTextHtmlEdit::RichTextHtmlEdit(QWidget *p) : QTextEdit(p) { @@ -37,8 +38,8 @@ static QString decodeMimeString(const QByteArray &src) { return QString(); if ((src.length() >= 4) && ((src.length() % sizeof(ushort)) == 0)) { - const ushort *ptr = reinterpret_cast<const ushort *>(src.constData()); - int len = static_cast<int>(src.length() / sizeof(ushort)); + const ushort *ptr = reinterpret_cast< const ushort * >(src.constData()); + int len = static_cast< int >(src.length() / sizeof(ushort)); if ((ptr[0] > 0) && (ptr[0] < 0x7f) && (ptr[1] > 0) && (ptr[1] < 0x7f)) { while (len && (ptr[len - 1] == 0)) --len; @@ -46,9 +47,10 @@ static QString decodeMimeString(const QByteArray &src) { } } - if ((sizeof(wchar_t) != sizeof(ushort)) && (src.length() >= static_cast<int>(sizeof(wchar_t))) && ((src.length() % sizeof(wchar_t)) == 0)) { - const wchar_t *ptr = reinterpret_cast<const wchar_t *>(src.constData()); - int len = static_cast<int>(src.length() / sizeof(wchar_t)); + if ((sizeof(wchar_t) != sizeof(ushort)) && (src.length() >= static_cast< int >(sizeof(wchar_t))) + && ((src.length() % sizeof(wchar_t)) == 0)) { + const wchar_t *ptr = reinterpret_cast< const wchar_t * >(src.constData()); + int len = static_cast< int >(src.length() / sizeof(wchar_t)); if (*ptr < 0x7f) { while (len && (ptr[len - 1] == 0)) --len; @@ -56,7 +58,7 @@ static QString decodeMimeString(const QByteArray &src) { } } const char *ptr = src.constData(); - int len = src.length(); + int len = src.length(); while (len && (ptr[len - 1] == 0)) --len; return QString::fromUtf8(ptr, len); @@ -75,19 +77,19 @@ void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) { #endif if (source->hasImage()) { - QImage img = qvariant_cast<QImage>(source->imageData()); + QImage img = qvariant_cast< QImage >(source->imageData()); QString html = Log::imageToImg(img); - if (! html.isEmpty()) + if (!html.isEmpty()) insertHtml(html); return; } QString mozurl = decodeMimeString(source->data(QLatin1String("text/x-moz-url"))); - if (! mozurl.isEmpty()) { + if (!mozurl.isEmpty()) { QStringList lines = mozurl.split(newline); qWarning() << mozurl << lines; if (lines.count() >= 2) { - uri = lines.at(0); + uri = lines.at(0); title = lines.at(1); } } @@ -100,38 +102,41 @@ void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) { if (uri.isEmpty()) { QStringList urls; #ifdef Q_OS_WIN - urls = decodeMimeString(source->data(QLatin1String("application/x-qt-windows-mime;value=\"UniformResourceLocatorW\""))).split(newline); + urls = decodeMimeString( + source->data(QLatin1String("application/x-qt-windows-mime;value=\"UniformResourceLocatorW\""))) + .split(newline); if (urls.isEmpty()) #endif urls = decodeMimeString(source->data(QLatin1String("text/uri-list"))).split(newline); - if (! urls.isEmpty()) + if (!urls.isEmpty()) uri = urls.at(0).trimmed(); } if (uri.isEmpty()) { QUrl url(source->text(), QUrl::StrictMode); - if (url.isValid() && ! url.isRelative()) { + if (url.isValid() && !url.isRelative()) { uri = url.toString(); } } #ifdef Q_OS_WIN - if (title.isEmpty() && source->hasFormat(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""))) { + if (title.isEmpty() + && source->hasFormat(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""))) { QByteArray qba = source->data(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\"")); if (qba.length() == sizeof(FILEGROUPDESCRIPTORW)) { - const FILEGROUPDESCRIPTORW *ptr = reinterpret_cast<const FILEGROUPDESCRIPTORW *>(qba.constData()); - title = QString::fromWCharArray(ptr->fgd[0].cFileName); + const FILEGROUPDESCRIPTORW *ptr = reinterpret_cast< const FILEGROUPDESCRIPTORW * >(qba.constData()); + title = QString::fromWCharArray(ptr->fgd[0].cFileName); if (title.endsWith(QLatin1String(".url"), Qt::CaseInsensitive)) title = title.left(title.length() - 4); } } #endif - if (! uri.isEmpty()) { + if (!uri.isEmpty()) { if (title.isEmpty()) title = uri; - uri = uri.toHtmlEscaped(); + uri = uri.toHtmlEscaped(); title = title.toHtmlEscaped(); insertHtml(QString::fromLatin1("<a href=\"%1\">%2</a>").arg(uri, title)); @@ -139,7 +144,7 @@ void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) { } QString html = decodeMimeString(source->data(QLatin1String("text/html"))); - if (! html.isEmpty()) { + if (!html.isEmpty()) { insertHtml(html); return; } @@ -150,7 +155,7 @@ void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) { RichTextEditorLink::RichTextEditorLink(const QString &txt, QWidget *p) : QDialog(p) { setupUi(this); - if (! txt.isEmpty()) { + if (!txt.isEmpty()) { qleText->setText(txt); } } @@ -161,7 +166,7 @@ QString RichTextEditorLink::text() const { txt = txt.toHtmlEscaped(); - if (url.isValid() && ! url.isRelative() && ! txt.isEmpty()) { + if (url.isValid() && !url.isRelative() && !txt.isEmpty()) { return QString::fromLatin1("<a href=\"%1\">%2</a>").arg(url.toString(), txt); } @@ -169,7 +174,7 @@ QString RichTextEditorLink::text() const { } RichTextEditor::RichTextEditor(QWidget *p) : QTabWidget(p) { - bChanged = false; + bChanged = false; bModified = false; bReadOnly = false; @@ -215,26 +220,28 @@ void RichTextEditor::on_qaColor_triggered() { } void RichTextEditor::on_qaLink_triggered() { - QTextCursor qtc = qteRichText->textCursor(); + QTextCursor qtc = qteRichText->textCursor(); RichTextEditorLink *rtel = new RichTextEditorLink(qtc.selectedText(), this); if (rtel->exec() == QDialog::Accepted) { QString html = rtel->text(); - if (! html.isEmpty()) + if (!html.isEmpty()) qteRichText->insertHtml(html); } delete rtel; } void RichTextEditor::on_qaImage_triggered() { - QPair<QByteArray, QImage> choice = g.mw->openImageFile(); + QPair< QByteArray, QImage > choice = g.mw->openImageFile(); QByteArray &qba = choice.first; if (qba.isEmpty()) return; - if ((g.uiImageLength > 0) && (static_cast<unsigned int>(qba.length()) > g.uiImageLength)) { - QMessageBox::warning(this, tr("Failed to load image"), tr("Image file too large to embed in document. Please use images smaller than %1 kB.").arg(g.uiImageLength /1024)); + if ((g.uiImageLength > 0) && (static_cast< unsigned int >(qba.length()) > g.uiImageLength)) { + QMessageBox::warning(this, tr("Failed to load image"), + tr("Image file too large to embed in document. Please use images smaller than %1 kB.") + .arg(g.uiImageLength / 1024)); return; } @@ -248,7 +255,7 @@ void RichTextEditor::on_qaImage_triggered() { } void RichTextEditor::onCurrentChanged(int index) { - if (! bChanged) + if (!bChanged) return; if (index == 1) @@ -261,15 +268,15 @@ void RichTextEditor::onCurrentChanged(int index) { void RichTextEditor::on_qptePlainText_textChanged() { bModified = true; - bChanged = true; + bChanged = true; } void RichTextEditor::on_qteRichText_textChanged() { bModified = true; - bChanged = true; + bChanged = true; updateActions(); - if (! g.uiMessageLength) + if (!g.uiMessageLength) return; richToPlain(); @@ -289,29 +296,28 @@ void RichTextEditor::on_qteRichText_textChanged() { QString qsOut; QXmlStreamReader qxsr(QString::fromLatin1("<document>%1</document>").arg(plainText)); QXmlStreamWriter qxsw(&qsOut); - while (! qxsr.atEnd()) { + while (!qxsr.atEnd()) { switch (qxsr.readNext()) { case QXmlStreamReader::Invalid: return; case QXmlStreamReader::StartElement: { - if (qxsr.name() == QLatin1String("img")) { - QXmlStreamAttributes attr = qxsr.attributes(); - - qxsw.writeStartElement(qxsr.namespaceUri().toString(), qxsr.name().toString()); - foreach(const QXmlStreamAttribute &a, qxsr.attributes()) - if (a.name() != QLatin1String("src")) - qxsw.writeAttribute(a); - } else { - qxsw.writeCurrentToken(qxsr); - } + if (qxsr.name() == QLatin1String("img")) { + QXmlStreamAttributes attr = qxsr.attributes(); + + qxsw.writeStartElement(qxsr.namespaceUri().toString(), qxsr.name().toString()); + foreach (const QXmlStreamAttribute &a, qxsr.attributes()) + if (a.name() != QLatin1String("src")) + qxsw.writeAttribute(a); + } else { + qxsw.writeCurrentToken(qxsr); } - break; + } break; default: qxsw.writeCurrentToken(qxsr); break; } } - over = (static_cast<unsigned int>(qsOut.length()) > g.uiMessageLength); + over = (static_cast< unsigned int >(qsOut.length()) > g.uiMessageLength); } @@ -321,9 +327,9 @@ void RichTextEditor::on_qteRichText_textChanged() { if (QToolTip::text() == tooltip) QToolTip::hideText(); } else { - QPoint p = QCursor::pos(); + QPoint p = QCursor::pos(); const QRect &r = qteRichText->rect(); - if (! r.contains(qteRichText->mapFromGlobal(p))) + if (!r.contains(qteRichText->mapFromGlobal(p))) p = qteRichText->mapToGlobal(r.center()); QToolTip::showText(p, tooltip, qteRichText); } @@ -342,7 +348,7 @@ void RichTextEditor::updateColor(const QColor &col) { return; qcColor = col; - QRect r(0,0,24,24); + QRect r(0, 0, 24, 24); QPixmap qpm(r.size()); QPainter qp(&qpm); @@ -368,7 +374,7 @@ void RichTextEditor::richToPlain() { int paragraphs = 0; - QMap<QString, QString> def; + QMap< QString, QString > def; def.insert(QLatin1String("margin-top"), QLatin1String("0px")); def.insert(QLatin1String("margin-bottom"), QLatin1String("0px")); @@ -390,7 +396,7 @@ void RichTextEditor::richToPlain() { QXmlStreamReader r(qsOutput); qsOutput = QString(); QXmlStreamWriter w(&qsOutput); - changed = XMLTools::unduplicateTags(r, w); + changed = XMLTools::unduplicateTags(r, w); qsOutput = qsOutput.trimmed(); } while (changed); @@ -398,15 +404,15 @@ void RichTextEditor::richToPlain() { } void RichTextEditor::setText(const QString &txt, bool readonly) { - qtbToolBar->setEnabled(! readonly && g.bAllowHTML); - qtbToolBar->setVisible(! readonly && g.bAllowHTML); - qptePlainText->setReadOnly(readonly || ! g.bAllowHTML); + qtbToolBar->setEnabled(!readonly && g.bAllowHTML); + qtbToolBar->setVisible(!readonly && g.bAllowHTML); + qptePlainText->setReadOnly(readonly || !g.bAllowHTML); qteRichText->setReadOnly(readonly); qteRichText->setHtml(txt); qptePlainText->setPlainText(txt); - bChanged = false; + bChanged = false; bModified = false; bReadOnly = readonly; } @@ -427,9 +433,9 @@ bool RichTextEditor::eventFilter(QObject *obj, QEvent *evt) { if (obj != qptePlainText && obj != qteRichText) return false; if (evt->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast<QKeyEvent *>(evt); - if (((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return)) && - (keyEvent->modifiers() == Qt::ControlModifier)) { + QKeyEvent *keyEvent = static_cast< QKeyEvent * >(evt); + if (((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return)) + && (keyEvent->modifiers() == Qt::ControlModifier)) { emit accept(); return true; } @@ -446,7 +452,7 @@ bool RichTextImage::isValidImage(const QByteArray &ba, QByteArray &fmt) { QByteArray detectedFormat = QImageReader::imageFormat(&qb).toLower(); if (detectedFormat == QByteArray("png") || detectedFormat == QByteArray("jpg") - || detectedFormat == QByteArray("jpeg") || detectedFormat == QByteArray("gif")) { + || detectedFormat == QByteArray("jpeg") || detectedFormat == QByteArray("gif")) { fmt = detectedFormat; return true; } diff --git a/src/mumble/RichTextEditor.h b/src/mumble/RichTextEditor.h index 29756ec89..7c1fbb9c1 100644 --- a/src/mumble/RichTextEditor.h +++ b/src/mumble/RichTextEditor.h @@ -12,15 +12,17 @@ class LogDocument; class RichTextHtmlEdit : public QTextEdit { - private: - Q_OBJECT - Q_DISABLE_COPY(RichTextHtmlEdit) - protected: - void insertFromMimeData(const QMimeData *source); - public: - RichTextHtmlEdit(QWidget *p); - private: - LogDocument *m_document; +private: + Q_OBJECT + Q_DISABLE_COPY(RichTextHtmlEdit) +protected: + void insertFromMimeData(const QMimeData *source); + +public: + RichTextHtmlEdit(QWidget *p); + +private: + LogDocument *m_document; }; #include "ui_RichTextEditor.h" @@ -28,54 +30,55 @@ class RichTextHtmlEdit : public QTextEdit { class RichTextEditorLink : public QDialog, Ui::RichTextEditorLink { - private: - Q_OBJECT - Q_DISABLE_COPY(RichTextEditorLink) - public: - RichTextEditorLink(const QString &text = QString(), QWidget *p = nullptr); - QString text() const; +private: + Q_OBJECT + Q_DISABLE_COPY(RichTextEditorLink) +public: + RichTextEditorLink(const QString &text = QString(), QWidget *p = nullptr); + QString text() const; }; class RichTextEditor : public QTabWidget, Ui::RichTextEditor { - private: - Q_OBJECT - Q_DISABLE_COPY(RichTextEditor) - protected: - bool bModified; - bool bChanged; - bool bReadOnly; - void richToPlain(); - QColor qcColor; - bool eventFilter(QObject *obj, QEvent *event) Q_DECL_OVERRIDE; - public: - RichTextEditor(QWidget *p = nullptr); - QString text(); - bool isModified() const; - signals: - /// The accept signal is emitted when Ctrl-Enter is pressed inside the RichTextEditor. - void accept(); - public slots: - void setText(const QString &text, bool readonly = false); - void updateColor(const QColor &); - void updateActions(); - protected slots: - void on_qaBold_triggered(bool); - void on_qaItalic_triggered(bool); - void on_qaUnderline_triggered(bool); - void on_qaColor_triggered(); - void on_qaLink_triggered(); - void on_qaImage_triggered(); +private: + Q_OBJECT + Q_DISABLE_COPY(RichTextEditor) +protected: + bool bModified; + bool bChanged; + bool bReadOnly; + void richToPlain(); + QColor qcColor; + bool eventFilter(QObject *obj, QEvent *event) Q_DECL_OVERRIDE; + +public: + RichTextEditor(QWidget *p = nullptr); + QString text(); + bool isModified() const; +signals: + /// The accept signal is emitted when Ctrl-Enter is pressed inside the RichTextEditor. + void accept(); +public slots: + void setText(const QString &text, bool readonly = false); + void updateColor(const QColor &); + void updateActions(); +protected slots: + void on_qaBold_triggered(bool); + void on_qaItalic_triggered(bool); + void on_qaUnderline_triggered(bool); + void on_qaColor_triggered(); + void on_qaLink_triggered(); + void on_qaImage_triggered(); - void on_qptePlainText_textChanged(); - void on_qteRichText_textChanged(); - void on_qteRichText_cursorPositionChanged(); - void on_qteRichText_currentCharFormatChanged(); - void onCurrentChanged(int); + void on_qptePlainText_textChanged(); + void on_qteRichText_textChanged(); + void on_qteRichText_cursorPositionChanged(); + void on_qteRichText_currentCharFormatChanged(); + void onCurrentChanged(int); }; class RichTextImage { - public: - static bool isValidImage(const QByteArray &buf, QByteArray &fmt); +public: + static bool isValidImage(const QByteArray &buf, QByteArray &fmt); }; #endif diff --git a/src/mumble/Screen.cpp b/src/mumble/Screen.cpp index 6b2084c2b..c9e5898b5 100644 --- a/src/mumble/Screen.cpp +++ b/src/mumble/Screen.cpp @@ -39,7 +39,7 @@ QScreen *Screen::screenAt(const QPoint &point) { return qApp->screenAt(point); #else // Adapted from qguiapplication.cpp (Qt) - QVarLengthArray<const QScreen *, 8> visitedScreens; + QVarLengthArray< const QScreen *, 8 > visitedScreens; for (const QScreen *screen : qApp->screens()) { if (visitedScreens.contains(screen)) { diff --git a/src/mumble/Screen.h b/src/mumble/Screen.h index eb8f98f50..93f844bb5 100644 --- a/src/mumble/Screen.h +++ b/src/mumble/Screen.h @@ -11,8 +11,7 @@ class QScreen; class QWidget; class QWindow; -class Screen -{ +class Screen { public: /// Inspired by https://phabricator.kde.org/D22379 static QWindow *windowFromWidget(const QWidget &widget); diff --git a/src/mumble/ServerHandler.cpp b/src/mumble/ServerHandler.cpp index bb81fc832..049809783 100644 --- a/src/mumble/ServerHandler.cpp +++ b/src/mumble/ServerHandler.cpp @@ -6,7 +6,7 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "ServerHandler.h" @@ -16,18 +16,18 @@ #include "Cert.h" #include "Connection.h" #include "Database.h" +#include "HostAddress.h" #include "MainWindow.h" #include "Message.h" +#include "Net.h" #include "NetworkConfig.h" #include "OSInfo.h" #include "PacketDataStream.h" #include "RichTextEditor.h" #include "SSL.h" -#include "User.h" -#include "Net.h" -#include "HostAddress.h" #include "ServerResolver.h" #include "ServerResolverRecord.h" +#include "User.h" #include "Utils.h" #include <QtCore/QtEndian> @@ -42,24 +42,26 @@ // redefinitions if the PCH header is used. // The workaround consists in including the header only if _DELAY_IMP_VER // (defined in the header) is not defined. -# ifndef _DELAY_IMP_VER -# include <delayimp.h> -# endif -# include <qos2.h> -# include <wincrypt.h> -# include <winsock2.h> +# ifndef _DELAY_IMP_VER +# include <delayimp.h> +# endif +# include <qos2.h> +# include <wincrypt.h> +# include <winsock2.h> #else -# if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) -# include <netinet/in.h> -# endif -# include <netinet/ip.h> -# include <sys/socket.h> +# if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) +# include <netinet/in.h> +# endif +# include <netinet/ip.h> +# include <sys/socket.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -ServerHandlerMessageEvent::ServerHandlerMessageEvent(const QByteArray &msg, unsigned int mtype, bool flush) : QEvent(static_cast<QEvent::Type>(SERVERSEND_EVENT)) { +ServerHandlerMessageEvent::ServerHandlerMessageEvent(const QByteArray &msg, unsigned int mtype, bool flush) + : QEvent(static_cast< QEvent::Type >(SERVERSEND_EVENT)) { qbaMsg = msg; uiType = mtype; bFlush = flush; @@ -72,24 +74,24 @@ static HANDLE loadQoS() { HRESULT hr = E_FAIL; // We don't support delay-loading QoS on MinGW. Only enable it for MSVC. -#ifdef _MSC_VER +# ifdef _MSC_VER __try { hr = __HrLoadAllImportsForDll("qwave.dll"); } - __except(EXCEPTION_EXECUTE_HANDLER) { + __except (EXCEPTION_EXECUTE_HANDLER) { hr = E_FAIL; } -#endif +# endif - if (! SUCCEEDED(hr)) { + if (!SUCCEEDED(hr)) { qWarning("ServerHandler: Failed to load qWave.dll, no QoS available"); } else { QOS_VERSION qvVer; qvVer.MajorVersion = 1; qvVer.MinorVersion = 0; - if (! QOSCreateHandle(&qvVer, &hQoS)) { + if (!QOSCreateHandle(&qvVer, &hQoS)) { qWarning("ServerHandler: Failed to create QOS2 handle"); hQoS = nullptr; } else { @@ -100,16 +102,15 @@ static HANDLE loadQoS() { } #endif -ServerHandler::ServerHandler() - : database(new Database(QLatin1String("ServerHandler"))) { +ServerHandler::ServerHandler() : database(new Database(QLatin1String("ServerHandler"))) { cConnection.reset(); - qusUdp = nullptr; - bStrong = false; - usPort = 0; - bUdp = true; + qusUdp = nullptr; + bStrong = false; + usPort = 0; + bUdp = true; tConnectionTimeoutTimer = nullptr; - uiVersion = 0; - iInFlightTCPPings = 0; + uiVersion = 0; + iInFlightTCPPings = 0; // Historically, the qWarning line below initialized OpenSSL for us. // It used to have this comment: @@ -125,9 +126,11 @@ ServerHandler::ServerHandler() MumbleSSL::addSystemCA(); { - QList<QSslCipher> ciphers = MumbleSSL::ciphersFromOpenSSLCipherString(g.s.qsSslCiphers); + QList< QSslCipher > ciphers = MumbleSSL::ciphersFromOpenSSLCipherString(g.s.qsSslCiphers); if (ciphers.isEmpty()) { - qFatal("Invalid 'net/sslciphers' config option. Either the cipher string is invalid or none of the ciphers are available:: \"%s\"", qPrintable(g.s.qsSslCiphers)); + qFatal("Invalid 'net/sslciphers' config option. Either the cipher string is invalid or none of the ciphers " + "are available:: \"%s\"", + qPrintable(g.s.qsSslCiphers)); } QSslConfiguration config = QSslConfiguration::defaultConfiguration(); @@ -135,9 +138,7 @@ ServerHandler::ServerHandler() QSslConfiguration::setDefaultConfiguration(config); QStringList pref; - foreach (QSslCipher c, ciphers) { - pref << c.name(); - } + foreach (QSslCipher c, ciphers) { pref << c.name(); } qWarning("ServerHandler: TLS cipher preference is \"%s\"", qPrintable(pref.join(QLatin1String(":")))); } @@ -147,7 +148,7 @@ ServerHandler::ServerHandler() Connection::setQoS(hQoS); #endif - connect(this, SIGNAL(pingRequested()), this, SLOT(sendPingInternal()), Qt::QueuedConnection); + connect(this, SIGNAL(pingRequested()), this, SLOT(sendPingInternal()), Qt::QueuedConnection); } ServerHandler::~ServerHandler() { @@ -165,7 +166,7 @@ void ServerHandler::customEvent(QEvent *evt) { if (evt->type() != SERVERSEND_EVENT) return; - ServerHandlerMessageEvent *shme = static_cast<ServerHandlerMessageEvent *>(evt); + ServerHandlerMessageEvent *shme = static_cast< ServerHandlerMessageEvent * >(evt); ConnectionPtr connection(cConnection); if (connection) { @@ -184,13 +185,13 @@ void ServerHandler::udpReady() { while (qusUdp->hasPendingDatagrams()) { char encrypted[UDP_MAX_SIZE]; char buffer[UDP_MAX_SIZE]; - unsigned int buflen = static_cast<unsigned int>(qusUdp->pendingDatagramSize()); + unsigned int buflen = static_cast< unsigned int >(qusUdp->pendingDatagramSize()); if (buflen > UDP_MAX_SIZE) { // Discard datagrams that exceed our buffer's size as we'd have to trim them down anyways and it is not very // likely that the data is valid in the trimmed down form. - // As we're using a maxSize of 0 it is okay to pass nullptr as the data buffer. Qt's docs (5.15) ensures that - // a maxSize of 0 means discarding the datagram. + // As we're using a maxSize of 0 it is okay to pass nullptr as the data buffer. Qt's docs (5.15) ensures + // that a maxSize of 0 means discarding the datagram. qusUdp->readDatagram(nullptr, 0); continue; } @@ -203,16 +204,17 @@ void ServerHandler::udpReady() { continue; ConnectionPtr connection(cConnection); - if (! connection) + if (!connection) continue; - if (! connection->csCrypt->isValid()) + if (!connection->csCrypt->isValid()) continue; if (buflen < 5) continue; - if (! connection->csCrypt->decrypt(reinterpret_cast<const unsigned char *>(encrypted), reinterpret_cast<unsigned char *>(buffer), buflen)) { + if (!connection->csCrypt->decrypt(reinterpret_cast< const unsigned char * >(encrypted), + reinterpret_cast< unsigned char * >(buffer), buflen)) { if (connection->csCrypt->tLastGood.elapsed() > 5000000ULL) { if (connection->csCrypt->tLastRequest.elapsed() > 5000000ULL) { connection->csCrypt->tLastRequest.restart(); @@ -223,18 +225,17 @@ void ServerHandler::udpReady() { continue; } - PacketDataStream pds(buffer + 1, buflen-5); + PacketDataStream pds(buffer + 1, buflen - 5); - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((buffer[0] >> 5) & 0x7); - unsigned int msgFlags = buffer[0] & 0x1f; + MessageHandler::UDPMessageType msgType = static_cast< MessageHandler::UDPMessageType >((buffer[0] >> 5) & 0x7); + unsigned int msgFlags = buffer[0] & 0x1f; switch (msgType) { case MessageHandler::UDPPing: { - quint64 t; - pds >> t; - accUDP(static_cast<double>(tTimestamp.elapsed() - t) / 1000.0); - } - break; + quint64 t; + pds >> t; + accUDP(static_cast< double >(tTimestamp.elapsed() - t) / 1000.0); + } break; case MessageHandler::UDPVoiceCELTAlpha: case MessageHandler::UDPVoiceCELTBeta: case MessageHandler::UDPVoiceSpeex: @@ -247,28 +248,29 @@ void ServerHandler::udpReady() { } } -void ServerHandler::handleVoicePacket(unsigned int msgFlags, PacketDataStream &pds, MessageHandler::UDPMessageType type) { +void ServerHandler::handleVoicePacket(unsigned int msgFlags, PacketDataStream &pds, + MessageHandler::UDPMessageType type) { unsigned int uiSession; pds >> uiSession; - ClientUser *p = ClientUser::get(uiSession); + ClientUser *p = ClientUser::get(uiSession); AudioOutputPtr ao = g.ao; if (ao && p && !(((msgFlags & 0x1f) == 2) && g.s.bWhisperFriends && p->qsFriendName.isEmpty())) { unsigned int iSeq; pds >> iSeq; QByteArray qba; qba.reserve(pds.left() + 1); - qba.append(static_cast<char>(msgFlags)); + qba.append(static_cast< char >(msgFlags)); qba.append(pds.dataBlock(pds.left())); ao->addFrameToBuffer(p, qba, iSeq, type); } } void ServerHandler::sendMessage(const char *data, int len, bool force) { - STACKVAR(unsigned char, crypto, len+4); + STACKVAR(unsigned char, crypto, len + 4); QMutexLocker qml(&qmUdp); - if (! qusUdp) + if (!qusUdp) return; ConnectionPtr connection(cConnection); @@ -279,17 +281,17 @@ void ServerHandler::sendMessage(const char *data, int len, bool force) { QByteArray qba; qba.resize(len + 6); - unsigned char *uc = reinterpret_cast<unsigned char *>(qba.data()); - * reinterpret_cast<quint16 *>(& uc[0]) = qToBigEndian(static_cast<quint16>(MessageHandler::UDPTunnel)); - * reinterpret_cast<quint32 *>(& uc[2]) = qToBigEndian(static_cast<quint32>(len)); + unsigned char *uc = reinterpret_cast< unsigned char * >(qba.data()); + *reinterpret_cast< quint16 * >(&uc[0]) = qToBigEndian(static_cast< quint16 >(MessageHandler::UDPTunnel)); + *reinterpret_cast< quint32 * >(&uc[2]) = qToBigEndian(static_cast< quint32 >(len)); memcpy(uc + 6, data, len); QApplication::postEvent(this, new ServerHandlerMessageEvent(qba, MessageHandler::UDPTunnel, true)); } else { - if (!connection->csCrypt->encrypt(reinterpret_cast<const unsigned char *>(data), crypto, len)) { + if (!connection->csCrypt->encrypt(reinterpret_cast< const unsigned char * >(data), crypto, len)) { return; } - qusUdp->writeDatagram(reinterpret_cast<const char *>(crypto), len + 4, qhaRemote, usResolvedPort); + qusUdp->writeDatagram(reinterpret_cast< const char * >(crypto), len + 4, qhaRemote, usResolvedPort); } } @@ -298,7 +300,7 @@ void ServerHandler::sendProtoMessage(const ::google::protobuf::Message &msg, uns if (QThread::currentThread() != thread()) { Connection::messageToNetwork(msg, msgType, qba); - ServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qba, 0, false); + ServerHandlerMessageEvent *shme = new ServerHandlerMessageEvent(qba, 0, false); QApplication::postEvent(this, shme); } else { ConnectionPtr connection(cConnection); @@ -324,8 +326,8 @@ void ServerHandler::setServerSynchronized(bool synchronized) { } void ServerHandler::hostnameResolved() { - ServerResolver *sr = qobject_cast<ServerResolver *>(QObject::sender()); - QList<ServerResolverRecord> records = sr->records(); + ServerResolver *sr = qobject_cast< ServerResolver * >(QObject::sender()); + QList< ServerResolverRecord > records = sr->records(); // Exit the ServerHandler thread's event loop with an // error code in case our hostname lookup failed. @@ -336,11 +338,9 @@ void ServerHandler::hostnameResolved() { // Create the list of target host:port pairs // that the ServerHandler should try to connect to. - QList<ServerAddress> ql; + QList< ServerAddress > ql; foreach (ServerResolverRecord record, records) { - foreach (HostAddress addr, record.addresses()) { - ql.append(ServerAddress(addr, record.port())); - } + foreach (HostAddress addr, record.addresses()) { ql.append(ServerAddress(addr, record.port())); } } qlAddresses = ql; @@ -363,22 +363,22 @@ void ServerHandler::run() { } } - QList<ServerAddress> targetAddresses(qlAddresses); + QList< ServerAddress > targetAddresses(qlAddresses); bool shouldTryNextTargetServer = true; do { saTargetServer = qlAddresses.takeFirst(); tConnectionTimeoutTimer = nullptr; - qbaDigest = QByteArray(); - bStrong = true; - qtsSock = new QSslSocket(this); + qbaDigest = QByteArray(); + bStrong = true; + qtsSock = new QSslSocket(this); qtsSock->setPeerVerifyName(qsHostName); - if (! g.s.bSuppressIdentity && CertWizard::validateCert(g.s.kpCertificate)) { + if (!g.s.bSuppressIdentity && CertWizard::validateCert(g.s.kpCertificate)) { qtsSock->setPrivateKey(g.s.kpCertificate.second); qtsSock->setLocalCertificate(g.s.kpCertificate.first.at(0)); - QSslConfiguration config = qtsSock->sslConfiguration(); - QList<QSslCertificate> certs = config.caCertificates(); + QSslConfiguration config = qtsSock->sslConfiguration(); + QList< QSslCertificate > certs = config.caCertificates(); certs << g.s.kpCertificate.first; config.setCaCertificates(certs); qtsSock->setSslConfiguration(config); @@ -397,23 +397,27 @@ void ServerHandler::run() { qscCert.clear(); connect(qtsSock, SIGNAL(encrypted()), this, SLOT(serverConnectionConnected())); - connect(qtsSock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(serverConnectionStateChanged(QAbstractSocket::SocketState))); - connect(connection.get(), SIGNAL(connectionClosed(QAbstractSocket::SocketError, const QString &)), this, SLOT(serverConnectionClosed(QAbstractSocket::SocketError, const QString &))); - connect(connection.get(), SIGNAL(message(unsigned int, const QByteArray &)), this, SLOT(message(unsigned int, const QByteArray &))); - connect(connection.get(), SIGNAL(handleSslErrors(const QList<QSslError> &)), this, SLOT(setSslErrors(const QList<QSslError> &))); + connect(qtsSock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, + SLOT(serverConnectionStateChanged(QAbstractSocket::SocketState))); + connect(connection.get(), SIGNAL(connectionClosed(QAbstractSocket::SocketError, const QString &)), this, + SLOT(serverConnectionClosed(QAbstractSocket::SocketError, const QString &))); + connect(connection.get(), SIGNAL(message(unsigned int, const QByteArray &)), this, + SLOT(message(unsigned int, const QByteArray &))); + connect(connection.get(), SIGNAL(handleSslErrors(const QList< QSslError > &)), this, + SLOT(setSslErrors(const QList< QSslError > &))); } bUdp = false; - #if QT_VERSION >= 0x050500 +#if QT_VERSION >= 0x050500 qtsSock->setProtocol(QSsl::TlsV1_0OrLater); - #elif QT_VERSION >= 0x050400 +#elif QT_VERSION >= 0x050400 // In Qt 5.4, QSsl::SecureProtocols is equivalent // to "TLSv1.0 or later", which we require. qtsSock->setProtocol(QSsl::SecureProtocols); - #else +#else qtsSock->setProtocol(QSsl::TlsV1_0); - #endif +#endif qtsSock->connectToHost(saTargetServer.host.toAddress(), saTargetServer.port); @@ -428,9 +432,9 @@ void ServerHandler::run() { accUDP = accTCP = accClean; - uiVersion = 0; - qsRelease = QString(); - qsOS = QString(); + uiVersion = 0; + qsRelease = QString(); + qsOS = QString(); qsOSVersion = QString(); int ret = exec(); @@ -443,15 +447,17 @@ void ServerHandler::run() { if (qusUdp) { QMutexLocker qml(&qmUdp); - #ifdef Q_OS_WIN +#ifdef Q_OS_WIN if (hQoS) { if (!QOSRemoveSocketFromFlow(hQoS, 0, dwFlowUDP, 0)) { - qWarning("ServerHandler: Failed to remove UDP from QoS. QOSRemoveSocketFromFlow() failed with error %u!", GetLastError()); + qWarning( + "ServerHandler: Failed to remove UDP from QoS. QOSRemoveSocketFromFlow() failed with error %u!", + GetLastError()); } dwFlowUDP = 0; } - #endif +#endif delete qusUdp; qusUdp = nullptr; } @@ -464,7 +470,7 @@ void ServerHandler::run() { } cConnection.reset(); - while (! cptr.unique()) { + while (!cptr.unique()) { msleep(100); } delete qtsSock; @@ -473,38 +479,37 @@ void ServerHandler::run() { } #ifdef Q_OS_WIN -extern DWORD WinVerifySslCert(const QByteArray& cert); +extern DWORD WinVerifySslCert(const QByteArray &cert); #endif -void ServerHandler::setSslErrors(const QList<QSslError> &errors) { +void ServerHandler::setSslErrors(const QList< QSslError > &errors) { ConnectionPtr connection(cConnection); - if (!connection) return; + if (!connection) + return; - qscCert = connection->peerCertificateChain(); - QList<QSslError> newErrors = errors; + qscCert = connection->peerCertificateChain(); + QList< QSslError > newErrors = errors; #ifdef Q_OS_WIN bool bRevalidate = false; - QList<QSslError> errorsToRemove; - foreach (const QSslError& e, errors) { + QList< QSslError > errorsToRemove; + foreach (const QSslError &e, errors) { switch (e.error()) { - case QSslError::UnableToGetLocalIssuerCertificate: - case QSslError::SelfSignedCertificateInChain: - bRevalidate = true; - errorsToRemove << e; - break; - default: - break; + case QSslError::UnableToGetLocalIssuerCertificate: + case QSslError::SelfSignedCertificateInChain: + bRevalidate = true; + errorsToRemove << e; + break; + default: + break; } } if (bRevalidate) { - QByteArray der = qscCert.first().toDer(); + QByteArray der = qscCert.first().toDer(); DWORD errorStatus = WinVerifySslCert(der); if (errorStatus == CERT_TRUST_NO_ERROR) { - foreach (const QSslError& e, errorsToRemove) { - newErrors.removeOne(e); - } + foreach (const QSslError &e, errorsToRemove) { newErrors.removeOne(e); } } if (newErrors.isEmpty()) { connection->proceedAnyway(); @@ -514,7 +519,9 @@ void ServerHandler::setSslErrors(const QList<QSslError> &errors) { #endif bStrong = false; - if ((qscCert.size() > 0) && (QString::fromLatin1(qscCert.at(0).digest(QCryptographicHash::Sha1).toHex()) == database->getDigest(qsHostName, usPort))) + if ((qscCert.size() > 0) + && (QString::fromLatin1(qscCert.at(0).digest(QCryptographicHash::Sha1).toHex()) + == database->getDigest(qsHostName, usPort))) connection->proceedAnyway(); else qlErrors = newErrors; @@ -550,7 +557,7 @@ void ServerHandler::sendPingInternal() { PacketDataStream pds(buffer + 1, 255); buffer[0] = MessageHandler::UDPPing << 5; pds << t; - sendMessage(reinterpret_cast<const char *>(buffer), pds.size() + 1, true); + sendMessage(reinterpret_cast< const char * >(buffer), pds.size() + 1, true); } MumbleProto::Ping mpp; @@ -563,16 +570,16 @@ void ServerHandler::sendPingInternal() { if (boost::accumulators::count(accUDP)) { - mpp.set_udp_ping_avg(static_cast<float>(boost::accumulators::mean(accUDP))); - mpp.set_udp_ping_var(static_cast<float>(boost::accumulators::variance(accUDP))); + mpp.set_udp_ping_avg(static_cast< float >(boost::accumulators::mean(accUDP))); + mpp.set_udp_ping_var(static_cast< float >(boost::accumulators::variance(accUDP))); } - mpp.set_udp_packets(static_cast<int>(boost::accumulators::count(accUDP))); + mpp.set_udp_packets(static_cast< int >(boost::accumulators::count(accUDP))); if (boost::accumulators::count(accTCP)) { - mpp.set_tcp_ping_avg(static_cast<float>(boost::accumulators::mean(accTCP))); - mpp.set_tcp_ping_var(static_cast<float>(boost::accumulators::variance(accTCP))); + mpp.set_tcp_ping_avg(static_cast< float >(boost::accumulators::mean(accTCP))); + mpp.set_tcp_ping_var(static_cast< float >(boost::accumulators::variance(accTCP))); } - mpp.set_tcp_packets(static_cast<int>(boost::accumulators::count(accTCP))); + mpp.set_tcp_packets(static_cast< int >(boost::accumulators::count(accTCP))); sendMessage(mpp); @@ -585,8 +592,8 @@ void ServerHandler::message(unsigned int msgType, const QByteArray &qbaMsg) { if (qbaMsg.length() < 1) return; - MessageHandler::UDPMessageType umsgType = static_cast<MessageHandler::UDPMessageType>((ptr[0] >> 5) & 0x7); - unsigned int msgFlags = ptr[0] & 0x1f; + MessageHandler::UDPMessageType umsgType = static_cast< MessageHandler::UDPMessageType >((ptr[0] >> 5) & 0x7); + unsigned int msgFlags = ptr[0] & 0x1f; PacketDataStream pds(qbaMsg.constData() + 1, qbaMsg.size()); switch (umsgType) { @@ -603,24 +610,27 @@ void ServerHandler::message(unsigned int msgType, const QByteArray &qbaMsg) { MumbleProto::Ping msg; if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { ConnectionPtr connection(cConnection); - if (!connection) return; + if (!connection) + return; // Reset in-flight TCP ping counter to 0. // We've received a ping. That means the // connection is still OK. iInFlightTCPPings = 0; - connection->csCrypt->uiRemoteGood = msg.good(); - connection->csCrypt->uiRemoteLate = msg.late(); - connection->csCrypt->uiRemoteLost = msg.lost(); + connection->csCrypt->uiRemoteGood = msg.good(); + connection->csCrypt->uiRemoteLate = msg.late(); + connection->csCrypt->uiRemoteLost = msg.lost(); connection->csCrypt->uiRemoteResync = msg.resync(); - accTCP(static_cast<double>(tTimestamp.elapsed() - msg.timestamp()) / 1000.0); + accTCP(static_cast< double >(tTimestamp.elapsed() - msg.timestamp()) / 1000.0); - if (((connection->csCrypt->uiRemoteGood == 0) || (connection->csCrypt->uiGood == 0)) && bUdp && (tTimestamp.elapsed() > 20000000ULL)) { + if (((connection->csCrypt->uiRemoteGood == 0) || (connection->csCrypt->uiGood == 0)) && bUdp + && (tTimestamp.elapsed() > 20000000ULL)) { bUdp = false; - if (! NetworkConfig::TcpModeEnabled()) { + if (!NetworkConfig::TcpModeEnabled()) { if ((connection->csCrypt->uiRemoteGood == 0) && (connection->csCrypt->uiGood == 0)) - g.mw->msgBox(tr("UDP packets cannot be sent to or received from the server. Switching to TCP mode.")); + g.mw->msgBox( + tr("UDP packets cannot be sent to or received from the server. Switching to TCP mode.")); else if (connection->csCrypt->uiRemoteGood == 0) g.mw->msgBox(tr("UDP packets cannot be sent to the server. Switching to TCP mode.")); else @@ -630,15 +640,16 @@ void ServerHandler::message(unsigned int msgType, const QByteArray &qbaMsg) { } } else if (!bUdp && (connection->csCrypt->uiRemoteGood > 3) && (connection->csCrypt->uiGood > 3)) { bUdp = true; - if (! NetworkConfig::TcpModeEnabled()) { - g.mw->msgBox(tr("UDP packets can be sent to and received from the server. Switching back to UDP mode.")); + if (!NetworkConfig::TcpModeEnabled()) { + g.mw->msgBox( + tr("UDP packets can be sent to and received from the server. Switching back to UDP mode.")); database->setUdp(qbaDigest, true); } } } } else { - ServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaMsg, msgType, false); + ServerHandlerMessageEvent *shme = new ServerHandlerMessageEvent(qbaMsg, msgType, false); QApplication::postEvent(g.mw, shme); } } @@ -646,13 +657,13 @@ void ServerHandler::message(unsigned int msgType, const QByteArray &qbaMsg) { void ServerHandler::disconnect() { // Actual TCP object is in a different thread, so signal it QByteArray qbaBuffer; - ServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaBuffer, 0, false); + ServerHandlerMessageEvent *shme = new ServerHandlerMessageEvent(qbaBuffer, 0, false); QApplication::postEvent(this, shme); } void ServerHandler::serverConnectionClosed(QAbstractSocket::SocketError err, const QString &reason) { Connection *c = cConnection.get(); - if (! c) + if (!c) return; if (c->bDisconnectedEmitted) return; @@ -668,8 +679,8 @@ void ServerHandler::serverConnectionClosed(QAbstractSocket::SocketError err, con if (!qlAddresses.isEmpty()) { if (err == QAbstractSocket::ConnectionRefusedError || err == QAbstractSocket::SocketTimeoutError) { qWarning("ServerHandler: connection attempt to %s:%i failed: %s (%li); trying next server....", - qPrintable(saTargetServer.host.toString()), static_cast<int>(saTargetServer.port), - qPrintable(reason), static_cast<long>(err)); + qPrintable(saTargetServer.host.toString()), static_cast< int >(saTargetServer.port), + qPrintable(reason), static_cast< long >(err)); exit(-2); return; } @@ -703,7 +714,8 @@ void ServerHandler::serverConnectionStateChanged(QAbstractSocket::SocketState st void ServerHandler::serverConnectionConnected() { ConnectionPtr connection(cConnection); - if (!connection) return; + if (!connection) + return; iInFlightTCPPings = 0; @@ -712,13 +724,13 @@ void ServerHandler::serverConnectionConnected() { if (g.s.bQoS) connection->setToS(); - qscCert = connection->peerCertificateChain(); + qscCert = connection->peerCertificateChain(); qscCipher = connection->sessionCipher(); - if (! qscCert.isEmpty()) { + if (!qscCert.isEmpty()) { const QSslCertificate &qsc = qscCert.last(); - qbaDigest = sha1(qsc.publicKey().toDer()); - bUdp = database->getUdp(qbaDigest); + qbaDigest = sha1(qsc.publicKey().toDer()); + bUdp = database->getUdp(qbaDigest); } else { // Shouldn't reach this qCritical("Server must have a certificate. Dropping connection"); @@ -746,11 +758,11 @@ void ServerHandler::serverConnectionConnected() { mpa.set_password(u8(qsPassword)); QStringList tokens = database->getTokens(qbaDigest); - foreach(const QString &qs, tokens) + foreach (const QString &qs, tokens) mpa.add_tokens(u8(qs)); - QMap<int, CELTCodec *>::const_iterator i; - for (i=g.qmCodecs.constBegin(); i != g.qmCodecs.constEnd(); ++i) + QMap< int, CELTCodec * >::const_iterator i; + for (i = g.qmCodecs.constBegin(); i != g.qmCodecs.constEnd(); ++i) mpa.add_celt_versions(i.key()); #ifdef USE_OPUS mpa.set_opus(true); @@ -762,15 +774,15 @@ void ServerHandler::serverConnectionConnected() { { QMutexLocker qml(&qmUdp); - qhaRemote = connection->peerAddress(); - qhaLocal = connection->localAddress(); + qhaRemote = connection->peerAddress(); + qhaLocal = connection->localAddress(); usResolvedPort = connection->peerPort(); if (qhaLocal.isNull()) { qFatal("ServerHandler: qhaLocal is unexpectedly a null addr"); } qusUdp = new QUdpSocket(this); - if (! qusUdp) { + if (!qusUdp) { qFatal("ServerHandler: qusUdp is unexpectedly a null addr"); } if (g.s.bUdpForceTcpAddr) { @@ -786,23 +798,24 @@ void ServerHandler::serverConnectionConnected() { connect(qusUdp, SIGNAL(readyRead()), this, SLOT(udpReady())); if (g.s.bQoS) { - #if defined(Q_OS_UNIX) int val = 0xe0; - if (setsockopt(static_cast<int>(qusUdp->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) { + if (setsockopt(static_cast< int >(qusUdp->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) { val = 0x80; - if (setsockopt(static_cast<int>(qusUdp->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) + if (setsockopt(static_cast< int >(qusUdp->socketDescriptor()), IPPROTO_IP, IP_TOS, &val, sizeof(val))) qWarning("ServerHandler: Failed to set TOS for UDP Socket"); } -#if defined(SO_PRIORITY) +# if defined(SO_PRIORITY) socklen_t optlen = sizeof(val); - if (getsockopt(static_cast<int>(qusUdp->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, &optlen) == 0) { + if (getsockopt(static_cast< int >(qusUdp->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, &optlen) + == 0) { if (val == 0) { val = 6; - setsockopt(static_cast<int>(qusUdp->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, sizeof(val)); + setsockopt(static_cast< int >(qusUdp->socketDescriptor()), SOL_SOCKET, SO_PRIORITY, &val, + sizeof(val)); } } -#endif +# endif #elif defined(Q_OS_WIN) if (hQoS) { struct sockaddr_in addr; @@ -812,7 +825,9 @@ void ServerHandler::serverConnectionConnected() { addr.sin_addr.s_addr = htonl(qhaRemote.toIPv4Address()); dwFlowUDP = 0; - if (! QOSAddSocketToFlow(hQoS, qusUdp->socketDescriptor(), reinterpret_cast<sockaddr *>(&addr), QOSTrafficTypeVoice, QOS_NON_ADAPTIVE_FLOW, reinterpret_cast<PQOS_FLOWID>(&dwFlowUDP))) + if (!QOSAddSocketToFlow(hQoS, qusUdp->socketDescriptor(), reinterpret_cast< sockaddr * >(&addr), + QOSTrafficTypeVoice, QOS_NON_ADAPTIVE_FLOW, + reinterpret_cast< PQOS_FLOWID >(&dwFlowUDP))) qWarning("ServerHandler: Failed to add UDP to QOS"); } #endif @@ -822,18 +837,19 @@ void ServerHandler::serverConnectionConnected() { emit connected(); } -void ServerHandler::setConnectionInfo(const QString &host, unsigned short port, const QString &username, const QString &pw) { +void ServerHandler::setConnectionInfo(const QString &host, unsigned short port, const QString &username, + const QString &pw) { qsHostName = host; - usPort = port; + usPort = port; qsUserName = username; qsPassword = pw; } void ServerHandler::getConnectionInfo(QString &host, unsigned short &port, QString &username, QString &pw) const { - host = qsHostName; - port = usPort; + host = qsHostName; + port = usPort; username = qsUserName; - pw = qsPassword; + pw = qsPassword; } bool ServerHandler::isStrong() const { @@ -853,12 +869,13 @@ void ServerHandler::joinChannel(unsigned int uiSession, unsigned int channel) { joinChannel(uiSession, channel, EMPTY); } -void ServerHandler::joinChannel(unsigned int uiSession, unsigned int channel, const QStringList &temporaryAccessTokens) { +void ServerHandler::joinChannel(unsigned int uiSession, unsigned int channel, + const QStringList &temporaryAccessTokens) { MumbleProto::UserState mpus; mpus.set_session(uiSession); mpus.set_channel_id(channel); - foreach(const QString &tmpToken, temporaryAccessTokens) { + foreach (const QString &tmpToken, temporaryAccessTokens) { mpus.add_temporary_access_tokens(tmpToken.toUtf8().constData()); } @@ -869,7 +886,7 @@ void ServerHandler::startListeningToChannel(int channel) { startListeningToChannels({ channel }); } -void ServerHandler::startListeningToChannels(const QList<int> &channelIDs) { +void ServerHandler::startListeningToChannels(const QList< int > &channelIDs) { if (channelIDs.isEmpty()) { return; } @@ -877,7 +894,7 @@ void ServerHandler::startListeningToChannels(const QList<int> &channelIDs) { MumbleProto::UserState mpus; mpus.set_session(g.uiSession); - foreach(int currentChannel, channelIDs) { + foreach (int currentChannel, channelIDs) { // The naming of the function is a bit unfortunate but what this does is to add // the channel ID to the message field listening_channel_add mpus.add_listening_channel_add(currentChannel); @@ -890,7 +907,7 @@ void ServerHandler::stopListeningToChannel(int channel) { stopListeningToChannels({ channel }); } -void ServerHandler::stopListeningToChannels(const QList<int> &channelIDs) { +void ServerHandler::stopListeningToChannels(const QList< int > &channelIDs) { if (channelIDs.isEmpty()) { return; } @@ -898,7 +915,7 @@ void ServerHandler::stopListeningToChannels(const QList<int> &channelIDs) { MumbleProto::UserState mpus; mpus.set_session(g.uiSession); - foreach(int currentChannel, channelIDs) { + foreach (int currentChannel, channelIDs) { // The naming of the function is a bit unfortunate but what this does is to add // the channel ID to the message field listening_channel_remove mpus.add_listening_channel_remove(currentChannel); @@ -907,7 +924,8 @@ void ServerHandler::stopListeningToChannels(const QList<int> &channelIDs) { sendMessage(mpus); } -void ServerHandler::createChannel(unsigned int parent_id, const QString &name, const QString &description, unsigned int position, bool temporary, unsigned int maxUsers) { +void ServerHandler::createChannel(unsigned int parent_id, const QString &name, const QString &description, + unsigned int position, bool temporary, unsigned int maxUsers) { MumbleProto::ChannelState mpcs; mpcs.set_parent(parent_id); mpcs.set_name(u8(name)); @@ -965,7 +983,8 @@ void ServerHandler::sendChannelTextMessage(unsigned int channel, const QString & } else { mptm.add_channel_id(channel); - if (message_ == QString::fromUtf8(g.ccHappyEaster + 10)) g.bHappyEaster = true; + if (message_ == QString::fromUtf8(g.ccHappyEaster + 10)) + g.bHappyEaster = true; } mptm.set_message(u8(message_)); sendMessage(mptm); @@ -986,7 +1005,7 @@ void ServerHandler::setUserTexture(unsigned int uiSession, const QByteArray &qba } else { QByteArray raw = qba; - QBuffer qb(& raw); + QBuffer qb(&raw); qb.open(QIODevice::ReadOnly); QImageReader qir; @@ -1000,10 +1019,10 @@ void ServerHandler::setUserTexture(unsigned int uiSession, const QByteArray &qba qir.setFormat(fmt); qir.setDevice(&qb); - QSize sz = qir.size(); - const int TEX_MAX_WIDTH = 600; + QSize sz = qir.size(); + const int TEX_MAX_WIDTH = 600; const int TEX_MAX_HEIGHT = 60; - const int TEX_RGBA_SIZE = TEX_MAX_WIDTH*TEX_MAX_HEIGHT*4; + const int TEX_RGBA_SIZE = TEX_MAX_WIDTH * TEX_MAX_HEIGHT * 4; sz.scale(TEX_MAX_WIDTH, TEX_MAX_HEIGHT, Qt::KeepAspectRatio); qir.setScaledSize(sz); @@ -1013,7 +1032,8 @@ void ServerHandler::setUserTexture(unsigned int uiSession, const QByteArray &qba } raw = QByteArray(TEX_RGBA_SIZE, 0); - QImage img(reinterpret_cast<unsigned char *>(raw.data()), TEX_MAX_WIDTH, TEX_MAX_HEIGHT, QImage::Format_ARGB32); + QImage img(reinterpret_cast< unsigned char * >(raw.data()), TEX_MAX_WIDTH, TEX_MAX_HEIGHT, + QImage::Format_ARGB32); QPainter imgp(&img); imgp.setRenderHint(QPainter::Antialiasing); @@ -1021,7 +1041,7 @@ void ServerHandler::setUserTexture(unsigned int uiSession, const QByteArray &qba imgp.setCompositionMode(QPainter::CompositionMode_SourceOver); imgp.drawImage(0, 0, tex); - texture = qCompress(QByteArray(reinterpret_cast<const char *>(img.bits()), TEX_RGBA_SIZE)); + texture = qCompress(QByteArray(reinterpret_cast< const char * >(img.bits()), TEX_RGBA_SIZE)); } MumbleProto::UserState mpus; @@ -1029,14 +1049,14 @@ void ServerHandler::setUserTexture(unsigned int uiSession, const QByteArray &qba mpus.set_texture(blob(texture)); sendMessage(mpus); - if (! texture.isEmpty()) { + if (!texture.isEmpty()) { database->setBlob(sha1(texture), texture); } } void ServerHandler::setTokens(const QStringList &tokens) { MumbleProto::Authenticate msg; - foreach(const QString &qs, tokens) + foreach (const QString &qs, tokens) msg.add_tokens(u8(qs)); sendMessage(msg); } @@ -1082,18 +1102,18 @@ void ServerHandler::announceRecordingState(bool recording) { QUrl ServerHandler::getServerURL(bool withPassword) const { QUrl url; - + url.setScheme(QLatin1String("mumble")); url.setHost(qsHostName); if (usPort != DEFAULT_MUMBLE_PORT) { url.setPort(usPort); } - + url.setUserName(qsUserName); - + if (withPassword && !qsPassword.isEmpty()) { url.setPassword(qsPassword); } - + return url; } diff --git a/src/mumble/ServerHandler.h b/src/mumble/ServerHandler.h index feb50fc27..a598af5ab 100644 --- a/src/mumble/ServerHandler.h +++ b/src/mumble/ServerHandler.h @@ -9,33 +9,33 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #ifndef Q_MOC_RUN -# include <boost/accumulators/accumulators.hpp> -# include <boost/accumulators/statistics/stats.hpp> -# include <boost/accumulators/statistics/mean.hpp> -# include <boost/accumulators/statistics/variance.hpp> -# include <boost/shared_ptr.hpp> +# include <boost/accumulators/accumulators.hpp> +# include <boost/accumulators/statistics/mean.hpp> +# include <boost/accumulators/statistics/stats.hpp> +# include <boost/accumulators/statistics/variance.hpp> +# include <boost/shared_ptr.hpp> #endif #include <QtCore/QEvent> #include <QtCore/QMutex> #include <QtCore/QObject> +#include <QtCore/QStringList> #include <QtCore/QThread> #include <QtCore/QTimer> -#include <QtCore/QStringList> #include <QtNetwork/QHostAddress> #include <QtNetwork/QSslCipher> #include <QtNetwork/QSslError> #define SERVERSEND_EVENT 3501 -#include "Timer.h" #include "Message.h" #include "Mumble.pb.h" #include "ServerAddress.h" +#include "Timer.h" class Connection; class Database; @@ -46,140 +46,147 @@ class QSslSocket; class VoiceRecorder; class ServerHandlerMessageEvent : public QEvent { - public: - unsigned int uiType; - QByteArray qbaMsg; - bool bFlush; - ServerHandlerMessageEvent(const QByteArray &msg, unsigned int type, bool flush = false); +public: + unsigned int uiType; + QByteArray qbaMsg; + bool bFlush; + ServerHandlerMessageEvent(const QByteArray &msg, unsigned int type, bool flush = false); }; -typedef boost::shared_ptr<Connection> ConnectionPtr; +typedef boost::shared_ptr< Connection > ConnectionPtr; class ServerHandler : public QThread { - private: - Q_OBJECT - Q_DISABLE_COPY(ServerHandler) - - Database *database; - protected: - QString qsHostName; - QString qsUserName; - QString qsPassword; - unsigned short usPort; - unsigned short usResolvedPort; - bool bUdp; - bool bStrong; - - /// Flag indicating whether the server we are currently connected to has - /// finished synchronizing already. - bool serverSynchronized = false; +private: + Q_OBJECT + Q_DISABLE_COPY(ServerHandler) + + Database *database; + +protected: + QString qsHostName; + QString qsUserName; + QString qsPassword; + unsigned short usPort; + unsigned short usResolvedPort; + bool bUdp; + bool bStrong; + + /// Flag indicating whether the server we are currently connected to has + /// finished synchronizing already. + bool serverSynchronized = false; #ifdef Q_OS_WIN - HANDLE hQoS; - DWORD dwFlowUDP; + HANDLE hQoS; + DWORD dwFlowUDP; #endif - QHostAddress qhaRemote; - QHostAddress qhaLocal; - QUdpSocket *qusUdp; - QMutex qmUdp; - - void handleVoicePacket(unsigned int msgFlags, PacketDataStream &pds, MessageHandler::UDPMessageType type); - public: - Timer tTimestamp; - int iInFlightTCPPings; - QTimer *tConnectionTimeoutTimer; - QList<QSslError> qlErrors; - QList<QSslCertificate> qscCert; - QSslCipher qscCipher; - ConnectionPtr cConnection; - QByteArray qbaDigest; - boost::shared_ptr<VoiceRecorder> recorder; - QSslSocket *qtsSock; - QList<ServerAddress> qlAddresses; - ServerAddress saTargetServer; - - unsigned int uiVersion; - QString qsRelease; - QString qsOS; - QString qsOSVersion; - - boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::mean, boost::accumulators::tag::variance, boost::accumulators::tag::count> > accTCP, accUDP, accClean; - - ServerHandler(); - ~ServerHandler(); - void setConnectionInfo(const QString &host, unsigned short port, const QString &username, const QString &pw); - void getConnectionInfo(QString &host, unsigned short &port, QString &username, QString &pw) const; - bool isStrong() const; - void customEvent(QEvent *evt) Q_DECL_OVERRIDE; - - void sendProtoMessage(const ::google::protobuf::Message &msg, unsigned int msgType); - void sendMessage(const char *data, int len, bool force = false); - - /// @returns Whether this handler is currently connected to a server. - bool isConnected() const; - - /// @returns Whether the server this handler is currently connected to, has finished - /// synchronizing yet. - bool hasSynchronized() const; - - /// @param synchronized Whether the server has finished synchronization - void setServerSynchronized(bool synchronized); - -#define MUMBLE_MH_MSG(x) void sendMessage(const MumbleProto:: x &msg) { sendProtoMessage(msg, MessageHandler:: x); } - MUMBLE_MH_ALL + QHostAddress qhaRemote; + QHostAddress qhaLocal; + QUdpSocket *qusUdp; + QMutex qmUdp; + + void handleVoicePacket(unsigned int msgFlags, PacketDataStream &pds, MessageHandler::UDPMessageType type); + +public: + Timer tTimestamp; + int iInFlightTCPPings; + QTimer *tConnectionTimeoutTimer; + QList< QSslError > qlErrors; + QList< QSslCertificate > qscCert; + QSslCipher qscCipher; + ConnectionPtr cConnection; + QByteArray qbaDigest; + boost::shared_ptr< VoiceRecorder > recorder; + QSslSocket *qtsSock; + QList< ServerAddress > qlAddresses; + ServerAddress saTargetServer; + + unsigned int uiVersion; + QString qsRelease; + QString qsOS; + QString qsOSVersion; + + boost::accumulators::accumulator_set< + double, boost::accumulators::stats< boost::accumulators::tag::mean, boost::accumulators::tag::variance, + boost::accumulators::tag::count > > + accTCP, accUDP, accClean; + + ServerHandler(); + ~ServerHandler(); + void setConnectionInfo(const QString &host, unsigned short port, const QString &username, const QString &pw); + void getConnectionInfo(QString &host, unsigned short &port, QString &username, QString &pw) const; + bool isStrong() const; + void customEvent(QEvent *evt) Q_DECL_OVERRIDE; + + void sendProtoMessage(const ::google::protobuf::Message &msg, unsigned int msgType); + void sendMessage(const char *data, int len, bool force = false); + + /// @returns Whether this handler is currently connected to a server. + bool isConnected() const; + + /// @returns Whether the server this handler is currently connected to, has finished + /// synchronizing yet. + bool hasSynchronized() const; + + /// @param synchronized Whether the server has finished synchronization + void setServerSynchronized(bool synchronized); + +#define MUMBLE_MH_MSG(x) \ + void sendMessage(const MumbleProto::x &msg) { sendProtoMessage(msg, MessageHandler::x); } + MUMBLE_MH_ALL #undef MUMBLE_MH_MSG - void requestUserStats(unsigned int uiSession, bool statsOnly); - void joinChannel(unsigned int uiSession, unsigned int channel); - void joinChannel(unsigned int uiSession, unsigned int channel, const QStringList &temporaryAccessTokens); - void startListeningToChannel(int channel); - void startListeningToChannels(const QList<int> &channelIDs); - void stopListeningToChannel(int channel); - void stopListeningToChannels(const QList<int> &channelIDs); - void createChannel(unsigned int parent_id, const QString &name, const QString &description, unsigned int position, bool temporary, unsigned int maxUsers); - void requestBanList(); - void requestUserList(); - void requestACL(unsigned int channel); - void registerUser(unsigned int uiSession); - void kickBanUser(unsigned int uiSession, const QString &reason, bool ban); - void sendUserTextMessage(unsigned int uiSession, const QString &message_); - void sendChannelTextMessage(unsigned int channel, const QString &message_, bool tree); - void setUserComment(unsigned int uiSession, const QString &comment); - void setUserTexture(unsigned int uiSession, const QByteArray &qba); - void setTokens(const QStringList &tokens); - void removeChannel(unsigned int channel); - void addChannelLink(unsigned int channel, unsigned int link); - void removeChannelLink(unsigned int channel, unsigned int link); - void requestChannelPermissions(unsigned int channel); - void setSelfMuteDeafState(bool mute, bool deaf); - void announceRecordingState(bool recording); - - /// Return connection information as a URL - QUrl getServerURL(bool withPassword = false) const; - - void disconnect(); - void run() Q_DECL_OVERRIDE; - signals: - void error(QAbstractSocket::SocketError, QString reason); - void disconnected(QAbstractSocket::SocketError, QString reason); - void connected(); - void pingRequested(); - protected slots: - void message(unsigned int, const QByteArray &); - void serverConnectionConnected(); - void serverConnectionTimeoutOnConnect(); - void serverConnectionStateChanged(QAbstractSocket::SocketState); - void serverConnectionClosed(QAbstractSocket::SocketError, const QString &); - void setSslErrors(const QList<QSslError> &); - void udpReady(); - void hostnameResolved(); - private slots: - void sendPingInternal(); - public slots: - void sendPing(); + void requestUserStats(unsigned int uiSession, bool statsOnly); + void joinChannel(unsigned int uiSession, unsigned int channel); + void joinChannel(unsigned int uiSession, unsigned int channel, const QStringList &temporaryAccessTokens); + void startListeningToChannel(int channel); + void startListeningToChannels(const QList< int > &channelIDs); + void stopListeningToChannel(int channel); + void stopListeningToChannels(const QList< int > &channelIDs); + void createChannel(unsigned int parent_id, const QString &name, const QString &description, unsigned int position, + bool temporary, unsigned int maxUsers); + void requestBanList(); + void requestUserList(); + void requestACL(unsigned int channel); + void registerUser(unsigned int uiSession); + void kickBanUser(unsigned int uiSession, const QString &reason, bool ban); + void sendUserTextMessage(unsigned int uiSession, const QString &message_); + void sendChannelTextMessage(unsigned int channel, const QString &message_, bool tree); + void setUserComment(unsigned int uiSession, const QString &comment); + void setUserTexture(unsigned int uiSession, const QByteArray &qba); + void setTokens(const QStringList &tokens); + void removeChannel(unsigned int channel); + void addChannelLink(unsigned int channel, unsigned int link); + void removeChannelLink(unsigned int channel, unsigned int link); + void requestChannelPermissions(unsigned int channel); + void setSelfMuteDeafState(bool mute, bool deaf); + void announceRecordingState(bool recording); + + /// Return connection information as a URL + QUrl getServerURL(bool withPassword = false) const; + + void disconnect(); + void run() Q_DECL_OVERRIDE; +signals: + void error(QAbstractSocket::SocketError, QString reason); + void disconnected(QAbstractSocket::SocketError, QString reason); + void connected(); + void pingRequested(); +protected slots: + void message(unsigned int, const QByteArray &); + void serverConnectionConnected(); + void serverConnectionTimeoutOnConnect(); + void serverConnectionStateChanged(QAbstractSocket::SocketState); + void serverConnectionClosed(QAbstractSocket::SocketError, const QString &); + void setSslErrors(const QList< QSslError > &); + void udpReady(); + void hostnameResolved(); +private slots: + void sendPingInternal(); +public slots: + void sendPing(); }; -typedef boost::shared_ptr<ServerHandler> ServerHandlerPtr; +typedef boost::shared_ptr< ServerHandler > ServerHandlerPtr; #endif diff --git a/src/mumble/Settings.cpp b/src/mumble/Settings.cpp index 2f99e969d..5df753d4b 100644 --- a/src/mumble/Settings.cpp +++ b/src/mumble/Settings.cpp @@ -21,33 +21,36 @@ #include <limits> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -const QPoint Settings::UNSPECIFIED_POSITION = QPoint(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); +const QPoint Settings::UNSPECIFIED_POSITION = + QPoint(std::numeric_limits< int >::min(), std::numeric_limits< int >::max()); bool Shortcut::isServerSpecific() const { - if (qvData.canConvert<ShortcutTarget>()) { - const ShortcutTarget &sc = qvariant_cast<ShortcutTarget> (qvData); + if (qvData.canConvert< ShortcutTarget >()) { + const ShortcutTarget &sc = qvariant_cast< ShortcutTarget >(qvData); return sc.isServerSpecific(); } return false; } -bool Shortcut::operator < (const Shortcut &other) const { +bool Shortcut::operator<(const Shortcut &other) const { return (iIndex < other.iIndex); } -bool Shortcut::operator == (const Shortcut &other) const { - return (iIndex == other.iIndex) && (qlButtons == other.qlButtons) && (qvData == other.qvData) && (bSuppress == other.bSuppress); +bool Shortcut::operator==(const Shortcut &other) const { + return (iIndex == other.iIndex) && (qlButtons == other.qlButtons) && (qvData == other.qvData) + && (bSuppress == other.bSuppress); } ShortcutTarget::ShortcutTarget() { - bUsers = true; + bUsers = true; bCurrentSelection = false; - iChannel = -3; + iChannel = -3; bLinks = bChildren = bForceCenter = false; } @@ -55,7 +58,7 @@ bool ShortcutTarget::isServerSpecific() const { return !bCurrentSelection && !bUsers && iChannel >= 0; } -bool ShortcutTarget::operator == (const ShortcutTarget &o) const { +bool ShortcutTarget::operator==(const ShortcutTarget &o) const { if ((bUsers != o.bUsers) || (bForceCenter != o.bForceCenter) || (bCurrentSelection != o.bCurrentSelection)) return false; if (bUsers) @@ -72,7 +75,7 @@ quint32 qHash(const ShortcutTarget &t) { } if (t.bUsers) { - foreach(unsigned int u, t.qlSessions) + foreach (unsigned int u, t.qlSessions) h ^= u; } else { h ^= t.iChannel; @@ -86,14 +89,14 @@ quint32 qHash(const ShortcutTarget &t) { return h; } -quint32 qHash(const QList<ShortcutTarget> &l) { +quint32 qHash(const QList< ShortcutTarget > &l) { quint32 h = l.count(); - foreach(const ShortcutTarget &st, l) + foreach (const ShortcutTarget &st, l) h ^= qHash(st); return h; } -QDataStream &operator<< (QDataStream &qds, const ShortcutTarget &st) { +QDataStream &operator<<(QDataStream &qds, const ShortcutTarget &st) { // Start by the version of this setting. This is needed to make sure we can stay compatible // with older versions (aka don't break existing shortcuts when updating the implementation) qds << QString::fromLatin1("v2"); @@ -109,7 +112,7 @@ QDataStream &operator<< (QDataStream &qds, const ShortcutTarget &st) { } } -QDataStream &operator>> (QDataStream &qds, ShortcutTarget &st) { +QDataStream &operator>>(QDataStream &qds, ShortcutTarget &st) { // Check for presence of a leading version string QString versionString; QIODevice *device = qds.device(); @@ -127,7 +130,7 @@ QDataStream &operator>> (QDataStream &qds, ShortcutTarget &st) { int read = device->peek(buf, sizeof(buf)); for (int i = 0; i < read; i++) { - if (buf[i] >= 31 ) { + if (buf[i] >= 31) { if (buf[i] == 'v') { qds >> versionString; } else { @@ -154,44 +157,44 @@ QDataStream &operator>> (QDataStream &qds, ShortcutTarget &st) { } } -const QString Settings::cqsDefaultPushClickOn = QLatin1String(":/on.ogg"); +const QString Settings::cqsDefaultPushClickOn = QLatin1String(":/on.ogg"); const QString Settings::cqsDefaultPushClickOff = QLatin1String(":/off.ogg"); OverlaySettings::OverlaySettings() { bEnable = false; - fX = 1.0f; - fY = 0.0f; + fX = 1.0f; + fY = 0.0f; fZoom = 0.875f; #ifdef Q_OS_MAC qsStyle = QLatin1String("Cleanlooks"); #endif - osShow = LinkedChannels; - bAlwaysSelf = true; + osShow = LinkedChannels; + bAlwaysSelf = true; uiActiveTime = 5; - osSort = Alphabetical; + osSort = Alphabetical; - qcUserName[Settings::Passive] = QColor(170, 170, 170); + qcUserName[Settings::Passive] = QColor(170, 170, 170); qcUserName[Settings::MutedTalking] = QColor(170, 170, 170); - qcUserName[Settings::Talking] = QColor(255, 255, 255); - qcUserName[Settings::Whispering] = QColor(128, 255, 128); - qcUserName[Settings::Shouting] = QColor(255, 128, 255); - qcChannel = QColor(255, 255, 128); - qcBoxPen = QColor(0, 0, 0, 224); - qcBoxFill = QColor(0, 0, 0); + qcUserName[Settings::Talking] = QColor(255, 255, 255); + qcUserName[Settings::Whispering] = QColor(128, 255, 128); + qcUserName[Settings::Shouting] = QColor(255, 128, 255); + qcChannel = QColor(255, 255, 128); + qcBoxPen = QColor(0, 0, 0, 224); + qcBoxFill = QColor(0, 0, 0); setPreset(); // FPS and Time display settings - qcFps = Qt::white; - fFps = 0.75f; - qfFps = qfUserName; - qrfFps = QRectF(0.0f, 0.05, -1, 0.023438f); - bFps = false; + qcFps = Qt::white; + fFps = 0.75f; + qfFps = qfUserName; + qrfFps = QRectF(0.0f, 0.05, -1, 0.023438f); + bFps = false; qrfTime = QRectF(0.0f, 0.0, -1, 0.023438f); - bTime = false; + bTime = false; oemOverlayExcludeMode = OverlaySettings::LauncherFilterExclusionMode; } @@ -199,11 +202,11 @@ OverlaySettings::OverlaySettings() { void OverlaySettings::setPreset(const OverlayPresets preset) { switch (preset) { case LargeSquareAvatar: - uiColumns = 2; - fUserName = 0.75f; - fChannel = 0.75f; + uiColumns = 2; + fUserName = 0.75f; + fChannel = 0.75f; fMutedDeafened = 0.5f; - fAvatar = 1.0f; + fAvatar = 1.0f; #if defined(Q_OS_WIN) || defined(Q_OS_MAC) qfUserName = QFont(QLatin1String("Verdana"), 20); @@ -212,38 +215,38 @@ void OverlaySettings::setPreset(const OverlayPresets preset) { #endif qfChannel = qfUserName; - fUser[Settings::Passive] = 0.5f; + fUser[Settings::Passive] = 0.5f; fUser[Settings::MutedTalking] = 0.5f; - fUser[Settings::Talking] = (7.0f / 8.0f); - fUser[Settings::Whispering] = (7.0f / 8.0f); - fUser[Settings::Shouting] = (7.0f / 8.0f); + fUser[Settings::Talking] = (7.0f / 8.0f); + fUser[Settings::Whispering] = (7.0f / 8.0f); + fUser[Settings::Shouting] = (7.0f / 8.0f); - qrfUserName = QRectF(-0.0625f, 0.101563f - 0.0625f, 0.125f, 0.023438f); - qrfChannel = QRectF(-0.03125f, -0.0625f, 0.09375f, 0.015625f); + qrfUserName = QRectF(-0.0625f, 0.101563f - 0.0625f, 0.125f, 0.023438f); + qrfChannel = QRectF(-0.03125f, -0.0625f, 0.09375f, 0.015625f); qrfMutedDeafened = QRectF(-0.0625f, -0.0625f, 0.0625f, 0.0625f); - qrfAvatar = QRectF(-0.0625f, -0.0625f, 0.125f, 0.125f); + qrfAvatar = QRectF(-0.0625f, -0.0625f, 0.125f, 0.125f); fBoxPenWidth = (1.f / 256.0f); - fBoxPad = (1.f / 256.0f); + fBoxPad = (1.f / 256.0f); - bUserName = true; - bChannel = true; + bUserName = true; + bChannel = true; bMutedDeafened = true; - bAvatar = true; - bBox = false; + bAvatar = true; + bBox = false; - qaUserName = Qt::AlignCenter; + qaUserName = Qt::AlignCenter; qaMutedDeafened = Qt::AlignLeft | Qt::AlignTop; - qaAvatar = Qt::AlignCenter; - qaChannel = Qt::AlignCenter; + qaAvatar = Qt::AlignCenter; + qaChannel = Qt::AlignCenter; break; case AvatarAndName: default: - uiColumns = 1; - fUserName = 1.0f; - fChannel = (7.0f / 8.0f); + uiColumns = 1; + fUserName = 1.0f; + fChannel = (7.0f / 8.0f); fMutedDeafened = (7.0f / 8.0f); - fAvatar = 1.0f; + fAvatar = 1.0f; #if defined(Q_OS_WIN) || defined(Q_OS_MAC) qfUserName = QFont(QLatin1String("Verdana"), 20); @@ -252,81 +255,81 @@ void OverlaySettings::setPreset(const OverlayPresets preset) { #endif qfChannel = qfUserName; - fUser[Settings::Passive] = 0.5f; + fUser[Settings::Passive] = 0.5f; fUser[Settings::MutedTalking] = 0.5f; - fUser[Settings::Talking] = (7.0f / 8.0f); - fUser[Settings::Whispering] = (7.0f / 8.0f); - fUser[Settings::Shouting] = (7.0f / 8.0f); + fUser[Settings::Talking] = (7.0f / 8.0f); + fUser[Settings::Whispering] = (7.0f / 8.0f); + fUser[Settings::Shouting] = (7.0f / 8.0f); - qrfUserName = QRectF(0.015625f, -0.015625f, 0.250f, 0.03125f); - qrfChannel = QRectF(0.03125f, -0.015625f, 0.1875f, 0.015625f); + qrfUserName = QRectF(0.015625f, -0.015625f, 0.250f, 0.03125f); + qrfChannel = QRectF(0.03125f, -0.015625f, 0.1875f, 0.015625f); qrfMutedDeafened = QRectF(0.234375f, -0.015625f, 0.03125f, 0.03125f); - qrfAvatar = QRectF(-0.03125f, -0.015625f, 0.03125f, 0.03125f); + qrfAvatar = QRectF(-0.03125f, -0.015625f, 0.03125f, 0.03125f); fBoxPenWidth = 0.0f; - fBoxPad = (1.f / 256.0f); + fBoxPad = (1.f / 256.0f); - bUserName = true; - bChannel = false; + bUserName = true; + bChannel = false; bMutedDeafened = true; - bAvatar = true; - bBox = true; + bAvatar = true; + bBox = true; - qaUserName = Qt::AlignLeft | Qt::AlignVCenter; + qaUserName = Qt::AlignLeft | Qt::AlignVCenter; qaMutedDeafened = Qt::AlignRight | Qt::AlignVCenter; - qaAvatar = Qt::AlignCenter; - qaChannel = Qt::AlignLeft | Qt::AlignTop; + qaAvatar = Qt::AlignCenter; + qaChannel = Qt::AlignLeft | Qt::AlignTop; break; } } Settings::Settings() { - qRegisterMetaType<ShortcutTarget> ("ShortcutTarget"); - qRegisterMetaTypeStreamOperators<ShortcutTarget> ("ShortcutTarget"); - qRegisterMetaType<QVariant> ("QVariant"); + qRegisterMetaType< ShortcutTarget >("ShortcutTarget"); + qRegisterMetaTypeStreamOperators< ShortcutTarget >("ShortcutTarget"); + qRegisterMetaType< QVariant >("QVariant"); - atTransmit = VAD; + atTransmit = VAD; bTransmitPosition = false; - bMute = bDeaf = false; - bTTS = true; - bTTSMessageReadBack = false; - bTTSNoScope = false; - bTTSNoAuthor = false; - iTTSVolume = 75; - iTTSThreshold = 250; - qsTTSLanguage = QString(); - iQuality = 40000; - fVolume = 1.0f; - fOtherVolume = 0.5f; - bAttenuateOthersOnTalk = false; - bAttenuateOthers = false; + bMute = bDeaf = false; + bTTS = true; + bTTSMessageReadBack = false; + bTTSNoScope = false; + bTTSNoAuthor = false; + iTTSVolume = 75; + iTTSThreshold = 250; + qsTTSLanguage = QString(); + iQuality = 40000; + fVolume = 1.0f; + fOtherVolume = 0.5f; + bAttenuateOthersOnTalk = false; + bAttenuateOthers = false; bAttenuateUsersOnPrioritySpeak = false; - bOnlyAttenuateSameOutput = false; - bAttenuateLoopbacks = false; - iMinLoudness = 1000; - iVoiceHold = 50; - iJitterBufferSize = 1; - iFramesPerPacket = 2; + bOnlyAttenuateSameOutput = false; + bAttenuateLoopbacks = false; + iMinLoudness = 1000; + iVoiceHold = 50; + iJitterBufferSize = 1; + iFramesPerPacket = 2; #ifdef USE_RNNOISE noiseCancelMode = NoiseCancelRNN; #else noiseCancelMode = NoiseCancelSpeex; #endif iSpeexNoiseCancelStrength = -30; - bAllowLowDelay = true; - uiAudioInputChannelMask = 0xffffffffffffffffULL; + bAllowLowDelay = true; + uiAudioInputChannelMask = 0xffffffffffffffffULL; // Idle auto actions - iIdleTime = 5 * 60; - iaeIdleAction = Nothing; + iIdleTime = 5 * 60; + iaeIdleAction = Nothing; bUndoIdleActionUponActivity = false; - vsVAD = Amplitude; + vsVAD = Amplitude; fVADmin = 0.80f; fVADmax = 0.98f; - bTxAudioCue = false; - qsTxAudioCueOn = cqsDefaultPushClickOn; + bTxAudioCue = false; + qsTxAudioCueOn = cqsDefaultPushClickOn; qsTxAudioCueOff = cqsDefaultPushClickOff; bUserTop = true; @@ -334,7 +337,7 @@ Settings::Settings() { bWhisperFriends = false; uiDoublePush = 0; - pttHold = 0; + pttHold = 0; #ifdef NO_UPDATE_CHECK bUpdateCheck = false; @@ -346,32 +349,33 @@ Settings::Settings() { qsImagePath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); - ceExpand = ChannelsWithUsers; - ceChannelDrag = Ask; - ceUserDrag = Move; - bMinimalView = false; - bHideFrame = false; - aotbAlwaysOnTop = OnTopNever; - bAskOnQuit = true; + ceExpand = ChannelsWithUsers; + ceChannelDrag = Ask; + ceUserDrag = Move; + bMinimalView = false; + bHideFrame = false; + aotbAlwaysOnTop = OnTopNever; + bAskOnQuit = true; bEnableDeveloperMenu = false; - bLockLayout = false; + bLockLayout = false; #ifdef Q_OS_WIN // Don't enable minimize to tray by default on Windows >= 7 const QSysInfo::WinVersion winVer = QSysInfo::windowsVersion(); - bHideInTray = (winVer < QSysInfo::WV_WINDOWS7); + bHideInTray = (winVer < QSysInfo::WV_WINDOWS7); #else - const bool isUnityDesktop = QProcessEnvironment::systemEnvironment().value(QLatin1String("XDG_CURRENT_DESKTOP")) == QLatin1String("Unity"); + const bool isUnityDesktop = + QProcessEnvironment::systemEnvironment().value(QLatin1String("XDG_CURRENT_DESKTOP")) == QLatin1String("Unity"); bHideInTray = !isUnityDesktop && QSystemTrayIcon::isSystemTrayAvailable(); #endif - bStateInTray = true; - bUsage = true; - bShowUserCount = false; - bShowVolumeAdjustments = true; - bChatBarUseSelection = false; + bStateInTray = true; + bUsage = true; + bShowUserCount = false; + bShowVolumeAdjustments = true; + bChatBarUseSelection = false; bFilterHidesEmptyChannels = true; - bFilterActive = false; + bFilterActive = false; - wlWindowLayout = LayoutClassic; + wlWindowLayout = LayoutClassic; bShowContextMenuInMenuBar = false; ssFilter = ShowReachable; @@ -380,13 +384,13 @@ Settings::Settings() { bASIOEnable = true; - qsALSAInput=QLatin1String("default"); - qsALSAOutput=QLatin1String("default"); + qsALSAInput = QLatin1String("default"); + qsALSAOutput = QLatin1String("default"); - qsJackClientName = QLatin1String("mumble"); + qsJackClientName = QLatin1String("mumble"); qsJackAudioOutput = QLatin1String("1"); - bJackStartServer = false; - bJackAutoConnect = true; + bJackStartServer = false; + bJackAutoConnect = true; #ifndef Q_OS_MAC // Enable echo cancellation by default everywhere except for Macs as we currently @@ -397,47 +401,47 @@ Settings::Settings() { #endif bEchoMulti = false; - bExclusiveInput = false; + bExclusiveInput = false; bExclusiveOutput = false; - iPortAudioInput = -1; // default device + iPortAudioInput = -1; // default device iPortAudioOutput = -1; // default device - bPositionalAudio = true; + bPositionalAudio = true; bPositionalHeadphone = false; - fAudioMinDistance = 1.0f; - fAudioMaxDistance = 15.0f; - fAudioMaxDistVolume = 0.80f; - fAudioBloom = 0.5f; + fAudioMinDistance = 1.0f; + fAudioMaxDistance = 15.0f; + fAudioMaxDistVolume = 0.80f; + fAudioBloom = 0.5f; // OverlayPrivateWin iOverlayWinHelperRestartCooldownMsec = 10000; - bOverlayWinHelperX86Enable = true; - bOverlayWinHelperX64Enable = true; + bOverlayWinHelperX86Enable = true; + bOverlayWinHelperX64Enable = true; - iLCDUserViewMinColWidth = 50; + iLCDUserViewMinColWidth = 50; iLCDUserViewSplitterWidth = 2; // PTT Button window bShowPTTButtonWindow = false; // Network settings - bTCPCompat = false; - bQoS = true; - bReconnect = true; - bAutoConnect = false; - bDisablePublicList = false; - ptProxyType = NoProxy; - usProxyPort = 0; - iMaxInFlightTCPPings = 4; - bUdpForceTcpAddr = true; - iPingIntervalMsec = 5000; + bTCPCompat = false; + bQoS = true; + bReconnect = true; + bAutoConnect = false; + bDisablePublicList = false; + ptProxyType = NoProxy; + usProxyPort = 0; + iMaxInFlightTCPPings = 4; + bUdpForceTcpAddr = true; + iPingIntervalMsec = 5000; iConnectionTimeoutDurationMsec = 30000; - iMaxImageWidth = 1024; // Allow 1024x1024 resolution - iMaxImageHeight = 1024; - bSuppressIdentity = false; - qsSslCiphers = MumbleSSL::defaultOpenSSLCipherString(); - bHideOS = false; + iMaxImageWidth = 1024; // Allow 1024x1024 resolution + iMaxImageHeight = 1024; + bSuppressIdentity = false; + qsSslCiphers = MumbleSSL::defaultOpenSSLCipherString(); + bHideOS = false; bShowTransmitModeComboBox = false; @@ -445,15 +449,15 @@ Settings::Settings() { bHighContrast = false; // Recording - qsRecordingPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); - qsRecordingFile = QLatin1String("Mumble-%date-%time-%host-%user"); - rmRecordingMode = RecordingMixdown; + qsRecordingPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); + qsRecordingFile = QLatin1String("Mumble-%date-%time-%host-%user"); + rmRecordingMode = RecordingMixdown; iRecordingFormat = 0; // Special configuration options not exposed to UI - bDisableCELT = false; + bDisableCELT = false; disableConnectDialogEditing = false; - bPingServersDialogViewed = false; + bPingServersDialogViewed = false; // Config updates uiUpdateCounter = 0; @@ -463,83 +467,83 @@ Settings::Settings() { #else lmLoopMode = None; #endif - dPacketLoss = 0; + dPacketLoss = 0; dMaxPacketDelay = 0.0f; - + requireRestartToApply = false; - iMaxLogBlocks = 0; - bLog24HourClock = true; + iMaxLogBlocks = 0; + bLog24HourClock = true; iChatMessageMargins = 3; - qpTalkingUI_Position = UNSPECIFIED_POSITION; - bShowTalkingUI = false; - bTalkingUI_LocalUserStaysVisible = false; - bTalkingUI_AbbreviateChannelNames = true; + qpTalkingUI_Position = UNSPECIFIED_POSITION; + bShowTalkingUI = false; + bTalkingUI_LocalUserStaysVisible = false; + bTalkingUI_AbbreviateChannelNames = true; bTalkingUI_AbbreviateCurrentChannel = false; - bTalkingUI_ShowLocalListeners = false; - iTalkingUI_RelativeFontSize = 100; - iTalkingUI_SilentUserLifeTime = 10; - iTalkingUI_ChannelHierarchyDepth = 1; - iTalkingUI_MaxChannelNameLength = 20; - iTalkingUI_PrefixCharCount = 3; - iTalkingUI_PostfixCharCount = 2; - qsTalkingUI_ChannelSeparator = QLatin1String("/"); + bTalkingUI_ShowLocalListeners = false; + iTalkingUI_RelativeFontSize = 100; + iTalkingUI_SilentUserLifeTime = 10; + iTalkingUI_ChannelHierarchyDepth = 1; + iTalkingUI_MaxChannelNameLength = 20; + iTalkingUI_PrefixCharCount = 3; + iTalkingUI_PostfixCharCount = 2; + qsTalkingUI_ChannelSeparator = QLatin1String("/"); qsTalkingUI_AbbreviationReplacement = QLatin1String("..."); manualPlugin_silentUserDisplaytime = 1; - bShortcutEnable = true; + bShortcutEnable = true; bSuppressMacEventTapWarning = false; - bEnableEvdev = false; - bEnableXInput2 = true; - bEnableGKey = false; - bEnableXboxInput = true; - bEnableWinHooks = true; - bDirectInputVerboseLogging = false; - bEnableUIAccess = true; - - for (int i=Log::firstMsgType; i<=Log::lastMsgType; ++i) { + bEnableEvdev = false; + bEnableXInput2 = true; + bEnableGKey = false; + bEnableXboxInput = true; + bEnableWinHooks = true; + bDirectInputVerboseLogging = false; + bEnableUIAccess = true; + + for (int i = Log::firstMsgType; i <= Log::lastMsgType; ++i) { qmMessages.insert(i, Settings::LogConsole | Settings::LogBalloon | Settings::LogTTS); qmMessageSounds.insert(i, QString()); } - qmMessageSounds[Log::CriticalError] = QLatin1String(":/Critical.ogg"); - qmMessageSounds[Log::PermissionDenied] = QLatin1String(":/PermissionDenied.ogg"); - qmMessageSounds[Log::SelfMute] = QLatin1String(":/SelfMutedDeafened.ogg"); - qmMessageSounds[Log::SelfUnmute] = QLatin1String(":/SelfMutedDeafened.ogg"); - qmMessageSounds[Log::SelfDeaf] = QLatin1String(":/SelfMutedDeafened.ogg"); - qmMessageSounds[Log::SelfUndeaf] = QLatin1String(":/SelfMutedDeafened.ogg"); - qmMessageSounds[Log::ServerConnected] = QLatin1String(":/ServerConnected.ogg"); - qmMessageSounds[Log::ServerDisconnected] = QLatin1String(":/ServerDisconnected.ogg"); - qmMessageSounds[Log::TextMessage] = QLatin1String(":/TextMessage.ogg"); - qmMessageSounds[Log::PrivateTextMessage] = qmMessageSounds[Log::TextMessage]; - qmMessageSounds[Log::ChannelJoin] = QLatin1String(":/UserJoinedChannel.ogg"); - qmMessageSounds[Log::ChannelLeave] = QLatin1String(":/UserLeftChannel.ogg"); - qmMessageSounds[Log::ChannelJoinConnect] = qmMessageSounds[Log::ChannelJoin]; + qmMessageSounds[Log::CriticalError] = QLatin1String(":/Critical.ogg"); + qmMessageSounds[Log::PermissionDenied] = QLatin1String(":/PermissionDenied.ogg"); + qmMessageSounds[Log::SelfMute] = QLatin1String(":/SelfMutedDeafened.ogg"); + qmMessageSounds[Log::SelfUnmute] = QLatin1String(":/SelfMutedDeafened.ogg"); + qmMessageSounds[Log::SelfDeaf] = QLatin1String(":/SelfMutedDeafened.ogg"); + qmMessageSounds[Log::SelfUndeaf] = QLatin1String(":/SelfMutedDeafened.ogg"); + qmMessageSounds[Log::ServerConnected] = QLatin1String(":/ServerConnected.ogg"); + qmMessageSounds[Log::ServerDisconnected] = QLatin1String(":/ServerDisconnected.ogg"); + qmMessageSounds[Log::TextMessage] = QLatin1String(":/TextMessage.ogg"); + qmMessageSounds[Log::PrivateTextMessage] = qmMessageSounds[Log::TextMessage]; + qmMessageSounds[Log::ChannelJoin] = QLatin1String(":/UserJoinedChannel.ogg"); + qmMessageSounds[Log::ChannelLeave] = QLatin1String(":/UserLeftChannel.ogg"); + qmMessageSounds[Log::ChannelJoinConnect] = qmMessageSounds[Log::ChannelJoin]; qmMessageSounds[Log::ChannelLeaveDisconnect] = qmMessageSounds[Log::ChannelLeave]; - qmMessageSounds[Log::YouMutedOther] = QLatin1String(":/UserMutedYouOrByYou.ogg"); - qmMessageSounds[Log::YouMuted] = QLatin1String(":/UserMutedYouOrByYou.ogg"); - qmMessageSounds[Log::YouKicked] = QLatin1String(":/UserKickedYouOrByYou.ogg"); - qmMessageSounds[Log::Recording] = QLatin1String(":/RecordingStateChanged.ogg"); - - qmMessages[Log::DebugInfo] = Settings::LogConsole; - qmMessages[Log::Warning] = Settings::LogConsole | Settings::LogBalloon; - qmMessages[Log::Information] = Settings::LogConsole; - qmMessages[Log::UserJoin] = Settings::LogConsole; - qmMessages[Log::UserLeave] = Settings::LogConsole; - qmMessages[Log::UserKicked] = Settings::LogConsole; - qmMessages[Log::OtherSelfMute] = Settings::LogConsole; + qmMessageSounds[Log::YouMutedOther] = QLatin1String(":/UserMutedYouOrByYou.ogg"); + qmMessageSounds[Log::YouMuted] = QLatin1String(":/UserMutedYouOrByYou.ogg"); + qmMessageSounds[Log::YouKicked] = QLatin1String(":/UserKickedYouOrByYou.ogg"); + qmMessageSounds[Log::Recording] = QLatin1String(":/RecordingStateChanged.ogg"); + + qmMessages[Log::DebugInfo] = Settings::LogConsole; + qmMessages[Log::Warning] = Settings::LogConsole | Settings::LogBalloon; + qmMessages[Log::Information] = Settings::LogConsole; + qmMessages[Log::UserJoin] = Settings::LogConsole; + qmMessages[Log::UserLeave] = Settings::LogConsole; + qmMessages[Log::UserKicked] = Settings::LogConsole; + qmMessages[Log::OtherSelfMute] = Settings::LogConsole; qmMessages[Log::OtherMutedOther] = Settings::LogConsole; - qmMessages[Log::UserRenamed] = Settings::LogConsole; - + qmMessages[Log::UserRenamed] = Settings::LogConsole; + // Default theme - themeName = QLatin1String("Mumble"); + themeName = QLatin1String("Mumble"); themeStyleName = QLatin1String("Lite"); } bool Settings::doEcho() const { - if (! bEcho) + if (!bEcho) return false; if (AudioInputRegistrar::qmNew) { @@ -579,10 +583,14 @@ BOOST_TYPEOF_REGISTER_TYPE(QVariant) BOOST_TYPEOF_REGISTER_TYPE(QFont) BOOST_TYPEOF_REGISTER_TEMPLATE(QList, 1) -#define SAVELOAD(var,name) var = qvariant_cast<BOOST_TYPEOF(var)>(settings_ptr->value(QLatin1String(name), var)) -#define LOADENUM(var, name) var = static_cast<BOOST_TYPEOF(var)>(settings_ptr->value(QLatin1String(name), var).toInt()) -#define LOADFLAG(var, name) var = static_cast<BOOST_TYPEOF(var)>(settings_ptr->value(QLatin1String(name), static_cast<int>(var)).toInt()) -#define DEPRECATED(name) do { } while (0) +#define SAVELOAD(var, name) var = qvariant_cast< BOOST_TYPEOF(var) >(settings_ptr->value(QLatin1String(name), var)) +#define LOADENUM(var, name) \ + var = static_cast< BOOST_TYPEOF(var) >(settings_ptr->value(QLatin1String(name), var).toInt()) +#define LOADFLAG(var, name) \ + var = static_cast< BOOST_TYPEOF(var) >(settings_ptr->value(QLatin1String(name), static_cast< int >(var)).toInt()) +#define DEPRECATED(name) \ + do { \ + } while (0) // Workaround for mumble-voip/mumble#2638. // @@ -598,20 +606,20 @@ BOOST_TYPEOF_REGISTER_TEMPLATE(QList, 1) // to their defaults, instead of being set to // a zero value. #ifdef Q_OS_MAC - #undef SAVELOAD - #define SAVELOAD(var, name) \ - do { \ - if (settings_ptr->value(QLatin1String(name)).toString() != QLatin1String("@Variant(")) { \ - var = qvariant_cast<BOOST_TYPEOF(var)>(settings_ptr->value(QLatin1String(name), var)); \ - } \ - } while (0) +# undef SAVELOAD +# define SAVELOAD(var, name) \ + do { \ + if (settings_ptr->value(QLatin1String(name)).toString() != QLatin1String("@Variant(")) { \ + var = qvariant_cast< BOOST_TYPEOF(var) >(settings_ptr->value(QLatin1String(name), var)); \ + } \ + } while (0) #endif void OverlaySettings::load() { load(g.qs); } -void OverlaySettings::load(QSettings* settings_ptr) { +void OverlaySettings::load(QSettings *settings_ptr) { SAVELOAD(bEnable, "enable"); LOADENUM(osShow, "show"); @@ -625,7 +633,7 @@ void OverlaySettings::load(QSettings* settings_ptr) { SAVELOAD(uiColumns, "columns"); settings_ptr->beginReadArray(QLatin1String("states")); - for (int i=0; i<4; ++i) { + for (int i = 0; i < 4; ++i) { settings_ptr->setArrayIndex(i); SAVELOAD(qcUserName[i], "color"); SAVELOAD(fUser[i], "opacity"); @@ -684,7 +692,7 @@ void Settings::load() { load(g.qs); } -void Settings::load(QSettings* settings_ptr) { +void Settings::load(QSettings *settings_ptr) { // Config updates SAVELOAD(uiUpdateCounter, "lastupdate"); @@ -906,8 +914,8 @@ void Settings::load(QSettings* settings_ptr) { SAVELOAD(iLCDUserViewMinColWidth, "lcd/userview/mincolwidth"); SAVELOAD(iLCDUserViewSplitterWidth, "lcd/userview/splitterwidth"); - QByteArray qba = qvariant_cast<QByteArray> (settings_ptr->value(QLatin1String("net/certificate"))); - if (! qba.isEmpty()) + QByteArray qba = qvariant_cast< QByteArray >(settings_ptr->value(QLatin1String("net/certificate"))); + if (!qba.isEmpty()) kpCertificate = CertWizard::importCert(qba); SAVELOAD(bShortcutEnable, "shortcut/enable"); @@ -921,7 +929,7 @@ void Settings::load(QSettings* settings_ptr) { SAVELOAD(bEnableUIAccess, "shortcut/windows/uiaccess/enable"); int nshorts = settings_ptr->beginReadArray(QLatin1String("shortcuts")); - for (int i=0; i<nshorts; i++) { + for (int i = 0; i < nshorts; i++) { settings_ptr->setArrayIndex(i); Shortcut s; @@ -937,27 +945,28 @@ void Settings::load(QSettings* settings_ptr) { settings_ptr->endArray(); settings_ptr->beginReadArray(QLatin1String("messages")); - for (QMap<int, quint32>::const_iterator it = qmMessages.constBegin(); it != qmMessages.constEnd(); ++it) { + for (QMap< int, quint32 >::const_iterator it = qmMessages.constBegin(); it != qmMessages.constEnd(); ++it) { settings_ptr->setArrayIndex(it.key()); SAVELOAD(qmMessages[it.key()], "log"); } settings_ptr->endArray(); settings_ptr->beginReadArray(QLatin1String("messagesounds")); - for (QMap<int, QString>::const_iterator it = qmMessageSounds.constBegin(); it != qmMessageSounds.constEnd(); ++it) { + for (QMap< int, QString >::const_iterator it = qmMessageSounds.constBegin(); it != qmMessageSounds.constEnd(); + ++it) { settings_ptr->setArrayIndex(it.key()); SAVELOAD(qmMessageSounds[it.key()], "logsound"); } settings_ptr->endArray(); settings_ptr->beginGroup(QLatin1String("lcd/devices")); - foreach(const QString &d, settings_ptr->childKeys()) { + foreach (const QString &d, settings_ptr->childKeys()) { qmLCDDevices.insert(d, settings_ptr->value(d, true).toBool()); } settings_ptr->endGroup(); settings_ptr->beginGroup(QLatin1String("audio/plugins")); - foreach(const QString &d, settings_ptr->childKeys()) { + foreach (const QString &d, settings_ptr->childKeys()) { qmPositionalAudioPlugins.insert(d, settings_ptr->value(d, true).toBool()); } settings_ptr->endGroup(); @@ -968,8 +977,16 @@ void Settings::load(QSettings* settings_ptr) { } #undef SAVELOAD -#define SAVELOAD(var,name) if (var != def.var) settings_ptr->setValue(QLatin1String(name), var); else settings_ptr->remove(QLatin1String(name)) -#define SAVEFLAG(var,name) if (var != def.var) settings_ptr->setValue(QLatin1String(name), static_cast<int>(var)); else settings_ptr->remove(QLatin1String(name)) +#define SAVELOAD(var, name) \ + if (var != def.var) \ + settings_ptr->setValue(QLatin1String(name), var); \ + else \ + settings_ptr->remove(QLatin1String(name)) +#define SAVEFLAG(var, name) \ + if (var != def.var) \ + settings_ptr->setValue(QLatin1String(name), static_cast< int >(var)); \ + else \ + settings_ptr->remove(QLatin1String(name)) #undef DEPRECATED #define DEPRECATED(name) settings_ptr->remove(QLatin1String(name)) @@ -977,7 +994,7 @@ void OverlaySettings::save() { save(g.qs); } -void OverlaySettings::save(QSettings* settings_ptr) { +void OverlaySettings::save(QSettings *settings_ptr) { OverlaySettings def; settings_ptr->setValue(QLatin1String("version"), QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); @@ -988,7 +1005,9 @@ void OverlaySettings::save(QSettings* settings_ptr) { #endif { QFile f(settings_ptr->fileName()); - f.setPermissions(f.permissions() & ~(QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther | QFile::WriteOther | QFile::ExeOther)); + f.setPermissions(f.permissions() + & ~(QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther + | QFile::WriteOther | QFile::ExeOther)); } SAVELOAD(bEnable, "enable"); @@ -1003,7 +1022,7 @@ void OverlaySettings::save(QSettings* settings_ptr) { SAVELOAD(uiColumns, "columns"); settings_ptr->beginReadArray(QLatin1String("states")); - for (int i=0; i<4; ++i) { + for (int i = 0; i < 4; ++i) { settings_ptr->setArrayIndex(i); SAVELOAD(qcUserName[i], "color"); SAVELOAD(fUser[i], "opacity"); @@ -1059,7 +1078,7 @@ void OverlaySettings::save(QSettings* settings_ptr) { } void Settings::save() { - QSettings* settings_ptr = g.qs; + QSettings *settings_ptr = g.qs; Settings def; // Config updates @@ -1281,8 +1300,8 @@ void Settings::save() { settings_ptr->beginWriteArray(QLatin1String("shortcuts")); int idx = 0; - foreach(const Shortcut &s, qlShortcuts) { - if (! s.isServerSpecific()) { + foreach (const Shortcut &s, qlShortcuts) { + if (!s.isServerSpecific()) { settings_ptr->setArrayIndex(idx++); settings_ptr->setValue(QLatin1String("index"), s.iIndex); settings_ptr->setValue(QLatin1String("keys"), s.qlButtons); @@ -1293,21 +1312,22 @@ void Settings::save() { settings_ptr->endArray(); settings_ptr->beginWriteArray(QLatin1String("messages")); - for (QMap<int, quint32>::const_iterator it = qmMessages.constBegin(); it != qmMessages.constEnd(); ++it) { + for (QMap< int, quint32 >::const_iterator it = qmMessages.constBegin(); it != qmMessages.constEnd(); ++it) { settings_ptr->setArrayIndex(it.key()); SAVELOAD(qmMessages[it.key()], "log"); } settings_ptr->endArray(); settings_ptr->beginWriteArray(QLatin1String("messagesounds")); - for (QMap<int, QString>::const_iterator it = qmMessageSounds.constBegin(); it != qmMessageSounds.constEnd(); ++it) { + for (QMap< int, QString >::const_iterator it = qmMessageSounds.constBegin(); it != qmMessageSounds.constEnd(); + ++it) { settings_ptr->setArrayIndex(it.key()); SAVELOAD(qmMessageSounds[it.key()], "logsound"); } settings_ptr->endArray(); settings_ptr->beginGroup(QLatin1String("lcd/devices")); - foreach(const QString &d, qmLCDDevices.keys()) { + foreach (const QString &d, qmLCDDevices.keys()) { bool v = qmLCDDevices.value(d); if (!v) settings_ptr->setValue(d, v); @@ -1317,7 +1337,7 @@ void Settings::save() { settings_ptr->endGroup(); settings_ptr->beginGroup(QLatin1String("audio/plugins")); - foreach(const QString &d, qmPositionalAudioPlugins.keys()) { + foreach (const QString &d, qmPositionalAudioPlugins.keys()) { bool v = qmPositionalAudioPlugins.value(d); if (!v) settings_ptr->setValue(d, v); diff --git a/src/mumble/Settings.h b/src/mumble/Settings.h index d7651e79e..ee7de014e 100644 --- a/src/mumble/Settings.h +++ b/src/mumble/Settings.h @@ -6,12 +6,12 @@ #ifndef MUMBLE_MUMBLE_SETTINGS_H_ #define MUMBLE_MUMBLE_SETTINGS_H_ -#include <QtCore/QVariant> #include <QtCore/QList> #include <QtCore/QPair> #include <QtCore/QRectF> #include <QtCore/QSettings> #include <QtCore/QStringList> +#include <QtCore/QVariant> #include <QtGui/QColor> #include <QtGui/QFont> #include <QtNetwork/QSslCertificate> @@ -26,19 +26,19 @@ struct Shortcut { int iIndex; - QList<QVariant> qlButtons; + QList< QVariant > qlButtons; QVariant qvData; bool bSuppress; - bool operator <(const Shortcut &) const; + bool operator<(const Shortcut &) const; bool isServerSpecific() const; - bool operator ==(const Shortcut &) const; + bool operator==(const Shortcut &) const; }; struct ShortcutTarget { bool bCurrentSelection; bool bUsers; QStringList qlUsers; - QList<unsigned int> qlSessions; + QList< unsigned int > qlSessions; int iChannel; QString qsGroup; bool bLinks; @@ -46,12 +46,12 @@ struct ShortcutTarget { bool bForceCenter; ShortcutTarget(); bool isServerSpecific() const; - bool operator <(const ShortcutTarget &) const; - bool operator ==(const ShortcutTarget &) const; + bool operator<(const ShortcutTarget &) const; + bool operator==(const ShortcutTarget &) const; }; quint32 qHash(const ShortcutTarget &); -quint32 qHash(const QList<ShortcutTarget> &); +quint32 qHash(const QList< ShortcutTarget > &); QDataStream &operator<<(QDataStream &, const ShortcutTarget &); QDataStream &operator>>(QDataStream &, ShortcutTarget &); @@ -136,9 +136,9 @@ struct OverlaySettings { void setPreset(const OverlayPresets preset = AvatarAndName); void load(); - void load(QSettings*); + void load(QSettings *); void save(); - void save(QSettings*); + void save(QSettings *); }; struct Settings { @@ -151,7 +151,7 @@ struct Settings { enum TalkState { Passive, Talking, Whispering, Shouting, MutedTalking }; enum IdleAction { Nothing, Deafen, Mute }; enum NoiseCancel { NoiseCancelOff, NoiseCancelSpeex, NoiseCancelRNN, NoiseCancelBoth }; - typedef QPair<QList<QSslCertificate>, QSslKey> KeyPair; + typedef QPair< QList< QSslCertificate >, QSslKey > KeyPair; AudioTransmit atTransmit; quint64 uiDoublePush; @@ -179,7 +179,7 @@ struct Settings { /// The language is expected to be in BCP47 form. /// /// The setting is currently only supported by the speech-dispatcher - ///backend. + /// backend. QString qsTTSLanguage; int iQuality, iMinLoudness, iVoiceHold, iJitterBufferSize; bool bAllowLowDelay; @@ -214,8 +214,8 @@ struct Settings { bool bASIOEnable; QString qsASIOclass; - QList<QVariant> qlASIOmic; - QList<QVariant> qlASIOspeaker; + QList< QVariant > qlASIOmic; + QList< QVariant > qlASIOspeaker; QString qsCoreAudioInput, qsCoreAudioOutput; @@ -248,7 +248,7 @@ struct Settings { bool bPositionalAudio; bool bPositionalHeadphone; float fAudioMinDistance, fAudioMaxDistance, fAudioMaxDistVolume, fAudioBloom; - QMap<QString, bool> qmPositionalAudioPlugins; + QMap< QString, bool > qmPositionalAudioPlugins; OverlaySettings os; @@ -258,7 +258,7 @@ struct Settings { int iLCDUserViewMinColWidth; int iLCDUserViewSplitterWidth; - QMap<QString, bool> qmLCDDevices; + QMap< QString, bool > qmLCDDevices; bool bShortcutEnable; bool bSuppressMacEventTapWarning; @@ -272,9 +272,16 @@ struct Settings { /// Enable use of UIAccess (Windows's UI automation feature). This allows /// Mumble greater access to global shortcuts. bool bEnableUIAccess; - QList<Shortcut> qlShortcuts; - - enum MessageLog { LogNone = 0x00, LogConsole = 0x01, LogTTS = 0x02, LogBalloon = 0x04, LogSoundfile = 0x08, LogHighlight = 0x10 }; + QList< Shortcut > qlShortcuts; + + enum MessageLog { + LogNone = 0x00, + LogConsole = 0x01, + LogTTS = 0x02, + LogBalloon = 0x04, + LogSoundfile = 0x08, + LogHighlight = 0x10 + }; int iMaxLogBlocks; bool bLog24HourClock; int iChatMessageMargins; @@ -298,8 +305,8 @@ struct Settings { int manualPlugin_silentUserDisplaytime; - QMap<int, QString> qmMessageSounds; - QMap<int, quint32> qmMessages; + QMap< int, QString > qmMessageSounds; + QMap< int, quint32 > qmMessages; QString qsLanguage; @@ -307,8 +314,9 @@ struct Settings { QString themeName; /// Name of the style to use from theme. @see Themes QString themeStyleName; - - QByteArray qbaMainWindowGeometry, qbaMainWindowState, qbaMinimalViewGeometry, qbaMinimalViewState, qbaSplitterState, qbaHeaderState; + + QByteArray qbaMainWindowGeometry, qbaMainWindowState, qbaMinimalViewGeometry, qbaMinimalViewState, qbaSplitterState, + qbaHeaderState; QByteArray qbaConfigGeometry; enum WindowLayout { LayoutClassic, LayoutStacked, LayoutHybrid, LayoutCustom }; WindowLayout wlWindowLayout; @@ -422,16 +430,16 @@ struct Settings { int iRecordingFormat; // Special configuration options not exposed to UI - + /// Codec kill-switch bool bDisableCELT; - + /// Removes the add and edit options in the connect dialog if set. bool disableConnectDialogEditing; /// Asks the user for consent to ping servers in the public server list if not set. bool bPingServersDialogViewed; - + // Config updates unsigned int uiUpdateCounter; @@ -450,7 +458,7 @@ struct Settings { Settings(); void load(); - void load(QSettings*); + void load(QSettings *); void save(); }; diff --git a/src/mumble/SharedMemory.h b/src/mumble/SharedMemory.h index 9cde78fc5..0da1e0d55 100644 --- a/src/mumble/SharedMemory.h +++ b/src/mumble/SharedMemory.h @@ -6,31 +6,32 @@ #ifndef MUMBLE_MUMBLE_SHAREDMEMORY_H_ #define MUMBLE_MUMBLE_SHAREDMEMORY_H_ -#include <QtCore/QString> #include <QtCore/QObject> +#include <QtCore/QString> struct SharedMemory2Private; class SharedMemory2 : QObject { - private: - Q_DISABLE_COPY(SharedMemory2) - Q_OBJECT - protected: - QString qsName; - SharedMemory2Private *d; - unsigned char *a_ucData; - unsigned int uiSize; - static unsigned int uiIndex; - public: - SharedMemory2(QObject *p, unsigned int minsize, const QString &name = QString()); - ~SharedMemory2() Q_DECL_OVERRIDE; +private: + Q_DISABLE_COPY(SharedMemory2) + Q_OBJECT +protected: + QString qsName; + SharedMemory2Private *d; + unsigned char *a_ucData; + unsigned int uiSize; + static unsigned int uiIndex; + +public: + SharedMemory2(QObject *p, unsigned int minsize, const QString &name = QString()); + ~SharedMemory2() Q_DECL_OVERRIDE; - void erase(); - void systemRelease(); + void erase(); + void systemRelease(); - QString name() const; - unsigned int size() const; - unsigned char *data(); - const unsigned char *data() const; + QString name() const; + unsigned int size() const; + unsigned char *data(); + const unsigned char *data() const; }; #endif diff --git a/src/mumble/SharedMemory_unix.cpp b/src/mumble/SharedMemory_unix.cpp index 6a031397f..509218604 100644 --- a/src/mumble/SharedMemory_unix.cpp +++ b/src/mumble/SharedMemory_unix.cpp @@ -5,10 +5,10 @@ #include "SharedMemory.h" -#include <sys/types.h> +#include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> -#include <fcntl.h> +#include <sys/types.h> #include <unistd.h> #include <QDebug> @@ -20,16 +20,16 @@ struct SharedMemory2Private { SharedMemory2::SharedMemory2(QObject *p, unsigned int minsize, const QString &memname) : QObject(p) { a_ucData = nullptr; - d = new SharedMemory2Private(); + d = new SharedMemory2Private(); d->iShmemFD = -1; int prot = PROT_READ; if (memname.isEmpty()) { prot |= PROT_WRITE; - for (int i=0;i<100;++i) { - qsName = QString::fromLatin1("/MumbleOverlayMemory%1").arg(++uiIndex); - d->iShmemFD=shm_open(qsName.toUtf8().constData(), O_RDWR|O_CREAT|O_EXCL, 0600); + for (int i = 0; i < 100; ++i) { + qsName = QString::fromLatin1("/MumbleOverlayMemory%1").arg(++uiIndex); + d->iShmemFD = shm_open(qsName.toUtf8().constData(), O_RDWR | O_CREAT | O_EXCL, 0600); if (d->iShmemFD != -1) { if (ftruncate(d->iShmemFD, minsize) == 0) { break; @@ -41,8 +41,8 @@ SharedMemory2::SharedMemory2(QObject *p, unsigned int minsize, const QString &me } } } else { - qsName = memname; - d->iShmemFD=shm_open(qsName.toUtf8().constData(), O_RDONLY, 0600); + qsName = memname; + d->iShmemFD = shm_open(qsName.toUtf8().constData(), O_RDONLY, 0600); } if (d->iShmemFD == -1) { qWarning() << "SharedMemory2: Failed to open shared memory segment" << qsName; @@ -50,14 +50,14 @@ SharedMemory2::SharedMemory2(QObject *p, unsigned int minsize, const QString &me } struct stat buf; fstat(d->iShmemFD, &buf); - unsigned int memsize = static_cast<unsigned int>(buf.st_size); + unsigned int memsize = static_cast< unsigned int >(buf.st_size); if (memsize < minsize) { qWarning() << "SharedMemory2: Segment too small" << memsize << minsize; - } else if (memsize > std::numeric_limits<unsigned int>::max()) { + } else if (memsize > std::numeric_limits< unsigned int >::max()) { qWarning() << "SharedMemory2: Segment too big" << memsize; } else { - a_ucData = reinterpret_cast<unsigned char *>(mmap(nullptr, minsize, prot, MAP_SHARED, d->iShmemFD, 0)); - if (a_ucData != reinterpret_cast<unsigned char *>(-1)) { + a_ucData = reinterpret_cast< unsigned char * >(mmap(nullptr, minsize, prot, MAP_SHARED, d->iShmemFD, 0)); + if (a_ucData != reinterpret_cast< unsigned char * >(-1)) { uiSize = memsize; return; } @@ -68,7 +68,6 @@ SharedMemory2::SharedMemory2(QObject *p, unsigned int minsize, const QString &me close(d->iShmemFD); d->iShmemFD = -1; shm_unlink(qsName.toUtf8().constData()); - } SharedMemory2::~SharedMemory2() { diff --git a/src/mumble/SharedMemory_win.cpp b/src/mumble/SharedMemory_win.cpp index 97a9fe6ac..68408fbc3 100644 --- a/src/mumble/SharedMemory_win.cpp +++ b/src/mumble/SharedMemory_win.cpp @@ -16,15 +16,16 @@ struct SharedMemory2Private { SharedMemory2::SharedMemory2(QObject *p, unsigned int minsize, const QString &memname) : QObject(p) { a_ucData = nullptr; - d = new SharedMemory2Private(); + d = new SharedMemory2Private(); d->hMemory = nullptr; if (memname.isEmpty()) { // Create a new segment - for (int i=0;i<100;++i) { - qsName = QString::fromLatin1("Local\\MumbleOverlayMemory%1").arg(++uiIndex); - d->hMemory = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, minsize, qsName.toStdWString().c_str()); + for (int i = 0; i < 100; ++i) { + qsName = QString::fromLatin1("Local\\MumbleOverlayMemory%1").arg(++uiIndex); + d->hMemory = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, minsize, + qsName.toStdWString().c_str()); if (d->hMemory && GetLastError() != ERROR_ALREADY_EXISTS) { break; } @@ -36,8 +37,9 @@ SharedMemory2::SharedMemory2(QObject *p, unsigned int minsize, const QString &me } else { // Open existing segment - qsName = memname; - d->hMemory = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, minsize, qsName.toStdWString().c_str()); + qsName = memname; + d->hMemory = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, minsize, + qsName.toStdWString().c_str()); qWarning("%p %lx", d->hMemory, GetLastError()); if (GetLastError() != ERROR_ALREADY_EXISTS) { qWarning() << "SharedMemory2: Memory doesn't exist" << qsName; @@ -51,7 +53,7 @@ SharedMemory2::SharedMemory2(QObject *p, unsigned int minsize, const QString &me if (!d->hMemory) { qWarning() << "SharedMemory2: CreateFileMapping failed for" << qsName; } else { - a_ucData = reinterpret_cast<unsigned char *>(MapViewOfFile(d->hMemory, FILE_MAP_ALL_ACCESS, 0, 0, 0)); + a_ucData = reinterpret_cast< unsigned char * >(MapViewOfFile(d->hMemory, FILE_MAP_ALL_ACCESS, 0, 0, 0)); if (!a_ucData) { qWarning() << "SharedMemory2: Failed to map memory" << qsName; diff --git a/src/mumble/SocketRPC.cpp b/src/mumble/SocketRPC.cpp index 3078c0ef5..0583af253 100644 --- a/src/mumble/SocketRPC.cpp +++ b/src/mumble/SocketRPC.cpp @@ -15,14 +15,16 @@ #include <QtNetwork/QLocalServer> #include <QtXml/QDomDocument> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" SocketRPCClient::SocketRPCClient(QLocalSocket *s, QObject *p) : QObject(p), qlsSocket(s), qbBuffer(nullptr) { qlsSocket->setParent(this); connect(qlsSocket, SIGNAL(disconnected()), this, SLOT(disconnected())); - connect(qlsSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(error(QLocalSocket::LocalSocketError))); + connect(qlsSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, + SLOT(error(QLocalSocket::LocalSocketError))); connect(qlsSocket, SIGNAL(readyRead()), this, SLOT(readyRead())); qxsrReader.setDevice(qlsSocket); @@ -44,29 +46,27 @@ void SocketRPCClient::readyRead() { forever { switch (qxsrReader.readNext()) { case QXmlStreamReader::Invalid: { - if (qxsrReader.error() != QXmlStreamReader::PrematureEndOfDocumentError) { - qWarning() << "Malformed" << qxsrReader.error(); - qlsSocket->abort(); - } - return; + if (qxsrReader.error() != QXmlStreamReader::PrematureEndOfDocumentError) { + qWarning() << "Malformed" << qxsrReader.error(); + qlsSocket->abort(); } - break; + return; + } break; case QXmlStreamReader::EndDocument: { - qxswWriter.writeCurrentToken(qxsrReader); + qxswWriter.writeCurrentToken(qxsrReader); - processXml(); + processXml(); - qxsrReader.clear(); - qxsrReader.setDevice(qlsSocket); + qxsrReader.clear(); + qxsrReader.setDevice(qlsSocket); - qxswWriter.setDevice(nullptr); - delete qbBuffer; - qbaOutput = QByteArray(); - qbBuffer = new QBuffer(&qbaOutput, this); - qbBuffer->open(QIODevice::WriteOnly); - qxswWriter.setDevice(qbBuffer); - } - break; + qxswWriter.setDevice(nullptr); + delete qbBuffer; + qbaOutput = QByteArray(); + qbBuffer = new QBuffer(&qbaOutput, this); + qbBuffer->open(QIODevice::WriteOnly); + qxswWriter.setDevice(qbBuffer); + } break; default: qxswWriter.writeCurrentToken(qxsrReader); break; @@ -80,21 +80,21 @@ void SocketRPCClient::processXml() { QDomElement request = qdd.firstChildElement(); - if (! request.isNull()) { + if (!request.isNull()) { bool ack = false; - QMap<QString, QVariant> qmRequest; - QMap<QString, QVariant> qmReply; - QMap<QString, QVariant>::const_iterator iter; + QMap< QString, QVariant > qmRequest; + QMap< QString, QVariant > qmReply; + QMap< QString, QVariant >::const_iterator iter; QDomNamedNodeMap attributes = request.attributes(); - for (int i=0;i<attributes.count();++i) { + for (int i = 0; i < attributes.count(); ++i) { QDomAttr attr = attributes.item(i).toAttr(); qmRequest.insert(attr.name(), attr.value()); } QDomNodeList childNodes = request.childNodes(); - for (int i=0;i<childNodes.count();++i) { + for (int i = 0; i < childNodes.count(); ++i) { QDomElement child = childNodes.item(i).toElement(); - if (! child.isNull()) + if (!child.isNull()) qmRequest.insert(child.nodeName(), child.text()); } @@ -113,7 +113,7 @@ void SocketRPCClient::processXml() { if (iter != qmRequest.constEnd()) { bool set = iter.value().toBool(); if (set != g.s.bMute) { - g.mw->qaAudioMute->setChecked(! set); + g.mw->qaAudioMute->setChecked(!set); g.mw->qaAudioMute->trigger(); } } @@ -132,7 +132,7 @@ void SocketRPCClient::processXml() { g.mw->qaAudioMute->setChecked(set); g.mw->qaAudioMute->trigger(); } else { - g.mw->qaAudioMute->setChecked(! set); + g.mw->qaAudioMute->setChecked(!set); g.mw->qaAudioMute->trigger(); } } @@ -140,7 +140,7 @@ void SocketRPCClient::processXml() { if (iter != qmRequest.constEnd()) { bool set = iter.value().toBool(); if (set != g.s.bDeaf) { - g.mw->qaAudioDeaf->setChecked(! set); + g.mw->qaAudioDeaf->setChecked(!set); g.mw->qaAudioDeaf->trigger(); } } @@ -159,7 +159,7 @@ void SocketRPCClient::processXml() { g.mw->qaAudioDeaf->setChecked(set); g.mw->qaAudioDeaf->trigger(); } else { - g.mw->qaAudioDeaf->setChecked(! set); + g.mw->qaAudioDeaf->setChecked(!set); g.mw->qaAudioDeaf->trigger(); } } @@ -210,7 +210,7 @@ void SocketRPCClient::processXml() { for (iter = qmReply.constBegin(); iter != qmReply.constEnd(); ++iter) { QDomElement elem = replydoc.createElement(iter.key()); - QDomText text = replydoc.createTextNode(iter.value().toString()); + QDomText text = replydoc.createTextNode(iter.value().toString()); elem.appendChild(text); reply.appendChild(elem); } @@ -231,9 +231,9 @@ SocketRPC::SocketRPC(const QString &basename, QObject *p) : QObject(p) { #else { QString xdgRuntimePath = QProcessEnvironment::systemEnvironment().value(QLatin1String("XDG_RUNTIME_DIR")); - QDir xdgRuntimeDir = QDir(xdgRuntimePath); + QDir xdgRuntimeDir = QDir(xdgRuntimePath); - if (! xdgRuntimePath.isNull() && xdgRuntimeDir.exists()) { + if (!xdgRuntimePath.isNull() && xdgRuntimeDir.exists()) { pipepath = xdgRuntimeDir.absoluteFilePath(basename + QLatin1String("Socket")); } else { pipepath = QDir::home().absoluteFilePath(QLatin1String(".") + basename + QLatin1String("Socket")); @@ -249,7 +249,7 @@ SocketRPC::SocketRPC(const QString &basename, QObject *p) : QObject(p) { } #endif - if (! qlsServer->listen(pipepath)) { + if (!qlsServer->listen(pipepath)) { qWarning() << "SocketRPC: Listen failed"; delete qlsServer; qlsServer = nullptr; @@ -261,13 +261,13 @@ SocketRPC::SocketRPC(const QString &basename, QObject *p) : QObject(p) { void SocketRPC::newConnection() { while (true) { QLocalSocket *qls = qlsServer->nextPendingConnection(); - if (! qls) + if (!qls) break; new SocketRPCClient(qls, this); } } -bool SocketRPC::send(const QString &basename, const QString &request, const QMap<QString, QVariant> ¶m) { +bool SocketRPC::send(const QString &basename, const QString &request, const QMap< QString, QVariant > ¶m) { QString pipepath; #ifdef Q_OS_WIN @@ -275,9 +275,9 @@ bool SocketRPC::send(const QString &basename, const QString &request, const QMap #else { QString xdgRuntimePath = QProcessEnvironment::systemEnvironment().value(QLatin1String("XDG_RUNTIME_DIR")); - QDir xdgRuntimeDir = QDir(xdgRuntimePath); + QDir xdgRuntimeDir = QDir(xdgRuntimePath); - if (! xdgRuntimePath.isNull() && xdgRuntimeDir.exists()) { + if (!xdgRuntimePath.isNull() && xdgRuntimeDir.exists()) { pipepath = xdgRuntimeDir.absoluteFilePath(basename + QLatin1String("Socket")); } else { pipepath = QDir::home().absoluteFilePath(QLatin1String(".") + basename + QLatin1String("Socket")); @@ -287,15 +287,15 @@ bool SocketRPC::send(const QString &basename, const QString &request, const QMap QLocalSocket qls; qls.connectToServer(pipepath); - if (! qls.waitForConnected(1000)) { + if (!qls.waitForConnected(1000)) { return false; } QDomDocument requestdoc; QDomElement req = requestdoc.createElement(request); - for (QMap<QString, QVariant>::const_iterator iter = param.constBegin(); iter != param.constEnd(); ++iter) { + for (QMap< QString, QVariant >::const_iterator iter = param.constBegin(); iter != param.constEnd(); ++iter) { QDomElement elem = requestdoc.createElement(iter.key()); - QDomText text = requestdoc.createTextNode(iter.value().toString()); + QDomText text = requestdoc.createTextNode(iter.value().toString()); elem.appendChild(text); req.appendChild(elem); } @@ -304,7 +304,7 @@ bool SocketRPC::send(const QString &basename, const QString &request, const QMap qls.write(requestdoc.toByteArray()); qls.flush(); - if (! qls.waitForReadyRead(2000)) { + if (!qls.waitForReadyRead(2000)) { return false; } @@ -314,7 +314,7 @@ bool SocketRPC::send(const QString &basename, const QString &request, const QMap replydoc.setContent(qba); QDomElement succ = replydoc.firstChildElement(QLatin1String("reply")); - succ = succ.firstChildElement(QLatin1String("succeeded")); + succ = succ.firstChildElement(QLatin1String("succeeded")); if (succ.isNull()) return false; diff --git a/src/mumble/SocketRPC.h b/src/mumble/SocketRPC.h index fc7295d92..bfb4b35a8 100644 --- a/src/mumble/SocketRPC.h +++ b/src/mumble/SocketRPC.h @@ -16,37 +16,39 @@ class QBuffer; class QLocalServer; class SocketRPCClient : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(SocketRPCClient) - protected: - QLocalSocket *qlsSocket; - QXmlStreamReader qxsrReader; - QXmlStreamWriter qxswWriter; - QBuffer *qbBuffer; - QByteArray qbaOutput; - - void processXml(); - public: - SocketRPCClient(QLocalSocket *s, QObject *p = nullptr); - public slots: - void disconnected(); - void error(QLocalSocket::LocalSocketError); - void readyRead(); +private: + Q_OBJECT + Q_DISABLE_COPY(SocketRPCClient) +protected: + QLocalSocket *qlsSocket; + QXmlStreamReader qxsrReader; + QXmlStreamWriter qxswWriter; + QBuffer *qbBuffer; + QByteArray qbaOutput; + + void processXml(); + +public: + SocketRPCClient(QLocalSocket *s, QObject *p = nullptr); +public slots: + void disconnected(); + void error(QLocalSocket::LocalSocketError); + void readyRead(); }; class SocketRPC : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(SocketRPC) - protected: - QLocalServer *qlsServer; - public: - typedef QMap<QString, QVariant> ParameterMap; - SocketRPC(const QString &basename, QObject *p = nullptr); - static bool send(const QString &basename, const QString &request, const ParameterMap ¶m = ParameterMap()); - public slots: - void newConnection(); +private: + Q_OBJECT + Q_DISABLE_COPY(SocketRPC) +protected: + QLocalServer *qlsServer; + +public: + typedef QMap< QString, QVariant > ParameterMap; + SocketRPC(const QString &basename, QObject *p = nullptr); + static bool send(const QString &basename, const QString &request, const ParameterMap ¶m = ParameterMap()); +public slots: + void newConnection(); }; #endif diff --git a/src/mumble/SvgIcon.cpp b/src/mumble/SvgIcon.cpp index 57eb334e9..9c5064c4c 100644 --- a/src/mumble/SvgIcon.cpp +++ b/src/mumble/SvgIcon.cpp @@ -5,13 +5,13 @@ #include "SvgIcon.h" -#include <QSvgRenderer> #include <QPainter> +#include <QSvgRenderer> void SvgIcon::addSvgPixmapsToIcon(QIcon &icon, QString fn) { QSvgRenderer svg(fn); - QList<QSize> commonSizes; + QList< QSize > commonSizes; commonSizes << QSize(8, 8); commonSizes << QSize(16, 16); commonSizes << QSize(22, 22); // Plasma notification area size diff --git a/src/mumble/SvgIcon.h b/src/mumble/SvgIcon.h index 7c0e0f9f7..712fcf76f 100644 --- a/src/mumble/SvgIcon.h +++ b/src/mumble/SvgIcon.h @@ -9,8 +9,7 @@ #include <QIcon> #include <QString> -class SvgIcon -{ +class SvgIcon { public: /// addSvgPixmapsToIcon renders the SVG file at |fn| in various /// common sizes from 8x8 up to 256x256 and adds the resulting diff --git a/src/mumble/TalkingUI.cpp b/src/mumble/TalkingUI.cpp index 16a99ba2d..e2bdeb40d 100644 --- a/src/mumble/TalkingUI.cpp +++ b/src/mumble/TalkingUI.cpp @@ -4,63 +4,60 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "TalkingUI.h" -#include "TalkingUIComponent.h" -#include "ClientUser.h" #include "Channel.h" +#include "ChannelListener.h" +#include "ClientUser.h" #include "MainWindow.h" +#include "TalkingUIComponent.h" #include "UserModel.h" -#include "ChannelListener.h" #include <QGroupBox> -#include <QLabel> -#include <QVBoxLayout> -#include <QHBoxLayout> #include <QGuiApplication> -#include <QtCore/QDateTime> -#include <QtCore/QTimer> -#include <QScreen> -#include <QMouseEvent> -#include <QPalette> +#include <QHBoxLayout> #include <QItemSelectionModel> +#include <QLabel> #include <QModelIndex> -#include <QtCore/QStringList> +#include <QMouseEvent> +#include <QPalette> +#include <QScreen> #include <QTextDocumentFragment> +#include <QVBoxLayout> +#include <QtCore/QDateTime> +#include <QtCore/QStringList> +#include <QtCore/QTimer> #include <QtGui/QPainter> #include <QtGui/QPixmap> #include <algorithm> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -TalkingUI::TalkingUI(QWidget *parent) - : QWidget(parent), - m_containers(), - m_currentSelection(nullptr) { - +TalkingUI::TalkingUI(QWidget *parent) : QWidget(parent), m_containers(), m_currentSelection(nullptr) { setupUI(); } int TalkingUI::findContainer(int associatedChannelID, ContainerType type) const { for (std::size_t i = 0; i < m_containers.size(); i++) { - const std::unique_ptr<TalkingUIContainer> ¤tContainer = m_containers[i]; + const std::unique_ptr< TalkingUIContainer > ¤tContainer = m_containers[i]; if (currentContainer->getType() == type && currentContainer->getAssociatedChannelID() == associatedChannelID) { - return static_cast<int>(i); + return static_cast< int >(i); } } return -1; } -std::unique_ptr<TalkingUIContainer> TalkingUI::removeContainer(const TalkingUIContainer &container) { +std::unique_ptr< TalkingUIContainer > TalkingUI::removeContainer(const TalkingUIContainer &container) { return removeContainer(container.getAssociatedChannelID(), container.getType()); } -std::unique_ptr<TalkingUIContainer> TalkingUI::removeContainer(int associatedChannelID, ContainerType type) { +std::unique_ptr< TalkingUIContainer > TalkingUI::removeContainer(int associatedChannelID, ContainerType type) { int index = findContainer(associatedChannelID, type); - std::unique_ptr<TalkingUIContainer> container(nullptr); + std::unique_ptr< TalkingUIContainer > container(nullptr); if (index >= 0) { // Move the container out of the vector @@ -76,7 +73,7 @@ std::unique_ptr<TalkingUIContainer> TalkingUI::removeContainer(int associatedCha return container; } -std::unique_ptr<TalkingUIContainer> TalkingUI::removeIfSuperfluous(const TalkingUIContainer &container) { +std::unique_ptr< TalkingUIContainer > TalkingUI::removeIfSuperfluous(const TalkingUIContainer &container) { if (container.isEmpty() && !container.isPermanent()) { return removeContainer(container); } @@ -85,7 +82,8 @@ std::unique_ptr<TalkingUIContainer> TalkingUI::removeIfSuperfluous(const Talking } struct container_ptr_less { - bool operator()(const std::unique_ptr<TalkingUIContainer> &first, const std::unique_ptr<TalkingUIContainer> &second) { + bool operator()(const std::unique_ptr< TalkingUIContainer > &first, + const std::unique_ptr< TalkingUIContainer > &second) { return *first < *second; } }; @@ -106,12 +104,12 @@ void TalkingUI::sortContainers() { } TalkingUIUser *TalkingUI::findUser(unsigned int userSession) { - for(auto ¤tContainer : m_containers) { + for (auto ¤tContainer : m_containers) { TalkingUIEntry *entry = currentContainer->get(userSession, EntryType::USER); if (entry) { // We know that it must be a TalkingUIUser since that is what we searched for - return static_cast<TalkingUIUser *>(entry); + return static_cast< TalkingUIUser * >(entry); } } @@ -146,10 +144,11 @@ void TalkingUI::addListener(const ClientUser *user, const Channel *channel) { // First make sure the channel exists addChannel(channel); - std::unique_ptr<TalkingUIContainer> &channelContainer = m_containers[findContainer(channel->iId, ContainerType::CHANNEL)]; + std::unique_ptr< TalkingUIContainer > &channelContainer = + m_containers[findContainer(channel->iId, ContainerType::CHANNEL)]; - std::unique_ptr<TalkingUIChannelListener> listenerEntry - = std::make_unique<TalkingUIChannelListener>(*user, *channel); + std::unique_ptr< TalkingUIChannelListener > listenerEntry = + std::make_unique< TalkingUIChannelListener >(*user, *channel); channelContainer->addEntry(std::move(listenerEntry)); @@ -161,12 +160,12 @@ TalkingUIChannelListener *TalkingUI::findListener(unsigned int userSession, int int channelIndex = findContainer(channelID, ContainerType::CHANNEL); if (channelIndex >= 0) { - std::unique_ptr<TalkingUIContainer> &channelContainer = m_containers[channelIndex]; + std::unique_ptr< TalkingUIContainer > &channelContainer = m_containers[channelIndex]; TalkingUIEntry *entry = channelContainer->get(userSession, EntryType::LISTENER); if (entry) { - return static_cast<TalkingUIChannelListener *>(entry); + return static_cast< TalkingUIChannelListener * >(entry); } } @@ -194,7 +193,7 @@ void TalkingUI::removeListener(unsigned int userSession, int channelID) { void TalkingUI::removeAllListeners() { // Find all listener entries - std::vector<TalkingUIEntry *> entriesToBeRemoved; + std::vector< TalkingUIEntry * > entriesToBeRemoved; for (auto ¤tContainer : m_containers) { for (auto ¤tEntry : currentContainer->getEntries()) { if (currentEntry->getType() == EntryType::LISTENER) { @@ -233,12 +232,13 @@ void TalkingUI::setupUI() { // properly and as the TalkingUI doesn't provide context help anyways, this is not a big loss. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - connect(g.mw->qtvUsers->selectionModel(), &QItemSelectionModel::currentChanged, this, &TalkingUI::on_mainWindowSelectionChanged); + connect(g.mw->qtvUsers->selectionModel(), &QItemSelectionModel::currentChanged, this, + &TalkingUI::on_mainWindowSelectionChanged); } void TalkingUI::setFontSize(QWidget *widget) { const double fontFactor = g.s.iTalkingUI_RelativeFontSize / 100.0; - + // We have to do this in a complicated way as Qt is very stubborn when it // comes to manipulating fonts. // We have to use stylesheets because this seems to be the only way Qt will @@ -249,13 +249,13 @@ void TalkingUI::setFontSize(QWidget *widget) { QFont newFont = widget->font(); if (font().pixelSize() >= 0) { // font specified in pixels - widget->setStyleSheet(QString::fromLatin1("font-size: %1px;").arg( - static_cast<int>(std::max(fontFactor * font().pixelSize(), 1.0)))); + widget->setStyleSheet(QString::fromLatin1("font-size: %1px;") + .arg(static_cast< int >(std::max(fontFactor * font().pixelSize(), 1.0)))); newFont.setPixelSize(std::max(fontFactor * font().pixelSize(), 1.0)); } else { // font specified in points - widget->setStyleSheet(QString::fromLatin1("font-size: %1pt;").arg( - static_cast<int>(std::max(fontFactor * font().pointSize(), 1.0)))); + widget->setStyleSheet(QString::fromLatin1("font-size: %1pt;") + .arg(static_cast< int >(std::max(fontFactor * font().pointSize(), 1.0)))); newFont.setPointSize(std::max(fontFactor * font().pointSize(), 1.0)); } @@ -270,10 +270,10 @@ void TalkingUI::updateStatusIcons(const ClientUser *user) { } TalkingUIUser::UserStatus status; - status.muted = user->bMute; - status.selfMuted = user->bSelfMute; - status.localMuted = user->bLocalMute; - status.deafened = user->bDeaf; + status.muted = user->bMute; + status.selfMuted = user->bSelfMute; + status.localMuted = user->bLocalMute; + status.deafened = user->bDeaf; status.selfDeafened = user->bSelfDeaf; userEntry->setStatus(status); @@ -285,8 +285,9 @@ void TalkingUI::hideUser(unsigned int session) { updateUI(); } -QString createChannelName(const Channel *chan, bool abbreviateName, int minPrefixChars, int minPostfixChars, int idealMaxChars, int parentLevel, - const QString &separator, const QString &abbreviationIndicator, bool abbreviateCurrentChannel) { +QString createChannelName(const Channel *chan, bool abbreviateName, int minPrefixChars, int minPostfixChars, + int idealMaxChars, int parentLevel, const QString &separator, + const QString &abbreviationIndicator, bool abbreviateCurrentChannel) { if (!abbreviateName) { return chan->qsName; } @@ -320,7 +321,8 @@ QString createChannelName(const Channel *chan, bool abbreviateName, int minPrefi QString groupName = reachedRoot ? separator : QString(); for (int i = nameList.size() - 1; i >= 0; i--) { - if (totalCharCount > idealMaxChars && nameList[i].size() >= abbreviableSize && (abbreviateCurrentChannel || i != 0)) { + if (totalCharCount > idealMaxChars && nameList[i].size() >= abbreviableSize + && (abbreviateCurrentChannel || i != 0)) { // Abbreviate the names as much as possible groupName += nameList[i].left(minPrefixChars) + abbreviationIndicator + nameList[i].right(minPostfixChars); } else { @@ -338,11 +340,14 @@ QString createChannelName(const Channel *chan, bool abbreviateName, int minPrefi void TalkingUI::addChannel(const Channel *channel) { if (findContainer(channel->iId, ContainerType::CHANNEL) < 0) { // Create a QGroupBox for this channel - const QString channelName = createChannelName(channel, g.s.bTalkingUI_AbbreviateChannelNames, g.s.iTalkingUI_PrefixCharCount, - g.s.iTalkingUI_PostfixCharCount, g.s.iTalkingUI_MaxChannelNameLength, g.s.iTalkingUI_ChannelHierarchyDepth, - g.s.qsTalkingUI_ChannelSeparator, g.s.qsTalkingUI_AbbreviationReplacement, g.s.bTalkingUI_AbbreviateCurrentChannel); + const QString channelName = + createChannelName(channel, g.s.bTalkingUI_AbbreviateChannelNames, g.s.iTalkingUI_PrefixCharCount, + g.s.iTalkingUI_PostfixCharCount, g.s.iTalkingUI_MaxChannelNameLength, + g.s.iTalkingUI_ChannelHierarchyDepth, g.s.qsTalkingUI_ChannelSeparator, + g.s.qsTalkingUI_AbbreviationReplacement, g.s.bTalkingUI_AbbreviateCurrentChannel); - std::unique_ptr<TalkingUIChannel> channelContainer = std::make_unique<TalkingUIChannel>(channel->iId, channelName, *this); + std::unique_ptr< TalkingUIChannel > channelContainer = + std::make_unique< TalkingUIChannel >(channel->iId, channelName, *this); QWidget *channelWidget = channelContainer->getWidget(); @@ -362,7 +367,7 @@ void TalkingUI::addUser(const ClientUser *user) { TalkingUIUser *oldUserEntry = findUser(user->uiSession); - bool nameMatches = true; + bool nameMatches = true; if (oldUserEntry) { // We also verify whether the name for that user matches up (if it is contained in m_entries) in case @@ -387,13 +392,14 @@ void TalkingUI::addUser(const ClientUser *user) { // We initially set the labels to not be visible, so that we'll // enter the code-block further down. - std::unique_ptr<TalkingUIContainer> &channelContainer = m_containers[findContainer(user->cChannel->iId, ContainerType::CHANNEL)]; + std::unique_ptr< TalkingUIContainer > &channelContainer = + m_containers[findContainer(user->cChannel->iId, ContainerType::CHANNEL)]; if (!channelContainer) { qCritical("TalkingUI::addUser requesting unknown channel!"); return; } - std::unique_ptr<TalkingUIUser> userEntry = std::make_unique<TalkingUIUser>(*user); + std::unique_ptr< TalkingUIUser > userEntry = std::make_unique< TalkingUIUser >(*user); // * 1000 as the setting is in seconds whereas the timer expects milliseconds userEntry->setLifeTime(g.s.iTalkingUI_SilentUserLifeTime * 1000); @@ -402,7 +408,8 @@ void TalkingUI::addUser(const ClientUser *user) { userEntry->setPriority(isSelf ? EntryPriority::HIGH : EntryPriority::DEFAULT); - QObject::connect(user, &ClientUser::localVolumeAdjustmentsChanged, this, &TalkingUI::on_userLocalVolumeAdjustmentsChanged); + QObject::connect(user, &ClientUser::localVolumeAdjustmentsChanged, this, + &TalkingUI::on_userLocalVolumeAdjustmentsChanged); // If this user is currently selected, mark him/her as such if (g.mw && g.mw->pmModel && g.mw->pmModel->getSelectedUser() == user) { @@ -424,7 +431,7 @@ void TalkingUI::moveUserToChannel(unsigned int userSession, int channelID) { return; } - std::unique_ptr<TalkingUIContainer> &targetChannel = m_containers[targetChanIndex]; + std::unique_ptr< TalkingUIContainer > &targetChannel = m_containers[targetChanIndex]; if (targetChannel->contains(userSession, EntryType::USER)) { // The given user is already in the target channel - nothing to do @@ -456,7 +463,7 @@ void TalkingUI::updateUI() { } void TalkingUI::setSelection(const TalkingUISelection &selection) { - if (dynamic_cast<const EmptySelection *>(&selection)) { + if (dynamic_cast< const EmptySelection * >(&selection)) { // The selection is set to an empty selection if (m_currentSelection) { // There currently is a selection -> clear and remove it @@ -494,23 +501,25 @@ void TalkingUI::mousePressEvent(QMouseEvent *event) { bool foundTarget = false; for (auto ¤tContainer : m_containers) { - QRect containerArea(currentContainer->getWidget()->mapToGlobal({0, 0}), - currentContainer->getWidget()->size()); + QRect containerArea(currentContainer->getWidget()->mapToGlobal({ 0, 0 }), + currentContainer->getWidget()->size()); if (containerArea.contains(event->globalPos())) { for (auto ¤tEntry : currentContainer->getEntries()) { - QRect entryArea(currentEntry->getWidget()->mapToGlobal({0, 0}), - currentEntry->getWidget()->size()); + QRect entryArea(currentEntry->getWidget()->mapToGlobal({ 0, 0 }), currentEntry->getWidget()->size()); if (entryArea.contains(event->globalPos())) { - switch(currentEntry->getType()) { + switch (currentEntry->getType()) { case EntryType::USER: - setSelection(UserSelection(currentEntry->getWidget(), currentEntry->getAssociatedUserSession())); + setSelection( + UserSelection(currentEntry->getWidget(), currentEntry->getAssociatedUserSession())); break; case EntryType::LISTENER: - TalkingUIChannelListener *listenerEntry = static_cast<TalkingUIChannelListener *>(currentEntry.get()); + TalkingUIChannelListener *listenerEntry = + static_cast< TalkingUIChannelListener * >(currentEntry.get()); setSelection(ListenerSelection(listenerEntry->getWidget(), - listenerEntry->getAssociatedUserSession(), listenerEntry->getAssociatedChannelID())); + listenerEntry->getAssociatedUserSession(), + listenerEntry->getAssociatedChannelID())); break; } @@ -522,7 +531,8 @@ void TalkingUI::mousePressEvent(QMouseEvent *event) { if (!foundTarget) { // Select channel itself - setSelection(ChannelSelection(currentContainer->getWidget(), currentContainer->getAssociatedChannelID())); + setSelection( + ChannelSelection(currentContainer->getWidget(), currentContainer->getAssociatedChannelID())); foundTarget = true; } @@ -533,14 +543,15 @@ void TalkingUI::mousePressEvent(QMouseEvent *event) { if (foundTarget) { if (event->button() == Qt::RightButton && g.mw) { - // If an entry is selected and the right mouse button was clicked, we pretend as if the user had clicked on the client in - // the MainWindow. For this to work we map the global mouse position to the local coordinate system of the UserView in the - // MainWindow. The function will use some internal logic to determine the user to invoke the context menu on but if that - // fails (which in this case it will), it'll fall back to the currently selected item. This item we have updated to the - // correct one with the setSelection() call above resulting in the proper context menu being shown at the position of the - // mouse which in this case is in the TalkingUI. - QMetaObject::invokeMethod(g.mw, "on_qtvUsers_customContextMenuRequested", Qt::QueuedConnection, Q_ARG(QPoint, - g.mw->qtvUsers->mapFromGlobal(event->globalPos()))); + // If an entry is selected and the right mouse button was clicked, we pretend as if the user had clicked on + // the client in the MainWindow. For this to work we map the global mouse position to the local coordinate + // system of the UserView in the MainWindow. The function will use some internal logic to determine the user + // to invoke the context menu on but if that fails (which in this case it will), it'll fall back to the + // currently selected item. This item we have updated to the correct one with the setSelection() call above + // resulting in the proper context menu being shown at the position of the mouse which in this case is in + // the TalkingUI. + QMetaObject::invokeMethod(g.mw, "on_qtvUsers_customContextMenuRequested", Qt::QueuedConnection, + Q_ARG(QPoint, g.mw->qtvUsers->mapFromGlobal(event->globalPos()))); } } else { // Clear selection @@ -562,17 +573,17 @@ QSize TalkingUI::sizeHint() const { // Prefer to occupy at least 10% of the screen's size // This aims to be a good compromise between not being in the way and not // being too small to being handled properly. - int width = QGuiApplication::screens()[0]->availableSize().width() * 0.1; + int width = QGuiApplication::screens()[0]->availableSize().width() * 0.1; - return {width, 0}; + return { width, 0 }; } QSize TalkingUI::minimumSizeHint() const { - return {0, 0}; + return { 0, 0 }; } void TalkingUI::on_talkingStateChanged() { - ClientUser *user = qobject_cast<ClientUser *>(sender()); + ClientUser *user = qobject_cast< ClientUser * >(sender()); if (!user) { // If the user that caused this event doesn't exist anymore, it means that it @@ -594,9 +605,10 @@ void TalkingUI::on_talkingStateChanged() { addUser(user); // addUser puts the user in its current channel, so we can fetch that and know that it'll contain the user - std::unique_ptr<TalkingUIContainer> &channel = m_containers[findContainer(user->cChannel->iId, ContainerType::CHANNEL)]; + std::unique_ptr< TalkingUIContainer > &channel = + m_containers[findContainer(user->cChannel->iId, ContainerType::CHANNEL)]; - TalkingUIUser *userEntry = static_cast<TalkingUIUser *>(channel->get(user->uiSession, EntryType::USER)); + TalkingUIUser *userEntry = static_cast< TalkingUIUser * >(channel->get(user->uiSession, EntryType::USER)); userEntry->setTalkingState(user->tsState); @@ -639,9 +651,10 @@ void TalkingUI::on_mainWindowSelectionChanged(const QModelIndex ¤t, const if (index >= 0) { // Only select the channel if there is present in the TalkingUI - std::unique_ptr<TalkingUIContainer> &targetContainer = m_containers[index]; + std::unique_ptr< TalkingUIContainer > &targetContainer = m_containers[index]; - setSelection(ChannelSelection(targetContainer->getWidget(), targetContainer->getAssociatedChannelID())); + setSelection( + ChannelSelection(targetContainer->getWidget(), targetContainer->getAssociatedChannelID())); clearSelection = false; } @@ -678,7 +691,7 @@ void TalkingUI::on_serverDisconnected() { void TalkingUI::on_channelChanged(QObject *obj) { // According to this function's doc, the passed object must be of type ClientUser - ClientUser *user = static_cast<ClientUser *>(obj); + ClientUser *user = static_cast< ClientUser * >(obj); if (!user) { return; @@ -709,16 +722,17 @@ void TalkingUI::on_settingsChanged() { continue; } - TalkingUIChannel *channelContainer = static_cast<TalkingUIChannel *>(currentContainer.get()); + TalkingUIChannel *channelContainer = static_cast< TalkingUIChannel * >(currentContainer.get()); const Channel *channel = Channel::get(currentContainer->getAssociatedChannelID()); if (channel) { // Update - channelContainer->setName(createChannelName(channel, g.s.bTalkingUI_AbbreviateChannelNames, g.s.iTalkingUI_PrefixCharCount, - g.s.iTalkingUI_PostfixCharCount, g.s.iTalkingUI_MaxChannelNameLength, g.s.iTalkingUI_ChannelHierarchyDepth, - g.s.qsTalkingUI_ChannelSeparator, g.s.qsTalkingUI_AbbreviationReplacement, g.s.bTalkingUI_AbbreviateCurrentChannel) - ); + channelContainer->setName( + createChannelName(channel, g.s.bTalkingUI_AbbreviateChannelNames, g.s.iTalkingUI_PrefixCharCount, + g.s.iTalkingUI_PostfixCharCount, g.s.iTalkingUI_MaxChannelNameLength, + g.s.iTalkingUI_ChannelHierarchyDepth, g.s.qsTalkingUI_ChannelSeparator, + g.s.qsTalkingUI_AbbreviationReplacement, g.s.bTalkingUI_AbbreviateCurrentChannel)); } else { qCritical("TalkingUI: Can't find channel for stored ID"); } @@ -730,7 +744,7 @@ void TalkingUI::on_settingsChanged() { currentEntry->setIconSize(m_currentLineHeight); if (currentEntry->getType() == EntryType::USER) { - TalkingUIUser *userEntry = static_cast<TalkingUIUser *>(currentEntry.get()); + TalkingUIUser *userEntry = static_cast< TalkingUIUser * >(currentEntry.get()); // The time that a silent user may stick around might have changed as well // * 1000 as the setting is in seconds whereas the timer expects milliseconds @@ -754,11 +768,11 @@ void TalkingUI::on_settingsChanged() { if (g.s.bTalkingUI_ShowLocalListeners) { const ClientUser *self = ClientUser::get(g.uiSession); if (self) { - const QSet<int> channels = ChannelListener::getListenedChannelsForUser(self->uiSession); + const QSet< int > channels = ChannelListener::getListenedChannelsForUser(self->uiSession); - for (int currentChannelID : channels) { + for (int currentChannelID : channels) { const Channel *channel = Channel::get(currentChannelID); - + if (channel) { addListener(self, channel); } @@ -772,7 +786,7 @@ void TalkingUI::on_clientDisconnected(unsigned int userSession) { } void TalkingUI::on_muteDeafStateChanged() { - ClientUser *user = qobject_cast<ClientUser *>(sender()); + ClientUser *user = qobject_cast< ClientUser * >(sender()); if (user) { // Update icons for local user only @@ -781,7 +795,7 @@ void TalkingUI::on_muteDeafStateChanged() { } void TalkingUI::on_userLocalVolumeAdjustmentsChanged(float, float) { - ClientUser *user = qobject_cast<ClientUser *>(sender()); + ClientUser *user = qobject_cast< ClientUser * >(sender()); if (user) { TalkingUIUser *userEntry = findUser(user->uiSession); diff --git a/src/mumble/TalkingUI.h b/src/mumble/TalkingUI.h index 6e4d64f22..21414567e 100644 --- a/src/mumble/TalkingUI.h +++ b/src/mumble/TalkingUI.h @@ -15,9 +15,9 @@ #include <vector> #include "Settings.h" -#include "TalkingUISelection.h" #include "TalkingUIContainer.h" #include "TalkingUIEntry.h" +#include "TalkingUISelection.h" class QLabel; class QGroupBox; @@ -33,94 +33,95 @@ class TalkingUIComponent; class TalkingUI : public QWidget { friend class TalkingUIUser; - private: - Q_OBJECT - Q_DISABLE_COPY(TalkingUI); - - std::vector<std::unique_ptr<TalkingUIContainer>> m_containers; - /// The Entry corresponding to the currently selected user - std::unique_ptr<TalkingUISelection> m_currentSelection; - - /// The current line height of an entry in the TalkingUI - int m_currentLineHeight; - - int findContainer(int associatedChannelID, ContainerType type) const; - std::unique_ptr<TalkingUIContainer> removeContainer(const TalkingUIContainer &container); - std::unique_ptr<TalkingUIContainer> removeContainer(int associatedChannelID, ContainerType type); - std::unique_ptr<TalkingUIContainer> removeIfSuperfluous(const TalkingUIContainer &container); - - void sortContainers(); - - TalkingUIUser *findUser(unsigned int userSession); - void removeUser(unsigned int userSession); - - void addListener(const ClientUser *user, const Channel *channel); - TalkingUIChannelListener *findListener(unsigned int userSession, int channelID); - void removeListener(unsigned int userSession, int channelID); - void removeAllListeners(); - - /// Sets up the UI components - void setupUI(); - /// Hides an user - /// - /// @param session The session ID of the user that shall be hidden - void hideUser(unsigned int session); - /// Adds an UI entry for the given Channel, if none exists yet. - /// - /// @param channel A pointer to the channel that shall be added - void addChannel(const Channel *channel);; - /// Adds an UI entry for the given User, if none exists yet. - /// - /// @param channel A pointer to the user that shall be added - void addUser(const ClientUser *user); - /// Moves the given user into the given channel - /// - /// @paam userSession The session ID of the user - /// @param channelID The channel ID of the channel - void moveUserToChannel(unsigned int userSession, int channelID); - - /// Update (resize) the UI to its content - void updateUI(); - - /// Sets the font size according to the settings - /// - /// @param widget a pointer to the widget to set the font size for - void setFontSize(QWidget *widget); - - /// Updates the user's status icons (reflecting e.g. its mut-state) - /// - /// @param user A pointer to the user that shall be processed - void updateStatusIcons(const ClientUser *user); - - /// Set the current selection - /// - /// @param selection The new selection - void setSelection(const TalkingUISelection &selection); - - bool isSelected(const TalkingUIComponent &component) const; - - void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; - - public: - TalkingUI(QWidget *parent = nullptr); - - void setVisible(bool visible) Q_DECL_OVERRIDE; - QSize sizeHint() const Q_DECL_OVERRIDE; - QSize minimumSizeHint() const Q_DECL_OVERRIDE; - - public slots: - void on_talkingStateChanged(); - void on_mainWindowSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); - void on_serverSynchronized(); - void on_serverDisconnected(); - void on_channelChanged(QObject *user); - void on_settingsChanged(); - void on_clientDisconnected(unsigned int userSession); - void on_muteDeafStateChanged(); - void on_userLocalVolumeAdjustmentsChanged(float newAdjustment, float oldAdjustment); - void on_channelListenerAdded(const ClientUser *user, const Channel *channel); - void on_channelListenerRemoved(const ClientUser *user, const Channel *channel); - void on_channelListenerLocalVolumeAdjustmentChanged(int channelID, float newAdjustment, float oldAdjustment); +private: + Q_OBJECT + Q_DISABLE_COPY(TalkingUI); + + std::vector< std::unique_ptr< TalkingUIContainer > > m_containers; + /// The Entry corresponding to the currently selected user + std::unique_ptr< TalkingUISelection > m_currentSelection; + + /// The current line height of an entry in the TalkingUI + int m_currentLineHeight; + + int findContainer(int associatedChannelID, ContainerType type) const; + std::unique_ptr< TalkingUIContainer > removeContainer(const TalkingUIContainer &container); + std::unique_ptr< TalkingUIContainer > removeContainer(int associatedChannelID, ContainerType type); + std::unique_ptr< TalkingUIContainer > removeIfSuperfluous(const TalkingUIContainer &container); + + void sortContainers(); + + TalkingUIUser *findUser(unsigned int userSession); + void removeUser(unsigned int userSession); + + void addListener(const ClientUser *user, const Channel *channel); + TalkingUIChannelListener *findListener(unsigned int userSession, int channelID); + void removeListener(unsigned int userSession, int channelID); + void removeAllListeners(); + + /// Sets up the UI components + void setupUI(); + /// Hides an user + /// + /// @param session The session ID of the user that shall be hidden + void hideUser(unsigned int session); + /// Adds an UI entry for the given Channel, if none exists yet. + /// + /// @param channel A pointer to the channel that shall be added + void addChannel(const Channel *channel); + ; + /// Adds an UI entry for the given User, if none exists yet. + /// + /// @param channel A pointer to the user that shall be added + void addUser(const ClientUser *user); + /// Moves the given user into the given channel + /// + /// @paam userSession The session ID of the user + /// @param channelID The channel ID of the channel + void moveUserToChannel(unsigned int userSession, int channelID); + + /// Update (resize) the UI to its content + void updateUI(); + + /// Sets the font size according to the settings + /// + /// @param widget a pointer to the widget to set the font size for + void setFontSize(QWidget *widget); + + /// Updates the user's status icons (reflecting e.g. its mut-state) + /// + /// @param user A pointer to the user that shall be processed + void updateStatusIcons(const ClientUser *user); + + /// Set the current selection + /// + /// @param selection The new selection + void setSelection(const TalkingUISelection &selection); + + bool isSelected(const TalkingUIComponent &component) const; + + void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + +public: + TalkingUI(QWidget *parent = nullptr); + + void setVisible(bool visible) Q_DECL_OVERRIDE; + QSize sizeHint() const Q_DECL_OVERRIDE; + QSize minimumSizeHint() const Q_DECL_OVERRIDE; + +public slots: + void on_talkingStateChanged(); + void on_mainWindowSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); + void on_serverSynchronized(); + void on_serverDisconnected(); + void on_channelChanged(QObject *user); + void on_settingsChanged(); + void on_clientDisconnected(unsigned int userSession); + void on_muteDeafStateChanged(); + void on_userLocalVolumeAdjustmentsChanged(float newAdjustment, float oldAdjustment); + void on_channelListenerAdded(const ClientUser *user, const Channel *channel); + void on_channelListenerRemoved(const ClientUser *user, const Channel *channel); + void on_channelListenerLocalVolumeAdjustmentChanged(int channelID, float newAdjustment, float oldAdjustment); }; #endif // MUMBLE_MUMBLE_TALKINGUI_H_ diff --git a/src/mumble/TalkingUIComponent.h b/src/mumble/TalkingUIComponent.h index a6aaa0278..e21105f67 100644 --- a/src/mumble/TalkingUIComponent.h +++ b/src/mumble/TalkingUIComponent.h @@ -9,9 +9,9 @@ class QWidget; class TalkingUIComponent { - public: - virtual QWidget *getWidget() = 0; - virtual const QWidget *getWidget() const = 0; +public: + virtual QWidget *getWidget() = 0; + virtual const QWidget *getWidget() const = 0; }; #endif // MUMBLE_MUMBLE_TALKINGUICOMPONENT_H_ diff --git a/src/mumble/TalkingUIContainer.cpp b/src/mumble/TalkingUIContainer.cpp index 62fbb2fc2..e89930192 100644 --- a/src/mumble/TalkingUIContainer.cpp +++ b/src/mumble/TalkingUIContainer.cpp @@ -13,7 +13,7 @@ struct entry_ptr_less { - bool operator()(const std::unique_ptr<TalkingUIEntry>& first, const std::unique_ptr<TalkingUIEntry>& second) { + bool operator()(const std::unique_ptr< TalkingUIEntry > &first, const std::unique_ptr< TalkingUIEntry > &second) { return *first < *second; } }; @@ -21,16 +21,15 @@ struct entry_ptr_less { TalkingUIContainer::TalkingUIContainer(int associatedChannelID, TalkingUI &talkingUI) - : m_associatedChannelID(associatedChannelID), - m_talkingUI(talkingUI) { + : m_associatedChannelID(associatedChannelID), m_talkingUI(talkingUI) { } int TalkingUIContainer::find(unsigned int associatedUserSession, EntryType type) const { for (std::size_t i = 0; i < m_entries.size(); i++) { - const std::unique_ptr<TalkingUIEntry> ¤tEntry = m_entries[i]; + const std::unique_ptr< TalkingUIEntry > ¤tEntry = m_entries[i]; if (currentEntry->getType() == type && currentEntry->getAssociatedUserSession() == associatedUserSession) { - return static_cast<int>(i); + return static_cast< int >(i); } } @@ -41,21 +40,21 @@ int TalkingUIContainer::getAssociatedChannelID() const { return m_associatedChannelID; } -void TalkingUIContainer::addEntry(std::unique_ptr<TalkingUIEntry> entry) { +void TalkingUIContainer::addEntry(std::unique_ptr< TalkingUIEntry > entry) { // set container entry->m_container = this; m_entries.push_back(std::move(entry)); } -std::unique_ptr<TalkingUIEntry> TalkingUIContainer::removeEntry(const TalkingUIEntry *entry) { +std::unique_ptr< TalkingUIEntry > TalkingUIContainer::removeEntry(const TalkingUIEntry *entry) { return removeEntry(entry->getAssociatedUserSession(), entry->getType()); } -std::unique_ptr<TalkingUIEntry> TalkingUIContainer::removeEntry(unsigned int associatedUserSession, EntryType type) { +std::unique_ptr< TalkingUIEntry > TalkingUIContainer::removeEntry(unsigned int associatedUserSession, EntryType type) { int index = find(associatedUserSession, type); - std::unique_ptr<TalkingUIEntry> entry(nullptr); + std::unique_ptr< TalkingUIEntry > entry(nullptr); if (index >= 0) { // Move the entry out of the vector @@ -69,11 +68,11 @@ std::unique_ptr<TalkingUIEntry> TalkingUIContainer::removeEntry(unsigned int ass return entry; } -std::vector<std::unique_ptr<TalkingUIEntry>> &TalkingUIContainer::getEntries() { +std::vector< std::unique_ptr< TalkingUIEntry > > &TalkingUIContainer::getEntries() { return m_entries; } -const std::vector<std::unique_ptr<TalkingUIEntry>> &TalkingUIContainer::getEntries() const { +const std::vector< std::unique_ptr< TalkingUIEntry > > &TalkingUIContainer::getEntries() const { return m_entries; } @@ -133,15 +132,10 @@ bool TalkingUIContainer::operator<=(const TalkingUIContainer &other) const { - - - const int CHANNEL_LAYOUT_TOP_MARGIN = 10; TalkingUIChannel::TalkingUIChannel(int associatedChannelID, QString name, TalkingUI &talkingUI) - : TalkingUIContainer(associatedChannelID, talkingUI), - m_channelBox(new QGroupBox()) { - + : TalkingUIContainer(associatedChannelID, talkingUI), m_channelBox(new QGroupBox()) { // Set name m_channelBox->setTitle(name); @@ -173,10 +167,10 @@ void TalkingUIChannel::setName(const QString &name) { int TalkingUIChannel::compare(const TalkingUIContainer &other) const { if (getType() != other.getType()) { - return static_cast<int>(other.getType()) - static_cast<int>(getType()); + return static_cast< int >(other.getType()) - static_cast< int >(getType()); } - const TalkingUIChannel &otherChannel = static_cast<const TalkingUIChannel &>(other); + const TalkingUIChannel &otherChannel = static_cast< const TalkingUIChannel & >(other); if (m_highestUserPriority != otherChannel.m_highestUserPriority) { return m_highestUserPriority < otherChannel.m_highestUserPriority ? 1 : -1; @@ -204,7 +198,7 @@ ContainerType TalkingUIChannel::getType() const { return ContainerType::CHANNEL; } -void TalkingUIChannel::addEntry(std::unique_ptr<TalkingUIEntry> entry) { +void TalkingUIChannel::addEntry(std::unique_ptr< TalkingUIEntry > entry) { if (entry->getPriority() > m_highestUserPriority) { m_highestUserPriority = entry->getPriority(); } @@ -224,8 +218,8 @@ void TalkingUIChannel::addEntry(std::unique_ptr<TalkingUIEntry> entry) { } } -std::unique_ptr<TalkingUIEntry> TalkingUIChannel::removeEntry(unsigned int associatedUserSession, EntryType type) { - std::unique_ptr<TalkingUIEntry> entry = TalkingUIContainer::removeEntry(associatedUserSession, type); +std::unique_ptr< TalkingUIEntry > TalkingUIChannel::removeEntry(unsigned int associatedUserSession, EntryType type) { + std::unique_ptr< TalkingUIEntry > entry = TalkingUIContainer::removeEntry(associatedUserSession, type); if (entry) { m_channelBox->layout()->removeWidget(entry->getWidget()); diff --git a/src/mumble/TalkingUIContainer.h b/src/mumble/TalkingUIContainer.h index 7b603874c..a35362051 100644 --- a/src/mumble/TalkingUIContainer.h +++ b/src/mumble/TalkingUIContainer.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MUMBLE_TALKINGUICONTAINER_H_ #define MUMBLE_MUMBLE_TALKINGUICONTAINER_H_ -#include "TalkingUIEntry.h" #include "TalkingUIComponent.h" +#include "TalkingUIEntry.h" #include <QString> @@ -17,86 +17,84 @@ class QWidget; class QGroupBox; class TalkingUI; -enum class ContainerType { - CHANNEL -}; +enum class ContainerType { CHANNEL }; class TalkingUIContainer : public TalkingUIComponent { friend class TalkingUIUser; - protected: - std::vector<std::unique_ptr<TalkingUIEntry> > m_entries; +protected: + std::vector< std::unique_ptr< TalkingUIEntry > > m_entries; - int m_associatedChannelID = -1; + int m_associatedChannelID = -1; - bool m_permanent = false; + bool m_permanent = false; - TalkingUI &m_talkingUI; + TalkingUI &m_talkingUI; - virtual int find(unsigned int associatedUserSession, EntryType type) const; + virtual int find(unsigned int associatedUserSession, EntryType type) const; - public: - TalkingUIContainer(int associatedChannelID, TalkingUI &talkingUI); - virtual ~TalkingUIContainer() = default; +public: + TalkingUIContainer(int associatedChannelID, TalkingUI &talkingUI); + virtual ~TalkingUIContainer() = default; - virtual QString getName() const = 0; + virtual QString getName() const = 0; - virtual int compare(const TalkingUIContainer &other) const = 0; + virtual int compare(const TalkingUIContainer &other) const = 0; - virtual ContainerType getType() const = 0; + virtual ContainerType getType() const = 0; - virtual int getAssociatedChannelID() const; + virtual int getAssociatedChannelID() const; - virtual void addEntry(std::unique_ptr<TalkingUIEntry> entry); - virtual std::unique_ptr<TalkingUIEntry> removeEntry(const TalkingUIEntry *entry); - virtual std::unique_ptr<TalkingUIEntry> removeEntry(unsigned int associatedUserSession, EntryType type); + virtual void addEntry(std::unique_ptr< TalkingUIEntry > entry); + virtual std::unique_ptr< TalkingUIEntry > removeEntry(const TalkingUIEntry *entry); + virtual std::unique_ptr< TalkingUIEntry > removeEntry(unsigned int associatedUserSession, EntryType type); - virtual std::vector<std::unique_ptr<TalkingUIEntry>> &getEntries(); - virtual const std::vector<std::unique_ptr<TalkingUIEntry>> &getEntries() const; + virtual std::vector< std::unique_ptr< TalkingUIEntry > > &getEntries(); + virtual const std::vector< std::unique_ptr< TalkingUIEntry > > &getEntries() const; - virtual bool contains(unsigned int associatedUserSession, EntryType type) const; + virtual bool contains(unsigned int associatedUserSession, EntryType type) const; - virtual std::size_t size() const; - virtual bool isEmpty() const; + virtual std::size_t size() const; + virtual bool isEmpty() const; - virtual void setPermanent(bool permanent); - virtual bool isPermanent() const; + virtual void setPermanent(bool permanent); + virtual bool isPermanent() const; - virtual TalkingUIEntry *get(unsigned int associatedUserSession, EntryType type); + virtual TalkingUIEntry *get(unsigned int associatedUserSession, EntryType type); - bool operator==(const TalkingUIContainer &other) const; - bool operator!=(const TalkingUIContainer &other) const; - bool operator>(const TalkingUIContainer &other) const; - bool operator>=(const TalkingUIContainer &other) const; - bool operator<(const TalkingUIContainer &other) const; - bool operator<=(const TalkingUIContainer &other) const; + bool operator==(const TalkingUIContainer &other) const; + bool operator!=(const TalkingUIContainer &other) const; + bool operator>(const TalkingUIContainer &other) const; + bool operator>=(const TalkingUIContainer &other) const; + bool operator<(const TalkingUIContainer &other) const; + bool operator<=(const TalkingUIContainer &other) const; }; class TalkingUIChannel : public TalkingUIContainer { - protected: - QGroupBox *m_channelBox; +protected: + QGroupBox *m_channelBox; - EntryPriority m_highestUserPriority = EntryPriority::LOW; + EntryPriority m_highestUserPriority = EntryPriority::LOW; - void updatePriority(); + void updatePriority(); - public: - TalkingUIChannel(int associatedChannelID, QString name, TalkingUI &talkingUI); - virtual ~TalkingUIChannel(); +public: + TalkingUIChannel(int associatedChannelID, QString name, TalkingUI &talkingUI); + virtual ~TalkingUIChannel(); - virtual QString getName() const override; - virtual void setName(const QString &name); + virtual QString getName() const override; + virtual void setName(const QString &name); - virtual int compare(const TalkingUIContainer &other) const override; + virtual int compare(const TalkingUIContainer &other) const override; - virtual QWidget *getWidget() override; - virtual const QWidget *getWidget() const override; + virtual QWidget *getWidget() override; + virtual const QWidget *getWidget() const override; - virtual ContainerType getType() const override; + virtual ContainerType getType() const override; - virtual void addEntry(std::unique_ptr<TalkingUIEntry> entry) override; - virtual std::unique_ptr<TalkingUIEntry> removeEntry(unsigned int associatedUserSession, EntryType type) override; + virtual void addEntry(std::unique_ptr< TalkingUIEntry > entry) override; + virtual std::unique_ptr< TalkingUIEntry > removeEntry(unsigned int associatedUserSession, EntryType type) override; }; #endif // MUMBLE_MUMBLE_TALKINGUICONTAINER_H_ diff --git a/src/mumble/TalkingUIEntry.cpp b/src/mumble/TalkingUIEntry.cpp index 6d9df0308..150869106 100644 --- a/src/mumble/TalkingUIEntry.cpp +++ b/src/mumble/TalkingUIEntry.cpp @@ -4,25 +4,25 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "TalkingUIEntry.h" -#include "TalkingUIContainer.h" -#include "TalkingUI.h" +#include "Channel.h" #include "ClientUser.h" +#include "TalkingUI.h" +#include "TalkingUIContainer.h" #include "UserModel.h" -#include "Channel.h" -#include <QWidget> -#include <QLabel> #include <QHBoxLayout> -#include <QVariant> +#include <QLabel> #include <QObject> #include <QPainter> #include <QPixmap> +#include <QVariant> +#include <QWidget> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -TalkingUIEntry::TalkingUIEntry(unsigned int associatedUserSession) - : m_associatedUserSession(associatedUserSession) { +TalkingUIEntry::TalkingUIEntry(unsigned int associatedUserSession) : m_associatedUserSession(associatedUserSession) { } unsigned int TalkingUIEntry::getAssociatedUserSession() const { @@ -39,7 +39,7 @@ const TalkingUIContainer *TalkingUIEntry::getContainer() const { int TalkingUIEntry::compare(const TalkingUIEntry &other) const { if (getPriority() != other.getPriority()) { - return static_cast<int>(getPriority()) - static_cast<int>(other.getPriority()); + return static_cast< int >(getPriority()) - static_cast< int >(other.getPriority()); } if (getType() != other.getType()) { @@ -87,31 +87,23 @@ bool TalkingUIEntry::operator>=(const TalkingUIEntry &other) const { - - static const int USER_CONTAINER_HORIZONTAL_MARGIN = 2; -static const int USER_CONTAINER_VERTICAL_MARGIN = 3; - +static const int USER_CONTAINER_VERTICAL_MARGIN = 3; -TalkingUIUser::TalkingUIUser(const ClientUser &user) - : TalkingUIEntry(user.uiSession), - m_name(user.qsName), - m_timer() { +TalkingUIUser::TalkingUIUser(const ClientUser &user) : TalkingUIEntry(user.uiSession), m_name(user.qsName), m_timer() { // Create background widget and its layout that we'll use to place all other // components on m_backgroundWidget = new QWidget(); m_backgroundWidget->setProperty("selected", false); QLayout *backgroundLayout = new QHBoxLayout(); - backgroundLayout->setContentsMargins(USER_CONTAINER_HORIZONTAL_MARGIN, - USER_CONTAINER_VERTICAL_MARGIN, - USER_CONTAINER_HORIZONTAL_MARGIN, - USER_CONTAINER_VERTICAL_MARGIN); + backgroundLayout->setContentsMargins(USER_CONTAINER_HORIZONTAL_MARGIN, USER_CONTAINER_VERTICAL_MARGIN, + USER_CONTAINER_HORIZONTAL_MARGIN, USER_CONTAINER_VERTICAL_MARGIN); m_backgroundWidget->setLayout(backgroundLayout); m_backgroundWidget->setAutoFillBackground(true); // Create the label we use to display the user's name - m_nameLabel = new QLabel(m_backgroundWidget); + m_nameLabel = new QLabel(m_backgroundWidget); const QString displayString = UserModel::createDisplayString(user, false, nullptr); setDisplayString(displayString); @@ -139,7 +131,7 @@ TalkingUIUser::TalkingUIUser(const ClientUser &user) // If the timer runs out, we remove this entry from its container (if any) // and thereby this will cause its deletion (smart-pointer goes out of scope) - QObject::connect(&m_timer, &QTimer::timeout, [this](){ + QObject::connect(&m_timer, &QTimer::timeout, [this]() { if (getContainer()) { // We let the TalkingUI handle the removing in order for it to do the necessary // housekeeping (e.g. making sure there is no active selection for this user). @@ -159,11 +151,11 @@ TalkingUIUser::~TalkingUIUser() { } const QIcon &TalkingUIUser::getTalkingIcon(Settings::TalkState talkState) const { - static const QIcon s_talkingIcon = QIcon(QLatin1String("skin:talking_on.svg")); + static const QIcon s_talkingIcon = QIcon(QLatin1String("skin:talking_on.svg")); static const QIcon s_mutedTalkingIcon = QIcon(QLatin1String("skin:talking_muted.svg")); - static const QIcon s_passiveIcon = QIcon(QLatin1String("skin:talking_off.svg")); - static const QIcon s_shoutingIcon = QIcon(QLatin1String("skin:talking_alt.svg")); - static const QIcon s_whisperingIcon = QIcon(QLatin1String("skin:talking_whisper.svg")); + static const QIcon s_passiveIcon = QIcon(QLatin1String("skin:talking_off.svg")); + static const QIcon s_shoutingIcon = QIcon(QLatin1String("skin:talking_alt.svg")); + static const QIcon s_whisperingIcon = QIcon(QLatin1String("skin:talking_whisper.svg")); switch (talkState) { case Settings::MutedTalking: @@ -202,10 +194,10 @@ QString TalkingUIUser::getName() const { int TalkingUIUser::compare(const TalkingUIEntry &other) const { if (other.getType() != getType()) { - return static_cast<int>(other.getType()) - static_cast<int>(getType()); + return static_cast< int >(other.getType()) - static_cast< int >(getType()); } - const TalkingUIUser &otherUser = static_cast<const TalkingUIUser &>(other); + const TalkingUIUser &otherUser = static_cast< const TalkingUIUser & >(other); if (getPriority() != otherUser.getPriority()) { return getPriority() < other.getPriority() ? 1 : -1; @@ -223,7 +215,8 @@ int TalkingUIUser::compare(const TalkingUIEntry &other) const { } void TalkingUIUser::updateTalkingIcon() { - m_talkingIcon->setPixmap(getTalkingIcon(m_talkingState).pixmap(QSize(m_iconSize, m_iconSize), QIcon::Normal, QIcon::On)); + m_talkingIcon->setPixmap( + getTalkingIcon(m_talkingState).pixmap(QSize(m_iconSize, m_iconSize), QIcon::Normal, QIcon::On)); } void TalkingUIUser::setTalkingState(Settings::TalkState talkState) { @@ -232,7 +225,7 @@ void TalkingUIUser::setTalkingState(Settings::TalkState talkState) { } m_talkingState = talkState; - + switch (talkState) { case Settings::Passive: if (m_restrictLifetime) { @@ -283,14 +276,14 @@ void TalkingUIUser::restrictLifetime(bool restrict) { } void TalkingUIUser::setStatus(UserStatus status) { - static const QIcon s_muteIcon = QIcon(QLatin1String("skin:muted_server.svg")); - static const QIcon s_deafIcon = QIcon(QLatin1String("skin:deafened_server.svg")); + static const QIcon s_muteIcon = QIcon(QLatin1String("skin:muted_server.svg")); + static const QIcon s_deafIcon = QIcon(QLatin1String("skin:deafened_server.svg")); static const QIcon s_localMuteIcon = QIcon(QLatin1String("skin:muted_local.svg")); - static const QIcon s_selfMuteIcon = QIcon(QLatin1String("skin:muted_self.svg")); - static const QIcon s_selfDeafIcon = QIcon(QLatin1String("skin:deafened_self.svg")); + static const QIcon s_selfMuteIcon = QIcon(QLatin1String("skin:muted_self.svg")); + static const QIcon s_selfDeafIcon = QIcon(QLatin1String("skin:deafened_self.svg")); - std::vector<std::reference_wrapper<const QIcon>> icons; + std::vector< std::reference_wrapper< const QIcon > > icons; if (status.muted) { icons.push_back(s_muteIcon); @@ -317,12 +310,12 @@ void TalkingUIUser::setStatus(UserStatus status) { const QSize size(m_iconSize * icons.size(), m_iconSize); QPixmap pixmap(size); pixmap.fill(Qt::transparent); - + // Draw the icons to the Pixmap QPainter painter(&pixmap); for (std::size_t i = 0; i < icons.size(); i++) { - painter.drawPixmap(i * m_iconSize, 0, icons[i].get().pixmap(QSize(m_iconSize, m_iconSize), - QIcon::Normal, QIcon::On)); + painter.drawPixmap(i * m_iconSize, 0, + icons[i].get().pixmap(QSize(m_iconSize, m_iconSize), QIcon::Normal, QIcon::On)); } m_statusIcons->setPixmap(pixmap); @@ -337,22 +330,15 @@ void TalkingUIUser::setStatus(UserStatus status) { - - TalkingUIChannelListener::TalkingUIChannelListener(const ClientUser &user, const Channel &channel) - : TalkingUIEntry(user.uiSession), - m_channelID(channel.iId), - m_name(user.qsName) { - + : TalkingUIEntry(user.uiSession), m_channelID(channel.iId), m_name(user.qsName) { // Create background widget and its layout that we'll use to place all other // components on m_backgroundWidget = new QWidget(); m_backgroundWidget->setProperty("selected", false); QLayout *backgroundLayout = new QHBoxLayout(); - backgroundLayout->setContentsMargins(USER_CONTAINER_HORIZONTAL_MARGIN, - USER_CONTAINER_VERTICAL_MARGIN, - USER_CONTAINER_HORIZONTAL_MARGIN, - USER_CONTAINER_VERTICAL_MARGIN); + backgroundLayout->setContentsMargins(USER_CONTAINER_HORIZONTAL_MARGIN, USER_CONTAINER_VERTICAL_MARGIN, + USER_CONTAINER_HORIZONTAL_MARGIN, USER_CONTAINER_VERTICAL_MARGIN); m_backgroundWidget->setLayout(backgroundLayout); m_backgroundWidget->setAutoFillBackground(true); @@ -366,7 +352,7 @@ TalkingUIChannelListener::TalkingUIChannelListener(const ClientUser &user, const setIconSize(iconSize); // Create the label we use to display the user's name - m_nameLabel = new QLabel(m_backgroundWidget); + m_nameLabel = new QLabel(m_backgroundWidget); const QString displayString = UserModel::createDisplayString(user, true, &channel); setDisplayString(displayString); diff --git a/src/mumble/TalkingUIEntry.h b/src/mumble/TalkingUIEntry.h index 477a81613..459fadc61 100644 --- a/src/mumble/TalkingUIEntry.h +++ b/src/mumble/TalkingUIEntry.h @@ -6,12 +6,12 @@ #ifndef MUMBLE_MUMBLE_TALKINGUIENTRY_H_ #define MUMBLE_MUMBLE_TALKINGUIENTRY_H_ -#include "TalkingUIComponent.h" #include "Settings.h" +#include "TalkingUIComponent.h" -#include <QString> #include <QIcon> #include <QLatin1String> +#include <QString> #include <QTimer> #include <vector> @@ -22,133 +22,125 @@ class TalkingUIContainer; class ClientUser; class Channel; -enum class EntryType { - USER, - LISTENER -}; +enum class EntryType { USER, LISTENER }; -enum class EntryPriority { - LOW, - DEFAULT, - HIGH -}; +enum class EntryPriority { LOW, DEFAULT, HIGH }; class TalkingUIEntry : public TalkingUIComponent { // Needed in order for the container class to be able to modify m_container friend class TalkingUIContainer; - protected: - unsigned int m_associatedUserSession; +protected: + unsigned int m_associatedUserSession; - TalkingUIContainer *m_container = nullptr; + TalkingUIContainer *m_container = nullptr; - EntryPriority m_priority = EntryPriority::DEFAULT; + EntryPriority m_priority = EntryPriority::DEFAULT; - public: - TalkingUIEntry(unsigned int associatedUserSession); - virtual ~TalkingUIEntry() = default; +public: + TalkingUIEntry(unsigned int associatedUserSession); + virtual ~TalkingUIEntry() = default; - virtual EntryType getType() const = 0; + virtual EntryType getType() const = 0; - virtual unsigned int getAssociatedUserSession() const; + virtual unsigned int getAssociatedUserSession() const; - virtual TalkingUIContainer *getContainer(); - virtual const TalkingUIContainer *getContainer() const; + virtual TalkingUIContainer *getContainer(); + virtual const TalkingUIContainer *getContainer() const; - virtual void setPriority(EntryPriority priority); - virtual EntryPriority getPriority() const; + virtual void setPriority(EntryPriority priority); + virtual EntryPriority getPriority() const; - virtual void setIconSize(int size) = 0; + virtual void setIconSize(int size) = 0; - virtual void setDisplayString(const QString &displayString) = 0; + virtual void setDisplayString(const QString &displayString) = 0; - virtual int compare(const TalkingUIEntry &other) const; + virtual int compare(const TalkingUIEntry &other) const; - bool operator==(const TalkingUIEntry &other) const; - bool operator!=(const TalkingUIEntry &other) const; - bool operator<(const TalkingUIEntry &other) const; - bool operator<=(const TalkingUIEntry &other) const; - bool operator>(const TalkingUIEntry &other) const; - bool operator>=(const TalkingUIEntry &other) const; + bool operator==(const TalkingUIEntry &other) const; + bool operator!=(const TalkingUIEntry &other) const; + bool operator<(const TalkingUIEntry &other) const; + bool operator<=(const TalkingUIEntry &other) const; + bool operator>(const TalkingUIEntry &other) const; + bool operator>=(const TalkingUIEntry &other) const; }; class TalkingUIUser : public TalkingUIEntry { - protected: - QWidget *m_backgroundWidget = nullptr; - - QLabel *m_talkingIcon = nullptr; - QLabel *m_nameLabel = nullptr; - QLabel *m_statusIcons = nullptr; +protected: + QWidget *m_backgroundWidget = nullptr; - QString m_name; + QLabel *m_talkingIcon = nullptr; + QLabel *m_nameLabel = nullptr; + QLabel *m_statusIcons = nullptr; - int m_iconSize = 5; - Settings::TalkState m_talkingState = Settings::Passive; + QString m_name; - QTimer m_timer; - bool m_restrictLifetime = false; + int m_iconSize = 5; + Settings::TalkState m_talkingState = Settings::Passive; - const QIcon &getTalkingIcon(Settings::TalkState talkState) const; + QTimer m_timer; + bool m_restrictLifetime = false; - virtual void updateTalkingIcon(); + const QIcon &getTalkingIcon(Settings::TalkState talkState) const; - public: + virtual void updateTalkingIcon(); - struct UserStatus { - bool muted, selfMuted, localMuted, deafened, selfDeafened; - }; +public: + struct UserStatus { + bool muted, selfMuted, localMuted, deafened, selfDeafened; + }; - TalkingUIUser(const ClientUser &user); - virtual ~TalkingUIUser() override; + TalkingUIUser(const ClientUser &user); + virtual ~TalkingUIUser() override; - virtual QWidget *getWidget() override; - virtual const QWidget *getWidget() const override; + virtual QWidget *getWidget() override; + virtual const QWidget *getWidget() const override; - virtual EntryType getType() const override; + virtual EntryType getType() const override; - virtual QString getName() const; + virtual QString getName() const; - virtual int compare(const TalkingUIEntry &other) const override; + virtual int compare(const TalkingUIEntry &other) const override; - virtual void setTalkingState(Settings::TalkState talkState); + virtual void setTalkingState(Settings::TalkState talkState); - virtual void setIconSize(int size) override; + virtual void setIconSize(int size) override; - virtual void setDisplayString(const QString &displayString) override; + virtual void setDisplayString(const QString &displayString) override; - virtual void setLifeTime(unsigned int time); - virtual void restrictLifetime(bool restrict); + virtual void setLifeTime(unsigned int time); + virtual void restrictLifetime(bool restrict); - virtual void setStatus(UserStatus status); + virtual void setStatus(UserStatus status); }; class TalkingUIChannelListener : public TalkingUIEntry { - protected: - QWidget *m_backgroundWidget = nullptr; +protected: + QWidget *m_backgroundWidget = nullptr; - QLabel *m_icon = nullptr; - QLabel *m_nameLabel = nullptr; + QLabel *m_icon = nullptr; + QLabel *m_nameLabel = nullptr; - int m_channelID; - QString m_name; + int m_channelID; + QString m_name; - public: - TalkingUIChannelListener(const ClientUser &user, const Channel &channel); - virtual ~TalkingUIChannelListener() override; +public: + TalkingUIChannelListener(const ClientUser &user, const Channel &channel); + virtual ~TalkingUIChannelListener() override; - virtual EntryType getType() const override; + virtual EntryType getType() const override; - virtual QWidget *getWidget() override; - virtual const QWidget *getWidget() const override; + virtual QWidget *getWidget() override; + virtual const QWidget *getWidget() const override; - virtual void setIconSize(int size) override; + virtual void setIconSize(int size) override; - virtual void setDisplayString(const QString &displayString) override; + virtual void setDisplayString(const QString &displayString) override; - virtual int getAssociatedChannelID() const; + virtual int getAssociatedChannelID() const; }; #endif // MUMBLE_MUMBLE_TALKINGUIENTRY_H_ diff --git a/src/mumble/TalkingUISelection.cpp b/src/mumble/TalkingUISelection.cpp index d2df01870..0378e0660 100644 --- a/src/mumble/TalkingUISelection.cpp +++ b/src/mumble/TalkingUISelection.cpp @@ -7,10 +7,11 @@ #include "MainWindow.h" #include "UserModel.h" -#include <QWidget> #include <QVariant> +#include <QWidget> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" TalkingUISelection::TalkingUISelection(QWidget *widget) : m_widget(widget) { @@ -51,8 +52,7 @@ bool TalkingUISelection::operator!=(const QWidget *widget) const { UserSelection::UserSelection(QWidget *widget, unsigned int userSession) - : TalkingUISelection(widget), - m_userSession(userSession) { + : TalkingUISelection(widget), m_userSession(userSession) { } void UserSelection::syncToMainWindow() const { @@ -61,15 +61,14 @@ void UserSelection::syncToMainWindow() const { } } -std::unique_ptr<TalkingUISelection> UserSelection::cloneToHeap() const { - return std::make_unique<UserSelection>(*this); +std::unique_ptr< TalkingUISelection > UserSelection::cloneToHeap() const { + return std::make_unique< UserSelection >(*this); } ChannelSelection::ChannelSelection(QWidget *widget, int channelID) - : TalkingUISelection(widget), - m_channelID(channelID) { + : TalkingUISelection(widget), m_channelID(channelID) { } void ChannelSelection::syncToMainWindow() const { @@ -78,16 +77,14 @@ void ChannelSelection::syncToMainWindow() const { } } -std::unique_ptr<TalkingUISelection> ChannelSelection::cloneToHeap() const { - return std::make_unique<ChannelSelection>(*this); +std::unique_ptr< TalkingUISelection > ChannelSelection::cloneToHeap() const { + return std::make_unique< ChannelSelection >(*this); } ListenerSelection::ListenerSelection(QWidget *widget, unsigned int userSession, int channelID) - : TalkingUISelection(widget), - m_userSession(userSession), - m_channelID(channelID) { + : TalkingUISelection(widget), m_userSession(userSession), m_channelID(channelID) { } void ListenerSelection::syncToMainWindow() const { @@ -96,8 +93,8 @@ void ListenerSelection::syncToMainWindow() const { } } -std::unique_ptr<TalkingUISelection> ListenerSelection::cloneToHeap() const { - return std::make_unique<ListenerSelection>(*this); +std::unique_ptr< TalkingUISelection > ListenerSelection::cloneToHeap() const { + return std::make_unique< ListenerSelection >(*this); } @@ -106,6 +103,6 @@ void EmptySelection::syncToMainWindow() const { // Do nothing } -std::unique_ptr<TalkingUISelection> EmptySelection::cloneToHeap() const { - return std::make_unique<EmptySelection>(*this); +std::unique_ptr< TalkingUISelection > EmptySelection::cloneToHeap() const { + return std::make_unique< EmptySelection >(*this); } diff --git a/src/mumble/TalkingUISelection.h b/src/mumble/TalkingUISelection.h index 721c2c0d5..17b00be58 100644 --- a/src/mumble/TalkingUISelection.h +++ b/src/mumble/TalkingUISelection.h @@ -12,92 +12,92 @@ class QWidget; /// Base class of all selections within the TalkingUI class TalkingUISelection { - protected: - /// The widget that is used to represent this selection (it'll be marked - /// as selected). - QWidget *m_widget; +protected: + /// The widget that is used to represent this selection (it'll be marked + /// as selected). + QWidget *m_widget; - explicit TalkingUISelection() = default; - - public: - explicit TalkingUISelection(QWidget *widget); - virtual ~TalkingUISelection() = default; + explicit TalkingUISelection() = default; - /// Turns this selection on or off. Turning it on usually involves marking the - /// associated Widget in a certain way while deactivating the selection reverts this effect. - /// - /// @param active Whether to activate this selection - virtual void setActive(bool active); +public: + explicit TalkingUISelection(QWidget *widget); + virtual ~TalkingUISelection() = default; - /// Applies this selection. This is a shortcut for setActive(true). - virtual void apply() final; + /// Turns this selection on or off. Turning it on usually involves marking the + /// associated Widget in a certain way while deactivating the selection reverts this effect. + /// + /// @param active Whether to activate this selection + virtual void setActive(bool active); - /// Discards this selection. This is a shortcut for setActive(false). - virtual void discard() final; + /// Applies this selection. This is a shortcut for setActive(true). + virtual void apply() final; - /// Synchronizes this selection to the MainWindow - virtual void syncToMainWindow() const = 0; + /// Discards this selection. This is a shortcut for setActive(false). + virtual void discard() final; - bool operator==(const TalkingUISelection &other) const; - bool operator!=(const TalkingUISelection &other) const; + /// Synchronizes this selection to the MainWindow + virtual void syncToMainWindow() const = 0; - bool operator==(const QWidget *widget) const; - bool operator!=(const QWidget *widget) const; + bool operator==(const TalkingUISelection &other) const; + bool operator!=(const TalkingUISelection &other) const; - virtual std::unique_ptr<TalkingUISelection> cloneToHeap() const = 0; + bool operator==(const QWidget *widget) const; + bool operator!=(const QWidget *widget) const; + + virtual std::unique_ptr< TalkingUISelection > cloneToHeap() const = 0; }; /// A class representing the selection of a user in the TalkingUI class UserSelection : public TalkingUISelection { - protected: - const unsigned int m_userSession; +protected: + const unsigned int m_userSession; - public: - explicit UserSelection(QWidget *widget, unsigned int userSession); - explicit UserSelection(const UserSelection &) = default; +public: + explicit UserSelection(QWidget *widget, unsigned int userSession); + explicit UserSelection(const UserSelection &) = default; - virtual void syncToMainWindow() const override; + virtual void syncToMainWindow() const override; - virtual std::unique_ptr<TalkingUISelection> cloneToHeap() const override; + virtual std::unique_ptr< TalkingUISelection > cloneToHeap() const override; }; /// A class representing the selection of a channel in the TalkingUI class ChannelSelection : public TalkingUISelection { - protected: - const int m_channelID; +protected: + const int m_channelID; - public: - explicit ChannelSelection(QWidget *widget, int channelID); - explicit ChannelSelection(const ChannelSelection &) = default; +public: + explicit ChannelSelection(QWidget *widget, int channelID); + explicit ChannelSelection(const ChannelSelection &) = default; - virtual void syncToMainWindow() const override; + virtual void syncToMainWindow() const override; - virtual std::unique_ptr<TalkingUISelection> cloneToHeap() const override; + virtual std::unique_ptr< TalkingUISelection > cloneToHeap() const override; }; class ListenerSelection : public TalkingUISelection { - protected: - unsigned int m_userSession; - const int m_channelID; +protected: + unsigned int m_userSession; + const int m_channelID; - public: - explicit ListenerSelection(QWidget *widget, unsigned int userSession, int channelID); - explicit ListenerSelection(const ListenerSelection &) = default; +public: + explicit ListenerSelection(QWidget *widget, unsigned int userSession, int channelID); + explicit ListenerSelection(const ListenerSelection &) = default; - virtual void syncToMainWindow() const override; + virtual void syncToMainWindow() const override; - virtual std::unique_ptr<TalkingUISelection> cloneToHeap() const override; + virtual std::unique_ptr< TalkingUISelection > cloneToHeap() const override; }; /// A class representing an empty selection in the TalkingUI class EmptySelection : public TalkingUISelection { - public: - explicit EmptySelection() = default; - explicit EmptySelection(const EmptySelection &) = default; +public: + explicit EmptySelection() = default; + explicit EmptySelection(const EmptySelection &) = default; - virtual void syncToMainWindow() const override; + virtual void syncToMainWindow() const override; - virtual std::unique_ptr<TalkingUISelection> cloneToHeap() const override; + virtual std::unique_ptr< TalkingUISelection > cloneToHeap() const override; }; #endif // MUMBLE_MUMBLE_TALKINGUISELECTION_H_ diff --git a/src/mumble/TaskList.cpp b/src/mumble/TaskList.cpp index 9fb047d0d..ab0a80b02 100644 --- a/src/mumble/TaskList.cpp +++ b/src/mumble/TaskList.cpp @@ -27,15 +27,16 @@ extern bool bIsWin7; void TaskList::addToRecentList(QString name, QString user, QString host, int port) { - if (! bIsWin7) + if (!bIsWin7) return; HRESULT hr; - IShellLink *link = nullptr; + IShellLink *link = nullptr; IPropertyStore *ps = nullptr; PROPVARIANT pt; - hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IShellLink), reinterpret_cast<void **>(&link)); + hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IShellLink), + reinterpret_cast< void ** >(&link)); if (!link || FAILED(hr)) return; @@ -53,13 +54,13 @@ void TaskList::addToRecentList(QString name, QString user, QString host, int por QSettings settings(QLatin1String("HKEY_CLASSES_ROOT"), QSettings::NativeFormat); QString app = settings.value(QLatin1String("mumble/DefaultIcon/.")).toString(); - if (app.isEmpty() || ! QFileInfo(app).exists()) + if (app.isEmpty() || !QFileInfo(app).exists()) app = QCoreApplication::applicationFilePath(); link->SetPath(app.toStdWString().c_str()); link->SetArguments(QString::fromLatin1(url.toEncoded()).toStdWString().c_str()); - hr = link->QueryInterface(__uuidof(IPropertyStore), reinterpret_cast<void **>(&ps)); + hr = link->QueryInterface(__uuidof(IPropertyStore), reinterpret_cast< void ** >(&ps)); if (FAILED(hr)) { qFatal("TaskList: Failed to get property store"); goto cleanup; diff --git a/src/mumble/TaskList.h b/src/mumble/TaskList.h index d82320c19..6d45736ee 100644 --- a/src/mumble/TaskList.h +++ b/src/mumble/TaskList.h @@ -9,8 +9,8 @@ class QString; class TaskList { - public: - static void addToRecentList(QString name, QString user, QString host, int port); +public: + static void addToRecentList(QString name, QString user, QString host, int port); }; -#endif // TASK_LIST_H_ +#endif // TASK_LIST_H_ diff --git a/src/mumble/TextMessage.h b/src/mumble/TextMessage.h index f9a7bdaf2..2dadec1dd 100644 --- a/src/mumble/TextMessage.h +++ b/src/mumble/TextMessage.h @@ -9,17 +9,18 @@ #include "ui_TextMessage.h" class TextMessage : public QDialog, public Ui::TextMessage { - private: - Q_OBJECT - Q_DISABLE_COPY(TextMessage) - protected: - QString qsRep; - public slots: - void on_qcbTreeMessage_stateChanged(int); - public: - TextMessage(QWidget *parent = nullptr, QString title = tr("Enter text"), bool bChannel = false); - QString message(); - bool bTreeMessage; +private: + Q_OBJECT + Q_DISABLE_COPY(TextMessage) +protected: + QString qsRep; +public slots: + void on_qcbTreeMessage_stateChanged(int); + +public: + TextMessage(QWidget *parent = nullptr, QString title = tr("Enter text"), bool bChannel = false); + QString message(); + bool bTreeMessage; }; #endif diff --git a/src/mumble/TextToSpeech.cpp b/src/mumble/TextToSpeech.cpp index 934c87f56..9d4796878 100644 --- a/src/mumble/TextToSpeech.cpp +++ b/src/mumble/TextToSpeech.cpp @@ -8,13 +8,13 @@ #include <QTextToSpeech> class TextToSpeechPrivate { - public: - QTextToSpeech *m_tts; - QVector<QVoice> m_voices; - TextToSpeechPrivate(); - ~TextToSpeechPrivate(); - void say(const QString &text); - void setVolume(int v); +public: + QTextToSpeech *m_tts; + QVector< QVoice > m_voices; + TextToSpeechPrivate(); + ~TextToSpeechPrivate(); + void say(const QString &text); + void setVolume(int v); }; TextToSpeechPrivate::TextToSpeechPrivate() { @@ -35,7 +35,7 @@ void TextToSpeechPrivate::setVolume(int volume) { TextToSpeech::TextToSpeech(QObject *p) : QObject(p) { enabled = true; - d = new TextToSpeechPrivate(); + d = new TextToSpeechPrivate(); } TextToSpeech::~TextToSpeech() { diff --git a/src/mumble/TextToSpeech.h b/src/mumble/TextToSpeech.h index bebb42d33..08d483140 100644 --- a/src/mumble/TextToSpeech.h +++ b/src/mumble/TextToSpeech.h @@ -11,23 +11,26 @@ class TextToSpeechPrivate; class TextToSpeech : public QObject { - friend class TextToSpeechPrivate; - private: - Q_OBJECT - Q_DISABLE_COPY(TextToSpeech) - Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) - protected: - bool enabled; - public: - TextToSpeech(QObject *parent = nullptr); - ~TextToSpeech() Q_DECL_OVERRIDE; - bool isEnabled() const; - public slots: - void say(const QString &text); - void setEnabled(bool ena); - void setVolume(int volume); - private: - TextToSpeechPrivate *d; + friend class TextToSpeechPrivate; + +private: + Q_OBJECT + Q_DISABLE_COPY(TextToSpeech) + Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) +protected: + bool enabled; + +public: + TextToSpeech(QObject *parent = nullptr); + ~TextToSpeech() Q_DECL_OVERRIDE; + bool isEnabled() const; +public slots: + void say(const QString &text); + void setEnabled(bool ena); + void setVolume(int volume); + +private: + TextToSpeechPrivate *d; }; #endif diff --git a/src/mumble/TextToSpeech_unix.cpp b/src/mumble/TextToSpeech_unix.cpp index 575e87efd..230339628 100644 --- a/src/mumble/TextToSpeech_unix.cpp +++ b/src/mumble/TextToSpeech_unix.cpp @@ -6,40 +6,41 @@ #include "TextToSpeech.h" #ifdef USE_SPEECHD -# ifdef USE_SPEECHD_PKGCONFIG -# include <speech-dispatcher/libspeechd.h> -# else -# include <libspeechd.h> -# endif +# ifdef USE_SPEECHD_PKGCONFIG +# include <speech-dispatcher/libspeechd.h> +# else +# include <libspeechd.h> +# endif #endif #include <QtCore/QLocale> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" class TextToSpeechPrivate { #ifdef USE_SPEECHD - protected: - SPDConnection *spd; - /// Used to store the requested volume of the TextToSpeech object - /// before speech-dispatcher has been initialized. - int volume; - bool initialized; - void ensureInitialized(); +protected: + SPDConnection *spd; + /// Used to store the requested volume of the TextToSpeech object + /// before speech-dispatcher has been initialized. + int volume; + bool initialized; + void ensureInitialized(); #endif - public: - TextToSpeechPrivate(); - ~TextToSpeechPrivate(); - void say(const QString &text); - void setVolume(int v); +public: + TextToSpeechPrivate(); + ~TextToSpeechPrivate(); + void say(const QString &text); + void setVolume(int v); }; #ifdef USE_SPEECHD TextToSpeechPrivate::TextToSpeechPrivate() { initialized = false; - volume = -1; - spd = nullptr; + volume = -1; + spd = nullptr; } TextToSpeechPrivate::~TextToSpeechPrivate() { @@ -55,7 +56,7 @@ void TextToSpeechPrivate::ensureInitialized() { } spd = spd_open("Mumble", nullptr, nullptr, SPD_MODE_THREADED); - if (! spd) { + if (!spd) { qWarning("TextToSpeech: Failed to contact speech dispatcher."); } else { QString lang; @@ -121,7 +122,7 @@ void TextToSpeechPrivate::setVolume(int) { TextToSpeech::TextToSpeech(QObject *p) : QObject(p) { enabled = true; - d = new TextToSpeechPrivate(); + d = new TextToSpeechPrivate(); } TextToSpeech::~TextToSpeech() { diff --git a/src/mumble/TextToSpeech_win.cpp b/src/mumble/TextToSpeech_win.cpp index 56706de44..e3befeb2b 100644 --- a/src/mumble/TextToSpeech_win.cpp +++ b/src/mumble/TextToSpeech_win.cpp @@ -12,21 +12,21 @@ // clang-format on #undef FAILED -#define FAILED(Status) (static_cast<HRESULT>(Status)<0) +#define FAILED(Status) (static_cast< HRESULT >(Status) < 0) class TextToSpeechPrivate { - public: - ISpVoice * pVoice; - TextToSpeechPrivate(); - ~TextToSpeechPrivate(); - void say(const QString &text); - void setVolume(int v); +public: + ISpVoice *pVoice; + TextToSpeechPrivate(); + ~TextToSpeechPrivate(); + void say(const QString &text); + void setVolume(int v); }; TextToSpeechPrivate::TextToSpeechPrivate() { pVoice = nullptr; - HRESULT hr = CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice); + HRESULT hr = CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **) &pVoice); if (FAILED(hr)) qWarning("TextToSpeechPrivate: Failed to allocate TTS Voice"); } @@ -49,7 +49,7 @@ void TextToSpeechPrivate::setVolume(int volume) { TextToSpeech::TextToSpeech(QObject *p) : QObject(p) { enabled = true; - d = new TextToSpeechPrivate(); + d = new TextToSpeechPrivate(); } TextToSpeech::~TextToSpeech() { diff --git a/src/mumble/ThemeInfo.cpp b/src/mumble/ThemeInfo.cpp index a281ed55d..1799c2273 100644 --- a/src/mumble/ThemeInfo.cpp +++ b/src/mumble/ThemeInfo.cpp @@ -21,143 +21,145 @@ QFileInfo ThemeInfo::StyleInfo::getPlatformQss() const { #endif } -boost::optional<ThemeInfo::StyleInfo> readStyleFromConfig(QSettings &themeConfig, const QString &styleId, const ThemeInfo &theme, const QDir &themeDir) { +boost::optional< ThemeInfo::StyleInfo > readStyleFromConfig(QSettings &themeConfig, const QString &styleId, + const ThemeInfo &theme, const QDir &themeDir) { QRegExp qssPlatformRegex(QString::fromLatin1("^%1/qss_(.*)").arg(styleId)); - + ThemeInfo::StyleInfo style; - - style.name = themeConfig.value(QString::fromLatin1("%1/name").arg(styleId)).toString(); + + style.name = themeConfig.value(QString::fromLatin1("%1/name").arg(styleId)).toString(); style.themeName = theme.name; - style.defaultQss = QFileInfo(themeDir.filePath(themeConfig.value(QString::fromLatin1("%1/qss").arg(styleId)).toString())); - + style.defaultQss = + QFileInfo(themeDir.filePath(themeConfig.value(QString::fromLatin1("%1/qss").arg(styleId)).toString())); + if (style.name.isNull()) { qWarning() << "Style " << styleId << " of theme" << theme.name << " has no name, skipping theme"; return boost::none; } - + if (!style.defaultQss.exists() || !style.defaultQss.isFile()) { - qWarning() << "Style " << style.name << " of theme " << theme.name << " references invalid qss " << style.defaultQss.filePath() << ", skipping theme"; + qWarning() << "Style " << style.name << " of theme " << theme.name << " references invalid qss " + << style.defaultQss.filePath() << ", skipping theme"; return boost::none; } - + foreach (const QString &platformQssConfig, themeConfig.allKeys().filter(qssPlatformRegex)) { qssPlatformRegex.indexIn(platformQssConfig); const QString platform = qssPlatformRegex.cap(1); - + QFileInfo platformQss = (themeDir.filePath(themeConfig.value(platformQssConfig).toString())); if (!platformQss.exists() || !platformQss.isFile()) { - qWarning() << "Style" << style.name << " of theme " << theme.name << " references invalid qss " << platformQss.filePath() << " for platform " << platform << ", skipping theme"; + qWarning() << "Style" << style.name << " of theme " << theme.name << " references invalid qss " + << platformQss.filePath() << " for platform " << platform << ", skipping theme"; return boost::none; } - + style.qssFiles.insert(platform, platformQss); } - + return style; } -boost::optional<ThemeInfo> loadLegacyThemeInfo(const QDir &themeDirectory) { +boost::optional< ThemeInfo > loadLegacyThemeInfo(const QDir &themeDirectory) { ThemeInfo theme; theme.name = themeDirectory.dirName(); - + QStringList filters; filters << QLatin1String("*.qss"); - + foreach (const QFileInfo &qssFile, themeDirectory.entryInfoList(filters, QDir::Files)) { ThemeInfo::StyleInfo style; - style.name = qssFile.baseName(); - style.themeName = theme.name; + style.name = qssFile.baseName(); + style.themeName = theme.name; style.defaultQss = qssFile; - + theme.styles.insert(style.name, style); } - + if (theme.styles.isEmpty()) { qWarning() << themeDirectory.absolutePath() << " does not seem to contain a old-style theme, skipping"; return boost::none; } - + theme.defaultStyle = theme.styles.begin()->name; return theme; } -boost::optional<ThemeInfo> ThemeInfo::load(const QDir &themeDirectory) { +boost::optional< ThemeInfo > ThemeInfo::load(const QDir &themeDirectory) { QFile themeFile(themeDirectory.absoluteFilePath(QLatin1String("theme.ini"))); if (!themeFile.exists()) { qWarning() << "Directory " << themeDirectory.absolutePath() << " has no theme.ini, trying fallback"; - + return loadLegacyThemeInfo(themeDirectory); } - + QSettings themeConfig(themeFile.fileName(), QSettings::IniFormat); if (themeConfig.status() != QSettings::NoError) { qWarning() << "Failed to load theme config from " << themeFile.fileName() << ", skipping"; return boost::none; } - + ThemeInfo theme; QStringList styleIds; - + theme.name = themeConfig.value(QLatin1String("theme/name")).toString(); - styleIds = themeConfig.value(QLatin1String("theme/styles")).toStringList(); - + styleIds = themeConfig.value(QLatin1String("theme/styles")).toStringList(); + if (theme.name.isNull()) { qWarning() << "Theme in " << themeFile.fileName() << " does not have a name, skipping"; return boost::none; } - + if (styleIds.isEmpty()) { qWarning() << "Theme " << theme.name << " doesn't have any styles, skipping"; return boost::none; } - + foreach (const QString &styleId, styleIds) { - boost::optional<ThemeInfo::StyleInfo> style = readStyleFromConfig(themeConfig, styleId, theme, themeDirectory); + boost::optional< ThemeInfo::StyleInfo > style = + readStyleFromConfig(themeConfig, styleId, theme, themeDirectory); if (!style) { return boost::none; } theme.styles.insert(style->name, *style); - } - + theme.defaultStyle = theme.styles.begin()->name; - + return theme; } ThemeInfo::StyleInfo ThemeInfo::getStyle(QString name_) const { Q_ASSERT(styles.contains(defaultStyle)); - + return styles.value(name_, styles.value(defaultStyle)); } ThemeMap ThemeInfo::scanDirectory(const QDir &themesDirectory) { ThemeMap themes; - + foreach (const QFileInfo &subdirInfo, themesDirectory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot)) { QDir subdir(subdirInfo.absoluteFilePath()); - - boost::optional<ThemeInfo> theme = ThemeInfo::load(subdir); + + boost::optional< ThemeInfo > theme = ThemeInfo::load(subdir); if (!theme) { continue; } - + themes.insert(theme->name, *theme); }; - + return themes; } -ThemeMap ThemeInfo::scanDirectories(const QVector<QDir> &themesDirectories) { +ThemeMap ThemeInfo::scanDirectories(const QVector< QDir > &themesDirectories) { ThemeMap themes; - + foreach (const QDir &themesDirectory, themesDirectories) { - foreach (const ThemeInfo &theme, scanDirectory(themesDirectory)) { - themes.insert(theme.name, theme); - } + foreach (const ThemeInfo &theme, scanDirectory(themesDirectory)) { themes.insert(theme.name, theme); } } - + return themes; } diff --git a/src/mumble/ThemeInfo.h b/src/mumble/ThemeInfo.h index ad93a6b9c..3277f84b9 100644 --- a/src/mumble/ThemeInfo.h +++ b/src/mumble/ThemeInfo.h @@ -6,19 +6,19 @@ #ifndef MUMBLE_MUMBLE_THEMEINFO_H_ #define MUMBLE_MUMBLE_THEMEINFO_H_ -#include <QtCore/QString> +#include <QMetaType> #include <QtCore/QFileInfo> #include <QtCore/QMap> -#include <QMetaType> +#include <QtCore/QString> #ifndef Q_MOC_RUN -#include <boost/optional.hpp> +# include <boost/optional.hpp> #endif class QSettings; class QDir; class ThemeInfo; -typedef QMap<QString, ThemeInfo> ThemeMap; +typedef QMap< QString, ThemeInfo > ThemeMap; /// Description of a Mumble theme with multiple styles class ThemeInfo { @@ -27,7 +27,7 @@ public: /// /// Multiple styles can for example be used to differentiate light/dark /// variants of a theme. - /// + /// /// A single style can refer to multiple run-time platform specific qss /// theme files. class StyleInfo { @@ -36,45 +36,45 @@ public: QString themeName; /// Name for the style QString name; - + /// @return Returns platform specific qss or defaultQss if none available QFileInfo getPlatformQss() const; - + /// Default QSS file for the style QFileInfo defaultQss; /// Platform specific QSS files available - QMap<QString, QFileInfo> qssFiles; + QMap< QString, QFileInfo > qssFiles; }; - typedef QMap<QString, StyleInfo> StylesMap; + typedef QMap< QString, StyleInfo > StylesMap; /// Takes stock of all mumble themes in the given folders. - /// + /// /// If a theme with the same name is available in multiple directories /// only the last occurance will be returned. - /// + /// /// @param themesDirectories List of directories to search for theme directories. /// @return Map of theme name to Theme - static ThemeMap scanDirectories(const QVector<QDir> &themesDirectories); - + static ThemeMap scanDirectories(const QVector< QDir > &themesDirectories); + /// Takes stock of all mumble themes in the given folder - /// + /// /// Uses loadThemeInfoFromDirectory on each directory in the folder /// to find themes. Themes with the same names will override each other. - /// + /// /// @param themesDirectory Directory to scan for theme directories /// @return Map of theme name to Theme static ThemeMap scanDirectory(const QDir &themesDirectory); - + /// Loads the theme description from a given directory - /// - /// @param themeDirectory + /// + /// @param themeDirectory /// @return Theme if description was correctly loaded. boost::none if not. - static boost::optional<ThemeInfo> load(const QDir &themeDirectory); - + static boost::optional< ThemeInfo > load(const QDir &themeDirectory); + /// @return Style with given name or default StyleInfo getStyle(QString name_) const; - + /// Ideally unique theme name. A theme with identical name can override. QString name; /// Style name to style mapping. diff --git a/src/mumble/Themes.cpp b/src/mumble/Themes.cpp index f20e23ab3..eb6389844 100644 --- a/src/mumble/Themes.cpp +++ b/src/mumble/Themes.cpp @@ -7,73 +7,74 @@ #include "MainWindow.h" #include "MumbleApplication.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -boost::optional<ThemeInfo::StyleInfo> Themes::getConfiguredStyle(const Settings &settings) { +boost::optional< ThemeInfo::StyleInfo > Themes::getConfiguredStyle(const Settings &settings) { if (settings.themeName.isEmpty() && settings.themeStyleName.isEmpty()) { - return boost::none; + return boost::none; } - const ThemeMap themes = getThemes(); + const ThemeMap themes = getThemes(); ThemeMap::const_iterator themeIt = themes.find(settings.themeName); if (themeIt == themes.end()) { qWarning() << "Could not find configured theme" << settings.themeName; return boost::none; } - + ThemeInfo::StylesMap::const_iterator styleIt = themeIt->styles.find(settings.themeStyleName); if (styleIt == themeIt->styles.end()) { - qWarning() << "Configured theme" << settings.themeName << "does not have configured style" << settings.themeStyleName; + qWarning() << "Configured theme" << settings.themeName << "does not have configured style" + << settings.themeStyleName; return boost::none; } - + return *styleIt; } -void Themes::setConfiguredStyle(Settings &settings, boost::optional<ThemeInfo::StyleInfo> style, bool &outChanged) { +void Themes::setConfiguredStyle(Settings &settings, boost::optional< ThemeInfo::StyleInfo > style, bool &outChanged) { if (style) { if (settings.themeName != style->themeName || settings.themeStyleName != style->name) { - settings.themeName = style->themeName; + settings.themeName = style->themeName; settings.themeStyleName = style->name; - outChanged = true; + outChanged = true; } } else { if (!settings.themeName.isEmpty() || !settings.themeStyleName.isEmpty()) { settings.themeName = settings.themeStyleName = QString(); - outChanged = true; + outChanged = true; } } } void Themes::applyFallback() { qWarning() << "Applying fallback style sheet"; - + QStringList skinPaths; skinPaths << QLatin1String(":/themes/Mumble"); QString defaultTheme = getDefaultStylesheet(); setTheme(defaultTheme, skinPaths); - } bool Themes::applyConfigured() { - boost::optional<ThemeInfo::StyleInfo> style = Themes::getConfiguredStyle(g.s); + boost::optional< ThemeInfo::StyleInfo > style = Themes::getConfiguredStyle(g.s); if (!style) { return false; } - + const QFileInfo qssFile(style->getPlatformQss()); - + qWarning() << "Theme:" << style->themeName; qWarning() << "Style:" << style->name; qWarning() << "--> qss:" << qssFile.absoluteFilePath(); - + QFile file(qssFile.absoluteFilePath()); if (!file.open(QFile::ReadOnly)) { qWarning() << "Failed to open theme stylesheet:" << file.errorString(); return false; } - + QStringList skinPaths; skinPaths << qssFile.path(); skinPaths << QLatin1String(":/themes/Mumble"); // Some skins might want to fall-back on our built-in resources @@ -85,19 +86,14 @@ bool Themes::applyConfigured() { void Themes::setTheme(QString &themeQss, QStringList &skinPaths) { QDir::setSearchPaths(QLatin1String("skin"), skinPaths); - + QString userStylesheetFn = userStylesheetPath(); QString userStylesheetContent; if (readStylesheet(userStylesheetFn, userStylesheetContent)) { qWarning("Themes: allowing user stylesheet at '%s' to override the stylesheet", qPrintable(userStylesheetFn)); } - - qApp->setStyleSheet( - themeQss + - QLatin1String("\n") + - userStylesheetContent - ); + qApp->setStyleSheet(themeQss + QLatin1String("\n") + userStylesheetContent); } bool Themes::apply() { @@ -105,7 +101,7 @@ bool Themes::apply() { if (!result) { applyFallback(); } - + if (g.mw) { g.mw->qteLog->document()->setDefaultStyleSheet(qApp->styleSheet()); } @@ -120,16 +116,17 @@ QDir Themes::getUserThemesDirectory() { return QDir(g.qdBasePath.absolutePath() + QLatin1String("/Themes")); } -QVector<QDir> Themes::getSearchDirectories() { - QVector<QDir> themeSearchDirectories; +QVector< QDir > Themes::getSearchDirectories() { + QVector< QDir > themeSearchDirectories; // Built-in themes contained in the binary have the lowest priority themeSearchDirectories << QDir(QLatin1String(":themes")); // Next come themes found in the applications Themes directory - themeSearchDirectories << QDir(MumbleApplication::instance()->applicationVersionRootPath() + QLatin1String("/Themes")); + themeSearchDirectories << QDir(MumbleApplication::instance()->applicationVersionRootPath() + + QLatin1String("/Themes")); // Highest priorty have themes located in the user directory themeSearchDirectories << getUserThemesDirectory(); - + return themeSearchDirectories; } @@ -149,5 +146,6 @@ bool Themes::readStylesheet(const QString &stylesheetFn, QString &stylesheetCont } QString Themes::getDefaultStylesheet() { - return QLatin1String(".log-channel{text-decoration:none;}.log-user{text-decoration:none;}p{margin:0;}#qwMacWarning,#qwInlineNotice{background-color:#FFFEDC;border-radius:5px;border:1px solid #B5B59E;}"); + return QLatin1String(".log-channel{text-decoration:none;}.log-user{text-decoration:none;}p{margin:0;}#qwMacWarning," + "#qwInlineNotice{background-color:#FFFEDC;border-radius:5px;border:1px solid #B5B59E;}"); } diff --git a/src/mumble/Themes.h b/src/mumble/Themes.h index f284ff824..f14cb6d63 100644 --- a/src/mumble/Themes.h +++ b/src/mumble/Themes.h @@ -6,51 +6,51 @@ #ifndef MUMBLE_MUMBLE_THEMES_H_ #define MUMBLE_MUMBLE_THEMES_H_ -#include <ThemeInfo.h> #include <Settings.h> +#include <ThemeInfo.h> #ifndef Q_MOC_RUN -#include <boost/optional.hpp> +# include <boost/optional.hpp> #endif class Themes { public: /// Returns the style configured in the given settings structure - static boost::optional<ThemeInfo::StyleInfo> getConfiguredStyle(const Settings& settings); - + static boost::optional< ThemeInfo::StyleInfo > getConfiguredStyle(const Settings &settings); + /// Updates the given settings object to be configured to the given style - /// + /// /// @note Does not apply the theme @see apply - /// + /// /// @param settings Settings object to update /// @param style Style to set /// @param outChanged Will be set to true if the style in settings actually changed. Will not be changed otherwise. - static void setConfiguredStyle(Settings& settings, boost::optional<ThemeInfo::StyleInfo> style, bool& outChanged); - + static void setConfiguredStyle(Settings &settings, boost::optional< ThemeInfo::StyleInfo > style, bool &outChanged); + /// Applies the theme - /// + /// /// @note Can only apply a theme before MainWindow etc. is opened static bool apply(); - + /// Return a theme name to theme map static ThemeMap getThemes(); /// Returns the per user themes directory static QDir getUserThemesDirectory(); - + private: /// Applies the fallback stylesheet static void applyFallback(); - + /// Tries to apply the configured theme. /// @return True on success. False on failure. static bool applyConfigured(); - + // Sets the theme to a QSS theme static void setTheme(QString &themeQss, QStringList &skinPaths); /// Returns list of theme search directories ordered ascending by priorty (lowest first) - static QVector<QDir> getSearchDirectories(); - + static QVector< QDir > getSearchDirectories(); + /// Returns default style-sheet used for fall-backs static QString getDefaultStylesheet(); diff --git a/src/mumble/Tokens.cpp b/src/mumble/Tokens.cpp index 469ca6ed4..81e7a946f 100644 --- a/src/mumble/Tokens.cpp +++ b/src/mumble/Tokens.cpp @@ -8,17 +8,18 @@ #include "Database.h" #include "ServerHandler.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" Tokens::Tokens(QWidget *p) : QDialog(p) { setupUi(this); qlwTokens->setAccessibleName(tr("Tokens")); - qbaDigest = g.sh->qbaDigest; + qbaDigest = g.sh->qbaDigest; QStringList tokens = g.db->getTokens(qbaDigest); tokens.sort(); - foreach(const QString &qs, tokens) { + foreach (const QString &qs, tokens) { QListWidgetItem *qlwi = new QListWidgetItem(qs); qlwi->setFlags(qlwi->flags() | Qt::ItemIsEditable); qlwTokens->addItem(qlwi); @@ -28,10 +29,10 @@ Tokens::Tokens(QWidget *p) : QDialog(p) { void Tokens::accept() { QStringList qsl; - QList<QListWidgetItem *> items = qlwTokens->findItems(QString(), Qt::MatchStartsWith); - foreach(QListWidgetItem *qlwi, items) { + QList< QListWidgetItem * > items = qlwTokens->findItems(QString(), Qt::MatchStartsWith); + foreach (QListWidgetItem *qlwi, items) { const QString &text = qlwi->text().trimmed(); - if (! text.isEmpty()) + if (!text.isEmpty()) qsl << text; } g.db->setTokens(qbaDigest, qsl); @@ -48,7 +49,6 @@ void Tokens::on_qpbAdd_clicked() { } void Tokens::on_qpbRemove_clicked() { - foreach(QListWidgetItem *qlwi, qlwTokens->selectedItems()) + foreach (QListWidgetItem *qlwi, qlwTokens->selectedItems()) delete qlwi; } - diff --git a/src/mumble/Tokens.h b/src/mumble/Tokens.h index 72d48b61e..b130d8a89 100644 --- a/src/mumble/Tokens.h +++ b/src/mumble/Tokens.h @@ -9,18 +9,19 @@ #include "ui_Tokens.h" class Tokens : public QDialog, public Ui::Tokens { - private: - Q_OBJECT - Q_DISABLE_COPY(Tokens) - protected: - QByteArray qbaDigest; - public: - Tokens(QWidget *p = nullptr); - public slots: - void accept() Q_DECL_OVERRIDE; - public slots: - void on_qpbAdd_clicked(); - void on_qpbRemove_clicked(); +private: + Q_OBJECT + Q_DISABLE_COPY(Tokens) +protected: + QByteArray qbaDigest; + +public: + Tokens(QWidget *p = nullptr); +public slots: + void accept() Q_DECL_OVERRIDE; +public slots: + void on_qpbAdd_clicked(); + void on_qpbRemove_clicked(); }; #endif diff --git a/src/mumble/Usage.cpp b/src/mumble/Usage.cpp index ae433616f..4d0e5a092 100644 --- a/src/mumble/Usage.cpp +++ b/src/mumble/Usage.cpp @@ -7,10 +7,10 @@ #include "ClientUser.h" #include "LCD.h" -#include "Global.h" #include "NetworkConfig.h" #include "OSInfo.h" #include "Version.h" +#include "Global.h" #include <QtCore/QTimer> #include <QtNetwork/QHostAddress> @@ -22,18 +22,19 @@ Usage::Usage(QObject *p) : QObject(p) { qbReport.open(QBuffer::ReadWrite); qdsReport.setDevice(&qbReport); qdsReport.setVersion(QDataStream::Qt_4_4); - qdsReport << static_cast<unsigned int>(2); + qdsReport << static_cast< unsigned int >(2); // Wait 10 minutes (so we know they're actually using this), then... QTimer::singleShot(60 * 10 * 1000, this, SLOT(registerUsage())); } void Usage::registerUsage() { - if (! g.s.bUsage || g.s.uiUpdateCounter == 0) // Only register usage if allowed by the user and first wizard run has finished + if (!g.s.bUsage + || g.s.uiUpdateCounter == 0) // Only register usage if allowed by the user and first wizard run has finished return; QDomDocument doc; - QDomElement root=doc.createElement(QLatin1String("usage")); + QDomElement root = doc.createElement(QLatin1String("usage")); doc.appendChild(root); QDomElement tag; @@ -41,19 +42,19 @@ void Usage::registerUsage() { OSInfo::fillXml(doc, root); - tag=doc.createElement(QLatin1String("in")); + tag = doc.createElement(QLatin1String("in")); root.appendChild(tag); - t=doc.createTextNode(g.s.qsAudioInput); + t = doc.createTextNode(g.s.qsAudioInput); tag.appendChild(t); - tag=doc.createElement(QLatin1String("out")); + tag = doc.createElement(QLatin1String("out")); root.appendChild(tag); - t=doc.createTextNode(g.s.qsAudioOutput); + t = doc.createTextNode(g.s.qsAudioOutput); tag.appendChild(t); - tag=doc.createElement(QLatin1String("lcd")); + tag = doc.createElement(QLatin1String("lcd")); root.appendChild(tag); - t=doc.createTextNode(QString::number(g.lcd->hasDevices() ? 1 : 0)); + t = doc.createTextNode(QString::number(g.lcd->hasDevices() ? 1 : 0)); tag.appendChild(t); QBuffer *qb = new QBuffer(); @@ -69,4 +70,3 @@ void Usage::registerUsage() { connect(rep, SIGNAL(finished()), rep, SLOT(deleteLater())); } - diff --git a/src/mumble/Usage.h b/src/mumble/Usage.h index 900121446..2388b7480 100644 --- a/src/mumble/Usage.h +++ b/src/mumble/Usage.h @@ -18,15 +18,16 @@ class ClientUser; /// the object's registerUsage function will be called that sends the respective /// information to the server. class Usage : public QObject { - Q_OBJECT - protected: - QBuffer qbReport; - QDataStream qdsReport; - public: - Usage(QObject *p = nullptr); - public slots: - /// Performs the actual registration. - void registerUsage(); + Q_OBJECT +protected: + QBuffer qbReport; + QDataStream qdsReport; + +public: + Usage(QObject *p = nullptr); +public slots: + /// Performs the actual registration. + void registerUsage(); }; #endif diff --git a/src/mumble/UserEdit.cpp b/src/mumble/UserEdit.cpp index 16d596134..fa16681eb 100644 --- a/src/mumble/UserEdit.cpp +++ b/src/mumble/UserEdit.cpp @@ -13,14 +13,12 @@ #include <QtCore/QItemSelectionModel> #include <QtWidgets/QMenu> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" UserEdit::UserEdit(const MumbleProto::UserList &userList, QWidget *p) - : QDialog(p) - , m_model(new UserListModel(userList, this)) - , m_filter(new UserListFilterProxyModel(this)) { - + : QDialog(p), m_model(new UserListModel(userList, this)), m_filter(new UserListFilterProxyModel(this)) { setupUi(this); qlSearch->setAccessibleName(tr("Search")); qcbInactive->setAccessibleName(tr("Inactive for")); @@ -34,10 +32,10 @@ UserEdit::UserEdit(const MumbleProto::UserList &userList, QWidget *p) qtvUserList->setModel(m_filter); QItemSelectionModel *selectionModel = qtvUserList->selectionModel(); - connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - this, SLOT(onSelectionChanged(QItemSelection,QItemSelection))); - connect(selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), - this, SLOT(onCurrentRowChanged(QModelIndex,QModelIndex))); + connect(selectionModel, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, + SLOT(onSelectionChanged(QItemSelection, QItemSelection))); + connect(selectionModel, SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, + SLOT(onCurrentRowChanged(QModelIndex, QModelIndex))); qtvUserList->setFocus(); qtvUserList->setContextMenuPolicy(Qt::CustomContextMenu); @@ -89,21 +87,19 @@ void UserEdit::on_qtvUserList_customContextMenuRequested(const QPoint &point) { if (qtvUserList->selectionModel()->currentIndex().isValid()) { QAction *renameAction = menu->addAction(tr("Rename")); - connect(renameAction, SIGNAL(triggered()), - this, SLOT(on_qpbRename_clicked())); + connect(renameAction, SIGNAL(triggered()), this, SLOT(on_qpbRename_clicked())); menu->addSeparator(); } QAction *removeMenuAction = menu->addAction(tr("Remove")); - connect(removeMenuAction, SIGNAL(triggered()), - this, SLOT(on_qpbRemove_clicked())); + connect(removeMenuAction, SIGNAL(triggered()), this, SLOT(on_qpbRemove_clicked())); menu->exec(qtvUserList->mapToGlobal(point)); delete menu; } -void UserEdit::onSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { +void UserEdit::onSelectionChanged(const QItemSelection & /*selected*/, const QItemSelection & /*deselected*/) { const bool somethingSelected = !(qtvUserList->selectionModel()->selection().empty()); qpbRemove->setEnabled(somethingSelected); } @@ -121,7 +117,7 @@ void UserEdit::on_qcbInactive_currentIndexChanged(int) { } void UserEdit::updateInactiveDaysFilter() { - const int timespanUnit = qcbInactive->currentIndex(); + const int timespanUnit = qcbInactive->currentIndex(); const int timespanCount = qsbInactive->value(); int minimumInactiveDays = 0; @@ -147,9 +143,7 @@ void UserEdit::updateInactiveDaysFilter() { UserListFilterProxyModel::UserListFilterProxyModel(QObject *parent_) - : QSortFilterProxyModel(parent_) - , m_minimumInactiveDays(0) { - + : QSortFilterProxyModel(parent_), m_minimumInactiveDays(0) { setFilterKeyColumn(UserListModel::COL_NICK); setFilterCaseSensitivity(Qt::CaseInsensitive); setSortLocaleAware(true); @@ -157,13 +151,12 @@ UserListFilterProxyModel::UserListFilterProxyModel(QObject *parent_) } bool UserListFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { - if(!QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent)) { + if (!QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent)) { return false; } - const QModelIndex inactiveDaysIdx = sourceModel()->index(source_row, - UserListModel::COL_INACTIVEDAYS, - source_parent); + const QModelIndex inactiveDaysIdx = + sourceModel()->index(source_row, UserListModel::COL_INACTIVEDAYS, source_parent); bool ok; const int inactiveDays = inactiveDaysIdx.data().toInt(&ok); @@ -182,6 +175,5 @@ void UserListFilterProxyModel::setFilterMinimumInactiveDays(int minimumInactiveD void UserListFilterProxyModel::removeRowsInSelection(const QItemSelection &selection) { QItemSelection sourceSelection = mapSelectionToSource(selection); - qobject_cast<UserListModel*>(sourceModel())->removeRowsInSelection(sourceSelection); + qobject_cast< UserListModel * >(sourceModel())->removeRowsInSelection(sourceSelection); } - diff --git a/src/mumble/UserEdit.h b/src/mumble/UserEdit.h index deca37305..5e0de7375 100644 --- a/src/mumble/UserEdit.h +++ b/src/mumble/UserEdit.h @@ -16,40 +16,40 @@ class UserListModel; class UserListFilterProxyModel; namespace MumbleProto { - class UserList; - class UserList_User; -} +class UserList; +class UserList_User; +} // namespace MumbleProto /// /// Dialog used for server-side registered user list editing. /// class UserEdit : public QDialog, public Ui::UserEdit { - Q_OBJECT - Q_DISABLE_COPY(UserEdit) - public: - /// Constructs a dialog for editing the given userList. - UserEdit(const MumbleProto::UserList &userList, QWidget *p = nullptr); - - public slots: - void accept() Q_DECL_OVERRIDE; - - void on_qlSearch_textChanged(QString); - void on_qpbRemove_clicked(); - void on_qpbRename_clicked(); - void on_qtvUserList_customContextMenuRequested(const QPoint&); - void onSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/); - void onCurrentRowChanged(const QModelIndex & current, const QModelIndex &/*previous*/); - void on_qsbInactive_valueChanged(int); - void on_qcbInactive_currentIndexChanged(int); - - private: - enum TimespanUnits { TU_DAYS, TU_WEEKS, TU_MONTHS, TU_YEARS, COUNT_TU }; - - /// Polls the inactive-filter controls for their current value and updates the model filter. - void updateInactiveDaysFilter(); - - UserListModel *m_model; - UserListFilterProxyModel *m_filter; + Q_OBJECT + Q_DISABLE_COPY(UserEdit) +public: + /// Constructs a dialog for editing the given userList. + UserEdit(const MumbleProto::UserList &userList, QWidget *p = nullptr); + +public slots: + void accept() Q_DECL_OVERRIDE; + + void on_qlSearch_textChanged(QString); + void on_qpbRemove_clicked(); + void on_qpbRename_clicked(); + void on_qtvUserList_customContextMenuRequested(const QPoint &); + void onSelectionChanged(const QItemSelection & /*selected*/, const QItemSelection & /*deselected*/); + void onCurrentRowChanged(const QModelIndex ¤t, const QModelIndex & /*previous*/); + void on_qsbInactive_valueChanged(int); + void on_qcbInactive_currentIndexChanged(int); + +private: + enum TimespanUnits { TU_DAYS, TU_WEEKS, TU_MONTHS, TU_YEARS, COUNT_TU }; + + /// Polls the inactive-filter controls for their current value and updates the model filter. + void updateInactiveDaysFilter(); + + UserListModel *m_model; + UserListFilterProxyModel *m_filter; }; /// @@ -68,7 +68,7 @@ public slots: /// Sets the amount of inactive days below which rows will get filterd by the proxy void setFilterMinimumInactiveDays(int minimumInactiveDays); /// Helper function for removing all rows involved in a given selection (must include COL_NICK). - void removeRowsInSelection(const QItemSelection& selection); + void removeRowsInSelection(const QItemSelection &selection); private: /// Every row with less inactive days will be filtered. diff --git a/src/mumble/UserInformation.cpp b/src/mumble/UserInformation.cpp index 9aa466306..4996bd856 100644 --- a/src/mumble/UserInformation.cpp +++ b/src/mumble/UserInformation.cpp @@ -13,7 +13,8 @@ #include <QtCore/QUrl> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" static QString decode_utf8_qssl_string(const QString &input) { @@ -70,12 +71,12 @@ void UserInformation::on_qpbCertificate_clicked() { QString UserInformation::secsToString(unsigned int secs) { QStringList qsl; - int weeks = secs / (60 * 60 * 24 * 7); - secs = secs % (60 * 60 * 24 * 7); - int days = secs / (60 * 60 * 24); - secs = secs % (60 * 60 * 24); - int hours = secs / (60 * 60); - secs = secs % (60 * 60); + int weeks = secs / (60 * 60 * 24 * 7); + secs = secs % (60 * 60 * 24 * 7); + int days = secs / (60 * 60 * 24); + secs = secs % (60 * 60 * 24); + int hours = secs / (60 * 60); + secs = secs % (60 * 60); int minutes = secs / 60; int seconds = secs % 60; @@ -104,16 +105,17 @@ void UserInformation::update(const MumbleProto::UserStats &msg) { if (msg.certificates_size() > 0) { showcon = true; qlCerts.clear(); - for (int i=0;i<msg.certificates_size(); ++i) { + for (int i = 0; i < msg.certificates_size(); ++i) { const std::string &s = msg.certificates(i); - QList<QSslCertificate> certs = QSslCertificate::fromData(QByteArray(s.data(), static_cast<int>(s.length())), QSsl::Der); - qlCerts <<certs; + QList< QSslCertificate > certs = + QSslCertificate::fromData(QByteArray(s.data(), static_cast< int >(s.length())), QSsl::Der); + qlCerts << certs; } - if (! qlCerts.isEmpty()) { + if (!qlCerts.isEmpty()) { qpbCertificate->setEnabled(true); - const QSslCertificate &cert = qlCerts.last(); - const QMultiMap<QSsl::AlternativeNameEntryType, QString> &alts = cert.subjectAlternativeNames(); + const QSslCertificate &cert = qlCerts.last(); + const QMultiMap< QSsl::AlternativeNameEntryType, QString > &alts = cert.subjectAlternativeNames(); if (alts.contains(QSsl::EmailEntry)) qlCertificate->setText(QStringList(alts.values(QSsl::EmailEntry)).join(tr(", "))); else @@ -146,8 +148,8 @@ void UserInformation::update(const MumbleProto::UserStats &msg) { } if (msg.celt_versions_size() > 0) { QStringList qsl; - for (int i=0;i<msg.celt_versions_size(); ++i) { - int v = msg.celt_versions(i); + for (int i = 0; i < msg.celt_versions_size(); ++i) { + int v = msg.celt_versions(i); CELTCodec *cc = g.qmCodecs.value(v); if (cc) qsl << cc->version(); @@ -186,8 +188,10 @@ void UserInformation::update(const MumbleProto::UserStats &msg) { qlToResync->setText(QString::number(to.resync())); quint32 allFromPackets = from.good() + from.late() + from.lost(); - qlFromLatePercent->setText(QString::number(allFromPackets > 0 ? from.late() * 100.0 / allFromPackets : 0., 'f', 2)); - qlFromLostPercent->setText(QString::number(allFromPackets > 0 ? from.lost() * 100.0 / allFromPackets : 0., 'f', 2)); + qlFromLatePercent->setText( + QString::number(allFromPackets > 0 ? from.late() * 100.0 / allFromPackets : 0., 'f', 2)); + qlFromLostPercent->setText( + QString::number(allFromPackets > 0 ? from.lost() * 100.0 / allFromPackets : 0., 'f', 2)); quint32 allToPackets = to.good() + to.late() + to.lost(); qlToLatePercent->setText(QString::number(allToPackets > 0 ? to.late() * 100.0 / allToPackets : 0., 'f', 2)); @@ -198,7 +202,8 @@ void UserInformation::update(const MumbleProto::UserStats &msg) { if (msg.has_onlinesecs()) { if (msg.has_idlesecs()) - qlTime->setText(tr("%1 online (%2 idle)").arg(secsToString(msg.onlinesecs()), secsToString(msg.idlesecs()))); + qlTime->setText( + tr("%1 online (%2 idle)").arg(secsToString(msg.onlinesecs()), secsToString(msg.idlesecs()))); else qlTime->setText(tr("%1 online").arg(secsToString(msg.onlinesecs()))); } diff --git a/src/mumble/UserInformation.h b/src/mumble/UserInformation.h index 261bce0c2..4b54fd2e8 100644 --- a/src/mumble/UserInformation.h +++ b/src/mumble/UserInformation.h @@ -19,23 +19,24 @@ class UserStats; class QTimer; class UserInformation : public QDialog, Ui::UserInformation { - private: - Q_OBJECT - Q_DISABLE_COPY(UserInformation) - protected: - bool bRequested; - unsigned int uiSession; - QTimer *qtTimer; - QList<QSslCertificate> qlCerts; - static QString secsToString(unsigned int secs); - QFont qfCertificateFont; - protected slots: - void tick(); - void on_qpbCertificate_clicked(); - public: - UserInformation(const MumbleProto::UserStats &msg, QWidget *p = nullptr); - void update(const MumbleProto::UserStats &msg); - unsigned int session() const; +private: + Q_OBJECT + Q_DISABLE_COPY(UserInformation) +protected: + bool bRequested; + unsigned int uiSession; + QTimer *qtTimer; + QList< QSslCertificate > qlCerts; + static QString secsToString(unsigned int secs); + QFont qfCertificateFont; +protected slots: + void tick(); + void on_qpbCertificate_clicked(); + +public: + UserInformation(const MumbleProto::UserStats &msg, QWidget *p = nullptr); + void update(const MumbleProto::UserStats &msg); + unsigned int session() const; }; #endif diff --git a/src/mumble/UserListModel.cpp b/src/mumble/UserListModel.cpp index f690cc7fa..b07b6bcee 100644 --- a/src/mumble/UserListModel.cpp +++ b/src/mumble/UserListModel.cpp @@ -12,23 +12,21 @@ #include <algorithm> #ifdef _MSC_VER -# include <functional> +# include <functional> #endif #include <vector> -UserListModel::UserListModel(const MumbleProto::UserList& userList, QObject *parent_) - : QAbstractTableModel(parent_) - , m_legacyMode(false) { - +UserListModel::UserListModel(const MumbleProto::UserList &userList, QObject *parent_) + : QAbstractTableModel(parent_), m_legacyMode(false) { m_userList.reserve(userList.users_size()); for (int i = 0; i < userList.users_size(); ++i) { m_userList.append(userList.users(i)); } if (!m_userList.empty()) { - const MumbleProto::UserList_User& user = m_userList.back(); - m_legacyMode = !user.has_last_seen() || !user.has_last_channel(); + const MumbleProto::UserList_User &user = m_userList.back(); + m_legacyMode = !user.has_last_seen() || !user.has_last_channel(); } } @@ -54,16 +52,20 @@ int UserListModel::columnCount(const QModelIndex &parentIndex) const { QVariant UserListModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal) return QVariant(); - + if (section < 0 || section >= columnCount()) return QVariant(); if (role == Qt::DisplayRole) { switch (section) { - case COL_NICK: return tr("Nick"); - case COL_INACTIVEDAYS: return tr("Inactive days"); - case COL_LASTCHANNEL: return tr("Last channel"); - default: return QVariant(); + case COL_NICK: + return tr("Nick"); + case COL_INACTIVEDAYS: + return tr("Inactive days"); + case COL_LASTCHANNEL: + return tr("Last channel"); + default: + return QVariant(); } } @@ -73,35 +75,44 @@ QVariant UserListModel::headerData(int section, Qt::Orientation orientation, int QVariant UserListModel::data(const QModelIndex &dataIndex, int role) const { if (!dataIndex.isValid()) return QVariant(); - + if (dataIndex.row() < 0 || dataIndex.row() >= m_userList.size()) return QVariant(); - + if (dataIndex.column() >= columnCount()) return QVariant(); - const MumbleProto::UserList_User& user = m_userList[dataIndex.row()]; + const MumbleProto::UserList_User &user = m_userList[dataIndex.row()]; if (role == Qt::DisplayRole) { switch (dataIndex.column()) { - case COL_NICK: return u8(user.name()); - case COL_INACTIVEDAYS: return lastSeenToTodayDayCount(user.last_seen()); - case COL_LASTCHANNEL: return pathForChannelId(user.last_channel()); - default: return QVariant(); + case COL_NICK: + return u8(user.name()); + case COL_INACTIVEDAYS: + return lastSeenToTodayDayCount(user.last_seen()); + case COL_LASTCHANNEL: + return pathForChannelId(user.last_channel()); + default: + return QVariant(); } } else if (role == Qt::ToolTipRole) { switch (dataIndex.column()) { - case COL_INACTIVEDAYS: return tr("Last seen: %1").arg(user.last_seen().empty() ? - tr("Never") - : u8(user.last_seen()).toHtmlEscaped()); - case COL_LASTCHANNEL: return tr("Channel ID: %1").arg(user.last_channel()); - default: return QVariant(); + case COL_INACTIVEDAYS: + return tr("Last seen: %1") + .arg(user.last_seen().empty() ? tr("Never") : u8(user.last_seen()).toHtmlEscaped()); + case COL_LASTCHANNEL: + return tr("Channel ID: %1").arg(user.last_channel()); + default: + return QVariant(); } } else if (role == Qt::UserRole) { switch (dataIndex.column()) { - case COL_INACTIVEDAYS: return isoUTCToDateTime(user.last_seen()); - case COL_LASTCHANNEL: return user.last_channel(); - default: return QVariant(); + case COL_INACTIVEDAYS: + return isoUTCToDateTime(user.last_seen()); + case COL_LASTCHANNEL: + return user.last_channel(); + default: + return QVariant(); } } else if (role == Qt::EditRole) { if (dataIndex.column() == COL_NICK) { @@ -115,10 +126,10 @@ QVariant UserListModel::data(const QModelIndex &dataIndex, int role) const { bool UserListModel::setData(const QModelIndex &dataIndex, const QVariant &value, int role) { if (!dataIndex.isValid()) return false; - + if (dataIndex.column() != COL_NICK || role != Qt::EditRole) return false; - + if (dataIndex.row() < 0 || dataIndex.row() >= m_userList.size()) return false; @@ -128,9 +139,9 @@ bool UserListModel::setData(const QModelIndex &dataIndex, const QVariant &value, return false; } - MumbleProto::UserList_User& user = m_userList[dataIndex.row()]; + MumbleProto::UserList_User &user = m_userList[dataIndex.row()]; if (newNick != user.name()) { - foreach (const MumbleProto::UserList_User& otherUser, m_userList) { + foreach (const MumbleProto::UserList_User &otherUser, m_userList) { if (otherUser.name() == newNick) { // Duplicate is not valid return false; @@ -163,11 +174,9 @@ bool UserListModel::removeRows(int row, int count, const QModelIndex &parentInde beginRemoveRows(parentIndex, row, row + count - 1); ModelUserList::Iterator startIt = m_userList.begin() + row; - ModelUserList::Iterator endIt = startIt + count; + ModelUserList::Iterator endIt = startIt + count; - for (ModelUserList::Iterator it = startIt; - it != endIt; - ++it) { + for (ModelUserList::Iterator it = startIt; it != endIt; ++it) { it->clear_name(); m_changes[it->user_id()] = *it; } @@ -181,10 +190,10 @@ bool UserListModel::removeRows(int row, int count, const QModelIndex &parentInde void UserListModel::removeRowsInSelection(const QItemSelection &selection) { QModelIndexList indices = selection.indexes(); - std::vector<int> rows; + std::vector< int > rows; rows.reserve(indices.size()); - foreach (const QModelIndex& idx, indices) { + foreach (const QModelIndex &idx, indices) { if (idx.column() != COL_NICK) continue; @@ -196,9 +205,9 @@ void UserListModel::removeRowsInSelection(const QItemSelection &selection) { // The basic idea is to take a number of sorted rows (e.g. 10,9,5,3,2,1) and // delete them with the minimum number of removeRows calls. This means grouping // adjacent rows (e.g. (10,9),(5),(3,2,1)) and using a removeRows call for each group. - std::sort(rows.begin(), rows.end(), std::greater<int>()); + std::sort(rows.begin(), rows.end(), std::greater< int >()); - int nextRow = -2; + int nextRow = -2; int groupRowCount = 0; for (size_t i = 0; i < rows.size(); ++i) { @@ -206,14 +215,14 @@ void UserListModel::removeRowsInSelection(const QItemSelection &selection) { ++groupRowCount; --nextRow; } else { - if (groupRowCount > 0) { + if (groupRowCount > 0) { // Remove previous group const int lastRowInGroup = nextRow + 1; removeRows(lastRowInGroup, groupRowCount); } // Start next group - nextRow = rows[i] - 1; + nextRow = rows[i] - 1; groupRowCount = 1; } } @@ -228,11 +237,9 @@ void UserListModel::removeRowsInSelection(const QItemSelection &selection) { MumbleProto::UserList UserListModel::getUserListUpdate() const { MumbleProto::UserList updateList; - for (ModelUserListChangeMap::ConstIterator it = m_changes.constBegin(); - it != m_changes.constEnd(); - ++it) { - MumbleProto::UserList_User* user = updateList.add_users(); - *user = it.value(); + for (ModelUserListChangeMap::ConstIterator it = m_changes.constBegin(); it != m_changes.constEnd(); ++it) { + MumbleProto::UserList_User *user = updateList.add_users(); + *user = it.value(); } return updateList; diff --git a/src/mumble/UserListModel.h b/src/mumble/UserListModel.h index d9b93bb4d..4da96e8ef 100644 --- a/src/mumble/UserListModel.h +++ b/src/mumble/UserListModel.h @@ -6,7 +6,6 @@ #ifndef MUMBLE_MUMBLE_USERLISTMODEL_H_ #define MUMBLE_MUMBLE_USERLISTMODEL_H_ -#include <Qt> #include <QAbstractTableModel> #include <QDateTime> #include <QHash> @@ -16,6 +15,7 @@ #include <QObject> #include <QString> #include <QVariant> +#include <Qt> #include "Mumble.pb.h" @@ -24,63 +24,62 @@ /// It supports removing rows and editing user nicks. /// class UserListModel : public QAbstractTableModel { - Q_OBJECT - public: - /// Enumerates the columns in the table model - enum Columns { COL_NICK, COL_INACTIVEDAYS, COL_LASTCHANNEL, COUNT_COL }; - - /// UserListModel constructs a table model representing the userList. - /// @param userList User list protobuf structure (will be copied) - /// @param parent Parent in QObject hierarchy - UserListModel(const MumbleProto::UserList& userList, QObject *parent = nullptr); - - int rowCount(const QModelIndex &parentIndex = QModelIndex()) const Q_DECL_OVERRIDE; - int columnCount(const QModelIndex &parentIndex = QModelIndex()) const Q_DECL_OVERRIDE; - - QVariant headerData(int section, Qt::Orientation orientation, int role) const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &dataIndex, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; - bool setData(const QModelIndex &dataIndex, const QVariant &value, int role) Q_DECL_OVERRIDE; - Qt::ItemFlags flags(const QModelIndex &flagIndex) const Q_DECL_OVERRIDE; - - bool removeRows(int row, int count, const QModelIndex &parentIndex = QModelIndex()) Q_DECL_OVERRIDE; - - /// Function for removing all rows in a selection - void removeRowsInSelection(const QItemSelection &selection); - - /// Returns a message for updating the original server state to the current model state. - MumbleProto::UserList getUserListUpdate() const; - - /// Returns true if the UserList given during construction was changed. - bool isUserListDirty() const; - - /// Returns true if the model only contains COL_NICK (true for Mumble <= 1.2.4) - bool isLegacy() const; - - private: - - /// Given an ISO formatted UTC time string returns the number of days since then. - /// @return QVariant() is returned for invalid strings. - QVariant lastSeenToTodayDayCount(const std::string& lastSeenDate) const; - /// Returns a textual representation of the channel hierarchy of the given channel - QString pathForChannelId(const int channelId) const; - /// Converts a ISO formatted UTC time string to a QDateTime object. - QDateTime isoUTCToDateTime(const std::string& isoTime) const; - - typedef QList<MumbleProto::UserList_User> ModelUserList; - /// Model backend for user data - ModelUserList m_userList; - - typedef QHash< ::google::protobuf::uint32, MumbleProto::UserList_User> ModelUserListChangeMap; - /// Change map indexed by user id - ModelUserListChangeMap m_changes; - - /// True if the message given on construction lacked column data (true for murmur <= 1.2.4) - bool m_legacyMode; - - /// Cache for lastSeenToTodayDayCount - mutable QHash<QString, QVariant> m_stringToLastSeenToTodayCount; - /// Cache for pathForChannelId conversions - mutable QHash<int, QString> m_channelIdToPathMap; + Q_OBJECT +public: + /// Enumerates the columns in the table model + enum Columns { COL_NICK, COL_INACTIVEDAYS, COL_LASTCHANNEL, COUNT_COL }; + + /// UserListModel constructs a table model representing the userList. + /// @param userList User list protobuf structure (will be copied) + /// @param parent Parent in QObject hierarchy + UserListModel(const MumbleProto::UserList &userList, QObject *parent = nullptr); + + int rowCount(const QModelIndex &parentIndex = QModelIndex()) const Q_DECL_OVERRIDE; + int columnCount(const QModelIndex &parentIndex = QModelIndex()) const Q_DECL_OVERRIDE; + + QVariant headerData(int section, Qt::Orientation orientation, int role) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &dataIndex, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + bool setData(const QModelIndex &dataIndex, const QVariant &value, int role) Q_DECL_OVERRIDE; + Qt::ItemFlags flags(const QModelIndex &flagIndex) const Q_DECL_OVERRIDE; + + bool removeRows(int row, int count, const QModelIndex &parentIndex = QModelIndex()) Q_DECL_OVERRIDE; + + /// Function for removing all rows in a selection + void removeRowsInSelection(const QItemSelection &selection); + + /// Returns a message for updating the original server state to the current model state. + MumbleProto::UserList getUserListUpdate() const; + + /// Returns true if the UserList given during construction was changed. + bool isUserListDirty() const; + + /// Returns true if the model only contains COL_NICK (true for Mumble <= 1.2.4) + bool isLegacy() const; + +private: + /// Given an ISO formatted UTC time string returns the number of days since then. + /// @return QVariant() is returned for invalid strings. + QVariant lastSeenToTodayDayCount(const std::string &lastSeenDate) const; + /// Returns a textual representation of the channel hierarchy of the given channel + QString pathForChannelId(const int channelId) const; + /// Converts a ISO formatted UTC time string to a QDateTime object. + QDateTime isoUTCToDateTime(const std::string &isoTime) const; + + typedef QList< MumbleProto::UserList_User > ModelUserList; + /// Model backend for user data + ModelUserList m_userList; + + typedef QHash<::google::protobuf::uint32, MumbleProto::UserList_User > ModelUserListChangeMap; + /// Change map indexed by user id + ModelUserListChangeMap m_changes; + + /// True if the message given on construction lacked column data (true for murmur <= 1.2.4) + bool m_legacyMode; + + /// Cache for lastSeenToTodayDayCount + mutable QHash< QString, QVariant > m_stringToLastSeenToTodayCount; + /// Cache for pathForChannelId conversions + mutable QHash< int, QString > m_channelIdToPathMap; }; #endif // MUMBLE_MUMBLE_USERLISTMODEL_H_ diff --git a/src/mumble/UserLocalVolumeDialog.cpp b/src/mumble/UserLocalVolumeDialog.cpp index 2975a830f..ee2d529f9 100644 --- a/src/mumble/UserLocalVolumeDialog.cpp +++ b/src/mumble/UserLocalVolumeDialog.cpp @@ -12,13 +12,13 @@ are met: - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -44,14 +44,13 @@ #include <cmath> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" UserLocalVolumeDialog::UserLocalVolumeDialog(unsigned int sessionId, - QMap<unsigned int, UserLocalVolumeDialog *> *qmUserVolTracker) - : QDialog(nullptr) - , m_clientSession(sessionId) - , m_qmUserVolTracker(qmUserVolTracker) { + QMap< unsigned int, UserLocalVolumeDialog * > *qmUserVolTracker) + : QDialog(nullptr), m_clientSession(sessionId), m_qmUserVolTracker(qmUserVolTracker) { setupUi(this); qsUserLocalVolume->setAccessibleName(tr("User volume")); qsbUserLocalVolume->setAccessibleName(tr("User volume")); @@ -77,7 +76,7 @@ void UserLocalVolumeDialog::closeEvent(QCloseEvent *event) { } void UserLocalVolumeDialog::present(unsigned int sessionId, - QMap<unsigned int, UserLocalVolumeDialog *> *qmUserVolTracker) { + QMap< unsigned int, UserLocalVolumeDialog * > *qmUserVolTracker) { if (qmUserVolTracker->contains(sessionId)) { qmUserVolTracker->value(sessionId)->raise(); } else { @@ -92,7 +91,7 @@ void UserLocalVolumeDialog::on_qsUserLocalVolume_valueChanged(int value) { ClientUser *user = ClientUser::get(m_clientSession); if (user) { // Decibel formula: +6db = *2 - user->setLocalVolumeAdjustment(static_cast<float>(pow(2.0, qsUserLocalVolume->value() / 6.0))); + user->setLocalVolumeAdjustment(static_cast< float >(pow(2.0, qsUserLocalVolume->value() / 6.0))); } } @@ -108,9 +107,9 @@ void UserLocalVolumeDialog::on_qbbUserLocalVolume_clicked(QAbstractButton *butto ClientUser *user = ClientUser::get(m_clientSession); if (user) { if (!user->qsHash.isEmpty()) { - g.db->setUserLocalVolume(user->qsHash, user->getLocalVolumeAdjustments()); + g.db->setUserLocalVolume(user->qsHash, user->getLocalVolumeAdjustments()); } else { - g.mw->logChangeNotPermanent(QObject::tr("Local Volume Adjustment..."), user); + g.mw->logChangeNotPermanent(QObject::tr("Local Volume Adjustment..."), user); } } UserLocalVolumeDialog::close(); diff --git a/src/mumble/UserLocalVolumeDialog.h b/src/mumble/UserLocalVolumeDialog.h index f3c622d2e..e4311e8c4 100644 --- a/src/mumble/UserLocalVolumeDialog.h +++ b/src/mumble/UserLocalVolumeDialog.h @@ -12,13 +12,13 @@ are met: - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -38,32 +38,30 @@ #include <QMap> -#include "ui_UserLocalVolumeDialog.h" #include "ClientUser.h" +#include "ui_UserLocalVolumeDialog.h" class UserLocalVolumeDialog : public QDialog, private Ui::UserLocalVolumeDialog { - Q_OBJECT - Q_DISABLE_COPY(UserLocalVolumeDialog); + Q_OBJECT + Q_DISABLE_COPY(UserLocalVolumeDialog); - /// The session ID for the user that the dialog is changing the volume for. - unsigned int m_clientSession; + /// The session ID for the user that the dialog is changing the volume for. + unsigned int m_clientSession; - /// The user's original adjustment (in dB) when entering the dialog. - int m_originalVolumeAdjustmentDecibel; - QMap<unsigned int, UserLocalVolumeDialog *> *m_qmUserVolTracker; + /// The user's original adjustment (in dB) when entering the dialog. + int m_originalVolumeAdjustmentDecibel; + QMap< unsigned int, UserLocalVolumeDialog * > *m_qmUserVolTracker; - public slots: - void closeEvent(QCloseEvent *event); - void on_qsUserLocalVolume_valueChanged(int value); - void on_qsbUserLocalVolume_valueChanged(int value); - void on_qbbUserLocalVolume_clicked(QAbstractButton *b); - void reject(); +public slots: + void closeEvent(QCloseEvent *event); + void on_qsUserLocalVolume_valueChanged(int value); + void on_qsbUserLocalVolume_valueChanged(int value); + void on_qbbUserLocalVolume_clicked(QAbstractButton *b); + void reject(); - public: - static void present(unsigned int sessionId, - QMap<unsigned int, UserLocalVolumeDialog *> *qmUserVolTracker); - UserLocalVolumeDialog(unsigned int sessionId, - QMap<unsigned int, UserLocalVolumeDialog *> *qmUserVolTracker); +public: + static void present(unsigned int sessionId, QMap< unsigned int, UserLocalVolumeDialog * > *qmUserVolTracker); + UserLocalVolumeDialog(unsigned int sessionId, QMap< unsigned int, UserLocalVolumeDialog * > *qmUserVolTracker); }; #endif diff --git a/src/mumble/UserLockFile.h b/src/mumble/UserLockFile.h index 89fc490cd..431978bd9 100644 --- a/src/mumble/UserLockFile.h +++ b/src/mumble/UserLockFile.h @@ -9,7 +9,7 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include <QtCore/QString> @@ -23,28 +23,28 @@ class UserLockFile { #endif QString m_path; - public: - /// Constructs a LockFile at path. - /// The path should be somewhere - /// owned by the current user, such - /// as inside the home directory of - /// the user. This is to avoid clashing - /// with other lock files. - UserLockFile(const QString &path); +public: + /// Constructs a LockFile at path. + /// The path should be somewhere + /// owned by the current user, such + /// as inside the home directory of + /// the user. This is to avoid clashing + /// with other lock files. + UserLockFile(const QString &path); - /// Destroys the LockFile, and ensures - /// that it is released. - ~UserLockFile(); + /// Destroys the LockFile, and ensures + /// that it is released. + ~UserLockFile(); - /// Returns the path that the lock file - /// exists at. - QString path() const; + /// Returns the path that the lock file + /// exists at. + QString path() const; - /// Acquires the lock file. - bool acquire(); + /// Acquires the lock file. + bool acquire(); - /// Releases the lock file. - void release(); + /// Releases the lock file. + void release(); }; #endif diff --git a/src/mumble/UserLockFile_win.cpp b/src/mumble/UserLockFile_win.cpp index 29c69242e..c77454b52 100644 --- a/src/mumble/UserLockFile_win.cpp +++ b/src/mumble/UserLockFile_win.cpp @@ -5,9 +5,7 @@ #include "UserLockFile.h" -UserLockFile::UserLockFile(const QString &lockFilePath) - : m_handle(0) - , m_path(lockFilePath) { +UserLockFile::UserLockFile(const QString &lockFilePath) : m_handle(0), m_path(lockFilePath) { } UserLockFile::~UserLockFile() { @@ -23,15 +21,8 @@ bool UserLockFile::acquire() { return false; } - m_handle = CreateFile( - reinterpret_cast<const wchar_t *>(m_path.utf16()), - GENERIC_WRITE, - 0, - nullptr, - CREATE_ALWAYS, - FILE_ATTRIBUTE_HIDDEN, - nullptr - ); + m_handle = CreateFile(reinterpret_cast< const wchar_t * >(m_path.utf16()), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_HIDDEN, nullptr); if (m_handle == INVALID_HANDLE_VALUE && GetLastError() == ERROR_SHARING_VIOLATION) { return false; } diff --git a/src/mumble/UserModel.cpp b/src/mumble/UserModel.cpp index ad3307ebd..33d946f67 100644 --- a/src/mumble/UserModel.cpp +++ b/src/mumble/UserModel.cpp @@ -5,20 +5,20 @@ #include "UserModel.h" -#include "ClientUser.h" #include "Channel.h" +#include "ClientUser.h" #include "Database.h" #include "LCD.h" #include "Log.h" #include "MainWindow.h" #include "Message.h" #ifdef USE_OVERLAY - #include "Overlay.h" +# include "Overlay.h" #endif +#include "ChannelListener.h" #include "ServerHandler.h" #include "Usage.h" #include "User.h" -#include "ChannelListener.h" #include <QtCore/QMimeData> #include <QtCore/QStack> @@ -27,29 +27,30 @@ #include <QtWidgets/QToolTip> #include <QtWidgets/QWhatsThis> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -QHash <const Channel *, ModelItem *> ModelItem::c_qhChannels; -QHash <const ClientUser *, ModelItem *> ModelItem::c_qhUsers; -QHash <const ClientUser *, QList<ModelItem *>> ModelItem::s_userProxies; +QHash< const Channel *, ModelItem * > ModelItem::c_qhChannels; +QHash< const ClientUser *, ModelItem * > ModelItem::c_qhUsers; +QHash< const ClientUser *, QList< ModelItem * > > ModelItem::s_userProxies; bool ModelItem::bUsersTop = false; ModelItem::ModelItem(Channel *c) { - this->cChan = c; - this->pUser = nullptr; + this->cChan = c; + this->pUser = nullptr; this->isListener = false; - bCommentSeen = true; + bCommentSeen = true; c_qhChannels.insert(c, this); parent = c_qhChannels.value(c->cParent); iUsers = 0; } ModelItem::ModelItem(ClientUser *p, bool isListener) { - this->cChan = nullptr; - this->pUser = p; + this->cChan = nullptr; + this->pUser = p; this->isListener = isListener; - bCommentSeen = true; + bCommentSeen = true; if (isListener) { // The way operator[] works for a QHash is that it'll insert a default-constructed // object first, before returning a reference to it, in case there is no entry for @@ -65,11 +66,11 @@ ModelItem::ModelItem(ClientUser *p, bool isListener) { ModelItem::ModelItem(ModelItem *i) { // Create a shallow clone - this->cChan = i->cChan; - this->pUser = i->pUser; - this->parent = i->parent; + this->cChan = i->cChan; + this->pUser = i->pUser; + this->parent = i->parent; this->bCommentSeen = i->bCommentSeen; - this->isListener = i->isListener; + this->isListener = i->isListener; if (pUser) { if (isListener) { @@ -77,8 +78,7 @@ ModelItem::ModelItem(ModelItem *i) { } else { c_qhUsers.insert(pUser, this); } - } - else if (cChan) + } else if (cChan) c_qhChannels.insert(cChan, this); iUsers = i->iUsers; @@ -100,7 +100,7 @@ ModelItem::~ModelItem() { } void ModelItem::wipe() { - foreach(ModelItem *i, qlChildren) { + foreach (ModelItem *i, qlChildren) { i->wipe(); delete i; } @@ -109,7 +109,7 @@ void ModelItem::wipe() { } ModelItem *ModelItem::child(int idx) const { - if (! validRow(idx)) + if (!validRow(idx)) return nullptr; return qlChildren.at(idx); @@ -120,26 +120,26 @@ bool ModelItem::validRow(int idx) const { } ClientUser *ModelItem::userAt(int idx) const { - if (! validRow(idx)) + if (!validRow(idx)) return nullptr; return qlChildren.at(idx)->pUser; } Channel *ModelItem::channelAt(int idx) const { - if (! validRow(idx)) + if (!validRow(idx)) return nullptr; return qlChildren.at(idx)->cChan; } int ModelItem::rowOf(Channel *c) const { - for (int i=0;i<qlChildren.count();i++) + for (int i = 0; i < qlChildren.count(); i++) if (qlChildren.at(i)->cChan == c) return i; return -1; } int ModelItem::rowOf(ClientUser *p, const bool isListener) const { - for (int i=0;i<qlChildren.count();i++) + for (int i = 0; i < qlChildren.count(); i++) if (qlChildren.at(i)->isListener == isListener && qlChildren.at(i)->pUser == p) return i; return -1; @@ -147,7 +147,7 @@ int ModelItem::rowOf(ClientUser *p, const bool isListener) const { int ModelItem::rowOfSelf() const { // Root? - if (! parent) + if (!parent) return 0; if (pUser) @@ -161,12 +161,12 @@ int ModelItem::rows() const { } int ModelItem::insertIndex(Channel *c) const { - QList<Channel*> qlpc; + QList< Channel * > qlpc; ModelItem *item; int ocount = 0; - foreach(item, qlChildren) { + foreach (item, qlChildren) { if (item->cChan) { if (item->cChan != c) { qlpc << item->cChan; @@ -180,13 +180,13 @@ int ModelItem::insertIndex(Channel *c) const { } int ModelItem::insertIndex(ClientUser *p, bool isListener) const { - QList<ClientUser*> qlclientuser; + QList< ClientUser * > qlclientuser; ModelItem *item; - int ocount = 0; + int ocount = 0; int listenerCount = 0; - foreach(item, qlChildren) { + foreach (item, qlChildren) { if (item->pUser) { if (item->pUser != p) { // Make sure listeners and non-listeners are all grouped together and not mixed @@ -214,8 +214,8 @@ int ModelItem::insertIndex(ClientUser *p, bool isListener) const { QString ModelItem::hash() const { if (pUser) { - if (! pUser->qsHash.isEmpty()) - return pUser->qsHash + (isListener ? QLatin1String("l"): QString()); + if (!pUser->qsHash.isEmpty()) + return pUser->qsHash + (isListener ? QLatin1String("l") : QString()); else return QLatin1String(sha1(pUser->qsName + (isListener ? QLatin1String("l") : QString())).toHex()); } else { @@ -235,38 +235,38 @@ QString ModelItem::hash() const { } UserModel::UserModel(QObject *p) : QAbstractItemModel(p) { - qiTalkingOff=QIcon(QLatin1String("skin:talking_off.svg")); - qiTalkingOn=QIcon(QLatin1String("skin:talking_on.svg")); - qiTalkingMuted=QIcon(QLatin1String("skin:talking_muted.svg")); - qiTalkingShout=QIcon(QLatin1String("skin:talking_alt.svg")); - qiTalkingWhisper=QIcon(QLatin1String("skin:talking_whisper.svg")); - qiPrioritySpeaker=QIcon(QLatin1String("skin:priority_speaker.svg")); - qiRecording=QIcon(QLatin1String("skin:actions/media-record.svg")); + qiTalkingOff = QIcon(QLatin1String("skin:talking_off.svg")); + qiTalkingOn = QIcon(QLatin1String("skin:talking_on.svg")); + qiTalkingMuted = QIcon(QLatin1String("skin:talking_muted.svg")); + qiTalkingShout = QIcon(QLatin1String("skin:talking_alt.svg")); + qiTalkingWhisper = QIcon(QLatin1String("skin:talking_whisper.svg")); + qiPrioritySpeaker = QIcon(QLatin1String("skin:priority_speaker.svg")); + qiRecording = QIcon(QLatin1String("skin:actions/media-record.svg")); qiMutedPushToMute.addFile(QLatin1String("skin:muted_pushtomute.svg")); - qiMutedSelf=QIcon(QLatin1String("skin:muted_self.svg")); - qiMutedServer=QIcon(QLatin1String("skin:muted_server.svg")); - qiMutedLocal=QIcon(QLatin1String("skin:muted_local.svg")); - qiIgnoredLocal=QIcon(QLatin1String("skin:status/text-missing.svg")); - qiMutedSuppressed=QIcon(QLatin1String("skin:muted_suppressed.svg")); - qiDeafenedSelf=QIcon(QLatin1String("skin:deafened_self.svg")); - qiDeafenedServer=QIcon(QLatin1String("skin:deafened_server.svg")); - qiAuthenticated=QIcon(QLatin1String("skin:authenticated.svg")); - qiChannel=QIcon(QLatin1String("skin:channel.svg")); - qiActiveChannel=QIcon(QLatin1String("skin:channel_active.svg")); - qiLinkedChannel=QIcon(QLatin1String("skin:channel_linked.svg")); - qiFriend=QIcon(QLatin1String("skin:emblems/emblem-favorite.svg")); - qiComment=QIcon(QLatin1String("skin:comment.svg")); - qiCommentSeen=QIcon(QLatin1String("skin:comment_seen.svg")); - qiFilter=QIcon(QLatin1String("skin:filter.svg")); - qiLock_locked=QIcon(QLatin1String("skin:lock_locked.svg")); - qiLock_unlocked=QIcon(QLatin1String("skin:lock_unlocked.svg")); - qiEar=QIcon(QLatin1String("skin:ear.svg")); + qiMutedSelf = QIcon(QLatin1String("skin:muted_self.svg")); + qiMutedServer = QIcon(QLatin1String("skin:muted_server.svg")); + qiMutedLocal = QIcon(QLatin1String("skin:muted_local.svg")); + qiIgnoredLocal = QIcon(QLatin1String("skin:status/text-missing.svg")); + qiMutedSuppressed = QIcon(QLatin1String("skin:muted_suppressed.svg")); + qiDeafenedSelf = QIcon(QLatin1String("skin:deafened_self.svg")); + qiDeafenedServer = QIcon(QLatin1String("skin:deafened_server.svg")); + qiAuthenticated = QIcon(QLatin1String("skin:authenticated.svg")); + qiChannel = QIcon(QLatin1String("skin:channel.svg")); + qiActiveChannel = QIcon(QLatin1String("skin:channel_active.svg")); + qiLinkedChannel = QIcon(QLatin1String("skin:channel_linked.svg")); + qiFriend = QIcon(QLatin1String("skin:emblems/emblem-favorite.svg")); + qiComment = QIcon(QLatin1String("skin:comment.svg")); + qiCommentSeen = QIcon(QLatin1String("skin:comment_seen.svg")); + qiFilter = QIcon(QLatin1String("skin:filter.svg")); + qiLock_locked = QIcon(QLatin1String("skin:lock_locked.svg")); + qiLock_unlocked = QIcon(QLatin1String("skin:lock_unlocked.svg")); + qiEar = QIcon(QLatin1String("skin:ear.svg")); ModelItem::bUsersTop = g.s.bUserTop; - uiSessionComment = 0; + uiSessionComment = 0; iChannelDescription = -1; - bClicked = false; + bClicked = false; miRoot = new ModelItem(Channel::get(0)); } @@ -291,16 +291,16 @@ QModelIndex UserModel::index(int row, int column, const QModelIndex &p) const { return QModelIndex(); } - if (! p.isValid()) { + if (!p.isValid()) { return createIndex(row, column, miRoot); } else { - item = static_cast<ModelItem *>(p.internalPointer()); + item = static_cast< ModelItem * >(p.internalPointer()); } - if (! item) + if (!item) return idx; - if (! item->validRow(row)) + if (!item->validRow(row)) return idx; idx = createIndex(row, column, item->child(row)); @@ -312,9 +312,9 @@ QModelIndex UserModel::index(ClientUser *p, int column) const { ModelItem *item = ModelItem::c_qhUsers.value(p); Q_ASSERT(p); Q_ASSERT(item); - if (!p || ! item) + if (!p || !item) return QModelIndex(); - QModelIndex idx=createIndex(item->rowOfSelf(), column, item); + QModelIndex idx = createIndex(item->rowOfSelf(), column, item); return idx; } @@ -324,7 +324,7 @@ QModelIndex UserModel::index(Channel *c, int column) const { Q_ASSERT(item); if (!item || !c) return QModelIndex(); - QModelIndex idx=createIndex(item->rowOfSelf(), column, item); + QModelIndex idx = createIndex(item->rowOfSelf(), column, item); return idx; } @@ -333,7 +333,7 @@ QModelIndex UserModel::index(ModelItem *item) const { } QModelIndex UserModel::channelListenerIndex(const ClientUser *user, const Channel *channel, int column) const { - QList<ModelItem *> items = ModelItem::s_userProxies.value(user); + QList< ModelItem * > items = ModelItem::s_userProxies.value(user); ModelItem *item = nullptr; for (ModelItem *currentItem : items) { @@ -357,14 +357,14 @@ QModelIndex UserModel::channelListenerIndex(const ClientUser *user, const Channe } QModelIndex UserModel::parent(const QModelIndex &idx) const { - if (! idx.isValid()) + if (!idx.isValid()) return QModelIndex(); - ModelItem *item = static_cast<ModelItem *>(idx.internalPointer()); + ModelItem *item = static_cast< ModelItem * >(idx.internalPointer()); ModelItem *parent_item = item ? item->parent : nullptr; - if (! parent_item) + if (!parent_item) return QModelIndex(); return createIndex(parent_item->rowOfSelf(), 0, parent_item); @@ -378,9 +378,9 @@ int UserModel::rowCount(const QModelIndex &p) const { if (!p.isValid()) return 1; else - item = static_cast<ModelItem *>(p.internalPointer()); + item = static_cast< ModelItem * >(p.internalPointer()); - if (! item || (p.column() != 0)) + if (!item || (p.column() != 0)) return 0; val = item->rows(); @@ -389,7 +389,7 @@ int UserModel::rowCount(const QModelIndex &p) const { } QString UserModel::stringIndex(const QModelIndex &idx) const { - ModelItem *item = static_cast<ModelItem *>(idx.internalPointer()); + ModelItem *item = static_cast< ModelItem * >(idx.internalPointer()); if (!idx.isValid()) return QLatin1String("invIdx"); if (!item) @@ -415,10 +415,10 @@ QVariant UserModel::data(const QModelIndex &idx, int role) const { if (!idx.isValid()) return QVariant(); - ModelItem *item = static_cast<ModelItem *>(idx.internalPointer()); + ModelItem *item = static_cast< ModelItem * >(idx.internalPointer()); - Channel *c = item->cChan; - ClientUser *p = item->pUser; + Channel *c = item->cChan; + ClientUser *p = item->pUser; ClientUser *pSelf = ClientUser::get(g.uiSession); if (!c && !p) { @@ -429,7 +429,7 @@ QVariant UserModel::data(const QModelIndex &idx, int role) const { if (v.isValid()) return v; - QList<QVariant> l; + QList< QVariant > l; if (p) { switch (role) { @@ -466,7 +466,7 @@ QVariant UserModel::data(const QModelIndex &idx, int role) const { case Qt::FontRole: if ((idx.column() == 0) && (p->uiSession == g.uiSession)) { QFont f = g.mw->font(); - f.setBold(! f.bold()); + f.setBold(!f.bold()); f.setItalic(item->isListener); return f; } @@ -487,7 +487,7 @@ QVariant UserModel::data(const QModelIndex &idx, int role) const { // Most of the following icons are for non-listeners (as listeners are merely proxies) only // but in order to not change the order of the icons, the condition is added to each case // individually instead of checking it up front. - if (! p->qbaCommentHash.isEmpty() && !item->isListener) + if (!p->qbaCommentHash.isEmpty() && !item->isListener) l << (item->bCommentSeen ? qiCommentSeen : qiComment); if (p->bPrioritySpeaker && !item->isListener) l << qiPrioritySpeaker; @@ -514,7 +514,7 @@ QVariant UserModel::data(const QModelIndex &idx, int role) const { l << qiDeafenedSelf; if (p->iId >= 0 && !item->isListener) l << qiAuthenticated; - if (! p->qsFriendName.isEmpty() && !item->isListener) + if (!p->qsFriendName.isEmpty() && !item->isListener) l << qiFriend; return l; default: @@ -535,12 +535,12 @@ QVariant UserModel::data(const QModelIndex &idx, int role) const { break; case Qt::DisplayRole: if (idx.column() == 0) { - if (! g.s.bShowUserCount || item->iUsers == 0) + if (!g.s.bShowUserCount || item->iUsers == 0) return c->qsName; return QString::fromLatin1("%1 (%2)").arg(c->qsName).arg(item->iUsers); } - if (! c->qbaDescHash.isEmpty()) + if (!c->qbaDescHash.isEmpty()) l << (item->bCommentSeen ? qiCommentSeen : qiComment); if (c->bFiltered) @@ -562,9 +562,9 @@ QVariant UserModel::data(const QModelIndex &idx, int role) const { if ((c == home) || qsLinked.contains(c)) { QFont f = g.mw->font(); if (qsLinked.count() > 1) - f.setItalic(! f.italic()); + f.setItalic(!f.italic()); if (c == home) - f.setBold(! f.bold()); + f.setBold(!f.bold()); return f; } } @@ -594,97 +594,98 @@ Qt::ItemFlags UserModel::flags(const QModelIndex &idx) const { } QVariant UserModel::otherRoles(const QModelIndex &idx, int role) const { - ModelItem *item = static_cast<ModelItem *>(idx.internalPointer()); - ClientUser *p = item->pUser; - Channel *c = item->cChan; - int section = idx.column(); - bool isUser = p; + ModelItem *item = static_cast< ModelItem * >(idx.internalPointer()); + ClientUser *p = item->pUser; + Channel *c = item->cChan; + int section = idx.column(); + bool isUser = p; switch (role) { case Qt::ToolTipRole: - const_cast<UserModel *>(this)->uiSessionComment = 0; - const_cast<UserModel *>(this)->iChannelDescription = -1; - const_cast<UserModel *>(this)->bClicked = false; + const_cast< UserModel * >(this)->uiSessionComment = 0; + const_cast< UserModel * >(this)->iChannelDescription = -1; + const_cast< UserModel * >(this)->bClicked = false; switch (section) { case 0: { - if (isUser) { - QString qsImage; - if (! p->qbaTextureHash.isEmpty()) { + if (isUser) { + QString qsImage; + if (!p->qbaTextureHash.isEmpty()) { + if (p->qbaTexture.isEmpty()) { + p->qbaTexture = g.db->blob(p->qbaTextureHash); if (p->qbaTexture.isEmpty()) { - p->qbaTexture = g.db->blob(p->qbaTextureHash); - if (p->qbaTexture.isEmpty()) { - MumbleProto::RequestBlob mprb; - mprb.add_session_texture(p->uiSession); - g.sh->sendMessage(mprb); - } else { + MumbleProto::RequestBlob mprb; + mprb.add_session_texture(p->uiSession); + g.sh->sendMessage(mprb); + } else { #ifdef USE_OVERLAY - g.o->verifyTexture(p); + g.o->verifyTexture(p); #endif - } } - if (! p->qbaTexture.isEmpty()) { - QBuffer qb(&p->qbaTexture); - qb.open(QIODevice::ReadOnly); - QImageReader qir(&qb, p->qbaTextureFormat); - QSize sz = qir.size(); - if (sz.width() > 0) { - qsImage = QString::fromLatin1("<img src=\"data:;base64,"); - qsImage.append(QString::fromLatin1(p->qbaTexture.toBase64().toPercentEncoding())); - if (sz.width() > 128) { - int targ = sz.width() / ((sz.width()+127)/ 128); - qsImage.append(QString::fromLatin1("\" width=\"%1\" />").arg(targ)); - } else { - qsImage.append(QString::fromLatin1("\" />")); - } + } + if (!p->qbaTexture.isEmpty()) { + QBuffer qb(&p->qbaTexture); + qb.open(QIODevice::ReadOnly); + QImageReader qir(&qb, p->qbaTextureFormat); + QSize sz = qir.size(); + if (sz.width() > 0) { + qsImage = QString::fromLatin1("<img src=\"data:;base64,"); + qsImage.append(QString::fromLatin1(p->qbaTexture.toBase64().toPercentEncoding())); + if (sz.width() > 128) { + int targ = sz.width() / ((sz.width() + 127) / 128); + qsImage.append(QString::fromLatin1("\" width=\"%1\" />").arg(targ)); + } else { + qsImage.append(QString::fromLatin1("\" />")); } } } + } - if (p->qbaCommentHash.isEmpty()) { - if (! qsImage.isEmpty()) - return qsImage; - else - return p->qsName; - } else { + if (p->qbaCommentHash.isEmpty()) { + if (!qsImage.isEmpty()) + return qsImage; + else + return p->qsName; + } else { + if (p->qsComment.isEmpty()) { + p->qsComment = QString::fromUtf8(g.db->blob(p->qbaCommentHash)); if (p->qsComment.isEmpty()) { - p->qsComment = QString::fromUtf8(g.db->blob(p->qbaCommentHash)); - if (p->qsComment.isEmpty()) { - const_cast<UserModel *>(this)->uiSessionComment = p->uiSession; - - MumbleProto::RequestBlob mprb; - mprb.add_session_comment(p->uiSession); - g.sh->sendMessage(mprb); - return QVariant(); - } + const_cast< UserModel * >(this)->uiSessionComment = p->uiSession; + + MumbleProto::RequestBlob mprb; + mprb.add_session_comment(p->uiSession); + g.sh->sendMessage(mprb); + return QVariant(); } - const_cast<UserModel *>(this)->seenComment(idx); - QString base = Log::validHtml(p->qsComment); - if (! qsImage.isEmpty()) - return QString::fromLatin1("<table><tr><td valign=\"top\">%1</td><td>%2</td></tr></table>").arg(qsImage,base); - return base; } + const_cast< UserModel * >(this)->seenComment(idx); + QString base = Log::validHtml(p->qsComment); + if (!qsImage.isEmpty()) + return QString::fromLatin1( + "<table><tr><td valign=\"top\">%1</td><td>%2</td></tr></table>") + .arg(qsImage, base); + return base; + } + } else { + if (c->qbaDescHash.isEmpty()) { + return c->qsName; } else { - if (c->qbaDescHash.isEmpty()) { - return c->qsName; - } else { + if (c->qsDesc.isEmpty()) { + c->qsDesc = QString::fromUtf8(g.db->blob(c->qbaDescHash)); if (c->qsDesc.isEmpty()) { - c->qsDesc = QString::fromUtf8(g.db->blob(c->qbaDescHash)); - if (c->qsDesc.isEmpty()) { - const_cast<UserModel *>(this)->iChannelDescription = c->iId; - - MumbleProto::RequestBlob mprb; - mprb.add_channel_description(c->iId); - g.sh->sendMessage(mprb); - return QVariant(); - } - } + const_cast< UserModel * >(this)->iChannelDescription = c->iId; - const_cast<UserModel *>(this)->seenComment(idx); - return Log::validHtml(c->qsDesc); + MumbleProto::RequestBlob mprb; + mprb.add_channel_description(c->iId); + g.sh->sendMessage(mprb); + return QVariant(); + } } + + const_cast< UserModel * >(this)->seenComment(idx); + return Log::validHtml(c->qsDesc); } } - break; + } break; case 1: return isUser ? p->getFlagsString() : QVariant(); } @@ -694,79 +695,94 @@ QVariant UserModel::otherRoles(const QModelIndex &idx, int role) const { case 0: if (isUser) return QString::fromLatin1("%1" - "<table>" - "<tr><td><img src=\"skin:talking_on.svg\" height=64 /></td><td valign=\"middle\">%2</td></tr>" - "<tr><td><img src=\"skin:talking_alt.svg\" height=64 /></td><td valign=\"middle\">%3</td></tr>" - "<tr><td><img src=\"skin:talking_whisper.svg\" height=64 /></td><td valign=\"middle\">%4</td></tr>" - "<tr><td><img src=\"skin:talking_off.svg\" height=64 /></td><td valign=\"middle\">%5</td></tr>" - "</table>").arg(tr("This is a user connected to the server. The icon to the left of the user indicates whether or not they are talking:"), - tr("Talking to your channel."), - tr("Shouting directly to your channel."), - tr("Whispering directly to you."), - tr("Not talking.") - ); + "<table>" + "<tr><td><img src=\"skin:talking_on.svg\" height=64 /></td><td " + "valign=\"middle\">%2</td></tr>" + "<tr><td><img src=\"skin:talking_alt.svg\" height=64 /></td><td " + "valign=\"middle\">%3</td></tr>" + "<tr><td><img src=\"skin:talking_whisper.svg\" height=64 /></td><td " + "valign=\"middle\">%4</td></tr>" + "<tr><td><img src=\"skin:talking_off.svg\" height=64 /></td><td " + "valign=\"middle\">%5</td></tr>" + "</table>") + .arg(tr("This is a user connected to the server. The icon to the left of the user " + "indicates whether or not they are talking:"), + tr("Talking to your channel."), tr("Shouting directly to your channel."), + tr("Whispering directly to you."), tr("Not talking.")); else return QString::fromLatin1("%1" - "<table>" - "<tr><td><img src=\"skin:channel_active.svg\" height=64 /></td><td valign=\"middle\">%2</td></tr>" - "<tr><td><img src=\"skin:channel_linked.svg\" height=64 /></td><td valign=\"middle\">%3</td></tr>" - "<tr><td><img src=\"skin:channel.svg\" height=64 /></td><td valign=\"middle\">%4</td></tr>" - "</table>").arg(tr("This is a channel on the server. The icon indicates the state of the channel:"), - tr("Your current channel."), - tr("A channel that is linked with your channel. Linked channels can talk to each other."), - tr("A channel on the server that you are not linked to.") - ); + "<table>" + "<tr><td><img src=\"skin:channel_active.svg\" height=64 /></td><td " + "valign=\"middle\">%2</td></tr>" + "<tr><td><img src=\"skin:channel_linked.svg\" height=64 /></td><td " + "valign=\"middle\">%3</td></tr>" + "<tr><td><img src=\"skin:channel.svg\" height=64 /></td><td " + "valign=\"middle\">%4</td></tr>" + "</table>") + .arg(tr("This is a channel on the server. The icon indicates the state of the channel:"), + tr("Your current channel."), + tr("A channel that is linked with your channel. Linked channels can talk to each " + "other."), + tr("A channel on the server that you are not linked to.")); case 1: if (isUser) return QString::fromLatin1("%1" - "<table>" - "<tr><td><img src=\"skin:emblems/emblem-favorite.svg\" height=64 /></td><td valign=\"middle\">%2</td></tr>" - "<tr><td><img src=\"skin:authenticated.svg\" height=64 /></td><td valign=\"middle\">%3</td></tr>" - "<tr><td><img src=\"skin:muted_self.svg\" height=64 /></td><td valign=\"middle\">%4</td></tr>" - "<tr><td><img src=\"skin:muted_server.svg\" height=64 /></td><td valign=\"middle\">%5</td></tr>" - "<tr><td><img src=\"skin:muted_suppressed.svg\" height=64 /></td><td valign=\"middle\">%6</td></tr>" - "<tr><td><img src=\"skin:muted_local.svg\" height=64 /></td><td valign=\"middle\">%7</td></tr>" - "<tr><td><img src=\"skin:muted_pushtomute.svg\" height=64 /></td><td valign=\"middle\">%8</td></tr>" - "<tr><td><img src=\"skin:deafened_self.svg\" height=64 /></td><td valign=\"middle\">%9</td></tr>" - "<tr><td><img src=\"skin:deafened_server.svg\" height=64 /></td><td valign=\"middle\">%10</td></tr>" - "<tr><td><img src=\"skin:comment.svg\" height=64 /></td><td valign=\"middle\">%11</td></tr>" - "<tr><td><img src=\"skin:comment_seen.svg\" height=64 /></td><td valign=\"middle\">%12</td></tr>" - "<tr><td><img src=\"skin:status/text-missing.svg\" height=64 /></td><td valign=\"middle\">%13</td></tr>" - "</table>").arg(tr("This shows the flags the user has on the server, if any:"), - tr("On your friend list"), - tr("Authenticated user"), - tr("Muted (manually muted by self)"), - tr("Muted (manually muted by admin)"), - tr("Muted (not allowed to speak in current channel)"), - tr("Muted (muted by you, only on your machine)"), - tr("Muted (push-to-mute)") - ).arg( - tr("Deafened (by self)"), - tr("Deafened (by admin)"), - tr("User has a new comment set (click to show)"), - tr("User has a comment set, which you've already seen. (click to show)"), - tr("Ignoring Text Messages") - ); + "<table>" + "<tr><td><img src=\"skin:emblems/emblem-favorite.svg\" height=64 " + "/></td><td valign=\"middle\">%2</td></tr>" + "<tr><td><img src=\"skin:authenticated.svg\" height=64 /></td><td " + "valign=\"middle\">%3</td></tr>" + "<tr><td><img src=\"skin:muted_self.svg\" height=64 /></td><td " + "valign=\"middle\">%4</td></tr>" + "<tr><td><img src=\"skin:muted_server.svg\" height=64 /></td><td " + "valign=\"middle\">%5</td></tr>" + "<tr><td><img src=\"skin:muted_suppressed.svg\" height=64 " + "/></td><td valign=\"middle\">%6</td></tr>" + "<tr><td><img src=\"skin:muted_local.svg\" height=64 /></td><td " + "valign=\"middle\">%7</td></tr>" + "<tr><td><img src=\"skin:muted_pushtomute.svg\" height=64 " + "/></td><td valign=\"middle\">%8</td></tr>" + "<tr><td><img src=\"skin:deafened_self.svg\" height=64 /></td><td " + "valign=\"middle\">%9</td></tr>" + "<tr><td><img src=\"skin:deafened_server.svg\" height=64 /></td><td " + "valign=\"middle\">%10</td></tr>" + "<tr><td><img src=\"skin:comment.svg\" height=64 /></td><td " + "valign=\"middle\">%11</td></tr>" + "<tr><td><img src=\"skin:comment_seen.svg\" height=64 /></td><td " + "valign=\"middle\">%12</td></tr>" + "<tr><td><img src=\"skin:status/text-missing.svg\" height=64 " + "/></td><td valign=\"middle\">%13</td></tr>" + "</table>") + .arg(tr("This shows the flags the user has on the server, if any:"), + tr("On your friend list"), tr("Authenticated user"), + tr("Muted (manually muted by self)"), tr("Muted (manually muted by admin)"), + tr("Muted (not allowed to speak in current channel)"), + tr("Muted (muted by you, only on your machine)"), tr("Muted (push-to-mute)")) + .arg(tr("Deafened (by self)"), tr("Deafened (by admin)"), + tr("User has a new comment set (click to show)"), + tr("User has a comment set, which you've already seen. (click to show)"), + tr("Ignoring Text Messages")); else return QString::fromLatin1("%1" - "<table>" - "<tr><td><img src=\"skin:comment.svg\" height=64 /></td><td valign=\"middle\">%10</td></tr>" - "<tr><td><img src=\"skin:comment_seen.svg\" height=64 /></td><td valign=\"middle\">%11</td></tr>" - "<tr><td><img src=\"skin:filter.svg\" height=64 /></td><td valign=\"middle\">%12</td></tr>" - "</table>").arg(tr("This shows the flags the channel has, if any:"), - tr("Channel has a new comment set (click to show)"), - tr("Channel has a comment set, which you've already seen. (click to show)"), - tr("Channel will be hidden when filtering is enabled") - ); - + "<table>" + "<tr><td><img src=\"skin:comment.svg\" height=64 /></td><td " + "valign=\"middle\">%10</td></tr>" + "<tr><td><img src=\"skin:comment_seen.svg\" height=64 /></td><td " + "valign=\"middle\">%11</td></tr>" + "<tr><td><img src=\"skin:filter.svg\" height=64 /></td><td " + "valign=\"middle\">%12</td></tr>" + "</table>") + .arg(tr("This shows the flags the channel has, if any:"), + tr("Channel has a new comment set (click to show)"), + tr("Channel has a comment set, which you've already seen. (click to show)"), + tr("Channel will be hidden when filtering is enabled")); } break; } return QVariant(); } -QVariant UserModel::headerData(int section, Qt::Orientation orientation, - int role) const { +QVariant UserModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal) return QVariant(); @@ -789,10 +805,10 @@ void UserModel::recursiveClone(const ModelItem *old, ModelItem *item, QModelInde beginInsertRows(index(item), 0, old->qlChildren.count()); - for (int i=0;i<old->qlChildren.count();++i) { - ModelItem *o = old->qlChildren.at(i); + for (int i = 0; i < old->qlChildren.count(); ++i) { + ModelItem *o = old->qlChildren.at(i); ModelItem *mi = new ModelItem(o); - mi->parent = item; + mi->parent = item; item->qlChildren << mi; @@ -804,7 +820,7 @@ void UserModel::recursiveClone(const ModelItem *old, ModelItem *item, QModelInde endInsertRows(); - for (int i=0;i<old->qlChildren.count();++i) + for (int i = 0; i < old->qlChildren.count(); ++i) recursiveClone(old->qlChildren.at(i), item->qlChildren.at(i), from, to); } @@ -826,7 +842,7 @@ ModelItem *UserModel::moveItem(ModelItem *oldparent, ModelItem *newparent, Model if ((oldparent == newparent) && (newrow == oldrow)) { // This is a no-op. We still claim that the data has changed in order // to trigger potential event handlers. - emit dataChanged(index(oldItem),index(oldItem)); + emit dataChanged(index(oldItem), index(oldItem)); return oldItem; } @@ -840,8 +856,8 @@ ModelItem *UserModel::moveItem(ModelItem *oldparent, ModelItem *newparent, Model // Check whether the moved item is currently selected and if so, store it as a persistent // model index in active. Also clear the selection as we're going to mess with the active // item. - QTreeView *v=g.mw->qtvUsers; - QItemSelectionModel *sel=v->selectionModel(); + QTreeView *v = g.mw->qtvUsers; + QItemSelectionModel *sel = v->selectionModel(); QPersistentModelIndex active; QModelIndex oindex = createIndex(oldrow, 0, oldItem); if (sel->isSelected(oindex) || (oindex == v->currentIndex())) { @@ -928,13 +944,13 @@ ModelItem *UserModel::moveItem(ModelItem *oldparent, ModelItem *newparent, Model } void UserModel::expandAll(Channel *c) { - QStack<Channel *> chans; + QStack< Channel * > chans; while (c) { chans.push(c); c = c->cParent; } - while (! chans.isEmpty()) { + while (!chans.isEmpty()) { c = chans.pop(); g.mw->qtvUsers->setExpanded(index(c), true); } @@ -952,30 +968,30 @@ void UserModel::collapseEmpty(Channel *c) { } void UserModel::ensureSelfVisible() { - if (! g.uiSession) + if (!g.uiSession) return; g.mw->qtvUsers->scrollTo(index(ClientUser::get(g.uiSession))); } void UserModel::recheckLinks() { - if (! g.uiSession) + if (!g.uiSession) return; ClientUser *clientUser = ClientUser::get(g.uiSession); - if (! clientUser) + if (!clientUser) return; bool bChanged = false; Channel *home = clientUser->cChannel; - QSet<Channel *> all = home->allLinks(); + QSet< Channel * > all = home->allLinks(); if (all == qsLinked) return; - QSet<Channel *> changed = (all - qsLinked); + QSet< Channel * > changed = (all - qsLinked); changed += (qsLinked - all); if ((all.count() == 1) || (qsLinked.count() == 1)) @@ -983,7 +999,7 @@ void UserModel::recheckLinks() { qsLinked = all; - foreach(Channel *c, changed) { + foreach (Channel *c, changed) { QModelIndex idx = index(c); emit dataChanged(idx, idx); bChanged = true; @@ -994,7 +1010,7 @@ void UserModel::recheckLinks() { ClientUser *UserModel::addUser(unsigned int id, const QString &name) { ClientUser *p = ClientUser::add(id, this); - p->qsName = name; + p->qsName = name; ModelItem *item = new ModelItem(p); @@ -1003,7 +1019,7 @@ ClientUser *UserModel::addUser(unsigned int id, const QString &name) { connect(p, SIGNAL(prioritySpeakerStateChanged()), this, SLOT(userStateChanged())); connect(p, SIGNAL(recordingStateChanged()), this, SLOT(userStateChanged())); - Channel *c = Channel::get(0); + Channel *c = Channel::get(0); ModelItem *citem = ModelItem::c_qhChannels.value(c); item->parent = citem; @@ -1031,8 +1047,8 @@ void UserModel::removeUser(ClientUser *p) { if (g.uiSession && p->uiSession == g.uiSession) g.uiSession = 0; - Channel *c = p->cChannel; - ModelItem *item = ModelItem::c_qhUsers.value(p); + Channel *c = p->cChannel; + ModelItem *item = ModelItem::c_qhUsers.value(p); ModelItem *citem = ModelItem::c_qhChannels.value(c); int row = citem->qlChildren.indexOf(item); @@ -1062,9 +1078,9 @@ void UserModel::removeUser(ClientUser *p) { } void UserModel::moveUser(ClientUser *p, Channel *np) { - Channel *oc = p->cChannel; - ModelItem *opi = ModelItem::c_qhChannels.value(oc); - ModelItem *pi = ModelItem::c_qhChannels.value(np); + Channel *oc = p->cChannel; + ModelItem *opi = ModelItem::c_qhChannels.value(oc); + ModelItem *pi = ModelItem::c_qhChannels.value(np); ModelItem *item = ModelItem::c_qhUsers.value(p); item = moveItem(opi, pi, item); @@ -1093,9 +1109,9 @@ void UserModel::moveUser(ClientUser *p, Channel *np) { void UserModel::renameUser(ClientUser *p, const QString &name) { Channel *c = p->cChannel; - p->qsName = name; + p->qsName = name; - ModelItem *pi = ModelItem::c_qhChannels.value(c); + ModelItem *pi = ModelItem::c_qhChannels.value(c); ModelItem *item = ModelItem::c_qhUsers.value(p); moveItem(pi, pi, item); @@ -1103,13 +1119,13 @@ void UserModel::renameUser(ClientUser *p, const QString &name) { } void UserModel::setUserId(ClientUser *p, int id) { - p->iId = id; + p->iId = id; QModelIndex idx = index(p, 0); emit dataChanged(idx, idx); } void UserModel::setHash(ClientUser *p, const QString &hash) { - if (! p->qsHash.isEmpty()) + if (!p->qsHash.isEmpty()) qmHashes.remove(p->qsHash); p->qsHash = hash; @@ -1127,19 +1143,20 @@ void UserModel::setComment(ClientUser *cu, const QString &comment) { if (comment != cu->qsComment) { ModelItem *item = ModelItem::c_qhUsers.value(cu); - int oldstate = (cu->qsComment.isEmpty() && cu->qbaCommentHash.isEmpty()) ? 0 : (item->bCommentSeen ? 2 : 1); - int newstate = 0; + int oldstate = (cu->qsComment.isEmpty() && cu->qbaCommentHash.isEmpty()) ? 0 : (item->bCommentSeen ? 2 : 1); + int newstate = 0; cu->qsComment = comment; - if (! comment.isEmpty()) { + if (!comment.isEmpty()) { g.db->setBlob(cu->qbaCommentHash, cu->qsComment.toUtf8()); if (cu->uiSession == uiSessionComment) { - uiSessionComment = 0; + uiSessionComment = 0; item->bCommentSeen = false; if (bClicked) { QRect r = g.mw->qtvUsers->visualRect(index(cu)); - QWhatsThis::showText(g.mw->qtvUsers->viewport()->mapToGlobal(r.bottomRight()), data(index(cu, 0), Qt::ToolTipRole).toString(), g.mw->qtvUsers); + QWhatsThis::showText(g.mw->qtvUsers->viewport()->mapToGlobal(r.bottomRight()), + data(index(cu, 0), Qt::ToolTipRole).toString(), g.mw->qtvUsers); } else { QToolTip::showText(QCursor::pos(), data(index(cu, 0), Qt::ToolTipRole).toString(), g.mw->qtvUsers); } @@ -1153,7 +1170,7 @@ void UserModel::setComment(ClientUser *cu, const QString &comment) { } } else { item->bCommentSeen = g.db->seenComment(item->hash(), cu->qbaCommentHash); - newstate = item->bCommentSeen ? 2 : 1; + newstate = item->bCommentSeen ? 2 : 1; } } else { item->bCommentSeen = true; @@ -1169,14 +1186,14 @@ void UserModel::setComment(ClientUser *cu, const QString &comment) { void UserModel::setCommentHash(ClientUser *cu, const QByteArray &hash) { if (hash != cu->qbaCommentHash) { ModelItem *item = ModelItem::c_qhUsers.value(cu); - int oldstate = (cu->qsComment.isEmpty() && cu->qbaCommentHash.isEmpty()) ? 0 : (item->bCommentSeen ? 2 : 1); + int oldstate = (cu->qsComment.isEmpty() && cu->qbaCommentHash.isEmpty()) ? 0 : (item->bCommentSeen ? 2 : 1); int newstate; - cu->qsComment = QString(); + cu->qsComment = QString(); cu->qbaCommentHash = hash; item->bCommentSeen = g.db->seenComment(item->hash(), cu->qbaCommentHash); - newstate = item->bCommentSeen ? 2 : 1; + newstate = item->bCommentSeen ? 2 : 1; if (oldstate != newstate) { QModelIndex idx = index(cu, 0); @@ -1190,26 +1207,27 @@ void UserModel::setComment(Channel *c, const QString &comment) { if (comment != c->qsDesc) { ModelItem *item = ModelItem::c_qhChannels.value(c); - int oldstate = c->qsDesc.isEmpty() ? 0 : (item->bCommentSeen ? 2 : 1); - int newstate = 0; + int oldstate = c->qsDesc.isEmpty() ? 0 : (item->bCommentSeen ? 2 : 1); + int newstate = 0; c->qsDesc = comment; - if (! comment.isEmpty()) { + if (!comment.isEmpty()) { g.db->setBlob(c->qbaDescHash, c->qsDesc.toUtf8()); if (c->iId == iChannelDescription) { iChannelDescription = -1; - item->bCommentSeen = false; + item->bCommentSeen = false; if (bClicked) { QRect r = g.mw->qtvUsers->visualRect(index(c)); - QWhatsThis::showText(g.mw->qtvUsers->viewport()->mapToGlobal(r.bottomRight()), data(index(c, 0), Qt::ToolTipRole).toString(), g.mw->qtvUsers); + QWhatsThis::showText(g.mw->qtvUsers->viewport()->mapToGlobal(r.bottomRight()), + data(index(c, 0), Qt::ToolTipRole).toString(), g.mw->qtvUsers); } else { QToolTip::showText(QCursor::pos(), data(index(c, 0), Qt::ToolTipRole).toString(), g.mw->qtvUsers); } } else { item->bCommentSeen = g.db->seenComment(item->hash(), c->qbaDescHash); - newstate = item->bCommentSeen ? 2 : 1; + newstate = item->bCommentSeen ? 2 : 1; } } else { item->bCommentSeen = true; @@ -1225,14 +1243,14 @@ void UserModel::setComment(Channel *c, const QString &comment) { void UserModel::setCommentHash(Channel *c, const QByteArray &hash) { if (hash != c->qbaDescHash) { ModelItem *item = ModelItem::c_qhChannels.value(c); - int oldstate = (c->qsDesc.isEmpty() && c->qbaDescHash.isEmpty()) ? 0 : (item->bCommentSeen ? 2 : 1); + int oldstate = (c->qsDesc.isEmpty() && c->qbaDescHash.isEmpty()) ? 0 : (item->bCommentSeen ? 2 : 1); int newstate; - c->qsDesc = QString(); + c->qsDesc = QString(); c->qbaDescHash = hash; item->bCommentSeen = g.db->seenComment(item->hash(), hash); - newstate = item->bCommentSeen ? 2 : 1; + newstate = item->bCommentSeen ? 2 : 1; if (oldstate != newstate) { QModelIndex idx = index(c, 0); @@ -1243,7 +1261,7 @@ void UserModel::setCommentHash(Channel *c, const QByteArray &hash) { void UserModel::seenComment(const QModelIndex &idx) { ModelItem *item; - item = static_cast<ModelItem *>(idx.internalPointer()); + item = static_cast< ModelItem * >(idx.internalPointer()); if (item->bCommentSeen) return; @@ -1265,8 +1283,8 @@ void UserModel::renameChannel(Channel *c, const QString &name) { QModelIndex idx = index(c); emit dataChanged(idx, idx); } else { - Channel *pc = c->cParent; - ModelItem *pi = ModelItem::c_qhChannels.value(pc); + Channel *pc = c->cParent; + ModelItem *pi = ModelItem::c_qhChannels.value(pc); ModelItem *item = ModelItem::c_qhChannels.value(c); moveItem(pi, pi, item); @@ -1280,8 +1298,8 @@ void UserModel::repositionChannel(Channel *c, const int position) { QModelIndex idx = index(c); emit dataChanged(idx, idx); } else { - Channel *pc = c->cParent; - ModelItem *pi = ModelItem::c_qhChannels.value(pc); + Channel *pc = c->cParent; + ModelItem *pi = ModelItem::c_qhChannels.value(pc); ModelItem *item = ModelItem::c_qhChannels.value(c); moveItem(pi, pi, item); @@ -1291,10 +1309,10 @@ void UserModel::repositionChannel(Channel *c, const int position) { Channel *UserModel::addChannel(int id, Channel *p, const QString &name) { Channel *c = Channel::add(id, name); - if (! c) + if (!c) return nullptr; - ModelItem *item = new ModelItem(c); + ModelItem *item = new ModelItem(c); ModelItem *citem = ModelItem::c_qhChannels.value(p); item->parent = citem; @@ -1313,7 +1331,7 @@ Channel *UserModel::addChannel(int id, Channel *p, const QString &name) { } void UserModel::addChannelListener(ClientUser *p, Channel *c) { - ModelItem *item = new ModelItem(p, true); + ModelItem *item = new ModelItem(p, true); ModelItem *citem = ModelItem::c_qhChannels.value(c); item->parent = citem; @@ -1337,7 +1355,7 @@ void UserModel::removeChannelListener(const ClientUser *p, const Channel *c) { // object first, before returning a reference to it, in case there is no entry for // the provided key yet. Thus we never have to worry about explicitly adding an empty // list for a new user before accessing it. - const QList<ModelItem *> &items = ModelItem::s_userProxies[p]; + const QList< ModelItem * > &items = ModelItem::s_userProxies[p]; if (items.isEmpty()) { return; @@ -1361,9 +1379,7 @@ void UserModel::removeChannelListener(const ClientUser *p, const Channel *c) { } } else { // remove all items - foreach(ModelItem *currentItem, items) { - removeChannelListener(currentItem); - } + foreach (ModelItem *currentItem, items) { removeChannelListener(currentItem); } } } @@ -1373,7 +1389,7 @@ bool UserModel::isChannelListener(const QModelIndex &idx) const { } ModelItem *item; - item = static_cast<ModelItem *>(idx.internalPointer()); + item = static_cast< ModelItem * >(idx.internalPointer()); return item->isListener; } @@ -1406,7 +1422,7 @@ void UserModel::removeChannelListener(ModelItem *item, ModelItem *citem) { } ClientUser *p = item->pUser; - Channel *c = citem->cChan; + Channel *c = citem->cChan; if (!p) { qCritical("UserModel::removeChannelListener: Can't find associated ClientUser"); @@ -1438,10 +1454,11 @@ void UserModel::removeChannelListener(ModelItem *item, ModelItem *citem) { bool UserModel::removeChannel(Channel *c, const bool onlyIfUnoccupied) { const ModelItem *item = ModelItem::c_qhChannels.value(c); - - if (onlyIfUnoccupied && item->iUsers !=0) return false; // Checks full hierarchy - foreach(const ModelItem *i, item->qlChildren) { + if (onlyIfUnoccupied && item->iUsers != 0) + return false; // Checks full hierarchy + + foreach (const ModelItem *i, item->qlChildren) { if (i->pUser) { if (i->isListener) { removeChannelListener(i->pUser, c); @@ -1455,7 +1472,7 @@ bool UserModel::removeChannel(Channel *c, const bool onlyIfUnoccupied) { Channel *p = c->cParent; - if (! p) + if (!p) return true; ModelItem *citem = ModelItem::c_qhChannels.value(p); @@ -1476,11 +1493,11 @@ bool UserModel::removeChannel(Channel *c, const bool onlyIfUnoccupied) { } void UserModel::moveChannel(Channel *c, Channel *p) { - Channel *oc = c->cParent; - ModelItem *opi = ModelItem::c_qhChannels.value(c->cParent); - ModelItem *pi = ModelItem::c_qhChannels.value(p); + Channel *oc = c->cParent; + ModelItem *opi = ModelItem::c_qhChannels.value(c->cParent); + ModelItem *pi = ModelItem::c_qhChannels.value(p); ModelItem *item = ModelItem::c_qhChannels.value(c); - item = moveItem(opi, pi, item); + item = moveItem(opi, pi, item); while (opi) { opi->iUsers -= item->iUsers; @@ -1498,14 +1515,14 @@ void UserModel::moveChannel(Channel *c, Channel *p) { } } -void UserModel::linkChannels(Channel *c, QList<Channel *> links) { - foreach(Channel *l, links) +void UserModel::linkChannels(Channel *c, QList< Channel * > links) { + foreach (Channel *l, links) c->link(l); recheckLinks(); } -void UserModel::unlinkChannels(Channel *c, QList<Channel *> links) { - foreach(Channel *l, links) +void UserModel::unlinkChannels(Channel *c, QList< Channel * > links) { + foreach (Channel *l, links) c->unlink(l); recheckLinks(); } @@ -1519,18 +1536,18 @@ void UserModel::removeAll() { ModelItem *item = miRoot; ModelItem *i; - uiSessionComment = 0; + uiSessionComment = 0; iChannelDescription = -1; - bClicked = false; + bClicked = false; // in order to avoid complications, we remove all ChannelListeners first - foreach(i, item->qlChildren) { + foreach (i, item->qlChildren) { if (i->pUser && i->isListener) { removeChannelListener(i, item); } } - foreach(i, item->qlChildren) { + foreach (i, item->qlChildren) { if (i->pUser) removeUser(i->pUser); else @@ -1543,11 +1560,11 @@ void UserModel::removeAll() { } ClientUser *UserModel::getUser(const QModelIndex &idx) const { - if (! idx.isValid()) + if (!idx.isValid()) return nullptr; ModelItem *item; - item = static_cast<ModelItem *>(idx.internalPointer()); + item = static_cast< ModelItem * >(idx.internalPointer()); return item->pUser; } @@ -1560,7 +1577,7 @@ ClientUser *UserModel::getSelectedUser() const { QModelIndex selected = getSelectedIndex(); if (selected.isValid()) { - ModelItem *item = static_cast<ModelItem *>(selected.internalPointer()); + ModelItem *item = static_cast< ModelItem * >(selected.internalPointer()); return item->pUser; } @@ -1582,11 +1599,11 @@ void UserModel::setSelectedUser(unsigned int session) { } Channel *UserModel::getChannel(const QModelIndex &idx) const { - if (! idx.isValid()) + if (!idx.isValid()) return nullptr; ModelItem *item; - item = static_cast<ModelItem *>(idx.internalPointer()); + item = static_cast< ModelItem * >(idx.internalPointer()); if (item->pUser) if (item->parent && item->parent->cChan) { @@ -1604,7 +1621,7 @@ Channel *UserModel::getSelectedChannel() const { QModelIndex selected = getSelectedIndex(); if (selected.isValid()) { - ModelItem *item = static_cast<ModelItem *>(selected.internalPointer()); + ModelItem *item = static_cast< ModelItem * >(selected.internalPointer()); return item->cChan; } @@ -1626,11 +1643,11 @@ void UserModel::setSelectedChannel(int id) { } Channel *UserModel::getSubChannel(Channel *p, int idx) const { - ModelItem *item=ModelItem::c_qhChannels.value(p); - if (! item) + ModelItem *item = ModelItem::c_qhChannels.value(p); + if (!item) return nullptr; - foreach(ModelItem *i, item->qlChildren) { + foreach (ModelItem *i, item->qlChildren) { if (i->cChan) { if (idx == 0) return i->cChan; @@ -1641,19 +1658,19 @@ Channel *UserModel::getSubChannel(Channel *p, int idx) const { } void UserModel::userStateChanged() { - ClientUser *user = qobject_cast<ClientUser *>(sender()); + ClientUser *user = qobject_cast< ClientUser * >(sender()); if (!user) return; const QModelIndex idx = index(user); emit dataChanged(idx, idx); - + updateOverlay(); } void UserModel::toggleChannelFiltered(Channel *c) { QModelIndex idx; - if(c) { + if (c) { c->bFiltered = !c->bFiltered; ServerHandlerPtr sh = g.sh; @@ -1681,9 +1698,9 @@ QMimeData *UserModel::mimeData(const QModelIndexList &idxs) const { QByteArray qba; QDataStream ds(&qba, QIODevice::WriteOnly); - foreach(idx, idxs) { + foreach (idx, idxs) { ClientUser *p = getUser(idx); - Channel *c = getChannel(idx); + Channel *c = getChannel(idx); if (p) { ds << false; ds << p->uiSession; @@ -1700,14 +1717,14 @@ QMimeData *UserModel::mimeData(const QModelIndexList &idxs) const { bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int column, const QModelIndex &p) { #define NAMECMPCHANNEL(first, second) (QString::localeAwareCompare(first->qsName, second->qsName) > 0) - if (! md->hasFormat(mimeTypes().at(0))) + if (!md->hasFormat(mimeTypes().at(0))) return false; QByteArray qba = md->data(mimeTypes().at(0)); QDataStream ds(qba); bool isChannel; - int iId = -1; + int iId = -1; unsigned int uiSession = 0; ds >> isChannel; @@ -1717,29 +1734,32 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c ds >> uiSession; Channel *c; - if (! p.isValid()) { + if (!p.isValid()) { c = Channel::get(0); } else { c = getChannel(p); } - if (! c) + if (!c) return false; expandAll(c); - if (! isChannel) { + if (!isChannel) { // User dropped somewhere int ret; switch (g.s.ceUserDrag) { case Settings::Ask: - ret=QMessageBox::question(g.mw, QLatin1String("Mumble"), tr("Are you sure you want to drag this user?"), QMessageBox::Yes, QMessageBox::No); + ret = + QMessageBox::question(g.mw, QLatin1String("Mumble"), tr("Are you sure you want to drag this user?"), + QMessageBox::Yes, QMessageBox::No); if (ret == QMessageBox::No) return false; break; case Settings::DoNothing: - g.l->log(Log::Information, MainWindow::tr("You have User Dragging set to \"Do Nothing\" so the user wasn't moved.")); + g.l->log(Log::Information, + MainWindow::tr("You have User Dragging set to \"Do Nothing\" so the user wasn't moved.")); return false; break; case Settings::Move: @@ -1754,13 +1774,17 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c int ret; switch (g.s.ceChannelDrag) { case Settings::Ask: - ret=QMessageBox::question(g.mw, QLatin1String("Mumble"), tr("Are you sure you want to drag this channel?"), QMessageBox::Yes, QMessageBox::No); + ret = QMessageBox::question(g.mw, QLatin1String("Mumble"), + tr("Are you sure you want to drag this channel?"), QMessageBox::Yes, + QMessageBox::No); if (ret == QMessageBox::No) return false; break; case Settings::DoNothing: - g.l->log(Log::Information, MainWindow::tr("You have Channel Dragging set to \"Do Nothing\" so the channel wasn't moved.")); + g.l->log( + Log::Information, + MainWindow::tr("You have Channel Dragging set to \"Do Nothing\" so the channel wasn't moved.")); return false; break; case Settings::Move: @@ -1772,22 +1796,24 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c } long long inewpos = 0; - Channel *dropped = Channel::c_qhChannels.value(iId); + Channel *dropped = Channel::c_qhChannels.value(iId); - if (! dropped) + if (!dropped) return false; if (p.isValid()) { - ModelItem *pi = static_cast<ModelItem *>(p.internalPointer()); + ModelItem *pi = static_cast< ModelItem * >(p.internalPointer()); if (pi->pUser) pi = pi->parent; int ifirst = 0; - int ilast = pi->rows() - 1; + int ilast = pi->rows() - 1; if (ilast > 0) { - while (pi->userAt(ifirst) && ifirst < ilast) ifirst++; - while (pi->userAt(ilast) && ilast > 0) ilast--; + while (pi->userAt(ifirst) && ifirst < ilast) + ifirst++; + while (pi->userAt(ilast) && ilast > 0) + ilast--; } if (row == -1 && column == -1) { @@ -1797,17 +1823,19 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c if (ilast > 0) { if (pi->bUsersTop) { if (pi->channelAt(ifirst) == dropped || NAMECMPCHANNEL(pi->channelAt(ifirst), dropped)) { - if (dropped->iPosition == pi->channelAt(ifirst)->iPosition) return true; + if (dropped->iPosition == pi->channelAt(ifirst)->iPosition) + return true; inewpos = pi->channelAt(ifirst)->iPosition; } else { - inewpos = static_cast<long long>(pi->channelAt(ifirst)->iPosition) - 20; + inewpos = static_cast< long long >(pi->channelAt(ifirst)->iPosition) - 20; } } else { if (dropped == pi->channelAt(ilast) || NAMECMPCHANNEL(dropped, pi->channelAt(ilast))) { - if (pi->channelAt(ilast)->iPosition == dropped->iPosition) return true; + if (pi->channelAt(ilast)->iPosition == dropped->iPosition) + return true; inewpos = pi->channelAt(ilast)->iPosition; } else { - inewpos = static_cast<long long>(pi->channelAt(ilast)->iPosition) + 20; + inewpos = static_cast< long long >(pi->channelAt(ilast)->iPosition) + 20; } } } @@ -1818,24 +1846,27 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c // No channels in there yet } else if (row <= ifirst) { if (pi->channelAt(ifirst) == dropped || NAMECMPCHANNEL(pi->channelAt(ifirst), dropped)) { - if (dropped->iPosition == pi->channelAt(ifirst)->iPosition) return true; + if (dropped->iPosition == pi->channelAt(ifirst)->iPosition) + return true; inewpos = pi->channelAt(ifirst)->iPosition; } else { - inewpos = static_cast<long long>(pi->channelAt(ifirst)->iPosition) - 20; + inewpos = static_cast< long long >(pi->channelAt(ifirst)->iPosition) - 20; } } else if (row > ilast) { if (dropped == pi->channelAt(ilast) || NAMECMPCHANNEL(dropped, pi->channelAt(ilast))) { - if (pi->channelAt(ilast)->iPosition == dropped->iPosition) return true; + if (pi->channelAt(ilast)->iPosition == dropped->iPosition) + return true; inewpos = pi->channelAt(ilast)->iPosition; } else { - inewpos = static_cast<long long>(pi->channelAt(ilast)->iPosition) + 20; + inewpos = static_cast< long long >(pi->channelAt(ilast)->iPosition) + 20; } } else { // Dropped between channels Channel *lower = pi->channelAt(row); Channel *upper = pi->channelAt(row - 1); - if (lower->iPosition == upper->iPosition && NAMECMPCHANNEL(lower, dropped) && NAMECMPCHANNEL(dropped, upper)) { + if (lower->iPosition == upper->iPosition && NAMECMPCHANNEL(lower, dropped) + && NAMECMPCHANNEL(dropped, upper)) { inewpos = upper->iPosition; } else if (lower->iPosition > upper->iPosition && NAMECMPCHANNEL(lower, dropped)) { inewpos = lower->iPosition; @@ -1844,11 +1875,13 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c } else if (lower == dropped || upper == dropped) { return true; } else if (abs(lower->iPosition) - abs(upper->iPosition) > 1) { - inewpos = upper->iPosition + (abs(lower->iPosition) - abs(upper->iPosition))/2; + inewpos = upper->iPosition + (abs(lower->iPosition) - abs(upper->iPosition)) / 2; } else { // Not enough space, other channels have to be moved - if (static_cast<long long>(pi->channelAt(ilast)->iPosition) + 40 > INT_MAX) { - QMessageBox::critical(g.mw, QLatin1String("Mumble"), tr("Cannot perform this movement automatically, please reset the numeric sorting indicators or adjust it manually.")); + if (static_cast< long long >(pi->channelAt(ilast)->iPosition) + 40 > INT_MAX) { + QMessageBox::critical(g.mw, QLatin1String("Mumble"), + tr("Cannot perform this movement automatically, please reset the " + "numeric sorting indicators or adjust it manually.")); return false; } for (int i = row; i <= ilast; i++) { @@ -1858,7 +1891,6 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c mpcs.set_channel_id(tmp->iId); mpcs.set_position(tmp->iPosition + 40); g.sh->sendMessage(mpcs); - } } inewpos = upper->iPosition + 20; @@ -1868,7 +1900,9 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c } if (inewpos > INT_MAX || inewpos < INT_MIN) { - QMessageBox::critical(g.mw, QLatin1String("Mumble"), tr("Cannot perform this movement automatically, please reset the numeric sorting indicators or adjust it manually.")); + QMessageBox::critical(g.mw, QLatin1String("Mumble"), + tr("Cannot perform this movement automatically, please reset the numeric sorting " + "indicators or adjust it manually.")); return false; } @@ -1876,7 +1910,7 @@ bool UserModel::dropMimeData(const QMimeData *md, Qt::DropAction, int row, int c mpcs.set_channel_id(iId); if (dropped->parent() != c) mpcs.set_parent(c->iId); - mpcs.set_position(static_cast<int>(inewpos)); + mpcs.set_position(static_cast< int >(inewpos)); g.sh->sendMessage(mpcs); } @@ -1892,11 +1926,12 @@ void UserModel::updateOverlay() const { QString UserModel::createDisplayString(const ClientUser &user, bool isChannelListener, const Channel *parentChannel) { - // Get the configured volume adjustment. Depending on whether + // Get the configured volume adjustment. Depending on whether // this display string is for a ChannelListener or a regular user, we have to fetch // the volume adjustment differently. float volumeAdjustment = isChannelListener && parentChannel - ? ChannelListener::getListenerLocalVolumeAdjustment(parentChannel->iId) : user.getLocalVolumeAdjustments(); + ? ChannelListener::getListenerLocalVolumeAdjustment(parentChannel->iId) + : user.getLocalVolumeAdjustments(); // Transform the adjustment into dB // *2 == 6 dB diff --git a/src/mumble/UserModel.h b/src/mumble/UserModel.h index 8b658a4b8..07de425b7 100644 --- a/src/mumble/UserModel.h +++ b/src/mumble/UserModel.h @@ -30,14 +30,14 @@ public: bool bCommentSeen; ModelItem *parent; - QList<ModelItem *> qlChildren; - QList<ModelItem *> qlHiddenChildren; + QList< ModelItem * > qlChildren; + QList< ModelItem * > qlHiddenChildren; /// Number of users in this channel (recursive) int iUsers; - static QHash <const Channel *, ModelItem *> c_qhChannels; - static QHash <const ClientUser *, ModelItem *> c_qhUsers; - static QHash <const ClientUser *, QList<ModelItem *>> s_userProxies; + static QHash< const Channel *, ModelItem * > c_qhChannels; + static QHash< const ClientUser *, ModelItem * > c_qhUsers; + static QHash< const ClientUser *, QList< ModelItem * > > s_userProxies; static bool bUsersTop; ModelItem(Channel *c); @@ -61,154 +61,157 @@ public: }; class UserModel : public QAbstractItemModel { - friend struct ModelItem; - friend class UserView; - private: - Q_OBJECT - Q_DISABLE_COPY(UserModel) - protected: - QIcon qiTalkingOn, qiTalkingMuted, qiTalkingWhisper, qiTalkingShout, qiTalkingOff; - QIcon qiMutedPushToMute, qiMutedSelf, qiMutedServer, qiMutedLocal, qiIgnoredLocal, qiMutedSuppressed; - QIcon qiPrioritySpeaker; - QIcon qiRecording; - QIcon qiDeafenedSelf, qiDeafenedServer; - QIcon qiAuthenticated, qiChannel, qiLinkedChannel, qiActiveChannel; - QIcon qiFriend; - QIcon qiComment, qiCommentSeen, qiFilter; - QIcon qiLock_locked, qiLock_unlocked; - QIcon qiEar; - ModelItem *miRoot; - QSet<Channel *> qsLinked; - QMap<QString, ClientUser *> qmHashes; - - bool bClicked; - - void recursiveClone(const ModelItem *old, ModelItem *item, QModelIndexList &from, QModelIndexList &to); - ModelItem *moveItem(ModelItem *oldparent, ModelItem *newparent, ModelItem *item); - - QString stringIndex(const QModelIndex &index) const; - - /// @returns The QModelIndex that is currently selected. If there is no selection, the returned index - /// is invalid. - QModelIndex getSelectedIndex() const; - - /// Removes the given user as a listener to the given channel - /// - /// @param item A pointer to the listener's ModelItem that shall be removed - /// @param citem A pointer to the ModelItem that represents the channel the listener - /// is in. The listener has to be a direct child of this item. If this is nullptr, - /// the parent of the provided item is used directly. - void removeChannelListener(ModelItem *item, ModelItem *citem = nullptr); - public: - UserModel(QObject *parent = 0); - ~UserModel() Q_DECL_OVERRIDE; - - QModelIndex index(ClientUser *, int column = 0) const; - QModelIndex index(Channel *, int column = 0) const; - QModelIndex index(ModelItem *) const; - QModelIndex channelListenerIndex(const ClientUser *, const Channel *, int column = 0) const; - - QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE; - int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - Qt::DropActions supportedDropActions() const Q_DECL_OVERRIDE; - QStringList mimeTypes() const Q_DECL_OVERRIDE; - QMimeData *mimeData(const QModelIndexList &idx) const Q_DECL_OVERRIDE; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex & parent) Q_DECL_OVERRIDE; - - ClientUser *addUser(unsigned int id, const QString &name); - ClientUser *getUser(const QModelIndex &idx) const; - ClientUser *getUser(const QString &hash) const; - /// @returns A pointer to the currently selected User or nullptr if there is none - ClientUser *getSelectedUser() const; - /// Sets the selection to the User with the given session - /// - /// @param session The session ID of the respective User - void setSelectedUser(unsigned int session); - - Channel *addChannel(int id, Channel *p, const QString &name); - Channel *getChannel(const QModelIndex &idx) const; - /// @returns A pointer to the currently selected Channel or nullptr if there is none - Channel *getSelectedChannel() const; - /// Sets the selection to the Channel with the given ID - /// - /// @param session The ID of the respective Channel - void setSelectedChannel(int id); - - /// Adds the guven user as a listener to the given channel - /// - /// @param p A pointer to the user - /// @param c A pointer to the channel - void addChannelListener(ClientUser *p, Channel *c); - /// Removes the guven user as a listener to the given channel - /// - /// @param p A pointer to the user - /// @param c A pointer to the channel. If this is nullptr, then all listeners - /// for the given user are removed (from all channels). - void removeChannelListener(const ClientUser *p, const Channel *c = nullptr); - /// @param idx The QModelIndex to check - /// @returns Whether the ModelItem associated with the given index is a listener-proxy - bool isChannelListener(const QModelIndex &idx) const; - - /// Sets the selection to the ChannelListener of the given user in the given channel - /// - /// @param userSession The session ID of the respective User - /// @param channelID The ID of the respective Channel - void setSelectedChannelListener(unsigned int userSession, int channelID); - - Channel *getSubChannel(Channel *p, int idx) const; - - void renameUser(ClientUser *p, const QString &name); - void renameChannel(Channel *c, const QString &name); - void repositionChannel(Channel *c, const int position); - void setUserId(ClientUser *p, int id); - void setHash(ClientUser *p, const QString &hash); - void setFriendName(ClientUser *p, const QString &name); - void setComment(ClientUser *p, const QString &comment); - void setCommentHash(ClientUser *p, const QByteArray &hash); - void seenComment(const QModelIndex &idx); - - void moveUser(ClientUser *p, Channel *c); - void moveChannel(Channel *c, Channel *p); - void setComment(Channel *c, const QString &comment); - void setCommentHash(Channel *c, const QByteArray &hash); - - void removeUser(ClientUser *p); - bool removeChannel(Channel *c, const bool onlyIfUnoccupied = false); - - void linkChannels(Channel *c, QList<Channel *> links); - void unlinkChannels(Channel *c, QList<Channel *> links); - void unlinkAll(Channel *c); - - void removeAll(); - - void expandAll(Channel *c); - void collapseEmpty(Channel *c); - - QVariant otherRoles(const QModelIndex &idx, int role) const; - - unsigned int uiSessionComment; - int iChannelDescription; - - - /// Creates the display string for the given user/listener - /// - /// @param user The user to create the string for - /// @param isChannelListener Whether the display String is in fact for a listener of the given user - /// @param parentChannel The channel in which the listener resides. May be nullptr, if isChannelListener is false - /// @return The created display string - static QString createDisplayString(const ClientUser &user, bool isChannelListener, const Channel *parentChannel); - public slots: - /// Invalidates the model data of the ClientUser triggering this slot. - void userStateChanged(); - void ensureSelfVisible(); - void recheckLinks(); - void updateOverlay() const; - void toggleChannelFiltered(Channel *c); + friend struct ModelItem; + friend class UserView; + +private: + Q_OBJECT + Q_DISABLE_COPY(UserModel) +protected: + QIcon qiTalkingOn, qiTalkingMuted, qiTalkingWhisper, qiTalkingShout, qiTalkingOff; + QIcon qiMutedPushToMute, qiMutedSelf, qiMutedServer, qiMutedLocal, qiIgnoredLocal, qiMutedSuppressed; + QIcon qiPrioritySpeaker; + QIcon qiRecording; + QIcon qiDeafenedSelf, qiDeafenedServer; + QIcon qiAuthenticated, qiChannel, qiLinkedChannel, qiActiveChannel; + QIcon qiFriend; + QIcon qiComment, qiCommentSeen, qiFilter; + QIcon qiLock_locked, qiLock_unlocked; + QIcon qiEar; + ModelItem *miRoot; + QSet< Channel * > qsLinked; + QMap< QString, ClientUser * > qmHashes; + + bool bClicked; + + void recursiveClone(const ModelItem *old, ModelItem *item, QModelIndexList &from, QModelIndexList &to); + ModelItem *moveItem(ModelItem *oldparent, ModelItem *newparent, ModelItem *item); + + QString stringIndex(const QModelIndex &index) const; + + /// @returns The QModelIndex that is currently selected. If there is no selection, the returned index + /// is invalid. + QModelIndex getSelectedIndex() const; + + /// Removes the given user as a listener to the given channel + /// + /// @param item A pointer to the listener's ModelItem that shall be removed + /// @param citem A pointer to the ModelItem that represents the channel the listener + /// is in. The listener has to be a direct child of this item. If this is nullptr, + /// the parent of the provided item is used directly. + void removeChannelListener(ModelItem *item, ModelItem *citem = nullptr); + +public: + UserModel(QObject *parent = 0); + ~UserModel() Q_DECL_OVERRIDE; + + QModelIndex index(ClientUser *, int column = 0) const; + QModelIndex index(Channel *, int column = 0) const; + QModelIndex index(ModelItem *) const; + QModelIndex channelListenerIndex(const ClientUser *, const Channel *, int column = 0) const; + + QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; + Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + Qt::DropActions supportedDropActions() const Q_DECL_OVERRIDE; + QStringList mimeTypes() const Q_DECL_OVERRIDE; + QMimeData *mimeData(const QModelIndexList &idx) const Q_DECL_OVERRIDE; + bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, + const QModelIndex &parent) Q_DECL_OVERRIDE; + + ClientUser *addUser(unsigned int id, const QString &name); + ClientUser *getUser(const QModelIndex &idx) const; + ClientUser *getUser(const QString &hash) const; + /// @returns A pointer to the currently selected User or nullptr if there is none + ClientUser *getSelectedUser() const; + /// Sets the selection to the User with the given session + /// + /// @param session The session ID of the respective User + void setSelectedUser(unsigned int session); + + Channel *addChannel(int id, Channel *p, const QString &name); + Channel *getChannel(const QModelIndex &idx) const; + /// @returns A pointer to the currently selected Channel or nullptr if there is none + Channel *getSelectedChannel() const; + /// Sets the selection to the Channel with the given ID + /// + /// @param session The ID of the respective Channel + void setSelectedChannel(int id); + + /// Adds the guven user as a listener to the given channel + /// + /// @param p A pointer to the user + /// @param c A pointer to the channel + void addChannelListener(ClientUser *p, Channel *c); + /// Removes the guven user as a listener to the given channel + /// + /// @param p A pointer to the user + /// @param c A pointer to the channel. If this is nullptr, then all listeners + /// for the given user are removed (from all channels). + void removeChannelListener(const ClientUser *p, const Channel *c = nullptr); + /// @param idx The QModelIndex to check + /// @returns Whether the ModelItem associated with the given index is a listener-proxy + bool isChannelListener(const QModelIndex &idx) const; + + /// Sets the selection to the ChannelListener of the given user in the given channel + /// + /// @param userSession The session ID of the respective User + /// @param channelID The ID of the respective Channel + void setSelectedChannelListener(unsigned int userSession, int channelID); + + Channel *getSubChannel(Channel *p, int idx) const; + + void renameUser(ClientUser *p, const QString &name); + void renameChannel(Channel *c, const QString &name); + void repositionChannel(Channel *c, const int position); + void setUserId(ClientUser *p, int id); + void setHash(ClientUser *p, const QString &hash); + void setFriendName(ClientUser *p, const QString &name); + void setComment(ClientUser *p, const QString &comment); + void setCommentHash(ClientUser *p, const QByteArray &hash); + void seenComment(const QModelIndex &idx); + + void moveUser(ClientUser *p, Channel *c); + void moveChannel(Channel *c, Channel *p); + void setComment(Channel *c, const QString &comment); + void setCommentHash(Channel *c, const QByteArray &hash); + + void removeUser(ClientUser *p); + bool removeChannel(Channel *c, const bool onlyIfUnoccupied = false); + + void linkChannels(Channel *c, QList< Channel * > links); + void unlinkChannels(Channel *c, QList< Channel * > links); + void unlinkAll(Channel *c); + + void removeAll(); + + void expandAll(Channel *c); + void collapseEmpty(Channel *c); + + QVariant otherRoles(const QModelIndex &idx, int role) const; + + unsigned int uiSessionComment; + int iChannelDescription; + + + /// Creates the display string for the given user/listener + /// + /// @param user The user to create the string for + /// @param isChannelListener Whether the display String is in fact for a listener of the given user + /// @param parentChannel The channel in which the listener resides. May be nullptr, if isChannelListener is false + /// @return The created display string + static QString createDisplayString(const ClientUser &user, bool isChannelListener, const Channel *parentChannel); +public slots: + /// Invalidates the model data of the ClientUser triggering this slot. + void userStateChanged(); + void ensureSelfVisible(); + void recheckLinks(); + void updateOverlay() const; + void toggleChannelFiltered(Channel *c); }; #endif diff --git a/src/mumble/UserView.cpp b/src/mumble/UserView.cpp index e30bb6605..2a563aee5 100644 --- a/src/mumble/UserView.cpp +++ b/src/mumble/UserView.cpp @@ -17,26 +17,27 @@ #include <QtGui/QPainter> #include <QtWidgets/QWhatsThis> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" const int UserDelegate::FLAG_ICON_DIMENSION = 16; -const int UserDelegate::FLAG_ICON_PADDING = 1; -const int UserDelegate::FLAG_DIMENSION = 18; +const int UserDelegate::FLAG_ICON_PADDING = 1; +const int UserDelegate::FLAG_DIMENSION = 18; UserDelegate::UserDelegate(QObject *p) : QStyledItemDelegate(p) { } -void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { +void UserDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QAbstractItemModel *m = index.model(); - const QModelIndex idxc1 = index.sibling(index.row(), 1); - QVariant data = m->data(idxc1); - QList<QVariant> ql = data.toList(); + const QModelIndex idxc1 = index.sibling(index.row(), 1); + QVariant data = m->data(idxc1); + QList< QVariant > ql = data.toList(); // Allow a UserView's BackgroundRole to override the current theme's default color. QVariant bg = index.data(Qt::BackgroundRole); if (bg.isValid()) { - painter->fillRect(option.rect, bg.value<QBrush>()); + painter->fillRect(option.rect, bg.value< QBrush >()); } painter->save(); @@ -44,14 +45,14 @@ void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, QStyleOptionViewItem o = option; initStyleOption(&o, index); - QStyle *style = o.widget->style(); + QStyle *style = o.widget->style(); QIcon::Mode iconMode = QIcon::Normal; QPalette::ColorRole colorRole = ((o.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::Text); #if defined(Q_OS_WIN) // Qt's Vista Style has the wrong highlight color for treeview items // We can't check for QStyleSheetStyle so we have to search the children list search for a QWindowsVistaStyle - QList<QObject *> hierarchy = style->findChildren<QObject *>(); + QList< QObject * > hierarchy = style->findChildren< QObject * >(); hierarchy.insert(0, style); foreach (QObject *obj, hierarchy) { if (QString::fromUtf8(obj->metaObject()->className()) == QString::fromUtf8("QWindowsVistaStyle")) { @@ -72,14 +73,13 @@ void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, o.icon.paint(painter, decorationRect, o.decorationAlignment, iconMode, QIcon::On); // draw text - QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget); + QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget); QString itemText = o.fontMetrics.elidedText(o.text, o.textElideMode, textRect.width()); painter->setFont(o.font); style->drawItemText(painter, textRect, o.displayAlignment, o.palette, true, itemText, colorRole); // draw flag icons to original rect - QRect ps = QRect(option.rect.right() - (ql.size() * FLAG_DIMENSION), - option.rect.y(), ql.size() * FLAG_DIMENSION, + QRect ps = QRect(option.rect.right() - (ql.size() * FLAG_DIMENSION), option.rect.y(), ql.size() * FLAG_DIMENSION, option.rect.height()); for (int i = 0; i < ql.size(); ++i) { @@ -87,20 +87,21 @@ void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, r.setSize(QSize(FLAG_ICON_DIMENSION, FLAG_ICON_DIMENSION)); r.translate(i * FLAG_DIMENSION + FLAG_ICON_PADDING, FLAG_ICON_PADDING); QRect p = QStyle::alignedRect(option.direction, option.decorationAlignment, r.size(), r); - qvariant_cast<QIcon>(ql[i]).paint(painter, p, option.decorationAlignment, iconMode, QIcon::On); + qvariant_cast< QIcon >(ql[i]).paint(painter, p, option.decorationAlignment, iconMode, QIcon::On); } painter->restore(); } -bool UserDelegate::helpEvent(QHelpEvent *evt, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index) { +bool UserDelegate::helpEvent(QHelpEvent *evt, QAbstractItemView *view, const QStyleOptionViewItem &option, + const QModelIndex &index) { if (index.isValid()) { - const QAbstractItemModel *m = index.model(); + const QAbstractItemModel *m = index.model(); const QModelIndex firstColumnIdx = index.sibling(index.row(), 1); - QVariant data = m->data(firstColumnIdx); - QList<QVariant> flagList = data.toList(); - const int offset = flagList.size() * -FLAG_DIMENSION; - const int firstFlagPos = option.rect.topRight().x() + offset; + QVariant data = m->data(firstColumnIdx); + QList< QVariant > flagList = data.toList(); + const int offset = flagList.size() * -FLAG_DIMENSION; + const int firstFlagPos = option.rect.topRight().x() + offset; if (evt->pos().x() >= firstFlagPos) { return QStyledItemDelegate::helpEvent(evt, view, option, firstColumnIdx); @@ -128,7 +129,7 @@ UserView::UserView(QWidget *p) : QTreeView(p) { */ bool UserView::event(QEvent *evt) { if (evt->type() == QEvent::WhatsThisClicked) { - QWhatsThisClickedEvent *qwtce = static_cast<QWhatsThisClickedEvent *>(evt); + QWhatsThisClickedEvent *qwtce = static_cast< QWhatsThisClickedEvent * >(evt); QDesktopServices::openUrl(qwtce->href()); evt->accept(); return true; @@ -145,12 +146,12 @@ void UserView::mouseReleaseEvent(QMouseEvent *evt) { QModelIndex idx = indexAt(clickPosition); if ((evt->button() == Qt::LeftButton) && idx.isValid()) { - UserModel *userModel = qobject_cast<UserModel *>(model()); + UserModel *userModel = qobject_cast< UserModel * >(model()); ClientUser *clientUser = userModel->getUser(idx); - Channel *channel = userModel->getChannel(idx); + Channel *channel = userModel->getChannel(idx); int commentFlagPxOffset = -UserDelegate::FLAG_DIMENSION; - bool hasComment = false; + bool hasComment = false; if (clientUser && !clientUser->qbaCommentHash.isEmpty()) { hasComment = true; @@ -173,7 +174,7 @@ void UserView::mouseReleaseEvent(QMouseEvent *evt) { commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION; if (clientUser->bDeaf) commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION; - if (! clientUser->qsFriendName.isEmpty()) + if (!clientUser->qsFriendName.isEmpty()) commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION; if (clientUser->iId >= 0) commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION; @@ -183,15 +184,14 @@ void UserView::mouseReleaseEvent(QMouseEvent *evt) { if (channel->bFiltered) commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION; - } if (hasComment) { - QRect r = visualRect(idx); + QRect r = visualRect(idx); const int commentFlagPxPos = r.topRight().x() + commentFlagPxOffset; if ((clickPosition.x() >= commentFlagPxPos) - && (clickPosition.x() <= (commentFlagPxPos + UserDelegate::FLAG_DIMENSION))) { + && (clickPosition.x() <= (commentFlagPxPos + UserDelegate::FLAG_DIMENSION))) { // Clicked comment icon QString str = userModel->data(idx, Qt::ToolTipRole).toString(); if (str.isEmpty()) { @@ -214,7 +214,7 @@ void UserView::keyPressEvent(QKeyEvent *ev) { } void UserView::nodeActivated(const QModelIndex &idx) { - UserModel *um = static_cast<UserModel *>(model()); + UserModel *um = static_cast< UserModel * >(model()); ClientUser *p = um->getUser(idx); if (p) { g.mw->openTextMessageDialog(p); @@ -234,7 +234,6 @@ void UserView::nodeActivated(const QModelIndex &idx) { * with with automatic expanding of folded channels. */ void UserView::keyboardSearch(const QString &search) { - if (qtSearch->isActive()) { qpmiSearch = QPersistentModelIndex(); qtSearch->stop(); @@ -243,14 +242,14 @@ void UserView::keyboardSearch(const QString &search) { bool forceSkip = false; if (tSearch.restart() > (QApplication::keyboardInputInterval() * 1000ULL)) { - qsSearch = QString(); + qsSearch = QString(); forceSkip = true; } bool isBackspace = (search.length() == 1) && (search.at(0).row() == 0) && (search.at(0).cell() == 8); if (isBackspace) { - if (! qsSearch.isEmpty()) - qsSearch = qsSearch.left(qsSearch.length()-1); + if (!qsSearch.isEmpty()) + qsSearch = qsSearch.left(qsSearch.length() - 1); } else { qsSearch += search; } @@ -264,12 +263,14 @@ void UserView::keyboardSearch(const QString &search) { if (forceSkip && start.isValid()) start = indexBelow(start); - if (! start.isValid()) + if (!start.isValid()) start = model()->index(0, 0, QModelIndex()); - QModelIndexList qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap | Qt::MatchRecursive)); + QModelIndexList qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, + Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap | Qt::MatchRecursive)); if (qmil.count() == 0) - qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchContains | Qt::MatchWrap | Qt::MatchRecursive)); + qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, + Qt::MatchFlags(Qt::MatchContains | Qt::MatchWrap | Qt::MatchRecursive)); if (qmil.isEmpty()) return; @@ -277,10 +278,10 @@ void UserView::keyboardSearch(const QString &search) { QModelIndex qmi = qmil.at(0); QModelIndex p = qmi.parent(); - bool visible = true; + bool visible = true; while (visible && p.isValid()) { visible = visible && isExpanded(p); - p = p.parent(); + p = p.parent(); } if (visible) @@ -298,33 +299,30 @@ void UserView::selectSearchResult() { qpmiSearch = QPersistentModelIndex(); } -bool channelHasUsers(const Channel *c) -{ - if(c->qlUsers.isEmpty() == false) +bool channelHasUsers(const Channel *c) { + if (c->qlUsers.isEmpty() == false) return true; - int i; + int i; - for(i=0;i<c->qlChannels.count();i++) - { - if(channelHasUsers(c->qlChannels[i])) + for (i = 0; i < c->qlChannels.count(); i++) { + if (channelHasUsers(c->qlChannels[i])) return true; } return false; } -static bool channelFiltered(const Channel *c) -{ - while(c) { - if(c->bFiltered) +static bool channelFiltered(const Channel *c) { + while (c) { + if (c->bFiltered) return true; - c=c->cParent; + c = c->cParent; } return false; } void UserView::updateChannel(const QModelIndex &idx) { - UserModel *um = static_cast<UserModel *>(model()); + UserModel *um = static_cast< UserModel * >(model()); if (!idx.isValid()) { return; @@ -341,10 +339,10 @@ void UserView::updateChannel(const QModelIndex &idx) { setRowHidden(idx.row(), idx.parent(), false); } else { bool isChannelUserIsIn = false; - + // Check whether user resides in this channel or a subchannel if (g.uiSession != 0) { - const ClientUser* user = ClientUser::get(g.uiSession); + const ClientUser *user = ClientUser::get(g.uiSession); if (user) { Channel *chan = user->cChannel; while (chan) { @@ -356,26 +354,26 @@ void UserView::updateChannel(const QModelIndex &idx) { } } } - - if(channelFiltered(c) && !isChannelUserIsIn) { - setRowHidden(idx.row(),idx.parent(),true); + + if (channelFiltered(c) && !isChannelUserIsIn) { + setRowHidden(idx.row(), idx.parent(), true); } else { - if(g.s.bFilterHidesEmptyChannels && !channelHasUsers(c)) { - setRowHidden(idx.row(),idx.parent(),true); + if (g.s.bFilterHidesEmptyChannels && !channelHasUsers(c)) { + setRowHidden(idx.row(), idx.parent(), true); } else { - setRowHidden(idx.row(),idx.parent(),false); + setRowHidden(idx.row(), idx.parent(), false); } } } } } -void UserView::dataChanged ( const QModelIndex & topLeft, const QModelIndex & bottomRight, const QVector<int> &) { - UserModel *um = static_cast<UserModel *>(model()); +void UserView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector< int > &) { + UserModel *um = static_cast< UserModel * >(model()); int nRowCount = um->rowCount(); int i; - for(i=0;i<nRowCount;i++) - updateChannel(um->index(i,0)); + for (i = 0; i < nRowCount; i++) + updateChannel(um->index(i, 0)); - QTreeView::dataChanged(topLeft,bottomRight); + QTreeView::dataChanged(topLeft, bottomRight); } diff --git a/src/mumble/UserView.h b/src/mumble/UserView.h index 44bffc574..fe3238013 100644 --- a/src/mumble/UserView.h +++ b/src/mumble/UserView.h @@ -13,45 +13,48 @@ #include "Timer.h" class UserDelegate : public QStyledItemDelegate { - private: - Q_OBJECT - Q_DISABLE_COPY(UserDelegate) - public: - UserDelegate(QObject *parent = nullptr); - void paint(QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; - - //! Width/height in px of user/channel flag icons - const static int FLAG_ICON_DIMENSION; - //! Padding in px around user/channel flag icons - const static int FLAG_ICON_PADDING; - //! Width/height in px of user/channel flags including padding - const static int FLAG_DIMENSION; - - public slots: - bool helpEvent(QHelpEvent *event, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index) Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(UserDelegate) +public: + UserDelegate(QObject *parent = nullptr); + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; + + //! Width/height in px of user/channel flag icons + const static int FLAG_ICON_DIMENSION; + //! Padding in px around user/channel flag icons + const static int FLAG_ICON_PADDING; + //! Width/height in px of user/channel flags including padding + const static int FLAG_DIMENSION; + +public slots: + bool helpEvent(QHelpEvent *event, QAbstractItemView *view, const QStyleOptionViewItem &option, + const QModelIndex &index) Q_DECL_OVERRIDE; }; class UserView : public QTreeView { - private: - Q_OBJECT - Q_DISABLE_COPY(UserView) - protected: - void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void keyPressEvent(QKeyEvent *) Q_DECL_OVERRIDE; - bool event(QEvent *) Q_DECL_OVERRIDE; - - QTimer *qtSearch; - QPersistentModelIndex qpmiSearch; - Timer tSearch; - QString qsSearch; - public: - UserView(QWidget *); - void keyboardSearch(const QString &search) Q_DECL_OVERRIDE; - void dataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight, const QVector<int> & roles = QVector<int> ()) Q_DECL_OVERRIDE; - public slots: - void nodeActivated(const QModelIndex &idx); - void selectSearchResult(); - void updateChannel(const QModelIndex &index); +private: + Q_OBJECT + Q_DISABLE_COPY(UserView) +protected: + void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE; + void keyPressEvent(QKeyEvent *) Q_DECL_OVERRIDE; + bool event(QEvent *) Q_DECL_OVERRIDE; + + QTimer *qtSearch; + QPersistentModelIndex qpmiSearch; + Timer tSearch; + QString qsSearch; + +public: + UserView(QWidget *); + void keyboardSearch(const QString &search) Q_DECL_OVERRIDE; + void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, + const QVector< int > &roles = QVector< int >()) Q_DECL_OVERRIDE; +public slots: + void nodeActivated(const QModelIndex &idx); + void selectSearchResult(); + void updateChannel(const QModelIndex &index); }; #endif diff --git a/src/mumble/VersionCheck.cpp b/src/mumble/VersionCheck.cpp index 2a5646e52..8defbe0d5 100644 --- a/src/mumble/VersionCheck.cpp +++ b/src/mumble/VersionCheck.cpp @@ -10,55 +10,58 @@ #include "WebFetch.h" #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include <QtCore/QUrlQuery> -#include <QtXml/QDomDocument> #include <QtWidgets/QMessageBox> +#include <QtXml/QDomDocument> #include <QtConcurrent/QtConcurrent> #ifdef Q_OS_WIN -# include <shellapi.h> -# include <softpub.h> +# include <shellapi.h> +# include <softpub.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" VersionCheck::VersionCheck(bool autocheck, QObject *p, bool focus) : QObject(p), m_preparationWatcher() { - connect(&m_preparationWatcher, &QFutureWatcher<void>::finished, this, &VersionCheck::performRequest); + connect(&m_preparationWatcher, &QFutureWatcher< void >::finished, this, &VersionCheck::performRequest); - QFuture<void> future = QtConcurrent::run([this, autocheck, focus]() { + QFuture< void > future = QtConcurrent::run([this, autocheck, focus]() { m_requestURL.setPath(focus ? QLatin1String("/v1/banner") : QLatin1String("/v1/version-check")); - QList<QPair<QString, QString> > queryItems; - queryItems << qMakePair(QString::fromLatin1("ver"), QString::fromLatin1(QUrl::toPercentEncoding(QLatin1String(MUMBLE_RELEASE)))); + QList< QPair< QString, QString > > queryItems; + queryItems << qMakePair(QString::fromLatin1("ver"), + QString::fromLatin1(QUrl::toPercentEncoding(QLatin1String(MUMBLE_RELEASE)))); #if defined(Q_OS_WIN) -# if defined(Q_OS_WIN64) +# if defined(Q_OS_WIN64) queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("WinX64")); -# else +# else queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("Win32")); -# endif +# endif #elif defined(Q_OS_MAC) -# if defined(USE_MAC_UNIVERSAL) +# if defined(USE_MAC_UNIVERSAL) queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("MacOSX-Universal")); -# else +# else queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("MacOSX")); -# endif +# endif #else queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("Unix")); #endif - if (! g.s.bUsage) + if (!g.s.bUsage) queryItems << qMakePair(QString::fromLatin1("nousage"), QString::fromLatin1("1")); if (autocheck) queryItems << qMakePair(QString::fromLatin1("auto"), QString::fromLatin1("1")); - queryItems << qMakePair(QString::fromLatin1("locale"), g.s.qsLanguage.isEmpty() ? QLocale::system().name() : g.s.qsLanguage); + queryItems << qMakePair(QString::fromLatin1("locale"), + g.s.qsLanguage.isEmpty() ? QLocale::system().name() : g.s.qsLanguage); QFile f(qApp->applicationFilePath()); - if (! f.open(QIODevice::ReadOnly)) { + if (!f.open(QIODevice::ReadOnly)) { qWarning("VersionCheck: Failed to open binary"); } else { QByteArray a = f.readAll(); @@ -80,32 +83,33 @@ VersionCheck::VersionCheck(bool autocheck, QObject *p, bool focus) : QObject(p), } void VersionCheck::performRequest() { - WebFetch::fetch(QLatin1String("update"), m_requestURL, this, SLOT(fetched(QByteArray,QUrl))); + WebFetch::fetch(QLatin1String("update"), m_requestURL, this, SLOT(fetched(QByteArray, QUrl))); } void VersionCheck::fetched(QByteArray a, QUrl url) { - if (! a.isNull()) { - if (! a.isEmpty()) { + if (!a.isNull()) { + if (!a.isEmpty()) { #ifdef SNAPSHOT_BUILD if (url.path() == QLatin1String("/v1/banner")) { g.mw->msgBox(QString::fromUtf8(a)); } else if (url.path() == QLatin1String("/v1/version-check")) { -#ifndef Q_OS_WIN +# ifndef Q_OS_WIN g.mw->msgBox(QString::fromUtf8(a)); -#else +# else QDomDocument qdd; qdd.setContent(a); QDomElement elem = qdd.firstChildElement(QLatin1String("p")); - elem = elem.firstChildElement(QLatin1String("a")); + elem = elem.firstChildElement(QLatin1String("a")); QUrl fetch = QUrl(elem.attribute(QLatin1String("href"))); fetch.setHost(QString()); fetch.setScheme(QString()); - if (! fetch.isValid()) { + if (!fetch.isValid()) { g.mw->msgBox(QString::fromUtf8(a)); } else { - QString filename = g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(fetch.path()).fileName()); + QString filename = + g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(fetch.path()).fileName()); QFile qf(filename); if (qf.exists()) { @@ -113,36 +117,39 @@ void VersionCheck::fetched(QByteArray a, QUrl url) { WINTRUST_FILE_INFO file; ZeroMemory(&file, sizeof(file)); - file.cbStruct = sizeof(file); + file.cbStruct = sizeof(file); file.pcwszFilePath = native.c_str(); WINTRUST_DATA data; ZeroMemory(&data, sizeof(data)); - data.cbStruct = sizeof(data); - data.dwUIChoice = WTD_UI_NONE; + data.cbStruct = sizeof(data); + data.dwUIChoice = WTD_UI_NONE; data.fdwRevocationChecks = WTD_REVOKE_NONE; - data.dwUnionChoice = WTD_CHOICE_FILE; - data.pFile = &file; - data.dwProvFlags = WTD_SAFER_FLAG | WTD_USE_DEFAULT_OSVER_CHECK; - data.dwUIContext = WTD_UICONTEXT_INSTALL; + data.dwUnionChoice = WTD_CHOICE_FILE; + data.pFile = &file; + data.dwProvFlags = WTD_SAFER_FLAG | WTD_USE_DEFAULT_OSVER_CHECK; + data.dwUIContext = WTD_UICONTEXT_INSTALL; static GUID guid = WINTRUST_ACTION_GENERIC_VERIFY_V2; - LONG ts = WinVerifyTrust(0, &guid , &data); + LONG ts = WinVerifyTrust(0, &guid, &data); if (ts == 0) { - if (QMessageBox::question(g.mw, - tr("Upgrade Mumble"), - tr("A new version of Mumble has been detected and automatically downloaded. It is recommended that you either upgrade to this version, or downgrade to the latest stable release. Do you want to launch the installer now?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { + if (QMessageBox::question( + g.mw, tr("Upgrade Mumble"), + tr("A new version of Mumble has been detected and automatically downloaded. It is " + "recommended that you either upgrade to this version, or downgrade to the " + "latest stable release. Do you want to launch the installer now?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) + == QMessageBox::Yes) { SHELLEXECUTEINFOW execinfo; std::wstring filenative = filename.toStdWString(); - std::wstring dirnative = QDir::toNativeSeparators(QDir::tempPath()).toStdWString(); + std::wstring dirnative = QDir::toNativeSeparators(QDir::tempPath()).toStdWString(); ZeroMemory(&execinfo, sizeof(execinfo)); - execinfo.cbSize = sizeof(execinfo); - execinfo.lpFile = filenative.c_str(); + execinfo.cbSize = sizeof(execinfo); + execinfo.lpFile = filenative.c_str(); execinfo.lpDirectory = dirnative.c_str(); - execinfo.nShow = SW_NORMAL; + execinfo.nShow = SW_NORMAL; if (ShellExecuteExW(&execinfo)) { g.mw->bSuppressAskOnQuit = true; @@ -160,12 +167,11 @@ void VersionCheck::fetched(QByteArray a, QUrl url) { // Delete all but the N most recent snapshots size_t numberOfSnapshotsToKeep = 1; - QDir snapdir(g.qdBasePath.absolutePath() + QLatin1String("/Snapshots/"), - QString(), - QDir::Name, - QDir::Files); + QDir snapdir(g.qdBasePath.absolutePath() + QLatin1String("/Snapshots/"), QString(), QDir::Name, + QDir::Files); - foreach(const QFileInfo fileInfo, snapdir.entryInfoList(QStringList(), QDir::NoFilter, QDir::Time)) { + foreach (const QFileInfo fileInfo, + snapdir.entryInfoList(QStringList(), QDir::NoFilter, QDir::Time)) { if (numberOfSnapshotsToKeep) { --numberOfSnapshotsToKeep; continue; @@ -176,13 +182,15 @@ void VersionCheck::fetched(QByteArray a, QUrl url) { file.remove(); } } else { - g.mw->msgBox(tr("Downloading new snapshot from %1 to %2").arg(fetch.toString().toHtmlEscaped(), filename.toHtmlEscaped())); - WebFetch::fetch(QLatin1String("dl"), fetch, this, SLOT(fetched(QByteArray,QUrl))); + g.mw->msgBox(tr("Downloading new snapshot from %1 to %2") + .arg(fetch.toString().toHtmlEscaped(), filename.toHtmlEscaped())); + WebFetch::fetch(QLatin1String("dl"), fetch, this, SLOT(fetched(QByteArray, QUrl))); return; } } } else { - QString filename = g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(url.path()).fileName()); + QString filename = + g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(url.path()).fileName()); QFile qf(filename); if (qf.open(QIODevice::WriteOnly)) { @@ -192,7 +200,7 @@ void VersionCheck::fetched(QByteArray a, QUrl url) { } else { g.mw->msgBox(tr("Failed to write new version to disk.")); } -#endif +# endif } #else Q_UNUSED(url); diff --git a/src/mumble/VersionCheck.h b/src/mumble/VersionCheck.h index fb9660276..30b512fe1 100644 --- a/src/mumble/VersionCheck.h +++ b/src/mumble/VersionCheck.h @@ -6,24 +6,25 @@ #ifndef MUMBLE_MUMBLE_VERSIONCHECK_H_ #define MUMBLE_MUMBLE_VERSIONCHECK_H_ -#include <QtCore/QObject> +#include <QFutureWatcher> #include <QtCore/QByteArray> +#include <QtCore/QObject> #include <QtCore/QUrl> -#include <QFutureWatcher> class VersionCheck : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(VersionCheck) +private: + Q_OBJECT + Q_DISABLE_COPY(VersionCheck) + + QFutureWatcher< void > m_preparationWatcher; + QUrl m_requestURL; +protected slots: + void performRequest(); +public slots: + void fetched(QByteArray data, QUrl url); - QFutureWatcher<void> m_preparationWatcher; - QUrl m_requestURL; - protected slots: - void performRequest(); - public slots: - void fetched(QByteArray data, QUrl url); - public: - VersionCheck(bool autocheck, QObject *parent = nullptr, bool focus = false); +public: + VersionCheck(bool autocheck, QObject *parent = nullptr, bool focus = false); }; #endif diff --git a/src/mumble/ViewCert.cpp b/src/mumble/ViewCert.cpp index 35b1bc951..e665ad1ab 100644 --- a/src/mumble/ViewCert.cpp +++ b/src/mumble/ViewCert.cpp @@ -20,20 +20,16 @@ static QString decode_utf8_qssl_string(const QString &input) { static QStringList processQSslCertificateInfo(QStringList in) { QStringList list; - foreach (QString str, in) { - list << decode_utf8_qssl_string(str); - } + foreach (QString str, in) { list << decode_utf8_qssl_string(str); } return list; } static void addQSslCertificateInfo(QStringList &l, const QString &label, const QStringList &items) { - foreach (const QString &item, items) { - l << QString(QLatin1String("%1: %2")).arg(label, item); - } + foreach (const QString &item, items) { l << QString(QLatin1String("%1: %2")).arg(label, item); } } static QString certificateFriendlyName(const QSslCertificate &cert) { - QStringList cnList = processQSslCertificateInfo(cert.subjectInfo(QSslCertificate::CommonName)); + QStringList cnList = processQSslCertificateInfo(cert.subjectInfo(QSslCertificate::CommonName)); QStringList orgList = processQSslCertificateInfo(cert.subjectInfo(QSslCertificate::Organization)); QString cn; @@ -49,7 +45,7 @@ static QString certificateFriendlyName(const QSslCertificate &cert) { return QString(QLatin1String("%1 %2")).arg(cn, org); } -ViewCert::ViewCert(QList<QSslCertificate> cl, QWidget *p) : QDialog(p) { +ViewCert::ViewCert(QList< QSslCertificate > cl, QWidget *p) : QDialog(p) { qlCerts = cl; setWindowTitle(tr("Certificate Chain Details")); @@ -58,28 +54,28 @@ ViewCert::ViewCert(QList<QSslCertificate> cl, QWidget *p) : QDialog(p) { QVBoxLayout *v; QGroupBox *qcbChain, *qcbDetails; - qcbChain=new QGroupBox(tr("Certificate chain"), this); - h = new QHBoxLayout(qcbChain); + qcbChain = new QGroupBox(tr("Certificate chain"), this); + h = new QHBoxLayout(qcbChain); qlwChain = new QListWidget(qcbChain); qlwChain->setObjectName(QLatin1String("Chain")); // load certs into a set as a hacky fix to #2141 #if QT_VERSION >= 0x050400 - QSet<QSslCertificate> qlCertSet; + QSet< QSslCertificate > qlCertSet; #else - QList<QSslCertificate> qlCertSet; + QList< QSslCertificate > qlCertSet; #endif - foreach(QSslCertificate c, qlCerts) { - if(!qlCertSet.contains(c)) { + foreach (QSslCertificate c, qlCerts) { + if (!qlCertSet.contains(c)) { qlwChain->addItem(certificateFriendlyName(c)); qlCertSet << c; } } h->addWidget(qlwChain); - qcbDetails=new QGroupBox(tr("Certificate details"), this); - h = new QHBoxLayout(qcbDetails); - qlwCert = new QListWidget(qcbDetails); + qcbDetails = new QGroupBox(tr("Certificate details"), this); + h = new QHBoxLayout(qcbDetails); + qlwCert = new QListWidget(qcbDetails); h->addWidget(qlwCert); QDialogButtonBox *qdbb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, this); @@ -92,13 +88,13 @@ ViewCert::ViewCert(QList<QSslCertificate> cl, QWidget *p) : QDialog(p) { QMetaObject::connectSlotsByName(this); connect(qdbb, SIGNAL(accepted()), this, SLOT(accept())); - resize(510,300); + resize(510, 300); } QString ViewCert::prettifyDigest(QString digest) { QString pretty_digest = digest.toUpper(); - int step = 2; - QChar separator = QChar::fromLatin1(':'); + int step = 2; + QChar separator = QChar::fromLatin1(':'); for (int i = step; i < pretty_digest.size(); i += step + 1) { pretty_digest.insert(i, separator); } @@ -111,34 +107,39 @@ void ViewCert::on_Chain_currentRowChanged(int idx) { return; QStringList l; - const QSslCertificate &c=qlCerts.at(idx); - - addQSslCertificateInfo(l, tr("Common Name"), processQSslCertificateInfo(c.subjectInfo(QSslCertificate::CommonName))); - addQSslCertificateInfo(l, tr("Organization"), processQSslCertificateInfo(c.subjectInfo(QSslCertificate::Organization))); - addQSslCertificateInfo(l, tr("Subunit"), processQSslCertificateInfo(c.subjectInfo(QSslCertificate::OrganizationalUnitName))); + const QSslCertificate &c = qlCerts.at(idx); + + addQSslCertificateInfo(l, tr("Common Name"), + processQSslCertificateInfo(c.subjectInfo(QSslCertificate::CommonName))); + addQSslCertificateInfo(l, tr("Organization"), + processQSslCertificateInfo(c.subjectInfo(QSslCertificate::Organization))); + addQSslCertificateInfo(l, tr("Subunit"), + processQSslCertificateInfo(c.subjectInfo(QSslCertificate::OrganizationalUnitName))); addQSslCertificateInfo(l, tr("Country"), processQSslCertificateInfo(c.subjectInfo(QSslCertificate::CountryName))); addQSslCertificateInfo(l, tr("Locality"), processQSslCertificateInfo(c.subjectInfo(QSslCertificate::LocalityName))); - addQSslCertificateInfo(l, tr("State"), processQSslCertificateInfo(c.subjectInfo(QSslCertificate::StateOrProvinceName))); + addQSslCertificateInfo(l, tr("State"), + processQSslCertificateInfo(c.subjectInfo(QSslCertificate::StateOrProvinceName))); l << tr("Valid from: %1").arg(c.effectiveDate().toString()); l << tr("Valid to: %1").arg(c.expiryDate().toString()); l << tr("Serial: %1").arg(QString::fromLatin1(c.serialNumber().toHex())); - l << tr("Public Key: %1 bits %2").arg(c.publicKey().length()).arg((c.publicKey().algorithm() == QSsl::Rsa) ? tr("RSA") : tr("DSA")); + l << tr("Public Key: %1 bits %2") + .arg(c.publicKey().length()) + .arg((c.publicKey().algorithm() == QSsl::Rsa) ? tr("RSA") : tr("DSA")); l << tr("Digest (SHA-1): %1").arg(prettifyDigest(QString::fromLatin1(c.digest(QCryptographicHash::Sha1).toHex()))); - l << tr("Digest (SHA-256): %1").arg(prettifyDigest(QString::fromLatin1(c.digest(QCryptographicHash::Sha256).toHex()))); + l << tr("Digest (SHA-256): %1") + .arg(prettifyDigest(QString::fromLatin1(c.digest(QCryptographicHash::Sha256).toHex()))); - const QMultiMap<QSsl::AlternativeNameEntryType, QString> &alts = c.subjectAlternativeNames(); - QMultiMap<QSsl::AlternativeNameEntryType, QString>::const_iterator i; + const QMultiMap< QSsl::AlternativeNameEntryType, QString > &alts = c.subjectAlternativeNames(); + QMultiMap< QSsl::AlternativeNameEntryType, QString >::const_iterator i; - for (i=alts.constBegin(); i != alts.constEnd(); ++i) { + for (i = alts.constBegin(); i != alts.constEnd(); ++i) { switch (i.key()) { case QSsl::EmailEntry: { - l << tr("Email: %1").arg(i.value()); - } - break; + l << tr("Email: %1").arg(i.value()); + } break; case QSsl::DnsEntry: { - l << tr("DNS: %1").arg(i.value()); - } - break; + l << tr("DNS: %1").arg(i.value()); + } break; default: break; } @@ -147,11 +148,14 @@ void ViewCert::on_Chain_currentRowChanged(int idx) { l << QString(); l << tr("Issued by:"); addQSslCertificateInfo(l, tr("Common Name"), processQSslCertificateInfo(c.issuerInfo(QSslCertificate::CommonName))); - addQSslCertificateInfo(l, tr("Organization"), processQSslCertificateInfo(c.issuerInfo(QSslCertificate::Organization))); - addQSslCertificateInfo(l, tr("Unit Name"), processQSslCertificateInfo(c.issuerInfo(QSslCertificate::OrganizationalUnitName))); + addQSslCertificateInfo(l, tr("Organization"), + processQSslCertificateInfo(c.issuerInfo(QSslCertificate::Organization))); + addQSslCertificateInfo(l, tr("Unit Name"), + processQSslCertificateInfo(c.issuerInfo(QSslCertificate::OrganizationalUnitName))); addQSslCertificateInfo(l, tr("Country"), processQSslCertificateInfo(c.issuerInfo(QSslCertificate::CountryName))); addQSslCertificateInfo(l, tr("Locality"), processQSslCertificateInfo(c.issuerInfo(QSslCertificate::LocalityName))); - addQSslCertificateInfo(l, tr("State"), processQSslCertificateInfo(c.issuerInfo(QSslCertificate::StateOrProvinceName))); + addQSslCertificateInfo(l, tr("State"), + processQSslCertificateInfo(c.issuerInfo(QSslCertificate::StateOrProvinceName))); qlwCert->addItems(l); } diff --git a/src/mumble/ViewCert.h b/src/mumble/ViewCert.h index 6eb82b3de..6d1ee70f3 100644 --- a/src/mumble/ViewCert.h +++ b/src/mumble/ViewCert.h @@ -6,26 +6,27 @@ #ifndef MUMBLE_MUMBLE_VIEWCERT_H_ #define MUMBLE_MUMBLE_VIEWCERT_H_ -#include <QtCore/QtGlobal> -#include <QtCore/QObject> #include <QtCore/QList> -#include <QtWidgets/QDialog> +#include <QtCore/QObject> +#include <QtCore/QtGlobal> #include <QtNetwork/QSslCertificate> +#include <QtWidgets/QDialog> class QListWidget; class ViewCert : public QDialog { - private: - Q_OBJECT - Q_DISABLE_COPY(ViewCert) - protected: - QList<QSslCertificate> qlCerts; - QListWidget *qlwChain, *qlwCert; - protected slots: - void on_Chain_currentRowChanged(int); - public: - ViewCert(QList<QSslCertificate> c, QWidget *p); - static QString prettifyDigest(QString); +private: + Q_OBJECT + Q_DISABLE_COPY(ViewCert) +protected: + QList< QSslCertificate > qlCerts; + QListWidget *qlwChain, *qlwCert; +protected slots: + void on_Chain_currentRowChanged(int); + +public: + ViewCert(QList< QSslCertificate > c, QWidget *p); + static QString prettifyDigest(QString); }; #endif diff --git a/src/mumble/VoiceRecorder.cpp b/src/mumble/VoiceRecorder.cpp index 535a524bb..cd2d5c331 100644 --- a/src/mumble/VoiceRecorder.cpp +++ b/src/mumble/VoiceRecorder.cpp @@ -13,27 +13,19 @@ #include <boost/make_shared.hpp> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -VoiceRecorder::RecordBuffer::RecordBuffer( - int recordInfoIndex_, - boost::shared_array<float> buffer_, - int samples_, - quint64 absoluteStartSample_) - - : recordInfoIndex(recordInfoIndex_) - , buffer(buffer_) - , samples(samples_) - , absoluteStartSample(absoluteStartSample_) { - +VoiceRecorder::RecordBuffer::RecordBuffer(int recordInfoIndex_, boost::shared_array< float > buffer_, int samples_, + quint64 absoluteStartSample_) + + : recordInfoIndex(recordInfoIndex_), buffer(buffer_), samples(samples_), absoluteStartSample(absoluteStartSample_) { // Nothing } -VoiceRecorder::RecordInfo::RecordInfo(const QString& userName_) - : userName(userName_) - , soundFile(nullptr) - , lastWrittenAbsoluteSample(0) { +VoiceRecorder::RecordInfo::RecordInfo(const QString &userName_) + : userName(userName_), soundFile(nullptr), lastWrittenAbsoluteSample(0) { } VoiceRecorder::RecordInfo::~RecordInfo() { @@ -43,16 +35,9 @@ VoiceRecorder::RecordInfo::~RecordInfo() { } } -VoiceRecorder::VoiceRecorder(QObject *p, const Config& config) - : QThread(p) - , m_recordUser(new RecordUser()) - , m_timestamp(new Timer()) - , m_config(config) - , m_recording(false) - , m_abort(false) - , m_recordingStartTime(QDateTime::currentDateTime()) - , m_absoluteSampleEstimation(0) { - +VoiceRecorder::VoiceRecorder(QObject *p, const Config &config) + : QThread(p), m_recordUser(new RecordUser()), m_timestamp(new Timer()), m_config(config), m_recording(false), + m_abort(false), m_recordingStartTime(QDateTime::currentDateTime()), m_absoluteSampleEstimation(0) { // Nothing } @@ -83,8 +68,10 @@ QString VoiceRecorder::sanitizeFilenameOrPathComponent(const QString &str) const // Replace < > : " / \ | ? * as well as chr(0) to chr(31) res = res.replace(QRegExp(QLatin1String("[<>:\"/\\\\|\\?\\*\\x00-\\x1F]")), QLatin1String("_")); - // Prepend reserved filenames CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 - res = res.replace(QRegExp(QLatin1String("^((CON|PRN|AUX|NUL|COM[1-9]|LPT1[1-9])(\\.|$))"), Qt::CaseInsensitive), QLatin1String("_\\1")); + // Prepend reserved filenames CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, + // LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 + res = res.replace(QRegExp(QLatin1String("^((CON|PRN|AUX|NUL|COM[1-9]|LPT1[1-9])(\\.|$))"), Qt::CaseInsensitive), + QLatin1String("_\\1")); // Make sure we do not exceed 255 characters if (res.length() > 255) { @@ -94,12 +81,12 @@ QString VoiceRecorder::sanitizeFilenameOrPathComponent(const QString &str) const } #else // For the rest just make sure the string doesn't contain a \0 or any forward-slashes - res = res.replace(QRegExp(QLatin1String("\\x00|/")), QLatin1String("_")); + res = res.replace(QRegExp(QLatin1String("\\x00|/")), QLatin1String("_")); #endif return res; } -QString VoiceRecorder::expandTemplateVariables(const QString &path, const QString& userName) const { +QString VoiceRecorder::expandTemplateVariables(const QString &path, const QString &userName) const { // Split path into components QString res; QStringList comp = path.split(QLatin1Char('/')); @@ -122,7 +109,7 @@ QString VoiceRecorder::expandTemplateVariables(const QString &path, const QStrin // %date Inserts the current date // %time Inserts the current time // %host Inserts the hostname - QHash<const QString, QString> vars; + QHash< const QString, QString > vars; vars.insert(QLatin1String("user"), userName); vars.insert(QLatin1String("date"), date); vars.insert(QLatin1String("time"), time); @@ -130,7 +117,7 @@ QString VoiceRecorder::expandTemplateVariables(const QString &path, const QStrin // Reassemble and expand bool first = true; - foreach(QString str, comp) { + foreach (QString str, comp) { bool replacements = false; QString tmp; @@ -138,13 +125,13 @@ QString VoiceRecorder::expandTemplateVariables(const QString &path, const QStrin for (int i = 0; i < str.size(); ++i) { bool replaced = false; if (str[i] == QLatin1Char('%')) { - QHashIterator<const QString, QString> it(vars); + QHashIterator< const QString, QString > it(vars); while (it.hasNext()) { it.next(); if (str.midRef(i + 1, it.key().length()) == it.key()) { i += it.key().length(); tmp += it.value(); - replaced = true; + replaced = true; replacements = true; break; } @@ -172,7 +159,7 @@ QString VoiceRecorder::expandTemplateVariables(const QString &path, const QStrin int VoiceRecorder::indexForUser(const ClientUser *clientUser) const { Q_ASSERT(!m_config.mixDownMode || !clientUser); - + return (m_config.mixDownMode) ? 0 : clientUser->uiSession; } @@ -181,48 +168,52 @@ SF_INFO VoiceRecorder::createSoundFileInfo() const { // When adding new formats make sure to properly configure needed additional // behavior after opening the file handle (e.g. to enable clipping). - + // Convert |fmFormat| to a SF_INFO structure for libsndfile. SF_INFO sfinfo; switch (m_config.recordingFormat) { case VoiceRecorderFormat::WAV: default: - sfinfo.frames = 0; + sfinfo.frames = 0; sfinfo.samplerate = m_config.sampleRate; - sfinfo.channels = 1; - sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_24; - sfinfo.sections = 0; - sfinfo.seekable = 0; - qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate << "hz in WAV format"; + sfinfo.channels = 1; + sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_24; + sfinfo.sections = 0; + sfinfo.seekable = 0; + qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate + << "hz in WAV format"; break; #ifndef NO_VORBIS_RECORDING case VoiceRecorderFormat::VORBIS: - sfinfo.frames = 0; + sfinfo.frames = 0; sfinfo.samplerate = m_config.sampleRate; - sfinfo.channels = 1; - sfinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS; - sfinfo.sections = 0; - sfinfo.seekable = 0; - qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate << "hz in OGG/Vorbis format"; + sfinfo.channels = 1; + sfinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS; + sfinfo.sections = 0; + sfinfo.seekable = 0; + qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate + << "hz in OGG/Vorbis format"; break; #endif case VoiceRecorderFormat::AU: - sfinfo.frames = 0; + sfinfo.frames = 0; sfinfo.samplerate = m_config.sampleRate; - sfinfo.channels = 1; - sfinfo.format = SF_ENDIAN_CPU | SF_FORMAT_AU | SF_FORMAT_FLOAT; - sfinfo.sections = 0; - sfinfo.seekable = 0; - qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate << "hz in AU format"; + sfinfo.channels = 1; + sfinfo.format = SF_ENDIAN_CPU | SF_FORMAT_AU | SF_FORMAT_FLOAT; + sfinfo.sections = 0; + sfinfo.seekable = 0; + qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate + << "hz in AU format"; break; case VoiceRecorderFormat::FLAC: - sfinfo.frames = 0; + sfinfo.frames = 0; sfinfo.samplerate = m_config.sampleRate; - sfinfo.channels = 1; - sfinfo.format = SF_FORMAT_FLAC | SF_FORMAT_PCM_24; - sfinfo.sections = 0; - sfinfo.seekable = 0; - qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate << "hz in FLAC format"; + sfinfo.channels = 1; + sfinfo.format = SF_FORMAT_FLAC | SF_FORMAT_PCM_24; + sfinfo.sections = 0; + sfinfo.seekable = 0; + qWarning() << "VoiceRecorder: recording started to" << m_config.fileName << "@" << m_config.sampleRate + << "hz in FLAC format"; break; } @@ -230,12 +221,12 @@ SF_INFO VoiceRecorder::createSoundFileInfo() const { return sfinfo; } -bool VoiceRecorder::ensureFileIsOpenedFor(SF_INFO& soundFileInfo, boost::shared_ptr<RecordInfo>& ri) { +bool VoiceRecorder::ensureFileIsOpenedFor(SF_INFO &soundFileInfo, boost::shared_ptr< RecordInfo > &ri) { if (ri->soundFile) { // Nothing to do return true; } - + QString filename = expandTemplateVariables(m_config.fileName, ri->userName); // Try to find a unique filename. @@ -244,12 +235,9 @@ bool VoiceRecorder::ensureFileIsOpenedFor(SF_INFO& soundFileInfo, boost::shared_ QString nf(filename); QFileInfo tfi(filename); while (QFile::exists(nf)) { - nf = tfi.path() - + QLatin1Char('/') - + tfi.completeBaseName() - + QString(QLatin1String(" (%1).")).arg(cnt) - + tfi.suffix(); - + nf = tfi.path() + QLatin1Char('/') + tfi.completeBaseName() + QString(QLatin1String(" (%1).")).arg(cnt) + + tfi.suffix(); + ++cnt; } filename = nf; @@ -273,7 +261,7 @@ bool VoiceRecorder::ensureFileIsOpenedFor(SF_INFO& soundFileInfo, boost::shared_ ri->soundFile = sf_open(qPrintable(filename), SFM_WRITE, &soundFileInfo); #endif if (!ri->soundFile) { - qWarning() << "Failed to open file for recorder: "<< sf_strerror(nullptr); + qWarning() << "Failed to open file for recorder: " << sf_strerror(nullptr); m_recording = false; emit error(CreateFileFailed, tr("Recorder failed to open file '%1'").arg(filename)); emit recording_stopped(); @@ -282,11 +270,10 @@ bool VoiceRecorder::ensureFileIsOpenedFor(SF_INFO& soundFileInfo, boost::shared_ // Store the username in the title attribute of the file (if supported by the format). sf_set_string(ri->soundFile, SF_STR_TITLE, qPrintable(ri->userName)); - + // Enable hard-clipping for non-float formats to prevent wrapping - if ((soundFileInfo.format & SF_FORMAT_SUBMASK) != SF_FORMAT_FLOAT && - (soundFileInfo.format & SF_FORMAT_SUBMASK) != SF_FORMAT_VORBIS) { - + if ((soundFileInfo.format & SF_FORMAT_SUBMASK) != SF_FORMAT_FLOAT + && (soundFileInfo.format & SF_FORMAT_SUBMASK) != SF_FORMAT_VORBIS) { sf_command(ri->soundFile, SFC_SET_CLIPPING, nullptr, SF_TRUE); } @@ -295,15 +282,15 @@ bool VoiceRecorder::ensureFileIsOpenedFor(SF_INFO& soundFileInfo, boost::shared_ void VoiceRecorder::run() { Q_ASSERT(!m_recording); - + if (g.sh && g.sh->uiVersion < 0x010203) return; SF_INFO soundFileInfo = createSoundFileInfo(); - + m_recording = true; emit recording_started(); - + forever { // Sleep until there is new data for us to process. m_sleepLock.lock(); @@ -315,43 +302,43 @@ void VoiceRecorder::run() { } while (!m_abort && !m_recordBuffer.isEmpty()) { - boost::shared_ptr<RecordBuffer> rb; + boost::shared_ptr< RecordBuffer > rb; { QMutexLocker l(&m_bufferLock); rb = m_recordBuffer.takeFirst(); } - + // Create the file for this RecordInfo instance if it's not yet open. - + Q_ASSERT(m_recordInfo.contains(rb->recordInfoIndex)); - boost::shared_ptr<RecordInfo> ri = m_recordInfo.value(rb->recordInfoIndex); - + boost::shared_ptr< RecordInfo > ri = m_recordInfo.value(rb->recordInfoIndex); + if (!ensureFileIsOpenedFor(soundFileInfo, ri)) { return; } const qint64 missingSamples = rb->absoluteStartSample - ri->lastWrittenAbsoluteSample; - + static const qint64 heuristicSilenceThreshold = m_config.sampleRate / 10; // 100ms if (missingSamples > heuristicSilenceThreshold) { static const qint64 maxSamplesPerIteration = m_config.sampleRate * 1; // 1s - + const bool requeue = missingSamples > maxSamplesPerIteration; - + // Write |missingSamples| samples of silence up to |maxSamplesPerIteration| const float buffer[1024] = {}; - + const qint64 silenceToWrite = std::min(missingSamples, maxSamplesPerIteration); - qint64 rest = silenceToWrite; - + qint64 rest = silenceToWrite; + for (; rest > 1024; rest -= 1024) sf_write_float(ri->soundFile, buffer, 1024); if (rest > 0) sf_write_float(ri->soundFile, buffer, rest); - + ri->lastWrittenAbsoluteSample += silenceToWrite; - + if (requeue) { // Requeue the writing for this buffer to keep thread responsive QMutexLocker l(&m_bufferLock); @@ -367,14 +354,14 @@ void VoiceRecorder::run() { m_sleepLock.unlock(); } - + m_recording = false; { QMutexLocker l(&m_bufferLock); m_recordInfo.clear(); m_recordBuffer.clear(); } - + emit recording_stopped(); qWarning() << "VoiceRecorder: recording stopped"; } @@ -382,43 +369,38 @@ void VoiceRecorder::run() { void VoiceRecorder::stop(bool force) { // Tell the main loop to terminate and wake up the sleep lock. m_recording = false; - m_abort = force; - + m_abort = force; + m_sleepCondition.wakeAll(); } void VoiceRecorder::prepareBufferAdds() { // Should be ms accurat - m_absoluteSampleEstimation = - (m_timestamp->elapsed() / 1000) * (m_config.sampleRate / 1000); + m_absoluteSampleEstimation = (m_timestamp->elapsed() / 1000) * (m_config.sampleRate / 1000); } -void VoiceRecorder::addBuffer(const ClientUser *clientUser, - boost::shared_array<float> buffer, - int samples) { - +void VoiceRecorder::addBuffer(const ClientUser *clientUser, boost::shared_array< float > buffer, int samples) { Q_ASSERT(!m_config.mixDownMode || !clientUser); if (!m_recording) return; - + // Create a new RecordInfo object if this is a new user. const int index = indexForUser(clientUser); - + if (!m_recordInfo.contains(index)) { - boost::shared_ptr<RecordInfo> ri = boost::make_shared<RecordInfo>( - m_config.mixDownMode ? QLatin1String("Mixdown") - : clientUser->qsName); - + boost::shared_ptr< RecordInfo > ri = + boost::make_shared< RecordInfo >(m_config.mixDownMode ? QLatin1String("Mixdown") : clientUser->qsName); + m_recordInfo.insert(index, ri); } { // Save the buffer in |qlRecordBuffer|. QMutexLocker l(&m_bufferLock); - boost::shared_ptr<RecordBuffer> rb = boost::make_shared<RecordBuffer>( - index, buffer, samples, m_absoluteSampleEstimation); - + boost::shared_ptr< RecordBuffer > rb = + boost::make_shared< RecordBuffer >(index, buffer, samples, m_absoluteSampleEstimation); + m_recordBuffer << rb; } diff --git a/src/mumble/VoiceRecorder.h b/src/mumble/VoiceRecorder.h index db06512e7..41ed20a94 100644 --- a/src/mumble/VoiceRecorder.h +++ b/src/mumble/VoiceRecorder.h @@ -9,12 +9,12 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #ifndef Q_MOC_RUN -# include <boost/scoped_ptr.hpp> -# include <boost/shared_array.hpp> +# include <boost/scoped_ptr.hpp> +# include <boost/shared_array.hpp> #endif #include <QtCore/QDateTime> @@ -25,7 +25,7 @@ #include <QtCore/QWaitCondition> #ifdef Q_OS_WIN -# define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1 +# define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1 #endif #include <sndfile.h> @@ -37,30 +37,30 @@ class Timer; /// Utilities and enums for voice recorder format handling namespace VoiceRecorderFormat { - /// List of all formats currently supported by the recorder. - enum Format { - /// WAVE Format - WAV = 0, +/// List of all formats currently supported by the recorder. +enum Format { + /// WAVE Format + WAV = 0, // When switching between a non vorbis capable lib and a vorbis capable one // this can mess up the selection stored in the config #ifndef NO_VORBIS_RECORDING - /// Ogg Vorbis Format - VORBIS, + /// Ogg Vorbis Format + VORBIS, #endif - /// AU Format - AU, - /// FLAC Format - FLAC, - kEnd - }; + /// AU Format + AU, + /// FLAC Format + FLAC, + kEnd +}; - /// Returns a human readable description of the format id. - QString getFormatDescription(VoiceRecorderFormat::Format fm); +/// Returns a human readable description of the format id. +QString getFormatDescription(VoiceRecorderFormat::Format fm); - /// Returns the default extension for the given format. - QString getFormatDefaultExtension(VoiceRecorderFormat::Format fm); +/// Returns the default extension for the given format. +QString getFormatDefaultExtension(VoiceRecorderFormat::Format fm); -} +} // namespace VoiceRecorderFormat /// Class for recording audio data. /// @@ -69,154 +69,152 @@ namespace VoiceRecorderFormat { /// and written to disk. /// class VoiceRecorder : public QThread { - Q_OBJECT - public: - /// Possible error conditions inside the recorder - enum Error { Unspecified, CreateDirectoryFailed, CreateFileFailed, InvalidSampleRate }; - - /// Structure for holding configuration of VoiceRecorder object - struct Config { - /// The current sample rate of the recorder. - int sampleRate; - - /// The path to store recordings. - QString fileName; - - /// True if multi channel recording is disabled. - bool mixDownMode; - - /// The current recording format. - VoiceRecorderFormat::Format recordingFormat; - }; - - /// Creates a new VoiceRecorder instance. - VoiceRecorder(QObject *p, const Config& config); - ~VoiceRecorder() Q_DECL_OVERRIDE; - - /// The main event loop of the thread, which writes all buffers to files. - void run() Q_DECL_OVERRIDE; - - /// Stops the main loop. - /// @param force If true buffers are discarded. Otherwise the thread will not stop before writing everything. - void stop(bool force = false); - - /// Remembers the current time for a set of coming addBuffer calls - void prepareBufferAdds(); - - /// Adds an audio buffer which contains |samples| audio samples to the recorder. - /// The audio data will be assumed to be recorded at the time - /// prepareBufferAdds was last called. - /// @param clientUser User for which to add the audio data. nullptr in mixdown mode. - void addBuffer(const ClientUser *clientUser, boost::shared_array<float> buffer, int samples); - - /// Returns the elapsed time since the recording started. - quint64 getElapsedTime() const; - - /// Returns a refence to the record user which is used to record local audio. - RecordUser &getRecordUser() const; - - /// Returns true if the recorder is recording mixed down data instead of multichannel - bool isInMixDownMode() const; + Q_OBJECT +public: + /// Possible error conditions inside the recorder + enum Error { Unspecified, CreateDirectoryFailed, CreateFileFailed, InvalidSampleRate }; + + /// Structure for holding configuration of VoiceRecorder object + struct Config { + /// The current sample rate of the recorder. + int sampleRate; + + /// The path to store recordings. + QString fileName; + + /// True if multi channel recording is disabled. + bool mixDownMode; + + /// The current recording format. + VoiceRecorderFormat::Format recordingFormat; + }; + + /// Creates a new VoiceRecorder instance. + VoiceRecorder(QObject *p, const Config &config); + ~VoiceRecorder() Q_DECL_OVERRIDE; + + /// The main event loop of the thread, which writes all buffers to files. + void run() Q_DECL_OVERRIDE; + + /// Stops the main loop. + /// @param force If true buffers are discarded. Otherwise the thread will not stop before writing everything. + void stop(bool force = false); + + /// Remembers the current time for a set of coming addBuffer calls + void prepareBufferAdds(); + + /// Adds an audio buffer which contains |samples| audio samples to the recorder. + /// The audio data will be assumed to be recorded at the time + /// prepareBufferAdds was last called. + /// @param clientUser User for which to add the audio data. nullptr in mixdown mode. + void addBuffer(const ClientUser *clientUser, boost::shared_array< float > buffer, int samples); + + /// Returns the elapsed time since the recording started. + quint64 getElapsedTime() const; + + /// Returns a refence to the record user which is used to record local audio. + RecordUser &getRecordUser() const; + + /// Returns true if the recorder is recording mixed down data instead of multichannel + bool isInMixDownMode() const; signals: - /// Emitted if an error is encountered - void error(int err, QString strerr); - - /// Emitted when recording is started - void recording_started(); - /// Emitted when recording is stopped - void recording_stopped(); - - private: - - /// Stores information about a recording buffer. - struct RecordBuffer { - /// Constructs a new RecordBuffer object. - RecordBuffer(int recordInfoIndex_, - boost::shared_array<float> buffer_, - int samples_, - quint64 absoluteStartSample_); - - /// Hashmap index for the user - const int recordInfoIndex; - - /// The buffer. - boost::shared_array<float> buffer; - - /// The number of samples in the buffer. - int samples; - - /// Absolute sample number at the start of this buffer - quint64 absoluteStartSample; - }; - - /// Stores the recording state for one user. - struct RecordInfo { - RecordInfo(const QString& userName_); - ~RecordInfo(); - - /// Name of the user being recorded - const QString userName; - - /// libsndfile's handle. - SNDFILE *soundFile; - - /// The last absolute sample we wrote for this users - quint64 lastWrittenAbsoluteSample; - }; - - typedef QHash< int, boost::shared_ptr<RecordInfo> > RecordInfoMap; - - /// Removes invalid characters in a path component. - QString sanitizeFilenameOrPathComponent(const QString &str) const; - - /// Expands the template variables in |path| for the given |userName|. - QString expandTemplateVariables(const QString &path, const QString& userName) const; - - /// Returns the RecordInfo hashmap index for the given user - int indexForUser(const ClientUser *clientUser) const; - - /// Create a sndfile SF_INFO structure describing the currently configured recording format - SF_INFO createSoundFileInfo() const; - - /// Opens the file for the given recording information - /// Helper function for run method. Will abort recording on failure. - bool ensureFileIsOpenedFor(SF_INFO &soundFileInfo, boost::shared_ptr<RecordInfo> &ri); - - /// Hash which maps the |uiSession| of all users for which we have to keep a recording state to the corresponding RecordInfo object. - RecordInfoMap m_recordInfo; - - /// List containing all unprocessed RecordBuffer objects. - QList< boost::shared_ptr<RecordBuffer> > m_recordBuffer; - - /// The user which is used to record local audio. - boost::scoped_ptr<RecordUser> m_recordUser; - - /// High precision timer for buffer timestamps. - boost::scoped_ptr<Timer> m_timestamp; - - /// Protects the buffer list |qlRecordBuffer|. - QMutex m_bufferLock; - - /// Wait condition and mutex to block until there is new data. - QMutex m_sleepLock; - QWaitCondition m_sleepCondition; - - /// Configuration for this instance - const Config m_config; - - /// True if the main loop is active. - bool m_recording; - - /// Tells the recorder to not finish writing its buffers before returning - bool m_abort; - - /// The timestamp where the recording started. - const QDateTime m_recordingStartTime; - - /// Absolute sample position to assume for buffer adds - quint64 m_absoluteSampleEstimation; + /// Emitted if an error is encountered + void error(int err, QString strerr); + + /// Emitted when recording is started + void recording_started(); + /// Emitted when recording is stopped + void recording_stopped(); + +private: + /// Stores information about a recording buffer. + struct RecordBuffer { + /// Constructs a new RecordBuffer object. + RecordBuffer(int recordInfoIndex_, boost::shared_array< float > buffer_, int samples_, + quint64 absoluteStartSample_); + + /// Hashmap index for the user + const int recordInfoIndex; + + /// The buffer. + boost::shared_array< float > buffer; + + /// The number of samples in the buffer. + int samples; + + /// Absolute sample number at the start of this buffer + quint64 absoluteStartSample; + }; + + /// Stores the recording state for one user. + struct RecordInfo { + RecordInfo(const QString &userName_); + ~RecordInfo(); + + /// Name of the user being recorded + const QString userName; + + /// libsndfile's handle. + SNDFILE *soundFile; + + /// The last absolute sample we wrote for this users + quint64 lastWrittenAbsoluteSample; + }; + + typedef QHash< int, boost::shared_ptr< RecordInfo > > RecordInfoMap; + + /// Removes invalid characters in a path component. + QString sanitizeFilenameOrPathComponent(const QString &str) const; + + /// Expands the template variables in |path| for the given |userName|. + QString expandTemplateVariables(const QString &path, const QString &userName) const; + + /// Returns the RecordInfo hashmap index for the given user + int indexForUser(const ClientUser *clientUser) const; + + /// Create a sndfile SF_INFO structure describing the currently configured recording format + SF_INFO createSoundFileInfo() const; + + /// Opens the file for the given recording information + /// Helper function for run method. Will abort recording on failure. + bool ensureFileIsOpenedFor(SF_INFO &soundFileInfo, boost::shared_ptr< RecordInfo > &ri); + + /// Hash which maps the |uiSession| of all users for which we have to keep a recording state to the corresponding + /// RecordInfo object. + RecordInfoMap m_recordInfo; + + /// List containing all unprocessed RecordBuffer objects. + QList< boost::shared_ptr< RecordBuffer > > m_recordBuffer; + + /// The user which is used to record local audio. + boost::scoped_ptr< RecordUser > m_recordUser; + + /// High precision timer for buffer timestamps. + boost::scoped_ptr< Timer > m_timestamp; + + /// Protects the buffer list |qlRecordBuffer|. + QMutex m_bufferLock; + + /// Wait condition and mutex to block until there is new data. + QMutex m_sleepLock; + QWaitCondition m_sleepCondition; + + /// Configuration for this instance + const Config m_config; + + /// True if the main loop is active. + bool m_recording; + + /// Tells the recorder to not finish writing its buffers before returning + bool m_abort; + + /// The timestamp where the recording started. + const QDateTime m_recordingStartTime; + + /// Absolute sample position to assume for buffer adds + quint64 m_absoluteSampleEstimation; }; -typedef boost::shared_ptr<VoiceRecorder> VoiceRecorderPtr; +typedef boost::shared_ptr< VoiceRecorder > VoiceRecorderPtr; #endif diff --git a/src/mumble/VoiceRecorderDialog.cpp b/src/mumble/VoiceRecorderDialog.cpp index 6227e23ec..5bb482138 100644 --- a/src/mumble/VoiceRecorderDialog.cpp +++ b/src/mumble/VoiceRecorderDialog.cpp @@ -13,7 +13,8 @@ #include <QtWidgets/QFileDialog> #include <QtWidgets/QMessageBox> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" VoiceRecorderDialog::VoiceRecorderDialog(QWidget *p) : QDialog(p), qtTimer(new QTimer(this)) { @@ -29,31 +30,30 @@ VoiceRecorderDialog::VoiceRecorderDialog(QWidget *p) : QDialog(p), qtTimer(new Q qrbDownmix->setChecked(g.s.rmRecordingMode == Settings::RecordingMixdown); qrbMultichannel->setChecked(g.s.rmRecordingMode == Settings::RecordingMultichannel); - QString qsTooltip = QString::fromLatin1( - "%1" - "<table>" - " <tr>" - " <td width=\"25%\">%user</td>" - " <td>%2</td>" - " </tr>" - " <tr>" - " <td>%date</td>" - " <td>%3</td>" - " </tr>" - " <tr>" - " <td>%time</td>" - " <td>%4</td>" - " </tr>" - " <tr>" - " <td>%host</td>" - " <td>%5</td>" - " </tr>" - "</table>"). - arg(tr("Valid variables are:")). - arg(tr("Inserts the user's name")). - arg(tr("Inserts the current date")). - arg(tr("Inserts the current time")). - arg(tr("Inserts the hostname")); + QString qsTooltip = QString::fromLatin1("%1" + "<table>" + " <tr>" + " <td width=\"25%\">%user</td>" + " <td>%2</td>" + " </tr>" + " <tr>" + " <td>%date</td>" + " <td>%3</td>" + " </tr>" + " <tr>" + " <td>%time</td>" + " <td>%4</td>" + " </tr>" + " <tr>" + " <td>%host</td>" + " <td>%5</td>" + " </tr>" + "</table>") + .arg(tr("Valid variables are:")) + .arg(tr("Inserts the user's name")) + .arg(tr("Inserts the current date")) + .arg(tr("Inserts the current time")) + .arg(tr("Inserts the hostname")); qleTargetDirectory->setToolTip(qsTooltip); qleFilename->setToolTip(qsTooltip); @@ -61,7 +61,7 @@ VoiceRecorderDialog::VoiceRecorderDialog(QWidget *p) : QDialog(p), qtTimer(new Q // Populate available codecs Q_ASSERT(VoiceRecorderFormat::kEnd != 0); for (int fm = 0; fm < VoiceRecorderFormat::kEnd; fm++) { - qcbFormat->addItem(VoiceRecorderFormat::getFormatDescription(static_cast<VoiceRecorderFormat::Format>(fm))); + qcbFormat->addItem(VoiceRecorderFormat::getFormatDescription(static_cast< VoiceRecorderFormat::Format >(fm))); } if (g.s.iRecordingFormat < 0 || g.s.iRecordingFormat > VoiceRecorderFormat::kEnd) @@ -78,11 +78,10 @@ void VoiceRecorderDialog::closeEvent(QCloseEvent *evt) { if (g.sh) { VoiceRecorderPtr recorder(g.sh->recorder); if (recorder && recorder->isRunning()) { - int ret = QMessageBox::warning(this, - tr("Recorder still running"), - tr("Closing the recorder without stopping it will discard unwritten audio. Do you really want to close the recorder?"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + int ret = QMessageBox::warning(this, tr("Recorder still running"), + tr("Closing the recorder without stopping it will discard unwritten audio. " + "Do you really want to close the recorder?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::No) { evt->ignore(); @@ -100,7 +99,7 @@ void VoiceRecorderDialog::closeEvent(QCloseEvent *evt) { else g.s.rmRecordingMode = Settings::RecordingMultichannel; - int i = qcbFormat->currentIndex(); + int i = qcbFormat->currentIndex(); g.s.iRecordingFormat = (i == -1) ? 0 : i; reset(); @@ -111,36 +110,29 @@ void VoiceRecorderDialog::closeEvent(QCloseEvent *evt) { void VoiceRecorderDialog::on_qpbStart_clicked() { if (!g.uiSession || !g.sh) { - QMessageBox::critical(this, - tr("Recorder"), - tr("Unable to start recording. Not connected to a server.")); + QMessageBox::critical(this, tr("Recorder"), tr("Unable to start recording. Not connected to a server.")); reset(); return; } if (g.sh->uiVersion < 0x010203) { - QMessageBox::critical(this, - tr("Recorder"), - tr("The server you are currently connected to is version 1.2.2 or older. " - "For privacy reasons, recording on servers of versions older than 1.2.3 " - "is not possible.\nPlease contact your server administrator for further " - "information.")); + QMessageBox::critical(this, tr("Recorder"), + tr("The server you are currently connected to is version 1.2.2 or older. " + "For privacy reasons, recording on servers of versions older than 1.2.3 " + "is not possible.\nPlease contact your server administrator for further " + "information.")); return; } if (g.sh->recorder) { - QMessageBox::information(this, - tr("Recorder"), - tr("There is already a recorder active for this server.")); + QMessageBox::information(this, tr("Recorder"), tr("There is already a recorder active for this server.")); return; } // Check validity of input int ifm = qcbFormat->currentIndex(); if (ifm == -1) { - QMessageBox::critical(this, - tr("Recorder"), - tr("Please select a recording format.")); + QMessageBox::critical(this, tr("Recorder"), tr("Please select a recording format.")); return; } @@ -157,7 +149,7 @@ void VoiceRecorderDialog::on_qpbStart_clicked() { QString basename(fi.baseName()); QString suffix(fi.completeSuffix()); if (suffix.isEmpty()) - suffix = VoiceRecorderFormat::getFormatDefaultExtension(static_cast<VoiceRecorderFormat::Format>(ifm)); + suffix = VoiceRecorderFormat::getFormatDefaultExtension(static_cast< VoiceRecorderFormat::Format >(ifm)); if (basename.isEmpty()) { @@ -174,10 +166,10 @@ void VoiceRecorderDialog::on_qpbStart_clicked() { // Create the recorder VoiceRecorder::Config config; - config.sampleRate = ao->getMixerFreq(); - config.fileName = dir.absoluteFilePath(basename + QLatin1Char('.') + suffix); - config.mixDownMode = qrbDownmix->isChecked(); - config.recordingFormat = static_cast<VoiceRecorderFormat::Format>(ifm); + config.sampleRate = ao->getMixerFreq(); + config.fileName = dir.absoluteFilePath(basename + QLatin1Char('.') + suffix); + config.mixDownMode = qrbDownmix->isChecked(); + config.recordingFormat = static_cast< VoiceRecorderFormat::Format >(ifm); g.sh->recorder.reset(new VoiceRecorder(this, config)); VoiceRecorderPtr recorder(g.sh->recorder); @@ -210,7 +202,7 @@ void VoiceRecorderDialog::on_qpbStop_clicked() { // Stop clock and recording qtTimer->stop(); recorder->stop(); - + // Disable stop botton to indicate we reacted qpbStop->setDisabled(true); qpbStop->setText(tr("Stopping")); @@ -233,15 +225,13 @@ void VoiceRecorderDialog::on_qtTimer_timeout() { return; } - const QTime elapsedTime = QTime(0,0).addMSecs(static_cast<int>(recorder->getElapsedTime() / 1000)); + const QTime elapsedTime = QTime(0, 0).addMSecs(static_cast< int >(recorder->getElapsedTime() / 1000)); qlTime->setText(elapsedTime.toString()); } void VoiceRecorderDialog::on_qpbTargetDirectoryBrowse_clicked() { - QString dir = QFileDialog::getExistingDirectory(this, - tr("Select target directory"), - QString(), - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + QString dir = QFileDialog::getExistingDirectory(this, tr("Select target directory"), QString(), + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!dir.isEmpty()) qleTargetDirectory->setText(dir); } @@ -279,9 +269,6 @@ void VoiceRecorderDialog::onRecorderStarted() { void VoiceRecorderDialog::onRecorderError(int err, QString strerr) { Q_UNUSED(err); - QMessageBox::critical(this, - tr("Recorder"), - strerr); + QMessageBox::critical(this, tr("Recorder"), strerr); reset(false); } - diff --git a/src/mumble/VoiceRecorderDialog.h b/src/mumble/VoiceRecorderDialog.h index bc7794f69..2d4973cde 100644 --- a/src/mumble/VoiceRecorderDialog.h +++ b/src/mumble/VoiceRecorderDialog.h @@ -11,27 +11,28 @@ #include "ui_VoiceRecorderDialog.h" class VoiceRecorderDialog : public QDialog, private Ui::VoiceRecorderDialog { - private: - Q_OBJECT - Q_DISABLE_COPY(VoiceRecorderDialog) - - QTimer *qtTimer; - public: - explicit VoiceRecorderDialog(QWidget *p = nullptr); - ~VoiceRecorderDialog() Q_DECL_OVERRIDE; - - void closeEvent(QCloseEvent *evt) Q_DECL_OVERRIDE; - public slots: - void on_qpbStart_clicked(); - void on_qpbStop_clicked(); - void on_qtTimer_timeout(); - void on_qpbTargetDirectoryBrowse_clicked(); - - void onRecorderStopped(); - void onRecorderStarted(); - void onRecorderError(int err, QString strerr); - - void reset(bool resettimer=true); +private: + Q_OBJECT + Q_DISABLE_COPY(VoiceRecorderDialog) + + QTimer *qtTimer; + +public: + explicit VoiceRecorderDialog(QWidget *p = nullptr); + ~VoiceRecorderDialog() Q_DECL_OVERRIDE; + + void closeEvent(QCloseEvent *evt) Q_DECL_OVERRIDE; +public slots: + void on_qpbStart_clicked(); + void on_qpbStop_clicked(); + void on_qtTimer_timeout(); + void on_qpbTargetDirectoryBrowse_clicked(); + + void onRecorderStopped(); + void onRecorderStarted(); + void onRecorderError(int err, QString strerr); + + void reset(bool resettimer = true); }; #endif // VOICERECORDERDIALOG_H_ diff --git a/src/mumble/WASAPI.cpp b/src/mumble/WASAPI.cpp index c942eab45..53338b3e3 100644 --- a/src/mumble/WASAPI.cpp +++ b/src/mumble/WASAPI.cpp @@ -9,30 +9,29 @@ #ifdef __MINGW32__ // Fix a redefinition issue in protobuf's "strutil.h" include file: // "redefinition of 'std::__cxx11::string google::protobuf::StrCat_instead_use_StringCbCat_or_StringCchCat'" -# ifdef StrCat -# undef StrCat -# endif +# ifdef StrCat +# undef StrCat +# endif #endif #include "MainWindow.h" #include "Utils.h" -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" // Now that Win7 is published, which includes public versions of these // interfaces, we simply inherit from those but use the "old" IIDs. -DEFINE_GUID(IID_IVistaAudioSessionControl2, 0x33969B1DL, 0xD06F, 0x4281, 0xB8, 0x37, 0x7E, 0xAA, 0xFD, 0x21, 0xA9, 0xC0); +DEFINE_GUID(IID_IVistaAudioSessionControl2, 0x33969B1DL, 0xD06F, 0x4281, 0xB8, 0x37, 0x7E, 0xAA, 0xFD, 0x21, 0xA9, + 0xC0); MIDL_INTERFACE("33969B1D-D06F-4281-B837-7EAAFD21A9C0") -IVistaAudioSessionControl2 : -public IAudioSessionControl2 { -}; +IVistaAudioSessionControl2 : public IAudioSessionControl2{}; DEFINE_GUID(IID_IAudioSessionQuery, 0x94BE9D30L, 0x53AC, 0x4802, 0x82, 0x9C, 0xF1, 0x3E, 0x5A, 0xD3, 0x47, 0x75); MIDL_INTERFACE("94BE9D30-53AC-4802-829C-F13E5AD34775") -IAudioSessionQuery : -public IUnknown { +IAudioSessionQuery : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetQueryInterface(IAudioSessionEnumerator **) = 0; }; @@ -50,32 +49,33 @@ static ERole WASAPIRoleFromSettings() { } class WASAPIInputRegistrar : public AudioInputRegistrar { - public: - WASAPIInputRegistrar(); - virtual AudioInput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); - virtual bool canEcho(const QString &) const; - virtual bool canExclusive() const; +public: + WASAPIInputRegistrar(); + virtual AudioInput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); + virtual bool canEcho(const QString &) const; + virtual bool canExclusive() const; }; class WASAPIOutputRegistrar : public AudioOutputRegistrar { - public: - WASAPIOutputRegistrar(); - virtual AudioOutput *create(); - virtual const QList<audioDevice> getDeviceChoices(); - virtual void setDeviceChoice(const QVariant &, Settings &); - bool canMuteOthers() const; - virtual bool canExclusive() const; +public: + WASAPIOutputRegistrar(); + virtual AudioOutput *create(); + virtual const QList< audioDevice > getDeviceChoices(); + virtual void setDeviceChoice(const QVariant &, Settings &); + bool canMuteOthers() const; + virtual bool canExclusive() const; }; class WASAPIInit : public DeferInit { - WASAPIInputRegistrar *wirReg; - WASAPIOutputRegistrar *worReg; - public: - WASAPIInit() : wirReg(nullptr), worReg(nullptr) { } - void initialize(); - void destroy(); + WASAPIInputRegistrar *wirReg; + WASAPIOutputRegistrar *worReg; + +public: + WASAPIInit() : wirReg(nullptr), worReg(nullptr) {} + void initialize(); + void destroy(); }; static WASAPIInit wasapiinit; @@ -86,7 +86,7 @@ void WASAPIInit::initialize() { wirReg = nullptr; worReg = nullptr; - if (! bIsVistaSP1) { + if (!bIsVistaSP1) { qWarning("WASAPIInit: Requires Vista SP1"); return; } @@ -114,7 +114,7 @@ WASAPIInputRegistrar::WASAPIInputRegistrar() : AudioInputRegistrar(QLatin1String /// Calls getMixFormat on given IAudioClient and checks whether it is compatible. /// At the moment this means the format is either 32bit float or 16bit PCM. -/// +/// /// @param sourceName Name to prepend to log in case of error /// @param deviceName Device name to refer to in case of error /// @param audioClient IAudioClient to get and check mix format for @@ -123,31 +123,28 @@ WASAPIInputRegistrar::WASAPIInputRegistrar() : AudioInputRegistrar(QLatin1String /// @param sampleFormat Receives either SampleFloat or SampleShort as valid format /// @return True if mix format is ok. False if incompatible or another error occured. -template <typename SAMPLEFORMAT> // Template on SampleFormat enum as AudioOutput and AudioInput each define their own -bool getAndCheckMixFormat(const char* sourceName, - const char* deviceName, - IAudioClient* audioClient, - WAVEFORMATEX **waveFormatEx, - WAVEFORMATEXTENSIBLE **waveFormatExtensible, - SAMPLEFORMAT *sampleFormat) { - - *waveFormatEx = nullptr; +template< typename SAMPLEFORMAT > // Template on SampleFormat enum as AudioOutput and AudioInput each define their own +bool getAndCheckMixFormat(const char *sourceName, const char *deviceName, IAudioClient *audioClient, + WAVEFORMATEX **waveFormatEx, WAVEFORMATEXTENSIBLE **waveFormatExtensible, + SAMPLEFORMAT *sampleFormat) { + *waveFormatEx = nullptr; *waveFormatExtensible = nullptr; - + HRESULT hr = audioClient->GetMixFormat(waveFormatEx); if (FAILED(hr)) { qWarning("%s: %s GetMixFormat failed: hr=0x%08lx", sourceName, deviceName, hr); return false; } - + if ((*waveFormatEx)->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { - (*waveFormatExtensible) = reinterpret_cast<WAVEFORMATEXTENSIBLE *>((*waveFormatEx)); + (*waveFormatExtensible) = reinterpret_cast< WAVEFORMATEXTENSIBLE * >((*waveFormatEx)); if ((*waveFormatExtensible)->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) { *sampleFormat = SAMPLEFORMAT::SampleFloat; } else if ((*waveFormatExtensible)->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) { *sampleFormat = SAMPLEFORMAT::SampleShort; } else { - qWarning() << sourceName << ":" << deviceName << "Subformat is not IEEE Float or PCM but:" << (*waveFormatExtensible)->SubFormat; + qWarning() << sourceName << ":" << deviceName + << "Subformat is not IEEE Float or PCM but:" << (*waveFormatExtensible)->SubFormat; return false; } } else { @@ -156,26 +153,30 @@ bool getAndCheckMixFormat(const char* sourceName, } else if ((*waveFormatEx)->wFormatTag != WAVE_FORMAT_PCM) { *sampleFormat = SAMPLEFORMAT::SampleShort; } else { - qWarning() << sourceName << ":" << deviceName << "format tag is not IEEE Float or PCM but:" << (*waveFormatEx)->wFormatTag; + qWarning() << sourceName << ":" << deviceName + << "format tag is not IEEE Float or PCM but:" << (*waveFormatEx)->wFormatTag; return false; } } - + if (*sampleFormat == SAMPLEFORMAT::SampleFloat) { if ((*waveFormatEx)->wBitsPerSample != (sizeof(float) * 8)) { - qWarning() << sourceName << ":" << deviceName << "unexpected number of bits per sample for IEEE Float:" << (*waveFormatEx)->wBitsPerSample; + qWarning() << sourceName << ":" << deviceName + << "unexpected number of bits per sample for IEEE Float:" << (*waveFormatEx)->wBitsPerSample; return false; } } else if (*sampleFormat == SAMPLEFORMAT::SampleShort) { if ((*waveFormatEx)->wBitsPerSample != (sizeof(short) * 8)) { - qWarning() << sourceName << ":" << deviceName << "unexpected number of bits per sample for PCM:" << (*waveFormatEx)->wBitsPerSample; + qWarning() << sourceName << ":" << deviceName + << "unexpected number of bits per sample for PCM:" << (*waveFormatEx)->wBitsPerSample; return false; } } else { - qFatal("%s: %s unexpected sample format %lu", sourceName, deviceName, static_cast<unsigned long>(*sampleFormat)); + qFatal("%s: %s unexpected sample format %lu", sourceName, deviceName, + static_cast< unsigned long >(*sampleFormat)); return false; } - + return true; } @@ -184,7 +185,7 @@ AudioInput *WASAPIInputRegistrar::create() { return new WASAPIInput(); } -const QList<audioDevice> WASAPIInputRegistrar::getDeviceChoices() { +const QList< audioDevice > WASAPIInputRegistrar::getDeviceChoices() { return WASAPISystem::mapToDevice(WASAPISystem::getInputDevices(), g.s.qsWASAPIInput); } @@ -207,7 +208,7 @@ AudioOutput *WASAPIOutputRegistrar::create() { return new WASAPIOutput(); } -const QList<audioDevice> WASAPIOutputRegistrar::getDeviceChoices() { +const QList< audioDevice > WASAPIOutputRegistrar::getDeviceChoices() { return WASAPISystem::mapToDevice(WASAPISystem::getOutputDevices(), g.s.qsWASAPIOutput); } @@ -223,37 +224,38 @@ bool WASAPIOutputRegistrar::canExclusive() const { return true; } -const QHash<QString, QString> WASAPISystem::getInputDevices() { +const QHash< QString, QString > WASAPISystem::getInputDevices() { return getDevices(eCapture); } -const QHash<QString, QString> WASAPISystem::getOutputDevices() { +const QHash< QString, QString > WASAPISystem::getOutputDevices() { return getDevices(eRender); } -const QHash<QString, QString> WASAPISystem::getDevices(EDataFlow dataflow) { - QHash<QString, QString> devices; +const QHash< QString, QString > WASAPISystem::getDevices(EDataFlow dataflow) { + QHash< QString, QString > devices; HRESULT hr; IMMDeviceEnumerator *pEnumerator = nullptr; IMMDeviceCollection *pCollection = nullptr; - hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void **>(&pEnumerator)); + hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), + reinterpret_cast< void ** >(&pEnumerator)); - if (! pEnumerator || FAILED(hr)) { + if (!pEnumerator || FAILED(hr)) { qWarning("WASAPI: Failed to instatiate enumerator: hr=0x%08lx", hr); } else { hr = pEnumerator->EnumAudioEndpoints(dataflow, DEVICE_STATE_ACTIVE, &pCollection); - if (! pCollection || FAILED(hr)) { + if (!pCollection || FAILED(hr)) { qWarning("WASAPI: Failed to enumerate: hr=0x%08lx", hr); } else { devices.insert(QString(), tr("Default Device")); UINT ndev = 0; pCollection->GetCount(&ndev); - for (unsigned int idx=0;idx<ndev;++idx) { - IMMDevice *pDevice = nullptr; + for (unsigned int idx = 0; idx < ndev; ++idx) { + IMMDevice *pDevice = nullptr; IPropertyStore *pStore = nullptr; pCollection->Item(idx, &pDevice); @@ -283,8 +285,8 @@ const QHash<QString, QString> WASAPISystem::getDevices(EDataFlow dataflow) { return devices; } -const QList<audioDevice> WASAPISystem::mapToDevice(const QHash<QString, QString>& devs, const QString& match) { - QList<audioDevice> qlReturn; +const QList< audioDevice > WASAPISystem::mapToDevice(const QHash< QString, QString > &devs, const QString &match) { + QList< audioDevice > qlReturn; QStringList qlDevices = devs.keys(); std::sort(qlDevices.begin(), qlDevices.end()); @@ -294,25 +296,23 @@ const QList<audioDevice> WASAPISystem::mapToDevice(const QHash<QString, QString> qlDevices.prepend(match); } - foreach(const QString &dev, qlDevices) { - qlReturn << audioDevice(devs.value(dev), dev); - } + foreach (const QString &dev, qlDevices) { qlReturn << audioDevice(devs.value(dev), dev); } return qlReturn; } -WASAPIInput::WASAPIInput() { -}; +WASAPIInput::WASAPIInput(){}; WASAPIInput::~WASAPIInput() { bRunning = false; wait(); } -static IMMDevice *openNamedOrDefaultDevice(const QString& name, EDataFlow dataFlow, ERole role) { +static IMMDevice *openNamedOrDefaultDevice(const QString &name, EDataFlow dataFlow, ERole role) { HRESULT hr; IMMDeviceEnumerator *pEnumerator = nullptr; - hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void **>(&pEnumerator)); + hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), + reinterpret_cast< void ** >(&pEnumerator)); if (!pEnumerator || FAILED(hr)) { qWarning("WASAPI: Failed to instantiate enumerator: hr=0x%08lx", hr); return nullptr; @@ -322,11 +322,12 @@ static IMMDevice *openNamedOrDefaultDevice(const QString& name, EDataFlow dataFl // Try to find a device pointer for |name|. if (!name.isEmpty()) { STACKVAR(wchar_t, devname, name.length() + 1); - int len = name.toWCharArray(devname); + int len = name.toWCharArray(devname); devname[len] = 0; - hr = pEnumerator->GetDevice(devname, &pDevice); + hr = pEnumerator->GetDevice(devname, &pDevice); if (FAILED(hr)) { - qWarning("WASAPI: Failed to open selected device %s %ls (df=%d, e=%d, hr=0x%08lx), falling back to default", qPrintable(name), devname, dataFlow, role, hr); + qWarning("WASAPI: Failed to open selected device %s %ls (df=%d, e=%d, hr=0x%08lx), falling back to default", + qPrintable(name), devname, dataFlow, role, hr); } else { WASAPINotificationClient::get().enlistDeviceAsUsed(devname); } @@ -343,7 +344,7 @@ static IMMDevice *openNamedOrDefaultDevice(const QString& name, EDataFlow dataFl goto cleanup; } wchar_t *devname = nullptr; - hr = pDevice->GetId(&devname); + hr = pDevice->GetId(&devname); if (FAILED(hr)) { qWarning("WASAPI: Failed to query device: df=%d, e=%d, hr=0x%08lx", dataFlow, role, hr); goto cleanup; @@ -367,11 +368,11 @@ cleanup: void WASAPIInput::run() { HRESULT hr; - IMMDevice *pMicDevice = nullptr; - IAudioClient *pMicAudioClient = nullptr; - IAudioCaptureClient *pMicCaptureClient = nullptr; - IMMDevice *pEchoDevice = nullptr; - IAudioClient *pEchoAudioClient = nullptr; + IMMDevice *pMicDevice = nullptr; + IAudioClient *pMicAudioClient = nullptr; + IAudioCaptureClient *pMicCaptureClient = nullptr; + IMMDevice *pEchoDevice = nullptr; + IAudioClient *pEchoAudioClient = nullptr; IAudioCaptureClient *pEchoCaptureClient = nullptr; WAVEFORMATEX *micpwfx = nullptr, *echopwfx = nullptr; WAVEFORMATEXTENSIBLE *micpwfxe = nullptr, *echopwfxe = nullptr; @@ -389,7 +390,7 @@ void WASAPIInput::run() { HANDLE hMmThread; float *tbuff = nullptr; short *sbuff = nullptr; - bool doecho = g.s.doEcho(); + bool doecho = g.s.doEcho(); REFERENCE_TIME def, min, latency, want; bool exclusive = false; @@ -424,62 +425,64 @@ void WASAPIInput::run() { pMicAudioClient->GetDevicePeriod(&def, &min); - want = qMax<REFERENCE_TIME>(min, 100000); + want = qMax< REFERENCE_TIME >(min, 100000); qWarning("WASAPIInput: Latencies %lld %lld => %lld", def, min, want); - if (g.s.bExclusiveInput && ! doecho) { - for (int channels = 1; channels<=2; ++channels) { + if (g.s.bExclusiveInput && !doecho) { + for (int channels = 1; channels <= 2; ++channels) { ZeroMemory(&wfe, sizeof(wfe)); - wfe.Format.cbSize = 0; - wfe.Format.wFormatTag = WAVE_FORMAT_PCM; - wfe.Format.nChannels = channels; - wfe.Format.nSamplesPerSec = 48000; - wfe.Format.wBitsPerSample = 16; - wfe.Format.nBlockAlign = wfe.Format.nChannels * wfe.Format.wBitsPerSample / 8; + wfe.Format.cbSize = 0; + wfe.Format.wFormatTag = WAVE_FORMAT_PCM; + wfe.Format.nChannels = channels; + wfe.Format.nSamplesPerSec = 48000; + wfe.Format.wBitsPerSample = 16; + wfe.Format.nBlockAlign = wfe.Format.nChannels * wfe.Format.wBitsPerSample / 8; wfe.Format.nAvgBytesPerSec = wfe.Format.nBlockAlign * wfe.Format.nSamplesPerSec; micpwfxe = &wfe; - micpwfx = reinterpret_cast<WAVEFORMATEX *>(&wfe); + micpwfx = reinterpret_cast< WAVEFORMATEX * >(&wfe); - hr = pMicAudioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, want, want, micpwfx, nullptr); + hr = pMicAudioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, want, want, + micpwfx, nullptr); if (SUCCEEDED(hr)) { eMicFormat = SampleShort; - exclusive = true; + exclusive = true; qWarning("WASAPIInput: Successfully opened exclusive mode"); break; } micpwfxe = nullptr; - micpwfx = nullptr; + micpwfx = nullptr; } } - if (! micpwfxe) { + if (!micpwfxe) { if (g.s.bExclusiveInput) qWarning("WASAPIInput: Failed to open exclusive mode."); - - if (!getAndCheckMixFormat("WASAPIInput", "Mic", pMicAudioClient, - &micpwfx, &micpwfxe, &eMicFormat)) { + + if (!getAndCheckMixFormat("WASAPIInput", "Mic", pMicAudioClient, &micpwfx, &micpwfxe, &eMicFormat)) { goto cleanup; } - hr = pMicAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, micpwfx, nullptr); + hr = pMicAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, micpwfx, + nullptr); if (FAILED(hr)) { qWarning("WASAPIInput: Mic Initialize failed: hr=0x%08lx", hr); if (hr == E_ACCESSDENIED) { - g.mw->msgBox(tr("Access to the microphone was denied. Please check that your operating system's microphone settings allow Mumble to use the microphone.")); + g.mw->msgBox(tr("Access to the microphone was denied. Please check that your operating system's " + "microphone settings allow Mumble to use the microphone.")); } goto cleanup; } } - + qWarning() << "WASAPIInput: Mic Stream format" << eMicFormat; pMicAudioClient->GetStreamLatency(&latency); hr = pMicAudioClient->GetBufferSize(&bufferFrameCount); qWarning("WASAPIInput: Stream Latency %lld (%d)", latency, bufferFrameCount); - hr = pMicAudioClient->GetService(__uuidof(IAudioCaptureClient), (void**)&pMicCaptureClient); + hr = pMicAudioClient->GetService(__uuidof(IAudioCaptureClient), (void **) &pMicCaptureClient); if (FAILED(hr)) { qWarning("WASAPIInput: Mic GetService failed: hr=0x%08lx", hr); goto cleanup; @@ -498,7 +501,7 @@ void WASAPIInput::run() { } iMicChannels = micpwfx->nChannels; - iMicFreq = micpwfx->nSamplesPerSec; + iMicFreq = micpwfx->nSamplesPerSec; if (doecho) { hr = pEchoDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void **) &pEchoAudioClient); @@ -506,20 +509,21 @@ void WASAPIInput::run() { qWarning("WASAPIInput: Activate Echo AudioClient failed: hr=0x%08lx", hr); goto cleanup; } - - if (!getAndCheckMixFormat("WASAPIInput", "Echo", pEchoAudioClient, - &echopwfx, &echopwfxe, &eEchoFormat)) { + + if (!getAndCheckMixFormat("WASAPIInput", "Echo", pEchoAudioClient, &echopwfx, &echopwfxe, &eEchoFormat)) { goto cleanup; } - hr = pEchoAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, echopwfx, nullptr); + hr = pEchoAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, + echopwfx, nullptr); if (FAILED(hr)) { qWarning("WASAPIInput: Echo Initialize failed: hr=0x%08lx", hr); goto cleanup; } hr = pEchoAudioClient->GetBufferSize(&bufferFrameCount); - hr = pEchoAudioClient->GetService(__uuidof(IAudioCaptureClient), (void**)&pEchoCaptureClient); + hr = pEchoAudioClient->GetService(__uuidof(IAudioCaptureClient), (void **) &pEchoCaptureClient); if (FAILED(hr)) { qWarning("WASAPIInput: Echo GetService failed: hr=0x%08lx", hr); goto cleanup; @@ -536,11 +540,11 @@ void WASAPIInput::run() { qWarning("WASAPIInput: Failed to start Echo: hr=0x%08lx", hr); goto cleanup; } - + qWarning() << "WASAPIInput: Echo Stream format" << eEchoFormat; iEchoChannels = echopwfx->nChannels; - iEchoFreq = echopwfx->nSamplesPerSec; + iEchoFreq = echopwfx->nSamplesPerSec; } initializeMixer(); @@ -549,7 +553,7 @@ void WASAPIInput::run() { if (exclusive) { sbuff = new short[allocLength]; - while (bRunning && ! FAILED(hr)) { + while (bRunning && !FAILED(hr)) { hr = pMicCaptureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, &qpcPosition); if (hr != AUDCLNT_S_BUFFER_EMPTY) { if (FAILED(hr)) @@ -557,9 +561,9 @@ void WASAPIInput::run() { UINT32 nFrames = numFramesAvailable * micpwfx->nChannels; if (nFrames > allocLength) { - delete [] sbuff; + delete[] sbuff; allocLength = nFrames; - sbuff = new short[allocLength]; + sbuff = new short[allocLength]; } memcpy(sbuff, pData, nFrames * sizeof(short)); @@ -568,14 +572,14 @@ void WASAPIInput::run() { goto cleanup; addMic(sbuff, numFramesAvailable); } - if (! FAILED(hr)) + if (!FAILED(hr)) WaitForSingleObject(hEvent, 100); } } else { tbuff = new float[allocLength]; - while (bRunning && ! FAILED(hr)) { + while (bRunning && !FAILED(hr)) { hr = pMicCaptureClient->GetNextPacketSize(&micPacketLength); - if (! FAILED(hr) && iEchoChannels) + if (!FAILED(hr) && iEchoChannels) hr = pEchoCaptureClient->GetNextPacketSize(&echoPacketLength); if (FAILED(hr)) { qWarning("WASAPIInput: GetNextPacketSize failed: hr=0x%08lx", hr); @@ -584,7 +588,8 @@ void WASAPIInput::run() { while ((micPacketLength > 0) || (echoPacketLength > 0)) { if (echoPacketLength > 0) { - hr = pEchoCaptureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, &qpcPosition); + hr = pEchoCaptureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, + &qpcPosition); if (FAILED(hr)) { qWarning("WASAPIInput: GetBuffer failed: hr=0x%08lx", hr); goto cleanup; @@ -592,9 +597,9 @@ void WASAPIInput::run() { UINT32 nFrames = numFramesAvailable * echopwfx->nChannels; if (nFrames > allocLength) { - delete [] tbuff; + delete[] tbuff; allocLength = nFrames; - tbuff = new float[allocLength]; + tbuff = new float[allocLength]; } memcpy(tbuff, pData, nFrames * sizeof(float)); hr = pEchoCaptureClient->ReleaseBuffer(numFramesAvailable); @@ -604,7 +609,8 @@ void WASAPIInput::run() { } addEcho(tbuff, numFramesAvailable); } else if (micPacketLength > 0) { - hr = pMicCaptureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, &qpcPosition); + hr = pMicCaptureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, + &qpcPosition); if (FAILED(hr)) { qWarning("WASAPIInput: GetBuffer failed: hr=0x%08lx", hr); goto cleanup; @@ -612,9 +618,9 @@ void WASAPIInput::run() { UINT32 nFrames = numFramesAvailable * micpwfx->nChannels; if (nFrames > allocLength) { - delete [] tbuff; + delete[] tbuff; allocLength = nFrames; - tbuff = new float[allocLength]; + tbuff = new float[allocLength]; } memcpy(tbuff, pData, nFrames * sizeof(float)); hr = pMicCaptureClient->ReleaseBuffer(numFramesAvailable); @@ -625,10 +631,10 @@ void WASAPIInput::run() { addMic(tbuff, numFramesAvailable); } hr = pMicCaptureClient->GetNextPacketSize(&micPacketLength); - if (! FAILED(hr) && iEchoChannels) + if (!FAILED(hr) && iEchoChannels) hr = pEchoCaptureClient->GetNextPacketSize(&echoPacketLength); } - if (! FAILED(hr)) + if (!FAILED(hr)) WaitForSingleObject(hEvent, 2000); } } @@ -663,8 +669,8 @@ cleanup: if (hEvent) CloseHandle(hEvent); - delete [] tbuff; - delete [] sbuff; + delete[] tbuff; + delete[] sbuff; } WASAPIOutput::WASAPIOutput() { @@ -678,11 +684,11 @@ WASAPIOutput::~WASAPIOutput() { void WASAPIOutput::setVolumes(IMMDevice *pDevice, bool talking) { HRESULT hr; - if (! talking) { - QMap<ISimpleAudioVolume *, VolumePair>::const_iterator i; - for (i=qmVolumes.constBegin(); i != qmVolumes.constEnd(); ++i) { + if (!talking) { + QMap< ISimpleAudioVolume *, VolumePair >::const_iterator i; + for (i = qmVolumes.constBegin(); i != qmVolumes.constEnd(); ++i) { float fVolume = 1.0f; - hr = i.key()->GetMasterVolume(&fVolume); + hr = i.key()->GetMasterVolume(&fVolume); if (qFuzzyCompare(i.value().second, fVolume)) hr = i.key()->SetMasterVolume(i.value().first, nullptr); i.key()->Release(); @@ -692,8 +698,8 @@ void WASAPIOutput::setVolumes(IMMDevice *pDevice, bool talking) { } IAudioSessionManager2 *pAudioSessionManager = nullptr; - int max = 0; - DWORD dwMumble = GetCurrentProcessId(); + int max = 0; + DWORD dwMumble = GetCurrentProcessId(); qmVolumes.clear(); if (qFuzzyCompare(g.s.fOtherVolume, 1.0f)) @@ -701,10 +707,11 @@ void WASAPIOutput::setVolumes(IMMDevice *pDevice, bool talking) { // FIXME: Try to keep the session object around when returning volume. - if (SUCCEEDED(hr = pDevice->Activate(bIsWin7 ? __uuidof(IAudioSessionManager2) : __uuidof(IAudioSessionManager), CLSCTX_ALL, nullptr, (void **) &pAudioSessionManager))) { + if (SUCCEEDED(hr = pDevice->Activate(bIsWin7 ? __uuidof(IAudioSessionManager2) : __uuidof(IAudioSessionManager), + CLSCTX_ALL, nullptr, (void **) &pAudioSessionManager))) { IAudioSessionEnumerator *pEnumerator = nullptr; - IAudioSessionQuery *pMysticQuery = nullptr; - if (! bIsWin7) { + IAudioSessionQuery *pMysticQuery = nullptr; + if (!bIsWin7) { if (SUCCEEDED(hr = pAudioSessionManager->QueryInterface(IID_IAudioSessionQuery, (void **) &pMysticQuery))) { hr = pMysticQuery->GetQueryInterface(&pEnumerator); } @@ -712,11 +719,11 @@ void WASAPIOutput::setVolumes(IMMDevice *pDevice, bool talking) { hr = pAudioSessionManager->GetSessionEnumerator(&pEnumerator); } - QSet<QUuid> seen; + QSet< QUuid > seen; if (SUCCEEDED(hr)) { if (SUCCEEDED(hr = pEnumerator->GetCount(&max))) { - for (int i=0;i<max;++i) { + for (int i = 0; i < max; ++i) { IAudioSessionControl *pControl = nullptr; if (SUCCEEDED(hr = pEnumerator->GetSession(i, &pControl))) { setVolumeForSessionControl(pControl, dwMumble, seen); @@ -732,64 +739,68 @@ void WASAPIOutput::setVolumes(IMMDevice *pDevice, bool talking) { } } -bool WASAPIOutput::setVolumeForSessionControl2(IAudioSessionControl2 *control2, const DWORD mumblePID, QSet<QUuid> &seen) { +bool WASAPIOutput::setVolumeForSessionControl2(IAudioSessionControl2 *control2, const DWORD mumblePID, + QSet< QUuid > &seen) { HRESULT hr; DWORD pid; - + // Don't set the volume for our own control if (FAILED(hr = control2->GetProcessId(&pid)) || (pid == mumblePID)) return true; - + // Don't work on expired audio sessions AudioSessionState ass; if (FAILED(hr = control2->GetState(&ass)) || (ass == AudioSessionStateExpired)) return false; - + // Don't act twice on the same session GUID group; if (FAILED(hr = control2->GetGroupingParam(&group))) return false; - + QUuid quuid(group); if (seen.contains(quuid)) return true; - + seen.insert(quuid); - + // Adjust volume ISimpleAudioVolume *pVolume = nullptr; if (FAILED(hr = control2->QueryInterface(__uuidof(ISimpleAudioVolume), (void **) &pVolume))) return false; - + BOOL bMute = TRUE; - bool keep = false; - if (SUCCEEDED(hr = pVolume->GetMute(&bMute)) && ! bMute) { + bool keep = false; + if (SUCCEEDED(hr = pVolume->GetMute(&bMute)) && !bMute) { float fVolume = 1.0f; - if (SUCCEEDED(hr = pVolume->GetMasterVolume(&fVolume)) && ! qFuzzyCompare(fVolume,0.0f)) { + if (SUCCEEDED(hr = pVolume->GetMasterVolume(&fVolume)) && !qFuzzyCompare(fVolume, 0.0f)) { float fSetVolume = fVolume * g.s.fOtherVolume; if (SUCCEEDED(hr = pVolume->SetMasterVolume(fSetVolume, nullptr))) { hr = pVolume->GetMasterVolume(&fSetVolume); - qmVolumes.insert(pVolume, VolumePair(fVolume,fSetVolume)); + qmVolumes.insert(pVolume, VolumePair(fVolume, fSetVolume)); keep = true; } } } - - if (! keep) + + if (!keep) pVolume->Release(); - + return true; } -bool WASAPIOutput::setVolumeForSessionControl(IAudioSessionControl *control, const DWORD mumblePID, QSet<QUuid> &seen) { +bool WASAPIOutput::setVolumeForSessionControl(IAudioSessionControl *control, const DWORD mumblePID, + QSet< QUuid > &seen) { HRESULT hr; IAudioSessionControl2 *pControl2 = nullptr; - if (!SUCCEEDED(hr = control->QueryInterface(bIsWin7 ? __uuidof(IAudioSessionControl2) : IID_IVistaAudioSessionControl2, (void **) &pControl2))) + if (!SUCCEEDED( + hr = control->QueryInterface(bIsWin7 ? __uuidof(IAudioSessionControl2) : IID_IVistaAudioSessionControl2, + (void **) &pControl2))) return false; - + bool result = setVolumeForSessionControl2(pControl2, mumblePID, seen); - + pControl2->Release(); return result; } @@ -800,11 +811,12 @@ static void SetDuckingOptOut(IMMDevice *pDevice) { HRESULT hr; IAudioSessionManager2 *pSessionManager2 = nullptr; - IAudioSessionControl *pSessionControl = nullptr; + IAudioSessionControl *pSessionControl = nullptr; IAudioSessionControl2 *pSessionControl2 = nullptr; // Get session manager & control1+2 to disable ducking - hr = pDevice->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(&pSessionManager2)); + hr = pDevice->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, nullptr, + reinterpret_cast< void ** >(&pSessionManager2)); if (FAILED(hr)) { qWarning("WASAPIOutput: Activate AudioSessionManager2 failed: hr=0x%08lx", hr); goto cleanup; @@ -816,7 +828,8 @@ static void SetDuckingOptOut(IMMDevice *pDevice) { goto cleanup; } - hr = pSessionControl->QueryInterface(__uuidof(IAudioSessionControl2), reinterpret_cast<void**>(&pSessionControl2)); + hr = pSessionControl->QueryInterface(__uuidof(IAudioSessionControl2), + reinterpret_cast< void ** >(&pSessionControl2)); if (FAILED(hr)) { qWarning("WASAPIOutput: Querying SessionControl2 failed: hr=0x%08lx", hr); goto cleanup; @@ -841,11 +854,11 @@ cleanup: void WASAPIOutput::run() { HRESULT hr; - IMMDevice *pDevice = nullptr; - IAudioClient *pAudioClient = nullptr; + IMMDevice *pDevice = nullptr; + IAudioClient *pAudioClient = nullptr; IAudioRenderClient *pRenderClient = nullptr; - WAVEFORMATEX *pwfx = nullptr; - WAVEFORMATEXTENSIBLE *pwfxe = nullptr; + WAVEFORMATEX *pwfx = nullptr; + WAVEFORMATEXTENSIBLE *pwfxe = nullptr; UINT32 bufferFrameCount; REFERENCE_TIME def, min, latency, want; UINT32 numFramesAvailable; @@ -855,11 +868,11 @@ void WASAPIOutput::run() { HANDLE hMmThread; int ns = 0; unsigned int chanmasks[32]; - QMap<DWORD, float> qmVolumes; - bool lastspoke = false; + QMap< DWORD, float > qmVolumes; + bool lastspoke = false; REFERENCE_TIME bufferDuration = (g.s.iOutputDelay > 1) ? (g.s.iOutputDelay + 1) * 100000 : 0; - bool exclusive = false; - bool mixed = false; + bool exclusive = false; + bool mixed = false; CoInitialize(nullptr); @@ -885,7 +898,7 @@ void WASAPIOutput::run() { } pAudioClient->GetDevicePeriod(&def, &min); - want = qMax<REFERENCE_TIME>(min, 100000); + want = qMax< REFERENCE_TIME >(min, 100000); qWarning("WASAPIOutput: Latencies %lld %lld => %lld", def, min, want); if (g.s.bExclusiveOutput) { @@ -896,7 +909,7 @@ void WASAPIOutput::run() { } if (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { - pwfxe = reinterpret_cast<WAVEFORMATEXTENSIBLE *>(pwfx); + pwfxe = reinterpret_cast< WAVEFORMATEXTENSIBLE * >(pwfx); } if (!g.s.bPositionalAudio) { @@ -913,38 +926,38 @@ void WASAPIOutput::run() { } else { pwfx->wFormatTag = WAVE_FORMAT_PCM; } - pwfx->nSamplesPerSec = 48000; - pwfx->wBitsPerSample = 16; - pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8; + pwfx->nSamplesPerSec = 48000; + pwfx->wBitsPerSample = 16; + pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8; pwfx->nAvgBytesPerSec = pwfx->nBlockAlign * pwfx->nSamplesPerSec; - hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, want, want, pwfx, nullptr); + hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, want, want, pwfx, + nullptr); if (SUCCEEDED(hr)) { eSampleFormat = SampleShort; - exclusive = true; + exclusive = true; qWarning("WASAPIOutput: Successfully opened exclusive mode"); } else { CoTaskMemFree(pwfx); pwfxe = nullptr; - pwfx = nullptr; + pwfx = nullptr; } } if (!pwfx) { if (g.s.bExclusiveOutput) qWarning("WASAPIOutput: Failed to open exclusive mode."); - - if (!getAndCheckMixFormat("WASAPIOutput", "Output", pAudioClient, - &pwfx, &pwfxe, &eSampleFormat)) { + + if (!getAndCheckMixFormat("WASAPIOutput", "Output", pAudioClient, &pwfx, &pwfxe, &eSampleFormat)) { goto cleanup; } if (!g.s.bPositionalAudio) { - pwfx->nChannels = 2; - pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8; + pwfx->nChannels = 2; + pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8; pwfx->nAvgBytesPerSec = pwfx->nBlockAlign * pwfx->nSamplesPerSec; - + if (pwfxe) { pwfxe->dwChannelMask = KSAUDIO_SPEAKER_STEREO; } @@ -952,13 +965,13 @@ void WASAPIOutput::run() { WAVEFORMATEX *closestFormat = nullptr; hr = pAudioClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, pwfx, &closestFormat); if (hr == S_FALSE) { - qWarning("WASAPIOutput: Driver says no to 2 channel output. Closest format: %d channels @ %lu kHz", closestFormat->nChannels, static_cast<unsigned long>(closestFormat->nSamplesPerSec)); + qWarning("WASAPIOutput: Driver says no to 2 channel output. Closest format: %d channels @ %lu kHz", + closestFormat->nChannels, static_cast< unsigned long >(closestFormat->nSamplesPerSec)); CoTaskMemFree(pwfx); - + // Fall back to whatever the device offers. - - if (!getAndCheckMixFormat("WASAPIOutput", "Output", pAudioClient, - &pwfx, &pwfxe, &eSampleFormat)) { + + if (!getAndCheckMixFormat("WASAPIOutput", "Output", pAudioClient, &pwfx, &pwfxe, &eSampleFormat)) { CoTaskMemFree(closestFormat); goto cleanup; } @@ -969,7 +982,8 @@ void WASAPIOutput::run() { CoTaskMemFree(closestFormat); } - hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, 0, pwfx, nullptr); + hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, 0, + pwfx, nullptr); if (FAILED(hr)) { qWarning("WASAPIOutput: Initialize failed: hr=0x%08lx", hr); goto cleanup; @@ -977,7 +991,7 @@ void WASAPIOutput::run() { } qWarning() << "WASAPIOutput: Output stream format" << eSampleFormat; - + pAudioClient->GetStreamLatency(&latency); pAudioClient->GetBufferSize(&bufferFrameCount); qWarning("WASAPIOutput: Stream Latency %lld (%d)", latency, bufferFrameCount); @@ -987,7 +1001,7 @@ void WASAPIOutput::run() { qWarning("WASAPIOutput: Periods %lldus %lldus (latency %lldus)", def / 10LL, min / 10LL, latency / 10LL); qWarning("WASAPIOutput: Buffer is %dus (%d)", (bufferFrameCount * 1000000) / iMixerFreq, g.s.iOutputDelay); - hr = pAudioClient->GetService(__uuidof(IAudioRenderClient), (void**)&pRenderClient); + hr = pAudioClient->GetService(__uuidof(IAudioRenderClient), (void **) &pRenderClient); if (FAILED(hr)) { qWarning("WASAPIOutput: GetService failed: hr=0x%08lx", hr); goto cleanup; @@ -1006,19 +1020,19 @@ void WASAPIOutput::run() { } if (pwfxe) { - for (int i=0;i<32;i++) { + for (int i = 0; i < 32; i++) { if (pwfxe->dwChannelMask & (1 << i)) { chanmasks[ns++] = 1 << i; } } } else { qWarning("WASAPIOutput: No chanmask available. Assigning in order."); - + for (int i = 0; i < pwfx->nChannels && i < 32; ++i) { chanmasks[ns++] = 1 << i; } } - + if (ns != pwfx->nChannels) { qWarning("WASAPIOutput: Chanmask bits doesn't match number of channels."); } @@ -1028,7 +1042,7 @@ void WASAPIOutput::run() { numFramesAvailable = 0; - while (bRunning && ! FAILED(hr)) { + while (bRunning && !FAILED(hr)) { if (!exclusive) { // Attenuate stream volumes. if (lastspoke != (g.bAttenuateOthers || mixed)) { @@ -1052,7 +1066,7 @@ void WASAPIOutput::run() { goto cleanup; } - mixed = mix(reinterpret_cast<float *>(pData), packetLength); + mixed = mix(reinterpret_cast< float * >(pData), packetLength); if (mixed) hr = pRenderClient->ReleaseBuffer(packetLength, 0); else @@ -1083,7 +1097,7 @@ void WASAPIOutput::run() { packetLength = bufferFrameCount - numFramesAvailable; } - if (! FAILED(hr)) + if (!FAILED(hr)) WaitForSingleObject(hEvent, exclusive ? 100 : 2000); } diff --git a/src/mumble/WASAPI.h b/src/mumble/WASAPI.h index 853036f2b..7ef33f4c0 100644 --- a/src/mumble/WASAPI.h +++ b/src/mumble/WASAPI.h @@ -14,56 +14,58 @@ #include <QtCore/QObject> #include <QtCore/QUuid> -#include <mmreg.h> -#include <strsafe.h> -#include <mmdeviceapi.h> -#include <avrt.h> #include <audioclient.h> -#include <ksmedia.h> +#include <avrt.h> #include <functiondiscoverykeys.h> +#include <ksmedia.h> +#include <mmdeviceapi.h> +#include <mmreg.h> +#include <strsafe.h> #ifdef _INC_FUNCTIONDISCOVERYKEYS -# undef _INC_FUNCTIONDISCOVERYKEYS +# undef _INC_FUNCTIONDISCOVERYKEYS #endif +#include <audiopolicy.h> #include <functiondiscoverykeys_devpkey.h> #include <propidl.h> -#include <audiopolicy.h> class WASAPISystem : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(WASAPISystem) - public: - static const QHash<QString, QString> getDevices(EDataFlow dataflow); - static const QHash<QString, QString> getInputDevices(); - static const QHash<QString, QString> getOutputDevices(); - static const QList<audioDevice> mapToDevice(const QHash<QString, QString>&, const QString&); +private: + Q_OBJECT + Q_DISABLE_COPY(WASAPISystem) +public: + static const QHash< QString, QString > getDevices(EDataFlow dataflow); + static const QHash< QString, QString > getInputDevices(); + static const QHash< QString, QString > getOutputDevices(); + static const QList< audioDevice > mapToDevice(const QHash< QString, QString > &, const QString &); }; class WASAPIInput : public AudioInput { - private: - Q_OBJECT - Q_DISABLE_COPY(WASAPIInput) - public: - WASAPIInput(); - ~WASAPIInput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(WASAPIInput) +public: + WASAPIInput(); + ~WASAPIInput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; class WASAPIOutput : public AudioOutput { - private: - Q_OBJECT - Q_DISABLE_COPY(WASAPIOutput) - - bool setVolumeForSessionControl(IAudioSessionControl *control, const DWORD mumblePID, QSet<QUuid> &seen); - bool setVolumeForSessionControl2(IAudioSessionControl2 *control2, const DWORD mumblePID, QSet<QUuid> &seen); - protected: - typedef QPair<float, float> VolumePair; - QMap<ISimpleAudioVolume *, VolumePair> qmVolumes; - void setVolumes(IMMDevice *, bool talking); - public: - WASAPIOutput(); - ~WASAPIOutput() Q_DECL_OVERRIDE; - void run() Q_DECL_OVERRIDE; +private: + Q_OBJECT + Q_DISABLE_COPY(WASAPIOutput) + + bool setVolumeForSessionControl(IAudioSessionControl *control, const DWORD mumblePID, QSet< QUuid > &seen); + bool setVolumeForSessionControl2(IAudioSessionControl2 *control2, const DWORD mumblePID, QSet< QUuid > &seen); + +protected: + typedef QPair< float, float > VolumePair; + QMap< ISimpleAudioVolume *, VolumePair > qmVolumes; + void setVolumes(IMMDevice *, bool talking); + +public: + WASAPIOutput(); + ~WASAPIOutput() Q_DECL_OVERRIDE; + void run() Q_DECL_OVERRIDE; }; #endif diff --git a/src/mumble/WASAPINotificationClient.cpp b/src/mumble/WASAPINotificationClient.cpp index 83cfb31eb..78c033e72 100644 --- a/src/mumble/WASAPINotificationClient.cpp +++ b/src/mumble/WASAPINotificationClient.cpp @@ -10,15 +10,16 @@ #include <QtCore/QMutexLocker> #include <boost/thread/once.hpp> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" -HRESULT STDMETHODCALLTYPE WASAPINotificationClient::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDevice) { +HRESULT STDMETHODCALLTYPE WASAPINotificationClient::OnDefaultDeviceChanged(EDataFlow flow, ERole role, + LPCWSTR pwstrDefaultDevice) { const QString device = QString::fromWCharArray(pwstrDefaultDevice); - qWarning() << "WASAPINotificationClient: Default device changed flow=" << flow - << "role=" << role - << "device" << device; + qWarning() << "WASAPINotificationClient: Default device changed flow=" << flow << "role=" << role << "device" + << device; QMutexLocker lock(&listsMutex); if (!usedDefaultDevices.empty() && role == eCommunications) { @@ -27,17 +28,17 @@ HRESULT STDMETHODCALLTYPE WASAPINotificationClient::OnDefaultDeviceChanged(EData return S_OK; } -HRESULT STDMETHODCALLTYPE WASAPINotificationClient::OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) { +HRESULT STDMETHODCALLTYPE WASAPINotificationClient::OnPropertyValueChanged(LPCWSTR pwstrDeviceId, + const PROPERTYKEY key) { const QString device = QString::fromWCharArray(pwstrDeviceId); - const bool formatChanged = (key == PKEY_AudioEngine_DeviceFormat); + const bool formatChanged = (key == PKEY_AudioEngine_DeviceFormat); const bool channelConfigChanged = (key == PKEY_AudioEndpoint_PhysicalSpeakers); QMutexLocker lock(&listsMutex); if ((formatChanged || channelConfigChanged) && usedDevices.contains(device)) { - qWarning() <<"WASAPINotificationClient: Property changed device=" << device - << "formatChanged=" << formatChanged - << "channelConfigChanged=" << channelConfigChanged; + qWarning() << "WASAPINotificationClient: Property changed device=" << device + << "formatChanged=" << formatChanged << "channelConfigChanged=" << channelConfigChanged; restartAudio(); } @@ -58,25 +59,19 @@ HRESULT STDMETHODCALLTYPE WASAPINotificationClient::OnDeviceRemoved(LPCWSTR pwst HRESULT STDMETHODCALLTYPE WASAPINotificationClient::OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) { const QString device = QString::fromWCharArray(pwstrDeviceId); - qWarning() << "WASAPINotificationClient: Device state changed newState=" << dwNewState - << "device=" << device; + qWarning() << "WASAPINotificationClient: Device state changed newState=" << dwNewState << "device=" << device; return S_OK; } HRESULT STDMETHODCALLTYPE WASAPINotificationClient::QueryInterface(REFIID riid, VOID **ppvInterface) { - if (IID_IUnknown == riid) - { - *ppvInterface = (IUnknown*)this; + if (IID_IUnknown == riid) { + *ppvInterface = (IUnknown *) this; AddRef(); - } - else if (__uuidof(IMMNotificationClient) == riid) - { - *ppvInterface = (IMMNotificationClient*)this; + } else if (__uuidof(IMMNotificationClient) == riid) { + *ppvInterface = (IMMNotificationClient *) this; AddRef(); - } - else - { + } else { *ppvInterface = nullptr; return E_NOINTERFACE; } @@ -110,14 +105,13 @@ void WASAPINotificationClient::enlistDeviceAsUsed(LPCWSTR pwstrDevice) { _enlistDeviceAsUsed(device); } -void WASAPINotificationClient::_enlistDeviceAsUsed(const QString& device) -{ +void WASAPINotificationClient::_enlistDeviceAsUsed(const QString &device) { if (!usedDevices.contains(device)) { usedDevices.append(device); } } -void WASAPINotificationClient::enlistDeviceAsUsed(const QString& device) { +void WASAPINotificationClient::enlistDeviceAsUsed(const QString &device) { QMutexLocker lock(&listsMutex); _enlistDeviceAsUsed(device); } @@ -134,8 +128,7 @@ void WASAPINotificationClient::clearUsedDefaultDeviceList() { usedDefaultDevices.clear(); } -void WASAPINotificationClient::_clearUsedDeviceLists() -{ +void WASAPINotificationClient::_clearUsedDeviceLists() { usedDefaultDevices.clear(); usedDevices.clear(); } @@ -146,17 +139,17 @@ void WASAPINotificationClient::clearUsedDeviceLists() { } void WASAPINotificationClient::doGetOnce() { - (void)WASAPINotificationClient::doGet(); + (void) WASAPINotificationClient::doGet(); } -WASAPINotificationClient& WASAPINotificationClient::doGet() { +WASAPINotificationClient &WASAPINotificationClient::doGet() { static WASAPINotificationClient instance; return instance; } static boost::once_flag notification_client_init_once = BOOST_ONCE_INIT; -WASAPINotificationClient& WASAPINotificationClient::get() { +WASAPINotificationClient &WASAPINotificationClient::get() { // Hacky way of making sure we get a thread-safe yet lazy initialization of the static. boost::call_once(&WASAPINotificationClient::doGetOnce, notification_client_init_once); return doGet(); @@ -165,7 +158,8 @@ WASAPINotificationClient& WASAPINotificationClient::get() { WASAPINotificationClient::WASAPINotificationClient() : QObject(), pEnumerator(0), listsMutex() { AddRef(); // Static singleton, always has a self-reference - HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void **>(&pEnumerator)); + HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), + reinterpret_cast< void ** >(&pEnumerator)); if (!pEnumerator || FAILED(hr)) { if (pEnumerator) { pEnumerator->Release(); diff --git a/src/mumble/WASAPINotificationClient.h b/src/mumble/WASAPINotificationClient.h index 6e2756402..fb1b64380 100644 --- a/src/mumble/WASAPINotificationClient.h +++ b/src/mumble/WASAPINotificationClient.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MUMBLE_WASAPINOTIFICATIONCLIENT_H_ #define MUMBLE_MUMBLE_WASAPINOTIFICATIONCLIENT_H_ -#include <QtCore/QObject> #include <QtCore/QMutex> +#include <QtCore/QObject> #include <mmdeviceapi.h> /** @@ -30,7 +30,7 @@ public: void enlistDefaultDeviceAsUsed(LPCWSTR pwstrDefaultDevice); void enlistDeviceAsUsed(LPCWSTR pwstrDevice); - void enlistDeviceAsUsed(const QString& device); + void enlistDeviceAsUsed(const QString &device); void unlistDevice(LPCWSTR pwstrDevice); @@ -40,23 +40,23 @@ public: /** * @return Singleton instance reference. */ - static WASAPINotificationClient& get(); + static WASAPINotificationClient &get(); private: WASAPINotificationClient(); ~WASAPINotificationClient() Q_DECL_OVERRIDE; - WASAPINotificationClient(const WASAPINotificationClient&); - WASAPINotificationClient& operator=(const WASAPINotificationClient&); + WASAPINotificationClient(const WASAPINotificationClient &); + WASAPINotificationClient &operator=(const WASAPINotificationClient &); - static WASAPINotificationClient& doGet(); + static WASAPINotificationClient &doGet(); static void doGetOnce(); void restartAudio(); /* _fu = Non locking versions */ void _clearUsedDeviceLists(); - void _enlistDeviceAsUsed(const QString& device); + void _enlistDeviceAsUsed(const QString &device); QStringList usedDefaultDevices; QStringList usedDevices; diff --git a/src/mumble/WebFetch.cpp b/src/mumble/WebFetch.cpp index d60c4d098..94c1fe10c 100644 --- a/src/mumble/WebFetch.cpp +++ b/src/mumble/WebFetch.cpp @@ -9,15 +9,12 @@ #include <QtNetwork/QNetworkReply> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" WebFetch::WebFetch(QString service, QUrl url, QObject *obj, const char *slot) - : QObject() - , qoObject(obj) - , cpSlot(slot) - , m_service(service) { - + : QObject(), qoObject(obj), cpSlot(slot), m_service(service) { url.setScheme(QLatin1String("https")); if (!g.s.qsServicePrefix.isEmpty()) { @@ -28,7 +25,7 @@ WebFetch::WebFetch(QString service, QUrl url, QObject *obj, const char *slot) qnr = Network::get(url); connect(qnr, SIGNAL(finished()), this, SLOT(finished())); - connect(this, SIGNAL(fetched(QByteArray,QUrl,QMap<QString,QString>)), obj, slot); + connect(this, SIGNAL(fetched(QByteArray, QUrl, QMap< QString, QString >)), obj, slot); } QString WebFetch::prefixedServiceHost() const { @@ -50,7 +47,7 @@ static QString fromUtf8(const QByteArray &qba) { void WebFetch::finished() { // Note that if this functions succeeds, it should deleteLater() itself, as this is a temporary object. - Q_ASSERT(qobject_cast<QNetworkReply *>(sender()) == qnr); + Q_ASSERT(qobject_cast< QNetworkReply * >(sender()) == qnr); qnr->disconnect(); qnr->deleteLater(); @@ -63,12 +60,12 @@ void WebFetch::finished() { if (a.isNull()) a.append(""); - QMap<QString, QString> headers; + QMap< QString, QString > headers; - foreach(const QByteArray &headerName, qnr->rawHeaderList()) { - QString name = fromUtf8(headerName); + foreach (const QByteArray &headerName, qnr->rawHeaderList()) { + QString name = fromUtf8(headerName); QString value = fromUtf8(qnr->rawHeader(headerName)); - if (! name.isEmpty() && ! value.isEmpty()) { + if (!name.isEmpty() && !value.isEmpty()) { headers.insert(name, value); if (name == QLatin1String("Use-Service-Prefix")) { QRegExp servicePrefixRegExp(QLatin1String("^[a-zA-Z]+$")); @@ -92,7 +89,7 @@ void WebFetch::finished() { qnr = Network::get(url); connect(qnr, SIGNAL(finished()), this, SLOT(finished())); } else { - emit fetched(QByteArray(), url, QMap<QString,QString>()); + emit fetched(QByteArray(), url, QMap< QString, QString >()); deleteLater(); } } diff --git a/src/mumble/WebFetch.h b/src/mumble/WebFetch.h index 678dc3f81..aa7dcd782 100644 --- a/src/mumble/WebFetch.h +++ b/src/mumble/WebFetch.h @@ -15,78 +15,79 @@ class QNetworkReply; /// WebFetch is a utility class to download data from Mumble services. class WebFetch : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(WebFetch) - protected: - QObject *qoObject; - const char *cpSlot; - QNetworkReply *qnr; - QString m_service; +private: + Q_OBJECT + Q_DISABLE_COPY(WebFetch) +protected: + QObject *qoObject; + const char *cpSlot; + QNetworkReply *qnr; + QString m_service; - QString prefixedServiceHost() const; - QString serviceHost() const; + QString prefixedServiceHost() const; + QString serviceHost() const; - WebFetch(QString service, QUrl url, QObject *obj, const char *slot); - signals: - void fetched(QByteArray data, QUrl url, QMap<QString, QString> headers); - protected slots: - void finished(); - public: - /// The fetch function downloads the resource specified by the url parameter from the - /// Mumble service given in the service parameter. Once the download completes, the - /// function invokes the slot specified via the slot parameter. - /// - /// Only the path part of the url parameter - /// is used to construct the final, fully-qualified URL from which the resource is - /// downloaded. - /// - /// By default, the service parameter and the url parameter are combined to create - /// a service as follows: - /// - /// fullyQualifiedURL = https://${service}.mumble.info/${url.path} - /// - /// When a resource is downloaded from a Mumble service, the service may optionally - /// specify a service prefix to use for future requests to all Mumble services. This - /// is communicated via the Use-Service-Prefix HTTP header in HTTP responses from - /// Mumble services. When this function encounters such a response header, it stores - /// the service prefix in the "net/serviceprefix" Mumble setting. If this setting - /// is non-empty, the fully-qualified URL is instead constructed as such: - /// - /// fullyQualifiedURL = https://${serivcePrefixSetting}-${service}.mumble.info/${url.path} - /// - /// The service prefix must only contain ASCII characters 'A' through 'Z' (upper case) - /// or 'a' through 'z (lower case). - /// - /// @param service The Mumble service name to use for this request. - /// - /// The service name specified is used to create base URL - /// used by the final, fully-qualified URL as follows: - /// - /// baseURL = https://${service}.mumble.info - /// - /// If the Mumble setting "net/serviceprefix" is non-empty, - /// it will be used as a prefix to the base URL. In this case, - /// the base URL will be constructed as follows: - /// - /// baseURL = https://${servicePrefixSetting}-${service}.mumble.info - /// - /// @param url The path to the endpoint that the request is targetted at. - /// Only the path of the URL will be used. The specified path is - /// used in combination with the base URL constructed by the service - /// parameter to construct the fully-qualified URL for the HTTP request - /// that will be sent by this function. - /// The path is used in combination with the base URL from the service - /// parameter as follows: - /// - /// fullyQualifiedURL = ${baseURL}/${url.path} - /// - /// @param slot A Qt slot of the form fetched(QByteArray data, QUrl url, - /// QMap<QString,QString> httpHeaders) - /// If the download initiated by the function was succesful, the data - /// parameter will be a non-null QByteArray. - /// If the download failed, the data parameter will be a null QByteArray. - static void fetch(const QString &service, const QUrl &url, QObject *obj, const char *slot); + WebFetch(QString service, QUrl url, QObject *obj, const char *slot); +signals: + void fetched(QByteArray data, QUrl url, QMap< QString, QString > headers); +protected slots: + void finished(); + +public: + /// The fetch function downloads the resource specified by the url parameter from the + /// Mumble service given in the service parameter. Once the download completes, the + /// function invokes the slot specified via the slot parameter. + /// + /// Only the path part of the url parameter + /// is used to construct the final, fully-qualified URL from which the resource is + /// downloaded. + /// + /// By default, the service parameter and the url parameter are combined to create + /// a service as follows: + /// + /// fullyQualifiedURL = https://${service}.mumble.info/${url.path} + /// + /// When a resource is downloaded from a Mumble service, the service may optionally + /// specify a service prefix to use for future requests to all Mumble services. This + /// is communicated via the Use-Service-Prefix HTTP header in HTTP responses from + /// Mumble services. When this function encounters such a response header, it stores + /// the service prefix in the "net/serviceprefix" Mumble setting. If this setting + /// is non-empty, the fully-qualified URL is instead constructed as such: + /// + /// fullyQualifiedURL = https://${serivcePrefixSetting}-${service}.mumble.info/${url.path} + /// + /// The service prefix must only contain ASCII characters 'A' through 'Z' (upper case) + /// or 'a' through 'z (lower case). + /// + /// @param service The Mumble service name to use for this request. + /// + /// The service name specified is used to create base URL + /// used by the final, fully-qualified URL as follows: + /// + /// baseURL = https://${service}.mumble.info + /// + /// If the Mumble setting "net/serviceprefix" is non-empty, + /// it will be used as a prefix to the base URL. In this case, + /// the base URL will be constructed as follows: + /// + /// baseURL = https://${servicePrefixSetting}-${service}.mumble.info + /// + /// @param url The path to the endpoint that the request is targetted at. + /// Only the path of the URL will be used. The specified path is + /// used in combination with the base URL constructed by the service + /// parameter to construct the fully-qualified URL for the HTTP request + /// that will be sent by this function. + /// The path is used in combination with the base URL from the service + /// parameter as follows: + /// + /// fullyQualifiedURL = ${baseURL}/${url.path} + /// + /// @param slot A Qt slot of the form fetched(QByteArray data, QUrl url, + /// QMap<QString,QString> httpHeaders) + /// If the download initiated by the function was succesful, the data + /// parameter will be a non-null QByteArray. + /// If the download failed, the data parameter will be a null QByteArray. + static void fetch(const QString &service, const QUrl &url, QObject *obj, const char *slot); }; #endif diff --git a/src/mumble/WinGUIDs.cpp b/src/mumble/WinGUIDs.cpp index 83ec0314f..b49862849 100644 --- a/src/mumble/WinGUIDs.cpp +++ b/src/mumble/WinGUIDs.cpp @@ -3,23 +3,24 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -#include <wtypes.h> -#include <initguid.h> -#include <propkey.h> #include <windows.h> -#include <mmreg.h> -#include <strsafe.h> -#include <mmdeviceapi.h> -#include <avrt.h> #include <audioclient.h> -#include <ksmedia.h> +#include <avrt.h> #include <functiondiscoverykeys.h> +#include <initguid.h> +#include <ksmedia.h> +#include <mmdeviceapi.h> +#include <mmreg.h> +#include <propkey.h> +#include <strsafe.h> +#include <wtypes.h> #ifdef _INC_FUNCTIONDISCOVERYKEYS -# undef _INC_FUNCTIONDISCOVERYKEYS +# undef _INC_FUNCTIONDISCOVERYKEYS #endif +#include <audiopolicy.h> #include <functiondiscoverykeys_devpkey.h> #include <propidl.h> -#include <audiopolicy.h> -DEFINE_GUID(IID_IVistaAudioSessionControl2, 0x33969B1DL, 0xD06F, 0x4281, 0xB8, 0x37, 0x7E, 0xAA, 0xFD, 0x21, 0xA9, 0xC0); +DEFINE_GUID(IID_IVistaAudioSessionControl2, 0x33969B1DL, 0xD06F, 0x4281, 0xB8, 0x37, 0x7E, 0xAA, 0xFD, 0x21, 0xA9, + 0xC0); DEFINE_GUID(IID_IAudioSessionQuery, 0x94BE9D30L, 0x53AC, 0x4802, 0x82, 0x9C, 0xF1, 0x3E, 0x5A, 0xD3, 0x47, 0x75); diff --git a/src/mumble/XMLTools.cpp b/src/mumble/XMLTools.cpp index b288ca750..2023b5eac 100644 --- a/src/mumble/XMLTools.cpp +++ b/src/mumble/XMLTools.cpp @@ -5,22 +5,18 @@ #include "XMLTools.h"
+#include <QStringList>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
-#include <QStringList>
-void XMLTools::recurseParse(QXmlStreamReader &reader,
- QXmlStreamWriter &writer,
- int ¶graphs,
- const QMap<QString, QString> &opstyle,
- const int close,
- bool ignore) {
- while (! reader.atEnd()) {
+void XMLTools::recurseParse(QXmlStreamReader &reader, QXmlStreamWriter &writer, int ¶graphs,
+ const QMap< QString, QString > &opstyle, const int close, bool ignore) {
+ while (!reader.atEnd()) {
QXmlStreamReader::TokenType tt = reader.readNext();
QXmlStreamAttributes a = reader.attributes();
- QMap<QString, QString> style;
- QMap<QString, QString> pstyle = opstyle;
+ QMap< QString, QString > style;
+ QMap< QString, QString > pstyle = opstyle;
QStringRef styleref = a.value(QLatin1String("style"));
if (!styleref.isNull()) {
@@ -31,53 +27,78 @@ void XMLTools::recurseParse(QXmlStreamReader &reader, // Qt 5.14 introduced the Qt::SplitBehavior flags deprecating the QString fields
QStringList styles = stylestring.split(QLatin1String(";"), QString::SkipEmptyParts);
#endif
- foreach(QString s, styles) {
- s = s.simplified();
- int idx = s.indexOf(QLatin1Char(':'));
+ foreach (QString s, styles) {
+ s = s.simplified();
+ int idx = s.indexOf(QLatin1Char(':'));
QString key = (idx > 0) ? s.left(idx).simplified() : s;
- QString val = (idx > 0) ? s.mid(idx+1).simplified() : QString();
+ QString val = (idx > 0) ? s.mid(idx + 1).simplified() : QString();
- if (! pstyle.contains(key) || (pstyle.value(key) != val)) {
- style.insert(key,val);
- pstyle.insert(key,val);
+ if (!pstyle.contains(key) || (pstyle.value(key) != val)) {
+ style.insert(key, val);
+ pstyle.insert(key, val);
}
}
}
switch (tt) {
case QXmlStreamReader::StartElement: {
- QString name = reader.name().toString();
- int rclose = 1;
- if (name == QLatin1String("body")) {
- rclose = 0;
- ignore = false;
- } else if (name == QLatin1String("span")) {
- // Substitute style with <b>, <i> and <u>
-
- rclose = 0;
- if (style.value(QLatin1String("font-weight")) == QLatin1String("600")) {
- writer.writeStartElement(QLatin1String("b"));
- rclose++;
- style.remove(QLatin1String("font-weight"));
- }
- if (style.value(QLatin1String("font-style")) == QLatin1String("italic")) {
- writer.writeStartElement(QLatin1String("i"));
- rclose++;
- style.remove(QLatin1String("font-style"));
+ QString name = reader.name().toString();
+ int rclose = 1;
+ if (name == QLatin1String("body")) {
+ rclose = 0;
+ ignore = false;
+ } else if (name == QLatin1String("span")) {
+ // Substitute style with <b>, <i> and <u>
+
+ rclose = 0;
+ if (style.value(QLatin1String("font-weight")) == QLatin1String("600")) {
+ writer.writeStartElement(QLatin1String("b"));
+ rclose++;
+ style.remove(QLatin1String("font-weight"));
+ }
+ if (style.value(QLatin1String("font-style")) == QLatin1String("italic")) {
+ writer.writeStartElement(QLatin1String("i"));
+ rclose++;
+ style.remove(QLatin1String("font-style"));
+ }
+ if (style.value(QLatin1String("text-decoration")) == QLatin1String("underline")) {
+ writer.writeStartElement(QLatin1String("u"));
+ rclose++;
+ style.remove(QLatin1String("text-decoration"));
+ }
+ if (!style.isEmpty()) {
+ rclose++;
+ writer.writeStartElement(name);
+
+ QStringList qsl;
+ QMap< QString, QString >::const_iterator i;
+ for (i = style.constBegin(); i != style.constEnd(); ++i) {
+ if (!i.value().isEmpty())
+ qsl << QString::fromLatin1("%1:%2").arg(i.key(), i.value());
+ else
+ qsl << i.key();
}
- if (style.value(QLatin1String("text-decoration")) == QLatin1String("underline")) {
- writer.writeStartElement(QLatin1String("u"));
- rclose++;
- style.remove(QLatin1String("text-decoration"));
+
+ writer.writeAttribute(QLatin1String("style"), qsl.join(QLatin1String("; ")));
+ }
+ } else if (name == QLatin1String("p")) {
+ paragraphs++;
+ if (paragraphs == 1) {
+ // Ignore first paragraph. If it is styled empty drop its contents (e.g. <br />) too.
+ if (style.value(QLatin1String("-qt-paragraph-type")) == QLatin1String("empty")) {
+ reader.skipCurrentElement();
+ continue;
}
- if (! style.isEmpty()) {
- rclose++;
- writer.writeStartElement(name);
+ rclose = 0;
+ } else {
+ rclose = 1;
+ writer.writeStartElement(name);
+ if (!style.isEmpty()) {
QStringList qsl;
- QMap<QString, QString>::const_iterator i;
- for (i=style.constBegin(); i != style.constEnd(); ++i) {
- if (! i.value().isEmpty())
+ QMap< QString, QString >::const_iterator i;
+ for (i = style.constBegin(); i != style.constEnd(); ++i) {
+ if (!i.value().isEmpty())
qsl << QString::fromLatin1("%1:%2").arg(i.key(), i.value());
else
qsl << i.key();
@@ -85,54 +106,28 @@ void XMLTools::recurseParse(QXmlStreamReader &reader, writer.writeAttribute(QLatin1String("style"), qsl.join(QLatin1String("; ")));
}
- } else if (name == QLatin1String("p")) {
- paragraphs++;
- if (paragraphs == 1) {
- // Ignore first paragraph. If it is styled empty drop its contents (e.g. <br />) too.
- if (style.value(QLatin1String("-qt-paragraph-type")) == QLatin1String("empty")) {
- reader.skipCurrentElement();
- continue;
- }
- rclose = 0;
- }
- else {
- rclose = 1;
- writer.writeStartElement(name);
-
- if (! style.isEmpty()) {
- QStringList qsl;
- QMap<QString, QString>::const_iterator i;
- for (i=style.constBegin(); i != style.constEnd(); ++i) {
- if (! i.value().isEmpty())
- qsl << QString::fromLatin1("%1:%2").arg(i.key(), i.value());
- else
- qsl << i.key();
- }
-
- writer.writeAttribute(QLatin1String("style"), qsl.join(QLatin1String("; ")));
- }
- }
- } else if (name == QLatin1String("a")) {
- // Set pstyle to include implicit blue underline.
- rclose = 1;
- writer.writeCurrentToken(reader);
- pstyle.insert(QLatin1String("text-decoration"), QLatin1String("underline"));
- pstyle.insert(QLatin1String("color"), QLatin1String("#0000ff"));
- } else if (! ignore) {
- rclose = 1;
- writer.writeCurrentToken(reader);
}
-
- recurseParse(reader, writer, paragraphs, pstyle, rclose, ignore);
- break;
+ } else if (name == QLatin1String("a")) {
+ // Set pstyle to include implicit blue underline.
+ rclose = 1;
+ writer.writeCurrentToken(reader);
+ pstyle.insert(QLatin1String("text-decoration"), QLatin1String("underline"));
+ pstyle.insert(QLatin1String("color"), QLatin1String("#0000ff"));
+ } else if (!ignore) {
+ rclose = 1;
+ writer.writeCurrentToken(reader);
}
+
+ recurseParse(reader, writer, paragraphs, pstyle, rclose, ignore);
+ break;
+ }
case QXmlStreamReader::EndElement:
if (!ignore)
- for (int i=0;i<close;++i)
+ for (int i = 0; i < close; ++i)
writer.writeEndElement();
return;
case QXmlStreamReader::Characters:
- if (! ignore)
+ if (!ignore)
writer.writeCharacters(reader.text().toString());
break;
default:
@@ -142,7 +137,7 @@ void XMLTools::recurseParse(QXmlStreamReader &reader, }
bool XMLTools::unduplicateTags(QXmlStreamReader &reader, QXmlStreamWriter &writer) {
- bool changed = false;
+ bool changed = false;
bool needclose = false;
QStringList qslConcat;
@@ -151,49 +146,47 @@ bool XMLTools::unduplicateTags(QXmlStreamReader &reader, QXmlStreamWriter &write qslConcat << QLatin1String("u");
qslConcat << QLatin1String("a");
- QList<QString> qlNames;
- QList<QXmlStreamAttributes> qlAttributes;
+ QList< QString > qlNames;
+ QList< QXmlStreamAttributes > qlAttributes;
- while (! reader.atEnd()) {
+ while (!reader.atEnd()) {
QXmlStreamReader::TokenType tt = reader.readNext();
- QString name = reader.name().toString();
+ QString name = reader.name().toString();
switch (tt) {
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
break;
case QXmlStreamReader::StartElement: {
- QXmlStreamAttributes a = reader.attributes();
+ QXmlStreamAttributes a = reader.attributes();
- if (name == QLatin1String("unduplicate"))
- break;
+ if (name == QLatin1String("unduplicate"))
+ break;
- if (needclose) {
- needclose = false;
+ if (needclose) {
+ needclose = false;
- if ((a == qlAttributes.last()) && (name == qlNames.last()) && (qslConcat.contains(name))) {
- changed = true;
- break;
- }
- qlNames.takeLast();
- qlAttributes.takeLast();
- writer.writeEndElement();
+ if ((a == qlAttributes.last()) && (name == qlNames.last()) && (qslConcat.contains(name))) {
+ changed = true;
+ break;
}
- writer.writeCurrentToken(reader);
- qlNames.append(name);
- qlAttributes.append(a);
+ qlNames.takeLast();
+ qlAttributes.takeLast();
+ writer.writeEndElement();
}
- break;
+ writer.writeCurrentToken(reader);
+ qlNames.append(name);
+ qlAttributes.append(a);
+ } break;
case QXmlStreamReader::EndElement: {
- if (name == QLatin1String("unduplicate"))
- break;
- if (needclose) {
- qlNames.takeLast();
- qlAttributes.takeLast();
- writer.writeCurrentToken(reader);
- }
- needclose = true;
+ if (name == QLatin1String("unduplicate"))
+ break;
+ if (needclose) {
+ qlNames.takeLast();
+ qlAttributes.takeLast();
+ writer.writeCurrentToken(reader);
}
- break;
+ needclose = true;
+ } break;
default:
if (needclose) {
writer.writeEndElement();
diff --git a/src/mumble/XMLTools.h b/src/mumble/XMLTools.h index 6c3deed60..2d09364f5 100644 --- a/src/mumble/XMLTools.h +++ b/src/mumble/XMLTools.h @@ -6,36 +6,33 @@ #ifndef MUMBLE_MUMBLE_XMLTOOLS_H_
#define MUMBLE_MUMBLE_XMLTOOLS_H_
-#include <QObject>
#include <QMap>
+#include <QObject>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
class XMLTools : public QObject {
- Q_OBJECT
- public:
- /* Recursively parse and output XHTML.
- * This will drop <head>, <html> etc, take the contents of <body> and strip out unnecesarry styles.
- * It will also change <span style=""> into matching <b>, <i> or <u>.
- */
- static void recurseParse(QXmlStreamReader &reader,
- QXmlStreamWriter &writer,
- int ¶graphs,
- const QMap<QString, QString> &opstyle,
- const int close = 0, bool ignore = true);
+ Q_OBJECT
+public:
+ /* Recursively parse and output XHTML.
+ * This will drop <head>, <html> etc, take the contents of <body> and strip out unnecesarry styles.
+ * It will also change <span style=""> into matching <b>, <i> or <u>.
+ */
+ static void recurseParse(QXmlStreamReader &reader, QXmlStreamWriter &writer, int ¶graphs,
+ const QMap< QString, QString > &opstyle, const int close = 0, bool ignore = true);
- /* Iterate XML and remove close-followed-by-open.
- * For example, make "<b>bold with </b><b><i>italic</i></b>" into
- * "<b>bold with <i>italic</i></b>"
- *
- * If the input XML is or may not be valid, a "unduplicate" tag can be used as a root element,
- * which will be dropped and not written to writer.
- *
- * Input XML has to be valid XML.
- *
- * Works on b, i, u, and a elements.
- */
- static bool unduplicateTags(QXmlStreamReader &reader, QXmlStreamWriter &writer);
+ /* Iterate XML and remove close-followed-by-open.
+ * For example, make "<b>bold with </b><b><i>italic</i></b>" into
+ * "<b>bold with <i>italic</i></b>"
+ *
+ * If the input XML is or may not be valid, a "unduplicate" tag can be used as a root element,
+ * which will be dropped and not written to writer.
+ *
+ * Input XML has to be valid XML.
+ *
+ * Works on b, i, u, and a elements.
+ */
+ static bool unduplicateTags(QXmlStreamReader &reader, QXmlStreamWriter &writer);
};
#endif // XMLTOOLS_H
diff --git a/src/mumble/XboxInput.cpp b/src/mumble/XboxInput.cpp index e7a4d4265..2ebcbe5da 100644 --- a/src/mumble/XboxInput.cpp +++ b/src/mumble/XboxInput.cpp @@ -10,12 +10,7 @@ const QUuid XboxInput::s_XboxInputGuid = QUuid(QString::fromLatin1("ca3937e3-640c-4d9e-9ef3-903f8b4fbcab"));
XboxInput::XboxInput()
- : GetState(nullptr)
- , m_getStateFunc(nullptr)
- , m_getStateExFunc(nullptr)
- , m_xinputlib(nullptr)
- , m_valid(false) {
-
+ : GetState(nullptr), m_getStateFunc(nullptr), m_getStateExFunc(nullptr), m_xinputlib(nullptr), m_valid(false) {
// Load the most suitable XInput DLL available.
//
// We prefer 1_4 and 1_3 over the others because they provide
@@ -31,8 +26,8 @@ XboxInput::XboxInput() alternatives << QLatin1String("xinput1_2.dll");
alternatives << QLatin1String("xinput1_1.dll");
- foreach(const QString &lib, alternatives) {
- m_xinputlib = LoadLibraryW(reinterpret_cast<const wchar_t *>(lib.utf16()));
+ foreach (const QString &lib, alternatives) {
+ m_xinputlib = LoadLibraryW(reinterpret_cast< const wchar_t * >(lib.utf16()));
if (m_xinputlib) {
qWarning("XboxInput: using XInput DLL '%s'", qPrintable(lib));
m_valid = true;
@@ -45,11 +40,11 @@ XboxInput::XboxInput() return;
}
- m_getStateFunc = reinterpret_cast<XboxInputGetStateFunc>(GetProcAddress(m_xinputlib, "XInputGetState"));
+ m_getStateFunc = reinterpret_cast< XboxInputGetStateFunc >(GetProcAddress(m_xinputlib, "XInputGetState"));
// Undocumented XInputGetStateEx -- ordinal 100. It is available in XInput 1.3 and greater.
// It provides access to the state of the guide button.
// For reference, see SDL's XInput support: http://www.libsdl.org/tmp/SDL/src/core/windows/SDL_xinput.c
- m_getStateExFunc = reinterpret_cast<XboxInputGetStateFunc>(GetProcAddress(m_xinputlib, (char *)100));
+ m_getStateExFunc = reinterpret_cast< XboxInputGetStateFunc >(GetProcAddress(m_xinputlib, (char *) 100));
if (m_getStateExFunc) {
GetState = m_getStateExFunc;
diff --git a/src/mumble/XboxInput.h b/src/mumble/XboxInput.h index a807d1c06..86496cd29 100644 --- a/src/mumble/XboxInput.h +++ b/src/mumble/XboxInput.h @@ -18,67 +18,67 @@ ///
/// In typical operation, one calls GetState()
/// in a loop bounded by XBOXINPUT_MAX_DEVICES.
-#define XBOXINPUT_MAX_DEVICES 4
+#define XBOXINPUT_MAX_DEVICES 4
/// XBOXINPUT_TRIGGER_THRESHOLD defines the thresold
/// that an analog trigger (leftTrigger and
/// rightTrigger of XboxInputState) must have exceeded
/// in order to count as a button press.
-#define XBOXINPUT_TRIGGER_THRESHOLD 30
+#define XBOXINPUT_TRIGGER_THRESHOLD 30
/// XboxInputState represents the state of an
/// Xbox controller as returned by GetState().
struct XboxInputState {
- uint32_t packetNumber;
- uint16_t buttons;
- uint8_t leftTrigger;
- uint8_t rightTrigger;
- uint16_t leftThumbX;
- uint16_t leftThumbY;
- uint16_t rightThumbY;
- uint16_t rightThumbX;
- uint32_t paddingReserved; // Required for XInputGetStateEx. Not required for XInputGetState.
+ uint32_t packetNumber;
+ uint16_t buttons;
+ uint8_t leftTrigger;
+ uint8_t rightTrigger;
+ uint16_t leftThumbX;
+ uint16_t leftThumbY;
+ uint16_t rightThumbY;
+ uint16_t rightThumbX;
+ uint32_t paddingReserved; // Required for XInputGetStateEx. Not required for XInputGetState.
};
-typedef uint32_t (WINAPI *XboxInputGetStateFunc)(uint32_t deviceIndex, XboxInputState *state);
+typedef uint32_t(WINAPI *XboxInputGetStateFunc)(uint32_t deviceIndex, XboxInputState *state);
/// XboxInput is an XInput wrapper that dynamically loads an appropriate
/// xinput*.dll on construction and provides access to its GetState(Ex)
/// function.
class XboxInput {
- public:
- XboxInput();
- virtual ~XboxInput();
-
- /// s_XboxInputGuid is the GUID used by GlobalShortcut_win
- /// to distinguish XboxInputLibrary's events from other event
- /// soures.
- static const QUuid s_XboxInputGuid;
-
- /// isValid determines wheter the XboxInputLibrary
- /// is usable.
- bool isValid() const;
-
- /// Query the state of the Xbox controller at deviceIndex.
- /// If the function succeeds, it returns 0 (Windows's ERROR_SUCCESS).
- /// If no device is connected, it returns 0x48F (Windows's ERROR_DEVICE_NOT_CONNECTED).
- XboxInputGetStateFunc GetState;
-
- protected:
- /// m_getStateFunc represents XInputGetState from the XInput DLL.
- XboxInputGetStateFunc m_getStateFunc;
-
- /// m_getStateFuncEx represents XInputGetStateEx, which is optionally
- /// available in the XInput DLL.
- XboxInputGetStateFunc m_getStateExFunc;
-
- /// m_xinputlib is the handle to the XInput DLL as returned by
- /// LoadLibrary.
- HMODULE m_xinputlib;
-
- /// m_valid determines whether or not the XboxInputLibrary
- /// is valid for use.
- bool m_valid;
+public:
+ XboxInput();
+ virtual ~XboxInput();
+
+ /// s_XboxInputGuid is the GUID used by GlobalShortcut_win
+ /// to distinguish XboxInputLibrary's events from other event
+ /// soures.
+ static const QUuid s_XboxInputGuid;
+
+ /// isValid determines wheter the XboxInputLibrary
+ /// is usable.
+ bool isValid() const;
+
+ /// Query the state of the Xbox controller at deviceIndex.
+ /// If the function succeeds, it returns 0 (Windows's ERROR_SUCCESS).
+ /// If no device is connected, it returns 0x48F (Windows's ERROR_DEVICE_NOT_CONNECTED).
+ XboxInputGetStateFunc GetState;
+
+protected:
+ /// m_getStateFunc represents XInputGetState from the XInput DLL.
+ XboxInputGetStateFunc m_getStateFunc;
+
+ /// m_getStateFuncEx represents XInputGetStateEx, which is optionally
+ /// available in the XInput DLL.
+ XboxInputGetStateFunc m_getStateExFunc;
+
+ /// m_xinputlib is the handle to the XInput DLL as returned by
+ /// LoadLibrary.
+ HMODULE m_xinputlib;
+
+ /// m_valid determines whether or not the XboxInputLibrary
+ /// is valid for use.
+ bool m_valid;
};
#endif
diff --git a/src/mumble/main.cpp b/src/mumble/main.cpp index bef715d48..093dac7ad 100644 --- a/src/mumble/main.cpp +++ b/src/mumble/main.cpp @@ -4,44 +4,44 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_OVERLAY - #include "Overlay.h" +# include "Overlay.h" #endif -#include "MainWindow.h" -#include "ServerHandler.h" #include "AudioInput.h" #include "AudioOutput.h" #include "AudioWizard.h" #include "Cert.h" #include "Database.h" -#include "Log.h" -#include "Plugins.h" -#include "LogEmitter.h" #include "DeveloperConsole.h" #include "LCD.h" +#include "Log.h" +#include "LogEmitter.h" +#include "MainWindow.h" +#include "Plugins.h" +#include "ServerHandler.h" #ifdef USE_BONJOUR -# include "BonjourClient.h" +# include "BonjourClient.h" #endif #ifdef USE_DBUS -# include "DBus.h" +# include "DBus.h" #endif #ifdef USE_VLD -# include "vld.h" +# include "vld.h" #endif -#include "VersionCheck.h" -#include "NetworkConfig.h" +#include "ApplicationPalette.h" +#include "Channel.h" +#include "ChannelListener.h" +#include "ClientUser.h" #include "CrashReporter.h" -#include "SocketRPC.h" -#include "SSL.h" +#include "EnvUtils.h" +#include "License.h" #include "MumbleApplication.h" -#include "ApplicationPalette.h" +#include "NetworkConfig.h" +#include "SSL.h" +#include "SocketRPC.h" +#include "TalkingUI.h" #include "Themes.h" #include "UserLockFile.h" -#include "License.h" -#include "EnvUtils.h" -#include "TalkingUI.h" -#include "Channel.h" -#include "ClientUser.h" -#include "ChannelListener.h" +#include "VersionCheck.h" #include <QtCore/QLibraryInfo> #include <QtCore/QProcess> @@ -51,22 +51,23 @@ #include <QtWidgets/QMessageBox> #ifdef USE_DBUS -# include <QtDBus/QDBusInterface> +# include <QtDBus/QDBusInterface> #endif #ifdef Q_OS_WIN -# include <shellapi.h> +# include <shellapi.h> #endif -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" #ifdef BOOST_NO_EXCEPTIONS namespace boost { - void throw_exception(std::exception const &) { - qFatal("Boost exception caught!"); - } +void throw_exception(std::exception const &) { + qFatal("Boost exception caught!"); } +} // namespace boost #endif extern void os_init(); @@ -98,9 +99,9 @@ int main(int argc, char **argv) { #if defined(Q_OS_WIN) SetDllDirectory(L""); #else -#ifndef Q_OS_MAC +# ifndef Q_OS_MAC EnvUtils::setenv(QLatin1String("AVAHI_COMPAT_NOWARN"), QLatin1String("1")); -#endif +# endif #endif // Initialize application object. @@ -120,7 +121,7 @@ int main(int argc, char **argv) { MumbleSSL::initialize(); - #ifdef USE_SBCELT +#ifdef USE_SBCELT { QDir d(a.applicationVersionRootPath()); QString helper = d.absoluteFilePath(QString::fromLatin1("sbcelt-helper")); @@ -131,14 +132,15 @@ int main(int argc, char **argv) { // This argument has to be parsed first, since it's value is needed to create the global struct, // which other switches are modifying. If it is parsed first, the order of the arguments does not matter. QStringList args = a.arguments(); - const int index = std::max(args.lastIndexOf(QLatin1String("-c")), args.lastIndexOf(QLatin1String("--config"))); + const int index = std::max(args.lastIndexOf(QLatin1String("-c")), args.lastIndexOf(QLatin1String("--config"))); if (index >= 0) { if (index + 1 < args.count()) { QFile inifile(args.at(index + 1)); if (inifile.exists() && inifile.permissions().testFlag(QFile::WriteUser)) { Global::g_global_struct = new Global(args.at(index + 1)); } else { - printf("%s", qPrintable(MainWindow::tr("Configuration file %1 does not exist or is not writable.\n").arg(args.at(index + 1)))); + printf("%s", qPrintable(MainWindow::tr("Configuration file %1 does not exist or is not writable.\n") + .arg(args.at(index + 1)))); return 1; } } else { @@ -149,20 +151,20 @@ int main(int argc, char **argv) { Global::g_global_struct = new Global(); } -#if QT_VERSION < QT_VERSION_CHECK(5,10,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // For Qt >= 5.10 we use QRandomNumberGenerator that is seeded automatically qsrand(QDateTime::currentDateTime().toTime_t()); #endif - g.le = QSharedPointer<LogEmitter>(new LogEmitter()); - g.c = new DeveloperConsole(); + g.le = QSharedPointer< LogEmitter >(new LogEmitter()); + g.c = new DeveloperConsole(); os_init(); - bool bAllowMultiple = false; - bool suppressIdentity = false; + bool bAllowMultiple = false; + bool suppressIdentity = false; bool customJackClientName = false; - bool bRpcMode = false; + bool bRpcMode = false; QString rpcCommand; QUrl url; @@ -173,72 +175,69 @@ int main(int argc, char **argv) { || args.at(i) == QLatin1String("/?") #endif ) { - QString helpMessage = MainWindow::tr( - "Usage: mumble [options] [<url>]\n" - "\n" - "<url> specifies a URL to connect to after startup instead of showing\n" - "the connection window, and has the following form:\n" - "mumble://[<username>[:<password>]@]<host>[:<port>][/<channel>[/<subchannel>...]][?version=<x.y.z>]\n" - "\n" - "The version query parameter has to be set in order to invoke the\n" - "correct client version. It currently defaults to 1.2.0.\n" - "\n" - "Valid options are:\n" - " -h, --help Show this help text and exit.\n" - " -m, --multiple\n" - " Allow multiple instances of the client to be started.\n" - " -c, --config\n" - " Specify an alternative configuration file.\n" - " If you use this to run multiple instances of Mumble at once,\n" - " make sure to set an alternative 'database' value in the config.\n" - " -n, --noidentity\n" - " Suppress loading of identity files (i.e., certificates.)\n" - " -jn, --jackname <arg>\n" - " Set custom Jack client name.\n" - " --license\n" - " Show the Mumble license.\n" - " --authors\n" - " Show the Mumble authors.\n" - " --third-party-licenses\n" - " Show licenses for third-party software used by Mumble.\n" - " --window-title-ext <arg>\n" - " Sets a custom window title extension.\n" - " --dump-input-streams\n" - " Dump PCM streams at various parts of the input chain\n" - " (useful for debugging purposes)\n" - " - raw microphone input\n" - " - speaker readback for echo cancelling\n" - " - processed microphone input\n" - " --print-echocancel-queue\n" - " Print on stdout the echo cancellation queue state\n" - " (useful for debugging purposes)\n" - "\n" - ); - QString rpcHelpBanner = MainWindow::tr( - "Remote controlling Mumble:\n" - "\n" - ); - QString rpcHelpMessage = MainWindow::tr( - "Usage: mumble rpc <action> [options]\n" - "\n" - "It is possible to remote control a running instance of Mumble by using\n" - "the 'mumble rpc' command.\n" - "\n" - "Valid actions are:\n" - " mute\n" - " Mute self\n" - " unmute\n" - " Unmute self\n" - " togglemute\n" - " Toggle self-mute status\n" - " deaf\n" - " Deafen self\n" - " undeaf\n" - " Undeafen self\n" - " toggledeaf\n" - " Toggle self-deafen status\n" - "\n" - ); + QString helpMessage = + MainWindow::tr("Usage: mumble [options] [<url>]\n" + "\n" + "<url> specifies a URL to connect to after startup instead of showing\n" + "the connection window, and has the following form:\n" + "mumble://[<username>[:<password>]@]<host>[:<port>][/<channel>[/" + "<subchannel>...]][?version=<x.y.z>]\n" + "\n" + "The version query parameter has to be set in order to invoke the\n" + "correct client version. It currently defaults to 1.2.0.\n" + "\n" + "Valid options are:\n" + " -h, --help Show this help text and exit.\n" + " -m, --multiple\n" + " Allow multiple instances of the client to be started.\n" + " -c, --config\n" + " Specify an alternative configuration file.\n" + " If you use this to run multiple instances of Mumble at once,\n" + " make sure to set an alternative 'database' value in the config.\n" + " -n, --noidentity\n" + " Suppress loading of identity files (i.e., certificates.)\n" + " -jn, --jackname <arg>\n" + " Set custom Jack client name.\n" + " --license\n" + " Show the Mumble license.\n" + " --authors\n" + " Show the Mumble authors.\n" + " --third-party-licenses\n" + " Show licenses for third-party software used by Mumble.\n" + " --window-title-ext <arg>\n" + " Sets a custom window title extension.\n" + " --dump-input-streams\n" + " Dump PCM streams at various parts of the input chain\n" + " (useful for debugging purposes)\n" + " - raw microphone input\n" + " - speaker readback for echo cancelling\n" + " - processed microphone input\n" + " --print-echocancel-queue\n" + " Print on stdout the echo cancellation queue state\n" + " (useful for debugging purposes)\n" + "\n"); + QString rpcHelpBanner = MainWindow::tr("Remote controlling Mumble:\n" + "\n"); + QString rpcHelpMessage = + MainWindow::tr("Usage: mumble rpc <action> [options]\n" + "\n" + "It is possible to remote control a running instance of Mumble by using\n" + "the 'mumble rpc' command.\n" + "\n" + "Valid actions are:\n" + " mute\n" + " Mute self\n" + " unmute\n" + " Unmute self\n" + " togglemute\n" + " Toggle self-mute status\n" + " deaf\n" + " Deafen self\n" + " undeaf\n" + " Undeafen self\n" + " toggledeaf\n" + " Toggle self-deafen status\n" + "\n"); QString helpOutput = helpMessage + rpcHelpBanner + rpcHelpMessage; if (bRpcMode) { @@ -254,11 +253,11 @@ int main(int argc, char **argv) { } else if (args.at(i) == QLatin1String("-m") || args.at(i) == QLatin1String("--multiple")) { bAllowMultiple = true; } else if (args.at(i) == QLatin1String("-n") || args.at(i) == QLatin1String("--noidentity")) { - suppressIdentity = true; + suppressIdentity = true; g.s.bSuppressIdentity = true; } else if (args.at(i) == QLatin1String("-jn") || args.at(i) == QLatin1String("--jackname")) { if (i + 1 < args.count()) { - g.s.qsJackClientName = QString(args.at(i+1)); + g.s.qsJackClientName = QString(args.at(i + 1)); customJackClientName = true; ++i; } else { @@ -267,7 +266,7 @@ int main(int argc, char **argv) { } } else if (args.at(i) == QLatin1String("--window-title-ext")) { if (i + 1 < args.count()) { - g.windowTitlePostfix = QString(args.at(i+1)); + g.windowTitlePostfix = QString(args.at(i + 1)); ++i; } else { qCritical("Missing argument for --window-title-ext!"); @@ -279,15 +278,15 @@ int main(int argc, char **argv) { } else if (args.at(i) == QLatin1String("-authors") || args.at(i) == QLatin1String("--authors")) { printf("%s\n", qPrintable(License::authors())); return 0; - } else if (args.at(i) == QLatin1String("-third-party-licenses") || args.at(i) == QLatin1String("--third-party-licenses")) { + } else if (args.at(i) == QLatin1String("-third-party-licenses") + || args.at(i) == QLatin1String("--third-party-licenses")) { printf("%s", qPrintable(License::printableThirdPartyLicenseInfo())); return 0; } else if (args.at(i) == QLatin1String("rpc")) { bRpcMode = true; if (args.count() - 1 > i) { rpcCommand = QString(args.at(i + 1)); - } - else { + } else { QString rpcError = MainWindow::tr("Error: No RPC command specified"); #if defined(Q_OS_WIN) QMessageBox::information(nullptr, MainWindow::tr("RPC"), rpcError); @@ -297,9 +296,9 @@ int main(int argc, char **argv) { return 1; } } else if (args.at(i) == QLatin1String("--dump-input-streams")) { - g.bDebugDumpInput = true; + g.bDebugDumpInput = true; } else if (args.at(i) == QLatin1String("--print-echocancel-queue")) { - g.bDebugPrintQueue = true; + g.bDebugPrintQueue = true; } else { if (!bRpcMode) { QUrl u = QUrl::fromEncoded(args.at(i).toUtf8()); @@ -317,7 +316,7 @@ int main(int argc, char **argv) { } #ifdef USE_DBUS -#ifdef Q_OS_WIN +# ifdef Q_OS_WIN // By default, windbus expects the path to dbus-daemon to be in PATH, and the path // should contain bin\\, and the path to the config is hardcoded as ..\etc @@ -326,11 +325,15 @@ int main(int argc, char **argv) { if (_wgetenv_s(&reqSize, nullptr, 0, L"PATH") != 0) { qWarning() << "Failed to get PATH. Not adding application directory to PATH. DBus bindings may not work."; } else if (reqSize > 0) { - STACKVAR(wchar_t, buff, reqSize+1); + STACKVAR(wchar_t, buff, reqSize + 1); if (_wgetenv_s(&reqSize, buff, reqSize, L"PATH") != 0) { - qWarning() << "Failed to get PATH. Not adding application directory to PATH. DBus bindings may not work."; + qWarning() + << "Failed to get PATH. Not adding application directory to PATH. DBus bindings may not work."; } else { - QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(MumbleApplication::instance()->applicationVersionRootPath())).arg(QString::fromWCharArray(buff)); + QString path = + QString::fromLatin1("%1;%2") + .arg(QDir::toNativeSeparators(MumbleApplication::instance()->applicationVersionRootPath())) + .arg(QString::fromWCharArray(buff)); STACKVAR(wchar_t, buffout, path.length() + 1); path.toWCharArray(buffout); if (_wputenv_s(L"PATH", buffout) != 0) { @@ -339,12 +342,12 @@ int main(int argc, char **argv) { } } } -#endif +# endif #endif if (bRpcMode) { bool sent = false; - QMap<QString, QVariant> param; + QMap< QString, QVariant > param; param.insert(rpcCommand, rpcCommand); sent = SocketRPC::send(QLatin1String("Mumble"), QLatin1String("self"), param); if (sent) { @@ -354,18 +357,19 @@ int main(int argc, char **argv) { } } - if (! bAllowMultiple) { + if (!bAllowMultiple) { if (url.isValid()) { #ifndef USE_DBUS - QMap<QString, QVariant> param; + QMap< QString, QVariant > param; param.insert(QLatin1String("href"), url); #endif bool sent = false; #ifdef USE_DBUS - QDBusInterface qdbi(QLatin1String("net.sourceforge.mumble.mumble"), QLatin1String("/"), QLatin1String("net.sourceforge.mumble.Mumble")); + QDBusInterface qdbi(QLatin1String("net.sourceforge.mumble.mumble"), QLatin1String("/"), + QLatin1String("net.sourceforge.mumble.Mumble")); - QDBusMessage reply=qdbi.call(QLatin1String("openUrl"), QLatin1String(url.toEncoded())); - sent = (reply.type() == QDBusMessage::ReplyMessage); + QDBusMessage reply = qdbi.call(QLatin1String("openUrl"), QLatin1String(url.toEncoded())); + sent = (reply.type() == QDBusMessage::ReplyMessage); #else sent = SocketRPC::send(QLatin1String("Mumble"), QLatin1String("url"), param); #endif @@ -374,16 +378,16 @@ int main(int argc, char **argv) { } else { bool sent = false; #ifdef USE_DBUS - QDBusInterface qdbi(QLatin1String("net.sourceforge.mumble.mumble"), QLatin1String("/"), QLatin1String("net.sourceforge.mumble.Mumble")); + QDBusInterface qdbi(QLatin1String("net.sourceforge.mumble.mumble"), QLatin1String("/"), + QLatin1String("net.sourceforge.mumble.Mumble")); - QDBusMessage reply=qdbi.call(QLatin1String("focus")); - sent = (reply.type() == QDBusMessage::ReplyMessage); + QDBusMessage reply = qdbi.call(QLatin1String("focus")); + sent = (reply.type() == QDBusMessage::ReplyMessage); #else sent = SocketRPC::send(QLatin1String("Mumble"), QLatin1String("focus")); #endif if (sent) return 0; - } } @@ -398,9 +402,10 @@ int main(int argc, char **argv) { // If another Mumble instance attempts to open the file, it will fail, // and that instance will know to terminate itself. UserLockFile userLockFile(g.qdBasePath.filePath(QLatin1String("mumble.lock"))); - if (! bAllowMultiple) { + if (!bAllowMultiple) { if (!userLockFile.acquire()) { - qWarning("Another process has already acquired the lock file at '%s'. Terminating...", qPrintable(userLockFile.path())); + qWarning("Another process has already acquired the lock file at '%s'. Terminating...", + qPrintable(userLockFile.path())); return 1; } } @@ -419,14 +424,13 @@ int main(int argc, char **argv) { if (hc.dwFlags & HCF_HIGHCONTRASTON) g.s.bHighContrast = true; - } #endif DeferInit::run_initializers(); ApplicationPalette applicationPalette; - + Themes::apply(); QString qsSystemLocale = QLocale::system().name(); @@ -458,24 +462,26 @@ int main(int argc, char **argv) { // // See http://doc.qt.io/qt-5/linguist-programmers.html#deploying-translations for more information QTranslator qttranslator; - // First we try and see if there is a translation packaged with Mumble that shall overwrite any potentially existing Qt translations. - // If not, we try to load the qt-translations installed on the host-machine and if that fails as well, - // we try to load translations bundled in Mumble. - // Note: Resource starting with :/ are bundled resources specified in a .qrc file + // First we try and see if there is a translation packaged with Mumble that shall overwrite any potentially existing + // Qt translations. If not, we try to load the qt-translations installed on the host-machine and if that fails as + // well, we try to load translations bundled in Mumble. Note: Resource starting with :/ are bundled resources + // specified in a .qrc file if (qttranslator.load(QLatin1String(":/mumble_overwrite_qt_") + locale)) { a.installTranslator(&qttranslator); - } else if (qttranslator.load(QLatin1String(":/mumble_overwrite_qtbase_") + locale)) { + } else if (qttranslator.load(QLatin1String(":/mumble_overwrite_qtbase_") + locale)) { a.installTranslator(&qttranslator); - } else if (qttranslator.load(QLatin1String("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { + } else if (qttranslator.load(QLatin1String("qt_") + locale, + QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { a.installTranslator(&qttranslator); - } else if (qttranslator.load(QLatin1String("qtbase_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { + } else if (qttranslator.load(QLatin1String("qtbase_") + locale, + QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { a.installTranslator(&qttranslator); } else if (qttranslator.load(QLatin1String(":/qt_") + locale)) { a.installTranslator(&qttranslator); } else if (qttranslator.load(QLatin1String(":/qtbase_") + locale)) { a.installTranslator(&qttranslator); } - + // Initialize proxy settings NetworkConfig::SetupProxy(); @@ -508,7 +514,7 @@ int main(int argc, char **argv) { a.processEvents(); // Main Window - g.mw=new MainWindow(nullptr); + g.mw = new MainWindow(nullptr); g.mw->show(); g.talkingUI = new TalkingUI(); @@ -527,8 +533,8 @@ int main(int argc, char **argv) { QObject::connect(g.mw, &MainWindow::userAddedChannelListener, g.talkingUI, &TalkingUI::on_channelListenerAdded); QObject::connect(g.mw, &MainWindow::userRemovedChannelListener, g.talkingUI, &TalkingUI::on_channelListenerRemoved); - QObject::connect(&ChannelListener::get(), &ChannelListener::localVolumeAdjustmentsChanged, - g.talkingUI, &TalkingUI::on_channelListenerLocalVolumeAdjustmentChanged); + QObject::connect(&ChannelListener::get(), &ChannelListener::localVolumeAdjustmentsChanged, g.talkingUI, + &TalkingUI::on_channelListenerLocalVolumeAdjustmentChanged); QObject::connect(g.mw, &MainWindow::serverSynchronized, g.talkingUI, &TalkingUI::on_serverSynchronized); @@ -576,8 +582,8 @@ int main(int argc, char **argv) { if (g.s.iIdleTime == 5 * 60) { // New default g.s.iaeIdleAction = Settings::Nothing; } else { - g.s.iIdleTime = 60 * qRound(g.s.iIdleTime / 60.); // Round to minutes - g.s.iaeIdleAction = Settings::Deafen; // Old behavior + g.s.iIdleTime = 60 * qRound(g.s.iIdleTime / 60.); // Round to minutes + g.s.iaeIdleAction = Settings::Deafen; // Old behavior } } @@ -589,7 +595,7 @@ int main(int argc, char **argv) { g.s.uiUpdateCounter = 2; - if (! CertWizard::validateCert(g.s.kpCertificate)) { + if (!CertWizard::validateCert(g.s.kpCertificate)) { QDir qd(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)); QFile qf(qd.absoluteFilePath(QLatin1String("MumbleAutomaticCertificateBackup.p12"))); if (qf.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) { @@ -598,12 +604,12 @@ int main(int argc, char **argv) { if (CertWizard::validateCert(kp)) g.s.kpCertificate = kp; } - if (! CertWizard::validateCert(g.s.kpCertificate)) { + if (!CertWizard::validateCert(g.s.kpCertificate)) { CertWizard *cw = new CertWizard(g.mw); cw->exec(); delete cw; - if (! CertWizard::validateCert(g.s.kpCertificate)) { + if (!CertWizard::validateCert(g.s.kpCertificate)) { g.s.kpCertificate = CertWizard::generateNewCert(); if (qf.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Unbuffered)) { qf.write(CertWizard::exportCert(g.s.kpCertificate)); @@ -614,20 +620,22 @@ int main(int argc, char **argv) { } if (QDateTime::currentDateTime().daysTo(g.s.kpCertificate.first.first().expiryDate()) < 14) - g.l->log(Log::Warning, CertWizard::tr("<b>Certificate Expiry:</b> Your certificate is about to expire. You need to renew it, or you will no longer be able to connect to servers you are registered on.")); + g.l->log(Log::Warning, + CertWizard::tr("<b>Certificate Expiry:</b> Your certificate is about to expire. You need to renew it, " + "or you will no longer be able to connect to servers you are registered on.")); #ifdef QT_NO_DEBUG // Only perform the version-check for non-debug builds if (g.s.bUpdateCheck) { // Use different settings for the version checks depending on whether this is a snapshot build // or a normal release build -#ifndef SNAPSHOT_BUILD +# ifndef SNAPSHOT_BUILD // release build new VersionCheck(true, g.mw); -#else +# else // snapshot build new VersionCheck(false, g.mw, true); -#endif +# endif } #else g.mw->msgBox(MainWindow::tr("Skipping version check in debug mode.")); @@ -640,7 +648,7 @@ int main(int argc, char **argv) { OpenURLEvent *oue = new OpenURLEvent(url); qApp->postEvent(g.mw, oue); #ifdef Q_OS_MAC - } else if (! a.quLaunchURL.isEmpty()) { + } else if (!a.quLaunchURL.isEmpty()) { OpenURLEvent *oue = new OpenURLEvent(a.quLaunchURL); qApp->postEvent(g.mw, oue); #endif @@ -648,13 +656,13 @@ int main(int argc, char **argv) { g.mw->on_qaServerConnect_triggered(true); } - if (! g.bQuit) - res=a.exec(); + if (!g.bQuit) + res = a.exec(); g.s.save(); url.clear(); - + ServerHandlerPtr sh = g.sh; if (sh) { if (sh->isRunning()) { @@ -679,7 +687,7 @@ int main(int argc, char **argv) { delete srpc; g.sh.reset(); - while (sh && ! sh.unique()) + while (sh && !sh.unique()) QThread::yieldCurrentThread(); sh.reset(); @@ -710,10 +718,10 @@ int main(int argc, char **argv) { Global::g_global_struct = nullptr; #ifndef QT_NO_DEBUG -#if (GOOGLE_PROTOBUF_VERSION >= 2001000) +# if (GOOGLE_PROTOBUF_VERSION >= 2001000) // Release global protobuf memory allocations. google::protobuf::ShutdownProtobufLibrary(); -#endif +# endif #endif #ifdef Q_OS_WIN @@ -728,7 +736,7 @@ int main(int argc, char **argv) { // Tear down OpenSSL state. MumbleSSL::destroy(); - + // At this point termination of our process is immenent. We can safely // launch another version of Mumble. The reason we do an actual // restart instead of re-creating our data structures is that making @@ -738,14 +746,18 @@ int main(int argc, char **argv) { // than sorry (and crash/bug out). Also take care to reconnect if possible. if (res == MUMBLE_EXIT_CODE_RESTART) { QStringList arguments; - - if (bAllowMultiple) arguments << QLatin1String("--multiple"); - if (suppressIdentity) arguments << QLatin1String("--noidentity"); - if (customJackClientName) arguments << QLatin1String("--jackname ") + g.s.qsJackClientName; - if (!url.isEmpty()) arguments << url.toString(); - + + if (bAllowMultiple) + arguments << QLatin1String("--multiple"); + if (suppressIdentity) + arguments << QLatin1String("--noidentity"); + if (customJackClientName) + arguments << QLatin1String("--jackname ") + g.s.qsJackClientName; + if (!url.isEmpty()) + arguments << url.toString(); + qWarning() << "Triggering restart of Mumble with arguments: " << arguments; - + #ifdef Q_OS_WIN // Work around bug related to QTBUG-7645. Mumble has uiaccess=true set // on windows which makes normal CreateProcess calls (like Qt uses in @@ -754,23 +766,21 @@ int main(int argc, char **argv) { // rights but only the right token on launch. Here we use ShellExecuteEx // which handles this transparently for us. const std::wstring applicationFilePath = qApp->applicationFilePath().toStdWString(); - const std::wstring argumentsString = arguments.join(QLatin1String(" ")).toStdWString(); - + const std::wstring argumentsString = arguments.join(QLatin1String(" ")).toStdWString(); + SHELLEXECUTEINFO si; ZeroMemory(&si, sizeof(SHELLEXECUTEINFO)); - si.cbSize = sizeof(SHELLEXECUTEINFO); - si.lpFile = applicationFilePath.data(); + si.cbSize = sizeof(SHELLEXECUTEINFO); + si.lpFile = applicationFilePath.data(); si.lpParameters = argumentsString.data(); - + bool ok = (ShellExecuteEx(&si) == TRUE); #else bool ok = QProcess::startDetached(qApp->applicationFilePath(), arguments); #endif - if(!ok) { - QMessageBox::warning(nullptr, - QApplication::tr("Failed to restart mumble"), - QApplication::tr("Mumble failed to restart itself. Please restart it manually.") - ); + if (!ok) { + QMessageBox::warning(nullptr, QApplication::tr("Failed to restart mumble"), + QApplication::tr("Mumble failed to restart itself. Please restart it manually.")); return 1; } return 0; @@ -791,10 +801,10 @@ extern "C" __declspec(dllexport) int MumbleMain(HINSTANCE instance, HINSTANCE pr return -1; } - QVector<QByteArray> argvS; + QVector< QByteArray > argvS; argvS.reserve(argc); - QVector<char *> argvV(argc, nullptr); + QVector< char * > argvV(argc, nullptr); for (int i = 0; i < argc; ++i) { argvS.append(QString::fromWCharArray(argvW[i]).toLocal8Bit()); argvV[i] = argvS.back().data(); diff --git a/src/mumble/mumble_pch.hpp b/src/mumble/mumble_pch.hpp index 9e884d9df..76dab5fea 100644 --- a/src/mumble/mumble_pch.hpp +++ b/src/mumble/mumble_pch.hpp @@ -4,117 +4,117 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef Q_MOC_RUN -#ifndef MUMBLE_MUMBLE_MUMBLE_PCH_H_ -#define MUMBLE_MUMBLE_MUMBLE_PCH_H_ - -#define QT_NO_CAST_TO_ASCII -#define QT_NO_CAST_FROM_ASCII -#define QT_USE_FAST_CONCATENATION -#define QT_USE_FAST_OPERATOR_PLUS - -#include <QtCore/QtGlobal> - -#ifdef Q_OS_WIN -# include "win.h" -#endif - -#define BOOST_TYPEOF_SUPPRESS_UNNAMED_NAMESPACE - -#ifdef __APPLE__ -# include <Carbon/Carbon.h> -# include <CoreFoundation/CoreFoundation.h> -# include <ApplicationServices/ApplicationServices.h> -# undef nil -# undef check -# undef TYPE_BOOL -#endif - -#include <QtCore/QtCore> -#include <QtGui/QtGui> -#include <QtWidgets/QtWidgets> - -#include <QtSvg/QtSvg> -#ifdef USE_DBUS -# include <QtDBus/QtDBus> -#endif -#include <QtNetwork/QtNetwork> -#include <QtSql/QtSql> -#include <QtXml/QtXml> - -#ifdef Q_OS_WIN -# define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1 -#endif -#include <sndfile.h> -#include <celt.h> -#ifdef USE_SBCELT -# include <sbcelt.h> -#endif -#include <speex/speex.h> -#include <speex/speex_jitter.h> -#include <speex/speex_preprocess.h> -#include <speex/speex_echo.h> -#include <speex/speex_resampler.h> - -#include <boost/array.hpp> -#include <boost/accumulators/accumulators.hpp> -#include <boost/accumulators/statistics/stats.hpp> -#include <boost/accumulators/statistics/mean.hpp> -#include <boost/accumulators/statistics/variance.hpp> -#include <boost/accumulators/statistics/extended_p_square.hpp> -#include <boost/bind.hpp> -#include <boost/enable_shared_from_this.hpp> -#include <boost/make_shared.hpp> -#include <boost/shared_ptr.hpp> -#include <boost/shared_array.hpp> -#include <boost/scoped_ptr.hpp> -#include <boost/scoped_array.hpp> -#include <boost/typeof/typeof.hpp> -#include <boost/weak_ptr.hpp> - -#include <algorithm> -#include <cmath> - -#ifdef Q_OS_WIN -# include <ws2tcpip.h> -# include <qos2.h> -# include <shellapi.h> -# include <wintrust.h> -# include <softpub.h> -# include <dbt.h> -# include <delayimp.h> -# include <shlobj.h> -# include <tlhelp32.h> -# include <psapi.h> -# include <mmreg.h> -#else // ifndef Q_OS_WIN -# include <sys/socket.h> -# include <sys/types.h> -# include <arpa/inet.h> -# include <netinet/in.h> -# include <netinet/tcp.h> -#endif - -#if !defined(Q_OS_OPENBSD) && (defined(__MMX__) || defined(Q_OS_WIN)) -# include <mmintrin.h> -#endif - -#ifdef USE_BONJOUR -# include <dns_sd.h> -#endif - -#ifdef __OBJC__ - #define nil 0 -#endif - -#include <openssl/aes.h> -#include <openssl/rand.h> -#include <openssl/pem.h> -#include <openssl/conf.h> -#include <openssl/x509v3.h> -#include <openssl/pkcs12.h> -#include <openssl/ssl.h> +# ifndef MUMBLE_MUMBLE_MUMBLE_PCH_H_ +# define MUMBLE_MUMBLE_MUMBLE_PCH_H_ + +# define QT_NO_CAST_TO_ASCII +# define QT_NO_CAST_FROM_ASCII +# define QT_USE_FAST_CONCATENATION +# define QT_USE_FAST_OPERATOR_PLUS + +# include <QtCore/QtGlobal> + +# ifdef Q_OS_WIN +# include "win.h" +# endif + +# define BOOST_TYPEOF_SUPPRESS_UNNAMED_NAMESPACE + +# ifdef __APPLE__ +# include <ApplicationServices/ApplicationServices.h> +# include <Carbon/Carbon.h> +# include <CoreFoundation/CoreFoundation.h> +# undef nil +# undef check +# undef TYPE_BOOL +# endif + +# include <QtCore/QtCore> +# include <QtGui/QtGui> +# include <QtWidgets/QtWidgets> + +# include <QtSvg/QtSvg> +# ifdef USE_DBUS +# include <QtDBus/QtDBus> +# endif +# include <QtNetwork/QtNetwork> +# include <QtSql/QtSql> +# include <QtXml/QtXml> + +# ifdef Q_OS_WIN +# define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1 +# endif +# include <celt.h> +# include <sndfile.h> +# ifdef USE_SBCELT +# include <sbcelt.h> +# endif +# include <speex/speex.h> +# include <speex/speex_echo.h> +# include <speex/speex_jitter.h> +# include <speex/speex_preprocess.h> +# include <speex/speex_resampler.h> + +# include <boost/accumulators/accumulators.hpp> +# include <boost/accumulators/statistics/extended_p_square.hpp> +# include <boost/accumulators/statistics/mean.hpp> +# include <boost/accumulators/statistics/stats.hpp> +# include <boost/accumulators/statistics/variance.hpp> +# include <boost/array.hpp> +# include <boost/bind.hpp> +# include <boost/enable_shared_from_this.hpp> +# include <boost/make_shared.hpp> +# include <boost/scoped_array.hpp> +# include <boost/scoped_ptr.hpp> +# include <boost/shared_array.hpp> +# include <boost/shared_ptr.hpp> +# include <boost/typeof/typeof.hpp> +# include <boost/weak_ptr.hpp> + +# include <algorithm> +# include <cmath> + +# ifdef Q_OS_WIN +# include <dbt.h> +# include <delayimp.h> +# include <mmreg.h> +# include <psapi.h> +# include <qos2.h> +# include <shellapi.h> +# include <shlobj.h> +# include <softpub.h> +# include <tlhelp32.h> +# include <wintrust.h> +# include <ws2tcpip.h> +# else // ifndef Q_OS_WIN +# include <arpa/inet.h> +# include <netinet/in.h> +# include <netinet/tcp.h> +# include <sys/socket.h> +# include <sys/types.h> +# endif + +# if !defined(Q_OS_OPENBSD) && (defined(__MMX__) || defined(Q_OS_WIN)) +# include <mmintrin.h> +# endif + +# ifdef USE_BONJOUR +# include <dns_sd.h> +# endif + +# ifdef __OBJC__ +# define nil 0 +# endif + +# include <openssl/aes.h> +# include <openssl/conf.h> +# include <openssl/pem.h> +# include <openssl/pkcs12.h> +# include <openssl/rand.h> +# include <openssl/ssl.h> +# include <openssl/x509v3.h> /* OpenSSL defines set_key. This breaks our protobuf-generated setters. */ -#undef set_key +# undef set_key -#endif +# endif #endif diff --git a/src/mumble/os_early_win.cpp b/src/mumble/os_early_win.cpp index a485e1d11..87c1e2d71 100644 --- a/src/mumble/os_early_win.cpp +++ b/src/mumble/os_early_win.cpp @@ -7,13 +7,13 @@ #include <string> +#include <sddl.h> #include <shlwapi.h> #include <stdio.h> -#include <sddl.h> // Alert shows a fatal error dialog and waits for the user to click OK. static void Alert(LPCWSTR title, LPCWSTR msg) { - MessageBox(nullptr, msg, title, MB_OK|MB_ICONERROR); + MessageBox(nullptr, msg, title, MB_OK | MB_ICONERROR); } // GetExecutablePath returns the path to mumble.exe. @@ -42,11 +42,13 @@ static bool UIAccessDisabledViaConfig() { // to zero-terminate. wchar_t buf[7]; memset(&buf, 0, sizeof(buf)); - DWORD sz = sizeof(buf) - 1*sizeof(wchar_t); + DWORD sz = sizeof(buf) - 1 * sizeof(wchar_t); HKEY key = nullptr; - bool success = (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Mumble\\Mumble\\shortcut\\windows\\uiaccess", 0, KEY_READ, &key) == ERROR_SUCCESS) && - (RegQueryValueExW(key, L"enable" , nullptr, nullptr, (LPBYTE)&buf, &sz) == ERROR_SUCCESS); + bool success = + (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Mumble\\Mumble\\shortcut\\windows\\uiaccess", 0, KEY_READ, &key) + == ERROR_SUCCESS) + && (RegQueryValueExW(key, L"enable", nullptr, nullptr, (LPBYTE) &buf, &sz) == ERROR_SUCCESS); if (success && _wcsicmp(buf, L"false") == 0) { return true; } @@ -61,7 +63,7 @@ static bool ProcessHasUIAccess() { return false; } - DWORD ui_access = 0; + DWORD ui_access = 0; DWORD ui_access_size = sizeof(ui_access); if (!GetTokenInformation(token, TokenUIAccess, &ui_access, sizeof(ui_access), &ui_access_size)) { CloseHandle(token); @@ -117,16 +119,8 @@ static bool RelaunchWithoutUIAccessIfNecessary() { return false; } - if (!CreateProcessW(exe_path.c_str(), - GetCommandLineW(), - nullptr, - nullptr, - FALSE, - 0, - nullptr, - nullptr, - &startup_info, - &process_info)) { + if (!CreateProcessW(exe_path.c_str(), GetCommandLineW(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, + &startup_info, &process_info)) { return false; } diff --git a/src/mumble/os_unix.cpp b/src/mumble/os_unix.cpp index 56c3daa0c..504bce4f3 100644 --- a/src/mumble/os_unix.cpp +++ b/src/mumble/os_unix.cpp @@ -5,27 +5,29 @@ #include "LogEmitter.h" #include "Global.h" -static QSharedPointer<LogEmitter> le; +static QSharedPointer< LogEmitter > le; static void mumbleMessageOutputQString(QtMsgType type, const QString &msg) { char c; switch (type) { case QtDebugMsg: - c='D'; + c = 'D'; break; case QtWarningMsg: - c='W'; + c = 'W'; break; case QtFatalMsg: - c='F'; + c = 'F'; break; default: - c='X'; + c = 'X'; } -#define LOG(f, msg) fprintf(f, "<%c>%s %s\n", c, \ - qPrintable(QDateTime::currentDateTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss.zzz"))), qPrintable(msg)) +#define LOG(f, msg) \ + fprintf(f, "<%c>%s %s\n", c, \ + qPrintable(QDateTime::currentDateTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss.zzz"))), \ + qPrintable(msg)) QString date = QDateTime::currentDateTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss.zzz")); QString fmsg = QString::fromLatin1("<%1>%2 %3").arg(c).arg(date).arg(msg); diff --git a/src/mumble/os_win.cpp b/src/mumble/os_win.cpp index 9728a980a..b2ac2be21 100644 --- a/src/mumble/os_win.cpp +++ b/src/mumble/os_win.cpp @@ -7,34 +7,35 @@ #include "MumbleApplication.h" #ifdef _MSC_VER -# include "Utils.h" +# include "Utils.h" #endif #include "Version.h" #include "win.h" -#include <cmath> #include <cfloat> +#include <cmath> -#include <wincrypt.h> -#include <tlhelp32.h> #include <dbghelp.h> +#include <tlhelp32.h> +#include <wincrypt.h> #ifdef _MSC_VER -# include <delayimp.h> +# include <delayimp.h> #endif #include <emmintrin.h> -#include <shobjidl.h> -#include <shlobj.h> #include <share.h> // For share flags for _wfsopen +#include <shlobj.h> +#include <shobjidl.h> -// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. +// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name +// (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" extern "C" { - void __cpuid(int a[4], int b); - void mumble_speex_init(); +void __cpuid(int a[4], int b); +void mumble_speex_init(); }; #define DUMP_BUFFER_SIZE 1024 @@ -45,11 +46,11 @@ static FILE *fConsole = nullptr; static wchar_t wcComment[DUMP_BUFFER_SIZE] = L""; static MINIDUMP_USER_STREAM musComment; -static QSharedPointer<LogEmitter> le; +static QSharedPointer< LogEmitter > le; static int cpuinfo[4]; -bool bIsWin7 = false; +bool bIsWin7 = false; bool bIsVistaSP1 = false; HWND mumble_mw_hwnd = 0; @@ -58,16 +59,16 @@ static void mumbleMessageOutputQString(QtMsgType type, const QString &msg) { char c; switch (type) { case QtDebugMsg: - c='D'; + c = 'D'; break; case QtWarningMsg: - c='W'; + c = 'W'; break; case QtFatalMsg: - c='F'; + c = 'F'; break; default: - c='X'; + c = 'X'; } QString date = QDateTime::currentDateTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss.zzz")); QString fmsg = QString::fromLatin1("<%1>%2 %3").arg(c).arg(date).arg(msg); @@ -86,9 +87,9 @@ static void mumbleMessageOutputWithContext(QtMsgType type, const QMessageLogCont mumbleMessageOutputQString(type, msg); } -static LONG WINAPI MumbleUnhandledExceptionFilter(struct _EXCEPTION_POINTERS* ExceptionInfo) { +static LONG WINAPI MumbleUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo) { MINIDUMP_EXCEPTION_INFORMATION i; - i.ThreadId = GetCurrentThreadId(); + i.ThreadId = GetCurrentThreadId(); i.ExceptionPointers = ExceptionInfo; MINIDUMP_USER_STREAM_INFORMATION musi; @@ -96,9 +97,13 @@ static LONG WINAPI MumbleUnhandledExceptionFilter(struct _EXCEPTION_POINTERS* Ex musi.UserStreamCount = 1; musi.UserStreamArray = &musComment; - HANDLE hMinidump = CreateFile(wcCrashDumpPath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE hMinidump = + CreateFile(wcCrashDumpPath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hMinidump != INVALID_HANDLE_VALUE) { - if (MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hMinidump, static_cast<MINIDUMP_TYPE>(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithThreadInfo), &i, &musi, nullptr)) { + if (MiniDumpWriteDump( + GetCurrentProcess(), GetCurrentProcessId(), hMinidump, + static_cast< MINIDUMP_TYPE >(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithThreadInfo), &i, + &musi, nullptr)) { FlushFileBuffers(hMinidump); } CloseHandle(hMinidump); @@ -114,18 +119,16 @@ static void enableCrashOnCrashes() { // See http://support.microsoft.com/kb/976038 // http://www.altdevblogaday.com/2012/07/06/when-even-crashing-doesnt-work/ - typedef BOOL (WINAPI *tGetPolicy)(LPDWORD lpFlags); - typedef BOOL (WINAPI *tSetPolicy)(DWORD dwFlags); + typedef BOOL(WINAPI * tGetPolicy)(LPDWORD lpFlags); + typedef BOOL(WINAPI * tSetPolicy)(DWORD dwFlags); const DWORD PROCESS_CALLBACK_FILTER_ENABLED = 0x01; HMODULE kernel32 = LoadLibrary(L"kernel32.dll"); - tGetPolicy pGetPolicy = (tGetPolicy) GetProcAddress(kernel32, - "GetProcessUserModeExceptionPolicy"); + tGetPolicy pGetPolicy = (tGetPolicy) GetProcAddress(kernel32, "GetProcessUserModeExceptionPolicy"); - tSetPolicy pSetPolicy = (tSetPolicy) GetProcAddress(kernel32, - "SetProcessUserModeExceptionPolicy"); + tSetPolicy pSetPolicy = (tSetPolicy) GetProcAddress(kernel32, "SetProcessUserModeExceptionPolicy"); if (pGetPolicy && pSetPolicy) { // Only available as of Vista SP2 / Win7 SP1 DWORD dwFlags; @@ -143,15 +146,15 @@ BOOL SetHeapOptions() { if (!hLib) return FALSE; - typedef BOOL (WINAPI *HSI)(HANDLE, HEAP_INFORMATION_CLASS, PVOID, SIZE_T); - HSI pHsi = (HSI)GetProcAddress(hLib, "HeapSetInformation"); + typedef BOOL(WINAPI * HSI)(HANDLE, HEAP_INFORMATION_CLASS, PVOID, SIZE_T); + HSI pHsi = (HSI) GetProcAddress(hLib, "HeapSetInformation"); if (!pHsi) { FreeLibrary(hLib); return FALSE; } #ifndef HeapEnableTerminationOnCorruption -#define HeapEnableTerminationOnCorruption (HEAP_INFORMATION_CLASS)1 +# define HeapEnableTerminationOnCorruption (HEAP_INFORMATION_CLASS) 1 #endif BOOL fRet = (pHsi)(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0) ? TRUE : FALSE; @@ -180,7 +183,7 @@ FARPROC WINAPI delayHook(unsigned dliNotify, PDelayLoadInfo pdli) { size_t offset = 0; if (_stricmp(filename + length - 4, ".dll") == 0) - offset = length-4; + offset = length - 4; else offset = length; @@ -221,7 +224,8 @@ void os_init() { #define MMXSSE 0x02800000 if ((cpuinfo[3] & MMXSSE) != MMXSSE) { - ::MessageBoxA(nullptr, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", MB_OK | MB_ICONERROR); + ::MessageBoxA(nullptr, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", + MB_OK | MB_ICONERROR); exit(0); } @@ -229,9 +233,9 @@ void os_init() { memset(&ovi, 0, sizeof(ovi)); ovi.dwOSVersionInfoSize = sizeof(ovi); - GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi)); - bIsWin7 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) &&(ovi.dwBuildNumber >= 7100)); - bIsVistaSP1 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) &&(ovi.dwBuildNumber >= 6001)); + GetVersionEx(reinterpret_cast< OSVERSIONINFOW * >(&ovi)); + bIsWin7 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) && (ovi.dwBuildNumber >= 7100)); + bIsVistaSP1 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) && (ovi.dwBuildNumber >= 6001)); #if _MSC_VER == 1800 && defined(_M_X64) // Disable MSVC 2013's FMA-optimized math routines on Windows @@ -258,7 +262,7 @@ void os_init() { #ifdef QT_NO_DEBUG QString console = g.qdBasePath.filePath(QLatin1String("Console.txt")); - fConsole = _wfsopen(console.toStdWString().c_str(), L"a+", _SH_DENYWR); + fConsole = _wfsopen(console.toStdWString().c_str(), L"a+", _SH_DENYWR); if (fConsole) { qInstallMessageHandler(mumbleMessageOutputWithContext); @@ -266,7 +270,7 @@ void os_init() { QString hash; QFile f(qApp->applicationFilePath()); - if (! f.open(QIODevice::ReadOnly)) { + if (!f.open(QIODevice::ReadOnly)) { qWarning("VersionCheck: Failed to open binary"); } else { QByteArray a = f.readAll(); @@ -277,12 +281,14 @@ void os_init() { } } - QString comment = QString::fromLatin1("%1\n%2\n%3").arg(QString::fromLatin1(MUMBLE_RELEASE), QString::fromLatin1(MUMTEXT(MUMBLE_VERSION_STRING)), hash); + QString comment = + QString::fromLatin1("%1\n%2\n%3") + .arg(QString::fromLatin1(MUMBLE_RELEASE), QString::fromLatin1(MUMTEXT(MUMBLE_VERSION_STRING)), hash); wcscpy_s(wcComment, DUMP_BUFFER_SIZE, comment.toStdWString().c_str()); - musComment.Type = CommentStreamW; - musComment.Buffer = wcComment; - musComment.BufferSize = static_cast<ULONG>(wcslen(wcComment) * sizeof(wchar_t)); + musComment.Type = CommentStreamW; + musComment.Buffer = wcComment; + musComment.BufferSize = static_cast< ULONG >(wcslen(wcComment) * sizeof(wchar_t)); QString dump = g.qdBasePath.filePath(QLatin1String("mumble.dmp")); @@ -299,26 +305,23 @@ void os_init() { SetCurrentProcessExplicitAppUserModelID(L"net.sourceforge.mumble.Mumble"); } -DWORD WinVerifySslCert(const QByteArray& cert) { +DWORD WinVerifySslCert(const QByteArray &cert) { DWORD errorStatus = -1; - PCCERT_CONTEXT certContext = CertCreateCertificateContext(X509_ASN_ENCODING, reinterpret_cast<const BYTE*>(cert.constData()), cert.size()); + PCCERT_CONTEXT certContext = CertCreateCertificateContext( + X509_ASN_ENCODING, reinterpret_cast< const BYTE * >(cert.constData()), cert.size()); if (!certContext) { return errorStatus; } - LPCSTR usage[] = { - szOID_PKIX_KP_SERVER_AUTH, - szOID_SERVER_GATED_CRYPTO, - szOID_SGC_NETSCAPE - }; + LPCSTR usage[] = { szOID_PKIX_KP_SERVER_AUTH, szOID_SERVER_GATED_CRYPTO, szOID_SGC_NETSCAPE }; CERT_CHAIN_PARA chainParameter; memset(&chainParameter, 0, sizeof(CERT_CHAIN_PARA)); - chainParameter.cbSize = sizeof(CERT_CHAIN_PARA); - chainParameter.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR; - chainParameter.RequestedUsage.Usage.cUsageIdentifier = ARRAYSIZE(usage); - chainParameter.RequestedUsage.Usage.rgpszUsageIdentifier = const_cast<LPSTR *>(usage); + chainParameter.cbSize = sizeof(CERT_CHAIN_PARA); + chainParameter.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR; + chainParameter.RequestedUsage.Usage.cUsageIdentifier = ARRAYSIZE(usage); + chainParameter.RequestedUsage.Usage.rgpszUsageIdentifier = const_cast< LPSTR * >(usage); PCCERT_CHAIN_CONTEXT chainContext = nullptr; CertGetCertificateChain(nullptr, certContext, nullptr, nullptr, &chainParameter, 0, nullptr, &chainContext); diff --git a/src/mumble/widgets/MUComboBox.cpp b/src/mumble/widgets/MUComboBox.cpp index b114d77fc..4b35da394 100644 --- a/src/mumble/widgets/MUComboBox.cpp +++ b/src/mumble/widgets/MUComboBox.cpp @@ -7,9 +7,7 @@ #include <QtWidgets/QListView> -MUComboBox::MUComboBox(QWidget *parent) - : QComboBox(parent) { - +MUComboBox::MUComboBox(QWidget *parent) : QComboBox(parent) { // Set the QComboBox to be backed by a QListView. // By default on macOS, QComboBoxes are backed by // something that tries to emulate a native macOS diff --git a/src/mumble_exe/Overlay.cpp b/src/mumble_exe/Overlay.cpp index 7d7861697..d47b3247a 100755..100644 --- a/src/mumble_exe/Overlay.cpp +++ b/src/mumble_exe/Overlay.cpp @@ -11,4 +11,4 @@ // defined here in mumble.exe (alongside the symbol in mumble_app.dll) because that // allows older versions of mumble_ol.dll that are not "mumble_app.dll"-aware at all // to continue to work in that world. -extern "C" __declspec(dllexport) void mumbleSelfDetection() {}; +extern "C" __declspec(dllexport) void mumbleSelfDetection(){}; diff --git a/src/mumble_exe/mumble_exe.cpp b/src/mumble_exe/mumble_exe.cpp index 2ec5d64ec..22b23df5d 100644 --- a/src/mumble_exe/mumble_exe.cpp +++ b/src/mumble_exe/mumble_exe.cpp @@ -17,7 +17,7 @@ typedef int (*DLL_DEBUG_MAIN)(int, char **); // Alert shows a fatal error dialog and waits for the user to click OK. static void Alert(LPCWSTR title, LPCWSTR msg) { - MessageBox(nullptr, msg, title, MB_OK|MB_ICONERROR); + MessageBox(nullptr, msg, title, MB_OK | MB_ICONERROR); } // Get the current Mumble version built into this executable. @@ -25,8 +25,8 @@ static void Alert(LPCWSTR title, LPCWSTR msg) { // string. static const std::wstring GetMumbleVersion() { #ifdef MUMBLE_VERSION -# define MUMXTEXT(X) L#X -# define MUMTEXT(X) MUMXTEXT(X) +# define MUMXTEXT(X) L# X +# define MUMTEXT(X) MUMXTEXT(X) const std::wstring version(MUMTEXT(MUMBLE_VERSION)); return version; #else @@ -167,7 +167,7 @@ int main(int argc, char **argv) { return -3; } - DLL_DEBUG_MAIN entry_point = reinterpret_cast<DLL_DEBUG_MAIN>(GetProcAddress(dll, "main")); + DLL_DEBUG_MAIN entry_point = reinterpret_cast< DLL_DEBUG_MAIN >(GetProcAddress(dll, "main")); if (!entry_point) { Alert(L"Mumble Launcher Error -4", L"Unable to find expected entry point ('main') in mumble_app.dll."); return -4; @@ -177,7 +177,7 @@ int main(int argc, char **argv) { return rc; } -#endif // DEBUG +#endif // DEBUG int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, wchar_t *cmdArg, int cmdShow) { if (!ConfigureEnvironment()) { @@ -210,7 +210,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, wchar_t *cmdAr return -3; } - DLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(GetProcAddress(dll, "MumbleMain")); + DLL_MAIN entry_point = reinterpret_cast< DLL_MAIN >(GetProcAddress(dll, "MumbleMain")); if (!entry_point) { Alert(L"Mumble Launcher Error -4", L"Unable to find expected entry point ('MumbleMain') in mumble_app.dll."); return -4; diff --git a/src/murmur/About.cpp b/src/murmur/About.cpp index 1759ef4ae..1906af930 100644 --- a/src/murmur/About.cpp +++ b/src/murmur/About.cpp @@ -4,9 +4,9 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "About.h" -#include "Version.h" #include "License.h" #include "Utils.h" +#include "Version.h" #include <QtWidgets/QApplication> #include <QtWidgets/QLabel> @@ -20,7 +20,7 @@ AboutDialog::AboutDialog(QWidget *p, AboutDialogOptions options) : QDialog(p) { setWindowTitle(tr("About Murmur")); setMinimumSize(QSize(400, 300)); - QTabWidget *qtwTab = new QTabWidget(this); + QTabWidget *qtwTab = new QTabWidget(this); QVBoxLayout *vblMain = new QVBoxLayout(this); QTextEdit *qteLicense = new QTextEdit(qtwTab); @@ -35,31 +35,30 @@ AboutDialog::AboutDialog(QWidget *p, AboutDialogOptions options) : QDialog(p) { qtb3rdPartyLicense->setReadOnly(true); qtb3rdPartyLicense->setOpenExternalLinks(true); - QList<LicenseInfo> thirdPartyLicenses = License::thirdPartyLicenses(); - foreach(LicenseInfo li, thirdPartyLicenses) { + QList< LicenseInfo > thirdPartyLicenses = License::thirdPartyLicenses(); + foreach (LicenseInfo li, thirdPartyLicenses) { qtb3rdPartyLicense->append(QString::fromLatin1("<h3>%1 (<a href=\"%2\">%2</a>)</h3><pre>%3</pre>") - .arg(li.name.toHtmlEscaped()) - .arg(li.url.toHtmlEscaped()) - .arg(li.license.toHtmlEscaped())); + .arg(li.name.toHtmlEscaped()) + .arg(li.url.toHtmlEscaped()) + .arg(li.license.toHtmlEscaped())); } qtb3rdPartyLicense->moveCursor(QTextCursor::Start); QWidget *about = new QWidget(qtwTab); - QLabel *icon = new QLabel(about); + QLabel *icon = new QLabel(about); QIcon windowIcon = QApplication::windowIcon(); icon->setPixmap(windowIcon.pixmap(windowIcon.actualSize(QSize(128, 128)))); QLabel *text = new QLabel(about); text->setOpenExternalLinks(true); - text->setText(tr( - "<h3>Murmur (%1)</h3>" - "<p>%3</p>" - "<p><tt><a href=\"%2\">%2</a></tt></p>" - ).arg(QLatin1String(MUMBLE_RELEASE)) - .arg(QLatin1String("http://www.mumble.info/")) - .arg(QLatin1String("Copyright 2005-2020 The Mumble Developers"))); + text->setText(tr("<h3>Murmur (%1)</h3>" + "<p>%3</p>" + "<p><tt><a href=\"%2\">%2</a></tt></p>") + .arg(QLatin1String(MUMBLE_RELEASE)) + .arg(QLatin1String("http://www.mumble.info/")) + .arg(QLatin1String("Copyright 2005-2020 The Mumble Developers"))); QHBoxLayout *qhbl = new QHBoxLayout(about); qhbl->addWidget(icon); qhbl->addWidget(text); diff --git a/src/murmur/About.h b/src/murmur/About.h index 8c4be64d0..f3efa5a53 100644 --- a/src/murmur/About.h +++ b/src/murmur/About.h @@ -6,8 +6,8 @@ #ifndef MUMBLE_MURMUR_ABOUT_H_ #define MUMBLE_MURMUR_ABOUT_H_ -#include <QtCore/QtGlobal> #include <QtCore/QObject> +#include <QtCore/QtGlobal> #include <QtWidgets/QDialog> enum AboutDialogOptions { @@ -20,11 +20,11 @@ enum AboutDialogOptions { }; class AboutDialog : public QDialog { - private: - Q_OBJECT - Q_DISABLE_COPY(AboutDialog) - public: - AboutDialog(QWidget *parent, AboutDialogOptions options = AboutDialogOptionsDefault); +private: + Q_OBJECT + Q_DISABLE_COPY(AboutDialog) +public: + AboutDialog(QWidget *parent, AboutDialogOptions options = AboutDialogOptionsDefault); }; #endif diff --git a/src/murmur/BonjourServer.cpp b/src/murmur/BonjourServer.cpp index de54465a4..9041557b3 100644 --- a/src/murmur/BonjourServer.cpp +++ b/src/murmur/BonjourServer.cpp @@ -11,7 +11,8 @@ BonjourServer::BonjourServer() { bsrRegister = nullptr; #ifdef Q_OS_WIN static bool bDelayLoadFailed = false; - if (bDelayLoadFailed) return; + if (bDelayLoadFailed) + return; HMODULE hLib = LoadLibrary(L"DNSSD.DLL"); if (!hLib) { diff --git a/src/murmur/BonjourServer.h b/src/murmur/BonjourServer.h index bc3611a29..3258aaefb 100644 --- a/src/murmur/BonjourServer.h +++ b/src/murmur/BonjourServer.h @@ -11,14 +11,14 @@ class BonjourServiceRegister; class BonjourServer : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(BonjourServer) - public: - BonjourServer(); - ~BonjourServer(); +private: + Q_OBJECT + Q_DISABLE_COPY(BonjourServer) +public: + BonjourServer(); + ~BonjourServer(); - BonjourServiceRegister *bsrRegister; + BonjourServiceRegister *bsrRegister; }; #endif diff --git a/src/murmur/Cert.cpp b/src/murmur/Cert.cpp index 52adf638c..c9f140564 100644 --- a/src/murmur/Cert.cpp +++ b/src/murmur/Cert.cpp @@ -6,31 +6,31 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "Meta.h" -#include "Server.h" #include "SelfSignedCertificate.h" +#include "Server.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #endif bool Server::isKeyForCert(const QSslKey &key, const QSslCertificate &cert) { if (key.isNull() || cert.isNull() || (key.type() != QSsl::PrivateKey)) return false; - QByteArray qbaKey = key.toDer(); + QByteArray qbaKey = key.toDer(); QByteArray qbaCert = cert.toDer(); - X509 *x509 = nullptr; + X509 *x509 = nullptr; EVP_PKEY *pkey = nullptr; - BIO *mem = nullptr; + BIO *mem = nullptr; mem = BIO_new_mem_buf(qbaKey.data(), qbaKey.size()); Q_UNUSED(BIO_set_close(mem, BIO_NOCLOSE)); @@ -80,30 +80,30 @@ void Server::initializeCert() { qsdhpDHParams = QSslDiffieHellmanParameters(); #endif - crt = getConf("certificate", QString()).toByteArray(); - key = getConf("key", QString()).toByteArray(); - pass = getConf("passphrase", QByteArray()).toByteArray(); + crt = getConf("certificate", QString()).toByteArray(); + key = getConf("key", QString()).toByteArray(); + pass = getConf("passphrase", QByteArray()).toByteArray(); dhparams = getConf("sslDHParams", Meta::mp.qbaDHParams).toByteArray(); - QList<QSslCertificate> ql; + QList< QSslCertificate > ql; // Attempt to load the private key. - if (! key.isEmpty()) { + if (!key.isEmpty()) { qskKey = Server::privateKeyFromPEM(key, pass); } // If we still can't load the key, try loading any keys from the certificate - if (qskKey.isNull() && ! crt.isEmpty()) { + if (qskKey.isNull() && !crt.isEmpty()) { qskKey = Server::privateKeyFromPEM(crt); } // If have a key, walk the list of certs, find the one for our key, // remove any certs for our key from the list, what's left is part of // the CA certificate chain. - if (! qskKey.isNull()) { + if (!qskKey.isNull()) { ql << QSslCertificate::fromData(crt); ql << QSslCertificate::fromData(key); - for (int i=0;i<ql.size();++i) { + for (int i = 0; i < ql.size(); ++i) { const QSslCertificate &c = ql.at(i); if (isKeyForCert(qskKey, c)) { qscCert = c; @@ -114,24 +114,26 @@ void Server::initializeCert() { } #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) - if (! dhparams.isEmpty()) { + if (!dhparams.isEmpty()) { QSslDiffieHellmanParameters qdhp = QSslDiffieHellmanParameters::fromEncoded(dhparams); if (qdhp.isValid()) { qsdhpDHParams = qdhp; } else { - log(QString::fromLatin1("Unable to use specified Diffie-Hellman parameters (sslDHParams): %1").arg(qdhp.errorString())); + log(QString::fromLatin1("Unable to use specified Diffie-Hellman parameters (sslDHParams): %1") + .arg(qdhp.errorString())); } } #else - if (! dhparams.isEmpty()) { - log("Diffie-Hellman parameters (sslDHParams) were specified, but will not be used. This version of Murmur does not support Diffie-Hellman parameters."); + if (!dhparams.isEmpty()) { + log("Diffie-Hellman parameters (sslDHParams) were specified, but will not be used. This version of Murmur does " + "not support Diffie-Hellman parameters."); } #endif QString issuer; QStringList issuerNames = qscCert.issuerInfo(QSslCertificate::CommonName); - if (! issuerNames.isEmpty()) { + if (!issuerNames.isEmpty()) { issuer = issuerNames.first(); } @@ -140,16 +142,17 @@ void Server::initializeCert() { if (issuer == QString::fromUtf8("Murmur Autogenerated Certificate")) { log("Old autogenerated certificate is unusable for registration, invalidating it"); qscCert = QSslCertificate(); - qskKey = QSslKey(); + qskKey = QSslKey(); } // If we have a cert, and it's a self-signed one, but we're binding to // all the same addresses as the Meta server is, use it's cert instead. // This allows a self-signed certificate generated by Murmur to be // replaced by a CA-signed certificate in the .ini file. - if (!qscCert.isNull() && issuer.startsWith(QString::fromUtf8("Murmur Autogenerated Certificate")) && ! Meta::mp.qscCert.isNull() && ! Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) { - qscCert = Meta::mp.qscCert; - qskKey = Meta::mp.qskKey; + if (!qscCert.isNull() && issuer.startsWith(QString::fromUtf8("Murmur Autogenerated Certificate")) + && !Meta::mp.qscCert.isNull() && !Meta::mp.qskKey.isNull() && (Meta::mp.qlBind == qlBind)) { + qscCert = Meta::mp.qscCert; + qskKey = Meta::mp.qskKey; qlIntermediates = Meta::mp.qlIntermediates; if (!qscCert.isNull() && !qskKey.isNull()) { @@ -159,12 +162,12 @@ void Server::initializeCert() { // If we still don't have a certificate by now, try to load the one from Meta if (qscCert.isNull() || qskKey.isNull()) { - if (! key.isEmpty() || ! crt.isEmpty()) { + if (!key.isEmpty() || !crt.isEmpty()) { log("Certificate specified, but failed to load."); } - qskKey = Meta::mp.qskKey; - qscCert = Meta::mp.qscCert; + qskKey = Meta::mp.qskKey; + qscCert = Meta::mp.qscCert; qlIntermediates = Meta::mp.qlIntermediates; if (!qscCert.isNull() && !qskKey.isNull()) { diff --git a/src/murmur/DBus.cpp b/src/murmur/DBus.cpp index db00c3d50..e08cf537f 100644 --- a/src/murmur/DBus.cpp +++ b/src/murmur/DBus.cpp @@ -6,7 +6,7 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "DBus.h" @@ -14,8 +14,8 @@ #include "Connection.h" #include "Message.h" #include "Server.h" -#include "ServerUser.h" #include "ServerDB.h" +#include "ServerUser.h" #include <QtCore/QCoreApplication> #include <QtCore/QStack> @@ -26,9 +26,9 @@ #include <QtDBus/QDBusReply> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #else -# include <arpa/inet.h> +# include <arpa/inet.h> #endif QDBusArgument &operator<<(QDBusArgument &a, const PlayerInfo &s) { @@ -38,7 +38,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const PlayerInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, PlayerInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, PlayerInfo &s) { a.beginStructure(); a >> s.session >> s.mute >> s.deaf >> s.suppressed >> s.selfMute >> s.selfDeaf >> s.channel; a.endStructure(); @@ -47,14 +47,16 @@ const QDBusArgument & operator >>(const QDBusArgument &a, PlayerInfo &s) { QDBusArgument &operator<<(QDBusArgument &a, const PlayerInfoExtended &s) { a.beginStructure(); - a << s.session << s.mute << s.deaf << s.suppressed << s.selfMute << s.selfDeaf << s.channel << s.id << s.name << s.onlinesecs << s.bytespersec; + a << s.session << s.mute << s.deaf << s.suppressed << s.selfMute << s.selfDeaf << s.channel << s.id << s.name + << s.onlinesecs << s.bytespersec; a.endStructure(); return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, PlayerInfoExtended &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, PlayerInfoExtended &s) { a.beginStructure(); - a >> s.session >> s.mute >> s.deaf >> s.suppressed >> s.selfMute >> s.selfDeaf >> s.channel >> s.id >> s.name >> s.onlinesecs >> s.bytespersec; + a >> s.session >> s.mute >> s.deaf >> s.suppressed >> s.selfMute >> s.selfDeaf >> s.channel >> s.id >> s.name + >> s.onlinesecs >> s.bytespersec; a.endStructure(); return a; } @@ -66,7 +68,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const ChannelInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, ChannelInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, ChannelInfo &s) { a.beginStructure(); a >> s.id >> s.name >> s.parent >> s.links; a.endStructure(); @@ -81,7 +83,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const GroupInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, GroupInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, GroupInfo &s) { a.beginStructure(); a >> s.name >> s.inherited >> s.inherit >> s.inheritable; a >> s.add >> s.remove >> s.members; @@ -98,7 +100,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const ACLInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, ACLInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, ACLInfo &s) { a.beginStructure(); a >> s.applyHere >> s.applySubs >> s.inherited; a >> s.playerid >> s.group; @@ -114,7 +116,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const BanInfo &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, BanInfo &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, BanInfo &s) { a.beginStructure(); a >> s.address >> s.bits; a.endStructure(); @@ -128,7 +130,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const RegisteredPlayer &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, RegisteredPlayer &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, RegisteredPlayer &s) { a.beginStructure(); a >> s.id >> s.name >> s.email >> s.pw; a.endStructure(); @@ -143,7 +145,7 @@ QDBusArgument &operator<<(QDBusArgument &a, const LogEntry &s) { return a; } -const QDBusArgument & operator >>(const QDBusArgument &a, LogEntry &s) { +const QDBusArgument &operator>>(const QDBusArgument &a, LogEntry &s) { a.beginStructure(); a >> s.timestamp >> s.txt; a.endStructure(); @@ -151,22 +153,22 @@ const QDBusArgument & operator >>(const QDBusArgument &a, LogEntry &s) { } void MurmurDBus::registerTypes() { - qDBusRegisterMetaType<PlayerInfo>(); - qDBusRegisterMetaType<PlayerInfoExtended>(); - qDBusRegisterMetaType<QList<PlayerInfoExtended> >(); - qDBusRegisterMetaType<ChannelInfo>(); - qDBusRegisterMetaType<QList<ChannelInfo> >(); - qDBusRegisterMetaType<GroupInfo>(); - qDBusRegisterMetaType<QList<GroupInfo> >(); - qDBusRegisterMetaType<ACLInfo>(); - qDBusRegisterMetaType<QList<ACLInfo> >(); - qDBusRegisterMetaType<BanInfo>(); - qDBusRegisterMetaType<QList<BanInfo> >(); - qDBusRegisterMetaType<RegisteredPlayer>(); - qDBusRegisterMetaType<QList<RegisteredPlayer> >(); - qDBusRegisterMetaType<ConfigMap>(); - qDBusRegisterMetaType<LogEntry>(); - qDBusRegisterMetaType<QList<LogEntry> >(); + qDBusRegisterMetaType< PlayerInfo >(); + qDBusRegisterMetaType< PlayerInfoExtended >(); + qDBusRegisterMetaType< QList< PlayerInfoExtended > >(); + qDBusRegisterMetaType< ChannelInfo >(); + qDBusRegisterMetaType< QList< ChannelInfo > >(); + qDBusRegisterMetaType< GroupInfo >(); + qDBusRegisterMetaType< QList< GroupInfo > >(); + qDBusRegisterMetaType< ACLInfo >(); + qDBusRegisterMetaType< QList< ACLInfo > >(); + qDBusRegisterMetaType< BanInfo >(); + qDBusRegisterMetaType< QList< BanInfo > >(); + qDBusRegisterMetaType< RegisteredPlayer >(); + qDBusRegisterMetaType< QList< RegisteredPlayer > >(); + qDBusRegisterMetaType< ConfigMap >(); + qDBusRegisterMetaType< LogEntry >(); + qDBusRegisterMetaType< QList< LogEntry > >(); } QDBusConnection *MurmurDBus::qdbc = nullptr; @@ -178,33 +180,35 @@ MurmurDBus::MurmurDBus(Server *srv) : QDBusAbstractAdaptor(srv) { void MurmurDBus::removeAuthenticator() { server->disconnectAuthenticator(this); - qsAuthPath = QString(); + qsAuthPath = QString(); qsAuthService = QString(); } void MurmurDBus::idToNameSlot(QString &name, int id) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<QString> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserName",id); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< QString > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserName", id); if (reply.isValid()) name = reply.value(); else { - server->log(QString("DBus Authenticator failed getUserName for %1: %2").arg(QString::number(id), QString(reply.error().message()))); + server->log(QString("DBus Authenticator failed getUserName for %1: %2") + .arg(QString::number(id), QString(reply.error().message()))); removeAuthenticator(); } } void MurmurDBus::idToTextureSlot(QByteArray &qba, int id) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<QByteArray> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserTexture",id); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< QByteArray > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserTexture", id); if (reply.isValid()) { qba = reply.value(); } } void MurmurDBus::nameToIdSlot(int &id, const QString &name) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserId",name); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getUserId", name); if (reply.isValid()) id = reply.value(); else { @@ -213,9 +217,10 @@ void MurmurDBus::nameToIdSlot(int &id, const QString &name) { } } -void MurmurDBus::registerUserSlot(int &res, const QMap<int, QString> &info) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "registerPlayer", info.value(ServerDB::User_Name)); +void MurmurDBus::registerUserSlot(int &res, const QMap< int, QString > &info) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "registerPlayer", + info.value(ServerDB::User_Name)); if (reply.isValid()) { res = reply.value(); if ((info.count() > 1) && (res > 0)) @@ -224,68 +229,73 @@ void MurmurDBus::registerUserSlot(int &res, const QMap<int, QString> &info) { } void MurmurDBus::unregisterUserSlot(int &res, int id) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "unregisterPlayer", id); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "unregisterPlayer", id); if (reply.isValid()) res = reply.value(); } -void MurmurDBus::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<RegisteredPlayer> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegistration", id); +void MurmurDBus::getRegistrationSlot(int &res, int id, QMap< int, QString > &info) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< RegisteredPlayer > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegistration", id); if (reply.isValid()) { const RegisteredPlayer &r = reply.value(); info.insert(ServerDB::User_Name, r.name); - if (! r.email.isEmpty()) + if (!r.email.isEmpty()) info.insert(ServerDB::User_Email, r.email); res = 1; } } -void MurmurDBus::getRegisteredUsersSlot(const QString &filter, QMap<int, QString > &m) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<QList<RegisteredPlayer> > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegisteredPlayers", filter); +void MurmurDBus::getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &m) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< QList< RegisteredPlayer > > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "getRegisteredPlayers", filter); if (reply.isValid()) { - const QList<RegisteredPlayer> &r = reply.value(); - foreach(const RegisteredPlayer &p, r) { - m.insert(p.id, p.name); - } + const QList< RegisteredPlayer > &r = reply.value(); + foreach (const RegisteredPlayer &p, r) { m.insert(p.id, p.name); } } } -void MurmurDBus::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { +void MurmurDBus::setInfoSlot(int &res, int id, const QMap< int, QString > &info) { if (info.contains(ServerDB::User_Name)) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setName",id, info.value(ServerDB::User_Name)); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setName", id, + info.value(ServerDB::User_Name)); if (reply.isValid()) res = reply.value(); } if (info.contains(ServerDB::User_Password)) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setPW",id, info.value(ServerDB::User_Password)); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setPW", id, + info.value(ServerDB::User_Password)); if (reply.isValid()) res = reply.value(); } if (info.contains(ServerDB::User_Email)) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setEmail",id, info.value(ServerDB::User_Email)); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setEmail", id, + info.value(ServerDB::User_Email)); if (reply.isValid()) res = reply.value(); } } void MurmurDBus::setTextureSlot(int &res, int id, const QByteArray &texture) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusReply<int> reply = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setTexture",id, texture); + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusReply< int > reply = + remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "setTexture", id, texture); if (reply.isValid()) res = reply.value(); } -void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &, const QString &, bool, const QString &pw) { - QDBusInterface remoteApp(qsAuthService,qsAuthPath,QString(),*qdbc); - QDBusMessage msg = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "authenticate",uname,pw); - QDBusError err = msg; - if (! err.isValid()) { +void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &, + const QString &, bool, const QString &pw) { + QDBusInterface remoteApp(qsAuthService, qsAuthPath, QString(), *qdbc); + QDBusMessage msg = remoteApp.call(bReentrant ? QDBus::BlockWithGui : QDBus::Block, "authenticate", uname, pw); + QDBusError err = msg; + if (!err.isValid()) { QString newname; int uid = -2; bool ok = true; @@ -294,7 +304,7 @@ void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const } if (ok && (msg.arguments().count() >= 2)) { newname = msg.arguments().at(1).toString(); - if (! newname.isEmpty()) { + if (!newname.isEmpty()) { uname = newname; } } @@ -313,40 +323,40 @@ void MurmurDBus::authenticateSlot(int &res, QString &uname, int sessionId, const } } -#define PLAYER_SETUP_VAR(var) \ - ServerUser *pUser = server->qhUsers.value(var); \ - if (! pUser) { \ - qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.session", "Invalid session id")); \ - return; \ - } +#define PLAYER_SETUP_VAR(var) \ + ServerUser *pUser = server->qhUsers.value(var); \ + if (!pUser) { \ + qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.session", "Invalid session id")); \ + return; \ + } #define PLAYER_SETUP PLAYER_SETUP_VAR(session) -#define CHANNEL_SETUP_VAR2(dst,var) \ - Channel *dst = server->qhChannels.value(var); \ - if (! dst) { \ - qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.channel", "Invalid channel id")); \ - return; \ - } +#define CHANNEL_SETUP_VAR2(dst, var) \ + Channel *dst = server->qhChannels.value(var); \ + if (!dst) { \ + qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.channel", "Invalid channel id")); \ + return; \ + } -#define CHANNEL_SETUP_VAR(var) CHANNEL_SETUP_VAR2(cChannel,var) +#define CHANNEL_SETUP_VAR(var) CHANNEL_SETUP_VAR2(cChannel, var) -void MurmurDBus::getPlayers(QList<PlayerInfoExtended> &a) { +void MurmurDBus::getPlayers(QList< PlayerInfoExtended > &a) { a.clear(); - foreach(ServerUser *p, server->qhUsers) { - if (static_cast<ServerUser *>(p)->sState == ServerUser::Authenticated) + foreach (ServerUser *p, server->qhUsers) { + if (static_cast< ServerUser * >(p)->sState == ServerUser::Authenticated) a << PlayerInfoExtended(p); } } -void MurmurDBus::getChannels(QList<ChannelInfo> &a) { +void MurmurDBus::getChannels(QList< ChannelInfo > &a) { a.clear(); - QQueue<Channel *> q; + QQueue< Channel * > q; q << server->qhChannels.value(0); - while (! q.isEmpty()) { + while (!q.isEmpty()) { Channel *c = q.dequeue(); a << ChannelInfo(c); - foreach(c, c->qlChannels) + foreach (c, c->qlChannels) q.enqueue(c); } } @@ -429,22 +439,23 @@ void MurmurDBus::setChannelState(const ChannelInfo &nci, const QDBusMessage &msg CHANNEL_SETUP_VAR(nci.id); CHANNEL_SETUP_VAR2(cParent, nci.parent); - QSet<Channel *> newset; - foreach(int id, nci.links) { + QSet< Channel * > newset; + foreach (int id, nci.links) { CHANNEL_SETUP_VAR2(cLink, id); newset << cLink; } - if (! server->setChannelState(cChannel, cParent, nci.name, newset)) { + if (!server->setChannelState(cChannel, cParent, nci.name, newset)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.channel", "Moving channel to subchannel")); return; } } -void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, QList<GroupInfo> &groups, bool &inherit) { +void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList< ACLInfo > &acls, QList< GroupInfo > &groups, + bool &inherit) { CHANNEL_SETUP_VAR(id); - QStack<Channel *> chans; + QStack< Channel * > chans; Channel *p; ChanACL *acl; @@ -454,15 +465,15 @@ void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, Q if ((p == cChannel) || (p->bInheritACL)) p = p->cParent; else - p =nullptr; + p = nullptr; } inherit = cChannel->bInheritACL; - while (! chans.isEmpty()) { + while (!chans.isEmpty()) { p = chans.pop(); - foreach(acl, p->qlACL) { - if ((p==cChannel) || (acl->bApplySubs)) { + foreach (acl, p->qlACL) { + if ((p == cChannel) || (acl->bApplySubs)) { ACLInfo ai(acl); if (p != cChannel) ai.inherited = true; @@ -471,24 +482,24 @@ void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, Q } } - p = cChannel->cParent; - QSet<QString> allnames = Group::groupNames(cChannel); + p = cChannel->cParent; + QSet< QString > allnames = Group::groupNames(cChannel); QString name; - foreach(name, allnames) { - Group *g = cChannel->qhGroups.value(name); + foreach (name, allnames) { + Group *g = cChannel->qhGroups.value(name); Group *pg = p ? Group::getGroup(p, name) : nullptr; - if (!g && ! pg) + if (!g && !pg) continue; GroupInfo gi(g ? g : pg); - QSet<int> members; + QSet< int > members; if (pg) members = pg->members(); if (g) { - gi.add = g->qsAdd.values(); - gi.remove = g->qsRemove.values(); + gi.add = g->qsAdd.values(); + gi.remove = g->qsRemove.values(); gi.inherited = false; - members+=g->qsAdd; - members-=g->qsRemove; + members += g->qsAdd; + members -= g->qsRemove; } else { gi.inherited = true; } @@ -497,7 +508,8 @@ void MurmurDBus::getACL(int id, const QDBusMessage &msg, QList<ACLInfo> &acls, Q } } -void MurmurDBus::setACL(int id, const QList<ACLInfo> &acls, const QList<GroupInfo> &groups, bool inherit, const QDBusMessage &msg) { +void MurmurDBus::setACL(int id, const QList< ACLInfo > &acls, const QList< GroupInfo > &groups, bool inherit, + const QDBusMessage &msg) { CHANNEL_SETUP_VAR(id); Group *g; @@ -505,75 +517,71 @@ void MurmurDBus::setACL(int id, const QList<ACLInfo> &acls, const QList<GroupInf ACLInfo ai; GroupInfo gi; - QHash<QString, QSet<int> > hOldTemp; + QHash< QString, QSet< int > > hOldTemp; - foreach(g, cChannel->qhGroups) { + foreach (g, cChannel->qhGroups) { hOldTemp.insert(g->qsName, g->qsTemporary); delete g; } - foreach(a, cChannel->qlACL) + foreach (a, cChannel->qlACL) delete a; cChannel->qhGroups.clear(); cChannel->qlACL.clear(); cChannel->bInheritACL = inherit; - foreach(gi, groups) { - g = new Group(cChannel, gi.name); - g->bInherit=gi.inherit; - g->bInheritable=gi.inheritable; + foreach (gi, groups) { + g = new Group(cChannel, gi.name); + g->bInherit = gi.inherit; + g->bInheritable = gi.inheritable; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - g->qsAdd = QSet<int>(gi.add.begin(), gi.add.end()); - g->qsRemove = QSet<int>(gi.remove.begin(), gi.remove.end()); + g->qsAdd = QSet< int >(gi.add.begin(), gi.add.end()); + g->qsRemove = QSet< int >(gi.remove.begin(), gi.remove.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now - g->qsAdd = gi.add.toSet(); + g->qsAdd = gi.add.toSet(); g->qsRemove = gi.remove.toSet(); #endif g->qsTemporary = hOldTemp.value(gi.name); } - foreach(ai, acls) { - a = new ChanACL(cChannel); + foreach (ai, acls) { + a = new ChanACL(cChannel); a->bApplyHere = ai.applyHere; a->bApplySubs = ai.applySubs; - a->iUserId = ai.playerid; - a->qsGroup = ai.group; - a->pDeny = static_cast<ChanACL::Permissions>(ai.deny) & ChanACL::All; - a->pAllow = static_cast<ChanACL::Permissions>(ai.allow) & ChanACL::All; + a->iUserId = ai.playerid; + a->qsGroup = ai.group; + a->pDeny = static_cast< ChanACL::Permissions >(ai.deny) & ChanACL::All; + a->pAllow = static_cast< ChanACL::Permissions >(ai.allow) & ChanACL::All; } server->clearACLCache(); server->updateChannel(cChannel); } -void MurmurDBus::getBans(QList<BanInfo> &bi) { +void MurmurDBus::getBans(QList< BanInfo > &bi) { bi.clear(); - foreach(const Ban &b, server->qlBans) { - if (! b.haAddress.isV6()) + foreach (const Ban &b, server->qlBans) { + if (!b.haAddress.isV6()) bi << BanInfo(b); } } -void MurmurDBus::setBans(const QList<BanInfo> &, const QDBusMessage &) { +void MurmurDBus::setBans(const QList< BanInfo > &, const QDBusMessage &) { } -void MurmurDBus::getPlayerNames(const QList<int> &ids, const QDBusMessage &, QStringList &names) { +void MurmurDBus::getPlayerNames(const QList< int > &ids, const QDBusMessage &, QStringList &names) { names.clear(); - foreach(int id, ids) { - names << server->getUserName(id); - } + foreach (int id, ids) { names << server->getUserName(id); } } -void MurmurDBus::getPlayerIds(const QStringList &names, const QDBusMessage &, QList<int> &ids) { +void MurmurDBus::getPlayerIds(const QStringList &names, const QDBusMessage &, QList< int > &ids) { ids.clear(); - foreach(QString name, names) { - ids << server->getUserID(name); - } + foreach (QString name, names) { ids << server->getUserID(name); } } void MurmurDBus::registerPlayer(const QString &name, const QDBusMessage &msg, int &id) { - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Name, name); id = server->registerUser(info); if (id < 0) { @@ -583,43 +591,44 @@ void MurmurDBus::registerPlayer(const QString &name, const QDBusMessage &msg, in } void MurmurDBus::unregisterPlayer(int id, const QDBusMessage &msg) { - if (! server->unregisterUser(id)) { + if (!server->unregisterUser(id)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } } void MurmurDBus::getRegistration(int id, const QDBusMessage &msg, RegisteredPlayer &user) { - QMap<int, QString> info = server->getRegistration(id); + QMap< int, QString > info = server->getRegistration(id); if (info.isEmpty()) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } - user.id = id; - user.name = info.value(ServerDB::User_Name); + user.id = id; + user.name = info.value(ServerDB::User_Name); user.email = info.value(ServerDB::User_Email); } -void MurmurDBus::setRegistration(int id, const QString &name, const QString &email, const QString &pw, const QDBusMessage &msg) { +void MurmurDBus::setRegistration(int id, const QString &name, const QString &email, const QString &pw, + const QDBusMessage &msg) { RegisteredPlayer user; - user.id = id; - user.name = name; + user.id = id; + user.name = name; user.email = email; - user.pw = pw; + user.pw = pw; updateRegistration(user, msg); } void MurmurDBus::updateRegistration(const RegisteredPlayer &user, const QDBusMessage &msg) { - QMap<int, QString> info; + QMap< int, QString > info; - if (! user.name.isEmpty()) + if (!user.name.isEmpty()) info.insert(ServerDB::User_Name, user.name); - if (! user.email.isEmpty()) + if (!user.email.isEmpty()) info.insert(ServerDB::User_Email, user.email); - if (! user.pw.isEmpty()) + if (!user.pw.isEmpty()) info.insert(ServerDB::User_Password, user.pw); if (info.isEmpty() || !server->setInfo(user.id, info)) { @@ -629,7 +638,7 @@ void MurmurDBus::updateRegistration(const RegisteredPlayer &user, const QDBusMes } void MurmurDBus::getTexture(int id, const QDBusMessage &msg, QByteArray &texture) { - if (! server->isUserId(id)) { + if (!server->isUserId(id)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } @@ -637,30 +646,30 @@ void MurmurDBus::getTexture(int id, const QDBusMessage &msg, QByteArray &texture } void MurmurDBus::setTexture(int id, const QByteArray &texture, const QDBusMessage &msg) { - if (! server->isUserId(id)) { + if (!server->isUserId(id)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.playerid", "Invalid player id")); return; } - if (! server->setTexture(id, texture)) { + if (!server->setTexture(id, texture)) { qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.texture", "Invalid texture")); return; } } -void MurmurDBus::getRegisteredPlayers(const QString &filter, QList<RegisteredPlayer> &users) { +void MurmurDBus::getRegisteredPlayers(const QString &filter, QList< RegisteredPlayer > &users) { users.clear(); - QMap<int, QString > l = server->getRegisteredUsers(filter); - QMap<int, QString >::const_iterator i; + QMap< int, QString > l = server->getRegisteredUsers(filter); + QMap< int, QString >::const_iterator i; for (i = l.constBegin(); i != l.constEnd(); ++i) { RegisteredPlayer r; - r.id = i.key(); + r.id = i.key(); r.name = i.value(); users << r; } } void MurmurDBus::verifyPassword(int id, const QString &pw, const QDBusMessage &msg, bool &ok) { - QList<int> ids; + QList< int > ids; ids << id; QStringList names; getPlayerNames(ids, msg, names); @@ -671,7 +680,7 @@ void MurmurDBus::verifyPassword(int id, const QString &pw, const QDBusMessage &m } QString name = names.at(0); - int nid = server->authenticate(name, pw); + int nid = server->authenticate(name, pw); if (nid == id) ok = true; else @@ -679,21 +688,21 @@ void MurmurDBus::verifyPassword(int id, const QString &pw, const QDBusMessage &m } #ifdef Q_OS_WIN -#undef interface +# undef interface #endif void MurmurDBus::setAuthenticator(const QDBusObjectPath &path, bool reentrant, const QDBusMessage &msg) { - if (! qsAuthPath.isNull() || ! qsAuthService.isNull()) + if (!qsAuthPath.isNull() || !qsAuthService.isNull()) removeAuthenticator(); server->connectAuthenticator(this); - qsAuthPath = path.path(); + qsAuthPath = path.path(); qsAuthService = msg.service(); QDBusConnectionInterface *interface = qdbc->interface(); - QDBusReply<QStringList> names = interface->registeredServiceNames(); + QDBusReply< QStringList > names = interface->registeredServiceNames(); if (names.isValid()) { - foreach(const QString &name, names.value()) { - QDBusReply<QString> owner = interface->serviceOwner(name); + foreach (const QString &name, names.value()) { + QDBusReply< QString > owner = interface->serviceOwner(name); if (owner.isValid() && (owner.value() != name) && (owner.value() == qsAuthService)) { qsAuthService = name; break; @@ -702,7 +711,8 @@ void MurmurDBus::setAuthenticator(const QDBusObjectPath &path, bool reentrant, c } bReentrant = reentrant; - server->log(QString("DBus Authenticator set to %1 %2 (%3)").arg(qsAuthService, qsAuthPath, QString::number(reentrant))); + server->log( + QString("DBus Authenticator set to %1 %2 (%3)").arg(qsAuthService, qsAuthPath, QString::number(reentrant))); } void MurmurDBus::setTemporaryGroups(int channel, int userid, const QStringList &groups, const QDBusMessage &msg) { @@ -712,29 +722,29 @@ void MurmurDBus::setTemporaryGroups(int channel, int userid, const QStringList & } PlayerInfo::PlayerInfo(const User *p) { - session = p->uiSession; - mute = p->bMute; - deaf = p->bDeaf; + session = p->uiSession; + mute = p->bMute; + deaf = p->bDeaf; suppressed = p->bSuppress; - selfMute = p->bSelfMute; - selfDeaf = p->bSelfDeaf; - channel = p->cChannel->iId; + selfMute = p->bSelfMute; + selfDeaf = p->bSelfDeaf; + channel = p->cChannel->iId; } PlayerInfoExtended::PlayerInfoExtended(const User *p) : PlayerInfo(p) { - id = p->iId; + id = p->iId; name = p->qsName; - const ServerUser *u = static_cast<const ServerUser *>(p); - onlinesecs = u->bwr.onlineSeconds(); - bytespersec = u->bwr.bandwidth(); + const ServerUser *u = static_cast< const ServerUser * >(p); + onlinesecs = u->bwr.onlineSeconds(); + bytespersec = u->bwr.bandwidth(); } ChannelInfo::ChannelInfo(const Channel *c) { - id = c->iId; - name = c->qsName; + id = c->iId; + name = c->qsName; parent = c->cParent ? c->cParent->iId : -1; - foreach(Channel *chn, c->qsPermLinks) + foreach (Channel *chn, c->qsPermLinks) links << chn->iId; } @@ -742,22 +752,22 @@ ACLInfo::ACLInfo(const ChanACL *acl) { applyHere = acl->bApplyHere; applySubs = acl->bApplySubs; inherited = false; - playerid = acl->iUserId; - group = acl->qsGroup; - allow = acl->pAllow; - deny = acl->pDeny; + playerid = acl->iUserId; + group = acl->qsGroup; + allow = acl->pAllow; + deny = acl->pDeny; } GroupInfo::GroupInfo(const Group *g) : inherited(false) { - name = g->qsName; - inherit = g->bInherit; + name = g->qsName; + inherit = g->bInherit; inheritable = g->bInheritable; members.clear(); } BanInfo::BanInfo(const Ban &b) { address = ntohl(b.haAddress.hash[3]); - bits = b.iMask; + bits = b.iMask; } RegisteredPlayer::RegisteredPlayer() { @@ -770,7 +780,7 @@ LogEntry::LogEntry() { LogEntry::LogEntry(const ServerDB::LogRecord &r) { timestamp = r.first; - txt = r.second; + txt = r.second; } void MurmurDBus::userStateChanged(const User *p) { @@ -822,15 +832,15 @@ void MetaDBus::stopped(Server *s) { void MetaDBus::start(int server_id, const QDBusMessage &msg) { if (meta->qhServers.contains(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.booted", "Server already booted")); - } else if (! ServerDB::serverExists(server_id)) { + } else if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); - } else if (! meta->boot(server_id)) { + } else if (!meta->boot(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.bootfail", "Booting server failed")); } } void MetaDBus::stop(int server_id, const QDBusMessage &msg) { - if (! meta->qhServers.contains(server_id)) { + if (!meta->qhServers.contains(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.booted", "Server not booted")); } else { meta->kill(server_id); @@ -844,18 +854,18 @@ void MetaDBus::newServer(int &server_id) { void MetaDBus::deleteServer(int server_id, const QDBusMessage &msg) { if (meta->qhServers.contains(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.booted", "Server is running")); - } else if (! ServerDB::serverExists(server_id)) { + } else if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { ServerDB::deleteServer(server_id); } } -void MetaDBus::getBootedServers(QList<int> &server_list) { +void MetaDBus::getBootedServers(QList< int > &server_list) { server_list = meta->qhServers.keys(); } -void MetaDBus::getAllServers(QList<int> &server_list) { +void MetaDBus::getAllServers(QList< int > &server_list) { server_list = ServerDB::getAllServers(); } @@ -864,18 +874,19 @@ void MetaDBus::isBooted(int server_id, bool &booted) { } void MetaDBus::getConf(int server_id, const QString &key, const QDBusMessage &msg, QString &value) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { if (key == "key" || key == "passphrase") - MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.writeonly", "Requested read of write-only field.")); + MurmurDBus::qdbc->send( + msg.createErrorReply("net.sourceforge.mumble.Error.writeonly", "Requested read of write-only field.")); else value = ServerDB::getConf(server_id, key).toString(); } } void MetaDBus::setConf(int server_id, const QString &key, const QString &value, const QDBusMessage &msg) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { ServerDB::setConf(server_id, key, value); @@ -886,7 +897,7 @@ void MetaDBus::setConf(int server_id, const QString &key, const QString &value, } void MetaDBus::getAllConf(int server_id, const QDBusMessage &msg, ConfigMap &values) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { values = ServerDB::getAllConf(server_id); @@ -896,15 +907,14 @@ void MetaDBus::getAllConf(int server_id, const QDBusMessage &msg, ConfigMap &val } } -void MetaDBus::getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &msg, QList<LogEntry> &entries) { - if (! ServerDB::serverExists(server_id)) { +void MetaDBus::getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &msg, + QList< LogEntry > &entries) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { entries.clear(); - QList<ServerDB::LogRecord> dblog = ServerDB::getLog(server_id, min_offset, max_offset); - foreach(const ServerDB::LogRecord &e, dblog) { - entries << LogEntry(e); - } + QList< ServerDB::LogRecord > dblog = ServerDB::getLog(server_id, min_offset, max_offset); + foreach (const ServerDB::LogRecord &e, dblog) { entries << LogEntry(e); } } } @@ -916,7 +926,7 @@ void MetaDBus::getDefaultConf(ConfigMap &values) { } void MetaDBus::setSuperUserPassword(int server_id, const QString &pw, const QDBusMessage &msg) { - if (! ServerDB::serverExists(server_id)) { + if (!ServerDB::serverExists(server_id)) { MurmurDBus::qdbc->send(msg.createErrorReply("net.sourceforge.mumble.Error.server", "Invalid server id")); } else { ServerDB::setSUPW(server_id, pw); diff --git a/src/murmur/DBus.h b/src/murmur/DBus.h index 9937d201e..64d9fe7d6 100644 --- a/src/murmur/DBus.h +++ b/src/murmur/DBus.h @@ -4,19 +4,19 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_DBUS -#ifndef MUMBLE_MURMUR_DBUS_H_ -#define MUMBLE_MURMUR_DBUS_H_ +# ifndef MUMBLE_MURMUR_DBUS_H_ +# define MUMBLE_MURMUR_DBUS_H_ -#include <QtDBus/QDBusAbstractAdaptor> -#include <QtDBus/QDBusConnection> +# include <QtDBus/QDBusAbstractAdaptor> +# include <QtDBus/QDBusConnection> -#include "ACL.h" -#include "Channel.h" -#include "Group.h" -#include "Meta.h" -#include "Server.h" -#include "ServerDB.h" -#include "User.h" +# include "ACL.h" +# include "Channel.h" +# include "Group.h" +# include "Meta.h" +# include "Server.h" +# include "ServerDB.h" +# include "User.h" struct Ban; class QDBusObjectPath; @@ -27,7 +27,8 @@ struct PlayerInfo { bool mute, deaf, suppressed; bool selfMute, selfDeaf; int channel; - PlayerInfo() : session(0), mute(false), deaf(false), suppressed(false), selfMute(false), selfDeaf(false), channel(-1) { }; + PlayerInfo() + : session(0), mute(false), deaf(false), suppressed(false), selfMute(false), selfDeaf(false), channel(-1){}; PlayerInfo(const User *); }; Q_DECLARE_METATYPE(PlayerInfo); @@ -37,52 +38,52 @@ struct PlayerInfoExtended : public PlayerInfo { QString name; int onlinesecs; int bytespersec; - PlayerInfoExtended() : id(-1), onlinesecs(-1), bytespersec(-1) {}; + PlayerInfoExtended() : id(-1), onlinesecs(-1), bytespersec(-1){}; PlayerInfoExtended(const User *); }; Q_DECLARE_METATYPE(PlayerInfoExtended); -Q_DECLARE_METATYPE(QList<PlayerInfoExtended>); +Q_DECLARE_METATYPE(QList< PlayerInfoExtended >); struct ChannelInfo { int id; QString name; int parent; - QList<int> links; - ChannelInfo() : id(-1), parent(-1) { }; + QList< int > links; + ChannelInfo() : id(-1), parent(-1){}; ChannelInfo(const Channel *c); }; Q_DECLARE_METATYPE(ChannelInfo); -Q_DECLARE_METATYPE(QList<ChannelInfo>); +Q_DECLARE_METATYPE(QList< ChannelInfo >); struct GroupInfo { QString name; bool inherited, inherit, inheritable; - QList<int> add, remove, members; - GroupInfo() : inherited(false), inherit(false), inheritable(false) { }; + QList< int > add, remove, members; + GroupInfo() : inherited(false), inherit(false), inheritable(false){}; GroupInfo(const Group *g); }; Q_DECLARE_METATYPE(GroupInfo); -Q_DECLARE_METATYPE(QList<GroupInfo>); +Q_DECLARE_METATYPE(QList< GroupInfo >); struct ACLInfo { bool applyHere, applySubs, inherited; int playerid; QString group; unsigned int allow, deny; - ACLInfo() : applyHere(false), applySubs(false), inherited(false), playerid(-1), allow(0), deny(0) { }; + ACLInfo() : applyHere(false), applySubs(false), inherited(false), playerid(-1), allow(0), deny(0){}; ACLInfo(const ChanACL *acl); }; Q_DECLARE_METATYPE(ACLInfo); -Q_DECLARE_METATYPE(QList<ACLInfo>); +Q_DECLARE_METATYPE(QList< ACLInfo >); struct BanInfo { unsigned int address; int bits; - BanInfo() : address(0), bits(0) { }; + BanInfo() : address(0), bits(0){}; BanInfo(const Ban &); }; Q_DECLARE_METATYPE(BanInfo); -Q_DECLARE_METATYPE(QList<BanInfo>); +Q_DECLARE_METATYPE(QList< BanInfo >); struct RegisteredPlayer { int id; @@ -92,7 +93,7 @@ struct RegisteredPlayer { RegisteredPlayer(); }; Q_DECLARE_METATYPE(RegisteredPlayer); -Q_DECLARE_METATYPE(QList<RegisteredPlayer>); +Q_DECLARE_METATYPE(QList< RegisteredPlayer >); struct LogEntry { unsigned int timestamp; @@ -101,137 +102,141 @@ struct LogEntry { LogEntry(const ServerDB::LogRecord &); }; Q_DECLARE_METATYPE(LogEntry); -Q_DECLARE_METATYPE(QList<LogEntry>); +Q_DECLARE_METATYPE(QList< LogEntry >); class MurmurDBus : public QDBusAbstractAdaptor { - private: - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Murmur") - Q_DISABLE_COPY(MurmurDBus) - protected: - Server *server; - bool bReentrant; - QString qsAuthService; - QString qsAuthPath; - void removeAuthenticator(); - public: - static QDBusConnection *qdbc; - - MurmurDBus(Server *srv); - static void registerTypes(); - public slots: - // These have the result ref as the first parameter, so won't be converted to DBus - void authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certs, const QString &certhash, bool strong, const QString &pw); - void registerUserSlot(int &res, const QMap<int, QString> &); - void unregisterUserSlot(int &res, int id); - void getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res); - void getRegistrationSlot(int &, int, QMap<int, QString> &); - void setInfoSlot(int &, int, const QMap<int, QString> &); - void setTextureSlot(int &res, int id, const QByteArray &texture); - void nameToIdSlot(int &res, const QString &name); - void idToNameSlot(QString &res, int id); - void idToTextureSlot(QByteArray &res, int id); - - // These use private types, so won't be converted to DBus - void userStateChanged(const User *p); - void userTextMessage(const User *, const TextMessage &); - void userConnected(const User *p); - void userDisconnected(const User *p); - - void channelStateChanged(const Channel *c); - void channelCreated(const Channel *c); - void channelRemoved(const Channel *c); - - public slots: - // Order of paremeters is IMPORTANT, or Qt will barf. - // Needs to be: - // First all input parameters (non-ref or const-ref) - // Then const QDbusMessage ref - // Then output paremeters (ref) - // Unfortunately, this makes things look chaotic, but luckily it looks sane again when introspected. - // make SURE arguments have sane names, the argument-name will be exported in introspection xml. - - void getPlayers(QList<PlayerInfoExtended> &player_list); - void getChannels(QList<ChannelInfo> &channel_list); - - void getACL(int channel, const QDBusMessage &, QList<ACLInfo> &acls,QList<GroupInfo> &groups, bool &inherit); - void setACL(int channel, const QList<ACLInfo> &acls, const QList<GroupInfo> &groups, bool inherit, const QDBusMessage &); - - void getBans(QList<BanInfo> &bans); - void setBans(const QList<BanInfo> &bans, const QDBusMessage &); - - void kickPlayer(unsigned int session, const QString &reason, const QDBusMessage &); - void getPlayerState(unsigned int session, const QDBusMessage &, PlayerInfo &state); - void setPlayerState(const PlayerInfo &state, const QDBusMessage &); - void sendMessage(unsigned int session, const QString &text, const QDBusMessage &); - - void getChannelState(int id, const QDBusMessage &, ChannelInfo &state); - void setChannelState(const ChannelInfo &state, const QDBusMessage &); - void removeChannel(int id, const QDBusMessage &); - void addChannel(const QString &name, int parent, const QDBusMessage &, int &newid); - void sendMessageChannel(int id, bool tree, const QString &text, const QDBusMessage &); - - void getPlayerNames(const QList<int> &ids, const QDBusMessage &, QStringList &names); - void getPlayerIds(const QStringList &names, const QDBusMessage &, QList<int> &ids); - - void setAuthenticator(const QDBusObjectPath &path, bool reentrant, const QDBusMessage &); - void setTemporaryGroups(int channel, int playerid, const QStringList &groups, const QDBusMessage &); - - void registerPlayer(const QString &name, const QDBusMessage &, int &id); - void unregisterPlayer(int id, const QDBusMessage &); - void updateRegistration(const RegisteredPlayer &player, const QDBusMessage &); - void setRegistration(int id, const QString &name, const QString &email, const QString &pw, const QDBusMessage &); - void getRegistration(int id, const QDBusMessage &, RegisteredPlayer &player); - void getRegisteredPlayers(const QString &filter, QList<RegisteredPlayer> &players); - void verifyPassword(int id, const QString &pw, const QDBusMessage &, bool &ok); - void getTexture(int id, const QDBusMessage &, QByteArray &texture); - void setTexture(int id, const QByteArray &, const QDBusMessage &); - signals: - void playerStateChanged(const PlayerInfo &state); - void playerConnected(const PlayerInfo &state); - void playerDisconnected(const PlayerInfo &state); - - void channelStateChanged(const ChannelInfo &state); - void channelCreated(const ChannelInfo &state); - void channelRemoved(const ChannelInfo &state); +private: + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Murmur") + Q_DISABLE_COPY(MurmurDBus) +protected: + Server *server; + bool bReentrant; + QString qsAuthService; + QString qsAuthPath; + void removeAuthenticator(); + +public: + static QDBusConnection *qdbc; + + MurmurDBus(Server *srv); + static void registerTypes(); +public slots: + // These have the result ref as the first parameter, so won't be converted to DBus + void authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certs, + const QString &certhash, bool strong, const QString &pw); + void registerUserSlot(int &res, const QMap< int, QString > &); + void unregisterUserSlot(int &res, int id); + void getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res); + void getRegistrationSlot(int &, int, QMap< int, QString > &); + void setInfoSlot(int &, int, const QMap< int, QString > &); + void setTextureSlot(int &res, int id, const QByteArray &texture); + void nameToIdSlot(int &res, const QString &name); + void idToNameSlot(QString &res, int id); + void idToTextureSlot(QByteArray &res, int id); + + // These use private types, so won't be converted to DBus + void userStateChanged(const User *p); + void userTextMessage(const User *, const TextMessage &); + void userConnected(const User *p); + void userDisconnected(const User *p); + + void channelStateChanged(const Channel *c); + void channelCreated(const Channel *c); + void channelRemoved(const Channel *c); + +public slots: + // Order of paremeters is IMPORTANT, or Qt will barf. + // Needs to be: + // First all input parameters (non-ref or const-ref) + // Then const QDbusMessage ref + // Then output paremeters (ref) + // Unfortunately, this makes things look chaotic, but luckily it looks sane again when introspected. + // make SURE arguments have sane names, the argument-name will be exported in introspection xml. + + void getPlayers(QList< PlayerInfoExtended > &player_list); + void getChannels(QList< ChannelInfo > &channel_list); + + void getACL(int channel, const QDBusMessage &, QList< ACLInfo > &acls, QList< GroupInfo > &groups, bool &inherit); + void setACL(int channel, const QList< ACLInfo > &acls, const QList< GroupInfo > &groups, bool inherit, + const QDBusMessage &); + + void getBans(QList< BanInfo > &bans); + void setBans(const QList< BanInfo > &bans, const QDBusMessage &); + + void kickPlayer(unsigned int session, const QString &reason, const QDBusMessage &); + void getPlayerState(unsigned int session, const QDBusMessage &, PlayerInfo &state); + void setPlayerState(const PlayerInfo &state, const QDBusMessage &); + void sendMessage(unsigned int session, const QString &text, const QDBusMessage &); + + void getChannelState(int id, const QDBusMessage &, ChannelInfo &state); + void setChannelState(const ChannelInfo &state, const QDBusMessage &); + void removeChannel(int id, const QDBusMessage &); + void addChannel(const QString &name, int parent, const QDBusMessage &, int &newid); + void sendMessageChannel(int id, bool tree, const QString &text, const QDBusMessage &); + + void getPlayerNames(const QList< int > &ids, const QDBusMessage &, QStringList &names); + void getPlayerIds(const QStringList &names, const QDBusMessage &, QList< int > &ids); + + void setAuthenticator(const QDBusObjectPath &path, bool reentrant, const QDBusMessage &); + void setTemporaryGroups(int channel, int playerid, const QStringList &groups, const QDBusMessage &); + + void registerPlayer(const QString &name, const QDBusMessage &, int &id); + void unregisterPlayer(int id, const QDBusMessage &); + void updateRegistration(const RegisteredPlayer &player, const QDBusMessage &); + void setRegistration(int id, const QString &name, const QString &email, const QString &pw, const QDBusMessage &); + void getRegistration(int id, const QDBusMessage &, RegisteredPlayer &player); + void getRegisteredPlayers(const QString &filter, QList< RegisteredPlayer > &players); + void verifyPassword(int id, const QString &pw, const QDBusMessage &, bool &ok); + void getTexture(int id, const QDBusMessage &, QByteArray &texture); + void setTexture(int id, const QByteArray &, const QDBusMessage &); +signals: + void playerStateChanged(const PlayerInfo &state); + void playerConnected(const PlayerInfo &state); + void playerDisconnected(const PlayerInfo &state); + + void channelStateChanged(const ChannelInfo &state); + void channelCreated(const ChannelInfo &state); + void channelRemoved(const ChannelInfo &state); }; -typedef QMap<QString, QString> ConfigMap; +typedef QMap< QString, QString > ConfigMap; Q_DECLARE_METATYPE(ConfigMap); class MetaDBus : public QDBusAbstractAdaptor { - private: - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Meta") - Q_DISABLE_COPY(MetaDBus) - protected: - Meta *meta; - public: - MetaDBus(Meta *m); - - public slots: - void started(Server *s); - void stopped(Server *s); - public slots: - void start(int server_id, const QDBusMessage &); - void stop(int server_id, const QDBusMessage &); - void newServer(int &server_id); - void deleteServer(int server_id, const QDBusMessage &); - void getBootedServers(QList<int> &server_list); - void getAllServers(QList<int> &server_list); - void isBooted(int server_id, bool &booted); - void getConf(int server_id, const QString &key, const QDBusMessage &, QString &value); - void getAllConf(int server_id, const QDBusMessage &, ConfigMap &values); - void getDefaultConf(ConfigMap &values); - void setConf(int server_id, const QString &key, const QString &value, const QDBusMessage &); - void setSuperUserPassword(int server_id, const QString &pw, const QDBusMessage &); - void getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &, QList<LogEntry> &entries); - void getVersion(int &major, int &minor, int &patch, QString &string); - void quit(); - signals: - void started(int server_id); - void stopped(int server_id); +private: + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "net.sourceforge.mumble.Meta") + Q_DISABLE_COPY(MetaDBus) +protected: + Meta *meta; + +public: + MetaDBus(Meta *m); + +public slots: + void started(Server *s); + void stopped(Server *s); +public slots: + void start(int server_id, const QDBusMessage &); + void stop(int server_id, const QDBusMessage &); + void newServer(int &server_id); + void deleteServer(int server_id, const QDBusMessage &); + void getBootedServers(QList< int > &server_list); + void getAllServers(QList< int > &server_list); + void isBooted(int server_id, bool &booted); + void getConf(int server_id, const QString &key, const QDBusMessage &, QString &value); + void getAllConf(int server_id, const QDBusMessage &, ConfigMap &values); + void getDefaultConf(ConfigMap &values); + void setConf(int server_id, const QString &key, const QString &value, const QDBusMessage &); + void setSuperUserPassword(int server_id, const QString &pw, const QDBusMessage &); + void getLog(int server_id, int min_offset, int max_offset, const QDBusMessage &, QList< LogEntry > &entries); + void getVersion(int &major, int &minor, int &patch, QString &string); + void quit(); +signals: + void started(int server_id); + void stopped(int server_id); }; -#endif +# endif #endif diff --git a/src/murmur/Messages.cpp b/src/murmur/Messages.cpp index e82b9308b..7ee2b4ef8 100644 --- a/src/murmur/Messages.cpp +++ b/src/murmur/Messages.cpp @@ -3,141 +3,140 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -#include "User.h" -#include "Channel.h" #include "ACL.h" +#include "Channel.h" +#include "ChannelListener.h" +#include "Connection.h" #include "Group.h" #include "Message.h" -#include "ServerDB.h" -#include "Connection.h" +#include "Meta.h" #include "Server.h" +#include "ServerDB.h" #include "ServerUser.h" +#include "User.h" #include "Version.h" #include "crypto/CryptState.h" -#include "Meta.h" -#include "ChannelListener.h" #include <QtCore/QStack> #include <QtCore/QtEndian> -#define RATELIMIT(user) \ +#define RATELIMIT(user) \ if (user->leakyBucket.ratelimit(1)) { \ - return; \ + return; \ } -#define MSG_SETUP(st) \ +#define MSG_SETUP(st) \ if (uSource->sState != st) { \ - return; \ - } \ + return; \ + } \ uSource->bwr.resetIdleSeconds() #define MSG_SETUP_NO_UNIDLE(st) \ - if (uSource->sState != st) \ - return + if (uSource->sState != st) \ + return -#define VICTIM_SETUP \ - ServerUser *pDstServerUser = uSource; \ - if (msg.has_session()) \ +#define VICTIM_SETUP \ + ServerUser *pDstServerUser = uSource; \ + if (msg.has_session()) \ pDstServerUser = qhUsers.value(msg.session()); \ - if (! pDstServerUser) \ - return; \ + if (!pDstServerUser) \ + return; \ Q_UNUSED(pDstServerUser) -#define PERM_DENIED(who, where, what) \ - { \ - MumbleProto::PermissionDenied mppd; \ - mppd.set_permission(static_cast<int>(what)); \ - mppd.set_channel_id(where->iId); \ - mppd.set_session(who->uiSession); \ - mppd.set_type(MumbleProto::PermissionDenied_DenyType_Permission); \ - sendMessage(uSource, mppd); \ - log(uSource, QString("%1 not allowed to %2 in %3").arg(who->qsName).arg(ChanACL::permName(what)).arg(where->qsName)); \ - } - -#define PERM_DENIED_TYPE(type) \ - { \ - MumbleProto::PermissionDenied mppd; \ +#define PERM_DENIED(who, where, what) \ + { \ + MumbleProto::PermissionDenied mppd; \ + mppd.set_permission(static_cast< int >(what)); \ + mppd.set_channel_id(where->iId); \ + mppd.set_session(who->uiSession); \ + mppd.set_type(MumbleProto::PermissionDenied_DenyType_Permission); \ + sendMessage(uSource, mppd); \ + log(uSource, \ + QString("%1 not allowed to %2 in %3").arg(who->qsName).arg(ChanACL::permName(what)).arg(where->qsName)); \ + } + +#define PERM_DENIED_TYPE(type) \ + { \ + MumbleProto::PermissionDenied mppd; \ mppd.set_type(MumbleProto::PermissionDenied_DenyType_##type); \ - sendMessage(uSource, mppd); \ + sendMessage(uSource, mppd); \ } -#define PERM_DENIED_FALLBACK(type,version,text) \ - { \ - MumbleProto::PermissionDenied mppd; \ +#define PERM_DENIED_FALLBACK(type, version, text) \ + { \ + MumbleProto::PermissionDenied mppd; \ mppd.set_type(MumbleProto::PermissionDenied_DenyType_##type); \ - if (uSource->uiVersion < version) \ - mppd.set_reason(u8(text)); \ - sendMessage(uSource, mppd); \ + if (uSource->uiVersion < version) \ + mppd.set_reason(u8(text)); \ + sendMessage(uSource, mppd); \ } -#define PERM_DENIED_HASH(user) \ - { \ - MumbleProto::PermissionDenied mppd; \ +#define PERM_DENIED_HASH(user) \ + { \ + MumbleProto::PermissionDenied mppd; \ mppd.set_type(MumbleProto::PermissionDenied_DenyType_MissingCertificate); \ - if (user) \ - mppd.set_session(user->uiSession); \ - sendMessage(uSource, mppd); \ + if (user) \ + mppd.set_session(user->uiSession); \ + sendMessage(uSource, mppd); \ } /// A helper class for managing temporary access tokens. /// It will add the tokens in the comstructor and remove them again in the destructor effectively /// turning the tokens into a scope-based property. class TemporaryAccessTokenHelper { - protected: - ServerUser *affectedUser; - QStringList qslTemporaryTokens; - Server *server; - - public: - TemporaryAccessTokenHelper(ServerUser *affectedUser, const QStringList &tokens, Server *server) - : affectedUser(affectedUser) - , qslTemporaryTokens(tokens) - , server(server) { - // Add the temporary tokens - QMutableStringListIterator it(this->qslTemporaryTokens); +protected: + ServerUser *affectedUser; + QStringList qslTemporaryTokens; + Server *server; - { - QMutexLocker qml(&server->qmCache); +public: + TemporaryAccessTokenHelper(ServerUser *affectedUser, const QStringList &tokens, Server *server) + : affectedUser(affectedUser), qslTemporaryTokens(tokens), server(server) { + // Add the temporary tokens + QMutableStringListIterator it(this->qslTemporaryTokens); - while (it.hasNext()) { - QString &token = it.next(); + { + QMutexLocker qml(&server->qmCache); - // If tokens are treated case-insensitively, transform all temp. tokens to lowercase first - if (Group::accessTokenCaseSensitivity == Qt::CaseInsensitive) { - token = token.toLower(); - } + while (it.hasNext()) { + QString &token = it.next(); - if (!this->affectedUser->qslAccessTokens.contains(token, Group::accessTokenCaseSensitivity)) { - // Add token - this->affectedUser->qslAccessTokens << token; - } else { - // It appears, as if the user already has this token set -> it's not a temporary one or a duplicate - it.remove(); - } + // If tokens are treated case-insensitively, transform all temp. tokens to lowercase first + if (Group::accessTokenCaseSensitivity == Qt::CaseInsensitive) { + token = token.toLower(); } - } - if (!this->qslTemporaryTokens.isEmpty()) { - // Clear the cache in order for tokens to take effect - server->clearACLCache(this->affectedUser); + if (!this->affectedUser->qslAccessTokens.contains(token, Group::accessTokenCaseSensitivity)) { + // Add token + this->affectedUser->qslAccessTokens << token; + } else { + // It appears, as if the user already has this token set -> it's not a temporary one or a duplicate + it.remove(); + } } } - ~TemporaryAccessTokenHelper() { - if (!this->qslTemporaryTokens.isEmpty()) { - { - QMutexLocker qml(&server->qmCache); + if (!this->qslTemporaryTokens.isEmpty()) { + // Clear the cache in order for tokens to take effect + server->clearACLCache(this->affectedUser); + } + } - // remove the temporary tokens - foreach(const QString &token, this->qslTemporaryTokens) { - this->affectedUser->qslAccessTokens.removeOne(token); - } - } + ~TemporaryAccessTokenHelper() { + if (!this->qslTemporaryTokens.isEmpty()) { + { + QMutexLocker qml(&server->qmCache); - // Clear cache to actually get rid of the temporary tokens - server->clearACLCache(this->affectedUser); + // remove the temporary tokens + foreach (const QString &token, this->qslTemporaryTokens) { + this->affectedUser->qslAccessTokens.removeOne(token); + } } + + // Clear cache to actually get rid of the temporary tokens + server->clearACLCache(this->affectedUser); } + } }; /// Checks whether the given channel has restrictions affecting the ENTER privilege @@ -146,7 +145,7 @@ class TemporaryAccessTokenHelper { /// @return Whether the provided channel has an ACL denying ENTER bool isChannelEnterRestricted(Channel *c) { // A channel is enter restricted if there's an ACL denying enter privileges - foreach(ChanACL *acl, c->qlACL) { + foreach (ChanACL *acl, c->qlACL) { if (acl->pDeny & ChanACL::Enter) { return true; } @@ -158,7 +157,7 @@ bool isChannelEnterRestricted(Channel *c) { void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg) { if ((msg.tokens_size() > 0) || (uSource->sState == ServerUser::Authenticated)) { QStringList qsl; - for (int i=0;i<msg.tokens_size();++i) + for (int i = 0; i < msg.tokens_size(); ++i) qsl << u8(msg.tokens(i)); { QMutexLocker qml(&qmCache); @@ -168,7 +167,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // Send back updated enter states of all channels MumbleProto::ChannelState mpcs; - foreach(Channel *chan, qhChannels) { + foreach (Channel *chan, qhChannels) { mpcs.set_channel_id(chan->iId); mpcs.set_can_enter(ChanACL::hasPermission(uSource, chan, ChanACL::Enter, &acCache)); // As no ACLs have changed, we don't need to update the is_access_restricted message field @@ -183,30 +182,31 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg uSource->qsName = u8(msg.username()); - bool ok = false; + bool ok = false; bool nameok = validateUserName(uSource->qsName); - QString pw = u8(msg.password()); + QString pw = u8(msg.password()); // Fetch ID and stored username. // Since this may call DBus, which may recall our dbus messages, this function needs // to support re-entrancy, and also to support the fact that sessions may go away. - int id = authenticate(uSource->qsName, pw, uSource->uiSession, uSource->qslEmail, uSource->qsHash, uSource->bVerified, uSource->peerCertificateChain()); + int id = authenticate(uSource->qsName, pw, uSource->uiSession, uSource->qslEmail, uSource->qsHash, + uSource->bVerified, uSource->peerCertificateChain()); uSource->iId = id >= 0 ? id : -1; QString reason; MumbleProto::Reject_RejectType rtType = MumbleProto::Reject_RejectType_None; - if (id==-2 && ! nameok) { + if (id == -2 && !nameok) { reason = "Invalid username"; rtType = MumbleProto::Reject_RejectType_InvalidUsername; - } else if (id==-1) { + } else if (id == -1) { reason = "Wrong certificate or password for existing user"; rtType = MumbleProto::Reject_RejectType_WrongUserPW; - } else if (id==-2 && ! qsPassword.isEmpty() && qsPassword != pw) { + } else if (id == -2 && !qsPassword.isEmpty() && qsPassword != pw) { reason = "Invalid server password"; rtType = MumbleProto::Reject_RejectType_WrongServerPW; - } else if (id==-3) { + } else if (id == -3) { reason = "Your account information can not be verified currently. Please try again later"; rtType = MumbleProto::Reject_RejectType_AuthenticatorFail; } else { @@ -214,11 +214,10 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg } ServerUser *uOld = nullptr; - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u == uSource) continue; - if (((u->iId>=0) && (u->iId == uSource->iId)) || - (u->qsName.toLower() == uSource->qsName.toLower())) { + if (((u->iId >= 0) && (u->iId == uSource->iId)) || (u->qsName.toLower() == uSource->qsName.toLower())) { uOld = u; break; } @@ -226,43 +225,44 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // Allow reuse of name from same IP if (ok && uOld && (uSource->iId == -1)) { - if ((uOld->peerAddress() != uSource->peerAddress()) && (uSource->qsHash.isEmpty() || (uSource->qsHash != uOld->qsHash))) { + if ((uOld->peerAddress() != uSource->peerAddress()) + && (uSource->qsHash.isEmpty() || (uSource->qsHash != uOld->qsHash))) { reason = "Username already in use"; rtType = MumbleProto::Reject_RejectType_UsernameInUse; - ok = false; + ok = false; } } if ((id != 0) && (qhUsers.count() > iMaxUsers)) { reason = QString::fromLatin1("Server is full (max %1 users)").arg(iMaxUsers); rtType = MumbleProto::Reject_RejectType_ServerFull; - ok = false; + ok = false; } if ((id != 0) && (uSource->qsHash.isEmpty() && bCertRequired)) { reason = QString::fromLatin1("A certificate is required to connect to this server"); rtType = MumbleProto::Reject_RejectType_NoCertificate; - ok = false; + ok = false; } Channel *lc; lc = qhChannels.value(readLastChannel(uSource->iId)); - if (! lc || ! hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { + if (!lc || !hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { lc = qhChannels.value(iDefaultChan); - if (! lc || ! hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { + if (!lc || !hasPermission(uSource, lc, ChanACL::Enter) || isChannelFull(lc, uSource)) { lc = root; if (isChannelFull(lc, uSource)) { reason = QString::fromLatin1("Server channels are full"); rtType = MumbleProto::Reject_RejectType_ServerFull; - ok = false; + ok = false; } } } - if (! ok) { + if (!ok) { log(uSource, QString("Rejected connection from %1: %2") - .arg(addressToString(uSource->peerAddress(), uSource->peerPort()), reason)); + .arg(addressToString(uSource->peerAddress(), uSource->peerPort()), reason)); MumbleProto::Reject mpr; mpr.set_reason(u8(reason)); mpr.set_type(rtType); @@ -299,10 +299,10 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg bool fake_celt_support = false; if (msg.celt_versions_size() > 0) { - for (int i=0;i < msg.celt_versions_size(); ++i) + for (int i = 0; i < msg.celt_versions_size(); ++i) uSource->qlCodecs.append(msg.celt_versions(i)); } else { - uSource->qlCodecs.append(static_cast<qint32>(0x8000000b)); + uSource->qlCodecs.append(static_cast< qint32 >(0x8000000b)); fake_celt_support = true; } uSource->bOpus = msg.opus(); @@ -316,15 +316,18 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpcv); if (!bOpus && uSource->bOpus && fake_celt_support) { - sendTextMessage(nullptr, uSource, false, QLatin1String("<strong>WARNING:</strong> Your client doesn't support the CELT codec, you won't be able to talk to or hear most clients. Please make sure your client was built with CELT support.")); + sendTextMessage( + nullptr, uSource, false, + QLatin1String("<strong>WARNING:</strong> Your client doesn't support the CELT codec, you won't be able to " + "talk to or hear most clients. Please make sure your client was built with CELT support.")); } // Transmit channel tree - QQueue<Channel *> q; - QSet<Channel *> chans; + QQueue< Channel * > q; + QSet< Channel * > chans; q << root; MumbleProto::ChannelState mpcs; - while (! q.isEmpty()) { + while (!q.isEmpty()) { c = q.dequeue(); chans.insert(c); @@ -340,9 +343,9 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg mpcs.set_position(c->iPosition); - if ((uSource->uiVersion >= 0x010202) && ! c->qbaDescHash.isEmpty()) + if ((uSource->uiVersion >= 0x010202) && !c->qbaDescHash.isEmpty()) mpcs.set_description_hash(blob(c->qbaDescHash)); - else if (! c->qsDesc.isEmpty()) + else if (!c->qsDesc.isEmpty()) mpcs.set_description(u8(c->qsDesc)); mpcs.set_max_users(c->uiMaxUsers); @@ -353,17 +356,17 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpcs); - foreach(c, c->qlChannels) + foreach (c, c->qlChannels) q.enqueue(c); } // Transmit links - foreach(c, chans) { + foreach (c, chans) { if (c->qhLinks.count() > 0) { mpcs.Clear(); mpcs.set_channel_id(c->iId); - foreach(Channel *l, c->qhLinks.keys()) + foreach (Channel *l, c->qhLinks.keys()) mpcs.add_links(l->iId); sendMessage(uSource, mpcs); } @@ -386,35 +389,37 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg hashAssign(uSource->qbaTexture, uSource->qbaTextureHash, getUserTexture(uSource->iId)); - if (! uSource->qbaTextureHash.isEmpty()) + if (!uSource->qbaTextureHash.isEmpty()) mpus.set_texture_hash(blob(uSource->qbaTextureHash)); - else if (! uSource->qbaTexture.isEmpty()) + else if (!uSource->qbaTexture.isEmpty()) mpus.set_texture(blob(uSource->qbaTexture)); - const QMap<int, QString> &info = getRegistration(uSource->iId); + const QMap< int, QString > &info = getRegistration(uSource->iId); if (info.contains(ServerDB::User_Comment)) { hashAssign(uSource->qsComment, uSource->qbaCommentHash, info.value(ServerDB::User_Comment)); - if (! uSource->qbaCommentHash.isEmpty()) + if (!uSource->qbaCommentHash.isEmpty()) mpus.set_comment_hash(blob(uSource->qbaCommentHash)); - else if (! uSource->qsComment.isEmpty()) + else if (!uSource->qsComment.isEmpty()) mpus.set_comment(u8(uSource->qsComment)); } } - if (! uSource->qsHash.isEmpty()) + if (!uSource->qsHash.isEmpty()) mpus.set_hash(u8(uSource->qsHash)); if (uSource->cChannel->iId != 0) mpus.set_channel_id(uSource->cChannel->iId); sendAll(mpus, 0x010202); - if ((uSource->qbaTexture.length() >= 4) && (qFromBigEndian<unsigned int>(reinterpret_cast<const unsigned char *>(uSource->qbaTexture.constData())) == 600 * 60 * 4)) + if ((uSource->qbaTexture.length() >= 4) + && (qFromBigEndian< unsigned int >(reinterpret_cast< const unsigned char * >(uSource->qbaTexture.constData())) + == 600 * 60 * 4)) mpus.set_texture(blob(uSource->qbaTexture)); - if (! uSource->qsComment.isEmpty()) + if (!uSource->qsComment.isEmpty()) mpus.set_comment(u8(uSource->qsComment)); - sendAll(mpus, ~ 0x010202); + sendAll(mpus, ~0x010202); // Transmit other users profiles - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->sState != ServerUser::Authenticated) continue; @@ -427,11 +432,14 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg if (u->iId >= 0) mpus.set_user_id(u->iId); if (uSource->uiVersion >= 0x010202) { - if (! u->qbaTextureHash.isEmpty()) + if (!u->qbaTextureHash.isEmpty()) mpus.set_texture_hash(blob(u->qbaTextureHash)); - else if (! u->qbaTexture.isEmpty()) + else if (!u->qbaTexture.isEmpty()) mpus.set_texture(blob(u->qbaTexture)); - } else if ((uSource->qbaTexture.length() >= 4) && (qFromBigEndian<unsigned int>(reinterpret_cast<const unsigned char *>(uSource->qbaTexture.constData())) == 600 * 60 * 4)) { + } else if ((uSource->qbaTexture.length() >= 4) + && (qFromBigEndian< unsigned int >( + reinterpret_cast< const unsigned char * >(uSource->qbaTexture.constData())) + == 600 * 60 * 4)) { mpus.set_texture(blob(u->qbaTexture)); } if (u->cChannel->iId != 0) @@ -450,14 +458,14 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg mpus.set_self_deaf(true); else if (u->bSelfMute) mpus.set_self_mute(true); - if ((uSource->uiVersion >= 0x010202) && ! u->qbaCommentHash.isEmpty()) + if ((uSource->uiVersion >= 0x010202) && !u->qbaCommentHash.isEmpty()) mpus.set_comment_hash(blob(u->qbaCommentHash)); - else if (! u->qsComment.isEmpty()) + else if (!u->qsComment.isEmpty()) mpus.set_comment(u8(u->qsComment)); - if (! u->qsHash.isEmpty()) + if (!u->qsHash.isEmpty()) mpus.set_hash(u8(u->qsHash)); - foreach(int channelID, ChannelListener::getListenedChannelsForUser(u)) { + foreach (int channelID, ChannelListener::getListenedChannelsForUser(u)) { mpus.add_listening_channel_add(channelID); } @@ -467,7 +475,7 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg // Send syncronisation packet MumbleProto::ServerSync mpss; mpss.set_session(uSource->uiSession); - if (! qsWelcomeText.isEmpty()) + if (!qsWelcomeText.isEmpty()) mpss.set_welcome_text(u8(qsWelcomeText)); mpss.set_max_bandwidth(iMaxBandwidth); @@ -489,11 +497,11 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpsc); MumbleProto::SuggestConfig mpsug; - if (! qvSuggestVersion.isNull()) + if (!qvSuggestVersion.isNull()) mpsug.set_version(qvSuggestVersion.toUInt()); - if (! qvSuggestPositional.isNull()) + if (!qvSuggestPositional.isNull()) mpsug.set_positional(qvSuggestPositional.toBool()); - if (! qvSuggestPushToTalk.isNull()) + if (!qvSuggestPushToTalk.isNull()) mpsug.set_push_to_talk(qvSuggestPushToTalk.toBool()); #if GOOGLE_PROTOBUF_VERSION >= 3004000 if (mpsug.ByteSizeLong() > 0) { @@ -504,18 +512,23 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg sendMessage(uSource, mpsug); } - if (uSource->uiVersion < 0x010400 && Meta::mp.iMaxListenersPerChannel > 0 && Meta::mp.iMaxListenerProxiesPerUser > 0) { - // The server has the ChannelListener feature enabled but the client that connects doesn't have version 1.4.0 or newer - // meaning that this client doesn't know what ChannelListeners are. Thus we'll send that user a text-message informing - // about this. + if (uSource->uiVersion < 0x010400 && Meta::mp.iMaxListenersPerChannel > 0 + && Meta::mp.iMaxListenerProxiesPerUser > 0) { + // The server has the ChannelListener feature enabled but the client that connects doesn't have version 1.4.0 or + // newer meaning that this client doesn't know what ChannelListeners are. Thus we'll send that user a + // text-message informing about this. MumbleProto::TextMessage mptm; if (Meta::mp.bAllowHTML) { - mptm.set_message("<b>[WARNING]</b>: This server has the <b>ChannelListener</b> feature enabled but your client version does not support it. " - "This means that users <b>might be listening to what you are saying in your channel without you noticing!</b> " - "You can solve this issue by upgrading to Mumble 1.4.0 or newer."); + mptm.set_message("<b>[WARNING]</b>: This server has the <b>ChannelListener</b> feature enabled but your " + "client version does not support it. " + "This means that users <b>might be listening to what you are saying in your channel " + "without you noticing!</b> " + "You can solve this issue by upgrading to Mumble 1.4.0 or newer."); } else { - mptm.set_message("[WARNING]: This server has the ChannelListener feature enabled but your client version does not support it. " + mptm.set_message( + "[WARNING]: This server has the ChannelListener feature enabled but your client version does not " + "support it. " "This means that users might be listening to what you are saying in your channel without you noticing! " "You can solve this issue by upgrading to Mumble 1.4.0 or newer."); } @@ -531,15 +544,15 @@ void Server::msgAuthenticate(ServerUser *uSource, MumbleProto::Authenticate &msg void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { MSG_SETUP(ServerUser::Authenticated); - QSet<Ban> previousBans, newBans; - if (! hasPermission(uSource, qhChannels.value(0), ChanACL::Ban)) { + QSet< Ban > previousBans, newBans; + if (!hasPermission(uSource, qhChannels.value(0), ChanACL::Ban)) { PERM_DENIED(uSource, qhChannels.value(0), ChanACL::Ban); return; } if (msg.query()) { msg.clear_query(); msg.clear_bans(); - foreach(const Ban &b, qlBans) { + foreach (const Ban &b, qlBans) { MumbleProto::BanList_BanEntry *be = msg.add_bans(); be->set_address(b.haAddress.toStdString()); be->set_mask(b.iMask); @@ -552,21 +565,21 @@ void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { sendMessage(uSource, msg); } else { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - previousBans = QSet<Ban>(qlBans.begin(), qlBans.end()); + previousBans = QSet< Ban >(qlBans.begin(), qlBans.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now previousBans = qlBans.toSet(); #endif qlBans.clear(); - for (int i=0;i < msg.bans_size(); ++i) { + for (int i = 0; i < msg.bans_size(); ++i) { const MumbleProto::BanList_BanEntry &be = msg.bans(i); Ban b; - b.haAddress = be.address(); - b.iMask = be.mask(); + b.haAddress = be.address(); + b.iMask = be.mask(); b.qsUsername = u8(be.name()); - b.qsHash = u8(be.hash()); - b.qsReason = u8(be.reason()); + b.qsHash = u8(be.hash()); + b.qsReason = u8(be.reason()); if (be.has_start()) { b.qdtStart = QDateTime::fromString(u8(be.start()), Qt::ISODate); b.qdtStart.setTimeSpec(Qt::UTC); @@ -579,19 +592,15 @@ void Server::msgBanList(ServerUser *uSource, MumbleProto::BanList &msg) { } } #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - newBans = QSet<Ban>(qlBans.begin(), qlBans.end()); + newBans = QSet< Ban >(qlBans.begin(), qlBans.end()); #else // In Qt 5.14 QList::toSet() has been deprecated as there exists a dedicated constructor of QSet for this now newBans = qlBans.toSet(); #endif - QSet<Ban> removed = previousBans - newBans; - QSet<Ban> added = newBans - previousBans; - foreach(const Ban &b, removed) { - log(uSource, QString("Removed ban: %1").arg(b.toString())); - } - foreach(const Ban &b, added) { - log(uSource, QString("New ban: %1").arg(b.toString())); - } + QSet< Ban > removed = previousBans - newBans; + QSet< Ban > added = newBans - previousBans; + foreach (const Ban &b, removed) { log(uSource, QString("Removed ban: %1").arg(b.toString())); } + foreach (const Ban &b, added) { log(uSource, QString("New ban: %1").arg(b.toString())); } saveBans(); log(uSource, "Updated banlist"); } @@ -610,7 +619,7 @@ void Server::msgUDPTunnel(ServerUser *uSource, MumbleProto::UDPTunnel &msg) { MSG_SETUP_NO_UNIDLE(ServerUser::Authenticated); const std::string &str = msg.packet(); - int len = static_cast<int>(str.length()); + int len = static_cast< int >(str.length()); if (len < 1) return; QReadLocker rl(&qrwlVoiceThread); @@ -643,10 +652,10 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (uSource == pDstServerUser) { RATELIMIT(uSource); } - + // Handle potential temporary access tokens QStringList temporaryAccessTokens; - for (int i=0; i < msg.temporary_access_tokens_size(); i++) { + for (int i = 0; i < msg.temporary_access_tokens_size(); i++) { temporaryAccessTokens << u8(msg.temporary_access_tokens(i)); } TemporaryAccessTokenHelper tempTokenHelper(uSource, temporaryAccessTokens, this); @@ -656,12 +665,12 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (!c || (c == pDstServerUser->cChannel)) return; - if ((uSource != pDstServerUser) && (! hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Move))) { + if ((uSource != pDstServerUser) && (!hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Move))) { PERM_DENIED(uSource, pDstServerUser->cChannel, ChanACL::Move); return; } - if (! hasPermission(uSource, c, ChanACL::Move) && ! hasPermission(pDstServerUser, c, ChanACL::Enter)) { + if (!hasPermission(uSource, c, ChanACL::Move) && !hasPermission(pDstServerUser, c, ChanACL::Enter)) { PERM_DENIED(pDstServerUser, c, ChanACL::Enter); return; } @@ -671,7 +680,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } } - QList<Channel *> listeningChannelsAdd; + QList< Channel * > listeningChannelsAdd; int passedChannelListener = 0; // Check permission for each channel for (int i = 0; i < msg.listening_channel_add_size(); i++) { @@ -687,16 +696,20 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } if (Meta::mp.iMaxListenersPerChannel >= 0 - && Meta::mp.iMaxListenersPerChannel - ChannelListener::getListenerCountForChannel(c) - 1 < 0) { + && Meta::mp.iMaxListenersPerChannel - ChannelListener::getListenerCountForChannel(c) - 1 < 0) { // A limit for the amount of listener proxies per channel is set and it has been reached already - PERM_DENIED_FALLBACK(ChannelListenerLimit, 0x010400, QLatin1String("No more listeners allowed in this channel")); + PERM_DENIED_FALLBACK(ChannelListenerLimit, 0x010400, + QLatin1String("No more listeners allowed in this channel")); continue; } if (Meta::mp.iMaxListenerProxiesPerUser >= 0 - && Meta::mp.iMaxListenerProxiesPerUser - ChannelListener::getListenedChannelCountForUser(uSource) - passedChannelListener - 1 < 0) { + && Meta::mp.iMaxListenerProxiesPerUser - ChannelListener::getListenedChannelCountForUser(uSource) + - passedChannelListener - 1 + < 0) { // A limit for the amount of listener proxies per user is set and it has been reached already - PERM_DENIED_FALLBACK(UserListenerLimit, 0x010400, QLatin1String("No more listeners allowed in this channel")); + PERM_DENIED_FALLBACK(UserListenerLimit, 0x010400, + QLatin1String("No more listeners allowed in this channel")); continue; } @@ -714,7 +727,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { PERM_DENIED_TYPE(TemporaryChannel); return; } - if (! hasPermission(uSource, pDstServerUser->cChannel, ChanACL::MuteDeafen) || msg.suppress()) { + if (!hasPermission(uSource, pDstServerUser->cChannel, ChanACL::MuteDeafen) || msg.suppress()) { PERM_DENIED(uSource, pDstServerUser->cChannel, ChanACL::MuteDeafen); return; } @@ -724,9 +737,9 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_comment()) { bool changed = false; - comment = u8(msg.comment()); + comment = u8(msg.comment()); if (uSource != pDstServerUser) { - if (! hasPermission(uSource, root, ChanACL::ResetUserContent)) { + if (!hasPermission(uSource, root, ChanACL::ResetUserContent)) { PERM_DENIED(uSource, root, ChanACL::ResetUserContent); return; } @@ -737,7 +750,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } - if (! isTextAllowed(comment, changed)) { + if (!isTextAllowed(comment, changed)) { PERM_DENIED_TYPE(TextTooLong); return; } @@ -746,12 +759,13 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } if (msg.has_texture()) { - if (iMaxImageMessageLength > 0 && (msg.texture().length() > static_cast<unsigned int>(iMaxImageMessageLength))) { + if (iMaxImageMessageLength > 0 + && (msg.texture().length() > static_cast< unsigned int >(iMaxImageMessageLength))) { PERM_DENIED_TYPE(TextTooLong); return; } if (uSource != pDstServerUser) { - if (! hasPermission(uSource, root, ChanACL::ResetUserContent)) { + if (!hasPermission(uSource, root, ChanACL::ResetUserContent)) { PERM_DENIED(uSource, root, ChanACL::ResetUserContent); return; } @@ -765,7 +779,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_user_id()) { ChanACL::Perm p = (uSource == pDstServerUser) ? ChanACL::SelfRegister : ChanACL::Register; - if ((pDstServerUser->iId >= 0) || ! hasPermission(uSource, root, p)) { + if ((pDstServerUser->iId >= 0) || !hasPermission(uSource, root, p)) { PERM_DENIED(uSource, root, p); return; } @@ -776,8 +790,10 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } // Prevent self-targeting state changes from being applied to others - if ((pDstServerUser != uSource) && (msg.has_self_deaf() || msg.has_self_mute() || msg.has_plugin_context() || msg.has_plugin_identity() - || msg.has_recording() || msg.listening_channel_add_size() > 0 || msg.listening_channel_remove_size() > 0)) { + if ((pDstServerUser != uSource) + && (msg.has_self_deaf() || msg.has_self_mute() || msg.has_plugin_context() || msg.has_plugin_identity() + || msg.has_recording() || msg.listening_channel_add_size() > 0 + || msg.listening_channel_remove_size() > 0)) { return; } @@ -790,7 +806,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { QByteArray qba = blob(msg.texture()); if (pDstServerUser->iId > 0) { // For registered users store the texture we just received in the database - if (! setTexture(pDstServerUser->iId, qba)) { + if (!setTexture(pDstServerUser->iId, qba)) { return; } } else { @@ -816,7 +832,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_self_mute()) { uSource->bSelfMute = msg.self_mute(); - if (! uSource->bSelfMute) { + if (!uSource->bSelfMute) { msg.set_self_deaf(false); uSource->bSelfDeaf = false; } @@ -837,11 +853,11 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { msg.clear_plugin_identity(); } - if (! comment.isNull()) { + if (!comment.isNull()) { hashAssign(pDstServerUser->qsComment, pDstServerUser->qbaCommentHash, comment); if (pDstServerUser->iId >= 0) { - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Comment, pDstServerUser->qsComment); setInfo(pDstServerUser->iId, info); } @@ -862,7 +878,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { } if (msg.has_mute()) { pDstServerUser->bMute = msg.mute(); - if (! pDstServerUser->bMute) { + if (!pDstServerUser->bMute) { msg.set_deaf(false); pDstServerUser->bDeaf = false; } @@ -873,11 +889,10 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (msg.has_priority_speaker()) pDstServerUser->bPrioritySpeaker = msg.priority_speaker(); - log(uSource, QString("Changed speak-state of %1 (%2 %3 %4 %5)").arg(QString(*pDstServerUser), - QString::number(pDstServerUser->bMute), - QString::number(pDstServerUser->bDeaf), - QString::number(pDstServerUser->bSuppress), - QString::number(pDstServerUser->bPrioritySpeaker))); + log(uSource, QString("Changed speak-state of %1 (%2 %3 %4 %5)") + .arg(QString(*pDstServerUser), QString::number(pDstServerUser->bMute), + QString::number(pDstServerUser->bDeaf), QString::number(pDstServerUser->bSuppress), + QString::number(pDstServerUser->bPrioritySpeaker))); bBroadcast = true; } @@ -892,7 +907,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { else mptm.set_message(u8(QString(QLatin1String("User '%1' stopped recording")).arg(pDstServerUser->qsName))); - sendAll(mptm, ~ 0x010203); + sendAll(mptm, ~0x010203); bBroadcast = true; } @@ -907,7 +922,7 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { // Handle channel listening // Note that it is important to handle the listening channels after channel-joins - foreach(Channel *c, listeningChannelsAdd) { + foreach (Channel *c, listeningChannelsAdd) { ChannelListener::addListener(uSource, c); log(QString::fromLatin1("\"%1\" is now listening to channel \"%2\"").arg(QString(*uSource)).arg(QString(*c))); @@ -930,11 +945,11 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { bool bDstAclChanged = false; if (msg.has_user_id()) { // Handle user (Self-)Registration - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Name, pDstServerUser->qsName); info.insert(ServerDB::User_Hash, pDstServerUser->qsHash); - if (! pDstServerUser->qslEmail.isEmpty()) + if (!pDstServerUser->qslEmail.isEmpty()) info.insert(ServerDB::User_Email, pDstServerUser->qslEmail.first()); int id = registerUser(info); if (id > 0) { @@ -952,24 +967,27 @@ void Server::msgUserState(ServerUser *uSource, MumbleProto::UserState &msg) { if (bBroadcast) { // Texture handling for clients < 1.2.2. // Send the texture data in the message. - if (msg.has_texture() && (pDstServerUser->qbaTexture.length() >= 4) && (qFromBigEndian<unsigned int>(reinterpret_cast<const unsigned char *>(pDstServerUser->qbaTexture.constData())) != 600 * 60 * 4)) { + if (msg.has_texture() && (pDstServerUser->qbaTexture.length() >= 4) + && (qFromBigEndian< unsigned int >( + reinterpret_cast< const unsigned char * >(pDstServerUser->qbaTexture.constData())) + != 600 * 60 * 4)) { // This is a new style texture, don't send it because the client doesn't handle it correctly / crashes. msg.clear_texture(); - sendAll(msg, ~ 0x010202); + sendAll(msg, ~0x010202); msg.set_texture(blob(pDstServerUser->qbaTexture)); } else { // This is an old style texture, empty texture or there was no texture in this packet, // send the message unchanged. - sendAll(msg, ~ 0x010202); + sendAll(msg, ~0x010202); } // Texture / comment handling for clients >= 1.2.2. // Send only a hash of the texture / comment text. The client will request the actual data if necessary. - if (msg.has_texture() && ! pDstServerUser->qbaTextureHash.isEmpty()) { + if (msg.has_texture() && !pDstServerUser->qbaTextureHash.isEmpty()) { msg.clear_texture(); msg.set_texture_hash(blob(pDstServerUser->qbaTextureHash)); } - if (msg.has_comment() && ! pDstServerUser->qbaCommentHash.isEmpty()) { + if (msg.has_comment() && !pDstServerUser->qbaCommentHash.isEmpty()) { msg.clear_comment(); msg.set_comment_hash(blob(pDstServerUser->qbaCommentHash)); } @@ -996,23 +1014,23 @@ void Server::msgUserRemove(ServerUser *uSource, MumbleProto::UserRemove &msg) { bool ban = msg.has_ban() && msg.ban(); - Channel *c = qhChannels.value(0); - QFlags<ChanACL::Perm> perm = ban ? ChanACL::Ban : (ChanACL::Ban|ChanACL::Kick); + Channel *c = qhChannels.value(0); + QFlags< ChanACL::Perm > perm = ban ? ChanACL::Ban : (ChanACL::Ban | ChanACL::Kick); - if ((pDstServerUser->iId ==0) || ! hasPermission(uSource, c, perm)) { + if ((pDstServerUser->iId == 0) || !hasPermission(uSource, c, perm)) { PERM_DENIED(uSource, c, perm); return; } if (ban) { Ban b; - b.haAddress = pDstServerUser->haAddress; - b.iMask = 128; - b.qsReason = u8(msg.reason()); + b.haAddress = pDstServerUser->haAddress; + b.iMask = 128; + b.qsReason = u8(msg.reason()); b.qsUsername = pDstServerUser->qsName; - b.qsHash = pDstServerUser->qsHash; - b.qdtStart = QDateTime::currentDateTime().toUTC(); - b.iDuration = 0; + b.qsHash = pDstServerUser->qsHash; + b.qdtStart = QDateTime::currentDateTime().toUTC(); + b.iDuration = 0; qlBans << b; saveBans(); } @@ -1034,7 +1052,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // If this message relates to an existing channel check if the id is really valid if (msg.has_channel_id()) { c = qhChannels.value(msg.channel_id()); - if (! c) + if (!c) return; } else { RATELIMIT(uSource); @@ -1043,7 +1061,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // Check if the parent exists if (msg.has_parent()) { p = qhChannels.value(msg.parent()); - if (! p) + if (!p) return; } @@ -1052,9 +1070,9 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg QString qsName; QString qsDesc; if (msg.has_description()) { - qsDesc = u8(msg.description()); + qsDesc = u8(msg.description()); bool changed = false; - if (! isTextAllowed(qsDesc, changed)) { + if (!isTextAllowed(qsDesc, changed)) { PERM_DENIED_TYPE(TextTooLong); return; } @@ -1067,7 +1085,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // check if the name is valid and not already in use. qsName = u8(msg.name()); - if (! validateChannelName(qsName)) { + if (!validateChannelName(qsName)) { PERM_DENIED_TYPE(ChannelName); return; } @@ -1079,7 +1097,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg if (p || (c && c->iId != 0)) { Channel *cp = p ? p : c->cParent; - foreach(Channel *sibling, cp->qlChannels) { + foreach (Channel *sibling, cp->qlChannels) { if (sibling->qsName == qsName) { PERM_DENIED_TYPE(ChannelName); return; @@ -1088,7 +1106,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } } - if(p) { + if (p) { // Having a parent channel given means we either want to create // a channel in or move a channel into this parent. @@ -1098,19 +1116,19 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } } - if (! c) { + if (!c) { // If we don't have a channel handle up to now we want to create a new channel // so check if the user has enough rights and we got everything we need. - if (! p || qsName.isNull()) + if (!p || qsName.isNull()) return; if (iChannelCountLimit != 0 && qhChannels.count() >= iChannelCountLimit) { PERM_DENIED_FALLBACK(ChannelCountLimit, 0x010300, QLatin1String("Channel count limit reached")); return; } - + ChanACL::Perm perm = msg.temporary() ? ChanACL::MakeTempChannel : ChanACL::MakeChannel; - if (! hasPermission(uSource, p, perm)) { + if (!hasPermission(uSource, p, perm)) { PERM_DENIED(uSource, p, perm); return; } @@ -1133,16 +1151,16 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg g->qsAdd << uSource->iId; } - if (! hasPermission(uSource, c, ChanACL::Write)) { - ChanACL *a = new ChanACL(c); - a->bApplyHere=true; - a->bApplySubs=false; + if (!hasPermission(uSource, c, ChanACL::Write)) { + ChanACL *a = new ChanACL(c); + a->bApplyHere = true; + a->bApplySubs = false; if (uSource->iId >= 0) - a->iUserId=uSource->iId; + a->iUserId = uSource->iId; else - a->qsGroup=QLatin1Char('$') + uSource->qsHash; - a->pDeny=ChanACL::None; - a->pAllow=ChanACL::Write | ChanACL::Traverse; + a->qsGroup = QLatin1Char('$') + uSource->qsHash; + a->pDeny = ChanACL::None; + a->pAllow = ChanACL::Write | ChanACL::Traverse; clearACLCache(); } @@ -1152,8 +1170,8 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg log(uSource, QString("Added channel %1 under %2").arg(QString(*c), QString(*p))); emit channelCreated(c); - sendAll(msg, ~ 0x010202); - if (! c->qbaDescHash.isEmpty()) { + sendAll(msg, ~0x010202); + if (!c->qbaDescHash.isEmpty()) { msg.clear_description(); msg.set_description_hash(blob(c->qbaDescHash)); } @@ -1171,20 +1189,20 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } else { // The message is related to an existing channel c so check if the user is allowed to modify it // and perform the modifications - if (! qsName.isNull()) { - if (! hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { + if (!qsName.isNull()) { + if (!hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } } - if (! qsDesc.isNull()) { - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!qsDesc.isNull()) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } } if (msg.has_position()) { - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1208,49 +1226,49 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg return; } - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } - if (! hasPermission(uSource, p, ChanACL::MakeChannel)) { + if (!hasPermission(uSource, p, ChanACL::MakeChannel)) { PERM_DENIED(uSource, p, ChanACL::MakeChannel); return; } QString name = qsName.isNull() ? c->qsName : qsName; - foreach(Channel *sibling, p->qlChannels) { + foreach (Channel *sibling, p->qlChannels) { if (sibling->qsName == name) { PERM_DENIED_TYPE(ChannelName); return; } } } - QList<Channel *> qlAdd; - QList<Channel *> qlRemove; + QList< Channel * > qlAdd; + QList< Channel * > qlRemove; if (msg.links_add_size() || msg.links_remove_size()) { - if (! hasPermission(uSource, c, ChanACL::LinkChannel)) { + if (!hasPermission(uSource, c, ChanACL::LinkChannel)) { PERM_DENIED(uSource, c, ChanACL::LinkChannel); return; } if (msg.links_remove_size()) { - for (int i=0;i < msg.links_remove_size(); ++i) { + for (int i = 0; i < msg.links_remove_size(); ++i) { unsigned int link = msg.links_remove(i); - Channel *l = qhChannels.value(link); - if (! l) + Channel *l = qhChannels.value(link); + if (!l) return; qlRemove << l; } } if (msg.links_add_size()) { - for (int i=0;i < msg.links_add_size(); ++i) { + for (int i = 0; i < msg.links_add_size(); ++i) { unsigned int link = msg.links_add(i); - Channel *l = qhChannels.value(link); - if (! l) + Channel *l = qhChannels.value(link); + if (!l) return; - if (! hasPermission(uSource, l, ChanACL::LinkChannel)) { + if (!hasPermission(uSource, l, ChanACL::LinkChannel)) { PERM_DENIED(uSource, l, ChanACL::LinkChannel); return; } @@ -1260,7 +1278,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg } if (msg.has_max_users()) { - if (! hasPermission(uSource, c, ChanACL::Write)) { + if (!hasPermission(uSource, c, ChanACL::Write)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1269,9 +1287,7 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg // All permission checks done -- the update is good. if (p) { - log(uSource, QString("Moved channel %1 from %2 to %3").arg(QString(*c), - QString(* c->cParent), - QString(*p))); + log(uSource, QString("Moved channel %1 from %2 to %3").arg(QString(*c), QString(*c->cParent), QString(*p))); { QWriteLocker wl(&qrwlVoiceThread); @@ -1279,23 +1295,18 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg p->addChannel(c); } } - if (! qsName.isNull()) { - log(uSource, QString("Renamed channel %1 to %2").arg(QString(*c), - QString(qsName))); + if (!qsName.isNull()) { + log(uSource, QString("Renamed channel %1 to %2").arg(QString(*c), QString(qsName))); c->qsName = qsName; } - if (! qsDesc.isNull()) + if (!qsDesc.isNull()) hashAssign(c->qsDesc, c->qbaDescHash, qsDesc); if (msg.has_position()) c->iPosition = msg.position(); - foreach(Channel *l, qlAdd) { - addLink(c, l); - } - foreach(Channel *l, qlRemove) { - removeLink(c, l); - } + foreach (Channel *l, qlAdd) { addLink(c, l); } + foreach (Channel *l, qlRemove) { removeLink(c, l); } if (msg.has_max_users()) c->uiMaxUsers = msg.max_users(); @@ -1303,8 +1314,8 @@ void Server::msgChannelState(ServerUser *uSource, MumbleProto::ChannelState &msg updateChannel(c); emit channelStateChanged(c); - sendAll(msg, ~ 0x010202); - if (msg.has_description() && ! c->qbaDescHash.isEmpty()) { + sendAll(msg, ~0x010202); + if (msg.has_description() && !c->qbaDescHash.isEmpty()) { msg.clear_description(); msg.set_description_hash(blob(c->qbaDescHash)); } @@ -1319,7 +1330,7 @@ void Server::msgChannelRemove(ServerUser *uSource, MumbleProto::ChannelRemove &m if (!c) return; - if (! hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { + if (!hasPermission(uSource, c, ChanACL::Write) || (c->iId == 0)) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1335,8 +1346,8 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) TextMessage tm; // for signal userTextMessage - QSet<ServerUser *> users; - QQueue<Channel *> q; + QSet< ServerUser * > users; + QQueue< Channel * > q; RATELIMIT(uSource); @@ -1359,7 +1370,7 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) QString text = u8(msg.message()); bool changed = false; - if (! isTextAllowed(text, changed)) { + if (!isTextAllowed(text, changed)) { PERM_DENIED_TYPE(TextTooLong); return; } @@ -1371,7 +1382,8 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) tm.qsText = text; { // Happy easter - char m[29] = {0117, 0160, 0145, 0156, 040, 0164, 0150, 0145, 040, 0160, 0157, 0144, 040, 0142, 0141, 0171, 040, 0144, 0157, 0157, 0162, 0163, 054, 040, 0110, 0101, 0114, 056, 0}; + char m[29] = { 0117, 0160, 0145, 0156, 040, 0164, 0150, 0145, 040, 0160, 0157, 0144, 040, 0142, 0141, + 0171, 040, 0144, 0157, 0157, 0162, 0163, 054, 040, 0110, 0101, 0114, 056, 0 }; if (msg.channel_id_size() == 1 && msg.channel_id(0) == 0 && msg.message() == m) { PERM_DENIED_TYPE(H9K); return; @@ -1379,32 +1391,32 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) } msg.set_actor(uSource->uiSession); - for (int i=0;i<msg.channel_id_size(); ++i) { + for (int i = 0; i < msg.channel_id_size(); ++i) { unsigned int id = msg.channel_id(i); Channel *c = qhChannels.value(id); - if (! c) + if (!c) return; - if (! ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { + if (!ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { PERM_DENIED(uSource, c, ChanACL::TextMessage); return; } - foreach(User *p, c->qlUsers) - users.insert(static_cast<ServerUser *>(p)); + foreach (User *p, c->qlUsers) + users.insert(static_cast< ServerUser * >(p)); tm.qlChannels.append(id); } - for (int i=0;i<msg.tree_id_size(); ++i) { + for (int i = 0; i < msg.tree_id_size(); ++i) { unsigned int id = msg.tree_id(i); Channel *c = qhChannels.value(id); - if (! c) + if (!c) return; - if (! ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { + if (!ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { PERM_DENIED(uSource, c, ChanACL::TextMessage); return; } @@ -1414,21 +1426,21 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) tm.qlTrees.append(id); } - while (! q.isEmpty()) { + while (!q.isEmpty()) { Channel *c = q.dequeue(); if (ChanACL::hasPermission(uSource, c, ChanACL::TextMessage, &acCache)) { - foreach(Channel *sub, c->qlChannels) + foreach (Channel *sub, c->qlChannels) q.enqueue(sub); - foreach(User *p, c->qlUsers) - users.insert(static_cast<ServerUser *>(p)); + foreach (User *p, c->qlUsers) + users.insert(static_cast< ServerUser * >(p)); } } - for (int i=0;i < msg.session_size(); ++i) { + for (int i = 0; i < msg.session_size(); ++i) { unsigned int session = msg.session(i); - ServerUser *u = qhUsers.value(session); + ServerUser *u = qhUsers.value(session); if (u) { - if (! ChanACL::hasPermission(uSource, u->cChannel, ChanACL::TextMessage, &acCache)) { + if (!ChanACL::hasPermission(uSource, u->cChannel, ChanACL::TextMessage, &acCache)) { PERM_DENIED(uSource, u->cChannel, ChanACL::TextMessage); return; } @@ -1440,7 +1452,7 @@ void Server::msgTextMessage(ServerUser *uSource, MumbleProto::TextMessage &msg) users.remove(uSource); - foreach(ServerUser *u, users) + foreach (ServerUser *u, users) sendMessage(u, msg); emit userTextMessage(uSource, tm); @@ -1460,24 +1472,29 @@ void logGroups(Server *server, const Channel *c, QString prefix = QString()) { server->log(QString::fromLatin1("Channel %1 (%2) has no groups set").arg(c->qsName).arg(c->iId)); return; } else { - server->log(QString::fromLatin1("%1Listing groups specified for channel \"%2\" (%3)...").arg(prefix.isEmpty() - ? QLatin1String("") : QLatin1String("\t")).arg(c->qsName).arg(c->iId)); + server->log(QString::fromLatin1("%1Listing groups specified for channel \"%2\" (%3)...") + .arg(prefix.isEmpty() ? QLatin1String("") : QLatin1String("\t")) + .arg(c->qsName) + .arg(c->iId)); } - foreach(Group *currentGroup, c->qhGroups) { + foreach (Group *currentGroup, c->qhGroups) { QString memberList; - foreach(int m, currentGroup->members()) { + foreach (int m, currentGroup->members()) { memberList += QString::fromLatin1("\"%1\"").arg(server->getUserName(m)); memberList += ", "; } if (currentGroup->members().size() > 0) { - memberList.remove(memberList.length() -2, 2); - server->log(QString::fromLatin1("%1Group: \"%2\" contains following users: %3").arg(prefix.isEmpty() - ? QLatin1String("\t") : QLatin1String("\t\t")).arg(currentGroup->qsName).arg(memberList)); + memberList.remove(memberList.length() - 2, 2); + server->log(QString::fromLatin1("%1Group: \"%2\" contains following users: %3") + .arg(prefix.isEmpty() ? QLatin1String("\t") : QLatin1String("\t\t")) + .arg(currentGroup->qsName) + .arg(memberList)); } else { - server->log(QString::fromLatin1("%1Group \"%2\" doesn't contain any users").arg(prefix.isEmpty() - ? QLatin1String("\t") : QLatin1String("\t\t")).arg(currentGroup->qsName)); + server->log(QString::fromLatin1("%1Group \"%2\" doesn't contain any users") + .arg(prefix.isEmpty() ? QLatin1String("\t") : QLatin1String("\t\t")) + .arg(currentGroup->qsName)); } } } @@ -1492,8 +1509,10 @@ void logACLs(Server *server, const Channel *c, QString prefix = QString()) { server->log(prefix); } - foreach(const ChanACL *a, c->qlACL) { - server->log(QString::fromLatin1("%1%2").arg(prefix.isEmpty() ? QLatin1String("") : QLatin1String("\t")).arg(static_cast<QString>(*a))); + foreach (const ChanACL *a, c->qlACL) { + server->log(QString::fromLatin1("%1%2") + .arg(prefix.isEmpty() ? QLatin1String("") : QLatin1String("\t")) + .arg(static_cast< QString >(*a))); } } @@ -1505,7 +1524,8 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { if (!c) return; - if (! hasPermission(uSource, c, ChanACL::Write) && !(c->cParent && hasPermission(uSource, c->cParent, ChanACL::Write))) { + if (!hasPermission(uSource, c, ChanACL::Write) + && !(c->cParent && hasPermission(uSource, c->cParent, ChanACL::Write))) { PERM_DENIED(uSource, c, ChanACL::Write); return; } @@ -1513,11 +1533,11 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { RATELIMIT(uSource); if (msg.has_query() && msg.query()) { - QStack<Channel *> chans; + QStack< Channel * > chans; Channel *p; ChanACL *acl; - QSet<int> qsId; + QSet< int > qsId; msg.clear_groups(); msg.clear_acls(); @@ -1527,15 +1547,15 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { p = c; while (p) { chans.push(p); - if ((p==c) || p->bInheritACL) + if ((p == c) || p->bInheritACL) p = p->cParent; else p = nullptr; } - while (! chans.isEmpty()) { + while (!chans.isEmpty()) { p = chans.pop(); - foreach(acl, p->qlACL) { + foreach (acl, p->qlACL) { if ((p == c) || (acl->bApplySubs)) { MumbleProto::ACL_ChanACL *mpacl = msg.add_acls(); @@ -1553,10 +1573,10 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { } } - p = c->cParent; - QSet<QString> allnames=Group::groupNames(c); - foreach(const QString &name, allnames) { - Group *g = c->qhGroups.value(name); + p = c->cParent; + QSet< QString > allnames = Group::groupNames(c); + foreach (const QString &name, allnames) { + Group *g = c->qhGroups.value(name); Group *pg = p ? Group::getGroup(p, name) : nullptr; MumbleProto::ACL_ChanGroup *group = msg.add_groups(); @@ -1565,17 +1585,17 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { group->set_inheritable(g ? g->bInheritable : true); group->set_inherited(pg && pg->bInheritable); if (g) { - foreach(int id, g->qsAdd) { + foreach (int id, g->qsAdd) { qsId.insert(id); group->add_add(id); } - foreach(int id, g->qsRemove) { + foreach (int id, g->qsRemove) { qsId.insert(id); group->add_remove(id); } } if (pg) { - foreach(int id, pg->members()) { + foreach (int id, pg->members()) { qsId.insert(id); group->add_inherited_members(id); } @@ -1585,9 +1605,9 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { sendMessage(uSource, msg); MumbleProto::QueryUsers mpqu; - foreach(int id, qsId) { - QString uname=getUserName(id); - if (! uname.isEmpty()) { + foreach (int id, qsId) { + QString uname = getUserName(id); + if (!uname.isEmpty()) { mpqu.add_ids(id); mpqu.add_names(u8(uname)); } @@ -1601,7 +1621,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { { QWriteLocker wl(&qrwlVoiceThread); - QHash<QString, QSet<int> > hOldTemp; + QHash< QString, QSet< int > > hOldTemp; if (Meta::mp.bLogGroupChanges || Meta::mp.bLogACLChanges) { log(uSource, QString::fromLatin1("Updating ACL in channel %1").arg(*c)); @@ -1611,7 +1631,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { logGroups(this, c, QLatin1String("These are the groups before applying the change:")); } - foreach(g, c->qhGroups) { + foreach (g, c->qhGroups) { hOldTemp.insert(g->qsName, g->qsTemporary); delete g; } @@ -1621,9 +1641,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { } // Clear old ACLs - foreach(a, c->qlACL) { - delete a; - } + foreach (a, c->qlACL) { delete a; } c->qhGroups.clear(); c->qlACL.clear(); @@ -1633,9 +1651,9 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { // Add new groups for (int i = 0; i < msg.groups_size(); ++i) { const MumbleProto::ACL_ChanGroup &group = msg.groups(i); - g = new Group(c, u8(group.name())); - g->bInherit = group.inherit(); - g->bInheritable = group.inheritable(); + g = new Group(c, u8(group.name())); + g->bInherit = group.inherit(); + g->bInheritable = group.inheritable(); for (int j = 0; j < group.add_size(); ++j) if (!getUserName(group.add(j)).isEmpty()) g->qsAdd << group.add(j); @@ -1656,30 +1674,29 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { if (mpacl.has_user_id() && getUserName(mpacl.user_id()).isEmpty()) continue; - a = new ChanACL(c); + a = new ChanACL(c); a->bApplyHere = mpacl.apply_here(); a->bApplySubs = mpacl.apply_subs(); if (mpacl.has_user_id()) a->iUserId = mpacl.user_id(); else a->qsGroup = u8(mpacl.group()); - a->pDeny = static_cast<ChanACL::Permissions>(mpacl.deny()) & ChanACL::All; - a->pAllow = static_cast<ChanACL::Permissions>(mpacl.grant()) & ChanACL::All; + a->pDeny = static_cast< ChanACL::Permissions >(mpacl.deny()) & ChanACL::All; + a->pAllow = static_cast< ChanACL::Permissions >(mpacl.grant()) & ChanACL::All; } if (Meta::mp.bLogACLChanges) { logACLs(this, c, QLatin1String("And these are the new ACLs:")); } - } clearACLCache(); - if (! hasPermission(uSource, c, ChanACL::Write) && ((uSource->iId >= 0) || !uSource->qsHash.isEmpty())) { + if (!hasPermission(uSource, c, ChanACL::Write) && ((uSource->iId >= 0) || !uSource->qsHash.isEmpty())) { { QWriteLocker wl(&qrwlVoiceThread); - a = new ChanACL(c); + a = new ChanACL(c); a->bApplyHere = true; a->bApplySubs = false; if (uSource->iId >= 0) @@ -1687,8 +1704,8 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { else a->qsGroup = QLatin1Char('$') + uSource->qsHash; a->iUserId = uSource->iId; - a->pDeny = ChanACL::None; - a->pAllow = ChanACL::Write | ChanACL::Traverse; + a->pDeny = ChanACL::None; + a->pAllow = ChanACL::Write | ChanACL::Traverse; } clearACLCache(); @@ -1701,7 +1718,7 @@ void Server::msgACL(ServerUser *uSource, MumbleProto::ACL &msg) { // Send refreshed enter states of this channel to all clients MumbleProto::ChannelState mpcs; mpcs.set_channel_id(c->iId); - foreach(ServerUser *user, qhUsers) { + foreach (ServerUser *user, qhUsers) { mpcs.set_is_enter_restricted(isChannelEnterRestricted(c)); mpcs.set_can_enter(ChanACL::hasPermission(user, c, ChanACL::Enter, &acCache)); @@ -1715,20 +1732,20 @@ void Server::msgQueryUsers(ServerUser *uSource, MumbleProto::QueryUsers &msg) { MumbleProto::QueryUsers reply; - for (int i=0;i<msg.ids_size();++i) { + for (int i = 0; i < msg.ids_size(); ++i) { int id = msg.ids(i); if (id >= 0) { const QString &name = getUserName(id); - if (! name.isEmpty()) { + if (!name.isEmpty()) { reply.add_ids(id); reply.add_names(u8(name)); } } } - for (int i=0;i<msg.names_size();++i) { + for (int i = 0; i < msg.names_size(); ++i) { QString name = u8(msg.names(i)); - int id = getUserID(name); + int id = getUserID(name); if (id >= 0) { name = getUserName(id); reply.add_ids(id); @@ -1744,16 +1761,16 @@ void Server::msgPing(ServerUser *uSource, MumbleProto::Ping &msg) { QMutexLocker l(&uSource->qmCrypt); - uSource->csCrypt->uiRemoteGood = msg.good(); - uSource->csCrypt->uiRemoteLate = msg.late(); - uSource->csCrypt->uiRemoteLost = msg.lost(); + uSource->csCrypt->uiRemoteGood = msg.good(); + uSource->csCrypt->uiRemoteLate = msg.late(); + uSource->csCrypt->uiRemoteLost = msg.lost(); uSource->csCrypt->uiRemoteResync = msg.resync(); - uSource->dUDPPingAvg = msg.udp_ping_avg(); - uSource->dUDPPingVar = msg.udp_ping_var(); + uSource->dUDPPingAvg = msg.udp_ping_avg(); + uSource->dUDPPingVar = msg.udp_ping_var(); uSource->uiUDPPackets = msg.udp_packets(); - uSource->dTCPPingAvg = msg.tcp_ping_avg(); - uSource->dTCPPingVar = msg.tcp_ping_var(); + uSource->dTCPPingAvg = msg.tcp_ping_avg(); + uSource->dTCPPingVar = msg.tcp_ping_var(); uSource->uiTCPPackets = msg.tcp_packets(); quint64 ts = msg.timestamp(); @@ -1773,14 +1790,14 @@ void Server::msgCryptSetup(ServerUser *uSource, MumbleProto::CryptSetup &msg) { QMutexLocker l(&uSource->qmCrypt); - if (! msg.has_client_nonce()) { + if (!msg.has_client_nonce()) { log(uSource, "Requested crypt-nonce resync"); msg.set_server_nonce(uSource->csCrypt->getEncryptIV()); sendMessage(uSource, msg); } else { const std::string &str = msg.client_nonce(); uSource->csCrypt->uiResync++; - if(!uSource->csCrypt->setDecryptIV(str)){ + if (!uSource->csCrypt->setDecryptIV(str)) { qWarning("Messages: Cipher resync failed: Invalid nonce from the client!"); } } @@ -1793,11 +1810,11 @@ void Server::msgContextAction(ServerUser *uSource, MumbleProto::ContextAction &m MSG_SETUP(ServerUser::Authenticated); unsigned int session = msg.has_session() ? msg.session() : 0; - int id = msg.has_channel_id() ? static_cast<int>(msg.channel_id()) : -1; + int id = msg.has_channel_id() ? static_cast< int >(msg.channel_id()) : -1; - if (session && ! qhUsers.contains(session)) + if (session && !qhUsers.contains(session)) return; - if ((id >= 0) && ! qhChannels.contains(id)) + if ((id >= 0) && !qhChannels.contains(id)) return; emit contextAction(uSource, u8(msg.action()), session, id); } @@ -1819,7 +1836,7 @@ void Server::msgVersion(ServerUser *uSource, MumbleProto::Version &msg) { RATELIMIT(uSource); if (msg.has_version()) { - uSource->uiVersion=msg.version(); + uSource->uiVersion = msg.version(); } if (msg.has_release()) { uSource->qsRelease = convertWithSizeRestriction(msg.release(), 100); @@ -1832,7 +1849,11 @@ void Server::msgVersion(ServerUser *uSource, MumbleProto::Version &msg) { } } - log(uSource, QString("Client version %1 (%2 %3: %4)").arg(MumbleVersion::toString(uSource->uiVersion)).arg(uSource->qsOS).arg(uSource->qsOSVersion).arg(uSource->qsRelease)); + log(uSource, QString("Client version %1 (%2 %3: %4)") + .arg(MumbleVersion::toString(uSource->uiVersion)) + .arg(uSource->qsOS) + .arg(uSource->qsOSVersion) + .arg(uSource->qsRelease)); } void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { @@ -1840,15 +1861,15 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { // The register permission is required on the root channel to be allowed to // view the registered users. - if (! hasPermission(uSource, qhChannels.value(0), ChanACL::Register)) { + if (!hasPermission(uSource, qhChannels.value(0), ChanACL::Register)) { PERM_DENIED(uSource, qhChannels.value(0), ChanACL::Register); return; } if (msg.users_size() == 0) { // Query mode. - QList<UserInfo> users = getRegisteredUsersEx(); - QList<UserInfo>::const_iterator it = users.constBegin(); + QList< UserInfo > users = getRegisteredUsersEx(); + QList< UserInfo >::const_iterator it = users.constBegin(); for (; it != users.constEnd(); ++it) { // Skip the SuperUser if (it->user_id > 0) { @@ -1864,14 +1885,14 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { sendMessage(uSource, msg); } else { // Update mode - for (int i=0; i < msg.users_size(); ++i) { + for (int i = 0; i < msg.users_size(); ++i) { const MumbleProto::UserList_User &user = msg.users(i); int id = user.user_id(); if (id == 0) continue; - if (! user.has_name()) { + if (!user.has_name()) { log(uSource, QString::fromLatin1("Unregistered user %1").arg(id)); unregisterUser(id); } else { @@ -1879,12 +1900,12 @@ void Server::msgUserList(ServerUser *uSource, MumbleProto::UserList &msg) { if (validateUserName(name)) { log(uSource, QString::fromLatin1("Renamed user %1 to '%2'").arg(QString::number(id), name)); - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Name, name); setInfo(id, info); MumbleProto::UserState mpus; - foreach(ServerUser *serverUser, qhUsers) { + foreach (ServerUser *serverUser, qhUsers) { if (serverUser->iId == id) { serverUser->qsName = name; mpus.set_session(serverUser->uiSession); @@ -1926,9 +1947,9 @@ void Server::msgVoiceTarget(ServerUser *uSource, MumbleProto::VoiceTarget &msg) uSource->qmTargets.remove(target); } else { WhisperTarget wt; - for (int i=0;i<count;++i) { + for (int i = 0; i < count; ++i) { const MumbleProto::VoiceTarget_Target &t = msg.targets(i); - for (int j=0;j<t.session_size(); ++j) { + for (int j = 0; j < t.session_size(); ++j) { unsigned int s = t.session(j); if (qhUsers.contains(s)) wt.qlSessions << s; @@ -1937,9 +1958,9 @@ void Server::msgVoiceTarget(ServerUser *uSource, MumbleProto::VoiceTarget &msg) unsigned int id = t.channel_id(); if (qhChannels.contains(id)) { WhisperTarget::Channel wtc; - wtc.iId = id; + wtc.iId = id; wtc.bChildren = t.children(); - wtc.bLinks = t.links(); + wtc.bLinks = t.links(); if (t.has_group()) wtc.qsGroup = u8(t.group()); wt.qlChannels << wtc; @@ -1966,21 +1987,21 @@ void Server::msgPermissionQuery(ServerUser *uSource, MumbleProto::PermissionQuer void Server::msgCodecVersion(ServerUser *, MumbleProto::CodecVersion &) { } -void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { +void Server::msgUserStats(ServerUser *uSource, MumbleProto::UserStats &msg) { MSG_SETUP_NO_UNIDLE(ServerUser::Authenticated); VICTIM_SETUP; - const BandwidthRecord &bwr = pDstServerUser->bwr; - const QList<QSslCertificate> &certs = pDstServerUser->peerCertificateChain(); + const BandwidthRecord &bwr = pDstServerUser->bwr; + const QList< QSslCertificate > &certs = pDstServerUser->peerCertificateChain(); bool extend = (uSource == pDstServerUser) || hasPermission(uSource, qhChannels.value(0), ChanACL::Register); - if (! extend && ! hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Enter)) { + if (!extend && !hasPermission(uSource, pDstServerUser->cChannel, ChanACL::Enter)) { PERM_DENIED(uSource, pDstServerUser->cChannel, ChanACL::Enter); return; } bool details = extend; - bool local = extend || (pDstServerUser->cChannel == uSource->cChannel); + bool local = extend || (pDstServerUser->cChannel == uSource->cChannel); if (msg.stats_only()) details = false; @@ -1989,7 +2010,7 @@ void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { msg.set_session(pDstServerUser->uiSession); if (details) { - foreach(const QSslCertificate &cert, certs) { + foreach (const QSslCertificate &cert, certs) { const QByteArray &der = cert.toDer(); msg.add_certificates(blob(der)); } @@ -2027,15 +2048,15 @@ void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { mpv = msg.mutable_version(); if (pDstServerUser->uiVersion) mpv->set_version(pDstServerUser->uiVersion); - if (! pDstServerUser->qsRelease.isEmpty()) + if (!pDstServerUser->qsRelease.isEmpty()) mpv->set_release(u8(pDstServerUser->qsRelease)); - if (! pDstServerUser->qsOS.isEmpty()) { + if (!pDstServerUser->qsOS.isEmpty()) { mpv->set_os(u8(pDstServerUser->qsOS)); - if (! pDstServerUser->qsOSVersion.isEmpty()) + if (!pDstServerUser->qsOSVersion.isEmpty()) mpv->set_os_version(u8(pDstServerUser->qsOSVersion)); } - foreach(int v, pDstServerUser->qlCodecs) + foreach (int v, pDstServerUser->qlCodecs) msg.add_celt_versions(v); msg.set_opus(pDstServerUser->bOpus); @@ -2054,16 +2075,16 @@ void Server::msgUserStats(ServerUser*uSource, MumbleProto::UserStats &msg) { void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) { MSG_SETUP_NO_UNIDLE(ServerUser::Authenticated); - int ntextures = msg.session_texture_size(); - int ncomments = msg.session_comment_size(); + int ntextures = msg.session_texture_size(); + int ncomments = msg.session_comment_size(); int ndescriptions = msg.channel_description_size(); if (ndescriptions) { MumbleProto::ChannelState mpcs; - for (int i=0;i<ndescriptions;++i) { - int id = msg.channel_description(i); + for (int i = 0; i < ndescriptions; ++i) { + int id = msg.channel_description(i); Channel *c = qhChannels.value(id); - if (c && ! c->qsDesc.isEmpty()) { + if (c && !c->qsDesc.isEmpty()) { mpcs.set_channel_id(id); mpcs.set_description(u8(c->qsDesc)); sendMessage(uSource, mpcs); @@ -2072,10 +2093,10 @@ void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) } if (ntextures || ncomments) { MumbleProto::UserState mpus; - for (int i=0;i<ntextures;++i) { - int session = msg.session_texture(i); + for (int i = 0; i < ntextures; ++i) { + int session = msg.session_texture(i); ServerUser *su = qhUsers.value(session); - if (su && ! su->qbaTexture.isEmpty()) { + if (su && !su->qbaTexture.isEmpty()) { mpus.set_session(session); mpus.set_texture(blob(su->qbaTexture)); sendMessage(uSource, mpus); @@ -2083,10 +2104,10 @@ void Server::msgRequestBlob(ServerUser *uSource, MumbleProto::RequestBlob &msg) } if (ntextures) mpus.clear_texture(); - for (int i=0;i<ncomments;++i) { - int session = msg.session_comment(i); + for (int i = 0; i < ncomments; ++i) { + int session = msg.session_comment(i); ServerUser *su = qhUsers.value(session); - if (su && ! su->qsComment.isEmpty()) { + if (su && !su->qsComment.isEmpty()) { mpus.set_session(session); mpus.set_comment(u8(su->qsComment)); sendMessage(uSource, mpus); diff --git a/src/murmur/Meta.cpp b/src/murmur/Meta.cpp index e149ebeba..a1d30c7a3 100644 --- a/src/murmur/Meta.cpp +++ b/src/murmur/Meta.cpp @@ -6,38 +6,38 @@ #include "Meta.h" #include "Connection.h" +#include "EnvUtils.h" +#include "FFDHE.h" #include "Net.h" -#include "ServerDB.h" -#include "Server.h" #include "OSInfo.h" -#include "Version.h" #include "SSL.h" -#include "EnvUtils.h" -#include "FFDHE.h" +#include "Server.h" +#include "ServerDB.h" +#include "Version.h" #include <QtCore/QCoreApplication> #include <QtCore/QSettings> #ifdef Q_OS_WIN -# include <QtCore/QStandardPaths> +# include <QtCore/QStandardPaths> #endif #include <QtNetwork/QHostInfo> #include <QtNetwork/QNetworkInterface> #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) -# include <QtNetwork/QSslDiffieHellmanParameters> +# include <QtNetwork/QSslDiffieHellmanParameters> #endif #ifdef Q_OS_WIN -# include <qos2.h> +# include <qos2.h> #else -# include <pwd.h> -# include <sys/resource.h> +# include <pwd.h> +# include <sys/resource.h> #endif -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - #include <QRandomGenerator> +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) +# include <QRandomGenerator> #endif MetaParams Meta::mp; @@ -47,43 +47,43 @@ HANDLE Meta::hQoS = nullptr; #endif MetaParams::MetaParams() { - qsPassword = QString(); - usPort = DEFAULT_MUMBLE_PORT; - iTimeout = 30; - iMaxBandwidth = 72000; - iMaxUsers = 1000; - iMaxUsersPerChannel = 0; - iMaxListenersPerChannel = -1; + qsPassword = QString(); + usPort = DEFAULT_MUMBLE_PORT; + iTimeout = 30; + iMaxBandwidth = 72000; + iMaxUsers = 1000; + iMaxUsersPerChannel = 0; + iMaxListenersPerChannel = -1; iMaxListenerProxiesPerUser = -1; - iMaxTextMessageLength = 5000; - iMaxImageMessageLength = 131072; - legacyPasswordHash = false; - kdfIterations = -1; - bAllowHTML = true; - iDefaultChan = 0; - bRememberChan = true; - iRememberChanDuration = 0; - qsWelcomeText = QString(); - qsWelcomeTextFile = QString(); - qsDatabase = QString(); - iSQLiteWAL = 0; - iDBPort = 0; - qsDBusService = "net.sourceforge.mumble.murmur"; - qsDBDriver = "QSQLITE"; - qsLogfile = "murmur.log"; + iMaxTextMessageLength = 5000; + iMaxImageMessageLength = 131072; + legacyPasswordHash = false; + kdfIterations = -1; + bAllowHTML = true; + iDefaultChan = 0; + bRememberChan = true; + iRememberChanDuration = 0; + qsWelcomeText = QString(); + qsWelcomeTextFile = QString(); + qsDatabase = QString(); + iSQLiteWAL = 0; + iDBPort = 0; + qsDBusService = "net.sourceforge.mumble.murmur"; + qsDBDriver = "QSQLITE"; + qsLogfile = "murmur.log"; iLogDays = 31; - iObfuscate = 0; - bSendVersion = true; - bBonjour = true; - bAllowPing = true; - bCertRequired = false; + iObfuscate = 0; + bSendVersion = true; + bBonjour = true; + bAllowPing = true; + bCertRequired = false; bForceExternalAuth = false; - iBanTries = 10; - iBanTimeframe = 120; - iBanTime = 300; + iBanTries = 10; + iBanTimeframe = 120; + iBanTime = 300; bBanSuccessful = true; #ifdef Q_OS_UNIX @@ -93,9 +93,9 @@ MetaParams::MetaParams() { iOpusThreshold = 100; iChannelNestingLimit = 10; - iChannelCountLimit = 1000; + iChannelCountLimit = 1000; - qrUserName = QRegExp(QLatin1String("[-=\\w\\[\\]\\{\\}\\(\\)\\@\\|\\.]+")); + qrUserName = QRegExp(QLatin1String("[-=\\w\\[\\]\\{\\}\\(\\)\\@\\|\\.]+")); qrChannelName = QRegExp(QLatin1String("[ \\-=\\w\\#\\[\\]\\{\\}\\(\\)\\@\\|]+")); iMessageLimit = 1; @@ -104,7 +104,7 @@ MetaParams::MetaParams() { qsCiphers = MumbleSSL::defaultOpenSSLCipherString(); bLogGroupChanges = false; - bLogACLChanges = false; + bLogACLChanges = false; qsSettings = nullptr; } @@ -127,7 +127,7 @@ MetaParams::~MetaParams() { * @param settings The QSettings object to read from. If null, the Meta's qsSettings will be used. * @return Setting if valid, default if not or setting not set. */ -template <class T> +template< class T > T MetaParams::typeCheckedFromSettings(const QString &name, const T &defaultValue, QSettings *settings) { // Use qsSettings unless a specific QSettings instance // is requested. @@ -137,12 +137,16 @@ T MetaParams::typeCheckedFromSettings(const QString &name, const T &defaultValue QVariant cfgVariable = settings->value(name, defaultValue); - if (!cfgVariable.convert(QVariant(defaultValue).type())) { // Bit convoluted as canConvert<T>() only does a static check without considering whether say a string like "blub" is actually a valid double (which convert does). - qCritical() << "Configuration variable" << name << "is of invalid format. Set to default value of" << defaultValue << "."; + if (!cfgVariable.convert( + QVariant(defaultValue) + .type())) { // Bit convoluted as canConvert<T>() only does a static check without considering whether + // say a string like "blub" is actually a valid double (which convert does). + qCritical() << "Configuration variable" << name << "is of invalid format. Set to default value of" + << defaultValue << "."; return defaultValue; } - return cfgVariable.value<T>(); + return cfgVariable.value< T >(); } void MetaParams::read(QString fname) { @@ -170,11 +174,11 @@ void MetaParams::read(QString fname) { datapaths << QDir::currentPath(); datapaths << QCoreApplication::instance()->applicationDirPath(); - foreach(const QString &p, datapaths) { - if (! p.isEmpty()) { + foreach (const QString &p, datapaths) { + if (!p.isEmpty()) { QFileInfo fi(p, "murmur.ini"); if (fi.exists() && fi.isReadable()) { - qdBasePath = QDir(p); + qdBasePath = QDir(p); qsAbsSettingsFilePath = fi.absoluteFilePath(); break; } @@ -182,15 +186,15 @@ void MetaParams::read(QString fname) { } if (qsAbsSettingsFilePath.isEmpty()) { QDir::root().mkpath(qdBasePath.absolutePath()); - qdBasePath = QDir(datapaths.at(0)); + qdBasePath = QDir(datapaths.at(0)); qsAbsSettingsFilePath = qdBasePath.absolutePath() + QLatin1String("/murmur.ini"); } } else { QFile f(fname); - if (! f.open(QIODevice::ReadOnly)) { + if (!f.open(QIODevice::ReadOnly)) { qFatal("Specified ini file %s could not be opened", qPrintable(fname)); } - qdBasePath = QFileInfo(f).absoluteDir(); + qdBasePath = QFileInfo(f).absoluteDir(); qsAbsSettingsFilePath = QFileInfo(f).absoluteFilePath(); f.close(); } @@ -198,47 +202,49 @@ void MetaParams::read(QString fname) { qsSettings = new QSettings(qsAbsSettingsFilePath, QSettings::IniFormat); qsSettings->setIniCodec("UTF-8"); - qWarning("Initializing settings from %s (basepath %s)", qPrintable(qsSettings->fileName()), qPrintable(qdBasePath.absolutePath())); + qWarning("Initializing settings from %s (basepath %s)", qPrintable(qsSettings->fileName()), + qPrintable(qdBasePath.absolutePath())); QString qsHost = qsSettings->value("host", QString()).toString(); - if (! qsHost.isEmpty()) { + if (!qsHost.isEmpty()) { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - foreach(const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), Qt::SkipEmptyParts)) { + foreach (const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), Qt::SkipEmptyParts)) { #else // Qt 5.14 introduced the Qt::SplitBehavior flags deprecating the QString fields - foreach(const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), QString::SkipEmptyParts)) { + foreach (const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), QString::SkipEmptyParts)) { #endif QHostAddress qhaddr; if (qhaddr.setAddress(host)) { qlBind << qhaddr; } else { - bool found = false; + bool found = false; QHostInfo hi = QHostInfo::fromName(host); - foreach(QHostAddress qha, hi.addresses()) { - if ((qha.protocol() == QAbstractSocket::IPv4Protocol) || (qha.protocol() == QAbstractSocket::IPv6Protocol)) { + foreach (QHostAddress qha, hi.addresses()) { + if ((qha.protocol() == QAbstractSocket::IPv4Protocol) + || (qha.protocol() == QAbstractSocket::IPv6Protocol)) { qlBind << qha; found = true; } } - if (! found) { + if (!found) { qFatal("Lookup of bind hostname %s failed", qPrintable(host)); } } } - foreach(const QHostAddress &qha, qlBind) + foreach (const QHostAddress &qha, qlBind) qWarning("Binding to address %s", qPrintable(qha.toString())); } if (qlBind.isEmpty()) { bool hasipv6 = false; bool hasipv4 = false; - int nif = 0; + int nif = 0; - QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces(); + QList< QNetworkInterface > interfaces = QNetworkInterface::allInterfaces(); if (interfaces.isEmpty()) { qWarning("Meta: Unable to acquire list of network interfaces."); } else { - foreach(const QNetworkInterface &qni, interfaces) { + foreach (const QNetworkInterface &qni, interfaces) { if (!(qni.flags() & QNetworkInterface::IsUp)) continue; if (!(qni.flags() & QNetworkInterface::IsRunning)) @@ -246,7 +252,7 @@ void MetaParams::read(QString fname) { if (qni.flags() & QNetworkInterface::IsLoopBack) continue; - foreach(const QNetworkAddressEntry &qna, qni.addressEntries()) { + foreach (const QNetworkAddressEntry &qna, qni.addressEntries()) { const QHostAddress &qha = qna.ip(); switch (qha.protocol()) { case QAbstractSocket::IPv4Protocol: @@ -284,65 +290,65 @@ void MetaParams::read(QString fname) { } } - qsPassword = typeCheckedFromSettings("serverpassword", qsPassword); - usPort = static_cast<unsigned short>(typeCheckedFromSettings("port", static_cast<uint>(usPort))); - iTimeout = typeCheckedFromSettings("timeout", iTimeout); + qsPassword = typeCheckedFromSettings("serverpassword", qsPassword); + usPort = static_cast< unsigned short >(typeCheckedFromSettings("port", static_cast< uint >(usPort))); + iTimeout = typeCheckedFromSettings("timeout", iTimeout); iMaxTextMessageLength = typeCheckedFromSettings("textmessagelength", iMaxTextMessageLength); - iMaxImageMessageLength = typeCheckedFromSettings("imagemessagelength", iMaxImageMessageLength); - legacyPasswordHash = typeCheckedFromSettings("legacypasswordhash", legacyPasswordHash); - kdfIterations = typeCheckedFromSettings("kdfiterations", -1); - bAllowHTML = typeCheckedFromSettings("allowhtml", bAllowHTML); - iMaxBandwidth = typeCheckedFromSettings("bandwidth", iMaxBandwidth); - iDefaultChan = typeCheckedFromSettings("defaultchannel", iDefaultChan); - bRememberChan = typeCheckedFromSettings("rememberchannel", bRememberChan); - iRememberChanDuration = typeCheckedFromSettings("rememberchannelduration", iRememberChanDuration); - iMaxUsers = typeCheckedFromSettings("users", iMaxUsers); - iMaxUsersPerChannel = typeCheckedFromSettings("usersperchannel", iMaxUsersPerChannel); - iMaxListenersPerChannel = typeCheckedFromSettings("listenersperchannel", iMaxListenersPerChannel); + iMaxImageMessageLength = typeCheckedFromSettings("imagemessagelength", iMaxImageMessageLength); + legacyPasswordHash = typeCheckedFromSettings("legacypasswordhash", legacyPasswordHash); + kdfIterations = typeCheckedFromSettings("kdfiterations", -1); + bAllowHTML = typeCheckedFromSettings("allowhtml", bAllowHTML); + iMaxBandwidth = typeCheckedFromSettings("bandwidth", iMaxBandwidth); + iDefaultChan = typeCheckedFromSettings("defaultchannel", iDefaultChan); + bRememberChan = typeCheckedFromSettings("rememberchannel", bRememberChan); + iRememberChanDuration = typeCheckedFromSettings("rememberchannelduration", iRememberChanDuration); + iMaxUsers = typeCheckedFromSettings("users", iMaxUsers); + iMaxUsersPerChannel = typeCheckedFromSettings("usersperchannel", iMaxUsersPerChannel); + iMaxListenersPerChannel = typeCheckedFromSettings("listenersperchannel", iMaxListenersPerChannel); iMaxListenerProxiesPerUser = typeCheckedFromSettings("listenersperuser", iMaxListenerProxiesPerUser); - qsWelcomeText = typeCheckedFromSettings("welcometext", qsWelcomeText); - qsWelcomeTextFile = typeCheckedFromSettings("welcometextfile", qsWelcomeTextFile); - bCertRequired = typeCheckedFromSettings("certrequired", bCertRequired); - bForceExternalAuth = typeCheckedFromSettings("forceExternalAuth", bForceExternalAuth); + qsWelcomeText = typeCheckedFromSettings("welcometext", qsWelcomeText); + qsWelcomeTextFile = typeCheckedFromSettings("welcometextfile", qsWelcomeTextFile); + bCertRequired = typeCheckedFromSettings("certrequired", bCertRequired); + bForceExternalAuth = typeCheckedFromSettings("forceExternalAuth", bForceExternalAuth); qsDatabase = typeCheckedFromSettings("database", qsDatabase); iSQLiteWAL = typeCheckedFromSettings("sqlite_wal", iSQLiteWAL); - qsDBDriver = typeCheckedFromSettings("dbDriver", qsDBDriver); + qsDBDriver = typeCheckedFromSettings("dbDriver", qsDBDriver); qsDBUserName = typeCheckedFromSettings("dbUsername", qsDBUserName); qsDBPassword = typeCheckedFromSettings("dbPassword", qsDBPassword); qsDBHostName = typeCheckedFromSettings("dbHost", qsDBHostName); - qsDBPrefix = typeCheckedFromSettings("dbPrefix", qsDBPrefix); - qsDBOpts = typeCheckedFromSettings("dbOpts", qsDBOpts); - iDBPort = typeCheckedFromSettings("dbPort", iDBPort); + qsDBPrefix = typeCheckedFromSettings("dbPrefix", qsDBPrefix); + qsDBOpts = typeCheckedFromSettings("dbOpts", qsDBOpts); + iDBPort = typeCheckedFromSettings("dbPort", iDBPort); - qsIceEndpoint = typeCheckedFromSettings("ice", qsIceEndpoint); - qsIceSecretRead = typeCheckedFromSettings("icesecret", qsIceSecretRead); - qsIceSecretRead = typeCheckedFromSettings("icesecretread", qsIceSecretRead); + qsIceEndpoint = typeCheckedFromSettings("ice", qsIceEndpoint); + qsIceSecretRead = typeCheckedFromSettings("icesecret", qsIceSecretRead); + qsIceSecretRead = typeCheckedFromSettings("icesecretread", qsIceSecretRead); qsIceSecretWrite = typeCheckedFromSettings("icesecretwrite", qsIceSecretRead); - qsGRPCAddress = typeCheckedFromSettings("grpc", qsGRPCAddress); - qsGRPCCert = typeCheckedFromSettings("grpccert", qsGRPCCert); - qsGRPCKey = typeCheckedFromSettings("grpckey", qsGRPCKey); + qsGRPCAddress = typeCheckedFromSettings("grpc", qsGRPCAddress); + qsGRPCCert = typeCheckedFromSettings("grpccert", qsGRPCCert); + qsGRPCKey = typeCheckedFromSettings("grpckey", qsGRPCKey); qsGRPCAuthorized = typeCheckedFromSettings("grpcauthorized", qsGRPCAuthorized); iLogDays = typeCheckedFromSettings("logdays", iLogDays); - qsDBus = typeCheckedFromSettings("dbus", qsDBus); + qsDBus = typeCheckedFromSettings("dbus", qsDBus); qsDBusService = typeCheckedFromSettings("dbusservice", qsDBusService); - qsLogfile = typeCheckedFromSettings("logfile", qsLogfile); - qsPid = typeCheckedFromSettings("pidfile", qsPid); + qsLogfile = typeCheckedFromSettings("logfile", qsLogfile); + qsPid = typeCheckedFromSettings("pidfile", qsPid); - qsRegName = typeCheckedFromSettings("registerName", qsRegName); + qsRegName = typeCheckedFromSettings("registerName", qsRegName); qsRegPassword = typeCheckedFromSettings("registerPassword", qsRegPassword); - qsRegHost = typeCheckedFromSettings("registerHostname", qsRegHost); + qsRegHost = typeCheckedFromSettings("registerHostname", qsRegHost); qsRegLocation = typeCheckedFromSettings("registerLocation", qsRegLocation); - qurlRegWeb = QUrl(typeCheckedFromSettings("registerUrl", qurlRegWeb).toString()); - bBonjour = typeCheckedFromSettings("bonjour", bBonjour); + qurlRegWeb = QUrl(typeCheckedFromSettings("registerUrl", qurlRegWeb).toString()); + bBonjour = typeCheckedFromSettings("bonjour", bBonjour); - iBanTries = typeCheckedFromSettings("autobanAttempts", iBanTries); - iBanTimeframe = typeCheckedFromSettings("autobanTimeframe", iBanTimeframe); - iBanTime = typeCheckedFromSettings("autobanTime", iBanTime); + iBanTries = typeCheckedFromSettings("autobanAttempts", iBanTries); + iBanTimeframe = typeCheckedFromSettings("autobanTimeframe", iBanTimeframe); + iBanTime = typeCheckedFromSettings("autobanTime", iBanTime); bBanSuccessful = typeCheckedFromSettings("autobanSuccessfulConnections", bBanSuccessful); qvSuggestVersion = MumbleVersion::getRaw(qsSettings->value("suggestVersion").toString()); @@ -358,12 +364,12 @@ void MetaParams::read(QString fname) { qvSuggestPushToTalk = QVariant(); bLogGroupChanges = typeCheckedFromSettings("loggroupchanges", bLogGroupChanges); - bLogACLChanges = typeCheckedFromSettings("logaclchanges", bLogACLChanges); + bLogACLChanges = typeCheckedFromSettings("logaclchanges", bLogACLChanges); iOpusThreshold = typeCheckedFromSettings("opusthreshold", iOpusThreshold); iChannelNestingLimit = typeCheckedFromSettings("channelnestinglimit", iChannelNestingLimit); - iChannelCountLimit = typeCheckedFromSettings("channelcountlimit", iChannelCountLimit); + iChannelCountLimit = typeCheckedFromSettings("channelcountlimit", iChannelCountLimit); #ifdef Q_OS_UNIX qsName = qsSettings->value("uname").toString(); @@ -372,13 +378,13 @@ void MetaParams::read(QString fname) { bool requested = true; if (qsName.isEmpty()) { // default server user name - qsName = "mumble-server"; + qsName = "mumble-server"; requested = false; } struct passwd *pw = getpwnam(qPrintable(qsName)); if (pw) { - uiUid = pw->pw_uid; - uiGid = pw->pw_gid; + uiUid = pw->pw_uid; + uiGid = pw->pw_gid; qsHome = QString::fromUtf8(pw->pw_dir); } else if (requested) { qFatal("Cannot find username %s", qPrintable(qsName)); @@ -387,7 +393,7 @@ void MetaParams::read(QString fname) { } #endif - qrUserName = QRegExp(typeCheckedFromSettings("username", qrUserName.pattern())); + qrUserName = QRegExp(typeCheckedFromSettings("username", qrUserName.pattern())); qrChannelName = QRegExp(typeCheckedFromSettings("channelname", qrChannelName.pattern())); iMessageLimit = typeCheckedFromSettings("messagelimit", 1); @@ -396,7 +402,7 @@ void MetaParams::read(QString fname) { bool bObfuscate = typeCheckedFromSettings("obfuscate", false); if (bObfuscate) { qWarning("IP address obfuscation enabled."); -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) iObfuscate = QRandomGenerator::global()->generate(); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor @@ -404,47 +410,50 @@ void MetaParams::read(QString fname) { #endif } bSendVersion = typeCheckedFromSettings("sendversion", bSendVersion); - bAllowPing = typeCheckedFromSettings("allowping", bAllowPing); + bAllowPing = typeCheckedFromSettings("allowping", bAllowPing); if (!loadSSLSettings()) { qFatal("MetaParams: Failed to load SSL settings. See previous errors."); } QStringList hosts; - foreach(const QHostAddress &qha, qlBind) { - hosts << qha.toString(); - } - qmConfig.insert(QLatin1String("host"),hosts.join(" ")); - qmConfig.insert(QLatin1String("password"),qsPassword); - qmConfig.insert(QLatin1String("port"),QString::number(usPort)); - qmConfig.insert(QLatin1String("timeout"),QString::number(iTimeout)); + foreach (const QHostAddress &qha, qlBind) { hosts << qha.toString(); } + qmConfig.insert(QLatin1String("host"), hosts.join(" ")); + qmConfig.insert(QLatin1String("password"), qsPassword); + qmConfig.insert(QLatin1String("port"), QString::number(usPort)); + qmConfig.insert(QLatin1String("timeout"), QString::number(iTimeout)); qmConfig.insert(QLatin1String("textmessagelength"), QString::number(iMaxTextMessageLength)); - qmConfig.insert(QLatin1String("legacypasswordhash"), legacyPasswordHash ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("legacypasswordhash"), + legacyPasswordHash ? QLatin1String("true") : QLatin1String("false")); qmConfig.insert(QLatin1String("kdfiterations"), QString::number(kdfIterations)); qmConfig.insert(QLatin1String("allowhtml"), bAllowHTML ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("bandwidth"),QString::number(iMaxBandwidth)); - qmConfig.insert(QLatin1String("users"),QString::number(iMaxUsers)); - qmConfig.insert(QLatin1String("defaultchannel"),QString::number(iDefaultChan)); - qmConfig.insert(QLatin1String("rememberchannel"),bRememberChan ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("rememberchannelduration"),QString::number(iRememberChanDuration)); - qmConfig.insert(QLatin1String("welcometext"),qsWelcomeText); - qmConfig.insert(QLatin1String("welcometextfile"),qsWelcomeTextFile); - qmConfig.insert(QLatin1String("registername"),qsRegName); - qmConfig.insert(QLatin1String("registerpassword"),qsRegPassword); - qmConfig.insert(QLatin1String("registerhostname"),qsRegHost); + qmConfig.insert(QLatin1String("bandwidth"), QString::number(iMaxBandwidth)); + qmConfig.insert(QLatin1String("users"), QString::number(iMaxUsers)); + qmConfig.insert(QLatin1String("defaultchannel"), QString::number(iDefaultChan)); + qmConfig.insert(QLatin1String("rememberchannel"), bRememberChan ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("rememberchannelduration"), QString::number(iRememberChanDuration)); + qmConfig.insert(QLatin1String("welcometext"), qsWelcomeText); + qmConfig.insert(QLatin1String("welcometextfile"), qsWelcomeTextFile); + qmConfig.insert(QLatin1String("registername"), qsRegName); + qmConfig.insert(QLatin1String("registerpassword"), qsRegPassword); + qmConfig.insert(QLatin1String("registerhostname"), qsRegHost); qmConfig.insert(QLatin1String("registerlocation"), qsRegLocation); - qmConfig.insert(QLatin1String("registerurl"),qurlRegWeb.toString()); + qmConfig.insert(QLatin1String("registerurl"), qurlRegWeb.toString()); qmConfig.insert(QLatin1String("bonjour"), bBonjour ? QLatin1String("true") : QLatin1String("false")); qmConfig.insert(QLatin1String("certificate"), QString::fromUtf8(qscCert.toPem())); qmConfig.insert(QLatin1String("key"), QString::fromUtf8(qskKey.toPem())); - qmConfig.insert(QLatin1String("obfuscate"),bObfuscate ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("username"),qrUserName.pattern()); - qmConfig.insert(QLatin1String("channelname"),qrChannelName.pattern()); + qmConfig.insert(QLatin1String("obfuscate"), bObfuscate ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("username"), qrUserName.pattern()); + qmConfig.insert(QLatin1String("channelname"), qrChannelName.pattern()); qmConfig.insert(QLatin1String("certrequired"), bCertRequired ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("forceExternalAuth"), bForceExternalAuth ? QLatin1String("true") : QLatin1String("false")); - qmConfig.insert(QLatin1String("suggestversion"), qvSuggestVersion.isNull() ? QString() : qvSuggestVersion.toString()); - qmConfig.insert(QLatin1String("suggestpositional"), qvSuggestPositional.isNull() ? QString() : qvSuggestPositional.toString()); - qmConfig.insert(QLatin1String("suggestpushtotalk"), qvSuggestPushToTalk.isNull() ? QString() : qvSuggestPushToTalk.toString()); + qmConfig.insert(QLatin1String("forceExternalAuth"), + bForceExternalAuth ? QLatin1String("true") : QLatin1String("false")); + qmConfig.insert(QLatin1String("suggestversion"), + qvSuggestVersion.isNull() ? QString() : qvSuggestVersion.toString()); + qmConfig.insert(QLatin1String("suggestpositional"), + qvSuggestPositional.isNull() ? QString() : qvSuggestPositional.toString()); + qmConfig.insert(QLatin1String("suggestpushtotalk"), + qvSuggestPushToTalk.isNull() ? QString() : qvSuggestPushToTalk.toString()); qmConfig.insert(QLatin1String("opusthreshold"), QString::number(iOpusThreshold)); qmConfig.insert(QLatin1String("channelnestinglimit"), QString::number(iChannelNestingLimit)); qmConfig.insert(QLatin1String("channelcountlimit"), QString::number(iChannelCountLimit)); @@ -458,27 +467,27 @@ bool MetaParams::loadSSLSettings() { QString tmpCiphersStr = typeCheckedFromSettings("sslCiphers", qsCiphers); - QString qsSSLCert = qsSettings->value("sslCert").toString(); - QString qsSSLKey = qsSettings->value("sslKey").toString(); - QString qsSSLCA = qsSettings->value("sslCA").toString(); + QString qsSSLCert = qsSettings->value("sslCert").toString(); + QString qsSSLKey = qsSettings->value("sslKey").toString(); + QString qsSSLCA = qsSettings->value("sslCA").toString(); QString qsSSLDHParams = typeCheckedFromSettings(QLatin1String("sslDHParams"), QString(QLatin1String("@ffdhe2048"))); qbaPassPhrase = qsSettings->value("sslPassPhrase").toByteArray(); QSslCertificate tmpCert; - QList<QSslCertificate> tmpCA; - QList<QSslCertificate> tmpIntermediates; + QList< QSslCertificate > tmpCA; + QList< QSslCertificate > tmpIntermediates; QSslKey tmpKey; QByteArray tmpDHParams; - QList<QSslCipher> tmpCiphers; + QList< QSslCipher > tmpCiphers; - if (! qsSSLCA.isEmpty()) { + if (!qsSSLCA.isEmpty()) { QFile pem(qsSSLCA); if (pem.open(QIODevice::ReadOnly)) { QByteArray qba = pem.readAll(); pem.close(); - QList<QSslCertificate> ql = QSslCertificate::fromData(qba); + QList< QSslCertificate > ql = QSslCertificate::fromData(qba); if (ql.isEmpty()) { qCritical("MetaParams: Failed to parse any CA certificates from %s", qPrintable(qsSSLCA)); return false; @@ -493,7 +502,7 @@ bool MetaParams::loadSSLSettings() { QByteArray crt, key; - if (! qsSSLCert.isEmpty()) { + if (!qsSSLCert.isEmpty()) { QFile pem(qsSSLCert); if (pem.open(QIODevice::ReadOnly)) { crt = pem.readAll(); @@ -503,7 +512,7 @@ bool MetaParams::loadSSLSettings() { return false; } } - if (! qsSSLKey.isEmpty()) { + if (!qsSSLKey.isEmpty()) { QFile pem(qsSSLKey); if (pem.open(QIODevice::ReadOnly)) { key = pem.readAll(); @@ -514,13 +523,13 @@ bool MetaParams::loadSSLSettings() { } } - if (! key.isEmpty() || ! crt.isEmpty()) { - if (! key.isEmpty()) { + if (!key.isEmpty() || !crt.isEmpty()) { + if (!key.isEmpty()) { tmpKey = Server::privateKeyFromPEM(key, qbaPassPhrase); } - if (tmpKey.isNull() && ! crt.isEmpty()) { + if (tmpKey.isNull() && !crt.isEmpty()) { tmpKey = Server::privateKeyFromPEM(crt, qbaPassPhrase); - if (! tmpKey.isNull()) + if (!tmpKey.isNull()) qCritical("MetaParams: Using private key found in certificate file."); } if (tmpKey.isNull()) { @@ -528,9 +537,9 @@ bool MetaParams::loadSSLSettings() { return false; } - QList<QSslCertificate> ql = QSslCertificate::fromData(crt); + QList< QSslCertificate > ql = QSslCertificate::fromData(crt); ql << QSslCertificate::fromData(key); - for (int i=0;i<ql.size(); ++i) { + for (int i = 0; i < ql.size(); ++i) { const QSslCertificate &c = ql.at(i); if (Server::isKeyForCert(tmpKey, c)) { tmpCert = c; @@ -551,18 +560,17 @@ bool MetaParams::loadSSLSettings() { QByteArray dhparams; #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) - if (! qsSSLDHParams.isEmpty()) { + if (!qsSSLDHParams.isEmpty()) { if (qsSSLDHParams.startsWith(QLatin1String("@"))) { - QString group = qsSSLDHParams.mid(1).trimmed(); + QString group = qsSSLDHParams.mid(1).trimmed(); QByteArray pem = FFDHE::PEMForNamedGroup(group); if (pem.isEmpty()) { QStringList names = FFDHE::NamedGroups(); QStringList atNames; - foreach (QString name, names) { - atNames << QLatin1String("@") + name; - } + foreach (QString name, names) { atNames << QLatin1String("@") + name; } QString supported = atNames.join(QLatin1String(", ")); - qFatal("MetaParms: Diffie-Hellman parameters with name '%s' is not available. (Supported: %s)", qPrintable(qsSSLDHParams), qPrintable(supported)); + qFatal("MetaParms: Diffie-Hellman parameters with name '%s' is not available. (Supported: %s)", + qPrintable(qsSSLDHParams), qPrintable(supported)); } dhparams = pem; } else { @@ -576,7 +584,7 @@ bool MetaParams::loadSSLSettings() { } } - if (! dhparams.isEmpty()) { + if (!dhparams.isEmpty()) { QSslDiffieHellmanParameters qdhp = QSslDiffieHellmanParameters::fromEncoded(dhparams); if (qdhp.isValid()) { tmpDHParams = dhparams; @@ -587,16 +595,19 @@ bool MetaParams::loadSSLSettings() { } #else QString qsSSLDHParamsIniValue = qsSettings->value(QLatin1String("sslDHParams")).toString(); - if (! qsSSLDHParamsIniValue.isEmpty()) { - qFatal("MetaParams: This version of Murmur does not support Diffie-Hellman parameters (sslDHParams). Murmur will not start unless you remove the option from your murmur.ini file."); + if (!qsSSLDHParamsIniValue.isEmpty()) { + qFatal("MetaParams: This version of Murmur does not support Diffie-Hellman parameters (sslDHParams). Murmur " + "will not start unless you remove the option from your murmur.ini file."); return false; } #endif { - QList<QSslCipher> ciphers = MumbleSSL::ciphersFromOpenSSLCipherString(tmpCiphersStr); + QList< QSslCipher > ciphers = MumbleSSL::ciphersFromOpenSSLCipherString(tmpCiphersStr); if (ciphers.isEmpty()) { - qCritical("MetaParams: Invalid sslCiphers option. Either the cipher string is invalid or none of the ciphers are available: \"%s\"", qPrintable(qsCiphers)); + qCritical("MetaParams: Invalid sslCiphers option. Either the cipher string is invalid or none of the " + "ciphers are available: \"%s\"", + qPrintable(qsCiphers)); return false; } @@ -606,7 +617,7 @@ bool MetaParams::loadSSLSettings() { // Hellman cipher suites in order to guarantee that we do not // use Qt's default Diffie-Hellman parameters. { - QList<QSslCipher> filtered; + QList< QSslCipher > filtered; foreach (QSslCipher c, ciphers) { if (c.keyExchangeMethod() == QLatin1String("DH")) { continue; @@ -615,8 +626,8 @@ bool MetaParams::loadSSLSettings() { } if (ciphers.size() != filtered.size()) { qWarning("MetaParams: Warning: all cipher suites in sslCiphers using Diffie-Hellman key exchange " - "have been removed. Qt %s does not support custom Diffie-Hellman parameters.", - qVersion()); + "have been removed. Qt %s does not support custom Diffie-Hellman parameters.", + qVersion()); } tmpCiphers = filtered; @@ -626,19 +637,17 @@ bool MetaParams::loadSSLSettings() { #endif QStringList pref; - foreach (QSslCipher c, tmpCiphers) { - pref << c.name(); - } + foreach (QSslCipher c, tmpCiphers) { pref << c.name(); } qWarning("MetaParams: TLS cipher preference is \"%s\"", qPrintable(pref.join(QLatin1String(":")))); } - qscCert = tmpCert; - qlCA = tmpCA; + qscCert = tmpCert; + qlCA = tmpCA; qlIntermediates = tmpIntermediates; - qskKey = tmpKey; - qbaDHParams = tmpDHParams; - qsCiphers = tmpCiphersStr; - qlCiphers = tmpCiphers; + qskKey = tmpKey; + qbaDHParams = tmpDHParams; + qsCiphers = tmpCiphersStr; + qlCiphers = tmpCiphers; qmConfig.insert(QLatin1String("certificate"), QString::fromUtf8(qscCert.toPem())); qmConfig.insert(QLatin1String("key"), QString::fromUtf8(qskKey.toPem())); @@ -661,7 +670,7 @@ Meta::Meta() { qWarning("Meta: Failed to load qWave.dll, no QoS available"); } else { FreeLibrary(hLib); - if (! QOSCreateHandle(&qvVer, &hQoS)) + if (!QOSCreateHandle(&qvVer, &hQoS)) qWarning("Meta: Failed to create QOS2 handle"); else Connection::setQoS(hQoS); @@ -700,23 +709,23 @@ bool Meta::reloadSSLSettings() { } void Meta::getOSInfo() { - qsOS = OSInfo::getOS(); + qsOS = OSInfo::getOS(); qsOSVersion = OSInfo::getOSDisplayableVersion(); } void Meta::bootAll() { - QList<int> ql = ServerDB::getBootServers(); - foreach(int snum, ql) + QList< int > ql = ServerDB::getBootServers(); + foreach (int snum, ql) boot(snum); } bool Meta::boot(int srvnum) { if (qhServers.contains(srvnum)) return false; - if (! ServerDB::serverExists(srvnum)) + if (!ServerDB::serverExists(srvnum)) return false; Server *s = new Server(srvnum, this); - if (! s->bValid) { + if (!s->bValid) { delete s; return false; } @@ -725,8 +734,8 @@ bool Meta::boot(int srvnum) { #ifdef Q_OS_UNIX unsigned int sockets = 19; // Base - foreach(s, qhServers) { - sockets += 11; // Listen sockets, signal pipes etc. + foreach (s, qhServers) { + sockets += 11; // Listen sockets, signal pipes etc. sockets += s->iMaxUsers; // One per user } @@ -746,7 +755,10 @@ bool Meta::boot(int srvnum) { } } if (r.rlim_cur < sockets) - qCritical("Current booted servers require minimum %d file descriptors when all slots are full, but only %lu file descriptors are allowed for this process. Your server will crash and burn; read the FAQ for details.", sockets, static_cast<unsigned long>(r.rlim_cur)); + qCritical( + "Current booted servers require minimum %d file descriptors when all slots are full, but only %lu file " + "descriptors are allowed for this process. Your server will crash and burn; read the FAQ for details.", + sockets, static_cast< unsigned long >(r.rlim_cur)); } #endif @@ -762,7 +774,7 @@ void Meta::kill(int srvnum) { } void Meta::killAll() { - foreach(Server *s, qhServers) { + foreach (Server *s, qhServers) { emit stopped(s); delete s; } @@ -771,7 +783,7 @@ void Meta::killAll() { void Meta::successfulConnectionFrom(const QHostAddress &addr) { if (!mp.bBanSuccessful) { - QList<Timer> &ql = qhAttempts[addr]; + QList< Timer > &ql = qhAttempts[addr]; // Seems like this is the most efficient way to clear the list, given: // 1. ql.clear() allocates a new array // 2. ql has less than iBanAttempts members @@ -793,10 +805,10 @@ bool Meta::banCheck(const QHostAddress &addr) { qhBans.remove(addr); } - QList<Timer> &ql = qhAttempts[addr]; + QList< Timer > &ql = qhAttempts[addr]; ql.append(Timer()); - while (! ql.isEmpty() && (ql.at(0).elapsed() > (1000000ULL * mp.iBanTimeframe))) + while (!ql.isEmpty() && (ql.at(0).elapsed() > (1000000ULL * mp.iBanTimeframe))) ql.removeFirst(); if (ql.count() > mp.iBanTries) { diff --git a/src/murmur/Meta.h b/src/murmur/Meta.h index 0c75fa733..4f98bc87e 100644 --- a/src/murmur/Meta.h +++ b/src/murmur/Meta.h @@ -9,7 +9,7 @@ #include "Timer.h" #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include <QtCore/QDir> @@ -18,8 +18,8 @@ #include <QtCore/QVariant> #include <QtNetwork/QHostAddress> #include <QtNetwork/QSslCertificate> -#include <QtNetwork/QSslKey> #include <QtNetwork/QSslCipher> +#include <QtNetwork/QSslKey> class Server; class QSettings; @@ -28,7 +28,7 @@ class MetaParams { public: QDir qdBasePath; - QList<QHostAddress> qlBind; + QList< QHostAddress > qlBind; unsigned short usPort; int iTimeout; int iMaxBandwidth; @@ -115,22 +115,22 @@ public: /// Simply put: it contains any certificates /// that aren't the main certificate, or "leaf" /// certificate. - QList<QSslCertificate> qlIntermediates; + QList< QSslCertificate > qlIntermediates; /// qlCA contains all certificates read from /// the PEM bundle pointed to by murmur.ini's /// sslCA option. - QList<QSslCertificate> qlCA; + QList< QSslCertificate > qlCA; /// qlCiphers contains the list of supported /// cipher suites. - QList<QSslCipher> qlCiphers; + QList< QSslCipher > qlCiphers; QByteArray qbaDHParams; QByteArray qbaPassPhrase; QString qsCiphers; - QMap<QString, QString> qmConfig; + QMap< QString, QString > qmConfig; #ifdef Q_OS_UNIX unsigned int uiUid, uiGid; @@ -163,50 +163,51 @@ public: bool loadSSLSettings(); private: - template <class T> + template< class T > T typeCheckedFromSettings(const QString &name, const T &variable, QSettings *settings = nullptr); }; class Meta : public QObject { - private: - Q_OBJECT; - Q_DISABLE_COPY(Meta); - public: - static MetaParams mp; - QHash<int, Server *> qhServers; - QHash<QHostAddress, QList<Timer> > qhAttempts; - QHash<QHostAddress, Timer> qhBans; - QString qsOS, qsOSVersion; - Timer tUptime; +private: + Q_OBJECT; + Q_DISABLE_COPY(Meta); + +public: + static MetaParams mp; + QHash< int, Server * > qhServers; + QHash< QHostAddress, QList< Timer > > qhAttempts; + QHash< QHostAddress, Timer > qhBans; + QString qsOS, qsOSVersion; + Timer tUptime; #ifdef Q_OS_WIN - static HANDLE hQoS; + static HANDLE hQoS; #endif - Meta(); - ~Meta(); - - /// reloadSSLSettings reloads Murmur's MetaParams's - /// SSL settings, and updates the certificate and - /// private key for all virtual servers that use the - /// Meta server's certificate and private key. - bool reloadSSLSettings(); - - void bootAll(); - bool boot(int); - bool banCheck(const QHostAddress &); - - /// Called whenever we get a successful connection from a client. - /// Used to reset autoban tracking for the address. - void successfulConnectionFrom(const QHostAddress &); - void kill(int); - void killAll(); - void getOSInfo(); - void connectListener(QObject *); - static void getVersion(int &major, int &minor, int &patch, QString &string); - signals: - void started(Server *); - void stopped(Server *); + Meta(); + ~Meta(); + + /// reloadSSLSettings reloads Murmur's MetaParams's + /// SSL settings, and updates the certificate and + /// private key for all virtual servers that use the + /// Meta server's certificate and private key. + bool reloadSSLSettings(); + + void bootAll(); + bool boot(int); + bool banCheck(const QHostAddress &); + + /// Called whenever we get a successful connection from a client. + /// Used to reset autoban tracking for the address. + void successfulConnectionFrom(const QHostAddress &); + void kill(int); + void killAll(); + void getOSInfo(); + void connectListener(QObject *); + static void getVersion(int &major, int &minor, int &patch, QString &string); +signals: + void started(Server *); + void stopped(Server *); }; extern Meta *meta; diff --git a/src/murmur/MurmurGRPCImpl.cpp b/src/murmur/MurmurGRPCImpl.cpp index a555bccd1..3299ddc94 100644 --- a/src/murmur/MurmurGRPCImpl.cpp +++ b/src/murmur/MurmurGRPCImpl.cpp @@ -4,25 +4,25 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef Q_MOC_RUN -# include <boost/function.hpp> +# include <boost/function.hpp> #endif #include "Mumble.pb.h" -#include "../Message.h" #include "../Group.h" +#include "../Message.h" +#include "Channel.h" #include "MurmurGRPCImpl.h" +#include "Server.h" #include "ServerDB.h" #include "ServerUser.h" -#include "Server.h" -#include "Channel.h" #include "Utils.h" #include <chrono> -#include <QtCore/QStack> #include <QCryptographicHash> #include <QRegularExpression> +#include <QtCore/QStack> #include "MurmurRPC.proto.Wrapper.cpp" @@ -95,12 +95,12 @@ void GRPCStart() { return; } const auto &cert = meta->mp.qsGRPCCert; - const auto &key = meta->mp.qsGRPCKey; - std::shared_ptr<::grpc::ServerCredentials> credentials; + const auto &key = meta->mp.qsGRPCKey; + std::shared_ptr<::grpc::ServerCredentials > credentials; if (cert.isEmpty() || key.isEmpty()) { credentials = ::grpc::InsecureServerCredentials(); } else { - std::shared_ptr<MurmurRPCAuthenticator> authenticator(new MurmurRPCAuthenticator()); + std::shared_ptr< MurmurRPCAuthenticator > authenticator(new MurmurRPCAuthenticator()); ::grpc::SslServerCredentialsOptions options(GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY); ::grpc::SslServerCredentialsOptions::PemKeyCertPair pair; { @@ -110,7 +110,7 @@ void GRPCStart() { return; } QTextStream stream(&file); - auto contents = stream.readAll(); + auto contents = stream.readAll(); pair.cert_chain = contents.toStdString(); } { @@ -120,7 +120,7 @@ void GRPCStart() { return; } QTextStream stream(&file); - auto contents = stream.readAll(); + auto contents = stream.readAll(); pair.private_key = contents.toStdString(); } options.pem_key_cert_pairs.push_back(pair); @@ -143,7 +143,7 @@ MurmurRPCAuthenticator::MurmurRPCAuthenticator() { QRegularExpression re("^(?:[[:xdigit:]]{2}:?){32}$"); const auto &authorized = meta->mp.qsGRPCAuthorized; - for (auto&& user : authorized.split(' ')) { + for (auto &&user : authorized.split(' ')) { if (!re.match(user).hasMatch()) { qWarning("gRPC: %s is not a valid hexadecimal SHA256 digest, ignoring", qUtf8Printable(user)); continue; @@ -153,7 +153,7 @@ MurmurRPCAuthenticator::MurmurRPCAuthenticator() { if (m_gRPCUsers.empty()) { qWarning("gRPC Security is enabled but no users are authorized to use the interface\n" - "Please set grpcauthorized to a list of authorized clients"); + "Please set grpcauthorized to a list of authorized clients"); } return; @@ -165,7 +165,8 @@ bool MurmurRPCAuthenticator::IsBlocking() const { } // We don't use any metadata. Just check to see if the certificate fingerprint matches -grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::grpc::AuthContext *ctx, OutputMetadata *used, OutputMetadata* resp) { +grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::grpc::AuthContext *ctx, + OutputMetadata *used, OutputMetadata *resp) { QByteArray fingerprint; QString identity; QStringList identities; @@ -174,7 +175,7 @@ grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::gr (void) resp; (void) authData; - for (auto&& i : ctx->GetPeerIdentity()) { + for (auto &&i : ctx->GetPeerIdentity()) { identities.append(QString::fromUtf8(i.data(), i.length())); } if (identities.empty()) { @@ -185,7 +186,7 @@ grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::gr qDebug("Incoming connection from: %s", qUtf8Printable(identity)); - for (auto&& pem : ctx->FindPropertyValues("x509_pem_cert")) { + for (auto &&pem : ctx->FindPropertyValues("x509_pem_cert")) { QSslCertificate cert(QByteArray(pem.data(), pem.length())); if (cert.isNull()) { continue; @@ -206,12 +207,12 @@ grpc::Status MurmurRPCAuthenticator::Process(const InputMetadata &authData, ::gr return ::grpc::Status(::grpc::StatusCode::UNAUTHENTICATED, "Certificate invalid or not presented"); } -MurmurRPCImpl::MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials> credentials) { +MurmurRPCImpl::MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials > credentials) { ::grpc::ServerBuilder builder; builder.AddListeningPort(u8(address), credentials); builder.RegisterService(&m_V1Service); m_completionQueue = builder.AddCompletionQueue(); - m_server = builder.BuildAndStart(); + m_server = builder.BuildAndStart(); meta->connectListener(this); m_isRunning = true; start(); @@ -225,7 +226,7 @@ MurmurRPCImpl::~MurmurRPCImpl() { m_completionQueue->Shutdown(); while (m_completionQueue->Next(&ignored_tag, &ignored_ok)) { if (ignored_tag) { - auto op = static_cast<boost::function<void(bool)> *>(ignored_tag); + auto op = static_cast< boost::function< void(bool) > * >(ignored_tag); delete op; } } @@ -243,7 +244,7 @@ void ToRPC(const ::Server *srv, const ::Channel *c, ::MurmurRPC::Channel *rc) { } rc->set_description(u8(c->qsDesc)); rc->set_position(c->iPosition); - foreach(::Channel *chn, c->qsPermLinks) { + foreach (::Channel *chn, c->qsPermLinks) { ::MurmurRPC::Channel *linked = rc->add_links(); linked->mutable_server()->set_id(srv->iServerNum); linked->set_id(chn->iId); @@ -270,7 +271,7 @@ void ToRPC(const ::Server *srv, const ::User *u, ::MurmurRPC::User *ru) { ru->mutable_channel()->set_id(u->cChannel->iId); ru->set_comment(u8(u->qsComment)); - const auto su = static_cast<const ServerUser *>(u); + const auto su = static_cast< const ServerUser * >(u); ru->set_online_secs(su->bwr.onlineSeconds()); ru->set_bytes_per_sec(su->bwr.bandwidth()); ru->mutable_version()->set_version(su->uiVersion); @@ -293,7 +294,8 @@ void ToRPC(const ::Server *srv, const ::User *u, ::MurmurRPC::User *ru) { ru->set_address(su->haAddress.toStdString()); } -void ToRPC(const ::Server *srv, const QMap<int, QString> &info, const QByteArray &texture, ::MurmurRPC::DatabaseUser *du) { +void ToRPC(const ::Server *srv, const QMap< int, QString > &info, const QByteArray &texture, + ::MurmurRPC::DatabaseUser *du) { du->mutable_server()->set_id(srv->iServerNum); if (info.contains(::ServerDB::User_Name)) { @@ -319,7 +321,7 @@ void ToRPC(const ::Server *srv, const QMap<int, QString> &info, const QByteArray } } -void FromRPC(const ::MurmurRPC::DatabaseUser &du, QMap<int, QString> &info) { +void FromRPC(const ::MurmurRPC::DatabaseUser &du, QMap< int, QString > &info) { if (du.has_name()) { info.insert(::ServerDB::User_Name, u8(du.name())); } @@ -376,13 +378,13 @@ void ToRPC(const ::Server *srv, const ::Ban &ban, ::MurmurRPC::Ban *rb) { } void FromRPC(const ::Server *, const ::MurmurRPC::Ban &rb, ::Ban &ban) { - ban.haAddress = HostAddress(rb.address()); - ban.iMask = rb.bits(); + ban.haAddress = HostAddress(rb.address()); + ban.iMask = rb.bits(); ban.qsUsername = u8(rb.name()); - ban.qsHash = u8(rb.hash()); - ban.qsReason = u8(rb.reason()); - ban.qdtStart = QDateTime::fromTime_t(static_cast<quint32>(rb.start())).toUTC(); - ban.iDuration = rb.duration_secs(); + ban.qsHash = u8(rb.hash()); + ban.qsReason = u8(rb.reason()); + ban.qdtStart = QDateTime::fromTime_t(static_cast< quint32 >(rb.start())).toUTC(); + ban.iDuration = rb.duration_secs(); } void ToRPC(int serverID, const ::ServerDB::LogRecord &log, ::MurmurRPC::Log *rl) { @@ -398,19 +400,19 @@ void ToRPC(const ::Server *srv, const ::User *user, const ::TextMessage &message rtm->mutable_actor()->mutable_server()->set_id(srv->iServerNum); rtm->mutable_actor()->set_session(user->uiSession); - foreach(auto session, message.qlSessions) { + foreach (auto session, message.qlSessions) { auto target = rtm->add_users(); target->mutable_server()->set_id(srv->iServerNum); target->set_session(session); } - foreach(auto id, message.qlChannels) { + foreach (auto id, message.qlChannels) { auto target = rtm->add_channels(); target->mutable_server()->set_id(srv->iServerNum); target->set_id(id); } - foreach(auto id, message.qlTrees) { + foreach (auto id, message.qlTrees) { auto target = rtm->add_trees(); target->mutable_server()->set_id(srv->iServerNum); target->set_id(id); @@ -426,7 +428,7 @@ void MurmurRPCImpl::sendMetaEvent(const ::MurmurRPC::Event &e) { for (auto i = listeners.constBegin(); i != listeners.constEnd(); ++i) { auto listener = *i; listener->ref(); - auto cb = [this, listener] (::MurmurRPC::Wrapper::V1_Events *, bool ok) { + auto cb = [this, listener](::MurmurRPC::Wrapper::V1_Events *, bool ok) { if (!ok && m_metaServiceListeners.remove(listener)) { listener->deref(); } @@ -440,8 +442,10 @@ void MurmurRPCImpl::sendMetaEvent(const ::MurmurRPC::Event &e) { void MurmurRPCImpl::started(::Server *server) { server->connectListener(this); server->connectAuthenticator(this); - connect(server, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, SLOT(contextAction(const User *, const QString &, unsigned int, int))); - connect(server, SIGNAL(textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &)), this, SLOT(textMessageFilter(int &, const User *, MumbleProto::TextMessage &))); + connect(server, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, + SLOT(contextAction(const User *, const QString &, unsigned int, int))); + connect(server, SIGNAL(textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &)), this, + SLOT(textMessageFilter(int &, const User *, MumbleProto::TextMessage &))); ::MurmurRPC::Event rpcEvent; rpcEvent.set_type(::MurmurRPC::Event_Type_ServerStarted); @@ -480,9 +484,11 @@ void MurmurRPCImpl::removeAuthenticator(const ::Server *s) { } // Called when a connecting user needs to be authenticated. -void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -493,7 +499,7 @@ void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, co if (!pw.isEmpty()) { request.mutable_authenticate()->set_password(u8(pw)); } - foreach(const auto &cert, certlist) { + foreach (const auto &cert, certlist) { auto data = cert.toDer(); request.mutable_authenticate()->add_certificates(data.constData(), data.size()); } @@ -513,43 +519,44 @@ void MurmurRPCImpl::authenticateSlot(int &res, QString &uname, int sessionId, co auto &response = authenticator->request; switch (response.authenticate().status()) { - case ::MurmurRPC::Authenticator_Response_Status_Success: - if (!response.authenticate().has_id()) { - res = -3; - break; - } - res = response.authenticate().id(); - if (response.authenticate().has_name()) { - uname = u8(response.authenticate().name()); - } - { - QStringList qsl; - for (int i = 0; i < response.authenticate().groups_size(); i++) { - auto &group = response.authenticate().groups(i); - if (group.has_name()) { - qsl << u8(group.name()); - } + case ::MurmurRPC::Authenticator_Response_Status_Success: + if (!response.authenticate().has_id()) { + res = -3; + break; } - if (!qsl.isEmpty()) { - s->setTempGroups(res, sessionId, nullptr, qsl); + res = response.authenticate().id(); + if (response.authenticate().has_name()) { + uname = u8(response.authenticate().name()); } - } - break; - case ::MurmurRPC::Authenticator_Response_Status_TemporaryFailure: - res = -3; - break; - case ::MurmurRPC::Authenticator_Response_Status_Failure: - res = -1; - break; - default: - break; + { + QStringList qsl; + for (int i = 0; i < response.authenticate().groups_size(); i++) { + auto &group = response.authenticate().groups(i); + if (group.has_name()) { + qsl << u8(group.name()); + } + } + if (!qsl.isEmpty()) { + s->setTempGroups(res, sessionId, nullptr, qsl); + } + } + break; + case ::MurmurRPC::Authenticator_Response_Status_TemporaryFailure: + res = -3; + break; + case ::MurmurRPC::Authenticator_Response_Status_Failure: + res = -1; + break; + default: + break; } } // Called when a user is being registered on the server. -void MurmurRPCImpl::registerUserSlot(int &res, const QMap<int, QString> &info) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::registerUserSlot(int &res, const QMap< int, QString > &info) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -568,25 +575,26 @@ void MurmurRPCImpl::registerUserSlot(int &res, const QMap<int, QString> &info) { auto &response = authenticator->request; switch (response.register_().status()) { - case ::MurmurRPC::Authenticator_Response_Status_Success: - if (!response.register_().has_user() || !response.register_().user().has_id()) { + case ::MurmurRPC::Authenticator_Response_Status_Success: + if (!response.register_().has_user() || !response.register_().user().has_id()) { + res = -1; + break; + } + res = response.register_().user().id(); + break; + case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: + break; + default: res = -1; break; - } - res = response.register_().user().id(); - break; - case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: - break; - default: - res = -1; - break; } } // Called when a user is being deregistered on the server. void MurmurRPCImpl::unregisterUserSlot(int &res, int id) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -612,9 +620,10 @@ void MurmurRPCImpl::unregisterUserSlot(int &res, int id) { } // Called when a list of registered users is requested. -void MurmurRPCImpl::getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -645,9 +654,10 @@ void MurmurRPCImpl::getRegisteredUsersSlot(const QString &filter, QMap<int, QStr } // Called when information about a registered user is requested. -void MurmurRPCImpl::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::getRegistrationSlot(int &res, int id, QMap< int, QString > &info) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -674,9 +684,10 @@ void MurmurRPCImpl::getRegistrationSlot(int &res, int id, QMap<int, QString> &in } // Called when information about a registered user is being updated. -void MurmurRPCImpl::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); +void MurmurRPCImpl::setInfoSlot(int &res, int id, const QMap< int, QString > &info) { + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -698,21 +709,22 @@ void MurmurRPCImpl::setInfoSlot(int &res, int id, const QMap<int, QString> &info auto &response = authenticator->request; switch (response.update().status()) { - case ::MurmurRPC::Authenticator_Response_Status_Success: - res = 1; - break; - case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: - res = -1; - break; - default: - break; + case ::MurmurRPC::Authenticator_Response_Status_Success: + res = 1; + break; + case ::MurmurRPC::Authenticator_Response_Status_Fallthrough: + res = -1; + break; + default: + break; } } // Called when a texture for a registered user is being updated. void MurmurRPCImpl::setTextureSlot(int &res, int id, const QByteArray &texture) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -738,8 +750,9 @@ void MurmurRPCImpl::setTextureSlot(int &res, int id, const QByteArray &texture) // Called when a user name needs to be converted to a user ID. void MurmurRPCImpl::nameToIdSlot(int &res, const QString &name) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -764,8 +777,9 @@ void MurmurRPCImpl::nameToIdSlot(int &res, const QString &name) { // Called when a user ID needs to be converted to a user name. void MurmurRPCImpl::idToNameSlot(QString &res, int id) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -790,8 +804,9 @@ void MurmurRPCImpl::idToNameSlot(QString &res, int id) { // Called when a texture for a given registered user is requested. void MurmurRPCImpl::idToTextureSlot(QByteArray &res, int id) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto authenticator = RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream>(m_authenticators.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto authenticator = + RPCCall::Ref<::MurmurRPC::Wrapper::V1_AuthenticatorStream >(m_authenticators.value(s->iServerNum)); if (!authenticator) { return; } @@ -811,20 +826,20 @@ void MurmurRPCImpl::idToTextureSlot(QByteArray &res, int id) { auto &response = authenticator->request; if (response.find().has_user() && response.find().user().has_texture()) { const auto &texture = response.find().user().texture(); - res = QByteArray(texture.data(), texture.size()); + res = QByteArray(texture.data(), texture.size()); } } // Sends a server event to subscribed listeners. void MurmurRPCImpl::sendServerEvent(const ::Server *s, const ::MurmurRPC::Server_Event &e) { auto listeners = m_serverServiceListeners; - auto serverID = s->iServerNum; - auto i = listeners.find(serverID); + auto serverID = s->iServerNum; + auto i = listeners.find(serverID); - for ( ; i != listeners.end() && i.key() == serverID; ++i) { + for (; i != listeners.end() && i.key() == serverID; ++i) { auto listener = i.value(); listener->ref(); - auto cb = [this, listener, serverID] (::MurmurRPC::Wrapper::V1_ServerEvents *, bool ok) { + auto cb = [this, listener, serverID](::MurmurRPC::Wrapper::V1_ServerEvents *, bool ok) { if (!ok && m_serverServiceListeners.remove(serverID, listener) > 0) { listener->deref(); } @@ -836,7 +851,7 @@ void MurmurRPCImpl::sendServerEvent(const ::Server *s, const ::MurmurRPC::Server // Called when a user's state changes. void MurmurRPCImpl::userStateChanged(const ::User *user) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -847,7 +862,7 @@ void MurmurRPCImpl::userStateChanged(const ::User *user) { // Called when a user sends a text message. void MurmurRPCImpl::userTextMessage(const ::User *user, const ::TextMessage &message) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -859,7 +874,7 @@ void MurmurRPCImpl::userTextMessage(const ::User *user, const ::TextMessage &mes // Called when a user successfully connects to a server. void MurmurRPCImpl::userConnected(const ::User *user) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -870,7 +885,7 @@ void MurmurRPCImpl::userConnected(const ::User *user) { // Called when a user disconnects from a server. void MurmurRPCImpl::userDisconnected(const ::User *user) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); removeUserActiveContextActions(s, user); @@ -883,7 +898,7 @@ void MurmurRPCImpl::userDisconnected(const ::User *user) { // Called when a channel's state changes. void MurmurRPCImpl::channelStateChanged(const ::Channel *channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -894,7 +909,7 @@ void MurmurRPCImpl::channelStateChanged(const ::Channel *channel) { // Called when a channel is created. void MurmurRPCImpl::channelCreated(const ::Channel *channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -905,7 +920,7 @@ void MurmurRPCImpl::channelCreated(const ::Channel *channel) { // Called when a channel is removed. void MurmurRPCImpl::channelRemoved(const ::Channel *channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); ::MurmurRPC::Server_Event event; event.mutable_server()->set_id(s->iServerNum); @@ -916,8 +931,8 @@ void MurmurRPCImpl::channelRemoved(const ::Channel *channel) { // Called when a user sends a text message. void MurmurRPCImpl::textMessageFilter(int &res, const User *user, MumbleProto::TextMessage &message) { - ::Server *s = qobject_cast< ::Server *> (sender()); - auto filter = RPCCall::Ref<::MurmurRPC::Wrapper::V1_TextMessageFilter>(m_textMessageFilters.value(s->iServerNum)); + ::Server *s = qobject_cast<::Server * >(sender()); + auto filter = RPCCall::Ref<::MurmurRPC::Wrapper::V1_TextMessageFilter >(m_textMessageFilters.value(s->iServerNum)); if (!filter) { return; } @@ -955,15 +970,15 @@ void MurmurRPCImpl::textMessageFilter(int &res, const User *user, MumbleProto::T } auto &response = filter->request; - res = response.action(); + res = response.action(); switch (response.action()) { - case ::MurmurRPC::TextMessage_Filter_Action_Accept: - if (response.has_message() && response.message().has_text()) { - message.set_message(response.message().text()); - } - break; - default: - break; + case ::MurmurRPC::TextMessage_Filter_Action_Accept: + if (response.has_message() && response.message().has_text()) { + message.set_message(response.message().text()); + } + break; + default: + break; } } @@ -1021,7 +1036,7 @@ void MurmurRPCImpl::removeActiveContextActions(const ::Server *s) { // Called when a context action event is triggered. void MurmurRPCImpl::contextAction(const ::User *user, const QString &action, unsigned int session, int channel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); if (!hasActiveContextAction(s, user, action)) { return; @@ -1041,13 +1056,13 @@ void MurmurRPCImpl::contextAction(const ::User *user, const QString &action, uns ca.mutable_channel()->set_id(channel); } - auto serverID = s->iServerNum; + auto serverID = s->iServerNum; auto listeners = this->m_contextActionListeners.value(serverID); - auto i = listeners.find(action); - for ( ; i != listeners.end() && i.key() == action; ++i) { + auto i = listeners.find(action); + for (; i != listeners.end() && i.key() == action; ++i) { auto listener = i.value(); listener->ref(); - auto cb = [this, listener, serverID, action] (::MurmurRPC::Wrapper::V1_ContextActionEvents *, bool ok) { + auto cb = [this, listener, serverID, action](::MurmurRPC::Wrapper::V1_ContextActionEvents *, bool ok) { if (!ok && m_contextActionListeners[serverID].remove(action, listener) > 0) { listener->deref(); } @@ -1067,16 +1082,14 @@ void MurmurRPCImpl::contextAction(const ::User *user, const QString &action, uns return user; } -template <class T> -::ServerUser *MustUser(const ::Server *server, const T &msg) { +template< class T >::ServerUser *MustUser(const ::Server *server, const T &msg) { if (!msg.has_user()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing user"); } return MustUser(server, msg.user().session()); } -template <> -::ServerUser *MustUser(const Server *server, const ::MurmurRPC::User &msg) { +template<>::ServerUser *MustUser(const Server *server, const ::MurmurRPC::User &msg) { if (!msg.has_session()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing user session"); } @@ -1099,8 +1112,7 @@ template <> return server; } -template <class T> -::Server *MustServer(const T &msg) { +template< class T >::Server *MustServer(const T &msg) { if (!msg.has_server()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing server"); } @@ -1110,16 +1122,14 @@ template <class T> return MustServer(msg.server().id()); } -template <> -::Server *MustServer(const ::MurmurRPC::Server &msg) { +template<>::Server *MustServer(const ::MurmurRPC::Server &msg) { if (!msg.has_id()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing server id"); } return MustServer(msg.id()); } -template <class T> -int MustServerID(const T &msg) { +template< class T > int MustServerID(const T &msg) { if (!msg.has_server()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing server"); } @@ -1160,16 +1170,14 @@ int MustServerID(const ::MurmurRPC::Server &msg) { return channel; } -template <class T> -::Channel *MustChannel(const Server *server, const T &msg) { +template< class T >::Channel *MustChannel(const Server *server, const T &msg) { if (!msg.has_channel()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing channel"); } return MustChannel(server, msg.channel()); } -template <> -::Channel *MustChannel(const Server *server, const ::MurmurRPC::Channel &msg) { +template<>::Channel *MustChannel(const Server *server, const ::MurmurRPC::Channel &msg) { if (!msg.has_id()) { throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing channel id"); } @@ -1179,7 +1187,7 @@ template <> // Qt event listener for RPCExecEvents. void MurmurRPCImpl::customEvent(QEvent *evt) { if (evt->type() == EXEC_QEVENT) { - auto event = static_cast<RPCExecEvent *>(evt); + auto event = static_cast< RPCExecEvent * >(evt); try { event->execute(); } catch (::grpc::Status &ex) { @@ -1200,7 +1208,7 @@ void MurmurRPCImpl::run() { break; } if (tag != nullptr) { - auto op = static_cast<boost::function<void(bool)> *>(tag); + auto op = static_cast< boost::function< void(bool) > * >(tag); (*op)(ok); delete op; } @@ -1219,1044 +1227,1039 @@ void MurmurRPCImpl::run() { namespace MurmurRPC { namespace Wrapper { -void V1_ServerCreate::impl(bool) { - auto id = ServerDB::addServer(); - - ::MurmurRPC::Server rpcServer; - rpcServer.set_id(id); - end(rpcServer); -} - -void V1_ServerQuery::impl(bool) { - ::MurmurRPC::Server_List list; + void V1_ServerCreate::impl(bool) { + auto id = ServerDB::addServer(); - foreach(int id, ServerDB::getAllServers()) { - auto rpcServer = list.add_servers(); - rpcServer->set_id(id); - try { - auto server = MustServer(id); - rpcServer->set_running(true); - rpcServer->mutable_uptime()->set_secs(server->tUptime.elapsed()/1000000LL); - } catch (::grpc::Status &ex) { - } + ::MurmurRPC::Server rpcServer; + rpcServer.set_id(id); + end(rpcServer); } - end(list); -} + void V1_ServerQuery::impl(bool) { + ::MurmurRPC::Server_List list; -void V1_ServerGet::impl(bool) { - auto serverID = MustServerID(request); + foreach (int id, ServerDB::getAllServers()) { + auto rpcServer = list.add_servers(); + rpcServer->set_id(id); + try { + auto server = MustServer(id); + rpcServer->set_running(true); + rpcServer->mutable_uptime()->set_secs(server->tUptime.elapsed() / 1000000LL); + } catch (::grpc::Status &ex) { + } + } - ::MurmurRPC::Server rpcServer; - rpcServer.set_id(serverID); - rpcServer.set_running(false); - try { - auto server = MustServer(serverID); - rpcServer.set_running(true); - rpcServer.mutable_uptime()->set_secs(server->tUptime.elapsed()/1000000LL); - } catch (::grpc::Status &ex) { + end(list); } - end(rpcServer); -} -void V1_ServerStart::impl(bool) { - auto serverID = MustServerID(request); + void V1_ServerGet::impl(bool) { + auto serverID = MustServerID(request); - if (!meta->boot(serverID)) { - throw ::grpc::Status(::grpc::UNKNOWN, "server could not be started, or is already started"); + ::MurmurRPC::Server rpcServer; + rpcServer.set_id(serverID); + rpcServer.set_running(false); + try { + auto server = MustServer(serverID); + rpcServer.set_running(true); + rpcServer.mutable_uptime()->set_secs(server->tUptime.elapsed() / 1000000LL); + } catch (::grpc::Status &ex) { + } + end(rpcServer); } - end(); -} + void V1_ServerStart::impl(bool) { + auto serverID = MustServerID(request); -void V1_ServerStop::impl(bool) { - auto server = MustServer(request); - meta->kill(server->iServerNum); - end(); -} + if (!meta->boot(serverID)) { + throw ::grpc::Status(::grpc::UNKNOWN, "server could not be started, or is already started"); + } -void V1_ServerRemove::impl(bool) { - auto serverID = MustServerID(request); + end(); + } - if (meta->qhServers.value(serverID)) { - throw ::grpc::Status(::grpc::FAILED_PRECONDITION, "cannot remove started server"); + void V1_ServerStop::impl(bool) { + auto server = MustServer(request); + meta->kill(server->iServerNum); + end(); } - ServerDB::deleteServer(serverID); - end(); -} + void V1_ServerRemove::impl(bool) { + auto serverID = MustServerID(request); -void V1_ServerEvents::impl(bool) { - auto server = MustServer(request); - rpc->m_serverServiceListeners.insert(server->iServerNum, this); -} + if (meta->qhServers.value(serverID)) { + throw ::grpc::Status(::grpc::FAILED_PRECONDITION, "cannot remove started server"); + } -void V1_ServerEvents::done(bool) { - auto &ssls = rpc->m_serverServiceListeners; - auto i = std::find(ssls.begin(), ssls.end(), this); - if (i != ssls.end()) { - ssls.erase(i); + ServerDB::deleteServer(serverID); + end(); } - deref(); -} -void V1_GetUptime::impl(bool) { - ::MurmurRPC::Uptime uptime; - uptime.set_secs(meta->tUptime.elapsed()/1000000LL); - end(uptime); -} + void V1_ServerEvents::impl(bool) { + auto server = MustServer(request); + rpc->m_serverServiceListeners.insert(server->iServerNum, this); + } -void V1_GetVersion::impl(bool) { - ::MurmurRPC::Version version; - int major, minor, patch; - QString release; - Meta::getVersion(major, minor, patch, release); - version.set_version(major << 16 | minor << 8 | patch); - version.set_release(u8(release)); - end(version); -} + void V1_ServerEvents::done(bool) { + auto &ssls = rpc->m_serverServiceListeners; + auto i = std::find(ssls.begin(), ssls.end(), this); + if (i != ssls.end()) { + ssls.erase(i); + } + deref(); + } -void V1_Events::impl(bool) { - rpc->m_metaServiceListeners.insert(this); -} + void V1_GetUptime::impl(bool) { + ::MurmurRPC::Uptime uptime; + uptime.set_secs(meta->tUptime.elapsed() / 1000000LL); + end(uptime); + } -void V1_Events::done(bool) { - auto &msls = rpc->m_metaServiceListeners; - auto i = std::find(msls.begin(), msls.end(), this); - if (i != msls.end()) { - msls.erase(i); + void V1_GetVersion::impl(bool) { + ::MurmurRPC::Version version; + int major, minor, patch; + QString release; + Meta::getVersion(major, minor, patch, release); + version.set_version(major << 16 | minor << 8 | patch); + version.set_release(u8(release)); + end(version); } - deref(); -} -void V1_ContextActionAdd::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + void V1_Events::impl(bool) { rpc->m_metaServiceListeners.insert(this); } - if (!request.has_action()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); - } - if (!request.has_text()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing text"); - } - if (!request.has_context()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing context"); + void V1_Events::done(bool) { + auto &msls = rpc->m_metaServiceListeners; + auto i = std::find(msls.begin(), msls.end(), this); + if (i != msls.end()) { + msls.erase(i); + } + deref(); } - rpc->addActiveContextAction(server, user, u8(request.action())); + void V1_ContextActionAdd::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); - ::MumbleProto::ContextActionModify mpcam; - mpcam.set_action(request.action()); - mpcam.set_text(request.text()); - mpcam.set_context(request.context()); - mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Add); - server->sendMessage(user, mpcam); + if (!request.has_action()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + } + if (!request.has_text()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing text"); + } + if (!request.has_context()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing context"); + } - end(); -} + rpc->addActiveContextAction(server, user, u8(request.action())); -void V1_ContextActionRemove::impl(bool) { - auto server = MustServer(request); + ::MumbleProto::ContextActionModify mpcam; + mpcam.set_action(request.action()); + mpcam.set_text(request.text()); + mpcam.set_context(request.context()); + mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Add); + server->sendMessage(user, mpcam); - if (!request.has_action()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + end(); } - auto action = u8(request.action()); + void V1_ContextActionRemove::impl(bool) { + auto server = MustServer(request); - ::MumbleProto::ContextActionModify mpcam; - mpcam.set_action(request.action()); - mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Remove); + if (!request.has_action()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + } - if (request.has_user()) { - // Remove context action from specific user - auto user = MustUser(server, request); - rpc->removeActiveContextAction(server, user, action); - server->sendMessage(user, mpcam); - } else { - // Remove context action from all users - foreach(::ServerUser *user, server->qhUsers) { - if (user->sState != ServerUser::Authenticated) { - continue; - } + auto action = u8(request.action()); + + ::MumbleProto::ContextActionModify mpcam; + mpcam.set_action(request.action()); + mpcam.set_operation(::MumbleProto::ContextActionModify_Operation_Remove); + + if (request.has_user()) { + // Remove context action from specific user + auto user = MustUser(server, request); rpc->removeActiveContextAction(server, user, action); server->sendMessage(user, mpcam); + } else { + // Remove context action from all users + foreach (::ServerUser *user, server->qhUsers) { + if (user->sState != ServerUser::Authenticated) { + continue; + } + rpc->removeActiveContextAction(server, user, action); + server->sendMessage(user, mpcam); + } } + + end(); } - end(); -} + void V1_ContextActionEvents::impl(bool) { + auto server = MustServer(request); -void V1_ContextActionEvents::impl(bool) { - auto server = MustServer(request); + if (!request.has_action()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + } - if (!request.has_action()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing action"); + rpc->m_contextActionListeners[server->iServerNum].insert(u8(request.action()), this); } - rpc->m_contextActionListeners[server->iServerNum].insert(u8(request.action()), this); -} - -void V1_ContextActionEvents::done(bool) { - auto server = MustServer(request); - auto &cals = rpc->m_contextActionListeners; - auto &scals = cals[server->iServerNum]; + void V1_ContextActionEvents::done(bool) { + auto server = MustServer(request); + auto &cals = rpc->m_contextActionListeners; + auto &scals = cals[server->iServerNum]; - auto i = std::find(scals.begin(), scals.end(), this); - if (i != scals.end()) { - scals.erase(i); - } - deref(); - if (scals.isEmpty()) { - auto i = std::find(cals.begin(), cals.end(), scals); - if (i != cals.end()) { - cals.erase(i); + auto i = std::find(scals.begin(), scals.end(), this); + if (i != scals.end()) { + scals.erase(i); + } + deref(); + if (scals.isEmpty()) { + auto i = std::find(cals.begin(), cals.end(), scals); + if (i != cals.end()) { + cals.erase(i); + } } } -} -void V1_TextMessageSend::impl(bool) { - auto server = MustServer(request); + void V1_TextMessageSend::impl(bool) { + auto server = MustServer(request); - ::MumbleProto::TextMessage tm; - tm.set_message(request.text()); - if (request.has_actor() && request.actor().has_session()) { - tm.set_actor(request.actor().session()); - } - for (int i = 0; i < request.users_size(); i++) { - if (request.users(i).has_session()) { - tm.add_session(request.users(i).session()); + ::MumbleProto::TextMessage tm; + tm.set_message(request.text()); + if (request.has_actor() && request.actor().has_session()) { + tm.set_actor(request.actor().session()); } - } - for (int i = 0; i < request.channels_size(); i++) { - if (request.channels(i).has_id()) { - tm.add_channel_id(request.channels(i).id()); + for (int i = 0; i < request.users_size(); i++) { + if (request.users(i).has_session()) { + tm.add_session(request.users(i).session()); + } } - } - for (int i = 0; i < request.trees_size(); i++) { - if (request.trees(i).has_id()) { - tm.add_tree_id(request.trees(i).id()); + for (int i = 0; i < request.channels_size(); i++) { + if (request.channels(i).has_id()) { + tm.add_channel_id(request.channels(i).id()); + } } - } - - server->sendTextMessageGRPC(tm); - - end(); -} - -void V1_TextMessageFilter::impl(bool) { - auto onInitialize = [this] (V1_TextMessageFilter *, bool ok) { - if (!ok) { - finish(ok); - return; + for (int i = 0; i < request.trees_size(); i++) { + if (request.trees(i).has_id()) { + tm.add_tree_id(request.trees(i).id()); + } } - auto server = MustServer(request); - QMutexLocker l(&rpc->qmTextMessageFilterLock); - rpc->removeTextMessageFilter(server); - rpc->m_textMessageFilters.insert(server->iServerNum, this); - }; - stream.Read(&request, callback(onInitialize)); -} - -void V1_TextMessageFilter::done(bool) { - auto server = MustServer(request); - auto filter = rpc->m_textMessageFilters.value(server->iServerNum); - if (filter == this) { - rpc->m_textMessageFilters.remove(server->iServerNum); - } - deref(); -} -void V1_LogQuery::impl(bool) { - auto serverID = MustServerID(request); + server->sendTextMessageGRPC(tm); - int total = ::ServerDB::getLogLen(serverID); - if (total < 0) { - throw ::grpc::Status(::grpc::StatusCode::UNAVAILABLE, "could not access database"); + end(); } - ::MurmurRPC::Log_List list; - list.mutable_server()->set_id(serverID); - list.set_total(total); - - if (!request.has_min() || !request.has_max()) { - end(list); - return; + void V1_TextMessageFilter::impl(bool) { + auto onInitialize = [this](V1_TextMessageFilter *, bool ok) { + if (!ok) { + finish(ok); + return; + } + auto server = MustServer(request); + QMutexLocker l(&rpc->qmTextMessageFilterLock); + rpc->removeTextMessageFilter(server); + rpc->m_textMessageFilters.insert(server->iServerNum, this); + }; + stream.Read(&request, callback(onInitialize)); } - list.set_min(request.min()); - list.set_max(request.max()); - auto dblog = ::ServerDB::getLog(serverID, request.min(), request.max()); - foreach(const ::ServerDB::LogRecord &record, dblog) { - auto rpcLog = list.add_entries(); - ToRPC(serverID, record, rpcLog); + void V1_TextMessageFilter::done(bool) { + auto server = MustServer(request); + auto filter = rpc->m_textMessageFilters.value(server->iServerNum); + if (filter == this) { + rpc->m_textMessageFilters.remove(server->iServerNum); + } + deref(); } - end(list); -} + void V1_LogQuery::impl(bool) { + auto serverID = MustServerID(request); -void V1_ConfigGet::impl(bool) { - auto serverID = MustServerID(request); - auto config = ServerDB::getAllConf(serverID); + int total = ::ServerDB::getLogLen(serverID); + if (total < 0) { + throw ::grpc::Status(::grpc::StatusCode::UNAVAILABLE, "could not access database"); + } - ::MurmurRPC::Config rpcConfig; - rpcConfig.mutable_server()->set_id(serverID); - auto &fields = *rpcConfig.mutable_fields(); - for (auto i = config.constBegin(); i != config.constEnd(); ++i) { - fields[u8(i.key())] = u8(i.value()); - } + ::MurmurRPC::Log_List list; + list.mutable_server()->set_id(serverID); + list.set_total(total); - end(rpcConfig); -} + if (!request.has_min() || !request.has_max()) { + end(list); + return; + } + list.set_min(request.min()); + list.set_max(request.max()); -void V1_ConfigGetField::impl(bool) { - auto serverID = MustServerID(request); - if (!request.has_key()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); - } - ::MurmurRPC::Config_Field rpcField; - rpcField.mutable_server()->set_id(serverID); - rpcField.set_key(request.key()); - rpcField.set_value(u8(ServerDB::getConf(serverID, u8(request.key()), QVariant()).toString())); - end(rpcField); -} + auto dblog = ::ServerDB::getLog(serverID, request.min(), request.max()); + foreach (const ::ServerDB::LogRecord &record, dblog) { + auto rpcLog = list.add_entries(); + ToRPC(serverID, record, rpcLog); + } -void V1_ConfigSetField::impl(bool) { - auto serverID = MustServerID(request); - if (!request.has_key()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); - } - QString key = u8(request.key()); - QString value; - if (request.has_value()) { - value = u8(request.value()); - } - ServerDB::setConf(serverID, key, value); - try { - auto server = MustServer(serverID); - server->setLiveConf(key, value); - } catch (::grpc::Status &ex) { + end(list); } - end(); -} + void V1_ConfigGet::impl(bool) { + auto serverID = MustServerID(request); + auto config = ServerDB::getAllConf(serverID); -void V1_ConfigGetDefault::impl(bool) { - ::MurmurRPC::Config rpcConfig; - auto &fields = *rpcConfig.mutable_fields(); - for (auto i = meta->mp.qmConfig.constBegin(); i != meta->mp.qmConfig.constEnd(); ++i) { - fields[u8(i.key())] = u8(i.value()); - } + ::MurmurRPC::Config rpcConfig; + rpcConfig.mutable_server()->set_id(serverID); + auto &fields = *rpcConfig.mutable_fields(); + for (auto i = config.constBegin(); i != config.constEnd(); ++i) { + fields[u8(i.key())] = u8(i.value()); + } - end(rpcConfig); -} + end(rpcConfig); + } -void V1_ChannelQuery::impl(bool) { - auto server = MustServer(request); + void V1_ConfigGetField::impl(bool) { + auto serverID = MustServerID(request); + if (!request.has_key()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); + } + ::MurmurRPC::Config_Field rpcField; + rpcField.mutable_server()->set_id(serverID); + rpcField.set_key(request.key()); + rpcField.set_value(u8(ServerDB::getConf(serverID, u8(request.key()), QVariant()).toString())); + end(rpcField); + } - ::MurmurRPC::Channel_List list; - list.mutable_server()->set_id(server->iServerNum); + void V1_ConfigSetField::impl(bool) { + auto serverID = MustServerID(request); + if (!request.has_key()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing key"); + } + QString key = u8(request.key()); + QString value; + if (request.has_value()) { + value = u8(request.value()); + } + ServerDB::setConf(serverID, key, value); + try { + auto server = MustServer(serverID); + server->setLiveConf(key, value); + } catch (::grpc::Status &ex) { + } - foreach(const ::Channel *channel, server->qhChannels) { - auto rpcChannel = list.add_channels(); - ToRPC(server, channel, rpcChannel); + end(); } - end(list); -} + void V1_ConfigGetDefault::impl(bool) { + ::MurmurRPC::Config rpcConfig; + auto &fields = *rpcConfig.mutable_fields(); + for (auto i = meta->mp.qmConfig.constBegin(); i != meta->mp.qmConfig.constEnd(); ++i) { + fields[u8(i.key())] = u8(i.value()); + } -void V1_ChannelGet::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + end(rpcConfig); + } - ::MurmurRPC::Channel rpcChannel; - ToRPC(server, channel, &rpcChannel); - end(rpcChannel); -} + void V1_ChannelQuery::impl(bool) { + auto server = MustServer(request); -void V1_ChannelAdd::impl(bool) { - auto server = MustServer(request); + ::MurmurRPC::Channel_List list; + list.mutable_server()->set_id(server->iServerNum); - if (!request.has_parent() || !request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "parent channel and name required"); - } - ::Channel *parent; - try { - parent = MustChannel(server, request.parent()); - } catch (::grpc::Status &ex) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid parent channel"); - } + foreach (const ::Channel *channel, server->qhChannels) { + auto rpcChannel = list.add_channels(); + ToRPC(server, channel, rpcChannel); + } - if (!server->canNest(parent)) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot nest channel in given parent"); + end(list); } - QString qsName = u8(request.name()); + void V1_ChannelGet::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); - ::Channel *nc; - - { - QWriteLocker wl(&server->qrwlVoiceThread); - nc = server->addChannel(parent, qsName, request.temporary(), request.position()); + ::MurmurRPC::Channel rpcChannel; + ToRPC(server, channel, &rpcChannel); + end(rpcChannel); } - nc->qsDesc = u8(request.description()); - - server->updateChannel(nc); - int newid = nc->iId; + void V1_ChannelAdd::impl(bool) { + auto server = MustServer(request); - ::MumbleProto::ChannelState mpcs; - mpcs.set_channel_id(newid); - mpcs.set_parent(parent->iId); - mpcs.set_name(request.name()); - mpcs.set_temporary(request.temporary()); - mpcs.set_position(request.position()); - mpcs.set_description(request.description()); - server->sendAll(mpcs); + if (!request.has_parent() || !request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "parent channel and name required"); + } + ::Channel *parent; + try { + parent = MustChannel(server, request.parent()); + } catch (::grpc::Status &ex) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid parent channel"); + } - ::MurmurRPC::Channel resChannel; - ToRPC(server, nc, &resChannel); - end(resChannel); -} + if (!server->canNest(parent)) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot nest channel in given parent"); + } -void V1_ChannelRemove::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + QString qsName = u8(request.name()); - if (!channel->cParent) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot remove the root channel"); - } + ::Channel *nc; - server->removeChannel(channel); + { + QWriteLocker wl(&server->qrwlVoiceThread); + nc = server->addChannel(parent, qsName, request.temporary(), request.position()); + } - end(); -} + nc->qsDesc = u8(request.description()); -void V1_ChannelUpdate::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + server->updateChannel(nc); + int newid = nc->iId; - ::MumbleProto::ChannelState mpcs; - mpcs.set_channel_id(channel->iId); - for (int i = 0; i < request.links_size(); i++) { - if (!request.links(i).has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel link"); - } - mpcs.add_links(request.links(i).id()); - } - if (request.has_parent()) { - if (!request.parent().has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel parent"); - } - mpcs.set_parent(request.parent().id()); - } - if (request.has_name()) { + ::MumbleProto::ChannelState mpcs; + mpcs.set_channel_id(newid); + mpcs.set_parent(parent->iId); mpcs.set_name(request.name()); - } - if (request.has_position()) { + mpcs.set_temporary(request.temporary()); mpcs.set_position(request.position()); - } - if (request.has_description()) { mpcs.set_description(request.description()); - } + server->sendAll(mpcs); - QString err; - if (!server->setChannelStateGRPC(mpcs, err)) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, u8(err)); + ::MurmurRPC::Channel resChannel; + ToRPC(server, nc, &resChannel); + end(resChannel); } - ::MurmurRPC::Channel rpcChannel; - ToRPC(server, channel, &rpcChannel); - end(rpcChannel); -} + void V1_ChannelRemove::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); -void V1_UserQuery::impl(bool) { - auto server = MustServer(request); + if (!channel->cParent) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "cannot remove the root channel"); + } - ::MurmurRPC::User_List list; - list.mutable_server()->set_id(server->iServerNum); + server->removeChannel(channel); - foreach(const ::ServerUser *user, server->qhUsers) { - if (user->sState != ServerUser::Authenticated) { - continue; - } - auto rpcUser = list.add_users(); - ToRPC(server, user, rpcUser); + end(); } - end(list); -} + void V1_ChannelUpdate::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); + + ::MumbleProto::ChannelState mpcs; + mpcs.set_channel_id(channel->iId); + for (int i = 0; i < request.links_size(); i++) { + if (!request.links(i).has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel link"); + } + mpcs.add_links(request.links(i).id()); + } + if (request.has_parent()) { + if (!request.parent().has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid channel parent"); + } + mpcs.set_parent(request.parent().id()); + } + if (request.has_name()) { + mpcs.set_name(request.name()); + } + if (request.has_position()) { + mpcs.set_position(request.position()); + } + if (request.has_description()) { + mpcs.set_description(request.description()); + } -void V1_UserGet::impl(bool) { - auto server = MustServer(request); + QString err; + if (!server->setChannelStateGRPC(mpcs, err)) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, u8(err)); + } - ::MurmurRPC::User rpcUser; + ::MurmurRPC::Channel rpcChannel; + ToRPC(server, channel, &rpcChannel); + end(rpcChannel); + } - if (request.has_session()) { - // Lookup user by session - auto user = MustUser(server, request); - ToRPC(server, user, &rpcUser); - end(rpcUser); - return; - } else if (request.has_name()) { - // Lookup user by name - QString qsName = u8(request.name()); - foreach(const ::ServerUser *user, server->qhUsers) { + void V1_UserQuery::impl(bool) { + auto server = MustServer(request); + + ::MurmurRPC::User_List list; + list.mutable_server()->set_id(server->iServerNum); + + foreach (const ::ServerUser *user, server->qhUsers) { if (user->sState != ServerUser::Authenticated) { continue; } - if (user->qsName == qsName) { - ToRPC(server, user, &rpcUser); - end(rpcUser); - return; - } + auto rpcUser = list.add_users(); + ToRPC(server, user, rpcUser); } - throw ::grpc::Status(::grpc::NOT_FOUND, "invalid user"); + + end(list); } - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "session or name required"); -} + void V1_UserGet::impl(bool) { + auto server = MustServer(request); -void V1_UserUpdate::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + ::MurmurRPC::User rpcUser; - auto channel = user->cChannel; - if (request.has_channel()) { - channel = MustChannel(server, request.channel()); - } - auto mute = user->bMute; - if (request.has_mute()) { - mute = request.mute(); - } - auto deaf = user->bDeaf; - if (request.has_deaf()) { - deaf = request.deaf(); - } - auto suppress = user->bSuppress; - if (request.has_suppress()) { - suppress = request.suppress(); - } - auto prioritySpeaker = user->bPrioritySpeaker; - if (request.has_priority_speaker()) { - prioritySpeaker = request.priority_speaker(); - } - auto name = user->qsName; - if (request.has_name()) { - name = u8(request.name()); - } - auto comment = user->qsComment; - if (request.has_comment()) { - comment = u8(request.comment()); + if (request.has_session()) { + // Lookup user by session + auto user = MustUser(server, request); + ToRPC(server, user, &rpcUser); + end(rpcUser); + return; + } else if (request.has_name()) { + // Lookup user by name + QString qsName = u8(request.name()); + foreach (const ::ServerUser *user, server->qhUsers) { + if (user->sState != ServerUser::Authenticated) { + continue; + } + if (user->qsName == qsName) { + ToRPC(server, user, &rpcUser); + end(rpcUser); + return; + } + } + throw ::grpc::Status(::grpc::NOT_FOUND, "invalid user"); + } + + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "session or name required"); } - server->setUserState(user, channel, mute, deaf, suppress, prioritySpeaker, name, comment); + void V1_UserUpdate::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); - ::MurmurRPC::User rpcUser; - ToRPC(server, user, &rpcUser); - end(rpcUser); -} + auto channel = user->cChannel; + if (request.has_channel()) { + channel = MustChannel(server, request.channel()); + } + auto mute = user->bMute; + if (request.has_mute()) { + mute = request.mute(); + } + auto deaf = user->bDeaf; + if (request.has_deaf()) { + deaf = request.deaf(); + } + auto suppress = user->bSuppress; + if (request.has_suppress()) { + suppress = request.suppress(); + } + auto prioritySpeaker = user->bPrioritySpeaker; + if (request.has_priority_speaker()) { + prioritySpeaker = request.priority_speaker(); + } + auto name = user->qsName; + if (request.has_name()) { + name = u8(request.name()); + } + auto comment = user->qsComment; + if (request.has_comment()) { + comment = u8(request.comment()); + } -void V1_UserKick::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + server->setUserState(user, channel, mute, deaf, suppress, prioritySpeaker, name, comment); - ::MumbleProto::UserRemove mpur; - mpur.set_session(user->uiSession); - if (request.has_reason()) { - mpur.set_reason(request.reason()); + ::MurmurRPC::User rpcUser; + ToRPC(server, user, &rpcUser); + end(rpcUser); } - if (request.has_actor() && request.actor().has_session()) { - mpur.set_actor(request.actor().session()); + + void V1_UserKick::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + + ::MumbleProto::UserRemove mpur; + mpur.set_session(user->uiSession); + if (request.has_reason()) { + mpur.set_reason(request.reason()); + } + if (request.has_actor() && request.actor().has_session()) { + mpur.set_actor(request.actor().session()); + } + server->sendAll(mpur); + user->disconnectSocket(); + + end(); } - server->sendAll(mpur); - user->disconnectSocket(); - end(); -} + void V1_TreeQuery::impl(bool) { + auto server = MustServer(request); -void V1_TreeQuery::impl(bool) { - auto server = MustServer(request); + auto channel = MustChannel(server, 0); + ::MurmurRPC::Tree root; - auto channel = MustChannel(server, 0); - ::MurmurRPC::Tree root; + QQueue< QPair< const ::Channel *, ::MurmurRPC::Tree * > > qQueue; + qQueue.enqueue(qMakePair(channel, &root)); - QQueue< QPair<const ::Channel *, ::MurmurRPC::Tree *> > qQueue; - qQueue.enqueue(qMakePair(channel, &root)); + while (!qQueue.isEmpty()) { + auto current = qQueue.dequeue(); + auto currentChannel = current.first; + auto currentTree = current.second; - while (!qQueue.isEmpty()) { - auto current = qQueue.dequeue(); - auto currentChannel = current.first; - auto currentTree = current.second; + ToRPC(server, currentChannel, currentTree->mutable_channel()); - ToRPC(server, currentChannel, currentTree->mutable_channel()); + QList<::User * > users = currentChannel->qlUsers; + std::sort(users.begin(), users.end(), + [](const ::User *a, const ::User *b) -> bool { return ::User::lessThan(a, b); }); + foreach (const ::User *u, users) { + auto rpcUser = currentTree->add_users(); + ToRPC(server, u, rpcUser); + } - QList< ::User *> users = currentChannel->qlUsers; - std::sort(users.begin(), users.end(), [] (const ::User *a, const ::User *b) -> bool { - return ::User::lessThan(a, b); - }); - foreach(const ::User *u, users) { - auto rpcUser = currentTree->add_users(); - ToRPC(server, u, rpcUser); + QList<::Channel * > channels = currentChannel->qlChannels; + std::sort(channels.begin(), channels.end(), + [](const ::Channel *a, const ::Channel *b) -> bool { return ::Channel::lessThan(a, b); }); + foreach (const ::Channel *subChannel, channels) { + auto subTree = currentTree->add_children(); + qQueue.enqueue(qMakePair(subChannel, subTree)); + } } - QList< ::Channel *> channels = currentChannel->qlChannels; - std::sort(channels.begin(), channels.end(), [] (const ::Channel *a, const ::Channel *b) -> bool { - return ::Channel::lessThan(a, b); - }); - foreach(const ::Channel *subChannel, channels) { - auto subTree = currentTree->add_children(); - qQueue.enqueue(qMakePair(subChannel, subTree)); - } + end(root); } - end(root); -} + void V1_BansGet::impl(bool) { + auto server = MustServer(request); -void V1_BansGet::impl(bool) { - auto server = MustServer(request); + ::MurmurRPC::Ban_List list; + list.mutable_server()->set_id(server->iServerNum); + foreach (const ::Ban &ban, server->qlBans) { + auto rpcBan = list.add_bans(); + ToRPC(server, ban, rpcBan); + } - ::MurmurRPC::Ban_List list; - list.mutable_server()->set_id(server->iServerNum); - foreach(const ::Ban &ban, server->qlBans) { - auto rpcBan = list.add_bans(); - ToRPC(server, ban, rpcBan); + end(list); } - end(list); -} + void V1_BansSet::impl(bool) { + auto server = MustServer(request); + server->qlBans.clear(); -void V1_BansSet::impl(bool) { - auto server = MustServer(request); - server->qlBans.clear(); + for (int i = 0; i < request.bans_size(); i++) { + const auto &rpcBan = request.bans(i); + ::Ban ban; + FromRPC(server, rpcBan, ban); + server->qlBans << ban; + } + server->saveBans(); - for (int i = 0; i < request.bans_size(); i++) { - const auto &rpcBan = request.bans(i); - ::Ban ban; - FromRPC(server, rpcBan, ban); - server->qlBans << ban; + end(); } - server->saveBans(); - - end(); -} -void V1_ACLGet::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + void V1_ACLGet::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); - ::MurmurRPC::ACL_List list; - list.set_inherit(channel->bInheritACL); + ::MurmurRPC::ACL_List list; + list.set_inherit(channel->bInheritACL); - QStack< ::Channel *> chans; - ChanACL *acl; - ::Channel *p = channel; - while (p) { - chans.push(p); - if ((p == channel) || p->bInheritACL) { - p = p->cParent; - } else { - p = nullptr; + QStack<::Channel * > chans; + ChanACL *acl; + ::Channel *p = channel; + while (p) { + chans.push(p); + if ((p == channel) || p->bInheritACL) { + p = p->cParent; + } else { + p = nullptr; + } } - } - while (!chans.isEmpty()) { - p = chans.pop(); - foreach(acl, p->qlACL) { - if (p == channel || acl->bApplySubs) { - auto rpcACL = list.add_acls(); - ToRPC(server, acl, rpcACL); - if (p != channel) { - rpcACL->set_inherited(true); + while (!chans.isEmpty()) { + p = chans.pop(); + foreach (acl, p->qlACL) { + if (p == channel || acl->bApplySubs) { + auto rpcACL = list.add_acls(); + ToRPC(server, acl, rpcACL); + if (p != channel) { + rpcACL->set_inherited(true); + } } } } - } - p = channel->cParent; - const QSet<QString> allnames = ::Group::groupNames(channel); - foreach(const QString &name, allnames) { - ::Group *g = channel->qhGroups.value(name); - ::Group *pg = p ? ::Group::getGroup(p, name) : nullptr; - if (!g && ! pg) { - continue; - } - auto aclGroup = list.add_groups(); - ToRPC(server, g ? g : pg, aclGroup); - QSet<int> members; - if (pg) { - members = pg->members(); - } - if (g) { - foreach(auto id, g->qsAdd) { - auto rpcUser = aclGroup->add_users_add(); - rpcUser->mutable_server()->set_id(server->iServerNum); - rpcUser->set_id(id); + p = channel->cParent; + const QSet< QString > allnames = ::Group::groupNames(channel); + foreach (const QString &name, allnames) { + ::Group *g = channel->qhGroups.value(name); + ::Group *pg = p ? ::Group::getGroup(p, name) : nullptr; + if (!g && !pg) { + continue; + } + auto aclGroup = list.add_groups(); + ToRPC(server, g ? g : pg, aclGroup); + QSet< int > members; + if (pg) { + members = pg->members(); + } + if (g) { + foreach (auto id, g->qsAdd) { + auto rpcUser = aclGroup->add_users_add(); + rpcUser->mutable_server()->set_id(server->iServerNum); + rpcUser->set_id(id); + } + foreach (auto id, g->qsRemove) { + auto rpcUser = aclGroup->add_users_remove(); + rpcUser->mutable_server()->set_id(server->iServerNum); + rpcUser->set_id(id); + } + aclGroup->set_inherited(false); + members += g->qsAdd; + members -= g->qsRemove; + } else { + aclGroup->set_inherited(true); } - foreach(auto id, g->qsRemove) { - auto rpcUser = aclGroup->add_users_remove(); + foreach (auto id, members) { + auto rpcUser = aclGroup->add_users(); rpcUser->mutable_server()->set_id(server->iServerNum); rpcUser->set_id(id); } - aclGroup->set_inherited(false); - members += g->qsAdd; - members -= g->qsRemove; - } else { - aclGroup->set_inherited(true); - } - foreach(auto id, members) { - auto rpcUser = aclGroup->add_users(); - rpcUser->mutable_server()->set_id(server->iServerNum); - rpcUser->set_id(id); } - } - end(list); -} + end(list); + } -void V1_ACLSet::impl(bool) { - auto server = MustServer(request); - auto channel = MustChannel(server, request); + void V1_ACLSet::impl(bool) { + auto server = MustServer(request); + auto channel = MustChannel(server, request); - ::Group *g; - ::ChanACL *acl; + ::Group *g; + ::ChanACL *acl; - { - QWriteLocker wl(&server->qrwlVoiceThread); + { + QWriteLocker wl(&server->qrwlVoiceThread); - QHash<QString, QSet<int> > hOldTemp; - foreach(g, channel->qhGroups) { - hOldTemp.insert(g->qsName, g->qsTemporary); - delete g; - } - foreach(acl, channel->qlACL) { - delete acl; - } + QHash< QString, QSet< int > > hOldTemp; + foreach (g, channel->qhGroups) { + hOldTemp.insert(g->qsName, g->qsTemporary); + delete g; + } + foreach (acl, channel->qlACL) { delete acl; } - channel->qhGroups.clear(); - channel->qlACL.clear(); + channel->qhGroups.clear(); + channel->qlACL.clear(); - channel->bInheritACL = request.inherit(); + channel->bInheritACL = request.inherit(); - for (int i = 0; i < request.groups_size(); i++) { - auto &rpcGroup = request.groups(i); - auto name = u8(rpcGroup.name()); - g = new ::Group(channel, name); - g->bInherit = rpcGroup.inherit(); - g->bInheritable = rpcGroup.inheritable(); - for (int j = 0; j < rpcGroup.users_add_size(); j++) { - g->qsAdd.insert(rpcGroup.users_add(j).id()); - } - for (int j = 0; j < rpcGroup.users_remove_size(); j++) { - g->qsRemove.insert(rpcGroup.users_remove(j).id()); - } - g->qsTemporary = hOldTemp.value(name); - } - for (int i = 0; i < request.acls_size(); i++) { - auto &rpcACL = request.acls(i); - acl = new ChanACL(channel); - acl->bApplyHere = rpcACL.apply_here(); - acl->bApplySubs = rpcACL.apply_subs(); - if (rpcACL.has_user()) { - acl->iUserId = rpcACL.user().id(); + for (int i = 0; i < request.groups_size(); i++) { + auto &rpcGroup = request.groups(i); + auto name = u8(rpcGroup.name()); + g = new ::Group(channel, name); + g->bInherit = rpcGroup.inherit(); + g->bInheritable = rpcGroup.inheritable(); + for (int j = 0; j < rpcGroup.users_add_size(); j++) { + g->qsAdd.insert(rpcGroup.users_add(j).id()); + } + for (int j = 0; j < rpcGroup.users_remove_size(); j++) { + g->qsRemove.insert(rpcGroup.users_remove(j).id()); + } + g->qsTemporary = hOldTemp.value(name); } - if (rpcACL.has_group() && rpcACL.group().has_name()) { - acl->qsGroup = u8(rpcACL.group().name()); + for (int i = 0; i < request.acls_size(); i++) { + auto &rpcACL = request.acls(i); + acl = new ChanACL(channel); + acl->bApplyHere = rpcACL.apply_here(); + acl->bApplySubs = rpcACL.apply_subs(); + if (rpcACL.has_user()) { + acl->iUserId = rpcACL.user().id(); + } + if (rpcACL.has_group() && rpcACL.group().has_name()) { + acl->qsGroup = u8(rpcACL.group().name()); + } + acl->pDeny = static_cast< ChanACL::Permissions >(rpcACL.deny()) & ChanACL::All; + acl->pAllow = static_cast< ChanACL::Permissions >(rpcACL.allow()) & ChanACL::All; } - acl->pDeny = static_cast<ChanACL::Permissions>(rpcACL.deny()) & ChanACL::All; - acl->pAllow = static_cast<ChanACL::Permissions>(rpcACL.allow()) & ChanACL::All; } - } - server->clearACLCache(); - server->updateChannel(channel); + server->clearACLCache(); + server->updateChannel(channel); - end(); -} - -void V1_ACLGetEffectivePermissions::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); - auto channel = MustChannel(server, request); - - auto flags = int(server->effectivePermissions(user, channel)); - - ::MurmurRPC::ACL rpcACL; - rpcACL.set_allow(::MurmurRPC::ACL_Permission(flags)); - end(rpcACL); -} + end(); + } -void V1_ACLAddTemporaryGroup::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); - auto channel = MustChannel(server, request); + void V1_ACLGetEffectivePermissions::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + auto channel = MustChannel(server, request); - if (!request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); - } + auto flags = int(server->effectivePermissions(user, channel)); - QString qsgroup = u8(request.name()); - if (qsgroup.isEmpty()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + ::MurmurRPC::ACL rpcACL; + rpcACL.set_allow(::MurmurRPC::ACL_Permission(flags)); + end(rpcACL); } - { - QWriteLocker wl(&server->qrwlVoiceThread); + void V1_ACLAddTemporaryGroup::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + auto channel = MustChannel(server, request); - ::Group *g = channel->qhGroups.value(qsgroup); - if (!g) { - g = new ::Group(channel, qsgroup); + if (!request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); } - g->qsTemporary.insert(-user->uiSession); - } + QString qsgroup = u8(request.name()); + if (qsgroup.isEmpty()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + } - server->clearACLCache(user); + { + QWriteLocker wl(&server->qrwlVoiceThread); - end(); -} + ::Group *g = channel->qhGroups.value(qsgroup); + if (!g) { + g = new ::Group(channel, qsgroup); + } -void V1_ACLRemoveTemporaryGroup::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); - auto channel = MustChannel(server, request); + g->qsTemporary.insert(-user->uiSession); + } - if (!request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); - } + server->clearACLCache(user); - QString qsgroup = u8(request.name()); - if (qsgroup.isEmpty()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + end(); } - { - QWriteLocker wl(&server->qrwlVoiceThread); + void V1_ACLRemoveTemporaryGroup::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + auto channel = MustChannel(server, request); - ::Group *g = channel->qhGroups.value(qsgroup); - if (!g) { - g = new ::Group(channel, qsgroup); + if (!request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); } - g->qsTemporary.remove(-user->uiSession); - } + QString qsgroup = u8(request.name()); + if (qsgroup.isEmpty()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "empty name"); + } - server->clearACLCache(user); + { + QWriteLocker wl(&server->qrwlVoiceThread); - end(); -} + ::Group *g = channel->qhGroups.value(qsgroup); + if (!g) { + g = new ::Group(channel, qsgroup); + } -void V1_AuthenticatorStream::impl(bool) { - auto onInitialize = [this] (V1_AuthenticatorStream *, bool ok) { - if (!ok) { - finish(ok); - return; - } - if (!request.has_initialize()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing initialize"); + g->qsTemporary.remove(-user->uiSession); } - auto server = MustServer(request.initialize()); - QMutexLocker l(&rpc->qmAuthenticatorsLock); - rpc->removeAuthenticator(server); - rpc->m_authenticators.insert(server->iServerNum, this); - }; - stream.Read(&request, callback(onInitialize)); -} -void V1_AuthenticatorStream::done(bool) { - auto i = std::find(rpc->m_authenticators.begin(), rpc->m_authenticators.end(), this); - if (i != rpc->m_authenticators.end()) { - rpc->m_authenticators.erase(i); + server->clearACLCache(user); + + end(); } - deref(); -} -void V1_DatabaseUserQuery::impl(bool) { - auto server = MustServer(request); + void V1_AuthenticatorStream::impl(bool) { + auto onInitialize = [this](V1_AuthenticatorStream *, bool ok) { + if (!ok) { + finish(ok); + return; + } + if (!request.has_initialize()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing initialize"); + } + auto server = MustServer(request.initialize()); + QMutexLocker l(&rpc->qmAuthenticatorsLock); + rpc->removeAuthenticator(server); + rpc->m_authenticators.insert(server->iServerNum, this); + }; + stream.Read(&request, callback(onInitialize)); + } - QString filter; - if (request.has_filter()) { - filter = u8(request.filter()); + void V1_AuthenticatorStream::done(bool) { + auto i = std::find(rpc->m_authenticators.begin(), rpc->m_authenticators.end(), this); + if (i != rpc->m_authenticators.end()) { + rpc->m_authenticators.erase(i); + } + deref(); } - auto users = server->getRegisteredUsers(filter); - ::MurmurRPC::DatabaseUser_List list; - list.mutable_server()->set_id(server->iServerNum); + void V1_DatabaseUserQuery::impl(bool) { + auto server = MustServer(request); - for (auto itr = users.constBegin(); itr != users.constEnd(); ++itr) { - auto user = list.add_users(); - user->mutable_server()->set_id(server->iServerNum); - user->set_id(itr.key()); - user->set_name(u8(itr.value())); - } + QString filter; + if (request.has_filter()) { + filter = u8(request.filter()); + } + auto users = server->getRegisteredUsers(filter); - end(list); -} + ::MurmurRPC::DatabaseUser_List list; + list.mutable_server()->set_id(server->iServerNum); -void V1_DatabaseUserGet::impl(bool) { - auto server = MustServer(request); + for (auto itr = users.constBegin(); itr != users.constEnd(); ++itr) { + auto user = list.add_users(); + user->mutable_server()->set_id(server->iServerNum); + user->set_id(itr.key()); + user->set_name(u8(itr.value())); + } - if (!request.has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); - } - auto info = server->getRegistration(request.id()); - if (info.isEmpty()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + end(list); } - auto texture = server->getUserTexture(request.id()); - ::MurmurRPC::DatabaseUser rpcDatabaseUser; - ToRPC(server, info, texture, &rpcDatabaseUser); - end(rpcDatabaseUser); -} + void V1_DatabaseUserGet::impl(bool) { + auto server = MustServer(request); -void V1_DatabaseUserUpdate::impl(bool) { - auto server = MustServer(request); + if (!request.has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); + } + auto info = server->getRegistration(request.id()); + if (info.isEmpty()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } + auto texture = server->getUserTexture(request.id()); - if (!request.has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); - } - if (!server->isUserId(request.id())) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + ::MurmurRPC::DatabaseUser rpcDatabaseUser; + ToRPC(server, info, texture, &rpcDatabaseUser); + end(rpcDatabaseUser); } - QMap<int, QString> info; - FromRPC(request, info); + void V1_DatabaseUserUpdate::impl(bool) { + auto server = MustServer(request); - if (!server->setInfo(request.id(), info)) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); - } - if (request.has_texture()) { - server->setTexture(request.id(), QByteArray(request.texture().c_str(), request.texture().size())); - } + if (!request.has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); + } + if (!server->isUserId(request.id())) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } - if (info.contains(ServerDB::User_Name) || info.contains(ServerDB::User_Comment)) { - foreach(::ServerUser *u, server->qhUsers) { - if (static_cast<unsigned int>(u->iId) == request.id()) { - QString name = u->qsName; - QString comment = u->qsComment; - if (info.contains(ServerDB::User_Name)) { - name = info.value(ServerDB::User_Name); - } - if (info.contains(ServerDB::User_Comment)) { - comment = info.value(ServerDB::User_Comment); + QMap< int, QString > info; + FromRPC(request, info); + + if (!server->setInfo(request.id(), info)) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } + if (request.has_texture()) { + server->setTexture(request.id(), QByteArray(request.texture().c_str(), request.texture().size())); + } + + if (info.contains(ServerDB::User_Name) || info.contains(ServerDB::User_Comment)) { + foreach (::ServerUser *u, server->qhUsers) { + if (static_cast< unsigned int >(u->iId) == request.id()) { + QString name = u->qsName; + QString comment = u->qsComment; + if (info.contains(ServerDB::User_Name)) { + name = info.value(ServerDB::User_Name); + } + if (info.contains(ServerDB::User_Comment)) { + comment = info.value(ServerDB::User_Comment); + } + server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, name, + comment); + break; } - server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, name, comment); - break; } } + + end(); } - end(); -} + void V1_DatabaseUserRegister::impl(bool) { + auto server = MustServer(request); -void V1_DatabaseUserRegister::impl(bool) { - auto server = MustServer(request); + QMap< int, QString > info; + FromRPC(request, info); - QMap<int, QString> info; - FromRPC(request, info); + auto userid = server->registerUser(info); + if (userid < 0) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } + QByteArray texture; + if (request.has_texture()) { + texture = QByteArray(request.texture().c_str(), request.texture().size()); + server->setTexture(request.id(), texture); + } - auto userid = server->registerUser(info); - if (userid < 0) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); - } - QByteArray texture; - if (request.has_texture()) { - texture = QByteArray(request.texture().c_str(), request.texture().size()); - server->setTexture(request.id(), texture); + ::MurmurRPC::DatabaseUser rpcDatabaseUser; + rpcDatabaseUser.set_id(userid); + ToRPC(server, info, texture, &rpcDatabaseUser); + end(rpcDatabaseUser); } - ::MurmurRPC::DatabaseUser rpcDatabaseUser; - rpcDatabaseUser.set_id(userid); - ToRPC(server, info, texture, &rpcDatabaseUser); - end(rpcDatabaseUser); -} + void V1_DatabaseUserDeregister::impl(bool) { + auto server = MustServer(request); -void V1_DatabaseUserDeregister::impl(bool) { - auto server = MustServer(request); + if (!request.has_id()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); + } + if (!server->unregisterUser(request.id())) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + } - if (!request.has_id()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing id"); - } - if (!server->unregisterUser(request.id())) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid user"); + end(); } - end(); -} - -void V1_DatabaseUserVerify::impl(bool) { - auto server = MustServer(request); + void V1_DatabaseUserVerify::impl(bool) { + auto server = MustServer(request); - if (!request.has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); - } - if (!request.has_password()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing password"); - } + if (!request.has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing name"); + } + if (!request.has_password()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing password"); + } - auto name = u8(request.name()); - auto password = u8(request.password()); + auto name = u8(request.name()); + auto password = u8(request.password()); + + auto ret = server->authenticate(name, password); + switch (ret) { + case -1: + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid username and/or password"); + case -2: + throw ::grpc::Status(::grpc::NOT_FOUND, "unknown user"); + case -3: + throw ::grpc::Status(::grpc::UNAVAILABLE, "authenticator temporarily unavailable"); + } - auto ret = server->authenticate(name, password); - switch (ret) { - case -1: - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "invalid username and/or password"); - case -2: - throw ::grpc::Status(::grpc::NOT_FOUND, "unknown user"); - case -3: - throw ::grpc::Status(::grpc::UNAVAILABLE, "authenticator temporarily unavailable"); + ::MurmurRPC::DatabaseUser rpcDatabaseUser; + rpcDatabaseUser.mutable_server()->set_id(server->iServerNum); + rpcDatabaseUser.set_id(ret); + end(rpcDatabaseUser); } - ::MurmurRPC::DatabaseUser rpcDatabaseUser; - rpcDatabaseUser.mutable_server()->set_id(server->iServerNum); - rpcDatabaseUser.set_id(ret); - end(rpcDatabaseUser); -} + void V1_RedirectWhisperGroupAdd::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); + + if (!request.source().has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); + } + if (!request.target().has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing target name"); + } -void V1_RedirectWhisperGroupAdd::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + QString qssource = u8(request.source().name()); + QString qstarget = u8(request.target().name()); - if (!request.source().has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); - } - if (!request.target().has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing target name"); - } + { + QWriteLocker wl(&server->qrwlVoiceThread); + user->qmWhisperRedirect.insert(qssource, qstarget); + } - QString qssource = u8(request.source().name()); - QString qstarget = u8(request.target().name()); + server->clearACLCache(user); - { - QWriteLocker wl(&server->qrwlVoiceThread); - user->qmWhisperRedirect.insert(qssource, qstarget); + end(); } - server->clearACLCache(user); + void V1_RedirectWhisperGroupRemove::impl(bool) { + auto server = MustServer(request); + auto user = MustUser(server, request); - end(); -} + if (!request.source().has_name()) { + throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); + } -void V1_RedirectWhisperGroupRemove::impl(bool) { - auto server = MustServer(request); - auto user = MustUser(server, request); + QString qssource = u8(request.source().name()); - if (!request.source().has_name()) { - throw ::grpc::Status(::grpc::INVALID_ARGUMENT, "missing source name"); - } + { + QWriteLocker wl(&server->qrwlVoiceThread); + user->qmWhisperRedirect.remove(qssource); + } - QString qssource = u8(request.source().name()); + server->clearACLCache(user); - { - QWriteLocker wl(&server->qrwlVoiceThread); - user->qmWhisperRedirect.remove(qssource); + end(); } - server->clearACLCache(user); - - end(); -} - -} -} +} // namespace Wrapper +} // namespace MurmurRPC diff --git a/src/murmur/MurmurGRPCImpl.h b/src/murmur/MurmurGRPCImpl.h index 14b62c088..69ec36d2a 100644 --- a/src/murmur/MurmurGRPCImpl.h +++ b/src/murmur/MurmurGRPCImpl.h @@ -4,149 +4,149 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_GRPC -#ifndef MUMBLE_MURMUR_MURMURRPC_H_ -#define MUMBLE_MURMUR_MURMURRPC_H_ +# ifndef MUMBLE_MURMUR_MURMURRPC_H_ +# define MUMBLE_MURMUR_MURMURRPC_H_ -#include <QtCore/QCoreApplication> +# include <QtCore/QCoreApplication> -#include <boost/bind.hpp> +# include <boost/bind.hpp> -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" -#include "MurmurRPC.grpc.pb.h" -#pragma GCC diagnostic pop +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wunused-parameter" +# include "MurmurRPC.grpc.pb.h" +# pragma GCC diagnostic pop -#include "Server.h" -#include "Meta.h" +# include "Meta.h" +# include "Server.h" -#include <atomic> +# include <atomic> -#include <QMultiHash> -#include <QSet> +# include <QMultiHash> +# include <QSet> -#include <grpc++/grpc++.h> -#include <grpc++/security/auth_context.h> +# include <grpc++/grpc++.h> +# include <grpc++/security/auth_context.h> class RPCCall; namespace MurmurRPC { - namespace Wrapper { - class V1_ContextActionEvents; - class V1_Events; - class V1_ServerEvents; - class V1_AuthenticatorStream; - class V1_TextMessageFilter; - } -} +namespace Wrapper { + class V1_ContextActionEvents; + class V1_Events; + class V1_ServerEvents; + class V1_AuthenticatorStream; + class V1_TextMessageFilter; +} // namespace Wrapper +} // namespace MurmurRPC class MurmurRPCAuthenticator : public ::grpc::AuthMetadataProcessor { - public: - MurmurRPCAuthenticator(); - grpc::Status Process(const InputMetadata&, ::grpc::AuthContext*, OutputMetadata*, OutputMetadata*); - bool IsBlocking() const; - protected: - QSet<QByteArray> m_gRPCUsers; +public: + MurmurRPCAuthenticator(); + grpc::Status Process(const InputMetadata &, ::grpc::AuthContext *, OutputMetadata *, OutputMetadata *); + bool IsBlocking() const; + +protected: + QSet< QByteArray > m_gRPCUsers; }; class MurmurRPCImpl : public QThread { - Q_OBJECT; - std::unique_ptr<grpc::Server> m_server; - volatile bool m_isRunning; - protected: - void customEvent(QEvent *evt); - public: - MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials> credentials); - ~MurmurRPCImpl(); - void run(); - std::unique_ptr<grpc::ServerCompletionQueue> m_completionQueue; - - // Services - MurmurRPC::V1::AsyncService m_V1Service; - - // Listeners - QHash<int, QMultiHash<QString, ::MurmurRPC::Wrapper::V1_ContextActionEvents *> > m_contextActionListeners; - - QSet<::MurmurRPC::Wrapper::V1_Events *> m_metaServiceListeners; - - QMultiHash<int, ::MurmurRPC::Wrapper::V1_ServerEvents *> m_serverServiceListeners; - - QMutex qmAuthenticatorsLock; - QHash<int, ::MurmurRPC::Wrapper::V1_AuthenticatorStream *> m_authenticators; - - QMutex qmTextMessageFilterLock; - QHash<int, ::MurmurRPC::Wrapper::V1_TextMessageFilter *> m_textMessageFilters; - - // Maps server id -> session -> context action - QMap<int, QMap<unsigned int, QSet<QString> > > m_activeContextActions; - - bool hasActiveContextAction(const ::Server *s, const ::User *u, const QString &action); - void addActiveContextAction(const ::Server *s, const ::User *u, const QString &action); - void removeActiveContextAction(const ::Server *s, const ::User *u, const QString &action); - void removeUserActiveContextActions(const ::Server *s, const ::User *u); - void removeActiveContextActions(const ::Server *s); - - void removeTextMessageFilter(const ::Server *s); - void removeAuthenticator(const ::Server *s); - void sendMetaEvent(const ::MurmurRPC::Event &e); - void sendServerEvent(const ::Server *s, const ::MurmurRPC::Server_Event &e); - - public slots: - void started(Server *server); - void stopped(Server *server); - - void authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw); - void registerUserSlot(int &res, const QMap<int, QString> &); - void unregisterUserSlot(int &res, int id); - void getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res); - void getRegistrationSlot(int &, int, QMap<int, QString> &); - void setInfoSlot(int &, int, const QMap<int, QString> &); - void setTextureSlot(int &res, int id, const QByteArray &texture); - void nameToIdSlot(int &res, const QString &name); - void idToNameSlot(QString &res, int id); - void idToTextureSlot(QByteArray &res, int id); - - void userStateChanged(const User *user); - void userTextMessage(const User *user, const TextMessage &message); - void userConnected(const User *user); - void userDisconnected(const User *user); - void channelStateChanged(const Channel *channel); - void channelCreated(const Channel *channel); - void channelRemoved(const Channel *channel); - - void textMessageFilter(int &res, const User *user, MumbleProto::TextMessage &message); - - void contextAction(const User *user, const QString &action, unsigned int session, int channel); + Q_OBJECT; + std::unique_ptr< grpc::Server > m_server; + volatile bool m_isRunning; + +protected: + void customEvent(QEvent *evt); + +public: + MurmurRPCImpl(const QString &address, std::shared_ptr<::grpc::ServerCredentials > credentials); + ~MurmurRPCImpl(); + void run(); + std::unique_ptr< grpc::ServerCompletionQueue > m_completionQueue; + + // Services + MurmurRPC::V1::AsyncService m_V1Service; + + // Listeners + QHash< int, QMultiHash< QString, ::MurmurRPC::Wrapper::V1_ContextActionEvents * > > m_contextActionListeners; + + QSet<::MurmurRPC::Wrapper::V1_Events * > m_metaServiceListeners; + + QMultiHash< int, ::MurmurRPC::Wrapper::V1_ServerEvents * > m_serverServiceListeners; + + QMutex qmAuthenticatorsLock; + QHash< int, ::MurmurRPC::Wrapper::V1_AuthenticatorStream * > m_authenticators; + + QMutex qmTextMessageFilterLock; + QHash< int, ::MurmurRPC::Wrapper::V1_TextMessageFilter * > m_textMessageFilters; + + // Maps server id -> session -> context action + QMap< int, QMap< unsigned int, QSet< QString > > > m_activeContextActions; + + bool hasActiveContextAction(const ::Server *s, const ::User *u, const QString &action); + void addActiveContextAction(const ::Server *s, const ::User *u, const QString &action); + void removeActiveContextAction(const ::Server *s, const ::User *u, const QString &action); + void removeUserActiveContextActions(const ::Server *s, const ::User *u); + void removeActiveContextActions(const ::Server *s); + + void removeTextMessageFilter(const ::Server *s); + void removeAuthenticator(const ::Server *s); + void sendMetaEvent(const ::MurmurRPC::Event &e); + void sendServerEvent(const ::Server *s, const ::MurmurRPC::Server_Event &e); + +public slots: + void started(Server *server); + void stopped(Server *server); + + void authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw); + void registerUserSlot(int &res, const QMap< int, QString > &); + void unregisterUserSlot(int &res, int id); + void getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res); + void getRegistrationSlot(int &, int, QMap< int, QString > &); + void setInfoSlot(int &, int, const QMap< int, QString > &); + void setTextureSlot(int &res, int id, const QByteArray &texture); + void nameToIdSlot(int &res, const QString &name); + void idToNameSlot(QString &res, int id); + void idToTextureSlot(QByteArray &res, int id); + + void userStateChanged(const User *user); + void userTextMessage(const User *user, const TextMessage &message); + void userConnected(const User *user); + void userDisconnected(const User *user); + void channelStateChanged(const Channel *channel); + void channelCreated(const Channel *channel); + void channelRemoved(const Channel *channel); + + void textMessageFilter(int &res, const User *user, MumbleProto::TextMessage &message); + + void contextAction(const User *user, const QString &action, unsigned int session, int channel); }; class RPCExecEvent : public ExecEvent { Q_DISABLE_COPY(RPCExecEvent); + public: RPCCall *call; - RPCExecEvent(::boost::function<void()> fn, RPCCall *rpc_call) : ExecEvent(fn), call(rpc_call) { - } + RPCExecEvent(::boost::function< void() > fn, RPCCall *rpc_call) : ExecEvent(fn), call(rpc_call) {} }; class RPCCall { ::std::atomic_int m_refs; + public: MurmurRPCImpl *rpc; ::grpc::ServerContext context; - RPCCall(MurmurRPCImpl *rpcImpl) : m_refs(0), rpc(rpcImpl) { - ref(); - } - virtual ~RPCCall() { - } - virtual ::boost::function<void(bool)> *done() { + RPCCall(MurmurRPCImpl *rpcImpl) : m_refs(0), rpc(rpcImpl) { ref(); } + virtual ~RPCCall() {} + virtual ::boost::function< void(bool) > *done() { auto done_fn = ::boost::bind(&RPCCall::finish, this, _1); - return new ::boost::function<void(bool)>(done_fn); + return new ::boost::function< void(bool) >(done_fn); } - virtual void error(const ::grpc::Status&) = 0; + virtual void error(const ::grpc::Status &) = 0; - virtual void finish(bool) { - deref(); - } + virtual void finish(bool) { deref(); } virtual void deref() { Q_ASSERT(m_refs > 0); @@ -154,13 +154,11 @@ public: delete this; } } - virtual void ref() { - m_refs++; - } + virtual void ref() { m_refs++; } - template<class T> - class Ref { + template< class T > class Ref { T *m_object; + public: Ref(T *object) : m_object(object) { if (object) { @@ -172,31 +170,21 @@ public: m_object->deref(); } } - operator bool() const { - return m_object != nullptr && !m_object->context.IsCancelled(); - } - T *operator->() { - return m_object; - } + operator bool() const { return m_object != nullptr && !m_object->context.IsCancelled(); } + T *operator->() { return m_object; } }; }; -template <class InType, class OutType> -class RPCSingleSingleCall : public RPCCall { +template< class InType, class OutType > class RPCSingleSingleCall : public RPCCall { public: InType request; - ::grpc::ServerAsyncResponseWriter < OutType > stream; + ::grpc::ServerAsyncResponseWriter< OutType > stream; - RPCSingleSingleCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) { - } + RPCSingleSingleCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) {} - virtual void error(const ::grpc::Status &err) { - stream.FinishWithError(err, done()); - } + virtual void error(const ::grpc::Status &err) { stream.FinishWithError(err, done()); } - virtual void end(const OutType &msg = OutType()) { - stream.Finish(msg, ::grpc::Status::OK, done()); - } + virtual void end(const OutType &msg = OutType()) { stream.Finish(msg, ::grpc::Status::OK, done()); } }; /// Base for "single-stream" RPC methods. @@ -204,19 +192,16 @@ public: /// The helper method "write" automatically queues writes to the stream. Without /// write queuing, the grpc crashes if a stream.Write is called before a /// previous stream.Write completes. -template <class InType, class OutType> -class RPCSingleStreamCall : public RPCCall { +template< class InType, class OutType > class RPCSingleStreamCall : public RPCCall { QMutex m_writeLock; - QQueue< QPair<OutType, void *> > m_writeQueue; + QQueue< QPair< OutType, void * > > m_writeQueue; + public: InType request; - ::grpc::ServerAsyncWriter < OutType > stream; - RPCSingleStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) { - } + ::grpc::ServerAsyncWriter< OutType > stream; + RPCSingleStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) {} - virtual void error(const ::grpc::Status &err) { - stream.Finish(err, done()); - } + virtual void error(const ::grpc::Status &err) { stream.Finish(err, done()); } void write(const OutType &msg, void *tag) { QMutexLocker l(&m_writeLock); @@ -230,15 +215,15 @@ public: private: void *writeCB() { - auto callback = ::boost::bind(&RPCSingleStreamCall<InType, OutType>::writeCallback, this, _1); - return new ::boost::function<void(bool)>(callback); + auto callback = ::boost::bind(&RPCSingleStreamCall< InType, OutType >::writeCallback, this, _1); + return new ::boost::function< void(bool) >(callback); } void writeCallback(bool ok) { QMutexLocker l(&m_writeLock); auto processed = m_writeQueue.dequeue(); if (processed.second) { - auto cb = static_cast< ::boost::function<void(bool)> *>(processed.second); + auto cb = static_cast<::boost::function< void(bool) > * >(processed.second); (*cb)(ok); delete cb; } @@ -248,21 +233,17 @@ private: } }; -template <class InType, class OutType> -class RPCStreamStreamCall : public RPCCall { +template< class InType, class OutType > class RPCStreamStreamCall : public RPCCall { public: InType request; OutType response; ::grpc::ServerAsyncReaderWriter< OutType, InType > stream; - RPCStreamStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) { - } + RPCStreamStreamCall(MurmurRPCImpl *rpcImpl) : RPCCall(rpcImpl), stream(&context) {} - virtual void error(const ::grpc::Status &err) { - stream.Finish(err, done()); - } + virtual void error(const ::grpc::Status &err) { stream.Finish(err, done()); } }; -#endif +# endif #endif diff --git a/src/murmur/MurmurI.h b/src/murmur/MurmurI.h index 89f20993b..ddca19fee 100644 --- a/src/murmur/MurmurI.h +++ b/src/murmur/MurmurI.h @@ -10,250 +10,181 @@ namespace Murmur { - class ServerI : virtual public Server { - public: +class ServerI : virtual public Server { +public: + virtual void isRunning_async(const ::Murmur::AMD_Server_isRunningPtr &, const Ice::Current &); - virtual void isRunning_async(const ::Murmur::AMD_Server_isRunningPtr&, - const Ice::Current&); + virtual void start_async(const ::Murmur::AMD_Server_startPtr &, const Ice::Current &); - virtual void start_async(const ::Murmur::AMD_Server_startPtr&, - const Ice::Current&); + virtual void stop_async(const ::Murmur::AMD_Server_stopPtr &, const Ice::Current &); - virtual void stop_async(const ::Murmur::AMD_Server_stopPtr&, - const Ice::Current&); + virtual void delete_async(const ::Murmur::AMD_Server_deletePtr &, const Ice::Current &); - virtual void delete_async(const ::Murmur::AMD_Server_deletePtr&, - const Ice::Current&); + virtual void addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr &, const ::Murmur::ServerCallbackPrx &, + const ::Ice::Current &); + virtual void removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr &, + const ::Murmur::ServerCallbackPrx &, const ::Ice::Current &); - virtual void addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr&, const ::Murmur::ServerCallbackPrx&, const ::Ice::Current&); - virtual void removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr&, const ::Murmur::ServerCallbackPrx&, const ::Ice::Current&); + virtual void setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr &, + const ::Murmur::ServerAuthenticatorPrx &, const ::Ice::Current &); - virtual void setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr&, const ::Murmur::ServerAuthenticatorPrx&, const ::Ice::Current&); + virtual void id_async(const ::Murmur::AMD_Server_idPtr &, const Ice::Current &); - virtual void id_async(const ::Murmur::AMD_Server_idPtr&, - const Ice::Current&); + virtual void getConf_async(const ::Murmur::AMD_Server_getConfPtr &, const ::std::string &, const Ice::Current &); - virtual void getConf_async(const ::Murmur::AMD_Server_getConfPtr&, - const ::std::string&, - const Ice::Current&); + virtual void getAllConf_async(const ::Murmur::AMD_Server_getAllConfPtr &, const Ice::Current &); - virtual void getAllConf_async(const ::Murmur::AMD_Server_getAllConfPtr&, - const Ice::Current&); + virtual void setConf_async(const ::Murmur::AMD_Server_setConfPtr &, const ::std::string &, const ::std::string &, + const Ice::Current &); - virtual void setConf_async(const ::Murmur::AMD_Server_setConfPtr&, - const ::std::string&, - const ::std::string&, - const Ice::Current&); + virtual void setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr &, const ::std::string &, + const Ice::Current &); - virtual void setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr&, - const ::std::string&, - const Ice::Current&); + virtual void getLog_async(const ::Murmur::AMD_Server_getLogPtr &, ::Ice::Int, ::Ice::Int, const Ice::Current &); - virtual void getLog_async(const ::Murmur::AMD_Server_getLogPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void getLogLen_async(const ::Murmur::AMD_Server_getLogLenPtr &, const Ice::Current &); - virtual void getLogLen_async(const ::Murmur::AMD_Server_getLogLenPtr&, - const Ice::Current&); + virtual void getUsers_async(const ::Murmur::AMD_Server_getUsersPtr &, const Ice::Current &); - virtual void getUsers_async(const ::Murmur::AMD_Server_getUsersPtr&, - const Ice::Current&); + virtual void getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr &, const Ice::Current &); - virtual void getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr&, - const Ice::Current&); + virtual void getTree_async(const ::Murmur::AMD_Server_getTreePtr &, const Ice::Current &); - virtual void getTree_async(const ::Murmur::AMD_Server_getTreePtr&, - const Ice::Current&); + virtual void getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr &, ::Ice::Int, + const ::Ice::Current &); - virtual void getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr&, - ::Ice::Int, - const ::Ice::Current&); + virtual void getBans_async(const ::Murmur::AMD_Server_getBansPtr &, const Ice::Current &); - virtual void getBans_async(const ::Murmur::AMD_Server_getBansPtr&, - const Ice::Current&); + virtual void setBans_async(const ::Murmur::AMD_Server_setBansPtr &, const ::Murmur::BanList &, + const Ice::Current &); - virtual void setBans_async(const ::Murmur::AMD_Server_setBansPtr&, - const ::Murmur::BanList&, - const Ice::Current&); + virtual void kickUser_async(const ::Murmur::AMD_Server_kickUserPtr &, ::Ice::Int, const ::std::string &, + const Ice::Current &); - virtual void kickUser_async(const ::Murmur::AMD_Server_kickUserPtr&, - ::Ice::Int, - const ::std::string&, - const Ice::Current&); + virtual void sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr &, ::Ice::Int, const ::std::string &, + const Ice::Current &); - virtual void sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr&, - ::Ice::Int, - const ::std::string&, - const Ice::Current&); + virtual void hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr &, ::Ice::Int, ::Ice::Int, ::Ice::Int, + const ::Ice::Current &); + virtual void effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr &, ::Ice::Int, + ::Ice::Int, const ::Ice::Current &); - virtual void hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr&, ::Ice::Int, ::Ice::Int, ::Ice::Int, const ::Ice::Current&); - virtual void effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr&, ::Ice::Int, ::Ice::Int, const ::Ice::Current&); + virtual void addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr &, ::Ice::Int, + const ::std::string &, const ::std::string &, + const ::Murmur::ServerContextCallbackPrx &, int, const ::Ice::Current &); + virtual void removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr &, + const ::Murmur::ServerContextCallbackPrx &, const ::Ice::Current &); - virtual void addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr&, ::Ice::Int, const ::std::string&, const ::std::string&, const ::Murmur::ServerContextCallbackPrx&, int, const ::Ice::Current&); - virtual void removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr&, const ::Murmur::ServerContextCallbackPrx&, const ::Ice::Current&); + virtual void getState_async(const ::Murmur::AMD_Server_getStatePtr &, ::Ice::Int, const Ice::Current &); - virtual void getState_async(const ::Murmur::AMD_Server_getStatePtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setState_async(const ::Murmur::AMD_Server_setStatePtr &, const ::Murmur::User &, const Ice::Current &); - virtual void setState_async(const ::Murmur::AMD_Server_setStatePtr&, - const ::Murmur::User&, - const Ice::Current&); + virtual void getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr &, ::Ice::Int, + const Ice::Current &); - virtual void getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr &, const ::Murmur::Channel &, + const Ice::Current &); - virtual void setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr&, - const ::Murmur::Channel&, - const Ice::Current&); + virtual void removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr &, ::Ice::Int, const Ice::Current &); - virtual void removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void addChannel_async(const ::Murmur::AMD_Server_addChannelPtr &, const ::std::string &, ::Ice::Int, + const Ice::Current &); - virtual void addChannel_async(const ::Murmur::AMD_Server_addChannelPtr&, - const ::std::string&, - ::Ice::Int, - const Ice::Current&); + virtual void sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr &, ::Ice::Int, bool, + const ::std::string &, const Ice::Current &); - virtual void sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr&, - ::Ice::Int, - bool, - const ::std::string&, - const Ice::Current&); + virtual void getACL_async(const ::Murmur::AMD_Server_getACLPtr &, ::Ice::Int, const Ice::Current &); - virtual void getACL_async(const ::Murmur::AMD_Server_getACLPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setACL_async(const ::Murmur::AMD_Server_setACLPtr &, ::Ice::Int, const ::Murmur::ACLList &, + const ::Murmur::GroupList &, bool, const Ice::Current &); - virtual void setACL_async(const ::Murmur::AMD_Server_setACLPtr&, - ::Ice::Int, - const ::Murmur::ACLList&, - const ::Murmur::GroupList&, - bool, - const Ice::Current&); + virtual void removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr &, ::Ice::Int, ::Ice::Int, + const ::std::string &, const ::Ice::Current &); - virtual void removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr&, ::Ice::Int, ::Ice::Int, const ::std::string&, const ::Ice::Current&); + virtual void addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr &, ::Ice::Int, ::Ice::Int, + const ::std::string &, const ::Ice::Current &); - virtual void addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr&, ::Ice::Int, ::Ice::Int, const ::std::string&, const ::Ice::Current&); + virtual void redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr &, ::Ice::Int, + const ::std::string &, const ::std::string &, const ::Ice::Current &); - virtual void redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr&, ::Ice::Int, const ::std::string&, const ::std::string&, const ::Ice::Current&); + virtual void getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr &, const ::Murmur::IdList &, + const Ice::Current &); - virtual void getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr&, - const ::Murmur::IdList&, - const Ice::Current&); + virtual void getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr &, const ::Murmur::NameList &, + const Ice::Current &); - virtual void getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr&, - const ::Murmur::NameList&, - const Ice::Current&); + virtual void registerUser_async(const ::Murmur::AMD_Server_registerUserPtr &, const Murmur::UserInfoMap &, + const Ice::Current &); - virtual void registerUser_async(const ::Murmur::AMD_Server_registerUserPtr&, - const Murmur::UserInfoMap&, - const Ice::Current&); + virtual void unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr &, ::Ice::Int, const Ice::Current &); - virtual void unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr &, Ice::Int, + const Murmur::UserInfoMap &, const Ice::Current &); - virtual void updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr&, - Ice::Int, - const Murmur::UserInfoMap&, - const Ice::Current&); + virtual void getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr &, ::Ice::Int, + const Ice::Current &); - virtual void getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr &, const ::std::string &, + const Ice::Current &); - virtual void getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr&, - const ::std::string&, - const Ice::Current&); + virtual void verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr &, const ::std::string &, + const ::std::string &, const Ice::Current &); - virtual void verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr&, - const ::std::string&, - const ::std::string&, - const Ice::Current&); + virtual void getTexture_async(const ::Murmur::AMD_Server_getTexturePtr &, ::Ice::Int, const Ice::Current &); - virtual void getTexture_async(const ::Murmur::AMD_Server_getTexturePtr&, - ::Ice::Int, - const Ice::Current&); + virtual void setTexture_async(const ::Murmur::AMD_Server_setTexturePtr &, ::Ice::Int, const ::Murmur::Texture &, + const Ice::Current &); - virtual void setTexture_async(const ::Murmur::AMD_Server_setTexturePtr&, - ::Ice::Int, - const ::Murmur::Texture&, - const Ice::Current&); + virtual void getUptime_async(const ::Murmur::AMD_Server_getUptimePtr &, const Ice::Current &); - virtual void getUptime_async(const ::Murmur::AMD_Server_getUptimePtr&, - const Ice::Current&); + virtual void updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr &, const std::string &, + const std::string &, const std::string &, const Ice::Current &); - virtual void updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr&, - const std::string&, - const std::string&, - const std::string&, - const Ice::Current&); + virtual void startListening_async(const ::Murmur::AMD_Server_startListeningPtr &, ::Ice::Int, ::Ice::Int, + const Ice::Current &); - virtual void startListening_async(const ::Murmur::AMD_Server_startListeningPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr &, ::Ice::Int, ::Ice::Int, + const Ice::Current &); - virtual void stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void isListening_async(const ::Murmur::AMD_Server_isListeningPtr &, ::Ice::Int, ::Ice::Int, + const Ice::Current &); - virtual void isListening_async(const ::Murmur::AMD_Server_isListeningPtr&, - ::Ice::Int, - ::Ice::Int, - const Ice::Current&); + virtual void getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr &, ::Ice::Int, + const Ice::Current &); - virtual void getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr &, ::Ice::Int, + const Ice::Current &); - virtual void getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void ice_ping(const Ice::Current &) const; +}; - virtual void ice_ping(const Ice::Current&) const; - }; +class MetaI : virtual public Meta { +public: + virtual void getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr &, const ::Ice::Current &); - class MetaI : virtual public Meta { - public: - virtual void getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr&, - const ::Ice::Current&); + virtual void getServer_async(const ::Murmur::AMD_Meta_getServerPtr &, ::Ice::Int, const Ice::Current &); - virtual void getServer_async(const ::Murmur::AMD_Meta_getServerPtr&, - ::Ice::Int, - const Ice::Current&); + virtual void newServer_async(const ::Murmur::AMD_Meta_newServerPtr &, const Ice::Current &); - virtual void newServer_async(const ::Murmur::AMD_Meta_newServerPtr&, - const Ice::Current&); + virtual void getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr &, const Ice::Current &); - virtual void getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr&, - const Ice::Current&); + virtual void getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr &, const Ice::Current &); - virtual void getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr&, - const Ice::Current&); + virtual void getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr &, const Ice::Current &); - virtual void getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr&, - const Ice::Current&); + virtual void getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr &, const Ice::Current &); - virtual void getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr&, - const Ice::Current&); + virtual void addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr &, const ::Murmur::MetaCallbackPrx &, + const ::Ice::Current & = ::Ice::Current()); + virtual void removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr &, const ::Murmur::MetaCallbackPrx &, + const ::Ice::Current & = ::Ice::Current()); - virtual void addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr&, const ::Murmur::MetaCallbackPrx&, const ::Ice::Current& = ::Ice::Current()); - virtual void removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr&, const ::Murmur::MetaCallbackPrx&, const ::Ice::Current& = ::Ice::Current()); + virtual void getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr &, const Ice::Current &); - virtual void getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr&, - const Ice::Current&); + virtual void getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr &, const Ice::Current &); +}; - virtual void getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr&, - const Ice::Current&); - }; - -} +} // namespace Murmur #endif diff --git a/src/murmur/MurmurIce.cpp b/src/murmur/MurmurIce.cpp index 76211f06a..64b025ed5 100644 --- a/src/murmur/MurmurIce.cpp +++ b/src/murmur/MurmurIce.cpp @@ -5,17 +5,17 @@ #include "MurmurIce.h" +#include "Ban.h" #include "Channel.h" +#include "ChannelListener.h" #include "Group.h" #include "Meta.h" #include "MurmurI.h" #include "Server.h" -#include "ServerUser.h" #include "ServerDB.h" +#include "ServerUser.h" #include "User.h" -#include "Ban.h" #include "Utils.h" -#include "ChannelListener.h" #include <QtCore/QCoreApplication> #include <QtCore/QSettings> @@ -53,7 +53,7 @@ void IceStop() { /// Remove all NUL bytes from |s|. static std::string iceRemoveNul(std::string s) { - std::vector<char> newstr; + std::vector< char > newstr; for (size_t i = 0; i < s.size(); i++) { char c = s.at(i); if (c == 0) { @@ -82,47 +82,47 @@ static std::string iceString(const QString &s) { /// If the function is passed a string bigger than that, /// it will return an empty string. static std::string iceBase64(const std::string &s) { - if (s.size() > static_cast<size_t>(std::numeric_limits<int>::max())) { + if (s.size() > static_cast< size_t >(std::numeric_limits< int >::max())) { return std::string(); } - QByteArray ba(s.data(), static_cast<int>(s.size())); + QByteArray ba(s.data(), static_cast< int >(s.size())); QByteArray ba64 = ba.toBase64(); - return std::string(ba64.data(), static_cast<size_t>(ba.size())); + return std::string(ba64.data(), static_cast< size_t >(ba.size())); } static void logToLog(const ServerDB::LogRecord &r, Murmur::LogEntry &le) { le.timestamp = r.first; - le.txt = iceString(r.second); + le.txt = iceString(r.second); } static void userToUser(const ::User *p, Murmur::User &mp) { - mp.session = p->uiSession; - mp.userid = p->iId; - mp.name = iceString(p->qsName); - mp.mute = p->bMute; - mp.deaf = p->bDeaf; - mp.suppress = p->bSuppress; - mp.recording = p->bRecording; + mp.session = p->uiSession; + mp.userid = p->iId; + mp.name = iceString(p->qsName); + mp.mute = p->bMute; + mp.deaf = p->bDeaf; + mp.suppress = p->bSuppress; + mp.recording = p->bRecording; mp.prioritySpeaker = p->bPrioritySpeaker; - mp.selfMute = p->bSelfMute; - mp.selfDeaf = p->bSelfDeaf; - mp.channel = p->cChannel->iId; - mp.comment = iceString(p->qsComment); - - const ServerUser *u=static_cast<const ServerUser *>(p); - mp.onlinesecs = u->bwr.onlineSeconds(); - mp.bytespersec = u->bwr.bandwidth(); - mp.version = u->uiVersion; - mp.release = iceString(u->qsRelease); - mp.os = iceString(u->qsOS); - mp.osversion = iceString(u->qsOSVersion); - mp.identity = iceString(u->qsIdentity); - mp.context = iceBase64(u->ssContext); - mp.idlesecs = u->bwr.idleSeconds(); - mp.udpPing = u->dUDPPingAvg; - mp.tcpPing = u->dTCPPingAvg; + mp.selfMute = p->bSelfMute; + mp.selfDeaf = p->bSelfDeaf; + mp.channel = p->cChannel->iId; + mp.comment = iceString(p->qsComment); + + const ServerUser *u = static_cast< const ServerUser * >(p); + mp.onlinesecs = u->bwr.onlineSeconds(); + mp.bytespersec = u->bwr.bandwidth(); + mp.version = u->uiVersion; + mp.release = iceString(u->qsRelease); + mp.os = iceString(u->qsOS); + mp.osversion = iceString(u->qsOSVersion); + mp.identity = iceString(u->qsIdentity); + mp.context = iceBase64(u->ssContext); + mp.idlesecs = u->bwr.idleSeconds(); + mp.udpPing = u->dUDPPingAvg; + mp.tcpPing = u->dTCPPingAvg; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) mp.tcponly = u->aiUdpFlag.loadRelaxed() == 0; @@ -133,20 +133,20 @@ static void userToUser(const ::User *p, Murmur::User &mp) { ::Murmur::NetAddress addr(16, 0); const Q_IPV6ADDR &a = u->haAddress.qip6; - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) addr[i] = a[i]; mp.address = addr; } static void channelToChannel(const ::Channel *c, Murmur::Channel &mc) { - mc.id = c->iId; - mc.name = iceString(c->qsName); - mc.parent = c->cParent ? c->cParent->iId : -1; + mc.id = c->iId; + mc.name = iceString(c->qsName); + mc.parent = c->cParent ? c->cParent->iId : -1; mc.description = iceString(c->qsDesc); - mc.position = c->iPosition; + mc.position = c->iPosition; mc.links.clear(); - foreach(::Channel *chn, c->qsPermLinks) + foreach (::Channel *chn, c->qsPermLinks) mc.links.push_back(chn->iId); mc.temporary = c->bTemporary; } @@ -155,15 +155,15 @@ static void ACLtoACL(const ::ChanACL *acl, Murmur::ACL &ma) { ma.applyHere = acl->bApplyHere; ma.applySubs = acl->bApplySubs; ma.inherited = false; - ma.userid = acl->iUserId; - ma.group = iceString(acl->qsGroup); - ma.allow = acl->pAllow; - ma.deny = acl->pDeny; + ma.userid = acl->iUserId; + ma.group = iceString(acl->qsGroup); + ma.allow = acl->pAllow; + ma.deny = acl->pDeny; } static void groupToGroup(const ::Group *g, Murmur::Group &mg) { - mg.name = iceString(g->qsName); - mg.inherit = g->bInherit; + mg.name = iceString(g->qsName); + mg.inherit = g->bInherit; mg.inheritable = g->bInheritable; mg.add.clear(); mg.remove.clear(); @@ -173,40 +173,40 @@ static void groupToGroup(const ::Group *g, Murmur::Group &mg) { static void banToBan(const ::Ban &b, Murmur::Ban &mb) { ::Murmur::NetAddress addr(16, 0); const Q_IPV6ADDR &a = b.haAddress.qip6; - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) addr[i] = a[i]; - mb.address = addr; - mb.bits = b.iMask; - mb.name = iceString(b.qsUsername); - mb.hash = iceString(b.qsHash); - mb.reason = iceString(b.qsReason); - mb.start = b.qdtStart.toLocalTime().toTime_t(); + mb.address = addr; + mb.bits = b.iMask; + mb.name = iceString(b.qsUsername); + mb.hash = iceString(b.qsHash); + mb.reason = iceString(b.qsReason); + mb.start = b.qdtStart.toLocalTime().toTime_t(); mb.duration = b.iDuration; } static void banToBan(const ::Murmur::Ban &mb, ::Ban &b) { if (mb.address.size() != 16) - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) b.haAddress.qip6[i] = 0; else - for (int i=0;i<16;++i) + for (int i = 0; i < 16; ++i) b.haAddress.qip6[i] = mb.address[i]; - b.iMask = mb.bits; + b.iMask = mb.bits; b.qsUsername = u8(mb.name); - b.qsHash = u8(mb.hash); - b.qsReason = u8(mb.reason); - b.qdtStart = QDateTime::fromTime_t(static_cast<quint32>(mb.start)).toUTC(); - b.iDuration = mb.duration; + b.qsHash = u8(mb.hash); + b.qsReason = u8(mb.reason); + b.qdtStart = QDateTime::fromTime_t(static_cast< quint32 >(mb.start)).toUTC(); + b.iDuration = mb.duration; } -static void infoToInfo(const QMap<int, QString> &info, Murmur::UserInfoMap &im) { - QMap<int, QString>::const_iterator i; +static void infoToInfo(const QMap< int, QString > &info, Murmur::UserInfoMap &im) { + QMap< int, QString >::const_iterator i; for (i = info.constBegin(); i != info.constEnd(); ++i) - im[static_cast<Murmur::UserInfo>(i.key())] = iceString(i.value()); + im[static_cast< Murmur::UserInfo >(i.key())] = iceString(i.value()); } -static void infoToInfo(const Murmur::UserInfoMap &im, QMap<int, QString> &info) { +static void infoToInfo(const Murmur::UserInfoMap &im, QMap< int, QString > &info) { Murmur::UserInfoMap::const_iterator i; for (i = im.begin(); i != im.end(); ++i) info.insert((*i).first, u8((*i).second)); @@ -215,21 +215,21 @@ static void infoToInfo(const Murmur::UserInfoMap &im, QMap<int, QString> &info) static void textmessageToTextmessage(const ::TextMessage &tm, Murmur::TextMessage &tmdst) { tmdst.text = iceString(tm.qsText); - foreach(unsigned int i, tm.qlSessions) + foreach (unsigned int i, tm.qlSessions) tmdst.sessions.push_back(i); - foreach(unsigned int i, tm.qlChannels) + foreach (unsigned int i, tm.qlChannels) tmdst.channels.push_back(i); - foreach(unsigned int i, tm.qlTrees) + foreach (unsigned int i, tm.qlTrees) tmdst.trees.push_back(i); } class ServerLocator : public virtual Ice::ServantLocator { - public: - virtual Ice::ObjectPtr locate(const Ice::Current &, Ice::LocalObjectPtr &); - virtual void finished(const Ice::Current &, const Ice::ObjectPtr &, const Ice::LocalObjectPtr &) {}; - virtual void deactivate(const std::string &) {}; +public: + virtual Ice::ObjectPtr locate(const Ice::Current &, Ice::LocalObjectPtr &); + virtual void finished(const Ice::Current &, const Ice::ObjectPtr &, const Ice::LocalObjectPtr &){}; + virtual void deactivate(const std::string &){}; }; MurmurIce::MurmurIce() { @@ -241,14 +241,14 @@ MurmurIce::MurmurIce() { Ice::PropertiesPtr ipp = Ice::createProperties(); ::Meta::mp.qsSettings->beginGroup("Ice"); - foreach(const QString &v, ::Meta::mp.qsSettings->childKeys()) { + foreach (const QString &v, ::Meta::mp.qsSettings->childKeys()) { ipp->setProperty(iceString(v), iceString(::Meta::mp.qsSettings->value(v).toString())); } ::Meta::mp.qsSettings->endGroup(); Ice::PropertyDict props = ippProperties->getPropertiesForPrefix(""); Ice::PropertyDict::iterator i; - for (i=props.begin(); i != props.end(); ++i) { + for (i = props.begin(); i != props.end(); ++i) { ipp->setProperty((*i).first, (*i).second); } ipp->setProperty("Ice.ImplicitContext", "Shared"); @@ -258,12 +258,12 @@ MurmurIce::MurmurIce() { try { communicator = Ice::initialize(idd); - if (! meta->mp.qsIceSecretWrite.isEmpty()) { + if (!meta->mp.qsIceSecretWrite.isEmpty()) { ::Ice::ImplicitContextPtr impl = communicator->getImplicitContext(); if (impl) impl->put("secret", iceString(meta->mp.qsIceSecretWrite)); } - adapter = communicator->createObjectAdapterWithEndpoints("Murmur", qPrintable(meta->mp.qsIceEndpoint)); + adapter = communicator->createObjectAdapterWithEndpoints("Murmur", qPrintable(meta->mp.qsIceEndpoint)); MetaPtr m = new MetaI; #if ICE_INT_VERSION >= 30700 MetaPrx mprx = MetaPrx::uncheckedCast(adapter->add(m, Ice::stringToIdentity("Meta"))); @@ -275,7 +275,7 @@ MurmurIce::MurmurIce() { iopServer = new ServerI; adapter->activate(); - foreach(const Ice::EndpointPtr ep, mprx->ice_getEndpoints()) { + foreach (const Ice::EndpointPtr ep, mprx->ice_getEndpoints()) { qWarning("MurmurIce: Endpoint \"%s\" running", qPrintable(u8(ep->toString()))); } @@ -294,7 +294,7 @@ MurmurIce::~MurmurIce() { communicator->shutdown(); communicator->waitForShutdown(); communicator->destroy(); - communicator=nullptr; + communicator = nullptr; qWarning("MurmurIce: Shutdown complete"); } iopServer = nullptr; @@ -302,7 +302,7 @@ MurmurIce::~MurmurIce() { void MurmurIce::customEvent(QEvent *evt) { if (evt->type() == EXEC_QEVENT) - static_cast<ExecEvent *>(evt)->execute(); + static_cast< ExecEvent * >(evt)->execute(); } void MurmurIce::badMetaProxy(const ::Murmur::MetaCallbackPrx &prx) { @@ -310,7 +310,7 @@ void MurmurIce::badMetaProxy(const ::Murmur::MetaCallbackPrx &prx) { removeMetaCallback(prx); } -void MurmurIce::badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server* server) { +void MurmurIce::badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server *server) { server->log(QString("Ice ServerCallback %1 failed").arg(QString::fromStdString(communicator->proxyToString(prx)))); removeServerCallback(server, prx); } @@ -323,91 +323,105 @@ void MurmurIce::badAuthenticator(::Server *server) { removeServerUpdatingAuthenticator(server); } -void MurmurIce::addMetaCallback(const ::Murmur::MetaCallbackPrx& prx) { +void MurmurIce::addMetaCallback(const ::Murmur::MetaCallbackPrx &prx) { if (!qlMetaCallbacks.contains(prx)) { qWarning("Added Ice MetaCallback %s", qPrintable(QString::fromStdString(communicator->proxyToString(prx)))); qlMetaCallbacks.append(prx); } } -void MurmurIce::removeMetaCallback(const ::Murmur::MetaCallbackPrx& prx) { +void MurmurIce::removeMetaCallback(const ::Murmur::MetaCallbackPrx &prx) { if (qlMetaCallbacks.removeAll(prx)) { qWarning("Removed Ice MetaCallback %s", qPrintable(QString::fromStdString(communicator->proxyToString(prx)))); } } -void MurmurIce::addServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx) { - QList< ::Murmur::ServerCallbackPrx >& cbList = qmServerCallbacks[server->iServerNum]; +void MurmurIce::addServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx) { + QList<::Murmur::ServerCallbackPrx > &cbList = qmServerCallbacks[server->iServerNum]; if (!cbList.contains(prx)) { - server->log(QString("Added Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log( + QString("Added Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); cbList.append(prx); } } -void MurmurIce::removeServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx) { +void MurmurIce::removeServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx) { if (qmServerCallbacks[server->iServerNum].removeAll(prx)) { - server->log(QString("Removed Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log( + QString("Removed Ice ServerCallback %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); } } -void MurmurIce::removeServerCallbacks(const ::Server* server) { +void MurmurIce::removeServerCallbacks(const ::Server *server) { if (qmServerCallbacks.contains(server->iServerNum)) { server->log(QString("Removed all Ice ServerCallbacks")); qmServerCallbacks.remove(server->iServerNum); } } -void MurmurIce::addServerContextCallback(const ::Server* server, int session_id, const QString& action, const ::Murmur::ServerContextCallbackPrx& prx) { - QMap<QString, ::Murmur::ServerContextCallbackPrx>& callbacks = qmServerContextCallbacks[server->iServerNum][session_id]; +void MurmurIce::addServerContextCallback(const ::Server *server, int session_id, const QString &action, + const ::Murmur::ServerContextCallbackPrx &prx) { + QMap< QString, ::Murmur::ServerContextCallbackPrx > &callbacks = + qmServerContextCallbacks[server->iServerNum][session_id]; if (!callbacks.contains(action) || callbacks[action] != prx) { - server->log(QString("Added Ice ServerContextCallback %1 for session %2, action %3").arg(QString::fromStdString(communicator->proxyToString(prx))).arg(session_id).arg(action)); + server->log(QString("Added Ice ServerContextCallback %1 for session %2, action %3") + .arg(QString::fromStdString(communicator->proxyToString(prx))) + .arg(session_id) + .arg(action)); callbacks.insert(action, prx); } } -const QMap< int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > MurmurIce::getServerContextCallbacks(const ::Server* server) const { +const QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > + MurmurIce::getServerContextCallbacks(const ::Server *server) const { return qmServerContextCallbacks[server->iServerNum]; } -void MurmurIce::removeServerContextCallback(const ::Server* server, int session_id, const QString& action) { +void MurmurIce::removeServerContextCallback(const ::Server *server, int session_id, const QString &action) { if (qmServerContextCallbacks[server->iServerNum][session_id].remove(action)) { server->log(QString("Removed Ice ServerContextCallback for session %1, action %2").arg(session_id).arg(action)); } } -void MurmurIce::setServerAuthenticator(const ::Server* server, const ::Murmur::ServerAuthenticatorPrx& prx) { +void MurmurIce::setServerAuthenticator(const ::Server *server, const ::Murmur::ServerAuthenticatorPrx &prx) { if (prx != qmServerAuthenticator[server->iServerNum]) { - server->log(QString("Set Ice Authenticator to %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log( + QString("Set Ice Authenticator to %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); qmServerAuthenticator[server->iServerNum] = prx; } } -const ::Murmur::ServerAuthenticatorPrx MurmurIce::getServerAuthenticator(const ::Server* server) const { +const ::Murmur::ServerAuthenticatorPrx MurmurIce::getServerAuthenticator(const ::Server *server) const { return qmServerAuthenticator[server->iServerNum]; } -void MurmurIce::removeServerAuthenticator(const ::Server* server) { +void MurmurIce::removeServerAuthenticator(const ::Server *server) { if (qmServerAuthenticator.remove(server->iServerNum)) { - server->log(QString("Removed Ice Authenticator %1").arg(QString::fromStdString(communicator->proxyToString(getServerAuthenticator(server))))); + server->log(QString("Removed Ice Authenticator %1") + .arg(QString::fromStdString(communicator->proxyToString(getServerAuthenticator(server))))); } } -void MurmurIce::setServerUpdatingAuthenticator(const ::Server* server, const ::Murmur::ServerUpdatingAuthenticatorPrx& prx) { +void MurmurIce::setServerUpdatingAuthenticator(const ::Server *server, + const ::Murmur::ServerUpdatingAuthenticatorPrx &prx) { if (prx != qmServerUpdatingAuthenticator[server->iServerNum]) { - server->log(QString("Set Ice UpdatingAuthenticator to %1").arg(QString::fromStdString(communicator->proxyToString(prx)))); + server->log(QString("Set Ice UpdatingAuthenticator to %1") + .arg(QString::fromStdString(communicator->proxyToString(prx)))); qmServerUpdatingAuthenticator[server->iServerNum] = prx; } } -const ::Murmur::ServerUpdatingAuthenticatorPrx MurmurIce::getServerUpdatingAuthenticator(const ::Server* server) const { +const ::Murmur::ServerUpdatingAuthenticatorPrx MurmurIce::getServerUpdatingAuthenticator(const ::Server *server) const { return qmServerUpdatingAuthenticator[server->iServerNum]; } -void MurmurIce::removeServerUpdatingAuthenticator(const ::Server* server) { +void MurmurIce::removeServerUpdatingAuthenticator(const ::Server *server) { if (qmServerUpdatingAuthenticator.contains(server->iServerNum)) { - server->log(QString("Removed Ice UpdatingAuthenticator %1").arg(QString::fromStdString(communicator->proxyToString(getServerUpdatingAuthenticator(server))))); + server->log( + QString("Removed Ice UpdatingAuthenticator %1") + .arg(QString::fromStdString(communicator->proxyToString(getServerUpdatingAuthenticator(server))))); qmServerUpdatingAuthenticator.remove(server->iServerNum); } } @@ -415,21 +429,22 @@ void MurmurIce::removeServerUpdatingAuthenticator(const ::Server* server) { static ServerPrx idToProxy(int id, const Ice::ObjectAdapterPtr &adapter) { Ice::Identity ident; ident.category = "s"; - ident.name = iceString(QString::number(id)); + ident.name = iceString(QString::number(id)); return ServerPrx::uncheckedCast(adapter->createProxy(ident)); } void MurmurIce::started(::Server *s) { s->connectListener(mi); - connect(s, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, SLOT(contextAction(const User *, const QString &, unsigned int, int))); + connect(s, SIGNAL(contextAction(const User *, const QString &, unsigned int, int)), this, + SLOT(contextAction(const User *, const QString &, unsigned int, int))); - const QList< ::Murmur::MetaCallbackPrx> &qlList = qlMetaCallbacks; + const QList<::Murmur::MetaCallbackPrx > &qlList = qlMetaCallbacks; if (qlList.isEmpty()) return; - foreach(const ::Murmur::MetaCallbackPrx &prx, qlList) { + foreach (const ::Murmur::MetaCallbackPrx &prx, qlList) { try { prx->started(idToProxy(s->iServerNum, adapter)); } catch (...) { @@ -443,12 +458,12 @@ void MurmurIce::stopped(::Server *s) { removeServerAuthenticator(s); removeServerUpdatingAuthenticator(s); - const QList< ::Murmur::MetaCallbackPrx> &qmList = qlMetaCallbacks; + const QList<::Murmur::MetaCallbackPrx > &qmList = qlMetaCallbacks; if (qmList.isEmpty()) return; - foreach(const ::Murmur::MetaCallbackPrx &prx, qmList) { + foreach (const ::Murmur::MetaCallbackPrx &prx, qmList) { try { prx->stopped(idToProxy(s->iServerNum, adapter)); } catch (...) { @@ -458,9 +473,9 @@ void MurmurIce::stopped(::Server *s) { } void MurmurIce::userConnected(const ::User *p) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -468,7 +483,7 @@ void MurmurIce::userConnected(const ::User *p) { ::Murmur::User mp; userToUser(p, mp); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userConnected(mp); } catch (...) { @@ -478,11 +493,11 @@ void MurmurIce::userConnected(const ::User *p) { } void MurmurIce::userDisconnected(const ::User *p) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); qmServerContextCallbacks[s->iServerNum].remove(p->uiSession); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -490,7 +505,7 @@ void MurmurIce::userDisconnected(const ::User *p) { ::Murmur::User mp; userToUser(p, mp); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userDisconnected(mp); } catch (...) { @@ -500,9 +515,9 @@ void MurmurIce::userDisconnected(const ::User *p) { } void MurmurIce::userStateChanged(const ::User *p) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -510,7 +525,7 @@ void MurmurIce::userStateChanged(const ::User *p) { ::Murmur::User mp; userToUser(p, mp); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userStateChanged(mp); } catch (...) { @@ -520,9 +535,9 @@ void MurmurIce::userStateChanged(const ::User *p) { } void MurmurIce::userTextMessage(const ::User *p, const ::TextMessage &message) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -533,7 +548,7 @@ void MurmurIce::userTextMessage(const ::User *p, const ::TextMessage &message) { ::Murmur::TextMessage textMessage; textmessageToTextmessage(message, textMessage); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->userTextMessage(mp, textMessage); } catch (...) { @@ -543,9 +558,9 @@ void MurmurIce::userTextMessage(const ::User *p, const ::TextMessage &message) { } void MurmurIce::channelCreated(const ::Channel *c) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -553,7 +568,7 @@ void MurmurIce::channelCreated(const ::Channel *c) { ::Murmur::Channel mc; channelToChannel(c, mc); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->channelCreated(mc); } catch (...) { @@ -563,9 +578,9 @@ void MurmurIce::channelCreated(const ::Channel *c) { } void MurmurIce::channelRemoved(const ::Channel *c) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -573,7 +588,7 @@ void MurmurIce::channelRemoved(const ::Channel *c) { ::Murmur::Channel mc; channelToChannel(c, mc); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->channelRemoved(mc); } catch (...) { @@ -583,9 +598,9 @@ void MurmurIce::channelRemoved(const ::Channel *c) { } void MurmurIce::channelStateChanged(const ::Channel *c) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - const QList< ::Murmur::ServerCallbackPrx> &qmList = qmServerCallbacks[s->iServerNum]; + const QList<::Murmur::ServerCallbackPrx > &qmList = qmServerCallbacks[s->iServerNum]; if (qmList.isEmpty()) return; @@ -593,7 +608,7 @@ void MurmurIce::channelStateChanged(const ::Channel *c) { ::Murmur::Channel mc; channelToChannel(c, mc); - foreach(const ::Murmur::ServerCallbackPrx &prx, qmList) { + foreach (const ::Murmur::ServerCallbackPrx &prx, qmList) { try { prx->channelStateChanged(mc); } catch (...) { @@ -603,18 +618,18 @@ void MurmurIce::channelStateChanged(const ::Channel *c) { } void MurmurIce::contextAction(const ::User *pSrc, const QString &action, unsigned int session, int iChannel) { - ::Server *s = qobject_cast< ::Server *> (sender()); + ::Server *s = qobject_cast<::Server * >(sender()); - QMap<int, QMap<int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > > &qmAll = qmServerContextCallbacks; - if (! qmAll.contains(s->iServerNum)) + QMap< int, QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > > &qmAll = qmServerContextCallbacks; + if (!qmAll.contains(s->iServerNum)) return; - QMap<int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > &qmServer = qmAll[s->iServerNum]; - if (! qmServer.contains(pSrc->uiSession)) + QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > &qmServer = qmAll[s->iServerNum]; + if (!qmServer.contains(pSrc->uiSession)) return; - QMap<QString, ::Murmur::ServerContextCallbackPrx> &qmUser = qmServer[pSrc->uiSession]; - if (! qmUser.contains(action)) + QMap< QString, ::Murmur::ServerContextCallbackPrx > &qmUser = qmServer[pSrc->uiSession]; + if (!qmUser.contains(action)) return; const ::Murmur::ServerContextCallbackPrx &prx = qmUser[action]; @@ -625,7 +640,10 @@ void MurmurIce::contextAction(const ::User *pSrc, const QString &action, unsigne try { prx->contextAction(iceString(action), mp, session, iChannel); } catch (...) { - s->log(QString("Ice ServerContextCallback %1 for session %2, action %3 failed").arg(QString::fromStdString(communicator->proxyToString(prx))).arg(pSrc->uiSession).arg(action)); + s->log(QString("Ice ServerContextCallback %1 for session %2, action %3 failed") + .arg(QString::fromStdString(communicator->proxyToString(prx))) + .arg(pSrc->uiSession) + .arg(action)); removeServerContextCallback(s, pSrc->uiSession, action); // Remove clientside entry @@ -639,7 +657,7 @@ void MurmurIce::contextAction(const ::User *pSrc, const QString &action, unsigne } void MurmurIce::idToNameSlot(QString &name, int id) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); try { @@ -649,15 +667,15 @@ void MurmurIce::idToNameSlot(QString &name, int id) { } } void MurmurIce::idToTextureSlot(QByteArray &qba, int id) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); try { const ::Murmur::Texture &tex = prx->idToTexture(id); - qba.resize(static_cast<int>(tex.size())); + qba.resize(static_cast< int >(tex.size())); char *ptr = qba.data(); - for (unsigned int i=0;i<tex.size();++i) + for (unsigned int i = 0; i < tex.size(); ++i) ptr[i] = tex[i]; } catch (...) { badAuthenticator(server); @@ -665,7 +683,7 @@ void MurmurIce::idToTextureSlot(QByteArray &qba, int id) { } void MurmurIce::nameToIdSlot(int &id, const QString &name) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); try { @@ -675,8 +693,9 @@ void MurmurIce::nameToIdSlot(int &id, const QString &name) { } } -void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerAuthenticatorPrx prx = getServerAuthenticator(server); ::std::string newname; @@ -684,18 +703,19 @@ void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const ::Murmur::CertificateList certs; certs.resize(certlist.size()); - for (int i=0;i<certlist.size();++i) { + for (int i = 0; i < certlist.size(); ++i) { ::Murmur::CertificateDer der; QByteArray qba = certlist.at(i).toDer(); der.resize(qba.size()); const char *ptr = qba.constData(); - for (int j=0;j<qba.size();++j) + for (int j = 0; j < qba.size(); ++j) der[j] = ptr[j]; certs[i] = der; } try { - res = prx->authenticate(iceString(uname), iceString(pw), certs, iceString(certhash), certstrong, newname, groups); + res = + prx->authenticate(iceString(uname), iceString(pw), certs, iceString(certhash), certstrong, newname, groups); } catch (...) { badAuthenticator(server); } @@ -703,19 +723,17 @@ void MurmurIce::authenticateSlot(int &res, QString &uname, int sessionId, const if (newname.length() > 0) uname = u8(newname); QStringList qsl; - foreach(const ::std::string &str, groups) { - qsl << u8(str); - } - if (! qsl.isEmpty()) + foreach (const ::std::string &str, groups) { qsl << u8(str); } + if (!qsl.isEmpty()) server->setTempGroups(res, sessionId, nullptr, qsl); } } -void MurmurIce::registerUserSlot(int &res, const QMap<int, QString> &info) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::registerUserSlot(int &res, const QMap< int, QString > &info) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; ::Murmur::UserInfoMap im; @@ -729,10 +747,10 @@ void MurmurIce::registerUserSlot(int &res, const QMap<int, QString> &info) { } void MurmurIce::unregisterUserSlot(int &res, int id) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; try { res = prx->unregisterUser(id); @@ -741,11 +759,11 @@ void MurmurIce::unregisterUserSlot(int &res, int id) { } } -void MurmurIce::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::getRegistrationSlot(int &res, int id, QMap< int, QString > &info) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; Murmur::UserInfoMap im; @@ -760,11 +778,11 @@ void MurmurIce::getRegistrationSlot(int &res, int id, QMap<int, QString> &info) } } -void MurmurIce::getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &m) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &m) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; ::Murmur::NameMap lst; @@ -776,15 +794,15 @@ void MurmurIce::getRegisteredUsersSlot(const QString &filter, QMap<int, QString return; } ::Murmur::NameMap::const_iterator i; - for (i=lst.begin(); i != lst.end(); ++i) + for (i = lst.begin(); i != lst.end(); ++i) m.insert((*i).first, u8((*i).second)); } -void MurmurIce::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { - ::Server *server = qobject_cast< ::Server *> (sender()); +void MurmurIce::setInfoSlot(int &res, int id, const QMap< int, QString > &info) { + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; Murmur::UserInfoMap im; @@ -798,16 +816,16 @@ void MurmurIce::setInfoSlot(int &res, int id, const QMap<int, QString> &info) { } void MurmurIce::setTextureSlot(int &res, int id, const QByteArray &texture) { - ::Server *server = qobject_cast< ::Server *> (sender()); + ::Server *server = qobject_cast<::Server * >(sender()); const ServerUpdatingAuthenticatorPrx prx = getServerUpdatingAuthenticator(server); - if (! prx) + if (!prx) return; ::Murmur::Texture tex; tex.resize(texture.size()); const char *ptr = texture.constData(); - for (int i=0;i<texture.size();++i) + for (int i = 0; i < texture.size(); ++i) tex[i] = ptr[i]; try { @@ -821,45 +839,44 @@ Ice::ObjectPtr ServerLocator::locate(const Ice::Current &, Ice::LocalObjectPtr & return iopServer; } -#define FIND_SERVER \ - ::Server *server = meta->qhServers.value(server_id); +#define FIND_SERVER ::Server *server = meta->qhServers.value(server_id); -#define NEED_SERVER_EXISTS \ - FIND_SERVER \ - if (!server && ! ServerDB::serverExists(server_id)) { \ - cb->ice_exception(::Ice::ObjectNotExistException(__FILE__,__LINE__)); \ - return; \ +#define NEED_SERVER_EXISTS \ + FIND_SERVER \ + if (!server && !ServerDB::serverExists(server_id)) { \ + cb->ice_exception(::Ice::ObjectNotExistException(__FILE__, __LINE__)); \ + return; \ } -#define NEED_SERVER \ - NEED_SERVER_EXISTS \ - if (! server) { \ +#define NEED_SERVER \ + NEED_SERVER_EXISTS \ + if (!server) { \ cb->ice_exception(ServerBootedException()); \ - return; \ + return; \ } -#define NEED_PLAYER \ - ServerUser *user = server->qhUsers.value(session); \ - if (!user) { \ +#define NEED_PLAYER \ + ServerUser *user = server->qhUsers.value(session); \ + if (!user) { \ cb->ice_exception(::Murmur::InvalidSessionException()); \ - return; \ + return; \ } -#define NEED_CHANNEL_VAR(x,y) \ - x = server->qhChannels.value(y); \ - if (!x) { \ +#define NEED_CHANNEL_VAR(x, y) \ + x = server->qhChannels.value(y); \ + if (!x) { \ cb->ice_exception(::Murmur::InvalidChannelException()); \ - return; \ + return; \ } -#define NEED_CHANNEL \ +#define NEED_CHANNEL \ ::Channel *channel; \ NEED_CHANNEL_VAR(channel, channelid); void ServerI::ice_ping(const Ice::Current ¤t) const { // This is executed in the ice thread. int server_id = u8(current.id.name).toInt(); - if (! ServerDB::serverExists(server_id)) + if (!ServerDB::serverExists(server_id)) throw ::Ice::ObjectNotExistException(__FILE__, __LINE__); } @@ -873,7 +890,7 @@ static void impl_Server_start(const ::Murmur::AMD_Server_startPtr cb, int server NEED_SERVER_EXISTS; if (server) cb->ice_exception(ServerBootedException()); - else if (! meta->boot(server_id)) + else if (!meta->boot(server_id)) cb->ice_exception(ServerFailureException()); else cb->ice_response(); @@ -895,11 +912,13 @@ static void impl_Server_delete(const ::Murmur::AMD_Server_deletePtr cb, int serv cb->ice_response(); } -static void impl_Server_addCallback(const Murmur::AMD_Server_addCallbackPtr cb, int server_id, const Murmur::ServerCallbackPrx& cbptr) { +static void impl_Server_addCallback(const Murmur::AMD_Server_addCallbackPtr cb, int server_id, + const Murmur::ServerCallbackPrx &cbptr) { NEED_SERVER; try { - const Murmur::ServerCallbackPrx &oneway = Murmur::ServerCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)); + const Murmur::ServerCallbackPrx &oneway = + Murmur::ServerCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)); mi->addServerCallback(server, oneway); cb->ice_response(); } catch (...) { @@ -907,11 +926,13 @@ static void impl_Server_addCallback(const Murmur::AMD_Server_addCallbackPtr cb, } } -static void impl_Server_removeCallback(const Murmur::AMD_Server_removeCallbackPtr cb, int server_id, const Murmur::ServerCallbackPrx& cbptr) { +static void impl_Server_removeCallback(const Murmur::AMD_Server_removeCallbackPtr cb, int server_id, + const Murmur::ServerCallbackPrx &cbptr) { NEED_SERVER; try { - const Murmur::ServerCallbackPrx &oneway = Murmur::ServerCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)); + const Murmur::ServerCallbackPrx &oneway = + Murmur::ServerCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)); mi->removeServerCallback(server, oneway); cb->ice_response(); } catch (...) { @@ -919,7 +940,8 @@ static void impl_Server_removeCallback(const Murmur::AMD_Server_removeCallbackPt } } -static void impl_Server_setAuthenticator(const ::Murmur::AMD_Server_setAuthenticatorPtr& cb, int server_id, const ::Murmur::ServerAuthenticatorPrx &aptr) { +static void impl_Server_setAuthenticator(const ::Murmur::AMD_Server_setAuthenticatorPtr &cb, int server_id, + const ::Murmur::ServerAuthenticatorPrx &aptr) { NEED_SERVER; if (mi->getServerAuthenticator(server)) @@ -929,7 +951,8 @@ static void impl_Server_setAuthenticator(const ::Murmur::AMD_Server_setAuthentic try { prx = ::Murmur::ServerAuthenticatorPrx::checkedCast(aptr->ice_connectionCached(false)->ice_timeout(5000)); - const ::Murmur::ServerUpdatingAuthenticatorPrx uprx = ::Murmur::ServerUpdatingAuthenticatorPrx::checkedCast(prx); + const ::Murmur::ServerUpdatingAuthenticatorPrx uprx = + ::Murmur::ServerUpdatingAuthenticatorPrx::checkedCast(prx); mi->setServerAuthenticator(server, prx); if (uprx) @@ -952,7 +975,7 @@ static void impl_Server_id(const ::Murmur::AMD_Server_idPtr cb, int server_id) { } #define ACCESS_Server_getConf_READ -static void impl_Server_getConf(const ::Murmur::AMD_Server_getConfPtr cb, int server_id, const ::std::string& key) { +static void impl_Server_getConf(const ::Murmur::AMD_Server_getConfPtr cb, int server_id, const ::std::string &key) { NEED_SERVER_EXISTS; if (key == "key" || key == "passphrase") cb->ice_exception(WriteOnlyException()); @@ -966,9 +989,9 @@ static void impl_Server_getAllConf(const ::Murmur::AMD_Server_getAllConfPtr cb, ::Murmur::ConfigMap cm; - QMap<QString, QString> values = ServerDB::getAllConf(server_id); - QMap<QString, QString>::const_iterator i; - for (i=values.constBegin();i != values.constEnd(); ++i) { + QMap< QString, QString > values = ServerDB::getAllConf(server_id); + QMap< QString, QString >::const_iterator i; + for (i = values.constBegin(); i != values.constEnd(); ++i) { if (i.key() == "key" || i.key() == "passphrase") continue; cm[iceString(i.key())] = iceString(i.value()); @@ -976,30 +999,32 @@ static void impl_Server_getAllConf(const ::Murmur::AMD_Server_getAllConfPtr cb, cb->ice_response(cm); } -static void impl_Server_setConf(const ::Murmur::AMD_Server_setConfPtr cb, int server_id, const ::std::string& key, const ::std::string& value) { +static void impl_Server_setConf(const ::Murmur::AMD_Server_setConfPtr cb, int server_id, const ::std::string &key, + const ::std::string &value) { NEED_SERVER_EXISTS; - QString k=u8(key); - QString v=u8(value); + QString k = u8(key); + QString v = u8(value); ServerDB::setConf(server_id, k, v); if (server) server->setLiveConf(k, v); cb->ice_response(); } -static void impl_Server_setSuperuserPassword(const ::Murmur::AMD_Server_setSuperuserPasswordPtr cb, int server_id, const ::std::string& pw) { +static void impl_Server_setSuperuserPassword(const ::Murmur::AMD_Server_setSuperuserPasswordPtr cb, int server_id, + const ::std::string &pw) { NEED_SERVER_EXISTS; ServerDB::setSUPW(server_id, u8(pw)); cb->ice_response(); } #define ACCESS_Server_getLog_READ -static void impl_Server_getLog(const ::Murmur::AMD_Server_getLogPtr cb, int server_id, ::Ice::Int min, ::Ice::Int max) { +static void impl_Server_getLog(const ::Murmur::AMD_Server_getLogPtr cb, int server_id, ::Ice::Int min, ::Ice::Int max) { NEED_SERVER_EXISTS; ::Murmur::LogList ll; - QList<ServerDB::LogRecord> dblog = ServerDB::getLog(server_id, min, max); - foreach(const ServerDB::LogRecord &e, dblog) { + QList< ServerDB::LogRecord > dblog = ServerDB::getLog(server_id, min, max); + foreach (const ServerDB::LogRecord &e, dblog) { ::Murmur::LogEntry le; logToLog(e, le); ll.push_back(le); @@ -1019,9 +1044,9 @@ static void impl_Server_getLogLen(const ::Murmur::AMD_Server_getLogLenPtr cb, in static void impl_Server_getUsers(const ::Murmur::AMD_Server_getUsersPtr cb, int server_id) { NEED_SERVER; ::Murmur::UserMap pm; - foreach(const ::User *p, server->qhUsers) { + foreach (const ::User *p, server->qhUsers) { ::Murmur::User mp; - if (static_cast<const ServerUser *>(p)->sState == ::ServerUser::Authenticated) { + if (static_cast< const ServerUser * >(p)->sState == ::ServerUser::Authenticated) { userToUser(p, mp); pm[p->uiSession] = mp; } @@ -1033,7 +1058,7 @@ static void impl_Server_getUsers(const ::Murmur::AMD_Server_getUsersPtr cb, int static void impl_Server_getChannels(const ::Murmur::AMD_Server_getChannelsPtr cb, int server_id) { NEED_SERVER; ::Murmur::ChannelMap cm; - foreach(const ::Channel *c, server->qhChannels) { + foreach (const ::Channel *c, server->qhChannels) { ::Murmur::Channel mc; channelToChannel(c, mc); cm[c->iId] = mc; @@ -1052,21 +1077,19 @@ static bool channelSort(const ::Channel *a, const ::Channel *b) { TreePtr recurseTree(const ::Channel *c) { TreePtr t = new Tree(); channelToChannel(c, t->c); - QList< ::User *> users = c->qlUsers; + QList<::User * > users = c->qlUsers; std::sort(users.begin(), users.end(), userSort); - foreach(const ::User *p, users) { + foreach (const ::User *p, users) { ::Murmur::User mp; userToUser(p, mp); t->users.push_back(mp); } - QList< ::Channel *> channels = c->qlChannels; + QList<::Channel * > channels = c->qlChannels; std::sort(channels.begin(), channels.end(), channelSort); - foreach(const ::Channel *chn, channels) { - t->children.push_back(recurseTree(chn)); - } + foreach (const ::Channel *chn, channels) { t->children.push_back(recurseTree(chn)); } return t; } @@ -1078,21 +1101,22 @@ static void impl_Server_getTree(const ::Murmur::AMD_Server_getTreePtr cb, int se } #define ACCESS_Server_getCertificateList_READ -static void impl_Server_getCertificateList(const ::Murmur::AMD_Server_getCertificateListPtr cb, int server_id, ::Ice::Int session) { +static void impl_Server_getCertificateList(const ::Murmur::AMD_Server_getCertificateListPtr cb, int server_id, + ::Ice::Int session) { NEED_SERVER; NEED_PLAYER; ::Murmur::CertificateList certs; - const QList<QSslCertificate> &certlist = user->peerCertificateChain(); + const QList< QSslCertificate > &certlist = user->peerCertificateChain(); certs.resize(certlist.size()); - for (int i=0;i<certlist.size();++i) { + for (int i = 0; i < certlist.size(); ++i) { ::Murmur::CertificateDer der; QByteArray qba = certlist.at(i).toDer(); der.resize(qba.size()); const char *ptr = qba.constData(); - for (int j=0;j<qba.size();++j) + for (int j = 0; j < qba.size(); ++j) der[j] = ptr[j]; certs[i] = der; } @@ -1103,7 +1127,7 @@ static void impl_Server_getCertificateList(const ::Murmur::AMD_Server_getCertifi static void impl_Server_getBans(const ::Murmur::AMD_Server_getBansPtr cb, int server_id) { NEED_SERVER; ::Murmur::BanList bl; - foreach(const ::Ban &ban, server->qlBans) { + foreach (const ::Ban &ban, server->qlBans) { ::Murmur::Ban mb; banToBan(ban, mb); bl.push_back(mb); @@ -1111,10 +1135,11 @@ static void impl_Server_getBans(const ::Murmur::AMD_Server_getBansPtr cb, int se cb->ice_response(bl); } -static void impl_Server_setBans(const ::Murmur::AMD_Server_setBansPtr cb, int server_id, const ::Murmur::BanList& bans) { +static void impl_Server_setBans(const ::Murmur::AMD_Server_setBansPtr cb, int server_id, + const ::Murmur::BanList &bans) { NEED_SERVER; server->qlBans.clear(); - foreach(const ::Murmur::Ban &mb, bans) { + foreach (const ::Murmur::Ban &mb, bans) { ::Ban ban; banToBan(mb, ban); server->qlBans << ban; @@ -1123,7 +1148,8 @@ static void impl_Server_setBans(const ::Murmur::AMD_Server_setBansPtr cb, int se cb->ice_response(); } -static void impl_Server_kickUser(const ::Murmur::AMD_Server_kickUserPtr cb, int server_id, ::Ice::Int session, const ::std::string& reason) { +static void impl_Server_kickUser(const ::Murmur::AMD_Server_kickUserPtr cb, int server_id, ::Ice::Int session, + const ::std::string &reason) { NEED_SERVER; NEED_PLAYER; @@ -1135,7 +1161,8 @@ static void impl_Server_kickUser(const ::Murmur::AMD_Server_kickUserPtr cb, int cb->ice_response(); } -static void impl_Server_sendMessage(const ::Murmur::AMD_Server_sendMessagePtr cb, int server_id, ::Ice::Int session, const ::std::string &text) { +static void impl_Server_sendMessage(const ::Murmur::AMD_Server_sendMessagePtr cb, int server_id, ::Ice::Int session, + const ::std::string &text) { NEED_SERVER; NEED_PLAYER; @@ -1144,34 +1171,41 @@ static void impl_Server_sendMessage(const ::Murmur::AMD_Server_sendMessagePtr cb } #define ACCESS_Server_hasPermission_READ -static void impl_Server_hasPermission(const ::Murmur::AMD_Server_hasPermissionPtr cb, int server_id, ::Ice::Int session, ::Ice::Int channelid, ::Ice::Int perm) { +static void impl_Server_hasPermission(const ::Murmur::AMD_Server_hasPermissionPtr cb, int server_id, ::Ice::Int session, + ::Ice::Int channelid, ::Ice::Int perm) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; - cb->ice_response(server->hasPermission(user, channel, static_cast<ChanACL::Perm>(perm))); + cb->ice_response(server->hasPermission(user, channel, static_cast< ChanACL::Perm >(perm))); } #define ACCESS_Server_effectivePermissions_READ -static void impl_Server_effectivePermissions(const ::Murmur::AMD_Server_effectivePermissionsPtr cb, int server_id, ::Ice::Int session, ::Ice::Int channelid) { +static void impl_Server_effectivePermissions(const ::Murmur::AMD_Server_effectivePermissionsPtr cb, int server_id, + ::Ice::Int session, ::Ice::Int channelid) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; cb->ice_response(server->effectivePermissions(user, channel)); } -static void impl_Server_addContextCallback(const Murmur::AMD_Server_addContextCallbackPtr cb, int server_id, ::Ice::Int session, const ::std::string& action, const ::std::string& text, const ::Murmur::ServerContextCallbackPrx& cbptr, int ctx) { +static void impl_Server_addContextCallback(const Murmur::AMD_Server_addContextCallbackPtr cb, int server_id, + ::Ice::Int session, const ::std::string &action, const ::std::string &text, + const ::Murmur::ServerContextCallbackPrx &cbptr, int ctx) { NEED_SERVER; NEED_PLAYER; - const QMap<QString, ::Murmur::ServerContextCallbackPrx>& qmPrx = mi->getServerContextCallbacks(server)[session]; + const QMap< QString, ::Murmur::ServerContextCallbackPrx > &qmPrx = mi->getServerContextCallbacks(server)[session]; - if (!(ctx & (MumbleProto::ContextActionModify_Context_Server | MumbleProto::ContextActionModify_Context_Channel | MumbleProto::ContextActionModify_Context_User))) { + if (!(ctx + & (MumbleProto::ContextActionModify_Context_Server | MumbleProto::ContextActionModify_Context_Channel + | MumbleProto::ContextActionModify_Context_User))) { cb->ice_exception(InvalidCallbackException()); return; } try { - const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::checkedCast( + cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); if (qmPrx.contains(u8(action))) { // Since the server has no notion of the ctx part of the context action // make sure we remove them all clientside when overriding an old callback @@ -1195,18 +1229,21 @@ static void impl_Server_addContextCallback(const Murmur::AMD_Server_addContextCa server->sendMessage(user, mpcam); } -static void impl_Server_removeContextCallback(const Murmur::AMD_Server_removeContextCallbackPtr cb, int server_id, const Murmur::ServerContextCallbackPrx& cbptr) { +static void impl_Server_removeContextCallback(const Murmur::AMD_Server_removeContextCallbackPtr cb, int server_id, + const Murmur::ServerContextCallbackPrx &cbptr) { NEED_SERVER; - const QMap< int, QMap<QString, ::Murmur::ServerContextCallbackPrx> >& qmPrx = mi->getServerContextCallbacks(server); + const QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > &qmPrx = + mi->getServerContextCallbacks(server); try { - const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::ServerContextCallbackPrx &oneway = Murmur::ServerContextCallbackPrx::uncheckedCast( + cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); - foreach(int session, qmPrx.keys()) { - ServerUser *user = server->qhUsers.value(session); - const QMap<QString, ::Murmur::ServerContextCallbackPrx> &qm = qmPrx[session]; - foreach(const QString &act, qm.keys(oneway)) { + foreach (int session, qmPrx.keys()) { + ServerUser *user = server->qhUsers.value(session); + const QMap< QString, ::Murmur::ServerContextCallbackPrx > &qm = qmPrx[session]; + foreach (const QString &act, qm.keys(oneway)) { mi->removeServerContextCallback(server, session, act); // Ask clients to remove the clientside callbacks @@ -1226,7 +1263,7 @@ static void impl_Server_removeContextCallback(const Murmur::AMD_Server_removeCon } #define ACCESS_Server_getState_READ -static void impl_Server_getState(const ::Murmur::AMD_Server_getStatePtr cb, int server_id, ::Ice::Int session) { +static void impl_Server_getState(const ::Murmur::AMD_Server_getStatePtr cb, int server_id, ::Ice::Int session) { NEED_SERVER; NEED_PLAYER; @@ -1235,18 +1272,21 @@ static void impl_Server_getState(const ::Murmur::AMD_Server_getStatePtr cb, int cb->ice_response(mp); } -static void impl_Server_setState(const ::Murmur::AMD_Server_setStatePtr cb, int server_id, const ::Murmur::User& state) { +static void impl_Server_setState(const ::Murmur::AMD_Server_setStatePtr cb, int server_id, + const ::Murmur::User &state) { int session = state.session; ::Channel *channel; NEED_SERVER; NEED_PLAYER; NEED_CHANNEL_VAR(channel, state.channel); - server->setUserState(user, channel, state.mute, state.deaf, state.suppress, state.prioritySpeaker, u8(state.name), u8(state.comment)); + server->setUserState(user, channel, state.mute, state.deaf, state.suppress, state.prioritySpeaker, u8(state.name), + u8(state.comment)); cb->ice_response(); } -static void impl_Server_sendMessageChannel(const ::Murmur::AMD_Server_sendMessageChannelPtr cb, int server_id, ::Ice::Int channelid, bool tree, const ::std::string &text) { +static void impl_Server_sendMessageChannel(const ::Murmur::AMD_Server_sendMessageChannelPtr cb, int server_id, + ::Ice::Int channelid, bool tree, const ::std::string &text) { NEED_SERVER; NEED_CHANNEL; @@ -1255,7 +1295,8 @@ static void impl_Server_sendMessageChannel(const ::Murmur::AMD_Server_sendMessag } #define ACCESS_Server_getChannelState_READ -static void impl_Server_getChannelState(const ::Murmur::AMD_Server_getChannelStatePtr cb, int server_id, ::Ice::Int channelid) { +static void impl_Server_getChannelState(const ::Murmur::AMD_Server_getChannelStatePtr cb, int server_id, + ::Ice::Int channelid) { NEED_SERVER; NEED_CHANNEL; @@ -1264,7 +1305,8 @@ static void impl_Server_getChannelState(const ::Murmur::AMD_Server_getChannelSta cb->ice_response(mc); } -static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelStatePtr cb, int server_id, const ::Murmur::Channel& state) { +static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelStatePtr cb, int server_id, + const ::Murmur::Channel &state) { int channelid = state.id; NEED_SERVER; NEED_CHANNEL; @@ -1275,8 +1317,8 @@ static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelSta QString qsName = u8(state.name); - QSet< ::Channel *> newset; - foreach(int linkid, state.links) { + QSet<::Channel * > newset; + foreach (int linkid, state.links) { ::Channel *cLink; NEED_CHANNEL_VAR(cLink, linkid); newset << cLink; @@ -1287,13 +1329,14 @@ static void impl_Server_setChannelState(const ::Murmur::AMD_Server_setChannelSta return; } - if (! server->setChannelState(channel, np, qsName, newset, u8(state.description), state.position)) + if (!server->setChannelState(channel, np, qsName, newset, u8(state.description), state.position)) cb->ice_exception(::Murmur::InvalidChannelException()); else cb->ice_response(); } -static void impl_Server_removeChannel(const ::Murmur::AMD_Server_removeChannelPtr cb, int server_id, ::Ice::Int channelid) { +static void impl_Server_removeChannel(const ::Murmur::AMD_Server_removeChannelPtr cb, int server_id, + ::Ice::Int channelid) { NEED_SERVER; NEED_CHANNEL; @@ -1305,7 +1348,8 @@ static void impl_Server_removeChannel(const ::Murmur::AMD_Server_removeChannelPt } } -static void impl_Server_addChannel(const ::Murmur::AMD_Server_addChannelPtr cb, int server_id, const ::std::string& name, ::Ice::Int parent) { +static void impl_Server_addChannel(const ::Murmur::AMD_Server_addChannelPtr cb, int server_id, + const ::std::string &name, ::Ice::Int parent) { NEED_SERVER; ::Channel *p, *nc; NEED_CHANNEL_VAR(p, parent); @@ -1338,7 +1382,7 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv ::Murmur::ACLList acls; ::Murmur::GroupList groups; - QStack< ::Channel *> chans; + QStack<::Channel * > chans; ::Channel *p; ChanACL *acl; p = channel; @@ -1352,10 +1396,10 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv bool inherit = channel->bInheritACL; - while (! chans.isEmpty()) { + while (!chans.isEmpty()) { p = chans.pop(); - foreach(acl, p->qlACL) { - if ((p==channel) || (acl->bApplySubs)) { + foreach (acl, p->qlACL) { + if ((p == channel) || (acl->bApplySubs)) { ::Murmur::ACL ma; ACLtoACL(acl, ma); if (p != channel) @@ -1365,24 +1409,24 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv } } - p = channel->cParent; - const QSet<QString> allnames = ::Group::groupNames(channel); - foreach(const QString &name, allnames) { - ::Group *g = channel->qhGroups.value(name); + p = channel->cParent; + const QSet< QString > allnames = ::Group::groupNames(channel); + foreach (const QString &name, allnames) { + ::Group *g = channel->qhGroups.value(name); ::Group *pg = p ? ::Group::getGroup(p, name) : nullptr; - if (!g && ! pg) + if (!g && !pg) continue; ::Murmur::Group mg; groupToGroup(g ? g : pg, mg); - QSet<int> members; + QSet< int > members; if (pg) members = pg->members(); if (g) { - QVector<int> addVec = g->qsAdd.values().toVector(); - QVector<int> removeVec = g->qsRemove.values().toVector(); + QVector< int > addVec = g->qsAdd.values().toVector(); + QVector< int > removeVec = g->qsRemove.values().toVector(); - mg.add = std::vector<int>(addVec.begin(), addVec.end()); - mg.remove = std::vector<int>(removeVec.begin(), removeVec.end()); + mg.add = std::vector< int >(addVec.begin(), addVec.end()); + mg.remove = std::vector< int >(removeVec.begin(), removeVec.end()); mg.inherited = false; members += g->qsAdd; members -= g->qsRemove; @@ -1390,58 +1434,59 @@ static void impl_Server_getACL(const ::Murmur::AMD_Server_getACLPtr cb, int serv mg.inherited = true; } - QVector<int> memberVec = members.values().toVector(); - mg.members = std::vector<int>(memberVec.begin(), memberVec.end()); + QVector< int > memberVec = members.values().toVector(); + mg.members = std::vector< int >(memberVec.begin(), memberVec.end()); groups.push_back(mg); } cb->ice_response(acls, groups, inherit); } -static void impl_Server_setACL(const ::Murmur::AMD_Server_setACLPtr cb, int server_id, ::Ice::Int channelid, const ::Murmur::ACLList& acls, const ::Murmur::GroupList& groups, bool inherit) { +static void impl_Server_setACL(const ::Murmur::AMD_Server_setACLPtr cb, int server_id, ::Ice::Int channelid, + const ::Murmur::ACLList &acls, const ::Murmur::GroupList &groups, bool inherit) { NEED_SERVER; NEED_CHANNEL; ::Group *g; ChanACL *acl; - QHash<QString, QSet<int> > hOldTemp; - foreach(g, channel->qhGroups) { + QHash< QString, QSet< int > > hOldTemp; + foreach (g, channel->qhGroups) { hOldTemp.insert(g->qsName, g->qsTemporary); delete g; } - foreach(acl, channel->qlACL) + foreach (acl, channel->qlACL) delete acl; channel->qhGroups.clear(); channel->qlACL.clear(); channel->bInheritACL = inherit; - foreach(const ::Murmur::Group &gi, groups) { - QString name = u8(gi.name); - g = new ::Group(channel, name); - g->bInherit = gi.inherit; + foreach (const ::Murmur::Group &gi, groups) { + QString name = u8(gi.name); + g = new ::Group(channel, name); + g->bInherit = gi.inherit; g->bInheritable = gi.inheritable; #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QVector<int> addVec(gi.add.begin(), gi.add.end()); - QVector<int> removeVec(gi.remove.begin(), gi.remove.end()); + QVector< int > addVec(gi.add.begin(), gi.add.end()); + QVector< int > removeVec(gi.remove.begin(), gi.remove.end()); - g->qsAdd = QSet<int>(addVec.begin(), addVec.end()); - g->qsRemove = QSet<int>(removeVec.begin(), removeVec.end()); + g->qsAdd = QSet< int >(addVec.begin(), addVec.end()); + g->qsRemove = QSet< int >(removeVec.begin(), removeVec.end()); #else // Qt 5.14 prefers to use the new range-based constructor for vectors and sets - g->qsAdd = QVector<int>::fromStdVector(gi.add).toList().toSet(); - g->qsRemove = QVector<int>::fromStdVector(gi.remove).toList().toSet(); + g->qsAdd = QVector< int >::fromStdVector(gi.add).toList().toSet(); + g->qsRemove = QVector< int >::fromStdVector(gi.remove).toList().toSet(); #endif g->qsTemporary = hOldTemp.value(name); } - foreach(const ::Murmur::ACL &ai, acls) { - acl = new ChanACL(channel); + foreach (const ::Murmur::ACL &ai, acls) { + acl = new ChanACL(channel); acl->bApplyHere = ai.applyHere; acl->bApplySubs = ai.applySubs; - acl->iUserId = ai.userid; - acl->qsGroup = u8(ai.group); - acl->pDeny = static_cast<ChanACL::Permissions>(ai.deny) & ChanACL::All; - acl->pAllow = static_cast<ChanACL::Permissions>(ai.allow) & ChanACL::All; + acl->iUserId = ai.userid; + acl->qsGroup = u8(ai.group); + acl->pDeny = static_cast< ChanACL::Permissions >(ai.deny) & ChanACL::All; + acl->pAllow = static_cast< ChanACL::Permissions >(ai.allow) & ChanACL::All; } server->clearACLCache(); @@ -1450,30 +1495,31 @@ static void impl_Server_setACL(const ::Murmur::AMD_Server_setACLPtr cb, int serv } #define ACCESS_Server_getUserNames_READ -static void impl_Server_getUserNames(const ::Murmur::AMD_Server_getUserNamesPtr cb, int server_id, const ::Murmur::IdList& ids) { +static void impl_Server_getUserNames(const ::Murmur::AMD_Server_getUserNamesPtr cb, int server_id, + const ::Murmur::IdList &ids) { NEED_SERVER; ::Murmur::NameMap nm; - foreach(int userid, ids) { - nm[userid] = iceString(server->getUserName(userid)); - } + foreach (int userid, ids) { nm[userid] = iceString(server->getUserName(userid)); } cb->ice_response(nm); } #define ACCESS_Server_getUserIds_READ -static void impl_Server_getUserIds(const ::Murmur::AMD_Server_getUserIdsPtr cb, int server_id, const ::Murmur::NameList& names) { +static void impl_Server_getUserIds(const ::Murmur::AMD_Server_getUserIdsPtr cb, int server_id, + const ::Murmur::NameList &names) { NEED_SERVER; ::Murmur::IdMap im; - foreach(const string &n, names) { + foreach (const string &n, names) { QString name = u8(n); - im[n] = server->getUserID(name); + im[n] = server->getUserID(name); } cb->ice_response(im); } -static void impl_Server_registerUser(const ::Murmur::AMD_Server_registerUserPtr cb, int server_id, const ::Murmur::UserInfoMap &im) { +static void impl_Server_registerUser(const ::Murmur::AMD_Server_registerUserPtr cb, int server_id, + const ::Murmur::UserInfoMap &im) { NEED_SERVER; - QMap<int, QString> info; + QMap< int, QString > info; infoToInfo(im, info); int userid = server->registerUser(info); @@ -1483,34 +1529,37 @@ static void impl_Server_registerUser(const ::Murmur::AMD_Server_registerUserPtr cb->ice_response(userid); } -static void impl_Server_unregisterUser(const ::Murmur::AMD_Server_unregisterUserPtr cb, int server_id, ::Ice::Int userid) { +static void impl_Server_unregisterUser(const ::Murmur::AMD_Server_unregisterUserPtr cb, int server_id, + ::Ice::Int userid) { NEED_SERVER; - if (! server->unregisterUser(userid)) + if (!server->unregisterUser(userid)) cb->ice_exception(InvalidUserException()); else cb->ice_response(); } -static void impl_Server_updateRegistration(const ::Murmur::AMD_Server_updateRegistrationPtr cb, int server_id, int id, const ::Murmur::UserInfoMap &im) { +static void impl_Server_updateRegistration(const ::Murmur::AMD_Server_updateRegistrationPtr cb, int server_id, int id, + const ::Murmur::UserInfoMap &im) { NEED_SERVER; - if (! server->isUserId(id)) { + if (!server->isUserId(id)) { cb->ice_exception(InvalidUserException()); return; } - QMap<int, QString> info; + QMap< int, QString > info; infoToInfo(im, info); - if (! server->setInfo(id, info)) { + if (!server->setInfo(id, info)) { cb->ice_exception(InvalidUserException()); return; } if (info.contains(ServerDB::User_Comment)) { - foreach(ServerUser *u, server->qhUsers) { + foreach (ServerUser *u, server->qhUsers) { if (u->iId == id) - server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, u->qsName, info.value(ServerDB::User_Comment)); + server->setUserState(u, u->cChannel, u->bMute, u->bDeaf, u->bSuppress, u->bPrioritySpeaker, u->qsName, + info.value(ServerDB::User_Comment)); } } @@ -1518,10 +1567,11 @@ static void impl_Server_updateRegistration(const ::Murmur::AMD_Server_updateRegi } #define ACCESS_Server_getRegistration_READ -static void impl_Server_getRegistration(const ::Murmur::AMD_Server_getRegistrationPtr cb, int server_id, ::Ice::Int userid) { +static void impl_Server_getRegistration(const ::Murmur::AMD_Server_getRegistrationPtr cb, int server_id, + ::Ice::Int userid) { NEED_SERVER; - QMap<int, QString> info = server->getRegistration(userid); + QMap< int, QString > info = server->getRegistration(userid); if (info.isEmpty()) { cb->ice_exception(InvalidUserException()); @@ -1534,12 +1584,13 @@ static void impl_Server_getRegistration(const ::Murmur::AMD_Server_getRegistrati } #define ACCESS_Server_getRegisteredUsers_READ -static void impl_Server_getRegisteredUsers(const ::Murmur::AMD_Server_getRegisteredUsersPtr cb, int server_id, const ::std::string& filter) { +static void impl_Server_getRegisteredUsers(const ::Murmur::AMD_Server_getRegisteredUsersPtr cb, int server_id, + const ::std::string &filter) { NEED_SERVER; Murmur::NameMap rpl; - const QMap<int, QString> l = server->getRegisteredUsers(u8(filter)); - QMap<int, QString>::const_iterator i; + const QMap< int, QString > l = server->getRegisteredUsers(u8(filter)); + QMap< int, QString >::const_iterator i; for (i = l.constBegin(); i != l.constEnd(); ++i) { rpl[i.key()] = u8(i.value()); } @@ -1548,17 +1599,18 @@ static void impl_Server_getRegisteredUsers(const ::Murmur::AMD_Server_getRegiste } #define ACCESS_Server_verifyPassword_READ -static void impl_Server_verifyPassword(const ::Murmur::AMD_Server_verifyPasswordPtr cb, int server_id, const ::std::string& name, const ::std::string& pw) { +static void impl_Server_verifyPassword(const ::Murmur::AMD_Server_verifyPasswordPtr cb, int server_id, + const ::std::string &name, const ::std::string &pw) { NEED_SERVER; QString uname = u8(name); cb->ice_response(server->authenticate(uname, u8(pw))); } #define ACCESS_Server_getTexture_READ -static void impl_Server_getTexture(const ::Murmur::AMD_Server_getTexturePtr cb, int server_id, ::Ice::Int userid) { +static void impl_Server_getTexture(const ::Murmur::AMD_Server_getTexturePtr cb, int server_id, ::Ice::Int userid) { NEED_SERVER; - if (! server->isUserId(userid)) { + if (!server->isUserId(userid)) { cb->ice_exception(InvalidUserException()); return; } @@ -1568,25 +1620,26 @@ static void impl_Server_getTexture(const ::Murmur::AMD_Server_getTexturePtr cb, ::Murmur::Texture tex; tex.resize(qba.size()); const char *ptr = qba.constData(); - for (int i=0;i<qba.size();++i) + for (int i = 0; i < qba.size(); ++i) tex[i] = ptr[i]; cb->ice_response(tex); } -static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, int server_id, ::Ice::Int userid, const ::Murmur::Texture& tex) { +static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, int server_id, ::Ice::Int userid, + const ::Murmur::Texture &tex) { NEED_SERVER; - if (! server->isUserId(userid)) { + if (!server->isUserId(userid)) { cb->ice_exception(InvalidUserException()); return; } - QByteArray qba(static_cast<int>(tex.size()), 0); + QByteArray qba(static_cast< int >(tex.size()), 0); char *ptr = qba.data(); - for (unsigned int i=0;i<tex.size();++i) + for (unsigned int i = 0; i < tex.size(); ++i) ptr[i] = tex[i]; - if (! server->setTexture(userid, qba)) { + if (!server->setTexture(userid, qba)) { cb->ice_exception(InvalidTextureException()); } else { ServerUser *user = server->qhUsers.value(userid); @@ -1596,7 +1649,7 @@ static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, mpus.set_texture(blob(user->qbaTexture)); server->sendAll(mpus, ~0x010202); - if (! user->qbaTextureHash.isEmpty()) { + if (!user->qbaTextureHash.isEmpty()) { mpus.clear_texture(); mpus.set_texture_hash(blob(user->qbaTextureHash)); } @@ -1610,10 +1663,12 @@ static void impl_Server_setTexture(const ::Murmur::AMD_Server_setTexturePtr cb, #define ACCESS_Server_getUptime_READ static void impl_Server_getUptime(const ::Murmur::AMD_Server_getUptimePtr cb, int server_id) { NEED_SERVER; - cb->ice_response(static_cast<int>(server->tUptime.elapsed()/1000000LL)); + cb->ice_response(static_cast< int >(server->tUptime.elapsed() / 1000000LL)); } -static void impl_Server_updateCertificate(const ::Murmur::AMD_Server_updateCertificatePtr cb, int server_id, const ::std::string& certificate, const ::std::string& privateKey, const ::std::string& passphrase) { +static void impl_Server_updateCertificate(const ::Murmur::AMD_Server_updateCertificatePtr cb, int server_id, + const ::std::string &certificate, const ::std::string &privateKey, + const ::std::string &passphrase) { NEED_SERVER; QByteArray certPem(certificate.c_str()); @@ -1655,7 +1710,8 @@ static void impl_Server_updateCertificate(const ::Murmur::AMD_Server_updateCerti cb->ice_response(); } -static void impl_Server_startListening(const ::Murmur::AMD_Server_startListeningPtr cb, int server_id, int session, int channelid) { +static void impl_Server_startListening(const ::Murmur::AMD_Server_startListeningPtr cb, int server_id, int session, + int channelid) { NEED_SERVER; NEED_CHANNEL; NEED_PLAYER; @@ -1665,7 +1721,8 @@ static void impl_Server_startListening(const ::Murmur::AMD_Server_startListening cb->ice_response(); } -static void impl_Server_stopListening(const ::Murmur::AMD_Server_stopListeningPtr cb, int server_id, int session, int channelid) { +static void impl_Server_stopListening(const ::Murmur::AMD_Server_stopListeningPtr cb, int server_id, int session, + int channelid) { NEED_SERVER; NEED_CHANNEL; NEED_PLAYER; @@ -1675,7 +1732,8 @@ static void impl_Server_stopListening(const ::Murmur::AMD_Server_stopListeningPt cb->ice_response(); } -static void impl_Server_isListening(const ::Murmur::AMD_Server_isListeningPtr cb, int server_id, int session, int channelid) { +static void impl_Server_isListening(const ::Murmur::AMD_Server_isListeningPtr cb, int server_id, int session, + int channelid) { NEED_SERVER; NEED_CHANNEL; NEED_PLAYER; @@ -1683,31 +1741,34 @@ static void impl_Server_isListening(const ::Murmur::AMD_Server_isListeningPtr cb cb->ice_response(ChannelListener::isListening(user, channel)); } -static void impl_Server_getListeningChannels(const ::Murmur::AMD_Server_getListeningChannelsPtr cb, int server_id, int session) { +static void impl_Server_getListeningChannels(const ::Murmur::AMD_Server_getListeningChannelsPtr cb, int server_id, + int session) { NEED_SERVER; NEED_PLAYER; ::Murmur::IntList channelIDs; - foreach(int currentChannelID, ChannelListener::getListenedChannelsForUser(user)) { + foreach (int currentChannelID, ChannelListener::getListenedChannelsForUser(user)) { channelIDs.push_back(currentChannelID); } cb->ice_response(channelIDs); } -static void impl_Server_getListeningUsers(const ::Murmur::AMD_Server_getListeningUsersPtr cb, int server_id, int channelid) { +static void impl_Server_getListeningUsers(const ::Murmur::AMD_Server_getListeningUsersPtr cb, int server_id, + int channelid) { NEED_SERVER; NEED_CHANNEL; ::Murmur::IntList userSessions; - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(channel)) { + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(channel)) { userSessions.push_back(currentSession); } cb->ice_response(userSessions); } -static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroupPtr cb, int server_id, ::Ice::Int channelid, ::Ice::Int session, const ::std::string& group) { +static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroupPtr cb, int server_id, + ::Ice::Int channelid, ::Ice::Int session, const ::std::string &group) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; @@ -1722,10 +1783,10 @@ static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroup QWriteLocker wl(&server->qrwlVoiceThread); ::Group *g = channel->qhGroups.value(qsgroup); - if (! g) + if (!g) g = new ::Group(channel, qsgroup); - g->qsTemporary.insert(- session); + g->qsTemporary.insert(-session); } server->clearACLCache(user); @@ -1733,7 +1794,8 @@ static void impl_Server_addUserToGroup(const ::Murmur::AMD_Server_addUserToGroup cb->ice_response(); } -static void impl_Server_removeUserFromGroup(const ::Murmur::AMD_Server_removeUserFromGroupPtr cb, int server_id, ::Ice::Int channelid, ::Ice::Int session, const ::std::string& group) { +static void impl_Server_removeUserFromGroup(const ::Murmur::AMD_Server_removeUserFromGroupPtr cb, int server_id, + ::Ice::Int channelid, ::Ice::Int session, const ::std::string &group) { NEED_SERVER; NEED_PLAYER; NEED_CHANNEL; @@ -1759,7 +1821,9 @@ static void impl_Server_removeUserFromGroup(const ::Murmur::AMD_Server_removeUse cb->ice_response(); } -static void impl_Server_redirectWhisperGroup(const ::Murmur::AMD_Server_redirectWhisperGroupPtr cb, int server_id, ::Ice::Int session, const ::std::string& source, const ::std::string& target) { +static void impl_Server_redirectWhisperGroup(const ::Murmur::AMD_Server_redirectWhisperGroupPtr cb, int server_id, + ::Ice::Int session, const ::std::string &source, + const ::std::string &target) { NEED_SERVER; NEED_PLAYER; @@ -1786,9 +1850,10 @@ static void impl_Meta_getSliceChecksums(const ::Murmur::AMD_Meta_getSliceChecksu } #define ACCESS_Meta_getServer_READ -static void impl_Meta_getServer(const ::Murmur::AMD_Meta_getServerPtr cb, const Ice::ObjectAdapterPtr adapter, ::Ice::Int id) { - QList<int> server_list = ServerDB::getAllServers(); - if (! server_list.contains(id)) +static void impl_Meta_getServer(const ::Murmur::AMD_Meta_getServerPtr cb, const Ice::ObjectAdapterPtr adapter, + ::Ice::Int id) { + QList< int > server_list = ServerDB::getAllServers(); + if (!server_list.contains(id)) cb->ice_response(nullptr); else cb->ice_response(idToProxy(id, adapter)); @@ -1802,7 +1867,7 @@ static void impl_Meta_newServer(const ::Murmur::AMD_Meta_newServerPtr cb, const static void impl_Meta_getAllServers(const ::Murmur::AMD_Meta_getAllServersPtr cb, const Ice::ObjectAdapterPtr adapter) { ::Murmur::ServerList sl; - foreach(int id, ServerDB::getAllServers()) + foreach (int id, ServerDB::getAllServers()) sl.push_back(idToProxy(id, adapter)); cb->ice_response(sl); } @@ -1810,8 +1875,8 @@ static void impl_Meta_getAllServers(const ::Murmur::AMD_Meta_getAllServersPtr cb #define ACCESS_Meta_getDefaultConf_READ static void impl_Meta_getDefaultConf(const ::Murmur::AMD_Meta_getDefaultConfPtr cb, const Ice::ObjectAdapterPtr) { ::Murmur::ConfigMap cm; - QMap<QString, QString>::const_iterator i; - for (i=meta->mp.qmConfig.constBegin();i != meta->mp.qmConfig.constEnd(); ++i) { + QMap< QString, QString >::const_iterator i; + for (i = meta->mp.qmConfig.constBegin(); i != meta->mp.qmConfig.constEnd(); ++i) { if (i.key() == "key" || i.key() == "passphrase") continue; cm[iceString(i.key())] = iceString(i.value()); @@ -1820,10 +1885,11 @@ static void impl_Meta_getDefaultConf(const ::Murmur::AMD_Meta_getDefaultConfPtr } #define ACCESS_Meta_getBootedServers_READ -static void impl_Meta_getBootedServers(const ::Murmur::AMD_Meta_getBootedServersPtr cb, const Ice::ObjectAdapterPtr adapter) { +static void impl_Meta_getBootedServers(const ::Murmur::AMD_Meta_getBootedServersPtr cb, + const Ice::ObjectAdapterPtr adapter) { ::Murmur::ServerList sl; - foreach(int id, meta->qhServers.keys()) + foreach (int id, meta->qhServers.keys()) sl.push_back(idToProxy(id, adapter)); cb->ice_response(sl); } @@ -1836,9 +1902,11 @@ static void impl_Meta_getVersion(const ::Murmur::AMD_Meta_getVersionPtr cb, cons cb->ice_response(major, minor, patch, iceString(txt)); } -static void impl_Meta_addCallback(const Murmur::AMD_Meta_addCallbackPtr cb, const Ice::ObjectAdapterPtr, const Murmur::MetaCallbackPrx& cbptr) { +static void impl_Meta_addCallback(const Murmur::AMD_Meta_addCallbackPtr cb, const Ice::ObjectAdapterPtr, + const Murmur::MetaCallbackPrx &cbptr) { try { - const Murmur::MetaCallbackPrx &oneway = Murmur::MetaCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::MetaCallbackPrx &oneway = + Murmur::MetaCallbackPrx::checkedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); mi->addMetaCallback(oneway); cb->ice_response(); } catch (...) { @@ -1846,9 +1914,11 @@ static void impl_Meta_addCallback(const Murmur::AMD_Meta_addCallbackPtr cb, cons } } -static void impl_Meta_removeCallback(const Murmur::AMD_Meta_removeCallbackPtr cb, const Ice::ObjectAdapterPtr, const Murmur::MetaCallbackPrx& cbptr) { +static void impl_Meta_removeCallback(const Murmur::AMD_Meta_removeCallbackPtr cb, const Ice::ObjectAdapterPtr, + const Murmur::MetaCallbackPrx &cbptr) { try { - const Murmur::MetaCallbackPrx &oneway = Murmur::MetaCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); + const Murmur::MetaCallbackPrx &oneway = + Murmur::MetaCallbackPrx::uncheckedCast(cbptr->ice_oneway()->ice_connectionCached(false)->ice_timeout(5000)); mi->removeMetaCallback(oneway); cb->ice_response(); } catch (...) { @@ -1858,7 +1928,7 @@ static void impl_Meta_removeCallback(const Murmur::AMD_Meta_removeCallbackPtr cb #define ACCESS_Meta_getUptime_ALL static void impl_Meta_getUptime(const ::Murmur::AMD_Meta_getUptimePtr cb, const Ice::ObjectAdapterPtr) { - cb->ice_response(static_cast<int>(meta->tUptime.elapsed()/1000000LL)); + cb->ice_response(static_cast< int >(meta->tUptime.elapsed() / 1000000LL)); } #include "MurmurIceWrapper.cpp" diff --git a/src/murmur/MurmurIce.h b/src/murmur/MurmurIce.h index a3c135c97..a5b3675ce 100644 --- a/src/murmur/MurmurIce.h +++ b/src/murmur/MurmurIce.h @@ -4,24 +4,24 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_ICE -#ifndef MUMBLE_MURMUR_MURMURICE_H_ -#define MUMBLE_MURMUR_MURMURICE_H_ +# ifndef MUMBLE_MURMUR_MURMURICE_H_ +# define MUMBLE_MURMUR_MURMURICE_H_ -#include <QtCore/QtGlobal> +# include <QtCore/QtGlobal> -#ifdef Q_OS_WIN +# ifdef Q_OS_WIN // To prevent <windows.h> (included by Ice) from including <winsock.h>. -# define WIN32_LEAN_AND_MEAN -#endif +# define WIN32_LEAN_AND_MEAN +# endif -#include <QtCore/QList> -#include <QtCore/QMap> -#include <QtCore/QMutex> -#include <QtCore/QObject> -#include <QtCore/QWaitCondition> -#include <QtNetwork/QSslCertificate> +# include <QtCore/QList> +# include <QtCore/QMap> +# include <QtCore/QMutex> +# include <QtCore/QObject> +# include <QtCore/QWaitCondition> +# include <QtNetwork/QSslCertificate> -#include "MurmurI.h" +# include "MurmurI.h" class Channel; class Server; @@ -29,67 +29,72 @@ class User; struct TextMessage; class MurmurIce : public QObject { - friend class MurmurLocker; - Q_OBJECT; - protected: - int count; - QMutex qmEvent; - QWaitCondition qwcEvent; - void customEvent(QEvent *evt); - void badMetaProxy(const ::Murmur::MetaCallbackPrx &prx); - void badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server* server); - void badAuthenticator(::Server *); - QList< ::Murmur::MetaCallbackPrx> qlMetaCallbacks; - QMap<int, QList< ::Murmur::ServerCallbackPrx> > qmServerCallbacks; - QMap<int, QMap<int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > > qmServerContextCallbacks; - QMap<int, ::Murmur::ServerAuthenticatorPrx> qmServerAuthenticator; - QMap<int, ::Murmur::ServerUpdatingAuthenticatorPrx> qmServerUpdatingAuthenticator; - public: - Ice::CommunicatorPtr communicator; - Ice::ObjectAdapterPtr adapter; - MurmurIce(); - ~MurmurIce(); + friend class MurmurLocker; + Q_OBJECT; + +protected: + int count; + QMutex qmEvent; + QWaitCondition qwcEvent; + void customEvent(QEvent *evt); + void badMetaProxy(const ::Murmur::MetaCallbackPrx &prx); + void badServerProxy(const ::Murmur::ServerCallbackPrx &prx, const ::Server *server); + void badAuthenticator(::Server *); + QList<::Murmur::MetaCallbackPrx > qlMetaCallbacks; + QMap< int, QList<::Murmur::ServerCallbackPrx > > qmServerCallbacks; + QMap< int, QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > > qmServerContextCallbacks; + QMap< int, ::Murmur::ServerAuthenticatorPrx > qmServerAuthenticator; + QMap< int, ::Murmur::ServerUpdatingAuthenticatorPrx > qmServerUpdatingAuthenticator; - void addMetaCallback(const ::Murmur::MetaCallbackPrx& prx); - void removeMetaCallback(const ::Murmur::MetaCallbackPrx& prx); - void addServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx); - void removeServerCallback(const ::Server* server, const ::Murmur::ServerCallbackPrx& prx); - void removeServerCallbacks(const ::Server* server); - void addServerContextCallback(const ::Server* server, int session_id, const QString& action, const ::Murmur::ServerContextCallbackPrx& prx); - const QMap< int, QMap<QString, ::Murmur::ServerContextCallbackPrx> > getServerContextCallbacks(const ::Server* server) const; - void removeServerContextCallback(const ::Server* server, int session_id, const QString& action); - void setServerAuthenticator(const ::Server* server, const ::Murmur::ServerAuthenticatorPrx& prx); - const ::Murmur::ServerAuthenticatorPrx getServerAuthenticator(const ::Server* server) const; - void removeServerAuthenticator(const ::Server* server); - void setServerUpdatingAuthenticator(const ::Server* server, const ::Murmur::ServerUpdatingAuthenticatorPrx& prx); - const ::Murmur::ServerUpdatingAuthenticatorPrx getServerUpdatingAuthenticator(const ::Server* server) const; - void removeServerUpdatingAuthenticator(const ::Server* server); +public: + Ice::CommunicatorPtr communicator; + Ice::ObjectAdapterPtr adapter; + MurmurIce(); + ~MurmurIce(); - public slots: - void started(Server *); - void stopped(Server *); + void addMetaCallback(const ::Murmur::MetaCallbackPrx &prx); + void removeMetaCallback(const ::Murmur::MetaCallbackPrx &prx); + void addServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx); + void removeServerCallback(const ::Server *server, const ::Murmur::ServerCallbackPrx &prx); + void removeServerCallbacks(const ::Server *server); + void addServerContextCallback(const ::Server *server, int session_id, const QString &action, + const ::Murmur::ServerContextCallbackPrx &prx); + const QMap< int, QMap< QString, ::Murmur::ServerContextCallbackPrx > > + getServerContextCallbacks(const ::Server *server) const; + void removeServerContextCallback(const ::Server *server, int session_id, const QString &action); + void setServerAuthenticator(const ::Server *server, const ::Murmur::ServerAuthenticatorPrx &prx); + const ::Murmur::ServerAuthenticatorPrx getServerAuthenticator(const ::Server *server) const; + void removeServerAuthenticator(const ::Server *server); + void setServerUpdatingAuthenticator(const ::Server *server, const ::Murmur::ServerUpdatingAuthenticatorPrx &prx); + const ::Murmur::ServerUpdatingAuthenticatorPrx getServerUpdatingAuthenticator(const ::Server *server) const; + void removeServerUpdatingAuthenticator(const ::Server *server); - void authenticateSlot(int &res, QString &uname, int sessionId, const QList<QSslCertificate> &certlist, const QString &certhash, bool certstrong, const QString &pw); - void registerUserSlot(int &res, const QMap<int, QString> &); - void unregisterUserSlot(int &res, int id); - void getRegisteredUsersSlot(const QString &filter, QMap<int, QString> &res); - void getRegistrationSlot(int &, int, QMap<int, QString> &); - void setInfoSlot(int &, int, const QMap<int, QString> &); - void setTextureSlot(int &res, int id, const QByteArray &texture); - void nameToIdSlot(int &res, const QString &name); - void idToNameSlot(QString &res, int id); - void idToTextureSlot(QByteArray &res, int id); +public slots: + void started(Server *); + void stopped(Server *); - void userStateChanged(const User *p); - void userTextMessage(const User *p, const TextMessage &); - void userConnected(const User *p); - void userDisconnected(const User *p); + void authenticateSlot(int &res, QString &uname, int sessionId, const QList< QSslCertificate > &certlist, + const QString &certhash, bool certstrong, const QString &pw); + void registerUserSlot(int &res, const QMap< int, QString > &); + void unregisterUserSlot(int &res, int id); + void getRegisteredUsersSlot(const QString &filter, QMap< int, QString > &res); + void getRegistrationSlot(int &, int, QMap< int, QString > &); + void setInfoSlot(int &, int, const QMap< int, QString > &); + void setTextureSlot(int &res, int id, const QByteArray &texture); + void nameToIdSlot(int &res, const QString &name); + void idToNameSlot(QString &res, int id); + void idToTextureSlot(QByteArray &res, int id); - void channelStateChanged(const Channel *c); - void channelCreated(const Channel *c); - void channelRemoved(const Channel *c); + void userStateChanged(const User *p); + void userTextMessage(const User *p, const TextMessage &); + void userConnected(const User *p); + void userDisconnected(const User *p); - void contextAction(const User *, const QString &, unsigned int, int); + void channelStateChanged(const Channel *c); + void channelCreated(const Channel *c); + void channelRemoved(const Channel *c); + + void contextAction(const User *, const QString &, unsigned int, int); }; -#endif +# endif #endif diff --git a/src/murmur/MurmurIceWrapper.cpp b/src/murmur/MurmurIceWrapper.cpp index 6d735fd27..8e909529f 100644 --- a/src/murmur/MurmurIceWrapper.cpp +++ b/src/murmur/MurmurIceWrapper.cpp @@ -5,54 +5,55 @@ void ::Murmur::ServerI::isRunning_async(const ::Murmur::AMD_Server_isRunningPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "isRunning" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_isRunning_ALL -#ifdef ACCESS_Server_isRunning_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_isRunning_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_isRunning_READ +# ifdef ACCESS_Server_isRunning_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_isRunning, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_isRunning, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::start_async(const ::Murmur::AMD_Server_startPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "start" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_start_ALL -#ifdef ACCESS_Server_start_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_start_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_start_READ +# ifdef ACCESS_Server_start_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -65,24 +66,24 @@ void ::Murmur::ServerI::start_async(const ::Murmur::AMD_Server_startPtr &cb, con void ::Murmur::ServerI::stop_async(const ::Murmur::AMD_Server_stopPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "stop" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_stop_ALL -#ifdef ACCESS_Server_stop_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_stop_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_stop_READ +# ifdef ACCESS_Server_stop_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -95,54 +96,55 @@ void ::Murmur::ServerI::stop_async(const ::Murmur::AMD_Server_stopPtr &cb, const void ::Murmur::ServerI::delete_async(const ::Murmur::AMD_Server_deletePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "delete" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_delete_ALL -#ifdef ACCESS_Server_delete_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_delete_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_delete_READ +# ifdef ACCESS_Server_delete_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_delete, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_delete, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::id_async(const ::Murmur::AMD_Server_idPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "id" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_id_ALL -#ifdef ACCESS_Server_id_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_id_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_id_READ +# ifdef ACCESS_Server_id_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -152,1527 +154,1630 @@ void ::Murmur::ServerI::id_async(const ::Murmur::AMD_Server_idPtr &cb, const ::I QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr &cb, const ::Murmur::ServerCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addCallback_async(const ::Murmur::AMD_Server_addCallbackPtr &cb, + const ::Murmur::ServerCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "addCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addCallback_ALL -#ifdef ACCESS_Server_addCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addCallback_READ +# ifdef ACCESS_Server_addCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_addCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr &cb, const ::Murmur::ServerCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeCallback_async(const ::Murmur::AMD_Server_removeCallbackPtr &cb, + const ::Murmur::ServerCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "removeCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeCallback_ALL -#ifdef ACCESS_Server_removeCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeCallback_READ +# ifdef ACCESS_Server_removeCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_removeCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr &cb, const ::Murmur::ServerAuthenticatorPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setAuthenticator_async(const ::Murmur::AMD_Server_setAuthenticatorPtr &cb, + const ::Murmur::ServerAuthenticatorPrx &p1, + const ::Ice::Current ¤t) { // qWarning() << "setAuthenticator" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setAuthenticator_ALL -#ifdef ACCESS_Server_setAuthenticator_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setAuthenticator_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setAuthenticator_READ +# ifdef ACCESS_Server_setAuthenticator_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setAuthenticator, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setAuthenticator, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getConf_async(const ::Murmur::AMD_Server_getConfPtr &cb, const ::std::string& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getConf_async(const ::Murmur::AMD_Server_getConfPtr &cb, const ::std::string &p1, + const ::Ice::Current ¤t) { // qWarning() << "getConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getConf_ALL -#ifdef ACCESS_Server_getConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getConf_READ +# ifdef ACCESS_Server_getConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getConf, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getConf, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getAllConf_async(const ::Murmur::AMD_Server_getAllConfPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getAllConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getAllConf_ALL -#ifdef ACCESS_Server_getAllConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getAllConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getAllConf_READ +# ifdef ACCESS_Server_getAllConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getAllConf, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getAllConf, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setConf_async(const ::Murmur::AMD_Server_setConfPtr &cb, const ::std::string& p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setConf_async(const ::Murmur::AMD_Server_setConfPtr &cb, const ::std::string &p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "setConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setConf_ALL -#ifdef ACCESS_Server_setConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setConf_READ +# ifdef ACCESS_Server_setConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setConf, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_setConf, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr &cb, const ::std::string& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setSuperuserPassword_async(const ::Murmur::AMD_Server_setSuperuserPasswordPtr &cb, + const ::std::string &p1, const ::Ice::Current ¤t) { // qWarning() << "setSuperuserPassword" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setSuperuserPassword_ALL -#ifdef ACCESS_Server_setSuperuserPassword_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setSuperuserPassword_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setSuperuserPassword_READ +# ifdef ACCESS_Server_setSuperuserPassword_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setSuperuserPassword, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setSuperuserPassword, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getLog_async(const ::Murmur::AMD_Server_getLogPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getLog_async(const ::Murmur::AMD_Server_getLogPtr &cb, ::Ice::Int p1, ::Ice::Int p2, + const ::Ice::Current ¤t) { // qWarning() << "getLog" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getLog_ALL -#ifdef ACCESS_Server_getLog_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getLog_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getLog_READ +# ifdef ACCESS_Server_getLog_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getLog, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getLog, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getLogLen_async(const ::Murmur::AMD_Server_getLogLenPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getLogLen" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getLogLen_ALL -#ifdef ACCESS_Server_getLogLen_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getLogLen_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getLogLen_READ +# ifdef ACCESS_Server_getLogLen_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getLogLen, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getLogLen, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getUsers_async(const ::Murmur::AMD_Server_getUsersPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getUsers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUsers_ALL -#ifdef ACCESS_Server_getUsers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUsers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUsers_READ +# ifdef ACCESS_Server_getUsers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUsers, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUsers, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getChannels_async(const ::Murmur::AMD_Server_getChannelsPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getChannels" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getChannels_ALL -#ifdef ACCESS_Server_getChannels_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getChannels_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getChannels_READ +# ifdef ACCESS_Server_getChannels_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getChannels, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getChannels, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getCertificateList_async(const ::Murmur::AMD_Server_getCertificateListPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getCertificateList" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getCertificateList_ALL -#ifdef ACCESS_Server_getCertificateList_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getCertificateList_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getCertificateList_READ +# ifdef ACCESS_Server_getCertificateList_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getCertificateList, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getCertificateList, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getTree_async(const ::Murmur::AMD_Server_getTreePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getTree" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getTree_ALL -#ifdef ACCESS_Server_getTree_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getTree_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getTree_READ +# ifdef ACCESS_Server_getTree_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getTree, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getTree, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getBans_async(const ::Murmur::AMD_Server_getBansPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getBans" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getBans_ALL -#ifdef ACCESS_Server_getBans_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getBans_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getBans_READ +# ifdef ACCESS_Server_getBans_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getBans, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getBans, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setBans_async(const ::Murmur::AMD_Server_setBansPtr &cb, const ::Murmur::BanList& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setBans_async(const ::Murmur::AMD_Server_setBansPtr &cb, const ::Murmur::BanList &p1, + const ::Ice::Current ¤t) { // qWarning() << "setBans" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setBans_ALL -#ifdef ACCESS_Server_setBans_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setBans_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setBans_READ +# ifdef ACCESS_Server_setBans_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setBans, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_setBans, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::kickUser_async(const ::Murmur::AMD_Server_kickUserPtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::kickUser_async(const ::Murmur::AMD_Server_kickUserPtr &cb, ::Ice::Int p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "kickUser" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_kickUser_ALL -#ifdef ACCESS_Server_kickUser_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_kickUser_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_kickUser_READ +# ifdef ACCESS_Server_kickUser_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_kickUser, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_kickUser, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getState_async(const ::Murmur::AMD_Server_getStatePtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getState_async(const ::Murmur::AMD_Server_getStatePtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getState_ALL -#ifdef ACCESS_Server_getState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getState_READ +# ifdef ACCESS_Server_getState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setState_async(const ::Murmur::AMD_Server_setStatePtr &cb, const ::Murmur::User& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setState_async(const ::Murmur::AMD_Server_setStatePtr &cb, const ::Murmur::User &p1, + const ::Ice::Current ¤t) { // qWarning() << "setState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setState_ALL -#ifdef ACCESS_Server_setState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setState_READ +# ifdef ACCESS_Server_setState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_setState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::sendMessage_async(const ::Murmur::AMD_Server_sendMessagePtr &cb, ::Ice::Int p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "sendMessage" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_sendMessage_ALL -#ifdef ACCESS_Server_sendMessage_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_sendMessage_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_sendMessage_READ +# ifdef ACCESS_Server_sendMessage_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_sendMessage, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_sendMessage, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr &cb, ::Ice::Int p1, ::Ice::Int p2, ::Ice::Int p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::hasPermission_async(const ::Murmur::AMD_Server_hasPermissionPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, ::Ice::Int p3, const ::Ice::Current ¤t) { // qWarning() << "hasPermission" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_hasPermission_ALL -#ifdef ACCESS_Server_hasPermission_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_hasPermission_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_hasPermission_READ +# ifdef ACCESS_Server_hasPermission_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_hasPermission, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_hasPermission, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::effectivePermissions_async(const ::Murmur::AMD_Server_effectivePermissionsPtr &cb, + ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "effectivePermissions" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_effectivePermissions_ALL -#ifdef ACCESS_Server_effectivePermissions_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_effectivePermissions_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_effectivePermissions_READ +# ifdef ACCESS_Server_effectivePermissions_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_effectivePermissions, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_effectivePermissions, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::std::string& p3, const ::Murmur::ServerContextCallbackPrx& p4, ::Ice::Int p5, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addContextCallback_async(const ::Murmur::AMD_Server_addContextCallbackPtr &cb, ::Ice::Int p1, + const ::std::string &p2, const ::std::string &p3, + const ::Murmur::ServerContextCallbackPrx &p4, ::Ice::Int p5, + const ::Ice::Current ¤t) { // qWarning() << "addContextCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addContextCallback_ALL -#ifdef ACCESS_Server_addContextCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addContextCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addContextCallback_READ +# ifdef ACCESS_Server_addContextCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addContextCallback, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4, p5)); + ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addContextCallback, cb, + QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4, p5)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr &cb, const ::Murmur::ServerContextCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeContextCallback_async(const ::Murmur::AMD_Server_removeContextCallbackPtr &cb, + const ::Murmur::ServerContextCallbackPrx &p1, + const ::Ice::Current ¤t) { // qWarning() << "removeContextCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeContextCallback_ALL -#ifdef ACCESS_Server_removeContextCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeContextCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeContextCallback_READ +# ifdef ACCESS_Server_removeContextCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeContextCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_removeContextCallback, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getChannelState_async(const ::Murmur::AMD_Server_getChannelStatePtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getChannelState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getChannelState_ALL -#ifdef ACCESS_Server_getChannelState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getChannelState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getChannelState_READ +# ifdef ACCESS_Server_getChannelState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr &cb, const ::Murmur::Channel& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setChannelState_async(const ::Murmur::AMD_Server_setChannelStatePtr &cb, + const ::Murmur::Channel &p1, const ::Ice::Current ¤t) { // qWarning() << "setChannelState" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setChannelState_ALL -#ifdef ACCESS_Server_setChannelState_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setChannelState_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setChannelState_READ +# ifdef ACCESS_Server_setChannelState_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setChannelState, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeChannel_async(const ::Murmur::AMD_Server_removeChannelPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "removeChannel" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeChannel_ALL -#ifdef ACCESS_Server_removeChannel_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeChannel_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeChannel_READ +# ifdef ACCESS_Server_removeChannel_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeChannel, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_removeChannel, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addChannel_async(const ::Murmur::AMD_Server_addChannelPtr &cb, const ::std::string& p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addChannel_async(const ::Murmur::AMD_Server_addChannelPtr &cb, const ::std::string &p1, + ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "addChannel" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addChannel_ALL -#ifdef ACCESS_Server_addChannel_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addChannel_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addChannel_READ +# ifdef ACCESS_Server_addChannel_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_addChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr &cb, ::Ice::Int p1, bool p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::sendMessageChannel_async(const ::Murmur::AMD_Server_sendMessageChannelPtr &cb, ::Ice::Int p1, + bool p2, const ::std::string &p3, const ::Ice::Current ¤t) { // qWarning() << "sendMessageChannel" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_sendMessageChannel_ALL -#ifdef ACCESS_Server_sendMessageChannel_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_sendMessageChannel_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_sendMessageChannel_READ +# ifdef ACCESS_Server_sendMessageChannel_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_sendMessageChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_sendMessageChannel, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getACL_async(const ::Murmur::AMD_Server_getACLPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getACL_async(const ::Murmur::AMD_Server_getACLPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getACL" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getACL_ALL -#ifdef ACCESS_Server_getACL_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getACL_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getACL_READ +# ifdef ACCESS_Server_getACL_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getACL, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getACL, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setACL_async(const ::Murmur::AMD_Server_setACLPtr &cb, ::Ice::Int p1, const ::Murmur::ACLList& p2, const ::Murmur::GroupList& p3, bool p4, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setACL_async(const ::Murmur::AMD_Server_setACLPtr &cb, ::Ice::Int p1, + const ::Murmur::ACLList &p2, const ::Murmur::GroupList &p3, bool p4, + const ::Ice::Current ¤t) { // qWarning() << "setACL" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setACL_ALL -#ifdef ACCESS_Server_setACL_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setACL_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setACL_READ +# ifdef ACCESS_Server_setACL_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setACL, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setACL, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3, p4)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::addUserToGroup_async(const ::Murmur::AMD_Server_addUserToGroupPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::std::string &p3, const ::Ice::Current ¤t) { // qWarning() << "addUserToGroup" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_addUserToGroup_ALL -#ifdef ACCESS_Server_addUserToGroup_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_addUserToGroup_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_addUserToGroup_READ +# ifdef ACCESS_Server_addUserToGroup_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_addUserToGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_addUserToGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::removeUserFromGroup_async(const ::Murmur::AMD_Server_removeUserFromGroupPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::std::string &p3, + const ::Ice::Current ¤t) { // qWarning() << "removeUserFromGroup" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_removeUserFromGroup_ALL -#ifdef ACCESS_Server_removeUserFromGroup_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_removeUserFromGroup_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_removeUserFromGroup_READ +# ifdef ACCESS_Server_removeUserFromGroup_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_removeUserFromGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_removeUserFromGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr &cb, ::Ice::Int p1, const ::std::string& p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::redirectWhisperGroup_async(const ::Murmur::AMD_Server_redirectWhisperGroupPtr &cb, + ::Ice::Int p1, const ::std::string &p2, const ::std::string &p3, + const ::Ice::Current ¤t) { // qWarning() << "redirectWhisperGroup" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_redirectWhisperGroup_ALL -#ifdef ACCESS_Server_redirectWhisperGroup_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_redirectWhisperGroup_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_redirectWhisperGroup_READ +# ifdef ACCESS_Server_redirectWhisperGroup_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_redirectWhisperGroup, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_redirectWhisperGroup, cb, + QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr &cb, const ::Murmur::IdList& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getUserNames_async(const ::Murmur::AMD_Server_getUserNamesPtr &cb, const ::Murmur::IdList &p1, + const ::Ice::Current ¤t) { // qWarning() << "getUserNames" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUserNames_ALL -#ifdef ACCESS_Server_getUserNames_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUserNames_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUserNames_READ +# ifdef ACCESS_Server_getUserNames_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUserNames, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUserNames, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr &cb, const ::Murmur::NameList& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getUserIds_async(const ::Murmur::AMD_Server_getUserIdsPtr &cb, const ::Murmur::NameList &p1, + const ::Ice::Current ¤t) { // qWarning() << "getUserIds" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUserIds_ALL -#ifdef ACCESS_Server_getUserIds_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUserIds_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUserIds_READ +# ifdef ACCESS_Server_getUserIds_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUserIds, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUserIds, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::registerUser_async(const ::Murmur::AMD_Server_registerUserPtr &cb, const ::Murmur::UserInfoMap& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::registerUser_async(const ::Murmur::AMD_Server_registerUserPtr &cb, + const ::Murmur::UserInfoMap &p1, const ::Ice::Current ¤t) { // qWarning() << "registerUser" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_registerUser_ALL -#ifdef ACCESS_Server_registerUser_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_registerUser_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_registerUser_READ +# ifdef ACCESS_Server_registerUser_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_registerUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_registerUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::unregisterUser_async(const ::Murmur::AMD_Server_unregisterUserPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "unregisterUser" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_unregisterUser_ALL -#ifdef ACCESS_Server_unregisterUser_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_unregisterUser_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_unregisterUser_READ +# ifdef ACCESS_Server_unregisterUser_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_unregisterUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_unregisterUser, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr &cb, ::Ice::Int p1, const ::Murmur::UserInfoMap& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::updateRegistration_async(const ::Murmur::AMD_Server_updateRegistrationPtr &cb, ::Ice::Int p1, + const ::Murmur::UserInfoMap &p2, const ::Ice::Current ¤t) { // qWarning() << "updateRegistration" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_updateRegistration_ALL -#ifdef ACCESS_Server_updateRegistration_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_updateRegistration_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_updateRegistration_READ +# ifdef ACCESS_Server_updateRegistration_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_updateRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_updateRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getRegistration_async(const ::Murmur::AMD_Server_getRegistrationPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getRegistration" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getRegistration_ALL -#ifdef ACCESS_Server_getRegistration_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getRegistration_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getRegistration_READ +# ifdef ACCESS_Server_getRegistration_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getRegistration, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr &cb, const ::std::string& p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getRegisteredUsers_async(const ::Murmur::AMD_Server_getRegisteredUsersPtr &cb, + const ::std::string &p1, const ::Ice::Current ¤t) { // qWarning() << "getRegisteredUsers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getRegisteredUsers_ALL -#ifdef ACCESS_Server_getRegisteredUsers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getRegisteredUsers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getRegisteredUsers_READ +# ifdef ACCESS_Server_getRegisteredUsers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getRegisteredUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getRegisteredUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr &cb, const ::std::string& p1, const ::std::string& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::verifyPassword_async(const ::Murmur::AMD_Server_verifyPasswordPtr &cb, const ::std::string &p1, + const ::std::string &p2, const ::Ice::Current ¤t) { // qWarning() << "verifyPassword" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_verifyPassword_ALL -#ifdef ACCESS_Server_verifyPassword_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_verifyPassword_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_verifyPassword_READ +# ifdef ACCESS_Server_verifyPassword_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_verifyPassword, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_verifyPassword, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getTexture_async(const ::Murmur::AMD_Server_getTexturePtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getTexture_async(const ::Murmur::AMD_Server_getTexturePtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getTexture" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getTexture_ALL -#ifdef ACCESS_Server_getTexture_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getTexture_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getTexture_READ +# ifdef ACCESS_Server_getTexture_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getTexture, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getTexture, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::setTexture_async(const ::Murmur::AMD_Server_setTexturePtr &cb, ::Ice::Int p1, const ::Murmur::Texture& p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::setTexture_async(const ::Murmur::AMD_Server_setTexturePtr &cb, ::Ice::Int p1, + const ::Murmur::Texture &p2, const ::Ice::Current ¤t) { // qWarning() << "setTexture" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_setTexture_ALL -#ifdef ACCESS_Server_setTexture_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_setTexture_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_setTexture_READ +# ifdef ACCESS_Server_setTexture_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_setTexture, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_setTexture, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } void ::Murmur::ServerI::getUptime_async(const ::Murmur::AMD_Server_getUptimePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getUptime" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getUptime_ALL -#ifdef ACCESS_Server_getUptime_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getUptime_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getUptime_READ +# ifdef ACCESS_Server_getUptime_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getUptime, cb, QString::fromStdString(current.id.name).toInt())); + ExecEvent *ie = + new ExecEvent(boost::bind(&impl_Server_getUptime, cb, QString::fromStdString(current.id.name).toInt())); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr &cb, const ::std::string& p1, const ::std::string& p2, const ::std::string& p3, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::updateCertificate_async(const ::Murmur::AMD_Server_updateCertificatePtr &cb, + const ::std::string &p1, const ::std::string &p2, + const ::std::string &p3, const ::Ice::Current ¤t) { // qWarning() << "updateCertificate" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_updateCertificate_ALL -#ifdef ACCESS_Server_updateCertificate_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_updateCertificate_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_updateCertificate_READ +# ifdef ACCESS_Server_updateCertificate_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_updateCertificate, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_updateCertificate, cb, QString::fromStdString(current.id.name).toInt(), p1, p2, p3)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::startListening_async(const ::Murmur::AMD_Server_startListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::startListening_async(const ::Murmur::AMD_Server_startListeningPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "startListening" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_startListening_ALL -#ifdef ACCESS_Server_startListening_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_startListening_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_startListening_READ +# ifdef ACCESS_Server_startListening_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_startListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_startListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::stopListening_async(const ::Murmur::AMD_Server_stopListeningPtr &cb, ::Ice::Int p1, + ::Ice::Int p2, const ::Ice::Current ¤t) { // qWarning() << "stopListening" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_stopListening_ALL -#ifdef ACCESS_Server_stopListening_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_stopListening_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_stopListening_READ +# ifdef ACCESS_Server_stopListening_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_stopListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_stopListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::isListening_async(const ::Murmur::AMD_Server_isListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::isListening_async(const ::Murmur::AMD_Server_isListeningPtr &cb, ::Ice::Int p1, ::Ice::Int p2, + const ::Ice::Current ¤t) { // qWarning() << "isListening" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_isListening_ALL -#ifdef ACCESS_Server_isListening_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_isListening_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_isListening_READ +# ifdef ACCESS_Server_isListening_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_isListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_isListening, cb, QString::fromStdString(current.id.name).toInt(), p1, p2)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getListeningChannels_async(const ::Murmur::AMD_Server_getListeningChannelsPtr &cb, + ::Ice::Int p1, const ::Ice::Current ¤t) { // qWarning() << "getListeningChannels" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getListeningChannels_ALL -#ifdef ACCESS_Server_getListeningChannels_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getListeningChannels_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getListeningChannels_READ +# ifdef ACCESS_Server_getListeningChannels_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getListeningChannels, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getListeningChannels, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::ServerI::getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::ServerI::getListeningUsers_async(const ::Murmur::AMD_Server_getListeningUsersPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getListeningUsers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Server_getListeningUsers_ALL -#ifdef ACCESS_Server_getListeningUsers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Server_getListeningUsers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Server_getListeningUsers_READ +# ifdef ACCESS_Server_getListeningUsers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } } #endif - ExecEvent *ie = new ExecEvent(boost::bind(&impl_Server_getListeningUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); + ExecEvent *ie = new ExecEvent( + boost::bind(&impl_Server_getListeningUsers, cb, QString::fromStdString(current.id.name).toInt(), p1)); QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getServer_async(const ::Murmur::AMD_Meta_getServerPtr &cb, ::Ice::Int p1, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getServer_async(const ::Murmur::AMD_Meta_getServerPtr &cb, ::Ice::Int p1, + const ::Ice::Current ¤t) { // qWarning() << "getServer" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getServer_ALL -#ifdef ACCESS_Meta_getServer_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getServer_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getServer_READ +# ifdef ACCESS_Meta_getServer_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1685,24 +1790,24 @@ void ::Murmur::MetaI::getServer_async(const ::Murmur::AMD_Meta_getServerPtr &cb, void ::Murmur::MetaI::newServer_async(const ::Murmur::AMD_Meta_newServerPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "newServer" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_newServer_ALL -#ifdef ACCESS_Meta_newServer_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_newServer_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_newServer_READ +# ifdef ACCESS_Meta_newServer_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1712,27 +1817,28 @@ void ::Murmur::MetaI::newServer_async(const ::Murmur::AMD_Meta_newServerPtr &cb, QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getBootedServers_async(const ::Murmur::AMD_Meta_getBootedServersPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getBootedServers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getBootedServers_ALL -#ifdef ACCESS_Meta_getBootedServers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getBootedServers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getBootedServers_READ +# ifdef ACCESS_Meta_getBootedServers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1742,27 +1848,28 @@ void ::Murmur::MetaI::getBootedServers_async(const ::Murmur::AMD_Meta_getBootedS QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getAllServers_async(const ::Murmur::AMD_Meta_getAllServersPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getAllServers" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getAllServers_ALL -#ifdef ACCESS_Meta_getAllServers_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getAllServers_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getAllServers_READ +# ifdef ACCESS_Meta_getAllServers_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1772,27 +1879,28 @@ void ::Murmur::MetaI::getAllServers_async(const ::Murmur::AMD_Meta_getAllServers QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultConfPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getDefaultConf" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getDefaultConf_ALL -#ifdef ACCESS_Meta_getDefaultConf_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getDefaultConf_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getDefaultConf_READ +# ifdef ACCESS_Meta_getDefaultConf_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1805,24 +1913,24 @@ void ::Murmur::MetaI::getDefaultConf_async(const ::Murmur::AMD_Meta_getDefaultCo void ::Murmur::MetaI::getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getVersion" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getVersion_ALL -#ifdef ACCESS_Meta_getVersion_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getVersion_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getVersion_READ +# ifdef ACCESS_Meta_getVersion_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1832,27 +1940,28 @@ void ::Murmur::MetaI::getVersion_async(const ::Murmur::AMD_Meta_getVersionPtr &c QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr &cb, const ::Murmur::MetaCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr &cb, + const ::Murmur::MetaCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "addCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_addCallback_ALL -#ifdef ACCESS_Meta_addCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_addCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_addCallback_READ +# ifdef ACCESS_Meta_addCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1862,27 +1971,28 @@ void ::Murmur::MetaI::addCallback_async(const ::Murmur::AMD_Meta_addCallbackPtr QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr &cb, const ::Murmur::MetaCallbackPrx& p1, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::removeCallback_async(const ::Murmur::AMD_Meta_removeCallbackPtr &cb, + const ::Murmur::MetaCallbackPrx &p1, const ::Ice::Current ¤t) { // qWarning() << "removeCallback" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_removeCallback_ALL -#ifdef ACCESS_Meta_removeCallback_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_removeCallback_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_removeCallback_READ +# ifdef ACCESS_Meta_removeCallback_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1895,24 +2005,24 @@ void ::Murmur::MetaI::removeCallback_async(const ::Murmur::AMD_Meta_removeCallba void ::Murmur::MetaI::getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr &cb, const ::Ice::Current ¤t) { // qWarning() << "getUptime" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getUptime_ALL -#ifdef ACCESS_Meta_getUptime_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getUptime_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getUptime_READ +# ifdef ACCESS_Meta_getUptime_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1922,27 +2032,28 @@ void ::Murmur::MetaI::getUptime_async(const ::Murmur::AMD_Meta_getUptimePtr &cb, QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr &cb, const ::Ice::Current ¤t) { +void ::Murmur::MetaI::getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceChecksumsPtr &cb, + const ::Ice::Current ¤t) { // qWarning() << "getSliceChecksums" << meta->mp.qsIceSecretRead.isNull() << meta->mp.qsIceSecretRead.isEmpty(); #ifndef ACCESS_Meta_getSliceChecksums_ALL -#ifdef ACCESS_Meta_getSliceChecksums_READ - if (! meta->mp.qsIceSecretRead.isNull()) { - bool ok = ! meta->mp.qsIceSecretRead.isEmpty(); -#else - if (! meta->mp.qsIceSecretRead.isNull() || ! meta->mp.qsIceSecretWrite.isNull()) { - bool ok = ! meta->mp.qsIceSecretWrite.isEmpty(); -#endif +# ifdef ACCESS_Meta_getSliceChecksums_READ + if (!meta->mp.qsIceSecretRead.isNull()) { + bool ok = !meta->mp.qsIceSecretRead.isEmpty(); +# else + if (!meta->mp.qsIceSecretRead.isNull() || !meta->mp.qsIceSecretWrite.isNull()) { + bool ok = !meta->mp.qsIceSecretWrite.isEmpty(); +# endif ::Ice::Context::const_iterator i = current.ctx.find("secret"); - ok = ok && (i != current.ctx.end()); + ok = ok && (i != current.ctx.end()); if (ok) { const QString &secret = u8((*i).second); -#ifdef ACCESS_Meta_getSliceChecksums_READ +# ifdef ACCESS_Meta_getSliceChecksums_READ ok = ((secret == meta->mp.qsIceSecretRead) || (secret == meta->mp.qsIceSecretWrite)); -#else +# else ok = (secret == meta->mp.qsIceSecretWrite); -#endif +# endif } - if (! ok) { + if (!ok) { cb->ice_exception(InvalidSecretException()); return; } @@ -1952,6 +2063,126 @@ void ::Murmur::MetaI::getSliceChecksums_async(const ::Murmur::AMD_Meta_getSliceC QCoreApplication::instance()->postEvent(mi, ie); } -void ::Murmur::MetaI::getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr& cb, const Ice::Current&) { - cb->ice_response(std::string("// Copyright 2005-2020 The Mumble Developers. All rights reserved.\n// Use of this source code is governed by a BSD-style license\n// that can be found in the LICENSE file at the root of the\n// Mumble source tree or at <https://www.mumble.info/LICENSE>.\n#include <Ice/SliceChecksumDict.ice>\nmodule Murmur\n{\n[\"python:seq:tuple\"] sequence<byte> NetAddress;\nstruct User {\nint session;\nint userid;\nbool mute;\nbool deaf;\nbool suppress;\nbool prioritySpeaker;\nbool selfMute;\nbool selfDeaf;\nbool recording;\nint channel;\nstring name;\nint onlinesecs;\nint bytespersec;\nint version;\nstring release;\nstring os;\nstring osversion;\nstring identity;\nstring context;\nstring comment;\nNetAddress address;\nbool tcponly;\nint idlesecs;\nfloat udpPing;\nfloat tcpPing;\n};\nsequence<int> IntList;\nstruct TextMessage {\nIntList sessions;\nIntList channels;\nIntList trees;\nstring text;\n};\nstruct Channel {\nint id;\nstring name;\nint parent;\nIntList links;\nstring description;\nbool temporary;\nint position;\n};\nstruct Group {\nstring name;\nbool inherited;\nbool inherit;\nbool inheritable;\nIntList add;\nIntList remove;\nIntList members;\n};\nconst int PermissionWrite = 0x01;\nconst int PermissionTraverse = 0x02;\nconst int PermissionEnter = 0x04;\nconst int PermissionSpeak = 0x08;\nconst int PermissionWhisper = 0x100;\nconst int PermissionMuteDeafen = 0x10;\nconst int PermissionMove = 0x20;\nconst int PermissionMakeChannel = 0x40;\nconst int PermissionMakeTempChannel = 0x400;\nconst int PermissionLinkChannel = 0x80;\nconst int PermissionTextMessage = 0x200;\nconst int PermissionKick = 0x10000;\nconst int PermissionBan = 0x20000;\nconst int PermissionRegister = 0x40000;\nconst int PermissionRegisterSelf = 0x80000;\nstruct ACL {\nbool applyHere;\nbool applySubs;\nbool inherited;\nint userid;\nstring group;\nint allow;\nint deny;\n};\nstruct Ban {\nNetAddress address;\nint bits;\nstring name;\nstring hash;\nstring reason;\nint start;\nint duration;\n};\nstruct LogEntry {\nint timestamp;\nstring txt;\n};\nclass Tree;\nsequence<Tree> TreeList;\nenum ChannelInfo { ChannelDescription, ChannelPosition };\nenum UserInfo { UserName, UserEmail, UserComment, UserHash, UserPassword, UserLastActive, UserKDFIterations };\ndictionary<int, User> UserMap;\ndictionary<int, Channel> ChannelMap;\nsequence<Channel> ChannelList;\nsequence<User> UserList;\nsequence<Group> GroupList;\nsequence<ACL> ACLList;\nsequence<LogEntry> LogList;\nsequence<Ban> BanList;\nsequence<int> IdList;\nsequence<string> NameList;\ndictionary<int, string> NameMap;\ndictionary<string, int> IdMap;\nsequence<byte> Texture;\ndictionary<string, string> ConfigMap;\nsequence<string> GroupNameList;\nsequence<byte> CertificateDer;\nsequence<CertificateDer> CertificateList;\ndictionary<UserInfo, string> UserInfoMap;\nclass Tree {\nChannel c;\nTreeList children;\nUserList users;\n};\nexception MurmurException {};\nexception InvalidSessionException extends MurmurException {};\nexception InvalidChannelException extends MurmurException {};\nexception InvalidServerException extends MurmurException {};\nexception ServerBootedException extends MurmurException {};\nexception ServerFailureException extends MurmurException {};\nexception InvalidUserException extends MurmurException {};\nexception InvalidTextureException extends MurmurException {};\nexception InvalidCallbackException extends MurmurException {};\nexception InvalidSecretException extends MurmurException {};\nexception NestingLimitException extends MurmurException {};\nexception WriteOnlyException extends MurmurException {};\nexception InvalidInputDataException extends MurmurException {};\ninterface ServerCallback {\nidempotent void userConnected(User state);\nidempotent void userDisconnected(User state);\nidempotent void userStateChanged(User state);\nidempotent void userTextMessage(User state, TextMessage message);\nidempotent void channelCreated(Channel state);\nidempotent void channelRemoved(Channel state);\nidempotent void channelStateChanged(Channel state);\n};\nconst int ContextServer = 0x01;\nconst int ContextChannel = 0x02;\nconst int ContextUser = 0x04;\ninterface ServerContextCallback {\nidempotent void contextAction(string action, User usr, int session, int channelid);\n};\ninterface ServerAuthenticator {\nidempotent int authenticate(string name, string pw, CertificateList certificates, string certhash, bool certstrong, out string newname, out GroupNameList groups);\nidempotent bool getInfo(int id, out UserInfoMap info);\nidempotent int nameToId(string name);\nidempotent string idToName(int id);\nidempotent Texture idToTexture(int id);\n};\ninterface ServerUpdatingAuthenticator extends ServerAuthenticator {\nint registerUser(UserInfoMap info);\nint unregisterUser(int id);\nidempotent NameMap getRegisteredUsers(string filter);\nidempotent int setInfo(int id, UserInfoMap info);\nidempotent int setTexture(int id, Texture tex);\n};\n[\"amd\"] interface Server {\nidempotent bool isRunning() throws InvalidSecretException;\nvoid start() throws ServerBootedException, ServerFailureException, InvalidSecretException;\nvoid stop() throws ServerBootedException, InvalidSecretException;\nvoid delete() throws ServerBootedException, InvalidSecretException;\nidempotent int id() throws InvalidSecretException;\nvoid addCallback(ServerCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid removeCallback(ServerCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid setAuthenticator(ServerAuthenticator *auth) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nidempotent string getConf(string key) throws InvalidSecretException, WriteOnlyException;\nidempotent ConfigMap getAllConf() throws InvalidSecretException;\nidempotent void setConf(string key, string value) throws InvalidSecretException;\nidempotent void setSuperuserPassword(string pw) throws InvalidSecretException;\nidempotent LogList getLog(int first, int last) throws InvalidSecretException;\nidempotent int getLogLen() throws InvalidSecretException;\nidempotent UserMap getUsers() throws ServerBootedException, InvalidSecretException;\nidempotent ChannelMap getChannels() throws ServerBootedException, InvalidSecretException;\nidempotent CertificateList getCertificateList(int session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent Tree getTree() throws ServerBootedException, InvalidSecretException;\nidempotent BanList getBans() throws ServerBootedException, InvalidSecretException;\nidempotent void setBans(BanList bans) throws ServerBootedException, InvalidSecretException;\nvoid kickUser(int session, string reason) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent User getState(int session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent void setState(User state) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nvoid sendMessage(int session, string text) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nbool hasPermission(int session, int channelid, int perm) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nidempotent int effectivePermissions(int session, int channelid) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nvoid addContextCallback(int session, string action, string text, ServerContextCallback *cb, int ctx) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid removeContextCallback(ServerContextCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;\nidempotent Channel getChannelState(int channelid) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void setChannelState(Channel state) throws ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid removeChannel(int channelid) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nint addChannel(string name, int parent) throws ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid sendMessageChannel(int channelid, bool tree, string text) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void getACL(int channelid, out ACLList acls, out GroupList groups, out bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void setACL(int channelid, ACLList acls, GroupList groups, bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void addUserToGroup(int channelid, int session, string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;\nidempotent void removeUserFromGroup(int channelid, int session, string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;\nidempotent void redirectWhisperGroup(int session, string source, string target) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent NameMap getUserNames(IdList ids) throws ServerBootedException, InvalidSecretException;\nidempotent IdMap getUserIds(NameList names) throws ServerBootedException, InvalidSecretException;\nint registerUser(UserInfoMap info) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nvoid unregisterUser(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void updateRegistration(int userid, UserInfoMap info) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent UserInfoMap getRegistration(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent NameMap getRegisteredUsers(string filter) throws ServerBootedException, InvalidSecretException;\nidempotent int verifyPassword(string name, string pw) throws ServerBootedException, InvalidSecretException;\nidempotent Texture getTexture(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void setTexture(int userid, Texture tex) throws ServerBootedException, InvalidUserException, InvalidTextureException, InvalidSecretException;\nidempotent int getUptime() throws ServerBootedException, InvalidSecretException;\n idempotent void updateCertificate(string certificate, string privateKey, string passphrase) throws ServerBootedException, InvalidSecretException, InvalidInputDataException;\n \n idempotent void startListening(int userid, int channelid);\n \n idempotent void stopListening(int userid, int channelid);\n \n idempotent bool isListening(int userid, int channelid);\n \n idempotent IntList getListeningChannels(int userid);\n \n idempotent IntList getListeningUsers(int channelid);\n};\ninterface MetaCallback {\nvoid started(Server *srv);\nvoid stopped(Server *srv);\n};\nsequence<Server *> ServerList;\n[\"amd\"] interface Meta {\nidempotent Server *getServer(int id) throws InvalidSecretException;\nServer *newServer() throws InvalidSecretException;\nidempotent ServerList getBootedServers() throws InvalidSecretException;\nidempotent ServerList getAllServers() throws InvalidSecretException;\nidempotent ConfigMap getDefaultConf() throws InvalidSecretException;\nidempotent void getVersion(out int major, out int minor, out int patch, out string text);\nvoid addCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nvoid removeCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nidempotent int getUptime();\nidempotent string getSlice();\nidempotent Ice::SliceChecksumDict getSliceChecksums();\n};\n};\n")); +void ::Murmur::MetaI::getSlice_async(const ::Murmur::AMD_Meta_getSlicePtr &cb, const Ice::Current &) { + cb->ice_response(std::string( + "// Copyright 2005-2020 The Mumble Developers. All rights reserved.\n// Use of this source code is governed by " + "a BSD-style license\n// that can be found in the LICENSE file at the root of the\n// Mumble source tree or at " + "<https://www.mumble.info/LICENSE>.\n#include <Ice/SliceChecksumDict.ice>\nmodule " + "Murmur\n{\n[\"python:seq:tuple\"] sequence<byte> NetAddress;\nstruct User {\nint session;\nint userid;\nbool " + "mute;\nbool deaf;\nbool suppress;\nbool prioritySpeaker;\nbool selfMute;\nbool selfDeaf;\nbool " + "recording;\nint channel;\nstring name;\nint onlinesecs;\nint bytespersec;\nint version;\nstring " + "release;\nstring os;\nstring osversion;\nstring identity;\nstring context;\nstring comment;\nNetAddress " + "address;\nbool tcponly;\nint idlesecs;\nfloat udpPing;\nfloat tcpPing;\n};\nsequence<int> IntList;\nstruct " + "TextMessage {\nIntList sessions;\nIntList channels;\nIntList trees;\nstring text;\n};\nstruct Channel {\nint " + "id;\nstring name;\nint parent;\nIntList links;\nstring description;\nbool temporary;\nint " + "position;\n};\nstruct Group {\nstring name;\nbool inherited;\nbool inherit;\nbool inheritable;\nIntList " + "add;\nIntList remove;\nIntList members;\n};\nconst int PermissionWrite = 0x01;\nconst int PermissionTraverse " + "= 0x02;\nconst int PermissionEnter = 0x04;\nconst int PermissionSpeak = 0x08;\nconst int PermissionWhisper = " + "0x100;\nconst int PermissionMuteDeafen = 0x10;\nconst int PermissionMove = 0x20;\nconst int " + "PermissionMakeChannel = 0x40;\nconst int PermissionMakeTempChannel = 0x400;\nconst int PermissionLinkChannel " + "= 0x80;\nconst int PermissionTextMessage = 0x200;\nconst int PermissionKick = 0x10000;\nconst int " + "PermissionBan = 0x20000;\nconst int PermissionRegister = 0x40000;\nconst int PermissionRegisterSelf = " + "0x80000;\nstruct ACL {\nbool applyHere;\nbool applySubs;\nbool inherited;\nint userid;\nstring group;\nint " + "allow;\nint deny;\n};\nstruct Ban {\nNetAddress address;\nint bits;\nstring name;\nstring hash;\nstring " + "reason;\nint start;\nint duration;\n};\nstruct LogEntry {\nint timestamp;\nstring txt;\n};\nclass " + "Tree;\nsequence<Tree> TreeList;\nenum ChannelInfo { ChannelDescription, ChannelPosition };\nenum UserInfo { " + "UserName, UserEmail, UserComment, UserHash, UserPassword, UserLastActive, UserKDFIterations " + "};\ndictionary<int, User> UserMap;\ndictionary<int, Channel> ChannelMap;\nsequence<Channel> " + "ChannelList;\nsequence<User> UserList;\nsequence<Group> GroupList;\nsequence<ACL> " + "ACLList;\nsequence<LogEntry> LogList;\nsequence<Ban> BanList;\nsequence<int> IdList;\nsequence<string> " + "NameList;\ndictionary<int, string> NameMap;\ndictionary<string, int> IdMap;\nsequence<byte> " + "Texture;\ndictionary<string, string> ConfigMap;\nsequence<string> GroupNameList;\nsequence<byte> " + "CertificateDer;\nsequence<CertificateDer> CertificateList;\ndictionary<UserInfo, string> UserInfoMap;\nclass " + "Tree {\nChannel c;\nTreeList children;\nUserList users;\n};\nexception MurmurException {};\nexception " + "InvalidSessionException extends MurmurException {};\nexception InvalidChannelException extends " + "MurmurException {};\nexception InvalidServerException extends MurmurException {};\nexception " + "ServerBootedException extends MurmurException {};\nexception ServerFailureException extends MurmurException " + "{};\nexception InvalidUserException extends MurmurException {};\nexception InvalidTextureException extends " + "MurmurException {};\nexception InvalidCallbackException extends MurmurException {};\nexception " + "InvalidSecretException extends MurmurException {};\nexception NestingLimitException extends MurmurException " + "{};\nexception WriteOnlyException extends MurmurException {};\nexception InvalidInputDataException extends " + "MurmurException {};\ninterface ServerCallback {\nidempotent void userConnected(User state);\nidempotent void " + "userDisconnected(User state);\nidempotent void userStateChanged(User state);\nidempotent void " + "userTextMessage(User state, TextMessage message);\nidempotent void channelCreated(Channel state);\nidempotent " + "void channelRemoved(Channel state);\nidempotent void channelStateChanged(Channel state);\n};\nconst int " + "ContextServer = 0x01;\nconst int ContextChannel = 0x02;\nconst int ContextUser = 0x04;\ninterface " + "ServerContextCallback {\nidempotent void contextAction(string action, User usr, int session, int " + "channelid);\n};\ninterface ServerAuthenticator {\nidempotent int authenticate(string name, string pw, " + "CertificateList certificates, string certhash, bool certstrong, out string newname, out GroupNameList " + "groups);\nidempotent bool getInfo(int id, out UserInfoMap info);\nidempotent int nameToId(string " + "name);\nidempotent string idToName(int id);\nidempotent Texture idToTexture(int id);\n};\ninterface " + "ServerUpdatingAuthenticator extends ServerAuthenticator {\nint registerUser(UserInfoMap info);\nint " + "unregisterUser(int id);\nidempotent NameMap getRegisteredUsers(string filter);\nidempotent int setInfo(int " + "id, UserInfoMap info);\nidempotent int setTexture(int id, Texture tex);\n};\n[\"amd\"] interface Server " + "{\nidempotent bool isRunning() throws InvalidSecretException;\nvoid start() throws ServerBootedException, " + "ServerFailureException, InvalidSecretException;\nvoid stop() throws ServerBootedException, " + "InvalidSecretException;\nvoid delete() throws ServerBootedException, InvalidSecretException;\nidempotent int " + "id() throws InvalidSecretException;\nvoid addCallback(ServerCallback *cb) throws ServerBootedException, " + "InvalidCallbackException, InvalidSecretException;\nvoid removeCallback(ServerCallback *cb) throws " + "ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid " + "setAuthenticator(ServerAuthenticator *auth) throws ServerBootedException, InvalidCallbackException, " + "InvalidSecretException;\nidempotent string getConf(string key) throws InvalidSecretException, " + "WriteOnlyException;\nidempotent ConfigMap getAllConf() throws InvalidSecretException;\nidempotent void " + "setConf(string key, string value) throws InvalidSecretException;\nidempotent void setSuperuserPassword(string " + "pw) throws InvalidSecretException;\nidempotent LogList getLog(int first, int last) throws " + "InvalidSecretException;\nidempotent int getLogLen() throws InvalidSecretException;\nidempotent UserMap " + "getUsers() throws ServerBootedException, InvalidSecretException;\nidempotent ChannelMap getChannels() throws " + "ServerBootedException, InvalidSecretException;\nidempotent CertificateList getCertificateList(int session) " + "throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent Tree getTree() " + "throws ServerBootedException, InvalidSecretException;\nidempotent BanList getBans() throws " + "ServerBootedException, InvalidSecretException;\nidempotent void setBans(BanList bans) throws " + "ServerBootedException, InvalidSecretException;\nvoid kickUser(int session, string reason) throws " + "ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent User getState(int " + "session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;\nidempotent void " + "setState(User state) throws ServerBootedException, InvalidSessionException, InvalidChannelException, " + "InvalidSecretException;\nvoid sendMessage(int session, string text) throws ServerBootedException, " + "InvalidSessionException, InvalidSecretException;\nbool hasPermission(int session, int channelid, int perm) " + "throws ServerBootedException, InvalidSessionException, InvalidChannelException, " + "InvalidSecretException;\nidempotent int effectivePermissions(int session, int channelid) throws " + "ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;\nvoid " + "addContextCallback(int session, string action, string text, ServerContextCallback *cb, int ctx) throws " + "ServerBootedException, InvalidCallbackException, InvalidSecretException;\nvoid " + "removeContextCallback(ServerContextCallback *cb) throws ServerBootedException, InvalidCallbackException, " + "InvalidSecretException;\nidempotent Channel getChannelState(int channelid) throws ServerBootedException, " + "InvalidChannelException, InvalidSecretException;\nidempotent void setChannelState(Channel state) throws " + "ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid " + "removeChannel(int channelid) throws ServerBootedException, InvalidChannelException, " + "InvalidSecretException;\nint addChannel(string name, int parent) throws ServerBootedException, " + "InvalidChannelException, InvalidSecretException, NestingLimitException;\nvoid sendMessageChannel(int " + "channelid, bool tree, string text) throws ServerBootedException, InvalidChannelException, " + "InvalidSecretException;\nidempotent void getACL(int channelid, out ACLList acls, out GroupList groups, out " + "bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;\nidempotent void " + "setACL(int channelid, ACLList acls, GroupList groups, bool inherit) throws ServerBootedException, " + "InvalidChannelException, InvalidSecretException;\nidempotent void addUserToGroup(int channelid, int session, " + "string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, " + "InvalidSecretException;\nidempotent void removeUserFromGroup(int channelid, int session, string group) throws " + "ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;\nidempotent " + "void redirectWhisperGroup(int session, string source, string target) throws ServerBootedException, " + "InvalidSessionException, InvalidSecretException;\nidempotent NameMap getUserNames(IdList ids) throws " + "ServerBootedException, InvalidSecretException;\nidempotent IdMap getUserIds(NameList names) throws " + "ServerBootedException, InvalidSecretException;\nint registerUser(UserInfoMap info) throws " + "ServerBootedException, InvalidUserException, InvalidSecretException;\nvoid unregisterUser(int userid) throws " + "ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void updateRegistration(int " + "userid, UserInfoMap info) throws ServerBootedException, InvalidUserException, " + "InvalidSecretException;\nidempotent UserInfoMap getRegistration(int userid) throws ServerBootedException, " + "InvalidUserException, InvalidSecretException;\nidempotent NameMap getRegisteredUsers(string filter) throws " + "ServerBootedException, InvalidSecretException;\nidempotent int verifyPassword(string name, string pw) throws " + "ServerBootedException, InvalidSecretException;\nidempotent Texture getTexture(int userid) throws " + "ServerBootedException, InvalidUserException, InvalidSecretException;\nidempotent void setTexture(int userid, " + "Texture tex) throws ServerBootedException, InvalidUserException, InvalidTextureException, " + "InvalidSecretException;\nidempotent int getUptime() throws ServerBootedException, InvalidSecretException;\n " + "idempotent void updateCertificate(string certificate, string privateKey, string passphrase) throws " + "ServerBootedException, InvalidSecretException, InvalidInputDataException;\n \n idempotent void " + "startListening(int userid, int channelid);\n \n idempotent void stopListening(int userid, int channelid);\n " + "\n idempotent bool isListening(int userid, int channelid);\n \n idempotent IntList getListeningChannels(int " + "userid);\n \n idempotent IntList getListeningUsers(int channelid);\n};\ninterface MetaCallback {\nvoid " + "started(Server *srv);\nvoid stopped(Server *srv);\n};\nsequence<Server *> ServerList;\n[\"amd\"] interface " + "Meta {\nidempotent Server *getServer(int id) throws InvalidSecretException;\nServer *newServer() throws " + "InvalidSecretException;\nidempotent ServerList getBootedServers() throws InvalidSecretException;\nidempotent " + "ServerList getAllServers() throws InvalidSecretException;\nidempotent ConfigMap getDefaultConf() throws " + "InvalidSecretException;\nidempotent void getVersion(out int major, out int minor, out int patch, out string " + "text);\nvoid addCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nvoid " + "removeCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;\nidempotent int " + "getUptime();\nidempotent string getSlice();\nidempotent Ice::SliceChecksumDict " + "getSliceChecksums();\n};\n};\n")); } diff --git a/src/murmur/PBKDF2.cpp b/src/murmur/PBKDF2.cpp index 905774ffe..f8fb895d2 100644 --- a/src/murmur/PBKDF2.cpp +++ b/src/murmur/PBKDF2.cpp @@ -13,13 +13,13 @@ are met: - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -39,9 +39,9 @@ #ifdef Q_OS_WIN // <openssl/rand.h> includes <windows.h> without defining NOMINMAX, // which breaks our compilation because of the "max" macro. -#ifndef NOMINMAX -# define NOMINMAX -#endif +# ifndef NOMINMAX +# define NOMINMAX +# endif #endif #include "PBKDF2.h" @@ -58,28 +58,29 @@ int PBKDF2::benchmark() { const QString pseudopass(QLatin1String("aboutAvg")); const QString hexSalt = getSalt(); // Could tolerate not getting a salt here, will likely only make it harder. - + int maxIterations = -1; - + QElapsedTimer timer; timer.start(); - + for (size_t i = 0; i < BENCHMARK_N; ++i) { int iterations = BENCHMARK_MINIMUM_ITERATION_COUNT / 2; - + timer.restart(); do { iterations *= 2; - + // Store return value in a volatile to prevent optimizer // from ever removing these side-effect-free calls. I don't // think the compiler can prove they have no side-effects but // better safe than sorry. volatile QString result = getHash(hexSalt, pseudopass, iterations); Q_UNUSED(result); - - } while (timer.restart() < BENCHMARK_DURATION_TARGET_IN_MS && (iterations / 2) < std::numeric_limits<int>::max()); - + + } while (timer.restart() < BENCHMARK_DURATION_TARGET_IN_MS + && (iterations / 2) < std::numeric_limits< int >::max()); + if (iterations > maxIterations) { maxIterations = iterations; } @@ -89,27 +90,26 @@ int PBKDF2::benchmark() { QString PBKDF2::getHash(const QString &hexSalt, const QString &password, int iterationCount) { QByteArray hash(DERIVED_KEY_LENGTH, 0); - + const QByteArray utf8Password = password.toUtf8(); - const QByteArray salt = QByteArray::fromHex(hexSalt.toLatin1()); + const QByteArray salt = QByteArray::fromHex(hexSalt.toLatin1()); if (PKCS5_PBKDF2_HMAC(utf8Password.constData(), utf8Password.size(), - reinterpret_cast<const unsigned char*>(salt.constData()), salt.size(), - iterationCount, - EVP_sha384(), - DERIVED_KEY_LENGTH, reinterpret_cast<unsigned char*>(hash.data())) == 0) { + reinterpret_cast< const unsigned char * >(salt.constData()), salt.size(), iterationCount, + EVP_sha384(), DERIVED_KEY_LENGTH, reinterpret_cast< unsigned char * >(hash.data())) + == 0) { qFatal("PBKDF2: PKCS5_PBKDF2_HMAC failed: %s", ERR_error_string(ERR_get_error(), nullptr)); return QString(); } - + return QString::fromLatin1(hash.toHex()); } QString PBKDF2::getSalt() { QByteArray salt(SALT_LENGTH, 0); - - if (RAND_bytes(reinterpret_cast<unsigned char*>(salt.data()), salt.size()) != 1) { + + if (RAND_bytes(reinterpret_cast< unsigned char * >(salt.data()), salt.size()) != 1) { qFatal("PBKDF2: RAND_bytes for salt failed: %s", ERR_error_string(ERR_get_error(), nullptr)); return QString(); } diff --git a/src/murmur/PBKDF2.h b/src/murmur/PBKDF2.h index 1b678ef39..377e59823 100644 --- a/src/murmur/PBKDF2.h +++ b/src/murmur/PBKDF2.h @@ -13,13 +13,13 @@ are met: - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. - Neither the name of the Mumble Developers nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -42,49 +42,46 @@ class QString; /// /// Fully static wrapper class for PBKF2 password hashing functionality used in Murmur. -/// +/// /// @note Using int all over the place because OpenSSL uses them in its C interface /// and we want to make sure not to parameterize it in unexpected ways. /// @warning Operations in this class that experience internal failure will abort /// program execution using qFatal. /// class PBKDF2 { - public: - /// - /// @return Upper bound on iterations possible in - /// BENCHMARK_DURATION_TARGET_IN_MS on this machine. - /// - static int benchmark(); - - /// Performs a PBKDF2 hash operation using EVP_sha384. - /// - /// @param hexSalt Hex encoded salt to use in operation. - /// @param password Password to hash. - /// @param iterationCount Number of PBKDF2 iterations to apply. - /// @return Hex encoded password hash of DERIVED_KEY_LENGTH octets. - /// - static QString getHash(const QString &hexSalt, - const QString &password, - int iterationCount); - - /// - /// @return SALT_LENGTH octets of hex encoded random salt. - /// - static QString getSalt(); - - /// Length of hash in octets - static const int DERIVED_KEY_LENGTH = 48; - /// Length salt in octests - static const int SALT_LENGTH = 8; - - /// Duration for hash operation the benchmark function should target - static const int BENCHMARK_DURATION_TARGET_IN_MS = 10; - /// Benchmark returns highest iteration number of N benchmark attemps - static const size_t BENCHMARK_N = 40; - /// Lower bound of iteration count returned by benchmark - /// regardless of duration (should be divisible by 2) - static const int BENCHMARK_MINIMUM_ITERATION_COUNT = 1000; +public: + /// + /// @return Upper bound on iterations possible in + /// BENCHMARK_DURATION_TARGET_IN_MS on this machine. + /// + static int benchmark(); + + /// Performs a PBKDF2 hash operation using EVP_sha384. + /// + /// @param hexSalt Hex encoded salt to use in operation. + /// @param password Password to hash. + /// @param iterationCount Number of PBKDF2 iterations to apply. + /// @return Hex encoded password hash of DERIVED_KEY_LENGTH octets. + /// + static QString getHash(const QString &hexSalt, const QString &password, int iterationCount); + + /// + /// @return SALT_LENGTH octets of hex encoded random salt. + /// + static QString getSalt(); + + /// Length of hash in octets + static const int DERIVED_KEY_LENGTH = 48; + /// Length salt in octests + static const int SALT_LENGTH = 8; + /// Duration for hash operation the benchmark function should target + static const int BENCHMARK_DURATION_TARGET_IN_MS = 10; + /// Benchmark returns highest iteration number of N benchmark attemps + static const size_t BENCHMARK_N = 40; + /// Lower bound of iteration count returned by benchmark + /// regardless of duration (should be divisible by 2) + static const int BENCHMARK_MINIMUM_ITERATION_COUNT = 1000; }; #endif // MUMBLE_MURMUR_PBKDF2_H_ diff --git a/src/murmur/RPC.cpp b/src/murmur/RPC.cpp index 2cb8deaab..0d0163744 100644 --- a/src/murmur/RPC.cpp +++ b/src/murmur/RPC.cpp @@ -6,28 +6,29 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "Channel.h" +#include "ChannelListener.h" #include "Group.h" #include "Meta.h" #include "Server.h" #include "ServerDB.h" #include "ServerUser.h" #include "Version.h" -#include "ChannelListener.h" #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #endif -void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, const QString& name, const QString &comment) { +void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, + const QString &name, const QString &comment) { bool changed = false; if (deaf) mute = true; - if (! mute) + if (!mute) deaf = false; MumbleProto::UserState mpus; @@ -52,7 +53,7 @@ void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, changed = true; mpus.set_comment(u8(comment)); if (pUser->iId >= 0) { - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Comment, comment); setInfo(pUser->iId, info); } @@ -64,13 +65,13 @@ void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, { QWriteLocker wl(&qrwlVoiceThread); - pUser->bDeaf = deaf; - pUser->bMute = mute; + pUser->bDeaf = deaf; + pUser->bMute = mute; pUser->bSuppress = suppressed; } pUser->bPrioritySpeaker = prioritySpeaker; - pUser->qsName = name; + pUser->qsName = name; hashAssign(pUser->qsComment, pUser->qbaCommentHash, comment); if (cChannel != pUser->cChannel) { @@ -80,8 +81,8 @@ void Server::setUserState(User *pUser, Channel *cChannel, bool mute, bool deaf, } if (changed) { - sendAll(mpus, ~ 0x010202); - if (mpus.has_comment() && ! pUser->qbaCommentHash.isEmpty()) { + sendAll(mpus, ~0x010202); + if (mpus.has_comment() && !pUser->qbaCommentHash.isEmpty()) { mpus.clear_comment(); mpus.set_comment_hash(blob(pUser->qbaCommentHash)); } @@ -111,7 +112,7 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e // Links and parent channel are processed first, because they can return // errors. Without doing this, the server state can be changed without // notifying users. - QSet< ::Channel *> newLinksSet; + QSet<::Channel * > newLinksSet; for (int i = 0; i < cs.links_size(); i++) { Channel *link = qhChannels.value(cs.links(i)); if (!link) { @@ -165,19 +166,19 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e } } - const QSet<Channel *> &oldLinksSet = channel->qsPermLinks; + const QSet< Channel * > &oldLinksSet = channel->qsPermLinks; if (newLinksSet != oldLinksSet) { // Remove - foreach(Channel *l, oldLinksSet) { + foreach (Channel *l, oldLinksSet) { if (!newLinksSet.contains(l)) { removeLink(channel, l); mpcs.add_links_remove(l->iId); } } // Add - foreach(Channel *l, newLinksSet) { - if (! oldLinksSet.contains(l)) { + foreach (Channel *l, newLinksSet) { + if (!oldLinksSet.contains(l)) { addLink(channel, l); mpcs.add_links_add(l->iId); } @@ -209,7 +210,7 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e updateChannel(channel); } if (changed) { - sendAll(mpcs, ~ 0x010202); + sendAll(mpcs, ~0x010202); if (mpcs.has_description() && !channel->qbaDescHash.isEmpty()) { mpcs.clear_description(); mpcs.set_description_hash(blob(channel->qbaDescHash)); @@ -221,7 +222,8 @@ bool Server::setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &e return true; } -bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString &qsName, const QSet<Channel *> &links, const QString &desc, const int position) { +bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString &qsName, const QSet< Channel * > &links, + const QString &desc, const int position) { bool changed = false; bool updated = false; @@ -259,20 +261,20 @@ bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString changed = true; } - const QSet<Channel *> &oldset = cChannel->qsPermLinks; + const QSet< Channel * > &oldset = cChannel->qsPermLinks; if (links != oldset) { // Remove - foreach(Channel *l, oldset) { - if (! links.contains(l)) { + foreach (Channel *l, oldset) { + if (!links.contains(l)) { removeLink(cChannel, l); mpcs.add_links_remove(l->iId); } } // Add - foreach(Channel *l, links) { - if (! oldset.contains(l)) { + foreach (Channel *l, links) { + if (!oldset.contains(l)) { addLink(cChannel, l); mpcs.add_links_add(l->iId); } @@ -282,13 +284,13 @@ bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString } if (position != cChannel->iPosition) { - changed = true; - updated = true; + changed = true; + updated = true; cChannel->iPosition = position; mpcs.set_position(position); } - if (! desc.isNull() && desc != cChannel->qsDesc) { + if (!desc.isNull() && desc != cChannel->qsDesc) { updated = true; changed = true; hashAssign(cChannel->qsDesc, cChannel->qbaDescHash, desc); @@ -298,8 +300,8 @@ bool Server::setChannelState(Channel *cChannel, Channel *cParent, const QString if (updated) updateChannel(cChannel); if (changed) { - sendAll(mpcs, ~ 0x010202); - if (mpcs.has_description() && ! cChannel->qbaDescHash.isEmpty()) { + sendAll(mpcs, ~0x010202); + if (mpcs.has_description() && !cChannel->qbaDescHash.isEmpty()) { mpcs.clear_description(); mpcs.set_description_hash(blob(cChannel->qbaDescHash)); } @@ -336,7 +338,7 @@ void Server::sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm) { } // Channel targets - QSet<Channel *> chans; + QSet< Channel * > chans; for (int i = 0; i < tm.channel_id_size(); i++) { Channel *channel = qhChannels.value(tm.channel_id(i)); @@ -347,7 +349,7 @@ void Server::sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm) { mptm.add_channel_id(channel->iId); } - QQueue<Channel *> chansQ; + QQueue< Channel * > chansQ; for (int i = 0; i < tm.tree_id_size(); i++) { Channel *channel = qhChannels.value(tm.tree_id(i)); if (!channel) { @@ -359,15 +361,11 @@ void Server::sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm) { while (!chansQ.isEmpty()) { Channel *c = chansQ.dequeue(); chans.insert(c); - foreach(c, c->qlChannels) { - chansQ.enqueue(c); - } + foreach (c, c->qlChannels) { chansQ.enqueue(c); } } - foreach(Channel *c, chans) { - foreach(::User *p, c->qlUsers) { - sendMessage(static_cast< ::ServerUser *>(p), mptm); - } + foreach (Channel *c, chans) { + foreach (::User *p, c->qlUsers) { sendMessage(static_cast<::ServerUser * >(p), mptm); } } } @@ -384,23 +382,23 @@ void Server::sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, co else mptm.add_channel_id(cChannel->iId); - QSet<Channel *> chans; - QQueue<Channel *> q; + QSet< Channel * > chans; + QQueue< Channel * > q; q << cChannel; chans.insert(cChannel); Channel *c; if (tree) { - while (! q.isEmpty()) { + while (!q.isEmpty()) { c = q.dequeue(); chans.insert(c); - foreach(c, c->qlChannels) + foreach (c, c->qlChannels) q.enqueue(c); } } - foreach(c, chans) { - foreach(User *p, c->qlUsers) - sendMessage(static_cast<ServerUser *>(p), mptm); + foreach (c, chans) { + foreach (User *p, c->qlUsers) + sendMessage(static_cast< ServerUser * >(p), mptm); } } } @@ -412,28 +410,28 @@ void Server::sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, co * If userid is negative the absolute value is a session id. If it is positive it is a registration id. */ void Server::setTempGroups(int userid, int sessionId, Channel *cChannel, const QStringList &groups) { - if (! cChannel) + if (!cChannel) cChannel = qhChannels.value(0); { QWriteLocker wl(&qrwlVoiceThread); Group *g; - foreach(g, cChannel->qhGroups) { + foreach (g, cChannel->qhGroups) { g->qsTemporary.remove(userid); if (sessionId != 0) - g->qsTemporary.remove(- sessionId); + g->qsTemporary.remove(-sessionId); } QString gname; - foreach(gname, groups) { + foreach (gname, groups) { g = cChannel->qhGroups.value(gname); - if (! g) { + if (!g) { g = new Group(cChannel, gname); } g->qsTemporary.insert(userid); if (sessionId != 0) - g->qsTemporary.insert(- sessionId); + g->qsTemporary.insert(-sessionId); } } @@ -447,8 +445,8 @@ void Server::setTempGroups(int userid, int sessionId, Channel *cChannel, const Q * If recursion is activated all temporary memberships in related channels will also be cleared. */ void Server::clearTempGroups(User *user, Channel *cChannel, bool recurse) { - QList<Channel*> qlChans; - if (! cChannel) + QList< Channel * > qlChans; + if (!cChannel) cChannel = qhChannels.value(0); qlChans.append(cChannel); @@ -459,9 +457,9 @@ void Server::clearTempGroups(User *user, Channel *cChannel, bool recurse) { while (!qlChans.isEmpty()) { Channel *chan = qlChans.takeLast(); Group *g; - foreach(g, chan->qhGroups) { + foreach (g, chan->qhGroups) { g->qsTemporary.remove(user->iId); - g->qsTemporary.remove(-static_cast<int>(user->uiSession)); + g->qsTemporary.remove(-static_cast< int >(user->uiSession)); } if (recurse) @@ -473,26 +471,46 @@ void Server::clearTempGroups(User *user, Channel *cChannel, bool recurse) { } void Server::connectAuthenticator(QObject *obj) { - connect(this, SIGNAL(registerUserSig(int &, const QMap<int, QString> &)), obj, SLOT(registerUserSlot(int &, const QMap<int, QString> &))); + connect(this, SIGNAL(registerUserSig(int &, const QMap< int, QString > &)), obj, + SLOT(registerUserSlot(int &, const QMap< int, QString > &))); connect(this, SIGNAL(unregisterUserSig(int &, int)), obj, SLOT(unregisterUserSlot(int &, int))); - connect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap<int, QString> &)), obj, SLOT(getRegisteredUsersSlot(const QString &, QMap<int, QString> &))); - connect(this, SIGNAL(getRegistrationSig(int &, int, QMap<int, QString> &)), obj, SLOT(getRegistrationSlot(int &, int, QMap<int, QString> &))); - connect(this, SIGNAL(authenticateSig(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &)), obj, SLOT(authenticateSlot(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &))); - connect(this, SIGNAL(setInfoSig(int &, int, const QMap<int, QString> &)), obj, SLOT(setInfoSlot(int &, int, const QMap<int, QString> &))); - connect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, SLOT(setTextureSlot(int &, int, const QByteArray &))); + connect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap< int, QString > &)), obj, + SLOT(getRegisteredUsersSlot(const QString &, QMap< int, QString > &))); + connect(this, SIGNAL(getRegistrationSig(int &, int, QMap< int, QString > &)), obj, + SLOT(getRegistrationSlot(int &, int, QMap< int, QString > &))); + connect(this, + SIGNAL(authenticateSig(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &)), + obj, + SLOT(authenticateSlot(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &))); + connect(this, SIGNAL(setInfoSig(int &, int, const QMap< int, QString > &)), obj, + SLOT(setInfoSlot(int &, int, const QMap< int, QString > &))); + connect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, + SLOT(setTextureSlot(int &, int, const QByteArray &))); connect(this, SIGNAL(idToNameSig(QString &, int)), obj, SLOT(idToNameSlot(QString &, int))); connect(this, SIGNAL(nameToIdSig(int &, const QString &)), obj, SLOT(nameToIdSlot(int &, const QString &))); connect(this, SIGNAL(idToTextureSig(QByteArray &, int)), obj, SLOT(idToTextureSlot(QByteArray &, int))); } void Server::disconnectAuthenticator(QObject *obj) { - disconnect(this, SIGNAL(registerUserSig(int &, const QMap<int, QString> &)), obj, SLOT(registerUserSlot(int &, const QMap<int, QString> &))); + disconnect(this, SIGNAL(registerUserSig(int &, const QMap< int, QString > &)), obj, + SLOT(registerUserSlot(int &, const QMap< int, QString > &))); disconnect(this, SIGNAL(unregisterUserSig(int &, int)), obj, SLOT(unregisterUserSlot(int &, int))); - disconnect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap<int, QString> &)), obj, SLOT(getRegisteredUsersSlot(const QString &, QMap<int, QString> &))); - disconnect(this, SIGNAL(getRegistrationSig(int &, int, QMap<int, QString> &)), obj, SLOT(getRegistrationSlot(int &, int, QMap<int, QString> &))); - disconnect(this, SIGNAL(authenticateSig(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &)), obj, SLOT(authenticateSlot(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &))); - disconnect(this, SIGNAL(setInfoSig(int &, int, const QMap<int, QString> &)), obj, SLOT(setInfoSlot(int &, int, const QMap<int, QString> &))); - disconnect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, SLOT(setTextureSlot(int &, int, const QByteArray &))); + disconnect(this, SIGNAL(getRegisteredUsersSig(const QString &, QMap< int, QString > &)), obj, + SLOT(getRegisteredUsersSlot(const QString &, QMap< int, QString > &))); + disconnect(this, SIGNAL(getRegistrationSig(int &, int, QMap< int, QString > &)), obj, + SLOT(getRegistrationSlot(int &, int, QMap< int, QString > &))); + disconnect(this, + SIGNAL(authenticateSig(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &)), + obj, + SLOT(authenticateSlot(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &))); + disconnect(this, SIGNAL(setInfoSig(int &, int, const QMap< int, QString > &)), obj, + SLOT(setInfoSlot(int &, int, const QMap< int, QString > &))); + disconnect(this, SIGNAL(setTextureSig(int &, int, const QByteArray &)), obj, + SLOT(setTextureSlot(int &, int, const QByteArray &))); disconnect(this, SIGNAL(idToNameSig(QString &, int)), obj, SLOT(idToNameSlot(QString &, int))); disconnect(this, SIGNAL(nameToIdSig(int &, const QString &)), obj, SLOT(nameToIdSlot(int &, const QString &))); disconnect(this, SIGNAL(idToTextureSig(QByteArray &, int)), obj, SLOT(idToTextureSlot(QByteArray &, int))); @@ -500,7 +518,8 @@ void Server::disconnectAuthenticator(QObject *obj) { void Server::connectListener(QObject *obj) { connect(this, SIGNAL(userStateChanged(const User *)), obj, SLOT(userStateChanged(const User *))); - connect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, SLOT(userTextMessage(const User *, const TextMessage &))); + connect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, + SLOT(userTextMessage(const User *, const TextMessage &))); connect(this, SIGNAL(userConnected(const User *)), obj, SLOT(userConnected(const User *))); connect(this, SIGNAL(userDisconnected(const User *)), obj, SLOT(userDisconnected(const User *))); connect(this, SIGNAL(channelStateChanged(const Channel *)), obj, SLOT(channelStateChanged(const Channel *))); @@ -510,7 +529,8 @@ void Server::connectListener(QObject *obj) { void Server::disconnectListener(QObject *obj) { disconnect(this, SIGNAL(userStateChanged(const User *)), obj, SLOT(userStateChanged(const User *))); - disconnect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, SLOT(userTextMessage(const User *, const TextMessage &))); + disconnect(this, SIGNAL(userTextMessage(const User *, const TextMessage &)), obj, + SLOT(userTextMessage(const User *, const TextMessage &))); disconnect(this, SIGNAL(userConnected(const User *)), obj, SLOT(userConnected(const User *))); disconnect(this, SIGNAL(userDisconnected(const User *)), obj, SLOT(userDisconnected(const User *))); disconnect(this, SIGNAL(channelStateChanged(const Channel *)), obj, SLOT(channelStateChanged(const Channel *))); diff --git a/src/murmur/Register.cpp b/src/murmur/Register.cpp index 8ef6e7129..72f5c8449 100644 --- a/src/murmur/Register.cpp +++ b/src/murmur/Register.cpp @@ -3,32 +3,34 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -#include "Server.h" #include "Meta.h" -#include "Version.h" #include "OSInfo.h" +#include "Server.h" +#include "Version.h" #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtXml/QDomDocument> -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - #include <QRandomGenerator> +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) +# include <QRandomGenerator> #endif void Server::initRegister() { connect(&qtTick, SIGNAL(timeout()), this, SLOT(update())); - if (! qsRegName.isEmpty()) { - if (!qsRegName.isEmpty() && !qsRegPassword.isEmpty() && qurlRegWeb.isValid() && qsPassword.isEmpty() && bAllowPing) -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - qtTick.start((60 + (QRandomGenerator::global()->generate() % 120))* 1000); + if (!qsRegName.isEmpty()) { + if (!qsRegName.isEmpty() && !qsRegPassword.isEmpty() && qurlRegWeb.isValid() && qsPassword.isEmpty() + && bAllowPing) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) + qtTick.start((60 + (QRandomGenerator::global()->generate() % 120)) * 1000); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor - qtTick.start((60 + (qrand() % 120))* 1000); + qtTick.start((60 + (qrand() % 120)) * 1000); #endif else - log("Registration needs nonempty 'registername', 'registerpassword' and 'registerurl', must have an empty 'password' and allowed pings."); + log("Registration needs nonempty 'registername', 'registerpassword' and 'registerurl', must have an empty " + "'password' and allowed pings."); } else { log("Not registering server as public"); } @@ -39,10 +41,10 @@ void Server::update() { return; // When QNAM distinguishes connections by client cert, move this to Meta - if (! qnamNetwork) + if (!qnamNetwork) qnamNetwork = new QNetworkAccessManager(this); -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) qtTick.start(1000 * (60 * 60 + (QRandomGenerator::global()->generate() % 300))); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor @@ -50,7 +52,7 @@ void Server::update() { #endif QDomDocument doc; - QDomElement root=doc.createElement(QLatin1String("server")); + QDomElement root = doc.createElement(QLatin1String("server")); doc.appendChild(root); OSInfo::fillXml(doc, root, meta->qsOS, meta->qsOSVersion, qlBind); @@ -58,50 +60,50 @@ void Server::update() { QDomElement tag; QDomText t; - tag=doc.createElement(QLatin1String("name")); + tag = doc.createElement(QLatin1String("name")); root.appendChild(tag); - t=doc.createTextNode(qsRegName); + t = doc.createTextNode(qsRegName); tag.appendChild(t); - tag=doc.createElement(QLatin1String("host")); + tag = doc.createElement(QLatin1String("host")); root.appendChild(tag); - t=doc.createTextNode(qsRegHost); + t = doc.createTextNode(qsRegHost); tag.appendChild(t); - tag=doc.createElement(QLatin1String("password")); + tag = doc.createElement(QLatin1String("password")); root.appendChild(tag); - t=doc.createTextNode(qsRegPassword); + t = doc.createTextNode(qsRegPassword); tag.appendChild(t); - tag=doc.createElement(QLatin1String("port")); + tag = doc.createElement(QLatin1String("port")); root.appendChild(tag); - t=doc.createTextNode(QString::number(usPort)); + t = doc.createTextNode(QString::number(usPort)); tag.appendChild(t); - tag=doc.createElement(QLatin1String("url")); + tag = doc.createElement(QLatin1String("url")); root.appendChild(tag); - t=doc.createTextNode(qurlRegWeb.toString()); + t = doc.createTextNode(qurlRegWeb.toString()); tag.appendChild(t); - tag=doc.createElement(QLatin1String("digest")); + tag = doc.createElement(QLatin1String("digest")); root.appendChild(tag); - t=doc.createTextNode(getDigest()); + t = doc.createTextNode(getDigest()); tag.appendChild(t); - tag=doc.createElement(QLatin1String("users")); + tag = doc.createElement(QLatin1String("users")); root.appendChild(tag); - t=doc.createTextNode(QString::number(qhUsers.count())); + t = doc.createTextNode(QString::number(qhUsers.count())); tag.appendChild(t); - tag=doc.createElement(QLatin1String("channels")); + tag = doc.createElement(QLatin1String("channels")); root.appendChild(tag); - t=doc.createTextNode(QString::number(qhChannels.count())); + t = doc.createTextNode(QString::number(qhChannels.count())); tag.appendChild(t); if (!qsRegLocation.isEmpty()) { - tag=doc.createElement(QLatin1String("location")); + tag = doc.createElement(QLatin1String("location")); root.appendChild(tag); - t=doc.createTextNode(qsRegLocation); + t = doc.createTextNode(qsRegLocation); tag.appendChild(t); } @@ -113,7 +115,7 @@ void Server::update() { ssl.setPrivateKey(qskKey); /* Work around bug in QSslConfiguration */ - QList<QSslCertificate> calist = ssl.caCertificates(); + QList< QSslCertificate > calist = ssl.caCertificates(); calist << QSslConfiguration::defaultConfiguration().caCertificates(); calist << Meta::mp.qlCA; calist << Meta::mp.qlIntermediates; @@ -126,11 +128,11 @@ void Server::update() { QNetworkReply *rep = qnamNetwork->post(qnr, doc.toString().toUtf8()); connect(rep, SIGNAL(finished()), this, SLOT(finished())); - connect(rep, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(regSslError(const QList<QSslError> &))); + connect(rep, SIGNAL(sslErrors(const QList< QSslError > &)), this, SLOT(regSslError(const QList< QSslError > &))); } void Server::finished() { - QNetworkReply *rep = qobject_cast<QNetworkReply *>(sender()); + QNetworkReply *rep = qobject_cast< QNetworkReply * >(sender()); if (rep->error() != QNetworkReply::NoError) { log(QString("Registration failed: %1").arg(rep->errorString())); @@ -141,7 +143,7 @@ void Server::finished() { rep->deleteLater(); } -void Server::regSslError(const QList<QSslError> &errs) { - foreach(const QSslError &e, errs) +void Server::regSslError(const QList< QSslError > &errs) { + foreach (const QSslError &e, errs) log(QString("Registration: SSL Handshake error: %1").arg(e.errorString())); } diff --git a/src/murmur/Server.cpp b/src/murmur/Server.cpp index 305a0f682..d01dd31df 100644 --- a/src/murmur/Server.cpp +++ b/src/murmur/Server.cpp @@ -6,53 +6,53 @@ #include "Server.h" #include "ACL.h" +#include "Channel.h" +#include "ChannelListener.h" #include "Connection.h" +#include "EnvUtils.h" #include "Group.h" -#include "User.h" -#include "Channel.h" +#include "HTMLFilter.h" +#include "HostAddress.h" #include "Message.h" #include "Meta.h" #include "PacketDataStream.h" #include "ServerDB.h" #include "ServerUser.h" -#include "Version.h" -#include "HTMLFilter.h" -#include "HostAddress.h" -#include "ChannelListener.h" #include "SpeechFlags.h" -#include "EnvUtils.h" +#include "User.h" +#include "Version.h" #ifdef USE_BONJOUR -# include "BonjourServer.h" -# include "BonjourServiceRegister.h" +# include "BonjourServer.h" +# include "BonjourServiceRegister.h" #endif #include "Utils.h" #include <QtCore/QCoreApplication> +#include <QtCore/QSet> #include <QtCore/QXmlStreamAttributes> #include <QtCore/QtEndian> -#include <QtCore/QSet> #include <QtNetwork/QHostInfo> #include <QtNetwork/QSslConfiguration> #include <boost/bind.hpp> #ifdef Q_OS_WIN -# include <qos2.h> -# include <ws2tcpip.h> +# include <qos2.h> +# include <ws2tcpip.h> #else -# include <netinet/in.h> -# include <poll.h> +# include <netinet/in.h> +# include <poll.h> #endif #ifndef MAX -# define MAX(a,b) ((a)>(b) ? (a):(b)) +# define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif #define UDP_PACKET_SIZE 1024 -ExecEvent::ExecEvent(boost::function<void ()> f) : QEvent(static_cast<QEvent::Type>(EXEC_QEVENT)) { +ExecEvent::ExecEvent(boost::function< void() > f) : QEvent(static_cast< QEvent::Type >(EXEC_QEVENT)) { func = f; } @@ -73,7 +73,8 @@ bool SslServer::hasDualStackSupport() { int s = ::socket(AF_INET6, SOCK_STREAM, 0); if (s != -1) { const int ipv6only = 0; - if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&ipv6only), sizeof(ipv6only)) == 0) { + if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< const char * >(&ipv6only), sizeof(ipv6only)) + == 0) { result = true; } ::close(s); @@ -89,7 +90,8 @@ bool SslServer::hasDualStackSupport() { SOCKET s = ::WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED); if (s != INVALID_SOCKET) { const int ipv6only = 0; - if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&ipv6only), sizeof(ipv6only)) == 0) { + if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< const char * >(&ipv6only), sizeof(ipv6only)) + == 0) { result = true; } closesocket(s); @@ -112,7 +114,7 @@ QSslSocket *SslServer::nextPendingSSLConnection() { } Server::Server(int snum, QObject *p) : QThread(p) { - bValid = true; + bValid = true; iServerNum = snum; #ifdef USE_BONJOUR bsRegistration = nullptr; @@ -127,60 +129,62 @@ Server::Server(int snum, QObject *p) : QThread(p) { qtTimeout = new QTimer(this); iCodecAlpha = iCodecBeta = 0; - bPreferAlpha = false; - bOpus = true; + bPreferAlpha = false; + bOpus = true; qnamNetwork = nullptr; readParams(); initialize(); - foreach(const QHostAddress &qha, qlBind) { + foreach (const QHostAddress &qha, qlBind) { SslServer *ss = new SslServer(this); connect(ss, SIGNAL(newConnection()), this, SLOT(newClient()), Qt::QueuedConnection); - if (! ss->listen(qha, usPort)) { - log(QString("Server: TCP Listen on %1 failed: %2").arg(addressToString(qha,usPort), ss->errorString())); + if (!ss->listen(qha, usPort)) { + log(QString("Server: TCP Listen on %1 failed: %2").arg(addressToString(qha, usPort), ss->errorString())); bValid = false; } else { - log(QString("Server listening on %1").arg(addressToString(qha,usPort))); + log(QString("Server listening on %1").arg(addressToString(qha, usPort))); } qlServer << ss; } - if (! bValid) + if (!bValid) return; - foreach(SslServer *ss, qlServer) { + foreach (SslServer *ss, qlServer) { sockaddr_storage addr; #ifdef Q_OS_UNIX - int tcpsock = static_cast<int>(ss->socketDescriptor()); + int tcpsock = static_cast< int >(ss->socketDescriptor()); socklen_t len = sizeof(addr); #else - SOCKET tcpsock = ss->socketDescriptor(); - int len = sizeof(addr); + SOCKET tcpsock = ss->socketDescriptor(); + int len = sizeof(addr); #endif memset(&addr, 0, sizeof(addr)); - getsockname(tcpsock, reinterpret_cast<struct sockaddr *>(&addr), &len); + getsockname(tcpsock, reinterpret_cast< struct sockaddr * >(&addr), &len); #ifdef Q_OS_UNIX int sock = ::socket(addr.ss_family, SOCK_DGRAM, 0); -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX int sockopt = 1; if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &sockopt, sizeof(sockopt))) log(QString("Failed to set IP_PKTINFO for %1").arg(addressToString(ss->serverAddress(), usPort))); sockopt = 1; if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &sockopt, sizeof(sockopt))) log(QString("Failed to set IPV6_RECVPKTINFO for %1").arg(addressToString(ss->serverAddress(), usPort))); -#endif +# endif #else -#ifndef SIO_UDP_CONNRESET -#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12) -#endif - SOCKET sock = ::WSASocket(addr.ss_family, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, WSA_FLAG_OVERLAPPED); +# ifndef SIO_UDP_CONNRESET +# define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12) +# endif + SOCKET sock = ::WSASocket(addr.ss_family, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, WSA_FLAG_OVERLAPPED); DWORD dwBytesReturned = 0; - BOOL bNewBehaviour = FALSE; - if (WSAIoctl(sock, SIO_UDP_CONNRESET, &bNewBehaviour, sizeof(bNewBehaviour), nullptr, 0, &dwBytesReturned, nullptr, nullptr) == SOCKET_ERROR) { + BOOL bNewBehaviour = FALSE; + if (WSAIoctl(sock, SIO_UDP_CONNRESET, &bNewBehaviour, sizeof(bNewBehaviour), nullptr, 0, &dwBytesReturned, + nullptr, nullptr) + == SOCKET_ERROR) { log(QString("Failed to set SIO_UDP_CONNRESET: %1").arg(WSAGetLastError())); } #endif @@ -194,16 +198,19 @@ Server::Server(int snum, QObject *p) : QThread(p) { // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms738574%28v=vs.85%29.aspx // This will fail for WindowsXP which is ok. Our TCP code will have split that up // into two sockets. - int ipv6only = 0; + int ipv6only = 0; socklen_t optlen = sizeof(ipv6only); - if (::getsockopt(tcpsock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char*>(&ipv6only), &optlen) == 0) { - if (::setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&ipv6only), optlen) == SOCKET_ERROR) { + if (::getsockopt(tcpsock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< char * >(&ipv6only), &optlen) + == 0) { + if (::setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast< const char * >(&ipv6only), + optlen) + == SOCKET_ERROR) { log(QString("Failed to copy IPV6_V6ONLY socket attribute from tcp to udp socket")); } } } - if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) == SOCKET_ERROR) { + if (::bind(sock, reinterpret_cast< sockaddr * >(&addr), len) == SOCKET_ERROR) { log(QString("Failed to bind UDP Socket to %1").arg(addressToString(ss->serverAddress(), usPort))); } else { #ifdef Q_OS_UNIX @@ -213,7 +220,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { if (setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val))) log("Server: Failed to set TOS for UDP Socket"); } -#if defined(SO_PRIORITY) +# if defined(SO_PRIORITY) socklen_t optlen = sizeof(val); if (getsockopt(sock, SOL_SOCKET, SO_PRIORITY, &val, &optlen) == 0) { if (val == 0) { @@ -221,7 +228,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &val, sizeof(val)); } } -#endif +# endif #endif } QSocketNotifier *qsn = new QSocketNotifier(sock, QSocketNotifier::Read, this); @@ -232,7 +239,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { } bValid = bValid && (qlServer.count() == qlBind.count()) && (qlUdpSocket.count() == qlBind.count()); - if (! bValid) + if (!bValid) return; #ifdef Q_OS_UNIX @@ -245,10 +252,11 @@ Server::Server(int snum, QObject *p) : QThread(p) { hNotify = CreateEvent(nullptr, FALSE, FALSE, nullptr); #endif - connect(this, SIGNAL(tcpTransmit(QByteArray, unsigned int)), this, SLOT(tcpTransmitData(QByteArray, unsigned int)), Qt::QueuedConnection); + connect(this, SIGNAL(tcpTransmit(QByteArray, unsigned int)), this, SLOT(tcpTransmitData(QByteArray, unsigned int)), + Qt::QueuedConnection); connect(this, SIGNAL(reqSync(unsigned int)), this, SLOT(doSync(unsigned int))); - for (int i=1;i<iMaxUsers*2;++i) + for (int i = 1; i < iMaxUsers * 2; ++i) qqIds.enqueue(i); connect(qtTimeout, SIGNAL(timeout()), this, SLOT(checkTimeout())); @@ -262,7 +270,7 @@ Server::Server(int snum, QObject *p) : QThread(p) { QString release; Meta::getVersion(major, minor, patch, release); - uiVersionBlob = qToBigEndian(static_cast<quint32>((major<<16) | (minor << 8) | patch)); + uiVersionBlob = qToBigEndian(static_cast< quint32 >((major << 16) | (minor << 8) | patch)); if (bValid) { #ifdef USE_BONJOUR @@ -270,16 +278,15 @@ Server::Server(int snum, QObject *p) : QThread(p) { initBonjour(); #endif initRegister(); - } } void Server::startThread() { - if (! isRunning()) { + if (!isRunning()) { log("Starting voice thread"); bRunning = true; - foreach(QSocketNotifier *qsn, qlUdpNotifier) + foreach (QSocketNotifier *qsn, qlUdpNotifier) qsn->setEnabled(false); start(QThread::HighestPriority); #ifdef Q_OS_LINUX @@ -288,14 +295,14 @@ void Server::startThread() { struct sched_param param; if (pthread_getschedparam(pthread_self(), &policy, ¶m) == 0) { if (policy == SCHED_OTHER) { - policy = SCHED_FIFO; + policy = SCHED_FIFO; param.sched_priority = 1; pthread_setschedparam(pthread_self(), policy, ¶m); } } #endif } - if (! qtTimeout->isActive()) + if (!qtTimeout->isActive()) qtTimeout->start(15500); } @@ -313,7 +320,7 @@ void Server::stopThread() { #endif wait(); - foreach(QSocketNotifier *qsn, qlUdpNotifier) + foreach (QSocketNotifier *qsn, qlUdpNotifier) qsn->setEnabled(true); } qtTimeout->stop(); @@ -326,11 +333,11 @@ Server::~Server() { stopThread(); - foreach(QSocketNotifier *qsn, qlUdpNotifier) + foreach (QSocketNotifier *qsn, qlUdpNotifier) delete qsn; #ifdef Q_OS_UNIX - foreach(int s, qlUdpSocket) + foreach (int s, qlUdpSocket) close(s); if (aiNotify[0] >= 0) @@ -338,7 +345,7 @@ Server::~Server() { if (aiNotify[1] >= 0) close(aiNotify[1]); #else - foreach(SOCKET s, qlUdpSocket) + foreach (SOCKET s, qlUdpSocket) closesocket(s); if (hNotify) CloseHandle(hNotify); @@ -384,87 +391,88 @@ static QVariant normalizeSuggestVersion(QVariant suggestVersion) { } void Server::readParams() { - qsPassword = Meta::mp.qsPassword; - usPort = static_cast<unsigned short>(Meta::mp.usPort + iServerNum - 1); - iTimeout = Meta::mp.iTimeout; - iMaxBandwidth = Meta::mp.iMaxBandwidth; - iMaxUsers = Meta::mp.iMaxUsers; - iMaxUsersPerChannel = Meta::mp.iMaxUsersPerChannel; - iMaxTextMessageLength = Meta::mp.iMaxTextMessageLength; + qsPassword = Meta::mp.qsPassword; + usPort = static_cast< unsigned short >(Meta::mp.usPort + iServerNum - 1); + iTimeout = Meta::mp.iTimeout; + iMaxBandwidth = Meta::mp.iMaxBandwidth; + iMaxUsers = Meta::mp.iMaxUsers; + iMaxUsersPerChannel = Meta::mp.iMaxUsersPerChannel; + iMaxTextMessageLength = Meta::mp.iMaxTextMessageLength; iMaxImageMessageLength = Meta::mp.iMaxImageMessageLength; - bAllowHTML = Meta::mp.bAllowHTML; - iDefaultChan = Meta::mp.iDefaultChan; - bRememberChan = Meta::mp.bRememberChan; - iRememberChanDuration = Meta::mp.iRememberChanDuration; - qsWelcomeText = Meta::mp.qsWelcomeText; - qsWelcomeTextFile = Meta::mp.qsWelcomeTextFile; - qlBind = Meta::mp.qlBind; - qsRegName = Meta::mp.qsRegName; - qsRegPassword = Meta::mp.qsRegPassword; - qsRegHost = Meta::mp.qsRegHost; - qsRegLocation = Meta::mp.qsRegLocation; - qurlRegWeb = Meta::mp.qurlRegWeb; - bBonjour = Meta::mp.bBonjour; - bAllowPing = Meta::mp.bAllowPing; - bCertRequired = Meta::mp.bCertRequired; - bForceExternalAuth = Meta::mp.bForceExternalAuth; - qrUserName = Meta::mp.qrUserName; - qrChannelName = Meta::mp.qrChannelName; - iMessageLimit = Meta::mp.iMessageLimit; - iMessageBurst = Meta::mp.iMessageBurst; - qvSuggestVersion = Meta::mp.qvSuggestVersion; - qvSuggestPositional = Meta::mp.qvSuggestPositional; - qvSuggestPushToTalk = Meta::mp.qvSuggestPushToTalk; - iOpusThreshold = Meta::mp.iOpusThreshold; - iChannelNestingLimit = Meta::mp.iChannelNestingLimit; - iChannelCountLimit = Meta::mp.iChannelCountLimit; + bAllowHTML = Meta::mp.bAllowHTML; + iDefaultChan = Meta::mp.iDefaultChan; + bRememberChan = Meta::mp.bRememberChan; + iRememberChanDuration = Meta::mp.iRememberChanDuration; + qsWelcomeText = Meta::mp.qsWelcomeText; + qsWelcomeTextFile = Meta::mp.qsWelcomeTextFile; + qlBind = Meta::mp.qlBind; + qsRegName = Meta::mp.qsRegName; + qsRegPassword = Meta::mp.qsRegPassword; + qsRegHost = Meta::mp.qsRegHost; + qsRegLocation = Meta::mp.qsRegLocation; + qurlRegWeb = Meta::mp.qurlRegWeb; + bBonjour = Meta::mp.bBonjour; + bAllowPing = Meta::mp.bAllowPing; + bCertRequired = Meta::mp.bCertRequired; + bForceExternalAuth = Meta::mp.bForceExternalAuth; + qrUserName = Meta::mp.qrUserName; + qrChannelName = Meta::mp.qrChannelName; + iMessageLimit = Meta::mp.iMessageLimit; + iMessageBurst = Meta::mp.iMessageBurst; + qvSuggestVersion = Meta::mp.qvSuggestVersion; + qvSuggestPositional = Meta::mp.qvSuggestPositional; + qvSuggestPushToTalk = Meta::mp.qvSuggestPushToTalk; + iOpusThreshold = Meta::mp.iOpusThreshold; + iChannelNestingLimit = Meta::mp.iChannelNestingLimit; + iChannelCountLimit = Meta::mp.iChannelCountLimit; QString qsHost = getConf("host", QString()).toString(); - if (! qsHost.isEmpty()) { + if (!qsHost.isEmpty()) { qlBind.clear(); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - foreach(const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), Qt::SkipEmptyParts)) { + foreach (const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), Qt::SkipEmptyParts)) { #else // Qt 5.14 introduced the Qt::SplitBehavior flags deprecating the QString fields - foreach(const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), QString::SkipEmptyParts)) { + foreach (const QString &host, qsHost.split(QRegExp(QLatin1String("\\s+")), QString::SkipEmptyParts)) { #endif QHostAddress qhaddr; if (qhaddr.setAddress(qsHost)) { qlBind << qhaddr; } else { - bool found = false; + bool found = false; QHostInfo hi = QHostInfo::fromName(host); - foreach(QHostAddress qha, hi.addresses()) { - if ((qha.protocol() == QAbstractSocket::IPv4Protocol) || (qha.protocol() == QAbstractSocket::IPv6Protocol)) { + foreach (QHostAddress qha, hi.addresses()) { + if ((qha.protocol() == QAbstractSocket::IPv4Protocol) + || (qha.protocol() == QAbstractSocket::IPv6Protocol)) { qlBind << qha; found = true; } } - if (! found) { + if (!found) { log(QString("Lookup of bind hostname %1 failed").arg(host)); } } } - foreach(const QHostAddress &qha, qlBind) + foreach (const QHostAddress &qha, qlBind) log(QString("Binding to address %1").arg(qha.toString())); if (qlBind.isEmpty()) qlBind = Meta::mp.qlBind; } - qsPassword = getConf("password", qsPassword).toString(); - usPort = static_cast<unsigned short>(getConf("port", usPort).toUInt()); - iTimeout = getConf("timeout", iTimeout).toInt(); - iMaxBandwidth = getConf("bandwidth", iMaxBandwidth).toInt(); - iMaxUsers = getConf("users", iMaxUsers).toInt(); - iMaxUsersPerChannel = getConf("usersperchannel", iMaxUsersPerChannel).toInt(); - iMaxTextMessageLength = getConf("textmessagelength", iMaxTextMessageLength).toInt(); + qsPassword = getConf("password", qsPassword).toString(); + usPort = static_cast< unsigned short >(getConf("port", usPort).toUInt()); + iTimeout = getConf("timeout", iTimeout).toInt(); + iMaxBandwidth = getConf("bandwidth", iMaxBandwidth).toInt(); + iMaxUsers = getConf("users", iMaxUsers).toInt(); + iMaxUsersPerChannel = getConf("usersperchannel", iMaxUsersPerChannel).toInt(); + iMaxTextMessageLength = getConf("textmessagelength", iMaxTextMessageLength).toInt(); iMaxImageMessageLength = getConf("imagemessagelength", iMaxImageMessageLength).toInt(); - bAllowHTML = getConf("allowhtml", bAllowHTML).toBool(); - iDefaultChan = getConf("defaultchannel", iDefaultChan).toInt(); - bRememberChan = getConf("rememberchannel", bRememberChan).toBool(); - iRememberChanDuration = getConf("rememberchannelduration", iRememberChanDuration).toInt(); - qsWelcomeText = getConf("welcometext", qsWelcomeText).toString(); - qsWelcomeTextFile = getConf("welcometextfile", qsWelcomeTextFile).toString(); + bAllowHTML = getConf("allowhtml", bAllowHTML).toBool(); + iDefaultChan = getConf("defaultchannel", iDefaultChan).toInt(); + bRememberChan = getConf("rememberchannel", bRememberChan).toBool(); + iRememberChanDuration = getConf("rememberchannelduration", iRememberChanDuration).toInt(); + qsWelcomeText = getConf("welcometext", qsWelcomeText).toString(); + qsWelcomeTextFile = getConf("welcometextfile", qsWelcomeTextFile).toString(); if (!qsWelcomeTextFile.isEmpty()) { if (qsWelcomeText.isEmpty()) { @@ -481,14 +489,14 @@ void Server::readParams() { } } - qsRegName = getConf("registername", qsRegName).toString(); - qsRegPassword = getConf("registerpassword", qsRegPassword).toString(); - qsRegHost = getConf("registerhostname", qsRegHost).toString(); - qsRegLocation = getConf("registerlocation", qsRegLocation).toString(); - qurlRegWeb = QUrl(getConf("registerurl", qurlRegWeb.toString()).toString()); - bBonjour = getConf("bonjour", bBonjour).toBool(); - bAllowPing = getConf("allowping", bAllowPing).toBool(); - bCertRequired = getConf("certrequired", bCertRequired).toBool(); + qsRegName = getConf("registername", qsRegName).toString(); + qsRegPassword = getConf("registerpassword", qsRegPassword).toString(); + qsRegHost = getConf("registerhostname", qsRegHost).toString(); + qsRegLocation = getConf("registerlocation", qsRegLocation).toString(); + qurlRegWeb = QUrl(getConf("registerurl", qurlRegWeb.toString()).toString()); + bBonjour = getConf("bonjour", bBonjour).toBool(); + bAllowPing = getConf("allowping", bAllowPing).toBool(); + bCertRequired = getConf("certrequired", bCertRequired).toBool(); bForceExternalAuth = getConf("forceExternalAuth", bForceExternalAuth).toBool(); qvSuggestVersion = normalizeSuggestVersion(getConf("suggestversion", qvSuggestVersion)); @@ -506,16 +514,16 @@ void Server::readParams() { iOpusThreshold = getConf("opusthreshold", iOpusThreshold).toInt(); iChannelNestingLimit = getConf("channelnestinglimit", iChannelNestingLimit).toInt(); - iChannelCountLimit = getConf("channelcountlimit", iChannelCountLimit).toInt(); + iChannelCountLimit = getConf("channelcountlimit", iChannelCountLimit).toInt(); - qrUserName=QRegExp(getConf("username", qrUserName.pattern()).toString()); - qrChannelName=QRegExp(getConf("channelname", qrChannelName.pattern()).toString()); + qrUserName = QRegExp(getConf("username", qrUserName.pattern()).toString()); + qrChannelName = QRegExp(getConf("channelname", qrChannelName.pattern()).toString()); - iMessageLimit=getConf("messagelimit", iMessageLimit).toUInt(); + iMessageLimit = getConf("messagelimit", iMessageLimit).toUInt(); if (iMessageLimit < 1) { // Prevent disabling messages entirely iMessageLimit = 1; } - iMessageBurst=getConf("messageburst", iMessageBurst).toUInt(); + iMessageBurst = getConf("messageburst", iMessageBurst).toUInt(); if (iMessageBurst < 1) { // Prevent disabling messages entirely iMessageBurst = 1; } @@ -523,7 +531,7 @@ void Server::readParams() { void Server::setLiveConf(const QString &key, const QString &value) { QString v = value.trimmed().isEmpty() ? QString() : value; - int i = v.toInt(); + int i = v.toInt(); if ((key == "password") || (key == "serverpassword")) qsPassword = !v.isNull() ? v : Meta::mp.qsPassword; else if (key == "timeout") @@ -597,7 +605,7 @@ void Server::setLiveConf(const QString &key, const QString &value) { QString text = !v.isNull() ? v : Meta::mp.qsRegName; if (text != qsRegName) { qsRegName = text; - if (! qsRegName.isEmpty()) { + if (!qsRegName.isEmpty()) { MumbleProto::ChannelState mpcs; mpcs.set_channel_id(0); mpcs.set_name(u8(qsRegName)); @@ -627,15 +635,16 @@ void Server::setLiveConf(const QString &key, const QString &value) { } else if (key == "allowping") bAllowPing = !v.isNull() ? QVariant(v).toBool() : Meta::mp.bAllowPing; else if (key == "username") - qrUserName=!v.isNull() ? QRegExp(v) : Meta::mp.qrUserName; + qrUserName = !v.isNull() ? QRegExp(v) : Meta::mp.qrUserName; else if (key == "channelname") - qrChannelName=!v.isNull() ? QRegExp(v) : Meta::mp.qrChannelName; + qrChannelName = !v.isNull() ? QRegExp(v) : Meta::mp.qrChannelName; else if (key == "suggestversion") - qvSuggestVersion = ! v.isNull() ? (v.isEmpty() ? QVariant() : normalizeSuggestVersion(v)) : Meta::mp.qvSuggestVersion; + qvSuggestVersion = + !v.isNull() ? (v.isEmpty() ? QVariant() : normalizeSuggestVersion(v)) : Meta::mp.qvSuggestVersion; else if (key == "suggestpositional") - qvSuggestPositional = ! v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPositional; + qvSuggestPositional = !v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPositional; else if (key == "suggestpushtotalk") - qvSuggestPushToTalk = ! v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPushToTalk; + qvSuggestPushToTalk = !v.isNull() ? (v.isEmpty() ? QVariant() : v) : Meta::mp.qvSuggestPushToTalk; else if (key == "opusthreshold") iOpusThreshold = (i >= 0 && !v.isNull()) ? qBound(0, i, 100) : Meta::mp.iOpusThreshold; else if (key == "channelnestinglimit") @@ -660,8 +669,7 @@ void Server::initBonjour() { bsRegistration = new BonjourServer(); if (bsRegistration->bsrRegister) { log("Announcing server via bonjour"); - bsRegistration->bsrRegister->registerService(BonjourRecord(qsRegName, "_mumble._tcp", ""), - usPort); + bsRegistration->bsrRegister->registerService(BonjourRecord(qsRegName, "_mumble._tcp", ""), usPort); } } @@ -674,7 +682,7 @@ void Server::removeBonjour() { void Server::customEvent(QEvent *evt) { if (evt->type() == EXEC_QEVENT) - static_cast<ExecEvent *>(evt)->execute(); + static_cast< ExecEvent * >(evt)->execute(); } void Server::udpActivated(int socket) { @@ -682,43 +690,44 @@ void Server::udpActivated(int socket) { char encrypt[UDP_PACKET_SIZE]; sockaddr_storage from; #ifdef Q_OS_UNIX -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX struct msghdr msg; struct iovec iov[1]; iov[0].iov_base = encrypt; - iov[0].iov_len = UDP_PACKET_SIZE; + iov[0].iov_len = UDP_PACKET_SIZE; - u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo),sizeof(struct in_pktinfo)))]; + u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo), sizeof(struct in_pktinfo)))]; memset(&msg, 0, sizeof(msg)); - msg.msg_name = reinterpret_cast<struct sockaddr *>(&from); - msg.msg_namelen = sizeof(from); - msg.msg_iov = iov; - msg.msg_iovlen = 1; - msg.msg_control = controldata; + msg.msg_name = reinterpret_cast< struct sockaddr * >(&from); + msg.msg_namelen = sizeof(from); + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = controldata; msg.msg_controllen = sizeof(controldata); int &sock = socket; - len=static_cast<quint32>(::recvmsg(sock, &msg, MSG_TRUNC)); -#else + len = static_cast< quint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); +# else socklen_t fromlen = sizeof(from); - int &sock = socket; - len=static_cast<qint32>(::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, reinterpret_cast<struct sockaddr *>(&from), &fromlen)); -#endif + int &sock = socket; + len = static_cast< qint32 >( + ::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, reinterpret_cast< struct sockaddr * >(&from), &fromlen)); +# endif #else int fromlen = sizeof(from); - SOCKET sock = static_cast<SOCKET>(socket); - len=::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast<struct sockaddr *>(&from), &fromlen); + SOCKET sock = static_cast< SOCKET >(socket); + len = ::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast< struct sockaddr * >(&from), &fromlen); #endif // Cloned from ::run(), as it's the only UDP data we care about until the thread is started. - quint32 *ping = reinterpret_cast<quint32 *>(encrypt); + quint32 *ping = reinterpret_cast< quint32 * >(encrypt); if ((len == 12) && (*ping == 0) && bAllowPing) { ping[0] = uiVersionBlob; - ping[3] = qToBigEndian(static_cast<quint32>(qhUsers.count())); - ping[4] = qToBigEndian(static_cast<quint32>(iMaxUsers)); - ping[5] = qToBigEndian(static_cast<quint32>(iMaxBandwidth)); + ping[3] = qToBigEndian(static_cast< quint32 >(qhUsers.count())); + ping[4] = qToBigEndian(static_cast< quint32 >(iMaxUsers)); + ping[5] = qToBigEndian(static_cast< quint32 >(iMaxBandwidth)); #ifdef Q_OS_LINUX // There will be space for only one header, and the only data we have asked for is the incoming @@ -726,7 +735,7 @@ void Server::udpActivated(int socket) { iov[0].iov_len = 6 * sizeof(quint32); ::sendmsg(sock, &msg, 0); #else - ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast<struct sockaddr *>(&from), fromlen); + ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast< struct sockaddr * >(&from), fromlen); #endif } } @@ -734,7 +743,7 @@ void Server::udpActivated(int socket) { void Server::run() { qint32 len; #if defined(__LP64__) - char encbuff[UDP_PACKET_SIZE+8]; + char encbuff[UDP_PACKET_SIZE + 8]; char *encrypt = encbuff + 4; #else char encrypt[UDP_PACKET_SIZE]; @@ -746,23 +755,23 @@ void Server::run() { #ifdef Q_OS_UNIX socklen_t fromlen; - STACKVAR(struct pollfd, fds, nfds+1); + STACKVAR(struct pollfd, fds, nfds + 1); - for (int i=0;i<nfds;++i) { - fds[i].fd = qlUdpSocket.at(i); - fds[i].events = POLLIN; + for (int i = 0; i < nfds; ++i) { + fds[i].fd = qlUdpSocket.at(i); + fds[i].events = POLLIN; fds[i].revents = 0; } - fds[nfds].fd=aiNotify[0]; - fds[nfds].events = POLLIN; + fds[nfds].fd = aiNotify[0]; + fds[nfds].events = POLLIN; fds[nfds].revents = 0; #else int fromlen; STACKVAR(SOCKET, fds, nfds); - STACKVAR(HANDLE, events, nfds+1); - for (int i=0;i<nfds;++i) { - fds[i] = qlUdpSocket.at(i); + STACKVAR(HANDLE, events, nfds + 1); + for (int i = 0; i < nfds; ++i) { + fds[i] = qlUdpSocket.at(i); events[i] = CreateEvent(nullptr, FALSE, FALSE, nullptr); ::WSAEventSelect(fds[i], events[i], FD_READ); } @@ -785,11 +794,12 @@ void Server::run() { if (fds[nfds - 1].revents) { // Drain pipe unsigned char val; - while (::recv(aiNotify[0], &val, 1, MSG_DONTWAIT) == 1) {}; + while (::recv(aiNotify[0], &val, 1, MSG_DONTWAIT) == 1) { + }; break; } - for (int i=0;i<nfds-1;++i) { + for (int i = 0; i < nfds - 1; ++i) { if (fds[i].revents) { if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) { qCritical("poll event failure"); @@ -799,7 +809,7 @@ void Server::run() { int sock = fds[i].fd; #else - for (int i=0;i<1;++i) { + for (int i = 0; i < 1; ++i) { { DWORD ret = WaitForMultipleObjects(nfds, events, FALSE, INFINITE); if (ret == (WAIT_OBJECT_0 + nfds - 1)) { @@ -815,30 +825,32 @@ void Server::run() { fromlen = sizeof(from); #ifdef Q_OS_WIN - len=::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast<struct sockaddr *>(&from), &fromlen); + len = ::recvfrom(sock, encrypt, UDP_PACKET_SIZE, 0, reinterpret_cast< struct sockaddr * >(&from), + &fromlen); #else -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX struct msghdr msg; struct iovec iov[1]; iov[0].iov_base = encrypt; - iov[0].iov_len = UDP_PACKET_SIZE; + iov[0].iov_len = UDP_PACKET_SIZE; - u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo),sizeof(struct in_pktinfo)))]; + u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo), sizeof(struct in_pktinfo)))]; memset(&msg, 0, sizeof(msg)); - msg.msg_name = reinterpret_cast<struct sockaddr *>(&from); - msg.msg_namelen = sizeof(from); - msg.msg_iov = iov; - msg.msg_iovlen = 1; - msg.msg_control = controldata; + msg.msg_name = reinterpret_cast< struct sockaddr * >(&from); + msg.msg_namelen = sizeof(from); + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = controldata; msg.msg_controllen = sizeof(controldata); - len=static_cast<quint32>(::recvmsg(sock, &msg, MSG_TRUNC)); + len = static_cast< quint32 >(::recvmsg(sock, &msg, MSG_TRUNC)); Q_UNUSED(fromlen); -#else - len=static_cast<qint32>(::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, reinterpret_cast<struct sockaddr *>(&from), &fromlen)); -#endif +# else + len = static_cast< qint32 >(::recvfrom(sock, encrypt, UDP_PACKET_SIZE, MSG_TRUNC, + reinterpret_cast< struct sockaddr * >(&from), &fromlen)); +# endif #endif if (len == 0) { break; @@ -853,38 +865,40 @@ void Server::run() { QReadLocker rl(&qrwlVoiceThread); - quint32 *ping = reinterpret_cast<quint32 *>(encrypt); + quint32 *ping = reinterpret_cast< quint32 * >(encrypt); if ((len == 12) && (*ping == 0) && bAllowPing) { ping[0] = uiVersionBlob; // 1 and 2 will be the timestamp, which we return unmodified. - ping[3] = qToBigEndian(static_cast<quint32>(qhUsers.count())); - ping[4] = qToBigEndian(static_cast<quint32>(iMaxUsers)); - ping[5] = qToBigEndian(static_cast<quint32>(iMaxBandwidth)); + ping[3] = qToBigEndian(static_cast< quint32 >(qhUsers.count())); + ping[4] = qToBigEndian(static_cast< quint32 >(iMaxUsers)); + ping[5] = qToBigEndian(static_cast< quint32 >(iMaxBandwidth)); #ifdef Q_OS_LINUX iov[0].iov_len = 6 * sizeof(quint32); ::sendmsg(sock, &msg, 0); #else - ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast<struct sockaddr *>(&from), fromlen); + ::sendto(sock, encrypt, 6 * sizeof(quint32), 0, reinterpret_cast< struct sockaddr * >(&from), + fromlen); #endif continue; } - quint16 port = (from.ss_family == AF_INET6) ? (reinterpret_cast<sockaddr_in6 *>(&from)->sin6_port) : (reinterpret_cast<sockaddr_in *>(&from)->sin_port); + quint16 port = (from.ss_family == AF_INET6) ? (reinterpret_cast< sockaddr_in6 * >(&from)->sin6_port) + : (reinterpret_cast< sockaddr_in * >(&from)->sin_port); const HostAddress &ha = HostAddress(from); - const QPair<HostAddress, quint16> &key = QPair<HostAddress, quint16>(ha, port); + const QPair< HostAddress, quint16 > &key = QPair< HostAddress, quint16 >(ha, port); ServerUser *u = qhPeerUsers.value(key); if (u) { - if (! checkDecrypt(u, encrypt, buffer, len)) { + if (!checkDecrypt(u, encrypt, buffer, len)) { continue; } } else { // Unknown peer - foreach(ServerUser *usr, qhHostUsers.value(ha)) { + foreach (ServerUser *usr, qhHostUsers.value(ha)) { if (checkDecrypt(usr, encrypt, buffer, len)) { // checkDecrypt takes the User's qrwlCrypt lock. // Every time we relock, reverify users' existance. // The main thread might delete the user while the lock isn't held. @@ -892,9 +906,9 @@ void Server::run() { rl.unlock(); qrwlVoiceThread.lockForWrite(); if (qhUsers.contains(uiSession)) { - u = usr; + u = usr; u->sUdpSocket = sock; - memcpy(& u->saiUdpAddress, &from, sizeof(from)); + memcpy(&u->saiUdpAddress, &from, sizeof(from)); qhHostUsers[from].remove(u); qhPeerUsers.insert(key, u); } @@ -905,19 +919,17 @@ void Server::run() { break; } } - if (! u) { + if (!u) { continue; } } len -= 4; - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((buffer[0] >> 5) & 0x7); - - if (msgType == MessageHandler::UDPVoiceSpeex || - msgType == MessageHandler::UDPVoiceCELTAlpha || - msgType == MessageHandler::UDPVoiceCELTBeta || - msgType == MessageHandler::UDPVoiceOpus) { + MessageHandler::UDPMessageType msgType = + static_cast< MessageHandler::UDPMessageType >((buffer[0] >> 5) & 0x7); + if (msgType == MessageHandler::UDPVoiceSpeex || msgType == MessageHandler::UDPVoiceCELTAlpha + || msgType == MessageHandler::UDPVoiceCELTBeta || msgType == MessageHandler::UDPVoiceOpus) { // Allow all voice packets through by default. bool ok = true; // ...Unless we're in Opus mode. In Opus mode, only Opus packets are allowed. @@ -940,7 +952,7 @@ void Server::run() { } } #ifdef Q_OS_WIN - for (int i=0;i<nfds-1;++i) { + for (int i = 0; i < nfds - 1; ++i) { ::WSAEventSelect(fds[i], nullptr, 0); CloseHandle(events[i]); } @@ -950,7 +962,9 @@ void Server::run() { bool Server::checkDecrypt(ServerUser *u, const char *encrypt, char *plain, unsigned int len) { QMutexLocker l(&u->qmCrypt); - if (u->csCrypt->isValid() && u->csCrypt->decrypt(reinterpret_cast<const unsigned char *>(encrypt), reinterpret_cast<unsigned char *>(plain), len)) + if (u->csCrypt->isValid() + && u->csCrypt->decrypt(reinterpret_cast< const unsigned char * >(encrypt), + reinterpret_cast< unsigned char * >(plain), len)) return true; if (u->csCrypt->tLastGood.elapsed() > 5000000ULL) { @@ -970,10 +984,10 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c if ((u->aiUdpFlag.load() == 1 || force) && (u->sUdpSocket != INVALID_SOCKET)) { #endif #if defined(__LP64__) - STACKVAR(char, ebuffer, len+4+16); - char *buffer = reinterpret_cast<char *>(((reinterpret_cast<quint64>(ebuffer) + 8) & ~7) + 4); + STACKVAR(char, ebuffer, len + 4 + 16); + char *buffer = reinterpret_cast< char * >(((reinterpret_cast< quint64 >(ebuffer) + 8) & ~7) + 4); #else - STACKVAR(char, buffer, len+4); + STACKVAR(char, buffer, len + 4); #endif { QMutexLocker wl(&u->qmCrypt); @@ -982,47 +996,51 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c return; } - if (!u->csCrypt->encrypt(reinterpret_cast<const unsigned char *>(data), reinterpret_cast<unsigned char *>(buffer), len)) { + if (!u->csCrypt->encrypt(reinterpret_cast< const unsigned char * >(data), + reinterpret_cast< unsigned char * >(buffer), len)) { return; } } #ifdef Q_OS_WIN DWORD dwFlow = 0; if (Meta::hQoS) - QOSAddSocketToFlow(Meta::hQoS, u->sUdpSocket, reinterpret_cast<struct sockaddr *>(& u->saiUdpAddress), QOSTrafficTypeVoice, QOS_NON_ADAPTIVE_FLOW, reinterpret_cast<PQOS_FLOWID>(&dwFlow)); + QOSAddSocketToFlow(Meta::hQoS, u->sUdpSocket, reinterpret_cast< struct sockaddr * >(&u->saiUdpAddress), + QOSTrafficTypeVoice, QOS_NON_ADAPTIVE_FLOW, reinterpret_cast< PQOS_FLOWID >(&dwFlow)); #endif #ifdef Q_OS_LINUX struct msghdr msg; struct iovec iov[1]; iov[0].iov_base = buffer; - iov[0].iov_len = len+4; + iov[0].iov_len = len + 4; - u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo),sizeof(struct in_pktinfo)))]; + u_char controldata[CMSG_SPACE(MAX(sizeof(struct in6_pktinfo), sizeof(struct in_pktinfo)))]; memset(controldata, 0, sizeof(controldata)); memset(&msg, 0, sizeof(msg)); - msg.msg_name = reinterpret_cast<struct sockaddr *>(& u->saiUdpAddress); - msg.msg_namelen = static_cast<socklen_t>((u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); - msg.msg_iov = iov; - msg.msg_iovlen = 1; - msg.msg_control = controldata; - msg.msg_controllen = CMSG_SPACE((u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct in6_pktinfo) : sizeof(struct in_pktinfo)); + msg.msg_name = reinterpret_cast< struct sockaddr * >(&u->saiUdpAddress); + msg.msg_namelen = static_cast< socklen_t >( + (u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = controldata; + msg.msg_controllen = CMSG_SPACE((u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct in6_pktinfo) + : sizeof(struct in_pktinfo)); struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); HostAddress tcpha(u->saiTcpLocalAddress); if (u->saiUdpAddress.ss_family == AF_INET6) { - cmsg->cmsg_level = IPPROTO_IPV6; - cmsg->cmsg_type = IPV6_PKTINFO; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); - struct in6_pktinfo *pktinfo = reinterpret_cast<struct in6_pktinfo *>(CMSG_DATA(cmsg)); + cmsg->cmsg_level = IPPROTO_IPV6; + cmsg->cmsg_type = IPV6_PKTINFO; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); + struct in6_pktinfo *pktinfo = reinterpret_cast< struct in6_pktinfo * >(CMSG_DATA(cmsg)); memset(pktinfo, 0, sizeof(*pktinfo)); memcpy(&pktinfo->ipi6_addr.s6_addr[0], &tcpha.qip6.c[0], sizeof(pktinfo->ipi6_addr.s6_addr)); } else { - cmsg->cmsg_level = IPPROTO_IP; - cmsg->cmsg_type = IP_PKTINFO; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); - struct in_pktinfo *pktinfo = reinterpret_cast<struct in_pktinfo *>(CMSG_DATA(cmsg)); + cmsg->cmsg_level = IPPROTO_IP; + cmsg->cmsg_type = IP_PKTINFO; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); + struct in_pktinfo *pktinfo = reinterpret_cast< struct in_pktinfo * >(CMSG_DATA(cmsg)); memset(pktinfo, 0, sizeof(*pktinfo)); if (tcpha.isV6()) return; @@ -1032,7 +1050,8 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c ::sendmsg(u->sUdpSocket, &msg, 0); #else - ::sendto(u->sUdpSocket, buffer, len+4, 0, reinterpret_cast<struct sockaddr *>(& u->saiUdpAddress), (u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); + ::sendto(u->sUdpSocket, buffer, len + 4, 0, reinterpret_cast< struct sockaddr * >(&u->saiUdpAddress), + (u->saiUdpAddress.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); #endif #ifdef Q_OS_WIN if (Meta::hQoS && dwFlow) @@ -1042,17 +1061,17 @@ void Server::sendMessage(ServerUser *u, const char *data, int len, QByteArray &c } else { if (cache.isEmpty()) cache = QByteArray(data, len); - emit tcpTransmit(cache,u->uiSession); + emit tcpTransmit(cache, u->uiSession); } } -#define SENDTO \ - if ((!pDst->bDeaf) && (!pDst->bSelfDeaf) && (pDst != u)) { \ - if ((poslen > 0) && (pDst->ssContext == u->ssContext)) \ - sendMessage(pDst, buffer, len, qba); \ - else \ - sendMessage(pDst, buffer, len - poslen, qba_npos); \ - } +#define SENDTO \ + if ((!pDst->bDeaf) && (!pDst->bSelfDeaf) && (pDst != u)) { \ + if ((poslen > 0) && (pDst->ssContext == u->ssContext)) \ + sendMessage(pDst, buffer, len, qba); \ + else \ + sendMessage(pDst, buffer, len - poslen, qba_npos); \ + } void Server::processMsg(ServerUser *u, const char *data, int len) { // Note that in this function we never have to aquire a read-lock on qrwlVoiceThread @@ -1067,8 +1086,8 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { unsigned int counter; char buffer[UDP_PACKET_SIZE]; PacketDataStream pdi(data + 1, len - 1); - PacketDataStream pds(buffer+1, UDP_PACKET_SIZE-1); - unsigned int type = data[0] & 0xe0; + PacketDataStream pds(buffer + 1, UDP_PACKET_SIZE - 1); + unsigned int type = data[0] & 0xe0; unsigned int target = data[0] & 0x1f; unsigned int poslen; @@ -1079,9 +1098,9 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { // IP + UDP + Crypt + Data const int packetsize = 20 + 8 + 4 + len; - if (! bw->addFrame(packetsize, iMaxBandwidth / 8)) { + if (!bw->addFrame(packetsize, iMaxBandwidth / 8)) { // Suppress packet. - return; + return; } } @@ -1110,7 +1129,7 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { len = pds.size() + 1; - if (poslen > static_cast<unsigned int>(len)) { + if (poslen > static_cast< unsigned int >(len)) { // poslen must never ever be bigger than len as this could lead to negative buffer sizes (len - poslen) being // used when further processing the packet. // Usually this shouldn't happen in the first place but can happen with malformed/malicious packets in certain @@ -1120,49 +1139,50 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { /// A set of users that'll receive the audio buffer because they are listening /// to a channel that received that audio. - QSet<ServerUser *> listeningUsers; + QSet< ServerUser * > listeningUsers; if (target == 0x1f) { // Server loopback - buffer[0] = static_cast<char>(type | SpeechFlags::Normal); + buffer[0] = static_cast< char >(type | SpeechFlags::Normal); sendMessage(u, buffer, len, qba); return; } else if (target == 0) { // Normal speech Channel *c = u->cChannel; - buffer[0] = static_cast<char>(type | SpeechFlags::Normal); + buffer[0] = static_cast< char >(type | SpeechFlags::Normal); // Send audio to all users that are listening to the channel - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(c)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(c)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst) { listeningUsers << pDst; } } // Send audio to all users in the same channel - foreach(User *p, c->qlUsers) { - ServerUser *pDst = static_cast<ServerUser *>(p); + foreach (User *p, c->qlUsers) { + ServerUser *pDst = static_cast< ServerUser * >(p); - // As we send the audio to this particular user here, we want to make sure to not send it again due to a listener proxy + // As we send the audio to this particular user here, we want to make sure to not send it again due to a + // listener proxy listeningUsers -= pDst; SENDTO; } // Send audio to all linked channels the user has speak-permission - if (! c->qhLinks.isEmpty()) { - QSet<Channel *> chans = c->allLinks(); + if (!c->qhLinks.isEmpty()) { + QSet< Channel * > chans = c->allLinks(); chans.remove(c); QMutexLocker qml(&qmCache); - foreach(Channel *l, chans) { + foreach (Channel *l, chans) { if (ChanACL::hasPermission(u, l, ChanACL::Speak, &acCache)) { // Send the audio stream to all users that are listening to the linked channel but are not // in the original channel the audio is coming from nor are they listening to the orignal // channel (in these cases they have received the audio already). - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(l)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(l)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst && pDst->cChannel != c && !ChannelListener::isListening(pDst, c)) { listeningUsers << pDst; } @@ -1171,11 +1191,12 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { // Send audio to users in the linked channel but only if they // haven't received the audio already (because they are listening // to the original channel). - foreach(User *p, l->qlUsers) { + foreach (User *p, l->qlUsers) { if (!ChannelListener::isListening(p->uiSession, c->iId)) { - ServerUser *pDst = static_cast<ServerUser *>(p); + ServerUser *pDst = static_cast< ServerUser * >(p); - // As we send the audio to this particular user here, we want to make sure to not send it again due to a listener proxy + // As we send the audio to this particular user here, we want to make sure to not send it + // again due to a listener proxy listeningUsers -= pDst; SENDTO; @@ -1185,35 +1206,33 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { } } } else if (u->qmTargets.contains(target)) { // Whisper/Shout - QSet<ServerUser *> channel; - QSet<ServerUser *> direct; - QSet<ServerUser *> listener; + QSet< ServerUser * > channel; + QSet< ServerUser * > direct; + QSet< ServerUser * > listener; if (u->qmTargetCache.contains(target)) { const WhisperTargetCache &cache = u->qmTargetCache.value(target); - channel = cache.channelTargets; - direct = cache.directTargets; - listener = cache.listeningTargets; + channel = cache.channelTargets; + direct = cache.directTargets; + listener = cache.listeningTargets; } else { const WhisperTarget &wt = u->qmTargets.value(target); - if (! wt.qlChannels.isEmpty()) { + if (!wt.qlChannels.isEmpty()) { QMutexLocker qml(&qmCache); - foreach(const WhisperTarget::Channel &wtc, wt.qlChannels) { + foreach (const WhisperTarget::Channel &wtc, wt.qlChannels) { Channel *wc = qhChannels.value(wtc.iId); if (wc) { - bool link = wtc.bLinks && ! wc->qhLinks.isEmpty(); - bool dochildren = wtc.bChildren && ! wc->qlChannels.isEmpty(); - bool group = ! wtc.qsGroup.isEmpty(); - if (!link && !dochildren && ! group) { + bool link = wtc.bLinks && !wc->qhLinks.isEmpty(); + bool dochildren = wtc.bChildren && !wc->qlChannels.isEmpty(); + bool group = !wtc.qsGroup.isEmpty(); + if (!link && !dochildren && !group) { // Common case if (ChanACL::hasPermission(u, wc, ChanACL::Whisper, &acCache)) { - foreach(User *p, wc->qlUsers) { - channel.insert(static_cast<ServerUser *>(p)); - } + foreach (User *p, wc->qlUsers) { channel.insert(static_cast< ServerUser * >(p)); } - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(wc)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(wc)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst) { listener << pDst; @@ -1221,7 +1240,7 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { } } } else { - QSet<Channel *> channels; + QSet< Channel * > channels; if (link) channels = wc->allLinks(); else @@ -1229,18 +1248,18 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { if (dochildren) channels.unite(wc->allChildren()); const QString &redirect = u->qmWhisperRedirect.value(wtc.qsGroup); - const QString &qsg = redirect.isEmpty() ? wtc.qsGroup : redirect; - foreach(Channel *tc, channels) { + const QString &qsg = redirect.isEmpty() ? wtc.qsGroup : redirect; + foreach (Channel *tc, channels) { if (ChanACL::hasPermission(u, tc, ChanACL::Whisper, &acCache)) { - foreach(User *p, tc->qlUsers) { - ServerUser *su = static_cast<ServerUser *>(p); - if (! group || Group::isMember(tc, tc, qsg, su)) { + foreach (User *p, tc->qlUsers) { + ServerUser *su = static_cast< ServerUser * >(p); + if (!group || Group::isMember(tc, tc, qsg, su)) { channel.insert(su); } } - foreach(unsigned int currentSession, ChannelListener::getListenersForChannel(tc)) { - ServerUser *pDst = static_cast<ServerUser *>(qhUsers.value(currentSession)); + foreach (unsigned int currentSession, ChannelListener::getListenersForChannel(tc)) { + ServerUser *pDst = static_cast< ServerUser * >(qhUsers.value(currentSession)); if (pDst) { listener << pDst; @@ -1260,9 +1279,10 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { { QMutexLocker qml(&qmCache); - foreach(unsigned int id, wt.qlSessions) { + foreach (unsigned int id, wt.qlSessions) { ServerUser *pDst = qhUsers.value(id); - if (pDst && ChanACL::hasPermission(u, pDst->cChannel, ChanACL::Whisper, &acCache) && !channel.contains(pDst)) + if (pDst && ChanACL::hasPermission(u, pDst->cChannel, ChanACL::Whisper, &acCache) + && !channel.contains(pDst)) direct.insert(pDst); } } @@ -1275,25 +1295,21 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { u->qmTargetCache.insert(target, { channel, direct, listener }); qrwlVoiceThread.unlock(); qrwlVoiceThread.lockForRead(); - if (! qhUsers.contains(uiSession)) + if (!qhUsers.contains(uiSession)) return; } - if (! channel.isEmpty()) { + if (!channel.isEmpty()) { // These users receive the audio because someone is shouting to their channel - buffer[0] = static_cast<char>(type | SpeechFlags::Shout); - foreach(ServerUser *pDst, channel) { - SENDTO; - } - if (! direct.isEmpty()) { + buffer[0] = static_cast< char >(type | SpeechFlags::Shout); + foreach (ServerUser *pDst, channel) { SENDTO; } + if (!direct.isEmpty()) { qba.clear(); qba_npos.clear(); } } - if (! direct.isEmpty()) { - buffer[0] = static_cast<char>(type | SpeechFlags::Whisper); - foreach(ServerUser *pDst, direct) { - SENDTO; - } + if (!direct.isEmpty()) { + buffer[0] = static_cast< char >(type | SpeechFlags::Whisper); + foreach (ServerUser *pDst, direct) { SENDTO; } } // Add the listening users to the set of current listeners @@ -1301,17 +1317,12 @@ void Server::processMsg(ServerUser *u, const char *data, int len) { } // Send the audio to all listening users - buffer[0] = static_cast<char>(type | SpeechFlags::Listen); - foreach(ServerUser *pDst, listeningUsers) { - SENDTO; - } + buffer[0] = static_cast< char >(type | SpeechFlags::Listen); + foreach (ServerUser *pDst, listeningUsers) { SENDTO; } } void Server::log(ServerUser *u, const QString &str) const { - QString msg = QString("<%1:%2(%3)> %4").arg(QString::number(u->uiSession), - u->qsName, - QString::number(u->iId), - str); + QString msg = QString("<%1:%2(%3)> %4").arg(QString::number(u->uiSession), u->qsName, QString::number(u->iId), str); log(msg); } @@ -1321,18 +1332,19 @@ void Server::log(const QString &msg) const { } void Server::newClient() { - SslServer *ss = qobject_cast<SslServer *>(sender()); - if (! ss) + SslServer *ss = qobject_cast< SslServer * >(sender()); + if (!ss) return; forever { QSslSocket *sock = ss->nextPendingSSLConnection(); - if (! sock) + if (!sock) return; QHostAddress adr = sock->peerAddress(); if (meta->banCheck(adr)) { - log(QString("Ignoring connection: %1 (Global ban)").arg(addressToString(sock->peerAddress(), sock->peerPort()))); + log(QString("Ignoring connection: %1 (Global ban)") + .arg(addressToString(sock->peerAddress(), sock->peerPort()))); sock->disconnectFromHost(); sock->deleteLater(); return; @@ -1340,8 +1352,8 @@ void Server::newClient() { HostAddress ha(adr); - QList<Ban> tmpBans = qlBans; - foreach(const Ban &ban, qlBans) { + QList< Ban > tmpBans = qlBans; + foreach (const Ban &ban, qlBans) { if (ban.isExpired()) tmpBans.removeOne(ban); } @@ -1350,9 +1362,11 @@ void Server::newClient() { saveBans(); } - foreach(const Ban &ban, qlBans) { + foreach (const Ban &ban, qlBans) { if (ban.haAddress.match(ha, ban.iMask)) { - log(QString("Ignoring connection: %1, Reason: %2, Username: %3, Hash: %4 (Server ban)").arg(addressToString(sock->peerAddress(), sock->peerPort()), ban.qsReason, ban.qsUsername, ban.qsHash)); + log(QString("Ignoring connection: %1, Reason: %2, Username: %3, Hash: %4 (Server ban)") + .arg(addressToString(sock->peerAddress(), sock->peerPort()), ban.qsReason, ban.qsUsername, + ban.qsHash)); sock->disconnectFromHost(); sock->deleteLater(); return; @@ -1374,9 +1388,10 @@ void Server::newClient() { sock->setLocalCertificate(qscCert); QSslConfiguration config; -#if QT_VERSION >= QT_VERSION_CHECK(5,15,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) config = sock->sslConfiguration(); - // Qt 5.15 introduced QSslConfiguration::addCaCertificate(s) that should be preferred over the functions in QSslSocket + // Qt 5.15 introduced QSslConfiguration::addCaCertificate(s) that should be preferred over the functions in + // QSslSocket // Treat the leaf certificate as a root. // This shouldn't strictly be necessary, @@ -1426,9 +1441,9 @@ void Server::newClient() { } ServerUser *u = new ServerUser(this, sock); - u->uiSession = qqIds.dequeue(); - u->haAddress = ha; - HostAddress(sock->localAddress()).toSockaddr(& u->saiTcpLocalAddress); + u->uiSession = qqIds.dequeue(); + u->haAddress = ha; + HostAddress(sock->localAddress()).toSockaddr(&u->saiTcpLocalAddress); { QWriteLocker wl(&qrwlVoiceThread); @@ -1436,9 +1451,12 @@ void Server::newClient() { qhHostUsers[ha].insert(u); } - connect(u, SIGNAL(connectionClosed(QAbstractSocket::SocketError, const QString &)), this, SLOT(connectionClosed(QAbstractSocket::SocketError, const QString &))); - connect(u, SIGNAL(message(unsigned int, const QByteArray &)), this, SLOT(message(unsigned int, const QByteArray &))); - connect(u, SIGNAL(handleSslErrors(const QList<QSslError> &)), this, SLOT(sslError(const QList<QSslError> &))); + connect(u, SIGNAL(connectionClosed(QAbstractSocket::SocketError, const QString &)), this, + SLOT(connectionClosed(QAbstractSocket::SocketError, const QString &))); + connect(u, SIGNAL(message(unsigned int, const QByteArray &)), this, + SLOT(message(unsigned int, const QByteArray &))); + connect(u, SIGNAL(handleSslErrors(const QList< QSslError > &)), this, + SLOT(sslError(const QList< QSslError > &))); connect(u, SIGNAL(encrypted()), this, SLOT(encrypted())); log(u, QString("New connection: %1").arg(addressToString(sock->peerAddress(), sock->peerPort()))); @@ -1461,7 +1479,7 @@ void Server::newClient() { } void Server::encrypted() { - ServerUser *uSource = qobject_cast<ServerUser *>(sender()); + ServerUser *uSource = qobject_cast< ServerUser * >(sender()); int major, minor, patch; QString release; @@ -1476,44 +1494,48 @@ void Server::encrypted() { } sendMessage(uSource, mpv); - QList<QSslCertificate> certs = uSource->peerCertificateChain(); + QList< QSslCertificate > certs = uSource->peerCertificateChain(); if (!certs.isEmpty()) { const QSslCertificate &cert = certs.last(); - uSource->qslEmail = cert.subjectAlternativeNames().values(QSsl::EmailEntry); - uSource->qsHash = QString::fromLatin1(cert.digest(QCryptographicHash::Sha1).toHex()); - if (! uSource->qslEmail.isEmpty() && uSource->bVerified) { + uSource->qslEmail = cert.subjectAlternativeNames().values(QSsl::EmailEntry); + uSource->qsHash = QString::fromLatin1(cert.digest(QCryptographicHash::Sha1).toHex()); + if (!uSource->qslEmail.isEmpty() && uSource->bVerified) { QString subject; QString issuer; QStringList subjectList = cert.subjectInfo(QSslCertificate::CommonName); - if (! subjectList.isEmpty()) { + if (!subjectList.isEmpty()) { subject = subjectList.first(); } QStringList issuerList = certs.first().issuerInfo(QSslCertificate::CommonName); - if (! issuerList.isEmpty()) { + if (!issuerList.isEmpty()) { issuer = issuerList.first(); } - log(uSource, QString::fromUtf8("Strong certificate for %1 <%2> (signed by %3)").arg(subject).arg(uSource->qslEmail.join(", ")).arg(issuer)); + log(uSource, QString::fromUtf8("Strong certificate for %1 <%2> (signed by %3)") + .arg(subject) + .arg(uSource->qslEmail.join(", ")) + .arg(issuer)); } - foreach(const Ban &ban, qlBans) { + foreach (const Ban &ban, qlBans) { if (ban.qsHash == uSource->qsHash) { - log(uSource, QString("Certificate hash is banned: %1, Username: %2, Reason: %3.").arg(ban.qsHash, ban.qsUsername, ban.qsReason)); + log(uSource, QString("Certificate hash is banned: %1, Username: %2, Reason: %3.") + .arg(ban.qsHash, ban.qsUsername, ban.qsReason)); uSource->disconnectSocket(); } } } } -void Server::sslError(const QList<QSslError> &errors) { - ServerUser *u = qobject_cast<ServerUser *>(sender()); +void Server::sslError(const QList< QSslError > &errors) { + ServerUser *u = qobject_cast< ServerUser * >(sender()); if (!u) return; bool ok = true; - foreach(QSslError e, errors) { + foreach (QSslError e, errors) { switch (e.error()) { case QSslError::InvalidPurpose: // Allow email certificates. @@ -1584,18 +1606,18 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r // "Error while reading: error:140E0197:SSL routines:SSL_shutdown:shutdown while in init [20]" // // Definitely not ideal, but it fixes a critical vulnerability. - qWarning("Ignored OpenSSL error 140E0197 for %p", static_cast<void *>(sender())); + qWarning("Ignored OpenSSL error 140E0197 for %p", static_cast< void * >(sender())); return; } - Connection *c = qobject_cast<Connection *>(sender()); - if (! c) + Connection *c = qobject_cast< Connection * >(sender()); + if (!c) return; if (c->bDisconnectedEmitted) return; c->bDisconnectedEmitted = true; - ServerUser *u = static_cast<ServerUser *>(c); + ServerUser *u = static_cast< ServerUser * >(c); log(u, QString("Connection closed: %1 [%2]").arg(reason).arg(err)); @@ -1608,7 +1630,7 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r MumbleProto::UserState mpus; mpus.set_session(u->uiSession); - foreach(int channelID, ChannelListener::getListenedChannelsForUser(u)) { + foreach (int channelID, ChannelListener::getListenedChannelsForUser(u)) { mpus.add_listening_channel_remove(channelID); // Also remove the client from the list on the server @@ -1633,8 +1655,10 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r qhUsers.remove(u->uiSession); qhHostUsers[u->haAddress].remove(u); - quint16 port = (u->saiUdpAddress.ss_family == AF_INET6) ? (reinterpret_cast<sockaddr_in6 *>(&u->saiUdpAddress)->sin6_port) : (reinterpret_cast<sockaddr_in *>(&u->saiUdpAddress)->sin_port); - const QPair<HostAddress, quint16> &key = QPair<HostAddress, quint16>(u->haAddress, port); + quint16 port = (u->saiUdpAddress.ss_family == AF_INET6) + ? (reinterpret_cast< sockaddr_in6 * >(&u->saiUdpAddress)->sin6_port) + : (reinterpret_cast< sockaddr_in * >(&u->saiUdpAddress)->sin_port); + const QPair< HostAddress, quint16 > &key = QPair< HostAddress, quint16 >(u->haAddress, port); qhPeerUsers.remove(key); if (old) @@ -1642,13 +1666,14 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r } if (old && old->bTemporary && old->qlUsers.isEmpty()) - QCoreApplication::instance()->postEvent(this, new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); + QCoreApplication::instance()->postEvent(this, + new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); - if (static_cast<int>(u->uiSession) < iMaxUsers * 2) + if (static_cast< int >(u->uiSession) < iMaxUsers * 2) qqIds.enqueue(u->uiSession); // Reinsert session id into pool if (u->sState == ServerUser::Authenticated) { - clearTempGroups(u); // Also clears ACL cache + clearTempGroups(u); // Also clears ACL cache recheckCodecVersions(); // Maybe can choose a better codec now } @@ -1660,7 +1685,7 @@ void Server::connectionClosed(QAbstractSocket::SocketError err, const QString &r void Server::message(unsigned int uiType, const QByteArray &qbaMsg, ServerUser *u) { if (!u) { - u = static_cast<ServerUser *>(sender()); + u = static_cast< ServerUser * >(sender()); } if (u->sState == ServerUser::Authenticated) { @@ -1680,13 +1705,10 @@ void Server::message(unsigned int uiType, const QByteArray &qbaMsg, ServerUser * const char *buffer = qbaMsg.constData(); - MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((buffer[0] >> 5) & 0x7); - - if (msgType == MessageHandler::UDPVoiceSpeex || - msgType == MessageHandler::UDPVoiceCELTAlpha || - msgType == MessageHandler::UDPVoiceCELTBeta || - msgType == MessageHandler::UDPVoiceOpus) { + MessageHandler::UDPMessageType msgType = static_cast< MessageHandler::UDPMessageType >((buffer[0] >> 5) & 0x7); + if (msgType == MessageHandler::UDPVoiceSpeex || msgType == MessageHandler::UDPVoiceCELTAlpha + || msgType == MessageHandler::UDPVoiceCELTBeta || msgType == MessageHandler::UDPVoiceOpus) { // Allow all voice packets through by default. bool ok = true; // ...Unless we're in Opus mode. In Opus mode, only Opus packets are allowed. @@ -1703,46 +1725,46 @@ void Server::message(unsigned int uiType, const QByteArray &qbaMsg, ServerUser * } #ifdef QT_NO_DEBUG -#define MUMBLE_MH_MSG(x) case MessageHandler:: x : { \ - MumbleProto:: x msg; \ - if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ - msg.DiscardUnknownFields(); \ - msg##x(u, msg); \ - } \ - break; \ - } +# define MUMBLE_MH_MSG(x) \ + case MessageHandler::x: { \ + MumbleProto::x msg; \ + if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ + msg.DiscardUnknownFields(); \ + msg##x(u, msg); \ + } \ + break; \ + } #else -#define MUMBLE_MH_MSG(x) case MessageHandler:: x : { \ - MumbleProto:: x msg; \ - if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ - if (uiType != MessageHandler::Ping) { \ - printf("== %s:\n", #x); \ - msg.PrintDebugString(); \ - } \ - msg.DiscardUnknownFields(); \ - msg##x(u, msg); \ - } \ - break; \ - } +# define MUMBLE_MH_MSG(x) \ + case MessageHandler::x: { \ + MumbleProto::x msg; \ + if (msg.ParseFromArray(qbaMsg.constData(), qbaMsg.size())) { \ + if (uiType != MessageHandler::Ping) { \ + printf("== %s:\n", #x); \ + msg.PrintDebugString(); \ + } \ + msg.DiscardUnknownFields(); \ + msg##x(u, msg); \ + } \ + break; \ + } #endif - switch (uiType) { - MUMBLE_MH_ALL - } + switch (uiType) { MUMBLE_MH_ALL } } void Server::checkTimeout() { - QList<ServerUser *> qlClose; + QList< ServerUser * > qlClose; qrwlVoiceThread.lockForRead(); - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->activityTime() > (iTimeout * 1000)) { log(u, "Timeout"); qlClose.append(u); } } qrwlVoiceThread.unlock(); - foreach(ServerUser *u, qlClose) + foreach (ServerUser *u, qlClose) u->disconnectSocket(true); } @@ -1753,9 +1775,9 @@ void Server::tcpTransmitData(QByteArray a, unsigned int id) { int len = a.size(); qba.resize(len + 6); - unsigned char *uc = reinterpret_cast<unsigned char *>(qba.data()); - * reinterpret_cast<quint16 *>(& uc[0]) = qToBigEndian(static_cast<quint16>(MessageHandler::UDPTunnel)); - * reinterpret_cast<quint32 *>(& uc[2]) = qToBigEndian(static_cast<quint32>(len)); + unsigned char *uc = reinterpret_cast< unsigned char * >(qba.data()); + *reinterpret_cast< quint16 * >(&uc[0]) = qToBigEndian(static_cast< quint16 >(MessageHandler::UDPTunnel)); + *reinterpret_cast< quint32 * >(&uc[2]) = qToBigEndian(static_cast< quint32 >(len)); memcpy(uc + 6, a.constData(), len); c->sendMessage(qba); @@ -1781,11 +1803,13 @@ void Server::sendProtoAll(const ::google::protobuf::Message &msg, unsigned int m sendProtoExcept(nullptr, msg, msgType, version); } -void Server::sendProtoExcept(ServerUser *u, const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int version) { +void Server::sendProtoExcept(ServerUser *u, const ::google::protobuf::Message &msg, unsigned int msgType, + unsigned int version) { QByteArray cache; - foreach(ServerUser *usr, qhUsers) + foreach (ServerUser *usr, qhUsers) if ((usr != u) && (usr->sState == ServerUser::Authenticated)) - if ((version == 0) || (usr->uiVersion >= version) || ((version & 0x80000000) && (usr->uiVersion < (~version)))) + if ((version == 0) || (usr->uiVersion >= version) + || ((version & 0x80000000) && (usr->uiVersion < (~version)))) usr->sendMessage(msg, msgType, cache); } @@ -1807,18 +1831,18 @@ void Server::removeChannel(Channel *chan, Channel *dest) { chan->unlink(nullptr); } - foreach(c, chan->qlChannels) { - removeChannel(c, dest); - } + foreach (c, chan->qlChannels) { removeChannel(c, dest); } - foreach(p, chan->qlUsers) { + foreach (p, chan->qlUsers) { { QWriteLocker wl(&qrwlVoiceThread); chan->removeUser(p); } Channel *target = dest; - while (target->cParent && (! hasPermission(static_cast<ServerUser *>(p), target, ChanACL::Enter) || isChannelFull(target, static_cast<ServerUser *>(p)))) + while (target->cParent + && (!hasPermission(static_cast< ServerUser * >(p), target, ChanACL::Enter) + || isChannelFull(target, static_cast< ServerUser * >(p)))) target = target->cParent; MumbleProto::UserState mpus; @@ -1829,7 +1853,7 @@ void Server::removeChannel(Channel *chan, Channel *dest) { emit userStateChanged(p); } - foreach(unsigned int userSession, ChannelListener::getListenersForChannel(chan)) { + foreach (unsigned int userSession, ChannelListener::getListenersForChannel(chan)) { ChannelListener::removeListener(userSession, chan->iId); // Notify that all clients that have been listening to this channel, will do so no more @@ -1856,33 +1880,33 @@ void Server::removeChannel(Channel *chan, Channel *dest) { } bool Server::unregisterUser(int id) { - if (! unregisterUserDB(id)) + if (!unregisterUserDB(id)) return false; { QMutexLocker lock(&qmCache); - foreach(Channel *c, qhChannels) { - bool write = false; - QList<ChanACL *> ql = c->qlACL; + foreach (Channel *c, qhChannels) { + bool write = false; + QList< ChanACL * > ql = c->qlACL; - foreach(ChanACL *acl, ql) { + foreach (ChanACL *acl, ql) { if (acl->iUserId == id) { c->qlACL.removeAll(acl); write = true; } } - foreach(Group *g, c->qhGroups) { + foreach (Group *g, c->qhGroups) { bool addrem = g->qsAdd.remove(id); bool remrem = g->qsRemove.remove(id); - write = write || addrem || remrem; + write = write || addrem || remrem; } if (write) updateChannel(c); } } - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->iId == id) { clearACLCache(u); MumbleProto::UserState mpus; @@ -1907,12 +1931,12 @@ void Server::userEnterChannel(User *p, Channel *c, MumbleProto::UserState &mpus) QWriteLocker wl(&qrwlVoiceThread); c->addUser(p); - bool mayspeak = ChanACL::hasPermission(static_cast<ServerUser *>(p), c, ChanACL::Speak, nullptr); - bool sup = p->bSuppress; + bool mayspeak = ChanACL::hasPermission(static_cast< ServerUser * >(p), c, ChanACL::Speak, nullptr); + bool sup = p->bSuppress; if (mayspeak == sup) { // Ok, he can speak and was suppressed, or vice versa - p->bSuppress = ! mayspeak; + p->bSuppress = !mayspeak; mpus.set_suppress(p->bSuppress); } } @@ -1921,20 +1945,21 @@ void Server::userEnterChannel(User *p, Channel *c, MumbleProto::UserState &mpus) setLastChannel(p); if (old && old->bTemporary && old->qlUsers.isEmpty()) { - QCoreApplication::instance()->postEvent(this, new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); + QCoreApplication::instance()->postEvent(this, + new ExecEvent(boost::bind(&Server::removeChannel, this, old->iId))); } - sendClientPermission(static_cast<ServerUser *>(p), c); + sendClientPermission(static_cast< ServerUser * >(p), c); if (c->cParent) - sendClientPermission(static_cast<ServerUser *>(p), c->cParent); + sendClientPermission(static_cast< ServerUser * >(p), c->cParent); } -bool Server::hasPermission(ServerUser *p, Channel *c, QFlags<ChanACL::Perm> perm) { +bool Server::hasPermission(ServerUser *p, Channel *c, QFlags< ChanACL::Perm > perm) { QMutexLocker qml(&qmCache); return ChanACL::hasPermission(p, c, perm, &acCache); } -QFlags<ChanACL::Perm> Server::effectivePermissions(ServerUser *p, Channel *c) { +QFlags< ChanACL::Perm > Server::effectivePermissions(ServerUser *p, Channel *c) { QMutexLocker qml(&qmCache); return ChanACL::effectivePermissions(p, c, &acCache); } @@ -1974,11 +1999,11 @@ void Server::sendClientPermission(ServerUser *u, Channel *c, bool forceupdate) { */ void Server::flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQuery &mppq) { - QMap<int, unsigned int>::const_iterator i; + QMap< int, unsigned int >::const_iterator i; bool match = (u->qmPermissionSent.count() < 20); for (i = u->qmPermissionSent.constBegin(); (match && (i != u->qmPermissionSent.constEnd())); ++i) { Channel *c = qhChannels.value(i.key()); - if (! c) { + if (!c) { match = false; } else { ChanACL::hasPermission(u, c, ChanACL::Enter, &acCache); @@ -1994,8 +2019,8 @@ void Server::flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQu u->qmPermissionSent.clear(); Channel *c = qhChannels.value(u->iLastPermissionCheck); - if (! c) { - c = u->cChannel; + if (!c) { + c = u->cChannel; u->iLastPermissionCheck = c->iId; } @@ -2021,13 +2046,13 @@ void Server::clearACLCache(User *p) { ChanACL::ChanCache *h = acCache.take(p); delete h; - flushClientPermissionCache(static_cast<ServerUser *>(p), mppq); + flushClientPermissionCache(static_cast< ServerUser * >(p), mppq); } else { - foreach(ChanACL::ChanCache *h, acCache) + foreach (ChanACL::ChanCache *h, acCache) delete h; acCache.clear(); - foreach(ServerUser *u, qhUsers) + foreach (ServerUser *u, qhUsers) if (u->sState == ServerUser::Authenticated) flushClientPermissionCache(u, mppq); } @@ -2041,9 +2066,7 @@ void Server::clearACLCache(User *p) { void Server::clearWhisperTargetCache() { QWriteLocker lock(&qrwlVoiceThread); - foreach(ServerUser *u, qhUsers) { - u->qmTargetCache.clear(); - } + foreach (ServerUser *u, qhUsers) { u->qmTargetCache.clear(); } } QString Server::addressToString(const QHostAddress &adr, unsigned short port) { @@ -2051,13 +2074,13 @@ QString Server::addressToString(const QHostAddress &adr, unsigned short port) { if ((Meta::mp.iObfuscate != 0)) { QCryptographicHash h(QCryptographicHash::Sha1); - h.addData(reinterpret_cast<const char *>(&Meta::mp.iObfuscate), sizeof(Meta::mp.iObfuscate)); + h.addData(reinterpret_cast< const char * >(&Meta::mp.iObfuscate), sizeof(Meta::mp.iObfuscate)); if (adr.protocol() == QAbstractSocket::IPv4Protocol) { quint32 num = adr.toIPv4Address(); - h.addData(reinterpret_cast<const char *>(&num), sizeof(num)); + h.addData(reinterpret_cast< const char * >(&num), sizeof(num)); } else if (adr.protocol() == QAbstractSocket::IPv6Protocol) { Q_IPV6ADDR num = adr.toIPv6Address(); - h.addData(reinterpret_cast<const char *>(num.c), sizeof(num.c)); + h.addData(reinterpret_cast< const char * >(num.c), sizeof(num.c)); } return QString("<<%1:%2>>").arg(QString::fromLatin1(h.result().toHex()), QString::number(port)); } @@ -2073,38 +2096,38 @@ bool Server::validateChannelName(const QString &name) { } void Server::recheckCodecVersions(ServerUser *connectingUser) { - QMap<int, int> qmCodecUsercount; - QMap<int, int>::const_iterator i; + QMap< int, int > qmCodecUsercount; + QMap< int, int >::const_iterator i; int users = 0; - int opus = 0; + int opus = 0; // Count how many users use which codec - foreach(ServerUser *u, qhUsers) { - if (u->qlCodecs.isEmpty() && ! u->bOpus) + foreach (ServerUser *u, qhUsers) { + if (u->qlCodecs.isEmpty() && !u->bOpus) continue; ++users; if (u->bOpus) ++opus; - foreach(int version, u->qlCodecs) + foreach (int version, u->qlCodecs) ++qmCodecUsercount[version]; } - if (! users) + if (!users) return; // Enable Opus if the number of users with Opus is higher than the threshold bool enableOpus = ((opus * 100 / users) >= iOpusThreshold); // Find the best possible codec most users support - int version = 0; + int version = 0; int maximum_users = 0; - i = qmCodecUsercount.constEnd(); + i = qmCodecUsercount.constEnd(); do { --i; if (i.value() > maximum_users) { - version = i.key(); + version = i.key(); maximum_users = i.value(); } } while (i != qmCodecUsercount.constBegin()); @@ -2117,10 +2140,10 @@ void Server::recheckCodecVersions(ServerUser *connectingUser) { // and announce it. if (current_version != version) { - if (version == static_cast<qint32>(0x8000000b)) + if (version == static_cast< qint32 >(0x8000000b)) bPreferAlpha = true; else - bPreferAlpha = ! bPreferAlpha; + bPreferAlpha = !bPreferAlpha; if (bPreferAlpha) iCodecAlpha = version; @@ -2128,7 +2151,11 @@ void Server::recheckCodecVersions(ServerUser *connectingUser) { iCodecBeta = version; } else if (bOpus == enableOpus) { if (bOpus && connectingUser && !connectingUser->bOpus) { - sendTextMessage(nullptr, connectingUser, false, QLatin1String("<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is using, you won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); + sendTextMessage( + nullptr, connectingUser, false, + QLatin1String( + "<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is using, you " + "won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); } return; } @@ -2143,17 +2170,25 @@ void Server::recheckCodecVersions(ServerUser *connectingUser) { sendAll(mpcv); if (bOpus) { - foreach(ServerUser *u, qhUsers) { - // Prevent connected users that could not yet declare their opus capability during msgAuthenticate from being spammed. - // Only authenticated users and the currently connecting user (if recheck is called in that context) have a reliable u->bOpus. - if((u->sState == ServerUser::Authenticated || u == connectingUser) - && !u->bOpus) { - sendTextMessage(nullptr, u, false, QLatin1String("<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is switching to, you won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); + foreach (ServerUser *u, qhUsers) { + // Prevent connected users that could not yet declare their opus capability during msgAuthenticate from + // being spammed. Only authenticated users and the currently connecting user (if recheck is called in that + // context) have a reliable u->bOpus. + if ((u->sState == ServerUser::Authenticated || u == connectingUser) && !u->bOpus) { + sendTextMessage( + nullptr, u, false, + QLatin1String( + "<strong>WARNING:</strong> Your client doesn't support the Opus codec the server is switching " + "to, you won't be able to talk or hear anyone. Please upgrade to a client with Opus support.")); } } } - log(QString::fromLatin1("CELT codec switch %1 %2 (prefer %3) (Opus %4)").arg(iCodecAlpha,0,16).arg(iCodecBeta,0,16).arg(bPreferAlpha ? iCodecAlpha : iCodecBeta,0,16).arg(bOpus)); + log(QString::fromLatin1("CELT codec switch %1 %2 (prefer %3) (Opus %4)") + .arg(iCodecAlpha, 0, 16) + .arg(iCodecBeta, 0, 16) + .arg(bPreferAlpha ? iCodecAlpha : iCodecBeta, 0, 16) + .arg(bOpus)); } void Server::hashAssign(QString &dest, QByteArray &hash, const QString &src) { @@ -2175,11 +2210,11 @@ void Server::hashAssign(QByteArray &dest, QByteArray &hash, const QByteArray &sr bool Server::isTextAllowed(QString &text, bool &changed) { changed = false; - if (! bAllowHTML) { + if (!bAllowHTML) { QString out; if (HTMLFilter::filter(text, out)) { changed = true; - text = out; + text = out; } return ((iMaxTextMessageLength == 0) || (text.length() <= iMaxTextMessageLength)); } else { @@ -2198,7 +2233,7 @@ bool Server::isTextAllowed(QString &text, bool &changed) { return true; // Over textlength, under imagelength. If no XML, this is a fail. - if (! text.contains(QLatin1Char('<'))) + if (!text.contains(QLatin1Char('<'))) return false; // Strip value from <img>s src attributes to check text-length only - @@ -2206,21 +2241,20 @@ bool Server::isTextAllowed(QString &text, bool &changed) { QString qsOut; QXmlStreamReader qxsr(QString::fromLatin1("<document>%1</document>").arg(text)); QXmlStreamWriter qxsw(&qsOut); - while (! qxsr.atEnd()) { + while (!qxsr.atEnd()) { switch (qxsr.readNext()) { case QXmlStreamReader::Invalid: return false; case QXmlStreamReader::StartElement: { - if (qxsr.name() == QLatin1String("img")) { - qxsw.writeStartElement(qxsr.namespaceUri().toString(), qxsr.name().toString()); - foreach(const QXmlStreamAttribute &a, qxsr.attributes()) - if (a.name() != QLatin1String("src")) - qxsw.writeAttribute(a); - } else { - qxsw.writeCurrentToken(qxsr); - } + if (qxsr.name() == QLatin1String("img")) { + qxsw.writeStartElement(qxsr.namespaceUri().toString(), qxsr.name().toString()); + foreach (const QXmlStreamAttribute &a, qxsr.attributes()) + if (a.name() != QLatin1String("src")) + qxsw.writeAttribute(a); + } else { + qxsw.writeCurrentToken(qxsr); } - break; + } break; default: qxsw.writeCurrentToken(qxsr); break; @@ -2238,7 +2272,7 @@ bool Server::isChannelFull(Channel *c, ServerUser *u) { return false; } if (c->uiMaxUsers) { - return static_cast<unsigned int>(c->qlUsers.count()) >= c->uiMaxUsers; + return static_cast< unsigned int >(c->qlUsers.count()) >= c->uiMaxUsers; } if (iMaxUsersPerChannel) { return c->qlUsers.count() >= iMaxUsersPerChannel; @@ -2247,8 +2281,8 @@ bool Server::isChannelFull(Channel *c, ServerUser *u) { } bool Server::canNest(Channel *newParent, Channel *channel) const { - const int parentLevel = newParent ? static_cast<int>(newParent->getLevel()) : -1; - const int channelDepth = channel ? static_cast<int>(channel->getDepth()) : 0; + const int parentLevel = newParent ? static_cast< int >(newParent->getLevel()) : -1; + const int channelDepth = channel ? static_cast< int >(channel->getDepth()) : 0; return (parentLevel + channelDepth) < iChannelNestingLimit; } diff --git a/src/murmur/Server.h b/src/murmur/Server.h index 7383d5a96..a104a9c5e 100644 --- a/src/murmur/Server.h +++ b/src/murmur/Server.h @@ -9,40 +9,40 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "ACL.h" +#include "Ban.h" +#include "HostAddress.h" #include "Message.h" #include "Mumble.pb.h" -#include "User.h" #include "Timer.h" -#include "HostAddress.h" -#include "Ban.h" +#include "User.h" #ifndef Q_MOC_RUN -# include <boost/function.hpp> +# include <boost/function.hpp> #endif #include <QtCore/QEvent> #include <QtCore/QMutex> -#include <QtCore/QTimer> #include <QtCore/QQueue> #include <QtCore/QReadWriteLock> -#include <QtCore/QStringList> #include <QtCore/QSocketNotifier> +#include <QtCore/QStringList> #include <QtCore/QThread> +#include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtNetwork/QSslCertificate> #include <QtNetwork/QSslKey> #include <QtNetwork/QSslSocket> #include <QtNetwork/QTcpServer> #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) -# include <QtNetwork/QSslDiffieHellmanParameters> +# include <QtNetwork/QSslDiffieHellmanParameters> #endif #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #endif class BonjourServer; @@ -53,390 +53,405 @@ class User; class QNetworkAccessManager; struct TextMessage { - QList<unsigned int> qlSessions; - QList<unsigned int> qlChannels; - QList<unsigned int> qlTrees; + QList< unsigned int > qlSessions; + QList< unsigned int > qlChannels; + QList< unsigned int > qlTrees; QString qsText; }; class SslServer : public QTcpServer { - private: - Q_OBJECT; - Q_DISABLE_COPY(SslServer) - protected: - QList<QSslSocket *> qlSockets; - void incomingConnection(qintptr) Q_DECL_OVERRIDE; - public: - QSslSocket *nextPendingSSLConnection(); - SslServer(QObject *parent = nullptr); - - /// Checks whether the AF_INET6 socket on this system has dual-stack support. - static bool hasDualStackSupport(); +private: + Q_OBJECT; + Q_DISABLE_COPY(SslServer) +protected: + QList< QSslSocket * > qlSockets; + void incomingConnection(qintptr) Q_DECL_OVERRIDE; + +public: + QSslSocket *nextPendingSSLConnection(); + SslServer(QObject *parent = nullptr); + + /// Checks whether the AF_INET6 socket on this system has dual-stack support. + static bool hasDualStackSupport(); }; #define EXEC_QEVENT (QEvent::User + 959) class ExecEvent : public QEvent { - Q_DISABLE_COPY(ExecEvent); - protected: - boost::function<void ()> func; - public: - ExecEvent(boost::function<void ()>); - void execute(); + Q_DISABLE_COPY(ExecEvent); + +protected: + boost::function< void() > func; + +public: + ExecEvent(boost::function< void() >); + void execute(); }; class Server : public QThread { - private: - Q_OBJECT; - Q_DISABLE_COPY(Server); - protected: - bool bRunning; +private: + Q_OBJECT; + Q_DISABLE_COPY(Server); + +protected: + bool bRunning; - QNetworkAccessManager *qnamNetwork; + QNetworkAccessManager *qnamNetwork; #ifdef USE_BONJOUR - BonjourServer *bsRegistration; + BonjourServer *bsRegistration; #endif - void startThread(); - void stopThread(); - - void customEvent(QEvent *evt); - // Former ServerParams - public: - QList<QHostAddress> qlBind; - unsigned short usPort; - int iTimeout; - int iMaxBandwidth; - int iMaxUsers; - int iMaxUsersPerChannel; - int iDefaultChan; - bool bRememberChan; - int iRememberChanDuration; - int iMaxTextMessageLength; - int iMaxImageMessageLength; - int iOpusThreshold; - bool bAllowHTML; - QString qsPassword; - QString qsWelcomeText; - QString qsWelcomeTextFile; - bool bCertRequired; - bool bForceExternalAuth; - - QString qsRegName; - QString qsRegPassword; - QString qsRegHost; - QString qsRegLocation; - QUrl qurlRegWeb; - bool bBonjour; - bool bAllowPing; - - QRegExp qrUserName; - QRegExp qrChannelName; - - unsigned int iMessageLimit; - unsigned int iMessageBurst; - - QVariant qvSuggestVersion; - QVariant qvSuggestPositional; - QVariant qvSuggestPushToTalk; - - bool bUsingMetaCert; - QSslCertificate qscCert; - QSslKey qskKey; - - /// qlIntermediates contains the certificates - /// from this virtual server's certificate PEM - // bundle that do not match the virtual server's - // private key. - /// - /// Simply put: it contains any certificates - /// that aren't the main certificate, or "leaf" - /// certificate. - QList<QSslCertificate> qlIntermediates; + void startThread(); + void stopThread(); + + void customEvent(QEvent *evt); + // Former ServerParams +public: + QList< QHostAddress > qlBind; + unsigned short usPort; + int iTimeout; + int iMaxBandwidth; + int iMaxUsers; + int iMaxUsersPerChannel; + int iDefaultChan; + bool bRememberChan; + int iRememberChanDuration; + int iMaxTextMessageLength; + int iMaxImageMessageLength; + int iOpusThreshold; + bool bAllowHTML; + QString qsPassword; + QString qsWelcomeText; + QString qsWelcomeTextFile; + bool bCertRequired; + bool bForceExternalAuth; + + QString qsRegName; + QString qsRegPassword; + QString qsRegHost; + QString qsRegLocation; + QUrl qurlRegWeb; + bool bBonjour; + bool bAllowPing; + + QRegExp qrUserName; + QRegExp qrChannelName; + + unsigned int iMessageLimit; + unsigned int iMessageBurst; + + QVariant qvSuggestVersion; + QVariant qvSuggestPositional; + QVariant qvSuggestPushToTalk; + + bool bUsingMetaCert; + QSslCertificate qscCert; + QSslKey qskKey; + + /// qlIntermediates contains the certificates + /// from this virtual server's certificate PEM + // bundle that do not match the virtual server's + // private key. + /// + /// Simply put: it contains any certificates + /// that aren't the main certificate, or "leaf" + /// certificate. + QList< QSslCertificate > qlIntermediates; #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) - QSslDiffieHellmanParameters qsdhpDHParams; + QSslDiffieHellmanParameters qsdhpDHParams; #endif - Timer tUptime; + Timer tUptime; - bool bValid; + bool bValid; - void readParams(); + void readParams(); - int iCodecAlpha; - int iCodecBeta; - bool bPreferAlpha; - bool bOpus; - void recheckCodecVersions(ServerUser *connectingUser = 0); + int iCodecAlpha; + int iCodecBeta; + bool bPreferAlpha; + bool bOpus; + void recheckCodecVersions(ServerUser *connectingUser = 0); #ifdef USE_BONJOUR - void initBonjour(); - void removeBonjour(); + void initBonjour(); + void removeBonjour(); #endif - // Registration, implementation in Register.cpp - QTimer qtTick; - void initRegister(); - - private: - int iChannelNestingLimit; - int iChannelCountLimit; - - public slots: - void regSslError(const QList<QSslError> &); - void finished(); - void update(); - - // Certificate stuff, implemented partially in Cert.cpp - public: - static bool isKeyForCert(const QSslKey &key, const QSslCertificate &cert); - /// Attempt to load a private key in PEM format from |buf|. - /// If |passphrase| is non-empty, it will be used for decrypting the private key in |buf|. - /// If a valid RSA, DSA or EC key is found, it is returned. - /// If no valid private key is found, a null QSslKey is returned. - static QSslKey privateKeyFromPEM(const QByteArray &buf, const QByteArray &pass = QByteArray()); - void initializeCert(); - const QString getDigest() const; - - public slots: - void newClient(); - void connectionClosed(QAbstractSocket::SocketError, const QString &); - void sslError(const QList<QSslError> &); - void message(unsigned int, const QByteArray &, ServerUser *cCon = nullptr); - void checkTimeout(); - void tcpTransmitData(QByteArray, unsigned int); - void doSync(unsigned int); - void encrypted(); - void udpActivated(int); - signals: - void reqSync(unsigned int); - void tcpTransmit(QByteArray, unsigned int id); - public: - int iServerNum; - QQueue<int> qqIds; - QList<SslServer *> qlServer; - QTimer *qtTimeout; + // Registration, implementation in Register.cpp + QTimer qtTick; + void initRegister(); + +private: + int iChannelNestingLimit; + int iChannelCountLimit; + +public slots: + void regSslError(const QList< QSslError > &); + void finished(); + void update(); + + // Certificate stuff, implemented partially in Cert.cpp +public: + static bool isKeyForCert(const QSslKey &key, const QSslCertificate &cert); + /// Attempt to load a private key in PEM format from |buf|. + /// If |passphrase| is non-empty, it will be used for decrypting the private key in |buf|. + /// If a valid RSA, DSA or EC key is found, it is returned. + /// If no valid private key is found, a null QSslKey is returned. + static QSslKey privateKeyFromPEM(const QByteArray &buf, const QByteArray &pass = QByteArray()); + void initializeCert(); + const QString getDigest() const; + +public slots: + void newClient(); + void connectionClosed(QAbstractSocket::SocketError, const QString &); + void sslError(const QList< QSslError > &); + void message(unsigned int, const QByteArray &, ServerUser *cCon = nullptr); + void checkTimeout(); + void tcpTransmitData(QByteArray, unsigned int); + void doSync(unsigned int); + void encrypted(); + void udpActivated(int); +signals: + void reqSync(unsigned int); + void tcpTransmit(QByteArray, unsigned int id); + +public: + int iServerNum; + QQueue< int > qqIds; + QList< SslServer * > qlServer; + QTimer *qtTimeout; #ifdef Q_OS_UNIX - int aiNotify[2]; - QList<int> qlUdpSocket; + int aiNotify[2]; + QList< int > qlUdpSocket; #else - HANDLE hNotify; - QList<SOCKET> qlUdpSocket; + HANDLE hNotify; + QList< SOCKET > qlUdpSocket; #endif - quint32 uiVersionBlob; - QList<QSocketNotifier *> qlUdpNotifier; - - /// This lock provides synchronization between the - /// main thread (where control channel messages and - /// RPC happens), and the Server's voice thread. - /// - /// These are the only two threads in Murmur that - /// access a Server's data. - /// - /// The easiest way to understand the locking strategy - /// and synchronization between the main thread and the - /// Server's voice thread is by using the concept of - /// ownership. - /// - /// A thread owning an object means that it is the only - /// thread that is allowed to write to that object. To - /// make changes to it. - /// - /// Most data in the Server class is owned by the main - /// thread. That means that the main thread is the only - /// thread that writes/updates those structures. - /// - /// When processing incoming voice data (and re- - /// broadcasting) that voice data), the Server's voice - /// thread needs to access various parts of Server's data, - /// such as qhUsers, qhChannels, User->cChannel, etc. - /// However, these are owned by the main thread. - /// - /// To ensure correct synchronization between the two - /// threads, the contract for using qrwlVoiceThread is - /// as follows: - /// - /// - When the Server's voice thread needs to read data - /// owned by the main thread, it must hold a read lock - /// on qrwlVoiceThread. - /// - /// - The Server's voice thread does not write to any data - /// that is owned by the main thread. - /// - /// - When the main thread needs to write to data owned by - /// itself that is accessed by the voice thread, it must - /// hold a write lock on qrwlVoiceThread. - /// - /// - When the main thread needs to read data that is owned - /// by itself, it DOES NOT hold a lock on qrwlVoiceThread. - /// That is because ownership of data guarantees that no - /// other thread can write to that data. - QReadWriteLock qrwlVoiceThread; - QHash<unsigned int, ServerUser *> qhUsers; - QHash<QPair<HostAddress, quint16>, ServerUser *> qhPeerUsers; - QHash<HostAddress, QSet<ServerUser *> > qhHostUsers; - QHash<unsigned int, Channel *> qhChannels; - - QMutex qmCache; - ChanACL::ACLCache acCache; - - QHash<int, QString> qhUserNameCache; - QHash<QString, int> qhUserIDCache; - - QList<Ban> qlBans; - - void processMsg(ServerUser *u, const char *data, int len); - void sendMessage(ServerUser *u, const char *data, int len, QByteArray &cache, bool force = false); - void run(); - - bool validateChannelName(const QString &name); - bool validateUserName(const QString &name); - - bool checkDecrypt(ServerUser *u, const char *encrypted, char *plain, unsigned int cryptlen); - - bool hasPermission(ServerUser *p, Channel *c, QFlags<ChanACL::Perm> perm); - QFlags<ChanACL::Perm> effectivePermissions(ServerUser *p, Channel *c); - void sendClientPermission(ServerUser *u, Channel *c, bool updatelast = false); - void flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQuery &mpqq); - void clearACLCache(User *p = nullptr); - void clearWhisperTargetCache(); - - void sendProtoAll(const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int minversion); - void sendProtoExcept(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int minversion); - void sendProtoMessage(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType); - - // sendAll sends a protobuf message to all users on the server whose version is either bigger than v or - // lower than ~v. If v == 0 the message is sent to everyone. -#define MUMBLE_MH_MSG(x) \ - void sendAll(const MumbleProto:: x &msg, unsigned int v = 0) { sendProtoAll(msg, MessageHandler:: x, v); } \ - void sendExcept(ServerUser *u, const MumbleProto:: x &msg, unsigned int v = 0) { sendProtoExcept(u, msg, MessageHandler:: x, v); } \ - void sendMessage(ServerUser *u, const MumbleProto:: x &msg) { sendProtoMessage(u, msg, MessageHandler:: x); } - - MUMBLE_MH_ALL + quint32 uiVersionBlob; + QList< QSocketNotifier * > qlUdpNotifier; + + /// This lock provides synchronization between the + /// main thread (where control channel messages and + /// RPC happens), and the Server's voice thread. + /// + /// These are the only two threads in Murmur that + /// access a Server's data. + /// + /// The easiest way to understand the locking strategy + /// and synchronization between the main thread and the + /// Server's voice thread is by using the concept of + /// ownership. + /// + /// A thread owning an object means that it is the only + /// thread that is allowed to write to that object. To + /// make changes to it. + /// + /// Most data in the Server class is owned by the main + /// thread. That means that the main thread is the only + /// thread that writes/updates those structures. + /// + /// When processing incoming voice data (and re- + /// broadcasting) that voice data), the Server's voice + /// thread needs to access various parts of Server's data, + /// such as qhUsers, qhChannels, User->cChannel, etc. + /// However, these are owned by the main thread. + /// + /// To ensure correct synchronization between the two + /// threads, the contract for using qrwlVoiceThread is + /// as follows: + /// + /// - When the Server's voice thread needs to read data + /// owned by the main thread, it must hold a read lock + /// on qrwlVoiceThread. + /// + /// - The Server's voice thread does not write to any data + /// that is owned by the main thread. + /// + /// - When the main thread needs to write to data owned by + /// itself that is accessed by the voice thread, it must + /// hold a write lock on qrwlVoiceThread. + /// + /// - When the main thread needs to read data that is owned + /// by itself, it DOES NOT hold a lock on qrwlVoiceThread. + /// That is because ownership of data guarantees that no + /// other thread can write to that data. + QReadWriteLock qrwlVoiceThread; + QHash< unsigned int, ServerUser * > qhUsers; + QHash< QPair< HostAddress, quint16 >, ServerUser * > qhPeerUsers; + QHash< HostAddress, QSet< ServerUser * > > qhHostUsers; + QHash< unsigned int, Channel * > qhChannels; + + QMutex qmCache; + ChanACL::ACLCache acCache; + + QHash< int, QString > qhUserNameCache; + QHash< QString, int > qhUserIDCache; + + QList< Ban > qlBans; + + void processMsg(ServerUser *u, const char *data, int len); + void sendMessage(ServerUser *u, const char *data, int len, QByteArray &cache, bool force = false); + void run(); + + bool validateChannelName(const QString &name); + bool validateUserName(const QString &name); + + bool checkDecrypt(ServerUser *u, const char *encrypted, char *plain, unsigned int cryptlen); + + bool hasPermission(ServerUser *p, Channel *c, QFlags< ChanACL::Perm > perm); + QFlags< ChanACL::Perm > effectivePermissions(ServerUser *p, Channel *c); + void sendClientPermission(ServerUser *u, Channel *c, bool updatelast = false); + void flushClientPermissionCache(ServerUser *u, MumbleProto::PermissionQuery &mpqq); + void clearACLCache(User *p = nullptr); + void clearWhisperTargetCache(); + + void sendProtoAll(const ::google::protobuf::Message &msg, unsigned int msgType, unsigned int minversion); + void sendProtoExcept(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType, + unsigned int minversion); + void sendProtoMessage(ServerUser *, const ::google::protobuf::Message &msg, unsigned int msgType); + + // sendAll sends a protobuf message to all users on the server whose version is either bigger than v or + // lower than ~v. If v == 0 the message is sent to everyone. +#define MUMBLE_MH_MSG(x) \ + void sendAll(const MumbleProto::x &msg, unsigned int v = 0) { sendProtoAll(msg, MessageHandler::x, v); } \ + void sendExcept(ServerUser *u, const MumbleProto::x &msg, unsigned int v = 0) { \ + sendProtoExcept(u, msg, MessageHandler::x, v); \ + } \ + void sendMessage(ServerUser *u, const MumbleProto::x &msg) { sendProtoMessage(u, msg, MessageHandler::x); } + + MUMBLE_MH_ALL #undef MUMBLE_MH_MSG - static void hashAssign(QString &destination, QByteArray &hash, const QString &str); - static void hashAssign(QByteArray &destination, QByteArray &hash, const QByteArray &source); - bool isTextAllowed(QString &str, bool &changed); - - void setLiveConf(const QString &key, const QString &value); - - QString addressToString(const QHostAddress &, unsigned short port); - - void log(const QString &) const; - void log(ServerUser *u, const QString &) const; - - void removeChannel(int id); - void removeChannel(Channel *c, Channel *dest = nullptr); - void userEnterChannel(User *u, Channel *c, MumbleProto::UserState &mpus); - bool unregisterUser(int id); - - Server(int snum, QObject *parent = nullptr); - ~Server(); - - bool canNest(Channel *newParent, Channel *channel = nullptr) const; - - // RPC functions. Implementation in RPC.cpp - void connectAuthenticator(QObject *p); - void disconnectAuthenticator(QObject *p); - void connectListener(QObject *p); - void disconnectListener(QObject *p); - void setTempGroups(int userid, int sessionId, Channel *cChannel, const QStringList &groups); - void clearTempGroups(User *user, Channel *cChannel = nullptr, bool recurse = true); - void startListeningToChannel(ServerUser *user, Channel *cChannel); - void stopListeningToChannel(ServerUser *user, Channel *cChannel); - signals: - void registerUserSig(int &, const QMap<int, QString> &); - void unregisterUserSig(int &, int); - void getRegisteredUsersSig(const QString &, QMap<int, QString > &); - void getRegistrationSig(int &, int, QMap<int, QString> &); - void authenticateSig(int &, QString &, int, const QList<QSslCertificate> &, const QString &, bool, const QString &); - void setInfoSig(int &, int, const QMap<int, QString> &); - void setTextureSig(int &, int, const QByteArray &); - void idToNameSig(QString &, int); - void nameToIdSig(int &, const QString &); - void idToTextureSig(QByteArray &, int); - - void userStateChanged(const User *); - void userTextMessage(const User *, const TextMessage &); - void userConnected(const User *); - void userDisconnected(const User *); - void channelStateChanged(const Channel *); - void channelCreated(const Channel *); - void channelRemoved(const Channel *); - - void textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &); - - void contextAction(const User *, const QString &, unsigned int, int); - public: - void setUserState(User *p, Channel *parent, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, const QString& name = QString(), const QString &comment = QString()); - - /// Update a channel's state using the ChannelState protobuf message and - /// broadcast the changes appropriately to the server. On return, if - /// err is non-empty, the operation failed, and err contains a description - /// of the error. - /// - /// This method is equivalent to the logic that happens in - /// Server::msgChannelState when a ChannelState message is recieved from - /// a user. However, this method doesn't do permissions checking. - /// - /// This method is used by the gRPC implementation to perform channel - /// state changes. - bool setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &err); - - bool setChannelState(Channel *c, Channel *parent, const QString &qsName, const QSet<Channel *> &links, const QString &desc = QString(), const int position = 0); - - /// Send a text message using the TextMessage protobuf message - /// as a template. - /// This is equivalent to the logic that happens in Server::msgTextMessage - /// when sending a receieved TextMessage, with the exception that this - /// method does not perform any permission checks. - /// It is used by our gRPC implementation to send text messages. - void sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm); - - void sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, const QString &text); - - /// Returns true if a channel is full. If a user is provided, false will always - /// be returned if the user has write permission in the channel. - bool isChannelFull(Channel *c, ServerUser *u = 0); - - // Database / DBus functions. Implementation in ServerDB.cpp - void initialize(); - int authenticate(QString &name, const QString &pw, int sessionId = 0, const QStringList &emails = QStringList(), const QString &certhash = QString(), bool bStrongCert = false, const QList<QSslCertificate> & = QList<QSslCertificate>()); - Channel *addChannel(Channel *c, const QString &name, bool temporary = false, int position = 0, unsigned int maxUsers = 0); - void removeChannelDB(const Channel *c); - void readChannels(Channel *p = nullptr); - void readLinks(); - void updateChannel(const Channel *c); - void readChannelPrivs(Channel *c); - void setLastChannel(const User *u); - int readLastChannel(int id); - - /// Set last_disconnect of a registered user to the current time - void setLastDisconnect(const User *u); - void dumpChannel(const Channel *c); - int getUserID(const QString &name); - QString getUserName(int id); - QByteArray getUserTexture(int id); - QMap<int, QString> getRegistration(int id); - int registerUser(const QMap<int, QString> &info); - bool unregisterUserDB(int id); - QList<UserInfo> getRegisteredUsersEx(); - QMap<int, QString > getRegisteredUsers(const QString &filter = QString()); - bool setInfo(int id, const QMap<int, QString> &info); - bool setTexture(int id, const QByteArray &texture); - bool isUserId(int id); - void addLink(Channel *c, Channel *l); - void removeLink(Channel *c, Channel *l); - void getBans(); - void saveBans(); - QVariant getConf(const QString &key, QVariant def); - void setConf(const QString &key, const QVariant &value); - void dblog(const QString &str) const; - - // From msgHandler. Implementation in Messages.cpp -#define MUMBLE_MH_MSG(x) void msg##x(ServerUser *, MumbleProto:: x &); - MUMBLE_MH_ALL + static void hashAssign(QString &destination, QByteArray &hash, const QString &str); + static void hashAssign(QByteArray &destination, QByteArray &hash, const QByteArray &source); + bool isTextAllowed(QString &str, bool &changed); + + void setLiveConf(const QString &key, const QString &value); + + QString addressToString(const QHostAddress &, unsigned short port); + + void log(const QString &) const; + void log(ServerUser *u, const QString &) const; + + void removeChannel(int id); + void removeChannel(Channel *c, Channel *dest = nullptr); + void userEnterChannel(User *u, Channel *c, MumbleProto::UserState &mpus); + bool unregisterUser(int id); + + Server(int snum, QObject *parent = nullptr); + ~Server(); + + bool canNest(Channel *newParent, Channel *channel = nullptr) const; + + // RPC functions. Implementation in RPC.cpp + void connectAuthenticator(QObject *p); + void disconnectAuthenticator(QObject *p); + void connectListener(QObject *p); + void disconnectListener(QObject *p); + void setTempGroups(int userid, int sessionId, Channel *cChannel, const QStringList &groups); + void clearTempGroups(User *user, Channel *cChannel = nullptr, bool recurse = true); + void startListeningToChannel(ServerUser *user, Channel *cChannel); + void stopListeningToChannel(ServerUser *user, Channel *cChannel); +signals: + void registerUserSig(int &, const QMap< int, QString > &); + void unregisterUserSig(int &, int); + void getRegisteredUsersSig(const QString &, QMap< int, QString > &); + void getRegistrationSig(int &, int, QMap< int, QString > &); + void authenticateSig(int &, QString &, int, const QList< QSslCertificate > &, const QString &, bool, + const QString &); + void setInfoSig(int &, int, const QMap< int, QString > &); + void setTextureSig(int &, int, const QByteArray &); + void idToNameSig(QString &, int); + void nameToIdSig(int &, const QString &); + void idToTextureSig(QByteArray &, int); + + void userStateChanged(const User *); + void userTextMessage(const User *, const TextMessage &); + void userConnected(const User *); + void userDisconnected(const User *); + void channelStateChanged(const Channel *); + void channelCreated(const Channel *); + void channelRemoved(const Channel *); + + void textMessageFilterSig(int &, const User *, MumbleProto::TextMessage &); + + void contextAction(const User *, const QString &, unsigned int, int); + +public: + void setUserState(User *p, Channel *parent, bool mute, bool deaf, bool suppressed, bool prioritySpeaker, + const QString &name = QString(), const QString &comment = QString()); + + /// Update a channel's state using the ChannelState protobuf message and + /// broadcast the changes appropriately to the server. On return, if + /// err is non-empty, the operation failed, and err contains a description + /// of the error. + /// + /// This method is equivalent to the logic that happens in + /// Server::msgChannelState when a ChannelState message is recieved from + /// a user. However, this method doesn't do permissions checking. + /// + /// This method is used by the gRPC implementation to perform channel + /// state changes. + bool setChannelStateGRPC(const MumbleProto::ChannelState &cs, QString &err); + + bool setChannelState(Channel *c, Channel *parent, const QString &qsName, const QSet< Channel * > &links, + const QString &desc = QString(), const int position = 0); + + /// Send a text message using the TextMessage protobuf message + /// as a template. + /// This is equivalent to the logic that happens in Server::msgTextMessage + /// when sending a receieved TextMessage, with the exception that this + /// method does not perform any permission checks. + /// It is used by our gRPC implementation to send text messages. + void sendTextMessageGRPC(const ::MumbleProto::TextMessage &tm); + + void sendTextMessage(Channel *cChannel, ServerUser *pUser, bool tree, const QString &text); + + /// Returns true if a channel is full. If a user is provided, false will always + /// be returned if the user has write permission in the channel. + bool isChannelFull(Channel *c, ServerUser *u = 0); + + // Database / DBus functions. Implementation in ServerDB.cpp + void initialize(); + int authenticate(QString &name, const QString &pw, int sessionId = 0, const QStringList &emails = QStringList(), + const QString &certhash = QString(), bool bStrongCert = false, + const QList< QSslCertificate > & = QList< QSslCertificate >()); + Channel *addChannel(Channel *c, const QString &name, bool temporary = false, int position = 0, + unsigned int maxUsers = 0); + void removeChannelDB(const Channel *c); + void readChannels(Channel *p = nullptr); + void readLinks(); + void updateChannel(const Channel *c); + void readChannelPrivs(Channel *c); + void setLastChannel(const User *u); + int readLastChannel(int id); + + /// Set last_disconnect of a registered user to the current time + void setLastDisconnect(const User *u); + void dumpChannel(const Channel *c); + int getUserID(const QString &name); + QString getUserName(int id); + QByteArray getUserTexture(int id); + QMap< int, QString > getRegistration(int id); + int registerUser(const QMap< int, QString > &info); + bool unregisterUserDB(int id); + QList< UserInfo > getRegisteredUsersEx(); + QMap< int, QString > getRegisteredUsers(const QString &filter = QString()); + bool setInfo(int id, const QMap< int, QString > &info); + bool setTexture(int id, const QByteArray &texture); + bool isUserId(int id); + void addLink(Channel *c, Channel *l); + void removeLink(Channel *c, Channel *l); + void getBans(); + void saveBans(); + QVariant getConf(const QString &key, QVariant def); + void setConf(const QString &key, const QVariant &value); + void dblog(const QString &str) const; + + // From msgHandler. Implementation in Messages.cpp +#define MUMBLE_MH_MSG(x) void msg##x(ServerUser *, MumbleProto::x &); + MUMBLE_MH_ALL #undef MUMBLE_MH_MSG }; diff --git a/src/murmur/ServerDB.cpp b/src/murmur/ServerDB.cpp index 460db00cb..58316d699 100644 --- a/src/murmur/ServerDB.cpp +++ b/src/murmur/ServerDB.cpp @@ -6,7 +6,7 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "ServerDB.h" @@ -17,20 +17,20 @@ #include "DBus.h" #include "Group.h" #include "Meta.h" +#include "PBKDF2.h" +#include "PasswordGenerator.h" #include "Server.h" #include "ServerUser.h" #include "User.h" -#include "PBKDF2.h" -#include "PasswordGenerator.h" #include <QtCore/QCoreApplication> #include <QtSql/QSqlError> #include <QtSql/QSqlQuery> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #else -# include <arpa/inet.h> +# include <arpa/inet.h> #endif #define SQLQUERY(x) ServerDB::query(query, QLatin1String(x), true) @@ -44,22 +44,22 @@ class TransactionHolder { - public: - QSqlQuery *qsqQuery; - TransactionHolder() { - ServerDB::db->transaction(); - qsqQuery = new QSqlQuery(); - } +public: + QSqlQuery *qsqQuery; + TransactionHolder() { + ServerDB::db->transaction(); + qsqQuery = new QSqlQuery(); + } - ~TransactionHolder() { - qsqQuery->clear(); - delete qsqQuery; - ServerDB::db->commit(); - } - TransactionHolder(const TransactionHolder & other) { - ServerDB::db->transaction(); - qsqQuery = other.qsqQuery ? new QSqlQuery(*other.qsqQuery) : 0; - } + ~TransactionHolder() { + qsqQuery->clear(); + delete qsqQuery; + ServerDB::db->commit(); + } + TransactionHolder(const TransactionHolder &other) { + ServerDB::db->transaction(); + qsqQuery = other.qsqQuery ? new QSqlQuery(*other.qsqQuery) : 0; + } }; QSqlDatabase *ServerDB::db = nullptr; @@ -80,7 +80,8 @@ void ServerDB::loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query) { // Didn't get a valid iteration count from DB, overwrite Meta::mp.kdfIterations = PBKDF2::benchmark(); - qWarning() << "Performed initial PBKDF2 benchmark. Will use" << Meta::mp.kdfIterations << "iterations as default"; + qWarning() << "Performed initial PBKDF2 benchmark. Will use" << Meta::mp.kdfIterations + << "iterations as default"; SQLPREP("INSERT INTO `%1meta` (`keystring`, `value`) VALUES('pbkdf2_iterations',?)"); query.addBindValue(Meta::mp.kdfIterations); @@ -89,16 +90,20 @@ void ServerDB::loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query) { } if (Meta::mp.kdfIterations < PBKDF2::BENCHMARK_MINIMUM_ITERATION_COUNT) { - qWarning() << "Configured default PBKDF2 iteration count of" << Meta::mp.kdfIterations << "is below minimum recommended value of" << PBKDF2::BENCHMARK_MINIMUM_ITERATION_COUNT << "and could be insecure."; + qWarning() << "Configured default PBKDF2 iteration count of" << Meta::mp.kdfIterations + << "is below minimum recommended value of" << PBKDF2::BENCHMARK_MINIMUM_ITERATION_COUNT + << "and could be insecure."; } } } ServerDB::ServerDB() { - if (Meta::mp.qsDBDriver != QLatin1String("QMYSQL") && Meta::mp.qsDBDriver != QLatin1String("QSQLITE") && Meta::mp.qsDBDriver != QLatin1String("QPSQL")) { - qFatal("ServerDB: invalid DB driver specified: '%s'. Murmur only supports QSQLITE, QMYSQL, and QPSQL.", qPrintable(Meta::mp.qsDBDriver)); + if (Meta::mp.qsDBDriver != QLatin1String("QMYSQL") && Meta::mp.qsDBDriver != QLatin1String("QSQLITE") + && Meta::mp.qsDBDriver != QLatin1String("QPSQL")) { + qFatal("ServerDB: invalid DB driver specified: '%s'. Murmur only supports QSQLITE, QMYSQL, and QPSQL.", + qPrintable(Meta::mp.qsDBDriver)); } - if (! QSqlDatabase::isDriverAvailable(Meta::mp.qsDBDriver)) { + if (!QSqlDatabase::isDriverAvailable(Meta::mp.qsDBDriver)) { qFatal("ServerDB: Database driver %s not available", qPrintable(Meta::mp.qsDBDriver)); } if (db) { @@ -112,7 +117,7 @@ ServerDB::ServerDB() { bool found = false; if (Meta::mp.qsDBDriver == "QSQLITE") { - if (! Meta::mp.qsDatabase.isEmpty()) { + if (!Meta::mp.qsDatabase.isEmpty()) { db->setDatabaseName(Meta::mp.qsDatabase); found = db->open(); } else { @@ -124,7 +129,7 @@ ServerDB::ServerDB() { datapaths << QCoreApplication::instance()->applicationDirPath(); datapaths << QDir::homePath(); - for (i = 0; (i < datapaths.size()) && ! found; i++) { + for (i = 0; (i < datapaths.size()) && !found; i++) { if (!datapaths[i].isEmpty()) { QFile f(datapaths[i] + "/murmur.sqlite"); if (f.exists()) { @@ -134,8 +139,8 @@ ServerDB::ServerDB() { } } - if (! found) { - for (i = 0; (i < datapaths.size()) && ! found; i++) { + if (!found) { + for (i = 0; (i < datapaths.size()) && !found; i++) { if (!datapaths[i].isEmpty()) { QFile f(datapaths[i] + "/murmur.sqlite"); db->setDatabaseName(f.fileName()); @@ -147,7 +152,7 @@ ServerDB::ServerDB() { if (found) { QFileInfo fi(db->databaseName()); qWarning("ServerDB: Opened SQLite database %s", qPrintable(fi.absoluteFilePath())); - if (! fi.isWritable()) + if (!fi.isWritable()) qFatal("ServerDB: Database is not writable"); } } else { @@ -160,9 +165,9 @@ ServerDB::ServerDB() { found = db->open(); } - if (! found) { + if (!found) { QSqlError e = db->lastError(); - qFatal("ServerDB: Failed initialization: %s",qPrintable(e.text())); + qFatal("ServerDB: Failed initialization: %s", qPrintable(e.text())); } // Use SQLite in WAL mode if possible. @@ -173,7 +178,7 @@ ServerDB::ServerDB() { QSqlQuery query; bool hasversion = false; - bool okversion = false; + bool okversion = false; QString version; SQLDO("SELECT sqlite_version();"); if (query.next()) { @@ -183,8 +188,8 @@ ServerDB::ServerDB() { QStringList splitVersion = version.split(QLatin1String(".")); int major = 0, minor = 0; if (splitVersion.count() >= 3) { - major = splitVersion.at(0).toInt(); - minor = splitVersion.at(1).toInt(); + major = splitVersion.at(0).toInt(); + minor = splitVersion.at(1).toInt(); hasversion = true; } if (major > 3 || (major == 3 && minor >= 7)) { @@ -201,12 +206,16 @@ ServerDB::ServerDB() { qWarning("ServerDB: Configured SQLite for journal_mode=WAL, synchronous=FULL"); } } else if (hasversion) { - qWarning("ServerDB: Unable to use SQLite in WAL mode due to incompatible SQLite version %i.%i", major, minor); + qWarning("ServerDB: Unable to use SQLite in WAL mode due to incompatible SQLite version %i.%i", major, + minor); } else { - qWarning("ServerDB: Unable to use SQLite in WAL mode because the SQLite version could not be determined."); + qWarning( + "ServerDB: Unable to use SQLite in WAL mode because the SQLite version could not be determined."); } } else { - qFatal("ServerDB: Invalid value '%i' for sqlite_wal. Please use 0 (no wal), 1 (wal), 2 (wal with synchronous=full)", Meta::mp.iSQLiteWAL); + qFatal("ServerDB: Invalid value '%i' for sqlite_wal. Please use 0 (no wal), 1 (wal), 2 (wal with " + "synchronous=full)", + Meta::mp.iSQLiteWAL); } } @@ -216,19 +225,24 @@ ServerDB::ServerDB() { // Ensure that a proper encoding is used for the DB if (Meta::mp.qsDBDriver == "QMYSQL") { - query.exec(QString::fromLatin1("SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '%1'").arg(Meta::mp.qsDatabase)); + query.exec(QString::fromLatin1( + "SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '%1'") + .arg(Meta::mp.qsDatabase)); if (query.next()) { QString encoding = query.value(0).toString(); - // Because MySQL's utf8 implementation is not actually utf8, we have to use a different name to access the actual - // utf8 implementation. (See https://mathiasbynens.be/notes/mysql-utf8mb4) + // Because MySQL's utf8 implementation is not actually utf8, we have to use a different name to access the + // actual utf8 implementation. (See https://mathiasbynens.be/notes/mysql-utf8mb4) if (encoding.toLower() != QLatin1String("utf8mb4")) { // Change the database's encoding qWarning("Changing database encoding to utf8mb4..."); - if (!query.exec(QString::fromLatin1("ALTER DATABASE `%1` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci").arg(Meta::mp.qsDatabase))) { - qFatal("ServerDB: Failed to set default encoding & collation to UTF-8: %s", qPrintable(query.lastError().text())); + if (!query.exec( + QString::fromLatin1("ALTER DATABASE `%1` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci") + .arg(Meta::mp.qsDatabase))) { + qFatal("ServerDB: Failed to set default encoding & collation to UTF-8: %s", + qPrintable(query.lastError().text())); } } } else { @@ -280,7 +294,8 @@ ServerDB::ServerDB() { SQLQUERY("CREATE TABLE IF NOT EXISTS `%1meta` (`keystring` varchar(255) PRIMARY KEY, `value` varchar(255))"); else // MySQL - SQLDO("CREATE TABLE IF NOT EXISTS `%1meta`(`keystring` varchar(255) PRIMARY KEY, `value` varchar(255)) ENGINE=InnoDB"); + SQLDO("CREATE TABLE IF NOT EXISTS `%1meta`(`keystring` varchar(255) PRIMARY KEY, `value` varchar(255)) " + "ENGINE=InnoDB"); // Query the database structure version the existing database conforms to SQLDO("SELECT `value` FROM `%1meta` WHERE `keystring` = 'version'"); @@ -368,80 +383,122 @@ ServerDB::ServerDB() { SQLDO("CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` DATE)"); SQLDO("CREATE INDEX `%1slog_time` ON `%1slog`(`msgtime`)"); - SQLDO("CREATE TRIGGER `%1slog_timestamp` AFTER INSERT ON `%1slog` FOR EACH ROW BEGIN UPDATE `%1slog` SET `msgtime` = datetime('now') WHERE rowid = new.rowid; END;"); - SQLDO("CREATE TRIGGER `%1slog_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1slog` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1slog_timestamp` AFTER INSERT ON `%1slog` FOR EACH ROW BEGIN UPDATE `%1slog` SET " + "`msgtime` = datetime('now') WHERE rowid = new.rowid; END;"); + SQLDO("CREATE TRIGGER `%1slog_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1slog` WHERE `server_id` = old.`server_id`; END;"); SQLDO("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` TEXT, `value` TEXT)"); SQLDO("CREATE UNIQUE INDEX `%1config_key` ON `%1config`(`server_id`, `key`)"); - SQLDO("CREATE TRIGGER `%1config_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1config` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1config_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1config` WHERE `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` INTEGER, `name` TEXT, `inheritacl` INTEGER)"); + SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` " + "INTEGER, `name` TEXT, `inheritacl` INTEGER)"); SQLDO("CREATE UNIQUE INDEX `%1channel_id` ON `%1channels`(`server_id`, `channel_id`)"); - SQLDO("CREATE TRIGGER `%1channels_parent_del` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channels` WHERE `parent_id` = old.`channel_id` AND `server_id` = old.`server_id`; UPDATE `%1users` SET `lastchannel`=0 WHERE `lastchannel` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TRIGGER `%1channels_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1channels` WHERE `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLDO( + "CREATE TRIGGER `%1channels_parent_del` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM " + "`%1channels` WHERE `parent_id` = old.`channel_id` AND `server_id` = old.`server_id`; UPDATE `%1users` " + "SET `lastchannel`=0 WHERE `lastchannel` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1channels_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1channels` WHERE `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` TEXT)"); SQLDO("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)"); - SQLDO("CREATE TRIGGER `%1channel_info_del_channel` AFTER DELETE on `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channel_info` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + SQLDO( + "CREATE TRIGGER `%1channel_info_del_channel` AFTER DELETE on `%1channels` FOR EACH ROW BEGIN DELETE " + "FROM `%1channel_info` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `pw` TEXT, `salt` TEXT, `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` BLOB, `last_active` DATE, `last_disconnect` DATE)"); + SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` TEXT NOT " + "NULL, `pw` TEXT, `salt` TEXT, `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` BLOB, " + "`last_active` DATE, `last_disconnect` DATE)"); SQLDO("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)"); SQLDO("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)"); - SQLDO("CREATE TRIGGER `%1users_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1users` WHERE `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TRIGGER `%1users_update_timestamp` AFTER UPDATE OF `lastchannel` ON `%1users` FOR EACH ROW BEGIN UPDATE `%1users` SET `last_active` = datetime('now') WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLDO("CREATE TRIGGER `%1users_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1users` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1users_update_timestamp` AFTER UPDATE OF `lastchannel` ON `%1users` FOR EACH ROW " + "BEGIN UPDATE `%1users` SET `last_active` = datetime('now') WHERE `user_id` = old.`user_id` AND " + "`server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` TEXT)"); SQLDO("CREATE UNIQUE INDEX `%1user_info_id` ON `%1user_info`(`server_id`, `user_id`, `key`)"); - SQLDO("CREATE TRIGGER `%1user_info_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM `%1user_info` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1user_info_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM " + "`%1user_info` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTOINCREMENT, `server_id` INTEGER NOT NULL, `name` TEXT, `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); + SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTOINCREMENT, `server_id` INTEGER NOT " + "NULL, `name` TEXT, `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); SQLDO("CREATE UNIQUE INDEX `%1groups_name_channels` ON `%1groups`(`server_id`, `channel_id`, `name`)"); - SQLDO("CREATE TRIGGER `%1groups_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1groups` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `addit` INTEGER)"); - SQLDO("CREATE TRIGGER `%1groups_members_del_group` AFTER DELETE ON `%1groups` FOR EACH ROW BEGIN DELETE FROM `%1group_members` WHERE `group_id` = old.`group_id`; END;"); - SQLDO("CREATE TRIGGER `%1groups_members_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM `%1group_members` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` INTEGER, `user_id` INTEGER, `group_name` TEXT, `apply_here` INTEGER, `apply_sub` INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER)"); + SQLDO("CREATE TRIGGER `%1groups_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM " + "`%1groups` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, " + "`user_id` INTEGER NOT NULL, `addit` INTEGER)"); + SQLDO("CREATE TRIGGER `%1groups_members_del_group` AFTER DELETE ON `%1groups` FOR EACH ROW BEGIN DELETE " + "FROM `%1group_members` WHERE `group_id` = old.`group_id`; END;"); + SQLDO("CREATE TRIGGER `%1groups_members_del_user` AFTER DELETE on `%1users` FOR EACH ROW BEGIN DELETE FROM " + "`%1group_members` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` " + "INTEGER, `user_id` INTEGER, `group_name` TEXT, `apply_here` INTEGER, `apply_sub` INTEGER, " + "`grantpriv` INTEGER, `revokepriv` INTEGER)"); SQLDO("CREATE UNIQUE INDEX `%1acl_channel_pri` ON `%1acl`(`server_id`, `channel_id`, `priority`)"); - SQLDO("CREATE TRIGGER `%1acl_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1acl` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); - SQLDO("CREATE TRIGGER `%1acl_del_user` AFTER DELETE ON `%1users` FOR EACH ROW BEGIN DELETE FROM `%1acl` WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); - - SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `link_id` INTEGER NOT NULL)"); - SQLDO("CREATE TRIGGER `%1channel_links_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channel_links` WHERE `server_id` = old.`server_id` AND (`channel_id` = old.`channel_id` OR `link_id` = old.`channel_id`); END;"); + SQLDO("CREATE TRIGGER `%1acl_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE FROM " + "`%1acl` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TRIGGER `%1acl_del_user` AFTER DELETE ON `%1users` FOR EACH ROW BEGIN DELETE FROM `%1acl` " + "WHERE `user_id` = old.`user_id` AND `server_id` = old.`server_id`; END;"); + + SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`link_id` INTEGER NOT NULL)"); + SQLDO("CREATE TRIGGER `%1channel_links_del_channel` AFTER DELETE ON `%1channels` FOR EACH ROW BEGIN DELETE " + "FROM `%1channel_links` WHERE `server_id` = old.`server_id` AND (`channel_id` = old.`channel_id` OR " + "`link_id` = old.`channel_id`); END;"); SQLDO("DELETE FROM `%1channel_links`"); - SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BLOB, `mask` INTEGER, `name` TEXT, `hash` TEXT, `reason` TEXT, `start` DATE, `duration` INTEGER)"); - SQLDO("CREATE TRIGGER `%1bans_del_server` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1bans` WHERE `server_id` = old.`server_id`; END;"); + SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BLOB, `mask` INTEGER, `name` TEXT, " + "`hash` TEXT, `reason` TEXT, `start` DATE, `duration` INTEGER)"); + SQLDO("CREATE TRIGGER `%1bans_del_server` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM " + "`%1bans` WHERE `server_id` = old.`server_id`; END;"); } else if (Meta::mp.qsDBDriver == "QPSQL") { if (version > 0) { - typedef QPair<QString, QString> qsp; - QList<qsp> qlForeignKeys; - QList<qsp> qlIndexes; + typedef QPair< QString, QString > qsp; + QList< qsp > qlForeignKeys; + QList< qsp > qlIndexes; - SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); + SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE " + "TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); query.addBindValue(Meta::mp.qsDatabase); SQLEXEC(); while (query.next()) qlForeignKeys << qsp(query.value(0).toString(), query.value(1).toString()); - foreach(const qsp &key, qlForeignKeys) { + foreach (const qsp &key, qlForeignKeys) { if (key.first.startsWith(Meta::mp.qsDBPrefix)) - ServerDB::exec(query, QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT FOREIGN KEY `%2`").arg(key.first).arg(key.second), true); + ServerDB::exec(query, + QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT FOREIGN KEY `%2`") + .arg(key.first) + .arg(key.second), + true); } - - SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=? AND CONSTRAINT_TYPE='PRIMARY KEY'"); + + SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE " + "TABLE_SCHEMA=? AND CONSTRAINT_TYPE='PRIMARY KEY'"); query.addBindValue(Meta::mp.qsDatabase); SQLEXEC(); while (query.next()) qlIndexes << qsp(query.value(0).toString(), query.value(1).toString()); - foreach(const qsp &key, qlIndexes) { + foreach (const qsp &key, qlIndexes) { if (key.first.startsWith(Meta::mp.qsDBPrefix)) - ServerDB::exec(query, QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT PRIMARY KEY `%2`").arg(key.first).arg(key.second), true); + ServerDB::exec(query, + QString::fromLatin1("ALTER TABLE `%1` DROP CONSTRAINT PRIMARY KEY `%2`") + .arg(key.first) + .arg(key.second), + true); } - - + + SQLQUERY("DROP INDEX IF EXISTS `%1slog_time` CASCADE"); SQLQUERY("DROP INDEX IF EXISTS `%1config_key` CASCADE"); SQLQUERY("DROP INDEX IF EXISTS `%1channel_id` CASCADE"); @@ -459,122 +516,181 @@ ServerDB::ServerDB() { } SQLQUERY("CREATE TABLE `%1servers`(`server_id` SERIAL PRIMARY KEY)"); - SQLQUERY("CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` TIMESTAMP DEFAULT now())"); + SQLQUERY( + "CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` TIMESTAMP DEFAULT now())"); SQLQUERY("CREATE INDEX `%1slog_time` ON `%1slog`(`msgtime`)"); - SQLQUERY("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); SQLQUERY("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` varchar(255), `value` TEXT)"); SQLQUERY("CREATE UNIQUE INDEX `%1config_key` ON `%1config`(`server_id`, `key`)"); - SQLQUERY("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` INTEGER, `name` varchar(255), `inheritacl` INTEGER)"); + SQLQUERY("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`parent_id` INTEGER, `name` varchar(255), `inheritacl` INTEGER)"); SQLQUERY("CREATE UNIQUE INDEX `%1channel_id` ON `%1channels`(`server_id`, `channel_id`)"); - SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, `parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, " + "`parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) " + "REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLQUERY("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`key` INTEGER, `value` TEXT)"); SQLQUERY("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)"); - SQLQUERY("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY " + "(`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` BYTEA, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP)"); + SQLQUERY("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` " + "varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` " + "INTEGER, `texture` BYTEA, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP)"); SQLQUERY("CREATE INDEX `%1users_channel` ON `%1users`(`server_id`, `lastchannel`)"); SQLQUERY("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)"); SQLQUERY("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)"); - SQLQUERY("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` INTEGER, `value` TEXT)"); + SQLQUERY("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` TEXT)"); SQLQUERY("CREATE UNIQUE INDEX `%1user_info_id` ON `%1user_info`(`server_id`, `user_id`, `key`)"); - SQLQUERY("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, " + "`user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1groups` (`group_id` SERIAL PRIMARY KEY, `server_id` INTEGER NOT NULL, `name` varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); + SQLQUERY("CREATE TABLE `%1groups` (`group_id` SERIAL PRIMARY KEY, `server_id` INTEGER NOT NULL, `name` " + "varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER)"); SQLQUERY("CREATE UNIQUE INDEX `%1groups_name_channels` ON `%1groups`(`server_id`, `channel_id`, `name`)"); - SQLQUERY("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLQUERY("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `addit` INTEGER)"); + SQLQUERY("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, " + "`user_id` INTEGER NOT NULL, `addit` INTEGER)"); SQLQUERY("CREATE INDEX `%1group_members_users` ON `%1group_members`(`server_id`, `user_id`)"); - SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY (`group_id`) REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); - SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - - SQLQUERY("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER)"); + SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY " + "(`group_id`) REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY " + "(`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + + SQLQUERY("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` " + "INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` " + "INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER)"); SQLQUERY("CREATE UNIQUE INDEX `%1acl_channel_pri` ON `%1acl`(`server_id`, `channel_id`, `priority`)"); SQLQUERY("CREATE INDEX `%1acl_user` ON `%1acl`(`server_id`, `user_id`)"); - SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); - - SQLQUERY("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `link_id` INTEGER NOT NULL)"); - SQLQUERY("ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) " + "REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLQUERY("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) " + "REFERENCES `%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); + + SQLQUERY("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`link_id` INTEGER NOT NULL)"); + SQLQUERY( + "ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); SQLQUERY("DELETE FROM `%1channel_links`"); - SQLQUERY("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BYTEA, `mask` INTEGER, `name` varchar(255), `hash` CHAR(40), `reason` TEXT, `start` TIMESTAMP, `duration` INTEGER)"); - SQLQUERY("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLQUERY("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BYTEA, `mask` INTEGER, `name` " + "varchar(255), `hash` CHAR(40), `reason` TEXT, `start` TIMESTAMP, `duration` INTEGER)"); + SQLQUERY("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); } else { // MySQL if (version > 0) { - typedef QPair<QString, QString> qsp; - QList<qsp> qlForeignKeys; - QList<qsp> qlIndexes; + typedef QPair< QString, QString > qsp; + QList< qsp > qlForeignKeys; + QList< qsp > qlIndexes; - SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); + SQLPREP("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE " + "TABLE_SCHEMA=? AND CONSTRAINT_TYPE='FOREIGN KEY'"); query.addBindValue(Meta::mp.qsDatabase); SQLEXEC(); while (query.next()) qlForeignKeys << qsp(query.value(0).toString(), query.value(1).toString()); - foreach(const qsp &key, qlForeignKeys) { + foreach (const qsp &key, qlForeignKeys) { if (key.first.startsWith(Meta::mp.qsDBPrefix)) - ServerDB::exec(query, QString::fromLatin1("ALTER TABLE `%1` DROP FOREIGN KEY `%2`").arg(key.first).arg(key.second), true); + ServerDB::exec(query, + QString::fromLatin1("ALTER TABLE `%1` DROP FOREIGN KEY `%2`") + .arg(key.first) + .arg(key.second), + true); } } SQLDO("CREATE TABLE `%1servers`(`server_id` INTEGER PRIMARY KEY AUTO_INCREMENT) ENGINE=InnoDB"); SQLDO("CREATE TABLE `%1slog`(`server_id` INTEGER NOT NULL, `msg` TEXT, `msgtime` TIMESTAMP) ENGINE=InnoDB"); SQLDO("CREATE INDEX `%1slog_time` ON `%1slog`(`msgtime`)"); - SQLDO("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1slog` ADD CONSTRAINT `%1slog_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` varchar(255), `value` TEXT) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1config` (`server_id` INTEGER NOT NULL, `key` varchar(255), `value` TEXT) " + "ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1config_key` ON `%1config`(`server_id`, `key`)"); - SQLDO("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1config` ADD CONSTRAINT `%1config_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` INTEGER, `name` varchar(255), `inheritacl` INTEGER) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1channels` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `parent_id` " + "INTEGER, `name` varchar(255), `inheritacl` INTEGER) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1channel_id` ON `%1channels`(`server_id`, `channel_id`)"); - SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, `parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_parent_del` FOREIGN KEY (`server_id`, " + "`parent_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1channels` ADD CONSTRAINT `%1channels_server_del` FOREIGN KEY (`server_id`) " + "REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1channel_info` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)"); - SQLDO("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1channel_info` ADD CONSTRAINT `%1channel_info_del_channel` FOREIGN KEY (`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`,`channel_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` LONGBLOB, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` " + "varchar(255), `pw` varchar(128), `salt` varchar(128), `kdfiterations` INTEGER, `lastchannel` " + "INTEGER, `texture` LONGBLOB, `last_active` TIMESTAMP, `last_disconnect` TIMESTAMP) ENGINE=InnoDB"); SQLDO("CREATE INDEX `%1users_channel` ON `%1users`(`server_id`, `lastchannel`)"); SQLDO("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)"); SQLDO("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)"); - SQLDO("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1users` ADD CONSTRAINT `%1users_server_del` FOREIGN KEY (`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1user_info` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `key` " + "INTEGER, `value` LONGTEXT) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1user_info_id` ON `%1user_info`(`server_id`, `user_id`, `key`)"); - SQLDO("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1user_info` ADD CONSTRAINT `%1user_info_del_user` FOREIGN KEY (`server_id`, " + "`user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTO_INCREMENT, `server_id` INTEGER NOT NULL, `name` varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1groups` (`group_id` INTEGER PRIMARY KEY AUTO_INCREMENT, `server_id` INTEGER NOT " + "NULL, `name` varchar(255), `channel_id` INTEGER NOT NULL, `inherit` INTEGER, `inheritable` INTEGER) " + "ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1groups_name_channels` ON `%1groups`(`server_id`, `channel_id`, `name`)"); - SQLDO("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1groups` ADD CONSTRAINT `%1groups_del_channel` FOREIGN KEY (`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `addit` INTEGER) ENGINE=InnoDB"); + SQLDO("CREATE TABLE `%1group_members` (`group_id` INTEGER NOT NULL, `server_id` INTEGER NOT NULL, " + "`user_id` INTEGER NOT NULL, `addit` INTEGER) ENGINE=InnoDB"); SQLDO("CREATE INDEX `%1group_members_users` ON `%1group_members`(`server_id`, `user_id`)"); - SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY (`group_id`) REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); - SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); - - SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` INTEGER, `grantpriv` INTEGER, `revokepriv` INTEGER) ENGINE=InnoDB"); + SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_group` FOREIGN KEY (`group_id`) " + "REFERENCES `%1groups`(`group_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1group_members` ADD CONSTRAINT `%1group_members_del_user` FOREIGN KEY (`server_id`, " + "`user_id`) REFERENCES `%1users`(`server_id`,`user_id`) ON DELETE CASCADE"); + + SQLDO("CREATE TABLE `%1acl` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `priority` " + "INTEGER, `user_id` INTEGER, `group_name` varchar(255), `apply_here` INTEGER, `apply_sub` INTEGER, " + "`grantpriv` INTEGER, `revokepriv` INTEGER) ENGINE=InnoDB"); SQLDO("CREATE UNIQUE INDEX `%1acl_channel_pri` ON `%1acl`(`server_id`, `channel_id`, `priority`)"); SQLDO("CREATE INDEX `%1acl_user` ON `%1acl`(`server_id`, `user_id`)"); - SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); - SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES `%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); - - SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `link_id` INTEGER NOT NULL) ENGINE=InnoDB"); - SQLDO("ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, `channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_channel` FOREIGN KEY (`server_id`, `channel_id`) " + "REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); + SQLDO("ALTER TABLE `%1acl` ADD CONSTRAINT `%1acl_del_user` FOREIGN KEY (`server_id`, `user_id`) REFERENCES " + "`%1users`(`server_id`, `user_id`) ON DELETE CASCADE"); + + SQLDO("CREATE TABLE `%1channel_links` (`server_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, " + "`link_id` INTEGER NOT NULL) ENGINE=InnoDB"); + SQLDO("ALTER TABLE `%1channel_links` ADD CONSTRAINT `%1channel_links_del_channel` FOREIGN KEY(`server_id`, " + "`channel_id`) REFERENCES `%1channels`(`server_id`, `channel_id`) ON DELETE CASCADE"); SQLDO("DELETE FROM `%1channel_links`"); - SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BINARY(16), `mask` INTEGER, `name` varchar(255), `hash` CHAR(40), `reason` TEXT, `start` DATETIME, `duration` INTEGER) ENGINE=InnoDB"); - SQLDO("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES `%1servers`(`server_id`) ON DELETE CASCADE"); + SQLDO("CREATE TABLE `%1bans` (`server_id` INTEGER NOT NULL, `base` BINARY(16), `mask` INTEGER, `name` " + "varchar(255), `hash` CHAR(40), `reason` TEXT, `start` DATETIME, `duration` INTEGER) ENGINE=InnoDB"); + SQLDO("ALTER TABLE `%1bans` ADD CONSTRAINT `%1bans_del_server` FOREIGN KEY(`server_id`) REFERENCES " + "`%1servers`(`server_id`) ON DELETE CASCADE"); } if (version == 0) { @@ -583,63 +699,84 @@ ServerDB::ServerDB() { // server) as well as the version info about the database structure version. SQLDO("INSERT INTO `%1servers` (`server_id`) VALUES(1)"); // Calling this function is the same as using the SQLDO macro - SQLDO_NO_CONVERSION(QLatin1String("INSERT INTO `%1meta` (`keystring`, `value`) ") - + QString::fromLatin1("VALUES('version','%1')").arg(QString::number(DB_STRUCTURE_VERSION))); + SQLDO_NO_CONVERSION( + QLatin1String("INSERT INTO `%1meta` (`keystring`, `value`) ") + + QString::fromLatin1("VALUES('version','%1')").arg(QString::number(DB_STRUCTURE_VERSION))); } else { qWarning("Importing old data..."); if (Meta::mp.qsDBDriver == "QMYSQL") SQLDO("SET FOREIGN_KEY_CHECKS = 0;"); SQLDO("INSERT INTO `%1servers` (`server_id`) SELECT `server_id` FROM `%1servers%2`"); - SQLDO("INSERT INTO `%1slog` (`server_id`, `msg`, `msgtime`) SELECT `server_id`, `msg`, `msgtime` FROM `%1slog%2`"); + SQLDO("INSERT INTO `%1slog` (`server_id`, `msg`, `msgtime`) SELECT `server_id`, `msg`, `msgtime` FROM " + "`%1slog%2`"); if (version < 4) - SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `keystring`, `value` FROM `%1config%2`"); + SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `keystring`, `value` " + "FROM `%1config%2`"); else - SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `key`, `value` FROM `%1config%2`"); + SQLDO("INSERT INTO `%1config` (`server_id`, `key`, `value`) SELECT `server_id`, `key`, `value` FROM " + "`%1config%2`"); - SQLDO("INSERT INTO `%1channels` (`server_id`, `channel_id`, `parent_id`, `name`, `inheritacl`) SELECT `server_id`, `channel_id`, `parent_id`, `name`, `inheritacl` FROM `%1channels%2` ORDER BY `parent_id`, `channel_id`"); + SQLDO("INSERT INTO `%1channels` (`server_id`, `channel_id`, `parent_id`, `name`, `inheritacl`) SELECT " + "`server_id`, `channel_id`, `parent_id`, `name`, `inheritacl` FROM `%1channels%2` ORDER BY " + "`parent_id`, `channel_id`"); if (version < 4) - SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`) SELECT `server_id`, `player_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active` FROM `%1players%2`"); + SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`) SELECT `server_id`, `player_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active` FROM `%1players%2`"); else if (version < 8) - SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active` FROM `%1users%2`"); + SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active` FROM `%1users%2`"); else - SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, `last_active`, `last_disconnect` FROM `%1users%2`"); + SQLDO("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`) SELECT `server_id`, `user_id`, `name`, `pw`, `lastchannel`, `texture`, " + "`last_active`, `last_disconnect` FROM `%1users%2`"); - SQLDO("INSERT INTO `%1groups` (`group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable`) SELECT `group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable` FROM `%1groups%2`"); + SQLDO("INSERT INTO `%1groups` (`group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable`) " + "SELECT `group_id`, `server_id`, `name`, `channel_id`, `inherit`, `inheritable` FROM `%1groups%2`"); if (version < 4) - SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, `server_id`, `player_id`, `addit` FROM `%1group_members%2`"); + SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, " + "`server_id`, `player_id`, `addit` FROM `%1group_members%2`"); else - SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, `server_id`, `user_id`, `addit` FROM `%1group_members%2`"); + SQLDO("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) SELECT `group_id`, " + "`server_id`, `user_id`, `addit` FROM `%1group_members%2`"); if (version < 4) - SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, `priority`, `player_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl%2`"); + SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, " + "`apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, " + "`priority`, `player_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` " + "FROM `%1acl%2`"); else - SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl%2`"); + SQLDO("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, " + "`apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) SELECT `server_id`, `channel_id`, " + "`priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM " + "`%1acl%2`"); - SQLDO("INSERT INTO `%1channel_links` (`server_id`, `channel_id`, `link_id`) SELECT `server_id`, `channel_id`, `link_id` FROM `%1channel_links%2`"); + SQLDO("INSERT INTO `%1channel_links` (`server_id`, `channel_id`, `link_id`) SELECT `server_id`, " + "`channel_id`, `link_id` FROM `%1channel_links%2`"); if (version < 4) { - QList<QList<QVariant> > ql; + QList< QList< QVariant > > ql; SQLPREP("SELECT `server_id`, `base`, `mask` FROM `%1bans%2`"); SQLEXEC(); while (query.next()) { - QList<QVariant> l; + QList< QVariant > l; l << query.value(0); l << query.value(1); l << query.value(2); ql << l; } SQLPREP("INSERT INTO `%1bans` (`server_id`, `base`, `mask`) VALUES (?, ?, ?)"); - foreach(const QList<QVariant> &l, ql) { - - quint32 addr = htonl(l.at(1).toUInt()); - const char *ptr = reinterpret_cast<const char *>(&addr); + foreach (const QList< QVariant > &l, ql) { + quint32 addr = htonl(l.at(1).toUInt()); + const char *ptr = reinterpret_cast< const char * >(&addr); QByteArray qba(16, 0); - qba[10] = static_cast<char>(-1); - qba[11] = static_cast<char>(-1); + qba[10] = static_cast< char >(-1); + qba[11] = static_cast< char >(-1); qba[12] = ptr[0]; qba[13] = ptr[1]; qba[14] = ptr[2]; @@ -651,14 +788,17 @@ ServerDB::ServerDB() { SQLEXEC(); } } else { - SQLDO("INSERT INTO `%1bans` (`server_id`, `base`, `mask`) SELECT `server_id`, `base`, `mask` FROM `%1bans%2`"); + SQLDO("INSERT INTO `%1bans` (`server_id`, `base`, `mask`) SELECT `server_id`, `base`, `mask` FROM " + "`%1bans%2`"); } if (version < 4) - SQLDO("INSERT INTO `%1user_info` SELECT `server_id`,`player_id`,1,`email` FROM `%1players%2` WHERE `email` IS NOT NULL"); + SQLDO("INSERT INTO `%1user_info` SELECT `server_id`,`player_id`,1,`email` FROM `%1players%2` WHERE " + "`email` IS NOT NULL"); if (version == 3) { - SQLDO("INSERT INTO `%1channel_info` SELECT `server_id`,`channel_id`,0,`description` FROM `%1channels%2` WHERE `description` IS NOT NULL"); + SQLDO("INSERT INTO `%1channel_info` SELECT `server_id`,`channel_id`,0,`description` FROM " + "`%1channels%2` WHERE `description` IS NOT NULL"); } if (version >= 4) { @@ -685,7 +825,7 @@ ServerDB::ServerDB() { SQLQUERY("DROP TABLE IF EXISTS `%1servers%2`"); SQLDO_NO_CONVERSION(QLatin1String("UPDATE `%1meta` SET `value` = ") - + QString::fromLatin1("'%1' WHERE `keystring` = 'version'").arg(DB_STRUCTURE_VERSION)); + + QString::fromLatin1("'%1' WHERE `keystring` = 'version'").arg(DB_STRUCTURE_VERSION)); } } query.clear(); @@ -698,7 +838,7 @@ ServerDB::~ServerDB() { } bool ServerDB::prepare(QSqlQuery &query, const QString &str, bool fatal, bool warn) { - if (! db->isValid()) { + if (!db->isValid()) { qWarning("SQL [%s] rejected: Database is gone", qPrintable(str)); return false; } @@ -715,12 +855,12 @@ bool ServerDB::prepare(QSqlQuery &query, const QString &str, bool fatal, bool wa if (Meta::mp.qsDBDriver == "QPSQL") { q.replace("`", "\""); } - + if (query.prepare(q)) { return true; } else { db->close(); - if (! db->open()) { + if (!db->open()) { qFatal("Lost connection to SQL Database: Reconnect: %s", qPrintable(db->lastError().text())); } query = QSqlQuery(); @@ -740,8 +880,8 @@ bool ServerDB::prepare(QSqlQuery &query, const QString &str, bool fatal, bool wa } bool ServerDB::query(QSqlQuery &query, const QString &str, bool fatal, bool warn) { - if (! str.isEmpty()) { - if (! db->isValid()) { + if (!str.isEmpty()) { + if (!db->isValid()) { qWarning("SQL [%s] rejected: Database is gone", qPrintable(str)); return false; } @@ -758,7 +898,7 @@ bool ServerDB::query(QSqlQuery &query, const QString &str, bool fatal, bool warn if (Meta::mp.qsDBDriver == "QPSQL") { q.replace("`", "\""); } - + if (query.exec(q)) { return true; } else { @@ -776,12 +916,11 @@ bool ServerDB::query(QSqlQuery &query, const QString &str, bool fatal, bool warn } bool ServerDB::exec(QSqlQuery &query, const QString &str, bool fatal, bool warn) { - if (! str.isEmpty()) + if (!str.isEmpty()) prepare(query, str, fatal, warn); if (query.exec()) { return true; } else { - if (fatal) { *db = QSqlDatabase(); qFatal("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); @@ -793,12 +932,11 @@ bool ServerDB::exec(QSqlQuery &query, const QString &str, bool fatal, bool warn) } bool ServerDB::execBatch(QSqlQuery &query, const QString &str, bool fatal) { - if (! str.isEmpty()) + if (!str.isEmpty()) prepare(query, str, fatal); if (query.execBatch()) { return true; } else { - if (fatal) { *db = QSqlDatabase(); qFatal("SQL Error [%s]: %s", qPrintable(query.lastQuery()), qPrintable(query.lastError().text())); @@ -816,14 +954,15 @@ void Server::initialize() { SQLPREP("SELECT `channel_id` FROM `%1channels` WHERE `server_id` = ? AND `channel_id` = 0"); query.addBindValue(iServerNum); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { SQLPREP("INSERT INTO `%1channels` (`server_id`, `channel_id`, `parent_id`, `name`) VALUES (?, ?, ?, ?)"); query.addBindValue(iServerNum); query.addBindValue(0); query.addBindValue(QVariant()); query.addBindValue(QLatin1String("Root")); SQLEXEC(); - SQLPREP("UPDATE `%1channels` SET `channel_id` = 0 WHERE `server_id` = ? AND `name` = ? AND `parent_id` IS NULL"); + SQLPREP( + "UPDATE `%1channels` SET `channel_id` = 0 WHERE `server_id` = ? AND `name` = ? AND `parent_id` IS NULL"); query.addBindValue(iServerNum); query.addBindValue(QLatin1String("Root")); SQLEXEC(); @@ -832,7 +971,7 @@ void Server::initialize() { SQLPREP("SELECT `user_id` FROM `%1users` WHERE `server_id` = ? AND `user_id` = 0"); query.addBindValue(iServerNum); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (?, ?, ?)"); query.addBindValue(iServerNum); query.addBindValue(0); @@ -844,7 +983,7 @@ void Server::initialize() { SQLEXEC(); const int passwordLength = 12; - QString pw = PasswordGenerator::generatePassword(passwordLength); + QString pw = PasswordGenerator::generatePassword(passwordLength); ServerDB::setSUPW(iServerNum, pw); log(QString("Password for 'SuperUser' set to '%2'").arg(pw)); } @@ -855,7 +994,8 @@ void Server::initialize() { if (query.next()) { int c = query.value(0).toInt(); if (c == 0) { - SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`) VALUES (?,?,?,?,?,?,?)"); + SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `group_name`, `apply_here`, " + "`apply_sub`, `grantpriv`) VALUES (?,?,?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(0); @@ -863,7 +1003,7 @@ void Server::initialize() { query.addBindValue(QLatin1String("admin")); query.addBindValue(1); query.addBindValue(1); - query.addBindValue(static_cast<int>(ChanACL::Write)); + query.addBindValue(static_cast< int >(ChanACL::Write)); SQLEXEC(); query.addBindValue(iServerNum); @@ -872,7 +1012,7 @@ void Server::initialize() { query.addBindValue(QLatin1String("auth")); query.addBindValue(1); query.addBindValue(1); - query.addBindValue(static_cast<int>(ChanACL::MakeTempChannel)); + query.addBindValue(static_cast< int >(ChanACL::MakeTempChannel)); SQLEXEC(); query.addBindValue(iServerNum); @@ -881,7 +1021,7 @@ void Server::initialize() { query.addBindValue(QLatin1String("all")); query.addBindValue(1); query.addBindValue(0); - query.addBindValue(static_cast<int>(ChanACL::SelfRegister)); + query.addBindValue(static_cast< int >(ChanACL::SelfRegister)); SQLEXEC(); } } @@ -893,7 +1033,8 @@ void Server::initialize() { if (query.next()) { int c = query.value(0).toInt(); if (c == 0) { - SQLPREP("INSERT INTO `%1groups`(`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES (?,?,?,?,?)"); + SQLPREP("INSERT INTO `%1groups`(`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES " + "(?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(0); query.addBindValue(QLatin1String("admin")); @@ -905,13 +1046,13 @@ void Server::initialize() { query.clear(); } -int Server::registerUser(const QMap<int, QString> &info) { +int Server::registerUser(const QMap< int, QString > &info) { const QString &name = info.value(ServerDB::User_Name); if (name.isEmpty()) return -1; - if (! validateUserName(name)) + if (!validateUserName(name)) return -1; if (getUserID(name) >= 0) @@ -933,7 +1074,7 @@ int Server::registerUser(const QMap<int, QString> &info) { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - + if (res < 0) { SQLPREP("SELECT MAX(`user_id`)+1 AS id FROM `%1users` WHERE `server_id`=? AND `user_id` < 1000000000"); @@ -946,7 +1087,9 @@ int Server::registerUser(const QMap<int, QString> &info) { } if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (:server_id,:user_id,:name) ON CONFLICT (`server_id`, `name`) DO UPDATE SET `user_id` = :u_user_id WHERE `%1users`.`server_id` = :u_server_id AND `%1users`.`name` = :u_name"); + SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (:server_id,:user_id,:name) ON " + "CONFLICT (`server_id`, `name`) DO UPDATE SET `user_id` = :u_user_id WHERE `%1users`.`server_id` = " + ":u_server_id AND `%1users`.`name` = :u_name"); query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", id); query.bindValue(":name", name); @@ -962,7 +1105,7 @@ int Server::registerUser(const QMap<int, QString> &info) { SQLEXEC(); } } - + qhUserNameCache.remove(id); setInfo(id, info); @@ -974,7 +1117,7 @@ bool Server::unregisterUserDB(int id) { if (id <= 0) return false; - QMap<int, QString> info = getRegistration(id); + QMap< int, QString > info = getRegistration(id); if (info.isEmpty()) return false; @@ -1004,15 +1147,13 @@ bool Server::unregisterUserDB(int id) { return true; } -QList<UserInfo> Server::getRegisteredUsersEx() { - - QMap<int, QString> rpcUsers; +QList< UserInfo > Server::getRegisteredUsersEx() { + QMap< int, QString > rpcUsers; emit getRegisteredUsersSig(QString(), rpcUsers); - QList<UserInfo> users; - QMap<int, QString>::iterator it = rpcUsers.begin(); - for (; it != rpcUsers.end(); ++it) - { + QList< UserInfo > users; + QMap< int, QString >::iterator it = rpcUsers.begin(); + for (; it != rpcUsers.end(); ++it) { users.insert(it.key(), UserInfo(it.key(), it.value())); } @@ -1025,10 +1166,10 @@ QList<UserInfo> Server::getRegisteredUsersEx() { while (query.next()) { UserInfo userinfo; - userinfo.user_id = query.value(0).toInt(); - userinfo.name = query.value(1).toString(); + userinfo.user_id = query.value(0).toInt(); + userinfo.name = query.value(1).toString(); userinfo.last_channel = query.value(2).toInt(); - userinfo.last_active = QDateTime::fromString(query.value(3).toString(), Qt::ISODate); + userinfo.last_active = QDateTime::fromString(query.value(3).toString(), Qt::ISODate); userinfo.last_active.setTimeSpec(Qt::UTC); users << userinfo; @@ -1037,8 +1178,8 @@ QList<UserInfo> Server::getRegisteredUsersEx() { return users; } -QMap<int, QString > Server::getRegisteredUsers(const QString &filter) { - QMap<int, QString > m; +QMap< int, QString > Server::getRegisteredUsers(const QString &filter) { + QMap< int, QString > m; emit getRegisteredUsersSig(filter, m); @@ -1056,7 +1197,7 @@ QMap<int, QString > Server::getRegisteredUsers(const QString &filter) { SQLEXEC(); while (query.next()) { - int id = query.value(0).toInt(); + int id = query.value(0).toInt(); QString name = query.value(1).toString(); m.insert(id, name); } @@ -1064,7 +1205,7 @@ QMap<int, QString > Server::getRegisteredUsers(const QString &filter) { } bool Server::isUserId(int id) { - QMap<int, QString> info; + QMap< int, QString > info; int res = -2; emit getRegistrationSig(res, id, info); if (res >= 0) @@ -1083,8 +1224,8 @@ bool Server::isUserId(int id) { return false; } -QMap<int, QString> Server::getRegistration(int id) { - QMap<int, QString> info; +QMap< int, QString > Server::getRegistration(int id) { + QMap< int, QString > info; int res = -2; emit getRegistrationSig(res, id, info); if (res >= 0) @@ -1116,7 +1257,8 @@ QMap<int, QString> Server::getRegistration(int id) { /// @return UserID of authenticated user, -1 for authentication failures, -2 for unknown user (fallthrough), /// -3 for authentication failures where the data could (temporarily) not be verified. -int Server::authenticate(QString &name, const QString &password, int sessionId, const QStringList &emails, const QString &certhash, bool bStrongCert, const QList<QSslCertificate> &certs) { +int Server::authenticate(QString &name, const QString &password, int sessionId, const QStringList &emails, + const QString &certhash, bool bStrongCert, const QList< QSslCertificate > &certs) { int res = bForceExternalAuth ? -3 : -2; emit authenticateSig(res, name, sessionId, certs, certhash, bStrongCert, password); @@ -1127,12 +1269,15 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - int lchan=readLastChannel(res); + int lchan = readLastChannel(res); if (lchan < 0) lchan = 0; if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `lastchannel`) VALUES (:server_id,:user_id,:name,:lastchannel) ON CONFLICT (`server_id`, `user_id`) DO UPDATE SET `name` = :u_name, `lastchannel` = :u_lastchannel WHERE `%1users`.`server_id` = :u_server_id AND `%1users`.`user_id` = :u_user_id"); + SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`, `lastchannel`) VALUES " + "(:server_id,:user_id,:name,:lastchannel) ON CONFLICT (`server_id`, `user_id`) DO UPDATE SET " + "`name` = :u_name, `lastchannel` = :u_lastchannel WHERE `%1users`.`server_id` = :u_server_id " + "AND `%1users`.`user_id` = :u_user_id"); query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", res); query.bindValue(":name", name); @@ -1161,33 +1306,34 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - SQLPREP("SELECT `user_id`,`name`,`pw`, `salt`, `kdfiterations` FROM `%1users` WHERE `server_id` = ? AND LOWER(`name`) = LOWER(?)"); + SQLPREP("SELECT `user_id`,`name`,`pw`, `salt`, `kdfiterations` FROM `%1users` WHERE `server_id` = ? AND " + "LOWER(`name`) = LOWER(?)"); query.addBindValue(iServerNum); query.addBindValue(name); SQLEXEC(); if (query.next()) { - const int userId = query.value(0).toInt(); + const int userId = query.value(0).toInt(); const QString storedPasswordHash = query.value(2).toString(); - const QString storedSalt = query.value(3).toString(); - const int storedKdfIterations = query.value(4).toInt(); - res = -1; + const QString storedSalt = query.value(3).toString(); + const int storedKdfIterations = query.value(4).toInt(); + res = -1; if (!storedPasswordHash.isEmpty()) { // A user has password authentication enabled if there is a password hash. - + if (storedKdfIterations <= 0) { // If storedKdfIterations is <=0 this means this is an old-style SHA1 hash // that hasn't been converted yet. Or we are operating in legacy mode. if (ServerDB::getLegacySHA1Hash(password) == storedPasswordHash) { name = query.value(1).toString(); - res = query.value(0).toInt(); - - if (! Meta::mp.legacyPasswordHash) { + res = query.value(0).toInt(); + + if (!Meta::mp.legacyPasswordHash) { // Unless disabled upgrade the user password hash - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Password, password); info.insert(ServerDB::User_KDFIterations, QString::number(Meta::mp.kdfIterations)); - + if (!setInfo(userId, info)) { qWarning("ServerDB: Failed to upgrade user account to PBKDF2 hash, rejecting login."); return -1; @@ -1197,11 +1343,11 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, } else { if (PBKDF2::getHash(storedSalt, password, storedKdfIterations) == storedPasswordHash) { name = query.value(1).toString(); - res = query.value(0).toInt(); - + res = query.value(0).toInt(); + if (Meta::mp.legacyPasswordHash) { // Downgrade the password to the legacy hash - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Password, password); if (!setInfo(userId, info)) { @@ -1210,19 +1356,20 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, } } else if (storedKdfIterations != Meta::mp.kdfIterations) { // User kdfiterations not equal to the global one. Update it. - QMap<int, QString> info; + QMap< int, QString > info; info.insert(ServerDB::User_Password, password); info.insert(ServerDB::User_KDFIterations, QString::number(Meta::mp.kdfIterations)); if (!setInfo(userId, info)) { - qWarning() << "ServerDB: Failed to update user PBKDF2 to new iteration count" << Meta::mp.kdfIterations << ", rejecting login."; + qWarning() << "ServerDB: Failed to update user PBKDF2 to new iteration count" + << Meta::mp.kdfIterations << ", rejecting login."; return -1; } } } } } - + if (userId == 0 && res < 0) { // For SuperUser only password based authentication is allowed. // If we couldn't verify the password don't proceed to cert auth @@ -1241,8 +1388,8 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, if (query.next()) { res = query.value(0).toInt(); } else if (bStrongCert) { - foreach(const QString &email, emails) { - if (! email.isEmpty()) { + foreach (const QString &email, emails) { + if (!email.isEmpty()) { query.addBindValue(iServerNum); query.addBindValue(ServerDB::User_Email); query.addBindValue(email); @@ -1259,16 +1406,19 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, query.addBindValue(iServerNum); query.addBindValue(res); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { res = -1; } else { name = query.value(0).toString(); } } } - if (! certhash.isEmpty() && (res > 0)) { + if (!certhash.isEmpty() && (res > 0)) { if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, :key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND `%1user_info`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, " + ":key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE " + "`%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND " + "`%1user_info`.`key` = :u_key"); query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", res); query.bindValue(":key", ServerDB::User_Hash); @@ -1286,8 +1436,8 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, query.addBindValue(certhash); SQLEXEC(); } - - if (! emails.isEmpty()) { + + if (!emails.isEmpty()) { if (Meta::mp.qsDBDriver == "QPSQL") { query.bindValue(":server_id", iServerNum); query.bindValue(":user_id", res); @@ -1314,10 +1464,10 @@ int Server::authenticate(QString &name, const QString &password, int sessionId, return res; } -bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { +bool Server::setInfo(int id, const QMap< int, QString > &setinfo) { int res = -2; - QMap<int, QString> info = setinfo; + QMap< int, QString > info = setinfo; if (info.contains(ServerDB::User_Name)) { const QString &uname = info.value(ServerDB::User_Name); @@ -1357,7 +1507,7 @@ bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { } } - salt = PBKDF2::getSalt(); + salt = PBKDF2::getSalt(); passwordHash = PBKDF2::getHash(salt, password, kdfIterations); } @@ -1379,8 +1529,8 @@ bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { SQLEXEC(); info.remove(ServerDB::User_Name); } - if (! info.isEmpty()) { - QMap<int, QString>::const_iterator i; + if (!info.isEmpty()) { + QMap< int, QString >::const_iterator i; QVariantList serverids, userids, keys, values; for (i = info.constBegin(); i != info.constEnd(); ++i) { @@ -1390,7 +1540,10 @@ bool Server::setInfo(int id, const QMap<int, QString> &setinfo) { values << i.value(); } if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, :key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND `%1user_info`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1user_info` (`server_id`, `user_id`, `key`, `value`) VALUES (:server_id, :user_id, " + ":key, :value) ON CONFLICT (`server_id`, `user_id`, `key`) DO UPDATE SET `value` = :u_value WHERE " + "`%1user_info`.`server_id` = :u_server_id AND `%1user_info`.`user_id` = :u_user_id AND " + "`%1user_info`.`key` = :u_key"); query.bindValue(":server_id", serverids); query.bindValue(":user_id", userids); query.bindValue(":key", keys); @@ -1423,7 +1576,7 @@ bool Server::setTexture(int id, const QByteArray &texture) { else tex = texture; - foreach(ServerUser *u, qhUsers) { + foreach (ServerUser *u, qhUsers) { if (u->iId == id) hashAssign(u->qbaTexture, u->qbaTextureHash, tex); } @@ -1453,7 +1606,7 @@ void ServerDB::writeSUPW(int srvnum, const QString &pwHash, const QString &saltH query.addBindValue(srvnum); query.addBindValue(0); SQLEXEC(); - if (! query.next()) { + if (!query.next()) { SQLPREP("INSERT INTO `%1users` (`server_id`, `user_id`, `name`) VALUES (?, ?, ?)"); query.addBindValue(srvnum); query.addBindValue(0); @@ -1476,7 +1629,7 @@ void ServerDB::setSUPW(int srvnum, const QString &pw) { if (!Meta::mp.legacyPasswordHash) { saltHash = PBKDF2::getSalt(); - pwHash = PBKDF2::getHash(saltHash, pw, Meta::mp.kdfIterations); + pwHash = PBKDF2::getHash(saltHash, pw, Meta::mp.kdfIterations); } else { pwHash = getLegacySHA1Hash(pw); } @@ -1485,7 +1638,7 @@ void ServerDB::setSUPW(int srvnum, const QString &pw) { } void ServerDB::disableSU(int srvnum) { - writeSUPW(srvnum, QString(), QString(), QVariant()); // nullptr, nullptr, nullptr + writeSUPW(srvnum, QString(), QString(), QVariant()); // nullptr, nullptr, nullptr } QString ServerDB::getLegacySHA1Hash(const QString &password) { @@ -1498,7 +1651,7 @@ QString Server::getUserName(int id) { return qhUserNameCache.value(id); QString name; emit idToNameSig(name, id); - if (! name.isEmpty()) { + if (!name.isEmpty()) { qhUserIDCache.insert(name, id); qhUserNameCache.insert(id, name); return name; @@ -1551,7 +1704,7 @@ int Server::getUserID(const QString &name) { QByteArray Server::getUserTexture(int id) { QByteArray qba; emit idToTextureSig(qba, id); - if (! qba.isNull()) { + if (!qba.isNull()) { return qba; } @@ -1564,7 +1717,7 @@ QByteArray Server::getUserTexture(int id) { SQLEXEC(); if (query.next()) { qba = query.value(0).toByteArray(); - if (! qba.isEmpty()) + if (!qba.isEmpty()) if (qba.size() == 600 * 60 * 4) qba = qCompress(qba); } @@ -1634,7 +1787,7 @@ Channel *Server::addChannel(Channel *p, const QString &name, bool temporary, int while (qhChannels.contains(id)) ++id; - if (! temporary) { + if (!temporary) { SQLPREP("INSERT INTO `%1channels` (`server_id`, `parent_id`, `channel_id`, `name`) VALUES (?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(p->iId); @@ -1664,16 +1817,16 @@ Channel *Server::addChannel(Channel *p, const QString &name, bool temporary, int SQLEXEC(); } - Channel *c = new Channel(id, name, p); + Channel *c = new Channel(id, name, p); c->bTemporary = temporary; - c->iPosition = position; + c->iPosition = position; c->uiMaxUsers = maxUsers; qhChannels.insert(id, c); return c; } void Server::removeChannelDB(const Channel *c) { - if (! c->bTemporary) { + if (!c->bTemporary) { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; @@ -1693,7 +1846,8 @@ void Server::updateChannel(const Channel *c) { ChanACL *acl; QSqlQuery &query = *th.qsqQuery; - SQLPREP("UPDATE `%1channels` SET `name` = ?, `parent_id` = ?, `inheritacl` = ? WHERE `server_id` = ? AND `channel_id` = ?"); + SQLPREP("UPDATE `%1channels` SET `name` = ?, `parent_id` = ?, `inheritacl` = ? WHERE `server_id` = ? AND " + "`channel_id` = ?"); query.addBindValue(c->qsName); query.addBindValue(c->cParent ? c->cParent->iId : QVariant()); query.addBindValue(c->bInheritACL ? 1 : 0); @@ -1703,7 +1857,10 @@ void Server::updateChannel(const Channel *c) { // Update channel description information if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1channel_info` (`server_id`, `channel_id`, `key`, `value`) VALUES (:server_id, :channel_id, :key, :value) ON CONFLICT (`server_id`, `channel_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1channel_info`.`server_id` = :u_server_id AND `%1channel_info`.`channel_id` = :u_channel_id AND `%1channel_info`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1channel_info` (`server_id`, `channel_id`, `key`, `value`) VALUES (:server_id, " + ":channel_id, :key, :value) ON CONFLICT (`server_id`, `channel_id`, `key`) DO UPDATE SET `value` = " + ":u_value WHERE `%1channel_info`.`server_id` = :u_server_id AND `%1channel_info`.`channel_id` = " + ":u_channel_id AND `%1channel_info`.`key` = :u_key"); query.bindValue(":server_id", iServerNum); query.bindValue(":channel_id", c->iId); query.bindValue(":key", ServerDB::Channel_Description); @@ -1768,37 +1925,40 @@ void Server::updateChannel(const Channel *c) { query.addBindValue(c->iId); SQLEXEC(); - foreach(g, c->qhGroups) { + foreach (g, c->qhGroups) { int id = 0; int pid; - + if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES (?,?,?,?,?) RETURNING group_id"); + SQLPREP("INSERT INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES " + "(?,?,?,?,?) RETURNING group_id"); query.addBindValue(iServerNum); query.addBindValue(g->c->iId); query.addBindValue(g->qsName); query.addBindValue(g->bInherit ? 1 : 0); query.addBindValue(g->bInheritable ? 1 : 0); SQLEXEC(); - + if (query.next()) { id = query.value(0).toInt(); } else { - qFatal("ServerDB: internal query failure: PostgreSQL query did not return the inserted group's group_id"); + qFatal( + "ServerDB: internal query failure: PostgreSQL query did not return the inserted group's group_id"); } } else { - SQLPREP("REPLACE INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES (?,?,?,?,?)"); + SQLPREP("REPLACE INTO `%1groups` (`server_id`, `channel_id`, `name`, `inherit`, `inheritable`) VALUES " + "(?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(g->c->iId); query.addBindValue(g->qsName); query.addBindValue(g->bInherit ? 1 : 0); query.addBindValue(g->bInheritable ? 1 : 0); SQLEXEC(); - + id = query.lastInsertId().toInt(); } - foreach(pid, g->qsAdd) { + foreach (pid, g->qsAdd) { SQLPREP("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) VALUES (?, ?, ?, ?)"); query.addBindValue(id); query.addBindValue(iServerNum); @@ -1806,7 +1966,7 @@ void Server::updateChannel(const Channel *c) { query.addBindValue(1); SQLEXEC(); } - foreach(pid, g->qsRemove) { + foreach (pid, g->qsRemove) { SQLPREP("INSERT INTO `%1group_members` (`group_id`, `server_id`, `user_id`, `addit`) VALUES (?, ?, ?, ?)"); query.addBindValue(id); query.addBindValue(iServerNum); @@ -1818,8 +1978,9 @@ void Server::updateChannel(const Channel *c) { int pri = 5; - foreach(acl, c->qlACL) { - SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv`) VALUES (?,?,?,?,?,?,?,?,?)"); + foreach (acl, c->qlACL) { + SQLPREP("INSERT INTO `%1acl` (`server_id`, `channel_id`, `priority`, `user_id`, `group_name`, `apply_here`, " + "`apply_sub`, `grantpriv`, `revokepriv`) VALUES (?,?,?,?,?,?,?,?,?)"); query.addBindValue(iServerNum); query.addBindValue(acl->c->iId); query.addBindValue(pri++); @@ -1828,8 +1989,8 @@ void Server::updateChannel(const Channel *c) { query.addBindValue((acl->qsGroup.isEmpty()) ? QVariant() : acl->qsGroup); query.addBindValue(acl->bApplyHere ? 1 : 0); query.addBindValue(acl->bApplySubs ? 1 : 0); - query.addBindValue(static_cast<int>(acl->pAllow)); - query.addBindValue(static_cast<int>(acl->pDeny)); + query.addBindValue(static_cast< int >(acl->pAllow)); + query.addBindValue(static_cast< int >(acl->pDeny)); SQLEXEC(); } } @@ -1849,7 +2010,7 @@ void Server::readChannelPrivs(Channel *c) { query.addBindValue(cid); SQLEXEC(); while (query.next()) { - int key = query.value(0).toInt(); + int key = query.value(0).toInt(); const QString &value = query.value(1).toString(); if (key == ServerDB::Channel_Description) { hashAssign(c->qsDesc, c->qbaDescHash, value); @@ -1860,19 +2021,21 @@ void Server::readChannelPrivs(Channel *c) { } } - SQLPREP("SELECT `group_id`, `name`, `inherit`, `inheritable` FROM `%1groups` WHERE `server_id` = ? AND `channel_id` = ?"); + SQLPREP("SELECT `group_id`, `name`, `inherit`, `inheritable` FROM `%1groups` WHERE `server_id` = ? AND " + "`channel_id` = ?"); query.addBindValue(iServerNum); query.addBindValue(cid); SQLEXEC(); while (query.next()) { - int gid = query.value(0).toInt(); - QString name = query.value(1).toString(); - Group *g = new Group(c, name); - g->bInherit = query.value(2).toBool(); + int gid = query.value(0).toInt(); + QString name = query.value(1).toString(); + Group *g = new Group(c, name); + g->bInherit = query.value(2).toBool(); g->bInheritable = query.value(3).toBool(); QSqlQuery mem; - mem.prepare(QString::fromLatin1("SELECT user_id, addit FROM %1group_members WHERE group_id = ?").arg(Meta::mp.qsDBPrefix)); + mem.prepare(QString::fromLatin1("SELECT user_id, addit FROM %1group_members WHERE group_id = ?") + .arg(Meta::mp.qsDBPrefix)); mem.addBindValue(gid); mem.exec(); while (mem.next()) { @@ -1884,23 +2047,24 @@ void Server::readChannelPrivs(Channel *c) { } } - SQLPREP("SELECT `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl` WHERE `server_id` = ? AND `channel_id` = ? ORDER BY `priority`"); + SQLPREP("SELECT `user_id`, `group_name`, `apply_here`, `apply_sub`, `grantpriv`, `revokepriv` FROM `%1acl` WHERE " + "`server_id` = ? AND `channel_id` = ? ORDER BY `priority`"); query.addBindValue(iServerNum); query.addBindValue(cid); SQLEXEC(); while (query.next()) { - ChanACL *acl = new ChanACL(c); - acl->iUserId = query.value(0).isNull() ? -1 : query.value(0).toInt(); - acl->qsGroup = query.value(1).toString(); + ChanACL *acl = new ChanACL(c); + acl->iUserId = query.value(0).isNull() ? -1 : query.value(0).toInt(); + acl->qsGroup = query.value(1).toString(); acl->bApplyHere = query.value(2).toBool(); acl->bApplySubs = query.value(3).toBool(); - acl->pAllow = static_cast<ChanACL::Permissions>(query.value(4).toInt()); - acl->pDeny = static_cast<ChanACL::Permissions>(query.value(5).toInt()); + acl->pAllow = static_cast< ChanACL::Permissions >(query.value(4).toInt()); + acl->pDeny = static_cast< ChanACL::Permissions >(query.value(5).toInt()); } } void Server::readChannels(Channel *p) { - QList<Channel *> kids; + QList< Channel * > kids; Channel *c; QSqlQuery query; int parentid = -1; @@ -1913,10 +2077,12 @@ void Server::readChannels(Channel *p) { { TransactionHolder th; if (parentid == -1) { - SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND `parent_id` IS NULL ORDER BY `name`"); + SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND `parent_id` " + "IS NULL ORDER BY `name`"); query.addBindValue(iServerNum); } else { - SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND `parent_id`=? ORDER BY `name`"); + SQLPREP("SELECT `channel_id`, `name`, `inheritacl` FROM `%1channels` WHERE `server_id` = ? AND " + "`parent_id`=? ORDER BY `name`"); query.addBindValue(iServerNum); query.addBindValue(parentid); } @@ -1924,7 +2090,7 @@ void Server::readChannels(Channel *p) { while (query.next()) { c = new Channel(query.value(0).toInt(), query.value(1).toString(), p); - if (! p) + if (!p) c->setParent(this); qhChannels.insert(c->iId, c); c->bInheritACL = query.value(2).toBool(); @@ -1934,7 +2100,7 @@ void Server::readChannels(Channel *p) { query.clear(); - foreach(c, kids) + foreach (c, kids) readChannels(c); } @@ -2003,7 +2169,7 @@ int Server::readLastChannel(int id) { QDateTime last_disconnect = QDateTime::fromString(query.value(1).toString(), Qt::ISODate); last_disconnect.setTimeSpec(Qt::UTC); QDateTime now = QDateTime::currentDateTime(); - now = now.toTimeSpec(Qt::UTC); + now = now.toTimeSpec(Qt::UTC); int duration = Meta::mp.iRememberChanDuration; if (duration <= 0 || last_disconnect.secsTo(now) <= duration) { @@ -2044,23 +2210,22 @@ void Server::dumpChannel(const Channel *c) { qWarning("Channel %s (ACLInherit %d)", qPrintable(c->qsName), c->bInheritACL); qWarning("Description: %s", qPrintable(c->qsDesc)); - foreach(g, c->qhGroups) { + foreach (g, c->qhGroups) { qWarning("Group %s (Inh %d Able %d)", qPrintable(g->qsName), g->bInherit, g->bInheritable); - foreach(pid, g->qsAdd) + foreach (pid, g->qsAdd) qWarning("Add %d", pid); - foreach(pid, g->qsRemove) + foreach (pid, g->qsRemove) qWarning("Remove %d", pid); } - foreach(acl, c->qlACL) { - int allow = static_cast<int>(acl->pAllow); - int deny = static_cast<int>(acl->pDeny); - qWarning("ChanACL Here %d Sub %d Allow %04x Deny %04x ID %d Group %s", acl->bApplyHere, acl->bApplySubs, allow, deny, acl->iUserId, qPrintable(acl->qsGroup)); + foreach (acl, c->qlACL) { + int allow = static_cast< int >(acl->pAllow); + int deny = static_cast< int >(acl->pDeny); + qWarning("ChanACL Here %d Sub %d Allow %04x Deny %04x ID %d Group %s", acl->bApplyHere, acl->bApplySubs, allow, + deny, acl->iUserId, qPrintable(acl->qsGroup)); } qWarning(" "); - foreach(c, c->qlChannels) { - dumpChannel(c); - } + foreach (c, c->qlChannels) { dumpChannel(c); } } void Server::getBans() { @@ -2073,15 +2238,14 @@ void Server::getBans() { query.addBindValue(iServerNum); SQLEXEC(); while (query.next()) { - Ban ban; ban.haAddress = query.value(0).toByteArray(); - ban.iMask = query.value(1).toInt(); + ban.iMask = query.value(1).toInt(); ban.qsUsername = query.value(2).toString(); - ban.qsHash = query.value(3).toString(); - ban.qsReason = query.value(4).toString(); - ban.qdtStart = query.value(5).toDateTime(); + ban.qsHash = query.value(3).toString(); + ban.qsReason = query.value(4).toString(); + ban.qdtStart = query.value(5).toDateTime(); ban.qdtStart.setTimeSpec(Qt::UTC); ban.iDuration = query.value(6).toInt(); @@ -2098,8 +2262,9 @@ void Server::saveBans() { query.addBindValue(iServerNum); SQLEXEC(); - SQLPREP("INSERT INTO `%1bans` (`server_id`, `base`,`mask`,`name`,`hash`,`reason`,`start`,`duration`) VALUES (?,?,?,?,?,?,?,?)"); - foreach(const Ban &ban, qlBans) { + SQLPREP("INSERT INTO `%1bans` (`server_id`, `base`,`mask`,`name`,`hash`,`reason`,`start`,`duration`) VALUES " + "(?,?,?,?,?,?,?,?)"); + foreach (const Ban &ban, qlBans) { query.addBindValue(iServerNum); query.addBindValue(ban.haAddress.toByteArray()); query.addBindValue(ban.iMask); @@ -2130,10 +2295,10 @@ QVariant ServerDB::getConf(int server_id, const QString &key, QVariant def) { return def; } -QMap<QString, QString> ServerDB::getAllConf(int server_id) { +QMap< QString, QString > ServerDB::getAllConf(int server_id) { TransactionHolder th; - QMap<QString, QString> map; + QMap< QString, QString > map; QSqlQuery &query = *th.qsqQuery; SQLPREP("SELECT `key`, `value` FROM `%1config` WHERE `server_id` = ?"); @@ -2186,10 +2351,10 @@ void ServerDB::wipeLogs() { SQLDO("DELETE FROM %1slog"); } -QList<QPair<unsigned int, QString> > ServerDB::getLog(int server_id, unsigned int offs_min, unsigned int offs_max) { +QList< QPair< unsigned int, QString > > ServerDB::getLog(int server_id, unsigned int offs_min, unsigned int offs_max) { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - + if (Meta::mp.qsDBDriver == "QPSQL") { SQLPREP("SELECT `msgtime`, `msg` FROM `%1slog` WHERE `server_id` = ? ORDER BY `msgtime` DESC LIMIT ? OFFSET ?"); query.addBindValue(server_id); @@ -2204,11 +2369,11 @@ QList<QPair<unsigned int, QString> > ServerDB::getLog(int server_id, unsigned in SQLEXEC(); } - QList<QPair<unsigned int, QString> > ql; + QList< QPair< unsigned int, QString > > ql; while (query.next()) { QDateTime qdt = query.value(0).toDateTime(); - QString msg = query.value(1).toString(); - ql << QPair<unsigned int, QString>(qdt.toLocalTime().toTime_t(), msg); + QString msg = query.value(1).toString(); + ql << QPair< unsigned int, QString >(qdt.toLocalTime().toTime_t(), msg); } return ql; } @@ -2240,7 +2405,9 @@ void ServerDB::setConf(int server_id, const QString &k, const QVariant &value) { query.addBindValue(key); } else { if (Meta::mp.qsDBDriver == "QPSQL") { - SQLPREP("INSERT INTO `%1config` (`server_id`, `key`, `value`) VALUES (:server_id, :key, :value) ON CONFLICT (`server_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1config`.`server_id` = :u_server_id AND `%1config`.`key` = :u_key"); + SQLPREP("INSERT INTO `%1config` (`server_id`, `key`, `value`) VALUES (:server_id, :key, :value) ON " + "CONFLICT (`server_id`, `key`) DO UPDATE SET `value` = :u_value WHERE `%1config`.`server_id` = " + ":u_server_id AND `%1config`.`key` = :u_key"); query.bindValue(":server_id", server_id); query.bindValue(":key", key); query.bindValue(":value", value.toString()); @@ -2258,31 +2425,31 @@ void ServerDB::setConf(int server_id, const QString &k, const QVariant &value) { } -QList<int> ServerDB::getAllServers() { +QList< int > ServerDB::getAllServers() { TransactionHolder th; QSqlQuery &query = *th.qsqQuery; SQLPREP("SELECT `server_id` FROM `%1servers`"); SQLEXEC(); - QList<int> ql; + QList< int > ql; while (query.next()) ql << query.value(0).toInt(); return ql; } -QList<int> ServerDB::getBootServers() { - QList<int> ql = getAllServers(); +QList< int > ServerDB::getBootServers() { + QList< int > ql = getAllServers(); TransactionHolder th; QSqlQuery &query = *th.qsqQuery; - QList<int> bootlist; - foreach(int i, ql) { + QList< int > bootlist; + foreach (int i, ql) { SQLPREP("SELECT `value` FROM `%1config` WHERE `server_id` = ? AND `key` = ?"); query.addBindValue(i); query.addBindValue(QLatin1String("boot")); SQLEXEC(); - if (! query.next() || query.value(0).toBool()) + if (!query.next() || query.value(0).toBool()) bootlist << i; } return bootlist; diff --git a/src/murmur/ServerDB.h b/src/murmur/ServerDB.h index 4c7df0038..2b05b0324 100644 --- a/src/murmur/ServerDB.h +++ b/src/murmur/ServerDB.h @@ -19,51 +19,59 @@ class QSqlQuery; class ServerDB : public QObject { Q_OBJECT; - public: - /// A version number that allows us to keep track of changes we make to the DB architecture - /// in order to provide backwards compatibility and perform automatic updates of older DBs. - /// Whenever you change the DB structure (add a new table, added a new column in a table, etc.) - /// you have to increase this version number by one and add the respective "backwards compatibility - /// code" into the ServerDB code. - static const int DB_STRUCTURE_VERSION = 8; - enum ChannelInfo { Channel_Description, Channel_Position, Channel_Max_Users }; - enum UserInfo { User_Name, User_Email, User_Comment, User_Hash, User_Password, User_LastActive, User_KDFIterations }; - ServerDB(); - ~ServerDB(); - typedef QPair<unsigned int, QString> LogRecord; - static Timer tLogClean; - static QSqlDatabase *db; - static QString qsUpgradeSuffix; - static void setSUPW(int iServNum, const QString &pw); - static void disableSU(int srvnum); - static QList<int> getBootServers(); - static QList<int> getAllServers(); - static int addServer(); - static void deleteServer(int server_id); - static bool serverExists(int num); - static QMap<QString, QString> getAllConf(int server_id); - static QVariant getConf(int server_id, const QString &key, QVariant def = QVariant()); - static void setConf(int server_id, const QString &key, const QVariant &value = QVariant()); - static QList<LogRecord> getLog(int server_id, unsigned int offs_min, unsigned int offs_max); - static QString getLegacySHA1Hash(const QString &password); - static int getLogLen(int server_id); - static void wipeLogs(); - static bool prepare(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); - static bool query(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); - static bool exec(QSqlQuery &, const QString &str = QString(), bool fatal= true, bool warn = true); - static bool execBatch(QSqlQuery &, const QString &str = QString(), bool fatal= true); - // No copy; private declaration without implementation - ServerDB(const ServerDB &); - - private: - static void loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query); - static void writeSUPW(int srvnum, const QString &pwHash, const QString &saltHash, const QVariant &kdfIterations); +public: + /// A version number that allows us to keep track of changes we make to the DB architecture + /// in order to provide backwards compatibility and perform automatic updates of older DBs. + /// Whenever you change the DB structure (add a new table, added a new column in a table, etc.) + /// you have to increase this version number by one and add the respective "backwards compatibility + /// code" into the ServerDB code. + static const int DB_STRUCTURE_VERSION = 8; - public slots: - /// Clear last_disconnect date of every user of the server - void clearLastDisconnect(Server *); + enum ChannelInfo { Channel_Description, Channel_Position, Channel_Max_Users }; + enum UserInfo { + User_Name, + User_Email, + User_Comment, + User_Hash, + User_Password, + User_LastActive, + User_KDFIterations + }; + ServerDB(); + ~ServerDB(); + typedef QPair< unsigned int, QString > LogRecord; + static Timer tLogClean; + static QSqlDatabase *db; + static QString qsUpgradeSuffix; + static void setSUPW(int iServNum, const QString &pw); + static void disableSU(int srvnum); + static QList< int > getBootServers(); + static QList< int > getAllServers(); + static int addServer(); + static void deleteServer(int server_id); + static bool serverExists(int num); + static QMap< QString, QString > getAllConf(int server_id); + static QVariant getConf(int server_id, const QString &key, QVariant def = QVariant()); + static void setConf(int server_id, const QString &key, const QVariant &value = QVariant()); + static QList< LogRecord > getLog(int server_id, unsigned int offs_min, unsigned int offs_max); + static QString getLegacySHA1Hash(const QString &password); + static int getLogLen(int server_id); + static void wipeLogs(); + static bool prepare(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); + static bool query(QSqlQuery &, const QString &, bool fatal = true, bool warn = true); + static bool exec(QSqlQuery &, const QString &str = QString(), bool fatal = true, bool warn = true); + static bool execBatch(QSqlQuery &, const QString &str = QString(), bool fatal = true); + // No copy; private declaration without implementation + ServerDB(const ServerDB &); +private: + static void loadOrSetupMetaPBKDF2IterationCount(QSqlQuery &query); + static void writeSUPW(int srvnum, const QString &pwHash, const QString &saltHash, const QVariant &kdfIterations); + +public slots: + /// Clear last_disconnect date of every user of the server + void clearLastDisconnect(Server *); }; #endif diff --git a/src/murmur/ServerUser.cpp b/src/murmur/ServerUser.cpp index d55845166..42a9782d2 100644 --- a/src/murmur/ServerUser.cpp +++ b/src/murmur/ServerUser.cpp @@ -9,11 +9,12 @@ #include "Server.h" #ifdef Q_OS_UNIX -# include "Utils.h" +# include "Utils.h" #endif -ServerUser::ServerUser(Server *p, QSslSocket *socket) : Connection(p, socket), User(), s(nullptr), leakyBucket(p->iMessageLimit, p->iMessageBurst) { - sState = ServerUser::Connected; +ServerUser::ServerUser(Server *p, QSslSocket *socket) + : Connection(p, socket), User(), s(nullptr), leakyBucket(p->iMessageLimit, p->iMessageBurst) { + sState = ServerUser::Connected; sUdpSocket = INVALID_SOCKET; memset(&saiUdpAddress, 0, sizeof(saiUdpAddress)); @@ -23,11 +24,11 @@ ServerUser::ServerUser(Server *p, QSslSocket *socket) : Connection(p, socket), U dTCPPingAvg = dTCPPingVar = 0.0f; uiUDPPackets = uiTCPPackets = 0; - aiUdpFlag = 1; - uiVersion = 0; - bVerified = true; + aiUdpFlag = 1; + uiVersion = 0; + bVerified = true; iLastPermissionCheck = -1; - + bOpus = false; } @@ -37,8 +38,8 @@ ServerUser::operator QString() const { } BandwidthRecord::BandwidthRecord() { iRecNum = 0; - iSum = 0; - for (int i=0;i<N_BANDWIDTH_SLOTS;i++) + iSum = 0; + for (int i = 0; i < N_BANDWIDTH_SLOTS; i++) a_iBW[i] = 0; } @@ -50,13 +51,13 @@ bool BandwidthRecord::addFrame(int size, int maxpersec) { if (elapsed == 0) return false; - int nsum = iSum-a_iBW[iRecNum]+size; - int bw = static_cast<int>((nsum * 1000000LL) / elapsed); + int nsum = iSum - a_iBW[iRecNum] + size; + int bw = static_cast< int >((nsum * 1000000LL) / elapsed); if (bw > maxpersec) return false; - a_iBW[iRecNum] = static_cast<unsigned short>(size); + a_iBW[iRecNum] = static_cast< unsigned short >(size); a_qtWhen[iRecNum].restart(); iSum = nsum; @@ -71,7 +72,7 @@ bool BandwidthRecord::addFrame(int size, int maxpersec) { int BandwidthRecord::onlineSeconds() const { QMutexLocker ml(&qmMutex); - return static_cast<int>(tFirst.elapsed() / 1000000LL); + return static_cast< int >(tFirst.elapsed() / 1000000LL); } int BandwidthRecord::idleSeconds() const { @@ -81,7 +82,7 @@ int BandwidthRecord::idleSeconds() const { if (tIdleControl.elapsed() < iIdle) iIdle = tIdleControl.elapsed(); - return static_cast<int>(iIdle / 1000000LL); + return static_cast< int >(iIdle / 1000000LL); } void BandwidthRecord::resetIdleSeconds() { @@ -93,11 +94,11 @@ void BandwidthRecord::resetIdleSeconds() { int BandwidthRecord::bandwidth() const { QMutexLocker ml(&qmMutex); - int sum = 0; + int sum = 0; quint64 elapsed = 0ULL; - for (int i=1;i<N_BANDWIDTH_SLOTS;++i) { - int idx = (iRecNum + N_BANDWIDTH_SLOTS - i) % N_BANDWIDTH_SLOTS; + for (int i = 1; i < N_BANDWIDTH_SLOTS; ++i) { + int idx = (iRecNum + N_BANDWIDTH_SLOTS - i) % N_BANDWIDTH_SLOTS; quint64 e = a_qtWhen[idx].elapsed(); if (e > 1000000ULL) { break; @@ -110,21 +111,18 @@ int BandwidthRecord::bandwidth() const { if (elapsed < 250000ULL) return 0; - return static_cast<int>((sum * 1000000ULL) / elapsed); + return static_cast< int >((sum * 1000000ULL) / elapsed); } LeakyBucket::LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens) - : m_tokensPerSec(tokensPerSec), - m_maxTokens(maxTokens), - m_currentTokens(0), - m_timer() { - m_timer.start(); - - if (!QElapsedTimer::isMonotonic()) { - qFatal("Non-monotonic clocks are not reliable enough and lead to issues as " - "https://github.com/mumble-voip/mumble/issues/3985. " - "This is a serious issue and should be reported!"); - } + : m_tokensPerSec(tokensPerSec), m_maxTokens(maxTokens), m_currentTokens(0), m_timer() { + m_timer.start(); + + if (!QElapsedTimer::isMonotonic()) { + qFatal("Non-monotonic clocks are not reliable enough and lead to issues as " + "https://github.com/mumble-voip/mumble/issues/3985. " + "This is a serious issue and should be reported!"); + } } bool LeakyBucket::ratelimit(int tokens) { @@ -172,7 +170,7 @@ bool LeakyBucket::ratelimit(int tokens) { } // Make sure that m_currentTokens never gets less than 0 by draining - if (static_cast<qint64>(m_currentTokens) < drainTokens) { + if (static_cast< qint64 >(m_currentTokens) < drainTokens) { m_currentTokens = 0; } else { m_currentTokens -= drainTokens; @@ -182,7 +180,7 @@ bool LeakyBucket::ratelimit(int tokens) { // the imaginary leaking bucket, we can check whether the given amount of tokens // still fit in this imaginary bucket (and thus the corresponding message may pass) // or if it doesn't (and thus the message will be limited (rejected)) - bool limit = m_currentTokens > ((static_cast<long>(m_maxTokens)) - tokens); + bool limit = m_currentTokens > ((static_cast< long >(m_maxTokens)) - tokens); // If the bucket is not overflowed, allow message and add tokens if (!limit) { diff --git a/src/murmur/ServerUser.h b/src/murmur/ServerUser.h index e89eaea62..c5ab6dda1 100644 --- a/src/murmur/ServerUser.h +++ b/src/murmur/ServerUser.h @@ -9,21 +9,21 @@ #include <QtCore/QtGlobal> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "Connection.h" +#include "HostAddress.h" #include "Timer.h" #include "User.h" -#include "HostAddress.h" -#include <QtCore/QStringList> #include <QtCore/QElapsedTimer> +#include <QtCore/QStringList> #ifdef Q_OS_WIN -# include <winsock2.h> +# include <winsock2.h> #else -# include <sys/socket.h> +# include <sys/socket.h> #endif // Unfortunately, this needs to be "large enough" to hold @@ -56,16 +56,16 @@ struct WhisperTarget { bool bLinks; QString qsGroup; }; - QList<unsigned int> qlSessions; - QList<WhisperTarget::Channel> qlChannels; + QList< unsigned int > qlSessions; + QList< WhisperTarget::Channel > qlChannels; }; class ServerUser; struct WhisperTargetCache { - QSet<ServerUser *> channelTargets; - QSet<ServerUser *> directTargets; - QSet<ServerUser *> listeningTargets; + QSet< ServerUser * > channelTargets; + QSet< ServerUser * > directTargets; + QSet< ServerUser * > listeningTargets; }; class Server; @@ -73,91 +73,92 @@ class Server; /// A simple implementation for rate-limiting. /// See https://en.wikipedia.org/wiki/Leaky_bucket class LeakyBucket { - private: - /// The amount of tokens that are drained per second. - /// (The sze of the whole in the bucket) - unsigned int m_tokensPerSec; - /// The maximum amount of tokens that may be encountered. - /// (The capacity of the bucket) - unsigned int m_maxTokens; - /// The amount of tokens currently stored - /// (The amount of whater currently in the bucket) - long m_currentTokens; - /// A timer that is used to measure time intervals. It is essential - /// that this timer uses a monotonic clock (which is why QElapsedTimer is - /// used instead of QTime or QDateTime). - QElapsedTimer m_timer; - - public: - /// @param tokens The amount of tokens that should be added. - /// @returns Whether adding this amount of tokens triggers rate - /// limiting (true means the corresponding packet has to be - /// discared and false means the packet may be processed) - bool ratelimit(int tokens); - - LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens); +private: + /// The amount of tokens that are drained per second. + /// (The sze of the whole in the bucket) + unsigned int m_tokensPerSec; + /// The maximum amount of tokens that may be encountered. + /// (The capacity of the bucket) + unsigned int m_maxTokens; + /// The amount of tokens currently stored + /// (The amount of whater currently in the bucket) + long m_currentTokens; + /// A timer that is used to measure time intervals. It is essential + /// that this timer uses a monotonic clock (which is why QElapsedTimer is + /// used instead of QTime or QDateTime). + QElapsedTimer m_timer; + +public: + /// @param tokens The amount of tokens that should be added. + /// @returns Whether adding this amount of tokens triggers rate + /// limiting (true means the corresponding packet has to be + /// discared and false means the packet may be processed) + bool ratelimit(int tokens); + + LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens); }; class ServerUser : public Connection, public User { - private: - Q_OBJECT - Q_DISABLE_COPY(ServerUser) - protected: - Server *s; - public: - enum State { Connected, Authenticated }; - State sState; - operator QString() const; - - float dUDPPingAvg, dUDPPingVar; - float dTCPPingAvg, dTCPPingVar; - quint32 uiUDPPackets, uiTCPPackets; - - unsigned int uiVersion; - QString qsRelease; - QString qsOS; - QString qsOSVersion; - - std::string ssContext; - QString qsIdentity; - - bool bVerified; - QStringList qslEmail; - - HostAddress haAddress; - - /// Holds whether the user is using TCP - /// or UDP for voice packets. - /// - /// If the flag is 0, the user is using - /// TCP. - /// - /// If the flag is 1, the user is using - /// UDP. - QAtomicInt aiUdpFlag; - - QList<int> qlCodecs; - bool bOpus; - - QStringList qslAccessTokens; - - QMap<int, WhisperTarget> qmTargets; - QMap<int, WhisperTargetCache> qmTargetCache; - QMap<QString, QString> qmWhisperRedirect; - - LeakyBucket leakyBucket; - - int iLastPermissionCheck; - QMap<int, unsigned int> qmPermissionSent; +private: + Q_OBJECT + Q_DISABLE_COPY(ServerUser) +protected: + Server *s; + +public: + enum State { Connected, Authenticated }; + State sState; + operator QString() const; + + float dUDPPingAvg, dUDPPingVar; + float dTCPPingAvg, dTCPPingVar; + quint32 uiUDPPackets, uiTCPPackets; + + unsigned int uiVersion; + QString qsRelease; + QString qsOS; + QString qsOSVersion; + + std::string ssContext; + QString qsIdentity; + + bool bVerified; + QStringList qslEmail; + + HostAddress haAddress; + + /// Holds whether the user is using TCP + /// or UDP for voice packets. + /// + /// If the flag is 0, the user is using + /// TCP. + /// + /// If the flag is 1, the user is using + /// UDP. + QAtomicInt aiUdpFlag; + + QList< int > qlCodecs; + bool bOpus; + + QStringList qslAccessTokens; + + QMap< int, WhisperTarget > qmTargets; + QMap< int, WhisperTargetCache > qmTargetCache; + QMap< QString, QString > qmWhisperRedirect; + + LeakyBucket leakyBucket; + + int iLastPermissionCheck; + QMap< int, unsigned int > qmPermissionSent; #ifdef Q_OS_UNIX - int sUdpSocket; + int sUdpSocket; #else - SOCKET sUdpSocket; + SOCKET sUdpSocket; #endif - BandwidthRecord bwr; - struct sockaddr_storage saiUdpAddress; - struct sockaddr_storage saiTcpLocalAddress; - ServerUser(Server *parent, QSslSocket *socket); + BandwidthRecord bwr; + struct sockaddr_storage saiUdpAddress; + struct sockaddr_storage saiTcpLocalAddress; + ServerUser(Server *parent, QSslSocket *socket); }; #endif diff --git a/src/murmur/Tray.cpp b/src/murmur/Tray.cpp index 6c5a876a8..8fed8a85e 100644 --- a/src/murmur/Tray.cpp +++ b/src/murmur/Tray.cpp @@ -6,10 +6,10 @@ #include "Tray.h" #include "About.h" +#include "LogEmitter.h" #include "Meta.h" #include "Server.h" #include "Version.h" -#include "LogEmitter.h" #include <QtWidgets/QAction> #include <QtWidgets/QApplication> @@ -54,12 +54,15 @@ Tray::Tray(QObject *p, LogEmitter *logger) : QObject(p) { void Tray::on_Tray_activated(QSystemTrayIcon::ActivationReason r) { if (r == QSystemTrayIcon::Trigger) { - qsti->showMessage(tr("Murmur"), tr("%1 server running.").arg(meta->qhServers.count()), QSystemTrayIcon::Information, 5000); + qsti->showMessage(tr("Murmur"), tr("%1 server running.").arg(meta->qhServers.count()), + QSystemTrayIcon::Information, 5000); } } void Tray::on_Quit_triggered() { - if (QMessageBox::question(nullptr, tr("Murmur"), tr("Are you sure you want to quit Murmur?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { + if (QMessageBox::question(nullptr, tr("Murmur"), tr("Are you sure you want to quit Murmur?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) + == QMessageBox::Yes) { qApp->quit(); } } @@ -79,7 +82,7 @@ void Tray::on_ShowLog_triggered() { connect(le, SIGNAL(newLogEntry(const QString &)), tb, SLOT(append(const QString &))); - foreach(const QString &m, qlLog) + foreach (const QString &m, qlLog) tb->append(m); mw->show(); diff --git a/src/murmur/Tray.h b/src/murmur/Tray.h index fec537411..43dc5881a 100644 --- a/src/murmur/Tray.h +++ b/src/murmur/Tray.h @@ -6,33 +6,35 @@ #ifndef MUMBLE_MURMUR_TRAY_H_ #define MUMBLE_MURMUR_TRAY_H_ -#include <QtCore/QStringList> #include <QtCore/QObject> +#include <QtCore/QStringList> #include <QtWidgets/QSystemTrayIcon> class LogEmitter; class QAction; class Tray : public QObject { - private: - Q_OBJECT - Q_DISABLE_COPY(Tray); - protected: - QSystemTrayIcon *qsti; - QMenu *qm; - QAction *qaQuit; - QAction *qaAbout; - QAction *qaShowLog; - QStringList qlLog; - LogEmitter *le; - public slots: - void on_Tray_activated(QSystemTrayIcon::ActivationReason); - void on_About_triggered(); - void on_Quit_triggered(); - void on_ShowLog_triggered(); - void addLogMessage(const QString &); - public: - Tray(QObject *parent, LogEmitter *le); +private: + Q_OBJECT + Q_DISABLE_COPY(Tray); + +protected: + QSystemTrayIcon *qsti; + QMenu *qm; + QAction *qaQuit; + QAction *qaAbout; + QAction *qaShowLog; + QStringList qlLog; + LogEmitter *le; +public slots: + void on_Tray_activated(QSystemTrayIcon::ActivationReason); + void on_About_triggered(); + void on_Quit_triggered(); + void on_ShowLog_triggered(); + void addLogMessage(const QString &); + +public: + Tray(QObject *parent, LogEmitter *le); }; #endif diff --git a/src/murmur/UnixMurmur.cpp b/src/murmur/UnixMurmur.cpp index 2b2abd0ec..68159177e 100644 --- a/src/murmur/UnixMurmur.cpp +++ b/src/murmur/UnixMurmur.cpp @@ -5,8 +5,8 @@ #include "UnixMurmur.h" -#include "Meta.h" #include "EnvUtils.h" +#include "Meta.h" #include <QtCore/QAbstractEventDispatcher> #include <QtCore/QCoreApplication> @@ -18,9 +18,9 @@ #include <signal.h> #ifdef Q_OS_LINUX -# include <sys/capability.h> -# include <sys/prctl.h> -# include <sys/resource.h> +# include <sys/capability.h> +# include <sys/prctl.h> +# include <sys/resource.h> #endif #include <sys/socket.h> @@ -45,11 +45,13 @@ void LimitTest::run() { void LimitTest::testLimits(QCoreApplication &a) { QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(); if (QLatin1String(ed->metaObject()->className()) != QLatin1String("QEventDispatcherGlib")) - qWarning("Not running with glib. While you may be able to open more descriptors, sockets above %d will not work", FD_SETSIZE); + qWarning( + "Not running with glib. While you may be able to open more descriptors, sockets above %d will not work", + FD_SETSIZE); qWarning("Running descriptor test."); int count; - QList<QFile *> ql; - for (count=0;count < 524288; ++count) { + QList< QFile * > ql; + for (count = 0; count < 524288; ++count) { QFile *qf = new QFile(a.applicationFilePath()); if (qf->open(QIODevice::ReadOnly)) ql.prepend(qf); @@ -58,13 +60,13 @@ void LimitTest::testLimits(QCoreApplication &a) { if ((count & 1023) == 0) qWarning("%d descriptors...", count); } - foreach(QFile *qf, ql) + foreach (QFile *qf, ql) delete qf; ql.clear(); qCritical("Managed to open %d descriptors", count); - qm = new QMutex(); - qw = new QWaitCondition(); + qm = new QMutex(); + qw = new QWaitCondition(); qstartw = new QWaitCondition(); int fdcount = count / 8; @@ -72,16 +74,16 @@ void LimitTest::testLimits(QCoreApplication &a) { if (fdcount > 1024) fdcount = 1024; - QList<LimitTest *> qtl; - for (count=0;count < fdcount; ++count) { + QList< LimitTest * > qtl; + for (count = 0; count < fdcount; ++count) { LimitTest *t = new LimitTest(); - t->tid = count; + t->tid = count; qtl << t; qm->lock(); t->start(); qstartw->wait(qm); qm->unlock(); - if (! t->isRunning()) + if (!t->isRunning()) break; if ((count & 511) == 0) qWarning("%d threads...", count); @@ -90,8 +92,8 @@ void LimitTest::testLimits(QCoreApplication &a) { qw->wakeAll(); qm->unlock(); - foreach(LimitTest *qt, qtl) { - if (! qt->wait(1000)) { + foreach (LimitTest *qt, qtl) { + if (!qt->wait(1000)) { qWarning("Thread %d failed to terminate...", qt->tid); qt->terminate(); } @@ -106,7 +108,7 @@ int UnixMurmur::iTermFd[2]; int UnixMurmur::iUsr1Fd[2]; UnixMurmur::UnixMurmur() { - bRoot = true; + bRoot = true; logToSyslog = false; if (geteuid() != 0 && getuid() != 0) { @@ -121,7 +123,7 @@ UnixMurmur::UnixMurmur() { if (::socketpair(AF_UNIX, SOCK_STREAM, 0, iUsr1Fd)) qFatal("Couldn't create USR1 socketpair"); - qsnHup = new QSocketNotifier(iHupFd[1], QSocketNotifier::Read, this); + qsnHup = new QSocketNotifier(iHupFd[1], QSocketNotifier::Read, this); qsnTerm = new QSocketNotifier(iTermFd[1], QSocketNotifier::Read, this); qsnUsr1 = new QSocketNotifier(iUsr1Fd[1], QSocketNotifier::Read, this); @@ -160,7 +162,7 @@ UnixMurmur::~UnixMurmur() { delete qsnTerm; delete qsnUsr1; - qsnHup = nullptr; + qsnHup = nullptr; qsnTerm = nullptr; qsnUsr1 = nullptr; @@ -173,19 +175,19 @@ UnixMurmur::~UnixMurmur() { } void UnixMurmur::hupSignalHandler(int) { - char a = 1; + char a = 1; ssize_t len = ::write(iHupFd[0], &a, sizeof(a)); Q_UNUSED(len); } void UnixMurmur::termSignalHandler(int) { - char a = 1; + char a = 1; ssize_t len = ::write(iTermFd[0], &a, sizeof(a)); Q_UNUSED(len); } void UnixMurmur::usr1SignalHandler(int) { - char a = 1; + char a = 1; ssize_t len = ::write(iUsr1Fd[0], &a, sizeof(a)); Q_UNUSED(len); } @@ -201,17 +203,17 @@ void UnixMurmur::handleSigHup() { if (logToSyslog) { qWarning("Caught SIGHUP, but logging to syslog"); - } else if (! qfLog) { + } else if (!qfLog) { qWarning("Caught SIGHUP, but logfile not in use"); - } else if (! qfLog->isOpen()) { + } else if (!qfLog->isOpen()) { qWarning("Caught SIGHUP, but logfile not in use -- interpreting as hint to quit"); QCoreApplication::instance()->quit(); } else { qWarning("Caught SIGHUP, will reopen %s", qPrintable(Meta::mp.qsLogfile)); QFile *newlog = new QFile(Meta::mp.qsLogfile); - bool result = newlog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); - if (! result) { + bool result = newlog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); + if (!result) { delete newlog; qCritical("Failed to reopen logfile for writing, keeping old log"); } else { @@ -252,7 +254,8 @@ void UnixMurmur::handleSigUsr1() { if (ok) { qWarning("UnixMurmur: Done reloading SSL settings."); } else { - qWarning("UnixMurmur: Failed to reload SSL settings. Server state is intact and fully operational. No configuration changes were made."); + qWarning("UnixMurmur: Failed to reload SSL settings. Server state is intact and fully operational. No " + "configuration changes were made."); } } @@ -263,7 +266,7 @@ void UnixMurmur::setuid() { if (Meta::mp.uiUid != 0) { #ifdef Q_OS_DARWIN qCritical("WARNING: You are launching murmurd as root on Mac OS X or Darwin. Murmur does not need " - "special privileges to set itself up on these systems, so this behavior is highly discouraged."); + "special privileges to set itself up on these systems, so this behavior is highly discouraged."); if (::setgid(Meta::mp.uiGid) != 0) qFatal("Failed to switch to gid %d", Meta::mp.uiGid); @@ -272,8 +275,7 @@ void UnixMurmur::setuid() { uid_t uid = getuid(), euid = geteuid(); gid_t gid = getgid(), egid = getegid(); - if (uid == Meta::mp.uiUid && euid == Meta::mp.uiUid - && gid == Meta::mp.uiGid && egid == Meta::mp.uiGid) { + if (uid == Meta::mp.uiUid && euid == Meta::mp.uiUid && gid == Meta::mp.uiGid && egid == Meta::mp.uiGid) { qCritical("Successfully switched to uid %d", Meta::mp.uiUid); } else qFatal("Couldn't switch uid/gid."); @@ -296,18 +298,19 @@ void UnixMurmur::setuid() { } #endif } else if (bRoot) { - qCritical("WARNING: You are running murmurd as root, without setting a uname in the ini file. This might be a security risk."); + qCritical("WARNING: You are running murmurd as root, without setting a uname in the ini file. This might be a " + "security risk."); } } void UnixMurmur::initialcap() { #ifdef Q_OS_LINUX - cap_value_t caps[] = {CAP_NET_ADMIN, CAP_SETUID, CAP_SETGID, CAP_CHOWN, CAP_SYS_RESOURCE, CAP_DAC_OVERRIDE }; + cap_value_t caps[] = { CAP_NET_ADMIN, CAP_SETUID, CAP_SETGID, CAP_CHOWN, CAP_SYS_RESOURCE, CAP_DAC_OVERRIDE }; - if (! bRoot) + if (!bRoot) return; - int ncap = sizeof(caps)/sizeof(cap_value_t); + int ncap = sizeof(caps) / sizeof(cap_value_t); if (geteuid() != 0) ncap--; @@ -328,10 +331,10 @@ void UnixMurmur::initialcap() { void UnixMurmur::finalcap() { #ifdef Q_OS_LINUX - cap_value_t caps[] = {CAP_SYS_RESOURCE}; + cap_value_t caps[] = { CAP_SYS_RESOURCE }; struct rlimit r; - if (! bRoot) + if (!bRoot) return; if (getrlimit(RLIMIT_RTPRIO, &r) != 0) { @@ -344,7 +347,7 @@ void UnixMurmur::finalcap() { } } - int ncap = sizeof(caps)/sizeof(cap_value_t); + int ncap = sizeof(caps) / sizeof(cap_value_t); cap_t c = cap_init(); cap_clear(c); @@ -359,7 +362,7 @@ void UnixMurmur::finalcap() { #endif } -const QString UnixMurmur::trySystemIniFiles(const QString& fname) { +const QString UnixMurmur::trySystemIniFiles(const QString &fname) { QString file = fname; if (!file.isEmpty()) return file; @@ -374,7 +377,7 @@ const QString UnixMurmur::trySystemIniFiles(const QString& fname) { inipaths << QLatin1String("/etc/mumble-server.ini"); inipaths << QLatin1String("/etc/murmur.ini"); - foreach(const QString &f, inipaths) { + foreach (const QString &f, inipaths) { QFileInfo fi(f); if (fi.exists() && fi.isReadable()) { file = fi.absoluteFilePath(); diff --git a/src/murmur/UnixMurmur.h b/src/murmur/UnixMurmur.h index 86950d7d8..faf63d318 100644 --- a/src/murmur/UnixMurmur.h +++ b/src/murmur/UnixMurmur.h @@ -15,43 +15,45 @@ class QSocketNotifier; class QWaitCondition; class LimitTest : public QThread { - Q_OBJECT - Q_DISABLE_COPY(LimitTest) - protected: - static QMutex *qm; - static QWaitCondition *qw, *qstartw; - LimitTest(); - public: - int tid; - void run(); - static void testLimits(QCoreApplication &); + Q_OBJECT + Q_DISABLE_COPY(LimitTest) +protected: + static QMutex *qm; + static QWaitCondition *qw, *qstartw; + LimitTest(); + +public: + int tid; + void run(); + static void testLimits(QCoreApplication &); }; class UnixMurmur : public QObject { - Q_OBJECT - Q_DISABLE_COPY(UnixMurmur) - protected: - bool bRoot; - static int iHupFd[2], iTermFd[2], iUsr1Fd[2]; - QSocketNotifier *qsnHup, *qsnTerm, *qsnUsr1; - - static void hupSignalHandler(int); - static void termSignalHandler(int); - static void usr1SignalHandler(int); - public slots: - void handleSigHup(); - void handleSigTerm(); - void handleSigUsr1(); - public: - bool logToSyslog; - - void setuid(); - void initialcap(); - void finalcap(); - const QString trySystemIniFiles(const QString& fname); - - UnixMurmur(); - ~UnixMurmur(); + Q_OBJECT + Q_DISABLE_COPY(UnixMurmur) +protected: + bool bRoot; + static int iHupFd[2], iTermFd[2], iUsr1Fd[2]; + QSocketNotifier *qsnHup, *qsnTerm, *qsnUsr1; + + static void hupSignalHandler(int); + static void termSignalHandler(int); + static void usr1SignalHandler(int); +public slots: + void handleSigHup(); + void handleSigTerm(); + void handleSigUsr1(); + +public: + bool logToSyslog; + + void setuid(); + void initialcap(); + void finalcap(); + const QString trySystemIniFiles(const QString &fname); + + UnixMurmur(); + ~UnixMurmur(); }; #endif diff --git a/src/murmur/main.cpp b/src/murmur/main.cpp index e194991df..1aff85a40 100644 --- a/src/murmur/main.cpp +++ b/src/murmur/main.cpp @@ -4,43 +4,43 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifdef USE_DBUS -# include "DBus.h" +# include "DBus.h" #endif +#include "EnvUtils.h" +#include "License.h" +#include "LogEmitter.h" +#include "Meta.h" +#include "SSL.h" #include "Server.h" #include "ServerDB.h" -#include "Meta.h" #include "Version.h" -#include "SSL.h" -#include "License.h" -#include "LogEmitter.h" -#include "EnvUtils.h" #ifdef Q_OS_WIN -# include "About.h" -# include "Tray.h" +# include "About.h" +# include "Tray.h" -# include <QtWidgets/QApplication> +# include <QtWidgets/QApplication> #else -# include "UnixMurmur.h" +# include "UnixMurmur.h" -# include <QtCore/QCoreApplication> +# include <QtCore/QCoreApplication> #endif #include <QtCore/QTextCodec> #ifdef USE_DBUS -# include <QtDBus/QDBusError> -# include <QtDBus/QDBusServer> +# include <QtDBus/QDBusError> +# include <QtDBus/QDBusServer> #endif #include <openssl/crypto.h> #ifdef Q_OS_WIN -# include <intrin.h> +# include <intrin.h> #else -# include <fcntl.h> -# include <sys/syslog.h> +# include <fcntl.h> +# include <sys/syslog.h> #endif QFile *qfLog = nullptr; @@ -67,19 +67,19 @@ static void murmurMessageOutputQString(QtMsgType type, const QString &msg) { if (unixMurmur->logToSyslog) { int level; switch (type) { - case QtDebugMsg: - level = LOG_DEBUG; - break; - case QtWarningMsg: - level = LOG_WARNING; - break; - case QtCriticalMsg: - level = LOG_CRIT; - break; - case QtFatalMsg: - default: - level = LOG_ALERT; - break; + case QtDebugMsg: + level = LOG_DEBUG; + break; + case QtWarningMsg: + level = LOG_WARNING; + break; + case QtCriticalMsg: + level = LOG_CRIT; + break; + case QtFatalMsg: + default: + level = LOG_ALERT; + break; } syslog(level, "%s", qPrintable(msg)); if (type == QtFatalMsg) { @@ -92,39 +92,42 @@ static void murmurMessageOutputQString(QtMsgType type, const QString &msg) { char c; switch (type) { case QtDebugMsg: - if (! bVerbose) + if (!bVerbose) return; - c='D'; + c = 'D'; break; case QtWarningMsg: - c='W'; + c = 'W'; break; case QtCriticalMsg: - c='C'; + c = 'C'; break; case QtFatalMsg: - c='F'; + c = 'F'; break; default: - c='X'; + c = 'X'; } - QString m= QString::fromLatin1("<%1>%2 %3").arg(QChar::fromLatin1(c)).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(msg); + QString m = QString::fromLatin1("<%1>%2 %3") + .arg(QChar::fromLatin1(c)) + .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")) + .arg(msg); - if (! qfLog || ! qfLog->isOpen()) { + if (!qfLog || !qfLog->isOpen()) { #ifdef Q_OS_UNIX - if (! detach) + if (!detach) fprintf(stderr, "%s\n", qPrintable(m)); else qlErrors << m; #else qlErrors << m; -#ifndef QT_NO_DEBUG +# ifndef QT_NO_DEBUG fprintf(stderr, "%s\n", qPrintable(m)); -#endif +# endif #endif } else { - if (! qlErrors.isEmpty()) { - foreach(const QString &e, qlErrors) { + if (!qlErrors.isEmpty()) { + foreach (const QString &e, qlErrors) { qfLog->write(e.toUtf8()); qfLog->write("\n"); } @@ -174,9 +177,10 @@ int main(int argc, char **argv) { int cpuinfo[4]; __cpuid(cpuinfo, 1); -#define MMXSSE 0x02800000 +# define MMXSSE 0x02800000 if ((cpuinfo[3] & MMXSSE) != MMXSSE) { - ::MessageBoxA(nullptr, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", MB_OK | MB_ICONERROR); + ::MessageBoxA(nullptr, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", + MB_OK | MB_ICONERROR); exit(0); } @@ -199,9 +203,9 @@ int main(int argc, char **argv) { icon.addFile(QLatin1String(":/murmur.64x64.png")); a.setWindowIcon(icon); #else -#ifndef Q_OS_MAC +# ifndef Q_OS_MAC EnvUtils::setenv(QLatin1String("AVAHI_COMPAT_NOWARN"), QLatin1String("1")); -#endif +# endif QCoreApplication a(argc, argv); UnixMurmur unixhandler; unixMurmur = &unixhandler; @@ -224,7 +228,8 @@ int main(int argc, char **argv) { if (path.isEmpty()) { qWarning() << "Failed to get PATH. Not adding application directory to PATH. DBus bindings may not work."; } else { - QString newPath = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(path); + QString newPath = + QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(path); if (!EnvUtils::setenv(QLatin1String("PATH"), newPath)) { qWarning() << "Failed to set PATH. DBus bindings may not work."; } @@ -235,16 +240,16 @@ int main(int argc, char **argv) { QString inifile; QString supw; bool disableSu = false; - bool wipeSsl = false; - bool wipeLogs = false; - int sunum = 1; + bool wipeSsl = false; + bool wipeLogs = false; + int sunum = 1; #ifdef Q_OS_UNIX bool readPw = false; #endif bool logGroups = false; - bool logACL = false; + bool logACL = false; -#if QT_VERSION < QT_VERSION_CHECK(5,10,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // For Qt >= 5.10 we use QRandomNumberGenerator that is seeded automatically qsrand(QDateTime::currentDateTime().toTime_t()); #endif @@ -257,14 +262,14 @@ int main(int argc, char **argv) { QStringList args = a.arguments(); for (int i = 1; i < args.size(); i++) { - bool bLast = false; + bool bLast = false; QString arg = args.at(i).toLower(); if ((arg == "-supw")) { detach = false; - if (i+1 < args.size()) { + if (i + 1 < args.size()) { i++; supw = args.at(i); - if (i+1 < args.size()) { + if (i + 1 < args.size()) { i++; sunum = args.at(i).toInt(); } @@ -280,21 +285,21 @@ int main(int argc, char **argv) { } else if ((arg == "-readsupw")) { detach = false; readPw = true; - if (i+1 < args.size()) { + if (i + 1 < args.size()) { i++; sunum = args.at(i).toInt(); } bLast = true; #endif } else if ((arg == "-disablesu")) { - detach = false; - disableSu = true; - if (i+1 < args.size()) { - i++; - sunum = args.at(i).toInt(); - } - bLast = true; - } else if ((arg == "-ini") && (i+1 < args.size())) { + detach = false; + disableSu = true; + if (i + 1 < args.size()) { + i++; + sunum = args.at(i).toInt(); + } + bLast = true; + } else if ((arg == "-ini") && (i + 1 < args.size())) { i++; inifile = args.at(i); } else if ((arg == "-wipessl")) { @@ -327,7 +332,8 @@ int main(int argc, char **argv) { qInfo("%s\n", qPrintable(License::authors())); return 0; #endif - } else if (args.at(i) == QLatin1String("-third-party-licenses") || args.at(i) == QLatin1String("--third-party-licenses")) { + } else if (args.at(i) == QLatin1String("-third-party-licenses") + || args.at(i) == QLatin1String("--third-party-licenses")) { #ifdef Q_OS_WIN AboutDialog ad(nullptr, AboutDialogOptionsShowThirdPartyLicenses); ad.exec(); @@ -339,35 +345,36 @@ int main(int argc, char **argv) { } else if ((arg == "-h") || (arg == "-help") || (arg == "--help")) { detach = false; qInfo("Usage: %s [-ini <inifile>] [-supw <password>]\n" - " -ini <inifile> Specify ini file to use.\n" - " -supw <pw> [srv] Set password for 'SuperUser' account on server srv.\n" + " -ini <inifile> Specify ini file to use.\n" + " -supw <pw> [srv] Set password for 'SuperUser' account on server srv.\n" #ifdef Q_OS_UNIX - " -readsupw [srv] Reads password for server srv from standard input.\n" + " -readsupw [srv] Reads password for server srv from standard input.\n" #endif - " -disablesu [srv] Disable password for 'SuperUser' account on server srv.\n" + " -disablesu [srv] Disable password for 'SuperUser' account on server srv.\n" #ifdef Q_OS_UNIX - " -limits Tests and shows how many file descriptors and threads can be created.\n" - " The purpose of this option is to test how many clients Murmur can handle.\n" - " Murmur will exit after this test.\n" + " -limits Tests and shows how many file descriptors and threads can be created.\n" + " The purpose of this option is to test how many clients Murmur can handle.\n" + " Murmur will exit after this test.\n" #endif - " -v Use verbose logging (include debug-logs).\n" + " -v Use verbose logging (include debug-logs).\n" #ifdef Q_OS_UNIX - " -fg Don't detach from console.\n" + " -fg Don't detach from console.\n" #else - " -fg Don't write to the log file.\n" -#endif - " -wipessl Remove SSL certificates from database.\n" - " -wipelogs Remove all log entries from database.\n" - " -loggroups Turns on logging for group changes for all servers." - " -logacls Turns on logging for ACL changes for all servers." - " -version Show version information.\n" - "\n" - " -license Show Murmur's license.\n" - " -authors Show Murmur's authors.\n" - " -third-party-licenses Show licenses for third-party software used by Murmur.\n" - "\n" - "If no inifile is provided, murmur will search for one in \n" - "default locations.", qPrintable(args.at(0))); + " -fg Don't write to the log file.\n" +#endif + " -wipessl Remove SSL certificates from database.\n" + " -wipelogs Remove all log entries from database.\n" + " -loggroups Turns on logging for group changes for all servers." + " -logacls Turns on logging for ACL changes for all servers." + " -version Show version information.\n" + "\n" + " -license Show Murmur's license.\n" + " -authors Show Murmur's authors.\n" + " -third-party-licenses Show licenses for third-party software used by Murmur.\n" + "\n" + "If no inifile is provided, murmur will search for one in \n" + "default locations.", + qPrintable(args.at(0))); return 0; #ifdef Q_OS_UNIX } else if (arg == "-limits") { @@ -385,7 +392,7 @@ int main(int argc, char **argv) { detach = false; qFatal("Unknown argument %s", qPrintable(args.at(i))); } - if (bLast && (i+1 != args.size())) { + if (bLast && (i + 1 != args.size())) { detach = false; qFatal("Password arguments must be last."); } @@ -415,16 +422,17 @@ int main(int argc, char **argv) { // http://article.gmane.org/gmane.comp.security.oss.general/4404 #ifdef Q_OS_UNIX unixhandler.logToSyslog = Meta::mp.qsLogfile == QLatin1String("syslog"); - if (detach && ! Meta::mp.qsLogfile.isEmpty() && !unixhandler.logToSyslog) { + if (detach && !Meta::mp.qsLogfile.isEmpty() && !unixhandler.logToSyslog) { #else - if (detach && ! Meta::mp.qsLogfile.isEmpty()) { + if (detach && !Meta::mp.qsLogfile.isEmpty()) { #endif qfLog = new QFile(Meta::mp.qsLogfile); - if (! qfLog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { + if (!qfLog->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { delete qfLog; qfLog = nullptr; #ifdef Q_OS_UNIX - fprintf(stderr, "murmurd: failed to open logfile %s: no logging will be done\n", qPrintable(Meta::mp.qsLogfile)); + fprintf(stderr, "murmurd: failed to open logfile %s: no logging will be done\n", + qPrintable(Meta::mp.qsLogfile)); #else qWarning("Failed to open logfile %s. No logging will be performed.", qPrintable(Meta::mp.qsLogfile)); #endif @@ -434,7 +442,8 @@ int main(int argc, char **argv) { Meta::mp.qsLogfile = qfi.absoluteFilePath(); #ifdef Q_OS_UNIX if (Meta::mp.uiUid != 0 && fchown(qfLog->handle(), Meta::mp.uiUid, Meta::mp.uiGid) == -1) { - qFatal("can't change log file owner to %d %d:%d - %s", qfLog->handle(), Meta::mp.uiUid, Meta::mp.uiGid, strerror(errno)); + qFatal("can't change log file owner to %d %d:%d - %s", qfLog->handle(), Meta::mp.uiUid, Meta::mp.uiGid, + strerror(errno)); } #endif } @@ -489,14 +498,14 @@ int main(int argc, char **argv) { } if (disableSu) { - ServerDB::disableSU(sunum); - qInfo("SuperUser password disabled on server %d", sunum); - return 0; + ServerDB::disableSU(sunum); + qInfo("SuperUser password disabled on server %d", sunum); + return 0; } if (wipeSsl) { qWarning("Removing all per-server SSL certificates from the database."); - foreach(int sid, ServerDB::getAllServers()) { + foreach (int sid, ServerDB::getAllServers()) { ServerDB::setConf(sid, "key"); ServerDB::setConf(sid, "certificate"); ServerDB::setConf(sid, "passphrase"); @@ -519,7 +528,7 @@ int main(int argc, char **argv) { _exit(0); } - if (! Meta::mp.qsPid.isEmpty()) { + if (!Meta::mp.qsPid.isEmpty()) { QFile pid(Meta::mp.qsPid); if (pid.open(QIODevice::WriteOnly)) { QFileInfo fi(pid); @@ -553,7 +562,7 @@ int main(int argc, char **argv) { #ifdef USE_DBUS MurmurDBus::registerTypes(); - if (! Meta::mp.qsDBus.isEmpty()) { + if (!Meta::mp.qsDBus.isEmpty()) { if (Meta::mp.qsDBus == "session") MurmurDBus::qdbc = new QDBusConnection(QDBusConnection::sessionBus()); else if (Meta::mp.qsDBus == "system") @@ -562,21 +571,22 @@ int main(int argc, char **argv) { // QtDBus is not quite finished yet. qWarning("Warning: Peer-to-peer session support is currently nonworking."); MurmurDBus::qdbc = new QDBusConnection(QDBusConnection::connectToBus(Meta::mp.qsDBus, "mainbus")); - if (! MurmurDBus::qdbc->isConnected()) { + if (!MurmurDBus::qdbc->isConnected()) { QDBusServer *qdbs = new QDBusServer(Meta::mp.qsDBus, &a); - qWarning("%s",qPrintable(qdbs->lastError().name())); - qWarning("%d",qdbs->isConnected()); - qWarning("%s",qPrintable(qdbs->address())); + qWarning("%s", qPrintable(qdbs->lastError().name())); + qWarning("%d", qdbs->isConnected()); + qWarning("%s", qPrintable(qdbs->address())); MurmurDBus::qdbc = new QDBusConnection(QDBusConnection::connectToBus(Meta::mp.qsDBus, "mainbus")); } } - if (! MurmurDBus::qdbc->isConnected()) { - qWarning("Failed to connect to D-Bus %s",qPrintable(Meta::mp.qsDBus)); + if (!MurmurDBus::qdbc->isConnected()) { + qWarning("Failed to connect to D-Bus %s", qPrintable(Meta::mp.qsDBus)); } else { new MetaDBus(meta); if (MurmurDBus::qdbc->isConnected()) { - if (! MurmurDBus::qdbc->registerObject("/", meta) || ! MurmurDBus::qdbc->registerService(Meta::mp.qsDBusService)) { - QDBusError e=MurmurDBus::qdbc->lastError(); + if (!MurmurDBus::qdbc->registerObject("/", meta) + || !MurmurDBus::qdbc->registerService(Meta::mp.qsDBusService)) { + QDBusError e = MurmurDBus::qdbc->lastError(); qWarning("Failed to register on DBus: %s %s", qPrintable(e.name()), qPrintable(e.message())); } else { qWarning("DBus registration succeeded"); @@ -594,7 +604,8 @@ int main(int argc, char **argv) { GRPCStart(); #else if (!meta->mp.qsGRPCAddress.isEmpty() || !meta->mp.qsGRPCCert.isEmpty() || !meta->mp.qsGRPCKey.isEmpty()) { - qWarning("This version of Murmur was built without gRPC support. Ignoring 'grpc' option from configuration file."); + qWarning( + "This version of Murmur was built without gRPC support. Ignoring 'grpc' option from configuration file."); } #endif @@ -604,11 +615,12 @@ int main(int argc, char **argv) { QString strver; meta->getVersion(major, minor, patch, strver); - qWarning("Murmur %d.%d.%d (%s) running on %s: %s: Booting servers", major, minor, patch, qPrintable(strver), qPrintable(meta->qsOS), qPrintable(meta->qsOSVersion)); + qWarning("Murmur %d.%d.%d (%s) running on %s: %s: Booting servers", major, minor, patch, qPrintable(strver), + qPrintable(meta->qsOS), qPrintable(meta->qsOSVersion)); meta->bootAll(); - res=a.exec(); + res = a.exec(); qWarning("Killing running servers"); @@ -637,7 +649,7 @@ int main(int argc, char **argv) { qInstallMessageHandler(nullptr); #ifdef Q_OS_UNIX - if (! Meta::mp.qsPid.isEmpty()) { + if (!Meta::mp.qsPid.isEmpty()) { QFile pid(Meta::mp.qsPid); pid.remove(); } diff --git a/src/murmur/murmur_pch.h b/src/murmur/murmur_pch.h index 3224728d8..d6f5ca8dd 100644 --- a/src/murmur/murmur_pch.h +++ b/src/murmur/murmur_pch.h @@ -4,101 +4,100 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #ifndef Q_MOC_RUN -#ifndef MUMBLE_MURMUR_MURMUR_PCH_H_ -#define MUMBLE_MURMUR_MURMUR_PCH_H_ +# ifndef MUMBLE_MURMUR_MURMUR_PCH_H_ +# define MUMBLE_MURMUR_MURMUR_PCH_H_ -#ifdef _MSC_VER -# define _USE_MATH_DEFINES -#endif +# ifdef _MSC_VER +# define _USE_MATH_DEFINES +# endif -#include <QtCore/QtGlobal> +# include <QtCore/QtGlobal> -#ifdef Q_OS_WIN -# include "win.h" -#endif +# ifdef Q_OS_WIN +# include "win.h" +# endif -#ifdef __APPLE__ -# include <CoreFoundation/CoreFoundation.h> -# include <CoreServices/CoreServices.h> -# undef check -# undef TYPE_BOOL -#endif +# ifdef __APPLE__ +# include <CoreFoundation/CoreFoundation.h> +# include <CoreServices/CoreServices.h> +# undef check +# undef TYPE_BOOL +# endif -#include <QtCore/QtCore> -#include <QtNetwork/QtNetwork> -#include <QtSql/QtSql> -#include <QtXml/QtXml> -#ifdef USE_DBUS -# include <QtDBus/QtDBus> -#endif +# include <QtCore/QtCore> +# include <QtNetwork/QtNetwork> +# include <QtSql/QtSql> +# include <QtXml/QtXml> +# ifdef USE_DBUS +# include <QtDBus/QtDBus> +# endif -#ifdef Q_OS_WIN -# include <QtGui/QtGui> +# ifdef Q_OS_WIN +# include <QtGui/QtGui> -# include <ws2tcpip.h> -# include <qos2.h> -# include <shellapi.h> -# include <delayimp.h> +# include <delayimp.h> +# include <qos2.h> +# include <shellapi.h> +# include <ws2tcpip.h> extern "C" { - void __cpuid(int a[4], int b); +void __cpuid(int a[4], int b); }; -#endif +# endif -#ifdef Q_OS_UNIX -# include <stdio.h> -# include <stdlib.h> -# include <unistd.h> -# include <sys/types.h> -# include <sys/stat.h> -# include <fcntl.h> -# include <sys/types.h> -# include <sys/socket.h> -# include <sys/time.h> -# include <sys/resource.h> -# include <syslog.h> -# ifdef Q_OS_LINUX -# include <linux/types.h> // needed to work around evil magic stuff in capability.h -# include <sys/capability.h> -# include <sys/prctl.h> -# endif -# include <pwd.h> -# include <grp.h> -# if defined __FreeBSD__ || defined __OpenBSD__ -# include <netinet/in_systm.h> -# endif -# include <netinet/in.h> -# include <netinet/ip.h> -# include <errno.h> -# include <signal.h> -# include <poll.h> -# ifdef Q_OS_DARWIN -# include <poll.h> -# endif -#endif +# ifdef Q_OS_UNIX +# include <fcntl.h> +# include <stdio.h> +# include <stdlib.h> +# include <sys/resource.h> +# include <sys/socket.h> +# include <sys/stat.h> +# include <sys/time.h> +# include <sys/types.h> +# include <syslog.h> +# include <unistd.h> +# ifdef Q_OS_LINUX +# include <linux/types.h> // needed to work around evil magic stuff in capability.h +# include <sys/capability.h> +# include <sys/prctl.h> +# endif +# include <grp.h> +# include <pwd.h> +# if defined __FreeBSD__ || defined __OpenBSD__ +# include <netinet/in_systm.h> +# endif +# include <errno.h> +# include <netinet/in.h> +# include <netinet/ip.h> +# include <poll.h> +# include <signal.h> +# ifdef Q_OS_DARWIN +# include <poll.h> +# endif +# endif -#include <cmath> +# include <cmath> -#include <boost/function.hpp> -#include <boost/bind.hpp> -#include <boost/shared_ptr.hpp> -#include <boost/weak_ptr.hpp> +# include <boost/bind.hpp> +# include <boost/function.hpp> +# include <boost/shared_ptr.hpp> +# include <boost/weak_ptr.hpp> -#ifdef USE_BONJOUR -# include <dns_sd.h> -#endif +# ifdef USE_BONJOUR +# include <dns_sd.h> +# endif -#include <openssl/opensslv.h> -#include <openssl/bn.h> -#include <openssl/aes.h> -#include <openssl/rand.h> -#include <openssl/pem.h> -#include <openssl/conf.h> -#include <openssl/x509v3.h> -#include <openssl/err.h> -#include <openssl/ssl.h> +# include <openssl/aes.h> +# include <openssl/bn.h> +# include <openssl/conf.h> +# include <openssl/err.h> +# include <openssl/opensslv.h> +# include <openssl/pem.h> +# include <openssl/rand.h> +# include <openssl/ssl.h> +# include <openssl/x509v3.h> /* OpenSSL defines set_key. This breaks our protobuf-generated setters. */ -#undef set_key +# undef set_key -#endif +# endif #endif diff --git a/src/murmur_grpcwrapper_protoc_plugin/main.cpp b/src/murmur_grpcwrapper_protoc_plugin/main.cpp index 66263edc1..3c832f05f 100644 --- a/src/murmur_grpcwrapper_protoc_plugin/main.cpp +++ b/src/murmur_grpcwrapper_protoc_plugin/main.cpp @@ -4,8 +4,8 @@ // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include <map> -#include <string> #include <sstream> +#include <string> #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/plugin.h> @@ -222,18 +222,18 @@ class WrapperGenerator : public CodeGenerator { } cpp.Print("namespace Wrapper {\n", "ns", ns); - map<string, string> tpl; + map< string, string > tpl; tpl["ns"] = ns; for (int i = 0; i < input->service_count(); i++) { - auto service = input->service(i); + auto service = input->service(i); tpl["service"] = service->name(); for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); + auto method = service->method(j); tpl["method"] = method->name(); - tpl["in"] = CompiledName(ns, method->input_type()); - tpl["out"] = CompiledName(ns, method->output_type()); + tpl["in"] = CompiledName(ns, method->input_type()); + tpl["out"] = CompiledName(ns, method->output_type()); const char *template_str; if (method->client_streaming()) { @@ -254,7 +254,7 @@ class WrapperGenerator : public CodeGenerator { cpp.Print(tpl, "void $service$_Init(MurmurRPCImpl *impl, ::$ns$::$service$::AsyncService *service) {\n"); for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); + auto method = service->method(j); tpl["method"] = method->name(); cpp.Print(tpl, "\t$service$_$method$::create(impl, service);\n"); } diff --git a/src/tests/Benchmark.cpp b/src/tests/Benchmark.cpp index 7919c7049..216d266ea 100644 --- a/src/tests/Benchmark.cpp +++ b/src/tests/Benchmark.cpp @@ -7,62 +7,61 @@ #include <QtNetwork> #ifndef Q_OS_WIN -#include <unistd.h> +# include <unistd.h> #endif -#include <sys/types.h> -#include <sys/stat.h> #include <fcntl.h> +#include <sys/stat.h> #include <sys/types.h> #ifndef Q_OS_WIN -#include <sys/socket.h> -#include <netinet/in.h> -#include <netinet/ip.h> -#include <sys/utsname.h> +# include <netinet/in.h> +# include <netinet/ip.h> +# include <sys/socket.h> +# include <sys/utsname.h> #endif #include <errno.h> +#include "Message.h" +#include "Mumble.pb.h" #include "PacketDataStream.h" #include "Timer.h" -#include "Message.h" #include "crypto/CryptState.h" -#include "Mumble.pb.h" -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) - #include <QRandomGenerator> +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) +# include <QRandomGenerator> #endif class Client : public QThread { - Q_OBJECT - public: - bool udp; - bool sender; - struct sockaddr_in srv; - unsigned int uiSession; - CryptStateOCB2 crypt; - int rcvd; - int socket; - int seq; - void run(); - void ping(); - void sendVoice(); - int numbytes; - int ptype; - QSslSocket *ssl; - Client(QObject *parent, QHostAddress srvaddr, unsigned short prt, bool send, bool tcponly); - void doUdp(const unsigned char *buffer, int size); - void sendMessage(const ::google::protobuf::Message &msg, unsigned int msgType); - ~Client(); - public slots: - void readyRead(); - void disconnected(); + Q_OBJECT +public: + bool udp; + bool sender; + struct sockaddr_in srv; + unsigned int uiSession; + CryptStateOCB2 crypt; + int rcvd; + int socket; + int seq; + void run(); + void ping(); + void sendVoice(); + int numbytes; + int ptype; + QSslSocket *ssl; + Client(QObject *parent, QHostAddress srvaddr, unsigned short prt, bool send, bool tcponly); + void doUdp(const unsigned char *buffer, int size); + void sendMessage(const ::google::protobuf::Message &msg, unsigned int msgType); + ~Client(); +public slots: + void readyRead(); + void disconnected(); }; Client::Client(QObject *p, QHostAddress qha, unsigned short prt, bool send, bool tcponly) : QThread(p) { - srv.sin_family = AF_INET; + srv.sin_family = AF_INET; srv.sin_addr.s_addr = htonl(qha.toIPv4Address()); - srv.sin_port = htons(prt); + srv.sin_port = htons(prt); - udp = ! tcponly; + udp = !tcponly; sender = send; ssl = new QSslSocket(this); @@ -73,7 +72,7 @@ Client::Client(QObject *p, QHostAddress qha, unsigned short prt, bool send, bool ssl->setProtocol(QSsl::TlsV1); ssl->connectToHostEncrypted(qha.toString(), prt); ssl->ignoreSslErrors(); - if (! ssl->waitForEncrypted()) + if (!ssl->waitForEncrypted()) qFatal("Connection failure"); static int ctr = 1; @@ -108,8 +107,8 @@ Client::Client(QObject *p, QHostAddress qha, unsigned short prt, bool send, bool if (udp) socket = ::socket(PF_INET, SOCK_DGRAM, 0); - seq = 0; - rcvd = 0; + seq = 0; + rcvd = 0; numbytes = -1; } @@ -123,12 +122,12 @@ void Client::sendMessage(const ::google::protobuf::Message &msg, unsigned int ms int len = msg.ByteSize(); Q_ASSERT(len < 4090); - * reinterpret_cast<quint16 *>(& uc[0]) = qToBigEndian(static_cast<quint16>(msgType)); - * reinterpret_cast<quint32 *>(& uc[2]) = qToBigEndian(static_cast<quint32>(len)); + *reinterpret_cast< quint16 * >(&uc[0]) = qToBigEndian(static_cast< quint16 >(msgType)); + *reinterpret_cast< quint32 * >(&uc[2]) = qToBigEndian(static_cast< quint32 >(len)); msg.SerializeToArray(uc + 6, len); - ssl->write(reinterpret_cast<const char *>(uc), len + 6); + ssl->write(reinterpret_cast< const char * >(uc), len + 6); } void Client::ping() { @@ -146,7 +145,7 @@ void Client::ping() { void Client::sendVoice() { unsigned char buffer[1024]; -#if QT_VERSION >= QT_VERSION_CHECK(5,10,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) int len = 32 + (QRandomGenerator::global()->generate() & 0x3f); #else // Qt 5.10 introduces the QRandomGenerator class and in Qt 5.15 qrand got deprecated in its favor @@ -165,13 +164,14 @@ void Client::sendVoice() { } void Client::doUdp(const unsigned char *buffer, int size) { - if (! udp || ! crypt.isValid()) + if (!udp || !crypt.isValid()) return; unsigned char crypted[2048]; - crypt.encrypt(reinterpret_cast<const unsigned char *>(buffer), crypted, size); - ::sendto(socket, reinterpret_cast<const char *>(crypted), size+4, 0, reinterpret_cast<struct sockaddr *>(&srv), sizeof(srv)); + crypt.encrypt(reinterpret_cast< const unsigned char * >(buffer), crypted, size); + ::sendto(socket, reinterpret_cast< const char * >(crypted), size + 4, 0, + reinterpret_cast< struct sockaddr * >(&srv), sizeof(srv)); } @@ -181,12 +181,13 @@ void Client::run() { socklen_t sz; int len; - if (! udp) + if (!udp) return; forever { - sz = sizeof(addr); - len = ::recvfrom(socket, reinterpret_cast<char *>(buffer), 1024, 0, reinterpret_cast<struct sockaddr *>(&addr), &sz); + sz = sizeof(addr); + len = ::recvfrom(socket, reinterpret_cast< char * >(buffer), 1024, 0, + reinterpret_cast< struct sockaddr * >(&addr), &sz); if (len <= 0) break; if (len >= 32) @@ -201,10 +202,10 @@ void Client::readyRead() { if (avail < 6) break; unsigned char b[6]; - ssl->read(reinterpret_cast<char *>(b), 6); + ssl->read(reinterpret_cast< char * >(b), 6); - ptype = qFromBigEndian(* reinterpret_cast<quint16 *>(& b[0])); - numbytes = qFromBigEndian(* reinterpret_cast<quint32 *>(& b[2])); + ptype = qFromBigEndian(*reinterpret_cast< quint16 * >(&b[0])); + numbytes = qFromBigEndian(*reinterpret_cast< quint32 * >(&b[2])); avail = ssl->bytesAvailable(); } @@ -213,49 +214,50 @@ void Client::readyRead() { numbytes = -1; unsigned char buff[65536]; Q_ASSERT(want < 65536); - ssl->read(reinterpret_cast<char *>(buff), want); + ssl->read(reinterpret_cast< char * >(buff), want); avail = ssl->bytesAvailable(); switch (ptype) { case MessageHandler::CryptSetup: { - MumbleProto::CryptSetup msg; - if (! msg.ParseFromArray(buff, want)) - qFatal("Failed parse crypt"); - - if (msg.has_key() && msg.has_client_nonce() && msg.has_server_nonce()) { - const std::string &key = msg.key(); - const std::string &client_nonce = msg.client_nonce(); - const std::string &server_nonce = msg.server_nonce(); - if (key.size() == AES_BLOCK_SIZE && client_nonce.size() == AES_BLOCK_SIZE && server_nonce.size() == AES_BLOCK_SIZE) - crypt.setKey(key, client_nonce, server_nonce); - } else if (msg.has_server_nonce()) { - const std::string &server_nonce = msg.server_nonce(); - if (server_nonce.size() == AES_BLOCK_SIZE) { - crypt.uiResync++; - crypt.setDecryptIV(server_nonce); - } - } else { - MumbleProto::CryptSetup mpcs; - mpcs.set_client_nonce(crypt.getEncryptIV()); - sendMessage(mpcs, MessageHandler::CryptSetup); + MumbleProto::CryptSetup msg; + if (!msg.ParseFromArray(buff, want)) + qFatal("Failed parse crypt"); + + if (msg.has_key() && msg.has_client_nonce() && msg.has_server_nonce()) { + const std::string &key = msg.key(); + const std::string &client_nonce = msg.client_nonce(); + const std::string &server_nonce = msg.server_nonce(); + if (key.size() == AES_BLOCK_SIZE && client_nonce.size() == AES_BLOCK_SIZE + && server_nonce.size() == AES_BLOCK_SIZE) + crypt.setKey(key, client_nonce, server_nonce); + } else if (msg.has_server_nonce()) { + const std::string &server_nonce = msg.server_nonce(); + if (server_nonce.size() == AES_BLOCK_SIZE) { + crypt.uiResync++; + crypt.setDecryptIV(server_nonce); } - break; + } else { + MumbleProto::CryptSetup mpcs; + mpcs.set_client_nonce(crypt.getEncryptIV()); + sendMessage(mpcs, MessageHandler::CryptSetup); } + break; + } case MessageHandler::ServerSync: { - MumbleProto::ServerSync msg; - if (! msg.ParseFromArray(buff, want)) - qFatal("Failed parse sync"); - uiSession = msg.session(); - break; - } + MumbleProto::ServerSync msg; + if (!msg.ParseFromArray(buff, want)) + qFatal("Failed parse sync"); + uiSession = msg.session(); + break; + } case MessageHandler::UDPTunnel: { - unsigned int msgUDPType = (buff[0] >> 5) & 0x7; - if (msgUDPType == MessageHandler::UDPVoiceCELTAlpha) - rcvd++; - break; - } + unsigned int msgUDPType = (buff[0] >> 5) & 0x7; + if (msgUDPType == MessageHandler::UDPVoiceCELTAlpha) + rcvd++; + break; + } } } else { break; @@ -269,38 +271,38 @@ void Client::disconnected() { } class Container : public QObject { - Q_OBJECT - public: - int sent; - int numsender, numudplistener, numtcplistener; - int isender, iudplistener, itcplistener; - bool live, forceping; - QHostAddress qha; - unsigned short port; - QTimer qtTick; - Timer tickPing, tickVoice, tickGo, tickSpawn; - QList<Client *> speakers; - QList<Client *> clients; - Container(QHostAddress srvaddr, unsigned short port, int nsend, int nudp, int ntcp); - public slots: - void tick(); - void go(); + Q_OBJECT +public: + int sent; + int numsender, numudplistener, numtcplistener; + int isender, iudplistener, itcplistener; + bool live, forceping; + QHostAddress qha; + unsigned short port; + QTimer qtTick; + Timer tickPing, tickVoice, tickGo, tickSpawn; + QList< Client * > speakers; + QList< Client * > clients; + Container(QHostAddress srvaddr, unsigned short port, int nsend, int nudp, int ntcp); +public slots: + void tick(); + void go(); }; Container::Container(QHostAddress qha, unsigned short port, int numsend, int numudp, int numtcp) { isender = iudplistener = itcplistener = 0; - live = false; - forceping = false; - sent = 0; + live = false; + forceping = false; + sent = 0; Timer t; - qWarning("Spawning %d speakers and %d listeners (%d UDP, %d TCP)", numsend, numudp+numtcp, numudp, numtcp); + qWarning("Spawning %d speakers and %d listeners (%d UDP, %d TCP)", numsend, numudp + numtcp, numudp, numtcp); - this->qha = qha; + this->qha = qha; this->port = port; - numsender = numsend; + numsender = numsend; numudplistener = numudp; numtcplistener = numtcp; @@ -315,34 +317,35 @@ void Container::tick() { if (forceping || tickPing.isElapsed(5000000ULL)) { forceping = false; - foreach(Client *c, clients) + foreach (Client *c, clients) c->ping(); if (live) { - - int lost = 0; + int lost = 0; quint64 totrcv = 0; - int nrcv = 0; - foreach(Client *c, clients) { - if (! c->sender) { + int nrcv = 0; + foreach (Client *c, clients) { + if (!c->sender) { totrcv += c->rcvd; lost += sent - c->rcvd; nrcv++; } } - qWarning("Sent: %8d Rcvd: %8lld Lost: %8d BW: %6.1fMbit/s", sent, totrcv / nrcv, (lost + nrcv - 1) / nrcv, (totrcv * 8.0 * 123.0) / (tickGo.elapsed() * 1.0)); + qWarning("Sent: %8d Rcvd: %8lld Lost: %8d BW: %6.1fMbit/s", sent, totrcv / nrcv, + (lost + nrcv - 1) / nrcv, (totrcv * 8.0 * 123.0) / (tickGo.elapsed() * 1.0)); } else { - qWarning("Spawned %3d/%3d", isender + iudplistener + itcplistener, numsender + numudplistener + numtcplistener); + qWarning("Spawned %3d/%3d", isender + iudplistener + itcplistener, + numsender + numudplistener + numtcplistener); } } if (live && tickVoice.isElapsed(10000ULL)) { - foreach(Client *c, speakers) { + foreach (Client *c, speakers) { sent++; c->sendVoice(); } } - if (! live) { + if (!live) { if (isender < numsender) { // Spawn a sender Client *c = new Client(this, qha, port, true, false); @@ -363,12 +366,13 @@ void Container::tick() { clients << c; itcplistener++; } else { - live = true; + live = true; quint64 elapsed = tickSpawn.elapsed(); - qWarning("Spawning took %lld ms (%lld us per client)", elapsed / 1000ULL, elapsed / (numsender+numudplistener+numtcplistener)); - foreach(Client *c, clients) + qWarning("Spawning took %lld ms (%lld us per client)", elapsed / 1000ULL, + elapsed / (numsender + numudplistener + numtcplistener)); + foreach (Client *c, clients) c->rcvd = 0; - sent = 0; + sent = 0; forceping = true; qtTick.start(10); } @@ -376,7 +380,7 @@ void Container::tick() { } void Container::go() { - foreach(Client *c, clients) + foreach (Client *c, clients) c->start(); qtTick.start(10); tickGo.restart(); @@ -388,11 +392,12 @@ int main(int argc, char **argv) { qWarning("Maximum # sockets is %d", FD_SETSIZE); if (argc != 6) - qFatal("Invalid number of arguments. These need to be passed: <host address> <port> <numsend> <numudp> <numtcp>"); + qFatal( + "Invalid number of arguments. These need to be passed: <host address> <port> <numsend> <numudp> <numtcp>"); - QHostAddress qha = QHostAddress(argv[1]); - int port = atoi(argv[2]); - int numsender = atoi(argv[3]); + QHostAddress qha = QHostAddress(argv[1]); + int port = atoi(argv[2]); + int numsender = atoi(argv[3]); int numudplistener = atoi(argv[4]); int numtcplistener = atoi(argv[5]); diff --git a/src/tests/Collections.cpp b/src/tests/Collections.cpp index 8114bcb9a..30a5b3930 100644 --- a/src/tests/Collections.cpp +++ b/src/tests/Collections.cpp @@ -12,17 +12,14 @@ using namespace std; #define SL 10000 #define NE 300 -template<class T> -class QListSet { - public: - QList<T> l; - void insert(const T &i) { - if (! l.contains(i)) - l.append(i); - } - void remove(const T &i) { - l.removeAll(i); - } +template< class T > class QListSet { +public: + QList< T > l; + void insert(const T &i) { + if (!l.contains(i)) + l.append(i); + } + void remove(const T &i) { l.removeAll(i); } }; int main(int argc, char **argv) { @@ -32,14 +29,14 @@ int main(int argc, char **argv) { { t.restart(); - QSet<int> s; + QSet< int > s; s.reserve(NE); - for (int i=0;i<NE;i++) + for (int i = 0; i < NE; i++) s.insert(i); usins = t.restart(); - sum = 0; - for (int j=0;j<SL;j++) - foreach(int v, s) + sum = 0; + for (int j = 0; j < SL; j++) + foreach (int v, s) sum += v; usiter = t.restart(); } @@ -47,13 +44,13 @@ int main(int argc, char **argv) { { t.restart(); - QList<int> s; - for (int i=0;i<NE;i++) + QList< int > s; + for (int i = 0; i < NE; i++) s.append(i); usins = t.restart(); - sum = 0; - for (int j=0;j<SL;j++) - foreach(int v, s) + sum = 0; + for (int j = 0; j < SL; j++) + foreach (int v, s) sum += v; usiter = t.restart(); } @@ -61,14 +58,14 @@ int main(int argc, char **argv) { { t.restart(); - QVector<int> s; + QVector< int > s; s.reserve(NE); - for (int i=0;i<NE;i++) + for (int i = 0; i < NE; i++) s.append(i); usins = t.restart(); - sum = 0; - for (int j=0;j<SL;j++) - foreach(int v, s) + sum = 0; + for (int j = 0; j < SL; j++) + foreach (int v, s) sum += v; usiter = t.restart(); } @@ -76,14 +73,14 @@ int main(int argc, char **argv) { { t.restart(); - vector<int> s; - for (int i=0;i<NE;i++) + vector< int > s; + for (int i = 0; i < NE; i++) s.push_back(i); - usins = t.restart(); - sum = 0; + usins = t.restart(); + sum = 0; int sz = s.size(); - for (int j=0;j<SL;j++) - for (int i=0;i<sz;i++) + for (int j = 0; j < SL; j++) + for (int i = 0; i < sz; i++) sum += s[i]; usiter = t.restart(); } @@ -92,12 +89,12 @@ int main(int argc, char **argv) { { t.restart(); int s[NE]; - for (int i=0;i<NE;i++) - s[i]=i; + for (int i = 0; i < NE; i++) + s[i] = i; usins = t.restart(); - sum = 0; - for (int j=0;j<SL;j++) - for (int i=0;i<NE;i++) + sum = 0; + for (int j = 0; j < SL; j++) + for (int i = 0; i < NE; i++) sum += s[i]; usiter = t.restart(); } @@ -106,13 +103,13 @@ int main(int argc, char **argv) { { t.restart(); - QListSet<int> s; - for (int i=0;i<NE;i++) + QListSet< int > s; + for (int i = 0; i < NE; i++) s.insert(i); usins = t.restart(); - sum = 0; - for (int j=0;j<SL;j++) - foreach(int v, s.l) + sum = 0; + for (int j = 0; j < SL; j++) + foreach (int v, s.l) sum += v; usiter = t.restart(); } diff --git a/src/tests/Emit.cpp b/src/tests/Emit.cpp index 533c31fda..81417573c 100644 --- a/src/tests/Emit.cpp +++ b/src/tests/Emit.cpp @@ -1,100 +1,92 @@ +#include "Timer.h" #include <QtCore> -#include <boost/signals.hpp> #include <boost/bind.hpp> -#include "Timer.h" +#include <boost/signals.hpp> class Slotter : public QObject { - Q_OBJECT; - public: - Slotter(QObject *p = nullptr) : QObject(p) {}; - public Q_SLOTS: - virtual void slottest(int &res) { - res+= 1; - }; + Q_OBJECT; + +public: + Slotter(QObject *p = nullptr) : QObject(p){}; +public Q_SLOTS: + virtual void slottest(int &res) { res += 1; }; }; class Emitter : public QObject { - Q_OBJECT; - public: - Slotter *s; - Emitter(Slotter *s) : QObject(s) { - this->s = s; - }; - - boost::signal< void(int &) > bsig; - Q_SIGNALS: - void sig(int &); - public Q_SLOTS: - void emittest(int &val) { - Q_EMIT sig(val); - }; - void directtest(int &val) { - s->slottest(val); - }; - void boosttest(int &val) { - bsig(val); - } + Q_OBJECT; + +public: + Slotter *s; + Emitter(Slotter *s) : QObject(s) { this->s = s; }; + + boost::signal< void(int &) > bsig; +Q_SIGNALS: + void sig(int &); +public Q_SLOTS: + void emittest(int &val) { Q_EMIT sig(val); }; + void directtest(int &val) { s->slottest(val); }; + void boosttest(int &val) { bsig(val); } }; int main(int argc, char **argv) { QCoreApplication a(argc, argv); Timer t; - Slotter *s = new Slotter(); + Slotter *s = new Slotter(); Slotter *s2 = new Slotter(); - Emitter *e = new Emitter(s); + Emitter *e = new Emitter(s); int v; v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) s->slottest(v); printf("Raw : %8lld %d\n", t.elapsed(), v); v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) e->directtest(v); printf("Direct: %8lld %d\n", t.elapsed(), v); v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) e->emittest(v); printf("NoSig : %8lld %d\n", t.elapsed(), v); QObject::connect(e, SIGNAL(sig(int &)), s, SLOT(slottest(int &))); v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) e->emittest(v); printf("Signal: %8lld %d\n", t.elapsed(), v); QObject::connect(e, SIGNAL(sig(int &)), s2, SLOT(slottest(int &))); v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) e->emittest(v); printf("2Slots: %8lld %d\n", t.elapsed(), v); v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) e->boosttest(v); printf("BNoSig: %8lld %d\n", t.elapsed(), v); e->bsig.connect(boost::bind(&Slotter::slottest, s, _1)); v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) e->boosttest(v); printf("Boost: %8lld %d\n", t.elapsed(), v); e->bsig.connect(boost::bind(&Slotter::slottest, s2, _1)); v = 0; t.restart(); - for (int i=0;i<1000000;++i) + for (int i = 0; i < 1000000; ++i) e->boosttest(v); printf("2Boost: %8lld %d\n", t.elapsed(), v); } diff --git a/src/tests/Hash.cpp b/src/tests/Hash.cpp index ad6b0713a..a82408177 100644 --- a/src/tests/Hash.cpp +++ b/src/tests/Hash.cpp @@ -4,46 +4,42 @@ #define ITER 100000 -typedef QPair<quint64,int> tr; +typedef QPair< quint64, int > tr; -template<class T> -class SpeedTest { - public: - QList<T> list; +template< class T > class SpeedTest { +public: + QList< T > list; - SpeedTest() { - } + SpeedTest() {} - void add(T v) { - list << v; - } + void add(T v) { list << v; } - tr testres(T v) { - int val = 0; - Timer t; - t.restart(); - for (int i=0;i<ITER;i++) { - if (list.contains(v)) - val++; - } - return tr(t.elapsed(), val); + tr testres(T v) { + int val = 0; + Timer t; + t.restart(); + for (int i = 0; i < ITER; i++) { + if (list.contains(v)) + val++; } + return tr(t.elapsed(), val); + } }; int main(int argc, char **argv) { QCoreApplication a(argc, argv); - QSet<int> set; - SpeedTest<QVariant> stv; - SpeedTest<int> sti; - SpeedTest<QList<QVariant> > stl; - SpeedTest<QVariant> stvl; + QSet< int > set; + SpeedTest< QVariant > stv; + SpeedTest< int > sti; + SpeedTest< QList< QVariant > > stl; + SpeedTest< QVariant > stvl; - for (int i=0;i<300;i++) { + for (int i = 0; i < 300; i++) { set.insert(i); QVariant v = i; - QList<QVariant> ql; + QList< QVariant > ql; ql << v; QVariant vl = QVariant(ql); @@ -53,9 +49,9 @@ int main(int argc, char **argv) { stvl.add(vl); } - int i = 397; + int i = 397; QVariant v = i; - QList<QVariant> ql; + QList< QVariant > ql; ql << v; QVariant vl = QVariant(ql); @@ -63,10 +59,10 @@ int main(int argc, char **argv) { tr t; int val = 0; tt.restart(); - for (int i=0;i<ITER;i++) + for (int i = 0; i < ITER; i++) if (set.contains(i)) val++; - t.first = tt.elapsed(); + t.first = tt.elapsed(); t.second = val; qWarning("set: %llu", t.first); @@ -81,7 +77,6 @@ int main(int argc, char **argv) { t = stvl.testres(vl); qWarning("vls: %llu", t.first / ITER); - } #include "Hash.moc" diff --git a/src/tests/Lock.cpp b/src/tests/Lock.cpp index 22b83d0ea..48edf602b 100644 --- a/src/tests/Lock.cpp +++ b/src/tests/Lock.cpp @@ -12,14 +12,14 @@ // one timeslice. #define ITER 100000000 -typedef QPair<quint64,int> tr; +typedef QPair< quint64, int > tr; class SillyLock { - public: - int counter; - SillyLock(); - void lock(); - void unlock(); +public: + int counter; + SillyLock(); + void lock(); + void unlock(); }; SillyLock::SillyLock() { @@ -41,11 +41,11 @@ void SillyLock::unlock() { } class PosixLock { - public: - pthread_mutex_t m; - PosixLock(); - void lock(); - void unlock(); +public: + pthread_mutex_t m; + PosixLock(); + void lock(); + void unlock(); }; PosixLock::PosixLock() { @@ -60,23 +60,21 @@ void PosixLock::unlock() { pthread_mutex_unlock(&m); } -template<class T> -class SpeedTest { - public: - T &lock; +template< class T > class SpeedTest { +public: + T &lock; - SpeedTest(T &l) : lock(l) { - } + SpeedTest(T &l) : lock(l) {} - quint64 test() { - Timer t; - t.restart(); - for (int i=0;i<ITER;i++) { - lock.lock(); - lock.unlock(); - } - return t.elapsed(); + quint64 test() { + Timer t; + t.restart(); + for (int i = 0; i < ITER; i++) { + lock.lock(); + lock.unlock(); } + return t.elapsed(); + } }; int main(int argc, char **argv) { @@ -87,10 +85,10 @@ int main(int argc, char **argv) { SillyLock sl; PosixLock pl; - SpeedTest<QMutex> stqm(qm); - SpeedTest<QMutex> stqmr(qmr); - SpeedTest<SillyLock> stsl(sl); - SpeedTest<PosixLock> stpl(pl); + SpeedTest< QMutex > stqm(qm); + SpeedTest< QMutex > stqmr(qmr); + SpeedTest< SillyLock > stsl(sl); + SpeedTest< PosixLock > stpl(pl); quint64 elapsed; diff --git a/src/tests/OverlayTest.cpp b/src/tests/OverlayTest.cpp index f909af245..56152c6c3 100644 --- a/src/tests/OverlayTest.cpp +++ b/src/tests/OverlayTest.cpp @@ -8,51 +8,52 @@ #include "Timer.h" #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include <QtCore> -#include <QtNetwork> #include <QtGui> +#include <QtNetwork> #include <ctime> class OverlayWidget : public QWidget { - Q_OBJECT - - protected: - QImage img; - OverlayMsg om; - QLocalSocket *qlsSocket; - SharedMemory2 *smMem; - QTimer *qtTimer; - QRect qrActive; - QTime qtWall; - - unsigned int iFrameCount; - int iLastFpsUpdate; - - unsigned int uiWidth, uiHeight; - - void resizeEvent(QResizeEvent *); - void paintEvent(QPaintEvent *); - void init(const QSize &); - void detach(); - - void keyPressEvent(QKeyEvent *); - protected slots: - void connected(); - void disconnected(); - void readyRead(); - void error(QLocalSocket::LocalSocketError); - void update(); - public: - OverlayWidget(QWidget *p = nullptr); + Q_OBJECT + +protected: + QImage img; + OverlayMsg om; + QLocalSocket *qlsSocket; + SharedMemory2 *smMem; + QTimer *qtTimer; + QRect qrActive; + QTime qtWall; + + unsigned int iFrameCount; + int iLastFpsUpdate; + + unsigned int uiWidth, uiHeight; + + void resizeEvent(QResizeEvent *); + void paintEvent(QPaintEvent *); + void init(const QSize &); + void detach(); + + void keyPressEvent(QKeyEvent *); +protected slots: + void connected(); + void disconnected(); + void readyRead(); + void error(QLocalSocket::LocalSocketError); + void update(); + +public: + OverlayWidget(QWidget *p = nullptr); }; OverlayWidget::OverlayWidget(QWidget *p) : QWidget(p) { qlsSocket = nullptr; - smMem = nullptr; + smMem = nullptr; uiWidth = uiHeight = 0; setFocusPolicy(Qt::StrongFocus); @@ -72,20 +73,21 @@ void OverlayWidget::keyPressEvent(QKeyEvent *evt) { void OverlayWidget::resizeEvent(QResizeEvent *evt) { QWidget::resizeEvent(evt); - if (! img.isNull()) + if (!img.isNull()) img = img.scaled(evt->size().width(), evt->size().height()); init(evt->size()); } void OverlayWidget::paintEvent(QPaintEvent *) { - if (! qlsSocket || qlsSocket->state() == QLocalSocket::UnconnectedState) { + if (!qlsSocket || qlsSocket->state() == QLocalSocket::UnconnectedState) { detach(); qlsSocket = new QLocalSocket(this); connect(qlsSocket, SIGNAL(connected()), this, SLOT(connected())); connect(qlsSocket, SIGNAL(disconnected()), this, SLOT(disconnected())); connect(qlsSocket, SIGNAL(readyRead()), this, SLOT(readyRead())); - connect(qlsSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(error(QLocalSocket::LocalSocketError))); + connect(qlsSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, + SLOT(error(QLocalSocket::LocalSocketError))); #ifdef Q_OS_WIN qlsSocket->connectToServer(QLatin1String("MumbleOverlayPipe")); #else @@ -94,7 +96,7 @@ void OverlayWidget::paintEvent(QPaintEvent *) { } QPainter painter(this); - painter.fillRect(0, 0, width(), height(), QColor(128,0,128)); + painter.fillRect(0, 0, width(), height(), QColor(128, 0, 128)); painter.setClipRect(qrActive); painter.drawImage(0, 0, img); } @@ -103,14 +105,14 @@ void OverlayWidget::init(const QSize &sz) { qWarning() << "Init" << sz.width() << sz.height(); qtWall.start(); - iFrameCount = 0; + iFrameCount = 0; iLastFpsUpdate = 0; OverlayMsg m; - m.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - m.omh.uiType = OVERLAY_MSGTYPE_INIT; - m.omh.iLength = sizeof(OverlayMsgInit); - m.omi.uiWidth = sz.width(); + m.omh.uiMagic = OVERLAY_MAGIC_NUMBER; + m.omh.uiType = OVERLAY_MSGTYPE_INIT; + m.omh.iLength = sizeof(OverlayMsgInit); + m.omi.uiWidth = sz.width(); m.omi.uiHeight = sz.height(); if (qlsSocket && qlsSocket->state() == QLocalSocket::ConnectedState) @@ -135,7 +137,7 @@ void OverlayWidget::connected() { OverlayMsg m; m.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - m.omh.uiType = OVERLAY_MSGTYPE_PID; + m.omh.uiType = OVERLAY_MSGTYPE_PID; m.omh.iLength = sizeof(OverlayMsgPid); #ifdef Q_OS_WIN m.omp.pid = GetCurrentProcessId(); @@ -152,7 +154,7 @@ void OverlayWidget::connected() { void OverlayWidget::disconnected() { qWarning() << "disconnected"; - QLocalSocket *qls = qobject_cast<QLocalSocket *>(sender()); + QLocalSocket *qls = qobject_cast< QLocalSocket * >(sender()); if (qls == qlsSocket) { detach(); } @@ -166,21 +168,21 @@ void OverlayWidget::error(QLocalSocket::LocalSocketError) { void OverlayWidget::update() { ++iFrameCount; - clock_t t = clock(); - float elapsed = static_cast<float>(qtWall.elapsed() - iLastFpsUpdate) / 1000.0f; + clock_t t = clock(); + float elapsed = static_cast< float >(qtWall.elapsed() - iLastFpsUpdate) / 1000.0f; if (elapsed > OVERLAY_FPS_INTERVAL) { struct OverlayMsg om; om.omh.uiMagic = OVERLAY_MAGIC_NUMBER; - om.omh.uiType = OVERLAY_MSGTYPE_FPS; + om.omh.uiType = OVERLAY_MSGTYPE_FPS; om.omh.iLength = sizeof(struct OverlayMsgFps); - om.omf.fps = static_cast<int>(static_cast<float>(iFrameCount) / elapsed); + om.omf.fps = static_cast< int >(static_cast< float >(iFrameCount) / elapsed); if (qlsSocket && qlsSocket->state() == QLocalSocket::ConnectedState) { - qlsSocket->write(reinterpret_cast<char*>(&om), sizeof(OverlayMsgHeader) + om.omh.iLength); + qlsSocket->write(reinterpret_cast< char * >(&om), sizeof(OverlayMsgHeader) + om.omh.iLength); } - iFrameCount = 0; + iFrameCount = 0; iLastFpsUpdate = 0; qtWall.start(); } @@ -189,7 +191,7 @@ void OverlayWidget::update() { } void OverlayWidget::readyRead() { - QLocalSocket *qls = qobject_cast<QLocalSocket *>(sender()); + QLocalSocket *qls = qobject_cast< QLocalSocket * >(sender()); if (qls != qlsSocket) return; @@ -200,8 +202,9 @@ void OverlayWidget::readyRead() { if (ready < sizeof(OverlayMsgHeader)) break; else { - qlsSocket->read(reinterpret_cast<char *>(om.headerbuffer), sizeof(OverlayMsgHeader)); - if ((om.omh.uiMagic != OVERLAY_MAGIC_NUMBER) || (om.omh.iLength < 0) || (om.omh.iLength > sizeof(OverlayMsgShmem))) { + qlsSocket->read(reinterpret_cast< char * >(om.headerbuffer), sizeof(OverlayMsgHeader)); + if ((om.omh.uiMagic != OVERLAY_MAGIC_NUMBER) || (om.omh.iLength < 0) + || (om.omh.iLength > sizeof(OverlayMsgShmem))) { detach(); return; } @@ -221,53 +224,50 @@ void OverlayWidget::readyRead() { switch (om.omh.uiType) { case OVERLAY_MSGTYPE_SHMEM: { - OverlayMsgShmem *oms = & om.oms; - QString key = QString::fromUtf8(oms->a_cName, length); - qWarning() << "SHMAT" << key; - if (smMem) - delete smMem; - smMem = new SharedMemory2(this, width() * height() * 4, key); - if (! smMem->data()) { - qWarning() << "SHMEM FAIL"; - delete smMem; - smMem = nullptr; - } else { - qWarning() << "SHMEM" << smMem->size(); - } + OverlayMsgShmem *oms = &om.oms; + QString key = QString::fromUtf8(oms->a_cName, length); + qWarning() << "SHMAT" << key; + if (smMem) + delete smMem; + smMem = new SharedMemory2(this, width() * height() * 4, key); + if (!smMem->data()) { + qWarning() << "SHMEM FAIL"; + delete smMem; + smMem = nullptr; + } else { + qWarning() << "SHMEM" << smMem->size(); } - break; + } break; case OVERLAY_MSGTYPE_BLIT: { - OverlayMsgBlit *omb = & om.omb; - length -= sizeof(OverlayMsgBlit); - - qWarning() << "BLIT" << omb->x << omb->y << omb->w << omb->h; + OverlayMsgBlit *omb = &om.omb; + length -= sizeof(OverlayMsgBlit); - if (! smMem) - break; + qWarning() << "BLIT" << omb->x << omb->y << omb->w << omb->h; - if (((omb->x + omb->w) > img.width()) || - ((omb->y + omb->h) > img.height())) - break; + if (!smMem) + break; + if (((omb->x + omb->w) > img.width()) || ((omb->y + omb->h) > img.height())) + break; - for (int y = 0; y < omb->h; ++y) { - unsigned char *src = reinterpret_cast<unsigned char *>(smMem->data()) + 4 * (width() * (y + omb->y) + omb->x); - unsigned char *dst = img.scanLine(y + omb->y) + omb->x * 4; - memcpy(dst, src, omb->w * 4); - } - update(); + for (int y = 0; y < omb->h; ++y) { + unsigned char *src = + reinterpret_cast< unsigned char * >(smMem->data()) + 4 * (width() * (y + omb->y) + omb->x); + unsigned char *dst = img.scanLine(y + omb->y) + omb->x * 4; + memcpy(dst, src, omb->w * 4); } - break; + + update(); + } break; case OVERLAY_MSGTYPE_ACTIVE: { - OverlayMsgActive *oma = & om.oma; + OverlayMsgActive *oma = &om.oma; - qWarning() << "ACTIVE" << oma->x << oma->y << oma->w << oma->h; + qWarning() << "ACTIVE" << oma->x << oma->y << oma->w << oma->h; - qrActive = QRect(oma->x, oma->y, oma->w, oma->h); - update(); - }; - break; + qrActive = QRect(oma->x, oma->y, oma->w, oma->h); + update(); + }; break; default: break; } @@ -280,12 +280,13 @@ void OverlayWidget::readyRead() { } class TestWin : public QObject { - Q_OBJECT + Q_OBJECT + +protected: + QWidget *qw; - protected: - QWidget *qw; - public: - TestWin(); +public: + TestWin(); }; TestWin::TestWin() { diff --git a/src/tests/ProtoBuf.cpp b/src/tests/ProtoBuf.cpp index e5f7c5e2c..faa47081c 100644 --- a/src/tests/ProtoBuf.cpp +++ b/src/tests/ProtoBuf.cpp @@ -2,12 +2,12 @@ * Protobuf binding benchmarks (serialisation, deserialization, ...). */ -#include <QtCore> -#include <vector> -#include "Timer.h" #include "Message.h" #include "PacketDataStream.h" #include "ProtoBuf.pb.h" +#include "Timer.h" +#include <QtCore> +#include <vector> using namespace std; @@ -25,11 +25,11 @@ int main(int argc, char **argv) { int v; t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { MessageServerAuthenticate ma; - Message *m = &ma; - ma.uiSession = 1; - ma.iVersion = -1; + Message *m = &ma; + ma.uiSession = 1; + ma.iVersion = -1; ma.qsUsername = n; ma.qsPassword = p; @@ -44,7 +44,7 @@ int main(int argc, char **argv) { printf("MsgBased : %8lld %d\n", t.elapsed(), v); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { Authenticate apb; apb.set_version(-1); apb.set_session(1); @@ -54,7 +54,7 @@ int main(int argc, char **argv) { std::string str; Universal u; - * (u.mutable_authenticate()) = apb; + *(u.mutable_authenticate()) = apb; u.SerializeToString(&str); u.ParseFromString(str); @@ -70,7 +70,7 @@ int main(int argc, char **argv) { printf("ProtoBuf : %8lld %d\n", t.elapsed(), v); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { Universal u; Authenticate *apb = u.mutable_authenticate(); apb->set_version(-1); @@ -96,7 +96,7 @@ int main(int argc, char **argv) { std::string sp = p.toStdString(); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { Universal u; Authenticate *apb = u.mutable_authenticate(); apb->set_version(-1); @@ -119,7 +119,7 @@ int main(int argc, char **argv) { printf("PBStdStr : %8lld %d\n", t.elapsed(), v); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { Universal u; Authenticate *apb = u.mutable_authenticate(); apb->set_version(-1); @@ -142,7 +142,7 @@ int main(int argc, char **argv) { printf("PBArray : %8lld %d\n", t.elapsed(), v); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { Universal u; Authenticate *apb = u.MutableExtension(extauth); apb->set_version(-1); @@ -165,7 +165,7 @@ int main(int argc, char **argv) { printf("PBExt : %8lld %d\n", t.elapsed(), v); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { Authenticate apb; apb.set_version(-1); apb.set_session(1); @@ -185,7 +185,7 @@ int main(int argc, char **argv) { t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { LongUniversal u; Authenticate *apb = u.mutable_z(); apb->set_version(-1); @@ -210,7 +210,7 @@ int main(int argc, char **argv) { LongUniversal u; const LongUniversal::Reflection *r = u.GetReflection(); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { u.Clear(); Authenticate *apb = u.mutable_z(); @@ -219,20 +219,22 @@ int main(int argc, char **argv) { apb->set_name(n.toStdString()); apb->set_pw(p.toStdString()); -// std::string str; + // std::string str; v = u.ByteSize(); u.SerializeToArray(buff, v); u.Clear(); u.ParseFromArray(buff, v); -// u.DiscardUnknownFields(); + // u.DiscardUnknownFields(); -// vector<const google::protobuf::FieldDescriptor *> v; -// r->ListFields(u, &v); -// printf("%d\n", v.size()); + // vector<const google::protobuf::FieldDescriptor *> v; + // r->ListFields(u, &v); + // printf("%d\n", v.size()); - if (u.has_a() || u.has_b() || u.has_c() || u.has_d() || u.has_e() || u.has_f() || u.has_g() || u.has_h() || u.has_i() || u.has_j() || u.has_k() || u.has_l() || u.has_m() || u.has_n() || u.has_o() || u.has_p() || u.has_q()) + if (u.has_a() || u.has_b() || u.has_c() || u.has_d() || u.has_e() || u.has_f() || u.has_g() || u.has_h() + || u.has_i() || u.has_j() || u.has_k() || u.has_l() || u.has_m() || u.has_n() || u.has_o() || u.has_p() + || u.has_q()) continue; @@ -246,7 +248,7 @@ int main(int argc, char **argv) { printf("PBCache : %8lld %d\n", t.elapsed(), v); t.restart(); - for (int i=0;i<1000000;++i) { + for (int i = 0; i < 1000000; ++i) { QString nn = QString::fromStdString(n.toStdString()); QString np = QString::fromStdString(p.toStdString()); } diff --git a/src/tests/Resample.cpp b/src/tests/Resample.cpp index 56a9d7f82..909b62554 100644 --- a/src/tests/Resample.cpp +++ b/src/tests/Resample.cpp @@ -3,7 +3,7 @@ */ #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #endif #include "Timer.h" @@ -24,7 +24,7 @@ int main(int argc, char **argv) { ippSetNumThreads(1); #ifdef Q_OS_WIN - if (!SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS)) + if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS)) qWarning("Application: Failed to set priority!"); #endif @@ -32,10 +32,10 @@ int main(int argc, char **argv) { SpeexResamplerState *srs; - int iMicFreq = 44100; + int iMicFreq = 44100; int iSampleRate = 48000; - int iFrameSize = iSampleRate / 100; - int err = 0; + int iFrameSize = iSampleRate / 100; + int err = 0; srs = speex_resampler_init(1, iMicFreq, iSampleRate, 3, &err); @@ -43,14 +43,14 @@ int main(int argc, char **argv) { qWarning() << iMicFreq << iSampleRate << iFrameSize << iMicLength; - float *pfInput = new float[iMicLength]; + float *pfInput = new float[iMicLength]; float *pfOutput = new float[iFrameSize]; - for (int i=0;i<iMicLength;++i) { + for (int i = 0; i < iMicLength; ++i) { pfInput[i] = sinf((M_PI * i * 20) / iMicLength); } - for (int i=0;i<iFrameSize;++i) + for (int i = 0; i < iFrameSize; ++i) pfOutput[i] = 0; qWarning() << "speex resampler latency: " << speex_resampler_get_input_latency(srs); @@ -58,8 +58,8 @@ int main(int argc, char **argv) { Timer t; - for (int i=0;i<ITER;++i) { - spx_uint32_t inlen = iMicLength; + for (int i = 0; i < ITER; ++i) { + spx_uint32_t inlen = iMicLength; spx_uint32_t outlen = iFrameSize; speex_resampler_process_float(srs, 0, pfInput, &inlen, pfOutput, &outlen); } @@ -71,35 +71,35 @@ int main(int argc, char **argv) { float min = 0.0; float max = 0.0; - for (int i=0;i<iFrameSize;++i) { + for (int i = 0; i < iFrameSize; ++i) { min = qMin(min, pfOutput[i]); max = qMax(max, pfOutput[i]); } qWarning() << "Speex bounds" << min << max; - delete [] pfOutput; + delete[] pfOutput; - int history=24; + int history = 24; int lastread = history; - double time = history; - int olen = 0; + double time = history; + int olen = 0; - float *inBuf = ippsMalloc_32f(iMicLength+history*2+2); - ippsZero_32f(inBuf, iMicLength+history*2+2); + float *inBuf = ippsMalloc_32f(iMicLength + history * 2 + 2); + ippsZero_32f(inBuf, iMicLength + history * 2 + 2); - pfOutput = ippsMalloc_32f(iFrameSize+2); + pfOutput = ippsMalloc_32f(iFrameSize + 2); - for (int i=0;i<iFrameSize;++i) + for (int i = 0; i < iFrameSize; ++i) pfOutput[i] = 0; IppsResamplingPolyphaseFixed_32f *pSpec = nullptr; - ippsResamplePolyphaseFixedInitAlloc_32f(&pSpec, iMicFreq, iSampleRate, 2*history, 0.90f, 8.0f, ippAlgHintFast); + ippsResamplePolyphaseFixedInitAlloc_32f(&pSpec, iMicFreq, iSampleRate, 2 * history, 0.90f, 8.0f, ippAlgHintFast); t.restart(); - for (int i=0;i<ITER;++i) { + for (int i = 0; i < ITER; ++i) { ippsCopy_32f(pfInput, inBuf + history, iMicLength); ippsResamplePolyphaseFixed_32f(pSpec, inBuf, iMicLength, pfOutput, .99f, &time, &olen); @@ -115,14 +115,14 @@ int main(int argc, char **argv) { min = 0.0; max = 0.0; - for (int i=0;i<iFrameSize;++i) { + for (int i = 0; i < iFrameSize; ++i) { min = qMin(min, pfOutput[i]); max = qMax(max, pfOutput[i]); } qWarning() << "IPP bounds" << min << max; - delete [] pfInput; + delete[] pfInput; return 0; } diff --git a/src/tests/TestCrypt/TestCrypt.cpp b/src/tests/TestCrypt/TestCrypt.cpp index 2eb9e3e8c..abc1ec370 100644 --- a/src/tests/TestCrypt/TestCrypt.cpp +++ b/src/tests/TestCrypt/TestCrypt.cpp @@ -6,23 +6,23 @@ #include <QtCore> #include <QtTest> -#include <string> #include "SSL.h" #include "Timer.h" -#include "crypto/CryptStateOCB2.h" #include "Utils.h" +#include "crypto/CryptStateOCB2.h" +#include <string> class TestCrypt : public QObject { - Q_OBJECT - private slots: - void initTestCase(); - void cleanupTestCase(); - void testvectors(); - void authcrypt(); - void xexstarAttack(); - void ivrecovery(); - void reverserecovery(); - void tamper(); + Q_OBJECT +private slots: + void initTestCase(); + void cleanupTestCase(); + void testvectors(); + void authcrypt(); + void xexstarAttack(); + void ivrecovery(); + void reverserecovery(); + void tamper(); }; void TestCrypt::initTestCase() { @@ -40,7 +40,7 @@ void TestCrypt::reverserecovery() { // For our testcase, we're going to FORCE iv char encrypt_iv[AES_BLOCK_SIZE]; memset(encrypt_iv, 0x55, AES_BLOCK_SIZE); - enc.setEncryptIV(std::string(reinterpret_cast<const char*>(encrypt_iv), AES_BLOCK_SIZE)); + enc.setEncryptIV(std::string(reinterpret_cast< const char * >(encrypt_iv), AES_BLOCK_SIZE)); dec.setKey(enc.getRawKey(), enc.getDecryptIV(), enc.getEncryptIV()); unsigned char secret[10] = "abcdefghi"; @@ -69,24 +69,24 @@ void TestCrypt::reverserecovery() { int i; - for (i=0;i<128;i++) + for (i = 0; i < 128; i++) enc.encrypt(secret, crypted[i], 10); - for (i=0;i<30;i++) - QVERIFY(dec.decrypt(crypted[127-i], decr, 14)); - for (;i<128;i++) - QVERIFY(!dec.decrypt(crypted[127-i], decr, 14)); - for (i=0;i<30;i++) - QVERIFY(!dec.decrypt(crypted[127-i], decr, 14)); + for (i = 0; i < 30; i++) + QVERIFY(dec.decrypt(crypted[127 - i], decr, 14)); + for (; i < 128; i++) + QVERIFY(!dec.decrypt(crypted[127 - i], decr, 14)); + for (i = 0; i < 30; i++) + QVERIFY(!dec.decrypt(crypted[127 - i], decr, 14)); // Extensive replay attack test - for (i=0;i<512;i++) + for (i = 0; i < 512; i++) enc.encrypt(secret, crypted[i], 10); - for (i=0;i<512;i++) + for (i = 0; i < 512; i++) QVERIFY(dec.decrypt(crypted[i], decr, 14)); - for (i=0;i<512;i++) + for (i = 0; i < 512; i++) QVERIFY(!dec.decrypt(crypted[i], decr, 14)); } @@ -97,7 +97,7 @@ void TestCrypt::ivrecovery() { // For our testcase, we're going to FORCE iv char encrypt_iv[AES_BLOCK_SIZE]; memset(encrypt_iv, 0x55, AES_BLOCK_SIZE); - enc.setEncryptIV(std::string(reinterpret_cast<const char*>(encrypt_iv), AES_BLOCK_SIZE)); + enc.setEncryptIV(std::string(reinterpret_cast< const char * >(encrypt_iv), AES_BLOCK_SIZE)); dec.setKey(enc.getRawKey(), enc.getDecryptIV(), enc.getEncryptIV()); unsigned char secret[10] = "abcdefghi"; @@ -109,21 +109,21 @@ void TestCrypt::ivrecovery() { // Can decrypt. QVERIFY(dec.decrypt(crypted, decr, 14)); // .. correctly. - QVERIFY(memcmp(secret, decr, 10)==0); + QVERIFY(memcmp(secret, decr, 10) == 0); // But will refuse to reuse same IV. - QVERIFY(! dec.decrypt(crypted, decr, 14)); + QVERIFY(!dec.decrypt(crypted, decr, 14)); // Recover from lost packet. - for (int i=0;i<16;i++) + for (int i = 0; i < 16; i++) enc.encrypt(secret, crypted, 10); QVERIFY(dec.decrypt(crypted, decr, 14)); // Wraparound. - for (int i=0;i<128;i++) { + for (int i = 0; i < 128; i++) { dec.uiLost = 0; - for (int j=0;j<15;j++) + for (int j = 0; j < 15; j++) enc.encrypt(secret, crypted, 10); QVERIFY(dec.decrypt(crypted, decr, 14)); QCOMPARE(dec.uiLost, 14U); @@ -132,10 +132,10 @@ void TestCrypt::ivrecovery() { QVERIFY(enc.getEncryptIV() == dec.getDecryptIV()); // Wrap too far - for (int i=0;i<257;i++) + for (int i = 0; i < 257; i++) enc.encrypt(secret, crypted, 10); - QVERIFY(! dec.decrypt(crypted, decr, 14)); + QVERIFY(!dec.decrypt(crypted, decr, 14)); // Sync it dec.setDecryptIV(enc.getEncryptIV()); @@ -146,47 +146,53 @@ void TestCrypt::ivrecovery() { void TestCrypt::testvectors() { // Test vectors are from draft-krovetz-ocb-00.txt - const unsigned char rawkey[AES_BLOCK_SIZE] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}; + const unsigned char rawkey[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; CryptStateOCB2 cs; - std::string rawkey_str = std::string(reinterpret_cast<const char*>(rawkey), AES_BLOCK_SIZE); + std::string rawkey_str = std::string(reinterpret_cast< const char * >(rawkey), AES_BLOCK_SIZE); cs.setKey(rawkey_str, rawkey_str, rawkey_str); unsigned char tag[16]; QVERIFY(cs.ocb_encrypt(nullptr, nullptr, 0, rawkey, tag)); - const unsigned char blanktag[AES_BLOCK_SIZE] = {0xBF,0x31,0x08,0x13,0x07,0x73,0xAD,0x5E,0xC7,0x0E,0xC6,0x9E,0x78,0x75,0xA7,0xB0}; - for (int i=0;i<AES_BLOCK_SIZE;i++) + const unsigned char blanktag[AES_BLOCK_SIZE] = { 0xBF, 0x31, 0x08, 0x13, 0x07, 0x73, 0xAD, 0x5E, + 0xC7, 0x0E, 0xC6, 0x9E, 0x78, 0x75, 0xA7, 0xB0 }; + for (int i = 0; i < AES_BLOCK_SIZE; i++) QCOMPARE(tag[i], blanktag[i]); unsigned char source[40]; unsigned char crypt[40]; - for (int i=0;i<40;i++) - source[i]=i; + for (int i = 0; i < 40; i++) + source[i] = i; QVERIFY(cs.ocb_encrypt(source, crypt, 40, rawkey, tag)); - const unsigned char longtag[AES_BLOCK_SIZE] = {0x9D,0xB0,0xCD,0xF8,0x80,0xF7,0x3E,0x3E,0x10,0xD4,0xEB,0x32,0x17,0x76,0x66,0x88}; - const unsigned char crypted[40] = {0xF7,0x5D,0x6B,0xC8,0xB4,0xDC,0x8D,0x66,0xB8,0x36,0xA2,0xB0,0x8B,0x32,0xA6,0x36,0x9F,0x1C,0xD3,0xC5,0x22,0x8D,0x79,0xFD, - 0x6C,0x26,0x7F,0x5F,0x6A,0xA7,0xB2,0x31,0xC7,0xDF,0xB9,0xD5,0x99,0x51,0xAE,0x9C - }; - - for (int i=0;i<AES_BLOCK_SIZE;i++) + const unsigned char longtag[AES_BLOCK_SIZE] = { 0x9D, 0xB0, 0xCD, 0xF8, 0x80, 0xF7, 0x3E, 0x3E, + 0x10, 0xD4, 0xEB, 0x32, 0x17, 0x76, 0x66, 0x88 }; + const unsigned char crypted[40] = { 0xF7, 0x5D, 0x6B, 0xC8, 0xB4, 0xDC, 0x8D, 0x66, 0xB8, 0x36, + 0xA2, 0xB0, 0x8B, 0x32, 0xA6, 0x36, 0x9F, 0x1C, 0xD3, 0xC5, + 0x22, 0x8D, 0x79, 0xFD, 0x6C, 0x26, 0x7F, 0x5F, 0x6A, 0xA7, + 0xB2, 0x31, 0xC7, 0xDF, 0xB9, 0xD5, 0x99, 0x51, 0xAE, 0x9C }; + + for (int i = 0; i < AES_BLOCK_SIZE; i++) QCOMPARE(tag[i], longtag[i]); - for (int i=0;i<40;i++) + for (int i = 0; i < 40; i++) QCOMPARE(crypt[i], crypted[i]); } void TestCrypt::authcrypt() { - for (int len=0;len<128;len++) { - const unsigned char rawkey[AES_BLOCK_SIZE] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}; - const unsigned char nonce[AES_BLOCK_SIZE] = {0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00}; - std::string rawkey_str = std::string(reinterpret_cast<const char*>(rawkey), AES_BLOCK_SIZE); - std::string nonce_str = std::string(reinterpret_cast<const char*>(nonce), AES_BLOCK_SIZE); + for (int len = 0; len < 128; len++) { + const unsigned char rawkey[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; + const unsigned char nonce[AES_BLOCK_SIZE] = { 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 }; + std::string rawkey_str = std::string(reinterpret_cast< const char * >(rawkey), AES_BLOCK_SIZE); + std::string nonce_str = std::string(reinterpret_cast< const char * >(nonce), AES_BLOCK_SIZE); CryptStateOCB2 cs; cs.setKey(rawkey_str, nonce_str, nonce_str); STACKVAR(unsigned char, src, len); - for (int i=0;i<len;i++) + for (int i = 0; i < len; i++) src[i] = (i + 1); unsigned char enctag[AES_BLOCK_SIZE]; @@ -197,20 +203,22 @@ void TestCrypt::authcrypt() { QVERIFY(cs.ocb_encrypt(src, encrypted, len, nonce, enctag)); QVERIFY(cs.ocb_decrypt(encrypted, decrypted, len, nonce, dectag)); - for (int i=0;i<AES_BLOCK_SIZE;i++) + for (int i = 0; i < AES_BLOCK_SIZE; i++) QCOMPARE(enctag[i], dectag[i]); - for (int i=0;i<len;i++) + for (int i = 0; i < len; i++) QCOMPARE(src[i], decrypted[i]); } } // Test prevention of the attack described in section 4.1 of https://eprint.iacr.org/2019/311 void TestCrypt::xexstarAttack() { - const unsigned char rawkey[AES_BLOCK_SIZE] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}; - const unsigned char nonce[AES_BLOCK_SIZE] = {0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00}; - std::string rawkey_str = std::string(reinterpret_cast<const char*>(rawkey), AES_BLOCK_SIZE); - std::string nonce_str = std::string(reinterpret_cast<const char*>(nonce), AES_BLOCK_SIZE); + const unsigned char rawkey[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; + const unsigned char nonce[AES_BLOCK_SIZE] = { 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 }; + std::string rawkey_str = std::string(reinterpret_cast< const char * >(rawkey), AES_BLOCK_SIZE); + std::string nonce_str = std::string(reinterpret_cast< const char * >(nonce), AES_BLOCK_SIZE); CryptStateOCB2 cs; cs.setKey(rawkey_str, nonce_str, nonce_str); @@ -246,26 +254,28 @@ void TestCrypt::xexstarAttack() { } void TestCrypt::tamper() { - const unsigned char rawkey[AES_BLOCK_SIZE] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}; - const unsigned char nonce[AES_BLOCK_SIZE] = {0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00}; - std::string rawkey_str = std::string(reinterpret_cast<const char*>(rawkey), AES_BLOCK_SIZE); - std::string nonce_str = std::string(reinterpret_cast<const char*>(nonce), AES_BLOCK_SIZE); + const unsigned char rawkey[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; + const unsigned char nonce[AES_BLOCK_SIZE] = { 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 }; + std::string rawkey_str = std::string(reinterpret_cast< const char * >(rawkey), AES_BLOCK_SIZE); + std::string nonce_str = std::string(reinterpret_cast< const char * >(nonce), AES_BLOCK_SIZE); CryptStateOCB2 cs; cs.setKey(rawkey_str, nonce_str, nonce_str); const unsigned char msg[] = "It was a funky funky town!"; - int len = sizeof(msg); + int len = sizeof(msg); - STACKVAR(unsigned char, encrypted, len+4); + STACKVAR(unsigned char, encrypted, len + 4); STACKVAR(unsigned char, decrypted, len); cs.encrypt(msg, encrypted, len); - for (int i=0;i<len*8;i++) { - encrypted[i/8] ^= 1 << (i % 8); - QVERIFY(! cs.decrypt(encrypted, decrypted, len+4)); - encrypted[i/8] ^= 1 << (i % 8); + for (int i = 0; i < len * 8; i++) { + encrypted[i / 8] ^= 1 << (i % 8); + QVERIFY(!cs.decrypt(encrypted, decrypted, len + 4)); + encrypted[i / 8] ^= 1 << (i % 8); } - QVERIFY(cs.decrypt(encrypted, decrypted, len+4)); + QVERIFY(cs.decrypt(encrypted, decrypted, len + 4)); } QTEST_MAIN(TestCrypt) diff --git a/src/tests/TestCryptographicHash/TestCryptographicHash.cpp b/src/tests/TestCryptographicHash/TestCryptographicHash.cpp index 90be99485..c1bfce51a 100644 --- a/src/tests/TestCryptographicHash/TestCryptographicHash.cpp +++ b/src/tests/TestCryptographicHash/TestCryptographicHash.cpp @@ -3,29 +3,29 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. +#include <QLatin1String> #include <QtCore> #include <QtTest> -#include <QLatin1String> #include "SSL.h" #include "crypto/CryptographicHash.h" class TestCryptographicHash : public QObject { - Q_OBJECT - private slots: - void initTestCase(); - void cleanupTestCase(); + Q_OBJECT +private slots: + void initTestCase(); + void cleanupTestCase(); - void sha1_data(); - void sha1(); + void sha1_data(); + void sha1(); - void sha256_data(); - void sha256(); + void sha256_data(); + void sha256(); - void staticHashVsObject(); - void multipleResultCalls(); - void addDataAfterResult(); + void staticHashVsObject(); + void multipleResultCalls(); + void addDataAfterResult(); }; void TestCryptographicHash::initTestCase() { @@ -55,15 +55,20 @@ static QByteArray normalizeHash(QByteArray buf) { } void TestCryptographicHash::sha1_data() { - QTest::addColumn<QString>("input"); - QTest::addColumn<QString>("expectedOutput"); + QTest::addColumn< QString >("input"); + QTest::addColumn< QString >("expectedOutput"); // First 4 SHA1 test vectors from http://www.di-mgt.com.au/sha_testvectors.html // ...The rest are a bit too excessive to put in a table-based test. - QTest::newRow("1") << QString(QLatin1String("abc")) << normalizeHash(QLatin1String("a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d")); - QTest::newRow("2") << QString(QLatin1String("")) << normalizeHash(QLatin1String("da39a3ee 5e6b4b0d 3255bfef 95601890 afd80709")); - QTest::newRow("3") << QString(QLatin1String("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) << normalizeHash(QLatin1String("84983e44 1c3bd26e baae4aa1 f95129e5 e54670f1")); - QTest::newRow("4") << QString(QLatin1String("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu")) << normalizeHash(QLatin1String("a49b2446 a02c645b f419f995 b6709125 3a04a259")); + QTest::newRow("1") << QString(QLatin1String("abc")) + << normalizeHash(QLatin1String("a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d")); + QTest::newRow("2") << QString(QLatin1String("")) + << normalizeHash(QLatin1String("da39a3ee 5e6b4b0d 3255bfef 95601890 afd80709")); + QTest::newRow("3") << QString(QLatin1String("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) + << normalizeHash(QLatin1String("84983e44 1c3bd26e baae4aa1 f95129e5 e54670f1")); + QTest::newRow("4") << QString(QLatin1String("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmn" + "opjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu")) + << normalizeHash(QLatin1String("a49b2446 a02c645b f419f995 b6709125 3a04a259")); } void TestCryptographicHash::sha1() { @@ -72,21 +77,29 @@ void TestCryptographicHash::sha1() { QByteArray outBuf = CryptographicHash::hash(input.toLatin1(), CryptographicHash::Sha1); QByteArray hexBuf = outBuf.toHex(); - QString output = QString::fromLatin1(hexBuf); + QString output = QString::fromLatin1(hexBuf); QCOMPARE(output, expectedOutput); } void TestCryptographicHash::sha256_data() { - QTest::addColumn<QString>("input"); - QTest::addColumn<QString>("expectedOutput"); + QTest::addColumn< QString >("input"); + QTest::addColumn< QString >("expectedOutput"); // First 4 SHA256 test vectors from http://www.di-mgt.com.au/sha_testvectors.html // ...The rest are a bit too excessive to put in a table-based test. - QTest::newRow("1") << QString(QLatin1String("abc")) << normalizeHash(QLatin1String("ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad")); - QTest::newRow("2") << QString(QLatin1String("")) << normalizeHash(QLatin1String("e3b0c442 98fc1c14 9afbf4c8 996fb924 27ae41e4 649b934c a495991b 7852b855")); - QTest::newRow("3") << QString(QLatin1String("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) << normalizeHash(QLatin1String("248d6a61 d20638b8 e5c02693 0c3e6039 a33ce459 64ff2167 f6ecedd4 19db06c1")); - QTest::newRow("4") << QString(QLatin1String("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu")) << normalizeHash(QLatin1String("cf5b16a7 78af8380 036ce59e 7b049237 0b249b11 e8f07a51 afac4503 7afee9d1")); + QTest::newRow("1") << QString(QLatin1String("abc")) + << normalizeHash( + QLatin1String("ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad")); + QTest::newRow("2") << QString(QLatin1String( + "")) << normalizeHash(QLatin1String("e3b0c442 98fc1c14 9afbf4c8 996fb924 27ae41e4 649b934c a495991b 7852b855")); + QTest::newRow("3") << QString(QLatin1String("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) + << normalizeHash( + QLatin1String("248d6a61 d20638b8 e5c02693 0c3e6039 a33ce459 64ff2167 f6ecedd4 19db06c1")); + QTest::newRow("4") << QString(QLatin1String("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmn" + "opjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu")) + << normalizeHash( + QLatin1String("cf5b16a7 78af8380 036ce59e 7b049237 0b249b11 e8f07a51 afac4503 7afee9d1")); } void TestCryptographicHash::sha256() { @@ -98,7 +111,7 @@ void TestCryptographicHash::sha256() { QVERIFY(!outBuf.isEmpty()); QByteArray hexBuf = outBuf.toHex(); - QString output = QString::fromLatin1(hexBuf); + QString output = QString::fromLatin1(hexBuf); QCOMPARE(output, expectedOutput); } @@ -128,7 +141,8 @@ void TestCryptographicHash::multipleResultCalls() { QVERIFY(!result2.isEmpty()); QVERIFY(!result3.isEmpty()); - QCOMPARE(result1.toHex(), normalizeHash(QByteArray("ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad"))); + QCOMPARE(result1.toHex(), + normalizeHash(QByteArray("ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad"))); QCOMPARE(result1, result2); QCOMPARE(result1, result3); } @@ -139,7 +153,8 @@ void TestCryptographicHash::addDataAfterResult() { QByteArray result1 = h.result(); - QCOMPARE(result1.toHex(), normalizeHash(QByteArray("ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad"))); + QCOMPARE(result1.toHex(), + normalizeHash(QByteArray("ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad"))); // Adding data after getting the result of a // CryptographicHash is an error. diff --git a/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp b/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp index ee1a2edd7..1c6dcd1d7 100644 --- a/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp +++ b/src/tests/TestCryptographicRandom/TestCryptographicRandom.cpp @@ -10,18 +10,18 @@ #include "crypto/CryptographicRandom.h" +#include <limits> #include <stdint.h> #include <stdlib.h> -#include <limits> class TestCryptographicRandom : public QObject { - Q_OBJECT - private slots: - void initTestCase(); - void cleanupTestCase(); - void fillBuffer(); - void uint32(); - void uniform(); + Q_OBJECT +private slots: + void initTestCase(); + void cleanupTestCase(); + void fillBuffer(); + void uint32(); + void uniform(); }; void TestCryptographicRandom::initTestCase() { @@ -48,7 +48,7 @@ void TestCryptographicRandom::fillBuffer() { const int buflen = 1000000; for (int i = 0; i < 10; i++) { - unsigned char *buf = reinterpret_cast<unsigned char *>(calloc(buflen, 1)); + unsigned char *buf = reinterpret_cast< unsigned char * >(calloc(buflen, 1)); CryptographicRandom::fillBuffer(buf, buflen); QVERIFY(verifyEntropy(buf, buflen)); free(buf); @@ -59,15 +59,15 @@ void TestCryptographicRandom::uint32() { const int buflen = 1000000; for (int i = 0; i < 10; i++) { - unsigned char *buf = reinterpret_cast<unsigned char *>(calloc(buflen, 1)); - int niter = buflen / sizeof(uint32_t); + unsigned char *buf = reinterpret_cast< unsigned char * >(calloc(buflen, 1)); + int niter = buflen / sizeof(uint32_t); for (int j = 0; j < niter; j++) { - int off = j * sizeof(uint32_t); + int off = j * sizeof(uint32_t); uint32_t val = CryptographicRandom::uint32(); - buf[off] = val & 0xff; - buf[off+1] = (val >> 8) & 0xff; - buf[off+2] = (val >> 16) & 0xff; - buf[off+3] = (val >> 24) & 0xff; + buf[off] = val & 0xff; + buf[off + 1] = (val >> 8) & 0xff; + buf[off + 2] = (val >> 16) & 0xff; + buf[off + 3] = (val >> 24) & 0xff; } QVERIFY(verifyEntropy(buf, buflen)); free(buf); diff --git a/src/tests/TestFFDHE/TestFFDHE.cpp b/src/tests/TestFFDHE/TestFFDHE.cpp index 4d1a4548a..926963ceb 100644 --- a/src/tests/TestFFDHE/TestFFDHE.cpp +++ b/src/tests/TestFFDHE/TestFFDHE.cpp @@ -7,22 +7,22 @@ #include <QtTest> #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) -# include <QtNetwork/QSslDiffieHellmanParameters> +# include <QtNetwork/QSslDiffieHellmanParameters> #endif -#include "SSL.h" #include "FFDHE.h" +#include "SSL.h" class TestFFDHE : public QObject { - Q_OBJECT - private slots: - void initTestCase(); - void cleanupTestCase(); + Q_OBJECT +private slots: + void initTestCase(); + void cleanupTestCase(); #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) - void exercise_data(); - void exercise(); - void namedGroupsMethod(); + void exercise_data(); + void exercise(); + void namedGroupsMethod(); #endif }; @@ -36,8 +36,8 @@ void TestFFDHE::cleanupTestCase() { #if defined(USE_QSSLDIFFIEHELLMANPARAMETERS) void TestFFDHE::exercise_data() { - QTest::addColumn<QString>("name"); - QTest::addColumn<bool>("expectedToWork"); + QTest::addColumn< QString >("name"); + QTest::addColumn< bool >("expectedToWork"); QTest::newRow("ffdhe2048") << QString(QLatin1String("ffdhe2048")) << true; QTest::newRow("ffdhe3072") << QString(QLatin1String("ffdhe3072")) << true; @@ -61,7 +61,7 @@ static bool tryFFDHELookupByName(QString name) { } if (ok) { QSslDiffieHellmanParameters dh = QSslDiffieHellmanParameters::fromEncoded(pem, QSsl::Pem); - ok = dh.isValid(); + ok = dh.isValid(); if (!ok) { qWarning("QSslDiffieHellman error: %s", qPrintable(dh.errorString())); } @@ -77,9 +77,7 @@ void TestFFDHE::exercise() { } void TestFFDHE::namedGroupsMethod() { - foreach (QString name, FFDHE::NamedGroups()) { - QCOMPARE(tryFFDHELookupByName(name), true); - } + foreach (QString name, FFDHE::NamedGroups()) { QCOMPARE(tryFFDHELookupByName(name), true); } } #endif diff --git a/src/tests/TestLink.cpp b/src/tests/TestLink.cpp index 09996bdf8..327f00cb6 100644 --- a/src/tests/TestLink.cpp +++ b/src/tests/TestLink.cpp @@ -9,30 +9,30 @@ #include <QtCore> #ifdef Q_OS_WIN -# include "win.h" +# include "win.h" #else -# include <fcntl.h> -# include <sys/mman.h> +# include <fcntl.h> +# include <sys/mman.h> #endif struct LinkedMem { #ifdef WIN32 - UINT32 uiVersion; - DWORD uiTick; + UINT32 uiVersion; + DWORD uiTick; #else uint32_t uiVersion; uint32_t uiTick; #endif - float fAvatarPosition[3]; - float fAvatarFront[3]; - float fAvatarTop[3]; - wchar_t name[256]; - float fCameraPosition[3]; - float fCameraFront[3]; - float fCameraTop[3]; - wchar_t identity[256]; + float fAvatarPosition[3]; + float fAvatarFront[3]; + float fAvatarTop[3]; + wchar_t name[256]; + float fCameraPosition[3]; + float fCameraFront[3]; + float fCameraTop[3]; + wchar_t identity[256]; #ifdef WIN32 - UINT32 context_len; + UINT32 context_len; #else uint32_t context_len; #endif @@ -44,7 +44,6 @@ LinkedMem *lm = nullptr; void initMumble() { - #ifdef WIN32 HANDLE hMapObject = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink"); if (!hMapObject) @@ -66,9 +65,9 @@ void initMumble() { return; } - lm = (LinkedMem *)(mmap(nullptr, sizeof(struct LinkedMem), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0)); + lm = (LinkedMem *) (mmap(nullptr, sizeof(struct LinkedMem), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0)); - if (lm == (void *)(-1)) { + if (lm == (void *) (-1)) { lm = nullptr; return; } @@ -76,7 +75,7 @@ void initMumble() { } void updateMumble() { - if (! lm) + if (!lm) return; if (lm->uiVersion != 2) { @@ -144,7 +143,7 @@ int main(int argc, char **argv) { #ifdef WIN32 Sleep(100); #else - usleep(100*1000); + usleep(100 * 1000); #endif } } diff --git a/src/tests/TestPacketDataStream/TestPacketDataStream.cpp b/src/tests/TestPacketDataStream/TestPacketDataStream.cpp index 95f121871..94ea14ab4 100644 --- a/src/tests/TestPacketDataStream/TestPacketDataStream.cpp +++ b/src/tests/TestPacketDataStream/TestPacketDataStream.cpp @@ -3,29 +3,29 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. +#include "Message.h" +#include "PacketDataStream.h" +#include <QObject> #include <QtCore> #include <QtNetwork> #include <QtTest> -#include <QObject> -#include "PacketDataStream.h" -#include "Message.h" class TestPacketDataStream : public QObject { - Q_OBJECT - private slots: - void integer(); - void integer_data(); - void string(); - void string_data(); - void space(); - void floating(); - void floating_data(); - void undersize(); + Q_OBJECT +private slots: + void integer(); + void integer_data(); + void string(); + void string_data(); + void space(); + void floating(); + void floating_data(); + void undersize(); }; void TestPacketDataStream::floating_data() { - QTest::addColumn<double>("value"); - for (int i=1;i<256;i++) { + QTest::addColumn< double >("value"); + for (int i = 1; i < 256; i++) { double v = 1.0L / (1.0L * i); QTest::newRow("Positive") << v; QTest::newRow("Negative") << -v; @@ -51,11 +51,11 @@ void TestPacketDataStream::undersize() { QByteArray qba(32, 'Z'); char buff[256]; - for (unsigned int i=0;i<32;i++) { + for (unsigned int i = 0; i < 32; i++) { PacketDataStream out(buff, i); out << qba; - QCOMPARE(33-i, out.undersize()); - QVERIFY(! out.isValid()); + QCOMPARE(33 - i, out.undersize()); + QVERIFY(!out.isValid()); QVERIFY(out.left() == 0); } PacketDataStream out(buff, 33); @@ -66,8 +66,8 @@ void TestPacketDataStream::undersize() { } void TestPacketDataStream::integer_data() { - QTest::addColumn<quint64>("value"); - for (int i=0;i<64;i++) { + QTest::addColumn< quint64 >("value"); + for (int i = 0; i < 64; i++) { quint64 v = 1ULL << i; QTest::newRow("Integer") << v; QTest::newRow("~Integer") << ~v; @@ -90,7 +90,7 @@ void TestPacketDataStream::integer() { } void TestPacketDataStream::string_data() { - QTest::addColumn<QString>("string"); + QTest::addColumn< QString >("string"); QTest::newRow("Empty") << QString(""); QTest::newRow("Null") << QString(); QTest::newRow("Bærtur") << QString("Bærtur"); @@ -113,8 +113,8 @@ void TestPacketDataStream::string() { void TestPacketDataStream::space() { char buff[256]; - for (int i=0;i<256;i++) - buff[i]= 0x55; + for (int i = 0; i < 256; i++) + buff[i] = 0x55; PacketDataStream out(buff, 1); @@ -128,7 +128,7 @@ void TestPacketDataStream::space() { out << val; - QVERIFY(! out.isValid()); + QVERIFY(!out.isValid()); QVERIFY(out.size() == 1); QVERIFY(out.left() == 0); QVERIFY(buff[1] == 0x55); @@ -144,7 +144,7 @@ void TestPacketDataStream::space() { QVERIFY(in.left() == 0); in >> v; - QVERIFY(! in.isValid()); + QVERIFY(!in.isValid()); QVERIFY(in.size() == 1); QVERIFY(in.left() == 0); } diff --git a/src/tests/TestPasswordGenerator/TestPasswordGenerator.cpp b/src/tests/TestPasswordGenerator/TestPasswordGenerator.cpp index bfb368f24..6d7e80291 100644 --- a/src/tests/TestPasswordGenerator/TestPasswordGenerator.cpp +++ b/src/tests/TestPasswordGenerator/TestPasswordGenerator.cpp @@ -11,14 +11,14 @@ #include "PasswordGenerator.h" // Get the password alphabet from PasswordGenerator. -extern QVector<QChar> mumble_password_generator_alphabet(); +extern QVector< QChar > mumble_password_generator_alphabet(); class TestPasswordGenerator : public QObject { - Q_OBJECT - private slots: - void initTestCase(); - void cleanupTestCase(); - void random(); + Q_OBJECT +private slots: + void initTestCase(); + void cleanupTestCase(); + void random(); }; void TestPasswordGenerator::initTestCase() { @@ -30,7 +30,7 @@ void TestPasswordGenerator::cleanupTestCase() { } void TestPasswordGenerator::random() { - QVector<QChar> alphabet = mumble_password_generator_alphabet(); + QVector< QChar > alphabet = mumble_password_generator_alphabet(); for (int i = 0; i < 100; i++) { QString out = PasswordGenerator::generatePassword(i); QVERIFY(out.size() == i); diff --git a/src/tests/TestSSLLocks/TestSSLLocks.cpp b/src/tests/TestSSLLocks/TestSSLLocks.cpp index 68d8ec784..4aa430de0 100644 --- a/src/tests/TestSSLLocks/TestSSLLocks.cpp +++ b/src/tests/TestSSLLocks/TestSSLLocks.cpp @@ -22,10 +22,7 @@ public: bool m_seed; QAtomicInt *m_running; - SSLRacer(QAtomicInt *running, bool seed) - : m_seed(seed) - , m_running(running) { - } + SSLRacer(QAtomicInt *running, bool seed) : m_seed(seed), m_running(running) {} void run() { unsigned char buf[64]; @@ -34,7 +31,7 @@ public: #else // Qt 5.14 introduced QAtomicInteger::loadRelaxed() which deprecates QAtomicInteger::load() while (m_running->load() == 1) { -#endif +#endif for (int i = 0; i < 1024; i++) { if (m_seed) { RAND_seed(buf, sizeof(buf)); @@ -47,11 +44,11 @@ public: }; class TestSSLLocks : public QObject { - Q_OBJECT - private slots: - void initTestCase(); - void cleanupTestCase(); - void stress(); + Q_OBJECT +private slots: + void initTestCase(); + void cleanupTestCase(); + void stress(); }; void TestSSLLocks::initTestCase() { @@ -76,7 +73,7 @@ void TestSSLLocks::cleanupTestCase() { /// The idea is that without proper locking, the data races we're causing /// should quite quickly cause the process to crash. void TestSSLLocks::stress() { - std::vector<SSLRacer *> racers; + std::vector< SSLRacer * > racers; QAtomicInt running(1); // Spawn 24 threads in total. 12 readers, and 12 writers. @@ -84,7 +81,7 @@ void TestSSLLocks::stress() { // pass or crash, so the threads will be cleaned up either way. int nthreads = 24; for (int i = 0; i < nthreads; i++) { - bool seeder = i % 2; + bool seeder = i % 2; SSLRacer *racer = new SSLRacer(&running, seeder); racers.push_back(racer); racer->start(); diff --git a/src/tests/TestSelfSignedCertificate/TestSelfSignedCertificate.cpp b/src/tests/TestSelfSignedCertificate/TestSelfSignedCertificate.cpp index 4c4f957a7..b65d15f23 100644 --- a/src/tests/TestSelfSignedCertificate/TestSelfSignedCertificate.cpp +++ b/src/tests/TestSelfSignedCertificate/TestSelfSignedCertificate.cpp @@ -11,12 +11,12 @@ #include "SelfSignedCertificate.h" class TestSelfSignedCertificate : public QObject { - Q_OBJECT - private slots: - void initTestCase(); - void cleanupTestCase(); - void exerciseClientCert(); - void exerciseServerCert(); + Q_OBJECT +private slots: + void initTestCase(); + void cleanupTestCase(); + void exerciseClientCert(); + void exerciseServerCert(); }; void TestSelfSignedCertificate::initTestCase() { @@ -30,8 +30,9 @@ void TestSelfSignedCertificate::cleanupTestCase() { void TestSelfSignedCertificate::exerciseClientCert() { QSslCertificate cert; QSslKey key; - - bool ok = SelfSignedCertificate::generateMumbleCertificate(QLatin1String("Test"), QLatin1String("test@test.test"), cert, key); + + bool ok = SelfSignedCertificate::generateMumbleCertificate(QLatin1String("Test"), QLatin1String("test@test.test"), + cert, key); QCOMPARE(ok, true); QCOMPARE(cert.isNull(), false); QCOMPARE(key.isNull(), false); @@ -51,7 +52,8 @@ void TestSelfSignedCertificate::exerciseClientCert() { // Test that it's possible to create a client certificate with // both a name and an email. - ok = SelfSignedCertificate::generateMumbleCertificate(QLatin1String("John Doe"), QLatin1String("john@doe.family"), cert, key); + ok = SelfSignedCertificate::generateMumbleCertificate(QLatin1String("John Doe"), QLatin1String("john@doe.family"), + cert, key); QCOMPARE(ok, true); QCOMPARE(cert.isNull(), false); QCOMPARE(key.isNull(), false); @@ -60,7 +62,7 @@ void TestSelfSignedCertificate::exerciseClientCert() { void TestSelfSignedCertificate::exerciseServerCert() { QSslCertificate cert; QSslKey key; - + bool ok = SelfSignedCertificate::generateMurmurV2Certificate(cert, key); QCOMPARE(ok, true); QCOMPARE(cert.isNull(), false); diff --git a/src/tests/TestServerAddress/TestServerAddress.cpp b/src/tests/TestServerAddress/TestServerAddress.cpp index c4a4b3e66..3fb5656e9 100644 --- a/src/tests/TestServerAddress/TestServerAddress.cpp +++ b/src/tests/TestServerAddress/TestServerAddress.cpp @@ -12,14 +12,14 @@ #include "ServerAddress.h" class TestServerAddress : public QObject { - Q_OBJECT - private slots: - void defaultCtor(); - void isValid(); - void ctor(); - void equals(); - void lessThan(); - void qhash(); + Q_OBJECT +private slots: + void defaultCtor(); + void isValid(); + void ctor(); + void equals(); + void lessThan(); + void qhash(); }; void TestServerAddress::defaultCtor() { @@ -49,7 +49,7 @@ void TestServerAddress::isValid() { void TestServerAddress::ctor() { ServerAddress sa(HostAddress(QHostAddress("127.0.0.1")), 443); QCOMPARE(sa.host, HostAddress(QHostAddress("127.0.0.1"))); - QCOMPARE(sa.port, static_cast<unsigned short>(443)); + QCOMPARE(sa.port, static_cast< unsigned short >(443)); } void TestServerAddress::equals() { @@ -65,7 +65,7 @@ void TestServerAddress::equals() { } void TestServerAddress::lessThan() { - QList<ServerAddress> testdata; + QList< ServerAddress > testdata; testdata << ServerAddress(); testdata << ServerAddress(HostAddress(), 1); @@ -80,7 +80,7 @@ void TestServerAddress::lessThan() { testdata << ServerAddress(HostAddress(QHostAddress("255.255.255.255")), 0); testdata << ServerAddress(HostAddress(QHostAddress("255.255.255.255")), 65535); - QList<ServerAddress> sorted(testdata); + QList< ServerAddress > sorted(testdata); std::sort(sorted.begin(), sorted.end()); QVERIFY(testdata == sorted); } diff --git a/src/tests/TestServerResolver/TestServerResolver.cpp b/src/tests/TestServerResolver/TestServerResolver.cpp index cd2fbff3e..d13619860 100644 --- a/src/tests/TestServerResolver/TestServerResolver.cpp +++ b/src/tests/TestServerResolver/TestServerResolver.cpp @@ -3,12 +3,12 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. +#include <QSignalSpy> #include <QtCore> #include <QtTest> -#include <QSignalSpy> -#include "ServerResolver.h" #include "PlatformCheck.h" +#include "ServerResolver.h" void signalSpyWait(QSignalSpy &spy) { // We increase the timeout from 5s to 8s because travis builds could fail otherwise (slow network response). @@ -17,13 +17,13 @@ void signalSpyWait(QSignalSpy &spy) { } class TestServerResolver : public QObject { - Q_OBJECT - private slots: - void simpleSrv(); - void srvCustomPort(); - void simpleA(); - void simpleAAAA(); - void simpleCNAME(); + Q_OBJECT +private slots: + void simpleSrv(); + void srvCustomPort(); + void simpleA(); + void simpleAAAA(); + void simpleCNAME(); }; void TestServerResolver::simpleSrv() { @@ -37,7 +37,7 @@ void TestServerResolver::simpleSrv() { QSignalSpy spy(&r, SIGNAL(resolved())); QString hostname = QString::fromLatin1("simple.serverresolver.mumble.info"); - quint16 port = 64738; + quint16 port = 64738; r.resolve(hostname, port); @@ -45,7 +45,7 @@ void TestServerResolver::simpleSrv() { QCOMPARE(spy.count(), 1); - QList<ServerResolverRecord> records = r.records(); + QList< ServerResolverRecord > records = r.records(); QCOMPARE(records.size(), 1); ServerResolverRecord record = records.at(0); @@ -85,7 +85,7 @@ void TestServerResolver::srvCustomPort() { ServerResolver r; QSignalSpy spy(&r, SIGNAL(resolved())); - QString hostname = QString::fromLatin1("customport.serverresolver.mumble.info"); + QString hostname = QString::fromLatin1("customport.serverresolver.mumble.info"); quint16 customPort = 36001; r.resolve(hostname, 64738); @@ -93,7 +93,7 @@ void TestServerResolver::srvCustomPort() { QCOMPARE(spy.count(), 1); - QList<ServerResolverRecord> records = r.records(); + QList< ServerResolverRecord > records = r.records(); QCOMPARE(records.size(), 1); ServerResolverRecord record = records.at(0); @@ -129,7 +129,7 @@ void TestServerResolver::simpleCNAME() { QSignalSpy spy(&r, SIGNAL(resolved())); QString hostname = QString::fromLatin1("cname.serverresolver.mumble.info"); - quint16 port = 64738; + quint16 port = 64738; r.resolve(hostname, port); @@ -137,7 +137,7 @@ void TestServerResolver::simpleCNAME() { QCOMPARE(spy.count(), 1); - QList<ServerResolverRecord> records = r.records(); + QList< ServerResolverRecord > records = r.records(); QCOMPARE(records.size(), 1); ServerResolverRecord record = records.at(0); @@ -171,7 +171,7 @@ void TestServerResolver::simpleA() { QSignalSpy spy(&r, SIGNAL(resolved())); QString hostname = QString::fromLatin1("simplea.serverresolver.mumble.info"); - quint16 port = 64738; + quint16 port = 64738; r.resolve(hostname, port); @@ -179,7 +179,7 @@ void TestServerResolver::simpleA() { QCOMPARE(spy.count(), 1); - QList<ServerResolverRecord> records = r.records(); + QList< ServerResolverRecord > records = r.records(); // Since not all systems have IPv4 support, we have to // skip this test if we get no matches. Not ideal, but // at least we get some test coverage on IPv4 systems. @@ -194,7 +194,7 @@ void TestServerResolver::simpleA() { QCOMPARE(record.hostname(), hostname); QCOMPARE(record.port(), port); QCOMPARE(record.addresses().size(), 1); - QCOMPARE(record.priority(), static_cast<qint64>(0)); + QCOMPARE(record.priority(), static_cast< qint64 >(0)); HostAddress want(QHostAddress(QLatin1String("127.0.0.1"))); HostAddress got = record.addresses().at(0); @@ -206,7 +206,7 @@ void TestServerResolver::simpleAAAA() { QSignalSpy spy(&r, SIGNAL(resolved())); QString hostname = QString::fromLatin1("simpleaaaa.serverresolver.mumble.info"); - quint16 port = 64738; + quint16 port = 64738; r.resolve(hostname, port); @@ -214,7 +214,7 @@ void TestServerResolver::simpleAAAA() { QCOMPARE(spy.count(), 1); - QList<ServerResolverRecord> records = r.records(); + QList< ServerResolverRecord > records = r.records(); // Since not all systems have IPv6 support, we have to // skip this test if we get no matches. Not ideal, but // at least we get some test coverage on IPv6 systems. @@ -229,7 +229,7 @@ void TestServerResolver::simpleAAAA() { QCOMPARE(record.hostname(), hostname); QCOMPARE(record.port(), port); QCOMPARE(record.addresses().size(), 1); - QCOMPARE(record.priority(), static_cast<qint64>(0)); + QCOMPARE(record.priority(), static_cast< qint64 >(0)); HostAddress want(QHostAddress(QLatin1String("::1"))); HostAddress got = record.addresses().at(0); diff --git a/src/tests/TestStdAbs/TestStdAbs.cpp b/src/tests/TestStdAbs/TestStdAbs.cpp index 8e6afb6d9..1f572c3eb 100644 --- a/src/tests/TestStdAbs/TestStdAbs.cpp +++ b/src/tests/TestStdAbs/TestStdAbs.cpp @@ -16,14 +16,14 @@ /// function. /// Test that it works for us. class TestStdAbs : public QObject { - Q_OBJECT - private slots: - void floatWorks(); + Q_OBJECT +private slots: + void floatWorks(); }; void TestStdAbs::floatWorks() { const float in = -1.5; - float out = std::abs(in); + float out = std::abs(in); QVERIFY(out > 1.2 && out < 1.8); } diff --git a/src/tests/TestTimer/TestTimer.cpp b/src/tests/TestTimer/TestTimer.cpp index 4dd9e5cc2..08dfb984f 100644 --- a/src/tests/TestTimer/TestTimer.cpp +++ b/src/tests/TestTimer/TestTimer.cpp @@ -9,10 +9,10 @@ #include "Timer.h" class TestTimer : public QObject { - Q_OBJECT - private slots: - void resolution(); - void order(); + Q_OBJECT +private slots: + void resolution(); + void order(); }; // This tests that the timer implemented by the Timer @@ -24,7 +24,7 @@ void TestTimer::resolution() { t.restart(); - quint64 nchanges = 0; + quint64 nchanges = 0; quint64 lastElapsed = 0; quint64 curElapsed = 0; @@ -36,11 +36,11 @@ void TestTimer::resolution() { lastElapsed = curElapsed; } while (curElapsed < 150000); // 150 ms - quint64 totalElapsed = t.elapsed(); - double usecsPerChange = static_cast<double>(totalElapsed) / static_cast<double>(nchanges); + quint64 totalElapsed = t.elapsed(); + double usecsPerChange = static_cast< double >(totalElapsed) / static_cast< double >(nchanges); - qWarning("Total elapsed time: %llu microseconds", static_cast<unsigned long long>(totalElapsed)); - qWarning("Number of elapsed changes: %llu", static_cast<unsigned long long>(nchanges)); + qWarning("Total elapsed time: %llu microseconds", static_cast< unsigned long long >(totalElapsed)); + qWarning("Number of elapsed changes: %llu", static_cast< unsigned long long >(nchanges)); qWarning("Resolution: %.2f microseconds", usecsPerChange); if (usecsPerChange >= 100.0f) { @@ -51,7 +51,8 @@ void TestTimer::resolution() { void TestTimer::order() { Timer a; - while (a.elapsed() == 0) {}; + while (a.elapsed() == 0) { + }; Timer b; diff --git a/src/tests/TestUnresolvedServerAddress/TestUnresolvedServerAddress.cpp b/src/tests/TestUnresolvedServerAddress/TestUnresolvedServerAddress.cpp index 98fcf3971..4ec0540c8 100644 --- a/src/tests/TestUnresolvedServerAddress/TestUnresolvedServerAddress.cpp +++ b/src/tests/TestUnresolvedServerAddress/TestUnresolvedServerAddress.cpp @@ -9,15 +9,15 @@ #include "UnresolvedServerAddress.h" class TestUnresolvedServerAddress : public QObject { - Q_OBJECT - private slots: - void defaultCtor(); - void isValid(); - void ctor(); - void caseInsensitive(); - void equals(); - void lessThan(); - void qhash(); + Q_OBJECT +private slots: + void defaultCtor(); + void isValid(); + void ctor(); + void caseInsensitive(); + void equals(); + void lessThan(); + void qhash(); }; void TestUnresolvedServerAddress::defaultCtor() { @@ -47,7 +47,7 @@ void TestUnresolvedServerAddress::isValid() { void TestUnresolvedServerAddress::ctor() { UnresolvedServerAddress usa(QLatin1String("mumble.info"), 443); QCOMPARE(usa.hostname, QString::fromLatin1("mumble.info")); - QCOMPARE(usa.port, static_cast<unsigned short>(443)); + QCOMPARE(usa.port, static_cast< unsigned short >(443)); } void TestUnresolvedServerAddress::caseInsensitive() { @@ -72,7 +72,7 @@ void TestUnresolvedServerAddress::equals() { } void TestUnresolvedServerAddress::lessThan() { - QList<UnresolvedServerAddress> testdata; + QList< UnresolvedServerAddress > testdata; testdata << UnresolvedServerAddress(); testdata << UnresolvedServerAddress(QString(), 1); @@ -87,11 +87,11 @@ void TestUnresolvedServerAddress::lessThan() { testdata << UnresolvedServerAddress(QLatin1String("zaaaa"), 0); testdata << UnresolvedServerAddress(QLatin1String("zaaaa"), 65535); - QList<UnresolvedServerAddress> sorted(testdata); + QList< UnresolvedServerAddress > sorted(testdata); std::sort(sorted.begin(), sorted.end()); int i = 0; - foreach(const UnresolvedServerAddress &unresolved, sorted) { + foreach (const UnresolvedServerAddress &unresolved, sorted) { qWarning("%i -> %s:%i", i, qPrintable(unresolved.hostname), unresolved.port); i += 1; } diff --git a/src/tests/TestXMLTools/TestXMLTools.cpp b/src/tests/TestXMLTools/TestXMLTools.cpp index df3e61ee2..535cae0a7 100644 --- a/src/tests/TestXMLTools/TestXMLTools.cpp +++ b/src/tests/TestXMLTools/TestXMLTools.cpp @@ -3,46 +3,46 @@ // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. -#include <QtCore> -#include <QtTest> +#include <QBuffer> #include <QXmlStreamReader> #include <QXmlStreamWriter> -#include <QBuffer> +#include <QtCore> +#include <QtTest> #include "XMLTools.h" class TestXMLTools : public QObject { - Q_OBJECT - public: - TestXMLTools(QObject *parent=0); - private slots: - void testParseExtractBody(); - void testParseConvertStyleBold(); - void testParseConvertStyleUnderline(); - void testParseConvertStyleItalic(); - void testParseKeepTags(); - void testParseDropEmptyFirstParagraphs(); - void testUndupNoopB(); - void testUndupNoopU(); - void testUndupNoopI(); - void testUndupNoopA(); - void testUndupSimpleB(); - void testUndupSimpleU(); - void testUndupSimpleI(); - void testUndupSimpleA(); - void testUndupMixedBU(); - void testUndupMixedBUIA(); - void testUndupWithSpace(); - void testUndupAnchor(); - void testUndupLinkSameHref(); - void testUndupLinkDifferingHref(); - void testUndupNoRootUndupTag(); - void testUndupUndupTagsRemoval(); - void testUndupStandard(); -// void testUndupInvalidXml1(); - private: - QString doParse(QString input); - QString doUnduplicate(QString input); + Q_OBJECT +public: + TestXMLTools(QObject *parent = 0); +private slots: + void testParseExtractBody(); + void testParseConvertStyleBold(); + void testParseConvertStyleUnderline(); + void testParseConvertStyleItalic(); + void testParseKeepTags(); + void testParseDropEmptyFirstParagraphs(); + void testUndupNoopB(); + void testUndupNoopU(); + void testUndupNoopI(); + void testUndupNoopA(); + void testUndupSimpleB(); + void testUndupSimpleU(); + void testUndupSimpleI(); + void testUndupSimpleA(); + void testUndupMixedBU(); + void testUndupMixedBUIA(); + void testUndupWithSpace(); + void testUndupAnchor(); + void testUndupLinkSameHref(); + void testUndupLinkDifferingHref(); + void testUndupNoRootUndupTag(); + void testUndupUndupTagsRemoval(); + void testUndupStandard(); + // void testUndupInvalidXml1(); +private: + QString doParse(QString input); + QString doUnduplicate(QString input); }; TestXMLTools::TestXMLTools(QObject *parent) : QObject(parent) { @@ -54,7 +54,7 @@ QString TestXMLTools::doParse(QString input) { QXmlStreamWriter writerOut(&outBuf); outBuf.open(QIODevice::WriteOnly); int paragraphs = 0; - QMap<QString, QString> pstyle; + QMap< QString, QString > pstyle; XMLTools::recurseParse(reader, writerOut, paragraphs, pstyle); outBuf.close(); return QString(outBuf.data()); @@ -62,8 +62,10 @@ QString TestXMLTools::doParse(QString input) { void TestXMLTools::testParseExtractBody() { QCOMPARE(doParse(QLatin1String("<html><head></head><body>one</body></html>")), QLatin1String("one")); - QCOMPARE(doParse(QLatin1String("<!DOCTYPE invalid><html><head></head><body>one</body></html>")), QLatin1String("one")); - QCOMPARE(doParse(QLatin1String("<html><head><title>ttt</title></head><body>one</body></html>")), QLatin1String("one")); + QCOMPARE(doParse(QLatin1String("<!DOCTYPE invalid><html><head></head><body>one</body></html>")), + QLatin1String("one")); + QCOMPARE(doParse(QLatin1String("<html><head><title>ttt</title></head><body>one</body></html>")), + QLatin1String("one")); QCOMPARE(doParse(QLatin1String("<html><head></head><body><b>one</b></body></html>")), QLatin1String("<b>one</b>")); } @@ -73,50 +75,90 @@ void TestXMLTools::testParseConvertStyleBold() { // For fonts wiht more boldness levels, the conversion we do here from a weight value to a <b> tag is problematic. // http://doc.qt.io/qt-4.8/stylesheet-reference.html#list-of-property-types // https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:100\">one</span></body></html>")), QLatin1String("<span style=\"font-weight:100\">one</span>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:100;\">one</span></body></html>")), QLatin1String("<span style=\"font-weight:100\">one</span>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:200;\">one</span></body></html>")), QLatin1String("<span style=\"font-weight:200\">one</span>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:300;\">one</span></body></html>")), QLatin1String("<span style=\"font-weight:300\">one</span>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:400;\">one</span></body></html>")), QLatin1String("<span style=\"font-weight:400\">one</span>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:500;\">one</span></body></html>")), QLatin1String("<span style=\"font-weight:500\">one</span>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:600\">one</span></body></html>")), QLatin1String("<b>one</b>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:600;\">one</span></body></html>")), QLatin1String("<b>one</b>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight: 600;\">one</span></body></html>")), QLatin1String("<b>one</b>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight: 600\">one</span></body></html>")), QLatin1String("<b>one</b>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:100\">one</span></body></html>")), + QLatin1String("<span style=\"font-weight:100\">one</span>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:100;\">one</span></body></html>")), + QLatin1String("<span style=\"font-weight:100\">one</span>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:200;\">one</span></body></html>")), + QLatin1String("<span style=\"font-weight:200\">one</span>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:300;\">one</span></body></html>")), + QLatin1String("<span style=\"font-weight:300\">one</span>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:400;\">one</span></body></html>")), + QLatin1String("<span style=\"font-weight:400\">one</span>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:500;\">one</span></body></html>")), + QLatin1String("<span style=\"font-weight:500\">one</span>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:600\">one</span></body></html>")), + QLatin1String("<b>one</b>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:600;\">one</span></body></html>")), + QLatin1String("<b>one</b>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight: 600;\">one</span></body></html>")), + QLatin1String("<b>one</b>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-weight: 600\">one</span></body></html>")), + QLatin1String("<b>one</b>")); // These currently fail -// QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:700;\">one</span></body></html>")), QLatin1String("<b>one</b>")); -// QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:800;\">one</span></body></html>")), QLatin1String("<b>one</b>")); -// QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:900;\">one</span></body></html>")), QLatin1String("<b>one</b>")); -// QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-weight:bold;\">one</span></body></html>")), QLatin1String("<b>one</b>")); + // QCOMPARE(doParse(QLatin1String("<html><head></head><body><span + //style=\"font-weight:700;\">one</span></body></html>")), QLatin1String("<b>one</b>")); + // QCOMPARE(doParse(QLatin1String("<html><head></head><body><span + //style=\"font-weight:800;\">one</span></body></html>")), QLatin1String("<b>one</b>")); + // QCOMPARE(doParse(QLatin1String("<html><head></head><body><span + //style=\"font-weight:900;\">one</span></body></html>")), QLatin1String("<b>one</b>")); + // QCOMPARE(doParse(QLatin1String("<html><head></head><body><span + //style=\"font-weight:bold;\">one</span></body></html>")), QLatin1String("<b>one</b>")); } void TestXMLTools::testParseConvertStyleUnderline() { - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"text-decoration:underline\">one</span></body></html>")), QLatin1String("<u>one</u>")); - // We only convert spans, so this will not create a u tag - QCOMPARE(doParse(QLatin1String("<html><head></head><body><b style=\"text-decoration:underline\">one</b></body></html>")), QLatin1String("<b style=\"text-decoration:underline\">one</b>")); + QCOMPARE(doParse(QLatin1String( + "<html><head></head><body><span style=\"text-decoration:underline\">one</span></body></html>")), + QLatin1String("<u>one</u>")); + // We only convert spans, so this will not create a u tag + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><b style=\"text-decoration:underline\">one</b></body></html>")), + QLatin1String("<b style=\"text-decoration:underline\">one</b>")); } void TestXMLTools::testParseConvertStyleItalic() { - QCOMPARE(doParse(QLatin1String("<html><head></head><body><span style=\"font-style:italic\">one</span></body></html>")), QLatin1String("<i>one</i>")); + QCOMPARE( + doParse(QLatin1String("<html><head></head><body><span style=\"font-style:italic\">one</span></body></html>")), + QLatin1String("<i>one</i>")); } void TestXMLTools::testParseKeepTags() { - QCOMPARE(doParse(QLatin1String("<html><head></head><body><b>one</b><i>two</i><u>three</u></body></html>")), QLatin1String("<b>one</b><i>two</i><u>three</u>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><i><b><u>one</u></b></i></body></html>")), QLatin1String("<i><b><u>one</u></b></i>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><b>one</b><i>two</i><u>three</u></body></html>")), + QLatin1String("<b>one</b><i>two</i><u>three</u>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><i><b><u>one</u></b></i></body></html>")), + QLatin1String("<i><b><u>one</u></b></i>")); } void TestXMLTools::testParseDropEmptyFirstParagraphs() { - QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><p>one</p></body></html>")), QLatin1String("<p>one</p>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><p>one</p><p></p></body></html>")), QLatin1String("<p>one</p><p/>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><p></p><p>one</p><p></p></body></html>")), QLatin1String("<p/><p>one</p><p/>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><div>one</div></body></html>")), QLatin1String("<div>one</div>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><p>one</p></body></html>")), + QLatin1String("<p>one</p>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><p>one</p><p></p></body></html>")), + QLatin1String("<p>one</p><p/>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><p></p><p>one</p><p></p></body></html>")), + QLatin1String("<p/><p>one</p><p/>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><p></p><div>one</div></body></html>")), + QLatin1String("<div>one</div>")); // <br> would be invalid XML. It is not dropped "correctly". -// QCOMPARE(doParse(QLatin1String("<html><head></head><body><p><br></p><p>one</p></body></html>")), QLatin1String("<p>one</p>")); + // QCOMPARE(doParse(QLatin1String("<html><head></head><body><p><br></p><p>one</p></body></html>")), + //QLatin1String("<p>one</p>")); // This is different from what is expected from a comment in the method being tested. It says // contents of empty paragraph would be dropped as well, but the br/space persists. - QCOMPARE(doParse(QLatin1String("<html><head></head><body><p><br/></p><p>one</p></body></html>")), QLatin1String("<br/><p>one</p>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><p><br /></p><p>one</p></body></html>")), QLatin1String("<br/><p>one</p>")); - QCOMPARE(doParse(QLatin1String("<html><head></head><body><p> </p><p>one</p></body></html>")), QLatin1String(" <p>one</p>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><p><br/></p><p>one</p></body></html>")), + QLatin1String("<br/><p>one</p>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><p><br /></p><p>one</p></body></html>")), + QLatin1String("<br/><p>one</p>")); + QCOMPARE(doParse(QLatin1String("<html><head></head><body><p> </p><p>one</p></body></html>")), + QLatin1String(" <p>one</p>")); } QString TestXMLTools::doUnduplicate(QString input) { @@ -146,52 +188,65 @@ void TestXMLTools::testUndupNoopA() { } void TestXMLTools::testUndupSimpleB() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>one</b><b>two</b></unduplicate>")), QLatin1String("<b>onetwo</b>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>one</b><b>two</b></unduplicate>")), + QLatin1String("<b>onetwo</b>")); } void TestXMLTools::testUndupSimpleU() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><u>one</u><u>two</u></unduplicate>")), QLatin1String("<u>onetwo</u>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><u>one</u><u>two</u></unduplicate>")), + QLatin1String("<u>onetwo</u>")); } void TestXMLTools::testUndupSimpleI() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><i>one</i><i>two</i></unduplicate>")), QLatin1String("<i>onetwo</i>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><i>one</i><i>two</i></unduplicate>")), + QLatin1String("<i>onetwo</i>")); } void TestXMLTools::testUndupSimpleA() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a>one</a><a>two</a></unduplicate>")), QLatin1String("<a>onetwo</a>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a>one</a><a>two</a></unduplicate>")), + QLatin1String("<a>onetwo</a>")); } void TestXMLTools::testUndupWithSpace() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>one</b><b> two</b></unduplicate>")), QLatin1String("<b>one two</b>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>one</b><b> two</b></unduplicate>")), + QLatin1String("<b>one two</b>")); } void TestXMLTools::testUndupMixedBU() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>one</b><u>two</u></unduplicate>")), QLatin1String("<b>one</b><u>two</u>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>one</b><u>two</u></unduplicate>")), + QLatin1String("<b>one</b><u>two</u>")); } void TestXMLTools::testUndupMixedBUIA() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a><i><b>one</b><u>two</u></i></a></unduplicate>")), QLatin1String("<a><i><b>one</b><u>two</u></i></a>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a><i><b>one</b><u>two</u></i></a></unduplicate>")), + QLatin1String("<a><i><b>one</b><u>two</u></i></a>")); } void TestXMLTools::testUndupAnchor() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a>one</a><a>two</a></unduplicate>")), QLatin1String("<a>onetwo</a>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a>one</a><a>two</a></unduplicate>")), + QLatin1String("<a>onetwo</a>")); } void TestXMLTools::testUndupLinkSameHref() { QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a href=\"#\">one</a><a href=\"#\">two</a></unduplicate>")), QLatin1String("<a href=\"#\">onetwo</a>")); - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a href=\"http://example.org\">one</a><a href=\"http://example.org\">two</a></unduplicate>")), - QLatin1String("<a href=\"http://example.org\">onetwo</a>")); + QCOMPARE( + doUnduplicate(QLatin1String( + "<unduplicate><a href=\"http://example.org\">one</a><a href=\"http://example.org\">two</a></unduplicate>")), + QLatin1String("<a href=\"http://example.org\">onetwo</a>")); } void TestXMLTools::testUndupLinkDifferingHref() { QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a href=\"#\">one</a><a>two</a></unduplicate>")), QLatin1String("<a href=\"#\">one</a><a>two</a>")); - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a href=\"http://example.org\">one</a><a>two</a></unduplicate>")), - QLatin1String("<a href=\"http://example.org\">one</a><a>two</a>")); - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a>one</a><a href=\"http://example.org\">two</a></unduplicate>")), - QLatin1String("<a>one</a><a href=\"http://example.org\">two</a>")); - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a href=\"http://example.org/path1\">one</a><a href=\"http://example.org/path2\">two</a></unduplicate>")), + QCOMPARE( + doUnduplicate(QLatin1String("<unduplicate><a href=\"http://example.org\">one</a><a>two</a></unduplicate>")), + QLatin1String("<a href=\"http://example.org\">one</a><a>two</a>")); + QCOMPARE( + doUnduplicate(QLatin1String("<unduplicate><a>one</a><a href=\"http://example.org\">two</a></unduplicate>")), + QLatin1String("<a>one</a><a href=\"http://example.org\">two</a>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><a href=\"http://example.org/path1\">one</a><a " + "href=\"http://example.org/path2\">two</a></unduplicate>")), QLatin1String("<a href=\"http://example.org/path1\">one</a><a href=\"http://example.org/path2\">two</a>")); } @@ -201,20 +256,26 @@ void TestXMLTools::testUndupNoRootUndupTag() { } void TestXMLTools::testUndupUndupTagsRemoval() { - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>one</b><unduplicate><unduplicate></unduplicate><b>two</b></unduplicate></unduplicate>")), QLatin1String("<b>onetwo</b>")); + QCOMPARE( + doUnduplicate(QLatin1String( + "<unduplicate><b>one</b><unduplicate><unduplicate></unduplicate><b>two</b></unduplicate></unduplicate>")), + QLatin1String("<b>onetwo</b>")); } void TestXMLTools::testUndupStandard() { - - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with </b><b><i>italic</i></b></unduplicate>")), QLatin1String("<b>bold with <i>italic</i></b>")); - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with </b><b><i></i><i>italic</i></b></unduplicate>")), QLatin1String("<b>bold with <i>italic</i></b>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with </b><b><i>italic</i></b></unduplicate>")), + QLatin1String("<b>bold with <i>italic</i></b>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with </b><b><i></i><i>italic</i></b></unduplicate>")), + QLatin1String("<b>bold with <i>italic</i></b>")); QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>test</b></unduplicate>")), QLatin1String("<b>test</b>")); - QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with </b><b><i></i><i>italic</i></b></unduplicate>")), QLatin1String("<b>bold with <i>italic</i></b>")); + QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with </b><b><i></i><i>italic</i></b></unduplicate>")), + QLatin1String("<b>bold with <i>italic</i></b>")); } // Will warn and fail. -//void TestXMLTools::testUndupInvalidXml1() { -// QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with <i></b>italic</i></unduplicate>")), QLatin1String("<b>bold with <i>italic</i></b>")); +// void TestXMLTools::testUndupInvalidXml1() { +// QCOMPARE(doUnduplicate(QLatin1String("<unduplicate><b>bold with <i></b>italic</i></unduplicate>")), +//QLatin1String("<b>bold with <i>italic</i></b>")); //} QTEST_MAIN(TestXMLTools) @@ -11,15 +11,15 @@ #define MUMBLE_WIN_H_ #ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN #endif #ifndef UNICODE -# define UNICODE +# define UNICODE #endif #ifndef NOMINMAX -# define NOMINMAX +# define NOMINMAX #endif #ifdef __MINGW32__ @@ -29,14 +29,14 @@ // we need. // This seems to be required only with MXE, with MSYS2 // the target is already Windows 7 -# if (_WIN32_WINNT < 0x0601) -# undef _WIN32_WINNT -# define _WIN32_WINNT 0x0601 -# endif -# if (NTDDI_VERSION < NTDDI_WIN7) -# undef NTDDI_VERSION -# define NTDDI_VERSION NTDDI_WIN7 -# endif +# if (_WIN32_WINNT < 0x0601) +# undef _WIN32_WINNT +# define _WIN32_WINNT 0x0601 +# endif +# if (NTDDI_VERSION < NTDDI_WIN7) +# undef NTDDI_VERSION +# define NTDDI_VERSION NTDDI_WIN7 +# endif #endif #include <windows.h> @@ -46,9 +46,9 @@ // so define QOS_FLOWID (and PQOS_FLOWID) as well as QOS_NON_ADAPTIVE_FLOW // ourselves to allow us to build with QoS support on MinGW. typedef UINT32 QOS_FLOWID, *PQOS_FLOWID; -# ifndef QOS_NON_ADAPTIVE_FLOW -# define QOS_NON_ADAPTIVE_FLOW 0x00000002 -# endif +# ifndef QOS_NON_ADAPTIVE_FLOW +# define QOS_NON_ADAPTIVE_FLOW 0x00000002 +# endif #endif #endif // MUMBLE_WIN_H_ |