From c1cf157116de7fc3da96203aa6f03c38c7ebb650 Mon Sep 17 00:00:00 2001 From: Manuel Nickschas Date: Tue, 25 Sep 2018 00:13:14 +0200 Subject: [PATCH] modernize: Reformat ALL the source... again! It's been more than six years since we last used an autoformatter on the codebase. Tooling has progressed, so has the language and of course our personal preferences. Use clang-format this time to reformat the whole codebase, following the rules laid out in .clang-format (which one can use for configuring an IDE, too, if it supports autoformatting). Overall, the new style is not too different from what we used before, with one significant change: We now attach pointer/reference indicators (*&) to the type rather than the name, i.e. we left-align. While this is a major deviation from the Qt style which we use for almost everything else, it aligns more closely with many other projects, as well as the C++ documentation and STL. It also makes more sense semantically, because */& are really part of the type. Other changes include (but are not limited to): - Use only one blank line between function definitions - Categorize includes from generic/system to local, sorting each category alphabetically. The generic-to-local sort order seems to be more common than the other way round, so we use that. - In .cpp files, the corresponding header is always included first. This is a general recommendation, because it makes it harder to accidentally introduce a reliance on transitive includes in headers. - Consistently break initializers in ctors before the comma, so the commas are left-aligned together with the colon. - Use two spaces between code and trailing comments. Note that sometimes even clang-format gets things wrong. In a few places, formatting was manually fixed; however, reviewing a diff of almost 80k lines is a rather boring task, so we didn't thoroughly go through all the changes. Wrong formatting can always be fixed in follow-up commits, anyway. Note also that we don't intend to re-run clang-format on a regular basis, nor do we want to religiously follow a hardcoded set of rules for new code in the future. Where it makes sense, the rules may be bent in favor of better readability or more pleasing code. --- .clang-format | 126 +++ src/client/abstractmessageprocessor.cpp | 5 +- src/client/abstractmessageprocessor.h | 8 +- src/client/abstractui.h | 12 +- src/client/backlogrequester.cpp | 55 +- src/client/backlogrequester.h | 35 +- src/client/backlogsettings.cpp | 14 - src/client/buffermodel.cpp | 50 +- src/client/buffermodel.h | 37 +- src/client/buffersettings.cpp | 28 +- src/client/buffersettings.h | 11 +- src/client/bufferviewoverlay.cpp | 51 +- src/client/bufferviewoverlay.h | 18 +- src/client/client.cpp | 218 ++--- src/client/client.h | 161 ++-- src/client/clientaliasmanager.cpp | 8 +- src/client/clientaliasmanager.h | 4 +- src/client/clientauthhandler.cpp | 182 ++-- src/client/clientauthhandler.h | 59 +- src/client/clientbacklogmanager.cpp | 49 +- src/client/clientbacklogmanager.h | 17 +- src/client/clientbufferviewconfig.cpp | 7 +- src/client/clientbufferviewconfig.h | 4 +- src/client/clientbufferviewmanager.cpp | 25 +- src/client/clientbufferviewmanager.h | 8 +- src/client/clientidentity.cpp | 36 +- src/client/clientidentity.h | 36 +- src/client/clientignorelistmanager.cpp | 15 +- src/client/clientignorelistmanager.h | 17 +- src/client/clientirclisthelper.cpp | 8 +- src/client/clientirclisthelper.h | 19 +- src/client/clientsettings.cpp | 126 +-- src/client/clientsettings.h | 42 +- src/client/clienttransfer.cpp | 45 +- src/client/clienttransfer.h | 8 +- src/client/clienttransfermanager.cpp | 12 +- src/client/clienttransfermanager.h | 4 +- src/client/clientuserinputhandler.cpp | 68 +- src/client/clientuserinputhandler.h | 27 +- src/client/coreaccount.cpp | 74 +- src/client/coreaccount.h | 24 +- src/client/coreaccountmodel.cpp | 69 +- src/client/coreaccountmodel.h | 27 +- src/client/coreconnection.cpp | 103 +-- src/client/coreconnection.h | 95 ++- src/client/execwrapper.cpp | 32 +- src/client/execwrapper.h | 13 +- src/client/irclistmodel.cpp | 22 +- src/client/irclistmodel.h | 20 +- src/client/messagefilter.cpp | 48 +- src/client/messagefilter.h | 13 +- src/client/messagemodel.cpp | 112 +-- src/client/messagemodel.h | 82 +- src/client/networkmodel.cpp | 562 +++++------- src/client/networkmodel.h | 188 ++-- src/client/selectionmodelsynchronizer.cpp | 113 +-- src/client/selectionmodelsynchronizer.h | 40 +- src/client/transfermodel.cpp | 45 +- src/client/transfermodel.h | 20 +- src/client/treemodel.cpp | 243 +++--- src/client/treemodel.h | 90 +- src/common/aliasmanager.cpp | 76 +- src/common/aliasmanager.h | 45 +- src/common/authhandler.cpp | 20 +- src/common/authhandler.h | 35 +- src/common/backlogmanager.h | 18 +- src/common/basichandler.cpp | 74 +- src/common/basichandler.h | 25 +- src/common/bufferinfo.cpp | 58 +- src/common/bufferinfo.h | 31 +- src/common/buffersyncer.cpp | 82 +- src/common/buffersyncer.h | 50 +- src/common/bufferviewconfig.cpp | 73 +- src/common/bufferviewconfig.h | 119 ++- src/common/bufferviewmanager.cpp | 21 +- src/common/bufferviewmanager.h | 39 +- src/common/compressor.cpp | 111 ++- src/common/compressor.h | 21 +- src/common/coreinfo.cpp | 6 +- src/common/coreinfo.h | 6 +- src/common/ctcpevent.cpp | 8 +- src/common/ctcpevent.h | 61 +- src/common/dccconfig.cpp | 32 +- src/common/dccconfig.h | 38 +- src/common/deferredptr.h | 15 +- src/common/event.cpp | 33 +- src/common/event.h | 18 +- src/common/eventmanager.cpp | 107 +-- src/common/eventmanager.h | 119 +-- src/common/expressionmatch.cpp | 156 ++-- src/common/expressionmatch.h | 58 +- src/common/funchelpers.h | 15 +- src/common/highlightrulemanager.cpp | 86 +- src/common/highlightrulemanager.h | 197 ++--- src/common/identity.cpp | 160 ++-- src/common/identity.h | 121 +-- src/common/ignorelistmanager.cpp | 96 +-- src/common/ignorelistmanager.h | 204 ++--- src/common/internalpeer.cpp | 79 +- src/common/internalpeer.h | 60 +- src/common/irccap.h | 268 +++--- src/common/ircchannel.cpp | 156 ++-- src/common/ircchannel.h | 114 +-- src/common/ircevent.cpp | 20 +- src/common/ircevent.h | 80 +- src/common/irclisthelper.h | 30 +- src/common/ircuser.cpp | 158 ++-- src/common/ircuser.h | 126 ++- src/common/logbacktrace_unix.cpp | 37 +- src/common/logbacktrace_win.cpp | 119 ++- src/common/logger.cpp | 38 +- src/common/logger.h | 20 +- src/common/logmessage.cpp | 13 +- src/common/logmessage.h | 22 +- src/common/mac_utils.cpp | 6 +- src/common/mac_utils.h | 3 +- src/common/message.cpp | 105 ++- src/common/message.h | 106 ++- src/common/messageevent.cpp | 30 +- src/common/messageevent.h | 28 +- src/common/network.cpp | 466 +++++----- src/common/network.h | 389 +++++---- src/common/networkconfig.cpp | 13 +- src/common/networkconfig.h | 27 +- src/common/networkevent.cpp | 31 +- src/common/networkevent.h | 77 +- src/common/nickhighlightmatcher.cpp | 19 +- src/common/nickhighlightmatcher.h | 38 +- src/common/peer.cpp | 43 +- src/common/peer.h | 95 +-- src/common/peerfactory.cpp | 29 +- src/common/peerfactory.h | 14 +- src/common/posixsignalwatcher.cpp | 8 +- src/common/posixsignalwatcher.h | 4 +- src/common/presetnetworks.cpp | 17 +- src/common/presetnetworks.h | 4 +- src/common/protocol.h | 114 +-- .../protocols/datastream/datastreampeer.cpp | 227 +++-- .../protocols/datastream/datastreampeer.h | 51 +- src/common/protocols/legacy/legacypeer.cpp | 269 +++--- src/common/protocols/legacy/legacypeer.h | 55 +- src/common/quassel.cpp | 113 +-- src/common/quassel.h | 96 ++- src/common/remotepeer.cpp | 75 +- src/common/remotepeer.h | 38 +- src/common/serializers/serializers.cpp | 625 +++++++------- src/common/serializers/serializers.h | 150 ++-- src/common/settings.cpp | 89 +- src/common/settings.h | 51 +- src/common/signalproxy.cpp | 352 ++++---- src/common/signalproxy.h | 167 ++-- src/common/singleton.h | 16 +- src/common/syncableobject.cpp | 77 +- src/common/syncableobject.h | 41 +- src/common/transfer.cpp | 109 +-- src/common/transfer.h | 45 +- src/common/transfermanager.cpp | 20 +- src/common/transfermanager.h | 22 +- src/common/types.cpp | 17 +- src/common/types.h | 169 ++-- src/common/util.cpp | 126 +-- src/common/util.h | 42 +- src/common/windowssignalwatcher.cpp | 18 +- src/common/windowssignalwatcher.h | 2 +- src/core/abstractsqlstorage.cpp | 132 ++- src/core/abstractsqlstorage.h | 146 ++-- src/core/authenticator.cpp | 1 + src/core/authenticator.h | 24 +- src/core/cipher.cpp | 225 +++-- src/core/cipher.h | 9 +- src/core/core.cpp | 273 +++--- src/core/core.h | 290 +++---- src/core/corealiasmanager.cpp | 15 +- src/core/corealiasmanager.h | 4 +- src/core/coreapplication.cpp | 4 +- src/core/coreapplication.h | 2 +- src/core/coreauthhandler.cpp | 95 ++- src/core/coreauthhandler.h | 14 +- src/core/corebacklogmanager.cpp | 19 +- src/core/corebacklogmanager.h | 14 +- src/core/corebasichandler.cpp | 80 +- src/core/corebasichandler.h | 63 +- src/core/corebuffersyncer.cpp | 63 +- src/core/corebuffersyncer.h | 21 +- src/core/corebufferviewconfig.cpp | 5 +- src/core/corebufferviewconfig.h | 14 +- src/core/corebufferviewmanager.cpp | 24 +- src/core/corebufferviewmanager.h | 10 +- src/core/coredccconfig.cpp | 3 +- src/core/coredccconfig.h | 4 +- src/core/coreeventmanager.h | 6 +- src/core/corehighlightrulemanager.cpp | 8 +- src/core/corehighlightrulemanager.h | 17 +- src/core/coreidentity.cpp | 43 +- src/core/coreidentity.h | 53 +- src/core/coreignorelistmanager.cpp | 21 +- src/core/coreignorelistmanager.h | 17 +- src/core/coreircchannel.cpp | 17 +- src/core/coreircchannel.h | 8 +- src/core/coreirclisthelper.cpp | 22 +- src/core/coreirclisthelper.h | 25 +- src/core/coreircuser.cpp | 13 +- src/core/coreircuser.h | 8 +- src/core/corenetwork.cpp | 351 ++++---- src/core/corenetwork.h | 186 ++-- src/core/corenetworkconfig.cpp | 8 +- src/core/corenetworkconfig.h | 2 +- src/core/coresession.cpp | 314 ++++--- src/core/coresession.h | 141 +-- src/core/coresessioneventprocessor.cpp | 546 ++++++------ src/core/coresessioneventprocessor.h | 186 ++-- src/core/coresettings.cpp | 21 +- src/core/coresettings.h | 12 +- src/core/coretransfer.cpp | 51 +- src/core/coretransfer.h | 14 +- src/core/coreuserinputhandler.cpp | 367 ++++---- src/core/coreuserinputhandler.h | 113 +-- src/core/coreusersettings.cpp | 29 +- src/core/coreusersettings.h | 14 +- src/core/ctcpparser.cpp | 150 ++-- src/core/ctcpparser.h | 76 +- src/core/eventstringifier.cpp | 273 +++--- src/core/eventstringifier.h | 129 ++- src/core/identserver.cpp | 66 +- src/core/identserver.h | 25 +- src/core/ircparser.cpp | 94 +- src/core/ircparser.h | 21 +- src/core/keyevent.cpp | 8 +- src/core/keyevent.h | 42 +- src/core/ldapauthenticator.cpp | 64 +- src/core/ldapauthenticator.h | 18 +- src/core/netsplit.cpp | 46 +- src/core/netsplit.h | 121 ++- src/core/oidentdconfiggenerator.cpp | 41 +- src/core/oidentdconfiggenerator.h | 35 +- src/core/postgresqlstorage.cpp | 377 ++++---- src/core/postgresqlstorage.h | 163 ++-- src/core/sessionthread.cpp | 20 +- src/core/sessionthread.h | 10 +- src/core/sqlauthenticator.cpp | 24 +- src/core/sqlauthenticator.h | 12 +- src/core/sqlitestorage.cpp | 284 +++--- src/core/sqlitestorage.h | 128 +-- src/core/sslserver.cpp | 77 +- src/core/sslserver.h | 31 +- src/core/storage.cpp | 23 +- src/core/storage.h | 138 +-- src/main/main.cpp | 33 +- src/main/monoapplication.cpp | 14 +- src/main/monoapplication.h | 2 +- src/qtui/aboutdlg.cpp | 100 ++- src/qtui/aboutdlg.h | 5 +- src/qtui/awaylogfilter.cpp | 15 +- src/qtui/awaylogfilter.h | 9 +- src/qtui/awaylogview.cpp | 9 +- src/qtui/awaylogview.h | 7 +- src/qtui/bufferwidget.cpp | 130 ++- src/qtui/bufferwidget.h | 30 +- src/qtui/channellistdlg.cpp | 41 +- src/qtui/channellistdlg.h | 21 +- src/qtui/chatitem.cpp | 311 +++---- src/qtui/chatitem.h | 187 ++-- src/qtui/chatline.cpp | 113 ++- src/qtui/chatline.h | 85 +- src/qtui/chatlinemodel.cpp | 18 +- src/qtui/chatlinemodel.h | 33 +- src/qtui/chatlinemodelitem.cpp | 53 +- src/qtui/chatlinemodelitem.h | 18 +- src/qtui/chatmonitorfilter.cpp | 54 +- src/qtui/chatmonitorfilter.h | 29 +- src/qtui/chatmonitorview.cpp | 28 +- src/qtui/chatmonitorview.h | 13 +- src/qtui/chatscene.cpp | 407 ++++----- src/qtui/chatscene.h | 114 +-- src/qtui/chatview.cpp | 128 ++- src/qtui/chatview.h | 37 +- src/qtui/chatviewsearchbar.cpp | 11 +- src/qtui/chatviewsearchbar.h | 27 +- src/qtui/chatviewsearchcontroller.cpp | 110 +-- src/qtui/chatviewsearchcontroller.h | 35 +- src/qtui/chatviewsettings.cpp | 36 +- src/qtui/chatviewsettings.h | 13 +- src/qtui/columnhandleitem.cpp | 53 +- src/qtui/columnhandleitem.h | 21 +- src/qtui/coreconfigwizard.cpp | 210 +++-- src/qtui/coreconfigwizard.h | 66 +- src/qtui/coreconnectdlg.cpp | 20 +- src/qtui/coreconnectdlg.h | 10 +- src/qtui/coreconnectionstatuswidget.cpp | 12 +- src/qtui/coreconnectionstatuswidget.h | 13 +- src/qtui/coreinfodlg.cpp | 83 +- src/qtui/coreinfodlg.h | 20 +- src/qtui/coresessionwidget.cpp | 23 +- src/qtui/coresessionwidget.h | 6 +- src/qtui/debugbufferviewoverlay.cpp | 19 +- src/qtui/debugbufferviewoverlay.h | 27 +- src/qtui/debugconsole.cpp | 5 +- src/qtui/debugconsole.h | 3 +- src/qtui/debuglogdlg.cpp | 11 +- src/qtui/debuglogdlg.h | 6 +- src/qtui/debugmessagemodelfilter.cpp | 9 +- src/qtui/debugmessagemodelfilter.h | 7 +- src/qtui/dockmanagernotificationbackend.cpp | 77 +- src/qtui/dockmanagernotificationbackend.h | 18 +- src/qtui/inputwidget.cpp | 172 ++-- src/qtui/inputwidget.h | 62 +- src/qtui/ircconnectionwizard.cpp | 54 +- src/qtui/ircconnectionwizard.h | 27 +- src/qtui/knotificationbackend.cpp | 65 +- src/qtui/knotificationbackend.h | 11 +- src/qtui/legacysystemtray.cpp | 47 +- src/qtui/legacysystemtray.h | 18 +- src/qtui/mainpage.cpp | 12 +- src/qtui/mainpage.h | 5 +- src/qtui/mainwin.cpp | 807 +++++++++--------- src/qtui/mainwin.h | 103 +-- src/qtui/markerlineitem.cpp | 23 +- src/qtui/markerlineitem.h | 13 +- src/qtui/msgprocessorstatuswidget.cpp | 3 +- src/qtui/msgprocessorstatuswidget.h | 3 +- src/qtui/nicklistwidget.cpp | 113 ++- src/qtui/nicklistwidget.h | 28 +- src/qtui/osxnotificationbackend.h | 14 +- src/qtui/passwordchangedlg.cpp | 15 +- src/qtui/passwordchangedlg.h | 2 +- src/qtui/qtmultimedianotificationbackend.cpp | 33 +- src/qtui/qtmultimedianotificationbackend.h | 15 +- src/qtui/qtui.cpp | 106 +-- src/qtui/qtui.h | 35 +- src/qtui/qtuiapplication.cpp | 113 ++- src/qtui/qtuiapplication.h | 8 +- src/qtui/qtuimessageprocessor.cpp | 80 +- src/qtui/qtuimessageprocessor.h | 89 +- src/qtui/qtuisettings.cpp | 28 +- src/qtui/qtuisettings.h | 10 +- src/qtui/qtuistyle.cpp | 110 +-- src/qtui/qtuistyle.h | 17 +- src/qtui/receivefiledlg.cpp | 17 +- src/qtui/receivefiledlg.h | 6 +- src/qtui/resourcetreedlg.cpp | 14 +- src/qtui/resourcetreedlg.h | 2 +- src/qtui/settingsdlg.cpp | 87 +- src/qtui/settingsdlg.h | 26 +- src/qtui/settingspagedlg.cpp | 44 +- src/qtui/settingspagedlg.h | 13 +- src/qtui/settingspages/aliasesmodel.cpp | 78 +- src/qtui/settingspages/aliasesmodel.h | 31 +- .../settingspages/aliasessettingspage.cpp | 7 +- src/qtui/settingspages/aliasessettingspage.h | 9 +- .../settingspages/appearancesettingspage.cpp | 79 +- .../settingspages/appearancesettingspage.h | 4 +- .../settingspages/backlogsettingspage.cpp | 9 +- src/qtui/settingspages/backlogsettingspage.h | 4 +- .../settingspages/bufferviewsettingspage.cpp | 165 ++-- .../settingspages/bufferviewsettingspage.h | 36 +- .../settingspages/chatmonitorsettingspage.cpp | 55 +- .../settingspages/chatmonitorsettingspage.h | 14 +- .../chatviewcolorsettingspage.cpp | 5 +- .../settingspages/chatviewcolorsettingspage.h | 3 +- .../settingspages/chatviewsettingspage.cpp | 26 +- src/qtui/settingspages/chatviewsettingspage.h | 4 +- .../settingspages/connectionsettingspage.cpp | 16 +- .../settingspages/connectionsettingspage.h | 7 +- .../settingspages/coreaccountsettingspage.cpp | 68 +- .../settingspages/coreaccountsettingspage.h | 43 +- .../coreconnectionsettingspage.cpp | 8 +- .../coreconnectionsettingspage.h | 3 +- .../corehighlightsettingspage.cpp | 336 ++++---- .../settingspages/corehighlightsettingspage.h | 49 +- src/qtui/settingspages/dccsettingspage.cpp | 17 +- src/qtui/settingspages/dccsettingspage.h | 15 +- .../settingspages/highlightsettingspage.cpp | 220 +++-- .../settingspages/highlightsettingspage.h | 20 +- .../settingspages/identitiessettingspage.cpp | 178 ++-- .../settingspages/identitiessettingspage.h | 36 +- src/qtui/settingspages/identityeditwidget.cpp | 132 ++- src/qtui/settingspages/identityeditwidget.h | 35 +- src/qtui/settingspages/ignorelistmodel.cpp | 59 +- src/qtui/settingspages/ignorelistmodel.h | 39 +- .../settingspages/ignorelistsettingspage.cpp | 60 +- .../settingspages/ignorelistsettingspage.h | 36 +- .../settingspages/inputwidgetsettingspage.cpp | 2 +- .../settingspages/inputwidgetsettingspage.h | 4 +- .../settingspages/itemviewsettingspage.cpp | 17 +- src/qtui/settingspages/itemviewsettingspage.h | 11 +- src/qtui/settingspages/keysequencewidget.cpp | 109 ++- src/qtui/settingspages/keysequencewidget.h | 30 +- .../settingspages/networkssettingspage.cpp | 510 ++++++----- src/qtui/settingspages/networkssettingspage.h | 43 +- .../notificationssettingspage.cpp | 34 +- .../settingspages/notificationssettingspage.h | 4 +- src/qtui/settingspages/previewbufferview.h | 11 +- src/qtui/settingspages/shortcutsmodel.cpp | 63 +- src/qtui/settingspages/shortcutsmodel.h | 40 +- .../settingspages/shortcutssettingspage.cpp | 35 +- .../settingspages/shortcutssettingspage.h | 20 +- src/qtui/settingspages/sonnetsettingspage.cpp | 9 +- src/qtui/settingspages/sonnetsettingspage.h | 4 +- .../settingspages/topicwidgetsettingspage.cpp | 2 +- .../settingspages/topicwidgetsettingspage.h | 4 +- src/qtui/simplenetworkeditor.cpp | 25 +- src/qtui/simplenetworkeditor.h | 15 +- src/qtui/snorenotificationbackend.cpp | 44 +- src/qtui/snorenotificationbackend.h | 26 +- src/qtui/sslinfodlg.cpp | 24 +- src/qtui/sslinfodlg.h | 11 +- src/qtui/statusnotifieritem.cpp | 135 ++- src/qtui/statusnotifieritem.h | 58 +- src/qtui/statusnotifieritemdbus.cpp | 90 +- src/qtui/statusnotifieritemdbus.h | 36 +- src/qtui/systemtray.cpp | 49 +- src/qtui/systemtray.h | 40 +- .../systrayanimationnotificationbackend.cpp | 23 +- .../systrayanimationnotificationbackend.h | 15 +- src/qtui/systraynotificationbackend.cpp | 46 +- src/qtui/systraynotificationbackend.h | 15 +- src/qtui/taskbarnotificationbackend.cpp | 33 +- src/qtui/taskbarnotificationbackend.h | 19 +- src/qtui/titlesetter.cpp | 18 +- src/qtui/titlesetter.h | 11 +- src/qtui/topicwidget.cpp | 70 +- src/qtui/topicwidget.h | 21 +- src/qtui/verticaldock.cpp | 35 +- src/qtui/verticaldock.h | 17 +- src/qtui/webpreviewitem.cpp | 60 +- src/qtui/webpreviewitem.h | 11 +- src/test/main/main.cpp | 6 +- src/test/main/testglobal.h | 4 +- src/uisupport/aboutdata.cpp | 402 ++++----- src/uisupport/aboutdata.h | 26 +- src/uisupport/abstractbuffercontainer.cpp | 20 +- src/uisupport/abstractbuffercontainer.h | 13 +- src/uisupport/abstractitemview.cpp | 32 +- src/uisupport/abstractitemview.h | 32 +- src/uisupport/abstractnotificationbackend.h | 20 +- src/uisupport/action.cpp | 18 +- src/uisupport/action.h | 20 +- src/uisupport/actioncollection.cpp | 99 +-- src/uisupport/actioncollection.h | 44 +- src/uisupport/bufferhotlistfilter.cpp | 21 +- src/uisupport/bufferhotlistfilter.h | 11 +- src/uisupport/bufferview.cpp | 204 ++--- src/uisupport/bufferview.h | 86 +- src/uisupport/bufferviewfilter.cpp | 122 ++- src/uisupport/bufferviewfilter.h | 44 +- src/uisupport/bufferviewoverlayfilter.cpp | 13 +- src/uisupport/bufferviewoverlayfilter.h | 8 +- src/uisupport/clearablelineedit.cpp | 15 +- src/uisupport/clearablelineedit.h | 8 +- src/uisupport/clickable.cpp | 30 +- src/uisupport/clickable.h | 12 +- src/uisupport/clickablelabel.cpp | 8 +- src/uisupport/clickablelabel.h | 4 +- src/uisupport/colorbutton.cpp | 9 +- src/uisupport/colorbutton.h | 10 +- src/uisupport/contextmenuactionprovider.cpp | 101 +-- src/uisupport/contextmenuactionprovider.h | 75 +- src/uisupport/flatproxymodel.cpp | 243 +++--- src/uisupport/flatproxymodel.h | 83 +- src/uisupport/fontselector.cpp | 18 +- src/uisupport/fontselector.h | 14 +- src/uisupport/graphicalui.cpp | 60 +- src/uisupport/graphicalui.h | 76 +- src/uisupport/icon.cpp | 18 +- src/uisupport/icon.h | 6 +- src/uisupport/multilineedit.cpp | 106 +-- src/uisupport/multilineedit.h | 50 +- src/uisupport/networkmodelcontroller.cpp | 199 +++-- src/uisupport/networkmodelcontroller.h | 108 ++- src/uisupport/nickview.cpp | 28 +- src/uisupport/nickview.h | 14 +- src/uisupport/nickviewfilter.cpp | 12 +- src/uisupport/nickviewfilter.h | 10 +- src/uisupport/qssparser.cpp | 100 +-- src/uisupport/qssparser.h | 38 +- src/uisupport/resizingstackedwidget.cpp | 7 +- src/uisupport/resizingstackedwidget.h | 2 +- src/uisupport/settingspage.cpp | 73 +- src/uisupport/settingspage.h | 30 +- src/uisupport/styledlabel.cpp | 54 +- src/uisupport/styledlabel.h | 29 +- src/uisupport/tabcompleter.cpp | 63 +- src/uisupport/tabcompleter.h | 19 +- src/uisupport/toolbaractionprovider.cpp | 70 +- src/uisupport/toolbaractionprovider.h | 23 +- src/uisupport/treeviewtouch.cpp | 17 +- src/uisupport/treeviewtouch.h | 47 +- src/uisupport/uisettings.cpp | 76 +- src/uisupport/uisettings.h | 25 +- src/uisupport/uistyle.cpp | 430 +++++----- src/uisupport/uistyle.h | 171 ++-- src/uisupport/widgethelpers.h | 37 +- 492 files changed, 14912 insertions(+), 17066 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..f555b2e0 --- /dev/null +++ b/.clang-format @@ -0,0 +1,126 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterClass: true + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: false + AfterExternBlock: false + BeforeCatch: true + BeforeElse: true + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: All +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 140 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^".*\-export\.h"' + Priority: -1 + - Regex: '^' + Priority: 1 + - Regex: '<[.]*>' + Priority: 2 + - Regex: '^"moc_.*"' + Priority: 9 + - Regex: '^"ui_.*"' + Priority: 8 + - Regex: '^".*/.*"' + Priority: 7 + - Regex: '^".*"' + Priority: 6 + - Regex: '.*' + Priority: 5 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentPPDirectives: AfterHash +IndentWidth: 4 +IndentWrappedFunctionNames: true +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 200 +PenaltyBreakBeforeFirstCallParameter: 500 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 10 +PenaltyReturnTypeOnItsOwnLine: 600 +PointerAlignment: Left +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 8 +UseTab: Never +... diff --git a/src/client/abstractmessageprocessor.cpp b/src/client/abstractmessageprocessor.cpp index 11320454..662a1ac8 100644 --- a/src/client/abstractmessageprocessor.cpp +++ b/src/client/abstractmessageprocessor.cpp @@ -22,7 +22,6 @@ #include "client.h" -AbstractMessageProcessor::AbstractMessageProcessor(QObject *parent) +AbstractMessageProcessor::AbstractMessageProcessor(QObject* parent) : QObject(parent) -{ -} +{} diff --git a/src/client/abstractmessageprocessor.h b/src/client/abstractmessageprocessor.h index a1b34668..ffb13ea2 100644 --- a/src/client/abstractmessageprocessor.h +++ b/src/client/abstractmessageprocessor.h @@ -31,17 +31,17 @@ class CLIENT_EXPORT AbstractMessageProcessor : public QObject Q_OBJECT public: - AbstractMessageProcessor(QObject *parent); + AbstractMessageProcessor(QObject* parent); virtual void reset() = 0; public slots: - virtual void process(Message &msg) = 0; - virtual void process(QList &msgs) = 0; + virtual void process(Message& msg) = 0; + virtual void process(QList& msgs) = 0; virtual void networkRemoved(NetworkId id) = 0; protected: // updateBufferActivity also sets the Message::Redirected flag which is later used // to determine where a message should be displayed. therefore it's crucial that it // is called before inserting the message into the model - inline void preProcess(Message &msg) { Client::networkModel()->updateBufferActivity(msg); } + inline void preProcess(Message& msg) { Client::networkModel()->updateBufferActivity(msg); } }; diff --git a/src/client/abstractui.h b/src/client/abstractui.h index 2c7e933c..83c96592 100644 --- a/src/client/abstractui.h +++ b/src/client/abstractui.h @@ -38,16 +38,18 @@ class CLIENT_EXPORT AbstractUi : public QObject Q_OBJECT public: - AbstractUi(QObject *parent = nullptr) : QObject(parent) {} - virtual void init() = 0; // called after the client is initialized - virtual MessageModel *createMessageModel(QObject *parent) = 0; - virtual AbstractMessageProcessor *createMessageProcessor(QObject *parent) = 0; + AbstractUi(QObject* parent = nullptr) + : QObject(parent) + {} + virtual void init() = 0; // called after the client is initialized + virtual MessageModel* createMessageModel(QObject* parent) = 0; + virtual AbstractMessageProcessor* createMessageProcessor(QObject* parent) = 0; public slots: virtual void connectedToCore() {} virtual void disconnectedFromCore() {} signals: - void connectToCore(const QVariantMap &connInfo); + void connectToCore(const QVariantMap& connInfo); void disconnectFromCore(); }; diff --git a/src/client/backlogrequester.cpp b/src/client/backlogrequester.cpp index b1ed56c5..3f5765e3 100644 --- a/src/client/backlogrequester.cpp +++ b/src/client/backlogrequester.cpp @@ -26,38 +26,34 @@ #include "bufferviewoverlay.h" #include "clientbacklogmanager.h" -BacklogRequester::BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager *backlogManager) - : backlogManager(backlogManager), - _isBuffering(buffering), - _requesterType(requesterType), - _totalBuffers(0) +BacklogRequester::BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager* backlogManager) + : backlogManager(backlogManager) + , _isBuffering(buffering) + , _requesterType(requesterType) + , _totalBuffers(0) { Q_ASSERT(backlogManager); } - -void BacklogRequester::setWaitingBuffers(const QSet &buffers) +void BacklogRequester::setWaitingBuffers(const QSet& buffers) { _buffersWaiting = buffers; _totalBuffers = _buffersWaiting.count(); } - void BacklogRequester::addWaitingBuffer(BufferId buffer) { _buffersWaiting << buffer; _totalBuffers++; } - -bool BacklogRequester::buffer(BufferId bufferId, const MessageList &messages) +bool BacklogRequester::buffer(BufferId bufferId, const MessageList& messages) { _bufferedMessages << messages; _buffersWaiting.remove(bufferId); return !_buffersWaiting.isEmpty(); } - BufferIdList BacklogRequester::allBufferIds() const { QSet bufferIds = Client::bufferViewOverlay()->bufferIds(); @@ -65,44 +61,41 @@ BufferIdList BacklogRequester::allBufferIds() const return bufferIds.toList(); } - void BacklogRequester::flushBuffer() { if (!_buffersWaiting.isEmpty()) { - qWarning() << Q_FUNC_INFO << "was called before all backlog was received:" - << _buffersWaiting.count() << "buffers are waiting."; + qWarning() << Q_FUNC_INFO << "was called before all backlog was received:" << _buffersWaiting.count() << "buffers are waiting."; } _bufferedMessages.clear(); _totalBuffers = 0; _buffersWaiting.clear(); } - // ======================================== // FIXED BACKLOG REQUESTER // ======================================== -FixedBacklogRequester::FixedBacklogRequester(ClientBacklogManager *backlogManager) +FixedBacklogRequester::FixedBacklogRequester(ClientBacklogManager* backlogManager) : BacklogRequester(true, BacklogRequester::PerBufferFixed, backlogManager) { BacklogSettings backlogSettings; _backlogCount = backlogSettings.fixedBacklogAmount(); } - -void FixedBacklogRequester::requestBacklog(const BufferIdList &bufferIds) +void FixedBacklogRequester::requestBacklog(const BufferIdList& bufferIds) { setWaitingBuffers(bufferIds); - backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 backlog messages for %2 buffers").arg(_backlogCount * bufferIds.count()).arg(bufferIds.count())); - foreach(BufferId bufferId, bufferIds) { + backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 backlog messages for %2 buffers") + .arg(_backlogCount * bufferIds.count()) + .arg(bufferIds.count())); + foreach (BufferId bufferId, bufferIds) { backlogManager->requestBacklog(bufferId, -1, -1, _backlogCount); } } - // ======================================== // GLOBAL UNREAD BACKLOG REQUESTER // ======================================== -GlobalUnreadBacklogRequester::GlobalUnreadBacklogRequester(ClientBacklogManager *backlogManager) +GlobalUnreadBacklogRequester::GlobalUnreadBacklogRequester(ClientBacklogManager* backlogManager) : BacklogRequester(false, BacklogRequester::GlobalUnread, backlogManager) { BacklogSettings backlogSettings; @@ -110,24 +103,23 @@ GlobalUnreadBacklogRequester::GlobalUnreadBacklogRequester(ClientBacklogManager _additional = backlogSettings.globalUnreadBacklogAdditional(); } - void GlobalUnreadBacklogRequester::requestInitialBacklog() { MsgId oldestUnreadMessage; - foreach(BufferId bufferId, allBufferIds()) { + foreach (BufferId bufferId, allBufferIds()) { MsgId msgId = Client::networkModel()->lastSeenMsgId(bufferId); if (!oldestUnreadMessage.isValid() || oldestUnreadMessage > msgId) oldestUnreadMessage = msgId; } - backlogManager->emitMessagesRequested(QObject::tr("Requesting up to %1 of all unread backlog messages (plus additional %2)").arg(_limit).arg(_additional)); + backlogManager->emitMessagesRequested( + QObject::tr("Requesting up to %1 of all unread backlog messages (plus additional %2)").arg(_limit).arg(_additional)); backlogManager->requestBacklogAll(oldestUnreadMessage, -1, _limit, _additional); } - // ======================================== // PER BUFFER UNREAD BACKLOG REQUESTER // ======================================== -PerBufferUnreadBacklogRequester::PerBufferUnreadBacklogRequester(ClientBacklogManager *backlogManager) +PerBufferUnreadBacklogRequester::PerBufferUnreadBacklogRequester(ClientBacklogManager* backlogManager) : BacklogRequester(true, BacklogRequester::PerBufferUnread, backlogManager) { BacklogSettings backlogSettings; @@ -135,12 +127,13 @@ PerBufferUnreadBacklogRequester::PerBufferUnreadBacklogRequester(ClientBacklogMa _additional = backlogSettings.perBufferUnreadBacklogAdditional(); } - -void PerBufferUnreadBacklogRequester::requestBacklog(const BufferIdList &bufferIds) +void PerBufferUnreadBacklogRequester::requestBacklog(const BufferIdList& bufferIds) { setWaitingBuffers(bufferIds); - backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 unread backlog messages for %2 buffers").arg((_limit + _additional) * bufferIds.count()).arg(bufferIds.count())); - foreach(BufferId bufferId, bufferIds) { + backlogManager->emitMessagesRequested(QObject::tr("Requesting a total of up to %1 unread backlog messages for %2 buffers") + .arg((_limit + _additional) * bufferIds.count()) + .arg(bufferIds.count())); + foreach (BufferId bufferId, bufferIds) { backlogManager->requestBacklog(bufferId, Client::networkModel()->lastSeenMsgId(bufferId), -1, _limit, _additional); } } diff --git a/src/client/backlogrequester.h b/src/client/backlogrequester.h index 420ef5d1..b2e346fb 100644 --- a/src/client/backlogrequester.h +++ b/src/client/backlogrequester.h @@ -33,37 +33,38 @@ class ClientBacklogManager; class BacklogRequester { public: - enum RequesterType { + enum RequesterType + { InvalidRequester = 0, PerBufferFixed, PerBufferUnread, GlobalUnread }; - BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager *backlogManger); + BacklogRequester(bool buffering, RequesterType requesterType, ClientBacklogManager* backlogManger); virtual ~BacklogRequester() = default; inline bool isBuffering() { return _isBuffering; } inline RequesterType type() { return _requesterType; } - inline const QList &bufferedMessages() { return _bufferedMessages; } + inline const QList& bufferedMessages() { return _bufferedMessages; } inline int buffersWaiting() const { return _buffersWaiting.count(); } inline int totalBuffers() const { return _totalBuffers; } - bool buffer(BufferId bufferId, const MessageList &messages); //! returns false if it was the last missing backlogpart + bool buffer(BufferId bufferId, const MessageList& messages); //! returns false if it was the last missing backlogpart - virtual void requestBacklog(const BufferIdList &bufferIds) = 0; + virtual void requestBacklog(const BufferIdList& bufferIds) = 0; virtual inline void requestInitialBacklog() { requestBacklog(allBufferIds()); } virtual void flushBuffer(); protected: BufferIdList allBufferIds() const; - inline void setWaitingBuffers(const QList &buffers) { setWaitingBuffers(buffers.toSet()); } - void setWaitingBuffers(const QSet &buffers); + inline void setWaitingBuffers(const QList& buffers) { setWaitingBuffers(buffers.toSet()); } + void setWaitingBuffers(const QSet& buffers); void addWaitingBuffer(BufferId buffer); - ClientBacklogManager *backlogManager; + ClientBacklogManager* backlogManager; private: bool _isBuffering; @@ -73,50 +74,46 @@ private: QSet _buffersWaiting; }; - // ======================================== // FIXED BACKLOG REQUESTER // ======================================== class FixedBacklogRequester : public BacklogRequester { public: - FixedBacklogRequester(ClientBacklogManager *backlogManager); - void requestBacklog(const BufferIdList &bufferIds) override; + FixedBacklogRequester(ClientBacklogManager* backlogManager); + void requestBacklog(const BufferIdList& bufferIds) override; private: int _backlogCount; }; - // ======================================== // GLOBAL UNREAD BACKLOG REQUESTER // ======================================== class GlobalUnreadBacklogRequester : public BacklogRequester { public: - GlobalUnreadBacklogRequester(ClientBacklogManager *backlogManager); + GlobalUnreadBacklogRequester(ClientBacklogManager* backlogManager); void requestInitialBacklog() override; - void requestBacklog(const BufferIdList &) override {} + void requestBacklog(const BufferIdList&) override {} private: int _limit; int _additional; }; - // ======================================== // PER BUFFER UNREAD BACKLOG REQUESTER // ======================================== class PerBufferUnreadBacklogRequester : public BacklogRequester { public: - PerBufferUnreadBacklogRequester(ClientBacklogManager *backlogManager); - void requestBacklog(const BufferIdList &bufferIds) override; + PerBufferUnreadBacklogRequester(ClientBacklogManager* backlogManager); + void requestBacklog(const BufferIdList& bufferIds) override; private: int _limit; int _additional; }; - -#endif //BACKLOGREQUESTER_H +#endif // BACKLOGREQUESTER_H diff --git a/src/client/backlogsettings.cpp b/src/client/backlogsettings.cpp index f1950b0f..37686471 100644 --- a/src/client/backlogsettings.cpp +++ b/src/client/backlogsettings.cpp @@ -24,85 +24,71 @@ BacklogSettings::BacklogSettings() : ClientSettings("Backlog") {} - int BacklogSettings::requesterType() const { return localValue("RequesterType", BacklogRequester::PerBufferUnread).toInt(); } - void BacklogSettings::setRequesterType(int requesterType) { setLocalValue("RequesterType", requesterType); } - int BacklogSettings::dynamicBacklogAmount() const { return localValue("DynamicBacklogAmount", 200).toInt(); } - void BacklogSettings::setDynamicBacklogAmount(int amount) { return setLocalValue("DynamicBacklogAmount", amount); } - int BacklogSettings::fixedBacklogAmount() const { return localValue("FixedBacklogAmount", 500).toInt(); } - void BacklogSettings::setFixedBacklogAmount(int amount) { return setLocalValue("FixedBacklogAmount", amount); } - int BacklogSettings::globalUnreadBacklogLimit() const { return localValue("GlobalUnreadBacklogLimit", 5000).toInt(); } - void BacklogSettings::setGlobalUnreadBacklogLimit(int limit) { return setLocalValue("GlobalUnreadBacklogLimit", limit); } - int BacklogSettings::globalUnreadBacklogAdditional() const { return localValue("GlobalUnreadBacklogAdditional", 100).toInt(); } - void BacklogSettings::setGlobalUnreadBacklogAdditional(int additional) { return setLocalValue("GlobalUnreadBacklogAdditional", additional); } - int BacklogSettings::perBufferUnreadBacklogLimit() const { return localValue("PerBufferUnreadBacklogLimit", 200).toInt(); } - void BacklogSettings::setPerBufferUnreadBacklogLimit(int limit) { return setLocalValue("PerBufferUnreadBacklogLimit", limit); } - int BacklogSettings::perBufferUnreadBacklogAdditional() const { return localValue("PerBufferUnreadBacklogAdditional", 50).toInt(); } - void BacklogSettings::setPerBufferUnreadBacklogAdditional(int additional) { return setLocalValue("PerBufferUnreadBacklogAdditional", additional); diff --git a/src/client/buffermodel.cpp b/src/client/buffermodel.cpp index 0d9ec2d9..959e4ab6 100644 --- a/src/client/buffermodel.cpp +++ b/src/client/buffermodel.cpp @@ -26,21 +26,19 @@ #include "networkmodel.h" #include "quassel.h" -BufferModel::BufferModel(NetworkModel *parent) - : QSortFilterProxyModel(parent), - _selectionModelSynchronizer(this) +BufferModel::BufferModel(NetworkModel* parent) + : QSortFilterProxyModel(parent) + , _selectionModelSynchronizer(this) { setSourceModel(parent); if (Quassel::isOptionSet("debugbufferswitches")) { - connect(_selectionModelSynchronizer.selectionModel(), &QItemSelectionModel::currentChanged, - this, &BufferModel::debug_currentChanged); + connect(_selectionModelSynchronizer.selectionModel(), &QItemSelectionModel::currentChanged, this, &BufferModel::debug_currentChanged); } connect(Client::instance(), &Client::networkCreated, this, &BufferModel::newNetwork); connect(this, &QAbstractItemModel::rowsInserted, this, &BufferModel::newBuffers); } - -bool BufferModel::filterAcceptsRow(int sourceRow, const QModelIndex &parent) const +bool BufferModel::filterAcceptsRow(int sourceRow, const QModelIndex& parent) const { Q_UNUSED(sourceRow); // only networks and buffers are allowed @@ -52,16 +50,13 @@ bool BufferModel::filterAcceptsRow(int sourceRow, const QModelIndex &parent) con return false; } - void BufferModel::newNetwork(NetworkId id) { - const Network *net = Client::network(id); + const Network* net = Client::network(id); Q_ASSERT(net); - connect(net, &Network::connectionStateSet, - this, &BufferModel::networkConnectionChanged); + connect(net, &Network::connectionStateSet, this, &BufferModel::networkConnectionChanged); } - void BufferModel::networkConnectionChanged(Network::ConnectionState state) { switch (state) { @@ -70,7 +65,7 @@ void BufferModel::networkConnectionChanged(Network::ConnectionState state) if (currentIndex().isValid()) return; { - auto *net = qobject_cast(sender()); + auto* net = qobject_cast(sender()); Q_ASSERT(net); setCurrentIndex(mapFromSource(Client::networkModel()->networkIndex(net->networkId()))); } @@ -80,28 +75,24 @@ void BufferModel::networkConnectionChanged(Network::ConnectionState state) } } - -void BufferModel::synchronizeView(QAbstractItemView *view) +void BufferModel::synchronizeView(QAbstractItemView* view) { _selectionModelSynchronizer.synchronizeSelectionModel(view->selectionModel()); } - -void BufferModel::setCurrentIndex(const QModelIndex &newCurrent) +void BufferModel::setCurrentIndex(const QModelIndex& newCurrent) { _selectionModelSynchronizer.selectionModel()->setCurrentIndex(newCurrent, QItemSelectionModel::Current); _selectionModelSynchronizer.selectionModel()->select(newCurrent, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } - -void BufferModel::switchToBuffer(const BufferId &bufferId) +void BufferModel::switchToBuffer(const BufferId& bufferId) { QModelIndex source_index = Client::networkModel()->bufferIndex(bufferId); setCurrentIndex(mapFromSource(source_index)); } - -void BufferModel::switchToBufferIndex(const QModelIndex &bufferIdx) +void BufferModel::switchToBufferIndex(const QModelIndex& bufferIdx) { // we accept indexes that directly belong to us or our parent - nothing else if (bufferIdx.model() == this) { @@ -117,8 +108,7 @@ void BufferModel::switchToBufferIndex(const QModelIndex &bufferIdx) qWarning() << "BufferModel::switchToBufferIndex(const QModelIndex &):" << bufferIdx << "does not belong to BufferModel or NetworkModel"; } - -void BufferModel::switchToOrJoinBuffer(NetworkId networkId, const QString &name, bool isQuery) +void BufferModel::switchToOrJoinBuffer(NetworkId networkId, const QString& name, bool isQuery) { BufferId bufId = Client::networkModel()->bufferId(networkId, name); if (bufId.isValid()) { @@ -135,15 +125,14 @@ void BufferModel::switchToOrJoinBuffer(NetworkId networkId, const QString &name, } } - void BufferModel::debug_currentChanged(QModelIndex current, QModelIndex previous) { Q_UNUSED(previous); - qDebug() << "Switched current Buffer: " << current << current.data().toString() << "Buffer:" << current.data(NetworkModel::BufferIdRole).value(); + qDebug() << "Switched current Buffer: " << current << current.data().toString() + << "Buffer:" << current.data(NetworkModel::BufferIdRole).value(); } - -void BufferModel::newBuffers(const QModelIndex &parent, int start, int end) +void BufferModel::newBuffers(const QModelIndex& parent, int start, int end) { if (parent.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType) return; @@ -154,20 +143,17 @@ void BufferModel::newBuffers(const QModelIndex &parent, int start, int end) } } - void BufferModel::newBuffer(BufferId bufferId) { BufferInfo bufferInfo = Client::networkModel()->bufferInfo(bufferId); - if (_bufferToSwitchTo.first == bufferInfo.networkId() - && _bufferToSwitchTo.second == bufferInfo.bufferName()) { + if (_bufferToSwitchTo.first == bufferInfo.networkId() && _bufferToSwitchTo.second == bufferInfo.bufferName()) { _bufferToSwitchTo.first = 0; _bufferToSwitchTo.second.clear(); switchToBuffer(bufferId); } } - -void BufferModel::switchToBufferAfterCreation(NetworkId network, const QString &name) +void BufferModel::switchToBufferAfterCreation(NetworkId network, const QString& name) { _bufferToSwitchTo = qMakePair(network, name); } diff --git a/src/client/buffermodel.h b/src/client/buffermodel.h index cbfabaae..361a1ed9 100644 --- a/src/client/buffermodel.h +++ b/src/client/buffermodel.h @@ -22,14 +22,14 @@ #include "client-export.h" -#include #include #include +#include #include "network.h" #include "networkmodel.h" -#include "types.h" #include "selectionmodelsynchronizer.h" +#include "types.h" class QAbstractItemView; @@ -38,37 +38,36 @@ class CLIENT_EXPORT BufferModel : public QSortFilterProxyModel Q_OBJECT public: - BufferModel(NetworkModel *parent = nullptr); + BufferModel(NetworkModel* parent = nullptr); - bool filterAcceptsRow(int sourceRow, const QModelIndex &parent) const override; + bool filterAcceptsRow(int sourceRow, const QModelIndex& parent) const override; - inline const SelectionModelSynchronizer *selectionModelSynchronizer() const { return &_selectionModelSynchronizer; } - inline QItemSelectionModel *standardSelectionModel() const { return _selectionModelSynchronizer.selectionModel(); } + inline const SelectionModelSynchronizer* selectionModelSynchronizer() const { return &_selectionModelSynchronizer; } + inline QItemSelectionModel* standardSelectionModel() const { return _selectionModelSynchronizer.selectionModel(); } - inline void synchronizeSelectionModel(QItemSelectionModel *selectionModel) { _selectionModelSynchronizer.synchronizeSelectionModel(selectionModel); } - void synchronizeView(QAbstractItemView *view); + inline void synchronizeSelectionModel(QItemSelectionModel* selectionModel) + { + _selectionModelSynchronizer.synchronizeSelectionModel(selectionModel); + } + void synchronizeView(QAbstractItemView* view); inline QModelIndex currentIndex() { return standardSelectionModel()->currentIndex(); } inline BufferId currentBuffer() { return currentIndex().data(NetworkModel::BufferIdRole).value(); } public slots: - void setCurrentIndex(const QModelIndex &newCurrent); - void switchToBuffer(const BufferId &bufferId); - void switchToBufferIndex(const QModelIndex &bufferIdx); - void switchToOrJoinBuffer(NetworkId network, const QString &bufferName, bool isQuery = false); - void switchToOrStartQuery(NetworkId network, const QString &nick) - { - switchToOrJoinBuffer(network, nick, true); - } - + void setCurrentIndex(const QModelIndex& newCurrent); + void switchToBuffer(const BufferId& bufferId); + void switchToBufferIndex(const QModelIndex& bufferIdx); + void switchToOrJoinBuffer(NetworkId network, const QString& bufferName, bool isQuery = false); + void switchToOrStartQuery(NetworkId network, const QString& nick) { switchToOrJoinBuffer(network, nick, true); } - void switchToBufferAfterCreation(NetworkId network, const QString &name); + void switchToBufferAfterCreation(NetworkId network, const QString& name); private slots: void debug_currentChanged(QModelIndex current, QModelIndex previous); void newNetwork(NetworkId id); void networkConnectionChanged(Network::ConnectionState state); - void newBuffers(const QModelIndex &parent, int start, int end); + void newBuffers(const QModelIndex& parent, int start, int end); private: void newBuffer(BufferId bufferId); diff --git a/src/client/buffersettings.cpp b/src/client/buffersettings.cpp index c7b123f3..7451079a 100644 --- a/src/client/buffersettings.cpp +++ b/src/client/buffersettings.cpp @@ -22,28 +22,22 @@ BufferSettings::BufferSettings(BufferId bufferId) : ClientSettings(QString("Buffer/%1").arg(bufferId.toInt())) -{ -} - +{} -BufferSettings::BufferSettings(const QString &idString) +BufferSettings::BufferSettings(const QString& idString) : ClientSettings(QString("Buffer/%1").arg(idString)) -{ -} +{} - -void BufferSettings::setValue(const QString &key, const QVariant &data) +void BufferSettings::setValue(const QString& key, const QVariant& data) { setLocalValue(key, data); } - -QVariant BufferSettings::value(const QString &key, const QVariant &def) const +QVariant BufferSettings::value(const QString& key, const QVariant& def) const { return localValue(key, def); } - void BufferSettings::filterMessage(Message::Type msgType, bool filter) { if (!hasFilter()) @@ -54,19 +48,16 @@ void BufferSettings::filterMessage(Message::Type msgType, bool filter) setLocalValue("MessageTypeFilter", localValue("MessageTypeFilter", 0).toInt() & ~msgType); } - bool BufferSettings::hasFilter() const { return localValue("hasMessageTypeFilter", false).toBool(); } - int BufferSettings::messageFilter() const { return localValue("MessageTypeFilter", 0).toInt(); } - void BufferSettings::setMessageFilter(int filter) { if (!hasFilter()) @@ -74,56 +65,47 @@ void BufferSettings::setMessageFilter(int filter) setLocalValue("MessageTypeFilter", filter); } - void BufferSettings::removeFilter() { setLocalValue("hasMessageTypeFilter", false); removeLocalKey("MessageTypeFilter"); } - bool BufferSettings::showUserStateIcons() const { return localValue("ShowUserStateIcons", true).toBool(); } - void BufferSettings::enableUserStateIcons(bool enabled) { setLocalValue("ShowUserStateIcons", enabled); } - int BufferSettings::userNoticesTarget() const { return localValue("UserNoticesTarget", RedirectTarget::DefaultBuffer | RedirectTarget::CurrentBuffer).toInt(); } - void BufferSettings::setUserNoticesTarget(int target) { setLocalValue("UserNoticesTarget", target); } - int BufferSettings::serverNoticesTarget() const { return localValue("ServerNoticesTarget", RedirectTarget::StatusBuffer).toInt(); } - void BufferSettings::setServerNoticesTarget(int target) { setLocalValue("ServerNoticesTarget", target); } - int BufferSettings::errorMsgsTarget() const { return localValue("ErrorMsgsTarget", RedirectTarget::DefaultBuffer).toInt(); } - void BufferSettings::setErrorMsgsTarget(int target) { setLocalValue("ErrorMsgsTarget", target); diff --git a/src/client/buffersettings.h b/src/client/buffersettings.h index 711e3bc5..2791f9d8 100644 --- a/src/client/buffersettings.h +++ b/src/client/buffersettings.h @@ -27,17 +27,18 @@ class CLIENT_EXPORT BufferSettings : public ClientSettings { public: - enum RedirectTarget { + enum RedirectTarget + { DefaultBuffer = 0x01, - StatusBuffer = 0x02, + StatusBuffer = 0x02, CurrentBuffer = 0x04 }; - BufferSettings(const QString &idString = "__default__"); + BufferSettings(const QString& idString = "__default__"); BufferSettings(BufferId bufferId); - void setValue(const QString &key, const QVariant &data); - QVariant value(const QString &key, const QVariant &def = {}) const; + void setValue(const QString& key, const QVariant& data); + QVariant value(const QString& key, const QVariant& def = {}) const; // Message Filter (default and per view) bool hasFilter() const; diff --git a/src/client/bufferviewoverlay.cpp b/src/client/bufferviewoverlay.cpp index 02e57029..e1b847b9 100644 --- a/src/client/bufferviewoverlay.cpp +++ b/src/client/bufferviewoverlay.cpp @@ -30,11 +30,9 @@ const int BufferViewOverlay::_updateEventId = QEvent::registerEventType(); -BufferViewOverlay::BufferViewOverlay(QObject *parent) +BufferViewOverlay::BufferViewOverlay(QObject* parent) : QObject(parent) -{ -} - +{} void BufferViewOverlay::reset() { @@ -52,13 +50,11 @@ void BufferViewOverlay::reset() _tempRemovedBuffers.clear(); } - void BufferViewOverlay::save() { CoreAccountSettings().setBufferViewOverlay(_bufferViewIds); } - void BufferViewOverlay::restore() { QSet currentIds = _bufferViewIds; @@ -71,13 +67,12 @@ void BufferViewOverlay::restore() } } - void BufferViewOverlay::addView(int viewId) { if (_bufferViewIds.contains(viewId)) return; - BufferViewConfig *config = Client::bufferViewManager()->bufferViewConfig(viewId); + BufferViewConfig* config = Client::bufferViewManager()->bufferViewConfig(viewId); if (!config) { qDebug() << "BufferViewOverlay::addView(): no such buffer view:" << viewId; return; @@ -93,11 +88,11 @@ void BufferViewOverlay::addView(int viewId) if (wasInitialized) { BufferIdList buffers; if (config->networkId().isValid()) { - foreach(BufferId bufferId, config->bufferList()) { + foreach (BufferId bufferId, config->bufferList()) { if (Client::networkModel()->networkId(bufferId) == config->networkId()) buffers << bufferId; } - foreach(BufferId bufferId, config->temporarilyRemovedBuffers().toList()) { + foreach (BufferId bufferId, config->temporarilyRemovedBuffers().toList()) { if (Client::networkModel()->networkId(bufferId) == config->networkId()) buffers << bufferId; } @@ -116,14 +111,13 @@ void BufferViewOverlay::addView(int viewId) save(); } - void BufferViewOverlay::removeView(int viewId) { if (!_bufferViewIds.contains(viewId)) return; _bufferViewIds.remove(viewId); - BufferViewConfig *config = Client::bufferViewManager()->bufferViewConfig(viewId); + BufferViewConfig* config = Client::bufferViewManager()->bufferViewConfig(viewId); if (config) disconnect(config, nullptr, this, nullptr); @@ -149,8 +143,7 @@ void BufferViewOverlay::removeView(int viewId) save(); } - -void BufferViewOverlay::viewInitialized(BufferViewConfig *config) +void BufferViewOverlay::viewInitialized(BufferViewConfig* config) { if (!config) { qWarning() << "BufferViewOverlay::viewInitialized() received invalid view!"; @@ -167,16 +160,14 @@ void BufferViewOverlay::viewInitialized(BufferViewConfig *config) emit initDone(); } - void BufferViewOverlay::viewInitialized() { - auto *config = qobject_cast(sender()); + auto* config = qobject_cast(sender()); Q_ASSERT(config); viewInitialized(config); } - void BufferViewOverlay::update() { if (_aboutToUpdate) { @@ -186,7 +177,6 @@ void BufferViewOverlay::update() QCoreApplication::postEvent(this, new QEvent((QEvent::Type)_updateEventId)); } - void BufferViewOverlay::updateHelper() { if (!_aboutToUpdate) @@ -202,7 +192,7 @@ void BufferViewOverlay::updateHelper() QSet tempRemovedBuffers; if (Client::bufferViewManager()) { - BufferViewConfig *config = nullptr; + BufferViewConfig* config = nullptr; QSet::const_iterator viewIter; for (viewIter = _bufferViewIds.constBegin(); viewIter != _bufferViewIds.constEnd(); ++viewIter) { config = Client::bufferViewManager()->bufferViewConfig(*viewIter); @@ -254,14 +244,13 @@ void BufferViewOverlay::updateHelper() emit hasChanged(); } - -QSet BufferViewOverlay::filterBuffersByConfig(const QList &buffers, const BufferViewConfig *config) +QSet BufferViewOverlay::filterBuffersByConfig(const QList& buffers, const BufferViewConfig* config) { Q_ASSERT(config); QSet bufferIds; BufferInfo bufferInfo; - foreach(BufferId bufferId, buffers) { + foreach (BufferId bufferId, buffers) { bufferInfo = Client::networkModel()->bufferInfo(bufferId); if (!(bufferInfo.type() & config->allowedBufferTypes())) continue; @@ -273,57 +262,49 @@ QSet BufferViewOverlay::filterBuffersByConfig(const QList &b return bufferIds; } - -void BufferViewOverlay::customEvent(QEvent *event) +void BufferViewOverlay::customEvent(QEvent* event) { if (event->type() == _updateEventId) { updateHelper(); } } - bool BufferViewOverlay::allNetworks() { updateHelper(); return _networkIds.contains(NetworkId()); } - -const QSet &BufferViewOverlay::networkIds() +const QSet& BufferViewOverlay::networkIds() { updateHelper(); return _networkIds; } - -const QSet &BufferViewOverlay::bufferIds() +const QSet& BufferViewOverlay::bufferIds() { updateHelper(); return _buffers; } - -const QSet &BufferViewOverlay::removedBufferIds() +const QSet& BufferViewOverlay::removedBufferIds() { updateHelper(); return _removedBuffers; } - -const QSet &BufferViewOverlay::tempRemovedBufferIds() +const QSet& BufferViewOverlay::tempRemovedBufferIds() { updateHelper(); return _tempRemovedBuffers; } - int BufferViewOverlay::allowedBufferTypes() { updateHelper(); return _allowedBufferTypes; } - int BufferViewOverlay::minimumActivity() { updateHelper(); diff --git a/src/client/bufferviewoverlay.h b/src/client/bufferviewoverlay.h index 4f3ab464..fc1a4487 100644 --- a/src/client/bufferviewoverlay.h +++ b/src/client/bufferviewoverlay.h @@ -34,15 +34,15 @@ class CLIENT_EXPORT BufferViewOverlay : public QObject Q_OBJECT public: - BufferViewOverlay(QObject *parent = nullptr); + BufferViewOverlay(QObject* parent = nullptr); - inline const QSet &bufferViewIds() { return _bufferViewIds; } + inline const QSet& bufferViewIds() { return _bufferViewIds; } bool allNetworks(); - const QSet &networkIds(); - const QSet &bufferIds(); - const QSet &removedBufferIds(); - const QSet &tempRemovedBufferIds(); + const QSet& networkIds(); + const QSet& bufferIds(); + const QSet& removedBufferIds(); + const QSet& tempRemovedBufferIds(); int allowedBufferTypes(); int minimumActivity(); @@ -65,15 +65,15 @@ signals: void initDone(); protected: - void customEvent(QEvent *event) override; + void customEvent(QEvent* event) override; private slots: void viewInitialized(); - void viewInitialized(BufferViewConfig *config); + void viewInitialized(BufferViewConfig* config); private: void updateHelper(); - QSet filterBuffersByConfig(const QList &buffers, const BufferViewConfig *config); + QSet filterBuffersByConfig(const QList& buffers, const BufferViewConfig* config); bool _aboutToUpdate{false}; diff --git a/src/client/client.cpp b/src/client/client.cpp index 91262394..906684c7 100644 --- a/src/client/client.cpp +++ b/src/client/client.cpp @@ -20,6 +20,9 @@ #include "client.h" +#include +#include + #include "abstractmessageprocessor.h" #include "abstractui.h" #include "bufferinfo.h" @@ -29,11 +32,12 @@ #include "bufferviewconfig.h" #include "bufferviewoverlay.h" #include "clientaliasmanager.h" +#include "clientauthhandler.h" #include "clientbacklogmanager.h" #include "clientbufferviewmanager.h" -#include "clientirclisthelper.h" #include "clientidentity.h" #include "clientignorelistmanager.h" +#include "clientirclisthelper.h" #include "clienttransfermanager.h" #include "clientuserinputhandler.h" #include "coreaccountmodel.h" @@ -50,27 +54,24 @@ #include "signalproxy.h" #include "transfermodel.h" #include "util.h" -#include "clientauthhandler.h" -#include -#include - -Client::Client(std::unique_ptr ui, QObject *parent) - : QObject(parent), Singleton(this), - _signalProxy(new SignalProxy(SignalProxy::Client, this)), - _mainUi(std::move(ui)), - _networkModel(new NetworkModel(this)), - _bufferModel(new BufferModel(_networkModel)), - _backlogManager(new ClientBacklogManager(this)), - _bufferViewOverlay(new BufferViewOverlay(this)), - _coreInfo(new CoreInfo(this)), - _ircListHelper(new ClientIrcListHelper(this)), - _inputHandler(new ClientUserInputHandler(this)), - _transferModel(new TransferModel(this)), - _messageModel(_mainUi->createMessageModel(this)), - _messageProcessor(_mainUi->createMessageProcessor(this)), - _coreAccountModel(new CoreAccountModel(this)), - _coreConnection(new CoreConnection(this)) +Client::Client(std::unique_ptr ui, QObject* parent) + : QObject(parent) + , Singleton(this) + , _signalProxy(new SignalProxy(SignalProxy::Client, this)) + , _mainUi(std::move(ui)) + , _networkModel(new NetworkModel(this)) + , _bufferModel(new BufferModel(_networkModel)) + , _backlogManager(new ClientBacklogManager(this)) + , _bufferViewOverlay(new BufferViewOverlay(this)) + , _coreInfo(new CoreInfo(this)) + , _ircListHelper(new ClientIrcListHelper(this)) + , _inputHandler(new ClientUserInputHandler(this)) + , _transferModel(new TransferModel(this)) + , _messageModel(_mainUi->createMessageModel(this)) + , _messageProcessor(_mainUi->createMessageProcessor(this)) + , _coreAccountModel(new CoreAccountModel(this)) + , _coreConnection(new CoreConnection(this)) { #ifdef EMBED_DATA Q_INIT_RESOURCE(data); @@ -86,27 +87,33 @@ Client::Client(std::unique_ptr ui, QObject *parent) connect(backlogManager(), &ClientBacklogManager::messagesReceived, _messageModel, &MessageModel::messagesReceived); connect(coreConnection(), &CoreConnection::stateChanged, this, &Client::connectionStateChanged); - SignalProxy *p = signalProxy(); + SignalProxy* p = signalProxy(); - p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &))); + p->attachSlot(SIGNAL(displayMsg(const Message&)), this, SLOT(recvMessage(const Message&))); p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString))); p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo))); p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString))); p->attachSignal(this, SIGNAL(requestNetworkStates())); - p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &))); + p->attachSignal(this, + SIGNAL(requestCreateIdentity(const Identity&, const QVariantMap&)), + SIGNAL(createIdentity(const Identity&, const QVariantMap&))); p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId))); - p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &))); + p->attachSlot(SIGNAL(identityCreated(const Identity&)), this, SLOT(coreIdentityCreated(const Identity&))); p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId))); - p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &))); + p->attachSignal(this, + SIGNAL(requestCreateNetwork(const NetworkInfo&, const QStringList&)), + SIGNAL(createNetwork(const NetworkInfo&, const QStringList&))); p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId))); p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId))); p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId))); - p->attachSignal(this, SIGNAL(requestPasswordChange(PeerPtr,QString,QString,QString)), SIGNAL(changePassword(PeerPtr,QString,QString,QString))); - p->attachSlot(SIGNAL(passwordChanged(PeerPtr,bool)), this, SLOT(corePasswordChanged(PeerPtr,bool))); + p->attachSignal(this, + SIGNAL(requestPasswordChange(PeerPtr, QString, QString, QString)), + SIGNAL(changePassword(PeerPtr, QString, QString, QString))); + p->attachSlot(SIGNAL(passwordChanged(PeerPtr, bool)), this, SLOT(corePasswordChanged(PeerPtr, bool))); p->attachSignal(this, SIGNAL(requestKickClient(int)), SIGNAL(kickClient(int))); p->attachSlot(SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore())); @@ -119,44 +126,37 @@ Client::Client(std::unique_ptr ui, QObject *parent) coreConnection()->init(); } - Client::~Client() { disconnectFromCore(); } - -AbstractUi *Client::mainUi() +AbstractUi* Client::mainUi() { return instance()->_mainUi.get(); } - bool Client::isCoreFeatureEnabled(Quassel::Feature feature) { return coreConnection()->peer() ? coreConnection()->peer()->hasFeature(feature) : false; } - bool Client::isConnected() { return instance()->_connected; } - bool Client::internalCore() { return currentCoreAccount().isInternal(); } - void Client::onDbUpgradeInProgress(bool inProgress) { emit dbUpgradeInProgress(inProgress); } - -void Client::onExitRequested(int exitCode, const QString &reason) +void Client::onExitRequested(int exitCode, const QString& reason) { if (!reason.isEmpty()) { qCritical() << reason; @@ -165,7 +165,6 @@ void Client::onExitRequested(int exitCode, const QString &reason) QCoreApplication::exit(exitCode); } - /*** Network handling ***/ QList Client::networkIds() @@ -173,29 +172,27 @@ QList Client::networkIds() return instance()->_networks.keys(); } - -const Network *Client::network(NetworkId networkid) +const Network* Client::network(NetworkId networkid) { - if (instance()->_networks.contains(networkid)) return instance()->_networks[networkid]; - else return nullptr; + if (instance()->_networks.contains(networkid)) + return instance()->_networks[networkid]; + else + return nullptr; } - -void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels) +void Client::createNetwork(const NetworkInfo& info, const QStringList& persistentChannels) { emit instance()->requestCreateNetwork(info, persistentChannels); } - void Client::removeNetwork(NetworkId id) { emit instance()->requestRemoveNetwork(id); } - -void Client::updateNetwork(const NetworkInfo &info) +void Client::updateNetwork(const NetworkInfo& info) { - Network *netptr = instance()->_networks.value(info.networkId, 0); + Network* netptr = instance()->_networks.value(info.networkId, 0); if (!netptr) { qWarning() << "Update for unknown network requested:" << info; return; @@ -203,8 +200,7 @@ void Client::updateNetwork(const NetworkInfo &info) netptr->requestSetNetworkInfo(info); } - -void Client::addNetwork(Network *net) +void Client::addNetwork(Network* net) { net->setProxy(signalProxy()); signalProxy()->synchronize(net); @@ -214,28 +210,25 @@ void Client::addNetwork(Network *net) emit instance()->networkCreated(net->networkId()); } - void Client::coreNetworkCreated(NetworkId id) { if (_networks.contains(id)) { qWarning() << "Creation of already existing network requested!"; return; } - auto *net = new Network(id, this); + auto* net = new Network(id, this); addNetwork(net); } - void Client::coreNetworkRemoved(NetworkId id) { if (!_networks.contains(id)) return; - Network *net = _networks.take(id); + Network* net = _networks.take(id); emit networkRemoved(net->networkId()); net->deleteLater(); } - /*** Identity handling ***/ QList Client::identityIds() @@ -243,15 +236,15 @@ QList Client::identityIds() return instance()->_identities.keys(); } - -const Identity *Client::identity(IdentityId id) +const Identity* Client::identity(IdentityId id) { - if (instance()->_identities.contains(id)) return instance()->_identities[id]; - else return nullptr; + if (instance()->_identities.contains(id)) + return instance()->_identities[id]; + else + return nullptr; } - -void Client::createIdentity(const CertIdentity &id) +void Client::createIdentity(const CertIdentity& id) { QVariantMap additional; #ifdef HAVE_SSL @@ -261,10 +254,9 @@ void Client::createIdentity(const CertIdentity &id) emit instance()->requestCreateIdentity(id, additional); } - -void Client::updateIdentity(IdentityId id, const QVariantMap &ser) +void Client::updateIdentity(IdentityId id, const QVariantMap& ser) { - Identity *idptr = instance()->_identities.value(id, 0); + Identity* idptr = instance()->_identities.value(id, 0); if (!idptr) { qWarning() << "Update for unknown identity requested:" << id; return; @@ -272,17 +264,15 @@ void Client::updateIdentity(IdentityId id, const QVariantMap &ser) idptr->requestUpdate(ser); } - void Client::removeIdentity(IdentityId id) { emit instance()->requestRemoveIdentity(id); } - -void Client::coreIdentityCreated(const Identity &other) +void Client::coreIdentityCreated(const Identity& other) { if (!_identities.contains(other.id())) { - auto *identity = new Identity(other, this); + auto* identity = new Identity(other, this); _identities[other.id()] = identity; identity->setInitialized(); signalProxy()->synchronize(identity); @@ -293,20 +283,18 @@ void Client::coreIdentityCreated(const Identity &other) } } - void Client::coreIdentityRemoved(IdentityId id) { if (_identities.contains(id)) { emit identityRemoved(id); - Identity *i = _identities.take(id); + Identity* i = _identities.take(id); i->deleteLater(); } } - /*** User input handling ***/ -void Client::userInput(const BufferInfo &bufferInfo, const QString &message) +void Client::userInput(const BufferInfo& bufferInfo, const QString& message) { // we need to make sure that AliasManager is ready before processing input if (aliasManager() && aliasManager()->isInitialized()) @@ -315,7 +303,6 @@ void Client::userInput(const BufferInfo &bufferInfo, const QString &message) instance()->_userInputBuffer.append(qMakePair(bufferInfo, message)); } - void Client::sendBufferedUserInput() { for (int i = 0; i < _userInputBuffer.count(); i++) @@ -324,7 +311,6 @@ void Client::sendBufferedUserInput() _userInputBuffer.clear(); } - /*** core connection stuff ***/ void Client::connectionStateChanged(CoreConnection::ConnectionState state) @@ -341,7 +327,6 @@ void Client::connectionStateChanged(CoreConnection::ConnectionState state) } } - void Client::setSyncedToCore() { // create buffersyncer @@ -358,7 +343,7 @@ void Client::setSyncedToCore() connect(bufferSyncer(), &BufferSyncer::highlightCountChanged, _networkModel, &NetworkModel::highlightCountChanged); connect(networkModel(), &NetworkModel::requestSetLastSeenMsg, bufferSyncer(), &BufferSyncer::requestSetLastSeenMsg); - SignalProxy *p = signalProxy(); + SignalProxy* p = signalProxy(); p->synchronize(bufferSyncer()); // create a new BufferViewManager @@ -387,21 +372,20 @@ void Client::setSyncedToCore() _highlightRuleManager = new HighlightRuleManager(this); p->synchronize(highlightRuleManager()); // Listen to network removed events - connect(this, &Client::networkRemoved, - _highlightRuleManager, &HighlightRuleManager::networkRemoved); - -/* not ready yet - // create TransferManager and DccConfig if core supports them - Q_ASSERT(!_dccConfig); - Q_ASSERT(!_transferManager); - if (isCoreFeatureEnabled(Quassel::Feature::DccFileTransfer)) { - _dccConfig = new DccConfig(this); - p->synchronize(dccConfig()); - _transferManager = new ClientTransferManager(this); - _transferModel->setManager(_transferManager); - p->synchronize(transferManager()); - } -*/ + connect(this, &Client::networkRemoved, _highlightRuleManager, &HighlightRuleManager::networkRemoved); + + /* not ready yet + // create TransferManager and DccConfig if core supports them + Q_ASSERT(!_dccConfig); + Q_ASSERT(!_transferManager); + if (isCoreFeatureEnabled(Quassel::Feature::DccFileTransfer)) { + _dccConfig = new DccConfig(this); + p->synchronize(dccConfig()); + _transferManager = new ClientTransferManager(this); + _transferModel->setManager(_transferManager); + p->synchronize(transferManager()); + } + */ // trigger backlog request once all active bufferviews are initialized connect(bufferViewOverlay(), &BufferViewOverlay::initDone, this, &Client::finishConnectionInitialization); @@ -431,13 +415,11 @@ void Client::finishConnectionInitialization() } } - void Client::requestInitialBacklog() { _backlogManager->requestInitialBacklog(); } - void Client::requestLegacyCoreInfo() { // On older cores, the CoreInfo object was only synchronized on demand. Synchronize now if @@ -458,7 +440,6 @@ void Client::requestLegacyCoreInfo() } } - void Client::disconnectFromCore() { if (!coreConnection()->isConnected()) @@ -467,7 +448,6 @@ void Client::disconnectFromCore() coreConnection()->disconnectFromCore(); } - void Client::setDisconnectedFromCore() { _connected = false; @@ -526,9 +506,9 @@ void Client::setDisconnectedFromCore() _messageModel->clear(); _networkModel->clear(); - QHash::iterator netIter = _networks.begin(); + QHash::iterator netIter = _networks.begin(); while (netIter != _networks.end()) { - Network *net = netIter.value(); + Network* net = netIter.value(); emit networkRemoved(net->networkId()); disconnect(net, &Network::destroyed, this, nullptr); netIter = _networks.erase(netIter); @@ -536,10 +516,10 @@ void Client::setDisconnectedFromCore() } Q_ASSERT(_networks.isEmpty()); - QHash::iterator idIter = _identities.begin(); + QHash::iterator idIter = _identities.begin(); while (idIter != _identities.end()) { emit identityRemoved(idIter.key()); - Identity *id = idIter.value(); + Identity* id = idIter.value(); idIter = _identities.erase(idIter); id->deleteLater(); } @@ -551,13 +531,12 @@ void Client::setDisconnectedFromCore() } } - /*** ***/ void Client::networkDestroyed() { - auto *net = static_cast(sender()); - QHash::iterator netIter = _networks.begin(); + auto* net = static_cast(sender()); + QHash::iterator netIter = _networks.begin(); while (netIter != _networks.end()) { if (*netIter == net) { netIter = _networks.erase(netIter); @@ -569,35 +548,30 @@ void Client::networkDestroyed() } } - // Hmm... we never used this... void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) { - //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg))); + // recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg))); } - -void Client::recvMessage(const Message &msg) +void Client::recvMessage(const Message& msg) { Message msg_ = msg; messageProcessor()->process(msg_); } - -void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) +void Client::setBufferLastSeenMsg(BufferId id, const MsgId& msgId) { if (bufferSyncer()) bufferSyncer()->requestSetLastSeenMsg(id, msgId); } - -void Client::setMarkerLine(BufferId id, const MsgId &msgId) +void Client::setMarkerLine(BufferId id, const MsgId& msgId) { if (bufferSyncer()) bufferSyncer()->requestSetMarkerLine(id, msgId); } - MsgId Client::markerLine(BufferId id) { if (id.isValid() && networkModel()) @@ -605,22 +579,20 @@ MsgId Client::markerLine(BufferId id) return {}; } - void Client::removeBuffer(BufferId id) { - if (!bufferSyncer()) return; + if (!bufferSyncer()) + return; bufferSyncer()->requestRemoveBuffer(id); } - -void Client::renameBuffer(BufferId bufferId, const QString &newName) +void Client::renameBuffer(BufferId bufferId, const QString& newName) { if (!bufferSyncer()) return; bufferSyncer()->requestRenameBuffer(bufferId, newName); } - void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) { if (!bufferSyncer()) @@ -628,7 +600,6 @@ void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2); } - void Client::purgeKnownBufferIds() { if (!bufferSyncer()) @@ -636,7 +607,6 @@ void Client::purgeKnownBufferIds() bufferSyncer()->requestPurgeBufferIds(); } - void Client::bufferRemoved(BufferId bufferId) { // select a sane buffer (status buffer) @@ -656,8 +626,7 @@ void Client::bufferRemoved(BufferId bufferId) networkModel()->removeBuffer(bufferId); } - -void Client::bufferRenamed(BufferId bufferId, const QString &newName) +void Client::bufferRenamed(BufferId bufferId, const QString& newName) { QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId); if (bufferIndex.isValid()) { @@ -665,7 +634,6 @@ void Client::bufferRenamed(BufferId bufferId, const QString &newName) } } - void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) { QModelIndex idx = networkModel()->bufferIndex(bufferId1); @@ -673,34 +641,30 @@ void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) networkModel()->removeBuffer(bufferId2); } - void Client::markBufferAsRead(BufferId id) { if (bufferSyncer() && id.isValid()) bufferSyncer()->requestMarkBufferAsRead(id); } - void Client::refreshLegacyCoreInfo() { instance()->requestLegacyCoreInfo(); } - -void Client::changePassword(const QString &oldPassword, const QString &newPassword) { +void Client::changePassword(const QString& oldPassword, const QString& newPassword) +{ CoreAccount account = currentCoreAccount(); account.setPassword(newPassword); coreAccountModel()->createOrUpdateAccount(account); emit instance()->requestPasswordChange(nullptr, account.user(), oldPassword, newPassword); } - void Client::kickClient(int peerId) { emit instance()->requestKickClient(peerId); } - void Client::corePasswordChanged(PeerPtr, bool success) { if (success) diff --git a/src/client/client.h b/src/client/client.h index dd76191f..0014025a 100644 --- a/src/client/client.h +++ b/src/client/client.h @@ -28,9 +28,9 @@ #include #include "bufferinfo.h" -#include "coreinfo.h" #include "coreaccount.h" #include "coreconnection.h" +#include "coreinfo.h" #include "highlightrulemanager.h" #include "quassel.h" #include "singleton.h" @@ -73,83 +73,84 @@ class CLIENT_EXPORT Client : public QObject, public Singleton Q_OBJECT public: - enum ClientMode { + enum ClientMode + { LocalCore, RemoteCore }; - Client(std::unique_ptr, QObject *parent = nullptr); + Client(std::unique_ptr, QObject* parent = nullptr); ~Client() override; - static AbstractUi *mainUi(); + static AbstractUi* mainUi(); static QList networkIds(); - static const Network *network(NetworkId); + static const Network* network(NetworkId); static QList identityIds(); - static const Identity *identity(IdentityId); + static const Identity* identity(IdentityId); //! Request creation of an identity with the given data. /** The request will be sent to the core, and will be propagated back to all the clients * with a new valid IdentityId. * \param identity The identity template for the new identity. It does not need to have a valid ID. */ - static void createIdentity(const CertIdentity &identity); + static void createIdentity(const CertIdentity& identity); //! Request update of an identity with the given data. /** The request will be sent to the core, and will be propagated back to all the clients. * \param id The identity to be updated. * \param serializedData The identity's content (cf. SyncableObject::toVariantMap()) */ - static void updateIdentity(IdentityId id, const QVariantMap &serializedData); + static void updateIdentity(IdentityId id, const QVariantMap& serializedData); //! Request removal of the identity with the given ID from the core (and all the clients, of course). /** \param id The ID of the identity to be removed. */ static void removeIdentity(IdentityId id); - static void createNetwork(const NetworkInfo &info, const QStringList &persistentChannels = QStringList()); - static void updateNetwork(const NetworkInfo &info); + static void createNetwork(const NetworkInfo& info, const QStringList& persistentChannels = QStringList()); + static void updateNetwork(const NetworkInfo& info); static void removeNetwork(NetworkId id); - static inline NetworkModel *networkModel() { return instance()->_networkModel; } - static inline BufferModel *bufferModel() { return instance()->_bufferModel; } - static inline MessageModel *messageModel() { return instance()->_messageModel; } - static inline AbstractMessageProcessor *messageProcessor() { return instance()->_messageProcessor; } - static inline SignalProxy *signalProxy() { return instance()->_signalProxy; } - - static inline ClientAliasManager *aliasManager() { return instance()->_aliasManager; } - static inline ClientBacklogManager *backlogManager() { return instance()->_backlogManager; } - static inline CoreInfo *coreInfo() { return instance()->_coreInfo; } - static inline DccConfig *dccConfig() { return instance()->_dccConfig; } - static inline ClientIrcListHelper *ircListHelper() { return instance()->_ircListHelper; } - static inline ClientBufferViewManager *bufferViewManager() { return instance()->_bufferViewManager; } - static inline BufferViewOverlay *bufferViewOverlay() { return instance()->_bufferViewOverlay; } - static inline ClientUserInputHandler *inputHandler() { return instance()->_inputHandler; } - static inline NetworkConfig *networkConfig() { return instance()->_networkConfig; } - static inline ClientIgnoreListManager *ignoreListManager() { return instance()->_ignoreListManager; } - static inline HighlightRuleManager *highlightRuleManager() { return instance()->_highlightRuleManager; } - static inline ClientTransferManager *transferManager() { return instance()->_transferManager; } - static inline TransferModel *transferModel() { return instance()->_transferModel; } - - static inline BufferSyncer *bufferSyncer() { return instance()->_bufferSyncer; } - - static inline CoreAccountModel *coreAccountModel() { return instance()->_coreAccountModel; } - static inline CoreConnection *coreConnection() { return instance()->_coreConnection; } + static inline NetworkModel* networkModel() { return instance()->_networkModel; } + static inline BufferModel* bufferModel() { return instance()->_bufferModel; } + static inline MessageModel* messageModel() { return instance()->_messageModel; } + static inline AbstractMessageProcessor* messageProcessor() { return instance()->_messageProcessor; } + static inline SignalProxy* signalProxy() { return instance()->_signalProxy; } + + static inline ClientAliasManager* aliasManager() { return instance()->_aliasManager; } + static inline ClientBacklogManager* backlogManager() { return instance()->_backlogManager; } + static inline CoreInfo* coreInfo() { return instance()->_coreInfo; } + static inline DccConfig* dccConfig() { return instance()->_dccConfig; } + static inline ClientIrcListHelper* ircListHelper() { return instance()->_ircListHelper; } + static inline ClientBufferViewManager* bufferViewManager() { return instance()->_bufferViewManager; } + static inline BufferViewOverlay* bufferViewOverlay() { return instance()->_bufferViewOverlay; } + static inline ClientUserInputHandler* inputHandler() { return instance()->_inputHandler; } + static inline NetworkConfig* networkConfig() { return instance()->_networkConfig; } + static inline ClientIgnoreListManager* ignoreListManager() { return instance()->_ignoreListManager; } + static inline HighlightRuleManager* highlightRuleManager() { return instance()->_highlightRuleManager; } + static inline ClientTransferManager* transferManager() { return instance()->_transferManager; } + static inline TransferModel* transferModel() { return instance()->_transferModel; } + + static inline BufferSyncer* bufferSyncer() { return instance()->_bufferSyncer; } + + static inline CoreAccountModel* coreAccountModel() { return instance()->_coreAccountModel; } + static inline CoreConnection* coreConnection() { return instance()->_coreConnection; } static inline CoreAccount currentCoreAccount() { return coreConnection()->currentAccount(); } static bool isCoreFeatureEnabled(Quassel::Feature feature); static bool isConnected(); static bool internalCore(); - static void userInput(const BufferInfo &bufferInfo, const QString &message); + static void userInput(const BufferInfo& bufferInfo, const QString& message); - static void setBufferLastSeenMsg(BufferId id, const MsgId &msgId); // this is synced to core and other clients - static void setMarkerLine(BufferId id, const MsgId &msgId); // this is synced to core and other clients + static void setBufferLastSeenMsg(BufferId id, const MsgId& msgId); // this is synced to core and other clients + static void setMarkerLine(BufferId id, const MsgId& msgId); // this is synced to core and other clients static MsgId markerLine(BufferId id); static void removeBuffer(BufferId id); - static void renameBuffer(BufferId bufferId, const QString &newName); + static void renameBuffer(BufferId bufferId, const QString& newName); static void mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2); static void purgeKnownBufferIds(); @@ -164,12 +165,10 @@ public: */ static void refreshLegacyCoreInfo(); - static void changePassword(const QString &oldPassword, const QString &newPassword); + static void changePassword(const QString& oldPassword, const QString& newPassword); static void kickClient(int peerId); - void displayIgnoreList(QString ignoreRule) { - emit showIgnoreList(ignoreRule); - } + void displayIgnoreList(QString ignoreRule) { emit showIgnoreList(ignoreRule); } /** * Request to show the channel list dialog for the network, optionally searching by channel name @@ -180,8 +179,7 @@ public: * @param channelFilters Partial channel name to search for, or empty to show all * @param listImmediately If true, immediately list channels, otherwise just show dialog */ - void displayChannelList(NetworkId networkId, const QString &channelFilters = {}, - bool listImmediately = false) + void displayChannelList(NetworkId networkId, const QString& channelFilters = {}, bool listImmediately = false) { emit showChannelList(networkId, channelFilters, listImmediately); } @@ -189,7 +187,7 @@ public: signals: void requestNetworkStates(); - void showConfigWizard(const QVariantMap &coredata); + void showConfigWizard(const QVariantMap& coredata); /** * Request to show the channel list dialog for the network, optionally searching by channel name @@ -200,8 +198,7 @@ signals: * @param channelFilters Partial channel name to search for, or empty to show all * @param listImmediately If true, immediately list channels, otherwise just show dialog */ - void showChannelList(NetworkId networkId, const QString &channelFilters = {}, - bool listImmediately = false); + void showChannelList(NetworkId networkId, const QString& channelFilters = {}, bool listImmediately = false); void showIgnoreList(QString ignoreRule); @@ -234,14 +231,14 @@ signals: void identityRemoved(IdentityId id); //! Sent to the core when an identity shall be created. Should not be used elsewhere. - void requestCreateIdentity(const Identity &, const QVariantMap &); + void requestCreateIdentity(const Identity&, const QVariantMap&); //! Sent to the core when an identity shall be removed. Should not be used elsewhere. void requestRemoveIdentity(IdentityId); void networkCreated(NetworkId id); void networkRemoved(NetworkId id); - void requestCreateNetwork(const NetworkInfo &info, const QStringList &persistentChannels = QStringList()); + void requestCreateNetwork(const NetworkInfo& info, const QStringList& persistentChannels = QStringList()); void requestRemoveNetwork(NetworkId); //! Emitted when a buffer has been marked as read @@ -252,7 +249,7 @@ signals: void bufferMarkedAsRead(BufferId id); //! Requests a password change (user name must match the currently logged in user) - void requestPasswordChange(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword); + void requestPasswordChange(PeerPtr peer, const QString& userName, const QString& oldPassword, const QString& newPassword); void requestKickClient(int peerId); void passwordChanged(bool success); @@ -261,30 +258,30 @@ signals: void dbUpgradeInProgress(bool inProgress); //! Emitted before an exit request is handled - void exitRequested(const QString &reason); + void exitRequested(const QString& reason); public slots: void disconnectFromCore(); void bufferRemoved(BufferId bufferId); - void bufferRenamed(BufferId bufferId, const QString &newName); + void bufferRenamed(BufferId bufferId, const QString& newName); void buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2); void markBufferAsRead(BufferId id); void onDbUpgradeInProgress(bool inProgress); - void onExitRequested(int exitCode, const QString &reason); + void onExitRequested(int exitCode, const QString& reason); private slots: void setSyncedToCore(); void setDisconnectedFromCore(); void connectionStateChanged(CoreConnection::ConnectionState); - void recvMessage(const Message &message); + void recvMessage(const Message& message); void recvStatusMsg(QString network, QString message); void networkDestroyed(); - void coreIdentityCreated(const Identity &); + void coreIdentityCreated(const Identity&); void coreIdentityRemoved(IdentityId); void coreNetworkCreated(NetworkId); void coreNetworkRemoved(NetworkId); @@ -309,41 +306,41 @@ private: */ void requestLegacyCoreInfo(); - static void addNetwork(Network *); + static void addNetwork(Network*); - SignalProxy *_signalProxy{nullptr}; + SignalProxy* _signalProxy{nullptr}; std::unique_ptr _mainUi; - NetworkModel *_networkModel{nullptr}; - BufferModel *_bufferModel{nullptr}; - BufferSyncer *_bufferSyncer{nullptr}; - ClientAliasManager *_aliasManager{nullptr}; - ClientBacklogManager *_backlogManager{nullptr}; - ClientBufferViewManager *_bufferViewManager{nullptr}; - BufferViewOverlay *_bufferViewOverlay{nullptr}; - CoreInfo *_coreInfo{nullptr}; - DccConfig *_dccConfig{nullptr}; - ClientIrcListHelper *_ircListHelper{nullptr}; - ClientUserInputHandler *_inputHandler{nullptr}; - NetworkConfig *_networkConfig{nullptr}; - ClientIgnoreListManager *_ignoreListManager{nullptr}; - HighlightRuleManager *_highlightRuleManager{nullptr}; - ClientTransferManager *_transferManager{nullptr}; - TransferModel *_transferModel{nullptr}; - - MessageModel *_messageModel{nullptr}; - AbstractMessageProcessor *_messageProcessor{nullptr}; - - CoreAccountModel *_coreAccountModel{nullptr}; - CoreConnection *_coreConnection{nullptr}; + NetworkModel* _networkModel{nullptr}; + BufferModel* _bufferModel{nullptr}; + BufferSyncer* _bufferSyncer{nullptr}; + ClientAliasManager* _aliasManager{nullptr}; + ClientBacklogManager* _backlogManager{nullptr}; + ClientBufferViewManager* _bufferViewManager{nullptr}; + BufferViewOverlay* _bufferViewOverlay{nullptr}; + CoreInfo* _coreInfo{nullptr}; + DccConfig* _dccConfig{nullptr}; + ClientIrcListHelper* _ircListHelper{nullptr}; + ClientUserInputHandler* _inputHandler{nullptr}; + NetworkConfig* _networkConfig{nullptr}; + ClientIgnoreListManager* _ignoreListManager{nullptr}; + HighlightRuleManager* _highlightRuleManager{nullptr}; + ClientTransferManager* _transferManager{nullptr}; + TransferModel* _transferModel{nullptr}; + + MessageModel* _messageModel{nullptr}; + AbstractMessageProcessor* _messageProcessor{nullptr}; + + CoreAccountModel* _coreAccountModel{nullptr}; + CoreConnection* _coreConnection{nullptr}; ClientMode clientMode{}; - QHash _networks; - QHash _identities; + QHash _networks; + QHash _identities; bool _connected{false}; - QList > _userInputBuffer; + QList> _userInputBuffer; friend class CoreConnection; }; diff --git a/src/client/clientaliasmanager.cpp b/src/client/clientaliasmanager.cpp index d3c4d089..c5a9994e 100644 --- a/src/client/clientaliasmanager.cpp +++ b/src/client/clientaliasmanager.cpp @@ -22,13 +22,11 @@ #include "client.h" -ClientAliasManager::ClientAliasManager(QObject *parent) +ClientAliasManager::ClientAliasManager(QObject* parent) : AliasManager(parent) -{ -} - +{} -const Network *ClientAliasManager::network(NetworkId id) const +const Network* ClientAliasManager::network(NetworkId id) const { return Client::network(id); } diff --git a/src/client/clientaliasmanager.h b/src/client/clientaliasmanager.h index 45bb6f24..6df5cc93 100644 --- a/src/client/clientaliasmanager.h +++ b/src/client/clientaliasmanager.h @@ -29,8 +29,8 @@ class CLIENT_EXPORT ClientAliasManager : public AliasManager Q_OBJECT public: - explicit ClientAliasManager(QObject *parent = nullptr); + explicit ClientAliasManager(QObject* parent = nullptr); protected: - const Network *network(NetworkId) const override; + const Network* network(NetworkId) const override; }; diff --git a/src/client/clientauthhandler.cpp b/src/client/clientauthhandler.cpp index 668c4a47..a5bf291b 100644 --- a/src/client/clientauthhandler.cpp +++ b/src/client/clientauthhandler.cpp @@ -23,9 +23,9 @@ #include #ifdef HAVE_SSL - #include +# include #else - #include +# include #endif #include "client.h" @@ -36,30 +36,26 @@ using namespace Protocol; -ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent) - : AuthHandler(parent), - _peer(nullptr), - _account(account), - _probing(false), - _legacy(false), - _connectionFeatures(0) -{ - -} +ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject* parent) + : AuthHandler(parent) + , _peer(nullptr) + , _account(account) + , _probing(false) + , _legacy(false) + , _connectionFeatures(0) +{} - -Peer *ClientAuthHandler::peer() const +Peer* ClientAuthHandler::peer() const { return _peer; } - void ClientAuthHandler::connectToCore() { CoreAccountSettings s; #ifdef HAVE_SSL - auto *socket = new QSslSocket(this); + auto* socket = new QSslSocket(this); // make sure the warning is shown if we happen to connect without SSL support later s.setAccountValue("ShowNoClientSslWarning", true); #else @@ -74,14 +70,13 @@ void ClientAuthHandler::connectToCore() s.setAccountValue("ShowNoClientSslWarning", false); } } - QTcpSocket *socket = new QTcpSocket(this); + QTcpSocket* socket = new QTcpSocket(this); #endif #ifndef QT_NO_NETWORKPROXY QNetworkProxy proxy; proxy.setType(_account.proxyType()); - if (_account.proxyType() == QNetworkProxy::Socks5Proxy || - _account.proxyType() == QNetworkProxy::HttpProxy) { + if (_account.proxyType() == QNetworkProxy::Socks5Proxy || _account.proxyType() == QNetworkProxy::HttpProxy) { proxy.setHostName(_account.proxyHostName()); proxy.setPort(_account.proxyPort()); proxy.setUser(_account.proxyUser()); @@ -90,7 +85,8 @@ void ClientAuthHandler::connectToCore() if (_account.proxyType() == QNetworkProxy::DefaultProxy) { QNetworkProxyFactory::setUseSystemConfiguration(true); - } else { + } + else { QNetworkProxyFactory::setUseSystemConfiguration(false); socket->setProxy(proxy); } @@ -105,39 +101,38 @@ void ClientAuthHandler::connectToCore() socket->connectToHost(_account.hostName(), _account.port()); } - void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState) { QString text; - switch(socketState) { - case QAbstractSocket::HostLookupState: - if (!_legacy) - text = tr("Looking up %1...").arg(_account.hostName()); - break; - case QAbstractSocket::ConnectingState: - if (!_legacy) - text = tr("Connecting to %1...").arg(_account.hostName()); - break; - case QAbstractSocket::ConnectedState: - text = tr("Connected to %1").arg(_account.hostName()); - break; - case QAbstractSocket::ClosingState: - if (!_probing) - text = tr("Disconnecting from %1...").arg(_account.hostName()); - break; - case QAbstractSocket::UnconnectedState: - if (!_probing) { - text = tr("Disconnected"); - // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet. - // The baseclass implementation will make sure to only send the signal once. - // However, we do want to prefer a potential socket error signal that may be on route already, so - // give this a chance to overtake us by spinning the loop... - QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected); - } - break; - default: - break; + switch (socketState) { + case QAbstractSocket::HostLookupState: + if (!_legacy) + text = tr("Looking up %1...").arg(_account.hostName()); + break; + case QAbstractSocket::ConnectingState: + if (!_legacy) + text = tr("Connecting to %1...").arg(_account.hostName()); + break; + case QAbstractSocket::ConnectedState: + text = tr("Connected to %1").arg(_account.hostName()); + break; + case QAbstractSocket::ClosingState: + if (!_probing) + text = tr("Disconnecting from %1...").arg(_account.hostName()); + break; + case QAbstractSocket::UnconnectedState: + if (!_probing) { + text = tr("Disconnected"); + // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet. + // The baseclass implementation will make sure to only send the signal once. + // However, we do want to prefer a potential socket error signal that may be on route already, so + // give this a chance to overtake us by spinning the loop... + QTimer::singleShot(0, this, &ClientAuthHandler::onSocketDisconnected); + } + break; + default: + break; } if (!text.isEmpty()) { @@ -152,11 +147,10 @@ void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error) return; } - _probing = false; // all other errors are unrelated to probing and should be handled + _probing = false; // all other errors are unrelated to probing and should be handled AuthHandler::onSocketError(error); } - void ClientAuthHandler::onSocketDisconnected() { if (_probing && _legacy) { @@ -171,7 +165,6 @@ void ClientAuthHandler::onSocketDisconnected() AuthHandler::onSocketDisconnected(); } - void ClientAuthHandler::onSocketConnected() { if (_peer) { @@ -185,7 +178,7 @@ void ClientAuthHandler::onSocketConnected() // First connection attempt, try probing for a capable core _probing = true; - QDataStream stream(socket()); // stream handles the endianness for us + QDataStream stream(socket()); // stream handles the endianness for us stream.setVersion(QDataStream::Qt_4_2); quint32 magic = Protocol::magic; @@ -201,13 +194,13 @@ void ClientAuthHandler::onSocketConnected() PeerFactory::ProtoList protos = PeerFactory::supportedProtocols(); for (int i = 0; i < protos.count(); ++i) { quint32 reply = protos[i].first; - reply |= protos[i].second<<8; + reply |= protos[i].second << 8; if (i == protos.count() - 1) - reply |= 0x80000000; // end list + reply |= 0x80000000; // end list stream << reply; } - socket()->flush(); // make sure the probing data is sent immediately + socket()->flush(); // make sure the probing data is sent immediately return; } @@ -215,32 +208,35 @@ void ClientAuthHandler::onSocketConnected() qDebug() << "Legacy core detected, switching to compatibility mode"; - auto *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this); + auto* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), + this, + socket(), + Compressor::NoCompression, + this); // Only needed for the legacy peer, as all others check the protocol version before instantiation connect(peer, &RemotePeer::protocolVersionMismatch, this, &ClientAuthHandler::onProtocolVersionMismatch); setPeer(peer); } - void ClientAuthHandler::onReadyRead() { if (socket()->bytesAvailable() < 4) return; if (!_probing) - return; // make sure to not read more data than needed + return; // make sure to not read more data than needed _probing = false; disconnect(socket(), &QIODevice::readyRead, this, &ClientAuthHandler::onReadyRead); quint32 reply; - socket()->read((char *)&reply, 4); + socket()->read((char*)&reply, 4); reply = qFromBigEndian(reply); auto type = static_cast(reply & 0xff); - auto protoFeatures = static_cast(reply>>8 & 0xffff); - _connectionFeatures = static_cast(reply>>24); + auto protoFeatures = static_cast(reply >> 8 & 0xffff); + _connectionFeatures = static_cast(reply >> 24); Compressor::CompressionLevel level; if (_connectionFeatures & Protocol::Compression) @@ -248,7 +244,7 @@ void ClientAuthHandler::onReadyRead() else level = Compressor::NoCompression; - RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this); + RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), level, this); if (!peer) { qWarning() << "No valid protocol supported for this core!"; emit errorPopup(tr("Incompatible Quassel Core!
" @@ -266,16 +262,15 @@ void ClientAuthHandler::onReadyRead() setPeer(peer); } - void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected) { emit errorPopup(tr("The Quassel Core you are trying to connect to is too old!
" - "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual)); + "We need at least protocol v%1, but the core speaks v%2 only.") + .arg(expected, actual)); requestDisconnect(tr("Incompatible protocol version, connection to core refused")); } - -void ClientAuthHandler::setPeer(RemotePeer *peer) +void ClientAuthHandler::setPeer(RemotePeer* peer) { qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "..."; @@ -290,7 +285,6 @@ void ClientAuthHandler::setPeer(RemotePeer *peer) checkAndEnableSsl(_connectionFeatures & Protocol::Encryption); } - void ClientAuthHandler::startRegistration() { emit statusMessage(tr("Synchronizing to core...")); @@ -304,15 +298,13 @@ void ClientAuthHandler::startRegistration() _peer->dispatch(RegisterClient(Quassel::Features{}, Quassel::buildInfo().fancyVersionString, Quassel::buildInfo().commitDate, useSsl)); } - -void ClientAuthHandler::handle(const ClientDenied &msg) +void ClientAuthHandler::handle(const ClientDenied& msg) { emit errorPopup(msg.errorString); requestDisconnect(tr("The core refused connection from this client")); } - -void ClientAuthHandler::handle(const ClientRegistered &msg) +void ClientAuthHandler::handle(const ClientRegistered& msg) { _coreConfigured = msg.coreConfigured; _backendInfo = msg.backendInfo; @@ -321,16 +313,15 @@ void ClientAuthHandler::handle(const ClientRegistered &msg) _peer->setFeatures(std::move(msg.features)); // The legacy protocol enables SSL at this point - if(_legacy && _account.useSsl()) + if (_legacy && _account.useSsl()) checkAndEnableSsl(msg.sslSupported); else onConnectionReady(); } - void ClientAuthHandler::onConnectionReady() { - const auto &coreFeatures = _peer->features(); + const auto& coreFeatures = _peer->features(); auto unsupported = coreFeatures.toStringList(false); if (!unsupported.isEmpty()) { quInfo() << qPrintable(tr("Core does not support the following features: %1").arg(unsupported.join(", "))); @@ -346,32 +337,28 @@ void ClientAuthHandler::onConnectionReady() // start wizard emit startCoreSetup(_backendInfo, _authenticatorInfo); } - else // TODO: check if we need LoginEnabled + else // TODO: check if we need LoginEnabled login(); } - -void ClientAuthHandler::setupCore(const SetupData &setupData) +void ClientAuthHandler::setupCore(const SetupData& setupData) { _peer->dispatch(setupData); } - -void ClientAuthHandler::handle(const SetupFailed &msg) +void ClientAuthHandler::handle(const SetupFailed& msg) { emit coreSetupFailed(msg.errorString); } - -void ClientAuthHandler::handle(const SetupDone &msg) +void ClientAuthHandler::handle(const SetupDone& msg) { Q_UNUSED(msg) emit coreSetupSuccessful(); } - -void ClientAuthHandler::login(const QString &user, const QString &password, bool remember) +void ClientAuthHandler::login(const QString& user, const QString& password, bool remember) { _account.setUser(user); _account.setPassword(password); @@ -379,13 +366,12 @@ void ClientAuthHandler::login(const QString &user, const QString &password, bool login(); } - -void ClientAuthHandler::login(const QString &previousError) +void ClientAuthHandler::login(const QString& previousError) { emit statusMessage(tr("Logging in...")); if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) { bool valid = false; - emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call + emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) { requestDisconnect(tr("Login canceled")); return; @@ -395,31 +381,27 @@ void ClientAuthHandler::login(const QString &previousError) _peer->dispatch(Login(_account.user(), _account.password())); } - -void ClientAuthHandler::handle(const LoginFailed &msg) +void ClientAuthHandler::handle(const LoginFailed& msg) { login(msg.errorString); } - -void ClientAuthHandler::handle(const LoginSuccess &msg) +void ClientAuthHandler::handle(const LoginSuccess& msg) { Q_UNUSED(msg) emit loginSuccessful(_account); } - -void ClientAuthHandler::handle(const SessionState &msg) +void ClientAuthHandler::handle(const SessionState& msg) { - disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get + disconnect(socket(), nullptr, this, nullptr); // this is the last message we shall ever get // give up ownership of the peer; CoreSession takes responsibility now _peer->setParent(nullptr); emit handshakeComplete(_peer, msg); } - /*** SSL Stuff ***/ void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl) @@ -432,7 +414,7 @@ void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl) // Make sure the warning is shown next time we don't have SSL in the core s.setAccountValue("ShowNoCoreSslWarning", true); - auto *sslSocket = qobject_cast(socket()); + auto* sslSocket = qobject_cast(socket()); Q_ASSERT(sslSocket); connect(sslSocket, &QSslSocket::encrypted, this, &ClientAuthHandler::onSslSocketEncrypted); connect(sslSocket, selectOverload&>(&QSslSocket::sslErrors), this, &ClientAuthHandler::onSslErrors); @@ -464,7 +446,7 @@ void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl) void ClientAuthHandler::onSslSocketEncrypted() { - auto *socket = qobject_cast(sender()); + auto* socket = qobject_cast(sender()); Q_ASSERT(socket); if (!socket->sslErrors().count()) { @@ -483,15 +465,15 @@ void ClientAuthHandler::onSslSocketEncrypted() startRegistration(); } - void ClientAuthHandler::onSslErrors() { - auto *socket = qobject_cast(sender()); + auto* socket = qobject_cast(sender()); Q_ASSERT(socket); CoreAccountSettings s; QByteArray knownDigest = s.accountValue("SslCert").toByteArray(); - ClientAuthHandler::DigestVersion knownDigestVersion = static_cast(s.accountValue("SslCertDigestVersion").toInt()); + ClientAuthHandler::DigestVersion knownDigestVersion = static_cast( + s.accountValue("SslCertDigestVersion").toInt()); QByteArray calculatedDigest; switch (knownDigestVersion) { diff --git a/src/client/clientauthhandler.h b/src/client/clientauthhandler.h index 8cc07d12..7813eb98 100644 --- a/src/client/clientauthhandler.h +++ b/src/client/clientauthhandler.h @@ -20,8 +20,8 @@ #pragma once -#include "compressor.h" #include "authhandler.h" +#include "compressor.h" #include "coreaccount.h" class QSslSocket; @@ -33,60 +33,61 @@ class ClientAuthHandler : public AuthHandler Q_OBJECT public: - enum DigestVersion { + enum DigestVersion + { Md5, Sha2_512, - Latest=Sha2_512 + Latest = Sha2_512 }; - ClientAuthHandler(CoreAccount account, QObject *parent = nullptr); + ClientAuthHandler(CoreAccount account, QObject* parent = nullptr); - Peer *peer() const; + Peer* peer() const; public slots: void connectToCore(); - void login(const QString &previousError = QString()); - void login(const QString &user, const QString &password, bool remember); - void setupCore(const Protocol::SetupData &setupData); + void login(const QString& previousError = QString()); + void login(const QString& user, const QString& password, bool remember); + void setupCore(const Protocol::SetupData& setupData); signals: - void statusMessage(const QString &message); - void errorMessage(const QString &message); - void errorPopup(const QString &message); + void statusMessage(const QString& message); + void errorMessage(const QString& message); + void errorPopup(const QString& message); void transferProgress(int current, int max); - void requestDisconnect(const QString &errorString = QString(), bool wantReconnect = false); + void requestDisconnect(const QString& errorString = QString(), bool wantReconnect = false); void connectionReady(); - void loginSuccessful(const CoreAccount &account); - void handshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState); + void loginSuccessful(const CoreAccount& account); + void handshakeComplete(RemotePeer* peer, const Protocol::SessionState& sessionState); // These signals MUST be handled synchronously! - void userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage = QString()); - void handleNoSslInClient(bool *accepted); - void handleNoSslInCore(bool *accepted); + void userAuthenticationRequired(CoreAccount* account, bool* valid, const QString& errorMessage = QString()); + void handleNoSslInClient(bool* accepted); + void handleNoSslInCore(bool* accepted); #ifdef HAVE_SSL - void handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently); + void handleSslErrors(const QSslSocket* socket, bool* accepted, bool* permanently); #endif void encrypted(bool isEncrypted = true); - void startCoreSetup(const QVariantList &backendInfo, const QVariantList &authenticatorInfo); + void startCoreSetup(const QVariantList& backendInfo, const QVariantList& authenticatorInfo); void coreSetupSuccessful(); - void coreSetupFailed(const QString &error); + void coreSetupFailed(const QString& error); private: using AuthHandler::handle; - void handle(const Protocol::ClientDenied &msg) override; - void handle(const Protocol::ClientRegistered &msg) override; - void handle(const Protocol::SetupFailed &msg) override; - void handle(const Protocol::SetupDone &msg) override; - void handle(const Protocol::LoginFailed &msg) override; - void handle(const Protocol::LoginSuccess &msg) override; - void handle(const Protocol::SessionState &msg) override; + void handle(const Protocol::ClientDenied& msg) override; + void handle(const Protocol::ClientRegistered& msg) override; + void handle(const Protocol::SetupFailed& msg) override; + void handle(const Protocol::SetupDone& msg) override; + void handle(const Protocol::LoginFailed& msg) override; + void handle(const Protocol::LoginSuccess& msg) override; + void handle(const Protocol::SessionState& msg) override; - void setPeer(RemotePeer *peer); + void setPeer(RemotePeer* peer); void checkAndEnableSsl(bool coreSupportsSsl); void startRegistration(); @@ -107,7 +108,7 @@ private slots: void onConnectionReady(); private: - RemotePeer *_peer; + RemotePeer* _peer; bool _coreConfigured; QVariantList _backendInfo; QVariantList _authenticatorInfo; diff --git a/src/client/clientbacklogmanager.cpp b/src/client/clientbacklogmanager.cpp index 03f851b7..e6254780 100644 --- a/src/client/clientbacklogmanager.cpp +++ b/src/client/clientbacklogmanager.cpp @@ -20,20 +20,18 @@ #include "clientbacklogmanager.h" -#include "abstractmessageprocessor.h" -#include "backlogsettings.h" -#include "backlogrequester.h" -#include "client.h" - #include #include -ClientBacklogManager::ClientBacklogManager(QObject *parent) - : BacklogManager(parent) -{ -} +#include "abstractmessageprocessor.h" +#include "backlogrequester.h" +#include "backlogsettings.h" +#include "client.h" +ClientBacklogManager::ClientBacklogManager(QObject* parent) + : BacklogManager(parent) +{} QVariantList ClientBacklogManager::requestBacklog(BufferId bufferId, MsgId first, MsgId last, int limit, int additional) { @@ -41,15 +39,17 @@ QVariantList ClientBacklogManager::requestBacklog(BufferId bufferId, MsgId first return BacklogManager::requestBacklog(bufferId, first, last, limit, additional); } - void ClientBacklogManager::receiveBacklog(BufferId bufferId, MsgId first, MsgId last, int limit, int additional, QVariantList msgs) { - Q_UNUSED(first) Q_UNUSED(last) Q_UNUSED(limit) Q_UNUSED(additional) + Q_UNUSED(first) + Q_UNUSED(last) + Q_UNUSED(limit) + Q_UNUSED(additional) emit messagesReceived(bufferId, msgs.count()); MessageList msglist; - foreach(QVariant v, msgs) { + foreach (QVariant v, msgs) { Message msg = v.value(); msg.setFlags(msg.flags() | Message::Backlog); msglist << msg; @@ -68,13 +68,15 @@ void ClientBacklogManager::receiveBacklog(BufferId bufferId, MsgId first, MsgId } } - void ClientBacklogManager::receiveBacklogAll(MsgId first, MsgId last, int limit, int additional, QVariantList msgs) { - Q_UNUSED(first) Q_UNUSED(last) Q_UNUSED(limit) Q_UNUSED(additional) + Q_UNUSED(first) + Q_UNUSED(last) + Q_UNUSED(limit) + Q_UNUSED(additional) MessageList msglist; - foreach(QVariant v, msgs) { + foreach (QVariant v, msgs) { Message msg = v.value(); msg.setFlags(msg.flags() | Message::Backlog); msglist << msg; @@ -83,7 +85,6 @@ void ClientBacklogManager::receiveBacklogAll(MsgId first, MsgId last, int limit, dispatchMessages(msglist); } - void ClientBacklogManager::requestInitialBacklog() { if (_initBacklogRequested) { @@ -112,12 +113,11 @@ void ClientBacklogManager::requestInitialBacklog() } } - -BufferIdList ClientBacklogManager::filterNewBufferIds(const BufferIdList &bufferIds) +BufferIdList ClientBacklogManager::filterNewBufferIds(const BufferIdList& bufferIds) { BufferIdList newBuffers; QSet availableBuffers = Client::networkModel()->allBufferIds().toSet(); - foreach(BufferId bufferId, bufferIds) { + foreach (BufferId bufferId, bufferIds) { if (_buffersRequested.contains(bufferId) || !availableBuffers.contains(bufferId)) continue; newBuffers << bufferId; @@ -125,8 +125,7 @@ BufferIdList ClientBacklogManager::filterNewBufferIds(const BufferIdList &buffer return newBuffers; } - -void ClientBacklogManager::checkForBacklog(const QList &bufferIds) +void ClientBacklogManager::checkForBacklog(const QList& bufferIds) { // we ingore all backlogrequests until we had our initial request if (!_initBacklogRequested) { @@ -143,8 +142,7 @@ void ClientBacklogManager::checkForBacklog(const QList &bufferIds) break; case BacklogRequester::PerBufferUnread: case BacklogRequester::PerBufferFixed: - default: - { + default: { BufferIdList buffers = filterNewBufferIds(bufferIds); if (!buffers.isEmpty()) _requester->requestBacklog(buffers); @@ -152,14 +150,12 @@ void ClientBacklogManager::checkForBacklog(const QList &bufferIds) }; } - bool ClientBacklogManager::isBuffering() { return _requester && _requester->isBuffering(); } - -void ClientBacklogManager::dispatchMessages(const MessageList &messages, bool sort) +void ClientBacklogManager::dispatchMessages(const MessageList& messages, bool sort) { if (messages.isEmpty()) return; @@ -175,7 +171,6 @@ void ClientBacklogManager::dispatchMessages(const MessageList &messages, bool so emit messagesProcessed(tr("Processed %1 messages in %2 seconds.").arg(messages.count()).arg((float)(end_t - start_t) / CLOCKS_PER_SEC)); } - void ClientBacklogManager::reset() { delete _requester; diff --git a/src/client/clientbacklogmanager.h b/src/client/clientbacklogmanager.h index aa58a4df..036eaa3e 100644 --- a/src/client/clientbacklogmanager.h +++ b/src/client/clientbacklogmanager.h @@ -32,10 +32,10 @@ class CLIENT_EXPORT ClientBacklogManager : public BacklogManager Q_OBJECT public: - ClientBacklogManager(QObject *parent = nullptr); + ClientBacklogManager(QObject* parent = nullptr); // helper for the backlogRequester, as it isn't a QObject and can't emit itself - inline void emitMessagesRequested(const QString &msg) const { emit messagesRequested(msg); } + inline void emitMessagesRequested(const QString& msg) const { emit messagesRequested(msg); } void reset(); @@ -47,27 +47,26 @@ public slots: void requestInitialBacklog(); void checkForBacklog(BufferId bufferId); - void checkForBacklog(const BufferIdList &bufferIds); + void checkForBacklog(const BufferIdList& bufferIds); signals: void messagesReceived(BufferId bufferId, int count) const; - void messagesRequested(const QString &) const; - void messagesProcessed(const QString &) const; + void messagesRequested(const QString&) const; + void messagesProcessed(const QString&) const; void updateProgress(int, int); private: bool isBuffering(); - BufferIdList filterNewBufferIds(const BufferIdList &bufferIds); + BufferIdList filterNewBufferIds(const BufferIdList& bufferIds); - void dispatchMessages(const MessageList &messages, bool sort = false); + void dispatchMessages(const MessageList& messages, bool sort = false); - BacklogRequester *_requester{nullptr}; + BacklogRequester* _requester{nullptr}; bool _initBacklogRequested{false}; QSet _buffersRequested; }; - // inlines inline void ClientBacklogManager::checkForBacklog(BufferId bufferId) { diff --git a/src/client/clientbufferviewconfig.cpp b/src/client/clientbufferviewconfig.cpp index 7d5362ef..983a6cd2 100644 --- a/src/client/clientbufferviewconfig.cpp +++ b/src/client/clientbufferviewconfig.cpp @@ -20,14 +20,13 @@ #include "clientbufferviewconfig.h" -ClientBufferViewConfig::ClientBufferViewConfig(int bufferViewId, QObject *parent) - : BufferViewConfig(bufferViewId, parent), - _locked(false) +ClientBufferViewConfig::ClientBufferViewConfig(int bufferViewId, QObject* parent) + : BufferViewConfig(bufferViewId, parent) + , _locked(false) { connect(this, &SyncableObject::initDone, this, &ClientBufferViewConfig::ensureDecoration); } - // currently we don't have a possibility to configure disableDecoration // if we have an old config this value can be true which is... bad. // so we upgrade the core stored bufferViewConfig. diff --git a/src/client/clientbufferviewconfig.h b/src/client/clientbufferviewconfig.h index 8205d2bb..6f3738d1 100644 --- a/src/client/clientbufferviewconfig.h +++ b/src/client/clientbufferviewconfig.h @@ -29,7 +29,7 @@ class CLIENT_EXPORT ClientBufferViewConfig : public BufferViewConfig Q_OBJECT public: - ClientBufferViewConfig(int bufferViewId, QObject *parent = nullptr); + ClientBufferViewConfig(int bufferViewId, QObject* parent = nullptr); inline bool isLocked() { return _locked || sortAlphabetically(); } inline void setLocked(bool locked) { _locked = locked; } @@ -37,7 +37,7 @@ public: inline void unlock() { setLocked(false); }; private slots: - void ensureDecoration(); // remove this in next release + void ensureDecoration(); // remove this in next release private: bool _locked; diff --git a/src/client/clientbufferviewmanager.cpp b/src/client/clientbufferviewmanager.cpp index d1975f67..c4731321 100644 --- a/src/client/clientbufferviewmanager.cpp +++ b/src/client/clientbufferviewmanager.cpp @@ -20,38 +20,33 @@ #include "clientbufferviewmanager.h" -#include "clientbufferviewconfig.h" #include "client.h" +#include "clientbufferviewconfig.h" #include "networkmodel.h" -ClientBufferViewManager::ClientBufferViewManager(SignalProxy *proxy, QObject *parent) +ClientBufferViewManager::ClientBufferViewManager(SignalProxy* proxy, QObject* parent) : BufferViewManager(proxy, parent) -{ -} +{} - -BufferViewConfig *ClientBufferViewManager::bufferViewConfigFactory(int bufferViewConfigId) +BufferViewConfig* ClientBufferViewManager::bufferViewConfigFactory(int bufferViewConfigId) { return new ClientBufferViewConfig(bufferViewConfigId, this); } - -QList ClientBufferViewManager::clientBufferViewConfigs() const +QList ClientBufferViewManager::clientBufferViewConfigs() const { - QList clientConfigs; - foreach(BufferViewConfig *config, bufferViewConfigs()) { - clientConfigs << static_cast(config); + QList clientConfigs; + foreach (BufferViewConfig* config, bufferViewConfigs()) { + clientConfigs << static_cast(config); } return clientConfigs; } - -ClientBufferViewConfig *ClientBufferViewManager::clientBufferViewConfig(int bufferViewId) const +ClientBufferViewConfig* ClientBufferViewManager::clientBufferViewConfig(int bufferViewId) const { - return static_cast(bufferViewConfig(bufferViewId)); + return static_cast(bufferViewConfig(bufferViewId)); } - void ClientBufferViewManager::setInitialized() { if (bufferViewConfigs().isEmpty()) { diff --git a/src/client/clientbufferviewmanager.h b/src/client/clientbufferviewmanager.h index 62123a11..a5cd3b9a 100644 --- a/src/client/clientbufferviewmanager.h +++ b/src/client/clientbufferviewmanager.h @@ -32,14 +32,14 @@ class CLIENT_EXPORT ClientBufferViewManager : public BufferViewManager Q_OBJECT public: - ClientBufferViewManager(SignalProxy *proxy, QObject *parent = nullptr); + ClientBufferViewManager(SignalProxy* proxy, QObject* parent = nullptr); - QList clientBufferViewConfigs() const; - ClientBufferViewConfig *clientBufferViewConfig(int bufferViewId) const; + QList clientBufferViewConfigs() const; + ClientBufferViewConfig* clientBufferViewConfig(int bufferViewId) const; public slots: void setInitialized() override; protected: - BufferViewConfig *bufferViewConfigFactory(int bufferViewConfigId) override; + BufferViewConfig* bufferViewConfigFactory(int bufferViewConfigId) override; }; diff --git a/src/client/clientidentity.cpp b/src/client/clientidentity.cpp index 8e561688..2a09f041 100644 --- a/src/client/clientidentity.cpp +++ b/src/client/clientidentity.cpp @@ -23,28 +23,22 @@ #include "client.h" #include "signalproxy.h" -CertIdentity::CertIdentity(IdentityId id, QObject *parent) +CertIdentity::CertIdentity(IdentityId id, QObject* parent) : Identity(id, parent) -{ -} +{} - -CertIdentity::CertIdentity(const Identity &other, QObject *parent) +CertIdentity::CertIdentity(const Identity& other, QObject* parent) : Identity(other, parent) -{ -} - +{} -CertIdentity::CertIdentity(const CertIdentity &other, QObject *parent) +CertIdentity::CertIdentity(const CertIdentity& other, QObject* parent) : Identity(other, parent) #ifdef HAVE_SSL , _isDirty(other._isDirty) , _sslKey(other._sslKey) , _sslCert(other._sslCert) #endif -{ -} - +{} #ifdef HAVE_SSL void CertIdentity::enableEditSsl(bool enable) @@ -53,15 +47,14 @@ void CertIdentity::enableEditSsl(bool enable) return; _certManager = new ClientCertManager(id(), this); - if (isValid()) { // this means we are not a newly created Identity but have a proper Id + if (isValid()) { // this means we are not a newly created Identity but have a proper Id Client::signalProxy()->synchronize(_certManager); connect(_certManager, &SyncableObject::updated, this, &CertIdentity::markClean); connect(_certManager, &SyncableObject::initDone, this, &CertIdentity::markClean); } } - -void CertIdentity::setSslKey(const QSslKey &key) +void CertIdentity::setSslKey(const QSslKey& key) { if (key.toPem() == _sslKey.toPem()) return; @@ -69,8 +62,7 @@ void CertIdentity::setSslKey(const QSslKey &key) _isDirty = true; } - -void CertIdentity::setSslCert(const QSslCertificate &cert) +void CertIdentity::setSslCert(const QSslCertificate& cert) { if (cert.toPem() == _sslCert.toPem()) return; @@ -78,7 +70,6 @@ void CertIdentity::setSslCert(const QSslCertificate &cert) _isDirty = true; } - void CertIdentity::requestUpdateSslSettings() { if (!_certManager) @@ -87,18 +78,16 @@ void CertIdentity::requestUpdateSslSettings() _certManager->requestUpdate(_certManager->toVariantMap()); } - void CertIdentity::markClean() { _isDirty = false; emit sslSettingsUpdated(); } - // ======================================== // ClientCertManager // ======================================== -void ClientCertManager::setSslKey(const QByteArray &encoded) +void ClientCertManager::setSslKey(const QByteArray& encoded) { QSslKey key(encoded, QSsl::Rsa); if (key.isNull() && Client::isCoreFeatureEnabled(Quassel::Feature::EcdsaCertfpKeys)) @@ -108,10 +97,9 @@ void ClientCertManager::setSslKey(const QByteArray &encoded) _certIdentity->setSslKey(key); } - -void ClientCertManager::setSslCert(const QByteArray &encoded) +void ClientCertManager::setSslCert(const QByteArray& encoded) { _certIdentity->setSslCert(QSslCertificate(encoded)); } -#endif // HAVE_SSL +#endif // HAVE_SSL diff --git a/src/client/clientidentity.h b/src/client/clientidentity.h index fb35acae..dfdf2b3d 100644 --- a/src/client/clientidentity.h +++ b/src/client/clientidentity.h @@ -31,9 +31,9 @@ class CLIENT_EXPORT CertIdentity : public Identity Q_OBJECT public: - CertIdentity(IdentityId id = 0, QObject *parent = nullptr); - CertIdentity(const Identity &other, QObject *parent = nullptr); - CertIdentity(const CertIdentity &other, QObject *parent = nullptr); + CertIdentity(IdentityId id = 0, QObject* parent = nullptr); + CertIdentity(const Identity& other, QObject* parent = nullptr); + CertIdentity(const CertIdentity& other, QObject* parent = nullptr); #ifdef HAVE_SSL inline bool isDirty() const { return _isDirty; } @@ -43,11 +43,11 @@ public: #ifdef HAVE_SSL void enableEditSsl(bool enable = true); - inline const QSslKey &sslKey() const { return _sslKey; } - inline const QSslCertificate &sslCert() const { return _sslCert; } + inline const QSslKey& sslKey() const { return _sslKey; } + inline const QSslCertificate& sslCert() const { return _sslCert; } - void setSslKey(const QSslKey &key); - void setSslCert(const QSslCertificate &cert); + void setSslKey(const QSslKey& key); + void setSslCert(const QSslCertificate& cert); public slots: void requestUpdateSslSettings(); @@ -59,14 +59,13 @@ private slots: void markClean(); private: - ClientCertManager *_certManager{nullptr}; + ClientCertManager* _certManager{nullptr}; bool _isDirty{false}; QSslKey _sslKey; QSslCertificate _sslCert; -#endif //HAVE_SSL +#endif // HAVE_SSL }; - // ======================================== // ClientCertManager // ======================================== @@ -77,17 +76,20 @@ class ClientCertManager : public CertManager Q_OBJECT public: - ClientCertManager(IdentityId id, CertIdentity *parent) : CertManager(id, parent), _certIdentity(parent) {} + ClientCertManager(IdentityId id, CertIdentity* parent) + : CertManager(id, parent) + , _certIdentity(parent) + {} - inline const QSslKey &sslKey() const override { return _certIdentity->sslKey(); } - inline const QSslCertificate &sslCert() const override { return _certIdentity->sslCert(); } + inline const QSslKey& sslKey() const override { return _certIdentity->sslKey(); } + inline const QSslCertificate& sslCert() const override { return _certIdentity->sslCert(); } public slots: - void setSslKey(const QByteArray &encoded) override; - void setSslCert(const QByteArray &encoded) override; + void setSslKey(const QByteArray& encoded) override; + void setSslCert(const QByteArray& encoded) override; private: - CertIdentity *_certIdentity; + CertIdentity* _certIdentity; }; -#endif //HAVE_SSL +#endif // HAVE_SSL diff --git a/src/client/clientignorelistmanager.cpp b/src/client/clientignorelistmanager.cpp index a23f8917..5ab91dcf 100644 --- a/src/client/clientignorelistmanager.cpp +++ b/src/client/clientignorelistmanager.cpp @@ -20,26 +20,25 @@ #include "clientignorelistmanager.h" -ClientIgnoreListManager::ClientIgnoreListManager(QObject *parent) +ClientIgnoreListManager::ClientIgnoreListManager(QObject* parent) : IgnoreListManager(parent) { connect(this, &SyncableObject::updatedRemotely, this, &ClientIgnoreListManager::ignoreListChanged); } - -bool ClientIgnoreListManager::pureMatch(const IgnoreListItem &item, const QString &string) const +bool ClientIgnoreListManager::pureMatch(const IgnoreListItem& item, const QString& string) const { return (item.contentsMatcher().match(string)); } - -QMap ClientIgnoreListManager::matchingRulesForHostmask(const QString &hostmask, const QString &network, const QString &channel) const +QMap ClientIgnoreListManager::matchingRulesForHostmask(const QString& hostmask, + const QString& network, + const QString& channel) const { QMap result; - foreach(IgnoreListItem item, ignoreList()) { + foreach (IgnoreListItem item, ignoreList()) { if (item.type() == SenderIgnore && pureMatch(item, hostmask) - && ((network.isEmpty() && channel.isEmpty()) - || item.scope() == GlobalScope + && ((network.isEmpty() && channel.isEmpty()) || item.scope() == GlobalScope || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network)) || (item.scope() == ChannelScope && item.scopeRuleMatcher().match(channel)))) { result[item.contents()] = item.isEnabled(); diff --git a/src/client/clientignorelistmanager.h b/src/client/clientignorelistmanager.h index 797235e3..f043e0e7 100644 --- a/src/client/clientignorelistmanager.h +++ b/src/client/clientignorelistmanager.h @@ -22,28 +22,29 @@ #include "client-export.h" -#include "ignorelistmanager.h" #include +#include "ignorelistmanager.h" + class CLIENT_EXPORT ClientIgnoreListManager : public IgnoreListManager { Q_OBJECT public: - explicit ClientIgnoreListManager(QObject *parent = nullptr); + explicit ClientIgnoreListManager(QObject* parent = nullptr); //! Fetch all matching ignore rules for a given hostmask /** \param hostmask The hostmask of the user - * \param network The network name - * \param channel The channel name - * \return Returns a QMap with the rule as key and a bool, representing if the rule is enabled or not, as value - */ - QMap matchingRulesForHostmask(const QString &hostmask, const QString &network, const QString &channel) const; + * \param network The network name + * \param channel The channel name + * \return Returns a QMap with the rule as key and a bool, representing if the rule is enabled or not, as value + */ + QMap matchingRulesForHostmask(const QString& hostmask, const QString& network, const QString& channel) const; signals: void ignoreListChanged(); private: // matches an ignore rule against a given string - bool pureMatch(const IgnoreListItem &item, const QString &string) const; + bool pureMatch(const IgnoreListItem& item, const QString& string) const; }; diff --git a/src/client/clientirclisthelper.cpp b/src/client/clientirclisthelper.cpp index 1e842e36..52cb931e 100644 --- a/src/client/clientirclisthelper.cpp +++ b/src/client/clientirclisthelper.cpp @@ -25,14 +25,13 @@ #include "client.h" #include "irclistmodel.h" -QVariantList ClientIrcListHelper::requestChannelList(const NetworkId &netId, const QStringList &channelFilters) +QVariantList ClientIrcListHelper::requestChannelList(const NetworkId& netId, const QStringList& channelFilters) { _netId = netId; return IrcListHelper::requestChannelList(netId, channelFilters); } - -void ClientIrcListHelper::receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QVariantList &channels) +void ClientIrcListHelper::receiveChannelList(const NetworkId& netId, const QStringList& channelFilters, const QVariantList& channels) { QVariantList::const_iterator iter = channels.constBegin(); QVariantList::const_iterator iterEnd = channels.constEnd(); @@ -48,8 +47,7 @@ void ClientIrcListHelper::receiveChannelList(const NetworkId &netId, const QStri emit channelListReceived(netId, channelFilters, channelList); } - -void ClientIrcListHelper::reportFinishedList(const NetworkId &netId) +void ClientIrcListHelper::reportFinishedList(const NetworkId& netId) { if (_netId == netId) { requestChannelList(netId, QStringList()); diff --git a/src/client/clientirclisthelper.h b/src/client/clientirclisthelper.h index d4dc98d0..7c32a10a 100644 --- a/src/client/clientirclisthelper.h +++ b/src/client/clientirclisthelper.h @@ -29,18 +29,21 @@ class CLIENT_EXPORT ClientIrcListHelper : public IrcListHelper Q_OBJECT public: - inline ClientIrcListHelper(QObject *object = nullptr) : IrcListHelper(object) {}; + inline ClientIrcListHelper(QObject* object = nullptr) + : IrcListHelper(object){}; public slots: - QVariantList requestChannelList(const NetworkId &netId, const QStringList &channelFilters) override; - void receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QVariantList &channels) override; - void reportFinishedList(const NetworkId &netId) override; - inline void reportError(const QString &error) override { emit errorReported(error); } + QVariantList requestChannelList(const NetworkId& netId, const QStringList& channelFilters) override; + void receiveChannelList(const NetworkId& netId, const QStringList& channelFilters, const QVariantList& channels) override; + void reportFinishedList(const NetworkId& netId) override; + inline void reportError(const QString& error) override { emit errorReported(error); } signals: - void channelListReceived(const NetworkId &netId, const QStringList &channelFilters, const QList &channelList); - void finishedListReported(const NetworkId &netId); - void errorReported(const QString &error); + void channelListReceived(const NetworkId& netId, + const QStringList& channelFilters, + const QList& channelList); + void finishedListReported(const NetworkId& netId); + void errorReported(const QString& error); private: NetworkId _netId; diff --git a/src/client/clientsettings.cpp b/src/client/clientsettings.cpp index 35860939..abac74c8 100644 --- a/src/client/clientsettings.cpp +++ b/src/client/clientsettings.cpp @@ -18,44 +18,39 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include - -#include - #include "clientsettings.h" +#include + #include +#include #ifdef HAVE_SSL -#include +# include #endif #include "client.h" #include "quassel.h" -ClientSettings::ClientSettings(QString g) : Settings(g, Quassel::buildInfo().clientApplicationName) -{ -} - +ClientSettings::ClientSettings(QString g) + : Settings(g, Quassel::buildInfo().clientApplicationName) +{} /***********************************************************************************************/ CoreAccountSettings::CoreAccountSettings(QString subgroup) - : ClientSettings("CoreAccounts"), - _subgroup(std::move(subgroup)) -{ -} - + : ClientSettings("CoreAccounts") + , _subgroup(std::move(subgroup)) +{} -QString CoreAccountSettings::keyForNotify(const QString &key) const +QString CoreAccountSettings::keyForNotify(const QString& key) const { return QString{"%1/%2/%3"}.arg(Client::currentCoreAccount().accountId().toInt()).arg(_subgroup).arg(key); } - QList CoreAccountSettings::knownAccounts() const { QList ids; - foreach(const QString &key, localChildGroups()) { + foreach (const QString& key, localChildGroups()) { AccountId acc = key.toInt(); if (acc.isValid()) ids << acc; @@ -63,59 +58,50 @@ QList CoreAccountSettings::knownAccounts() const return ids; } - AccountId CoreAccountSettings::lastAccount() const { return localValue("LastAccount", 0).toInt(); } - void CoreAccountSettings::setLastAccount(AccountId account) { setLocalValue("LastAccount", account.toInt()); } - AccountId CoreAccountSettings::autoConnectAccount() const { return localValue("AutoConnectAccount", 0).toInt(); } - void CoreAccountSettings::setAutoConnectAccount(AccountId account) { setLocalValue("AutoConnectAccount", account.toInt()); } - bool CoreAccountSettings::autoConnectOnStartup() const { return localValue("AutoConnectOnStartup", false).toBool(); } - void CoreAccountSettings::setAutoConnectOnStartup(bool b) { setLocalValue("AutoConnectOnStartup", b); } - bool CoreAccountSettings::autoConnectToFixedAccount() const { return localValue("AutoConnectToFixedAccount", false).toBool(); } - void CoreAccountSettings::setAutoConnectToFixedAccount(bool b) { setLocalValue("AutoConnectToFixedAccount", b); } - -void CoreAccountSettings::storeAccountData(AccountId id, const QVariantMap &data) +void CoreAccountSettings::storeAccountData(AccountId id, const QVariantMap& data) { QString base = QString::number(id.toInt()); - foreach(const QString &key, data.keys()) { + foreach (const QString& key, data.keys()) { setLocalValue(base + "/" + key, data.value(key)); } @@ -123,12 +109,11 @@ void CoreAccountSettings::storeAccountData(AccountId id, const QVariantMap &data removeLocalKey(QString("%1/Connection").arg(base)); } - QVariantMap CoreAccountSettings::retrieveAccountData(AccountId id) const { QVariantMap map; QString base = QString::number(id.toInt()); - foreach(const QString &key, localChildKeys(base)) { + foreach (const QString& key, localChildKeys(base)) { map[key] = localValue(base + "/" + key); } @@ -157,24 +142,21 @@ QVariantMap CoreAccountSettings::retrieveAccountData(AccountId id) const return map; } - -void CoreAccountSettings::setAccountValue(const QString &key, const QVariant &value) +void CoreAccountSettings::setAccountValue(const QString& key, const QVariant& value) { if (!Client::currentCoreAccount().isValid()) return; setLocalValue(QString("%1/%2/%3").arg(Client::currentCoreAccount().accountId().toInt()).arg(_subgroup).arg(key), value); } - -QVariant CoreAccountSettings::accountValue(const QString &key, const QVariant &def) const +QVariant CoreAccountSettings::accountValue(const QString& key, const QVariant& def) const { if (!Client::currentCoreAccount().isValid()) return QVariant(); return localValue(QString("%1/%2/%3").arg(Client::currentCoreAccount().accountId().toInt()).arg(_subgroup).arg(key), def); } - -void CoreAccountSettings::setJumpKeyMap(const QHash &keyMap) +void CoreAccountSettings::setJumpKeyMap(const QHash& keyMap) { QVariantMap variants; QHash::const_iterator mapIter = keyMap.constBegin(); @@ -185,7 +167,6 @@ void CoreAccountSettings::setJumpKeyMap(const QHash &keyMap) setAccountValue("JumpKeyMap", variants); } - QHash CoreAccountSettings::jumpKeyMap() const { QHash keyMap; @@ -198,17 +179,15 @@ QHash CoreAccountSettings::jumpKeyMap() const return keyMap; } - -void CoreAccountSettings::setBufferViewOverlay(const QSet &viewIds) +void CoreAccountSettings::setBufferViewOverlay(const QSet& viewIds) { QVariantList variants; - foreach(int viewId, viewIds) { + foreach (int viewId, viewIds) { variants << qVariantFromValue(viewId); } setAccountValue("BufferViewOverlay", variants); } - QSet CoreAccountSettings::bufferViewOverlay() const { QSet viewIds; @@ -219,20 +198,17 @@ QSet CoreAccountSettings::bufferViewOverlay() const return viewIds; } - void CoreAccountSettings::removeAccount(AccountId id) { removeLocalKey(QString("%1").arg(id.toInt())); } - void CoreAccountSettings::clearAccounts() { - foreach(const QString &key, localChildGroups()) - removeLocalKey(key); + foreach (const QString& key, localChildGroups()) + removeLocalKey(key); } - /***********************************************************************************************/ // CoreConnectionSettings: @@ -245,201 +221,167 @@ void CoreConnectionSettings::setNetworkDetectionMode(NetworkDetectionMode mode) setLocalValue("NetworkDetectionMode", mode); } - CoreConnectionSettings::NetworkDetectionMode CoreConnectionSettings::networkDetectionMode() const { auto mode = localValue("NetworkDetectionMode", UseQNetworkConfigurationManager).toInt(); if (mode == 0) - mode = UseQNetworkConfigurationManager; // UseSolid is gone, map that to the new default + mode = UseQNetworkConfigurationManager; // UseSolid is gone, map that to the new default return static_cast(mode); } - void CoreConnectionSettings::setAutoReconnect(bool autoReconnect) { setLocalValue("AutoReconnect", autoReconnect); } - bool CoreConnectionSettings::autoReconnect() const { return localValue("AutoReconnect", true).toBool(); } - void CoreConnectionSettings::setPingTimeoutInterval(int interval) { setLocalValue("PingTimeoutInterval", interval); } - int CoreConnectionSettings::pingTimeoutInterval() const { return localValue("PingTimeoutInterval", 60).toInt(); } - void CoreConnectionSettings::setReconnectInterval(int interval) { setLocalValue("ReconnectInterval", interval); } - int CoreConnectionSettings::reconnectInterval() const { return localValue("ReconnectInterval", 60).toInt(); } - /***********************************************************************************************/ // NotificationSettings: NotificationSettings::NotificationSettings() : ClientSettings("Notification") -{ -} - +{} -void NotificationSettings::setValue(const QString &key, const QVariant &data) +void NotificationSettings::setValue(const QString& key, const QVariant& data) { setLocalValue(key, data); } - -QVariant NotificationSettings::value(const QString &key, const QVariant &def) const +QVariant NotificationSettings::value(const QString& key, const QVariant& def) const { return localValue(key, def); } - -void NotificationSettings::remove(const QString &key) +void NotificationSettings::remove(const QString& key) { removeLocalKey(key); } - -void NotificationSettings::setHighlightList(const QVariantList &highlightList) +void NotificationSettings::setHighlightList(const QVariantList& highlightList) { setLocalValue("Highlights/CustomList", highlightList); } - QVariantList NotificationSettings::highlightList() const { return localValue("Highlights/CustomList").toList(); } - void NotificationSettings::setHighlightNick(NotificationSettings::HighlightNickType highlightNickType) { setLocalValue("Highlights/HighlightNick", highlightNickType); } - NotificationSettings::HighlightNickType NotificationSettings::highlightNick() const { - return (NotificationSettings::HighlightNickType)localValue("Highlights/HighlightNick", - CurrentNick).toInt(); + return (NotificationSettings::HighlightNickType)localValue("Highlights/HighlightNick", CurrentNick).toInt(); } - void NotificationSettings::setNicksCaseSensitive(bool cs) { setLocalValue("Highlights/NicksCaseSensitive", cs); } - bool NotificationSettings::nicksCaseSensitive() const { return localValue("Highlights/NicksCaseSensitive", false).toBool(); } - // ======================================== // TabCompletionSettings // ======================================== TabCompletionSettings::TabCompletionSettings() : ClientSettings("TabCompletion") -{ -} - +{} -void TabCompletionSettings::setCompletionSuffix(const QString &suffix) +void TabCompletionSettings::setCompletionSuffix(const QString& suffix) { setLocalValue("CompletionSuffix", suffix); } - QString TabCompletionSettings::completionSuffix() const { return localValue("CompletionSuffix", ": ").toString(); } - void TabCompletionSettings::setAddSpaceMidSentence(bool space) { setLocalValue("AddSpaceMidSentence", space); } - bool TabCompletionSettings::addSpaceMidSentence() const { return localValue("AddSpaceMidSentence", false).toBool(); } - void TabCompletionSettings::setSortMode(SortMode mode) { setLocalValue("SortMode", mode); } - TabCompletionSettings::SortMode TabCompletionSettings::sortMode() const { return static_cast(localValue("SortMode"), LastActivity); } - void TabCompletionSettings::setCaseSensitivity(Qt::CaseSensitivity cs) { setLocalValue("CaseSensitivity", cs); } - Qt::CaseSensitivity TabCompletionSettings::caseSensitivity() const { return (Qt::CaseSensitivity)localValue("CaseSensitivity", Qt::CaseInsensitive).toInt(); } - void TabCompletionSettings::setUseLastSpokenTo(bool use) { setLocalValue("UseLastSpokenTo", use); } - bool TabCompletionSettings::useLastSpokenTo() const { return localValue("UseLastSpokenTo", false).toBool(); } - // ======================================== // ItemViewSettings // ======================================== -ItemViewSettings::ItemViewSettings(const QString &group) : ClientSettings(group) -{ -} - +ItemViewSettings::ItemViewSettings(const QString& group) + : ClientSettings(group) +{} bool ItemViewSettings::displayTopicInTooltip() const { return localValue("DisplayTopicInTooltip", false).toBool(); } - bool ItemViewSettings::mouseWheelChangesBuffer() const { return localValue("MouseWheelChangesBuffer", false).toBool(); diff --git a/src/client/clientsettings.h b/src/client/clientsettings.h index de5633a0..a33329c0 100644 --- a/src/client/clientsettings.h +++ b/src/client/clientsettings.h @@ -23,7 +23,6 @@ #include "client-export.h" #include "settings.h" - #include "types.h" class QHostAddress; @@ -31,12 +30,10 @@ class QSslSocket; class CLIENT_EXPORT ClientSettings : public Settings { - protected: ClientSettings(QString group = "General"); }; - // ======================================== // CoreAccountSettings // ======================================== @@ -66,34 +63,34 @@ public: void clearAccounts(); - void storeAccountData(AccountId id, const QVariantMap &data); + void storeAccountData(AccountId id, const QVariantMap& data); QVariantMap retrieveAccountData(AccountId) const; void removeAccount(AccountId); - void setJumpKeyMap(const QHash &keyMap); + void setJumpKeyMap(const QHash& keyMap); QHash jumpKeyMap() const; - void setBufferViewOverlay(const QSet &viewIds); + void setBufferViewOverlay(const QSet& viewIds); QSet bufferViewOverlay() const; - void setAccountValue(const QString &key, const QVariant &data); - QVariant accountValue(const QString &key, const QVariant &def = QVariant()) const; + void setAccountValue(const QString& key, const QVariant& data); + QVariant accountValue(const QString& key, const QVariant& def = QVariant()) const; protected: - QString keyForNotify(const QString &key) const override; + QString keyForNotify(const QString& key) const override; private: QString _subgroup; }; - // ======================================== // NotificationSettings // ======================================== class CLIENT_EXPORT NotificationSettings : public ClientSettings { public: - enum HighlightNickType { + enum HighlightNickType + { NoNick = 0x00, CurrentNick = 0x01, AllNicks = 0x02 @@ -101,11 +98,11 @@ public: NotificationSettings(); - void setValue(const QString &key, const QVariant &data); - QVariant value(const QString &key, const QVariant &def = {}) const; - void remove(const QString &key); + void setValue(const QString& key, const QVariant& data); + QVariant value(const QString& key, const QVariant& def = {}) const; + void remove(const QString& key); - void setHighlightList(const QVariantList &highlightList); + void setHighlightList(const QVariantList& highlightList); QVariantList highlightList() const; void setHighlightNick(HighlightNickType); @@ -115,7 +112,6 @@ public: bool nicksCaseSensitive() const; }; - // ======================================== // CoreConnectionSettings // ======================================== @@ -123,8 +119,9 @@ public: class CLIENT_EXPORT CoreConnectionSettings : public ClientSettings { public: - enum NetworkDetectionMode { - UseQNetworkConfigurationManager = 1, // UseSolid is gone + enum NetworkDetectionMode + { + UseQNetworkConfigurationManager = 1, // UseSolid is gone UsePingTimeout, NoActiveDetection }; @@ -144,7 +141,6 @@ public: int reconnectInterval() const; }; - // ======================================== // TabCompletionSettings // ======================================== @@ -152,14 +148,15 @@ public: class CLIENT_EXPORT TabCompletionSettings : public ClientSettings { public: - enum SortMode { + enum SortMode + { Alphabetical, LastActivity }; TabCompletionSettings(); - void setCompletionSuffix(const QString &); + void setCompletionSuffix(const QString&); QString completionSuffix() const; void setAddSpaceMidSentence(bool); @@ -175,14 +172,13 @@ public: bool useLastSpokenTo() const; }; - // ======================================== // ItemViewSettings // ======================================== class CLIENT_EXPORT ItemViewSettings : public ClientSettings { public: - ItemViewSettings(const QString &group = "ItemViews"); + ItemViewSettings(const QString& group = "ItemViews"); bool displayTopicInTooltip() const; bool mouseWheelChangesBuffer() const; diff --git a/src/client/clienttransfer.cpp b/src/client/clienttransfer.cpp index ca91e5c8..fd2e7052 100644 --- a/src/client/clienttransfer.cpp +++ b/src/client/clienttransfer.cpp @@ -18,18 +18,17 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include - #include "clienttransfer.h" -ClientTransfer::ClientTransfer(const QUuid &uuid, QObject *parent) - : Transfer(uuid, parent), - _file(nullptr) +#include + +ClientTransfer::ClientTransfer(const QUuid& uuid, QObject* parent) + : Transfer(uuid, parent) + , _file(nullptr) { connect(this, &Transfer::statusChanged, this, &ClientTransfer::onStatusChanged); } - quint64 ClientTransfer::transferred() const { if (status() == Status::Completed) @@ -38,7 +37,6 @@ quint64 ClientTransfer::transferred() const return _file ? _file->size() : 0; } - void ClientTransfer::cleanUp() { if (_file) { @@ -48,14 +46,12 @@ void ClientTransfer::cleanUp() } } - QString ClientTransfer::savePath() const { return _savePath; } - -void ClientTransfer::accept(const QString &savePath) const +void ClientTransfer::accept(const QString& savePath) const { _savePath = savePath; PeerPtr ptr = nullptr; @@ -63,7 +59,6 @@ void ClientTransfer::accept(const QString &savePath) const emit accepted(); } - void ClientTransfer::reject() const { PeerPtr ptr = nullptr; @@ -71,13 +66,12 @@ void ClientTransfer::reject() const emit rejected(); } - -void ClientTransfer::dataReceived(PeerPtr, const QByteArray &data) +void ClientTransfer::dataReceived(PeerPtr, const QByteArray& data) { // TODO: proper error handling (relay to core) if (!_file) { _file = new QFile(_savePath, this); - if (!_file->open(QFile::WriteOnly|QFile::Truncate)) { + if (!_file->open(QFile::WriteOnly | QFile::Truncate)) { qWarning() << Q_FUNC_INFO << "Could not open file:" << _file->errorString(); return; } @@ -94,19 +88,18 @@ void ClientTransfer::dataReceived(PeerPtr, const QByteArray &data) emit transferredChanged(transferred()); } - void ClientTransfer::onStatusChanged(Transfer::Status status) { - switch(status) { - case Status::Completed: - if (_file) - _file->close(); - break; - case Status::Failed: - if (_file) - _file->remove(); - break; - default: - ; + switch (status) { + case Status::Completed: + if (_file) + _file->close(); + break; + case Status::Failed: + if (_file) + _file->remove(); + break; + default: + ; } } diff --git a/src/client/clienttransfer.h b/src/client/clienttransfer.h index 9b27666d..ccd85d58 100644 --- a/src/client/clienttransfer.h +++ b/src/client/clienttransfer.h @@ -31,7 +31,7 @@ class ClientTransfer : public Transfer Q_OBJECT public: - ClientTransfer(const QUuid &uuid, QObject *parent = nullptr); + ClientTransfer(const QUuid& uuid, QObject* parent = nullptr); QString savePath() const; @@ -39,11 +39,11 @@ public: public slots: // called on the client side - void accept(const QString &savePath) const override; + void accept(const QString& savePath) const override; void reject() const override; private slots: - void dataReceived(PeerPtr peer, const QByteArray &data) override; + void dataReceived(PeerPtr peer, const QByteArray& data) override; void onStatusChanged(Transfer::Status status); private: @@ -51,5 +51,5 @@ private: mutable QString _savePath; - QFile *_file; + QFile* _file; }; diff --git a/src/client/clienttransfermanager.cpp b/src/client/clienttransfermanager.cpp index 751a85aa..9a6b0b1c 100644 --- a/src/client/clienttransfermanager.cpp +++ b/src/client/clienttransfermanager.cpp @@ -23,15 +23,14 @@ #include "client.h" #include "clienttransfer.h" -void ClientTransferManager::setTransferIds(const QList &transferIds) +void ClientTransferManager::setTransferIds(const QList& transferIds) { - for(auto &&id : transferIds) { + for (auto&& id : transferIds) { onCoreTransferAdded(id); } } - -void ClientTransferManager::onCoreTransferAdded(const QUuid &uuid) +void ClientTransferManager::onCoreTransferAdded(const QUuid& uuid) { if (uuid.isNull()) { qWarning() << Q_FUNC_INFO << "Invalid transfer uuid" << uuid.toString(); @@ -39,14 +38,13 @@ void ClientTransferManager::onCoreTransferAdded(const QUuid &uuid) } auto transfer = new ClientTransfer(uuid, this); - connect(transfer, &SyncableObject::initDone, this, &ClientTransferManager::onTransferInitDone); // we only want to add initialized transfers + connect(transfer, &SyncableObject::initDone, this, &ClientTransferManager::onTransferInitDone); // we only want to add initialized transfers Client::signalProxy()->synchronize(transfer); } - void ClientTransferManager::onTransferInitDone() { - auto *transfer = qobject_cast(sender()); + auto* transfer = qobject_cast(sender()); Q_ASSERT(transfer); addTransfer(transfer); } diff --git a/src/client/clienttransfermanager.h b/src/client/clienttransfermanager.h index 8f38444c..a47d749d 100644 --- a/src/client/clienttransfermanager.h +++ b/src/client/clienttransfermanager.h @@ -32,7 +32,7 @@ public: using TransferManager::TransferManager; private slots: - void setTransferIds(const QList &transferIds) override; - void onCoreTransferAdded(const QUuid &uuid) override; + void setTransferIds(const QList& transferIds) override; + void onCoreTransferAdded(const QUuid& uuid) override; void onTransferInitDone(); }; diff --git a/src/client/clientuserinputhandler.cpp b/src/client/clientuserinputhandler.cpp index 9315a5ee..7c839eb8 100644 --- a/src/client/clientuserinputhandler.cpp +++ b/src/client/clientuserinputhandler.cpp @@ -20,6 +20,8 @@ #include "clientuserinputhandler.h" +#include + #include "bufferinfo.h" #include "buffermodel.h" #include "client.h" @@ -35,9 +37,7 @@ #include "network.h" #include "types.h" -#include - -ClientUserInputHandler::ClientUserInputHandler(QObject *parent) +ClientUserInputHandler::ClientUserInputHandler(QObject* parent) : BasicHandler(parent) { TabCompletionSettings s; @@ -45,8 +45,7 @@ ClientUserInputHandler::ClientUserInputHandler(QObject *parent) completionSuffixChanged(s.completionSuffix()); } - -void ClientUserInputHandler::completionSuffixChanged(const QVariant &v) +void ClientUserInputHandler::completionSuffixChanged(const QVariant& v) { QString suffix = v.toString(); QString letter = "A-Za-z"; @@ -54,17 +53,16 @@ void ClientUserInputHandler::completionSuffixChanged(const QVariant &v) _nickRx = QRegExp(QString("^([%1%2][%1%2\\d-]*)%3").arg(letter, special, suffix).trimmed()); } - // this would be the place for a client-side hook -void ClientUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) +void ClientUserInputHandler::handleUserInput(const BufferInfo& bufferInfo, const QString& msg) { if (msg.isEmpty()) return; if (!msg.startsWith('/')) { if (_nickRx.indexIn(msg) == 0) { - const Network *net = Client::network(bufferInfo.networkId()); - IrcUser *user = net ? net->ircUser(_nickRx.cap(1)) : nullptr; + const Network* net = Client::network(bufferInfo.networkId()); + IrcUser* user = net ? net->ircUser(_nickRx.cap(1)) : nullptr; if (user) user->setLastSpokenTo(bufferInfo.bufferId(), QDateTime::currentDateTime().toUTC()); } @@ -79,22 +77,19 @@ void ClientUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const } } - -void ClientUserInputHandler::defaultHandler(const QString &cmd, const BufferInfo &bufferInfo, const QString &text) +void ClientUserInputHandler::defaultHandler(const QString& cmd, const BufferInfo& bufferInfo, const QString& text) { QString command = QString("/%1 %2").arg(cmd, text); emit sendInput(bufferInfo, command); } - -void ClientUserInputHandler::handleExec(const BufferInfo &bufferInfo, const QString &execString) +void ClientUserInputHandler::handleExec(const BufferInfo& bufferInfo, const QString& execString) { - auto *exec = new ExecWrapper(this); // gets suicidal when it's done + auto* exec = new ExecWrapper(this); // gets suicidal when it's done exec->start(bufferInfo, execString); } - -void ClientUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &text) +void ClientUserInputHandler::handleJoin(const BufferInfo& bufferInfo, const QString& text) { if (text.isEmpty()) { Client::messageModel()->insertErrorMessage(bufferInfo, tr("/JOIN expects a channel")); @@ -105,8 +100,7 @@ void ClientUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QStr defaultHandler("JOIN", bufferInfo, text); } - -void ClientUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &text) +void ClientUserInputHandler::handleQuery(const BufferInfo& bufferInfo, const QString& text) { if (text.isEmpty()) { Client::messageModel()->insertErrorMessage(bufferInfo, tr("/QUERY expects at least a nick")); @@ -117,8 +111,7 @@ void ClientUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QSt defaultHandler("QUERY", bufferInfo, text); } - -void ClientUserInputHandler::handleIgnore(const BufferInfo &bufferInfo, const QString &text) +void ClientUserInputHandler::handleIgnore(const BufferInfo& bufferInfo, const QString& text) { if (text.isEmpty()) { emit Client::instance()->displayIgnoreList(""); @@ -127,27 +120,24 @@ void ClientUserInputHandler::handleIgnore(const BufferInfo &bufferInfo, const QS // If rule contains no ! or @, we assume it is just a nickname, and turn it into an ignore rule for that nick QString rule = (text.contains('!') || text.contains('@')) ? text : text + "!*@*"; - Client::ignoreListManager()->requestAddIgnoreListItem( - IgnoreListManager::IgnoreType::SenderIgnore, - rule, - false, - // Use a dynamic ignore rule, for reversibility - IgnoreListManager::StrictnessType::SoftStrictness, - // Use current network as scope - IgnoreListManager::ScopeType::NetworkScope, - Client::network(bufferInfo.networkId())->networkName(), - true - ); + Client::ignoreListManager()->requestAddIgnoreListItem(IgnoreListManager::IgnoreType::SenderIgnore, + rule, + false, + // Use a dynamic ignore rule, for reversibility + IgnoreListManager::StrictnessType::SoftStrictness, + // Use current network as scope + IgnoreListManager::ScopeType::NetworkScope, + Client::network(bufferInfo.networkId())->networkName(), + true); } -void ClientUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &text) +void ClientUserInputHandler::handleList(const BufferInfo& bufferInfo, const QString& text) { // Pass along any potential search parameters, list channels immediately Client::instance()->displayChannelList(bufferInfo.networkId(), text, true); } - -void ClientUserInputHandler::switchBuffer(const NetworkId &networkId, const QString &bufferName) +void ClientUserInputHandler::switchBuffer(const NetworkId& networkId, const QString& bufferName) { BufferId newBufId = Client::networkModel()->bufferId(networkId, bufferName); if (!newBufId.isValid()) { @@ -156,15 +146,15 @@ void ClientUserInputHandler::switchBuffer(const NetworkId &networkId, const QStr else { Client::bufferModel()->switchToBuffer(newBufId); // unhide the buffer - ClientBufferViewManager *clientBufferViewManager = Client::bufferViewManager(); - QList bufferViewConfigList = clientBufferViewManager->clientBufferViewConfigs(); - foreach(ClientBufferViewConfig *bufferViewConfig, bufferViewConfigList) { + ClientBufferViewManager* clientBufferViewManager = Client::bufferViewManager(); + QList bufferViewConfigList = clientBufferViewManager->clientBufferViewConfigs(); + foreach (ClientBufferViewConfig* bufferViewConfig, bufferViewConfigList) { if (bufferViewConfig->temporarilyRemovedBuffers().contains(newBufId)) { bufferViewConfig->requestAddBuffer(newBufId, bufferViewConfig->bufferList().length()); - //if (bufferViewConfig->sortAlphabetically()) { + // if (bufferViewConfig->sortAlphabetically()) { // TODO we need to trigger a sort here, but can't reach the model required // to get a bufferviewfilter, as the bufferviewmanager only managers configs - //BufferViewFilter *filter = qobject_cast(model()); + // BufferViewFilter *filter = qobject_cast(model()); //} } } diff --git a/src/client/clientuserinputhandler.h b/src/client/clientuserinputhandler.h index 6df0da0f..536bbe0d 100644 --- a/src/client/clientuserinputhandler.h +++ b/src/client/clientuserinputhandler.h @@ -31,33 +31,32 @@ class ClientUserInputHandler : public BasicHandler Q_OBJECT public: - ClientUserInputHandler(QObject *parent = nullptr); + ClientUserInputHandler(QObject* parent = nullptr); public slots: - void handleUserInput(const BufferInfo &bufferInfo, const QString &msg); + void handleUserInput(const BufferInfo& bufferInfo, const QString& msg); signals: - void sendInput(const BufferInfo &, const QString &); + void sendInput(const BufferInfo&, const QString&); private slots: - void completionSuffixChanged(const QVariant &); + void completionSuffixChanged(const QVariant&); - void handleExec(const BufferInfo &bufferInfo, const QString &execString); - void handleJoin(const BufferInfo &bufferInfo, const QString &text); - void handleQuery(const BufferInfo &bufferInfo, const QString &text); - void handleIgnore(const BufferInfo &bufferInfo, const QString &text); - void handleList(const BufferInfo &bufferInfo, const QString &text); - void defaultHandler(const QString &cmd, const BufferInfo &bufferInfo, const QString &text); + void handleExec(const BufferInfo& bufferInfo, const QString& execString); + void handleJoin(const BufferInfo& bufferInfo, const QString& text); + void handleQuery(const BufferInfo& bufferInfo, const QString& text); + void handleIgnore(const BufferInfo& bufferInfo, const QString& text); + void handleList(const BufferInfo& bufferInfo, const QString& text); + void defaultHandler(const QString& cmd, const BufferInfo& bufferInfo, const QString& text); private: QRegExp _nickRx; //! Helper method for switching to new/existing buffers /** Immediately switches to the given buffer or schedules a switch for whenever - * the buffer is created - */ - void switchBuffer(const NetworkId &networkId, const QString &bufferName); + * the buffer is created + */ + void switchBuffer(const NetworkId& networkId, const QString& bufferName); }; - #endif diff --git a/src/client/coreaccount.cpp b/src/client/coreaccount.cpp index ad0dedcd..3b98daa3 100644 --- a/src/client/coreaccount.cpp +++ b/src/client/coreaccount.cpp @@ -31,101 +31,85 @@ CoreAccount::CoreAccount(AccountId accountId) _proxyPort = 8080; } - void CoreAccount::setAccountId(AccountId id) { _accountId = id; } - -void CoreAccount::setAccountName(const QString &name) +void CoreAccount::setAccountName(const QString& name) { _accountName = name; } - -void CoreAccount::setUuid(const QUuid &uuid) +void CoreAccount::setUuid(const QUuid& uuid) { _uuid = uuid; } - void CoreAccount::setInternal(bool internal) { _internal = internal; } - -void CoreAccount::setUser(const QString &user) +void CoreAccount::setUser(const QString& user) { _user = user; } - -void CoreAccount::setPassword(const QString &password) +void CoreAccount::setPassword(const QString& password) { _password = password; } - void CoreAccount::setStorePassword(bool store) { _storePassword = store; } - -void CoreAccount::setHostName(const QString &hostname) +void CoreAccount::setHostName(const QString& hostname) { _hostName = hostname; } - void CoreAccount::setPort(uint port) { _port = port; } - void CoreAccount::setUseSsl(bool useSsl) { _useSsl = useSsl; } - void CoreAccount::setProxyType(QNetworkProxy::ProxyType type) { _proxyType = type; } - -void CoreAccount::setProxyUser(const QString &proxyUser) +void CoreAccount::setProxyUser(const QString& proxyUser) { _proxyUser = proxyUser; } - -void CoreAccount::setProxyPassword(const QString &proxyPassword) +void CoreAccount::setProxyPassword(const QString& proxyPassword) { _proxyPassword = proxyPassword; } - -void CoreAccount::setProxyHostName(const QString &proxyHostName) +void CoreAccount::setProxyHostName(const QString& proxyHostName) { _proxyHostName = proxyHostName; } - void CoreAccount::setProxyPort(uint proxyPort) { _proxyPort = proxyPort; } - QVariantMap CoreAccount::toVariantMap(bool forcePassword) const { QVariantMap v; - v["AccountId"] = accountId().toInt(); // can't use AccountId because then comparison fails + v["AccountId"] = accountId().toInt(); // can't use AccountId because then comparison fails v["AccountName"] = accountName(); v["Uuid"] = uuid().toString(); v["Internal"] = isInternal(); @@ -146,8 +130,7 @@ QVariantMap CoreAccount::toVariantMap(bool forcePassword) const return v; } - -void CoreAccount::fromVariantMap(const QVariantMap &v) +void CoreAccount::fromVariantMap(const QVariantMap& v) { setAccountId((AccountId)v.value("AccountId").toInt()); setAccountName(v.value("AccountName").toString()); @@ -168,35 +151,32 @@ void CoreAccount::fromVariantMap(const QVariantMap &v) _storePassword = !password().isEmpty(); } - -bool CoreAccount::operator==(const CoreAccount &other) const +bool CoreAccount::operator==(const CoreAccount& other) const { return toVariantMap(true) == other.toVariantMap(true); } - -bool CoreAccount::operator!=(const CoreAccount &other) const +bool CoreAccount::operator!=(const CoreAccount& other) const { return !(*this == other); } - -QDebug operator<<(QDebug dbg, const CoreAccount &acc) +QDebug operator<<(QDebug dbg, const CoreAccount& acc) { dbg.nospace() << qPrintable(QString("CoreAccount(AccountId:")) << acc.accountId() - << qPrintable(QString(", AccountName:")) << acc.accountName() - << qPrintable(QString(", Uuid:")) << acc.uuid() - << qPrintable(QString(", Internal:")) << acc.isInternal() - << qPrintable(QString(", User:")) << acc.user() - << qPrintable(QString(", Password:")) << acc.password() - << qPrintable(QString(", StorePassword:")) << acc.storePassword() - << qPrintable(QString(", HostName:")) << acc.hostName() - << qPrintable(QString(", Port:")) << acc.port() - << qPrintable(QString(", UseSSL:")) << acc.useSsl() - << qPrintable(QString(", ProxyType:")) << acc.proxyType() - << qPrintable(QString(", ProxyUser:")) << acc.proxyUser() - << qPrintable(QString(", ProxyPassword:")) << acc.proxyPassword() - << qPrintable(QString(", ProxyHostName:")) << acc.proxyHostName() - << qPrintable(QString(", ProxyPort:")) << acc.proxyPort(); + << qPrintable(QString(", AccountName:")) << acc.accountName() + << qPrintable(QString(", Uuid:")) << acc.uuid() + << qPrintable(QString(", Internal:")) << acc.isInternal() + << qPrintable(QString(", User:")) << acc.user() + << qPrintable(QString(", Password:")) << acc.password() + << qPrintable(QString(", StorePassword:")) << acc.storePassword() + << qPrintable(QString(", HostName:")) << acc.hostName() + << qPrintable(QString(", Port:")) << acc.port() + << qPrintable(QString(", UseSSL:")) << acc.useSsl() + << qPrintable(QString(", ProxyType:")) << acc.proxyType() + << qPrintable(QString(", ProxyUser:")) << acc.proxyUser() + << qPrintable(QString(", ProxyPassword:")) << acc.proxyPassword() + << qPrintable(QString(", ProxyHostName:")) << acc.proxyHostName() + << qPrintable(QString(", ProxyPort:")) << acc.proxyPort(); return dbg.space(); } diff --git a/src/client/coreaccount.h b/src/client/coreaccount.h index b69552c5..e5d507d5 100644 --- a/src/client/coreaccount.h +++ b/src/client/coreaccount.h @@ -56,32 +56,32 @@ public: inline uint proxyPort() const { return _proxyPort; } void setAccountId(AccountId id); - void setAccountName(const QString &accountName); - void setUuid(const QUuid &uuid); + void setAccountName(const QString& accountName); + void setUuid(const QUuid& uuid); void setInternal(bool); - void setUser(const QString &user); + void setUser(const QString& user); void setStorePassword(bool); - void setHostName(const QString &hostname); + void setHostName(const QString& hostname); void setPort(uint port); void setUseSsl(bool); void setProxyType(QNetworkProxy::ProxyType); - void setProxyUser(const QString &); - void setProxyHostName(const QString &); + void setProxyUser(const QString&); + void setProxyHostName(const QString&); void setProxyPort(uint); /* These might be overridden for KWallet/QtKeychain support */ virtual inline QString password() const { return _password; } - virtual void setPassword(const QString &password); + virtual void setPassword(const QString& password); virtual inline QString proxyPassword() const { return _proxyPassword; } - virtual void setProxyPassword(const QString &); + virtual void setProxyPassword(const QString&); virtual QVariantMap toVariantMap(bool forcePassword = false) const; - virtual void fromVariantMap(const QVariantMap &); + virtual void fromVariantMap(const QVariantMap&); - bool operator==(const CoreAccount &other) const; - bool operator!=(const CoreAccount &other) const; + bool operator==(const CoreAccount& other) const; + bool operator!=(const CoreAccount& other) const; private: AccountId _accountId; @@ -96,4 +96,4 @@ private: uint _proxyPort; }; -QDebug operator<<(QDebug dbg, const CoreAccount &msg); +QDebug operator<<(QDebug dbg, const CoreAccount& msg); diff --git a/src/client/coreaccountmodel.cpp b/src/client/coreaccountmodel.cpp index 04ee15f5..86dc7df9 100644 --- a/src/client/coreaccountmodel.cpp +++ b/src/client/coreaccountmodel.cpp @@ -23,26 +23,23 @@ #include "clientsettings.h" #include "quassel.h" -CoreAccountModel::CoreAccountModel(QObject *parent) - : QAbstractListModel(parent), - _internalAccount(0) -{ -} - +CoreAccountModel::CoreAccountModel(QObject* parent) + : QAbstractListModel(parent) + , _internalAccount(0) +{} -CoreAccountModel::CoreAccountModel(const CoreAccountModel *other, QObject *parent) - : QAbstractListModel(parent), - _internalAccount(0) +CoreAccountModel::CoreAccountModel(const CoreAccountModel* other, QObject* parent) + : QAbstractListModel(parent) + , _internalAccount(0) { update(other); } - -void CoreAccountModel::update(const CoreAccountModel *other) +void CoreAccountModel::update(const CoreAccountModel* other) { clear(); if (other->_accounts.count() > 0) { - beginInsertRows(QModelIndex(), 0, other->_accounts.count() -1); + beginInsertRows(QModelIndex(), 0, other->_accounts.count() - 1); _accounts = other->_accounts; endInsertRows(); } @@ -50,15 +47,14 @@ void CoreAccountModel::update(const CoreAccountModel *other) _removedAccounts = other->_removedAccounts; } - void CoreAccountModel::load() { clear(); CoreAccountSettings s; - foreach(AccountId accId, s.knownAccounts()) { + foreach (AccountId accId, s.knownAccounts()) { QVariantMap map = s.retrieveAccountData(accId); CoreAccount acc; - acc.fromVariantMap(map); // TODO Hook into kwallet/password saving stuff + acc.fromVariantMap(map); // TODO Hook into kwallet/password saving stuff insertAccount(acc); } if (Quassel::runMode() == Quassel::Monolithic && !internalAccount().isValid()) { @@ -70,21 +66,19 @@ void CoreAccountModel::load() } } - void CoreAccountModel::save() { CoreAccountSettings s; - foreach(AccountId id, _removedAccounts) { + foreach (AccountId id, _removedAccounts) { s.removeAccount(id); } _removedAccounts.clear(); - foreach(const CoreAccount &acc, accounts()) { - QVariantMap map = acc.toVariantMap(false); // TODO Hook into kwallet/password saving stuff + foreach (const CoreAccount& acc, accounts()) { + QVariantMap map = acc.toVariantMap(false); // TODO Hook into kwallet/password saving stuff s.storeAccountData(acc.accountId(), map); } } - void CoreAccountModel::clear() { beginResetModel(); @@ -93,13 +87,12 @@ void CoreAccountModel::clear() endResetModel(); } - -QVariant CoreAccountModel::data(const QModelIndex &index, int role) const +QVariant CoreAccountModel::data(const QModelIndex& index, int role) const { if (!index.isValid() || index.row() >= rowCount() || index.column() >= 1) return QVariant(); - const CoreAccount &acc = accounts().at(index.row()); + const CoreAccount& acc = accounts().at(index.row()); switch (role) { case Qt::DisplayRole: @@ -114,7 +107,6 @@ QVariant CoreAccountModel::data(const QModelIndex &index, int role) const } } - CoreAccount CoreAccountModel::account(AccountId id) const { int idx = findAccountIdx(id); @@ -123,44 +115,38 @@ CoreAccount CoreAccountModel::account(AccountId id) const return CoreAccount(); } - -CoreAccount CoreAccountModel::account(const QModelIndex &idx) const +CoreAccount CoreAccountModel::account(const QModelIndex& idx) const { if (idx.isValid() && idx.row() < _accounts.count()) return _accounts.value(idx.row()); return CoreAccount(); } - QList CoreAccountModel::accounts() const { return _accounts; } - QList CoreAccountModel::accountIds() const { QList list; - foreach(const CoreAccount &acc, accounts()) - list << acc.accountId(); + foreach (const CoreAccount& acc, accounts()) + list << acc.accountId(); return list; } - -bool CoreAccountModel::operator==(const CoreAccountModel &other) const +bool CoreAccountModel::operator==(const CoreAccountModel& other) const { return _accounts == other._accounts; } - -bool CoreAccountModel::operator!=(const CoreAccountModel &other) const +bool CoreAccountModel::operator!=(const CoreAccountModel& other) const { return !(*this == other); } - // TODO with Qt 4.6, use QAbstractItemModel move semantics to properly do this -AccountId CoreAccountModel::createOrUpdateAccount(const CoreAccount &newAcc) +AccountId CoreAccountModel::createOrUpdateAccount(const CoreAccount& newAcc) { CoreAccount acc = newAcc; @@ -170,7 +156,7 @@ AccountId CoreAccountModel::createOrUpdateAccount(const CoreAccount &newAcc) if (!acc.accountId().isValid()) { // find free Id AccountId newId = 0; - const QList &ids = accountIds(); + const QList& ids = accountIds(); for (int i = 1;; i++) { if (!_removedAccounts.contains(i) && !ids.contains(i)) { newId = i; @@ -198,8 +184,7 @@ AccountId CoreAccountModel::createOrUpdateAccount(const CoreAccount &newAcc) return acc.accountId(); } - -void CoreAccountModel::insertAccount(const CoreAccount &acc) +void CoreAccountModel::insertAccount(const CoreAccount& acc) { if (acc.isInternal()) { if (internalAccount().isValid()) { @@ -211,7 +196,7 @@ void CoreAccountModel::insertAccount(const CoreAccount &acc) // check for Quuid int idx = 0; - while (idx<_accounts.count() && acc.accountName()> _accounts.at(idx).accountName() && !acc.isInternal()) + while (idx < _accounts.count() && acc.accountName() > _accounts.at(idx).accountName() && !acc.isInternal()) ++idx; beginInsertRows(QModelIndex(), idx, idx); @@ -219,7 +204,6 @@ void CoreAccountModel::insertAccount(const CoreAccount &acc) endInsertRows(); } - CoreAccount CoreAccountModel::takeAccount(AccountId accId) { int idx = findAccountIdx(accId); @@ -236,14 +220,12 @@ CoreAccount CoreAccountModel::takeAccount(AccountId accId) return acc; } - void CoreAccountModel::removeAccount(AccountId accId) { takeAccount(accId); _removedAccounts.insert(accId); } - QModelIndex CoreAccountModel::accountIndex(AccountId accId) const { for (int i = 0; i < _accounts.count(); i++) { @@ -253,7 +235,6 @@ QModelIndex CoreAccountModel::accountIndex(AccountId accId) const return {}; } - int CoreAccountModel::findAccountIdx(AccountId id) const { QModelIndex idx = accountIndex(id); diff --git a/src/client/coreaccountmodel.h b/src/client/coreaccountmodel.h index 88bc341d..853aa9e5 100644 --- a/src/client/coreaccountmodel.h +++ b/src/client/coreaccountmodel.h @@ -32,18 +32,19 @@ class CLIENT_EXPORT CoreAccountModel : public QAbstractListModel Q_OBJECT public: - enum { + enum + { AccountIdRole = Qt::UserRole, UuidRole }; - CoreAccountModel(QObject *parent = nullptr); - CoreAccountModel(const CoreAccountModel *other, QObject *parent = nullptr); + CoreAccountModel(QObject* parent = nullptr); + CoreAccountModel(const CoreAccountModel* other, QObject* parent = nullptr); - inline int rowCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + inline int rowCount(const QModelIndex& parent = QModelIndex()) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - CoreAccount account(const QModelIndex &) const; + CoreAccount account(const QModelIndex&) const; CoreAccount account(AccountId) const; QList accounts() const; QList accountIds() const; @@ -51,14 +52,14 @@ public: inline AccountId internalAccount() const; - AccountId createOrUpdateAccount(const CoreAccount &newAccountData); + AccountId createOrUpdateAccount(const CoreAccount& newAccountData); CoreAccount takeAccount(AccountId); void removeAccount(AccountId); - void update(const CoreAccountModel *other); + void update(const CoreAccountModel* other); - bool operator==(const CoreAccountModel &other) const; - bool operator!=(const CoreAccountModel &other) const; + bool operator==(const CoreAccountModel& other) const; + bool operator!=(const CoreAccountModel& other) const; public slots: void save(); @@ -66,7 +67,7 @@ public slots: void clear(); protected: - void insertAccount(const CoreAccount &); + void insertAccount(const CoreAccount&); int findAccountIdx(AccountId) const; private: @@ -77,14 +78,12 @@ private: AccountId _internalAccount; }; - // Inlines -int CoreAccountModel::rowCount(const QModelIndex &) const +int CoreAccountModel::rowCount(const QModelIndex&) const { return _accounts.count(); } - AccountId CoreAccountModel::internalAccount() const { return _internalAccount; diff --git a/src/client/coreconnection.cpp b/src/client/coreconnection.cpp index 3c62fca6..982d0c86 100644 --- a/src/client/coreconnection.cpp +++ b/src/client/coreconnection.cpp @@ -34,14 +34,13 @@ #include "protocols/legacy/legacypeer.h" -CoreConnection::CoreConnection(QObject *parent) - : QObject(parent), - _authHandler(nullptr) +CoreConnection::CoreConnection(QObject* parent) + : QObject(parent) + , _authHandler(nullptr) { qRegisterMetaType("CoreConnection::ConnectionState"); } - void CoreConnection::init() { Client::signalProxy()->setHeartBeatInterval(30); @@ -60,14 +59,12 @@ void CoreConnection::init() networkDetectionModeChanged(s.networkDetectionMode()); } - -CoreAccountModel *CoreConnection::accountModel() const +CoreAccountModel* CoreConnection::accountModel() const { return Client::coreAccountModel(); } - -void CoreConnection::setProgressText(const QString &text) +void CoreConnection::setProgressText(const QString& text) { if (_progressText != text) { _progressText = text; @@ -75,7 +72,6 @@ void CoreConnection::setProgressText(const QString &text) } } - void CoreConnection::setProgressValue(int value) { if (_progressValue != value) { @@ -84,7 +80,6 @@ void CoreConnection::setProgressValue(int value) } } - void CoreConnection::setProgressMinimum(int minimum) { if (_progressMinimum != minimum) { @@ -93,7 +88,6 @@ void CoreConnection::setProgressMinimum(int minimum) } } - void CoreConnection::setProgressMaximum(int maximum) { if (_progressMaximum != maximum) { @@ -102,7 +96,6 @@ void CoreConnection::setProgressMaximum(int maximum) } } - void CoreConnection::updateProgress(int value, int max) { if (max != _progressMaximum) { @@ -112,7 +105,6 @@ void CoreConnection::updateProgress(int value, int max) setProgressValue(value); } - void CoreConnection::reconnectTimeout() { if (!_peer) { @@ -120,17 +112,16 @@ void CoreConnection::reconnectTimeout() if (_wantReconnect && s.autoReconnect()) { // If using QNetworkConfigurationManager, we don't want to reconnect if we're offline if (s.networkDetectionMode() == CoreConnectionSettings::UseQNetworkConfigurationManager) { - if (!_qNetworkConfigurationManager->isOnline()) { + if (!_qNetworkConfigurationManager->isOnline()) { return; - } + } } reconnectToCore(); } } } - -void CoreConnection::networkDetectionModeChanged(const QVariant &vmode) +void CoreConnection::networkDetectionModeChanged(const QVariant& vmode) { CoreConnectionSettings s; auto mode = (CoreConnectionSettings::NetworkDetectionMode)vmode.toInt(); @@ -141,42 +132,39 @@ void CoreConnection::networkDetectionModeChanged(const QVariant &vmode) } } - -void CoreConnection::pingTimeoutIntervalChanged(const QVariant &interval) +void CoreConnection::pingTimeoutIntervalChanged(const QVariant& interval) { CoreConnectionSettings s; if (s.networkDetectionMode() == CoreConnectionSettings::UsePingTimeout) Client::signalProxy()->setMaxHeartBeatCount(interval.toInt() / 30); // interval is 30 seconds } - -void CoreConnection::reconnectIntervalChanged(const QVariant &interval) +void CoreConnection::reconnectIntervalChanged(const QVariant& interval) { _reconnectTimer.setInterval(interval.toInt() * 1000); } - void CoreConnection::onlineStateChanged(bool isOnline) { CoreConnectionSettings s; if (s.networkDetectionMode() != CoreConnectionSettings::UseQNetworkConfigurationManager) return; - if(isOnline) { + if (isOnline) { // qDebug() << "QNetworkConfigurationManager reports Online"; if (state() == Disconnected) { if (_wantReconnect && s.autoReconnect()) { reconnectToCore(); } } - } else { + } + else { // qDebug() << "QNetworkConfigurationManager reports Offline"; if (state() != Disconnected && !isLocalConnection()) disconnectFromCore(tr("Network is down"), true); } } - QPointer CoreConnection::peer() const { if (_peer) { @@ -185,13 +173,11 @@ QPointer CoreConnection::peer() const return _authHandler ? _authHandler->peer() : nullptr; } - bool CoreConnection::isEncrypted() const { return _peer && _peer->isSecure(); } - bool CoreConnection::isLocalConnection() const { if (!isConnected()) @@ -206,13 +192,11 @@ bool CoreConnection::isLocalConnection() const return false; } - void CoreConnection::onConnectionReady() { setState(Connected); } - void CoreConnection::setState(ConnectionState state) { if (state != _state) { @@ -225,15 +209,13 @@ void CoreConnection::setState(ConnectionState state) } } - -void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString &errorString) +void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString& errorString) { Q_UNUSED(error) disconnectFromCore(errorString, true); } - void CoreConnection::coreSocketDisconnected() { setState(Disconnected); @@ -241,26 +223,24 @@ void CoreConnection::coreSocketDisconnected() resetConnection(_wantReconnect); } - void CoreConnection::disconnectFromCore() { - disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect + disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect } - -void CoreConnection::disconnectFromCore(const QString &errorString, bool wantReconnect) +void CoreConnection::disconnectFromCore(const QString& errorString, bool wantReconnect) { if (wantReconnect) _reconnectTimer.start(); else _reconnectTimer.stop(); - _wantReconnect = wantReconnect; // store if disconnect was requested + _wantReconnect = wantReconnect; // store if disconnect was requested _wasReconnect = false; if (_authHandler) _authHandler->close(); - else if(_peer) + else if (_peer) _peer->close(); if (errorString.isEmpty()) @@ -269,7 +249,6 @@ void CoreConnection::disconnectFromCore(const QString &errorString, bool wantRec emit connectionError(errorString); } - void CoreConnection::resetConnection(bool wantReconnect) { if (_resetting) @@ -295,7 +274,7 @@ void CoreConnection::resetConnection(bool wantReconnect) _netsToSync.clear(); _numNetsToSync = 0; - setProgressMaximum(-1); // disable + setProgressMaximum(-1); // disable setState(Disconnected); emit lagUpdated(-1); @@ -312,7 +291,6 @@ void CoreConnection::resetConnection(bool wantReconnect) _resetting = false; } - void CoreConnection::reconnectToCore() { if (currentAccount().isValid()) { @@ -321,7 +299,6 @@ void CoreConnection::reconnectToCore() } } - bool CoreConnection::connectToCore(AccountId accId) { if (isConnected()) @@ -361,7 +338,6 @@ bool CoreConnection::connectToCore(AccountId accId) return true; } - void CoreConnection::connectToCurrentAccount() { if (_authHandler) { @@ -375,9 +351,9 @@ void CoreConnection::connectToCurrentAccount() return; } - auto *peer = new InternalPeer(); + auto* peer = new InternalPeer(); _peer = peer; - Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership + Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership emit connectionMsg(tr("Initializing...")); emit connectToInternalCore(peer); setState(Connected); @@ -390,7 +366,10 @@ void CoreConnection::connectToCurrentAccount() connect(_authHandler, &ClientAuthHandler::connectionReady, this, &CoreConnection::onConnectionReady); connect(_authHandler, &ClientAuthHandler::socketError, this, &CoreConnection::coreSocketError); connect(_authHandler, &ClientAuthHandler::transferProgress, this, &CoreConnection::updateProgress); - connect(_authHandler, &ClientAuthHandler::requestDisconnect, this, selectOverload(&CoreConnection::disconnectFromCore)); + connect(_authHandler, + &ClientAuthHandler::requestDisconnect, + this, + selectOverload(&CoreConnection::disconnectFromCore)); connect(_authHandler, &ClientAuthHandler::errorMessage, this, &CoreConnection::connectionError); connect(_authHandler, &ClientAuthHandler::errorPopup, this, &CoreConnection::connectionErrorPopup, Qt::QueuedConnection); @@ -412,20 +391,17 @@ void CoreConnection::connectToCurrentAccount() _authHandler->connectToCore(); } - -void CoreConnection::setupCore(const Protocol::SetupData &setupData) +void CoreConnection::setupCore(const Protocol::SetupData& setupData) { _authHandler->setupCore(setupData); } - -void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember) +void CoreConnection::loginToCore(const QString& user, const QString& password, bool remember) { _authHandler->login(user, password, remember); } - -void CoreConnection::onLoginSuccessful(const CoreAccount &account) +void CoreConnection::onLoginSuccessful(const CoreAccount& account) { updateProgress(0, 0); @@ -440,8 +416,7 @@ void CoreConnection::onLoginSuccessful(const CoreAccount &account) emit connectionMsg(tr("Synchronizing to %1...").arg(account.accountName())); } - -void CoreConnection::onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState) +void CoreConnection::onHandshakeComplete(RemotePeer* peer, const Protocol::SessionState& sessionState) { updateProgress(100, 100); @@ -459,30 +434,28 @@ void CoreConnection::onHandshakeComplete(RemotePeer *peer, const Protocol::Sessi syncToCore(sessionState); } - -void CoreConnection::internalSessionStateReceived(const Protocol::SessionState &sessionState) +void CoreConnection::internalSessionStateReceived(const Protocol::SessionState& sessionState) { updateProgress(100, 100); setState(Synchronizing); syncToCore(sessionState); } - -void CoreConnection::syncToCore(const Protocol::SessionState &sessionState) +void CoreConnection::syncToCore(const Protocol::SessionState& sessionState) { setProgressText(tr("Receiving network states")); updateProgress(0, 100); // create identities - foreach(const QVariant &vid, sessionState.identities) { + foreach (const QVariant& vid, sessionState.identities) { Client::instance()->coreIdentityCreated(vid.value()); } // create buffers // FIXME: get rid of this crap -- why? - NetworkModel *networkModel = Client::networkModel(); + NetworkModel* networkModel = Client::networkModel(); Q_ASSERT(networkModel); - foreach(const QVariant &vinfo, sessionState.bufferInfos) + foreach (const QVariant& vinfo, sessionState.bufferInfos) networkModel->bufferUpdated(vinfo.value()); // create BufferItems // prepare sync progress thingys... @@ -491,11 +464,11 @@ void CoreConnection::syncToCore(const Protocol::SessionState &sessionState) updateProgress(0, _numNetsToSync); // create network objects - foreach(const QVariant &networkid, sessionState.networkIds) { + foreach (const QVariant& networkid, sessionState.networkIds) { NetworkId netid = networkid.value(); if (Client::network(netid)) continue; - auto *net = new Network(netid, Client::instance()); + auto* net = new Network(netid, Client::instance()); _netsToSync.insert(net); connect(net, &SyncableObject::initDone, this, &CoreConnection::networkInitDone); connect(net, &QObject::destroyed, this, &CoreConnection::networkInitDone); @@ -504,11 +477,10 @@ void CoreConnection::syncToCore(const Protocol::SessionState &sessionState) checkSyncState(); } - // this is also called for destroyed networks! void CoreConnection::networkInitDone() { - QObject *net = sender(); + QObject* net = sender(); Q_ASSERT(net); disconnect(net, nullptr, this, nullptr); _netsToSync.remove(net); @@ -516,7 +488,6 @@ void CoreConnection::networkInitDone() checkSyncState(); } - void CoreConnection::checkSyncState() { if (_netsToSync.isEmpty() && state() >= Synchronizing) { diff --git a/src/client/coreconnection.h b/src/client/coreconnection.h index dff1f5a7..fe932eab 100644 --- a/src/client/coreconnection.h +++ b/src/client/coreconnection.h @@ -27,9 +27,9 @@ #include #ifdef HAVE_SSL -# include +# include #else -# include +# include #endif #include "coreaccount.h" @@ -48,7 +48,8 @@ class CLIENT_EXPORT CoreConnection : public QObject Q_OBJECT public: - enum ConnectionState { + enum ConnectionState + { Disconnected, Connecting, Connected, @@ -56,7 +57,7 @@ public: Synchronized }; - CoreConnection(QObject *parent = nullptr); + CoreConnection(QObject* parent = nullptr); void init(); @@ -81,9 +82,9 @@ public slots: bool connectToCore(AccountId = 0); void reconnectToCore(); void disconnectFromCore(); - void internalSessionStateReceived(const Protocol::SessionState &sessionState); + void internalSessionStateReceived(const Protocol::SessionState& sessionState); - void setupCore(const Protocol::SetupData &setupData); + void setupCore(const Protocol::SetupData& setupData); signals: void stateChanged(CoreConnection::ConnectionState); @@ -91,60 +92,60 @@ signals: void synchronized(); void lagUpdated(int msecs); - void connectionError(const QString &errorMsg); - void connectionErrorPopup(const QString &errorMsg); - void connectionMsg(const QString &msg); + void connectionError(const QString& errorMsg); + void connectionErrorPopup(const QString& errorMsg); + void connectionMsg(const QString& msg); void disconnected(); void progressRangeChanged(int minimum, int maximum); void progressValueChanged(int value); - void progressTextChanged(const QString &); + void progressTextChanged(const QString&); - void startCoreSetup(const QVariantList &backendInfo, const QVariantList &authenticatorInfo); + void startCoreSetup(const QVariantList& backendInfo, const QVariantList& authenticatorInfo); void coreSetupSuccess(); - void coreSetupFailed(const QString &error); + void coreSetupFailed(const QString& error); void connectToInternalCore(QPointer connection); // These signals MUST be handled synchronously! - void userAuthenticationRequired(CoreAccount *, bool *valid, const QString &errorMessage = QString()); - void handleNoSslInClient(bool *accepted); - void handleNoSslInCore(bool *accepted); + void userAuthenticationRequired(CoreAccount*, bool* valid, const QString& errorMessage = QString()); + void handleNoSslInClient(bool* accepted); + void handleNoSslInCore(bool* accepted); #ifdef HAVE_SSL - void handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently); + void handleSslErrors(const QSslSocket* socket, bool* accepted, bool* permanently); #endif private slots: void connectToCurrentAccount(); - void disconnectFromCore(const QString &errorString, bool wantReconnect = true); + void disconnectFromCore(const QString& errorString, bool wantReconnect = true); - void coreSocketError(QAbstractSocket::SocketError error, const QString &errorString); + void coreSocketError(QAbstractSocket::SocketError error, const QString& errorString); void coreSocketDisconnected(); // for sync progress void networkInitDone(); void checkSyncState(); - void loginToCore(const QString &user, const QString &password, bool remember); // for config wizard - void syncToCore(const Protocol::SessionState &sessionState); + void loginToCore(const QString& user, const QString& password, bool remember); // for config wizard + void syncToCore(const Protocol::SessionState& sessionState); void resetConnection(bool wantReconnect = false); void onConnectionReady(); - void onLoginSuccessful(const CoreAccount &account); - void onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState); + void onLoginSuccessful(const CoreAccount& account); + void onHandshakeComplete(RemotePeer* peer, const Protocol::SessionState& sessionState); void updateProgress(int value, int maximum); - void setProgressText(const QString &text); + void setProgressText(const QString& text); void setProgressValue(int value); void setProgressMinimum(int minimum); void setProgressMaximum(int maximum); void setState(ConnectionState state); - void networkDetectionModeChanged(const QVariant &mode); - void pingTimeoutIntervalChanged(const QVariant &interval); - void reconnectIntervalChanged(const QVariant &interval); + void networkDetectionModeChanged(const QVariant& mode); + void pingTimeoutIntervalChanged(const QVariant& interval); + void reconnectIntervalChanged(const QVariant& interval); void reconnectTimeout(); void onlineStateChanged(bool isOnline); @@ -158,7 +159,7 @@ private: bool _wantReconnect{false}; bool _wasReconnect{false}; - QSet _netsToSync; + QSet _netsToSync; int _numNetsToSync; int _progressMinimum{0}, _progressMaximum{-1}, _progressValue{-1}; QString _progressText; @@ -166,22 +167,42 @@ private: bool _resetting{false}; CoreAccount _account; - CoreAccountModel *accountModel() const; + CoreAccountModel* accountModel() const; QPointer _qNetworkConfigurationManager; friend class CoreConfigWizard; }; - Q_DECLARE_METATYPE(CoreConnection::ConnectionState) // Inlines -inline int CoreConnection::progressMinimum() const { return _progressMinimum; } -inline int CoreConnection::progressMaximum() const { return _progressMaximum; } -inline int CoreConnection::progressValue() const { return _progressValue; } -inline QString CoreConnection::progressText() const { return _progressText; } - -inline CoreConnection::ConnectionState CoreConnection::state() const { return _state; } -inline bool CoreConnection::isConnected() const { return state() >= Connected; } -inline CoreAccount CoreConnection::currentAccount() const { return _account; } +inline int CoreConnection::progressMinimum() const +{ + return _progressMinimum; +} +inline int CoreConnection::progressMaximum() const +{ + return _progressMaximum; +} +inline int CoreConnection::progressValue() const +{ + return _progressValue; +} +inline QString CoreConnection::progressText() const +{ + return _progressText; +} + +inline CoreConnection::ConnectionState CoreConnection::state() const +{ + return _state; +} +inline bool CoreConnection::isConnected() const +{ + return state() >= Connected; +} +inline CoreAccount CoreConnection::currentAccount() const +{ + return _account; +} diff --git a/src/client/execwrapper.cpp b/src/client/execwrapper.cpp index 67292df2..44d5e58e 100644 --- a/src/client/execwrapper.cpp +++ b/src/client/execwrapper.cpp @@ -18,17 +18,18 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "execwrapper.h" + #include #include -#include "execwrapper.h" - #include "client.h" #include "messagemodel.h" #include "quassel.h" #include "util.h" -ExecWrapper::ExecWrapper(QObject *parent) : QObject(parent) +ExecWrapper::ExecWrapper(QObject* parent) + : QObject(parent) { connect(&_process, &QProcess::readyReadStandardOutput, this, &ExecWrapper::processReadStdout); connect(&_process, &QProcess::readyReadStandardError, this, &ExecWrapper::processReadStderr); @@ -39,8 +40,7 @@ ExecWrapper::ExecWrapper(QObject *parent) : QObject(parent) connect(this, &ExecWrapper::error, this, &ExecWrapper::postStderr); } - -void ExecWrapper::start(const BufferInfo &info, const QString &command) +void ExecWrapper::start(const BufferInfo& info, const QString& command) { _bufferInfo = info; QString params; @@ -59,7 +59,7 @@ void ExecWrapper::start(const BufferInfo &info, const QString &command) emit error(tr(R"(Name "%1" is invalid: ../ or ..\ are not allowed!)").arg(_scriptName)); else { - foreach(QString scriptDir, Quassel::scriptDirPaths()) { + foreach (QString scriptDir, Quassel::scriptDirPaths()) { QString fileName = scriptDir + _scriptName; if (!QFile::exists(fileName)) continue; @@ -70,24 +70,21 @@ void ExecWrapper::start(const BufferInfo &info, const QString &command) emit error(tr("Could not find script \"%1\"").arg(_scriptName)); } - deleteLater(); // self-destruct + deleteLater(); // self-destruct } - -void ExecWrapper::postStdout(const QString &msg) +void ExecWrapper::postStdout(const QString& msg) { if (_bufferInfo.isValid()) Client::userInput(_bufferInfo, msg); } - -void ExecWrapper::postStderr(const QString &msg) +void ExecWrapper::postStderr(const QString& msg) { if (_bufferInfo.isValid()) Client::messageModel()->insertErrorMessage(_bufferInfo, msg); } - void ExecWrapper::processFinished(int exitCode, QProcess::ExitStatus status) { if (status == QProcess::CrashExit) { @@ -96,16 +93,15 @@ void ExecWrapper::processFinished(int exitCode, QProcess::ExitStatus status) // empty buffers if (!_stdoutBuffer.isEmpty()) - foreach(QString msg, _stdoutBuffer.split('\n')) - emit output(msg); + foreach (QString msg, _stdoutBuffer.split('\n')) + emit output(msg); if (!_stderrBuffer.isEmpty()) - foreach(QString msg, _stderrBuffer.split('\n')) - emit error(msg); + foreach (QString msg, _stderrBuffer.split('\n')) + emit error(msg); deleteLater(); } - void ExecWrapper::processError(QProcess::ProcessError err) { if (err == QProcess::FailedToStart) @@ -117,7 +113,6 @@ void ExecWrapper::processError(QProcess::ProcessError err) deleteLater(); } - void ExecWrapper::processReadStdout() { QString str = QTextCodec::codecForLocale()->toUnicode(_process.readAllStandardOutput()); @@ -130,7 +125,6 @@ void ExecWrapper::processReadStdout() } } - void ExecWrapper::processReadStderr() { QString str = QTextCodec::codecForLocale()->toUnicode(_process.readAllStandardError()); diff --git a/src/client/execwrapper.h b/src/client/execwrapper.h index ce828479..5f3fcce7 100644 --- a/src/client/execwrapper.h +++ b/src/client/execwrapper.h @@ -30,14 +30,14 @@ class ExecWrapper : public QObject Q_OBJECT public: - ExecWrapper(QObject *parent = nullptr); + ExecWrapper(QObject* parent = nullptr); public slots: - void start(const BufferInfo &info, const QString &command); + void start(const BufferInfo& info, const QString& command); signals: - void error(const QString &errorMsg); - void output(const QString &out); + void error(const QString& errorMsg); + void output(const QString& out); private slots: void processReadStdout(); @@ -45,8 +45,8 @@ private slots: void processFinished(int exitCode, QProcess::ExitStatus exitStatus); void processError(QProcess::ProcessError); - void postStdout(const QString &); - void postStderr(const QString &); + void postStdout(const QString&); + void postStderr(const QString&); private: QProcess _process; @@ -56,5 +56,4 @@ private: QString _stderrBuffer; }; - #endif diff --git a/src/client/irclistmodel.cpp b/src/client/irclistmodel.cpp index 91ea7ec0..97dcdfc6 100644 --- a/src/client/irclistmodel.cpp +++ b/src/client/irclistmodel.cpp @@ -22,13 +22,11 @@ #include -IrcListModel::IrcListModel(QObject *parent) +IrcListModel::IrcListModel(QObject* parent) : QAbstractItemModel(parent) -{ -} +{} - -QVariant IrcListModel::data(const QModelIndex &index, int role) const +QVariant IrcListModel::data(const QModelIndex& index, int role) const { if (!index.isValid() || index.row() >= rowCount() || index.column() >= columnCount() || role != Qt::DisplayRole) return QVariant(); @@ -47,8 +45,7 @@ QVariant IrcListModel::data(const QModelIndex &index, int role) const } } - -Qt::ItemFlags IrcListModel::flags(const QModelIndex &index) const +Qt::ItemFlags IrcListModel::flags(const QModelIndex& index) const { if (!index.isValid()) { return Qt::ItemIsDropEnabled; @@ -58,13 +55,10 @@ Qt::ItemFlags IrcListModel::flags(const QModelIndex &index) const } } - QVariant IrcListModel::headerData(int section, Qt::Orientation orientation, int role) const { QStringList header; - header << tr("Channel") - << tr("Users") - << tr("Topic"); + header << tr("Channel") << tr("Users") << tr("Topic"); if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return header[section]; @@ -72,8 +66,7 @@ QVariant IrcListModel::headerData(int section, Qt::Orientation orientation, int return QVariant(); } - -QModelIndex IrcListModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex IrcListModel::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(parent); if (row >= rowCount() || column >= columnCount()) @@ -82,8 +75,7 @@ QModelIndex IrcListModel::index(int row, int column, const QModelIndex &parent) return createIndex(row, column); } - -void IrcListModel::setChannelList(const QList &channelList) +void IrcListModel::setChannelList(const QList& channelList) { if (rowCount() > 0) { beginRemoveRows(QModelIndex(), 0, _channelList.count() - 1); diff --git a/src/client/irclistmodel.h b/src/client/irclistmodel.h index 76227bc3..0c970a13 100644 --- a/src/client/irclistmodel.h +++ b/src/client/irclistmodel.h @@ -22,31 +22,31 @@ #include "client-export.h" -#include "irclisthelper.h" - #include +#include "irclisthelper.h" + class CLIENT_EXPORT IrcListModel : public QAbstractItemModel { Q_OBJECT public: - IrcListModel(QObject *parent = nullptr); + IrcListModel(QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role) const override; - Qt::ItemFlags flags(const QModelIndex &index) const override; + QVariant data(const QModelIndex& index, int role) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; - inline QModelIndex parent(const QModelIndex &) const override { return {}; } + inline QModelIndex parent(const QModelIndex&) const override { return {}; } - inline int rowCount(const QModelIndex &parent = QModelIndex()) const override { Q_UNUSED(parent) return _channelList.count(); } - inline int columnCount(const QModelIndex &parent = QModelIndex()) const override { Q_UNUSED(parent) return 3; } + inline int rowCount(const QModelIndex& parent = QModelIndex()) const override { Q_UNUSED(parent) return _channelList.count(); } + inline int columnCount(const QModelIndex& parent = QModelIndex()) const override { Q_UNUSED(parent) return 3; } public slots: - void setChannelList(const QList &channelList = QList()); + void setChannelList(const QList& channelList = QList()); private: QList _channelList; diff --git a/src/client/messagefilter.cpp b/src/client/messagefilter.cpp index 18aedd21..64ea2a4d 100644 --- a/src/client/messagefilter.cpp +++ b/src/client/messagefilter.cpp @@ -22,32 +22,30 @@ #include +#include "buffermodel.h" #include "buffersettings.h" #include "client.h" -#include "buffermodel.h" +#include "clientignorelistmanager.h" #include "messagemodel.h" #include "networkmodel.h" -#include "clientignorelistmanager.h" -MessageFilter::MessageFilter(QAbstractItemModel *source, QObject *parent) - : QSortFilterProxyModel(parent), - _messageTypeFilter(0) +MessageFilter::MessageFilter(QAbstractItemModel* source, QObject* parent) + : QSortFilterProxyModel(parent) + , _messageTypeFilter(0) { init(); setSourceModel(source); } - -MessageFilter::MessageFilter(MessageModel *source, const QList &buffers, QObject *parent) - : QSortFilterProxyModel(parent), - _validBuffers(buffers.toSet()), - _messageTypeFilter(0) +MessageFilter::MessageFilter(MessageModel* source, const QList& buffers, QObject* parent) + : QSortFilterProxyModel(parent) + , _validBuffers(buffers.toSet()) + , _messageTypeFilter(0) { init(); setSourceModel(source); } - void MessageFilter::init() { setDynamicSortFilter(true); @@ -70,7 +68,6 @@ void MessageFilter::init() mySettings.notify("hasMessageTypeFilter", this, &MessageFilter::messageTypeFilterChanged); } - void MessageFilter::messageTypeFilterChanged() { int newFilter; @@ -88,7 +85,6 @@ void MessageFilter::messageTypeFilterChanged() } } - void MessageFilter::messageRedirectionChanged() { BufferSettings bufferSettings; @@ -113,7 +109,6 @@ void MessageFilter::messageRedirectionChanged() invalidateFilter(); } - QString MessageFilter::idString() const { if (_validBuffers.isEmpty()) @@ -123,14 +118,13 @@ QString MessageFilter::idString() const qSort(bufferIds); QStringList bufferIdStrings; - foreach(BufferId id, bufferIds) - bufferIdStrings << QString::number(id.toInt()); + foreach (BufferId id, bufferIds) + bufferIdStrings << QString::number(id.toInt()); return bufferIdStrings.join("|"); } - -bool MessageFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const +bool MessageFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { Q_UNUSED(sourceParent); QModelIndex sourceIdx = sourceModel()->index(sourceRow, 2); @@ -159,7 +153,8 @@ bool MessageFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourcePar // ignorelist handling // only match if message is not flagged as server msg if (!(flags & Message::ServerMsg) && Client::ignoreListManager() - && Client::ignoreListManager()->match(sourceIdx.data(MessageModel::MessageRole).value(), Client::networkModel()->networkName(bufferId))) + && Client::ignoreListManager()->match(sourceIdx.data(MessageModel::MessageRole).value(), + Client::networkModel()->networkName(bufferId))) return false; if (flags & Message::Redirected) { @@ -224,10 +219,8 @@ bool MessageFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourcePar return false; // Extract timestamp and nickname from the new quit message - qint64 messageTimestamp = sourceModel()->data(sourceIdx, MessageModel::TimestampRole) - .value().toMSecsSinceEpoch(); - QString quiter = nickFromMask(sourceModel()->data(sourceIdx, MessageModel::MessageRole) - .value().sender()).toLower(); + qint64 messageTimestamp = sourceModel()->data(sourceIdx, MessageModel::TimestampRole).value().toMSecsSinceEpoch(); + QString quiter = nickFromMask(sourceModel()->data(sourceIdx, MessageModel::MessageRole).value().sender()).toLower(); // Check that nickname matches query name if (quiter != bufferName().toLower()) @@ -236,22 +229,21 @@ bool MessageFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourcePar // Check if a quit message was already forwarded within +/- 1000 ms static constexpr qint64 MAX_QUIT_DELTA_MS = 1 * 1000; // No need to check if it's the appropriate buffer, each query has a unique message filter - if (std::binary_search(_filteredQuitMsgTime.begin(), _filteredQuitMsgTime.end(), - messageTimestamp, - [](qint64 a, qint64 b) { return ((a + MAX_QUIT_DELTA_MS) < b); } )) { + if (std::binary_search(_filteredQuitMsgTime.begin(), _filteredQuitMsgTime.end(), messageTimestamp, [](qint64 a, qint64 b) { + return ((a + MAX_QUIT_DELTA_MS) < b); + })) { // New element is less than if at least 1000 ms older/newer // Match found, no need to forward another quit message return false; } // Mark query as having a quit message inserted - auto *that = const_cast(this); + auto* that = const_cast(this); that->_filteredQuitMsgTime.insert(messageTimestamp); return true; } } - void MessageFilter::requestBacklog() { QSet::const_iterator bufferIdIter = _validBuffers.constBegin(); diff --git a/src/client/messagefilter.h b/src/client/messagefilter.h index 2919704b..f883dc98 100644 --- a/src/client/messagefilter.h +++ b/src/client/messagefilter.h @@ -22,9 +22,10 @@ #include "client-export.h" -#include #include +#include + #include "bufferinfo.h" #include "client.h" #include "messagemodel.h" @@ -36,19 +37,19 @@ class CLIENT_EXPORT MessageFilter : public QSortFilterProxyModel Q_OBJECT protected: - MessageFilter(QAbstractItemModel *source, QObject *parent = nullptr); + MessageFilter(QAbstractItemModel* source, QObject* parent = nullptr); public: - MessageFilter(MessageModel *, const QList &buffers = QList(), QObject *parent = nullptr); + MessageFilter(MessageModel*, const QList& buffers = QList(), QObject* parent = nullptr); virtual QString idString() const; bool isSingleBufferFilter() const { return _validBuffers.count() == 1; } BufferId singleBufferId() const { return *(_validBuffers.constBegin()); } - bool containsBuffer(const BufferId &id) const { return _validBuffers.contains(id); } + bool containsBuffer(const BufferId& id) const { return _validBuffers.contains(id); } QSet containedBuffers() const { return _validBuffers; } - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; public slots: void messageTypeFilterChanged(); @@ -66,7 +67,7 @@ private: void init(); QSet _validBuffers; - std::set _filteredQuitMsgTime; ///< Timestamps (ms) of already forwarded quit messages + std::set _filteredQuitMsgTime; ///< Timestamps (ms) of already forwarded quit messages int _messageTypeFilter; int _userNoticesTarget; diff --git a/src/client/messagemodel.cpp b/src/client/messagemodel.cpp index a4b050d2..fd59ddb2 100644 --- a/src/client/messagemodel.cpp +++ b/src/client/messagemodel.cpp @@ -23,36 +23,36 @@ #include #include "backlogsettings.h" -#include "clientbacklogmanager.h" #include "client.h" +#include "clientbacklogmanager.h" #include "message.h" #include "networkmodel.h" class ProcessBufferEvent : public QEvent { public: - inline ProcessBufferEvent() : QEvent(QEvent::User) {} + inline ProcessBufferEvent() + : QEvent(QEvent::User) + {} }; - -MessageModel::MessageModel(QObject *parent) +MessageModel::MessageModel(QObject* parent) : QAbstractItemModel(parent) { QDateTime now = QDateTime::currentDateTime(); now.setTimeSpec(Qt::UTC); _nextDayChange.setTimeSpec(Qt::UTC); - _nextDayChange.setMSecsSinceEpoch( - ((now.toMSecsSinceEpoch() / DAY_IN_MSECS) + 1) * DAY_IN_MSECS); + _nextDayChange.setMSecsSinceEpoch(((now.toMSecsSinceEpoch() / DAY_IN_MSECS) + 1) * DAY_IN_MSECS); _nextDayChange.setTimeSpec(Qt::LocalTime); _dayChangeTimer.setInterval(QDateTime::currentDateTime().secsTo(_nextDayChange) * 1000); _dayChangeTimer.start(); connect(&_dayChangeTimer, &QTimer::timeout, this, &MessageModel::changeOfDay); } - -QVariant MessageModel::data(const QModelIndex &index, int role) const +QVariant MessageModel::data(const QModelIndex& index, int role) const { - int row = index.row(); int column = index.column(); + int row = index.row(); + int column = index.column(); if (row < 0 || row >= messageCount() || column < 0) return QVariant(); @@ -63,8 +63,7 @@ QVariant MessageModel::data(const QModelIndex &index, int role) const // return _messageList[row]->data(index.column(), role); } - -bool MessageModel::setData(const QModelIndex &index, const QVariant &value, int role) +bool MessageModel::setData(const QModelIndex& index, const QVariant& value, int role) { int row = index.row(); if (row < 0 || row >= messageCount()) @@ -77,12 +76,11 @@ bool MessageModel::setData(const QModelIndex &index, const QVariant &value, int return false; } - -bool MessageModel::insertMessage(const Message &msg, bool fakeMsg) +bool MessageModel::insertMessage(const Message& msg, bool fakeMsg) { MsgId id = msg.msgId(); int idx = indexForId(id); - if (!fakeMsg && idx < messageCount()) { // check for duplicate + if (!fakeMsg && idx < messageCount()) { // check for duplicate if (messageItemAt(idx)->msgId() == id) return false; } @@ -91,8 +89,7 @@ bool MessageModel::insertMessage(const Message &msg, bool fakeMsg) return true; } - -void MessageModel::insertMessages(const QList &msglist) +void MessageModel::insertMessages(const QList& msglist) { if (msglist.isEmpty()) return; @@ -118,12 +115,11 @@ void MessageModel::insertMessages(const QList &msglist) } } - -void MessageModel::insertMessageGroup(const QList &msglist) +void MessageModel::insertMessageGroup(const QList& msglist) { - Q_ASSERT(!msglist.isEmpty()); // the msglist can be assumed to be non empty -// int last = msglist.count() - 1; -// Q_ASSERT(0 == last || msglist.at(0).msgId() != msglist.at(last).msgId() || msglist.at(last).type() == Message::DayChange); + Q_ASSERT(!msglist.isEmpty()); // the msglist can be assumed to be non empty + // int last = msglist.count() - 1; + // Q_ASSERT(0 == last || msglist.at(0).msgId() != msglist.at(last).msgId() || msglist.at(last).type() == Message::DayChange); int start = indexForId(msglist.first().msgId()); int end = start + msglist.count() - 1; Message dayChangeMsg; @@ -132,8 +128,7 @@ void MessageModel::insertMessageGroup(const QList &msglist) // check if the preceeding msg is a daychange message and if so if // we have to drop or relocate it at the end of this chunk int prevIdx = start - 1; - if (messageItemAt(prevIdx)->msgType() == Message::DayChange - && messageItemAt(prevIdx)->timestamp() > msglist.at(0).timestamp()) { + if (messageItemAt(prevIdx)->msgType() == Message::DayChange && messageItemAt(prevIdx)->timestamp() > msglist.at(0).timestamp()) { beginRemoveRows(QModelIndex(), prevIdx, prevIdx); Message oldDayChangeMsg = takeMessageAt(prevIdx); if (msglist.last().timestamp() < oldDayChangeMsg.timestamp()) { @@ -180,13 +175,13 @@ void MessageModel::insertMessageGroup(const QList &msglist) insertMessage__(start + msglist.count(), dayChangeMsg); endInsertRows(); - Q_ASSERT(start == end || messageItemAt(start)->msgId() != messageItemAt(end)->msgId() || messageItemAt(end)->msgType() == Message::DayChange); + Q_ASSERT(start == end || messageItemAt(start)->msgId() != messageItemAt(end)->msgId() + || messageItemAt(end)->msgType() == Message::DayChange); Q_ASSERT(start == 0 || messageItemAt(start - 1)->msgId() < messageItemAt(start)->msgId()); Q_ASSERT(end + 1 == messageCount() || messageItemAt(end)->msgId() < messageItemAt(end + 1)->msgId()); } - -int MessageModel::insertMessagesGracefully(const QList &msglist) +int MessageModel::insertMessagesGracefully(const QList& msglist) { /* short description: * 1) first we check where the message with the highest msgId from msglist would be inserted @@ -201,13 +196,13 @@ int MessageModel::insertMessagesGracefully(const QList &msglist) QList grouplist; MsgId minId; MsgId dupeId; - int processedMsgs = 1; // we know the list isn't empty, so we at least process one message + int processedMsgs = 1; // we know the list isn't empty, so we at least process one message int idx; bool fastForward = false; QList::const_iterator iter; if (inOrder) { iter = msglist.constEnd(); - --iter; // this op is safe as we've allready passed an empty check + --iter; // this op is safe as we've allready passed an empty check } else { iter = msglist.constBegin(); @@ -240,7 +235,7 @@ int MessageModel::insertMessagesGracefully(const QList &msglist) break; processedMsgs++; - if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId + if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId idx = indexForId((*iter).msgId()); if (idx >= 0 && !messagesIsEmpty()) dupeId = messageItemAt(idx)->msgId(); @@ -272,7 +267,7 @@ int MessageModel::insertMessagesGracefully(const QList &msglist) break; processedMsgs++; - if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId + if (grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId idx = indexForId((*iter).msgId()); if (idx >= 0 && !messagesIsEmpty()) dupeId = messageItemAt(idx)->msgId(); @@ -305,8 +300,7 @@ int MessageModel::insertMessagesGracefully(const QList &msglist) return processedMsgs; } - -void MessageModel::customEvent(QEvent *event) +void MessageModel::customEvent(QEvent* event) { if (event->type() != QEvent::User) return; @@ -326,7 +320,6 @@ void MessageModel::customEvent(QEvent *event) QCoreApplication::postEvent(this, new ProcessBufferEvent()); } - void MessageModel::clear() { _messagesWaiting.clear(); @@ -337,7 +330,6 @@ void MessageModel::clear() } } - // returns index of msg with given Id or of the next message after that (i.e., the index where we'd insert this msg) int MessageModel::indexForId(MsgId id) { @@ -348,17 +340,19 @@ int MessageModel::indexForId(MsgId id) return messageCount(); // binary search - int start = 0; int end = messageCount() - 1; + int start = 0; + int end = messageCount() - 1; while (true) { if (end - start == 1) return end; int pivot = (end + start) / 2; - if (id <= messageItemAt(pivot)->msgId()) end = pivot; - else start = pivot; + if (id <= messageItemAt(pivot)->msgId()) + end = pivot; + else + start = pivot; } } - void MessageModel::changeOfDay() { _dayChangeTimer.setInterval(DAY_IN_MSECS); @@ -376,21 +370,19 @@ void MessageModel::changeOfDay() _nextDayChange = _nextDayChange.addMSecs(DAY_IN_MSECS); } - -void MessageModel::insertErrorMessage(BufferInfo bufferInfo, const QString &errorString) +void MessageModel::insertErrorMessage(BufferInfo bufferInfo, const QString& errorString) { int idx = messageCount(); beginInsertRows(QModelIndex(), idx, idx); Message msg(bufferInfo, Message::Error, errorString); if (!messagesIsEmpty()) - msg.setMsgId(messageItemAt(idx-1)->msgId()); + msg.setMsgId(messageItemAt(idx - 1)->msgId()); else msg.setMsgId(0); insertMessage__(idx, msg); endInsertRows(); } - void MessageModel::requestBacklog(BufferId bufferId) { if (_messagesWaiting.contains(bufferId)) @@ -403,16 +395,15 @@ void MessageModel::requestBacklog(BufferId bufferId) if (messageItemAt(i)->bufferId() == bufferId) { _messagesWaiting[bufferId] = requestCount; Client::backlogManager()->emitMessagesRequested(tr("Requesting %1 messages from backlog for buffer %2:%3") - .arg(requestCount) - .arg(Client::networkModel()->networkName(bufferId)) - .arg(Client::networkModel()->bufferName(bufferId))); + .arg(requestCount) + .arg(Client::networkModel()->networkName(bufferId)) + .arg(Client::networkModel()->bufferName(bufferId))); Client::backlogManager()->requestBacklog(bufferId, -1, messageItemAt(i)->msgId(), requestCount); return; } } } - void MessageModel::messagesReceived(BufferId bufferId, int count) { if (!_messagesWaiting.contains(bufferId)) @@ -425,7 +416,6 @@ void MessageModel::messagesReceived(BufferId bufferId, int count) } } - void MessageModel::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) { for (int i = 0; i < messageCount(); i++) { @@ -437,7 +427,6 @@ void MessageModel::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferI } } - // ======================================== // MessageModelItem // ======================================== @@ -466,8 +455,7 @@ QVariant MessageModelItem::data(int column, int role) const } } - -bool MessageModelItem::setData(int column, const QVariant &value, int role) +bool MessageModelItem::setData(int column, const QVariant& value, int role) { Q_UNUSED(column); @@ -480,38 +468,32 @@ bool MessageModelItem::setData(int column, const QVariant &value, int role) } } - // Stuff for later -bool MessageModelItem::lessThan(const MessageModelItem *m1, const MessageModelItem *m2) +bool MessageModelItem::lessThan(const MessageModelItem* m1, const MessageModelItem* m2) { return (*m1) < (*m2); } - -bool MessageModelItem::operator<(const MessageModelItem &other) const +bool MessageModelItem::operator<(const MessageModelItem& other) const { return msgId() < other.msgId(); } - -bool MessageModelItem::operator==(const MessageModelItem &other) const +bool MessageModelItem::operator==(const MessageModelItem& other) const { return msgId() == other.msgId(); } - -bool MessageModelItem::operator>(const MessageModelItem &other) const +bool MessageModelItem::operator>(const MessageModelItem& other) const { return msgId() > other.msgId(); } - -QDebug operator<<(QDebug dbg, const MessageModelItem &msgItem) +QDebug operator<<(QDebug dbg, const MessageModelItem& msgItem) { - dbg.nospace() << qPrintable(QString("MessageModelItem(MsgId:")) << msgItem.msgId() - << qPrintable(QString(",")) << msgItem.timestamp() - << qPrintable(QString(", Type:")) << msgItem.msgType() - << qPrintable(QString(", Flags:")) << msgItem.msgFlags() << qPrintable(QString(")")) - << msgItem.data(1, Qt::DisplayRole).toString() << ":" << msgItem.data(2, Qt::DisplayRole).toString(); + dbg.nospace() << qPrintable(QString("MessageModelItem(MsgId:")) << msgItem.msgId() << qPrintable(QString(",")) << msgItem.timestamp() + << qPrintable(QString(", Type:")) << msgItem.msgType() << qPrintable(QString(", Flags:")) << msgItem.msgFlags() + << qPrintable(QString(")")) << msgItem.data(1, Qt::DisplayRole).toString() << ":" + << msgItem.data(2, Qt::DisplayRole).toString(); return dbg; } diff --git a/src/client/messagemodel.h b/src/client/messagemodel.h index 63772822..e7094d28 100644 --- a/src/client/messagemodel.h +++ b/src/client/messagemodel.h @@ -37,7 +37,8 @@ class CLIENT_EXPORT MessageModel : public QAbstractItemModel Q_OBJECT public: - enum MessageModelRole { + enum MessageModelRole + { DisplayRole = Qt::DisplayRole, EditRole = Qt::EditRole, BackgroundRole = Qt::BackgroundRole, @@ -53,24 +54,28 @@ public: UserRole }; - enum ColumnType { - TimestampColumn, SenderColumn, ContentsColumn, UserColumnType + enum ColumnType + { + TimestampColumn, + SenderColumn, + ContentsColumn, + UserColumnType }; - MessageModel(QObject *parent); + MessageModel(QObject* parent); - inline QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; - inline QModelIndex parent(const QModelIndex &) const override { return {}; } - inline int rowCount(const QModelIndex &parent = QModelIndex()) const override { return parent.isValid() ? 0 : messageCount(); } - inline int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const override { return 3; } + inline QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + inline QModelIndex parent(const QModelIndex&) const override { return {}; } + inline int rowCount(const QModelIndex& parent = QModelIndex()) const override { return parent.isValid() ? 0 : messageCount(); } + inline int columnCount(const QModelIndex& /*parent*/ = QModelIndex()) const override { return 3; } - QVariant data(const QModelIndex &index, int role) const override; - bool setData(const QModelIndex &index, const QVariant &value, int role) override; + QVariant data(const QModelIndex& index, int role) const override; + bool setData(const QModelIndex& index, const QVariant& value, int role) override; - //virtual Qt::ItemFlags flags(const QModelIndex &index) const; + // virtual Qt::ItemFlags flags(const QModelIndex &index) const; - bool insertMessage(const Message &, bool fakeMsg = false); - void insertMessages(const QList &); + bool insertMessage(const Message&, bool fakeMsg = false); + void insertMessages(const QList&); void clear(); @@ -81,33 +86,33 @@ public slots: void requestBacklog(BufferId bufferId); void messagesReceived(BufferId bufferId, int count); void buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2); - void insertErrorMessage(BufferInfo bufferInfo, const QString &errorString); + void insertErrorMessage(BufferInfo bufferInfo, const QString& errorString); protected: -// virtual MessageModelItem *createMessageModelItem(const Message &) = 0; + // virtual MessageModelItem *createMessageModelItem(const Message &) = 0; virtual int messageCount() const = 0; virtual bool messagesIsEmpty() const = 0; - virtual const MessageModelItem *messageItemAt(int i) const = 0; - virtual MessageModelItem *messageItemAt(int i) = 0; - virtual const MessageModelItem *firstMessageItem() const = 0; - virtual MessageModelItem *firstMessageItem() = 0; - virtual const MessageModelItem *lastMessageItem() const = 0; - virtual MessageModelItem *lastMessageItem() = 0; - virtual void insertMessage__(int pos, const Message &) = 0; - virtual void insertMessages__(int pos, const QList &) = 0; + virtual const MessageModelItem* messageItemAt(int i) const = 0; + virtual MessageModelItem* messageItemAt(int i) = 0; + virtual const MessageModelItem* firstMessageItem() const = 0; + virtual MessageModelItem* firstMessageItem() = 0; + virtual const MessageModelItem* lastMessageItem() const = 0; + virtual MessageModelItem* lastMessageItem() = 0; + virtual void insertMessage__(int pos, const Message&) = 0; + virtual void insertMessages__(int pos, const QList&) = 0; virtual void removeMessageAt(int i) = 0; virtual void removeAllMessages() = 0; virtual Message takeMessageAt(int i) = 0; - void customEvent(QEvent *event) override; + void customEvent(QEvent* event) override; private slots: void changeOfDay(); private: - void insertMessageGroup(const QList &); - int insertMessagesGracefully(const QList &); // inserts as many contiguous msgs as possible. returns numer of inserted msgs. + void insertMessageGroup(const QList&); + int insertMessagesGracefully(const QList&); // inserts as many contiguous msgs as possible. returns numer of inserted msgs. int indexForId(MsgId); // QList _messageList; @@ -121,9 +126,8 @@ private: const qint64 DAY_IN_MSECS = 24 * 60 * 60 * 1000; }; - // inlines -QModelIndex MessageModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex MessageModel::index(int row, int column, const QModelIndex& parent) const { if (row < 0 || row >= rowCount(parent) || column < 0 || column >= columnCount(parent)) return {}; @@ -131,7 +135,6 @@ QModelIndex MessageModel::index(int row, int column, const QModelIndex &parent) return createIndex(row, column); } - // ************************************************** // MessageModelItem // ************************************************** @@ -146,25 +149,24 @@ public: inline virtual ~MessageModelItem() = default; virtual QVariant data(int column, int role) const; - virtual bool setData(int column, const QVariant &value, int role); + virtual bool setData(int column, const QVariant& value, int role); - virtual const Message &message() const = 0; - virtual const QDateTime ×tamp() const = 0; - virtual const MsgId &msgId() const = 0; - virtual const BufferId &bufferId() const = 0; + virtual const Message& message() const = 0; + virtual const QDateTime& timestamp() const = 0; + virtual const MsgId& msgId() const = 0; + virtual const BufferId& bufferId() const = 0; virtual void setBufferId(BufferId bufferId) = 0; virtual Message::Type msgType() const = 0; virtual Message::Flags msgFlags() const = 0; // For sorting - bool operator<(const MessageModelItem &) const; - bool operator==(const MessageModelItem &) const; - bool operator>(const MessageModelItem &) const; - static bool lessThan(const MessageModelItem *m1, const MessageModelItem *m2); + bool operator<(const MessageModelItem&) const; + bool operator==(const MessageModelItem&) const; + bool operator>(const MessageModelItem&) const; + static bool lessThan(const MessageModelItem* m1, const MessageModelItem* m2); private: BufferId _redirectedTo; }; - -QDebug operator<<(QDebug dbg, const MessageModelItem &msgItem); +QDebug operator<<(QDebug dbg, const MessageModelItem& msgItem); diff --git a/src/client/networkmodel.cpp b/src/client/networkmodel.cpp index 12410201..752eb1e9 100644 --- a/src/client/networkmodel.cpp +++ b/src/client/networkmodel.cpp @@ -20,27 +20,28 @@ #include "networkmodel.h" +#include + #include #include -#include #include "buffermodel.h" #include "buffersettings.h" +#include "buffersyncer.h" #include "client.h" #include "clientignorelistmanager.h" #include "clientsettings.h" #include "ircchannel.h" #include "network.h" #include "signalproxy.h" -#include "buffersyncer.h" /***************************************** -* Network Items -*****************************************/ -NetworkItem::NetworkItem(const NetworkId &netid, AbstractTreeItem *parent) - : PropertyMapItem(parent), - _networkId(netid), - _statusBufferItem(nullptr) + * Network Items + *****************************************/ +NetworkItem::NetworkItem(const NetworkId& netid, AbstractTreeItem* parent) + : PropertyMapItem(parent) + , _networkId(netid) + , _statusBufferItem(nullptr) { // DO NOT EMIT dataChanged() DIRECTLY IN NetworkItem // use networkDataChanged() instead. Otherwise you will end up in a infinite loop @@ -50,14 +51,12 @@ NetworkItem::NetworkItem(const NetworkId &netid, AbstractTreeItem *parent) connect(this, &NetworkItem::beginRemoveChilds, this, &NetworkItem::onBeginRemoveChilds); } - QStringList NetworkItem::propertyOrder() const { static QStringList order{"networkName", "currentServer", "nickCount"}; return order; } - QVariant NetworkItem::data(int column, int role) const { switch (role) { @@ -80,7 +79,7 @@ QVariant NetworkItem::data(int column, int role) const } } -QString NetworkItem::escapeHTML(const QString &string, bool useNonbreakingSpaces) +QString NetworkItem::escapeHTML(const QString& string, bool useNonbreakingSpaces) { // QString.replace() doesn't guarantee the source string will remain constant. // Use a local variable to avoid compiler errors. @@ -88,14 +87,13 @@ QString NetworkItem::escapeHTML(const QString &string, bool useNonbreakingSpaces return (useNonbreakingSpaces ? formattedString.replace(" ", " ") : formattedString); } - // FIXME shouldn't we check the bufferItemCache here? -BufferItem *NetworkItem::findBufferItem(BufferId bufferId) +BufferItem* NetworkItem::findBufferItem(BufferId bufferId) { - BufferItem *bufferItem = nullptr; + BufferItem* bufferItem = nullptr; for (int i = 0; i < childCount(); i++) { - bufferItem = qobject_cast(child(i)); + bufferItem = qobject_cast(child(i)); if (!bufferItem) continue; if (bufferItem->bufferId() == bufferId) @@ -104,10 +102,9 @@ BufferItem *NetworkItem::findBufferItem(BufferId bufferId) return nullptr; } - -BufferItem *NetworkItem::bufferItem(const BufferInfo &bufferInfo) +BufferItem* NetworkItem::bufferItem(const BufferInfo& bufferInfo) { - BufferItem *bufferItem = findBufferItem(bufferInfo); + BufferItem* bufferItem = findBufferItem(bufferInfo); if (bufferItem) return bufferItem; @@ -133,61 +130,48 @@ BufferItem *NetworkItem::bufferItem(const BufferInfo &bufferInfo) // postprocess... this is necessary because Qt doesn't seem to like adding children which already have children on their own switch (bufferInfo.type()) { - case BufferInfo::ChannelBuffer: - { - auto *channelBufferItem = static_cast(bufferItem); + case BufferInfo::ChannelBuffer: { + auto* channelBufferItem = static_cast(bufferItem); if (_network) { - IrcChannel *ircChannel = _network->ircChannel(bufferInfo.bufferName()); + IrcChannel* ircChannel = _network->ircChannel(bufferInfo.bufferName()); if (ircChannel) channelBufferItem->attachIrcChannel(ircChannel); } - } - break; + } break; default: break; } - BufferSyncer *bufferSyncer = Client::bufferSyncer(); + BufferSyncer* bufferSyncer = Client::bufferSyncer(); if (bufferSyncer) { - bufferItem->addActivity( - bufferSyncer->activity(bufferItem->bufferId()), - bufferSyncer->highlightCount(bufferItem->bufferId()) > 0 - ); + bufferItem->addActivity(bufferSyncer->activity(bufferItem->bufferId()), bufferSyncer->highlightCount(bufferItem->bufferId()) > 0); } return bufferItem; } - -void NetworkItem::attachNetwork(Network *network) +void NetworkItem::attachNetwork(Network* network) { if (!network) return; _network = network; - connect(network, &Network::networkNameSet, - this, &NetworkItem::setNetworkName); - connect(network, &Network::currentServerSet, - this, &NetworkItem::setCurrentServer); - connect(network, &Network::ircChannelAdded, - this, &NetworkItem::attachIrcChannel); - connect(network, &Network::ircUserAdded, - this, &NetworkItem::attachIrcUser); - connect(network, &Network::connectedSet, - this, [this]() { emit networkDataChanged(); }); - connect(network, &QObject::destroyed, - this, &NetworkItem::onNetworkDestroyed); + connect(network, &Network::networkNameSet, this, &NetworkItem::setNetworkName); + connect(network, &Network::currentServerSet, this, &NetworkItem::setCurrentServer); + connect(network, &Network::ircChannelAdded, this, &NetworkItem::attachIrcChannel); + connect(network, &Network::ircUserAdded, this, &NetworkItem::attachIrcUser); + connect(network, &Network::connectedSet, this, [this]() { emit networkDataChanged(); }); + connect(network, &QObject::destroyed, this, &NetworkItem::onNetworkDestroyed); emit networkDataChanged(); } - -void NetworkItem::attachIrcChannel(IrcChannel *ircChannel) +void NetworkItem::attachIrcChannel(IrcChannel* ircChannel) { - ChannelBufferItem *channelItem; + ChannelBufferItem* channelItem; for (int i = 0; i < childCount(); i++) { - channelItem = qobject_cast(child(i)); + channelItem = qobject_cast(child(i)); if (!channelItem) continue; @@ -198,12 +182,11 @@ void NetworkItem::attachIrcChannel(IrcChannel *ircChannel) } } - -void NetworkItem::attachIrcUser(IrcUser *ircUser) +void NetworkItem::attachIrcUser(IrcUser* ircUser) { - QueryBufferItem *queryItem = nullptr; + QueryBufferItem* queryItem = nullptr; for (int i = 0; i < childCount(); i++) { - queryItem = qobject_cast(child(i)); + queryItem = qobject_cast(child(i)); if (!queryItem) continue; @@ -214,26 +197,23 @@ void NetworkItem::attachIrcUser(IrcUser *ircUser) } } - -void NetworkItem::setNetworkName(const QString &networkName) +void NetworkItem::setNetworkName(const QString& networkName) { Q_UNUSED(networkName); emit networkDataChanged(0); } - -void NetworkItem::setCurrentServer(const QString &serverName) +void NetworkItem::setCurrentServer(const QString& serverName) { Q_UNUSED(serverName); emit networkDataChanged(1); } - QString NetworkItem::toolTip(int column) const { Q_UNUSED(column); QString strTooltip; - QTextStream tooltip( &strTooltip, QIODevice::WriteOnly ); + QTextStream tooltip(&strTooltip, QIODevice::WriteOnly); tooltip << ""; // Function to add a row to the tooltip table @@ -252,18 +232,18 @@ QString NetworkItem::toolTip(int column) const addRow(tr("Lag"), NetworkItem::escapeHTML(tr("%1 msecs").arg(_network->latency()), true), true); tooltip << ""; - } else { + } + else { tooltip << "

" << tr("Not connected") << "

"; } tooltip << "
"; return strTooltip; } - void NetworkItem::onBeginRemoveChilds(int start, int end) { for (int i = start; i <= end; i++) { - auto *statusBufferItem = qobject_cast(child(i)); + auto* statusBufferItem = qobject_cast(child(i)); if (statusBufferItem) { _statusBufferItem = nullptr; break; @@ -271,7 +251,6 @@ void NetworkItem::onBeginRemoveChilds(int start, int end) } } - void NetworkItem::onNetworkDestroyed() { _network = nullptr; @@ -279,26 +258,23 @@ void NetworkItem::onNetworkDestroyed() removeAllChilds(); } - /***************************************** -* Fancy Buffer Items -*****************************************/ -BufferItem::BufferItem(BufferInfo bufferInfo, AbstractTreeItem *parent) - : PropertyMapItem(parent), - _bufferInfo(std::move(bufferInfo)), - _activity(BufferInfo::NoActivity) + * Fancy Buffer Items + *****************************************/ +BufferItem::BufferItem(BufferInfo bufferInfo, AbstractTreeItem* parent) + : PropertyMapItem(parent) + , _bufferInfo(std::move(bufferInfo)) + , _activity(BufferInfo::NoActivity) { setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); } - QStringList BufferItem::propertyOrder() const { static QStringList order{"bufferName", "topic", "nickCount"}; return order; } - void BufferItem::setActivityLevel(BufferInfo::ActivityLevel level) { if (_activity != level) { @@ -307,13 +283,13 @@ void BufferItem::setActivityLevel(BufferInfo::ActivityLevel level) } } - void BufferItem::clearActivityLevel() { if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) { // If the core handles activity sync, clear only the highlight flag _activity &= ~BufferInfo::Highlight; - } else { + } + else { _activity = BufferInfo::NoActivity; } _firstUnreadMsgId = MsgId(); @@ -326,8 +302,7 @@ void BufferItem::clearActivityLevel() emit dataChanged(); } - -void BufferItem::updateActivityLevel(const Message &msg) +void BufferItem::updateActivityLevel(const Message& msg) { // If the core handles activity, and this message is not a highlight, ignore this if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync) && !msg.flags().testFlag(Message::Highlight)) { @@ -338,11 +313,10 @@ void BufferItem::updateActivityLevel(const Message &msg) return; } - if (msg.flags() & Message::Self) // don't update activity for our own messages + if (msg.flags() & Message::Self) // don't update activity for our own messages return; - if (Client::ignoreListManager() - && Client::ignoreListManager()->match(msg, qobject_cast(parent())->networkName())) + if (Client::ignoreListManager() && Client::ignoreListManager()->match(msg, qobject_cast(parent())->networkName())) return; if (msg.msgId() <= lastSeenMsgId()) @@ -358,7 +332,8 @@ void BufferItem::updateActivityLevel(const Message &msg) // If the core handles activities, ignore types if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) { type = Message::Types(); - } else { + } + else { type = msg.type(); } @@ -367,7 +342,8 @@ void BufferItem::updateActivityLevel(const Message &msg) } } -void BufferItem::setActivity(Message::Types type, bool highlight) { +void BufferItem::setActivity(Message::Types type, bool highlight) +{ BufferInfo::ActivityLevel oldLevel = activityLevel(); _activity &= BufferInfo::Highlight; @@ -378,7 +354,8 @@ void BufferItem::setActivity(Message::Types type, bool highlight) { } } -bool BufferItem::addActivity(Message::Types type, bool highlight) { +bool BufferItem::addActivity(Message::Types type, bool highlight) +{ auto oldActivity = activityLevel(); if (type != Message::Types()) @@ -393,7 +370,6 @@ bool BufferItem::addActivity(Message::Types type, bool highlight) { return oldActivity != _activity; } - QVariant BufferItem::data(int column, int role) const { switch (role) { @@ -420,8 +396,7 @@ QVariant BufferItem::data(int column, int role) const } } - -bool BufferItem::setData(int column, const QVariant &value, int role) +bool BufferItem::setData(int column, const QVariant& value, int role) { switch (role) { case NetworkModel::BufferActivityRole: @@ -433,14 +408,12 @@ bool BufferItem::setData(int column, const QVariant &value, int role) return true; } - -void BufferItem::setBufferName(const QString &name) +void BufferItem::setBufferName(const QString& name) { _bufferInfo = BufferInfo(_bufferInfo.bufferId(), _bufferInfo.networkId(), _bufferInfo.type(), _bufferInfo.groupId(), name); emit dataChanged(0); } - void BufferItem::setLastSeenMsgId(MsgId msgId) { _lastSeenMsgId = msgId; @@ -454,71 +427,63 @@ void BufferItem::setLastSeenMsgId(MsgId msgId) setActivityLevel(BufferInfo::NoActivity); } - void BufferItem::setMarkerLineMsgId(MsgId msgId) { _markerLineMsgId = msgId; emit dataChanged(); } - bool BufferItem::isCurrentBuffer() const { return _bufferInfo.bufferId() == Client::bufferModel()->currentIndex().data(NetworkModel::BufferIdRole).value(); } - QString BufferItem::toolTip(int column) const { Q_UNUSED(column); return tr("

%1 - %2

").arg(bufferInfo().bufferId().toInt()).arg(bufferName()); } - /***************************************** -* StatusBufferItem -*****************************************/ -StatusBufferItem::StatusBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent) + * StatusBufferItem + *****************************************/ +StatusBufferItem::StatusBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent) : BufferItem(bufferInfo, parent) -{ -} - +{} QString StatusBufferItem::toolTip(int column) const { - auto *networkItem = qobject_cast(parent()); + auto* networkItem = qobject_cast(parent()); if (networkItem) return networkItem->toolTip(column); else return QString(); } - /***************************************** -* QueryBufferItem -*****************************************/ -QueryBufferItem::QueryBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent) - : BufferItem(bufferInfo, parent), - _ircUser(nullptr) + * QueryBufferItem + *****************************************/ +QueryBufferItem::QueryBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent) + : BufferItem(bufferInfo, parent) + , _ircUser(nullptr) { setFlags(flags() | Qt::ItemIsDropEnabled | Qt::ItemIsEditable); - const Network *net = Client::network(bufferInfo.networkId()); + const Network* net = Client::network(bufferInfo.networkId()); if (!net) return; - IrcUser *ircUser = net->ircUser(bufferInfo.bufferName()); + IrcUser* ircUser = net->ircUser(bufferInfo.bufferName()); setIrcUser(ircUser); } - QVariant QueryBufferItem::data(int column, int role) const { switch (role) { case Qt::EditRole: return BufferItem::data(column, Qt::DisplayRole); case NetworkModel::IrcUserRole: - return QVariant::fromValue(_ircUser); + return QVariant::fromValue(_ircUser); case NetworkModel::UserAwayRole: return (bool)_ircUser ? _ircUser->isAway() : false; default: @@ -526,15 +491,13 @@ QVariant QueryBufferItem::data(int column, int role) const } } - -bool QueryBufferItem::setData(int column, const QVariant &value, int role) +bool QueryBufferItem::setData(int column, const QVariant& value, int role) { if (column != 0) return BufferItem::setData(column, value, role); switch (role) { - case Qt::EditRole: - { + case Qt::EditRole: { QString newName = value.toString(); // Sanity check - buffer names must not contain newlines! @@ -549,30 +512,27 @@ bool QueryBufferItem::setData(int column, const QVariant &value, int role) else { return false; } - } - break; + } break; default: return BufferItem::setData(column, value, role); } } - -void QueryBufferItem::setBufferName(const QString &name) +void QueryBufferItem::setBufferName(const QString& name) { BufferItem::setBufferName(name); NetworkId netId = data(0, NetworkModel::NetworkIdRole).value(); - const Network *net = Client::network(netId); + const Network* net = Client::network(netId); if (net) setIrcUser(net->ircUser(name)); } - QString QueryBufferItem::toolTip(int column) const { // pretty much code duplication of IrcUserItem::toolTip() but inheritance won't solve this... Q_UNUSED(column); QString strTooltip; - QTextStream tooltip( &strTooltip, QIODevice::WriteOnly ); + QTextStream tooltip(&strTooltip, QIODevice::WriteOnly); tooltip << ""; // Keep track of whether or not information has been added @@ -584,7 +544,8 @@ QString QueryBufferItem::toolTip(int column) const if (!_ircUser) { // User seems to be offline, let the no information message be added below tooltip << "

"; - } else { + } + else { // Function to add a row to the tooltip table auto addRow = [&](const QString& key, const QString& value, bool condition) { if (condition) { @@ -595,7 +556,7 @@ QString QueryBufferItem::toolTip(int column) const // User information is available if (_ircUser->userModes() != "") { - //TODO Translate user Modes and add them to the table below and in IrcUserItem::toolTip + // TODO Translate user Modes and add them to the table below and in IrcUserItem::toolTip tooltip << " (" << _ircUser->userModes() << ")"; } tooltip << "

"; @@ -610,16 +571,13 @@ QString QueryBufferItem::toolTip(int column) const } addRow(NetworkItem::escapeHTML(tr("Away message"), true), awayMessageHTML, true); } - addRow(tr("Realname"), - NetworkItem::escapeHTML(_ircUser->realName()), - !_ircUser->realName().isEmpty()); + addRow(tr("Realname"), NetworkItem::escapeHTML(_ircUser->realName()), !_ircUser->realName().isEmpty()); // suserHost may return " is available for help", which should be translated. // See https://www.alien.net.au/irc/irc2numerics.html - if(_ircUser->suserHost().endsWith("available for help")) { - addRow(NetworkItem::escapeHTML(tr("Help status"), true), - NetworkItem::escapeHTML(tr("Available for help")), - true); - } else { + if (_ircUser->suserHost().endsWith("available for help")) { + addRow(NetworkItem::escapeHTML(tr("Help status"), true), NetworkItem::escapeHTML(tr("Available for help")), true); + } + else { addRow(NetworkItem::escapeHTML(tr("Service status"), true), NetworkItem::escapeHTML(_ircUser->suserHost()), !_ircUser->suserHost().isEmpty()); @@ -627,7 +585,7 @@ QString QueryBufferItem::toolTip(int column) const // Keep track of whether or not the account information's been added. Don't show it twice. bool accountAdded = false; - if(!_ircUser->account().isEmpty()) { + if (!_ircUser->account().isEmpty()) { // IRCv3 account-notify is supported by the core and IRC server. // Assume logged out (seems to be more common) QString accountHTML = QString("

%1

").arg(tr("Not logged in")); @@ -636,22 +594,19 @@ QString QueryBufferItem::toolTip(int column) const if (_ircUser->account() != "*") { accountHTML = NetworkItem::escapeHTML(_ircUser->account()); } - addRow(NetworkItem::escapeHTML(tr("Account"), true), - accountHTML, - true); + addRow(NetworkItem::escapeHTML(tr("Account"), true), accountHTML, true); // Mark the row as added accountAdded = true; } // whoisServiceReply may return " is identified for this nick", which should be translated. // See https://www.alien.net.au/irc/irc2numerics.html - if(_ircUser->whoisServiceReply().endsWith("identified for this nick")) { - addRow(NetworkItem::escapeHTML(tr("Account"), true), - NetworkItem::escapeHTML(tr("Identified for this nick")), - !accountAdded); + if (_ircUser->whoisServiceReply().endsWith("identified for this nick")) { + addRow(NetworkItem::escapeHTML(tr("Account"), true), NetworkItem::escapeHTML(tr("Identified for this nick")), !accountAdded); // Don't add the account row again if information's already added via account-notify // Not used further down... // accountAdded = true; - } else { + } + else { addRow(NetworkItem::escapeHTML(tr("Service Reply"), true), NetworkItem::escapeHTML(_ircUser->whoisServiceReply()), !_ircUser->whoisServiceReply().isEmpty()); @@ -687,8 +642,7 @@ QString QueryBufferItem::toolTip(int column) const return strTooltip; } - -void QueryBufferItem::setIrcUser(IrcUser *ircUser) +void QueryBufferItem::setIrcUser(IrcUser* ircUser) { if (_ircUser == ircUser) return; @@ -708,7 +662,6 @@ void QueryBufferItem::setIrcUser(IrcUser *ircUser) emit dataChanged(); } - void QueryBufferItem::removeIrcUser() { if (_ircUser) { @@ -729,34 +682,31 @@ void QueryBufferItem::removeIrcUser() } } - /***************************************** -* ChannelBufferItem -*****************************************/ -ChannelBufferItem::ChannelBufferItem(const BufferInfo &bufferInfo, AbstractTreeItem *parent) - : BufferItem(bufferInfo, parent), - _ircChannel(nullptr) + * ChannelBufferItem + *****************************************/ +ChannelBufferItem::ChannelBufferItem(const BufferInfo& bufferInfo, AbstractTreeItem* parent) + : BufferItem(bufferInfo, parent) + , _ircChannel(nullptr) { setFlags(flags() | Qt::ItemIsDropEnabled); } - QVariant ChannelBufferItem::data(int column, int role) const { switch (role) { case NetworkModel::IrcChannelRole: - return QVariant::fromValue(_ircChannel); + return QVariant::fromValue(_ircChannel); default: return BufferItem::data(column, role); } } - QString ChannelBufferItem::toolTip(int column) const { Q_UNUSED(column); QString strTooltip; - QTextStream tooltip( &strTooltip, QIODevice::WriteOnly ); + QTextStream tooltip(&strTooltip, QIODevice::WriteOnly); tooltip << ""; // Function to add a row to the tooltip table @@ -774,7 +724,7 @@ QString ChannelBufferItem::toolTip(int column) const addRow(tr("Users"), QString::number(nickCount()), true); if (_ircChannel) { - QString channelMode = _ircChannel->channelModeString(); // channelModeString is compiled on the fly -> thus cache the result + QString channelMode = _ircChannel->channelModeString(); // channelModeString is compiled on the fly -> thus cache the result if (!channelMode.isEmpty()) addRow(tr("Mode"), channelMode, true); } @@ -791,7 +741,8 @@ QString ChannelBufferItem::toolTip(int column) const } tooltip << ""; - } else { + } + else { tooltip << "

" << tr("Not active, double-click to join") << "

"; } @@ -799,8 +750,7 @@ QString ChannelBufferItem::toolTip(int column) const return strTooltip; } - -void ChannelBufferItem::attachIrcChannel(IrcChannel *ircChannel) +void ChannelBufferItem::attachIrcChannel(IrcChannel* ircChannel) { if (_ircChannel) { qWarning() << Q_FUNC_INFO << "IrcChannel already set; cleanup failed!?"; @@ -825,7 +775,7 @@ void ChannelBufferItem::attachIrcChannel(IrcChannel *ircChannel) emit dataChanged(); } -QString ChannelBufferItem::nickChannelModes(const QString &nick) const +QString ChannelBufferItem::nickChannelModes(const QString& nick) const { if (!_ircChannel) { qDebug() << Q_FUNC_INFO << "IrcChannel not set, can't get user modes"; @@ -835,7 +785,6 @@ QString ChannelBufferItem::nickChannelModes(const QString &nick) const return _ircChannel->userModes(nick); } - void ChannelBufferItem::ircChannelParted() { Q_CHECK_PTR(_ircChannel); @@ -845,7 +794,6 @@ void ChannelBufferItem::ircChannelParted() removeAllChilds(); } - void ChannelBufferItem::ircChannelDestroyed() { if (_ircChannel) { @@ -855,20 +803,18 @@ void ChannelBufferItem::ircChannelDestroyed() } } - -void ChannelBufferItem::join(const QList &ircUsers) +void ChannelBufferItem::join(const QList& ircUsers) { addUsersToCategory(ircUsers); emit dataChanged(2); } - -UserCategoryItem *ChannelBufferItem::findCategoryItem(int categoryId) +UserCategoryItem* ChannelBufferItem::findCategoryItem(int categoryId) { - UserCategoryItem *categoryItem = nullptr; + UserCategoryItem* categoryItem = nullptr; for (int i = 0; i < childCount(); i++) { - categoryItem = qobject_cast(child(i)); + categoryItem = qobject_cast(child(i)); if (!categoryItem) continue; if (categoryItem->categoryId() == categoryId) @@ -877,42 +823,39 @@ UserCategoryItem *ChannelBufferItem::findCategoryItem(int categoryId) return nullptr; } - -void ChannelBufferItem::addUserToCategory(IrcUser *ircUser) +void ChannelBufferItem::addUserToCategory(IrcUser* ircUser) { - addUsersToCategory(QList() << ircUser); + addUsersToCategory(QList() << ircUser); } - -void ChannelBufferItem::addUsersToCategory(const QList &ircUsers) +void ChannelBufferItem::addUsersToCategory(const QList& ircUsers) { Q_ASSERT(_ircChannel); - QHash > categories; + QHash> categories; int categoryId = -1; - UserCategoryItem *categoryItem = nullptr; + UserCategoryItem* categoryItem = nullptr; - foreach(IrcUser *ircUser, ircUsers) { + foreach (IrcUser* ircUser, ircUsers) { categoryId = UserCategoryItem::categoryFromModes(_ircChannel->userModes(ircUser)); categoryItem = findCategoryItem(categoryId); if (!categoryItem) { categoryItem = new UserCategoryItem(categoryId, this); - categories[categoryItem] = QList(); + categories[categoryItem] = QList(); newChild(categoryItem); } categories[categoryItem] << ircUser; } - QHash >::const_iterator catIter = categories.constBegin(); + QHash>::const_iterator catIter = categories.constBegin(); while (catIter != categories.constEnd()) { catIter.key()->addUsers(catIter.value()); ++catIter; } } - -void ChannelBufferItem::part(IrcUser *ircUser) +void ChannelBufferItem::part(IrcUser* ircUser) { if (!ircUser) { qWarning() << bufferName() << "ChannelBufferItem::part(): unknown User" << ircUser; @@ -924,8 +867,7 @@ void ChannelBufferItem::part(IrcUser *ircUser) emit dataChanged(2); } - -void ChannelBufferItem::removeUserFromCategory(IrcUser *ircUser) +void ChannelBufferItem::removeUserFromCategory(IrcUser* ircUser) { if (!_ircChannel) { // If we parted the channel there might still be some ircUsers connected. @@ -934,9 +876,9 @@ void ChannelBufferItem::removeUserFromCategory(IrcUser *ircUser) return; } - UserCategoryItem *categoryItem = nullptr; + UserCategoryItem* categoryItem = nullptr; for (int i = 0; i < childCount(); i++) { - categoryItem = qobject_cast(child(i)); + categoryItem = qobject_cast(child(i)); if (categoryItem->removeUser(ircUser)) { if (categoryItem->childCount() == 0) removeChild(i); @@ -945,17 +887,16 @@ void ChannelBufferItem::removeUserFromCategory(IrcUser *ircUser) } } - -void ChannelBufferItem::userModeChanged(IrcUser *ircUser) +void ChannelBufferItem::userModeChanged(IrcUser* ircUser) { Q_ASSERT(_ircChannel); int categoryId = UserCategoryItem::categoryFromModes(_ircChannel->userModes(ircUser)); - UserCategoryItem *categoryItem = findCategoryItem(categoryId); + UserCategoryItem* categoryItem = findCategoryItem(categoryId); if (categoryItem) { if (categoryItem->findIrcUser(ircUser)) { - return; // already in the right category; + return; // already in the right category; } } else { @@ -964,11 +905,11 @@ void ChannelBufferItem::userModeChanged(IrcUser *ircUser) } // find the item that needs reparenting - IrcUserItem *ircUserItem = nullptr; + IrcUserItem* ircUserItem = nullptr; for (int i = 0; i < childCount(); i++) { - auto *oldCategoryItem = qobject_cast(child(i)); + auto* oldCategoryItem = qobject_cast(child(i)); Q_ASSERT(oldCategoryItem); - IrcUserItem *userItem = oldCategoryItem->findIrcUser(ircUser); + IrcUserItem* userItem = oldCategoryItem->findIrcUser(ircUser); if (userItem) { ircUserItem = userItem; break; @@ -982,31 +923,28 @@ void ChannelBufferItem::userModeChanged(IrcUser *ircUser) ircUserItem->reParent(categoryItem); } - /***************************************** -* User Category Items (like @vh etc.) -*****************************************/ + * User Category Items (like @vh etc.) + *****************************************/ // we hardcode this even though we have PREFIX in network... but that wouldn't help with mapping modes to // category strings anyway. const QList UserCategoryItem::categories = QList() << 'q' << 'a' << 'o' << 'h' << 'v'; -UserCategoryItem::UserCategoryItem(int category, AbstractTreeItem *parent) - : PropertyMapItem(parent), - _category(category) +UserCategoryItem::UserCategoryItem(int category, AbstractTreeItem* parent) + : PropertyMapItem(parent) + , _category(category) { setFlags(Qt::ItemIsEnabled); setTreeItemFlags(AbstractTreeItem::DeleteOnLastChildRemoved); setObjectName(parent->data(0, Qt::DisplayRole).toString() + "/" + QString::number(category)); } - QStringList UserCategoryItem::propertyOrder() const { static QStringList order{"categoryName"}; return order; } - // caching this makes no sense, since we display the user number dynamically QString UserCategoryItem::categoryName() const { @@ -1027,13 +965,12 @@ QString UserCategoryItem::categoryName() const } } - -IrcUserItem *UserCategoryItem::findIrcUser(IrcUser *ircUser) +IrcUserItem* UserCategoryItem::findIrcUser(IrcUser* ircUser) { - IrcUserItem *userItem = nullptr; + IrcUserItem* userItem = nullptr; for (int i = 0; i < childCount(); i++) { - userItem = qobject_cast(child(i)); + userItem = qobject_cast(child(i)); if (!userItem) continue; if (userItem->ircUser() == ircUser) @@ -1042,20 +979,18 @@ IrcUserItem *UserCategoryItem::findIrcUser(IrcUser *ircUser) return nullptr; } - -void UserCategoryItem::addUsers(const QList &ircUsers) +void UserCategoryItem::addUsers(const QList& ircUsers) { - QList userItems; - foreach(IrcUser *ircUser, ircUsers) - userItems << new IrcUserItem(ircUser, this); + QList userItems; + foreach (IrcUser* ircUser, ircUsers) + userItems << new IrcUserItem(ircUser, this); newChilds(userItems); emit dataChanged(0); } - -bool UserCategoryItem::removeUser(IrcUser *ircUser) +bool UserCategoryItem::removeUser(IrcUser* ircUser) { - IrcUserItem *userItem = findIrcUser(ircUser); + IrcUserItem* userItem = findIrcUser(ircUser); auto success = (bool)userItem; if (success) { removeChild(userItem); @@ -1064,8 +999,7 @@ bool UserCategoryItem::removeUser(IrcUser *ircUser) return success; } - -int UserCategoryItem::categoryFromModes(const QString &modes) +int UserCategoryItem::categoryFromModes(const QString& modes) { for (int i = 0; i < categories.count(); i++) { if (modes.contains(categories[i])) @@ -1074,7 +1008,6 @@ int UserCategoryItem::categoryFromModes(const QString &modes) return categories.count(); } - QVariant UserCategoryItem::data(int column, int role) const { switch (role) { @@ -1095,13 +1028,12 @@ QVariant UserCategoryItem::data(int column, int role) const } } - /***************************************** -* Irc User Items -*****************************************/ -IrcUserItem::IrcUserItem(IrcUser *ircUser, AbstractTreeItem *parent) - : PropertyMapItem(parent), - _ircUser(ircUser) + * Irc User Items + *****************************************/ +IrcUserItem::IrcUserItem(IrcUser* ircUser, AbstractTreeItem* parent) + : PropertyMapItem(parent) + , _ircUser(ircUser) { setObjectName(ircUser->nick()); connect(ircUser, &IrcUser::quited, this, &IrcUserItem::ircUserQuited); @@ -1109,14 +1041,12 @@ IrcUserItem::IrcUserItem(IrcUser *ircUser, AbstractTreeItem *parent) connect(ircUser, &IrcUser::awaySet, this, [this]() { emit dataChanged(); }); } - QStringList IrcUserItem::propertyOrder() const { static QStringList order{"nickName"}; return order; } - QVariant IrcUserItem::data(int column, int role) const { switch (role) { @@ -1133,7 +1063,7 @@ QVariant IrcUserItem::data(int column, int role) const case NetworkModel::IrcChannelRole: return parent()->data(column, role); case NetworkModel::IrcUserRole: - return QVariant::fromValue(_ircUser.data()); + return QVariant::fromValue(_ircUser.data()); case NetworkModel::UserAwayRole: return (bool)_ircUser ? _ircUser->isAway() : false; default: @@ -1141,12 +1071,11 @@ QVariant IrcUserItem::data(int column, int role) const } } - QString IrcUserItem::toolTip(int column) const { Q_UNUSED(column); QString strTooltip; - QTextStream tooltip( &strTooltip, QIODevice::WriteOnly ); + QTextStream tooltip(&strTooltip, QIODevice::WriteOnly); tooltip << ""; // Keep track of whether or not information has been added @@ -1155,23 +1084,20 @@ QString IrcUserItem::toolTip(int column) const // Use bufferName() for QueryBufferItem, nickName() for IrcUserItem tooltip << "

" << NetworkItem::escapeHTML(nickName(), true); if (_ircUser->userModes() != "") { - //TODO: Translate user Modes and add them to the table below and in QueryBufferItem::toolTip + // TODO: Translate user Modes and add them to the table below and in QueryBufferItem::toolTip tooltip << " (" << _ircUser->userModes() << ")"; } tooltip << "

"; auto addRow = [&](const QString& key, const QString& value, bool condition) { - if (condition) - { + if (condition) { tooltip << "" << key << "" << value << ""; infoAdded = true; } }; tooltip << ""; - addRow(tr("Modes"), - NetworkItem::escapeHTML(channelModes()), - !channelModes().isEmpty()); + addRow(tr("Modes"), NetworkItem::escapeHTML(channelModes()), !channelModes().isEmpty()); if (_ircUser->isAway()) { QString awayMessageHTML = QString("

%1

").arg(tr("Unknown")); @@ -1181,17 +1107,14 @@ QString IrcUserItem::toolTip(int column) const } addRow(NetworkItem::escapeHTML(tr("Away message"), true), awayMessageHTML, true); } - addRow(tr("Realname"), - NetworkItem::escapeHTML(_ircUser->realName()), - !_ircUser->realName().isEmpty()); + addRow(tr("Realname"), NetworkItem::escapeHTML(_ircUser->realName()), !_ircUser->realName().isEmpty()); // suserHost may return " is available for help", which should be translated. // See https://www.alien.net.au/irc/irc2numerics.html - if(_ircUser->suserHost().endsWith("available for help")) { - addRow(NetworkItem::escapeHTML(tr("Help status"), true), - NetworkItem::escapeHTML(tr("Available for help")), - true); - } else { + if (_ircUser->suserHost().endsWith("available for help")) { + addRow(NetworkItem::escapeHTML(tr("Help status"), true), NetworkItem::escapeHTML(tr("Available for help")), true); + } + else { addRow(NetworkItem::escapeHTML(tr("Service status"), true), NetworkItem::escapeHTML(_ircUser->suserHost()), !_ircUser->suserHost().isEmpty()); @@ -1199,7 +1122,7 @@ QString IrcUserItem::toolTip(int column) const // Keep track of whether or not the account information's been added. Don't show it twice. bool accountAdded = false; - if(!_ircUser->account().isEmpty()) { + if (!_ircUser->account().isEmpty()) { // IRCv3 account-notify is supported by the core and IRC server. // Assume logged out (seems to be more common) QString accountHTML = QString("

%1

").arg(tr("Not logged in")); @@ -1208,22 +1131,19 @@ QString IrcUserItem::toolTip(int column) const if (_ircUser->account() != "*") { accountHTML = NetworkItem::escapeHTML(_ircUser->account()); } - addRow(NetworkItem::escapeHTML(tr("Account"), true), - accountHTML, - true); + addRow(NetworkItem::escapeHTML(tr("Account"), true), accountHTML, true); // Mark the row as added accountAdded = true; } // whoisServiceReply may return " is identified for this nick", which should be translated. // See https://www.alien.net.au/irc/irc2numerics.html - if(_ircUser->whoisServiceReply().endsWith("identified for this nick")) { - addRow(NetworkItem::escapeHTML(tr("Account"), true), - NetworkItem::escapeHTML(tr("Identified for this nick")), - !accountAdded); + if (_ircUser->whoisServiceReply().endsWith("identified for this nick")) { + addRow(NetworkItem::escapeHTML(tr("Account"), true), NetworkItem::escapeHTML(tr("Identified for this nick")), !accountAdded); // Don't add the account row again if information's already added via account-notify // Not used further down... // accountAdded = true; - } else { + } + else { addRow(NetworkItem::escapeHTML(tr("Service Reply"), true), NetworkItem::escapeHTML(_ircUser->whoisServiceReply()), !_ircUser->whoisServiceReply().isEmpty()); @@ -1262,22 +1182,21 @@ QString IrcUserItem::channelModes() const { // IrcUserItems are parented to UserCategoryItem, which are parented to ChannelBufferItem. // We want the channel buffer item in order to get the channel-specific user modes. - auto *category = qobject_cast(parent()); + auto* category = qobject_cast(parent()); if (!category) return QString(); - auto *channel = qobject_cast(category->parent()); + auto* channel = qobject_cast(category->parent()); if (!channel) return QString(); return channel->nickChannelModes(nickName()); } - /***************************************** * NetworkModel *****************************************/ -NetworkModel::NetworkModel(QObject *parent) +NetworkModel::NetworkModel(QObject* parent) : TreeModel(NetworkModel::defaultHeader(), parent) { connect(this, &NetworkModel::rowsInserted, this, &NetworkModel::checkForNewBuffers); @@ -1290,7 +1209,6 @@ NetworkModel::NetworkModel(QObject *parent) messageRedirectionSettingsChanged(); } - QList NetworkModel::defaultHeader() { QList data; @@ -1298,18 +1216,16 @@ QList NetworkModel::defaultHeader() return data; } - -bool NetworkModel::isBufferIndex(const QModelIndex &index) const +bool NetworkModel::isBufferIndex(const QModelIndex& index) const { return index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType; } - int NetworkModel::networkRow(NetworkId networkId) const { - NetworkItem *netItem = nullptr; + NetworkItem* netItem = nullptr; for (int i = 0; i < rootItem->childCount(); i++) { - netItem = qobject_cast(rootItem->child(i)); + netItem = qobject_cast(rootItem->child(i)); if (!netItem) continue; if (netItem->networkId() == networkId) @@ -1318,30 +1234,27 @@ int NetworkModel::networkRow(NetworkId networkId) const return -1; } - QModelIndex NetworkModel::networkIndex(NetworkId networkId) { int netRow = networkRow(networkId); if (netRow == -1) return {}; else - return indexByItem(qobject_cast(rootItem->child(netRow))); + return indexByItem(qobject_cast(rootItem->child(netRow))); } - -NetworkItem *NetworkModel::findNetworkItem(NetworkId networkId) const +NetworkItem* NetworkModel::findNetworkItem(NetworkId networkId) const { int netRow = networkRow(networkId); if (netRow == -1) return nullptr; else - return qobject_cast(rootItem->child(netRow)); + return qobject_cast(rootItem->child(netRow)); } - -NetworkItem *NetworkModel::networkItem(NetworkId networkId) +NetworkItem* NetworkModel::networkItem(NetworkId networkId) { - NetworkItem *netItem = findNetworkItem(networkId); + NetworkItem* netItem = findNetworkItem(networkId); if (netItem == nullptr) { netItem = new NetworkItem(networkId, rootItem); @@ -1350,8 +1263,7 @@ NetworkItem *NetworkModel::networkItem(NetworkId networkId) return netItem; } - -void NetworkModel::networkRemoved(const NetworkId &networkId) +void NetworkModel::networkRemoved(const NetworkId& networkId) { int netRow = networkRow(networkId); if (netRow != -1) { @@ -1359,7 +1271,6 @@ void NetworkModel::networkRemoved(const NetworkId &networkId) } } - QModelIndex NetworkModel::bufferIndex(BufferId bufferId) { if (!_bufferItemCache.contains(bufferId)) @@ -1368,8 +1279,7 @@ QModelIndex NetworkModel::bufferIndex(BufferId bufferId) return indexByItem(_bufferItemCache[bufferId]); } - -BufferItem *NetworkModel::findBufferItem(BufferId bufferId) const +BufferItem* NetworkModel::findBufferItem(BufferId bufferId) const { if (_bufferItemCache.contains(bufferId)) return _bufferItemCache[bufferId]; @@ -1377,17 +1287,15 @@ BufferItem *NetworkModel::findBufferItem(BufferId bufferId) const return nullptr; } - -BufferItem *NetworkModel::bufferItem(const BufferInfo &bufferInfo) +BufferItem* NetworkModel::bufferItem(const BufferInfo& bufferInfo) { if (_bufferItemCache.contains(bufferInfo.bufferId())) return _bufferItemCache[bufferInfo.bufferId()]; - NetworkItem *netItem = networkItem(bufferInfo.networkId()); + NetworkItem* netItem = networkItem(bufferInfo.networkId()); return netItem->bufferItem(bufferInfo); } - QStringList NetworkModel::mimeTypes() const { // mimetypes we accept for drops @@ -1398,16 +1306,14 @@ QStringList NetworkModel::mimeTypes() const return types; } - -bool NetworkModel::mimeContainsBufferList(const QMimeData *mimeData) +bool NetworkModel::mimeContainsBufferList(const QMimeData* mimeData) { return mimeData->hasFormat("application/Quassel/BufferItemList"); } - -QList > NetworkModel::mimeDataToBufferList(const QMimeData *mimeData) +QList> NetworkModel::mimeDataToBufferList(const QMimeData* mimeData) { - QList > bufferList; + QList> bufferList; if (!mimeContainsBufferList(mimeData)) return bufferList; @@ -1415,7 +1321,7 @@ QList > NetworkModel::mimeDataToBufferList(const QMim QStringList rawBufferList = QString::fromLatin1(mimeData->data("application/Quassel/BufferItemList")).split(","); NetworkId networkId; BufferId bufferUid; - foreach(QString rawBuffer, rawBufferList) { + foreach (QString rawBuffer, rawBufferList) { if (!rawBuffer.contains(":")) continue; networkId = rawBuffer.section(":", 0, 0).toInt(); @@ -1425,14 +1331,13 @@ QList > NetworkModel::mimeDataToBufferList(const QMim return bufferList; } - -QMimeData *NetworkModel::mimeData(const QModelIndexList &indexes) const +QMimeData* NetworkModel::mimeData(const QModelIndexList& indexes) const { - auto *mimeData = new QMimeData(); + auto* mimeData = new QMimeData(); QStringList bufferlist; QString netid, uid, bufferid; - foreach(QModelIndex index, indexes) { + foreach (QModelIndex index, indexes) { netid = QString::number(index.data(NetworkIdRole).value().toInt()); uid = QString::number(index.data(BufferIdRole).value().toInt()); bufferid = QString("%1:%2").arg(netid).arg(uid); @@ -1445,32 +1350,28 @@ QMimeData *NetworkModel::mimeData(const QModelIndexList &indexes) const return mimeData; } - -void NetworkModel::attachNetwork(Network *net) +void NetworkModel::attachNetwork(Network* net) { - NetworkItem *netItem = networkItem(net->networkId()); + NetworkItem* netItem = networkItem(net->networkId()); netItem->attachNetwork(net); } - void NetworkModel::bufferUpdated(BufferInfo bufferInfo) { - BufferItem *bufItem = bufferItem(bufferInfo); + BufferItem* bufItem = bufferItem(bufferInfo); QModelIndex itemindex = indexByItem(bufItem); emit dataChanged(itemindex, itemindex); } - void NetworkModel::removeBuffer(BufferId bufferId) { - BufferItem *buffItem = findBufferItem(bufferId); + BufferItem* buffItem = findBufferItem(bufferId); if (!buffItem) return; buffItem->parent()->removeChild(buffItem); } - MsgId NetworkModel::lastSeenMsgId(BufferId bufferId) const { if (!_bufferItemCache.contains(bufferId)) @@ -1479,7 +1380,6 @@ MsgId NetworkModel::lastSeenMsgId(BufferId bufferId) const return _bufferItemCache[bufferId]->lastSeenMsgId(); } - MsgId NetworkModel::markerLineMsgId(BufferId bufferId) const { if (!_bufferItemCache.contains(bufferId)) @@ -1488,11 +1388,10 @@ MsgId NetworkModel::markerLineMsgId(BufferId bufferId) const return _bufferItemCache[bufferId]->markerLineMsgId(); } - // FIXME we always seem to use this (expensive) non-const version -MsgId NetworkModel::lastSeenMsgId(const BufferId &bufferId) +MsgId NetworkModel::lastSeenMsgId(const BufferId& bufferId) { - BufferItem *bufferItem = findBufferItem(bufferId); + BufferItem* bufferItem = findBufferItem(bufferId); if (!bufferItem) { qDebug() << "NetworkModel::lastSeenMsgId(): buffer is unknown:" << bufferId; Client::purgeKnownBufferIds(); @@ -1501,10 +1400,9 @@ MsgId NetworkModel::lastSeenMsgId(const BufferId &bufferId) return bufferItem->lastSeenMsgId(); } - -void NetworkModel::setLastSeenMsgId(const BufferId &bufferId, const MsgId &msgId) +void NetworkModel::setLastSeenMsgId(const BufferId& bufferId, const MsgId& msgId) { - BufferItem *bufferItem = findBufferItem(bufferId); + BufferItem* bufferItem = findBufferItem(bufferId); if (!bufferItem) { qDebug() << "NetworkModel::setLastSeenMsgId(): buffer is unknown:" << bufferId; Client::purgeKnownBufferIds(); @@ -1514,10 +1412,9 @@ void NetworkModel::setLastSeenMsgId(const BufferId &bufferId, const MsgId &msgId emit lastSeenMsgSet(bufferId, msgId); } - -void NetworkModel::setMarkerLineMsgId(const BufferId &bufferId, const MsgId &msgId) +void NetworkModel::setMarkerLineMsgId(const BufferId& bufferId, const MsgId& msgId) { - BufferItem *bufferItem = findBufferItem(bufferId); + BufferItem* bufferItem = findBufferItem(bufferId); if (!bufferItem) { qDebug() << "NetworkModel::setMarkerLineMsgId(): buffer is unknown:" << bufferId; Client::purgeKnownBufferIds(); @@ -1527,8 +1424,7 @@ void NetworkModel::setMarkerLineMsgId(const BufferId &bufferId, const MsgId &msg emit markerLineSet(bufferId, msgId); } - -void NetworkModel::updateBufferActivity(Message &msg) +void NetworkModel::updateBufferActivity(Message& msg) { int redirectionTarget = 0; switch (msg.type()) { @@ -1552,8 +1448,8 @@ void NetworkModel::updateBufferActivity(Message &msg) case Message::Plain: case Message::Action: if (bufferType(msg.bufferId()) == BufferInfo::ChannelBuffer) { - const Network *net = Client::network(msg.bufferInfo().networkId()); - IrcUser *user = net ? net->ircUser(nickFromMask(msg.sender())) : nullptr; + const Network* net = Client::network(msg.bufferInfo().networkId()); + IrcUser* user = net ? net->ircUser(nickFromMask(msg.sender())) : nullptr; if (user) user->setLastChannelActivity(msg.bufferId(), msg.timestamp()); } @@ -1567,7 +1463,7 @@ void NetworkModel::updateBufferActivity(Message &msg) updateBufferActivity(bufferItem(msg.bufferInfo()), msg); if (redirectionTarget & BufferSettings::StatusBuffer) { - const NetworkItem *netItem = findNetworkItem(msg.bufferInfo().networkId()); + const NetworkItem* netItem = findNetworkItem(msg.bufferInfo().networkId()); if (netItem) { updateBufferActivity(netItem->statusBufferItem(), msg); } @@ -1579,8 +1475,7 @@ void NetworkModel::updateBufferActivity(Message &msg) } } - -void NetworkModel::updateBufferActivity(BufferItem *bufferItem, const Message &msg) +void NetworkModel::updateBufferActivity(BufferItem* bufferItem, const Message& msg) { if (!bufferItem) return; @@ -1590,10 +1485,9 @@ void NetworkModel::updateBufferActivity(BufferItem *bufferItem, const Message &m emit requestSetLastSeenMsg(bufferItem->bufferId(), msg.msgId()); } - -void NetworkModel::setBufferActivity(const BufferId &bufferId, BufferInfo::ActivityLevel level) +void NetworkModel::setBufferActivity(const BufferId& bufferId, BufferInfo::ActivityLevel level) { - BufferItem *bufferItem = findBufferItem(bufferId); + BufferItem* bufferItem = findBufferItem(bufferId); if (!bufferItem) { qDebug() << "NetworkModel::setBufferActivity(): buffer is unknown:" << bufferId; return; @@ -1601,10 +1495,9 @@ void NetworkModel::setBufferActivity(const BufferId &bufferId, BufferInfo::Activ bufferItem->setActivityLevel(level); } - -void NetworkModel::clearBufferActivity(const BufferId &bufferId) +void NetworkModel::clearBufferActivity(const BufferId& bufferId) { - BufferItem *bufferItem = findBufferItem(bufferId); + BufferItem* bufferItem = findBufferItem(bufferId); if (!bufferItem) { qDebug() << "NetworkModel::clearBufferActivity(): buffer is unknown:" << bufferId; return; @@ -1612,8 +1505,7 @@ void NetworkModel::clearBufferActivity(const BufferId &bufferId) bufferItem->clearActivityLevel(); } - -const Network *NetworkModel::networkByIndex(const QModelIndex &index) const +const Network* NetworkModel::networkByIndex(const QModelIndex& index) const { QVariant netVariant = index.data(NetworkIdRole); if (!netVariant.isValid()) @@ -1623,8 +1515,7 @@ const Network *NetworkModel::networkByIndex(const QModelIndex &index) const return Client::network(networkId); } - -void NetworkModel::checkForRemovedBuffers(const QModelIndex &parent, int start, int end) +void NetworkModel::checkForRemovedBuffers(const QModelIndex& parent, int start, int end) { if (parent.data(ItemTypeRole) != NetworkItemType) return; @@ -1634,19 +1525,17 @@ void NetworkModel::checkForRemovedBuffers(const QModelIndex &parent, int start, } } - -void NetworkModel::checkForNewBuffers(const QModelIndex &parent, int start, int end) +void NetworkModel::checkForNewBuffers(const QModelIndex& parent, int start, int end) { if (parent.data(ItemTypeRole) != NetworkItemType) return; for (int row = start; row <= end; row++) { QModelIndex child = parent.child(row, 0); - _bufferItemCache[child.data(BufferIdRole).value < BufferId > ()] = static_cast(child.internalPointer()); + _bufferItemCache[child.data(BufferIdRole).value()] = static_cast(child.internalPointer()); } } - QString NetworkModel::bufferName(BufferId bufferId) const { if (!_bufferItemCache.contains(bufferId)) @@ -1655,7 +1544,6 @@ QString NetworkModel::bufferName(BufferId bufferId) const return _bufferItemCache[bufferId]->bufferName(); } - BufferInfo::Type NetworkModel::bufferType(BufferId bufferId) const { if (!_bufferItemCache.contains(bufferId)) @@ -1664,7 +1552,6 @@ BufferInfo::Type NetworkModel::bufferType(BufferId bufferId) const return _bufferItemCache[bufferId]->bufferType(); } - BufferInfo NetworkModel::bufferInfo(BufferId bufferId) const { if (!_bufferItemCache.contains(bufferId)) @@ -1673,52 +1560,48 @@ BufferInfo NetworkModel::bufferInfo(BufferId bufferId) const return _bufferItemCache[bufferId]->bufferInfo(); } - NetworkId NetworkModel::networkId(BufferId bufferId) const { if (!_bufferItemCache.contains(bufferId)) return {}; - auto *netItem = qobject_cast(_bufferItemCache[bufferId]->parent()); + auto* netItem = qobject_cast(_bufferItemCache[bufferId]->parent()); if (netItem) return netItem->networkId(); else return {}; } - QString NetworkModel::networkName(BufferId bufferId) const { if (!_bufferItemCache.contains(bufferId)) return QString(); - auto *netItem = qobject_cast(_bufferItemCache[bufferId]->parent()); + auto* netItem = qobject_cast(_bufferItemCache[bufferId]->parent()); if (netItem) return netItem->networkName(); else return QString(); } - -BufferId NetworkModel::bufferId(NetworkId networkId, const QString &bufferName, Qt::CaseSensitivity cs) const +BufferId NetworkModel::bufferId(NetworkId networkId, const QString& bufferName, Qt::CaseSensitivity cs) const { - const NetworkItem *netItem = findNetworkItem(networkId); + const NetworkItem* netItem = findNetworkItem(networkId); if (!netItem) return {}; for (int i = 0; i < netItem->childCount(); i++) { - auto *bufferItem = qobject_cast(netItem->child(i)); + auto* bufferItem = qobject_cast(netItem->child(i)); if (bufferItem && !bufferItem->bufferName().compare(bufferName, cs)) return bufferItem->bufferId(); } return {}; } - -void NetworkModel::sortBufferIds(QList &bufferIds) const +void NetworkModel::sortBufferIds(QList& bufferIds) const { - QList bufferItems; - foreach(BufferId bufferId, bufferIds) { + QList bufferItems; + foreach (BufferId bufferId, bufferIds) { if (_bufferItemCache.contains(bufferId)) bufferItems << _bufferItemCache[bufferId]; } @@ -1726,12 +1609,11 @@ void NetworkModel::sortBufferIds(QList &bufferIds) const qSort(bufferItems.begin(), bufferItems.end(), bufferItemLessThan); bufferIds.clear(); - foreach(BufferItem *bufferItem, bufferItems) { + foreach (BufferItem* bufferItem, bufferItems) { bufferIds << bufferItem->bufferId(); } } - QList NetworkModel::allBufferIdsSorted() const { QList bufferIds = allBufferIds(); @@ -1739,8 +1621,7 @@ QList NetworkModel::allBufferIdsSorted() const return bufferIds; } - -bool NetworkModel::bufferItemLessThan(const BufferItem *left, const BufferItem *right) +bool NetworkModel::bufferItemLessThan(const BufferItem* left, const BufferItem* right) { int leftType = left->bufferType(); int rightType = right->bufferType(); @@ -1751,7 +1632,6 @@ bool NetworkModel::bufferItemLessThan(const BufferItem *left, const BufferItem * return QString::compare(left->bufferName(), right->bufferName(), Qt::CaseInsensitive) < 0; } - void NetworkModel::messageRedirectionSettingsChanged() { BufferSettings bufferSettings; @@ -1761,7 +1641,8 @@ void NetworkModel::messageRedirectionSettingsChanged() _errorMsgsTarget = bufferSettings.errorMsgsTarget(); } -void NetworkModel::bufferActivityChanged(BufferId bufferId, const Message::Types activity) { +void NetworkModel::bufferActivityChanged(BufferId bufferId, const Message::Types activity) +{ auto _bufferItem = findBufferItem(bufferId); if (!_bufferItem) { qDebug() << "NetworkModel::bufferActivityChanged(): buffer is unknown:" << bufferId; @@ -1773,7 +1654,8 @@ void NetworkModel::bufferActivityChanged(BufferId bufferId, const Message::Types _bufferItem->setActivity(activityVisibleTypesIntersection, false); } -void NetworkModel::highlightCountChanged(BufferId bufferId, int count) { +void NetworkModel::highlightCountChanged(BufferId bufferId, int count) +{ auto _bufferItem = findBufferItem(bufferId); if (!_bufferItem) { qDebug() << "NetworkModel::highlightCountChanged(): buffer is unknown:" << bufferId; diff --git a/src/client/networkmodel.h b/src/client/networkmodel.h index 370e6de3..1e707a0a 100644 --- a/src/client/networkmodel.h +++ b/src/client/networkmodel.h @@ -41,8 +41,8 @@ class NetworkItem : public PropertyMapItem Q_PROPERTY(QString currentServer READ currentServer) Q_PROPERTY(int nickCount READ nickCount) -public : - NetworkItem(const NetworkId &netid, AbstractTreeItem *parent = nullptr); +public: + NetworkItem(const NetworkId& netid, AbstractTreeItem* parent = nullptr); QStringList propertyOrder() const override; @@ -59,29 +59,29 @@ public : * If true, replace spaces with non-breaking spaces (i.e. ' '), otherwise only HTML escape. * @endparblock */ - static QString escapeHTML(const QString &string, bool useNonbreakingSpaces = false); + static QString escapeHTML(const QString& string, bool useNonbreakingSpaces = false); inline bool isActive() const { return (bool)_network ? _network->isConnected() : false; } - inline const NetworkId &networkId() const { return _networkId; } + inline const NetworkId& networkId() const { return _networkId; } inline QString networkName() const { return (bool)_network ? _network->networkName() : QString(); } inline QString currentServer() const { return (bool)_network ? _network->currentServer() : QString(); } inline int nickCount() const { return (bool)_network ? _network->ircUsers().count() : 0; } QString toolTip(int column) const override; - BufferItem *findBufferItem(BufferId bufferId); - inline BufferItem *findBufferItem(const BufferInfo &bufferInfo) { return findBufferItem(bufferInfo.bufferId()); } - BufferItem *bufferItem(const BufferInfo &bufferInfo); - inline StatusBufferItem *statusBufferItem() const { return _statusBufferItem; } + BufferItem* findBufferItem(BufferId bufferId); + inline BufferItem* findBufferItem(const BufferInfo& bufferInfo) { return findBufferItem(bufferInfo.bufferId()); } + BufferItem* bufferItem(const BufferInfo& bufferInfo); + inline StatusBufferItem* statusBufferItem() const { return _statusBufferItem; } public slots: - void setNetworkName(const QString &networkName); - void setCurrentServer(const QString &serverName); + void setNetworkName(const QString& networkName); + void setCurrentServer(const QString& serverName); - void attachNetwork(Network *network); - void attachIrcChannel(IrcChannel *channel); - void attachIrcUser(IrcUser *ircUser); + void attachNetwork(Network* network); + void attachIrcChannel(IrcChannel* channel); + void attachIrcUser(IrcUser* ircUser); signals: void networkDataChanged(int column = -1); @@ -92,12 +92,11 @@ private slots: private: NetworkId _networkId; - StatusBufferItem *_statusBufferItem; + StatusBufferItem* _statusBufferItem; QPointer _network; }; - /***************************************** * Fancy Buffer Items *****************************************/ @@ -108,24 +107,24 @@ class BufferItem : public PropertyMapItem Q_PROPERTY(QString topic READ topic) Q_PROPERTY(int nickCount READ nickCount) -public : - BufferItem(BufferInfo bufferInfo, AbstractTreeItem *parent = nullptr); +public: + BufferItem(BufferInfo bufferInfo, AbstractTreeItem* parent = nullptr); QStringList propertyOrder() const override; - inline const BufferInfo &bufferInfo() const { return _bufferInfo; } + inline const BufferInfo& bufferInfo() const { return _bufferInfo; } QVariant data(int column, int role) const override; - bool setData(int column, const QVariant &value, int role) override; + bool setData(int column, const QVariant& value, int role) override; inline BufferId bufferId() const { return _bufferInfo.bufferId(); } inline BufferInfo::Type bufferType() const { return _bufferInfo.type(); } - virtual void setBufferName(const QString &name); + virtual void setBufferName(const QString& name); virtual inline QString bufferName() const { return _bufferInfo.bufferName(); } virtual inline QString topic() const { return QString(); } virtual inline int nickCount() const { return 0; } - virtual inline bool isActive() const { return qobject_cast(parent())->isActive(); } + virtual inline bool isActive() const { return qobject_cast(parent())->isActive(); } inline MsgId lastSeenMsgId() const { return _lastSeenMsgId; } inline MsgId markerLineMsgId() const { return _markerLineMsgId; } @@ -135,17 +134,17 @@ public : inline BufferInfo::ActivityLevel activityLevel() const { return _activity; } void setActivityLevel(BufferInfo::ActivityLevel level); void clearActivityLevel(); - void updateActivityLevel(const Message &msg); + void updateActivityLevel(const Message& msg); void setActivity(Message::Types msg, bool highlight); bool addActivity(Message::Types msg, bool highlight); - inline const MsgId &firstUnreadMsgId() const { return _firstUnreadMsgId; } + inline const MsgId& firstUnreadMsgId() const { return _firstUnreadMsgId; } bool isCurrentBuffer() const; QString toolTip(int column) const override; public slots: - virtual inline void setTopic(const QString &) { emit dataChanged(1); } + virtual inline void setTopic(const QString&) { emit dataChanged(1); } virtual inline void setEncrypted(bool) { emit dataChanged(); } private: @@ -156,52 +155,49 @@ private: MsgId _firstUnreadMsgId; }; - /***************************************** -* StatusBufferItem -*****************************************/ + * StatusBufferItem + *****************************************/ class StatusBufferItem : public BufferItem { Q_OBJECT public: - StatusBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent); + StatusBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent); QString toolTip(int column) const override; inline QString bufferName() const override { return tr("Status Buffer"); } }; - /***************************************** -* QueryBufferItem -*****************************************/ + * QueryBufferItem + *****************************************/ class QueryBufferItem : public BufferItem { Q_OBJECT public: - QueryBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent); + QueryBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent); QVariant data(int column, int role) const override; - bool setData(int column, const QVariant &value, int role) override; + bool setData(int column, const QVariant& value, int role) override; inline bool isActive() const override { return (bool)_ircUser; } QString toolTip(int column) const override; - void setBufferName(const QString &name) override; + void setBufferName(const QString& name) override; public slots: - void setIrcUser(IrcUser *ircUser); + void setIrcUser(IrcUser* ircUser); void removeIrcUser(); private: - IrcUser *_ircUser; + IrcUser* _ircUser; }; - /***************************************** -* ChannelBufferItem -*****************************************/ + * ChannelBufferItem + *****************************************/ class UserCategoryItem; class ChannelBufferItem : public BufferItem @@ -209,7 +205,7 @@ class ChannelBufferItem : public BufferItem Q_OBJECT public: - ChannelBufferItem(const BufferInfo &bufferInfo, AbstractTreeItem *parent); + ChannelBufferItem(const BufferInfo& bufferInfo, AbstractTreeItem* parent); QVariant data(int column, int role) const override; inline bool isActive() const override { return (bool)_ircChannel; } @@ -218,7 +214,7 @@ public: inline QString topic() const override { return (bool)_ircChannel ? _ircChannel->topic() : QString(); } inline int nickCount() const override { return (bool)_ircChannel ? _ircChannel->ircUsers().count() : 0; } - void attachIrcChannel(IrcChannel *ircChannel); + void attachIrcChannel(IrcChannel* ircChannel); /** * Gets the list of channel modes for a given nick. @@ -226,30 +222,29 @@ public: * @param[in] nick IrcUser nickname to check * @returns Channel modes as a string if any, otherwise empty string */ - QString nickChannelModes(const QString &nick) const; + QString nickChannelModes(const QString& nick) const; public slots: - void join(const QList &ircUsers); - void part(IrcUser *ircUser); + void join(const QList& ircUsers); + void part(IrcUser* ircUser); - UserCategoryItem *findCategoryItem(int categoryId); - void addUserToCategory(IrcUser *ircUser); - void addUsersToCategory(const QList &ircUser); - void removeUserFromCategory(IrcUser *ircUser); - void userModeChanged(IrcUser *ircUser); + UserCategoryItem* findCategoryItem(int categoryId); + void addUserToCategory(IrcUser* ircUser); + void addUsersToCategory(const QList& ircUser); + void removeUserFromCategory(IrcUser* ircUser); + void userModeChanged(IrcUser* ircUser); private slots: void ircChannelParted(); void ircChannelDestroyed(); private: - IrcChannel *_ircChannel; + IrcChannel* _ircChannel; }; - /***************************************** -* User Category Items (like @vh etc.) -*****************************************/ + * User Category Items (like @vh etc.) + *****************************************/ class IrcUserItem; class CLIENT_EXPORT UserCategoryItem : public PropertyMapItem @@ -257,8 +252,8 @@ class CLIENT_EXPORT UserCategoryItem : public PropertyMapItem Q_OBJECT Q_PROPERTY(QString categoryName READ categoryName) -public : - UserCategoryItem(int category, AbstractTreeItem *parent); +public: + UserCategoryItem(int category, AbstractTreeItem* parent); QStringList propertyOrder() const override; @@ -266,11 +261,11 @@ public : inline int categoryId() const { return _category; } QVariant data(int column, int role) const override; - IrcUserItem *findIrcUser(IrcUser *ircUser); - void addUsers(const QList &ircUser); - bool removeUser(IrcUser *ircUser); + IrcUserItem* findIrcUser(IrcUser* ircUser); + void addUsers(const QList& ircUser); + bool removeUser(IrcUser* ircUser); - static int categoryFromModes(const QString &modes); + static int categoryFromModes(const QString& modes); private: int _category; @@ -278,24 +273,23 @@ private: static const QList categories; }; - /***************************************** -* Irc User Items -*****************************************/ + * Irc User Items + *****************************************/ class IrcUserItem : public PropertyMapItem { Q_OBJECT Q_PROPERTY(QString nickName READ nickName) -public : - IrcUserItem(IrcUser *ircUser, AbstractTreeItem *parent); +public: + IrcUserItem(IrcUser* ircUser, AbstractTreeItem* parent); QStringList propertyOrder() const override; inline QString nickName() const { return _ircUser ? _ircUser->nick() : QString(); } inline bool isActive() const { return _ircUser ? !_ircUser->isAway() : false; } - inline IrcUser *ircUser() { return _ircUser; } + inline IrcUser* ircUser() { return _ircUser; } QVariant data(int column, int role) const override; QString toolTip(int column) const override; @@ -313,7 +307,6 @@ private: QPointer _ircUser; }; - /***************************************** * NetworkModel *****************************************/ @@ -322,7 +315,8 @@ class CLIENT_EXPORT NetworkModel : public TreeModel Q_OBJECT public: - enum Role { + enum Role + { BufferTypeRole = TreeModel::UserRole, ItemActiveRole, BufferActivityRole, @@ -337,7 +331,8 @@ public: MarkerLineMsgIdRole, }; - enum ItemType { + enum ItemType + { NetworkItemType = 0x01, BufferItemType = 0x02, UserCategoryItemType = 0x04, @@ -345,25 +340,25 @@ public: }; Q_DECLARE_FLAGS(ItemTypes, ItemType) - NetworkModel(QObject *parent = nullptr); + NetworkModel(QObject* parent = nullptr); static QList defaultHeader(); - static bool mimeContainsBufferList(const QMimeData *mimeData); - static QList > mimeDataToBufferList(const QMimeData *mimeData); + static bool mimeContainsBufferList(const QMimeData* mimeData); + static QList> mimeDataToBufferList(const QMimeData* mimeData); QStringList mimeTypes() const override; - QMimeData *mimeData(const QModelIndexList &) const override; + QMimeData* mimeData(const QModelIndexList&) const override; - void attachNetwork(Network *network); + void attachNetwork(Network* network); - bool isBufferIndex(const QModelIndex &) const; - //Buffer *getBufferByIndex(const QModelIndex &) const; + bool isBufferIndex(const QModelIndex&) const; + // Buffer *getBufferByIndex(const QModelIndex &) const; QModelIndex networkIndex(NetworkId networkId); QModelIndex bufferIndex(BufferId bufferId); - const Network *networkByIndex(const QModelIndex &index) const; + const Network* networkByIndex(const QModelIndex& index) const; - BufferInfo::ActivityLevel bufferActivity(const BufferInfo &buffer) const; + BufferInfo::ActivityLevel bufferActivity(const BufferInfo& buffer) const; //! Finds a buffer with a given name in a given network /** This performs a linear search through all BufferItems, hence it is expensive. @@ -371,7 +366,7 @@ public: * @param bufferName The bufferName we look for * @return The id of the buffer if found, an invalid one else */ - BufferId bufferId(NetworkId networkId, const QString &bufferName, Qt::CaseSensitivity cs = Qt::CaseInsensitive) const; + BufferId bufferId(NetworkId networkId, const QString& bufferName, Qt::CaseSensitivity cs = Qt::CaseInsensitive) const; QString bufferName(BufferId bufferId) const; BufferInfo::Type bufferType(BufferId bufferId) const; @@ -383,18 +378,18 @@ public: inline QList allBufferIds() const { return _bufferItemCache.keys(); } QList allBufferIdsSorted() const; - void sortBufferIds(QList &bufferIds) const; + void sortBufferIds(QList& bufferIds) const; public slots: void bufferUpdated(BufferInfo bufferInfo); void removeBuffer(BufferId bufferId); - MsgId lastSeenMsgId(const BufferId &bufferId); - void setLastSeenMsgId(const BufferId &bufferId, const MsgId &msgId); - void setMarkerLineMsgId(const BufferId &bufferId, const MsgId &msgId); - void setBufferActivity(const BufferId &bufferId, BufferInfo::ActivityLevel activity); - void clearBufferActivity(const BufferId &bufferId); - void updateBufferActivity(Message &msg); - void networkRemoved(const NetworkId &networkId); + MsgId lastSeenMsgId(const BufferId& bufferId); + void setLastSeenMsgId(const BufferId& bufferId, const MsgId& msgId); + void setMarkerLineMsgId(const BufferId& bufferId, const MsgId& msgId); + void setBufferActivity(const BufferId& bufferId, BufferInfo::ActivityLevel activity); + void clearBufferActivity(const BufferId& bufferId); + void updateBufferActivity(Message& msg); + void networkRemoved(const NetworkId& networkId); void bufferActivityChanged(BufferId, Message::Types); void highlightCountChanged(BufferId, int); @@ -404,28 +399,27 @@ signals: void markerLineSet(BufferId buffer, MsgId msg); private slots: - void checkForRemovedBuffers(const QModelIndex &parent, int start, int end); - void checkForNewBuffers(const QModelIndex &parent, int start, int end); + void checkForRemovedBuffers(const QModelIndex& parent, int start, int end); + void checkForNewBuffers(const QModelIndex& parent, int start, int end); void messageRedirectionSettingsChanged(); private: int networkRow(NetworkId networkId) const; - NetworkItem *findNetworkItem(NetworkId networkId) const; - NetworkItem *networkItem(NetworkId networkId); - inline BufferItem *findBufferItem(const BufferInfo &bufferInfo) const { return findBufferItem(bufferInfo.bufferId()); } - BufferItem *findBufferItem(BufferId bufferId) const; - BufferItem *bufferItem(const BufferInfo &bufferInfo); + NetworkItem* findNetworkItem(NetworkId networkId) const; + NetworkItem* networkItem(NetworkId networkId); + inline BufferItem* findBufferItem(const BufferInfo& bufferInfo) const { return findBufferItem(bufferInfo.bufferId()); } + BufferItem* findBufferItem(BufferId bufferId) const; + BufferItem* bufferItem(const BufferInfo& bufferInfo); - void updateBufferActivity(BufferItem *bufferItem, const Message &msg); + void updateBufferActivity(BufferItem* bufferItem, const Message& msg); - static bool bufferItemLessThan(const BufferItem *left, const BufferItem *right); + static bool bufferItemLessThan(const BufferItem* left, const BufferItem* right); - QHash _bufferItemCache; + QHash _bufferItemCache; int _userNoticesTarget; int _serverNoticesTarget; int _errorMsgsTarget; }; - Q_DECLARE_OPERATORS_FOR_FLAGS(NetworkModel::ItemTypes) diff --git a/src/client/selectionmodelsynchronizer.cpp b/src/client/selectionmodelsynchronizer.cpp index fc732d4a..e9c72209 100644 --- a/src/client/selectionmodelsynchronizer.cpp +++ b/src/client/selectionmodelsynchronizer.cpp @@ -22,29 +22,25 @@ #include #include - #include -SelectionModelSynchronizer::SelectionModelSynchronizer(QAbstractItemModel *parent) - : QObject(parent), - _model(parent), - _selectionModel(parent) +SelectionModelSynchronizer::SelectionModelSynchronizer(QAbstractItemModel* parent) + : QObject(parent) + , _model(parent) + , _selectionModel(parent) { - connect(&_selectionModel, &QItemSelectionModel::currentChanged, - this, &SelectionModelSynchronizer::currentChanged); - connect(&_selectionModel, &QItemSelectionModel::selectionChanged, - this, &SelectionModelSynchronizer::selectionChanged); + connect(&_selectionModel, &QItemSelectionModel::currentChanged, this, &SelectionModelSynchronizer::currentChanged); + connect(&_selectionModel, &QItemSelectionModel::selectionChanged, this, &SelectionModelSynchronizer::selectionChanged); } - -bool SelectionModelSynchronizer::checkBaseModel(QItemSelectionModel *selectionModel) +bool SelectionModelSynchronizer::checkBaseModel(QItemSelectionModel* selectionModel) { if (!selectionModel) return false; - const QAbstractItemModel *baseModel = selectionModel->model(); - const QAbstractProxyModel *proxyModel = nullptr; - while ((proxyModel = qobject_cast(baseModel)) != nullptr) { + const QAbstractItemModel* baseModel = selectionModel->model(); + const QAbstractProxyModel* proxyModel = nullptr; + while ((proxyModel = qobject_cast(baseModel)) != nullptr) { baseModel = proxyModel->sourceModel(); if (baseModel == model()) break; @@ -52,8 +48,7 @@ bool SelectionModelSynchronizer::checkBaseModel(QItemSelectionModel *selectionMo return baseModel == model(); } - -void SelectionModelSynchronizer::synchronizeSelectionModel(QItemSelectionModel *selectionModel) +void SelectionModelSynchronizer::synchronizeSelectionModel(QItemSelectionModel* selectionModel) { if (!checkBaseModel(selectionModel)) { qWarning() << "cannot Synchronize SelectionModel" << selectionModel << "which has a different baseModel()"; @@ -66,29 +61,25 @@ void SelectionModelSynchronizer::synchronizeSelectionModel(QItemSelectionModel * return; } - connect(selectionModel, &QItemSelectionModel::currentChanged, - this, &SelectionModelSynchronizer::syncedCurrentChanged); - connect(selectionModel, &QItemSelectionModel::selectionChanged, - this, &SelectionModelSynchronizer::syncedSelectionChanged); + connect(selectionModel, &QItemSelectionModel::currentChanged, this, &SelectionModelSynchronizer::syncedCurrentChanged); + connect(selectionModel, &QItemSelectionModel::selectionChanged, this, &SelectionModelSynchronizer::syncedSelectionChanged); connect(selectionModel, &QObject::destroyed, this, &SelectionModelSynchronizer::selectionModelDestroyed); _selectionModels << selectionModel; } - -void SelectionModelSynchronizer::removeSelectionModel(QItemSelectionModel *model) +void SelectionModelSynchronizer::removeSelectionModel(QItemSelectionModel* model) { disconnect(model, nullptr, this, nullptr); disconnect(this, nullptr, model, nullptr); selectionModelDestroyed(model); } - -void SelectionModelSynchronizer::selectionModelDestroyed(QObject *object) +void SelectionModelSynchronizer::selectionModelDestroyed(QObject* object) { - auto *model = static_cast(object); - QSet::iterator iter = _selectionModels.begin(); + auto* model = static_cast(object); + QSet::iterator iter = _selectionModels.begin(); while (iter != _selectionModels.end()) { if (*iter == model) { iter = _selectionModels.erase(iter); @@ -99,23 +90,21 @@ void SelectionModelSynchronizer::selectionModelDestroyed(QObject *object) } } - -void SelectionModelSynchronizer::syncedCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous) +void SelectionModelSynchronizer::syncedCurrentChanged(const QModelIndex& current, const QModelIndex& previous) { Q_UNUSED(previous); if (!_changeCurrentEnabled) return; - auto *selectionModel = qobject_cast(sender()); + auto* selectionModel = qobject_cast(sender()); Q_ASSERT(selectionModel); QModelIndex newSourceCurrent = mapToSource(current, selectionModel); if (newSourceCurrent.isValid() && newSourceCurrent != currentIndex()) setCurrentIndex(newSourceCurrent); } - -void SelectionModelSynchronizer::syncedSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) +void SelectionModelSynchronizer::syncedSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { Q_UNUSED(selected); Q_UNUSED(deselected); @@ -123,7 +112,7 @@ void SelectionModelSynchronizer::syncedSelectionChanged(const QItemSelection &se if (!_changeSelectionEnabled) return; - auto *selectionModel = qobject_cast(sender()); + auto* selectionModel = qobject_cast(sender()); Q_ASSERT(selectionModel); QItemSelection mappedSelection = selectionModel->selection(); @@ -144,18 +133,17 @@ void SelectionModelSynchronizer::syncedSelectionChanged(const QItemSelection &se setCurrentSelection(mapSelectionToSource(mappedSelection, selectionModel)); } - -QModelIndex SelectionModelSynchronizer::mapFromSource(const QModelIndex &sourceIndex, const QItemSelectionModel *selectionModel) +QModelIndex SelectionModelSynchronizer::mapFromSource(const QModelIndex& sourceIndex, const QItemSelectionModel* selectionModel) { Q_ASSERT(selectionModel); QModelIndex mappedIndex = sourceIndex; // make a list of all involved proxies, wie have to traverse backwards - QList proxyModels; - const QAbstractItemModel *baseModel = selectionModel->model(); - const QAbstractProxyModel *proxyModel = nullptr; - while ((proxyModel = qobject_cast(baseModel)) != nullptr) { + QList proxyModels; + const QAbstractItemModel* baseModel = selectionModel->model(); + const QAbstractProxyModel* proxyModel = nullptr; + while ((proxyModel = qobject_cast(baseModel)) != nullptr) { if (baseModel == model()) break; proxyModels << proxyModel; @@ -170,18 +158,18 @@ QModelIndex SelectionModelSynchronizer::mapFromSource(const QModelIndex &sourceI return mappedIndex; } - -QItemSelection SelectionModelSynchronizer::mapSelectionFromSource(const QItemSelection &sourceSelection, const QItemSelectionModel *selectionModel) +QItemSelection SelectionModelSynchronizer::mapSelectionFromSource(const QItemSelection& sourceSelection, + const QItemSelectionModel* selectionModel) { Q_ASSERT(selectionModel); QItemSelection mappedSelection = sourceSelection; // make a list of all involved proxies, wie have to traverse backwards - QList proxyModels; - const QAbstractItemModel *baseModel = selectionModel->model(); - const QAbstractProxyModel *proxyModel = nullptr; - while ((proxyModel = qobject_cast(baseModel)) != nullptr) { + QList proxyModels; + const QAbstractItemModel* baseModel = selectionModel->model(); + const QAbstractProxyModel* proxyModel = nullptr; + while ((proxyModel = qobject_cast(baseModel)) != nullptr) { if (baseModel == model()) break; proxyModels << proxyModel; @@ -195,15 +183,14 @@ QItemSelection SelectionModelSynchronizer::mapSelectionFromSource(const QItemSel return mappedSelection; } - -QModelIndex SelectionModelSynchronizer::mapToSource(const QModelIndex &index, QItemSelectionModel *selectionModel) +QModelIndex SelectionModelSynchronizer::mapToSource(const QModelIndex& index, QItemSelectionModel* selectionModel) { Q_ASSERT(selectionModel); QModelIndex sourceIndex = index; - const QAbstractItemModel *baseModel = selectionModel->model(); - const QAbstractProxyModel *proxyModel = nullptr; - while ((proxyModel = qobject_cast(baseModel)) != nullptr) { + const QAbstractItemModel* baseModel = selectionModel->model(); + const QAbstractProxyModel* proxyModel = nullptr; + while ((proxyModel = qobject_cast(baseModel)) != nullptr) { sourceIndex = proxyModel->mapToSource(sourceIndex); baseModel = proxyModel->sourceModel(); if (baseModel == model()) @@ -212,15 +199,14 @@ QModelIndex SelectionModelSynchronizer::mapToSource(const QModelIndex &index, QI return sourceIndex; } - -QItemSelection SelectionModelSynchronizer::mapSelectionToSource(const QItemSelection &selection, QItemSelectionModel *selectionModel) +QItemSelection SelectionModelSynchronizer::mapSelectionToSource(const QItemSelection& selection, QItemSelectionModel* selectionModel) { Q_ASSERT(selectionModel); QItemSelection sourceSelection = selection; - const QAbstractItemModel *baseModel = selectionModel->model(); - const QAbstractProxyModel *proxyModel = nullptr; - while ((proxyModel = qobject_cast(baseModel)) != nullptr) { + const QAbstractItemModel* baseModel = selectionModel->model(); + const QAbstractProxyModel* proxyModel = nullptr; + while ((proxyModel = qobject_cast(baseModel)) != nullptr) { sourceSelection = proxyModel->mapSelectionToSource(sourceSelection); baseModel = proxyModel->sourceModel(); if (baseModel == model()) @@ -229,25 +215,22 @@ QItemSelection SelectionModelSynchronizer::mapSelectionToSource(const QItemSelec return sourceSelection; } - -void SelectionModelSynchronizer::setCurrentIndex(const QModelIndex &index) +void SelectionModelSynchronizer::setCurrentIndex(const QModelIndex& index) { _selectionModel.setCurrentIndex(index, QItemSelectionModel::Current); } - -void SelectionModelSynchronizer::setCurrentSelection(const QItemSelection &selection) +void SelectionModelSynchronizer::setCurrentSelection(const QItemSelection& selection) { _selectionModel.select(selection, QItemSelectionModel::ClearAndSelect); } - -void SelectionModelSynchronizer::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) +void SelectionModelSynchronizer::currentChanged(const QModelIndex& current, const QModelIndex& previous) { Q_UNUSED(previous); _changeCurrentEnabled = false; - QSet::iterator iter = _selectionModels.begin(); + QSet::iterator iter = _selectionModels.begin(); while (iter != _selectionModels.end()) { (*iter)->setCurrentIndex(mapFromSource(current, (*iter)), QItemSelectionModel::Current); ++iter; @@ -257,19 +240,17 @@ void SelectionModelSynchronizer::currentChanged(const QModelIndex ¤t, cons // Trigger a dataChanged() signal from the base model to update all proxy models (e.g. filters). // Since signals are protected, we have to use invokeMethod for faking signal emission. if (previous.isValid()) { - QMetaObject::invokeMethod(model(), "dataChanged", Qt::DirectConnection, - Q_ARG(QModelIndex, previous), Q_ARG(QModelIndex, previous)); + QMetaObject::invokeMethod(model(), "dataChanged", Qt::DirectConnection, Q_ARG(QModelIndex, previous), Q_ARG(QModelIndex, previous)); } } - -void SelectionModelSynchronizer::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) +void SelectionModelSynchronizer::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { Q_UNUSED(selected); Q_UNUSED(deselected); _changeSelectionEnabled = false; - QSet::iterator iter = _selectionModels.begin(); + QSet::iterator iter = _selectionModels.begin(); while (iter != _selectionModels.end()) { (*iter)->select(mapSelectionFromSource(currentSelection(), (*iter)), QItemSelectionModel::ClearAndSelect); ++iter; diff --git a/src/client/selectionmodelsynchronizer.h b/src/client/selectionmodelsynchronizer.h index b830d31a..6bcf8dda 100644 --- a/src/client/selectionmodelsynchronizer.h +++ b/src/client/selectionmodelsynchronizer.h @@ -22,8 +22,8 @@ #include "client-export.h" -#include #include +#include class QAbstractItemModel; @@ -32,39 +32,39 @@ class CLIENT_EXPORT SelectionModelSynchronizer : public QObject Q_OBJECT public: - SelectionModelSynchronizer(QAbstractItemModel *parent = nullptr); + SelectionModelSynchronizer(QAbstractItemModel* parent = nullptr); - void synchronizeSelectionModel(QItemSelectionModel *selectionModel); - void removeSelectionModel(QItemSelectionModel *selectionModel); + void synchronizeSelectionModel(QItemSelectionModel* selectionModel); + void removeSelectionModel(QItemSelectionModel* selectionModel); - inline QAbstractItemModel *model() { return _model; } - inline QItemSelectionModel *selectionModel() const { return const_cast(&_selectionModel); } + inline QAbstractItemModel* model() { return _model; } + inline QItemSelectionModel* selectionModel() const { return const_cast(&_selectionModel); } inline QModelIndex currentIndex() const { return _selectionModel.currentIndex(); } inline QItemSelection currentSelection() const { return _selectionModel.selection(); } private slots: - void syncedCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous); - void syncedSelectionChanged(const QItemSelection &selected, const QItemSelection &previous); + void syncedCurrentChanged(const QModelIndex& current, const QModelIndex& previous); + void syncedSelectionChanged(const QItemSelection& selected, const QItemSelection& previous); - void setCurrentIndex(const QModelIndex &index); - void setCurrentSelection(const QItemSelection &selection); + void setCurrentIndex(const QModelIndex& index); + void setCurrentSelection(const QItemSelection& selection); - void currentChanged(const QModelIndex ¤t, const QModelIndex &previous); - void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); + void currentChanged(const QModelIndex& current, const QModelIndex& previous); + void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected); - void selectionModelDestroyed(QObject *object); + void selectionModelDestroyed(QObject* object); private: - QAbstractItemModel *_model; + QAbstractItemModel* _model; QItemSelectionModel _selectionModel; bool _changeCurrentEnabled{true}; bool _changeSelectionEnabled{true}; - bool checkBaseModel(QItemSelectionModel *model); - QModelIndex mapFromSource(const QModelIndex &sourceIndex, const QItemSelectionModel *selectionModel); - QItemSelection mapSelectionFromSource(const QItemSelection &sourceSelection, const QItemSelectionModel *selectionModel); - QModelIndex mapToSource(const QModelIndex &index, QItemSelectionModel *selectionModel); - QItemSelection mapSelectionToSource(const QItemSelection &selection, QItemSelectionModel *selectionModel); + bool checkBaseModel(QItemSelectionModel* model); + QModelIndex mapFromSource(const QModelIndex& sourceIndex, const QItemSelectionModel* selectionModel); + QItemSelection mapSelectionFromSource(const QItemSelection& sourceSelection, const QItemSelectionModel* selectionModel); + QModelIndex mapToSource(const QModelIndex& index, QItemSelectionModel* selectionModel); + QItemSelection mapSelectionToSource(const QItemSelection& selection, QItemSelectionModel* selectionModel); - QSet _selectionModels; + QSet _selectionModels; }; diff --git a/src/client/transfermodel.cpp b/src/client/transfermodel.cpp index a75b8c50..4a6ba1b1 100644 --- a/src/client/transfermodel.cpp +++ b/src/client/transfermodel.cpp @@ -25,27 +25,23 @@ #include "transfermanager.h" namespace { - constexpr int colCount{8}; +constexpr int colCount{8}; } - int TransferModel::rowCount(const QModelIndex& index) const { return index.isValid() ? 0 : _transferIds.size(); } - int TransferModel::columnCount(const QModelIndex& index) const { return index.isValid() ? 0 : colCount; } - QVariant TransferModel::headerData(int section, Qt::Orientation orientation, int role) const { - static std::array headers = {{ - tr("Type"), tr("File"), tr("Status"), tr("Progress"), tr("Transferred"), tr("Speed"), tr("Peer"), tr("Peer Address") - }}; + static std::array headers = { + {tr("Type"), tr("File"), tr("Status"), tr("Progress"), tr("Transferred"), tr("Speed"), tr("Peer"), tr("Peer Address")}}; if (section < 0 || section >= columnCount() || orientation != Qt::Horizontal) return {}; @@ -59,7 +55,6 @@ QVariant TransferModel::headerData(int section, Qt::Orientation orientation, int } } - QVariant TransferModel::data(const QModelIndex& index, int role) const { if (!_manager) @@ -76,21 +71,21 @@ QVariant TransferModel::data(const QModelIndex& index, int role) const switch (role) { case Qt::DisplayRole: switch (index.column()) { - case 0: // Type + case 0: // Type return t->direction() == Transfer::Direction::Send ? tr("Send") : tr("Receive"); - case 1: // File + case 1: // File return t->fileName(); - case 2: // Status + case 2: // Status return t->prettyStatus(); - case 3: // Progress + case 3: // Progress return (t->transferred() / t->fileSize()) * 100; - case 4: // Transferred - return t->transferred(); // TODO: use pretty units and show total - case 5: // Speed - return "n/a"; // TODO: fixme - case 6: // Peer + case 4: // Transferred + return t->transferred(); // TODO: use pretty units and show total + case 5: // Speed + return "n/a"; // TODO: fixme + case 6: // Peer return t->nick(); - case 7: // Peer Address + case 7: // Peer Address return QString("%1.%2").arg(t->address().toString(), t->port()); } break; @@ -102,8 +97,7 @@ QVariant TransferModel::data(const QModelIndex& index, int role) const return {}; } - -void TransferModel::setManager(const TransferManager *manager) +void TransferModel::setManager(const TransferManager* manager) { if (_manager) { disconnect(_manager, nullptr, this, nullptr); @@ -116,14 +110,13 @@ void TransferModel::setManager(const TransferManager *manager) if (_manager) { connect(manager, &TransferManager::transferAdded, this, &TransferModel::onTransferAdded); connect(manager, &TransferManager::transferRemoved, this, &TransferModel::onTransferRemoved); - for (auto &&transferId : _manager->transferIds()) { + for (auto&& transferId : _manager->transferIds()) { onTransferAdded(transferId); } } } - -void TransferModel::onTransferAdded(const QUuid &transferId) +void TransferModel::onTransferAdded(const QUuid& transferId) { auto transfer = _manager->transfer(transferId); if (!transfer) { @@ -146,8 +139,7 @@ void TransferModel::onTransferAdded(const QUuid &transferId) endInsertRows(); } - -void TransferModel::onTransferRemoved(const QUuid &transferId) +void TransferModel::onTransferRemoved(const QUuid& transferId) { // Check if the transfer object still exists, which means we still should disconnect auto transfer = _manager->transfer(transferId); @@ -164,10 +156,9 @@ void TransferModel::onTransferRemoved(const QUuid &transferId) } } - void TransferModel::onTransferDataChanged() { - auto transfer = qobject_cast(sender()); + auto transfer = qobject_cast(sender()); if (!transfer) return; diff --git a/src/client/transfermodel.h b/src/client/transfermodel.h index 42b9c9be..9211ce9a 100644 --- a/src/client/transfermodel.h +++ b/src/client/transfermodel.h @@ -22,8 +22,8 @@ #include #include -#include #include +#include #include "transfer.h" @@ -40,9 +40,9 @@ public: using QAbstractTableModel::QAbstractTableModel; // see base class docs - int rowCount(const QModelIndex &index = {}) const override; - int columnCount(const QModelIndex &index = {}) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + int rowCount(const QModelIndex& index = {}) const override; + int columnCount(const QModelIndex& index = {}) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; /** @@ -51,7 +51,7 @@ public: * @param[in] transferId Transfer ID * @returns A pointer to the transfer with the given ID, or nullptr for an unknown ID */ - Transfer *transfer(const QUuid &transferId) const; + Transfer* transfer(const QUuid& transferId) const; /** * Sets the TransferManager associated with this model. @@ -61,7 +61,7 @@ public: * * @param[in] manager Pointer to the TransferManager instance, or nullptr for clearing the model */ - void setManager(const TransferManager *manager); + void setManager(const TransferManager* manager); private slots: /** @@ -69,14 +69,14 @@ private slots: * * @param[in] transferId The transfer's ID */ - void onTransferAdded(const QUuid &transferId); + void onTransferAdded(const QUuid& transferId); /** * Slot to be called when a transfer is removed. * * @param[in] transferId The transfer's ID */ - void onTransferRemoved(const QUuid &transferId); + void onTransferRemoved(const QUuid& transferId); /** * Slot to be called when a transfer's data changes. @@ -84,6 +84,6 @@ private slots: void onTransferDataChanged(); private: - const TransferManager *_manager{nullptr}; ///< Pointer to the active TransferManager instance, if any - QVector _transferIds; ///< List of transfer IDs + const TransferManager* _manager{nullptr}; ///< Pointer to the active TransferManager instance, if any + QVector _transferIds; ///< List of transfer IDs }; diff --git a/src/client/treemodel.cpp b/src/client/treemodel.cpp index 507a5daf..ed8f12b0 100644 --- a/src/client/treemodel.cpp +++ b/src/client/treemodel.cpp @@ -20,34 +20,35 @@ #include "treemodel.h" +#include + #include #include -#include #include "quassel.h" class RemoveChildLaterEvent : public QEvent { public: - RemoveChildLaterEvent(AbstractTreeItem *child) : QEvent(QEvent::User), _child(child) {}; - inline AbstractTreeItem *child() { return _child; } + RemoveChildLaterEvent(AbstractTreeItem* child) + : QEvent(QEvent::User) + , _child(child){}; + inline AbstractTreeItem* child() { return _child; } + private: - AbstractTreeItem *_child; + AbstractTreeItem* _child; }; - /***************************************** * Abstract Items of a TreeModel *****************************************/ -AbstractTreeItem::AbstractTreeItem(AbstractTreeItem *parent) - : QObject(parent), - _flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled), - _treeItemFlags(nullptr) -{ -} +AbstractTreeItem::AbstractTreeItem(AbstractTreeItem* parent) + : QObject(parent) + , _flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled) + , _treeItemFlags(nullptr) +{} - -bool AbstractTreeItem::newChild(AbstractTreeItem *item) +bool AbstractTreeItem::newChild(AbstractTreeItem* item) { int newRow = childCount(); emit beginAppendChilds(newRow, newRow); @@ -56,8 +57,7 @@ bool AbstractTreeItem::newChild(AbstractTreeItem *item) return true; } - -bool AbstractTreeItem::newChilds(const QList &items) +bool AbstractTreeItem::newChilds(const QList& items) { if (items.isEmpty()) return false; @@ -72,7 +72,6 @@ bool AbstractTreeItem::newChilds(const QList &items) return true; } - bool AbstractTreeItem::removeChild(int row) { if (row < 0 || childCount() <= row) @@ -80,7 +79,7 @@ bool AbstractTreeItem::removeChild(int row) child(row)->removeAllChilds(); emit beginRemoveChilds(row, row); - AbstractTreeItem *treeitem = _childItems.takeAt(row); + AbstractTreeItem* treeitem = _childItems.takeAt(row); delete treeitem; emit endRemoveChilds(); @@ -89,7 +88,6 @@ bool AbstractTreeItem::removeChild(int row) return true; } - void AbstractTreeItem::removeAllChilds() { const int numChilds = childCount(); @@ -97,14 +95,14 @@ void AbstractTreeItem::removeAllChilds() if (numChilds == 0) return; - AbstractTreeItem *child; + AbstractTreeItem* child; - QList::iterator childIter; + QList::iterator childIter; childIter = _childItems.begin(); while (childIter != _childItems.end()) { child = *childIter; - child->setTreeItemFlags(nullptr); // disable self deletion, as this would only fuck up consitency and the child gets deleted anyways + child->setTreeItemFlags(nullptr); // disable self deletion, as this would only fuck up consitency and the child gets deleted anyways child->removeAllChilds(); ++childIter; } @@ -121,22 +119,20 @@ void AbstractTreeItem::removeAllChilds() checkForDeletion(); } - -void AbstractTreeItem::removeChildLater(AbstractTreeItem *child) +void AbstractTreeItem::removeChildLater(AbstractTreeItem* child) { Q_ASSERT(child); QCoreApplication::postEvent(this, new RemoveChildLaterEvent(child)); } - -void AbstractTreeItem::customEvent(QEvent *event) +void AbstractTreeItem::customEvent(QEvent* event) { if (event->type() != QEvent::User) return; event->accept(); - auto *removeEvent = static_cast(event); + auto* removeEvent = static_cast(event); int childRow = _childItems.indexOf(removeEvent->child()); if (childRow == -1) return; @@ -148,13 +144,12 @@ void AbstractTreeItem::customEvent(QEvent *event) removeChild(childRow); } - -bool AbstractTreeItem::reParent(AbstractTreeItem *newParent) +bool AbstractTreeItem::reParent(AbstractTreeItem* newParent) { // currently we support only re parenting if the child that's about to be // adopted does not have any children itself. if (childCount() != 0) { - qDebug() << "AbstractTreeItem::reParent(): cannot reparent" << this << "with children."; + qDebug() << "AbstractTreeItem::reParent(): cannot reparent" << this << "with children."; return false; } @@ -166,12 +161,13 @@ bool AbstractTreeItem::reParent(AbstractTreeItem *newParent) parent()->_childItems.removeAt(oldRow); emit parent()->endRemoveChilds(); - AbstractTreeItem *oldParent = parent(); + AbstractTreeItem* oldParent = parent(); setParent(newParent); bool success = newParent->newChild(this); if (!success) - qWarning() << "AbstractTreeItem::reParent(): failed to attach to new parent after removing from old parent! this:" << this << "new parent:" << newParent; + qWarning() << "AbstractTreeItem::reParent(): failed to attach to new parent after removing from old parent! this:" << this + << "new parent:" << newParent; if (oldParent) oldParent->checkForDeletion(); @@ -179,8 +175,7 @@ bool AbstractTreeItem::reParent(AbstractTreeItem *newParent) return success; } - -AbstractTreeItem *AbstractTreeItem::child(int row) const +AbstractTreeItem* AbstractTreeItem::child(int row) const { if (childCount() <= row) return nullptr; @@ -188,7 +183,6 @@ AbstractTreeItem *AbstractTreeItem::child(int row) const return _childItems[row]; } - int AbstractTreeItem::childCount(int column) const { if (column > 0) @@ -197,7 +191,6 @@ int AbstractTreeItem::childCount(int column) const return _childItems.count(); } - int AbstractTreeItem::row() const { if (!parent()) { @@ -205,19 +198,18 @@ int AbstractTreeItem::row() const return -1; } - int row_ = parent()->_childItems.indexOf(const_cast(this)); + int row_ = parent()->_childItems.indexOf(const_cast(this)); if (row_ == -1) qWarning() << "AbstractTreeItem::row():" << this << "is not in the child list of" << QObject::parent(); return row_; } - void AbstractTreeItem::dumpChildList() { qDebug() << "==== Childlist for Item:" << this << "===="; if (childCount() > 0) { - AbstractTreeItem *child; - QList::const_iterator childIter = _childItems.constBegin(); + AbstractTreeItem* child; + QList::const_iterator childIter = _childItems.constBegin(); while (childIter != _childItems.constEnd()) { child = *childIter; qDebug() << "Row:" << child->row() << child << child->data(0, Qt::DisplayRole); @@ -227,16 +219,13 @@ void AbstractTreeItem::dumpChildList() qDebug() << "==== End Of Childlist ===="; } - /***************************************** * SimpleTreeItem *****************************************/ -SimpleTreeItem::SimpleTreeItem(QList data, AbstractTreeItem *parent) - : AbstractTreeItem(parent), - _itemData(std::move(data)) -{ -} - +SimpleTreeItem::SimpleTreeItem(QList data, AbstractTreeItem* parent) + : AbstractTreeItem(parent) + , _itemData(std::move(data)) +{} QVariant SimpleTreeItem::data(int column, int role) const { @@ -246,8 +235,7 @@ QVariant SimpleTreeItem::data(int column, int role) const return _itemData[column]; } - -bool SimpleTreeItem::setData(int column, const QVariant &value, int role) +bool SimpleTreeItem::setData(int column, const QVariant& value, int role) { if (column > columnCount() || role != Qt::DisplayRole) return false; @@ -261,21 +249,17 @@ bool SimpleTreeItem::setData(int column, const QVariant &value, int role) return true; } - int SimpleTreeItem::columnCount() const { return _itemData.count(); } - /***************************************** * PropertyMapItem *****************************************/ -PropertyMapItem::PropertyMapItem(AbstractTreeItem *parent) +PropertyMapItem::PropertyMapItem(AbstractTreeItem* parent) : AbstractTreeItem(parent) -{ -} - +{} QVariant PropertyMapItem::data(int column, int role) const { @@ -286,15 +270,14 @@ QVariant PropertyMapItem::data(int column, int role) const case Qt::ToolTipRole: return toolTip(column); case Qt::DisplayRole: - case TreeModel::SortRole: // fallthrough, since SortRole should default to DisplayRole + case TreeModel::SortRole: // fallthrough, since SortRole should default to DisplayRole return property(propertyOrder()[column].toLatin1()); default: return QVariant(); } } - -bool PropertyMapItem::setData(int column, const QVariant &value, int role) +bool PropertyMapItem::setData(int column, const QVariant& value, int role) { if (column >= columnCount() || role != Qt::DisplayRole) return false; @@ -304,64 +287,54 @@ bool PropertyMapItem::setData(int column, const QVariant &value, int role) return true; } - int PropertyMapItem::columnCount() const { return propertyOrder().count(); } - /***************************************** * TreeModel *****************************************/ -TreeModel::TreeModel(const QList &data, QObject *parent) - : QAbstractItemModel(parent), - _childStatus(QModelIndex(), 0, 0, 0), - _aboutToRemoveOrInsert(false) +TreeModel::TreeModel(const QList& data, QObject* parent) + : QAbstractItemModel(parent) + , _childStatus(QModelIndex(), 0, 0, 0) + , _aboutToRemoveOrInsert(false) { rootItem = new SimpleTreeItem(data, nullptr); connectItem(rootItem); if (Quassel::isOptionSet("debugmodel")) { - connect(this, &QAbstractItemModel::rowsAboutToBeInserted, - this, &TreeModel::debug_rowsAboutToBeInserted); - connect(this, &QAbstractItemModel::rowsAboutToBeRemoved, - this, &TreeModel::debug_rowsAboutToBeRemoved); - connect(this, &QAbstractItemModel::rowsInserted, - this, &TreeModel::debug_rowsInserted); - connect(this, &QAbstractItemModel::rowsRemoved, - this, &TreeModel::debug_rowsRemoved); - connect(this, &QAbstractItemModel::dataChanged, - this, &TreeModel::debug_dataChanged); + connect(this, &QAbstractItemModel::rowsAboutToBeInserted, this, &TreeModel::debug_rowsAboutToBeInserted); + connect(this, &QAbstractItemModel::rowsAboutToBeRemoved, this, &TreeModel::debug_rowsAboutToBeRemoved); + connect(this, &QAbstractItemModel::rowsInserted, this, &TreeModel::debug_rowsInserted); + connect(this, &QAbstractItemModel::rowsRemoved, this, &TreeModel::debug_rowsRemoved); + connect(this, &QAbstractItemModel::dataChanged, this, &TreeModel::debug_dataChanged); } } - TreeModel::~TreeModel() { delete rootItem; } - -AbstractTreeItem *TreeModel::root() const +AbstractTreeItem* TreeModel::root() const { return rootItem; } - -QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex TreeModel::index(int row, int column, const QModelIndex& parent) const { if (row < 0 || row >= rowCount(parent) || column < 0 || column >= columnCount(parent)) return {}; - AbstractTreeItem *parentItem; + AbstractTreeItem* parentItem; if (!parent.isValid()) parentItem = rootItem; else - parentItem = static_cast(parent.internalPointer()); + parentItem = static_cast(parent.internalPointer()); - AbstractTreeItem *childItem = parentItem->child(row); + AbstractTreeItem* childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); @@ -369,8 +342,7 @@ QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) con return {}; } - -QModelIndex TreeModel::indexByItem(AbstractTreeItem *item) const +QModelIndex TreeModel::indexByItem(AbstractTreeItem* item) const { if (item == nullptr) { qWarning() << "TreeModel::indexByItem(AbstractTreeItem *item) received NULL-Pointer"; @@ -383,8 +355,7 @@ QModelIndex TreeModel::indexByItem(AbstractTreeItem *item) const return createIndex(item->row(), 0, item); } - -QModelIndex TreeModel::parent(const QModelIndex &index) const +QModelIndex TreeModel::parent(const QModelIndex& index) const { if (!index.isValid()) { // ModelTest does this @@ -392,8 +363,8 @@ QModelIndex TreeModel::parent(const QModelIndex &index) const return {}; } - auto *childItem = static_cast(index.internalPointer()); - AbstractTreeItem *parentItem = childItem->parent(); + auto* childItem = static_cast(index.internalPointer()); + AbstractTreeItem* parentItem = childItem->parent(); Q_ASSERT(parentItem); if (parentItem == rootItem) @@ -402,20 +373,18 @@ QModelIndex TreeModel::parent(const QModelIndex &index) const return createIndex(parentItem->row(), 0, parentItem); } - -int TreeModel::rowCount(const QModelIndex &parent) const +int TreeModel::rowCount(const QModelIndex& parent) const { - AbstractTreeItem *parentItem; + AbstractTreeItem* parentItem; if (!parent.isValid()) parentItem = rootItem; else - parentItem = static_cast(parent.internalPointer()); + parentItem = static_cast(parent.internalPointer()); return parentItem->childCount(parent.column()); } - -int TreeModel::columnCount(const QModelIndex &parent) const +int TreeModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent) return rootItem->columnCount(); @@ -424,47 +393,43 @@ int TreeModel::columnCount(const QModelIndex &parent) const // actually this gives us more freedom cause we don't have to ensure that a rows parent // has equal or more columns than that row -// AbstractTreeItem *parentItem; -// if(!parent.isValid()) -// parentItem = rootItem; -// else -// parentItem = static_cast(parent.internalPointer()); -// return parentItem->columnCount(); + // AbstractTreeItem *parentItem; + // if(!parent.isValid()) + // parentItem = rootItem; + // else + // parentItem = static_cast(parent.internalPointer()); + // return parentItem->columnCount(); } - -QVariant TreeModel::data(const QModelIndex &index, int role) const +QVariant TreeModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); - auto *item = static_cast(index.internalPointer()); + auto* item = static_cast(index.internalPointer()); return item->data(index.column(), role); } - -bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role) +bool TreeModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid()) return false; - auto *item = static_cast(index.internalPointer()); + auto* item = static_cast(index.internalPointer()); return item->setData(index.column(), value, role); } - -Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const +Qt::ItemFlags TreeModel::flags(const QModelIndex& index) const { if (!index.isValid()) { return rootItem->flags() & Qt::ItemIsDropEnabled; } else { - auto *item = static_cast(index.internalPointer()); + auto* item = static_cast(index.internalPointer()); return item->flags(); } } - QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) @@ -473,10 +438,9 @@ QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int rol return QVariant(); } - void TreeModel::itemDataChanged(int column) { - auto *item = qobject_cast(sender()); + auto* item = qobject_cast(sender()); QModelIndex leftIndex, rightIndex; if (item == rootItem) @@ -494,27 +458,20 @@ void TreeModel::itemDataChanged(int column) emit dataChanged(leftIndex, rightIndex); } - -void TreeModel::connectItem(AbstractTreeItem *item) +void TreeModel::connectItem(AbstractTreeItem* item) { - connect(item, &AbstractTreeItem::dataChanged, - this, &TreeModel::itemDataChanged); + connect(item, &AbstractTreeItem::dataChanged, this, &TreeModel::itemDataChanged); - connect(item, &AbstractTreeItem::beginAppendChilds, - this, &TreeModel::beginAppendChilds); - connect(item, &AbstractTreeItem::endAppendChilds, - this, &TreeModel::endAppendChilds); + connect(item, &AbstractTreeItem::beginAppendChilds, this, &TreeModel::beginAppendChilds); + connect(item, &AbstractTreeItem::endAppendChilds, this, &TreeModel::endAppendChilds); - connect(item, &AbstractTreeItem::beginRemoveChilds, - this, &TreeModel::beginRemoveChilds); - connect(item, &AbstractTreeItem::endRemoveChilds, - this, &TreeModel::endRemoveChilds); + connect(item, &AbstractTreeItem::beginRemoveChilds, this, &TreeModel::beginRemoveChilds); + connect(item, &AbstractTreeItem::endRemoveChilds, this, &TreeModel::endRemoveChilds); } - void TreeModel::beginAppendChilds(int firstRow, int lastRow) { - auto *parentItem = qobject_cast(sender()); + auto* parentItem = qobject_cast(sender()); if (!parentItem) { qWarning() << "TreeModel::beginAppendChilds(): cannot append Children to unknown parent"; return; @@ -528,10 +485,9 @@ void TreeModel::beginAppendChilds(int firstRow, int lastRow) beginInsertRows(parent, firstRow, lastRow); } - void TreeModel::endAppendChilds() { - auto *parentItem = qobject_cast(sender()); + auto* parentItem = qobject_cast(sender()); if (!parentItem) { qWarning() << "TreeModel::endAppendChilds(): cannot append Children to unknown parent"; return; @@ -550,10 +506,9 @@ void TreeModel::endAppendChilds() endInsertRows(); } - void TreeModel::beginRemoveChilds(int firstRow, int lastRow) { - auto *parentItem = qobject_cast(sender()); + auto* parentItem = qobject_cast(sender()); if (!parentItem) { qWarning() << "TreeModel::beginRemoveChilds(): cannot append Children to unknown parent"; return; @@ -574,10 +529,9 @@ void TreeModel::beginRemoveChilds(int firstRow, int lastRow) beginRemoveRows(parent, firstRow, lastRow); } - void TreeModel::endRemoveChilds() { - auto *parentItem = qobject_cast(sender()); + auto* parentItem = qobject_cast(sender()); if (!parentItem) { qWarning() << "TreeModel::endRemoveChilds(): cannot remove Children from unknown parent"; return; @@ -596,23 +550,21 @@ void TreeModel::endRemoveChilds() endRemoveRows(); } - void TreeModel::clear() { rootItem->removeAllChilds(); } - -void TreeModel::debug_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end) +void TreeModel::debug_rowsAboutToBeInserted(const QModelIndex& parent, int start, int end) { - qDebug() << "debug_rowsAboutToBeInserted" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end; + qDebug() << "debug_rowsAboutToBeInserted" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start + << end; } - -void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) +void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) { - AbstractTreeItem *parentItem; - parentItem = static_cast(parent.internalPointer()); + AbstractTreeItem* parentItem; + parentItem = static_cast(parent.internalPointer()); if (!parentItem) parentItem = rootItem; qDebug() << "debug_rowsAboutToBeRemoved" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end; @@ -625,11 +577,10 @@ void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, } } - -void TreeModel::debug_rowsInserted(const QModelIndex &parent, int start, int end) +void TreeModel::debug_rowsInserted(const QModelIndex& parent, int start, int end) { - AbstractTreeItem *parentItem; - parentItem = static_cast(parent.internalPointer()); + AbstractTreeItem* parentItem; + parentItem = static_cast(parent.internalPointer()); if (!parentItem) parentItem = rootItem; qDebug() << "debug_rowsInserted:" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end; @@ -642,14 +593,12 @@ void TreeModel::debug_rowsInserted(const QModelIndex &parent, int start, int end } } - -void TreeModel::debug_rowsRemoved(const QModelIndex &parent, int start, int end) +void TreeModel::debug_rowsRemoved(const QModelIndex& parent, int start, int end) { qDebug() << "debug_rowsRemoved" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end; } - -void TreeModel::debug_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) +void TreeModel::debug_dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) { qDebug() << "debug_dataChanged" << topLeft << bottomRight; QStringList displayData; diff --git a/src/client/treemodel.h b/src/client/treemodel.h index fcb6bd2d..aa4ac149 100644 --- a/src/client/treemodel.h +++ b/src/client/treemodel.h @@ -22,12 +22,11 @@ #include "client-export.h" +#include +#include // needed for debug #include #include #include -#include - -#include // needed for debug /***************************************** * general item used in the Tree Model @@ -37,31 +36,32 @@ class CLIENT_EXPORT AbstractTreeItem : public QObject Q_OBJECT public: - enum TreeItemFlag { + enum TreeItemFlag + { NoTreeItemFlag = 0x00, DeleteOnLastChildRemoved = 0x01 }; Q_DECLARE_FLAGS(TreeItemFlags, TreeItemFlag) - AbstractTreeItem(AbstractTreeItem *parent = nullptr); + AbstractTreeItem(AbstractTreeItem* parent = nullptr); - bool newChild(AbstractTreeItem *child); - bool newChilds(const QList &items); + bool newChild(AbstractTreeItem* child); + bool newChilds(const QList& items); bool removeChild(int row); - inline bool removeChild(AbstractTreeItem *child) { return removeChild(child->row()); } + inline bool removeChild(AbstractTreeItem* child) { return removeChild(child->row()); } void removeAllChilds(); - bool reParent(AbstractTreeItem *newParent); + bool reParent(AbstractTreeItem* newParent); - AbstractTreeItem *child(int row) const; + AbstractTreeItem* child(int row) const; int childCount(int column = 0) const; virtual int columnCount() const = 0; virtual QVariant data(int column, int role) const = 0; - virtual bool setData(int column, const QVariant &value, int role) = 0; + virtual bool setData(int column, const QVariant& value, int role) = 0; virtual inline Qt::ItemFlags flags() const { return _flags; } virtual inline void setFlags(Qt::ItemFlags flags) { _flags = flags; } @@ -69,7 +69,7 @@ public: inline AbstractTreeItem::TreeItemFlags treeItemFlags() const { return _treeItemFlags; } inline void setTreeItemFlags(AbstractTreeItem::TreeItemFlags flags) { _treeItemFlags = flags; } int row() const; - inline AbstractTreeItem *parent() const { return qobject_cast(QObject::parent()); } + inline AbstractTreeItem* parent() const { return qobject_cast(QObject::parent()); } void dumpChildList(); @@ -83,21 +83,21 @@ signals: void endRemoveChilds(); protected: - void customEvent(QEvent *event) override; + void customEvent(QEvent* event) override; private: - QList _childItems; + QList _childItems; Qt::ItemFlags _flags; TreeItemFlags _treeItemFlags; - void removeChildLater(AbstractTreeItem *child); + void removeChildLater(AbstractTreeItem* child); inline void checkForDeletion() { - if (treeItemFlags() & DeleteOnLastChildRemoved && childCount() == 0) parent()->removeChildLater(this); + if (treeItemFlags() & DeleteOnLastChildRemoved && childCount() == 0) + parent()->removeChildLater(this); } }; - /***************************************** * SimpleTreeItem *****************************************/ @@ -106,10 +106,10 @@ class CLIENT_EXPORT SimpleTreeItem : public AbstractTreeItem Q_OBJECT public: - SimpleTreeItem(QList data, AbstractTreeItem *parent = nullptr); + SimpleTreeItem(QList data, AbstractTreeItem* parent = nullptr); QVariant data(int column, int role) const override; - bool setData(int column, const QVariant &value, int role) override; + bool setData(int column, const QVariant& value, int role) override; int columnCount() const override; @@ -117,7 +117,6 @@ private: QList _itemData; }; - /***************************************** * PropertyMapItem *****************************************/ @@ -126,18 +125,17 @@ class CLIENT_EXPORT PropertyMapItem : public AbstractTreeItem Q_OBJECT public: - PropertyMapItem(AbstractTreeItem *parent = nullptr); + PropertyMapItem(AbstractTreeItem* parent = nullptr); virtual QStringList propertyOrder() const = 0; QVariant data(int column, int role) const override; - bool setData(int column, const QVariant &value, int role) override; + bool setData(int column, const QVariant& value, int role) override; virtual QString toolTip(int column) const { Q_UNUSED(column) return QString(); } int columnCount() const override; }; - /***************************************** * TreeModel *****************************************/ @@ -146,29 +144,30 @@ class CLIENT_EXPORT TreeModel : public QAbstractItemModel Q_OBJECT public: - enum myRoles { + enum myRoles + { SortRole = Qt::UserRole, UserRole }; - TreeModel(const QList &, QObject *parent = nullptr); + TreeModel(const QList&, QObject* parent = nullptr); ~TreeModel() override; - AbstractTreeItem *root() const; + AbstractTreeItem* root() const; - QVariant data(const QModelIndex &index, int role) const override; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + QVariant data(const QModelIndex& index, int role) const override; + bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex &index) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; - QModelIndex indexByItem(AbstractTreeItem *item) const; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + QModelIndex indexByItem(AbstractTreeItem* item) const; - QModelIndex parent(const QModelIndex &index) const override; + QModelIndex parent(const QModelIndex& index) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + int columnCount(const QModelIndex& parent = QModelIndex()) const override; virtual void clear(); @@ -182,25 +181,30 @@ private slots: void endRemoveChilds(); protected: - AbstractTreeItem *rootItem; + AbstractTreeItem* rootItem; private: - void connectItem(AbstractTreeItem *item); + void connectItem(AbstractTreeItem* item); - struct ChildStatus { + struct ChildStatus + { QModelIndex parent; int childCount; int start; int end; - inline ChildStatus(QModelIndex parent_, int cc_, int s_, int e_) : parent(parent_), childCount(cc_), start(s_), end(e_) {}; + inline ChildStatus(QModelIndex parent_, int cc_, int s_, int e_) + : parent(parent_) + , childCount(cc_) + , start(s_) + , end(e_){}; }; ChildStatus _childStatus; int _aboutToRemoveOrInsert; private slots: - void debug_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end); - void debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end); - void debug_rowsInserted(const QModelIndex &parent, int start, int end); - void debug_rowsRemoved(const QModelIndex &parent, int start, int end); - void debug_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); + void debug_rowsAboutToBeInserted(const QModelIndex& parent, int start, int end); + void debug_rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end); + void debug_rowsInserted(const QModelIndex& parent, int start, int end); + void debug_rowsRemoved(const QModelIndex& parent, int start, int end); + void debug_dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight); }; diff --git a/src/common/aliasmanager.cpp b/src/common/aliasmanager.cpp index 356cd324..fc5510a3 100644 --- a/src/common/aliasmanager.cpp +++ b/src/common/aliasmanager.cpp @@ -18,13 +18,14 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "aliasmanager.h" + #include #include -#include "aliasmanager.h" #include "network.h" -AliasManager &AliasManager::operator=(const AliasManager &other) +AliasManager& AliasManager::operator=(const AliasManager& other) { if (this == &other) return *this; @@ -34,8 +35,7 @@ AliasManager &AliasManager::operator=(const AliasManager &other) return *this; } - -int AliasManager::indexOf(const QString &name) const +int AliasManager::indexOf(const QString& name) const { for (int i = 0; i < _aliases.count(); i++) { if (_aliases[i].name == name) @@ -44,7 +44,6 @@ int AliasManager::indexOf(const QString &name) const return -1; } - QVariantMap AliasManager::initAliases() const { QVariantMap aliases; @@ -61,14 +60,14 @@ QVariantMap AliasManager::initAliases() const return aliases; } - -void AliasManager::initSetAliases(const QVariantMap &aliases) +void AliasManager::initSetAliases(const QVariantMap& aliases) { QStringList names = aliases["names"].toStringList(); QStringList expansions = aliases["expansions"].toStringList(); if (names.count() != expansions.count()) { - qWarning() << "AliasesManager::initSetAliases: received" << names.count() << "alias names but only" << expansions.count() << "expansions!"; + qWarning() << "AliasesManager::initSetAliases: received" << names.count() << "alias names but only" << expansions.count() + << "expansions!"; return; } @@ -78,8 +77,7 @@ void AliasManager::initSetAliases(const QVariantMap &aliases) } } - -void AliasManager::addAlias(const QString &name, const QString &expansion) +void AliasManager::addAlias(const QString& name, const QString& expansion) { if (contains(name)) { return; @@ -90,39 +88,29 @@ void AliasManager::addAlias(const QString &name, const QString &expansion) SYNC(ARG(name), ARG(expansion)) } - AliasManager::AliasList AliasManager::defaults() { AliasList aliases; - aliases << Alias("j", "/join $0") - << Alias("ns", "/msg nickserv $0") - << Alias("nickserv", "/msg nickserv $0") - << Alias("cs", "/msg chanserv $0") - << Alias("chanserv", "/msg chanserv $0") - << Alias("hs", "/msg hostserv $0") - << Alias("hostserv", "/msg hostserv $0") - << Alias("wii", "/whois $0 $0") - << Alias("back", "/quote away"); + aliases << Alias("j", "/join $0") << Alias("ns", "/msg nickserv $0") << Alias("nickserv", "/msg nickserv $0") + << Alias("cs", "/msg chanserv $0") << Alias("chanserv", "/msg chanserv $0") << Alias("hs", "/msg hostserv $0") + << Alias("hostserv", "/msg hostserv $0") << Alias("wii", "/whois $0 $0") << Alias("back", "/quote away"); #ifdef Q_OS_LINUX // let's add aliases for scripts that only run on linux - aliases << Alias("inxi", "/exec inxi $0") - << Alias("sysinfo", "/exec inxi -d"); + aliases << Alias("inxi", "/exec inxi $0") << Alias("sysinfo", "/exec inxi -d"); #endif return aliases; } - -AliasManager::CommandList AliasManager::processInput(const BufferInfo &info, const QString &msg) +AliasManager::CommandList AliasManager::processInput(const BufferInfo& info, const QString& msg) { CommandList result; processInput(info, msg, result); return result; } - -void AliasManager::processInput(const BufferInfo &info, const QString &msg_, CommandList &list) +void AliasManager::processInput(const BufferInfo& info, const QString& msg_, CommandList& list) { QString msg = msg_; @@ -135,7 +123,7 @@ void AliasManager::processInput(const BufferInfo &info, const QString &msg_, Com msg.remove(0, 1); // "//asdf" is transformed to "/asdf" else if (msg.startsWith("/ ")) msg.remove(0, 2); // "/ /asdf" is transformed to "/asdf" - msg.prepend("/SAY "); // make sure we only send proper commands to the core + msg.prepend("/SAY "); // make sure we only send proper commands to the core } else { // check for aliases @@ -151,10 +139,9 @@ void AliasManager::processInput(const BufferInfo &info, const QString &msg_, Com list.append(qMakePair(info, msg)); } - -void AliasManager::expand(const QString &alias, const BufferInfo &bufferInfo, const QString &msg, CommandList &list) +void AliasManager::expand(const QString& alias, const BufferInfo& bufferInfo, const QString& msg, CommandList& list) { - const Network *net = network(bufferInfo.networkId()); + const Network* net = network(bufferInfo.networkId()); if (!net) { // FIXME send error as soon as we have a method for that! return; @@ -187,19 +174,16 @@ void AliasManager::expand(const QString &alias, const BufferInfo &bufferInfo, co for (int j = params.count(); j > 0; j--) { // Find the referenced IRC user... - IrcUser *ircUser = net->ircUser(params[j - 1]); + IrcUser* ircUser = net->ircUser(params[j - 1]); // ...and replace components, using short-circuit evaluation as ircUser might be null // Account, or "*" if blank/nonexistent/logged out - command = command.replace( - QString("$%1:account").arg(j), - (ircUser && !ircUser->account().isEmpty()) ? ircUser->account() - : QString("*")); + command = command.replace(QString("$%1:account").arg(j), + (ircUser && !ircUser->account().isEmpty()) ? ircUser->account() : QString("*")); // Hostname, or "*" if blank/nonexistent - command = command.replace( - QString("$%1:hostname").arg(j), - (ircUser && !ircUser->host().isEmpty()) ? ircUser->host() : QString("*")); + command = command.replace(QString("$%1:hostname").arg(j), + (ircUser && !ircUser->host().isEmpty()) ? ircUser->host() : QString("*")); // Identd // Ident if verified, or "*" if blank/unknown/unverified (prefixed with "~") @@ -210,25 +194,21 @@ void AliasManager::expand(const QString &alias, const BufferInfo &bufferInfo, co // server does not verify idents, it usually won't add "~". // // Identd must be replaced before ident to avoid being treated as "$i:ident" + "d" - command = command.replace( - QString("$%1:identd").arg(j), - (ircUser && !ircUser->user().isEmpty() - && !ircUser->user().startsWith("~")) - ? ircUser->user() : QString("*")); + command = command.replace(QString("$%1:identd").arg(j), + (ircUser && !ircUser->user().isEmpty() && !ircUser->user().startsWith("~")) ? ircUser->user() + : QString("*")); // Ident, or "*" if blank/nonexistent - command = command.replace( - QString("$%1:ident").arg(j), - (ircUser && !ircUser->user().isEmpty()) ? ircUser->user() : QString("*")); + command = command.replace(QString("$%1:ident").arg(j), (ircUser && !ircUser->user().isEmpty()) ? ircUser->user() : QString("*")); // Nickname // Must be replaced last to avoid interferring with more specific aliases command = command.replace(QString("$%1").arg(j), params[j - 1]); } command = command.replace("$0", msg); - command = command.replace("$channelname", bufferInfo.bufferName()); // legacy + command = command.replace("$channelname", bufferInfo.bufferName()); // legacy command = command.replace("$channel", bufferInfo.bufferName()); - command = command.replace("$currentnick", net->myNick()); // legacy + command = command.replace("$currentnick", net->myNick()); // legacy command = command.replace("$nick", net->myNick()); expandedCommands << command; } diff --git a/src/common/aliasmanager.h b/src/common/aliasmanager.h index b061465c..01de9f3e 100644 --- a/src/common/aliasmanager.h +++ b/src/common/aliasmanager.h @@ -22,9 +22,10 @@ #include "common-export.h" -#include #include +#include + #include "bufferinfo.h" #include "syncableobject.h" @@ -36,44 +37,52 @@ class COMMON_EXPORT AliasManager : public SyncableObject SYNCABLE_OBJECT public: - inline AliasManager(QObject *parent = nullptr) : SyncableObject(parent) { setAllowClientUpdates(true); } - AliasManager &operator=(const AliasManager &other); - - struct Alias { + inline AliasManager(QObject* parent = nullptr) + : SyncableObject(parent) + { + setAllowClientUpdates(true); + } + AliasManager& operator=(const AliasManager& other); + + struct Alias + { QString name; QString expansion; - Alias(QString name_, QString expansion_) : name(std::move(name_)), expansion(std::move(expansion_)) {} + Alias(QString name_, QString expansion_) + : name(std::move(name_)) + , expansion(std::move(expansion_)) + {} }; using AliasList = QList; - int indexOf(const QString &name) const; - inline bool contains(const QString &name) const { return indexOf(name) != -1; } + int indexOf(const QString& name) const; + inline bool contains(const QString& name) const { return indexOf(name) != -1; } inline bool isEmpty() const { return _aliases.isEmpty(); } inline int count() const { return _aliases.count(); } inline void removeAt(int index) { _aliases.removeAt(index); } - inline Alias &operator[](int i) { return _aliases[i]; } - inline const Alias &operator[](int i) const { return _aliases.at(i); } - inline const AliasList &aliases() const { return _aliases; } + inline Alias& operator[](int i) { return _aliases[i]; } + inline const Alias& operator[](int i) const { return _aliases.at(i); } + inline const AliasList& aliases() const { return _aliases; } static AliasList defaults(); using CommandList = QList>; - CommandList processInput(const BufferInfo &info, const QString &message); + CommandList processInput(const BufferInfo& info, const QString& message); public slots: virtual QVariantMap initAliases() const; - virtual void initSetAliases(const QVariantMap &aliases); + virtual void initSetAliases(const QVariantMap& aliases); - virtual void addAlias(const QString &name, const QString &expansion); + virtual void addAlias(const QString& name, const QString& expansion); protected: - void setAliases(const QList &aliases) { _aliases = aliases; } - virtual const Network *network(NetworkId) const = 0; // core and client require different access + void setAliases(const QList& aliases) { _aliases = aliases; } + virtual const Network* network(NetworkId) const = 0; // core and client require different access private: - void processInput(const BufferInfo &info, const QString &message, CommandList &previousCommands); - void expand(const QString &alias, const BufferInfo &bufferInfo, const QString &msg, CommandList &previousCommands); + void processInput(const BufferInfo& info, const QString& message, CommandList& previousCommands); + void expand(const QString& alias, const BufferInfo& bufferInfo, const QString& msg, CommandList& previousCommands); AliasList _aliases; }; diff --git a/src/common/authhandler.cpp b/src/common/authhandler.cpp index ddc8fcfb..eb8a00c9 100644 --- a/src/common/authhandler.cpp +++ b/src/common/authhandler.cpp @@ -18,32 +18,28 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "authhandler.h" + #include -#include "authhandler.h" #include "util.h" -AuthHandler::AuthHandler(QObject *parent) +AuthHandler::AuthHandler(QObject* parent) : QObject(parent) -{ - -} - +{} -QTcpSocket *AuthHandler::socket() const +QTcpSocket* AuthHandler::socket() const { return _socket; } - -void AuthHandler::setSocket(QTcpSocket *socket) +void AuthHandler::setSocket(QTcpSocket* socket) { _socket = socket; connect(socket, selectOverload(&QTcpSocket::error), this, &AuthHandler::onSocketError); connect(socket, &QAbstractSocket::disconnected, this, &AuthHandler::onSocketDisconnected); } - bool AuthHandler::isLocal() const { if (socket()) { @@ -53,7 +49,6 @@ bool AuthHandler::isLocal() const return false; } - // Some errors (e.g. connection refused) don't trigger a disconnected() from the socket, so send this explicitly // (but make sure it's only sent once!) void AuthHandler::onSocketError(QAbstractSocket::SocketError error) @@ -68,7 +63,6 @@ void AuthHandler::onSocketError(QAbstractSocket::SocketError error) } } - void AuthHandler::onSocketDisconnected() { if (!_disconnectedSent) { @@ -77,13 +71,11 @@ void AuthHandler::onSocketDisconnected() } } - void AuthHandler::invalidMessage() { qWarning() << Q_FUNC_INFO << "No handler for message!"; } - void AuthHandler::close() { if (_socket && _socket->isOpen()) diff --git a/src/common/authhandler.h b/src/common/authhandler.h index 0d30e662..6a429d31 100644 --- a/src/common/authhandler.h +++ b/src/common/authhandler.h @@ -33,36 +33,39 @@ class COMMON_EXPORT AuthHandler : public QObject Q_OBJECT public: - AuthHandler(QObject *parent = nullptr); + AuthHandler(QObject* parent = nullptr); - QTcpSocket *socket() const; + QTcpSocket* socket() const; bool isLocal() const; - virtual void handle(const Protocol::RegisterClient &) { invalidMessage(); } - virtual void handle(const Protocol::ClientDenied &) { invalidMessage(); } - virtual void handle(const Protocol::ClientRegistered &) { invalidMessage(); } - virtual void handle(const Protocol::SetupData &) { invalidMessage(); } - virtual void handle(const Protocol::SetupFailed &) { invalidMessage(); } - virtual void handle(const Protocol::SetupDone &) { invalidMessage(); } - virtual void handle(const Protocol::Login &) { invalidMessage(); } - virtual void handle(const Protocol::LoginFailed &) { invalidMessage(); } - virtual void handle(const Protocol::LoginSuccess &) { invalidMessage(); } - virtual void handle(const Protocol::SessionState &) { invalidMessage(); } + virtual void handle(const Protocol::RegisterClient&) { invalidMessage(); } + virtual void handle(const Protocol::ClientDenied&) { invalidMessage(); } + virtual void handle(const Protocol::ClientRegistered&) { invalidMessage(); } + virtual void handle(const Protocol::SetupData&) { invalidMessage(); } + virtual void handle(const Protocol::SetupFailed&) { invalidMessage(); } + virtual void handle(const Protocol::SetupDone&) { invalidMessage(); } + virtual void handle(const Protocol::Login&) { invalidMessage(); } + virtual void handle(const Protocol::LoginFailed&) { invalidMessage(); } + virtual void handle(const Protocol::LoginSuccess&) { invalidMessage(); } + virtual void handle(const Protocol::SessionState&) { invalidMessage(); } // fallback for unknown types, will trigger an error template - void handle(const T &) { invalidMessage(); } + void handle(const T&) + { + invalidMessage(); + } public slots: void close(); signals: void disconnected(); - void socketError(QAbstractSocket::SocketError error, const QString &errorString); + void socketError(QAbstractSocket::SocketError error, const QString& errorString); protected: - void setSocket(QTcpSocket *socket); + void setSocket(QTcpSocket* socket); protected slots: virtual void onSocketError(QAbstractSocket::SocketError error); @@ -71,6 +74,6 @@ protected slots: private: void invalidMessage(); - QTcpSocket *_socket{nullptr}; // FIXME: should be a QSharedPointer? -> premature disconnect before the peer has taken over + QTcpSocket* _socket{nullptr}; // FIXME: should be a QSharedPointer? -> premature disconnect before the peer has taken over bool _disconnectedSent{false}; }; diff --git a/src/common/backlogmanager.h b/src/common/backlogmanager.h index ad7c8061..6318a97b 100644 --- a/src/common/backlogmanager.h +++ b/src/common/backlogmanager.h @@ -31,18 +31,22 @@ class COMMON_EXPORT BacklogManager : public SyncableObject SYNCABLE_OBJECT public: - BacklogManager(QObject *parent = nullptr) : SyncableObject(parent) {} + BacklogManager(QObject* parent = nullptr) + : SyncableObject(parent) + {} public slots: virtual QVariantList requestBacklog(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0); - virtual QVariantList requestBacklogFiltered(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1); - inline virtual void receiveBacklog(BufferId, MsgId, MsgId, int, int, QVariantList) {}; - inline virtual void receiveBacklogFiltered(BufferId, MsgId, MsgId, int, int, int, int, QVariantList) {}; + virtual QVariantList requestBacklogFiltered( + BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1); + inline virtual void receiveBacklog(BufferId, MsgId, MsgId, int, int, QVariantList){}; + inline virtual void receiveBacklogFiltered(BufferId, MsgId, MsgId, int, int, int, int, QVariantList){}; virtual QVariantList requestBacklogAll(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0); - virtual QVariantList requestBacklogAllFiltered(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1); - inline virtual void receiveBacklogAll(MsgId, MsgId, int, int, QVariantList) {}; - inline virtual void receiveBacklogAllFiltered(MsgId, MsgId, int, int, int, int, QVariantList) {}; + virtual QVariantList requestBacklogAllFiltered( + MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1); + inline virtual void receiveBacklogAll(MsgId, MsgId, int, int, QVariantList){}; + inline virtual void receiveBacklogAllFiltered(MsgId, MsgId, int, int, int, int, QVariantList){}; signals: void backlogRequested(BufferId, MsgId, MsgId, int, int); diff --git a/src/common/basichandler.cpp b/src/common/basichandler.cpp index 906e82e4..ddb397ef 100644 --- a/src/common/basichandler.cpp +++ b/src/common/basichandler.cpp @@ -20,31 +20,27 @@ #include "basichandler.h" -#include -#include #include -BasicHandler::BasicHandler(QObject *parent) - : QObject(parent), - _methodPrefix("handle") -{ -} - +#include +#include -BasicHandler::BasicHandler(QString methodPrefix, QObject *parent) - : QObject(parent), - _methodPrefix(std::move(methodPrefix)) -{ -} +BasicHandler::BasicHandler(QObject* parent) + : QObject(parent) + , _methodPrefix("handle") +{} +BasicHandler::BasicHandler(QString methodPrefix, QObject* parent) + : QObject(parent) + , _methodPrefix(std::move(methodPrefix)) +{} QStringList BasicHandler::providesHandlers() { return handlerHash().keys(); } - -const QHash &BasicHandler::handlerHash() +const QHash& BasicHandler::handlerHash() { if (!_initDone) { for (int i = metaObject()->methodOffset(); i < metaObject()->methodCount(); i++) { @@ -57,8 +53,8 @@ const QHash &BasicHandler::handlerHash() if (!methodSignature.startsWith(_methodPrefix)) continue; - methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list - methodSignature = methodSignature.mid(_methodPrefix.length()); // strip "handle" or whatever the prefix is + methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list + methodSignature = methodSignature.mid(_methodPrefix.length()); // strip "handle" or whatever the prefix is _handlerHash[methodSignature] = i; } _initDone = true; @@ -66,12 +62,16 @@ const QHash &BasicHandler::handlerHash() return _handlerHash; } - -void BasicHandler::handle(const QString &member, QGenericArgument val0, - QGenericArgument val1, QGenericArgument val2, - QGenericArgument val3, QGenericArgument val4, - QGenericArgument val5, QGenericArgument val6, - QGenericArgument val7, QGenericArgument val8) +void BasicHandler::handle(const QString& member, + QGenericArgument val0, + QGenericArgument val1, + QGenericArgument val2, + QGenericArgument val3, + QGenericArgument val4, + QGenericArgument val5, + QGenericArgument val6, + QGenericArgument val7, + QGenericArgument val8) { // Now we try to find a handler for this message. BTW, I do love the Trolltech guys ;-) // and now we even have a fast lookup! Thanks thiago! @@ -85,14 +85,34 @@ void BasicHandler::handle(const QString &member, QGenericArgument val0, return; } else { - void *param[] = { nullptr, Q_ARG(QString, member).data(), val0.data(), val1.data(), val2.data(), val3.data(), val4.data(), - val5.data(), val6.data(), val7.data(), val8.data(), val8.data() }; + void* param[] = {nullptr, + Q_ARG(QString, member).data(), + val0.data(), + val1.data(), + val2.data(), + val3.data(), + val4.data(), + val5.data(), + val6.data(), + val7.data(), + val8.data(), + val8.data()}; qt_metacall(QMetaObject::InvokeMetaMethod, _defaultHandler, param); return; } } - void *param[] = { nullptr, val0.data(), val1.data(), val2.data(), val3.data(), val4.data(), - val5.data(), val6.data(), val7.data(), val8.data(), val8.data(), nullptr }; + void* param[] = {nullptr, + val0.data(), + val1.data(), + val2.data(), + val3.data(), + val4.data(), + val5.data(), + val6.data(), + val7.data(), + val8.data(), + val8.data(), + nullptr}; qt_metacall(QMetaObject::InvokeMetaMethod, handlerHash()[handler], param); } diff --git a/src/common/basichandler.h b/src/common/basichandler.h index d2a3ef2b..86cce870 100644 --- a/src/common/basichandler.h +++ b/src/common/basichandler.h @@ -22,31 +22,36 @@ #include "common-export.h" +#include +#include #include #include #include -#include -#include class COMMON_EXPORT BasicHandler : public QObject { Q_OBJECT public: - BasicHandler(QObject *parent = nullptr); - BasicHandler(QString methodPrefix, QObject *parent = nullptr); + BasicHandler(QObject* parent = nullptr); + BasicHandler(QString methodPrefix, QObject* parent = nullptr); QStringList providesHandlers(); protected: - virtual void handle(const QString &member, QGenericArgument val0 = QGenericArgument(nullptr), - QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), - QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), - QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), - QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument()); + virtual void handle(const QString& member, + QGenericArgument val0 = QGenericArgument(nullptr), + QGenericArgument val1 = QGenericArgument(), + QGenericArgument val2 = QGenericArgument(), + QGenericArgument val3 = QGenericArgument(), + QGenericArgument val4 = QGenericArgument(), + QGenericArgument val5 = QGenericArgument(), + QGenericArgument val6 = QGenericArgument(), + QGenericArgument val7 = QGenericArgument(), + QGenericArgument val8 = QGenericArgument()); private: - const QHash &handlerHash(); + const QHash& handlerHash(); QHash _handlerHash; int _defaultHandler{-1}; bool _initDone{false}; diff --git a/src/common/bufferinfo.cpp b/src/common/bufferinfo.cpp index 2eaa2ed4..2583f809 100644 --- a/src/common/bufferinfo.cpp +++ b/src/common/bufferinfo.cpp @@ -18,40 +18,36 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include -#include -#include -#include +#include "bufferinfo.h" + #include -#include "bufferinfo.h" +#include +#include +#include +#include #include "util.h" BufferInfo::BufferInfo() - : _bufferId(0), - _netid(0), - _bufferName(QString()) -{ -} - - -BufferInfo::BufferInfo(BufferId id, NetworkId networkid, Type type, uint gid, QString buf) - : _bufferId(id), - _netid(networkid), - _type(type), - _groupId(gid), - _bufferName(std::move(buf)) -{ -} - + : _bufferId(0) + , _netid(0) + , _bufferName(QString()) +{} + +BufferInfo::BufferInfo(BufferId id, NetworkId networkid, Type type, uint gid, QString buf) + : _bufferId(id) + , _netid(networkid) + , _type(type) + , _groupId(gid) + , _bufferName(std::move(buf)) +{} BufferInfo BufferInfo::fakeStatusBuffer(NetworkId networkId) { return BufferInfo(0, networkId, StatusBuffer); } - QString BufferInfo::bufferName() const { if (isChannelName(_bufferName)) @@ -60,30 +56,27 @@ QString BufferInfo::bufferName() const return nickFromMask(_bufferName); // FIXME get rid of global functions and use the Network stuff instead! } - bool BufferInfo::acceptsRegularMessages() const { - if(_type == StatusBuffer || _type == InvalidBuffer) + if (_type == StatusBuffer || _type == InvalidBuffer) return false; return true; } - -QDebug operator<<(QDebug dbg, const BufferInfo &b) +QDebug operator<<(QDebug dbg, const BufferInfo& b) { - dbg.nospace() << "(bufId: " << b.bufferId() << ", netId: " << b.networkId() << ", groupId: " << b.groupId() << ", buf: " << b.bufferName() << ")"; + dbg.nospace() << "(bufId: " << b.bufferId() << ", netId: " << b.networkId() << ", groupId: " << b.groupId() + << ", buf: " << b.bufferName() << ")"; return dbg.space(); } - -QDataStream &operator<<(QDataStream &out, const BufferInfo &bufferInfo) +QDataStream& operator<<(QDataStream& out, const BufferInfo& bufferInfo) { out << bufferInfo._bufferId << bufferInfo._netid << (qint16)bufferInfo._type << bufferInfo._groupId << bufferInfo._bufferName.toUtf8(); return out; } - -QDataStream &operator>>(QDataStream &in, BufferInfo &bufferInfo) +QDataStream& operator>>(QDataStream& in, BufferInfo& bufferInfo) { QByteArray buffername; qint16 bufferType; @@ -93,8 +86,7 @@ QDataStream &operator>>(QDataStream &in, BufferInfo &bufferInfo) return in; } - -uint qHash(const BufferInfo &bufferid) +uint qHash(const BufferInfo& bufferid) { return qHash(bufferid._bufferId); } diff --git a/src/common/bufferinfo.h b/src/common/bufferinfo.h index e20ce9b3..7c243f4c 100644 --- a/src/common/bufferinfo.h +++ b/src/common/bufferinfo.h @@ -30,7 +30,8 @@ class QDataStream; class COMMON_EXPORT BufferInfo { public: - enum Type { + enum Type + { InvalidBuffer = 0x00, StatusBuffer = 0x01, ChannelBuffer = 0x02, @@ -38,7 +39,8 @@ public: GroupBuffer = 0x08 }; - enum Activity { + enum Activity + { NoActivity = 0x00, OtherActivity = 0x01, NewMessage = 0x02, @@ -52,17 +54,17 @@ public: static BufferInfo fakeStatusBuffer(NetworkId networkId); inline bool isValid() const { return _bufferId != 0; } - inline const BufferId &bufferId() const { return _bufferId; } + inline const BufferId& bufferId() const { return _bufferId; } inline void setBufferId(BufferId id) { _bufferId = id; } - inline const NetworkId &networkId() const { return _netid; } - inline const Type &type() const { return _type; } - inline const uint &groupId() const { return _groupId; } + inline const NetworkId& networkId() const { return _netid; } + inline const Type& type() const { return _type; } + inline const uint& groupId() const { return _groupId; } void setGroupId(uint gid) { _groupId = gid; } QString bufferName() const; bool acceptsRegularMessages() const; - inline bool operator==(const BufferInfo &other) const { return _bufferId == other._bufferId; } + inline bool operator==(const BufferInfo& other) const { return _bufferId == other._bufferId; } private: BufferId _bufferId; @@ -71,17 +73,16 @@ private: uint _groupId{0}; QString _bufferName; - friend uint qHash(const BufferInfo &); - friend QDataStream &operator<<(QDataStream &out, const BufferInfo &bufferInfo); - friend QDataStream &operator>>(QDataStream &in, BufferInfo &bufferInfo); + friend uint qHash(const BufferInfo&); + friend QDataStream& operator<<(QDataStream& out, const BufferInfo& bufferInfo); + friend QDataStream& operator>>(QDataStream& in, BufferInfo& bufferInfo); }; - -QDataStream &operator<<(QDataStream &out, const BufferInfo &bufferInfo); -QDataStream &operator>>(QDataStream &in, BufferInfo &bufferInfo); -QDebug operator<<(QDebug dbg, const BufferInfo &b); +QDataStream& operator<<(QDataStream& out, const BufferInfo& bufferInfo); +QDataStream& operator>>(QDataStream& in, BufferInfo& bufferInfo); +QDebug operator<<(QDebug dbg, const BufferInfo& b); Q_DECLARE_METATYPE(BufferInfo) Q_DECLARE_OPERATORS_FOR_FLAGS(BufferInfo::ActivityLevel) -uint qHash(const BufferInfo &); +uint qHash(const BufferInfo&); diff --git a/src/common/buffersyncer.cpp b/src/common/buffersyncer.cpp index 99493068..32f579ea 100644 --- a/src/common/buffersyncer.cpp +++ b/src/common/buffersyncer.cpp @@ -22,34 +22,28 @@ #include -BufferSyncer::BufferSyncer(QObject *parent) +BufferSyncer::BufferSyncer(QObject* parent) : SyncableObject(parent) -{ -} - - -BufferSyncer::BufferSyncer( - QHash lastSeenMsg, - QHash markerLines, - QHash activities, - QHash highlightCounts, - QObject *parent -) : SyncableObject(parent), - _lastSeenMsg(std::move(lastSeenMsg)), - _markerLines(std::move(markerLines)), - _bufferActivities(std::move(activities)), - _highlightCounts(std::move(highlightCounts)) -{ -} +{} +BufferSyncer::BufferSyncer(QHash lastSeenMsg, + QHash markerLines, + QHash activities, + QHash highlightCounts, + QObject* parent) + : SyncableObject(parent) + , _lastSeenMsg(std::move(lastSeenMsg)) + , _markerLines(std::move(markerLines)) + , _bufferActivities(std::move(activities)) + , _highlightCounts(std::move(highlightCounts)) +{} MsgId BufferSyncer::lastSeenMsg(BufferId buffer) const { return _lastSeenMsg.value(buffer, MsgId()); } - -bool BufferSyncer::setLastSeenMsg(BufferId buffer, const MsgId &msgId) +bool BufferSyncer::setLastSeenMsg(BufferId buffer, const MsgId& msgId) { if (!msgId.isValid()) return false; @@ -64,14 +58,12 @@ bool BufferSyncer::setLastSeenMsg(BufferId buffer, const MsgId &msgId) return false; } - MsgId BufferSyncer::markerLine(BufferId buffer) const { return _markerLines.value(buffer, MsgId()); } - -bool BufferSyncer::setMarkerLine(BufferId buffer, const MsgId &msgId) +bool BufferSyncer::setMarkerLine(BufferId buffer, const MsgId& msgId) { if (!msgId.isValid()) return false; @@ -85,82 +77,71 @@ bool BufferSyncer::setMarkerLine(BufferId buffer, const MsgId &msgId) return true; } - QVariantList BufferSyncer::initLastSeenMsg() const { QVariantList list; QHash::const_iterator iter = _lastSeenMsg.constBegin(); while (iter != _lastSeenMsg.constEnd()) { - list << QVariant::fromValue(iter.key()) - << QVariant::fromValue(iter.value()); + list << QVariant::fromValue(iter.key()) << QVariant::fromValue(iter.value()); ++iter; } return list; } - -void BufferSyncer::initSetLastSeenMsg(const QVariantList &list) +void BufferSyncer::initSetLastSeenMsg(const QVariantList& list) { _lastSeenMsg.clear(); Q_ASSERT(list.count() % 2 == 0); for (int i = 0; i < list.count(); i += 2) { - setLastSeenMsg(list.at(i).value(), list.at(i+1).value()); + setLastSeenMsg(list.at(i).value(), list.at(i + 1).value()); } } - QVariantList BufferSyncer::initMarkerLines() const { QVariantList list; QHash::const_iterator iter = _markerLines.constBegin(); while (iter != _markerLines.constEnd()) { - list << QVariant::fromValue(iter.key()) - << QVariant::fromValue(iter.value()); + list << QVariant::fromValue(iter.key()) << QVariant::fromValue(iter.value()); ++iter; } return list; } - -void BufferSyncer::initSetMarkerLines(const QVariantList &list) +void BufferSyncer::initSetMarkerLines(const QVariantList& list) { _markerLines.clear(); Q_ASSERT(list.count() % 2 == 0); for (int i = 0; i < list.count(); i += 2) { - setMarkerLine(list.at(i).value(), list.at(i+1).value()); + setMarkerLine(list.at(i).value(), list.at(i + 1).value()); } } - QVariantList BufferSyncer::initActivities() const { QVariantList list; auto iter = _bufferActivities.constBegin(); while (iter != _bufferActivities.constEnd()) { - list << QVariant::fromValue(iter.key()) - << QVariant::fromValue((int) iter.value()); + list << QVariant::fromValue(iter.key()) << QVariant::fromValue((int)iter.value()); ++iter; } return list; } - -void BufferSyncer::initSetActivities(const QVariantList &list) +void BufferSyncer::initSetActivities(const QVariantList& list) { _bufferActivities.clear(); Q_ASSERT(list.count() % 2 == 0); for (int i = 0; i < list.count(); i += 2) { - setBufferActivity(list.at(i).value(), list.at(i+1).value()); + setBufferActivity(list.at(i).value(), list.at(i + 1).value()); } } - Message::Types BufferSyncer::activity(BufferId buffer) const { return _bufferActivities.value(buffer, Message::Types()); } - void BufferSyncer::removeBuffer(BufferId buffer) { if (_lastSeenMsg.contains(buffer)) @@ -175,7 +156,6 @@ void BufferSyncer::removeBuffer(BufferId buffer) emit bufferRemoved(buffer); } - void BufferSyncer::mergeBuffersPermanently(BufferId buffer1, BufferId buffer2) { if (_lastSeenMsg.contains(buffer2)) @@ -190,25 +170,27 @@ void BufferSyncer::mergeBuffersPermanently(BufferId buffer1, BufferId buffer2) emit buffersPermanentlyMerged(buffer1, buffer2); } -int BufferSyncer::highlightCount(BufferId buffer) const { +int BufferSyncer::highlightCount(BufferId buffer) const +{ return _highlightCounts.value(buffer, 0); } -QVariantList BufferSyncer::initHighlightCounts() const { +QVariantList BufferSyncer::initHighlightCounts() const +{ QVariantList list; auto iter = _highlightCounts.constBegin(); while (iter != _highlightCounts.constEnd()) { - list << QVariant::fromValue(iter.key()) - << QVariant::fromValue((int) iter.value()); + list << QVariant::fromValue(iter.key()) << QVariant::fromValue((int)iter.value()); ++iter; } return list; } -void BufferSyncer::initSetHighlightCounts(const QVariantList &list) { +void BufferSyncer::initSetHighlightCounts(const QVariantList& list) +{ _highlightCounts.clear(); Q_ASSERT(list.count() % 2 == 0); for (int i = 0; i < list.count(); i += 2) { - setHighlightCount(list.at(i).value(), list.at(i+1).value()); + setHighlightCount(list.at(i).value(), list.at(i + 1).value()); } } diff --git a/src/common/buffersyncer.h b/src/common/buffersyncer.h index 6d9160cd..c0d6de9d 100644 --- a/src/common/buffersyncer.h +++ b/src/common/buffersyncer.h @@ -22,9 +22,9 @@ #include "common-export.h" +#include "message.h" #include "syncableobject.h" #include "types.h" -#include "message.h" class COMMON_EXPORT BufferSyncer : public SyncableObject { @@ -32,21 +32,27 @@ class COMMON_EXPORT BufferSyncer : public SyncableObject SYNCABLE_OBJECT public: - explicit BufferSyncer(QObject *parent); - explicit BufferSyncer(QHash lastSeenMsg, QHash markerLines, QHash activities, QHash highlightCounts, QObject *parent); + explicit BufferSyncer(QObject* parent); + explicit BufferSyncer(QHash lastSeenMsg, + QHash markerLines, + QHash activities, + QHash highlightCounts, + QObject* parent); MsgId lastSeenMsg(BufferId buffer) const; MsgId markerLine(BufferId buffer) const; Message::Types activity(BufferId buffer) const; int highlightCount(BufferId buffer) const; - void markActivitiesChanged() { + void markActivitiesChanged() + { for (auto buffer : _bufferActivities.keys()) { emit bufferActivityChanged(buffer, activity(buffer)); } } - void markHighlightCountsChanged() { + void markHighlightCountsChanged() + { for (auto buffer : _highlightCounts.keys()) { emit highlightCountChanged(buffer, highlightCount(buffer)); } @@ -54,28 +60,33 @@ public: public slots: QVariantList initLastSeenMsg() const; - void initSetLastSeenMsg(const QVariantList &); + void initSetLastSeenMsg(const QVariantList&); QVariantList initMarkerLines() const; - void initSetMarkerLines(const QVariantList &); + void initSetMarkerLines(const QVariantList&); QVariantList initActivities() const; - void initSetActivities(const QVariantList &); + void initSetActivities(const QVariantList&); QVariantList initHighlightCounts() const; - void initSetHighlightCounts(const QVariantList &); + void initSetHighlightCounts(const QVariantList&); - virtual inline void requestSetLastSeenMsg(BufferId buffer, const MsgId &msgId) { REQUEST(ARG(buffer), ARG(msgId)) } - virtual inline void requestSetMarkerLine(BufferId buffer, const MsgId &msgId) { REQUEST(ARG(buffer), ARG(msgId)) setMarkerLine(buffer, msgId); } + virtual inline void requestSetLastSeenMsg(BufferId buffer, const MsgId& msgId) { REQUEST(ARG(buffer), ARG(msgId)) } + virtual inline void requestSetMarkerLine(BufferId buffer, const MsgId& msgId) + { + REQUEST(ARG(buffer), ARG(msgId)) setMarkerLine(buffer, msgId); + } - virtual inline void setBufferActivity(BufferId buffer, int activity) { + virtual inline void setBufferActivity(BufferId buffer, int activity) + { auto flags = Message::Types(activity); SYNC(ARG(buffer), ARG(activity)); _bufferActivities[buffer] = flags; emit bufferActivityChanged(buffer, flags); } - virtual inline void setHighlightCount(BufferId buffer, int count) { + virtual inline void setHighlightCount(BufferId buffer, int count) + { SYNC(ARG(buffer), ARG(count)); _highlightCounts[buffer] = count; emit highlightCountChanged(buffer, count); @@ -85,7 +96,10 @@ public slots: virtual void removeBuffer(BufferId buffer); virtual inline void requestRenameBuffer(BufferId buffer, QString newName) { REQUEST(ARG(buffer), ARG(newName)) } - virtual inline void renameBuffer(BufferId buffer, QString newName) { SYNC(ARG(buffer), ARG(newName)) emit bufferRenamed(buffer, newName); } + virtual inline void renameBuffer(BufferId buffer, QString newName) + { + SYNC(ARG(buffer), ARG(newName)) emit bufferRenamed(buffer, newName); + } virtual inline void requestMergeBuffersPermanently(BufferId buffer1, BufferId buffer2) { emit REQUEST(ARG(buffer1), ARG(buffer2)) } virtual void mergeBuffersPermanently(BufferId buffer1, BufferId buffer2); @@ -96,8 +110,8 @@ public slots: virtual inline void markBufferAsRead(BufferId buffer) { SYNC(ARG(buffer)) emit bufferMarkedAsRead(buffer); } signals: - void lastSeenMsgSet(BufferId buffer, const MsgId &msgId); - void markerLineSet(BufferId buffer, const MsgId &msgId); + void lastSeenMsgSet(BufferId buffer, const MsgId& msgId); + void markerLineSet(BufferId buffer, const MsgId& msgId); void bufferRemoved(BufferId buffer); void bufferRenamed(BufferId buffer, QString newName); void buffersPermanentlyMerged(BufferId buffer1, BufferId buffer2); @@ -106,8 +120,8 @@ signals: void highlightCountChanged(BufferId, int); protected slots: - bool setLastSeenMsg(BufferId buffer, const MsgId &msgId); - bool setMarkerLine(BufferId buffer, const MsgId &msgId); + bool setLastSeenMsg(BufferId buffer, const MsgId& msgId); + bool setMarkerLine(BufferId buffer, const MsgId& msgId); protected: inline QList lastSeenBufferIds() const { return _lastSeenMsg.keys(); } diff --git a/src/common/bufferviewconfig.cpp b/src/common/bufferviewconfig.cpp index 5bb9b1e1..fff1ef1e 100644 --- a/src/common/bufferviewconfig.cpp +++ b/src/common/bufferviewconfig.cpp @@ -20,24 +20,22 @@ #include "bufferviewconfig.h" -BufferViewConfig::BufferViewConfig(int bufferViewId, QObject *parent) - : SyncableObject(parent), - _bufferViewId(bufferViewId) +BufferViewConfig::BufferViewConfig(int bufferViewId, QObject* parent) + : SyncableObject(parent) + , _bufferViewId(bufferViewId) { setObjectName(QString::number(bufferViewId)); } - -BufferViewConfig::BufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent) - : SyncableObject(parent), - _bufferViewId(bufferViewId) +BufferViewConfig::BufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent) + : SyncableObject(parent) + , _bufferViewId(bufferViewId) { fromVariantMap(properties); setObjectName(QString::number(bufferViewId)); } - -void BufferViewConfig::setBufferViewName(const QString &bufferViewName) +void BufferViewConfig::setBufferViewName(const QString& bufferViewName) { if (_bufferViewName == bufferViewName) return; @@ -47,8 +45,7 @@ void BufferViewConfig::setBufferViewName(const QString &bufferViewName) emit bufferViewNameSet(bufferViewName); } - -void BufferViewConfig::setNetworkId(const NetworkId &networkId) +void BufferViewConfig::setNetworkId(const NetworkId& networkId) { if (_networkId == networkId) return; @@ -59,7 +56,6 @@ void BufferViewConfig::setNetworkId(const NetworkId &networkId) emit configChanged(); } - void BufferViewConfig::setAddNewBuffersAutomatically(bool addNewBuffersAutomatically) { if (_addNewBuffersAutomatically == addNewBuffersAutomatically) @@ -70,7 +66,6 @@ void BufferViewConfig::setAddNewBuffersAutomatically(bool addNewBuffersAutomatic emit configChanged(); } - void BufferViewConfig::setSortAlphabetically(bool sortAlphabetically) { if (_sortAlphabetically == sortAlphabetically) @@ -81,7 +76,6 @@ void BufferViewConfig::setSortAlphabetically(bool sortAlphabetically) emit configChanged(); } - void BufferViewConfig::setDisableDecoration(bool disableDecoration) { if (_disableDecoration == disableDecoration) @@ -91,7 +85,6 @@ void BufferViewConfig::setDisableDecoration(bool disableDecoration) SYNC(ARG(disableDecoration)) } - void BufferViewConfig::setAllowedBufferTypes(int bufferTypes) { if (_allowedBufferTypes == bufferTypes) @@ -102,7 +95,6 @@ void BufferViewConfig::setAllowedBufferTypes(int bufferTypes) emit configChanged(); } - void BufferViewConfig::setMinimumActivity(int activity) { if (_minimumActivity == activity) @@ -113,7 +105,6 @@ void BufferViewConfig::setMinimumActivity(int activity) emit configChanged(); } - void BufferViewConfig::setHideInactiveBuffers(bool hideInactiveBuffers) { if (_hideInactiveBuffers == hideInactiveBuffers) @@ -134,7 +125,8 @@ void BufferViewConfig::setHideInactiveNetworks(bool hideInactiveNetworks) emit configChanged(); } -void BufferViewConfig::setShowSearch(bool showSearch) { +void BufferViewConfig::setShowSearch(bool showSearch) +{ if (_showSearch == showSearch) { return; } @@ -144,88 +136,80 @@ void BufferViewConfig::setShowSearch(bool showSearch) { emit configChanged(); } - QVariantList BufferViewConfig::initBufferList() const { QVariantList buffers; - foreach(BufferId bufferId, _buffers) { + foreach (BufferId bufferId, _buffers) { buffers << qVariantFromValue(bufferId); } return buffers; } - -void BufferViewConfig::initSetBufferList(const QVariantList &buffers) +void BufferViewConfig::initSetBufferList(const QVariantList& buffers) { _buffers.clear(); - foreach(QVariant buffer, buffers) { + foreach (QVariant buffer, buffers) { _buffers << buffer.value(); } - emit configChanged(); // used to track changes in the settingspage + emit configChanged(); // used to track changes in the settingspage } - -void BufferViewConfig::initSetBufferList(const QList &buffers) +void BufferViewConfig::initSetBufferList(const QList& buffers) { _buffers.clear(); - foreach(BufferId bufferId, buffers) { + foreach (BufferId bufferId, buffers) { _buffers << bufferId; } - emit configChanged(); // used to track changes in the settingspage + emit configChanged(); // used to track changes in the settingspage } - QVariantList BufferViewConfig::initRemovedBuffers() const { QVariantList removedBuffers; - foreach(BufferId bufferId, _removedBuffers) { + foreach (BufferId bufferId, _removedBuffers) { removedBuffers << qVariantFromValue(bufferId); } return removedBuffers; } - -void BufferViewConfig::initSetRemovedBuffers(const QVariantList &buffers) +void BufferViewConfig::initSetRemovedBuffers(const QVariantList& buffers) { _removedBuffers.clear(); - foreach(QVariant buffer, buffers) { + foreach (QVariant buffer, buffers) { _removedBuffers << buffer.value(); } } - QVariantList BufferViewConfig::initTemporarilyRemovedBuffers() const { QVariantList temporarilyRemovedBuffers; - foreach(BufferId bufferId, _temporarilyRemovedBuffers) { + foreach (BufferId bufferId, _temporarilyRemovedBuffers) { temporarilyRemovedBuffers << qVariantFromValue(bufferId); } return temporarilyRemovedBuffers; } - -void BufferViewConfig::initSetTemporarilyRemovedBuffers(const QVariantList &buffers) +void BufferViewConfig::initSetTemporarilyRemovedBuffers(const QVariantList& buffers) { _temporarilyRemovedBuffers.clear(); - foreach(QVariant buffer, buffers) { + foreach (QVariant buffer, buffers) { _temporarilyRemovedBuffers << buffer.value(); } } - -void BufferViewConfig::addBuffer(const BufferId &bufferId, int pos) +void BufferViewConfig::addBuffer(const BufferId& bufferId, int pos) { if (_buffers.contains(bufferId)) return; @@ -247,8 +231,7 @@ void BufferViewConfig::addBuffer(const BufferId &bufferId, int pos) emit configChanged(); } - -void BufferViewConfig::moveBuffer(const BufferId &bufferId, int pos) +void BufferViewConfig::moveBuffer(const BufferId& bufferId, int pos) { if (!_buffers.contains(bufferId)) return; @@ -264,8 +247,7 @@ void BufferViewConfig::moveBuffer(const BufferId &bufferId, int pos) emit configChanged(); } - -void BufferViewConfig::removeBuffer(const BufferId &bufferId) +void BufferViewConfig::removeBuffer(const BufferId& bufferId) { if (_buffers.contains(bufferId)) _buffers.removeAt(_buffers.indexOf(bufferId)); @@ -279,8 +261,7 @@ void BufferViewConfig::removeBuffer(const BufferId &bufferId) emit configChanged(); } - -void BufferViewConfig::removeBufferPermanently(const BufferId &bufferId) +void BufferViewConfig::removeBufferPermanently(const BufferId& bufferId) { if (_buffers.contains(bufferId)) _buffers.removeAt(_buffers.indexOf(bufferId)); diff --git a/src/common/bufferviewconfig.h b/src/common/bufferviewconfig.h index 0390ddb6..2d803de1 100644 --- a/src/common/bufferviewconfig.h +++ b/src/common/bufferviewconfig.h @@ -22,9 +22,8 @@ #include "common-export.h" -#include "syncableobject.h" - #include "bufferinfo.h" +#include "syncableobject.h" #include "types.h" class COMMON_EXPORT BufferViewConfig : public SyncableObject @@ -43,18 +42,18 @@ class COMMON_EXPORT BufferViewConfig : public SyncableObject Q_PROPERTY(int minimumActivity READ minimumActivity WRITE setMinimumActivity) Q_PROPERTY(bool showSearch READ showSearch WRITE setShowSearch) -public : - BufferViewConfig(int bufferViewId, QObject *parent = nullptr); - BufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent = nullptr); +public: + BufferViewConfig(int bufferViewId, QObject* parent = nullptr); + BufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent = nullptr); public slots: inline int bufferViewId() const { return _bufferViewId; } - inline const QString &bufferViewName() const { return _bufferViewName; } - void setBufferViewName(const QString &bufferViewName); + inline const QString& bufferViewName() const { return _bufferViewName; } + void setBufferViewName(const QString& bufferViewName); - inline const NetworkId &networkId() const { return _networkId; } - void setNetworkId(const NetworkId &networkId); + inline const NetworkId& networkId() const { return _networkId; } + void setNetworkId(const NetworkId& networkId); inline bool addNewBuffersAutomatically() const { return _addNewBuffersAutomatically; } void setAddNewBuffersAutomatically(bool addNewBuffersAutomatically); @@ -80,69 +79,67 @@ public slots: inline bool showSearch() const { return _showSearch; } void setShowSearch(bool showSearch); - virtual inline void requestSetBufferViewName(const QString &bufferViewName) { REQUEST(ARG(bufferViewName)) } + virtual inline void requestSetBufferViewName(const QString& bufferViewName) { REQUEST(ARG(bufferViewName)) } - const QList &bufferList() const { return _buffers; } - const QSet &removedBuffers() const { return _removedBuffers; } - const QSet &temporarilyRemovedBuffers() const { return _temporarilyRemovedBuffers; } + const QList& bufferList() const { return _buffers; } + const QSet& removedBuffers() const { return _removedBuffers; } + const QSet& temporarilyRemovedBuffers() const { return _temporarilyRemovedBuffers; } QVariantList initBufferList() const; - void initSetBufferList(const QVariantList &buffers); - void initSetBufferList(const QList &buffers); + void initSetBufferList(const QVariantList& buffers); + void initSetBufferList(const QList& buffers); QVariantList initRemovedBuffers() const; - void initSetRemovedBuffers(const QVariantList &buffers); + void initSetRemovedBuffers(const QVariantList& buffers); QVariantList initTemporarilyRemovedBuffers() const; - void initSetTemporarilyRemovedBuffers(const QVariantList &buffers); - - void addBuffer(const BufferId &bufferId, int pos); - virtual inline void requestAddBuffer(const BufferId &bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) } - void moveBuffer(const BufferId &bufferId, int pos); - virtual inline void requestMoveBuffer(const BufferId &bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) } - void removeBuffer(const BufferId &bufferId); - virtual inline void requestRemoveBuffer(const BufferId &bufferId) { REQUEST(ARG(bufferId)) } - void removeBufferPermanently(const BufferId &bufferId); - virtual inline void requestRemoveBufferPermanently(const BufferId &bufferId) { REQUEST(ARG(bufferId)) } - -signals: - void bufferViewNameSet(const QString &bufferViewName); // invalidate + void initSetTemporarilyRemovedBuffers(const QVariantList& buffers); + + void addBuffer(const BufferId& bufferId, int pos); + virtual inline void requestAddBuffer(const BufferId& bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) } + void moveBuffer(const BufferId& bufferId, int pos); + virtual inline void requestMoveBuffer(const BufferId& bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) } + void removeBuffer(const BufferId& bufferId); + virtual inline void requestRemoveBuffer(const BufferId& bufferId) { REQUEST(ARG(bufferId)) } + void removeBufferPermanently(const BufferId& bufferId); + virtual inline void requestRemoveBufferPermanently(const BufferId& bufferId){REQUEST(ARG(bufferId))} + + signals : void bufferViewNameSet(const QString& bufferViewName); // invalidate void configChanged(); - void networkIdSet(const NetworkId &networkId); -// void addNewBuffersAutomaticallySet(bool addNewBuffersAutomatically); // invalidate -// void sortAlphabeticallySet(bool sortAlphabetically); // invalidate -// // void disableDecorationSet(bool disableDecoration); // invalidate -// void allowedBufferTypesSet(int allowedBufferTypes); // invalidate -// void minimumActivitySet(int activity); // invalidate -// void hideInactiveBuffersSet(bool hideInactiveBuffers); // invalidate - void bufferListSet(); // invalidate - - void bufferAdded(const BufferId &bufferId, int pos); -// void addBufferRequested(const BufferId &bufferId, int pos); - void bufferMoved(const BufferId &bufferId, int pos); -// void moveBufferRequested(const BufferId &bufferId, int pos); - void bufferRemoved(const BufferId &bufferId); - void bufferPermanentlyRemoved(const BufferId &bufferId); -// void removeBufferRequested(const BufferId &bufferId); -// void removeBufferPermanentlyRequested(const BufferId &bufferId); - -// void setBufferViewNameRequested(const QString &bufferViewName); + void networkIdSet(const NetworkId& networkId); + // void addNewBuffersAutomaticallySet(bool addNewBuffersAutomatically); // invalidate + // void sortAlphabeticallySet(bool sortAlphabetically); // invalidate + // // void disableDecorationSet(bool disableDecoration); // invalidate + // void allowedBufferTypesSet(int allowedBufferTypes); // invalidate + // void minimumActivitySet(int activity); // invalidate + // void hideInactiveBuffersSet(bool hideInactiveBuffers); // invalidate + void bufferListSet(); // invalidate + + void bufferAdded(const BufferId& bufferId, int pos); + // void addBufferRequested(const BufferId &bufferId, int pos); + void bufferMoved(const BufferId& bufferId, int pos); + // void moveBufferRequested(const BufferId &bufferId, int pos); + void bufferRemoved(const BufferId& bufferId); + void bufferPermanentlyRemoved(const BufferId& bufferId); + // void removeBufferRequested(const BufferId &bufferId); + // void removeBufferPermanentlyRequested(const BufferId &bufferId); + + // void setBufferViewNameRequested(const QString &bufferViewName); private: - int _bufferViewId = 0; ///< ID of the associated BufferView - QString _bufferViewName = {}; ///< Display name of the associated BufferView - NetworkId _networkId = {}; ///< Network ID this buffer belongs to - - bool _addNewBuffersAutomatically = true; ///< Automatically add new buffers when created - bool _sortAlphabetically = true; ///< Sort buffers alphabetically - bool _hideInactiveBuffers = false; ///< Hide buffers without activity - bool _hideInactiveNetworks = false; ///< Hide networks without activity - bool _disableDecoration = false; ///< Disable buffer decoration (not fully implemented) + int _bufferViewId = 0; ///< ID of the associated BufferView + QString _bufferViewName = {}; ///< Display name of the associated BufferView + NetworkId _networkId = {}; ///< Network ID this buffer belongs to + + bool _addNewBuffersAutomatically = true; ///< Automatically add new buffers when created + bool _sortAlphabetically = true; ///< Sort buffers alphabetically + bool _hideInactiveBuffers = false; ///< Hide buffers without activity + bool _hideInactiveNetworks = false; ///< Hide networks without activity + bool _disableDecoration = false; ///< Disable buffer decoration (not fully implemented) /// Buffer types allowed within this view - int _allowedBufferTypes = (BufferInfo::StatusBuffer | BufferInfo::ChannelBuffer - | BufferInfo::QueryBuffer | BufferInfo::GroupBuffer); - int _minimumActivity = 0; ///< Minimum activity for a buffer to show - bool _showSearch = false; ///< Persistently show the buffer search UI + int _allowedBufferTypes = (BufferInfo::StatusBuffer | BufferInfo::ChannelBuffer | BufferInfo::QueryBuffer | BufferInfo::GroupBuffer); + int _minimumActivity = 0; ///< Minimum activity for a buffer to show + bool _showSearch = false; ///< Persistently show the buffer search UI QList _buffers; QSet _removedBuffers; diff --git a/src/common/bufferviewmanager.cpp b/src/common/bufferviewmanager.cpp index 2287dda1..89ba596f 100644 --- a/src/common/bufferviewmanager.cpp +++ b/src/common/bufferviewmanager.cpp @@ -23,15 +23,14 @@ #include "bufferviewconfig.h" #include "signalproxy.h" -BufferViewManager::BufferViewManager(SignalProxy *proxy, QObject *parent) - : SyncableObject(parent), - _proxy(proxy) +BufferViewManager::BufferViewManager(SignalProxy* proxy, QObject* parent) + : SyncableObject(parent) + , _proxy(proxy) { _proxy->synchronize(this); } - -BufferViewConfig *BufferViewManager::bufferViewConfig(int bufferViewId) const +BufferViewConfig* BufferViewManager::bufferViewConfig(int bufferViewId) const { if (_bufferViewConfigs.contains(bufferViewId)) return _bufferViewConfigs[bufferViewId]; @@ -39,13 +38,11 @@ BufferViewConfig *BufferViewManager::bufferViewConfig(int bufferViewId) const return nullptr; } - -BufferViewConfig *BufferViewManager::bufferViewConfigFactory(int bufferViewConfigId) +BufferViewConfig* BufferViewManager::bufferViewConfigFactory(int bufferViewConfigId) { return new BufferViewConfig(bufferViewConfigId, this); } - void BufferViewManager::addBufferViewConfig(int bufferViewConfigId) { if (_bufferViewConfigs.contains(bufferViewConfigId)) { @@ -55,8 +52,7 @@ void BufferViewManager::addBufferViewConfig(int bufferViewConfigId) addBufferViewConfig(bufferViewConfigFactory(bufferViewConfigId)); } - -void BufferViewManager::addBufferViewConfig(BufferViewConfig *config) +void BufferViewManager::addBufferViewConfig(BufferViewConfig* config) { if (_bufferViewConfigs.contains(config->bufferViewId())) { delete config; @@ -70,7 +66,6 @@ void BufferViewManager::addBufferViewConfig(BufferViewConfig *config) emit bufferViewConfigAdded(bufferViewId); } - void BufferViewManager::deleteBufferViewConfig(int bufferViewConfigId) { if (!_bufferViewConfigs.contains(bufferViewConfigId)) @@ -82,7 +77,6 @@ void BufferViewManager::deleteBufferViewConfig(int bufferViewConfigId) emit bufferViewConfigDeleted(bufferViewConfigId); } - QVariantList BufferViewManager::initBufferViewIds() const { QVariantList bufferViewIds; @@ -95,10 +89,9 @@ QVariantList BufferViewManager::initBufferViewIds() const return bufferViewIds; } - void BufferViewManager::initSetBufferViewIds(const QVariantList bufferViewIds) { - for (auto &&id : bufferViewIds) { + for (auto&& id : bufferViewIds) { addBufferViewConfig(id.value()); } } diff --git a/src/common/bufferviewmanager.h b/src/common/bufferviewmanager.h index c066d77d..9d5eba61 100644 --- a/src/common/bufferviewmanager.h +++ b/src/common/bufferviewmanager.h @@ -22,10 +22,10 @@ #include "common-export.h" -#include "syncableobject.h" - -#include #include +#include + +#include "syncableobject.h" class BufferViewConfig; class SignalProxy; @@ -36,10 +36,10 @@ class COMMON_EXPORT BufferViewManager : public SyncableObject SYNCABLE_OBJECT public: - BufferViewManager(SignalProxy *proxy, QObject *parent = nullptr); + BufferViewManager(SignalProxy* proxy, QObject* parent = nullptr); - inline QList bufferViewConfigs() const { return _bufferViewConfigs.values(); } - BufferViewConfig *bufferViewConfig(int bufferViewId) const; + inline QList bufferViewConfigs() const { return _bufferViewConfigs.values(); } + BufferViewConfig* bufferViewConfig(int bufferViewId) const; public slots: QVariantList initBufferViewIds() const; @@ -48,27 +48,26 @@ public slots: void addBufferViewConfig(int bufferViewConfigId); void deleteBufferViewConfig(int bufferViewConfigId); - virtual inline void requestCreateBufferView(const QVariantMap &properties) { REQUEST(ARG(properties)) } - virtual inline void requestCreateBufferViews(const QVariantList &properties) { REQUEST(ARG(properties)) } + virtual inline void requestCreateBufferView(const QVariantMap& properties) { REQUEST(ARG(properties)) } + virtual inline void requestCreateBufferViews(const QVariantList& properties) { REQUEST(ARG(properties)) } virtual inline void requestDeleteBufferView(int bufferViewId) { REQUEST(ARG(bufferViewId)) } - virtual inline void requestDeleteBufferViews(const QVariantList &bufferViews) { REQUEST(ARG(bufferViews)) } + virtual inline void requestDeleteBufferViews(const QVariantList& bufferViews) { REQUEST(ARG(bufferViews)) } -signals: - void bufferViewConfigAdded(int bufferViewConfigId); + signals : void bufferViewConfigAdded(int bufferViewConfigId); void bufferViewConfigDeleted(int bufferViewConfigId); -// void createBufferViewRequested(const QVariantMap &properties); -// void createBufferViewsRequested(const QVariantList &properties); -// void deleteBufferViewRequested(int bufferViewId); -// void deleteBufferViewsRequested(const QVariantList &bufferViews); + // void createBufferViewRequested(const QVariantMap &properties); + // void createBufferViewsRequested(const QVariantList &properties); + // void deleteBufferViewRequested(int bufferViewId); + // void deleteBufferViewsRequested(const QVariantList &bufferViews); protected: - using BufferViewConfigHash = QHash; - inline const BufferViewConfigHash &bufferViewConfigHash() { return _bufferViewConfigs; } - virtual BufferViewConfig *bufferViewConfigFactory(int bufferViewConfigId); + using BufferViewConfigHash = QHash; + inline const BufferViewConfigHash& bufferViewConfigHash() { return _bufferViewConfigs; } + virtual BufferViewConfig* bufferViewConfigFactory(int bufferViewConfigId); - void addBufferViewConfig(BufferViewConfig *config); + void addBufferViewConfig(BufferViewConfig* config); private: BufferViewConfigHash _bufferViewConfigs; - SignalProxy *_proxy; + SignalProxy* _proxy; }; diff --git a/src/common/compressor.cpp b/src/common/compressor.cpp index 816f26c8..df08f93d 100644 --- a/src/common/compressor.cpp +++ b/src/common/compressor.cpp @@ -23,15 +23,15 @@ #include #include -const int maxBufferSize = 64 * 1024 * 1024; // protect us from zip bombs -const int ioBufferSize = 64 * 1024; // chunk size for inflate/deflate; should not be too large as we preallocate that space! - -Compressor::Compressor(QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent) - : QObject(parent), - _socket(socket), - _level(level), - _inflater(nullptr), - _deflater(nullptr) +const int maxBufferSize = 64 * 1024 * 1024; // protect us from zip bombs +const int ioBufferSize = 64 * 1024; // chunk size for inflate/deflate; should not be too large as we preallocate that space! + +Compressor::Compressor(QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent) + : QObject(parent) + , _socket(socket) + , _level(level) + , _inflater(nullptr) + , _deflater(nullptr) { connect(socket, &QIODevice::readyRead, this, &Compressor::readData); @@ -51,7 +51,6 @@ Compressor::Compressor(QTcpSocket *socket, Compressor::CompressionLevel level, Q QTimer::singleShot(0, this, &Compressor::readData); } - Compressor::~Compressor() { // release resources allocated by zlib @@ -65,19 +64,18 @@ Compressor::~Compressor() } } - bool Compressor::initStreams() { int zlevel; - switch(compressionLevel()) { - case BestCompression: - zlevel = 9; - break; - case BestSpeed: - zlevel = 1; - break; - default: - zlevel = Z_DEFAULT_COMPRESSION; + switch (compressionLevel()) { + case BestCompression: + zlevel = 9; + break; + case BestSpeed: + zlevel = 1; + break; + default: + zlevel = Z_DEFAULT_COMPRESSION; } _inflater = new z_stream; @@ -94,23 +92,20 @@ bool Compressor::initStreams() return false; } - _inputBuffer.reserve(ioBufferSize); // pre-allocate space - _outputBuffer.resize(ioBufferSize); // not a typo; we never change the size of this buffer anyway (we *do* for _inputBuffer!) + _inputBuffer.reserve(ioBufferSize); // pre-allocate space + _outputBuffer.resize(ioBufferSize); // not a typo; we never change the size of this buffer anyway (we *do* for _inputBuffer!) qDebug() << "Enabling compression..."; return true; } - - qint64 Compressor::bytesAvailable() const { return _readBuffer.size(); } - -qint64 Compressor::read(char *data, qint64 maxSize) +qint64 Compressor::read(char* data, qint64 maxSize) { if (maxSize <= 0) maxSize = _readBuffer.size(); @@ -131,11 +126,10 @@ qint64 Compressor::read(char *data, qint64 maxSize) return n; } - // The usual usage pattern is to write a blocksize first, followed by the actual data. // By setting NoFlush, one can indicate that the write buffer should not immediately be // written, which should make things a bit more efficient. -qint64 Compressor::write(const char *data, qint64 count, WriteBufferHint flush) +qint64 Compressor::write(const char* data, qint64 count, WriteBufferHint flush) { int pos = _writeBuffer.size(); _writeBuffer.resize(pos + count); @@ -147,11 +141,10 @@ qint64 Compressor::write(const char *data, qint64 count, WriteBufferHint flush) return count; } - void Compressor::readData() { // don't try to read more data if we're already closing - if (_socket->state() != QAbstractSocket::ConnectedState) + if (_socket->state() != QAbstractSocket::ConnectedState) return; if (!_socket->bytesAvailable() || _readBuffer.size() >= maxBufferSize) @@ -173,17 +166,17 @@ void Compressor::readData() _readBuffer.resize(_readBuffer.size() + ioBufferSize); _inputBuffer.append(_socket->read(ioBufferSize - _inputBuffer.size())); - _inflater->next_in = reinterpret_cast(_inputBuffer.data()); + _inflater->next_in = reinterpret_cast(_inputBuffer.data()); _inflater->avail_in = _inputBuffer.size(); - _inflater->next_out = reinterpret_cast(_readBuffer.data() + _readBuffer.size() - ioBufferSize); + _inflater->next_out = reinterpret_cast(_readBuffer.data() + _readBuffer.size() - ioBufferSize); _inflater->avail_out = ioBufferSize; - const unsigned char *orig_out = _inflater->next_out; // so we see if we have actually produced any output + const unsigned char* orig_out = _inflater->next_out; // so we see if we have actually produced any output - int status = inflate(_inflater, Z_SYNC_FLUSH); // get as much data as possible + int status = inflate(_inflater, Z_SYNC_FLUSH); // get as much data as possible // adjust input and output buffers - _readBuffer.resize(_inflater->next_out - reinterpret_cast(_readBuffer.data())); + _readBuffer.resize(_inflater->next_out - reinterpret_cast(_readBuffer.data())); if (_inflater->avail_in > 0) memmove(_inputBuffer.data(), _inflater->next_in, _inflater->avail_in); _inputBuffer.resize(_inflater->avail_in); @@ -191,29 +184,28 @@ void Compressor::readData() if (_inflater->next_out != orig_out) emit readyRead(); - switch(status) { - case Z_NEED_DICT: - case Z_DATA_ERROR: - case Z_MEM_ERROR: - case Z_STREAM_ERROR: - qWarning() << "Error while decompressing stream:" << status; - emit error(StreamError); - return; - case Z_BUF_ERROR: - // means that we need more input to continue, so this is not an actual error - return; - case Z_STREAM_END: - qWarning() << "Reached end of zlib stream!"; // this should really never happen - return; - default: - // just try to get more out of the stream - break; + switch (status) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: + case Z_STREAM_ERROR: + qWarning() << "Error while decompressing stream:" << status; + emit error(StreamError); + return; + case Z_BUF_ERROR: + // means that we need more input to continue, so this is not an actual error + return; + case Z_STREAM_END: + qWarning() << "Reached end of zlib stream!"; // this should really never happen + return; + default: + // just try to get more out of the stream + break; } } - //qDebug() << "inflate in:" << _inflater->total_in << "out:" << _inflater->total_out << "ratio:" << (double)_inflater->total_in/_inflater->total_out; + // qDebug() << "inflate in:" << _inflater->total_in << "out:" << _inflater->total_out << "ratio:" << (double)_inflater->total_in/_inflater->total_out; } - void Compressor::writeData() { if (compressionLevel() == NoCompression) { @@ -222,12 +214,12 @@ void Compressor::writeData() return; } - _deflater->next_in = reinterpret_cast(_writeBuffer.data()); + _deflater->next_in = reinterpret_cast(_writeBuffer.data()); _deflater->avail_in = _writeBuffer.size(); int status; do { - _deflater->next_out = reinterpret_cast(_outputBuffer.data()); + _deflater->next_out = reinterpret_cast(_outputBuffer.data()); _deflater->avail_out = ioBufferSize; status = deflate(_deflater, Z_PARTIAL_FLUSH); if (status != Z_OK && status != Z_BUF_ERROR) { @@ -237,14 +229,14 @@ void Compressor::writeData() } if (_deflater->avail_out == static_cast(ioBufferSize)) - continue; // nothing to write here + continue; // nothing to write here if (!_socket->write(_outputBuffer.constData(), ioBufferSize - _deflater->avail_out)) { qWarning() << "Error while writing to socket:" << _socket->errorString(); emit error(DeviceError); return; } - } while (_deflater->avail_out == 0); // the output buffer being full is the only reason we should have to loop here! + } while (_deflater->avail_out == 0); // the output buffer being full is the only reason we should have to loop here! if (_deflater->avail_in > 0) { qWarning() << "Oops, something weird happened: data still remaining in write buffer!"; @@ -253,10 +245,9 @@ void Compressor::writeData() _writeBuffer.resize(0); - //qDebug() << "deflate in:" << _deflater->total_in << "out:" << _deflater->total_out << "ratio:" << (double)_deflater->total_out/_deflater->total_in; + // qDebug() << "deflate in:" << _deflater->total_in << "out:" << _deflater->total_out << "ratio:" << (double)_deflater->total_out/_deflater->total_in; } - void Compressor::flush() { if (compressionLevel() == NoCompression && _socket->state() == QAbstractSocket::ConnectedState) diff --git a/src/common/compressor.h b/src/common/compressor.h index 37d951de..7ec8889d 100644 --- a/src/common/compressor.h +++ b/src/common/compressor.h @@ -20,10 +20,10 @@ #pragma once -#include - #include +#include + class QTcpSocket; class Compressor : public QObject @@ -31,33 +31,36 @@ class Compressor : public QObject Q_OBJECT public: - enum CompressionLevel { + enum CompressionLevel + { NoCompression, DefaultCompression, BestCompression, BestSpeed }; - enum Error { + enum Error + { NoError, StreamError, DeviceError }; - enum WriteBufferHint { + enum WriteBufferHint + { NoFlush, Flush }; - Compressor(QTcpSocket *socket, CompressionLevel level, QObject *parent = nullptr); + Compressor(QTcpSocket* socket, CompressionLevel level, QObject* parent = nullptr); ~Compressor() override; CompressionLevel compressionLevel() const { return _level; } qint64 bytesAvailable() const; - qint64 read(char *data, qint64 maxSize); - qint64 write(const char *data, qint64 count, WriteBufferHint flush = Flush); + qint64 read(char* data, qint64 maxSize); + qint64 write(const char* data, qint64 count, WriteBufferHint flush = Flush); void flush(); @@ -73,7 +76,7 @@ private: void writeData(); private: - QTcpSocket *_socket; + QTcpSocket* _socket; CompressionLevel _level; QByteArray _readBuffer; diff --git a/src/common/coreinfo.cpp b/src/common/coreinfo.cpp index d4339d13..5e8a78e1 100644 --- a/src/common/coreinfo.cpp +++ b/src/common/coreinfo.cpp @@ -20,14 +20,16 @@ #include "coreinfo.h" -CoreInfo::CoreInfo(QObject *parent) : SyncableObject(parent) {} +CoreInfo::CoreInfo(QObject* parent) + : SyncableObject(parent) +{} QVariantMap CoreInfo::coreData() const { return _coreData; } -void CoreInfo::setCoreData(const QVariantMap &coreData) +void CoreInfo::setCoreData(const QVariantMap& coreData) { _coreData = coreData; SYNC(ARG(coreData)); diff --git a/src/common/coreinfo.h b/src/common/coreinfo.h index 17db3cb1..54a45a68 100644 --- a/src/common/coreinfo.h +++ b/src/common/coreinfo.h @@ -36,8 +36,8 @@ class COMMON_EXPORT CoreInfo : public SyncableObject Q_PROPERTY(QVariantMap coreData READ coreData WRITE setCoreData) public: - explicit CoreInfo(QObject *parent = nullptr); - inline QVariant &at(const QString &key) { return _coreData[key]; } + explicit CoreInfo(QObject* parent = nullptr); + inline QVariant& at(const QString& key) { return _coreData[key]; } void setConnectedClientData(int, QVariantList); @@ -54,7 +54,7 @@ signals: public slots: QVariantMap coreData() const; - void setCoreData(const QVariantMap &); + void setCoreData(const QVariantMap&); private: QVariantMap _coreData; diff --git a/src/common/ctcpevent.cpp b/src/common/ctcpevent.cpp index c4ca95fb..fab8c8b4 100644 --- a/src/common/ctcpevent.cpp +++ b/src/common/ctcpevent.cpp @@ -20,7 +20,7 @@ #include "ctcpevent.h" -Event *CtcpEvent::create(EventManager::EventType type, QVariantMap &map, Network *network) +Event* CtcpEvent::create(EventManager::EventType type, QVariantMap& map, Network* network) { if (type == EventManager::CtcpEvent || type == EventManager::CtcpEventFlush) return new CtcpEvent(type, map, network); @@ -28,8 +28,7 @@ Event *CtcpEvent::create(EventManager::EventType type, QVariantMap &map, Network return nullptr; } - -CtcpEvent::CtcpEvent(EventManager::EventType type, QVariantMap &map, Network *network) +CtcpEvent::CtcpEvent(EventManager::EventType type, QVariantMap& map, Network* network) : IrcEvent(type, map, network) { _ctcpType = static_cast(map.take("ctcpType").toInt()); @@ -40,8 +39,7 @@ CtcpEvent::CtcpEvent(EventManager::EventType type, QVariantMap &map, Network *ne _uuid = map.take("uuid").toString(); } - -void CtcpEvent::toVariantMap(QVariantMap &map) const +void CtcpEvent::toVariantMap(QVariantMap& map) const { IrcEvent::toVariantMap(map); map["ctcpType"] = ctcpType(); diff --git a/src/common/ctcpevent.h b/src/common/ctcpevent.h index f9d7f437..ef2674d2 100644 --- a/src/common/ctcpevent.h +++ b/src/common/ctcpevent.h @@ -22,70 +22,73 @@ #include "common-export.h" -#include "ircevent.h" +#include #include -#include + +#include "ircevent.h" class COMMON_EXPORT CtcpEvent : public IrcEvent { public: - enum CtcpType { + enum CtcpType + { Query, Reply }; - explicit CtcpEvent(EventManager::EventType type, Network *network, const QString &prefix, QString target, - CtcpType ctcpType, QString ctcpCmd, QString param, - const QDateTime ×tamp = QDateTime(), const QUuid &uuid = QUuid()) - : IrcEvent(type, network, prefix), - _ctcpType(ctcpType), - _ctcpCmd(std::move(ctcpCmd)), - _target(std::move(target)), - _param(std::move(param)), - _uuid(uuid) + explicit CtcpEvent(EventManager::EventType type, + Network* network, + const QString& prefix, + QString target, + CtcpType ctcpType, + QString ctcpCmd, + QString param, + const QDateTime& timestamp = QDateTime(), + const QUuid& uuid = QUuid()) + : IrcEvent(type, network, prefix) + , _ctcpType(ctcpType) + , _ctcpCmd(std::move(ctcpCmd)) + , _target(std::move(target)) + , _param(std::move(param)) + , _uuid(uuid) { setTimestamp(timestamp); } - inline CtcpType ctcpType() const { return _ctcpType; } inline void setCtcpType(CtcpType type) { _ctcpType = type; } inline QString ctcpCmd() const { return _ctcpCmd; } - inline void setCtcpCmd(const QString &ctcpCmd) { _ctcpCmd = ctcpCmd; } + inline void setCtcpCmd(const QString& ctcpCmd) { _ctcpCmd = ctcpCmd; } inline QString target() const { return _target; } - inline void setTarget(const QString &target) { _target = target; } + inline void setTarget(const QString& target) { _target = target; } inline QString param() const { return _param; } - inline void setParam(const QString ¶m) { _param = param; } + inline void setParam(const QString& param) { _param = param; } inline QString reply() const { return _reply; } - inline void setReply(const QString &reply) { _reply = reply; } + inline void setReply(const QString& reply) { _reply = reply; } inline QUuid uuid() const { return _uuid; } - inline void setUuid(const QUuid &uuid) { _uuid = uuid; } + inline void setUuid(const QUuid& uuid) { _uuid = uuid; } - static Event *create(EventManager::EventType type, QVariantMap &map, Network *network); + static Event* create(EventManager::EventType type, QVariantMap& map, Network* network); protected: - explicit CtcpEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit CtcpEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "CtcpEvent"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); - dbg << ", prefix = " << qPrintable(prefix()) - << ", target = " << qPrintable(target()) - << ", ctcptype = " << (ctcpType() == Query ? "query" : "reply") - << ", cmd = " << qPrintable(ctcpCmd()) - << ", param = " << qPrintable(param()) - << ", reply = " << qPrintable(reply()); + dbg << ", prefix = " << qPrintable(prefix()) << ", target = " << qPrintable(target()) + << ", ctcptype = " << (ctcpType() == Query ? "query" : "reply") << ", cmd = " << qPrintable(ctcpCmd()) + << ", param = " << qPrintable(param()) << ", reply = " << qPrintable(reply()); } - private: CtcpType _ctcpType; QString _ctcpCmd; diff --git a/src/common/dccconfig.cpp b/src/common/dccconfig.cpp index 7767735c..ae9a0e00 100644 --- a/src/common/dccconfig.cpp +++ b/src/common/dccconfig.cpp @@ -24,7 +24,7 @@ #include "types.h" -DccConfig::DccConfig(QObject *parent) +DccConfig::DccConfig(QObject* parent) : SyncableObject(parent) { static auto regTypes = []() -> bool { @@ -38,8 +38,7 @@ DccConfig::DccConfig(QObject *parent) setAllowClientUpdates(true); } - -DccConfig &DccConfig::operator=(const DccConfig &other) +DccConfig& DccConfig::operator=(const DccConfig& other) { if (this == &other) return *this; @@ -55,8 +54,7 @@ DccConfig &DccConfig::operator=(const DccConfig &other) return *this; } - -bool DccConfig::operator==(const DccConfig &other) +bool DccConfig::operator==(const DccConfig& other) { // NOTE: We don't compare the SyncableObject attributes (isInitialized, clientUpdatesAllowed()) static auto propCount = staticMetaObject.propertyCount(); @@ -70,126 +68,106 @@ bool DccConfig::operator==(const DccConfig &other) return false; } else if (property(propName) != other.property(propName)) - return false; + return false; } return true; } - bool DccConfig::isDccEnabled() const { return _dccEnabled; } - void DccConfig::setDccEnabled(bool enabled) { _dccEnabled = enabled; } - QHostAddress DccConfig::outgoingIp() const { return _outgoingIp; } - -void DccConfig::setOutgoingIp(const QHostAddress &outgoingIp) +void DccConfig::setOutgoingIp(const QHostAddress& outgoingIp) { _outgoingIp = outgoingIp; } - DccConfig::IpDetectionMode DccConfig::ipDetectionMode() const { return _ipDetectionMode; } - void DccConfig::setIpDetectionMode(DccConfig::IpDetectionMode detectionMode) { _ipDetectionMode = detectionMode; } - DccConfig::PortSelectionMode DccConfig::portSelectionMode() const { return _portSelectionMode; } - void DccConfig::setPortSelectionMode(DccConfig::PortSelectionMode portSelectionMode) { _portSelectionMode = portSelectionMode; } - quint16 DccConfig::minPort() const { return _minPort; } - void DccConfig::setMinPort(quint16 port) { _minPort = port; } - quint16 DccConfig::maxPort() const { return _maxPort; } - void DccConfig::setMaxPort(quint16 port) { _maxPort = port; } - int DccConfig::chunkSize() const { return _chunkSize; } - void DccConfig::setChunkSize(int chunkSize) { _chunkSize = chunkSize; } - int DccConfig::sendTimeout() const { return _sendTimeout; } - void DccConfig::setSendTimeout(int timeout) { _sendTimeout = timeout; } - bool DccConfig::usePassiveDcc() const { return _usePassiveDcc; } - void DccConfig::setUsePassiveDcc(bool use) { _usePassiveDcc = use; } - bool DccConfig::useFastSend() const { return _useFastSend; } - void DccConfig::setUseFastSend(bool use) { _useFastSend = use; diff --git a/src/common/dccconfig.h b/src/common/dccconfig.h index f919dcc9..e35400a3 100644 --- a/src/common/dccconfig.h +++ b/src/common/dccconfig.h @@ -62,7 +62,8 @@ public: /** * Mode for detecting the outgoing IP */ - enum class IpDetectionMode : quint8 { + enum class IpDetectionMode : quint8 + { Automatic, ///< Automatic detection (network socket or USERHOST) Manual, ///< Manually specified IP }; @@ -71,9 +72,10 @@ public: /** * Mode for selecting the port range for DCC */ - enum class PortSelectionMode : quint8 { - Automatic, ///< Automatic port selection - Manual, ///< Manually specified port range + enum class PortSelectionMode : quint8 + { + Automatic, ///< Automatic port selection + Manual, ///< Manually specified port range }; Q_ENUMS(PortSelectionMode) @@ -84,7 +86,7 @@ public: * * @param[in] parent QObject parent */ - DccConfig(QObject *parent = nullptr); + DccConfig(QObject* parent = nullptr); /** * Assignment operator. @@ -94,7 +96,7 @@ public: * @param[in] other Right-hand side instance * @returns The updated instance */ - DccConfig &operator=(const DccConfig &other); + DccConfig& operator=(const DccConfig& other); /** * Equality operator. @@ -104,7 +106,7 @@ public: * @param[in] other Right-hand side instance * @returns Whether the two instances have equal properties */ - bool operator==(const DccConfig &other); + bool operator==(const DccConfig& other); /// @name Getters /// @{ @@ -124,7 +126,7 @@ public slots: /// @name Setters /// @{ void setDccEnabled(bool enabled); - void setOutgoingIp(const QHostAddress &outgoingIp); + void setOutgoingIp(const QHostAddress& outgoingIp); void setIpDetectionMode(DccConfig::IpDetectionMode ipDetectionMode); void setPortSelectionMode(DccConfig::PortSelectionMode portSelectionMode); void setMinPort(quint16 port); @@ -137,14 +139,14 @@ public slots: private: // The given values are used as default for both initialization and settings - bool _dccEnabled {false}; - QHostAddress _outgoingIp {QHostAddress::LocalHost}; - IpDetectionMode _ipDetectionMode {IpDetectionMode::Automatic}; - PortSelectionMode _portSelectionMode {PortSelectionMode::Automatic}; - quint16 _minPort {1024}; - quint16 _maxPort {32767}; - int _chunkSize {16}; - int _sendTimeout {180}; - bool _usePassiveDcc {false}; - bool _useFastSend {false}; + bool _dccEnabled{false}; + QHostAddress _outgoingIp{QHostAddress::LocalHost}; + IpDetectionMode _ipDetectionMode{IpDetectionMode::Automatic}; + PortSelectionMode _portSelectionMode{PortSelectionMode::Automatic}; + quint16 _minPort{1024}; + quint16 _maxPort{32767}; + int _chunkSize{16}; + int _sendTimeout{180}; + bool _usePassiveDcc{false}; + bool _useFastSend{false}; }; diff --git a/src/common/deferredptr.h b/src/common/deferredptr.h index 8e02db88..21cfcb73 100644 --- a/src/common/deferredptr.h +++ b/src/common/deferredptr.h @@ -35,15 +35,17 @@ namespace detail { * QObject should always be deleted by calling deleteLater() on them, so the event loop can * perform necessary cleanups. */ -struct DeferredDeleter { +struct DeferredDeleter +{ /// Deletes the given QObject - void operator()(QObject *object) const { + void operator()(QObject* object) const + { if (object) object->deleteLater(); } }; -} // detail +} // namespace detail /** * Unique pointer for QObjects with deferred deletion @@ -53,7 +55,6 @@ struct DeferredDeleter { template using DeferredUniquePtr = std::unique_ptr; - /** * Helper function for creating a DeferredUniquePtr * @@ -65,14 +66,13 @@ using DeferredUniquePtr = std::unique_ptr; * @param[in] args Constructor arguments * @returns A DeferredUniquePtr holding a new instance of T */ -template +template DeferredUniquePtr makeDeferredUnique(Args... args) { static_assert(std::is_base_of::value, "Type must inherit from QObject"); return DeferredUniquePtr(new T(std::forward(args)...)); } - /** * Shared pointer for QObjects with deferred deletion * @@ -81,7 +81,6 @@ DeferredUniquePtr makeDeferredUnique(Args... args) template using DeferredSharedPtr = std::shared_ptr; - /** * Helper function for creating a DeferredSharedPtr * @@ -93,7 +92,7 @@ using DeferredSharedPtr = std::shared_ptr; * @param[in] args Constructor arguments * @returns A DeferredSharedPtr holding a new instance of T */ -template +template DeferredSharedPtr makeDeferredShared(Args... args) { static_assert(std::is_base_of::value, "Type must inherit from QObject"); diff --git a/src/common/event.cpp b/src/common/event.cpp index 7341b2d0..02d3f667 100644 --- a/src/common/event.cpp +++ b/src/common/event.cpp @@ -20,18 +20,16 @@ #include "ctcpevent.h" #include "ircevent.h" -#include "networkevent.h" #include "messageevent.h" +#include "networkevent.h" #include "peer.h" #include "signalproxy.h" Event::Event(EventManager::EventType type) : _type(type) -{ -} - +{} -Event::Event(EventManager::EventType type, QVariantMap &map) +Event::Event(EventManager::EventType type, QVariantMap& map) : _type(type) { if (!map.contains("flags") || !map.contains("timestamp")) { @@ -43,18 +41,18 @@ Event::Event(EventManager::EventType type, QVariantMap &map) Q_ASSERT(SignalProxy::current()); Q_ASSERT(SignalProxy::current()->sourcePeer()); - setFlags(static_cast(map.take("flags").toInt())); // TODO sanity check? + setFlags(static_cast(map.take("flags").toInt())); // TODO sanity check? if (SignalProxy::current()->sourcePeer()->hasFeature(Quassel::Feature::LongTime)) { // timestamp is a qint64, signed rather than unsigned setTimestamp(QDateTime::fromMSecsSinceEpoch(map.take("timestamp").toLongLong())); - } else { + } + else { setTimestamp(QDateTime::fromTime_t(map.take("timestamp").toUInt())); } } - -void Event::toVariantMap(QVariantMap &map) const +void Event::toVariantMap(QVariantMap& map) const { Q_ASSERT(SignalProxy::current()); Q_ASSERT(SignalProxy::current()->targetPeer()); @@ -64,12 +62,12 @@ void Event::toVariantMap(QVariantMap &map) const if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) { // toMSecs returns a qint64, signed rather than unsigned map["timestamp"] = timestamp().toMSecsSinceEpoch(); - } else { + } + else { map["timestamp"] = timestamp().toTime_t(); } } - QVariantMap Event::toVariantMap() const { QVariantMap map; @@ -77,8 +75,7 @@ QVariantMap Event::toVariantMap() const return map; } - -Event *Event::fromVariantMap(QVariantMap &map, Network *network) +Event* Event::fromVariantMap(QVariantMap& map, Network* network) { int inttype = map.take("type").toInt(); // sanity check if we have a valid enum value @@ -93,7 +90,7 @@ Event *Event::fromVariantMap(QVariantMap &map, Network *network) auto group = static_cast(type & EventManager::EventGroupMask); - Event *e = nullptr; + Event* e = nullptr; // we use static create() functions to keep group-specific special cases in the files they belong // e.g. IrcEventRawMessage @@ -129,14 +126,12 @@ Event *Event::fromVariantMap(QVariantMap &map, Network *network) return e; } - -QDebug operator<<(QDebug dbg, Event *e) +QDebug operator<<(QDebug dbg, Event* e) { dbg.nospace() << qPrintable(e->className()) << "(" - << "type = 0x" << qPrintable(QString::number(e->type(), 16)); + << "type = 0x" << qPrintable(QString::number(e->type(), 16)); e->debugInfo(dbg); //<< ", data = " << e->data(); // we don't use data anywhere yet - dbg.nospace() << ", flags = 0x" << qPrintable(QString::number(e->flags(), 16)) - << ")"; + dbg.nospace() << ", flags = 0x" << qPrintable(QString::number(e->flags(), 16)) << ")"; return dbg.space(); } diff --git a/src/common/event.h b/src/common/event.h index b6525872..5c21f793 100644 --- a/src/common/event.h +++ b/src/common/event.h @@ -46,25 +46,25 @@ public: inline void stop() { setFlag(EventManager::Stopped); } inline bool isStopped() { return _flags.testFlag(EventManager::Stopped); } - inline void setTimestamp(const QDateTime &time) { _timestamp = time; } + inline void setTimestamp(const QDateTime& time) { _timestamp = time; } inline QDateTime timestamp() const { return _timestamp; } - //inline void setData(const QVariant &data) { _data = data; } - //inline QVariant data() const { return _data; } + // inline void setData(const QVariant &data) { _data = data; } + // inline QVariant data() const { return _data; } // call EventManager::createEvent(map) instead! - static Event *fromVariantMap(QVariantMap &map, Network *network); + static Event* fromVariantMap(QVariantMap& map, Network* network); QVariantMap toVariantMap() const; protected: virtual inline QString className() const { return "Event"; } - virtual inline void debugInfo(QDebug &dbg) const { Q_UNUSED(dbg); } + virtual inline void debugInfo(QDebug& dbg) const { Q_UNUSED(dbg); } - explicit Event(EventManager::EventType type, QVariantMap &map); + explicit Event(EventManager::EventType type, QVariantMap& map); // must only use primitive types: string, int, double, list, hash // we want to convert this to JSON in the future! - virtual void toVariantMap(QVariantMap &map) const; + virtual void toVariantMap(QVariantMap& map) const; inline void setValid(bool valid) { _valid = valid; } @@ -74,7 +74,7 @@ private: QDateTime _timestamp; bool _valid{true}; - friend COMMON_EXPORT QDebug operator<<(QDebug dbg, Event *e); + friend COMMON_EXPORT QDebug operator<<(QDebug dbg, Event* e); }; -COMMON_EXPORT QDebug operator<<(QDebug dbg, Event *e); +COMMON_EXPORT QDebug operator<<(QDebug dbg, Event* e); diff --git a/src/common/eventmanager.cpp b/src/common/eventmanager.cpp index 606356d6..6057c388 100644 --- a/src/common/eventmanager.cpp +++ b/src/common/eventmanager.cpp @@ -21,8 +21,8 @@ #include "eventmanager.h" #include -#include #include +#include #include "event.h" #include "ircevent.h" @@ -33,20 +33,19 @@ class QueuedQuasselEvent : public QEvent { public: - QueuedQuasselEvent(Event *event) - : QEvent(QEvent::User), event(event) {} - Event *event; + QueuedQuasselEvent(Event* event) + : QEvent(QEvent::User) + , event(event) + {} + Event* event; }; - // ============================================================ // EventManager // ============================================================ -EventManager::EventManager(QObject *parent) +EventManager::EventManager(QObject* parent) : QObject(parent) -{ -} - +{} QMetaEnum EventManager::eventEnum() { @@ -59,42 +58,36 @@ QMetaEnum EventManager::eventEnum() return _enum; } - -EventManager::EventType EventManager::eventTypeByName(const QString &name) +EventManager::EventType EventManager::eventTypeByName(const QString& name) { int val = eventEnum().keyToValue(name.toLatin1()); return (val == -1) ? Invalid : static_cast(val); } - -EventManager::EventType EventManager::eventGroupByName(const QString &name) +EventManager::EventType EventManager::eventGroupByName(const QString& name) { EventType type = eventTypeByName(name); return type == Invalid ? Invalid : static_cast(type & EventGroupMask); } - QString EventManager::enumName(EventType type) { return eventEnum().valueToKey(type); } - QString EventManager::enumName(int type) { return eventEnum().valueToKey(type); } - -Event *EventManager::createEvent(const QVariantMap &map) +Event* EventManager::createEvent(const QVariantMap& map) { QVariantMap m = map; - Network *net = networkById(m.take("network").toInt()); + Network* net = networkById(m.take("network").toInt()); return Event::fromVariantMap(m, net); } - /* NOTE: Registering and calling handlers works fine even if they specify a subclass of Event as their parameter. However, this most probably is a result from a reinterpret_cast somewhere deep inside Qt, so there is *no* @@ -109,20 +102,20 @@ Event *EventManager::createEvent(const QVariantMap &map) with the actual class. Possibly (optionally) using rtti... */ -int EventManager::findEventType(const QString &methodSignature_, const QString &methodPrefix) const +int EventManager::findEventType(const QString& methodSignature_, const QString& methodPrefix) const { if (!methodSignature_.startsWith(methodPrefix)) return -1; QString methodSignature = methodSignature_; - methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list - methodSignature = methodSignature.mid(methodPrefix.length()); // strip prefix + methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list + methodSignature = methodSignature.mid(methodPrefix.length()); // strip prefix int eventType = -1; // special handling for numeric IrcEvents: IrcEvent042 gets mapped to IrcEventNumeric + 42 - if (methodSignature.length() == 8+3 && methodSignature.startsWith("IrcEvent")) { + if (methodSignature.length() == 8 + 3 && methodSignature.startsWith("IrcEvent")) { int num = methodSignature.right(3).toUInt(); if (num > 0) { QString numericSig = methodSignature.left(methodSignature.length() - 3) + "Numeric"; @@ -144,8 +137,7 @@ int EventManager::findEventType(const QString &methodSignature_, const QString & return eventType; } - -void EventManager::registerObject(QObject *object, Priority priority, const QString &methodPrefix, const QString &filterPrefix) +void EventManager::registerObject(QObject* object, Priority priority, const QString& methodPrefix, const QString& filterPrefix) { for (int i = object->metaObject()->methodOffset(); i < object->metaObject()->methodCount(); i++) { QString methodSignature = object->metaObject()->method(i).methodSignature(); @@ -153,37 +145,33 @@ void EventManager::registerObject(QObject *object, Priority priority, const QStr if (eventType > 0) { Handler handler(object, i, priority); registeredHandlers()[eventType].append(handler); - //qDebug() << "Registered event handler for" << methodSignature << "in" << object; + // qDebug() << "Registered event handler for" << methodSignature << "in" << object; } eventType = findEventType(methodSignature, filterPrefix); if (eventType > 0) { Handler handler(object, i, priority); registeredFilters()[eventType].append(handler); - //qDebug() << "Registered event filterer for" << methodSignature << "in" << object; + // qDebug() << "Registered event filterer for" << methodSignature << "in" << object; } } } - -void EventManager::registerEventFilter(EventType event, QObject *object, const char *slot) +void EventManager::registerEventFilter(EventType event, QObject* object, const char* slot) { registerEventHandler(QList() << event, object, slot, NormalPriority, true); } - -void EventManager::registerEventFilter(QList events, QObject *object, const char *slot) +void EventManager::registerEventFilter(QList events, QObject* object, const char* slot) { registerEventHandler(events, object, slot, NormalPriority, true); } - -void EventManager::registerEventHandler(EventType event, QObject *object, const char *slot, Priority priority, bool isFilter) +void EventManager::registerEventHandler(EventType event, QObject* object, const char* slot, Priority priority, bool isFilter) { registerEventHandler(QList() << event, object, slot, priority, isFilter); } - -void EventManager::registerEventHandler(QList events, QObject *object, const char *slot, Priority priority, bool isFilter) +void EventManager::registerEventHandler(QList events, QObject* object, const char* slot, Priority priority, bool isFilter) { int methodIndex = object->metaObject()->indexOfMethod(slot); if (methodIndex < 0) { @@ -191,7 +179,7 @@ void EventManager::registerEventHandler(QList events, QObject *object return; } Handler handler(object, methodIndex, priority); - foreach(EventType event, events) { + foreach (EventType event, events) { if (isFilter) { registeredFilters()[event].append(handler); qDebug() << "Registered event filter for" << event << "in" << object; @@ -203,11 +191,10 @@ void EventManager::registerEventHandler(QList events, QObject *object } } - -void EventManager::postEvent(Event *event) +void EventManager::postEvent(Event* event) { if (sender() && sender()->thread() != this->thread()) { - auto *queuedEvent = new QueuedQuasselEvent(event); + auto* queuedEvent = new QueuedQuasselEvent(event); QCoreApplication::postEvent(this, queuedEvent); } else { @@ -219,18 +206,16 @@ void EventManager::postEvent(Event *event) } } - -void EventManager::customEvent(QEvent *event) +void EventManager::customEvent(QEvent* event) { if (event->type() == QEvent::User) { - auto *queuedEvent = static_cast(event); + auto* queuedEvent = static_cast(event); processEvent(queuedEvent->event); event->accept(); } } - -void EventManager::processEvent(Event *event) +void EventManager::processEvent(Event* event) { Q_ASSERT(_eventQueue.isEmpty()); dispatchEvent(event); @@ -241,24 +226,23 @@ void EventManager::processEvent(Event *event) } } - -void EventManager::dispatchEvent(Event *event) +void EventManager::dispatchEvent(Event* event) { - //qDebug() << "Dispatching" << event; + // qDebug() << "Dispatching" << event; // we try handlers from specialized to generic by masking the enum // build a list sorted by priorities that contains all eligible handlers QList handlers; - QHash filters; - QSet ignored; + QHash filters; + QSet ignored; uint type = event->type(); bool checkDupes = false; // special handling for numeric IrcEvents if ((type & ~IrcEventNumericMask) == IrcEventNumeric) { - auto *numEvent = static_cast< ::IrcEventNumeric *>(event); + auto* numEvent = static_cast<::IrcEventNumeric*>(event); if (!numEvent) qWarning() << "Invalid event type for IrcEventNumeric!"; else { @@ -284,24 +268,24 @@ void EventManager::dispatchEvent(Event *event) // now dispatch the event QList::const_iterator it; for (it = handlers.begin(); it != handlers.end() && !event->isStopped(); ++it) { - QObject *obj = it->object; + QObject* obj = it->object; - if (ignored.contains(obj)) // object has filtered the event + if (ignored.contains(obj)) // object has filtered the event continue; - if (filters.contains(obj)) { // we have a filter, so let's check if we want to deliver the event + if (filters.contains(obj)) { // we have a filter, so let's check if we want to deliver the event Handler filter = filters.value(obj); bool result = false; - void *param[] = { Q_RETURN_ARG(bool, result).data(), Q_ARG(Event *, event).data() }; + void* param[] = {Q_RETURN_ARG(bool, result).data(), Q_ARG(Event*, event).data()}; obj->qt_metacall(QMetaObject::InvokeMetaMethod, filter.methodIndex, param); if (!result) { ignored.insert(obj); - continue; // mmmh, event filter told us to not accept + continue; // mmmh, event filter told us to not accept } } // finally, deliverance! - void *param[] = { nullptr, Q_ARG(Event *, event).data() }; + void* param[] = {nullptr, Q_ARG(Event*, event).data()}; obj->qt_metacall(QMetaObject::InvokeMetaMethod, it->methodIndex, param); } @@ -309,10 +293,9 @@ void EventManager::dispatchEvent(Event *event) delete event; } - -void EventManager::insertHandlers(const QList &newHandlers, QList &existing, bool checkDupes) +void EventManager::insertHandlers(const QList& newHandlers, QList& existing, bool checkDupes) { - foreach(const Handler &handler, newHandlers) { + foreach (const Handler& handler, newHandlers) { if (existing.isEmpty()) existing.append(handler); else { @@ -336,16 +319,14 @@ void EventManager::insertHandlers(const QList &newHandlers, QList &newFilters, QHash &existing) +void EventManager::insertFilters(const QList& newFilters, QHash& existing) { - foreach(const Handler &filter, newFilters) { + foreach (const Handler& filter, newFilters) { if (!existing.contains(filter.object)) existing[filter.object] = filter; } } - QMetaEnum EventManager::_enum; diff --git a/src/common/eventmanager.h b/src/common/eventmanager.h index 0a72a70a..cd8056c2 100644 --- a/src/common/eventmanager.h +++ b/src/common/eventmanager.h @@ -35,14 +35,15 @@ class COMMON_EXPORT EventManager : public QObject Q_FLAGS(EventFlag EventFlags) Q_ENUMS(EventType) -public : - - enum RegistrationMode { +public: + enum RegistrationMode + { Prepend, Append }; - enum Priority { + enum Priority + { VeryLowPriority, LowPriority, NormalPriority, @@ -50,13 +51,14 @@ public : HighestPriority }; - enum EventFlag { - Self = 0x01, ///< Self-generated (user input) event - Fake = 0x08, ///< Ignore this in CoreSessionEventProcessor - Netsplit = 0x10, ///< Netsplit join/part, ignore on display - Backlog = 0x20, - Silent = 0x40, ///< Don't generate a MessageEvent - Stopped = 0x80 + enum EventFlag + { + Self = 0x01, ///< Self-generated (user input) event + Fake = 0x08, ///< Ignore this in CoreSessionEventProcessor + Netsplit = 0x10, ///< Netsplit join/part, ignore on display + Backlog = 0x20, + Silent = 0x40, ///< Don't generate a MessageEvent + Stopped = 0x80 }; Q_DECLARE_FLAGS(EventFlags, EventFlag) @@ -64,15 +66,16 @@ public : */ /* These values make sense! Don't change without knowing what you do! */ - enum EventType { - Invalid = 0xffffffff, - GenericEvent = 0x00000000, + enum EventType + { + Invalid = 0xffffffff, + GenericEvent = 0x00000000, // for event group handlers (handleIrcEvent() will handle all IrcEvent* enums) // event groups are specified by bits 20-24 - EventGroupMask = 0x00ff0000, + EventGroupMask = 0x00ff0000, - NetworkEvent = 0x00010000, + NetworkEvent = 0x00010000, NetworkConnecting, NetworkInitializing, NetworkInitialized, @@ -83,11 +86,11 @@ public : NetworkSplitQuit, NetworkIncoming, - IrcServerEvent = 0x00020000, + IrcServerEvent = 0x00020000, IrcServerIncoming, IrcServerParseError, - IrcEvent = 0x00030000, + IrcEvent = 0x00030000, IrcEventAuthenticate, IrcEventAccount, IrcEventAway, @@ -105,62 +108,63 @@ public : IrcEventPrivmsg, IrcEventQuit, IrcEventTopic, - IrcEventError, /// ERROR message from server + IrcEventError, /// ERROR message from server IrcEventWallops, - IrcEventRawPrivmsg, ///< Undecoded privmsg (still needs CTCP parsing) - IrcEventRawNotice, ///< Undecoded notice (still needs CTCP parsing) - IrcEventUnknown, ///< Unknown non-numeric cmd + IrcEventRawPrivmsg, ///< Undecoded privmsg (still needs CTCP parsing) + IrcEventRawNotice, ///< Undecoded notice (still needs CTCP parsing) + IrcEventUnknown, ///< Unknown non-numeric cmd - IrcEventNumeric = 0x00031000, /* needs 1000 (0x03e8) consecutive free values! */ - IrcEventNumericMask = 0x00000fff, /* for checking if an event is numeric */ + IrcEventNumeric = 0x00031000, /* needs 1000 (0x03e8) consecutive free values! */ + IrcEventNumericMask = 0x00000fff, /* for checking if an event is numeric */ - MessageEvent = 0x00040000, ///< Stringified event suitable for converting to Message + MessageEvent = 0x00040000, ///< Stringified event suitable for converting to Message - CtcpEvent = 0x00050000, + CtcpEvent = 0x00050000, CtcpEventFlush, - KeyEvent = 0x00060000 + KeyEvent = 0x00060000 }; - EventManager(QObject *parent = nullptr); + EventManager(QObject* parent = nullptr); - static EventType eventTypeByName(const QString &name); - static EventType eventGroupByName(const QString &name); + static EventType eventTypeByName(const QString& name); + static EventType eventGroupByName(const QString& name); static QString enumName(EventType type); - static QString enumName(int type); // for sanity tests + static QString enumName(int type); // for sanity tests - Event *createEvent(const QVariantMap &map); + Event* createEvent(const QVariantMap& map); public slots: - void registerObject(QObject *object, Priority priority = NormalPriority, - const QString &methodPrefix = "process", - const QString &filterPrefix = "filter"); - void registerEventHandler(EventType event, QObject *object, const char *slot, - Priority priority = NormalPriority, bool isFilter = false); - void registerEventHandler(QList events, QObject *object, const char *slot, - Priority priority = NormalPriority, bool isFilter = false); + void registerObject(QObject* object, + Priority priority = NormalPriority, + const QString& methodPrefix = "process", + const QString& filterPrefix = "filter"); + void registerEventHandler(EventType event, QObject* object, const char* slot, Priority priority = NormalPriority, bool isFilter = false); + void registerEventHandler( + QList events, QObject* object, const char* slot, Priority priority = NormalPriority, bool isFilter = false); - void registerEventFilter(EventType event, QObject *object, const char *slot); - void registerEventFilter(QList events, QObject *object, const char *slot); + void registerEventFilter(EventType event, QObject* object, const char* slot); + void registerEventFilter(QList events, QObject* object, const char* slot); //! Send an event to the registered handlers /** The EventManager takes ownership of the event and will delete it once it's processed. @param event The event to be dispatched */ - void postEvent(Event *event); + void postEvent(Event* event); protected: - virtual Network *networkById(NetworkId id) const = 0; - void customEvent(QEvent *event) override; + virtual Network* networkById(NetworkId id) const = 0; + void customEvent(QEvent* event) override; private: - struct Handler { - QObject *object; + struct Handler + { + QObject* object; int methodIndex; Priority priority; - explicit Handler(QObject *obj = nullptr, int method = 0, Priority prio = NormalPriority) + explicit Handler(QObject* obj = nullptr, int method = 0, Priority prio = NormalPriority) { object = obj; methodIndex = method; @@ -170,30 +174,29 @@ private: using HandlerHash = QHash>; - inline const HandlerHash ®isteredHandlers() const { return _registeredHandlers; } - inline HandlerHash ®isteredHandlers() { return _registeredHandlers; } + inline const HandlerHash& registeredHandlers() const { return _registeredHandlers; } + inline HandlerHash& registeredHandlers() { return _registeredHandlers; } - inline const HandlerHash ®isteredFilters() const { return _registeredFilters; } - inline HandlerHash ®isteredFilters() { return _registeredFilters; } + inline const HandlerHash& registeredFilters() const { return _registeredFilters; } + inline HandlerHash& registeredFilters() { return _registeredFilters; } //! Add handlers to an existing sorted (by priority) handler list - void insertHandlers(const QList &newHandlers, QList &existing, bool checkDupes = false); + void insertHandlers(const QList& newHandlers, QList& existing, bool checkDupes = false); //! Add filters to an existing filter hash - void insertFilters(const QList &newFilters, QHash &existing); + void insertFilters(const QList& newFilters, QHash& existing); - int findEventType(const QString &methodSignature, const QString &methodPrefix) const; + int findEventType(const QString& methodSignature, const QString& methodPrefix) const; - void processEvent(Event *event); - void dispatchEvent(Event *event); + void processEvent(Event* event); + void dispatchEvent(Event* event); //! @return the EventType enum static QMetaEnum eventEnum(); HandlerHash _registeredHandlers; HandlerHash _registeredFilters; - QList _eventQueue; + QList _eventQueue; static QMetaEnum _enum; }; - Q_DECLARE_OPERATORS_FOR_FLAGS(EventManager::EventFlags) diff --git a/src/common/expressionmatch.cpp b/src/common/expressionmatch.cpp index ae5661e1..17d08a52 100644 --- a/src/common/expressionmatch.cpp +++ b/src/common/expressionmatch.cpp @@ -27,7 +27,7 @@ #include "logmessage.h" -ExpressionMatch::ExpressionMatch(const QString &expression, MatchMode mode, bool caseSensitive) +ExpressionMatch::ExpressionMatch(const QString& expression, MatchMode mode, bool caseSensitive) { // Store the original parameters for later reference _sourceExpression = expression; @@ -41,8 +41,7 @@ ExpressionMatch::ExpressionMatch(const QString &expression, MatchMode mode, bool cacheRegEx(); } - -bool ExpressionMatch::match(const QString &string, bool matchEmpty) const +bool ExpressionMatch::match(const QString& string, bool matchEmpty) const { // Handle empty expression strings if (_sourceExpressionEmpty) { @@ -77,8 +76,7 @@ bool ExpressionMatch::match(const QString &string, bool matchEmpty) const } } - -QString ExpressionMatch::trimMultiWildcardWhitespace(const QString &originalRule) +QString ExpressionMatch::trimMultiWildcardWhitespace(const QString& originalRule) { // This gets handled in two steps: // @@ -207,10 +205,9 @@ QString ExpressionMatch::trimMultiWildcardWhitespace(const QString &originalRule break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar + << "character!"; break; } consecutiveSlashes = 0; @@ -228,10 +225,9 @@ QString ExpressionMatch::trimMultiWildcardWhitespace(const QString &originalRule } else if (consecutiveSlashes > 3) { // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar + << "character!"; break; } break; @@ -254,10 +250,8 @@ QString ExpressionMatch::trimMultiWildcardWhitespace(const QString &originalRule break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), applying newline split anyways!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), applying newline split anyways!"; break; } @@ -288,10 +282,9 @@ QString ExpressionMatch::trimMultiWildcardWhitespace(const QString &originalRule break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring " << curChar << "char escape!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring " << curChar + << "char escape!"; break; } consecutiveSlashes = 0; @@ -308,7 +301,6 @@ QString ExpressionMatch::trimMultiWildcardWhitespace(const QString &originalRule return result.trimmed(); } - void ExpressionMatch::cacheRegEx() { _matchRegExActive = false; @@ -326,8 +318,7 @@ void ExpressionMatch::cacheRegEx() // Match entire phrase, noninverted // Don't trim whitespace for phrase matching as someone might want to match on " word ", a // more-specific request than "word". - _matchRegEx = regExFactory("(?:^|\\W)" + regExEscape(_sourceExpression) + "(?:\\W|$)", - _sourceCaseSensitive); + _matchRegEx = regExFactory("(?:^|\\W)" + regExEscape(_sourceExpression) + "(?:\\W|$)", _sourceCaseSensitive); _matchRegExActive = true; break; case MatchMode::MatchMultiPhrase: @@ -342,19 +333,16 @@ void ExpressionMatch::cacheRegEx() if (_sourceExpression.startsWith("!")) { // Inverted rule: take the remainder of the string // "^" + invertComponents.at(0) + "$" - _matchInvertRegEx = regExFactory("^" + wildcardToRegEx(_sourceExpression.mid(1)) + "$", - _sourceCaseSensitive); + _matchInvertRegEx = regExFactory("^" + wildcardToRegEx(_sourceExpression.mid(1)) + "$", _sourceCaseSensitive); _matchInvertRegExActive = true; } else { // Normal rule: take the whole string // Account for any escaped "!" (i.e. "\!") by skipping past the "\", but don't skip past // escaped "\" (i.e. "\\!") - _matchRegEx = - regExFactory("^" + wildcardToRegEx(_sourceExpression.startsWith("\\!") - ? _sourceExpression.mid(1) - : _sourceExpression) + "$", - _sourceCaseSensitive); + _matchRegEx = regExFactory("^" + wildcardToRegEx(_sourceExpression.startsWith("\\!") ? _sourceExpression.mid(1) : _sourceExpression) + + "$", + _sourceCaseSensitive); _matchRegExActive = true; } break; @@ -375,10 +363,8 @@ void ExpressionMatch::cacheRegEx() // Normal rule: take the whole string // Account for any escaped "!" (i.e. "\!") by skipping past the "\", but don't skip past // escaped "\" (i.e. "\\!") - _matchRegEx = - regExFactory(_sourceExpression.startsWith("\\!") ? _sourceExpression.mid(1) - : _sourceExpression, - _sourceCaseSensitive); + _matchRegEx = regExFactory(_sourceExpression.startsWith("\\!") ? _sourceExpression.mid(1) : _sourceExpression, + _sourceCaseSensitive); _matchRegExActive = true; } break; @@ -393,28 +379,24 @@ void ExpressionMatch::cacheRegEx() // level as ideally someone's not just going to leave a broken match rule around. For // MatchRegEx, they probably need to fix their regex rule. For the other modes, there's // probably a bug in the parsing routines (which should also be fixed). - quInfo() << "Could not parse expression match rule" - << _sourceExpression << "(match mode:" << (int)_sourceMode + quInfo() << "Could not parse expression match rule" << _sourceExpression << "(match mode:" << (int)_sourceMode << "), this rule will be ignored"; } } - -QRegularExpression ExpressionMatch::regExFactory(const QString ®ExString, - bool caseSensitive) +QRegularExpression ExpressionMatch::regExFactory(const QString& regExString, bool caseSensitive) { // Construct the regular expression object, setting case sensitivity as appropriate - QRegularExpression newRegEx = QRegularExpression(regExString, caseSensitive ? - QRegularExpression::PatternOption::NoPatternOption - : QRegularExpression::PatternOption::CaseInsensitiveOption); + QRegularExpression newRegEx = QRegularExpression(regExString, + caseSensitive ? QRegularExpression::PatternOption::NoPatternOption + : QRegularExpression::PatternOption::CaseInsensitiveOption); // Check if rule is valid if (!newRegEx.isValid()) { // This can happen with invalid regex, so make it a bit more user-friendly. Keep this // distinct from the main info-level message for easier debugging in case a regex component // in Wildcard or Phrase mode breaks. - qDebug() << "Internal regular expression component" << regExString - << "is invalid and will be ignored"; + qDebug() << "Internal regular expression component" << regExString << "is invalid and will be ignored"; } // Qt offers explicit control over when QRegularExpression objects get optimized. // By default, patterns are only optimized after some number of uses as defined @@ -443,22 +425,20 @@ QRegularExpression ExpressionMatch::regExFactory(const QString ®ExString, return newRegEx; } - -QString ExpressionMatch::regExEscape(const QString &phrase) +QString ExpressionMatch::regExEscape(const QString& phrase) { // Escape the given phrase of any special regular expression characters return QRegularExpression::escape(phrase); } - -QString ExpressionMatch::convertFromMultiPhrase(const QString &originalRule) +QString ExpressionMatch::convertFromMultiPhrase(const QString& originalRule) { // Convert the multi-phrase rule into regular expression format // Split apart the original rule into components // Use QStringList instead of std::vector to make use of Qt's built-in .join() method QStringList components = {}; // Split on "\n" - for (auto &&component : originalRule.split("\n", QString::SkipEmptyParts)) { + for (auto&& component : originalRule.split("\n", QString::SkipEmptyParts)) { // Don't trim whitespace to maintain consistency with single phrase matching // As trimming is not performed, empty components will already be skipped. This means " " // is considered a valid matching phrase. @@ -483,8 +463,7 @@ QString ExpressionMatch::convertFromMultiPhrase(const QString &originalRule) } } - -void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, bool caseSensitive) +void ExpressionMatch::generateFromMultiWildcard(const QString& originalRule, bool caseSensitive) { // Convert the wildcard rule into regular expression format // First, reset the existing match expressions @@ -533,7 +512,6 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo // "\\" and "\" are not downconverted to allow for other escape codes to be detected in // ExpressionMatch::wildcardToRegex - // Example: // // > Wildcard rule @@ -679,10 +657,9 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar + << "character!"; isRuleStart = false; break; } @@ -708,10 +685,9 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar + << "character!"; break; } } @@ -724,16 +700,15 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo break; case 1: case 2: - // "\!" -> Elsewhere: keep as "\!" - // "\\!" -> Elsewhere: keep as "\\!" + // "\!" -> Elsewhere: keep as "\!" + // "\\!" -> Elsewhere: keep as "\\!" curString.append(QString(R"(\)").repeated(consecutiveSlashes) + "!"); break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar + << "character!"; break; } } @@ -755,10 +730,9 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo } else if (consecutiveSlashes > 3) { // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar + << "character!"; break; } // Don't set "isRuleStart" here as "\" is used in escape sequences @@ -782,10 +756,8 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), applying newline split anyways!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), applying newline split anyways!"; break; } @@ -823,10 +795,9 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << rule << "resulted in rule component" - << curString << "with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring " << curChar << "char escape!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString + << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring " << curChar + << "char escape!"; break; } // Don't mark as past rule start for whitespace (whitespace gets trimmed) @@ -872,15 +843,13 @@ void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, boo _matchInvertRegEx = regExFactory("^" + invertComponents.at(0) + "$", caseSensitive); } else { - _matchInvertRegEx = - regExFactory("^(?:" + invertComponents.join("|") + ")$", caseSensitive); + _matchInvertRegEx = regExFactory("^(?:" + invertComponents.join("|") + ")$", caseSensitive); } _matchInvertRegExActive = true; } } - -QString ExpressionMatch::wildcardToRegEx(const QString &expression) +QString ExpressionMatch::wildcardToRegEx(const QString& expression) { // Convert the wildcard expression into regular expression format @@ -993,10 +962,9 @@ QString ExpressionMatch::wildcardToRegEx(const QString &expression) break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << expression << "resulted in escaped regular expression string" - << regExEscaped << " with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << expression << "resulted in escaped regular expression string" + << regExEscaped << " with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" + << curChar << "character!"; break; } consecutiveSlashes = 0; @@ -1016,10 +984,9 @@ QString ExpressionMatch::wildcardToRegEx(const QString &expression) break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << expression << "resulted in escaped regular expression string" - << regExEscaped << " with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "character!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << expression << "resulted in escaped regular expression string" + << regExEscaped << " with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" + << curChar << "character!"; break; } consecutiveSlashes = 0; @@ -1059,10 +1026,9 @@ QString ExpressionMatch::wildcardToRegEx(const QString &expression) break; default: // This shouldn't ever happen (even with invalid wildcard rules), log a warning - qWarning() << Q_FUNC_INFO << "Wildcard rule" - << expression << "resulted in escaped regular expression string" - << regExEscaped << " with unexpected count of consecutive '\\' (" - << consecutiveSlashes << "), ignoring" << curChar << "char escape!"; + qWarning() << Q_FUNC_INFO << "Wildcard rule" << expression << "resulted in escaped regular expression string" + << regExEscaped << " with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" + << curChar << "char escape!"; break; } consecutiveSlashes = 0; diff --git a/src/common/expressionmatch.h b/src/common/expressionmatch.h index 689d14f9..daaa6e8c 100644 --- a/src/common/expressionmatch.h +++ b/src/common/expressionmatch.h @@ -31,15 +31,15 @@ */ class COMMON_EXPORT ExpressionMatch { - public: /// Expression matching mode - enum class MatchMode { - MatchPhrase, ///< Match phrase as specified, no special handling - MatchMultiPhrase, ///< Match phrase as specified, split on \n only - MatchWildcard, ///< Match wildcards, "!" at start inverts, "\" escapes - MatchMultiWildcard, ///< Match wildcards, split ; or \n, "!" at start inverts, "\" escapes - MatchRegEx ///< Match as regular expression, "!..." invert regex, "\" escapes + enum class MatchMode + { + MatchPhrase, ///< Match phrase as specified, no special handling + MatchMultiPhrase, ///< Match phrase as specified, split on \n only + MatchWildcard, ///< Match wildcards, "!" at start inverts, "\" escapes + MatchMultiWildcard, ///< Match wildcards, split ; or \n, "!" at start inverts, "\" escapes + MatchRegEx ///< Match as regular expression, "!..." invert regex, "\" escapes }; /** @@ -58,7 +58,7 @@ public: * @endparblock * @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching */ - ExpressionMatch(const QString &expression, MatchMode mode, bool caseSensitive); + ExpressionMatch(const QString& expression, MatchMode mode, bool caseSensitive); /** * Check if the given string matches the stored expression @@ -67,7 +67,7 @@ public: * @param matchEmpty If true, always match when the expression is empty, otherwise never match * @return True if match found, otherwise false */ - bool match(const QString &string, bool matchEmpty = false) const; + bool match(const QString& string, bool matchEmpty = false) const; /** * Gets if the source expression is empty @@ -81,10 +81,10 @@ public: * * @return True if given expression is valid, otherwise false */ - inline bool isValid() const { + inline bool isValid() const + { // Either this must be empty, or normal or inverted rules must be valid and active - return (_sourceExpressionEmpty - || (_matchRegExActive && _matchRegEx.isValid()) + return (_sourceExpressionEmpty || (_matchRegExActive && _matchRegEx.isValid()) || (_matchInvertRegExActive && _matchInvertRegEx.isValid())); } @@ -100,7 +100,8 @@ public: * * @param expression A phrase, wildcard expression, or regular expression */ - void setSourceExpression(const QString &expression) { + void setSourceExpression(const QString& expression) + { if (_sourceExpression != expression) { _sourceExpression = expression; cacheRegEx(); @@ -123,7 +124,8 @@ public: * @see ExpressionMatch::MatchMode * @endparblock */ - void setSourceMode(MatchMode mode) { + void setSourceMode(MatchMode mode) + { if (_sourceMode != mode) { _sourceMode = mode; cacheRegEx(); @@ -142,18 +144,18 @@ public: * * @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching */ - void setSourceCaseSensitive(bool caseSensitive) { + void setSourceCaseSensitive(bool caseSensitive) + { if (_sourceCaseSensitive != caseSensitive) { _sourceCaseSensitive = caseSensitive; cacheRegEx(); } } - bool operator!=(const ExpressionMatch &other) const + bool operator!=(const ExpressionMatch& other) const { - return (_sourceExpression != other._sourceExpression || - _sourceMode != other._sourceMode || - _sourceCaseSensitive != other._sourceCaseSensitive); + return (_sourceExpression != other._sourceExpression || _sourceMode != other._sourceMode + || _sourceCaseSensitive != other._sourceCaseSensitive); } /** @@ -167,7 +169,7 @@ public: * @param originalRule MultiWildcard rule list, ";"-separated * @return Trimmed MultiWildcard rule list */ - static QString trimMultiWildcardWhitespace(const QString &originalRule); + static QString trimMultiWildcardWhitespace(const QString& originalRule); private: /** @@ -184,7 +186,7 @@ private: * @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching * @return Configured QRegularExpression */ - static QRegularExpression regExFactory(const QString ®ExString, bool caseSensitive); + static QRegularExpression regExFactory(const QString& regExString, bool caseSensitive); /** * Escapes any regular expression characters in a string so they have no special meaning @@ -192,7 +194,7 @@ private: * @param phrase String containing potential regular expression special characters * @return QString with all regular expression characters escaped */ - static QString regExEscape(const QString &phrase); + static QString regExEscape(const QString& phrase); /** * Converts a multiple-phrase rule into a regular expression @@ -202,7 +204,7 @@ private: * @param originalRule MultiPhrase rule list, "\n"-separated * @return A regular expression matching the given phrases */ - static QString convertFromMultiPhrase(const QString &originalRule); + static QString convertFromMultiPhrase(const QString& originalRule); /** * Internally converts a wildcard rule into regular expressions @@ -212,7 +214,7 @@ private: * @param originalRule MultiWildcard rule list, ";"-separated * @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching */ - void generateFromMultiWildcard(const QString &originalRule, bool caseSensitive); + void generateFromMultiWildcard(const QString& originalRule, bool caseSensitive); /** * Converts a wildcard expression into a regular expression @@ -222,7 +224,7 @@ private: * @see ExpressionMatch::convertFromWildcard() * @return QString with all regular expression characters escaped */ - static QString wildcardToRegEx(const QString &expression); + static QString wildcardToRegEx(const QString& expression); // Original/source components QString _sourceExpression = {}; ///< Expression match string given on creation @@ -230,13 +232,13 @@ private: bool _sourceCaseSensitive = false; ///< Expression case sensitive on creation // Derived components - bool _sourceExpressionEmpty = false; ///< Cached expression match string is empty + bool _sourceExpressionEmpty = false; ///< Cached expression match string is empty /// Underlying regular expression matching instance for normal (noninverted) rules QRegularExpression _matchRegEx = {}; - bool _matchRegExActive = false; ///< If true, use normal expression in matching + bool _matchRegExActive = false; ///< If true, use normal expression in matching /// Underlying regular expression matching instance for inverted rules QRegularExpression _matchInvertRegEx = {}; - bool _matchInvertRegExActive = false; ///< If true, use invert expression in matching + bool _matchInvertRegExActive = false; ///< If true, use invert expression in matching }; diff --git a/src/common/funchelpers.h b/src/common/funchelpers.h index 6c7aeb63..01ee8222 100644 --- a/src/common/funchelpers.h +++ b/src/common/funchelpers.h @@ -29,15 +29,18 @@ namespace detail { // Primary template template -struct FuncHelper : public FuncHelper {}; +struct FuncHelper : public FuncHelper +{}; // Overload for member function with const call operator -template -struct FuncHelper : public FuncHelper {}; +template +struct FuncHelper : public FuncHelper +{}; // Overload for member function with non-const call operator -template -struct FuncHelper { +template +struct FuncHelper +{ using ClassType = C; using FunctionType = std::function; using ReturnType = R; @@ -46,7 +49,7 @@ struct FuncHelper { /// @endcond -} // detail +} // namespace detail /** * Provides traits for the given callable. diff --git a/src/common/highlightrulemanager.cpp b/src/common/highlightrulemanager.cpp index 0d0e7be4..ec3e8e83 100644 --- a/src/common/highlightrulemanager.cpp +++ b/src/common/highlightrulemanager.cpp @@ -25,7 +25,7 @@ #include "expressionmatch.h" #include "util.h" -HighlightRuleManager &HighlightRuleManager::operator=(const HighlightRuleManager &other) +HighlightRuleManager& HighlightRuleManager::operator=(const HighlightRuleManager& other) { if (this == &other) return *this; @@ -37,7 +37,6 @@ HighlightRuleManager &HighlightRuleManager::operator=(const HighlightRuleManager return *this; } - int HighlightRuleManager::indexOf(int id) const { for (int i = 0; i < _highlightRuleList.count(); i++) { @@ -47,7 +46,6 @@ int HighlightRuleManager::indexOf(int id) const return -1; } - int HighlightRuleManager::nextId() { int max = 0; @@ -60,7 +58,6 @@ int HighlightRuleManager::nextId() return max + 1; } - QVariantMap HighlightRuleManager::initHighlightRuleList() const { QVariantList id; @@ -95,8 +92,7 @@ QVariantMap HighlightRuleManager::initHighlightRuleList() const return highlightRuleListMap; } - -void HighlightRuleManager::initSetHighlightRuleList(const QVariantMap &highlightRuleList) +void HighlightRuleManager::initSetHighlightRuleList(const QVariantMap& highlightRuleList) { QVariantList id = highlightRuleList["id"].toList(); QStringList name = highlightRuleList["name"].toStringList(); @@ -108,24 +104,27 @@ void HighlightRuleManager::initSetHighlightRuleList(const QVariantMap &highlight QStringList channel = highlightRuleList["channel"].toStringList(); int count = id.count(); - if (count != name.count() || count != isRegEx.count() || count != isCaseSensitive.count() || - count != isActive.count() || count != isInverse.count() || count != sender.count() || - count != channel.count()) { + if (count != name.count() || count != isRegEx.count() || count != isCaseSensitive.count() || count != isActive.count() + || count != isInverse.count() || count != sender.count() || count != channel.count()) { qWarning() << "Corrupted HighlightRuleList settings! (Count mismatch)"; return; } _highlightRuleList.clear(); for (int i = 0; i < name.count(); i++) { - _highlightRuleList << HighlightRule(id[i].toInt(), name[i], isRegEx[i].toBool(), isCaseSensitive[i].toBool(), - isActive[i].toBool(), isInverse[i].toBool(), sender[i], channel[i]); + _highlightRuleList << HighlightRule(id[i].toInt(), + name[i], + isRegEx[i].toBool(), + isCaseSensitive[i].toBool(), + isActive[i].toBool(), + isInverse[i].toBool(), + sender[i], + channel[i]); } } - -void HighlightRuleManager::addHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive, - bool isActive, bool isInverse, const QString &sender, - const QString &channel) +void HighlightRuleManager::addHighlightRule( + int id, const QString& name, bool isRegEx, bool isCaseSensitive, bool isActive, bool isInverse, const QString& sender, const QString& channel) { if (contains(id)) { return; @@ -134,28 +133,26 @@ void HighlightRuleManager::addHighlightRule(int id, const QString &name, bool is HighlightRule newItem = HighlightRule(id, name, isRegEx, isCaseSensitive, isActive, isInverse, sender, channel); _highlightRuleList << newItem; - SYNC(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isActive), ARG(isInverse), ARG(sender), - ARG(channel)) + SYNC(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isActive), ARG(isInverse), ARG(sender), ARG(channel)) } - -bool HighlightRuleManager::match(const NetworkId &netId, - const QString &msgContents, - const QString &msgSender, +bool HighlightRuleManager::match(const NetworkId& netId, + const QString& msgContents, + const QString& msgSender, Message::Type msgType, Message::Flags msgFlags, - const QString &bufferName, - const QString ¤tNick, - const QStringList &identityNicks) + const QString& bufferName, + const QString& currentNick, + const QStringList& identityNicks) { if (!((msgType & (Message::Plain | Message::Notice | Message::Action)) && !(msgFlags & Message::Self))) { - return false; + return false; } bool matches = false; for (int i = 0; i < _highlightRuleList.count(); i++) { - auto &rule = _highlightRuleList.at(i); + auto& rule = _highlightRuleList.at(i); if (!rule.isEnabled()) continue; @@ -203,14 +200,12 @@ bool HighlightRuleManager::match(const NetworkId &netId, return false; } - void HighlightRuleManager::removeHighlightRule(int highlightRule) { removeAt(indexOf(highlightRule)); SYNC(ARG(highlightRule)) } - void HighlightRuleManager::toggleHighlightRule(int highlightRule) { int idx = indexOf(highlightRule); @@ -220,31 +215,28 @@ void HighlightRuleManager::toggleHighlightRule(int highlightRule) SYNC(ARG(highlightRule)) } - -bool HighlightRuleManager::match(const Message &msg, const QString ¤tNick, const QStringList &identityNicks) +bool HighlightRuleManager::match(const Message& msg, const QString& currentNick, const QStringList& identityNicks) { - return match(msg.bufferInfo().networkId(), msg.contents(), msg.sender(), msg.type(), msg.flags(), - msg.bufferInfo().bufferName(), currentNick, identityNicks); + return match(msg.bufferInfo().networkId(), + msg.contents(), + msg.sender(), + msg.type(), + msg.flags(), + msg.bufferInfo().bufferName(), + currentNick, + identityNicks); } - /************************************************************************** * HighlightRule *************************************************************************/ -bool HighlightRuleManager::HighlightRule::operator!=(const HighlightRule &other) const +bool HighlightRuleManager::HighlightRule::operator!=(const HighlightRule& other) const { - return (_id != other._id || - _contents != other._contents || - _isRegEx != other._isRegEx || - _isCaseSensitive != other._isCaseSensitive || - _isEnabled != other._isEnabled || - _isInverse != other._isInverse || - _sender != other._sender || - _chanName != other._chanName); + return (_id != other._id || _contents != other._contents || _isRegEx != other._isRegEx || _isCaseSensitive != other._isCaseSensitive + || _isEnabled != other._isEnabled || _isInverse != other._isInverse || _sender != other._sender || _chanName != other._chanName); // Don't compare ExpressionMatch objects as they are created as needed from the above } - void HighlightRuleManager::HighlightRule::determineExpressions() const { // Don't update if not needed @@ -254,13 +246,9 @@ void HighlightRuleManager::HighlightRule::determineExpressions() const // Set up matching rules // Message is either phrase or regex - ExpressionMatch::MatchMode contentsMode = - _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : - ExpressionMatch::MatchMode::MatchPhrase; + ExpressionMatch::MatchMode contentsMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchPhrase; // Sender and channel are either multiple wildcard entries or regex - ExpressionMatch::MatchMode scopeMode = - _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : - ExpressionMatch::MatchMode::MatchMultiWildcard; + ExpressionMatch::MatchMode scopeMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchMultiWildcard; _contentsMatch = ExpressionMatch(_contents, contentsMode, _isCaseSensitive); _senderMatch = ExpressionMatch(_sender, scopeMode, _isCaseSensitive); diff --git a/src/common/highlightrulemanager.h b/src/common/highlightrulemanager.h index 0db44fc5..475b3ade 100644 --- a/src/common/highlightrulemanager.h +++ b/src/common/highlightrulemanager.h @@ -43,14 +43,19 @@ class COMMON_EXPORT HighlightRuleManager : public SyncableObject Q_PROPERTY(bool nicksCaseSensitive READ nicksCaseSensitive WRITE setNicksCaseSensitive) public: - enum HighlightNickType { + enum HighlightNickType + { NoNick = 0x00, CurrentNick = 0x01, AllNicks = 0x02 }; - inline HighlightRuleManager(QObject *parent = nullptr) : SyncableObject(parent) { setAllowClientUpdates(true); } - HighlightRuleManager &operator=(const HighlightRuleManager &other); + inline HighlightRuleManager(QObject* parent = nullptr) + : SyncableObject(parent) + { + setAllowClientUpdates(true); + } + HighlightRuleManager& operator=(const HighlightRuleManager& other); /** * Individual highlight rule @@ -75,10 +80,16 @@ public: * @param sender String representing a message sender expression to match * @param chanName String representing a channel name expression to match */ - HighlightRule(int id, QString contents, bool isRegEx, bool isCaseSensitive, bool isEnabled, - bool isInverse, QString sender, QString chanName) - : _id(id), _contents(std::move(contents)), _isRegEx(isRegEx), _isCaseSensitive(isCaseSensitive), - _isEnabled(isEnabled), _isInverse(isInverse), _sender(std::move(sender)), _chanName(std::move(chanName)) + HighlightRule( + int id, QString contents, bool isRegEx, bool isCaseSensitive, bool isEnabled, bool isInverse, QString sender, QString chanName) + : _id(id) + , _contents(std::move(contents)) + , _isRegEx(isRegEx) + , _isCaseSensitive(isCaseSensitive) + , _isEnabled(isEnabled) + , _isInverse(isInverse) + , _sender(std::move(sender)) + , _chanName(std::move(chanName)) { _cacheInvalid = true; // Cache expression matches on construction @@ -97,9 +108,7 @@ public: * * @return Integer ID of the rule */ - inline int id() const { - return _id; - } + inline int id() const { return _id; } /** * Sets the ID of this rule * @@ -107,9 +116,7 @@ public: * * @param id Integer ID of the rule */ - inline void setId(int id) { - _id = id; - } + inline void setId(int id) { _id = id; } /** * Gets the message contents this rule matches @@ -118,15 +125,14 @@ public: * * @return String representing a phrase or expression to match */ - inline QString contents() const { - return _contents; - } + inline QString contents() const { return _contents; } /** * Sets the message contents this rule matches * * @param contents String representing a phrase or expression to match */ - inline void setContents(const QString &contents) { + inline void setContents(const QString& contents) + { _contents = contents; _cacheInvalid = true; } @@ -136,15 +142,14 @@ public: * * @return True if regular expression, otherwise false */ - inline bool isRegEx() const { - return _isRegEx; - } + inline bool isRegEx() const { return _isRegEx; } /** * Sets if this rule is a regular expression rule * * @param isRegEx True if regular expression, otherwise false */ - inline void setIsRegEx(bool isRegEx) { + inline void setIsRegEx(bool isRegEx) + { _isRegEx = isRegEx; _cacheInvalid = true; } @@ -154,15 +159,14 @@ public: * * @return True if case sensitive, otherwise false */ - inline bool isCaseSensitive() const { - return _isCaseSensitive; - } + inline bool isCaseSensitive() const { return _isCaseSensitive; } /** * Sets if this rule is case sensitive * * @param isCaseSensitive True if case sensitive, otherwise false */ - inline void setIsCaseSensitive(bool isCaseSensitive) { + inline void setIsCaseSensitive(bool isCaseSensitive) + { _isCaseSensitive = isCaseSensitive; _cacheInvalid = true; } @@ -172,34 +176,26 @@ public: * * @return True if enabled, otherwise false */ - inline bool isEnabled() const { - return _isEnabled; - } + inline bool isEnabled() const { return _isEnabled; } /** * Sets if this rule is enabled and active * * @param isEnabled True if enabled, otherwise false */ - inline void setIsEnabled(bool isEnabled) { - _isEnabled = isEnabled; - } + inline void setIsEnabled(bool isEnabled) { _isEnabled = isEnabled; } /** * Gets if this rule is a highlight ignore rule * * @return True if rule is treated as highlight ignore, otherwise false */ - inline bool isInverse() const { - return _isInverse; - } + inline bool isInverse() const { return _isInverse; } /** * Sets if this rule is a highlight ignore rule * * @param isInverse True if rule is treated as highlight ignore, otherwise false */ - inline void setIsInverse(bool isInverse) { - _isInverse = isInverse; - } + inline void setIsInverse(bool isInverse) { _isInverse = isInverse; } /** * Gets the message sender this rule matches @@ -214,7 +210,8 @@ public: * * @param sender String representing a phrase or expression to match */ - inline void setSender(const QString &sender) { + inline void setSender(const QString& sender) + { _sender = sender; _cacheInvalid = true; } @@ -232,7 +229,8 @@ public: * * @param chanName String representing a phrase or expression to match */ - inline void setChanName(const QString &chanName) { + inline void setChanName(const QString& chanName) + { _chanName = chanName; _cacheInvalid = true; } @@ -242,7 +240,8 @@ public: * * @return Expression matcher to compare with message contents */ - inline ExpressionMatch contentsMatcher() const { + inline ExpressionMatch contentsMatcher() const + { if (_cacheInvalid) { determineExpressions(); } @@ -254,7 +253,8 @@ public: * * @return Expression matcher to compare with message sender */ - inline ExpressionMatch senderMatcher() const { + inline ExpressionMatch senderMatcher() const + { if (_cacheInvalid) { determineExpressions(); } @@ -266,14 +266,15 @@ public: * * @return Expression matcher to compare with channel name */ - inline ExpressionMatch chanNameMatcher() const { + inline ExpressionMatch chanNameMatcher() const + { if (_cacheInvalid) { determineExpressions(); } return _chanNameMatch; } - bool operator!=(const HighlightRule &other) const; + bool operator!=(const HighlightRule& other) const; private: /** @@ -292,10 +293,10 @@ public: // These represent internal cache and should be safe to mutate in 'const' functions // See https://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration - mutable bool _cacheInvalid = true; ///< If true, match cache needs redone - mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message content - mutable ExpressionMatch _senderMatch = {}; ///< Expression match cache for sender - mutable ExpressionMatch _chanNameMatch = {}; ///< Expression match cache for channel name + mutable bool _cacheInvalid = true; ///< If true, match cache needs redone + mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message content + mutable ExpressionMatch _senderMatch = {}; ///< Expression match cache for sender + mutable ExpressionMatch _chanNameMatch = {}; ///< Expression match cache for channel name }; using HighlightRuleList = QList; @@ -306,9 +307,9 @@ public: inline int count() const { return _highlightRuleList.count(); } inline void removeAt(int index) { _highlightRuleList.removeAt(index); } inline void clear() { _highlightRuleList.clear(); } - inline HighlightRule &operator[](int i) { return _highlightRuleList[i]; } - inline const HighlightRule &operator[](int i) const { return _highlightRuleList.at(i); } - inline const HighlightRuleList &highlightRuleList() const { return _highlightRuleList; } + inline HighlightRule& operator[](int i) { return _highlightRuleList[i]; } + inline const HighlightRule& operator[](int i) const { return _highlightRuleList.at(i); } + inline const HighlightRuleList& highlightRuleList() const { return _highlightRuleList; } int nextId(); @@ -317,68 +318,73 @@ public: //! Check if a message matches the HighlightRule /** This method checks if a message matches the users highlight rules. - * \param msg The Message that should be checked - */ - bool match(const Message &msg, const QString ¤tNick, const QStringList &identityNicks); + * \param msg The Message that should be checked + */ + bool match(const Message& msg, const QString& currentNick, const QStringList& identityNicks); public slots: virtual QVariantMap initHighlightRuleList() const; - virtual void initSetHighlightRuleList(const QVariantMap &HighlightRuleList); + virtual void initSetHighlightRuleList(const QVariantMap& HighlightRuleList); //! Request removal of an ignore rule based on the rule itself. /** Use this method if you want to remove a single ignore rule - * and get that synced with the core immediately. - * \param highlightRule A valid ignore rule - */ + * and get that synced with the core immediately. + * \param highlightRule A valid ignore rule + */ virtual inline void requestRemoveHighlightRule(int highlightRule) { REQUEST(ARG(highlightRule)) } virtual void removeHighlightRule(int highlightRule); //! Request toggling of "isEnabled" flag of a given ignore rule. /** Use this method if you want to toggle the "isEnabled" flag of a single ignore rule - * and get that synced with the core immediately. - * \param highlightRule A valid ignore rule - */ + * and get that synced with the core immediately. + * \param highlightRule A valid ignore rule + */ virtual inline void requestToggleHighlightRule(int highlightRule) { REQUEST(ARG(highlightRule)) } virtual void toggleHighlightRule(int highlightRule); //! Request an HighlightRule to be added to the ignore list /** Items added to the list with this method, get immediately synced with the core - * \param name The rule - * \param isRegEx If the rule should be interpreted as a nickname, or a regex - * \param isCaseSensitive If the rule should be interpreted as case-sensitive - * \param isEnabled If the rule is active - * @param chanName The channel in which the rule should apply - */ - virtual inline void requestAddHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive, bool isEnabled, - bool isInverse, const QString &sender, const QString &chanName) + * \param name The rule + * \param isRegEx If the rule should be interpreted as a nickname, or a regex + * \param isCaseSensitive If the rule should be interpreted as case-sensitive + * \param isEnabled If the rule is active + * @param chanName The channel in which the rule should apply + */ + virtual inline void requestAddHighlightRule(int id, + const QString& name, + bool isRegEx, + bool isCaseSensitive, + bool isEnabled, + bool isInverse, + const QString& sender, + const QString& chanName) { - REQUEST(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isEnabled), ARG(isInverse), ARG(sender), - ARG(chanName)) + REQUEST(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isEnabled), ARG(isInverse), ARG(sender), ARG(chanName)) } + virtual void addHighlightRule(int id, + const QString& name, + bool isRegEx, + bool isCaseSensitive, + bool isEnabled, + bool isInverse, + const QString& sender, + const QString& chanName); - virtual void addHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive, bool isEnabled, - bool isInverse, const QString &sender, const QString &chanName); + virtual inline void requestSetHighlightNick(int highlightNick) { REQUEST(ARG(highlightNick)) } - virtual inline void requestSetHighlightNick(int highlightNick) + inline void setHighlightNick(int highlightNick) { - REQUEST(ARG(highlightNick)) - } - - inline void setHighlightNick(int highlightNick) { _highlightNick = static_cast(highlightNick); // Convert from HighlightRuleManager::HighlightNickType to // NickHighlightMatcher::HighlightNickType - _nickMatcher.setHighlightMode( - static_cast(_highlightNick)); + _nickMatcher.setHighlightMode(static_cast(_highlightNick)); } - virtual inline void requestSetNicksCaseSensitive(bool nicksCaseSensitive) - { - REQUEST(ARG(nicksCaseSensitive)) - } + virtual inline void requestSetNicksCaseSensitive(bool nicksCaseSensitive) { REQUEST(ARG(nicksCaseSensitive)) } - inline void setNicksCaseSensitive(bool nicksCaseSensitive) { + inline void setNicksCaseSensitive(bool nicksCaseSensitive) + { _nicksCaseSensitive = nicksCaseSensitive; // Update nickname matcher, too _nickMatcher.setCaseSensitive(nicksCaseSensitive); @@ -391,31 +397,32 @@ public slots: * * @param id Network ID of removed network */ - inline void networkRemoved(NetworkId id) { + inline void networkRemoved(NetworkId id) + { // Clean up nickname matching cache _nickMatcher.removeNetwork(id); } protected: - void setHighlightRuleList(const QList &HighlightRuleList) { _highlightRuleList = HighlightRuleList; } + void setHighlightRuleList(const QList& HighlightRuleList) { _highlightRuleList = HighlightRuleList; } - bool match(const NetworkId &netId, - const QString &msgContents, - const QString &msgSender, + bool match(const NetworkId& netId, + const QString& msgContents, + const QString& msgSender, Message::Type msgType, Message::Flags msgFlags, - const QString &bufferName, - const QString ¤tNick, - const QStringList &identityNicks); + const QString& bufferName, + const QString& currentNick, + const QStringList& identityNicks); signals: void ruleAdded(QString name, bool isRegEx, bool isCaseSensitive, bool isEnabled, bool isInverse, QString sender, QString chanName); private: - HighlightRuleList _highlightRuleList = {}; ///< Custom highlight rule list - NickHighlightMatcher _nickMatcher = {}; ///< Nickname highlight matcher + HighlightRuleList _highlightRuleList = {}; ///< Custom highlight rule list + NickHighlightMatcher _nickMatcher = {}; ///< Nickname highlight matcher /// Nickname highlighting mode HighlightNickType _highlightNick = HighlightNickType::CurrentNick; - bool _nicksCaseSensitive = false; ///< If true, match nicknames with exact case + bool _nicksCaseSensitive = false; ///< If true, match nicknames with exact case }; diff --git a/src/common/identity.cpp b/src/common/identity.cpp index 9d885e0e..4b78cfd1 100644 --- a/src/common/identity.cpp +++ b/src/common/identity.cpp @@ -21,78 +21,75 @@ #include "identity.h" #include -#include #include +#include #ifdef Q_OS_MAC -# include -# include "mac_utils.h" +# include + +# include "mac_utils.h" #endif #ifdef Q_OS_UNIX -# include -# include -# include +# include +# include +# include #endif #ifdef Q_OS_WIN -# include -# include -# define SECURITY_WIN32 -# include +# include +# include +# define SECURITY_WIN32 +# include #endif -Identity::Identity(IdentityId id, QObject *parent) - : SyncableObject(parent), - _identityId(id) +Identity::Identity(IdentityId id, QObject* parent) + : SyncableObject(parent) + , _identityId(id) { init(); setToDefaults(); } - -Identity::Identity(const Identity &other, QObject *parent) - : SyncableObject(parent), - _identityId(other.id()), - _identityName(other.identityName()), - _realName(other.realName()), - _nicks(other.nicks()), - _awayNick(other.awayNick()), - _awayNickEnabled(other.awayNickEnabled()), - _awayReason(other.awayReason()), - _awayReasonEnabled(other.awayReasonEnabled()), - _autoAwayEnabled(other.autoAwayEnabled()), - _autoAwayTime(other.autoAwayTime()), - _autoAwayReason(other.autoAwayReason()), - _autoAwayReasonEnabled(other.autoAwayReasonEnabled()), - _detachAwayEnabled(other.detachAwayEnabled()), - _detachAwayReason(other.detachAwayReason()), - _detachAwayReasonEnabled(other.detachAwayReasonEnabled()), - _ident(other.ident()), - _kickReason(other.kickReason()), - _partReason(other.partReason()), - _quitReason(other.quitReason()) +Identity::Identity(const Identity& other, QObject* parent) + : SyncableObject(parent) + , _identityId(other.id()) + , _identityName(other.identityName()) + , _realName(other.realName()) + , _nicks(other.nicks()) + , _awayNick(other.awayNick()) + , _awayNickEnabled(other.awayNickEnabled()) + , _awayReason(other.awayReason()) + , _awayReasonEnabled(other.awayReasonEnabled()) + , _autoAwayEnabled(other.autoAwayEnabled()) + , _autoAwayTime(other.autoAwayTime()) + , _autoAwayReason(other.autoAwayReason()) + , _autoAwayReasonEnabled(other.autoAwayReasonEnabled()) + , _detachAwayEnabled(other.detachAwayEnabled()) + , _detachAwayReason(other.detachAwayReason()) + , _detachAwayReasonEnabled(other.detachAwayReasonEnabled()) + , _ident(other.ident()) + , _kickReason(other.kickReason()) + , _partReason(other.partReason()) + , _quitReason(other.quitReason()) { init(); } - #ifdef Q_OS_WIN -#ifdef UNICODE -QString tcharToQString(TCHAR *tchar) +# ifdef UNICODE +QString tcharToQString(TCHAR* tchar) { - return QString::fromUtf16(reinterpret_cast(tchar)); + return QString::fromUtf16(reinterpret_cast(tchar)); } - -#else -QString tcharToQString(TCHAR *tchar) +# else +QString tcharToQString(TCHAR* tchar) { return QString::fromLocal8Bit(tchar); } - -#endif +# endif #endif void Identity::init() @@ -101,10 +98,9 @@ void Identity::init() setAllowClientUpdates(true); } - QString Identity::defaultNick() { - QString nick = QString("quassel%1").arg(qrand() & 0xff); // FIXME provide more sensible default nicks + QString nick = QString("quassel%1").arg(qrand() & 0xff); // FIXME provide more sensible default nicks #ifdef Q_OS_MAC QString shortUserName = CFStringToQString(CSCopyUserName(true)); @@ -113,7 +109,7 @@ QString Identity::defaultNick() #elif defined(Q_OS_UNIX) QString userName; - struct passwd *pwd = getpwuid(getuid()); + struct passwd* pwd = getpwuid(getuid()); if (pwd) userName = pwd->pw_name; if (!userName.isEmpty()) @@ -122,7 +118,7 @@ QString Identity::defaultNick() #elif defined(Q_OS_WIN) TCHAR infoBuf[128]; DWORD bufCharCount = 128; - //if(GetUserNameEx(/* NameSamCompatible */ 1, infoBuf, &bufCharCount)) + // if(GetUserNameEx(/* NameSamCompatible */ 1, infoBuf, &bufCharCount)) if (GetUserNameEx(NameSamCompatible, infoBuf, &bufCharCount)) { QString nickName(tcharToQString(infoBuf)); int lastBs = nickName.lastIndexOf('\\'); @@ -140,7 +136,6 @@ QString Identity::defaultNick() return nick; } - QString Identity::defaultRealName() { QString generalDefault = tr("Quassel IRC User"); @@ -150,7 +145,7 @@ QString Identity::defaultRealName() #elif defined(Q_OS_UNIX) QString realName; - struct passwd *pwd = getpwuid(getuid()); + struct passwd* pwd = getpwuid(getuid()); if (pwd) realName = QString::fromUtf8(pwd->pw_gecos); if (!realName.isEmpty()) @@ -170,7 +165,6 @@ QString Identity::defaultRealName() #endif } - void Identity::setToDefaults() { setIdentityName(tr("")); @@ -194,7 +188,6 @@ void Identity::setToDefaults() setQuitReason(tr("https://quassel-irc.org - Chat comfortably. Anywhere.")); } - /*** setters ***/ void Identity::setId(IdentityId _id) @@ -205,137 +198,118 @@ void Identity::setId(IdentityId _id) renameObject(QString::number(id().toInt())); } - -void Identity::setIdentityName(const QString &identityName) +void Identity::setIdentityName(const QString& identityName) { _identityName = identityName; SYNC(ARG(identityName)) } - -void Identity::setRealName(const QString &realName) +void Identity::setRealName(const QString& realName) { _realName = realName; SYNC(ARG(realName)) } - -void Identity::setNicks(const QStringList &nicks) +void Identity::setNicks(const QStringList& nicks) { _nicks = nicks; SYNC(ARG(nicks)) emit nicksSet(nicks); } - -void Identity::setAwayNick(const QString &nick) +void Identity::setAwayNick(const QString& nick) { _awayNick = nick; SYNC(ARG(nick)) } - -void Identity::setAwayReason(const QString &reason) +void Identity::setAwayReason(const QString& reason) { _awayReason = reason; SYNC(ARG(reason)) } - void Identity::setAwayNickEnabled(bool enabled) { _awayNickEnabled = enabled; SYNC(ARG(enabled)) } - void Identity::setAwayReasonEnabled(bool enabled) { _awayReasonEnabled = enabled; SYNC(ARG(enabled)) } - void Identity::setAutoAwayEnabled(bool enabled) { _autoAwayEnabled = enabled; SYNC(ARG(enabled)) } - void Identity::setAutoAwayTime(int time) { _autoAwayTime = time; SYNC(ARG(time)) } - -void Identity::setAutoAwayReason(const QString &reason) +void Identity::setAutoAwayReason(const QString& reason) { _autoAwayReason = reason; SYNC(ARG(reason)) } - void Identity::setAutoAwayReasonEnabled(bool enabled) { _autoAwayReasonEnabled = enabled; SYNC(ARG(enabled)) } - void Identity::setDetachAwayEnabled(bool enabled) { _detachAwayEnabled = enabled; SYNC(ARG(enabled)) } - -void Identity::setDetachAwayReason(const QString &reason) +void Identity::setDetachAwayReason(const QString& reason) { _detachAwayReason = reason; SYNC(ARG(reason)) } - void Identity::setDetachAwayReasonEnabled(bool enabled) { _detachAwayReasonEnabled = enabled; SYNC(ARG(enabled)) } - -void Identity::setIdent(const QString &ident) +void Identity::setIdent(const QString& ident) { _ident = ident; SYNC(ARG(ident)) } - -void Identity::setKickReason(const QString &reason) +void Identity::setKickReason(const QString& reason) { _kickReason = reason; SYNC(ARG(reason)) } - -void Identity::setPartReason(const QString &reason) +void Identity::setPartReason(const QString& reason) { _partReason = reason; SYNC(ARG(reason)) } - -void Identity::setQuitReason(const QString &reason) +void Identity::setQuitReason(const QString& reason) { _quitReason = reason; SYNC(ARG(reason)) } - /*** ***/ -void Identity::copyFrom(const Identity &other) +void Identity::copyFrom(const Identity& other) { for (int idx = staticMetaObject.propertyOffset(); idx < staticMetaObject.propertyCount(); idx++) { QMetaProperty metaProp = staticMetaObject.property(idx); @@ -346,42 +320,40 @@ void Identity::copyFrom(const Identity &other) } } - -bool Identity::operator==(const Identity &other) const +bool Identity::operator==(const Identity& other) const { for (int idx = staticMetaObject.propertyOffset(); idx < staticMetaObject.propertyCount(); idx++) { QMetaProperty metaProp = staticMetaObject.property(idx); Q_ASSERT(metaProp.isValid()); QVariant v1 = this->property(metaProp.name()); - QVariant v2 = other.property(metaProp.name()); // qDebug() << v1 << v2; + QVariant v2 = other.property(metaProp.name()); // qDebug() << v1 << v2; // QVariant cannot compare custom types, so we need to check for this special case if (QString(v1.typeName()) == "IdentityId") { - if (v1.value() != v2.value()) return false; + if (v1.value() != v2.value()) + return false; } else { - if (v1 != v2) return false; + if (v1 != v2) + return false; } } return true; } - -bool Identity::operator!=(const Identity &other) const +bool Identity::operator!=(const Identity& other) const { return !(*this == other); } - /////////////////////////////// -QDataStream &operator<<(QDataStream &out, Identity id) +QDataStream& operator<<(QDataStream& out, Identity id) { out << id.toVariantMap(); return out; } - -QDataStream &operator>>(QDataStream &in, Identity &id) +QDataStream& operator>>(QDataStream& in, Identity& id) { QVariantMap i; in >> i; diff --git a/src/common/identity.h b/src/common/identity.h index 4345642d..08f0ddc7 100644 --- a/src/common/identity.h +++ b/src/common/identity.h @@ -28,8 +28,8 @@ #include #include -#include "types.h" #include "syncableobject.h" +#include "types.h" class COMMON_EXPORT Identity : public SyncableObject { @@ -56,80 +56,80 @@ class COMMON_EXPORT Identity : public SyncableObject Q_PROPERTY(QString partReason READ partReason WRITE setPartReason) Q_PROPERTY(QString quitReason READ quitReason WRITE setQuitReason) -public : - Identity(IdentityId id = 0, QObject *parent = nullptr); - Identity(const Identity &other, QObject *parent = nullptr); +public: + Identity(IdentityId id = 0, QObject* parent = nullptr); + Identity(const Identity& other, QObject* parent = nullptr); void setToDefaults(); - bool operator==(const Identity &other) const; - bool operator!=(const Identity &other) const; + bool operator==(const Identity& other) const; + bool operator!=(const Identity& other) const; inline bool isValid() const { return id().isValid(); } inline IdentityId id() const { return _identityId; } - inline const QString &identityName() const { return _identityName; } - inline const QString &realName() const { return _realName; } - inline const QStringList &nicks() const { return _nicks; } - inline const QString &awayNick() const { return _awayNick; } + inline const QString& identityName() const { return _identityName; } + inline const QString& realName() const { return _realName; } + inline const QStringList& nicks() const { return _nicks; } + inline const QString& awayNick() const { return _awayNick; } inline bool awayNickEnabled() const { return _awayNickEnabled; } - inline const QString &awayReason() const { return _awayReason; } + inline const QString& awayReason() const { return _awayReason; } inline bool awayReasonEnabled() const { return _awayReasonEnabled; } inline bool autoAwayEnabled() const { return _autoAwayEnabled; } inline int autoAwayTime() const { return _autoAwayTime; } - inline const QString &autoAwayReason() const { return _autoAwayReason; } + inline const QString& autoAwayReason() const { return _autoAwayReason; } inline bool autoAwayReasonEnabled() const { return _autoAwayReasonEnabled; } inline bool detachAwayEnabled() const { return _detachAwayEnabled; } - inline const QString &detachAwayReason() const { return _detachAwayReason; } + inline const QString& detachAwayReason() const { return _detachAwayReason; } inline bool detachAwayReasonEnabled() const { return _detachAwayReasonEnabled; } - inline const QString &ident() const { return _ident; } - inline const QString &kickReason() const { return _kickReason; } - inline const QString &partReason() const { return _partReason; } - inline const QString &quitReason() const { return _quitReason; } + inline const QString& ident() const { return _ident; } + inline const QString& kickReason() const { return _kickReason; } + inline const QString& partReason() const { return _partReason; } + inline const QString& quitReason() const { return _quitReason; } public slots: void setId(IdentityId id); - void setIdentityName(const QString &name); - void setRealName(const QString &realName); - void setNicks(const QStringList &nicks); - void setAwayNick(const QString &awayNick); + void setIdentityName(const QString& name); + void setRealName(const QString& realName); + void setNicks(const QStringList& nicks); + void setAwayNick(const QString& awayNick); void setAwayNickEnabled(bool enabled); - void setAwayReason(const QString &awayReason); + void setAwayReason(const QString& awayReason); void setAwayReasonEnabled(bool enabled); void setAutoAwayEnabled(bool enabled); void setAutoAwayTime(int time); - void setAutoAwayReason(const QString &reason); + void setAutoAwayReason(const QString& reason); void setAutoAwayReasonEnabled(bool enabled); void setDetachAwayEnabled(bool enabled); - void setDetachAwayReason(const QString &reason); + void setDetachAwayReason(const QString& reason); void setDetachAwayReasonEnabled(bool enabled); - void setIdent(const QString &ident); - void setKickReason(const QString &reason); - void setPartReason(const QString &reason); - void setQuitReason(const QString &reason); + void setIdent(const QString& ident); + void setKickReason(const QString& reason); + void setPartReason(const QString& reason); + void setQuitReason(const QString& reason); - void copyFrom(const Identity &other); + void copyFrom(const Identity& other); signals: void idSet(IdentityId id); -// void identityNameSet(const QString &name); -// void realNameSet(const QString &realName); - void nicksSet(const QStringList &nicks); -// void awayNickSet(const QString &awayNick); -// void awayNickEnabledSet(bool); -// void awayReasonSet(const QString &awayReason); -// void awayReasonEnabledSet(bool); -// void autoAwayEnabledSet(bool); -// void autoAwayTimeSet(int); -// void autoAwayReasonSet(const QString &); -// void autoAwayReasonEnabledSet(bool); -// void detachAwayEnabledSet(bool); -// void detachAwayReasonSet(const QString &); -// void detachAwayReasonEnabledSet(bool); -// void identSet(const QString &); -// void kickReasonSet(const QString &); -// void partReasonSet(const QString &); -// void quitReasonSet(const QString &); + // void identityNameSet(const QString &name); + // void realNameSet(const QString &realName); + void nicksSet(const QStringList& nicks); + // void awayNickSet(const QString &awayNick); + // void awayNickEnabledSet(bool); + // void awayReasonSet(const QString &awayReason); + // void awayReasonEnabledSet(bool); + // void autoAwayEnabledSet(bool); + // void autoAwayTimeSet(int); + // void autoAwayReasonSet(const QString &); + // void autoAwayReasonEnabledSet(bool); + // void detachAwayEnabledSet(bool); + // void detachAwayReasonSet(const QString &); + // void detachAwayReasonEnabledSet(bool); + // void identSet(const QString &); + // void kickReasonSet(const QString &); + // void partReasonSet(const QString &); + // void quitReasonSet(const QString &); private: IdentityId _identityId; @@ -152,18 +152,17 @@ private: QString defaultNick(); QString defaultRealName(); - friend QDataStream &operator>>(QDataStream &in, Identity &identity); + friend QDataStream& operator>>(QDataStream& in, Identity& identity); }; - -QDataStream &operator<<(QDataStream &out, Identity identity); -QDataStream &operator>>(QDataStream &in, Identity &identity); +QDataStream& operator<<(QDataStream& out, Identity identity); +QDataStream& operator>>(QDataStream& in, Identity& identity); Q_DECLARE_METATYPE(Identity) #ifdef HAVE_SSL -#include -#include +# include +# include class COMMON_EXPORT CertManager : public SyncableObject { @@ -173,17 +172,19 @@ class COMMON_EXPORT CertManager : public SyncableObject Q_PROPERTY(QByteArray sslKey READ sslKeyPem WRITE setSslKey) Q_PROPERTY(QByteArray sslCert READ sslCertPem WRITE setSslCert) -public : - CertManager(IdentityId id, QObject *parent = nullptr) : SyncableObject(QString::number(id.toInt()), parent) {} +public: + CertManager(IdentityId id, QObject* parent = nullptr) + : SyncableObject(QString::number(id.toInt()), parent) + {} - virtual const QSslKey &sslKey() const = 0; + virtual const QSslKey& sslKey() const = 0; inline QByteArray sslKeyPem() const { return sslKey().toPem(); } - virtual const QSslCertificate &sslCert() const = 0; + virtual const QSslCertificate& sslCert() const = 0; inline QByteArray sslCertPem() const { return sslCert().toPem(); } public slots: - inline virtual void setSslKey(const QByteArray &encoded) { SYNC(ARG(encoded)) } - inline virtual void setSslCert(const QByteArray &encoded) { SYNC(ARG(encoded)) } + inline virtual void setSslKey(const QByteArray& encoded) { SYNC(ARG(encoded)) } + inline virtual void setSslCert(const QByteArray& encoded) { SYNC(ARG(encoded)) } }; -#endif // HAVE_SSL +#endif // HAVE_SSL diff --git a/src/common/ignorelistmanager.cpp b/src/common/ignorelistmanager.cpp index 4871b746..3d9ae5ff 100644 --- a/src/common/ignorelistmanager.cpp +++ b/src/common/ignorelistmanager.cpp @@ -20,11 +20,11 @@ #include "ignorelistmanager.h" -#include #include #include +#include -IgnoreListManager &IgnoreListManager::operator=(const IgnoreListManager &other) +IgnoreListManager& IgnoreListManager::operator=(const IgnoreListManager& other) { if (this == &other) return *this; @@ -34,8 +34,7 @@ IgnoreListManager &IgnoreListManager::operator=(const IgnoreListManager &other) return *this; } - -int IgnoreListManager::indexOf(const QString &ignore) const +int IgnoreListManager::indexOf(const QString& ignore) const { for (int i = 0; i < _ignoreList.count(); i++) { if (_ignoreList[i].contents() == ignore) @@ -44,7 +43,6 @@ int IgnoreListManager::indexOf(const QString &ignore) const return -1; } - QVariantMap IgnoreListManager::initIgnoreList() const { QVariantMap ignoreListMap; @@ -76,8 +74,7 @@ QVariantMap IgnoreListManager::initIgnoreList() const return ignoreListMap; } - -void IgnoreListManager::initSetIgnoreList(const QVariantMap &ignoreList) +void IgnoreListManager::initSetIgnoreList(const QVariantMap& ignoreList) { QVariantList ignoreType = ignoreList["ignoreType"].toList(); QStringList ignoreRule = ignoreList["ignoreRule"].toStringList(); @@ -88,42 +85,50 @@ void IgnoreListManager::initSetIgnoreList(const QVariantMap &ignoreList) QVariantList isActive = ignoreList["isActive"].toList(); int count = ignoreRule.count(); - if (count != scopeRule.count() || count != isRegEx.count() || - count != scope.count() || count != strictness.count() || count != ignoreType.count() || count != isActive.count()) { + if (count != scopeRule.count() || count != isRegEx.count() || count != scope.count() || count != strictness.count() + || count != ignoreType.count() || count != isActive.count()) { qWarning() << "Corrupted IgnoreList settings! (Count mismatch)"; return; } _ignoreList.clear(); for (int i = 0; i < ignoreRule.count(); i++) { - _ignoreList << IgnoreListItem(static_cast(ignoreType[i].toInt()), ignoreRule[i], isRegEx[i].toBool(), - static_cast(strictness[i].toInt()), static_cast(scope[i].toInt()), - scopeRule[i], isActive[i].toBool()); + _ignoreList << IgnoreListItem(static_cast(ignoreType[i].toInt()), + ignoreRule[i], + isRegEx[i].toBool(), + static_cast(strictness[i].toInt()), + static_cast(scope[i].toInt()), + scopeRule[i], + isActive[i].toBool()); } } - /* since overloaded methods aren't syncable (yet?) we can't use that anymore void IgnoreListManager::addIgnoreListItem(const IgnoreListItem &item) { addIgnoreListItem(item.type(), item.contents(), item.isRegEx(), item.strictness(), item.scope(), item.scopeRule(), item.isEnabled()); } */ -void IgnoreListManager::addIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness, - int scope, const QString &scopeRule, bool isActive) +void IgnoreListManager::addIgnoreListItem( + int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive) { if (contains(ignoreRule)) { return; } - IgnoreListItem newItem = IgnoreListItem(static_cast(type), ignoreRule, isRegEx, static_cast(strictness), - static_cast(scope), scopeRule, isActive); + IgnoreListItem newItem = IgnoreListItem(static_cast(type), + ignoreRule, + isRegEx, + static_cast(strictness), + static_cast(scope), + scopeRule, + isActive); _ignoreList << newItem; SYNC(ARG(type), ARG(ignoreRule), ARG(isRegEx), ARG(strictness), ARG(scope), ARG(scopeRule), ARG(isActive)) } - -IgnoreListManager::StrictnessType IgnoreListManager::_match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName) +IgnoreListManager::StrictnessType IgnoreListManager::_match( + const QString& msgContents, const QString& msgSender, Message::Type msgType, const QString& network, const QString& bufferName) { // We method don't rely on a proper Message object to make this method more versatile. // This allows us to use it in the core with unprocessed Messages or in the Client @@ -131,11 +136,10 @@ IgnoreListManager::StrictnessType IgnoreListManager::_match(const QString &msgCo if (!(msgType & (Message::Plain | Message::Notice | Message::Action))) return UnmatchedStrictness; - foreach(IgnoreListItem item, _ignoreList) { + foreach (IgnoreListItem item, _ignoreList) { if (!item.isEnabled() || item.type() == CtcpIgnore) continue; - if (item.scope() == GlobalScope - || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network)) + if (item.scope() == GlobalScope || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network)) || (item.scope() == ChannelScope && item.scopeRuleMatcher().match(bufferName))) { QString str; if (item.type() == MessageIgnore) @@ -143,11 +147,11 @@ IgnoreListManager::StrictnessType IgnoreListManager::_match(const QString &msgCo else str = msgSender; -// qDebug() << "IgnoreListManager::match: "; -// qDebug() << "string: " << str; -// qDebug() << "pattern: " << ruleRx.pattern(); -// qDebug() << "scopeRule: " << item.scopeRule; -// qDebug() << "now testing"; + // qDebug() << "IgnoreListManager::match: "; + // qDebug() << "string: " << str; + // qDebug() << "pattern: " << ruleRx.pattern(); + // qDebug() << "scopeRule: " << item.scopeRule; + // qDebug() << "now testing"; if (item.contentsMatcher().match(str)) { return item.strictness(); } @@ -156,15 +160,13 @@ IgnoreListManager::StrictnessType IgnoreListManager::_match(const QString &msgCo return UnmatchedStrictness; } - -void IgnoreListManager::removeIgnoreListItem(const QString &ignoreRule) +void IgnoreListManager::removeIgnoreListItem(const QString& ignoreRule) { removeAt(indexOf(ignoreRule)); SYNC(ARG(ignoreRule)) } - -void IgnoreListManager::toggleIgnoreRule(const QString &ignoreRule) +void IgnoreListManager::toggleIgnoreRule(const QString& ignoreRule) { int idx = indexOf(ignoreRule); if (idx == -1) @@ -173,20 +175,16 @@ void IgnoreListManager::toggleIgnoreRule(const QString &ignoreRule) SYNC(ARG(ignoreRule)) } - -bool IgnoreListManager::ctcpMatch(const QString sender, const QString &network, const QString &type) +bool IgnoreListManager::ctcpMatch(const QString sender, const QString& network, const QString& type) { - foreach(IgnoreListItem item, _ignoreList) { + foreach (IgnoreListItem item, _ignoreList) { if (!item.isEnabled()) continue; - if (item.scope() == GlobalScope - || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network))) { - + if (item.scope() == GlobalScope || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network))) { // For CTCP ignore rules, use ctcpSender if (item.senderCTCPMatcher().match(sender)) { // Sender matches, check types - if (item.ctcpTypes().isEmpty() - || item.ctcpTypes().contains(type, Qt::CaseInsensitive)) { + if (item.ctcpTypes().isEmpty() || item.ctcpTypes().contains(type, Qt::CaseInsensitive)) { // Either all types are blocked, or type matches return true; } @@ -196,23 +194,16 @@ bool IgnoreListManager::ctcpMatch(const QString sender, const QString &network, return false; } - /************************************************************************** * IgnoreListItem *************************************************************************/ -bool IgnoreListManager::IgnoreListItem::operator!=(const IgnoreListItem &other) const +bool IgnoreListManager::IgnoreListItem::operator!=(const IgnoreListItem& other) const { - return (_type != other._type || - _contents != other._contents || - _isRegEx != other._isRegEx || - _strictness != other._strictness || - _scope != other._scope || - _scopeRule != other._scopeRule || - _isEnabled != other._isEnabled); + return (_type != other._type || _contents != other._contents || _isRegEx != other._isRegEx || _strictness != other._strictness + || _scope != other._scope || _scopeRule != other._scopeRule || _isEnabled != other._isEnabled); // Don't compare ExpressionMatch objects as they are created as needed from the above } - void IgnoreListManager::IgnoreListItem::determineExpressions() const { // Don't update if not needed @@ -222,9 +213,7 @@ void IgnoreListManager::IgnoreListItem::determineExpressions() const // Set up matching rules // Message is either wildcard or regex - ExpressionMatch::MatchMode contentsMode = - _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : - ExpressionMatch::MatchMode::MatchWildcard; + ExpressionMatch::MatchMode contentsMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchWildcard; // Ignore rules are always case-insensitive // Scope matching is always wildcard @@ -242,8 +231,7 @@ void IgnoreListManager::IgnoreListItem::determineExpressions() const } // Scope rules are always multiple wildcard entries // (Adding a regex option would be awesome, but requires a backwards-compatible protocol change) - _scopeRuleMatch = ExpressionMatch(_scopeRule, - ExpressionMatch::MatchMode::MatchMultiWildcard, false); + _scopeRuleMatch = ExpressionMatch(_scopeRule, ExpressionMatch::MatchMode::MatchMultiWildcard, false); _cacheInvalid = false; } diff --git a/src/common/ignorelistmanager.h b/src/common/ignorelistmanager.h index 79acff65..d3d1d873 100644 --- a/src/common/ignorelistmanager.h +++ b/src/common/ignorelistmanager.h @@ -22,10 +22,11 @@ #include "common-export.h" +#include + +#include #include #include -#include -#include #include "expressionmatch.h" #include "message.h" @@ -37,22 +38,29 @@ class COMMON_EXPORT IgnoreListManager : public SyncableObject SYNCABLE_OBJECT public: - inline IgnoreListManager(QObject *parent = nullptr) : SyncableObject(parent) { setAllowClientUpdates(true); } - IgnoreListManager &operator=(const IgnoreListManager &other); + inline IgnoreListManager(QObject* parent = nullptr) + : SyncableObject(parent) + { + setAllowClientUpdates(true); + } + IgnoreListManager& operator=(const IgnoreListManager& other); - enum IgnoreType { + enum IgnoreType + { SenderIgnore, MessageIgnore, CtcpIgnore }; - enum StrictnessType { + enum StrictnessType + { UnmatchedStrictness = 0, SoftStrictness = 1, HardStrictness = 2 }; - enum ScopeType { + enum ScopeType + { GlobalScope, NetworkScope, ChannelScope, @@ -61,7 +69,8 @@ public: /** * Individual ignore list rule */ - class COMMON_EXPORT IgnoreListItem { + class COMMON_EXPORT IgnoreListItem + { public: /** * Construct an empty ignore rule @@ -82,11 +91,14 @@ public: * @param scopeRule String representing a scope rule expression to match * @param isEnabled True if enabled, otherwise false */ - IgnoreListItem(IgnoreType type, QString contents, bool isRegEx, - StrictnessType strictness, ScopeType scope, QString scopeRule, - bool isEnabled) - : _contents(std::move(contents)), _isRegEx(isRegEx), _strictness(strictness), - _scope(scope), _scopeRule(std::move(scopeRule)), _isEnabled(isEnabled) + IgnoreListItem( + IgnoreType type, QString contents, bool isRegEx, StrictnessType strictness, ScopeType scope, QString scopeRule, bool isEnabled) + : _contents(std::move(contents)) + , _isRegEx(isRegEx) + , _strictness(strictness) + , _scope(scope) + , _scopeRule(std::move(scopeRule)) + , _isEnabled(isEnabled) { // Allow passing empty "contents" as they can happen when editing an ignore rule @@ -110,15 +122,14 @@ public: * * @return IgnoreType of the rule */ - inline IgnoreType type() const { - return _type; - } + inline IgnoreType type() const { return _type; } /** * Sets the type of this ignore rule * * @param type IgnoreType of the rule */ - inline void setType(IgnoreType type) { + inline void setType(IgnoreType type) + { // Handle CTCP ignores if (type == CtcpIgnore) { // This is not performance-intensive; sticking with QRegExp for Qt 4 is fine @@ -159,15 +170,14 @@ public: * * @return String representing a phrase or expression to match */ - inline QString contents() const { - return _contents; - } + inline QString contents() const { return _contents; } /** * Sets the message contents this rule matches * * @param contents String representing a phrase or expression to match */ - inline void setContents(const QString &contents) { + inline void setContents(const QString& contents) + { // Allow passing empty "contents" as they can happen when editing an ignore rule _contents = contents; _cacheInvalid = true; @@ -178,15 +188,14 @@ public: * * @return True if regular expression, otherwise false */ - inline bool isRegEx() const { - return _isRegEx; - } + inline bool isRegEx() const { return _isRegEx; } /** * Sets if this rule is a regular expression rule * * @param isRegEx True if regular expression, otherwise false */ - inline void setIsRegEx(bool isRegEx) { + inline void setIsRegEx(bool isRegEx) + { _isRegEx = isRegEx; _cacheInvalid = true; } @@ -196,34 +205,26 @@ public: * * @return StrictnessType of the rule */ - inline StrictnessType strictness() const { - return _strictness; - } + inline StrictnessType strictness() const { return _strictness; } /** * Sets the strictness of this ignore rule * * @param strictness StrictnessType of the rule */ - inline void setStrictness(StrictnessType strictness) { - _strictness = strictness; - } + inline void setStrictness(StrictnessType strictness) { _strictness = strictness; } /** * Gets what to match scope rule against * * @return ScopeType of the rule */ - inline ScopeType scope() const { - return _scope; - } + inline ScopeType scope() const { return _scope; } /** * Sets what to match scope rule against * * @param type ScopeType of the rule */ - inline void setScope(ScopeType scope) { - _scope = scope; - } + inline void setScope(ScopeType scope) { _scope = scope; } /** * Gets the scope rule this rule matches @@ -232,15 +233,14 @@ public: * * @return String representing a phrase or expression to match */ - inline QString scopeRule() const { - return _scopeRule; - } + inline QString scopeRule() const { return _scopeRule; } /** * Sets the scope rule this rule matches * * @param scopeRule String representing a phrase or expression to match */ - inline void setScopeRule(const QString &scopeRule) { + inline void setScopeRule(const QString& scopeRule) + { _scopeRule = scopeRule; _cacheInvalid = true; } @@ -250,33 +250,28 @@ public: * * @return True if enabled, otherwise false */ - inline bool isEnabled() const { - return _isEnabled; - } + inline bool isEnabled() const { return _isEnabled; } /** * Sets if this rule is enabled and active * * @param isEnabled True if enabled, otherwise false */ - inline void setIsEnabled(bool isEnabled) { - _isEnabled = isEnabled; - } + inline void setIsEnabled(bool isEnabled) { _isEnabled = isEnabled; } /** * Gets the ignored CTCP types for CTCP ignores * * @return List of CTCP types to ignore, or empty for all */ - inline QStringList ctcpTypes() const { - return _cacheCtcpTypes; - } + inline QStringList ctcpTypes() const { return _cacheCtcpTypes; } /** * Gets the expression matcher for the message contents, caching if needed * * @return Expression matcher to compare with message contents */ - inline ExpressionMatch contentsMatcher() const { + inline ExpressionMatch contentsMatcher() const + { if (_cacheInvalid) { determineExpressions(); } @@ -288,7 +283,8 @@ public: * * @return Expression matcher to compare with scope */ - inline ExpressionMatch scopeRuleMatcher() const { + inline ExpressionMatch scopeRuleMatcher() const + { if (_cacheInvalid) { determineExpressions(); } @@ -300,14 +296,15 @@ public: * * @return Expression matcher to compare with message contents */ - inline ExpressionMatch senderCTCPMatcher() const { + inline ExpressionMatch senderCTCPMatcher() const + { if (_cacheInvalid) { determineExpressions(); } return _ctcpSenderMatch; } - bool operator!=(const IgnoreListItem &other) const; + bool operator!=(const IgnoreListItem& other) const; private: /** @@ -323,87 +320,96 @@ public: QString _scopeRule = {}; bool _isEnabled = true; - QString _cacheCtcpSender = {}; ///< For CTCP rules, precalculate sender - QStringList _cacheCtcpTypes = {}; ///< For CTCP rules, precalculate types + QString _cacheCtcpSender = {}; ///< For CTCP rules, precalculate sender + QStringList _cacheCtcpTypes = {}; ///< For CTCP rules, precalculate types // These represent internal cache and should be safe to mutate in 'const' functions // See https://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration - mutable bool _cacheInvalid = true; ///< If true, match cache needs redone - mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message - mutable ExpressionMatch _scopeRuleMatch = {}; ///< Expression match cache for scope rule - mutable ExpressionMatch _ctcpSenderMatch = {}; ///< Expression match cache for CTCP nick + mutable bool _cacheInvalid = true; ///< If true, match cache needs redone + mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message + mutable ExpressionMatch _scopeRuleMatch = {}; ///< Expression match cache for scope rule + mutable ExpressionMatch _ctcpSenderMatch = {}; ///< Expression match cache for CTCP nick }; using IgnoreList = QList; - int indexOf(const QString &ignore) const; - inline bool contains(const QString &ignore) const { return indexOf(ignore) != -1; } + int indexOf(const QString& ignore) const; + inline bool contains(const QString& ignore) const { return indexOf(ignore) != -1; } inline bool isEmpty() const { return _ignoreList.isEmpty(); } inline int count() const { return _ignoreList.count(); } inline void removeAt(int index) { _ignoreList.removeAt(index); } - inline IgnoreListItem &operator[](int i) { return _ignoreList[i]; } - inline const IgnoreListItem &operator[](int i) const { return _ignoreList.at(i); } - inline const IgnoreList &ignoreList() const { return _ignoreList; } + inline IgnoreListItem& operator[](int i) { return _ignoreList[i]; } + inline const IgnoreListItem& operator[](int i) const { return _ignoreList.at(i); } + inline const IgnoreList& ignoreList() const { return _ignoreList; } //! Check if a message matches the IgnoreRule /** This method checks if a message matches the users ignorelist. - * \param msg The Message that should be checked - * \param network The networkname the message belongs to - * \return UnmatchedStrictness, HardStrictness or SoftStrictness representing the match type - */ - inline StrictnessType match(const Message &msg, const QString &network = QString()) { return _match(msg.contents(), msg.sender(), msg.type(), network, msg.bufferInfo().bufferName()); } + * \param msg The Message that should be checked + * \param network The networkname the message belongs to + * \return UnmatchedStrictness, HardStrictness or SoftStrictness representing the match type + */ + inline StrictnessType match(const Message& msg, const QString& network = QString()) + { + return _match(msg.contents(), msg.sender(), msg.type(), network, msg.bufferInfo().bufferName()); + } - bool ctcpMatch(const QString sender, const QString &network, const QString &type = QString()); + bool ctcpMatch(const QString sender, const QString& network, const QString& type = QString()); -// virtual void addIgnoreListItem(const IgnoreListItem &item); + // virtual void addIgnoreListItem(const IgnoreListItem &item); public slots: virtual QVariantMap initIgnoreList() const; - virtual void initSetIgnoreList(const QVariantMap &ignoreList); + virtual void initSetIgnoreList(const QVariantMap& ignoreList); //! Request removal of an ignore rule based on the rule itself. /** Use this method if you want to remove a single ignore rule - * and get that synced with the core immediately. - * \param ignoreRule A valid ignore rule - */ - virtual inline void requestRemoveIgnoreListItem(const QString &ignoreRule) { REQUEST(ARG(ignoreRule)) } - virtual void removeIgnoreListItem(const QString &ignoreRule); + * and get that synced with the core immediately. + * \param ignoreRule A valid ignore rule + */ + virtual inline void requestRemoveIgnoreListItem(const QString& ignoreRule) { REQUEST(ARG(ignoreRule)) } + virtual void removeIgnoreListItem(const QString& ignoreRule); //! Request toggling of "isActive" flag of a given ignore rule. /** Use this method if you want to toggle the "isActive" flag of a single ignore rule - * and get that synced with the core immediately. - * \param ignoreRule A valid ignore rule - */ - virtual inline void requestToggleIgnoreRule(const QString &ignoreRule) { REQUEST(ARG(ignoreRule)) } - virtual void toggleIgnoreRule(const QString &ignoreRule); + * and get that synced with the core immediately. + * \param ignoreRule A valid ignore rule + */ + virtual inline void requestToggleIgnoreRule(const QString& ignoreRule) { REQUEST(ARG(ignoreRule)) } + virtual void toggleIgnoreRule(const QString& ignoreRule); //! Request an IgnoreListItem to be added to the ignore list /** Items added to the list with this method, get immediately synced with the core - * \param type The IgnoreType of the new rule - * \param ignoreRule The rule itself - * \param isRegEx Signals if the rule should be interpreted as a regular expression - * \param strictness Th StrictnessType that should be applied - * \param scope The ScopeType that should be set - * \param scopeRule A string of semi-colon separated network- or channelnames - * \param isActive Signals if the rule is enabled or not - */ - virtual inline void requestAddIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness, - int scope, const QString &scopeRule, bool isActive) + * \param type The IgnoreType of the new rule + * \param ignoreRule The rule itself + * \param isRegEx Signals if the rule should be interpreted as a regular expression + * \param strictness Th StrictnessType that should be applied + * \param scope The ScopeType that should be set + * \param scopeRule A string of semi-colon separated network- or channelnames + * \param isActive Signals if the rule is enabled or not + */ + virtual inline void requestAddIgnoreListItem( + int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive) { REQUEST(ARG(type), ARG(ignoreRule), ARG(isRegEx), ARG(strictness), ARG(scope), ARG(scopeRule), ARG(isActive)) } - - virtual void addIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness, - int scope, const QString &scopeRule, bool isActive); + virtual void addIgnoreListItem( + int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive); protected: - void setIgnoreList(const QList &ignoreList) { _ignoreList = ignoreList; } + void setIgnoreList(const QList& ignoreList) { _ignoreList = ignoreList; } - StrictnessType _match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName); + StrictnessType _match( + const QString& msgContents, const QString& msgSender, Message::Type msgType, const QString& network, const QString& bufferName); signals: - void ignoreAdded(IgnoreType type, const QString &ignoreRule, bool isRegex, StrictnessType strictness, ScopeType scope, const QVariant &scopeRule, bool isActive); + void ignoreAdded(IgnoreType type, + const QString& ignoreRule, + bool isRegex, + StrictnessType strictness, + ScopeType scope, + const QVariant& scopeRule, + bool isActive); private: IgnoreList _ignoreList; diff --git a/src/common/internalpeer.cpp b/src/common/internalpeer.cpp index b538d2a3..2e0514a2 100644 --- a/src/common/internalpeer.cpp +++ b/src/common/internalpeer.cpp @@ -19,11 +19,12 @@ ***************************************************************************/ #include "internalpeer.h" + #include "util.h" using namespace Protocol; -InternalPeer::InternalPeer(QObject *parent) +InternalPeer::InternalPeer(QObject* parent) : Peer(nullptr, parent) { static bool registered = []() { @@ -39,7 +40,6 @@ InternalPeer::InternalPeer(QObject *parent) setFeatures(Quassel::Features{}); } - InternalPeer::~InternalPeer() { if (_isOpen) { @@ -47,63 +47,53 @@ InternalPeer::~InternalPeer() } } - QString InternalPeer::description() const { return tr("internal connection"); } - QString InternalPeer::address() const { return tr("internal connection"); } - quint16 InternalPeer::port() const { return 0; } - bool InternalPeer::isOpen() const { return _isOpen; } - bool InternalPeer::isSecure() const { return true; } - bool InternalPeer::isLocal() const { return true; } - -void InternalPeer::close(const QString &reason) +void InternalPeer::close(const QString& reason) { Q_UNUSED(reason); _isOpen = false; } - int InternalPeer::lag() const { return 0; } - -::SignalProxy *InternalPeer::signalProxy() const +::SignalProxy* InternalPeer::signalProxy() const { return _proxy; } - -void InternalPeer::setSignalProxy(::SignalProxy *proxy) +void InternalPeer::setSignalProxy(::SignalProxy* proxy) { if (!proxy && _proxy) { _proxy = nullptr; @@ -123,24 +113,30 @@ void InternalPeer::setSignalProxy(::SignalProxy *proxy) qWarning() << Q_FUNC_INFO << "Changing the SignalProxy is not supported!"; } - -void InternalPeer::setPeer(InternalPeer *peer) -{ - connect(peer, selectOverload(&InternalPeer::dispatchMessage), - this, selectOverload(&InternalPeer::handleMessage)); - connect(peer, selectOverload(&InternalPeer::dispatchMessage), - this, selectOverload(&InternalPeer::handleMessage)); - connect(peer, selectOverload(&InternalPeer::dispatchMessage), - this, selectOverload(&InternalPeer::handleMessage)); - connect(peer, selectOverload(&InternalPeer::dispatchMessage), - this, selectOverload(&InternalPeer::handleMessage)); +void InternalPeer::setPeer(InternalPeer* peer) +{ + connect(peer, + selectOverload(&InternalPeer::dispatchMessage), + this, + selectOverload(&InternalPeer::handleMessage)); + connect(peer, + selectOverload(&InternalPeer::dispatchMessage), + this, + selectOverload(&InternalPeer::handleMessage)); + connect(peer, + selectOverload(&InternalPeer::dispatchMessage), + this, + selectOverload(&InternalPeer::handleMessage)); + connect(peer, + selectOverload(&InternalPeer::dispatchMessage), + this, + selectOverload(&InternalPeer::handleMessage)); connect(peer, &Peer::disconnected, this, &InternalPeer::peerDisconnected); _isOpen = true; } - void InternalPeer::peerDisconnected() { disconnect(sender(), nullptr, this, nullptr); @@ -150,59 +146,50 @@ void InternalPeer::peerDisconnected() } } - -void InternalPeer::dispatch(const SyncMessage &msg) +void InternalPeer::dispatch(const SyncMessage& msg) { emit dispatchMessage(msg); } - -void InternalPeer::dispatch(const RpcCall &msg) +void InternalPeer::dispatch(const RpcCall& msg) { emit dispatchMessage(msg); } - -void InternalPeer::dispatch(const InitRequest &msg) +void InternalPeer::dispatch(const InitRequest& msg) { emit dispatchMessage(msg); } - -void InternalPeer::dispatch(const InitData &msg) +void InternalPeer::dispatch(const InitData& msg) { emit dispatchMessage(msg); } - -void InternalPeer::handleMessage(const Protocol::SyncMessage &msg) +void InternalPeer::handleMessage(const Protocol::SyncMessage& msg) { handle(msg); } - -void InternalPeer::handleMessage(const Protocol::RpcCall &msg) +void InternalPeer::handleMessage(const Protocol::RpcCall& msg) { handle(msg); } - -void InternalPeer::handleMessage(const Protocol::InitRequest &msg) +void InternalPeer::handleMessage(const Protocol::InitRequest& msg) { handle(msg); } - -void InternalPeer::handleMessage(const Protocol::InitData &msg) +void InternalPeer::handleMessage(const Protocol::InitData& msg) { handle(msg); } - template -void InternalPeer::handle(const T &msg) +void InternalPeer::handle(const T& msg) { - static auto setSourcePeer = [](Peer *peer) { + static auto setSourcePeer = [](Peer* peer) { auto p = SignalProxy::current(); if (p) { p->setSourcePeer(peer); diff --git a/src/common/internalpeer.h b/src/common/internalpeer.h index 62e070d9..6fdb062d 100644 --- a/src/common/internalpeer.h +++ b/src/common/internalpeer.h @@ -34,7 +34,7 @@ class COMMON_EXPORT InternalPeer : public Peer Q_OBJECT public: - InternalPeer(QObject *parent = nullptr); + InternalPeer(QObject* parent = nullptr); ~InternalPeer() override; Protocol::Type protocol() const override { return Protocol::InternalProtocol; } @@ -43,11 +43,11 @@ public: QString address() const override; quint16 port() const override; - SignalProxy *signalProxy() const override; - void setSignalProxy(SignalProxy *proxy) override; + SignalProxy* signalProxy() const override; + void setSignalProxy(SignalProxy* proxy) override; - InternalPeer *peer() const; - void setPeer(InternalPeer *peer); + InternalPeer* peer() const; + void setPeer(InternalPeer* peer); bool isOpen() const override; bool isSecure() const override; @@ -55,46 +55,46 @@ public: int lag() const override; - void dispatch(const Protocol::SyncMessage &msg) override; - void dispatch(const Protocol::RpcCall &msg) override; - void dispatch(const Protocol::InitRequest &msg) override; - void dispatch(const Protocol::InitData &msg) override; + void dispatch(const Protocol::SyncMessage& msg) override; + void dispatch(const Protocol::RpcCall& msg) override; + void dispatch(const Protocol::InitRequest& msg) override; + void dispatch(const Protocol::InitData& msg) override; /* These are not needed for InternalPeer */ - void dispatch(const Protocol::RegisterClient &) override {} - void dispatch(const Protocol::ClientDenied &) override {} - void dispatch(const Protocol::ClientRegistered &) override {} - void dispatch(const Protocol::SetupData &) override {} - void dispatch(const Protocol::SetupFailed &) override {} - void dispatch(const Protocol::SetupDone &) override {} - void dispatch(const Protocol::Login &) override {} - void dispatch(const Protocol::LoginFailed &) override {} - void dispatch(const Protocol::LoginSuccess &) override {} - void dispatch(const Protocol::SessionState &) override {} + void dispatch(const Protocol::RegisterClient&) override {} + void dispatch(const Protocol::ClientDenied&) override {} + void dispatch(const Protocol::ClientRegistered&) override {} + void dispatch(const Protocol::SetupData&) override {} + void dispatch(const Protocol::SetupFailed&) override {} + void dispatch(const Protocol::SetupDone&) override {} + void dispatch(const Protocol::Login&) override {} + void dispatch(const Protocol::LoginFailed&) override {} + void dispatch(const Protocol::LoginSuccess&) override {} + void dispatch(const Protocol::SessionState&) override {} public slots: - void close(const QString &reason = QString()) override; + void close(const QString& reason = QString()) override; signals: - void dispatchMessage(const Protocol::SyncMessage &msg); - void dispatchMessage(const Protocol::RpcCall &msg); - void dispatchMessage(const Protocol::InitRequest &msg); - void dispatchMessage(const Protocol::InitData &msg); + void dispatchMessage(const Protocol::SyncMessage& msg); + void dispatchMessage(const Protocol::RpcCall& msg); + void dispatchMessage(const Protocol::InitRequest& msg); + void dispatchMessage(const Protocol::InitData& msg); private slots: void peerDisconnected(); - void handleMessage(const Protocol::SyncMessage &msg); - void handleMessage(const Protocol::RpcCall &msg); - void handleMessage(const Protocol::InitRequest &msg); - void handleMessage(const Protocol::InitData &msg); + void handleMessage(const Protocol::SyncMessage& msg); + void handleMessage(const Protocol::RpcCall& msg); + void handleMessage(const Protocol::InitRequest& msg); + void handleMessage(const Protocol::InitData& msg); private: template - void handle(const T &msg); + void handle(const T& msg); private: - SignalProxy *_proxy{nullptr}; + SignalProxy* _proxy{nullptr}; bool _isOpen{true}; }; diff --git a/src/common/irccap.h b/src/common/irccap.h index b1c9c5a0..147a7671 100644 --- a/src/common/irccap.h +++ b/src/common/irccap.h @@ -32,138 +32,136 @@ */ namespace IrcCap { - // NOTE: If you add or modify the constants below, update the knownCaps list. - - /** - * Account change notification. - * - * http://ircv3.net/specs/extensions/account-notify-3.1.html - */ - const QString ACCOUNT_NOTIFY = "account-notify"; - - /** - * Magic number for WHOX, used to ignore user-requested WHOX replies from servers - * - * If a user initiates a WHOX, there's no easy way to tell what fields were requested. It's - * simpler to not attempt to parse data from user-requested WHOX replies. - */ - const uint ACCOUNT_NOTIFY_WHOX_NUM = 369; - - /** - * Away change notification. - * - * http://ircv3.net/specs/extensions/away-notify-3.1.html - */ - const QString AWAY_NOTIFY = "away-notify"; - - /** - * Capability added/removed notification. - * - * This is implicitly enabled via CAP LS 302, and is here for servers that only partially - * support IRCv3.2. - * - * http://ircv3.net/specs/extensions/cap-notify-3.2.html - */ - const QString CAP_NOTIFY = "cap-notify"; - - /** - * Hostname/user changed notification. - * - * http://ircv3.net/specs/extensions/chghost-3.2.html - */ - const QString CHGHOST = "chghost"; - - /** - * Extended join information. - * - * http://ircv3.net/specs/extensions/extended-join-3.1.html - */ - const QString EXTENDED_JOIN = "extended-join"; - - /** - * Multiple mode prefixes in MODE and WHO replies. - * - * http://ircv3.net/specs/extensions/multi-prefix-3.1.html - */ - const QString MULTI_PREFIX = "multi-prefix"; - - /** - * SASL authentication. - * - * http://ircv3.net/specs/extensions/sasl-3.2.html - */ - const QString SASL = "sasl"; - - /** - * Userhost in names replies. - * - * http://ircv3.net/specs/extensions/userhost-in-names-3.2.html - */ - const QString USERHOST_IN_NAMES = "userhost-in-names"; - - /** - * Vendor-specific capabilities - */ - namespace Vendor { - - /** - * Twitch.tv membership message support - * - * User list in a channel can be quite large and often non required for bot users and is then optional. - * - * From Twitch.tv documentation: - * "Adds membership state event data. By default, we do not send this data to clients without this capability." - * - * https://dev.twitch.tv/docs/v5/guides/irc/#twitch-irc-capability-membership - */ - const QString TWITCH_MEMBERSHIP = "twitch.tv/membership"; - - /** - * Self message support, as recognized by ZNC. - * - * Some servers (e.g. Bitlbee) assume self-message support; ZNC requires a capability - * instead. As self-message is already implemented, there's little reason to not do this. - * - * More information in the IRCv3 commit that removed the 'self-message' capability. - * - * https://github.com/ircv3/ircv3-specifications/commit/1bfba47843c2526707c902034b3395af934713c8 - */ - const QString ZNC_SELF_MESSAGE = "znc.in/self-message"; - } - - /** - * List of capabilities currently implemented and requested during capability negotiation. - */ - const QStringList knownCaps = QStringList { - ACCOUNT_NOTIFY, - AWAY_NOTIFY, - CAP_NOTIFY, - CHGHOST, - EXTENDED_JOIN, - MULTI_PREFIX, - SASL, - USERHOST_IN_NAMES, - Vendor::TWITCH_MEMBERSHIP, - Vendor::ZNC_SELF_MESSAGE - }; - // NOTE: If you modify the knownCaps list, update the constants above as needed. - - /** - * SASL authentication mechanisms - * - * http://ircv3.net/specs/extensions/sasl-3.1.html - */ - namespace SaslMech { - /** - * PLAIN authentication, e.g. hashed password - */ - const QString PLAIN = "PLAIN"; - - /** - * EXTERNAL authentication, e.g. SSL certificate and keys - */ - const QString EXTERNAL = "EXTERNAL"; - } -} - -#endif // IRCCAP_H +// NOTE: If you add or modify the constants below, update the knownCaps list. + +/** + * Account change notification. + * + * http://ircv3.net/specs/extensions/account-notify-3.1.html + */ +const QString ACCOUNT_NOTIFY = "account-notify"; + +/** + * Magic number for WHOX, used to ignore user-requested WHOX replies from servers + * + * If a user initiates a WHOX, there's no easy way to tell what fields were requested. It's + * simpler to not attempt to parse data from user-requested WHOX replies. + */ +const uint ACCOUNT_NOTIFY_WHOX_NUM = 369; + +/** + * Away change notification. + * + * http://ircv3.net/specs/extensions/away-notify-3.1.html + */ +const QString AWAY_NOTIFY = "away-notify"; + +/** + * Capability added/removed notification. + * + * This is implicitly enabled via CAP LS 302, and is here for servers that only partially + * support IRCv3.2. + * + * http://ircv3.net/specs/extensions/cap-notify-3.2.html + */ +const QString CAP_NOTIFY = "cap-notify"; + +/** + * Hostname/user changed notification. + * + * http://ircv3.net/specs/extensions/chghost-3.2.html + */ +const QString CHGHOST = "chghost"; + +/** + * Extended join information. + * + * http://ircv3.net/specs/extensions/extended-join-3.1.html + */ +const QString EXTENDED_JOIN = "extended-join"; + +/** + * Multiple mode prefixes in MODE and WHO replies. + * + * http://ircv3.net/specs/extensions/multi-prefix-3.1.html + */ +const QString MULTI_PREFIX = "multi-prefix"; + +/** + * SASL authentication. + * + * http://ircv3.net/specs/extensions/sasl-3.2.html + */ +const QString SASL = "sasl"; + +/** + * Userhost in names replies. + * + * http://ircv3.net/specs/extensions/userhost-in-names-3.2.html + */ +const QString USERHOST_IN_NAMES = "userhost-in-names"; + +/** + * Vendor-specific capabilities + */ +namespace Vendor { + +/** + * Twitch.tv membership message support + * + * User list in a channel can be quite large and often non required for bot users and is then optional. + * + * From Twitch.tv documentation: + * "Adds membership state event data. By default, we do not send this data to clients without this capability." + * + * https://dev.twitch.tv/docs/v5/guides/irc/#twitch-irc-capability-membership + */ +const QString TWITCH_MEMBERSHIP = "twitch.tv/membership"; + +/** + * Self message support, as recognized by ZNC. + * + * Some servers (e.g. Bitlbee) assume self-message support; ZNC requires a capability + * instead. As self-message is already implemented, there's little reason to not do this. + * + * More information in the IRCv3 commit that removed the 'self-message' capability. + * + * https://github.com/ircv3/ircv3-specifications/commit/1bfba47843c2526707c902034b3395af934713c8 + */ +const QString ZNC_SELF_MESSAGE = "znc.in/self-message"; +} // namespace Vendor + +/** + * List of capabilities currently implemented and requested during capability negotiation. + */ +const QStringList knownCaps = QStringList{ACCOUNT_NOTIFY, + AWAY_NOTIFY, + CAP_NOTIFY, + CHGHOST, + EXTENDED_JOIN, + MULTI_PREFIX, + SASL, + USERHOST_IN_NAMES, + Vendor::TWITCH_MEMBERSHIP, + Vendor::ZNC_SELF_MESSAGE}; +// NOTE: If you modify the knownCaps list, update the constants above as needed. + +/** + * SASL authentication mechanisms + * + * http://ircv3.net/specs/extensions/sasl-3.1.html + */ +namespace SaslMech { +/** + * PLAIN authentication, e.g. hashed password + */ +const QString PLAIN = "PLAIN"; + +/** + * EXTERNAL authentication, e.g. SSL certificate and keys + */ +const QString EXTERNAL = "EXTERNAL"; +} // namespace SaslMech +} // namespace IrcCap + +#endif // IRCCAP_H diff --git a/src/common/ircchannel.cpp b/src/common/ircchannel.cpp index 37318d9e..d49c9b62 100644 --- a/src/common/ircchannel.cpp +++ b/src/common/ircchannel.cpp @@ -20,34 +20,32 @@ #include "ircchannel.h" -#include "network.h" -#include "ircuser.h" -#include "util.h" - -#include +#include #include +#include #include -#include +#include "ircuser.h" +#include "network.h" +#include "util.h" -IrcChannel::IrcChannel(const QString &channelname, Network *network) - : SyncableObject(network), - _initialized(false), - _name(channelname), - _topic(QString()), - _encrypted(false), - _network(network), - _codecForEncoding(nullptr), - _codecForDecoding(nullptr) +IrcChannel::IrcChannel(const QString& channelname, Network* network) + : SyncableObject(network) + , _initialized(false) + , _name(channelname) + , _topic(QString()) + , _encrypted(false) + , _network(network) + , _codecForEncoding(nullptr) + , _codecForDecoding(nullptr) { - setObjectName(QString::number(network->networkId().toInt()) + "/" + channelname); + setObjectName(QString::number(network->networkId().toInt()) + "/" + channelname); } - // ==================== // PUBLIC: // ==================== -bool IrcChannel::isKnownUser(IrcUser *ircuser) const +bool IrcChannel::isKnownUser(IrcUser* ircuser) const { if (ircuser == nullptr) { qWarning() << "Channel" << name() << "received IrcUser Nullpointer!"; @@ -62,8 +60,7 @@ bool IrcChannel::isKnownUser(IrcUser *ircuser) const return true; } - -bool IrcChannel::isValidChannelUserMode(const QString &mode) const +bool IrcChannel::isValidChannelUserMode(const QString& mode) const { bool isvalid = true; if (mode.size() > 1) { @@ -73,8 +70,7 @@ bool IrcChannel::isValidChannelUserMode(const QString &mode) const return isvalid; } - -QString IrcChannel::userModes(IrcUser *ircuser) const +QString IrcChannel::userModes(IrcUser* ircuser) const { if (_userModes.contains(ircuser)) return _userModes[ircuser]; @@ -82,45 +78,39 @@ QString IrcChannel::userModes(IrcUser *ircuser) const return QString(); } - -QString IrcChannel::userModes(const QString &nick) const +QString IrcChannel::userModes(const QString& nick) const { return userModes(network()->ircUser(nick)); } - -void IrcChannel::setCodecForEncoding(const QString &name) +void IrcChannel::setCodecForEncoding(const QString& name) { setCodecForEncoding(QTextCodec::codecForName(name.toLatin1())); } - -void IrcChannel::setCodecForEncoding(QTextCodec *codec) +void IrcChannel::setCodecForEncoding(QTextCodec* codec) { _codecForEncoding = codec; } - -void IrcChannel::setCodecForDecoding(const QString &name) +void IrcChannel::setCodecForDecoding(const QString& name) { setCodecForDecoding(QTextCodec::codecForName(name.toLatin1())); } - -void IrcChannel::setCodecForDecoding(QTextCodec *codec) +void IrcChannel::setCodecForDecoding(QTextCodec* codec) { _codecForDecoding = codec; } - -QString IrcChannel::decodeString(const QByteArray &text) const +QString IrcChannel::decodeString(const QByteArray& text) const { - if (!codecForDecoding()) return network()->decodeString(text); + if (!codecForDecoding()) + return network()->decodeString(text); return ::decodeString(text, _codecForDecoding); } - -QByteArray IrcChannel::encodeString(const QString &string) const +QByteArray IrcChannel::encodeString(const QString& string) const { if (codecForEncoding()) { return _codecForEncoding->fromUnicode(string); @@ -128,19 +118,17 @@ QByteArray IrcChannel::encodeString(const QString &string) const return network()->encodeString(string); } - // ==================== // PUBLIC SLOTS: // ==================== -void IrcChannel::setTopic(const QString &topic) +void IrcChannel::setTopic(const QString& topic) { _topic = topic; SYNC(ARG(topic)) emit topicSet(topic); } - -void IrcChannel::setPassword(const QString &password) +void IrcChannel::setPassword(const QString& password) { _password = password; SYNC(ARG(password)) @@ -153,8 +141,7 @@ void IrcChannel::setEncrypted(bool encrypted) emit encryptedSet(encrypted); } - -void IrcChannel::joinIrcUsers(const QList &users, const QStringList &modes) +void IrcChannel::joinIrcUsers(const QList& users, const QStringList& modes) { if (users.isEmpty()) return; @@ -169,9 +156,9 @@ void IrcChannel::joinIrcUsers(const QList &users, const QStringList & QStringList newNicks; QStringList newModes; - QList newUsers; + QList newUsers; - IrcUser *ircuser; + IrcUser* ircuser; for (int i = 0; i < users.count(); i++) { ircuser = users[i]; if (!ircuser) @@ -183,7 +170,8 @@ void IrcChannel::joinIrcUsers(const QList &users, const QStringList & for (int i_m = 0; i_m < sortedModes[i].count(); ++i_m) { addUserMode(ircuser, sortedModes[i][i_m]); } - } else { + } + else { addUserMode(ircuser, sortedModes[i]); } continue; @@ -209,27 +197,24 @@ void IrcChannel::joinIrcUsers(const QList &users, const QStringList & emit ircUsersJoined(newUsers); } - -void IrcChannel::joinIrcUsers(const QStringList &nicks, const QStringList &modes) +void IrcChannel::joinIrcUsers(const QStringList& nicks, const QStringList& modes) { - QList users; - foreach(QString nick, nicks) - users << network()->newIrcUser(nick); + QList users; + foreach (QString nick, nicks) + users << network()->newIrcUser(nick); joinIrcUsers(users, modes); } - -void IrcChannel::joinIrcUser(IrcUser *ircuser) +void IrcChannel::joinIrcUser(IrcUser* ircuser) { - QList users; + QList users; users << ircuser; QStringList modes; modes << QString(); joinIrcUsers(users, modes); } - -void IrcChannel::part(IrcUser *ircuser) +void IrcChannel::part(IrcUser* ircuser) { if (isKnownUser(ircuser)) { _userModes.remove(ircuser); @@ -242,9 +227,9 @@ void IrcChannel::part(IrcUser *ircuser) if (network()->isMe(ircuser) || _userModes.isEmpty()) { // in either case we're no longer in the channel // -> clean up the channel and destroy it - QList users = _userModes.keys(); + QList users = _userModes.keys(); _userModes.clear(); - foreach(IrcUser *user, users) { + foreach (IrcUser* user, users) { disconnect(user, nullptr, this, nullptr); user->partChannel(this); } @@ -254,15 +239,13 @@ void IrcChannel::part(IrcUser *ircuser) } } - -void IrcChannel::part(const QString &nick) +void IrcChannel::part(const QString& nick) { part(network()->ircUser(nick)); } - // SET USER MODE -void IrcChannel::setUserModes(IrcUser *ircuser, const QString &modes) +void IrcChannel::setUserModes(IrcUser* ircuser, const QString& modes) { if (isKnownUser(ircuser)) { // Keep user modes sorted @@ -273,15 +256,13 @@ void IrcChannel::setUserModes(IrcUser *ircuser, const QString &modes) } } - -void IrcChannel::setUserModes(const QString &nick, const QString &modes) +void IrcChannel::setUserModes(const QString& nick, const QString& modes) { setUserModes(network()->ircUser(nick), modes); } - // ADD USER MODE -void IrcChannel::addUserMode(IrcUser *ircuser, const QString &mode) +void IrcChannel::addUserMode(IrcUser* ircuser, const QString& mode) { if (!isKnownUser(ircuser) || !isValidChannelUserMode(mode)) return; @@ -295,15 +276,13 @@ void IrcChannel::addUserMode(IrcUser *ircuser, const QString &mode) } } - -void IrcChannel::addUserMode(const QString &nick, const QString &mode) +void IrcChannel::addUserMode(const QString& nick, const QString& mode) { addUserMode(network()->ircUser(nick), mode); } - // REMOVE USER MODE -void IrcChannel::removeUserMode(IrcUser *ircuser, const QString &mode) +void IrcChannel::removeUserMode(IrcUser* ircuser, const QString& mode) { if (!isKnownUser(ircuser) || !isValidChannelUserMode(mode)) return; @@ -317,18 +296,16 @@ void IrcChannel::removeUserMode(IrcUser *ircuser, const QString &mode) } } - -void IrcChannel::removeUserMode(const QString &nick, const QString &mode) +void IrcChannel::removeUserMode(const QString& nick, const QString& mode) { removeUserMode(network()->ircUser(nick), mode); } - // INIT SET USER MODES QVariantMap IrcChannel::initUserModes() const { QVariantMap usermodes; - QHash::const_iterator iter = _userModes.constBegin(); + QHash::const_iterator iter = _userModes.constBegin(); while (iter != _userModes.constEnd()) { usermodes[iter.key()->nick()] = iter.value(); ++iter; @@ -336,10 +313,9 @@ QVariantMap IrcChannel::initUserModes() const return usermodes; } - -void IrcChannel::initSetUserModes(const QVariantMap &usermodes) +void IrcChannel::initSetUserModes(const QVariantMap& usermodes) { - QList users; + QList users; QStringList modes; QVariantMap::const_iterator iter = usermodes.constBegin(); while (iter != usermodes.constEnd()) { @@ -351,7 +327,6 @@ void IrcChannel::initSetUserModes(const QVariantMap &usermodes) joinIrcUsers(users, modes); } - QVariantMap IrcChannel::initChanModes() const { QVariantMap channelModes; @@ -391,8 +366,7 @@ QVariantMap IrcChannel::initChanModes() const return channelModes; } - -void IrcChannel::initSetChanModes(const QVariantMap &channelModes) +void IrcChannel::initSetChanModes(const QVariantMap& channelModes) { QVariantMap::const_iterator iter = channelModes["A"].toMap().constBegin(); QVariantMap::const_iterator iterEnd = channelModes["A"].toMap().constEnd(); @@ -421,25 +395,22 @@ void IrcChannel::initSetChanModes(const QVariantMap &channelModes) } } - void IrcChannel::ircUserDestroyed() { - auto *ircUser = static_cast(sender()); + auto* ircUser = static_cast(sender()); Q_ASSERT(ircUser); _userModes.remove(ircUser); // no further propagation. // this leads only to fuck ups. } - void IrcChannel::ircUserNickSet(QString nick) { - auto *ircUser = qobject_cast(sender()); + auto* ircUser = qobject_cast(sender()); Q_ASSERT(ircUser); emit ircUserNickSet(ircUser, nick); } - /******************************************************************************* * * 3.3 CHANMODES @@ -485,7 +456,7 @@ void IrcChannel::ircUserNickSet(QString nick) // NOTE: the behavior of addChannelMode and removeChannelMode depends on the type of mode // see list above for chanmode types -void IrcChannel::addChannelMode(const QChar &mode, const QString &value) +void IrcChannel::addChannelMode(const QChar& mode, const QString& value) { Network::ChannelModeType modeType = network()->channelModeType(mode); @@ -514,8 +485,7 @@ void IrcChannel::addChannelMode(const QChar &mode, const QString &value) SYNC(ARG(mode), ARG(value)) } - -void IrcChannel::removeChannelMode(const QChar &mode, const QString &value) +void IrcChannel::removeChannelMode(const QChar& mode, const QString& value) { Network::ChannelModeType modeType = network()->channelModeType(mode); @@ -542,8 +512,7 @@ void IrcChannel::removeChannelMode(const QChar &mode, const QString &value) SYNC(ARG(mode), ARG(value)) } - -bool IrcChannel::hasMode(const QChar &mode) const +bool IrcChannel::hasMode(const QChar& mode) const { Network::ChannelModeType modeType = network()->channelModeType(mode); @@ -562,8 +531,7 @@ bool IrcChannel::hasMode(const QChar &mode) const return false; } - -QString IrcChannel::modeValue(const QChar &mode) const +QString IrcChannel::modeValue(const QChar& mode) const { Network::ChannelModeType modeType = network()->channelModeType(mode); @@ -583,8 +551,7 @@ QString IrcChannel::modeValue(const QChar &mode) const } } - -QStringList IrcChannel::modeValueList(const QChar &mode) const +QStringList IrcChannel::modeValueList(const QChar& mode) const { Network::ChannelModeType modeType = network()->channelModeType(mode); @@ -599,7 +566,6 @@ QStringList IrcChannel::modeValueList(const QChar &mode) const return {}; } - QString IrcChannel::channelModeString() const { QStringList params; diff --git a/src/common/ircchannel.h b/src/common/ircchannel.h index bcb6f59e..4a71e0f2 100644 --- a/src/common/ircchannel.h +++ b/src/common/ircchannel.h @@ -43,89 +43,89 @@ class COMMON_EXPORT IrcChannel : public SyncableObject Q_PROPERTY(QString password READ password WRITE setPassword) Q_PROPERTY(bool encrypted READ encrypted WRITE setEncrypted) -public : - IrcChannel(const QString &channelname, Network *network); +public: + IrcChannel(const QString& channelname, Network* network); - bool isKnownUser(IrcUser *ircuser) const; - bool isValidChannelUserMode(const QString &mode) const; + bool isKnownUser(IrcUser* ircuser) const; + bool isValidChannelUserMode(const QString& mode) const; inline QString name() const { return _name; } inline QString topic() const { return _topic; } inline QString password() const { return _password; } inline bool encrypted() const { return _encrypted; } - inline Network *network() const { return _network; } + inline Network* network() const { return _network; } - inline QList ircUsers() const { return _userModes.keys(); } + inline QList ircUsers() const { return _userModes.keys(); } - QString userModes(IrcUser *ircuser) const; - QString userModes(const QString &nick) const; + QString userModes(IrcUser* ircuser) const; + QString userModes(const QString& nick) const; - bool hasMode(const QChar &mode) const; - QString modeValue(const QChar &mode) const; - QStringList modeValueList(const QChar &mode) const; + bool hasMode(const QChar& mode) const; + QString modeValue(const QChar& mode) const; + QStringList modeValueList(const QChar& mode) const; QString channelModeString() const; - inline QTextCodec *codecForEncoding() const { return _codecForEncoding; } - inline QTextCodec *codecForDecoding() const { return _codecForDecoding; } - void setCodecForEncoding(const QString &codecName); - void setCodecForEncoding(QTextCodec *codec); - void setCodecForDecoding(const QString &codecName); - void setCodecForDecoding(QTextCodec *codec); + inline QTextCodec* codecForEncoding() const { return _codecForEncoding; } + inline QTextCodec* codecForDecoding() const { return _codecForDecoding; } + void setCodecForEncoding(const QString& codecName); + void setCodecForEncoding(QTextCodec* codec); + void setCodecForDecoding(const QString& codecName); + void setCodecForDecoding(QTextCodec* codec); - QString decodeString(const QByteArray &text) const; - QByteArray encodeString(const QString &string) const; + QString decodeString(const QByteArray& text) const; + QByteArray encodeString(const QString& string) const; public slots: - void setTopic(const QString &topic); - void setPassword(const QString &password); + void setTopic(const QString& topic); + void setPassword(const QString& password); void setEncrypted(bool encrypted); - void joinIrcUsers(const QList &users, const QStringList &modes); - void joinIrcUsers(const QStringList &nicks, const QStringList &modes); - void joinIrcUser(IrcUser *ircuser); + void joinIrcUsers(const QList& users, const QStringList& modes); + void joinIrcUsers(const QStringList& nicks, const QStringList& modes); + void joinIrcUser(IrcUser* ircuser); - void part(IrcUser *ircuser); - void part(const QString &nick); + void part(IrcUser* ircuser); + void part(const QString& nick); - void setUserModes(IrcUser *ircuser, const QString &modes); - void setUserModes(const QString &nick, const QString &modes); + void setUserModes(IrcUser* ircuser, const QString& modes); + void setUserModes(const QString& nick, const QString& modes); - void addUserMode(IrcUser *ircuser, const QString &mode); - void addUserMode(const QString &nick, const QString &mode); + void addUserMode(IrcUser* ircuser, const QString& mode); + void addUserMode(const QString& nick, const QString& mode); - void removeUserMode(IrcUser *ircuser, const QString &mode); - void removeUserMode(const QString &nick, const QString &mode); + void removeUserMode(IrcUser* ircuser, const QString& mode); + void removeUserMode(const QString& nick, const QString& mode); - void addChannelMode(const QChar &mode, const QString &value); - void removeChannelMode(const QChar &mode, const QString &value); + void addChannelMode(const QChar& mode, const QString& value); + void removeChannelMode(const QChar& mode, const QString& value); // init geters QVariantMap initUserModes() const; QVariantMap initChanModes() const; // init seters - void initSetUserModes(const QVariantMap &usermodes); - void initSetChanModes(const QVariantMap &chanModes); + void initSetUserModes(const QVariantMap& usermodes); + void initSetChanModes(const QVariantMap& chanModes); signals: - void topicSet(const QString &topic); // needed by NetworkModel + void topicSet(const QString& topic); // needed by NetworkModel void encryptedSet(bool encrypted); -// void passwordSet(const QString &password); -// void userModesSet(QString nick, QString modes); -// void userModeAdded(QString nick, QString mode); -// void userModeRemoved(QString nick, QString mode); -// void channelModeAdded(const QChar &mode, const QString &value); -// void channelModeRemoved(const QChar &mode, const QString &value); - - void ircUsersJoined(const QList &ircusers); -// void ircUsersJoined(QStringList nicks, QStringList modes); - void ircUserParted(IrcUser *ircuser); - void ircUserNickSet(IrcUser *ircuser, QString nick); - void ircUserModeAdded(IrcUser *ircuser, QString mode); - void ircUserModeRemoved(IrcUser *ircuser, QString mode); - void ircUserModesSet(IrcUser *ircuser, QString modes); - - void parted(); // convenience signal emitted before channels destruction + // void passwordSet(const QString &password); + // void userModesSet(QString nick, QString modes); + // void userModeAdded(QString nick, QString mode); + // void userModeRemoved(QString nick, QString mode); + // void channelModeAdded(const QChar &mode, const QString &value); + // void channelModeRemoved(const QChar &mode, const QString &value); + + void ircUsersJoined(const QList& ircusers); + // void ircUsersJoined(QStringList nicks, QStringList modes); + void ircUserParted(IrcUser* ircuser); + void ircUserNickSet(IrcUser* ircuser, QString nick); + void ircUserModeAdded(IrcUser* ircuser, QString mode); + void ircUserModeRemoved(IrcUser* ircuser, QString mode); + void ircUserModesSet(IrcUser* ircuser, QString modes); + + void parted(); // convenience signal emitted before channels destruction private slots: void ircUserDestroyed(); @@ -138,12 +138,12 @@ private: QString _password; bool _encrypted; - QHash _userModes; + QHash _userModes; - Network *_network; + Network* _network; - QTextCodec *_codecForEncoding; - QTextCodec *_codecForDecoding; + QTextCodec* _codecForEncoding; + QTextCodec* _codecForDecoding; QHash _A_channelModes; QHash _B_channelModes; diff --git a/src/common/ircevent.cpp b/src/common/ircevent.cpp index 797f4538..2e0838d7 100644 --- a/src/common/ircevent.cpp +++ b/src/common/ircevent.cpp @@ -20,7 +20,7 @@ #include "ircevent.h" -Event *IrcEvent::create(EventManager::EventType type, QVariantMap &map, Network *network) +Event* IrcEvent::create(EventManager::EventType type, QVariantMap& map, Network* network) { if ((type & ~EventManager::IrcEventNumericMask) == EventManager::IrcEventNumeric) return new IrcEventNumeric(type, map, network); @@ -38,47 +38,41 @@ Event *IrcEvent::create(EventManager::EventType type, QVariantMap &map, Network } } - -IrcEvent::IrcEvent(EventManager::EventType type, QVariantMap &map, Network *network) +IrcEvent::IrcEvent(EventManager::EventType type, QVariantMap& map, Network* network) : NetworkEvent(type, map, network) { _prefix = map.take("prefix").toString(); _params = map.take("params").toStringList(); } - -void IrcEvent::toVariantMap(QVariantMap &map) const +void IrcEvent::toVariantMap(QVariantMap& map) const { NetworkEvent::toVariantMap(map); map["prefix"] = prefix(); map["params"] = params(); } - -IrcEventNumeric::IrcEventNumeric(EventManager::EventType type, QVariantMap &map, Network *network) +IrcEventNumeric::IrcEventNumeric(EventManager::EventType type, QVariantMap& map, Network* network) : IrcEvent(type, map, network) { _number = map.take("number").toUInt(); _target = map.take("target").toString(); } - -void IrcEventNumeric::toVariantMap(QVariantMap &map) const +void IrcEventNumeric::toVariantMap(QVariantMap& map) const { IrcEvent::toVariantMap(map); map["number"] = number(); map["target"] = target(); } - -IrcEventRawMessage::IrcEventRawMessage(EventManager::EventType type, QVariantMap &map, Network *network) +IrcEventRawMessage::IrcEventRawMessage(EventManager::EventType type, QVariantMap& map, Network* network) : IrcEvent(type, map, network) { _rawMessage = map.take("rawMessage").toByteArray(); } - -void IrcEventRawMessage::toVariantMap(QVariantMap &map) const +void IrcEventRawMessage::toVariantMap(QVariantMap& map) const { IrcEvent::toVariantMap(map); map["rawMessage"] = rawMessage(); diff --git a/src/common/ircevent.h b/src/common/ircevent.h index 5d13b2f5..69915694 100644 --- a/src/common/ircevent.h +++ b/src/common/ircevent.h @@ -20,80 +20,74 @@ #pragma once -#include - #include "common-export.h" +#include + #include "networkevent.h" #include "util.h" class COMMON_EXPORT IrcEvent : public NetworkEvent { public: - explicit IrcEvent(EventManager::EventType type, Network *network, QString prefix, QStringList params = QStringList()) - : NetworkEvent(type, network), - _prefix(std::move(prefix)), - _params(std::move(params)) + explicit IrcEvent(EventManager::EventType type, Network* network, QString prefix, QStringList params = QStringList()) + : NetworkEvent(type, network) + , _prefix(std::move(prefix)) + , _params(std::move(params)) {} inline QString prefix() const { return _prefix; } - inline void setPrefix(const QString &prefix) { _prefix = prefix; } + inline void setPrefix(const QString& prefix) { _prefix = prefix; } inline QString nick() const { return nickFromMask(prefix()); } inline QStringList params() const { return _params; } - inline void setParams(const QStringList ¶ms) { _params = params; } + inline void setParams(const QStringList& params) { _params = params; } - static Event *create(EventManager::EventType type, QVariantMap &map, Network *network); + static Event* create(EventManager::EventType type, QVariantMap& map, Network* network); protected: - explicit IrcEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit IrcEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "IrcEvent"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); - dbg << ", prefix = " << qPrintable(prefix()) - << ", params = " << params(); + dbg << ", prefix = " << qPrintable(prefix()) << ", params = " << params(); } - private: QString _prefix; QStringList _params; }; - class COMMON_EXPORT IrcEventNumeric : public IrcEvent { public: - explicit IrcEventNumeric(uint number, Network *network, const QString &prefix, QString target, const QStringList ¶ms = QStringList()) - : IrcEvent(EventManager::IrcEventNumeric, network, prefix, params), - _number(number), - _target(std::move(target)) + explicit IrcEventNumeric(uint number, Network* network, const QString& prefix, QString target, const QStringList& params = QStringList()) + : IrcEvent(EventManager::IrcEventNumeric, network, prefix, params) + , _number(number) + , _target(std::move(target)) {} inline uint number() const { return _number; } inline QString target() const { return _target; } - inline void setTarget(const QString &target) { _target = target; } + inline void setTarget(const QString& target) { _target = target; } protected: - explicit IrcEventNumeric(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit IrcEventNumeric(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "IrcEventNumeric"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { dbg << ", num = " << number(); NetworkEvent::debugInfo(dbg); - dbg << ", target = " << qPrintable(target()) - << ", prefix = " << qPrintable(prefix()) - << ", params = " << params(); + dbg << ", target = " << qPrintable(target()) << ", prefix = " << qPrintable(prefix()) << ", params = " << params(); } - private: uint _number; QString _target; @@ -101,40 +95,38 @@ private: friend class IrcEvent; }; - class COMMON_EXPORT IrcEventRawMessage : public IrcEvent { public: - explicit inline IrcEventRawMessage(EventManager::EventType type, Network *network, - QByteArray rawMessage, const QString &prefix, const QString &target, - const QDateTime ×tamp = QDateTime()) - : IrcEvent(type, network, prefix, QStringList() << target), - _rawMessage(std::move(rawMessage)) + explicit inline IrcEventRawMessage(EventManager::EventType type, + Network* network, + QByteArray rawMessage, + const QString& prefix, + const QString& target, + const QDateTime& timestamp = QDateTime()) + : IrcEvent(type, network, prefix, QStringList() << target) + , _rawMessage(std::move(rawMessage)) { setTimestamp(timestamp); } - inline QString target() const { return params().at(0); } - inline void setTarget(const QString &target) { setParams(QStringList() << target); } + inline void setTarget(const QString& target) { setParams(QStringList() << target); } inline QByteArray rawMessage() const { return _rawMessage; } - inline void setRawMessage(const QByteArray &rawMessage) { _rawMessage = rawMessage; } + inline void setRawMessage(const QByteArray& rawMessage) { _rawMessage = rawMessage; } protected: - explicit IrcEventRawMessage(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit IrcEventRawMessage(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "IrcEventRawMessage"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); - dbg << ", target = " << qPrintable(target()) - << ", prefix = " << qPrintable(prefix()) - << ", msg = " << rawMessage(); + dbg << ", target = " << qPrintable(target()) << ", prefix = " << qPrintable(prefix()) << ", msg = " << rawMessage(); } - private: QByteArray _rawMessage; diff --git a/src/common/irclisthelper.h b/src/common/irclisthelper.h index aee7cf12..72a58243 100644 --- a/src/common/irclisthelper.h +++ b/src/common/irclisthelper.h @@ -20,10 +20,10 @@ #pragma once -#include - #include "common-export.h" +#include + #include "syncableobject.h" #include "types.h" @@ -41,18 +41,30 @@ class COMMON_EXPORT IrcListHelper : public SyncableObject SYNCABLE_OBJECT public: - inline IrcListHelper(QObject *parent = nullptr) : SyncableObject(parent) { setInitialized(); }; + inline IrcListHelper(QObject* parent = nullptr) + : SyncableObject(parent) + { + setInitialized(); + }; - struct ChannelDescription { + struct ChannelDescription + { QString channelName; quint32 userCount; QString topic; - ChannelDescription(QString channelName_, quint32 userCount_, QString topic_) : channelName(std::move(channelName_)), userCount(userCount_), topic(std::move(topic_)) {}; + ChannelDescription(QString channelName_, quint32 userCount_, QString topic_) + : channelName(std::move(channelName_)) + , userCount(userCount_) + , topic(std::move(topic_)){}; }; public slots: - inline virtual QVariantList requestChannelList(const NetworkId &netId, const QStringList &channelFilters) { REQUEST(ARG(netId), ARG(channelFilters)); return QVariantList(); } - inline virtual void receiveChannelList(const NetworkId &, const QStringList &, const QVariantList &) {}; - inline virtual void reportFinishedList(const NetworkId &netId) { SYNC(ARG(netId)) } - inline virtual void reportError(const QString &error) { SYNC(ARG(error)) } + inline virtual QVariantList requestChannelList(const NetworkId& netId, const QStringList& channelFilters) + { + REQUEST(ARG(netId), ARG(channelFilters)); + return QVariantList(); + } + inline virtual void receiveChannelList(const NetworkId&, const QStringList&, const QVariantList&){}; + inline virtual void reportFinishedList(const NetworkId& netId) { SYNC(ARG(netId)) } + inline virtual void reportError(const QString& error) { SYNC(ARG(error)) } }; diff --git a/src/common/ircuser.cpp b/src/common/ircuser.cpp index cf1aedaa..a952ec0f 100644 --- a/src/common/ircuser.cpp +++ b/src/common/ircuser.cpp @@ -19,39 +19,40 @@ ***************************************************************************/ #include "ircuser.h" -#include "util.h" +#include +#include + +#include "ircchannel.h" #include "network.h" #include "signalproxy.h" -#include "ircchannel.h" - -#include -#include +#include "util.h" -IrcUser::IrcUser(const QString &hostmask, Network *network) : SyncableObject(network), - _initialized(false), - _nick(nickFromMask(hostmask)), - _user(userFromMask(hostmask)), - _host(hostFromMask(hostmask)), - _realName(), - _awayMessage(), - _away(false), - _server(), +IrcUser::IrcUser(const QString& hostmask, Network* network) + : SyncableObject(network) + , _initialized(false) + , _nick(nickFromMask(hostmask)) + , _user(userFromMask(hostmask)) + , _host(hostFromMask(hostmask)) + , _realName() + , _awayMessage() + , _away(false) + , _server() + , // _idleTime(QDateTime::currentDateTime()), - _ircOperator(), - _lastAwayMessageTime(), - _whoisServiceReply(), - _encrypted(false), - _network(network), - _codecForEncoding(nullptr), - _codecForDecoding(nullptr) + _ircOperator() + , _lastAwayMessageTime() + , _whoisServiceReply() + , _encrypted(false) + , _network(network) + , _codecForEncoding(nullptr) + , _codecForDecoding(nullptr) { updateObjectName(); _lastAwayMessageTime.setTimeSpec(Qt::UTC); _lastAwayMessageTime.setMSecsSinceEpoch(0); } - // ==================== // PUBLIC: // ==================== @@ -61,11 +62,9 @@ QString IrcUser::hostmask() const return QString("%1!%2@%3").arg(nick()).arg(user()).arg(host()); } - QDateTime IrcUser::idleTime() { - if ((QDateTime::currentDateTime().toMSecsSinceEpoch() - _idleTimeSet.toMSecsSinceEpoch()) - > 1200000) { + if ((QDateTime::currentDateTime().toMSecsSinceEpoch() - _idleTimeSet.toMSecsSinceEpoch()) > 1200000) { // 20 * 60 * 1000 = 1200000 // 20 minutes have elapsed, clear the known idle time as it's likely inaccurate by now _idleTime = QDateTime(); @@ -73,50 +72,44 @@ QDateTime IrcUser::idleTime() return _idleTime; } - QStringList IrcUser::channels() const { QStringList chanList; - IrcChannel *channel; - foreach(channel, _channels) { + IrcChannel* channel; + foreach (channel, _channels) { chanList << channel->name(); } return chanList; } - -void IrcUser::setCodecForEncoding(const QString &name) +void IrcUser::setCodecForEncoding(const QString& name) { setCodecForEncoding(QTextCodec::codecForName(name.toLatin1())); } - -void IrcUser::setCodecForEncoding(QTextCodec *codec) +void IrcUser::setCodecForEncoding(QTextCodec* codec) { _codecForEncoding = codec; } - -void IrcUser::setCodecForDecoding(const QString &name) +void IrcUser::setCodecForDecoding(const QString& name) { setCodecForDecoding(QTextCodec::codecForName(name.toLatin1())); } - -void IrcUser::setCodecForDecoding(QTextCodec *codec) +void IrcUser::setCodecForDecoding(QTextCodec* codec) { _codecForDecoding = codec; } - -QString IrcUser::decodeString(const QByteArray &text) const +QString IrcUser::decodeString(const QByteArray& text) const { - if (!codecForDecoding()) return network()->decodeString(text); + if (!codecForDecoding()) + return network()->decodeString(text); return ::decodeString(text, codecForDecoding()); } - -QByteArray IrcUser::encodeString(const QString &string) const +QByteArray IrcUser::encodeString(const QString& string) const { if (codecForEncoding()) { return codecForEncoding()->fromUnicode(string); @@ -124,11 +117,10 @@ QByteArray IrcUser::encodeString(const QString &string) const return network()->encodeString(string); } - // ==================== // PUBLIC SLOTS: // ==================== -void IrcUser::setUser(const QString &user) +void IrcUser::setUser(const QString& user) { if (!user.isEmpty() && _user != user) { _user = user; @@ -136,8 +128,7 @@ void IrcUser::setUser(const QString &user) } } - -void IrcUser::setRealName(const QString &realName) +void IrcUser::setRealName(const QString& realName) { if (!realName.isEmpty() && _realName != realName) { _realName = realName; @@ -145,8 +136,7 @@ void IrcUser::setRealName(const QString &realName) } } - -void IrcUser::setAccount(const QString &account) +void IrcUser::setAccount(const QString& account) { if (_account != account) { _account = account; @@ -154,7 +144,6 @@ void IrcUser::setAccount(const QString &account) } } - void IrcUser::setAway(bool away) { if (away != _away) { @@ -165,8 +154,7 @@ void IrcUser::setAway(bool away) } } - -void IrcUser::setAwayMessage(const QString &awayMessage) +void IrcUser::setAwayMessage(const QString& awayMessage) { if (!awayMessage.isEmpty() && _awayMessage != awayMessage) { _awayMessage = awayMessage; @@ -175,8 +163,7 @@ void IrcUser::setAwayMessage(const QString &awayMessage) } } - -void IrcUser::setIdleTime(const QDateTime &idleTime) +void IrcUser::setIdleTime(const QDateTime& idleTime) { if (idleTime.isValid() && _idleTime != idleTime) { _idleTime = idleTime; @@ -185,8 +172,7 @@ void IrcUser::setIdleTime(const QDateTime &idleTime) } } - -void IrcUser::setLoginTime(const QDateTime &loginTime) +void IrcUser::setLoginTime(const QDateTime& loginTime) { if (loginTime.isValid() && _loginTime != loginTime) { _loginTime = loginTime; @@ -194,8 +180,7 @@ void IrcUser::setLoginTime(const QDateTime &loginTime) } } - -void IrcUser::setServer(const QString &server) +void IrcUser::setServer(const QString& server) { if (!server.isEmpty() && _server != server) { _server = server; @@ -203,8 +188,7 @@ void IrcUser::setServer(const QString &server) } } - -void IrcUser::setIrcOperator(const QString &ircOperator) +void IrcUser::setIrcOperator(const QString& ircOperator) { if (!ircOperator.isEmpty() && _ircOperator != ircOperator) { _ircOperator = ircOperator; @@ -212,7 +196,6 @@ void IrcUser::setIrcOperator(const QString &ircOperator) } } - // This function is only ever called by SYNC calls from legacy cores (pre-0.13). // Therefore, no SYNC call is needed here. void IrcUser::setLastAwayMessage(int lastAwayMessage) @@ -228,8 +211,7 @@ void IrcUser::setLastAwayMessage(int lastAwayMessage) setLastAwayMessageTime(lastAwayMessageTime); } - -void IrcUser::setLastAwayMessageTime(const QDateTime &lastAwayMessageTime) +void IrcUser::setLastAwayMessageTime(const QDateTime& lastAwayMessageTime) { if (lastAwayMessageTime > _lastAwayMessageTime) { _lastAwayMessageTime = lastAwayMessageTime; @@ -237,8 +219,7 @@ void IrcUser::setLastAwayMessageTime(const QDateTime &lastAwayMessageTime) } } - -void IrcUser::setHost(const QString &host) +void IrcUser::setHost(const QString& host) { if (!host.isEmpty() && _host != host) { _host = host; @@ -246,8 +227,7 @@ void IrcUser::setHost(const QString &host) } } - -void IrcUser::setNick(const QString &nick) +void IrcUser::setNick(const QString& nick) { if (!nick.isEmpty() && nick != _nick) { _nick = nick; @@ -257,8 +237,7 @@ void IrcUser::setNick(const QString &nick) } } - -void IrcUser::setWhoisServiceReply(const QString &whoisServiceReply) +void IrcUser::setWhoisServiceReply(const QString& whoisServiceReply) { if (!whoisServiceReply.isEmpty() && whoisServiceReply != _whoisServiceReply) { _whoisServiceReply = whoisServiceReply; @@ -266,8 +245,7 @@ void IrcUser::setWhoisServiceReply(const QString &whoisServiceReply) } } - -void IrcUser::setSuserHost(const QString &suserHost) +void IrcUser::setSuserHost(const QString& suserHost) { if (!suserHost.isEmpty() && suserHost != _suserHost) { _suserHost = suserHost; @@ -275,7 +253,6 @@ void IrcUser::setSuserHost(const QString &suserHost) } } - void IrcUser::setEncrypted(bool encrypted) { _encrypted = encrypted; @@ -283,14 +260,12 @@ void IrcUser::setEncrypted(bool encrypted) SYNC(ARG(encrypted)) } - void IrcUser::updateObjectName() { renameObject(QString::number(network()->networkId().toInt()) + "/" + _nick); } - -void IrcUser::updateHostmask(const QString &mask) +void IrcUser::updateHostmask(const QString& mask) { if (mask == hostmask()) return; @@ -301,8 +276,7 @@ void IrcUser::updateHostmask(const QString &mask) setHost(host); } - -void IrcUser::joinChannel(IrcChannel *channel, bool skip_channel_join) +void IrcUser::joinChannel(IrcChannel* channel, bool skip_channel_join) { Q_ASSERT(channel); if (!_channels.contains(channel)) { @@ -312,14 +286,12 @@ void IrcUser::joinChannel(IrcChannel *channel, bool skip_channel_join) } } - -void IrcUser::joinChannel(const QString &channelname) +void IrcUser::joinChannel(const QString& channelname) { joinChannel(network()->newIrcChannel(channelname)); } - -void IrcUser::partChannel(IrcChannel *channel) +void IrcUser::partChannel(IrcChannel* channel) { if (_channels.contains(channel)) { _channels.remove(channel); @@ -332,10 +304,9 @@ void IrcUser::partChannel(IrcChannel *channel) } } - -void IrcUser::partChannel(const QString &channelname) +void IrcUser::partChannel(const QString& channelname) { - IrcChannel *channel = network()->ircChannel(channelname); + IrcChannel* channel = network()->ircChannel(channelname); if (channel == nullptr) { qWarning() << "IrcUser::partChannel(): received part for unknown Channel" << channelname; } @@ -344,12 +315,11 @@ void IrcUser::partChannel(const QString &channelname) } } - void IrcUser::quit() { - QList channels = _channels.toList(); + QList channels = _channels.toList(); _channels.clear(); - foreach(IrcChannel *channel, channels) { + foreach (IrcChannel* channel, channels) { disconnect(channel, nullptr, this, nullptr); channel->part(this); } @@ -358,11 +328,10 @@ void IrcUser::quit() emit quited(); } - void IrcUser::channelDestroyed() { // private slot! - auto *channel = static_cast(sender()); + auto* channel = static_cast(sender()); if (_channels.contains(channel)) { _channels.remove(channel); if (_channels.isEmpty() && !network()->isMe(this)) @@ -370,8 +339,7 @@ void IrcUser::channelDestroyed() } } - -void IrcUser::setUserModes(const QString &modes) +void IrcUser::setUserModes(const QString& modes) { if (_userModes != modes) { _userModes = modes; @@ -380,8 +348,7 @@ void IrcUser::setUserModes(const QString &modes) } } - -void IrcUser::addUserModes(const QString &modes) +void IrcUser::addUserModes(const QString& modes) { if (modes.isEmpty()) return; @@ -401,8 +368,7 @@ void IrcUser::addUserModes(const QString &modes) } } - -void IrcUser::removeUserModes(const QString &modes) +void IrcUser::removeUserModes(const QString& modes) { if (modes.isEmpty()) return; @@ -414,15 +380,13 @@ void IrcUser::removeUserModes(const QString &modes) emit userModesRemoved(modes); } - -void IrcUser::setLastChannelActivity(BufferId buffer, const QDateTime &time) +void IrcUser::setLastChannelActivity(BufferId buffer, const QDateTime& time) { _lastActivity[buffer] = time; emit lastChannelActivityUpdated(buffer, time); } - -void IrcUser::setLastSpokenTo(BufferId buffer, const QDateTime &time) +void IrcUser::setLastSpokenTo(BufferId buffer, const QDateTime& time) { _lastSpokenTo[buffer] = time; emit lastSpokenToUpdated(buffer, time); diff --git a/src/common/ircuser.h b/src/common/ircuser.h index a880d4bc..87115cbf 100644 --- a/src/common/ircuser.h +++ b/src/common/ircuser.h @@ -22,11 +22,11 @@ #include "common-export.h" +#include #include #include #include #include -#include #include "syncableobject.h" #include "types.h" @@ -59,8 +59,8 @@ class COMMON_EXPORT IrcUser : public SyncableObject Q_PROPERTY(QStringList channels READ channels) Q_PROPERTY(QString userModes READ userModes WRITE setUserModes) -public : - IrcUser(const QString &hostmask, Network *network); +public: + IrcUser(const QString& hostmask, Network* network); inline QString user() const { return _user; } inline QString host() const { return _host; } @@ -83,28 +83,28 @@ public : inline QString whoisServiceReply() const { return _whoisServiceReply; } inline QString suserHost() const { return _suserHost; } inline bool encrypted() const { return _encrypted; } - inline Network *network() const { return _network; } + inline Network* network() const { return _network; } inline QString userModes() const { return _userModes; } QStringList channels() const; // user-specific encodings - inline QTextCodec *codecForEncoding() const { return _codecForEncoding; } - inline QTextCodec *codecForDecoding() const { return _codecForDecoding; } - void setCodecForEncoding(const QString &codecName); - void setCodecForEncoding(QTextCodec *codec); - void setCodecForDecoding(const QString &codecName); - void setCodecForDecoding(QTextCodec *codec); + inline QTextCodec* codecForEncoding() const { return _codecForEncoding; } + inline QTextCodec* codecForDecoding() const { return _codecForDecoding; } + void setCodecForEncoding(const QString& codecName); + void setCodecForEncoding(QTextCodec* codec); + void setCodecForDecoding(const QString& codecName); + void setCodecForDecoding(QTextCodec* codec); - QString decodeString(const QByteArray &text) const; - QByteArray encodeString(const QString &string) const; + QString decodeString(const QByteArray& text) const; + QByteArray encodeString(const QString& string) const; // only valid on client side, these are not synced! inline QDateTime lastChannelActivity(BufferId id) const { return _lastActivity.value(id); } - void setLastChannelActivity(BufferId id, const QDateTime &time); + void setLastChannelActivity(BufferId id, const QDateTime& time); inline QDateTime lastSpokenTo(BufferId id) const { return _lastSpokenTo.value(id); } - void setLastSpokenTo(BufferId id, const QDateTime &time); + void setLastSpokenTo(BufferId id, const QDateTime& time); /** * Gets whether or not the away state has changed since it was last acknowledged @@ -132,61 +132,61 @@ public : } public slots: - void setUser(const QString &user); - void setHost(const QString &host); - void setNick(const QString &nick); - void setRealName(const QString &realName); + void setUser(const QString& user); + void setHost(const QString& host); + void setNick(const QString& nick); + void setRealName(const QString& realName); /** * Set account name, e.g. NickServ/SASL account * * @param[in] account Account name if logged in, * if logged out, or empty string if unknown */ - void setAccount(const QString &account); + void setAccount(const QString& account); void setAway(bool away); - void setAwayMessage(const QString &awayMessage); - void setIdleTime(const QDateTime &idleTime); - void setLoginTime(const QDateTime &loginTime); - void setServer(const QString &server); - void setIrcOperator(const QString &ircOperator); + void setAwayMessage(const QString& awayMessage); + void setIdleTime(const QDateTime& idleTime); + void setLoginTime(const QDateTime& loginTime); + void setServer(const QString& server); + void setIrcOperator(const QString& ircOperator); // setLastAwayMessage is only called by legacy (pre-0.13) cores, which automatically gets // converted to setting the appropriate lastAwayMessageTime. Do not use this in new code. void setLastAwayMessage(int lastAwayMessage); - void setLastAwayMessageTime(const QDateTime &lastAwayMessageTime); - void setWhoisServiceReply(const QString &whoisServiceReply); - void setSuserHost(const QString &suserHost); + void setLastAwayMessageTime(const QDateTime& lastAwayMessageTime); + void setWhoisServiceReply(const QString& whoisServiceReply); + void setSuserHost(const QString& suserHost); void setEncrypted(bool encrypted); - void updateHostmask(const QString &mask); + void updateHostmask(const QString& mask); - void setUserModes(const QString &modes); + void setUserModes(const QString& modes); /*! * \brief joinChannel Called when user joins some channel, this function inserts the channel to internal list of channels this user is in. * \param channel Pointer to a channel this user just joined * \param skip_channel_join If this is false, this function will also call IrcChannel::joinIrcUser, can be set to true as a performance tweak. */ - void joinChannel(IrcChannel *channel, bool skip_channel_join = false); - void joinChannel(const QString &channelname); - void partChannel(IrcChannel *channel); - void partChannel(const QString &channelname); + void joinChannel(IrcChannel* channel, bool skip_channel_join = false); + void joinChannel(const QString& channelname); + void partChannel(IrcChannel* channel); + void partChannel(const QString& channelname); void quit(); - void addUserModes(const QString &modes); - void removeUserModes(const QString &modes); + void addUserModes(const QString& modes); + void removeUserModes(const QString& modes); signals: -// void userSet(QString user); -// void hostSet(QString host); - void nickSet(QString newnick); // needed in NetworkModel -// void realNameSet(QString realName); - void awaySet(bool away); // needed in NetworkModel -// void awayMessageSet(QString awayMessage); -// void idleTimeSet(QDateTime idleTime); -// void loginTimeSet(QDateTime loginTime); -// void serverSet(QString server); -// void ircOperatorSet(QString ircOperator); -// void lastAwayMessageTimeSet(QDateTime lastAwayMessageTime); -// void whoisServiceReplySet(QString whoisServiceReply); -// void suserHostSet(QString suserHost); + // void userSet(QString user); + // void hostSet(QString host); + void nickSet(QString newnick); // needed in NetworkModel + // void realNameSet(QString realName); + void awaySet(bool away); // needed in NetworkModel + // void awayMessageSet(QString awayMessage); + // void idleTimeSet(QDateTime idleTime); + // void loginTimeSet(QDateTime loginTime); + // void serverSet(QString server); + // void ircOperatorSet(QString ircOperator); + // void lastAwayMessageTimeSet(QDateTime lastAwayMessageTime); + // void whoisServiceReplySet(QString whoisServiceReply); + // void suserHostSet(QString suserHost); void encryptedSet(bool encrypted); void userModesSet(QString modes); @@ -197,34 +197,24 @@ signals: void channelParted(QString channel); void quited(); - void lastChannelActivityUpdated(BufferId id, const QDateTime &newTime); - void lastSpokenToUpdated(BufferId id, const QDateTime &newTime); + void lastChannelActivityUpdated(BufferId id, const QDateTime& newTime); + void lastSpokenToUpdated(BufferId id, const QDateTime& newTime); private slots: void updateObjectName(); void channelDestroyed(); private: - inline bool operator==(const IrcUser &ircuser2) - { - return (_nick.toLower() == ircuser2.nick().toLower()); - } + inline bool operator==(const IrcUser& ircuser2) { return (_nick.toLower() == ircuser2.nick().toLower()); } - - inline bool operator==(const QString &nickname) - { - return (_nick.toLower() == nickname.toLower()); - } + inline bool operator==(const QString& nickname) { return (_nick.toLower() == nickname.toLower()); } /** * Sets the last away state change as unacknowledged * * @see IrcUser::hasAwayChanged() */ - inline void markAwayChanged() - { - _awayChanged = true; - } + inline void markAwayChanged() { _awayChanged = true; } bool _initialized; @@ -232,7 +222,7 @@ private: QString _user; QString _host; QString _realName; - QString _account; /// Account name, e.g. NickServ/SASL account + QString _account; /// Account name, e.g. NickServ/SASL account QString _awayMessage; bool _away; QString _server; @@ -246,13 +236,13 @@ private: bool _encrypted; // QSet _channels; - QSet _channels; + QSet _channels; QString _userModes; - Network *_network; + Network* _network; - QTextCodec *_codecForEncoding; - QTextCodec *_codecForDecoding; + QTextCodec* _codecForEncoding; + QTextCodec* _codecForDecoding; QHash _lastActivity; QHash _lastSpokenTo; diff --git a/src/common/logbacktrace_unix.cpp b/src/common/logbacktrace_unix.cpp index c9bedd3d..85553586 100644 --- a/src/common/logbacktrace_unix.cpp +++ b/src/common/logbacktrace_unix.cpp @@ -21,21 +21,23 @@ #include "quassel.h" #if defined(HAVE_BACKTRACE) && !defined(Q_OS_MAC) -# define BUILD_CRASHHANDLER -# include -# include -# include -# include -# include -# include "backtrace_config.h" +# define BUILD_CRASHHANDLER +# include +# include +# include + +# include +# include + +# include "backtrace_config.h" #endif -void Quassel::logBacktrace(const QString &filename) +void Quassel::logBacktrace(const QString& filename) { #ifndef BUILD_CRASHHANDLER Q_UNUSED(filename) #else - void *callstack[128]; + void* callstack[128]; int i, frames = backtrace(callstack, 128); QFile dumpFile(filename); @@ -54,15 +56,15 @@ void Quassel::logBacktrace(const QString &filename) // void *dli_saddr; /* Exact value of nearest symbol. */ // } Dl_info; - #ifdef __LP64__ +# ifdef __LP64__ int addrSize = 16; - #else +# else int addrSize = 8; - #endif +# endif QString funcName; if (info.dli_sname) { - char *func = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, nullptr); + char* func = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, nullptr); if (func) { funcName = QString(func); free(func); @@ -84,10 +86,11 @@ void Quassel::logBacktrace(const QString &filename) fileName = fileName.mid(slashPos + 1); } - QString debugLine = QString("#%1 %2 0x%3 %4").arg(i, 3, 10) - .arg(fileName, -20) - .arg((ulong)(callstack[i]), addrSize, 16, QLatin1Char('0')) - .arg(funcName); + QString debugLine = QString("#%1 %2 0x%3 %4") + .arg(i, 3, 10) + .arg(fileName, -20) + .arg((ulong)(callstack[i]), addrSize, 16, QLatin1Char('0')) + .arg(funcName); dumpStream << debugLine << "\n"; qDebug() << qPrintable(debugLine); diff --git a/src/common/logbacktrace_win.cpp b/src/common/logbacktrace_win.cpp index f6d922bd..d465b466 100644 --- a/src/common/logbacktrace_win.cpp +++ b/src/common/logbacktrace_win.cpp @@ -18,51 +18,51 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include "quassel.h" +#include #include #include -#include -// #include #include #include -void loadHelpStackFrame(IMAGEHLP_STACK_FRAME &ihsf, const STACKFRAME64 &stackFrame) +#include "quassel.h" + +void loadHelpStackFrame(IMAGEHLP_STACK_FRAME& ihsf, const STACKFRAME64& stackFrame) { ZeroMemory(&ihsf, sizeof(IMAGEHLP_STACK_FRAME)); ihsf.InstructionOffset = stackFrame.AddrPC.Offset; ihsf.FrameOffset = stackFrame.AddrFrame.Offset; } - BOOL CALLBACK EnumSymbolsCB(PSYMBOL_INFO symInfo, ULONG size, PVOID user) { Q_UNUSED(size) - QStringList *params = (QStringList *)user; + QStringList* params = (QStringList*)user; if (symInfo->Flags & SYMFLAG_PARAMETER) { params->append(symInfo->Name); } return TRUE; } - -struct EnumModulesContext { +struct EnumModulesContext +{ HANDLE hProcess; - QTextStream &stream; - EnumModulesContext(HANDLE hProcess, QTextStream &stream) : hProcess(hProcess), stream(stream) {} + QTextStream& stream; + EnumModulesContext(HANDLE hProcess, QTextStream& stream) + : hProcess(hProcess) + , stream(stream) + {} }; BOOL CALLBACK EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVOID UserContext) { Q_UNUSED(ModuleName) IMAGEHLP_MODULE64 mod; - EnumModulesContext *context = (EnumModulesContext *)UserContext; + EnumModulesContext* context = (EnumModulesContext*)UserContext; mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64); if (SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod)) { - QString line = QString("%1 0x%2 Image: %3").arg(mod.ModuleName, -14) - .arg(BaseOfDll, 8, 16, QLatin1Char('0')) - .arg(mod.LoadedImageName); + QString line = QString("%1 0x%2 Image: %3").arg(mod.ModuleName, -14).arg(BaseOfDll, 8, 16, QLatin1Char('0')).arg(mod.LoadedImageName); // qDebug() << qPrintable(line); context->stream << line << '\n'; @@ -76,16 +76,15 @@ BOOL CALLBACK EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVOID UserCont return TRUE; } - #if defined(_M_IX86) && defined(Q_CC_MSVC) // Disable global optimization and ignore /GS waning caused by // inline assembly. // not needed with mingw cause we can tell mingw which registers we use - #pragma optimize("g", off) - #pragma warning(push) - #pragma warning(disable : 4748) +# pragma optimize("g", off) +# pragma warning(push) +# pragma warning(disable : 4748) #endif -void Quassel::logBacktrace(const QString &filename) +void Quassel::logBacktrace(const QString& filename) { DWORD MachineType; CONTEXT Context; @@ -95,16 +94,16 @@ void Quassel::logBacktrace(const QString &filename) ZeroMemory(&Context, sizeof(CONTEXT)); Context.ContextFlags = CONTEXT_CONTROL; -#ifdef __MINGW32__ - asm ("Label:\n\t" - "movl %%ebp,%0;\n\t" - "movl %%esp,%1;\n\t" - "movl $Label,%%eax;\n\t" - "movl %%eax,%2;\n\t" - : "=r" (Context.Ebp), "=r" (Context.Esp), "=r" (Context.Eip) - : //no input - : "eax"); -#else +# ifdef __MINGW32__ + asm("Label:\n\t" + "movl %%ebp,%0;\n\t" + "movl %%esp,%1;\n\t" + "movl $Label,%%eax;\n\t" + "movl %%eax,%2;\n\t" + : "=r"(Context.Ebp), "=r"(Context.Esp), "=r"(Context.Eip) + : // no input + : "eax"); +# else _asm { Label: mov[Context.Ebp], ebp; @@ -112,43 +111,43 @@ Label: mov eax, [Label]; mov[Context.Eip], eax; } -#endif +# endif #else RtlCaptureContext(&Context); #endif ZeroMemory(&StackFrame, sizeof(STACKFRAME64)); #ifdef _M_IX86 - MachineType = IMAGE_FILE_MACHINE_I386; - StackFrame.AddrPC.Offset = Context.Eip; - StackFrame.AddrPC.Mode = AddrModeFlat; + MachineType = IMAGE_FILE_MACHINE_I386; + StackFrame.AddrPC.Offset = Context.Eip; + StackFrame.AddrPC.Mode = AddrModeFlat; StackFrame.AddrFrame.Offset = Context.Ebp; - StackFrame.AddrFrame.Mode = AddrModeFlat; + StackFrame.AddrFrame.Mode = AddrModeFlat; StackFrame.AddrStack.Offset = Context.Esp; - StackFrame.AddrStack.Mode = AddrModeFlat; + StackFrame.AddrStack.Mode = AddrModeFlat; #elif defined(_M_X64) - MachineType = IMAGE_FILE_MACHINE_AMD64; - StackFrame.AddrPC.Offset = Context.Rip; - StackFrame.AddrPC.Mode = AddrModeFlat; + MachineType = IMAGE_FILE_MACHINE_AMD64; + StackFrame.AddrPC.Offset = Context.Rip; + StackFrame.AddrPC.Mode = AddrModeFlat; StackFrame.AddrFrame.Offset = Context.Rsp; - StackFrame.AddrFrame.Mode = AddrModeFlat; + StackFrame.AddrFrame.Mode = AddrModeFlat; StackFrame.AddrStack.Offset = Context.Rsp; - StackFrame.AddrStack.Mode = AddrModeFlat; + StackFrame.AddrStack.Mode = AddrModeFlat; #elif defined(_M_IA64) - MachineType = IMAGE_FILE_MACHINE_IA64; - StackFrame.AddrPC.Offset = Context.StIIP; - StackFrame.AddrPC.Mode = AddrModeFlat; + MachineType = IMAGE_FILE_MACHINE_IA64; + StackFrame.AddrPC.Offset = Context.StIIP; + StackFrame.AddrPC.Mode = AddrModeFlat; StackFrame.AddrFrame.Offset = Context.IntSp; - StackFrame.AddrFrame.Mode = AddrModeFlat; + StackFrame.AddrFrame.Mode = AddrModeFlat; StackFrame.AddrBStore.Offset = Context.RsBSP; - StackFrame.AddrBStore.Mode = AddrModeFlat; + StackFrame.AddrBStore.Mode = AddrModeFlat; StackFrame.AddrStack.Offset = Context.IntSp; - StackFrame.AddrStack.Mode = AddrModeFlat; + StackFrame.AddrStack.Mode = AddrModeFlat; #else - #error "Unsupported platform" +# error "Unsupported platform" #endif - //EnterCriticalSection(&DbgHelpLock); + // EnterCriticalSection(&DbgHelpLock); QFile logFile(filename); logFile.open(QIODevice::Append); @@ -160,9 +159,7 @@ Label: DWORD64 dwDisplacement; - ULONG64 buffer[(sizeof(SYMBOL_INFO) + - MAX_SYM_NAME*sizeof(TCHAR) + - sizeof(ULONG64) - 1) / sizeof(ULONG64)]; + ULONG64 buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer; pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); pSymbol->MaxNameLen = MAX_SYM_NAME; @@ -179,7 +176,7 @@ Label: break; loadHelpStackFrame(ihsf, StackFrame); - if (StackFrame.AddrPC.Offset != 0) { // Valid frame. + if (StackFrame.AddrPC.Offset != 0) { // Valid frame. QString fileName("???"); if (SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod)) { fileName = QString(mod.ImageName); @@ -198,17 +195,18 @@ Label: SymSetContext(hProcess, &ihsf, NULL); SymEnumSymbols(hProcess, 0, NULL, EnumSymbolsCB, (PVOID)¶ms); - QString debugLine = QString("#%1 %2 0x%3 %4(%5)").arg(i, 3, 10) - .arg(fileName, -20) - .arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0')) - .arg(funcName) - .arg(params.join(", ")); + QString debugLine = QString("#%1 %2 0x%3 %4(%5)") + .arg(i, 3, 10) + .arg(fileName, -20) + .arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0')) + .arg(funcName) + .arg(params.join(", ")); // qDebug() << qPrintable(debugLine); logStream << debugLine << '\n'; i++; } else { - break; // we're at the end. + break; // we're at the end. } } @@ -220,8 +218,7 @@ Label: logFile.close(); } - #if defined(_M_IX86) && defined(Q_CC_MSVC) - #pragma warning(pop) - #pragma optimize("g", on) +# pragma warning(pop) +# pragma optimize("g", on) #endif diff --git a/src/common/logger.cpp b/src/common/logger.cpp index 97afb40d..b37abc29 100644 --- a/src/common/logger.cpp +++ b/src/common/logger.cpp @@ -21,7 +21,7 @@ #include #ifdef HAVE_SYSLOG -# include +# include #endif #include @@ -35,15 +35,14 @@ namespace { -QByteArray msgWithTime(const Logger::LogEntry &msg) +QByteArray msgWithTime(const Logger::LogEntry& msg) { return (msg.timeStamp.toString("yyyy-MM-dd hh:mm:ss ") + msg.message + "\n").toUtf8(); } -} - +} // namespace -Logger::Logger(QObject *parent) +Logger::Logger(QObject* parent) : QObject(parent) { static bool registered = []() { @@ -57,24 +56,21 @@ Logger::Logger(QObject *parent) qInstallMessageHandler(Logger::messageHandler); } - Logger::~Logger() { // If we're not initialized yet, output pending messages so they don't get lost if (!_initialized) { - for (auto &&message : _messages) { + for (auto&& message : _messages) { std::cerr << msgWithTime(message).constData(); } } } - std::vector Logger::messages() const { return _messages; } - void Logger::setup(bool keepMessages) { _keepMessages = keepMessages; @@ -98,12 +94,12 @@ void Logger::setup(bool keepMessages) QString logfilename = Quassel::optionValue("logfile"); if (!logfilename.isEmpty()) { _logFile.setFileName(logfilename); - if (!_logFile.open(QFile::Append|QFile::Unbuffered|QFile::Text)) { + if (!_logFile.open(QFile::Append | QFile::Unbuffered | QFile::Text)) { qCritical() << qPrintable(tr("Could not open log file \"%1\": %2").arg(logfilename, _logFile.errorString())); } } if (!_logFile.isOpen()) { - if (!_logFile.open(stderr, QFile::WriteOnly|QFile::Unbuffered|QFile::Text)) { + if (!_logFile.open(stderr, QFile::WriteOnly | QFile::Unbuffered | QFile::Text)) { qCritical() << qPrintable(tr("Cannot write to stderr: %1").arg(_logFile.errorString())); } } @@ -115,7 +111,7 @@ void Logger::setup(bool keepMessages) _initialized = true; // Now that we've setup our logging backends, output pending messages - for (auto &&message : _messages) { + for (auto&& message : _messages) { outputMessage(message); } if (!_keepMessages) { @@ -123,14 +119,12 @@ void Logger::setup(bool keepMessages) } } - -void Logger::messageHandler(QtMsgType type, const QMessageLogContext &, const QString &message) +void Logger::messageHandler(QtMsgType type, const QMessageLogContext&, const QString& message) { Quassel::instance()->logger()->handleMessage(type, message); } - -void Logger::handleMessage(QtMsgType type, const QString &msg) +void Logger::handleMessage(QtMsgType type, const QString& msg) { switch (type) { case QtDebugMsg: @@ -151,8 +145,7 @@ void Logger::handleMessage(QtMsgType type, const QString &msg) } } - -void Logger::handleMessage(LogLevel level, const QString &msg) +void Logger::handleMessage(LogLevel level, const QString& msg) { QString logString; @@ -178,8 +171,7 @@ void Logger::handleMessage(LogLevel level, const QString &msg) emit messageLogged({QDateTime::currentDateTime(), level, logString += msg}); } - -void Logger::onMessageLogged(const LogEntry &message) +void Logger::onMessageLogged(const LogEntry& message) { if (_keepMessages) { _messages.push_back(message); @@ -191,8 +183,7 @@ void Logger::onMessageLogged(const LogEntry &message) } } - -void Logger::outputMessage(const LogEntry &message) +void Logger::outputMessage(const LogEntry& message) { if (message.logLevel < _outputLevel) { return; @@ -217,7 +208,7 @@ void Logger::outputMessage(const LogEntry &message) case LogLevel::Fatal: prio = LOG_CRIT; } - syslog(prio|LOG_USER, "%s", qPrintable(message.message)); + syslog(prio | LOG_USER, "%s", qPrintable(message.message)); } #endif @@ -235,5 +226,4 @@ void Logger::outputMessage(const LogEntry &message) } } #endif - } diff --git a/src/common/logger.h b/src/common/logger.h index 9d80305b..751fa05f 100644 --- a/src/common/logger.h +++ b/src/common/logger.h @@ -38,10 +38,11 @@ class COMMON_EXPORT Logger : public QObject Q_OBJECT public: - Logger(QObject *parent = nullptr); + Logger(QObject* parent = nullptr); ~Logger() override; - enum class LogLevel { + enum class LogLevel + { Debug, Info, Warning, @@ -49,7 +50,8 @@ public: Fatal }; - struct LogEntry { + struct LogEntry + { QDateTime timeStamp; LogLevel logLevel; QString message; @@ -74,7 +76,7 @@ public: */ std::vector messages() const; - static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message); + static void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message); /** * Takes the given message with the given log level, formats it and emits the @a messageLogged() signal. @@ -84,7 +86,7 @@ public: * @param logLevel The log leve of the message * @param message The message */ - void handleMessage(LogLevel logLevel, const QString &message); + void handleMessage(LogLevel logLevel, const QString& message); signals: /** @@ -92,14 +94,14 @@ signals: * * @param message The message that was logged */ - void messageLogged(const Logger::LogEntry &message); + void messageLogged(const Logger::LogEntry& message); private slots: - void onMessageLogged(const Logger::LogEntry &message); + void onMessageLogged(const Logger::LogEntry& message); private: - void handleMessage(QtMsgType type, const QString &message); - void outputMessage(const LogEntry &message); + void handleMessage(QtMsgType type, const QString& message); + void outputMessage(const LogEntry& message); private: LogLevel _outputLevel{LogLevel::Info}; diff --git a/src/common/logmessage.cpp b/src/common/logmessage.cpp index 1715cfbf..573e61fc 100644 --- a/src/common/logmessage.cpp +++ b/src/common/logmessage.cpp @@ -20,33 +20,30 @@ #include "logmessage.h" +#include #include #include -#include #include "quassel.h" LogMessage::LogMessage(Logger::LogLevel level) : _stream(&_buffer, QIODevice::WriteOnly) , _logLevel(level) -{ -} - +{} LogMessage::~LogMessage() { Quassel::instance()->logger()->handleMessage(_logLevel, _buffer); } - -LogMessage &LogMessage::operator<<(const QStringList &t) +LogMessage& LogMessage::operator<<(const QStringList& t) { _stream << t.join(" ") << " "; return *this; } - -LogMessage &LogMessage::operator<<(bool t) { +LogMessage& LogMessage::operator<<(bool t) +{ _stream << (t ? "true" : "false") << " "; return *this; } diff --git a/src/common/logmessage.h b/src/common/logmessage.h index bd9acc6d..b4795ad7 100644 --- a/src/common/logmessage.h +++ b/src/common/logmessage.h @@ -40,13 +40,14 @@ public: ~LogMessage(); template - LogMessage &operator<<(const T &value) { + LogMessage& operator<<(const T& value) + { _stream << value << " "; return *this; } - LogMessage &operator<<(const QStringList &t); - LogMessage &operator<<(bool t); + LogMessage& operator<<(const QStringList& t); + LogMessage& operator<<(bool t); private: QTextStream _stream; @@ -54,7 +55,6 @@ private: Logger::LogLevel _logLevel; }; - // The only reason for LogMessage and the helpers below to exist is the fact that Qt versions // prior to 5.5 did not support the Info level. // Once we can rely on Qt 5.5, they will be removed and replaced by the native Qt functions. @@ -67,10 +67,11 @@ private: class quInfo : public LogMessage { public: - quInfo() : LogMessage(Logger::LogLevel::Info) {} + quInfo() + : LogMessage(Logger::LogLevel::Info) + {} }; - /** * Creates a warning-level log message. * @@ -79,10 +80,11 @@ public: class quWarning : public LogMessage { public: - quWarning() : LogMessage(Logger::LogLevel::Warning) {} + quWarning() + : LogMessage(Logger::LogLevel::Warning) + {} }; - /** * Creates an error-level log message. * @@ -91,5 +93,7 @@ public: class quError : public LogMessage { public: - quError() : LogMessage(Logger::LogLevel::Error) {} + quError() + : LogMessage(Logger::LogLevel::Error) + {} }; diff --git a/src/common/mac_utils.cpp b/src/common/mac_utils.cpp index 017f4a42..13021fcd 100644 --- a/src/common/mac_utils.cpp +++ b/src/common/mac_utils.cpp @@ -28,11 +28,11 @@ QString CFStringToQString(CFStringRef str) return QString(); CFIndex length = CFStringGetLength(str); - const UniChar *chars = CFStringGetCharactersPtr(str); + const UniChar* chars = CFStringGetCharactersPtr(str); if (chars) - return QString(reinterpret_cast(chars), length); + return QString(reinterpret_cast(chars), length); QVarLengthArray buffer(length); CFStringGetCharacters(str, CFRangeMake(0, length), buffer.data()); - return QString(reinterpret_cast(buffer.constData()), length); + return QString(reinterpret_cast(buffer.constData()), length); } diff --git a/src/common/mac_utils.h b/src/common/mac_utils.h index 0ade199d..16784fc2 100644 --- a/src/common/mac_utils.h +++ b/src/common/mac_utils.h @@ -22,8 +22,9 @@ #define MAC_UTILS_H #include + #include QString CFStringToQString(CFStringRef str); -#endif //MAC_UTILS_H +#endif // MAC_UTILS_H diff --git a/src/common/message.cpp b/src/common/message.cpp index 8cf74d2c..3ad6e87d 100644 --- a/src/common/message.cpp +++ b/src/common/message.cpp @@ -20,45 +20,48 @@ #include "message.h" -#include "util.h" -#include "peer.h" -#include "signalproxy.h" - -#include #include -Message::Message(BufferInfo bufferInfo, Type type, QString contents, QString sender, - QString senderPrefixes, QString realName, QString avatarUrl, Flags flags) - : _timestamp(QDateTime::currentDateTime().toUTC()), - _bufferInfo(std::move(bufferInfo)), - _contents(std::move(contents)), - _sender(std::move(sender)), - _senderPrefixes(std::move(senderPrefixes)), - _realName(std::move(realName)), - _avatarUrl(std::move(avatarUrl)), - _type(type), - _flags(flags) -{ -} - - -Message::Message(QDateTime ts, BufferInfo bufferInfo, Type type, QString contents, - QString sender, QString senderPrefixes, QString realName, - QString avatarUrl, Flags flags) - : _timestamp(std::move(ts)), - _bufferInfo(std::move(bufferInfo)), - _contents(std::move(contents)), - _sender(std::move(sender)), - _senderPrefixes(std::move(senderPrefixes)), - _realName(std::move(realName)), - _avatarUrl(std::move(avatarUrl)), - _type(type), - _flags(flags) -{ -} +#include +#include "peer.h" +#include "signalproxy.h" +#include "util.h" -QDataStream &operator<<(QDataStream &out, const Message &msg) +Message::Message( + BufferInfo bufferInfo, Type type, QString contents, QString sender, QString senderPrefixes, QString realName, QString avatarUrl, Flags flags) + : _timestamp(QDateTime::currentDateTime().toUTC()) + , _bufferInfo(std::move(bufferInfo)) + , _contents(std::move(contents)) + , _sender(std::move(sender)) + , _senderPrefixes(std::move(senderPrefixes)) + , _realName(std::move(realName)) + , _avatarUrl(std::move(avatarUrl)) + , _type(type) + , _flags(flags) +{} + +Message::Message(QDateTime ts, + BufferInfo bufferInfo, + Type type, + QString contents, + QString sender, + QString senderPrefixes, + QString realName, + QString avatarUrl, + Flags flags) + : _timestamp(std::move(ts)) + , _bufferInfo(std::move(bufferInfo)) + , _contents(std::move(contents)) + , _sender(std::move(sender)) + , _senderPrefixes(std::move(senderPrefixes)) + , _realName(std::move(realName)) + , _avatarUrl(std::move(avatarUrl)) + , _type(type) + , _flags(flags) +{} + +QDataStream& operator<<(QDataStream& out, const Message& msg) { Q_ASSERT(SignalProxy::current()); Q_ASSERT(SignalProxy::current()->targetPeer()); @@ -68,15 +71,13 @@ QDataStream &operator<<(QDataStream &out, const Message &msg) if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) { // toMSecs returns a qint64, signed rather than unsigned - out << (qint64) msg.timestamp().toMSecsSinceEpoch(); - } else { - out << (quint32) msg.timestamp().toTime_t(); + out << (qint64)msg.timestamp().toMSecsSinceEpoch(); + } + else { + out << (quint32)msg.timestamp().toTime_t(); } - out << (quint32) msg.type() - << (quint8) msg.flags() - << msg.bufferInfo() - << msg.sender().toUtf8(); + out << (quint32)msg.type() << (quint8)msg.flags() << msg.bufferInfo() << msg.sender().toUtf8(); if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::SenderPrefixes)) out << msg.senderPrefixes().toUtf8(); @@ -90,8 +91,7 @@ QDataStream &operator<<(QDataStream &out, const Message &msg) return out; } - -QDataStream &operator>>(QDataStream &in, Message &msg) +QDataStream& operator>>(QDataStream& in, Message& msg) { Q_ASSERT(SignalProxy::current()); Q_ASSERT(SignalProxy::current()->sourcePeer()); @@ -103,7 +103,8 @@ QDataStream &operator>>(QDataStream &in, Message &msg) qint64 timeStamp; in >> timeStamp; msg._timestamp = QDateTime::fromMSecsSinceEpoch(timeStamp); - } else { + } + else { quint32 timeStamp; in >> timeStamp; msg._timestamp = QDateTime::fromTime_t(timeStamp); @@ -144,15 +145,11 @@ QDataStream &operator>>(QDataStream &in, Message &msg) return in; } - -QDebug operator<<(QDebug dbg, const Message &msg) +QDebug operator<<(QDebug dbg, const Message& msg) { - dbg.nospace() << qPrintable(QString("Message(MsgId:")) << msg.msgId() - << qPrintable(QString(",")) << msg.timestamp() - << qPrintable(QString(", Type:")) << msg.type() - << qPrintable(QString(", RealName:")) << msg.realName() - << qPrintable(QString(", AvatarURL:")) << msg.avatarUrl() - << qPrintable(QString(", Flags:")) << msg.flags() << qPrintable(QString(")")) - << msg.senderPrefixes() << msg.sender() << ":" << msg.contents(); + dbg.nospace() << qPrintable(QString("Message(MsgId:")) << msg.msgId() << qPrintable(QString(",")) << msg.timestamp() + << qPrintable(QString(", Type:")) << msg.type() << qPrintable(QString(", RealName:")) << msg.realName() + << qPrintable(QString(", AvatarURL:")) << msg.avatarUrl() << qPrintable(QString(", Flags:")) << msg.flags() + << qPrintable(QString(")")) << msg.senderPrefixes() << msg.sender() << ":" << msg.contents(); return dbg; } diff --git a/src/common/message.h b/src/common/message.h index 8b16aa0d..4c700eff 100644 --- a/src/common/message.h +++ b/src/common/message.h @@ -34,67 +34,80 @@ class COMMON_EXPORT Message public: /** The different types a message can have for display */ - enum Type { - Plain = 0x00001, - Notice = 0x00002, - Action = 0x00004, - Nick = 0x00008, - Mode = 0x00010, - Join = 0x00020, - Part = 0x00040, - Quit = 0x00080, - Kick = 0x00100, - Kill = 0x00200, - Server = 0x00400, - Info = 0x00800, - Error = 0x01000, - DayChange = 0x02000, - Topic = 0x04000, + enum Type + { + Plain = 0x00001, + Notice = 0x00002, + Action = 0x00004, + Nick = 0x00008, + Mode = 0x00010, + Join = 0x00020, + Part = 0x00040, + Quit = 0x00080, + Kick = 0x00100, + Kill = 0x00200, + Server = 0x00400, + Info = 0x00800, + Error = 0x01000, + DayChange = 0x02000, + Topic = 0x04000, NetsplitJoin = 0x08000, NetsplitQuit = 0x10000, - Invite = 0x20000, + Invite = 0x20000, }; Q_DECLARE_FLAGS(Types, Type) // DO NOT CHANGE without knowing what you do, some of these flags are stored in the database - enum Flag { - None = 0x00, - Self = 0x01, - Highlight = 0x02, + enum Flag + { + None = 0x00, + Self = 0x01, + Highlight = 0x02, Redirected = 0x04, - ServerMsg = 0x08, - StatusMsg = 0x10, - Backlog = 0x80 + ServerMsg = 0x08, + StatusMsg = 0x10, + Backlog = 0x80 }; Q_DECLARE_FLAGS(Flags, Flag) - Message(BufferInfo bufferInfo = BufferInfo(), Type type = Plain, QString contents = {}, - QString sender = {}, QString senderPrefixes = {}, QString realName = {}, - QString avatarUrl = {}, Flags flags = None); - Message(QDateTime ts, BufferInfo buffer = BufferInfo(), Type type = Plain, - QString contents = {}, QString sender = {}, QString senderPrefixes = {}, - QString realName = {}, QString avatarUrl = {}, Flags flags = None); - - inline static Message ChangeOfDay(const QDateTime &day) { return Message(day, BufferInfo(), DayChange); } - inline const MsgId &msgId() const { return _msgId; } + Message(BufferInfo bufferInfo = BufferInfo(), + Type type = Plain, + QString contents = {}, + QString sender = {}, + QString senderPrefixes = {}, + QString realName = {}, + QString avatarUrl = {}, + Flags flags = None); + Message(QDateTime ts, + BufferInfo buffer = BufferInfo(), + Type type = Plain, + QString contents = {}, + QString sender = {}, + QString senderPrefixes = {}, + QString realName = {}, + QString avatarUrl = {}, + Flags flags = None); + + inline static Message ChangeOfDay(const QDateTime& day) { return Message(day, BufferInfo(), DayChange); } + inline const MsgId& msgId() const { return _msgId; } inline void setMsgId(MsgId id) { _msgId = id; } - inline const BufferInfo &bufferInfo() const { return _bufferInfo; } - inline const BufferId &bufferId() const { return _bufferInfo.bufferId(); } + inline const BufferInfo& bufferInfo() const { return _bufferInfo; } + inline const BufferId& bufferId() const { return _bufferInfo.bufferId(); } inline void setBufferId(BufferId id) { _bufferInfo.setBufferId(id); } - inline const QString &contents() const { return _contents; } - inline const QString &sender() const { return _sender; } - inline const QString &senderPrefixes() const { return _senderPrefixes; } - inline const QString &realName() const { return _realName; } - inline const QString &avatarUrl() const { return _avatarUrl; } + inline const QString& contents() const { return _contents; } + inline const QString& sender() const { return _sender; } + inline const QString& senderPrefixes() const { return _senderPrefixes; } + inline const QString& realName() const { return _realName; } + inline const QString& avatarUrl() const { return _avatarUrl; } inline Type type() const { return _type; } inline Flags flags() const { return _flags; } inline void setFlags(Flags flags) { _flags = flags; } - inline const QDateTime ×tamp() const { return _timestamp; } + inline const QDateTime& timestamp() const { return _timestamp; } inline bool isValid() const { return _msgId.isValid(); } - inline bool operator<(const Message &other) const { return _msgId < other._msgId; } + inline bool operator<(const Message& other) const { return _msgId < other._msgId; } private: QDateTime _timestamp; @@ -108,15 +121,14 @@ private: Type _type; Flags _flags; - friend QDataStream &operator>>(QDataStream &in, Message &msg); + friend QDataStream& operator>>(QDataStream& in, Message& msg); }; - using MessageList = QList; -QDataStream &operator<<(QDataStream &out, const Message &msg); -QDataStream &operator>>(QDataStream &in, Message &msg); -QDebug operator<<(QDebug dbg, const Message &msg); +QDataStream& operator<<(QDataStream& out, const Message& msg); +QDataStream& operator>>(QDataStream& in, Message& msg); +QDebug operator<<(QDebug dbg, const Message& msg); Q_DECLARE_METATYPE(Message) Q_DECLARE_OPERATORS_FOR_FLAGS(Message::Types) diff --git a/src/common/messageevent.cpp b/src/common/messageevent.cpp index f58fa0b4..41485e21 100644 --- a/src/common/messageevent.cpp +++ b/src/common/messageevent.cpp @@ -22,7 +22,7 @@ #include -Event *MessageEvent::create(EventManager::EventType type, QVariantMap &map, Network *network) +Event* MessageEvent::create(EventManager::EventType type, QVariantMap& map, Network* network) { if (type == EventManager::MessageEvent) return new MessageEvent(type, map, network); @@ -30,17 +30,16 @@ Event *MessageEvent::create(EventManager::EventType type, QVariantMap &map, Netw return nullptr; } - -MessageEvent::MessageEvent(Message::Type msgType, Network *net, QString msg, const QString &sender, QString target, - Message::Flags flags, const QDateTime ×tamp) - : NetworkEvent(EventManager::MessageEvent, net), - _msgType(msgType), - _text(std::move(msg)), - _sender(sender), - _target(std::move(target)), - _msgFlags(flags) +MessageEvent::MessageEvent( + Message::Type msgType, Network* net, QString msg, const QString& sender, QString target, Message::Flags flags, const QDateTime& timestamp) + : NetworkEvent(EventManager::MessageEvent, net) + , _msgType(msgType) + , _text(std::move(msg)) + , _sender(sender) + , _target(std::move(target)) + , _msgFlags(flags) { - IrcChannel *channel = network()->ircChannel(_target); + IrcChannel* channel = network()->ircChannel(_target); if (!channel) { if (!_target.isEmpty() && network()->prefixes().contains(_target.at(0))) _target = _target.mid(1); @@ -57,8 +56,7 @@ MessageEvent::MessageEvent(Message::Type msgType, Network *net, QString msg, con setTimestamp(QDateTime::currentDateTime()); } - -MessageEvent::MessageEvent(EventManager::EventType type, QVariantMap &map, Network *network) +MessageEvent::MessageEvent(EventManager::EventType type, QVariantMap& map, Network* network) : NetworkEvent(type, map, network) { _msgType = static_cast(map.take("messageType").toInt()); @@ -69,8 +67,7 @@ MessageEvent::MessageEvent(EventManager::EventType type, QVariantMap &map, Netwo _target = map.take("target").toString(); } - -void MessageEvent::toVariantMap(QVariantMap &map) const +void MessageEvent::toVariantMap(QVariantMap& map) const { NetworkEvent::toVariantMap(map); map["messageType"] = msgType(); @@ -81,8 +78,7 @@ void MessageEvent::toVariantMap(QVariantMap &map) const map["target"] = target(); } - -BufferInfo::Type MessageEvent::bufferTypeByTarget(const QString &target) const +BufferInfo::Type MessageEvent::bufferTypeByTarget(const QString& target) const { if (target.isEmpty()) return BufferInfo::StatusBuffer; diff --git a/src/common/messageevent.h b/src/common/messageevent.h index 7e6df266..8faf1fda 100644 --- a/src/common/messageevent.h +++ b/src/common/messageevent.h @@ -32,13 +32,12 @@ class COMMON_EXPORT MessageEvent : public NetworkEvent { public: explicit MessageEvent(Message::Type msgType, - Network *network, - QString msg, - const QString &sender = QString(), - QString target = QString(), - Message::Flags msgFlags = Message::None, - const QDateTime ×tamp = QDateTime() - ); + Network* network, + QString msg, + const QString& sender = QString(), + QString target = QString(), + Message::Flags msgFlags = Message::None, + const QDateTime& timestamp = QDateTime()); inline Message::Type msgType() const { return _msgType; } inline void setMsgType(Message::Type type) { _msgType = type; } @@ -54,27 +53,24 @@ public: inline void setMsgFlag(Message::Flag flag) { _msgFlags |= flag; } inline void setMsgFlags(Message::Flags flags) { _msgFlags = flags; } - static Event *create(EventManager::EventType type, QVariantMap &map, Network *network); + static Event* create(EventManager::EventType type, QVariantMap& map, Network* network); protected: - explicit MessageEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit MessageEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "MessageEvent"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); - dbg.nospace() << ", sender = " << qPrintable(sender()) - << ", target = " << qPrintable(target()) - << ", text = " << text() + dbg.nospace() << ", sender = " << qPrintable(sender()) << ", target = " << qPrintable(target()) << ", text = " << text() << ", msgtype = " << qPrintable(QString::number(msgType(), 16)) << ", buffertype = " << qPrintable(QString::number(bufferType(), 16)) << ", msgflags = " << qPrintable(QString::number(msgFlags(), 16)); } - private: - BufferInfo::Type bufferTypeByTarget(const QString &target) const; + BufferInfo::Type bufferTypeByTarget(const QString& target) const; Message::Type _msgType; BufferInfo::Type _bufferType; diff --git a/src/common/network.cpp b/src/common/network.cpp index 686c2e05..1cd441e9 100644 --- a/src/common/network.cpp +++ b/src/common/network.cpp @@ -18,61 +18,60 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "network.h" + #include #include -#include "network.h" #include "peer.h" -QTextCodec *Network::_defaultCodecForServer = nullptr; -QTextCodec *Network::_defaultCodecForEncoding = nullptr; -QTextCodec *Network::_defaultCodecForDecoding = nullptr; +QTextCodec* Network::_defaultCodecForServer = nullptr; +QTextCodec* Network::_defaultCodecForEncoding = nullptr; +QTextCodec* Network::_defaultCodecForDecoding = nullptr; // ==================== // Public: // ==================== -Network::Network(const NetworkId &networkid, QObject *parent) - : SyncableObject(parent), - _proxy(nullptr), - _networkId(networkid), - _identity(0), - _myNick(QString()), - _latency(0), - _networkName(QString("")), - _currentServer(QString()), - _connected(false), - _connectionState(Disconnected), - _prefixes(QString()), - _prefixModes(QString()), - _useRandomServer(false), - _useAutoIdentify(false), - _useSasl(false), - _useAutoReconnect(false), - _autoReconnectInterval(60), - _autoReconnectRetries(10), - _unlimitedReconnectRetries(false), - _useCustomMessageRate(false), - _messageRateBurstSize(5), - _messageRateDelay(2200), - _unlimitedMessageRate(false), - _codecForServer(nullptr), - _codecForEncoding(nullptr), - _codecForDecoding(nullptr), - _autoAwayActive(false) +Network::Network(const NetworkId& networkid, QObject* parent) + : SyncableObject(parent) + , _proxy(nullptr) + , _networkId(networkid) + , _identity(0) + , _myNick(QString()) + , _latency(0) + , _networkName(QString("")) + , _currentServer(QString()) + , _connected(false) + , _connectionState(Disconnected) + , _prefixes(QString()) + , _prefixModes(QString()) + , _useRandomServer(false) + , _useAutoIdentify(false) + , _useSasl(false) + , _useAutoReconnect(false) + , _autoReconnectInterval(60) + , _autoReconnectRetries(10) + , _unlimitedReconnectRetries(false) + , _useCustomMessageRate(false) + , _messageRateBurstSize(5) + , _messageRateDelay(2200) + , _unlimitedMessageRate(false) + , _codecForServer(nullptr) + , _codecForEncoding(nullptr) + , _codecForDecoding(nullptr) + , _autoAwayActive(false) { setObjectName(QString::number(networkid.toInt())); } - Network::~Network() { emit aboutToBeDestroyed(); } - -bool Network::isChannelName(const QString &channelname) const +bool Network::isChannelName(const QString& channelname) const { if (channelname.isEmpty()) return false; @@ -83,8 +82,7 @@ bool Network::isChannelName(const QString &channelname) const return QString("#&!+").contains(channelname[0]); } - -bool Network::isStatusMsg(const QString &target) const +bool Network::isStatusMsg(const QString& target) const { if (target.isEmpty()) return false; @@ -95,7 +93,6 @@ bool Network::isStatusMsg(const QString &target) const return QString("@+").contains(target[0]); } - NetworkInfo Network::networkInfo() const { NetworkInfo info; @@ -126,29 +123,47 @@ NetworkInfo Network::networkInfo() const return info; } - -void Network::setNetworkInfo(const NetworkInfo &info) +void Network::setNetworkInfo(const NetworkInfo& info) { // we don't set our ID! - if (!info.networkName.isEmpty() && info.networkName != networkName()) setNetworkName(info.networkName); - if (info.identity > 0 && info.identity != identity()) setIdentity(info.identity); - if (info.codecForServer != codecForServer()) setCodecForServer(QTextCodec::codecForName(info.codecForServer)); - if (info.codecForEncoding != codecForEncoding()) setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding)); - if (info.codecForDecoding != codecForDecoding()) setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding)); - if (info.serverList.count()) setServerList(toVariantList(info.serverList)); // FIXME compare components - if (info.useRandomServer != useRandomServer()) setUseRandomServer(info.useRandomServer); - if (info.perform != perform()) setPerform(info.perform); - if (info.useAutoIdentify != useAutoIdentify()) setUseAutoIdentify(info.useAutoIdentify); - if (info.autoIdentifyService != autoIdentifyService()) setAutoIdentifyService(info.autoIdentifyService); - if (info.autoIdentifyPassword != autoIdentifyPassword()) setAutoIdentifyPassword(info.autoIdentifyPassword); - if (info.useSasl != useSasl()) setUseSasl(info.useSasl); - if (info.saslAccount != saslAccount()) setSaslAccount(info.saslAccount); - if (info.saslPassword != saslPassword()) setSaslPassword(info.saslPassword); - if (info.useAutoReconnect != useAutoReconnect()) setUseAutoReconnect(info.useAutoReconnect); - if (info.autoReconnectInterval != autoReconnectInterval()) setAutoReconnectInterval(info.autoReconnectInterval); - if (info.autoReconnectRetries != autoReconnectRetries()) setAutoReconnectRetries(info.autoReconnectRetries); - if (info.unlimitedReconnectRetries != unlimitedReconnectRetries()) setUnlimitedReconnectRetries(info.unlimitedReconnectRetries); - if (info.rejoinChannels != rejoinChannels()) setRejoinChannels(info.rejoinChannels); + if (!info.networkName.isEmpty() && info.networkName != networkName()) + setNetworkName(info.networkName); + if (info.identity > 0 && info.identity != identity()) + setIdentity(info.identity); + if (info.codecForServer != codecForServer()) + setCodecForServer(QTextCodec::codecForName(info.codecForServer)); + if (info.codecForEncoding != codecForEncoding()) + setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding)); + if (info.codecForDecoding != codecForDecoding()) + setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding)); + if (info.serverList.count()) + setServerList(toVariantList(info.serverList)); // FIXME compare components + if (info.useRandomServer != useRandomServer()) + setUseRandomServer(info.useRandomServer); + if (info.perform != perform()) + setPerform(info.perform); + if (info.useAutoIdentify != useAutoIdentify()) + setUseAutoIdentify(info.useAutoIdentify); + if (info.autoIdentifyService != autoIdentifyService()) + setAutoIdentifyService(info.autoIdentifyService); + if (info.autoIdentifyPassword != autoIdentifyPassword()) + setAutoIdentifyPassword(info.autoIdentifyPassword); + if (info.useSasl != useSasl()) + setUseSasl(info.useSasl); + if (info.saslAccount != saslAccount()) + setSaslAccount(info.saslAccount); + if (info.saslPassword != saslPassword()) + setSaslPassword(info.saslPassword); + if (info.useAutoReconnect != useAutoReconnect()) + setUseAutoReconnect(info.useAutoReconnect); + if (info.autoReconnectInterval != autoReconnectInterval()) + setAutoReconnectInterval(info.autoReconnectInterval); + if (info.autoReconnectRetries != autoReconnectRetries()) + setAutoReconnectRetries(info.autoReconnectRetries); + if (info.unlimitedReconnectRetries != unlimitedReconnectRetries()) + setUnlimitedReconnectRetries(info.unlimitedReconnectRetries); + if (info.rejoinChannels != rejoinChannels()) + setRejoinChannels(info.rejoinChannels); // Custom rate limiting if (info.useCustomMessageRate != useCustomMessageRate()) setUseCustomMessageRate(info.useCustomMessageRate); @@ -160,8 +175,7 @@ void Network::setNetworkInfo(const NetworkInfo &info) setUnlimitedMessageRate(info.unlimitedMessageRate); } - -QString Network::prefixToMode(const QString &prefix) const +QString Network::prefixToMode(const QString& prefix) const { if (prefixes().contains(prefix)) return QString(prefixModes()[prefixes().indexOf(prefix)]); @@ -169,8 +183,7 @@ QString Network::prefixToMode(const QString &prefix) const return QString(); } - -QString Network::modeToPrefix(const QString &mode) const +QString Network::modeToPrefix(const QString& mode) const { if (prefixModes().contains(mode)) return QString(prefixes()[prefixModes().indexOf(mode)]); @@ -178,8 +191,7 @@ QString Network::modeToPrefix(const QString &mode) const return QString(); } - -QString Network::sortPrefixModes(const QString &modes) const +QString Network::sortPrefixModes(const QString& modes) const { // If modes is empty or we don't have any modes, nothing can be sorted, bail out early if (modes.isEmpty() || prefixModes().isEmpty()) { @@ -194,7 +206,7 @@ QString Network::sortPrefixModes(const QString &modes) const // Sort modes as if a QChar array // See https://en.cppreference.com/w/cpp/algorithm/sort // Defining lambda with [&] implicitly captures variables by reference - std::sort(sortedModes.begin(), sortedModes.end(), [&](const QChar &lmode, const QChar &rmode) { + std::sort(sortedModes.begin(), sortedModes.end(), [&](const QChar& lmode, const QChar& rmode) { // Compare characters according to prefix modes // Return true if lmode comes before rmode (is "less than") @@ -202,10 +214,12 @@ QString Network::sortPrefixModes(const QString &modes) const if (!prefixModes().contains(lmode)) { // Left mode not in prefix list, send to end return false; - } else if (!prefixModes().contains(rmode)) { + } + else if (!prefixModes().contains(rmode)) { // Right mode not in prefix list, send to end return true; - } else { + } + else { // Both characters known, sort according to index in prefixModes() return (prefixModes().indexOf(lmode) < prefixModes().indexOf(rmode)); } @@ -214,19 +228,17 @@ QString Network::sortPrefixModes(const QString &modes) const return sortedModes; } - QStringList Network::nicks() const { // we don't use _ircUsers.keys() since the keys may be // not up to date after a nick change QStringList nicks; - foreach(IrcUser *ircuser, _ircUsers.values()) { + foreach (IrcUser* ircuser, _ircUsers.values()) { nicks << ircuser->nick(); } return nicks; } - QString Network::prefixes() const { if (_prefixes.isNull()) @@ -235,7 +247,6 @@ QString Network::prefixes() const return _prefixes; } - QString Network::prefixModes() const { if (_prefixModes.isNull()) @@ -244,9 +255,8 @@ QString Network::prefixModes() const return _prefixModes; } - // example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG -Network::ChannelModeType Network::channelModeType(const QString &mode) +Network::ChannelModeType Network::channelModeType(const QString& mode) { if (mode.isEmpty()) return NOT_A_CHANMODE; @@ -269,8 +279,7 @@ Network::ChannelModeType Network::channelModeType(const QString &mode) return modeType; } - -QString Network::support(const QString ¶m) const +QString Network::support(const QString& param) const { QString support_ = param.toUpper(); if (_supports.contains(support_)) @@ -279,8 +288,7 @@ QString Network::support(const QString ¶m) const return QString(); } - -bool Network::saslMaybeSupports(const QString &saslMechanism) const +bool Network::saslMaybeSupports(const QString& saslMechanism) const { if (!capAvailable(IrcCap::SASL)) { // If SASL's not advertised at all, it's likely the mechanism isn't supported, as per specs. @@ -297,16 +305,14 @@ bool Network::saslMaybeSupports(const QString &saslMechanism) const // reduce the risk of breaking existing setups. // See: http://ircv3.net/specs/extensions/sasl-3.1.html // And: http://ircv3.net/specs/extensions/sasl-3.2.html - return (saslCapValue.length() == 0) - || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive)); + return (saslCapValue.length() == 0) || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive)); } - -IrcUser *Network::newIrcUser(const QString &hostmask, const QVariantMap &initData) +IrcUser* Network::newIrcUser(const QString& hostmask, const QVariantMap& initData) { QString nick(nickFromMask(hostmask).toLower()); if (!_ircUsers.contains(nick)) { - IrcUser *ircuser = ircUserFactory(hostmask); + IrcUser* ircuser = ircUserFactory(hostmask); if (!initData.isEmpty()) { ircuser->fromVariantMap(initData); ircuser->setInitialized(); @@ -333,8 +339,7 @@ IrcUser *Network::newIrcUser(const QString &hostmask, const QVariantMap &initDat return _ircUsers[nick]; } - -IrcUser *Network::ircUser(QString nickname) const +IrcUser* Network::ircUser(QString nickname) const { nickname = nickname.toLower(); if (_ircUsers.contains(nickname)) @@ -343,8 +348,7 @@ IrcUser *Network::ircUser(QString nickname) const return nullptr; } - -void Network::removeIrcUser(IrcUser *ircuser) +void Network::removeIrcUser(IrcUser* ircuser) { QString nick = _ircUsers.key(ircuser); if (nick.isNull()) @@ -355,8 +359,7 @@ void Network::removeIrcUser(IrcUser *ircuser) ircuser->deleteLater(); } - -void Network::removeIrcChannel(IrcChannel *channel) +void Network::removeIrcChannel(IrcChannel* channel) { QString chanName = _ircChannels.key(channel); if (chanName.isNull()) @@ -367,23 +370,21 @@ void Network::removeIrcChannel(IrcChannel *channel) channel->deleteLater(); } - void Network::removeChansAndUsers() { - QList users = ircUsers(); + QList users = ircUsers(); _ircUsers.clear(); - QList channels = ircChannels(); + QList channels = ircChannels(); _ircChannels.clear(); qDeleteAll(users); qDeleteAll(channels); } - -IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap &initData) +IrcChannel* Network::newIrcChannel(const QString& channelname, const QVariantMap& initData) { if (!_ircChannels.contains(channelname.toLower())) { - IrcChannel *channel = ircChannelFactory(channelname); + IrcChannel* channel = ircChannelFactory(channelname); if (!initData.isEmpty()) { channel->fromVariantMap(initData); channel->setInitialized(); @@ -403,8 +404,7 @@ IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap return _ircChannels[channelname.toLower()]; } - -IrcChannel *Network::ircChannel(QString channelname) const +IrcChannel* Network::ircChannel(QString channelname) const { channelname = channelname.toLower(); if (_ircChannels.contains(channelname)) @@ -413,7 +413,6 @@ IrcChannel *Network::ircChannel(QString channelname) const return nullptr; } - QByteArray Network::defaultCodecForServer() { if (_defaultCodecForServer) @@ -421,13 +420,11 @@ QByteArray Network::defaultCodecForServer() return QByteArray(); } - -void Network::setDefaultCodecForServer(const QByteArray &name) +void Network::setDefaultCodecForServer(const QByteArray& name) { _defaultCodecForServer = QTextCodec::codecForName(name); } - QByteArray Network::defaultCodecForEncoding() { if (_defaultCodecForEncoding) @@ -435,13 +432,11 @@ QByteArray Network::defaultCodecForEncoding() return QByteArray(); } - -void Network::setDefaultCodecForEncoding(const QByteArray &name) +void Network::setDefaultCodecForEncoding(const QByteArray& name) { _defaultCodecForEncoding = QTextCodec::codecForName(name); } - QByteArray Network::defaultCodecForDecoding() { if (_defaultCodecForDecoding) @@ -449,13 +444,11 @@ QByteArray Network::defaultCodecForDecoding() return QByteArray(); } - -void Network::setDefaultCodecForDecoding(const QByteArray &name) +void Network::setDefaultCodecForDecoding(const QByteArray& name) { _defaultCodecForDecoding = QTextCodec::codecForName(name); } - QByteArray Network::codecForServer() const { if (_codecForServer) @@ -463,14 +456,12 @@ QByteArray Network::codecForServer() const return QByteArray(); } - -void Network::setCodecForServer(const QByteArray &name) +void Network::setCodecForServer(const QByteArray& name) { setCodecForServer(QTextCodec::codecForName(name)); } - -void Network::setCodecForServer(QTextCodec *codec) +void Network::setCodecForServer(QTextCodec* codec) { _codecForServer = codec; QByteArray codecName = codecForServer(); @@ -478,7 +469,6 @@ void Network::setCodecForServer(QTextCodec *codec) emit configChanged(); } - QByteArray Network::codecForEncoding() const { if (_codecForEncoding) @@ -486,14 +476,12 @@ QByteArray Network::codecForEncoding() const return QByteArray(); } - -void Network::setCodecForEncoding(const QByteArray &name) +void Network::setCodecForEncoding(const QByteArray& name) { setCodecForEncoding(QTextCodec::codecForName(name)); } - -void Network::setCodecForEncoding(QTextCodec *codec) +void Network::setCodecForEncoding(QTextCodec* codec) { _codecForEncoding = codec; QByteArray codecName = codecForEncoding(); @@ -501,22 +489,20 @@ void Network::setCodecForEncoding(QTextCodec *codec) emit configChanged(); } - QByteArray Network::codecForDecoding() const { if (_codecForDecoding) return _codecForDecoding->name(); - else return QByteArray(); + else + return QByteArray(); } - -void Network::setCodecForDecoding(const QByteArray &name) +void Network::setCodecForDecoding(const QByteArray& name) { setCodecForDecoding(QTextCodec::codecForName(name)); } - -void Network::setCodecForDecoding(QTextCodec *codec) +void Network::setCodecForDecoding(QTextCodec* codec) { _codecForDecoding = codec; QByteArray codecName = codecForDecoding(); @@ -524,17 +510,16 @@ void Network::setCodecForDecoding(QTextCodec *codec) emit configChanged(); } - // FIXME use server encoding if appropriate -QString Network::decodeString(const QByteArray &text) const +QString Network::decodeString(const QByteArray& text) const { if (_codecForDecoding) return ::decodeString(text, _codecForDecoding); - else return ::decodeString(text, _defaultCodecForDecoding); + else + return ::decodeString(text, _defaultCodecForDecoding); } - -QByteArray Network::encodeString(const QString &string) const +QByteArray Network::encodeString(const QString& string) const { if (_codecForEncoding) { return _codecForEncoding->fromUnicode(string); @@ -545,8 +530,7 @@ QByteArray Network::encodeString(const QString &string) const return string.toLatin1(); } - -QString Network::decodeServerString(const QByteArray &text) const +QString Network::decodeServerString(const QByteArray& text) const { if (_codecForServer) return ::decodeString(text, _codecForServer); @@ -554,8 +538,7 @@ QString Network::decodeServerString(const QByteArray &text) const return ::decodeString(text, _defaultCodecForServer); } - -QByteArray Network::encodeServerString(const QString &string) const +QByteArray Network::encodeServerString(const QString& string) const { if (_codecForServer) { return _codecForServer->fromUnicode(string); @@ -566,11 +549,10 @@ QByteArray Network::encodeServerString(const QString &string) const return string.toLatin1(); } - // ==================== // Public Slots: // ==================== -void Network::setNetworkName(const QString &networkName) +void Network::setNetworkName(const QString& networkName) { _networkName = networkName; SYNC(ARG(networkName)) @@ -578,15 +560,13 @@ void Network::setNetworkName(const QString &networkName) emit configChanged(); } - -void Network::setCurrentServer(const QString ¤tServer) +void Network::setCurrentServer(const QString& currentServer) { _currentServer = currentServer; SYNC(ARG(currentServer)) emit currentServerSet(currentServer); } - void Network::setConnected(bool connected) { if (_connected == connected) @@ -602,18 +582,16 @@ void Network::setConnected(bool connected) emit connectedSet(connected); } - -//void Network::setConnectionState(ConnectionState state) { +// void Network::setConnectionState(ConnectionState state) { void Network::setConnectionState(int state) { _connectionState = (ConnectionState)state; - //qDebug() << "netstate" << networkId() << networkName() << state; + // qDebug() << "netstate" << networkId() << networkName() << state; SYNC(ARG(state)) emit connectionStateSet(_connectionState); } - -void Network::setMyNick(const QString &nickname) +void Network::setMyNick(const QString& nickname) { _myNick = nickname; if (!_myNick.isEmpty() && !ircUser(myNick())) { @@ -623,7 +601,6 @@ void Network::setMyNick(const QString &nickname) emit myNickSet(nickname); } - void Network::setLatency(int latency) { if (_latency == latency) @@ -632,7 +609,6 @@ void Network::setLatency(int latency) SYNC(ARG(latency)) } - void Network::setIdentity(IdentityId id) { _identity = id; @@ -641,15 +617,13 @@ void Network::setIdentity(IdentityId id) emit configChanged(); } - -void Network::setServerList(const QVariantList &serverList) +void Network::setServerList(const QVariantList& serverList) { _serverList = fromVariantList(serverList); SYNC(ARG(serverList)) emit configChanged(); } - void Network::setUseRandomServer(bool use) { _useRandomServer = use; @@ -657,15 +631,13 @@ void Network::setUseRandomServer(bool use) emit configChanged(); } - -void Network::setPerform(const QStringList &perform) +void Network::setPerform(const QStringList& perform) { _perform = perform; SYNC(ARG(perform)) emit configChanged(); } - void Network::setUseAutoIdentify(bool use) { _useAutoIdentify = use; @@ -673,23 +645,20 @@ void Network::setUseAutoIdentify(bool use) emit configChanged(); } - -void Network::setAutoIdentifyService(const QString &service) +void Network::setAutoIdentifyService(const QString& service) { _autoIdentifyService = service; SYNC(ARG(service)) emit configChanged(); } - -void Network::setAutoIdentifyPassword(const QString &password) +void Network::setAutoIdentifyPassword(const QString& password) { _autoIdentifyPassword = password; SYNC(ARG(password)) emit configChanged(); } - void Network::setUseSasl(bool use) { _useSasl = use; @@ -697,23 +666,20 @@ void Network::setUseSasl(bool use) emit configChanged(); } - -void Network::setSaslAccount(const QString &account) +void Network::setSaslAccount(const QString& account) { _saslAccount = account; SYNC(ARG(account)) emit configChanged(); } - -void Network::setSaslPassword(const QString &password) +void Network::setSaslPassword(const QString& password) { _saslPassword = password; SYNC(ARG(password)) emit configChanged(); } - void Network::setUseAutoReconnect(bool use) { _useAutoReconnect = use; @@ -721,7 +687,6 @@ void Network::setUseAutoReconnect(bool use) emit configChanged(); } - void Network::setAutoReconnectInterval(quint32 interval) { _autoReconnectInterval = interval; @@ -729,7 +694,6 @@ void Network::setAutoReconnectInterval(quint32 interval) emit configChanged(); } - void Network::setAutoReconnectRetries(quint16 retries) { _autoReconnectRetries = retries; @@ -737,7 +701,6 @@ void Network::setAutoReconnectRetries(quint16 retries) emit configChanged(); } - void Network::setUnlimitedReconnectRetries(bool unlimited) { _unlimitedReconnectRetries = unlimited; @@ -745,7 +708,6 @@ void Network::setUnlimitedReconnectRetries(bool unlimited) emit configChanged(); } - void Network::setRejoinChannels(bool rejoin) { _rejoinChannels = rejoin; @@ -753,7 +715,6 @@ void Network::setRejoinChannels(bool rejoin) emit configChanged(); } - void Network::setUseCustomMessageRate(bool useCustomRate) { if (_useCustomMessageRate != useCustomRate) { @@ -764,14 +725,14 @@ void Network::setUseCustomMessageRate(bool useCustomRate) } } - void Network::setMessageRateBurstSize(quint32 burstSize) { if (burstSize < 1) { // Can't go slower than one message at a time. Also blocks old clients from trying to set // this to 0. qDebug() << "Received invalid setMessageRateBurstSize data - message burst size must be " - "non-zero positive, given" << burstSize; + "non-zero positive, given" + << burstSize; return; } if (_messageRateBurstSize != burstSize) { @@ -782,14 +743,14 @@ void Network::setMessageRateBurstSize(quint32 burstSize) } } - void Network::setMessageRateDelay(quint32 messageDelay) { if (messageDelay == 0) { // Nonsensical to have no delay - just check the Unlimited box instead. Also blocks old // clients from trying to set this to 0. qDebug() << "Received invalid setMessageRateDelay data - message delay must be non-zero " - "positive, given" << messageDelay; + "positive, given" + << messageDelay; return; } if (_messageRateDelay != messageDelay) { @@ -800,7 +761,6 @@ void Network::setMessageRateDelay(quint32 messageDelay) } } - void Network::setUnlimitedMessageRate(bool unlimitedRate) { if (_unlimitedMessageRate != unlimitedRate) { @@ -811,8 +771,7 @@ void Network::setUnlimitedMessageRate(bool unlimitedRate) } } - -void Network::addSupport(const QString ¶m, const QString &value) +void Network::addSupport(const QString& param, const QString& value) { if (!_supports.contains(param)) { _supports[param] = value; @@ -820,8 +779,7 @@ void Network::addSupport(const QString ¶m, const QString &value) } } - -void Network::removeSupport(const QString ¶m) +void Network::removeSupport(const QString& param) { if (_supports.contains(param)) { _supports.remove(param); @@ -829,7 +787,6 @@ void Network::removeSupport(const QString ¶m) } } - QVariantMap Network::initSupports() const { QVariantMap supports; @@ -841,7 +798,7 @@ QVariantMap Network::initSupports() const return supports; } -void Network::addCap(const QString &capability, const QString &value) +void Network::addCap(const QString& capability, const QString& value) { // IRCv3 specs all use lowercase capability names QString _capLowercase = capability.toLower(); @@ -852,7 +809,7 @@ void Network::addCap(const QString &capability, const QString &value) } } -void Network::acknowledgeCap(const QString &capability) +void Network::acknowledgeCap(const QString& capability) { // IRCv3 specs all use lowercase capability names QString _capLowercase = capability.toLower(); @@ -863,7 +820,7 @@ void Network::acknowledgeCap(const QString &capability) } } -void Network::removeCap(const QString &capability) +void Network::removeCap(const QString& capability) { // IRCv3 specs all use lowercase capability names QString _capLowercase = capability.toLower(); @@ -890,7 +847,7 @@ void Network::clearCaps() // If performance issues arise, this can be converted to a more-efficient setup without breaking // protocol (in theory). QString _capLowercase; - foreach (const QString &capability, _caps) { + foreach (const QString& capability, _caps) { _capLowercase = capability.toLower(); emit capRemoved(_capLowercase); } @@ -912,7 +869,6 @@ QVariantMap Network::initCaps() const return caps; } - // There's potentially a lot of users and channels, so it makes sense to optimize the format of this. // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times. @@ -926,8 +882,8 @@ QVariantMap Network::initIrcUsersAndChannels() const if (_ircUsers.count()) { QHash users; - QHash::const_iterator it = _ircUsers.begin(); - QHash::const_iterator end = _ircUsers.end(); + QHash::const_iterator it = _ircUsers.begin(); + QHash::const_iterator end = _ircUsers.end(); while (it != end) { QVariantMap map = it.value()->toVariantMap(); // If the peer doesn't support LongTime, replace the lastAwayMessageTime field @@ -954,17 +910,17 @@ QVariantMap Network::initIrcUsersAndChannels() const // Can't have a container with a value type != QVariant in a QVariant :( // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above. QVariantMap userMap; - foreach(const QString &key, users.keys()) + foreach (const QString& key, users.keys()) userMap[key] = users[key]; usersAndChannels["Users"] = userMap; } if (_ircChannels.count()) { QHash channels; - QHash::const_iterator it = _ircChannels.begin(); - QHash::const_iterator end = _ircChannels.end(); + QHash::const_iterator it = _ircChannels.begin(); + QHash::const_iterator end = _ircChannels.end(); while (it != end) { - const QVariantMap &map = it.value()->toVariantMap(); + const QVariantMap& map = it.value()->toVariantMap(); QVariantMap::const_iterator mapiter = map.begin(); while (mapiter != map.end()) { channels[mapiter.key()] << mapiter.value(); @@ -973,7 +929,7 @@ QVariantMap Network::initIrcUsersAndChannels() const ++it; } QVariantMap channelMap; - foreach(const QString &key, channels.keys()) + foreach (const QString& key, channels.keys()) channelMap[key] = channels[key]; usersAndChannels["Channels"] = channelMap; } @@ -981,24 +937,24 @@ QVariantMap Network::initIrcUsersAndChannels() const return usersAndChannels; } - -void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels) +void Network::initSetIrcUsersAndChannels(const QVariantMap& usersAndChannels) { Q_ASSERT(proxy()); Q_ASSERT(proxy()->sourcePeer()); if (isInitialized()) { - qWarning() << "Network" << networkId() << "received init data for users and channels although there already are known users or channels!"; + qWarning() << "Network" << networkId() + << "received init data for users and channels although there already are known users or channels!"; return; } // toMap() and toList() are cheap, so we can avoid copying to lists... // However, we really have to make sure to never accidentally detach from the shared data! - const QVariantMap &users = usersAndChannels["Users"].toMap(); + const QVariantMap& users = usersAndChannels["Users"].toMap(); // sanity check int count = users["nick"].toList().count(); - foreach(const QString &key, users.keys()) { + foreach (const QString& key, users.keys()) { if (users[key].toList().count() != count) { qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!"; return; @@ -1006,9 +962,9 @@ void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels) } // now create the individual IrcUsers - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { QVariantMap map; - foreach(const QString &key, users.keys()) + foreach (const QString& key, users.keys()) map[key] = users[key].toList().at(i); // If the peer doesn't support LongTime, upconvert the lastAwayMessageTime field @@ -1026,31 +982,30 @@ void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels) map["lastAwayMessageTime"] = lastAwayMessageTime; } - newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick + newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick } // same thing for IrcChannels - const QVariantMap &channels = usersAndChannels["Channels"].toMap(); + const QVariantMap& channels = usersAndChannels["Channels"].toMap(); // sanity check count = channels["name"].toList().count(); - foreach(const QString &key, channels.keys()) { + foreach (const QString& key, channels.keys()) { if (channels[key].toList().count() != count) { qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!"; return; } } // now create the individual IrcChannels - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { QVariantMap map; - foreach(const QString &key, channels.keys()) + foreach (const QString& key, channels.keys()) map[key] = channels[key].toList().at(i); newIrcChannel(map["name"].toString(), map); } } - -void Network::initSetSupports(const QVariantMap &supports) +void Network::initSetSupports(const QVariantMap& supports) { QMapIterator iter(supports); while (iter.hasNext()) { @@ -1059,8 +1014,7 @@ void Network::initSetSupports(const QVariantMap &supports) } } - -void Network::initSetCaps(const QVariantMap &caps) +void Network::initSetCaps(const QVariantMap& caps) { QMapIterator iter(caps); while (iter.hasNext()) { @@ -1069,11 +1023,10 @@ void Network::initSetCaps(const QVariantMap &caps) } } - -IrcUser *Network::updateNickFromMask(const QString &mask) +IrcUser* Network::updateNickFromMask(const QString& mask) { QString nick(nickFromMask(mask).toLower()); - IrcUser *ircuser; + IrcUser* ircuser; if (_ircUsers.contains(nick)) { ircuser = _ircUsers[nick]; @@ -1085,27 +1038,25 @@ IrcUser *Network::updateNickFromMask(const QString &mask) return ircuser; } - void Network::ircUserNickChanged(QString newnick) { - QString oldnick = _ircUsers.key(qobject_cast(sender())); + QString oldnick = _ircUsers.key(qobject_cast(sender())); if (oldnick.isNull()) return; - if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick); + if (newnick.toLower() != oldnick) + _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick); if (myNick().toLower() == oldnick) setMyNick(newnick); } - -void Network::emitConnectionError(const QString &errorMsg) +void Network::emitConnectionError(const QString& errorMsg) { emit connectionError(errorMsg); } - // ==================== // Private: // ==================== @@ -1154,13 +1105,11 @@ void Network::determinePrefixes() const } } - /************************************************************************ * NetworkInfo ************************************************************************/ - -bool NetworkInfo::operator==(const NetworkInfo &other) const +bool NetworkInfo::operator==(const NetworkInfo& other) const { return networkName == other.networkName && serverList == other.serverList @@ -1189,14 +1138,12 @@ bool NetworkInfo::operator==(const NetworkInfo &other) const ; } - -bool NetworkInfo::operator!=(const NetworkInfo &other) const +bool NetworkInfo::operator!=(const NetworkInfo& other) const { return !(*this == other); } - -QDataStream &operator<<(QDataStream &out, const NetworkInfo &info) +QDataStream& operator<<(QDataStream& out, const NetworkInfo& info) { QVariantMap i; i["NetworkName"] = info.networkName; @@ -1227,8 +1174,7 @@ QDataStream &operator<<(QDataStream &out, const NetworkInfo &info) return out; } - -QDataStream &operator>>(QDataStream &in, NetworkInfo &info) +QDataStream& operator>>(QDataStream& in, NetworkInfo& info) { QVariantMap i; in >> i; @@ -1259,27 +1205,23 @@ QDataStream &operator>>(QDataStream &in, NetworkInfo &info) return in; } - -QDebug operator<<(QDebug dbg, const NetworkInfo &i) +QDebug operator<<(QDebug dbg, const NetworkInfo& i) { dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity - << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding - << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform - << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword - << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword - << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval - << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries - << " rejoinChannels = " << i.rejoinChannels - << " useCustomMessageRate = " << i.useCustomMessageRate - << " messageRateBurstSize = " << i.messageRateBurstSize - << " messageRateDelay = " << i.messageRateDelay - << " unlimitedMessageRate = " << i.unlimitedMessageRate - << ")"; + << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding + << " codecForDecoding = " << i.codecForDecoding << " serverList = " << i.serverList + << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform << " useAutoIdentify = " << i.useAutoIdentify + << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword + << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword + << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval + << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries + << " rejoinChannels = " << i.rejoinChannels << " useCustomMessageRate = " << i.useCustomMessageRate + << " messageRateBurstSize = " << i.messageRateBurstSize << " messageRateDelay = " << i.messageRateDelay + << " unlimitedMessageRate = " << i.unlimitedMessageRate << ")"; return dbg.space(); } - -QDataStream &operator<<(QDataStream &out, const Network::Server &server) +QDataStream& operator<<(QDataStream& out, const Network::Server& server) { QVariantMap serverMap; serverMap["Host"] = server.host; @@ -1298,8 +1240,7 @@ QDataStream &operator<<(QDataStream &out, const Network::Server &server) return out; } - -QDataStream &operator>>(QDataStream &in, Network::Server &server) +QDataStream& operator>>(QDataStream& in, Network::Server& server) { QVariantMap serverMap; in >> serverMap; @@ -1318,34 +1259,43 @@ QDataStream &operator>>(QDataStream &in, Network::Server &server) return in; } - -bool Network::Server::operator==(const Server &other) const +bool Network::Server::operator==(const Server& other) const { - if (host != other.host) return false; - if (port != other.port) return false; - if (password != other.password) return false; - if (useSsl != other.useSsl) return false; - if (sslVerify != other.sslVerify) return false; - if (sslVersion != other.sslVersion) return false; - if (useProxy != other.useProxy) return false; - if (proxyType != other.proxyType) return false; - if (proxyHost != other.proxyHost) return false; - if (proxyPort != other.proxyPort) return false; - if (proxyUser != other.proxyUser) return false; - if (proxyPass != other.proxyPass) return false; + if (host != other.host) + return false; + if (port != other.port) + return false; + if (password != other.password) + return false; + if (useSsl != other.useSsl) + return false; + if (sslVerify != other.sslVerify) + return false; + if (sslVersion != other.sslVersion) + return false; + if (useProxy != other.useProxy) + return false; + if (proxyType != other.proxyType) + return false; + if (proxyHost != other.proxyHost) + return false; + if (proxyPort != other.proxyPort) + return false; + if (proxyUser != other.proxyUser) + return false; + if (proxyPass != other.proxyPass) + return false; return true; } - -bool Network::Server::operator!=(const Server &other) const +bool Network::Server::operator!=(const Server& other) const { return !(*this == other); } - -QDebug operator<<(QDebug dbg, const Network::Server &server) +QDebug operator<<(QDebug dbg, const Network::Server& server) { - dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << - server.useSsl << ", sslVerify = " << server.sslVerify << ")"; + dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl + << ", sslVerify = " << server.sslVerify << ")"; return dbg.space(); } diff --git a/src/common/network.h b/src/common/network.h index 12754363..8b2633a8 100644 --- a/src/common/network.h +++ b/src/common/network.h @@ -22,24 +22,24 @@ #include "common-export.h" -#include -#include +#include + +#include +#include #include +#include #include -#include -#include #include -#include -#include -#include +#include +#include +#include +#include "ircchannel.h" +#include "ircuser.h" +#include "signalproxy.h" +#include "syncableobject.h" #include "types.h" #include "util.h" -#include "syncableobject.h" - -#include "signalproxy.h" -#include "ircuser.h" -#include "ircchannel.h" // IRCv3 capabilities #include "irccap.h" @@ -65,7 +65,7 @@ class COMMON_EXPORT Network : public SyncableObject Q_PROPERTY(QByteArray codecForDecoding READ codecForDecoding WRITE setCodecForDecoding) Q_PROPERTY(IdentityId identityId READ identity WRITE setIdentity) Q_PROPERTY(bool isConnected READ isConnected WRITE setConnected) - //Q_PROPERTY(Network::ConnectionState connectionState READ connectionState WRITE setConnectionState) + // Q_PROPERTY(Network::ConnectionState connectionState READ connectionState WRITE setConnectionState) Q_PROPERTY(int connectionState READ connectionState WRITE setConnectionState) Q_PROPERTY(bool useRandomServer READ useRandomServer WRITE setUseRandomServer) Q_PROPERTY(QStringList perform READ perform WRITE setPerform) @@ -86,8 +86,9 @@ class COMMON_EXPORT Network : public SyncableObject Q_PROPERTY(quint32 msgRateMessageDelay READ messageRateDelay WRITE setMessageRateDelay) Q_PROPERTY(bool unlimitedMessageRate READ unlimitedMessageRate WRITE setUnlimitedMessageRate) -public : - enum ConnectionState { +public: + enum ConnectionState + { Disconnected, Connecting, Initializing, @@ -99,7 +100,8 @@ public : // see: // http://www.irc.org/tech_docs/005.html // http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt - enum ChannelModeType { + enum ChannelModeType + { NOT_A_CHANMODE = 0x00, A_CHANMODE = 0x01, B_CHANMODE = 0x02, @@ -110,17 +112,19 @@ public : // Default port assignments according to what many IRC networks have settled on. // Technically not a standard, but it's fairly widespread. // See https://freenode.net/news/port-6697-irc-via-tlsssl - enum PortDefaults { - PORT_PLAINTEXT = 6667, /// Default port for unencrypted connections - PORT_SSL = 6697 /// Default port for encrypted connections + enum PortDefaults + { + PORT_PLAINTEXT = 6667, /// Default port for unencrypted connections + PORT_SSL = 6697 /// Default port for encrypted connections }; - struct Server { + struct Server + { QString host; uint port{6667}; QString password; bool useSsl{false}; - bool sslVerify{true}; /// If true, validate SSL certificates + bool sslVerify{true}; /// If true, validate SSL certificates int sslVersion{0}; bool useProxy{false}; @@ -132,31 +136,38 @@ public : // sslVerify only applies when useSsl is true. sslVerify should be enabled by default, // so enabling useSsl offers a more secure default. - Server() : proxyHost("localhost") {} - - Server(QString host, uint port, QString password, bool useSsl, - bool sslVerify) - : host(std::move(host)), port(port), password(std::move(password)), useSsl(useSsl), sslVerify(sslVerify), - proxyType(QNetworkProxy::Socks5Proxy), - proxyHost("localhost"), proxyPort(8080) {} - - bool operator==(const Server &other) const; - bool operator!=(const Server &other) const; + Server() + : proxyHost("localhost") + {} + + Server(QString host, uint port, QString password, bool useSsl, bool sslVerify) + : host(std::move(host)) + , port(port) + , password(std::move(password)) + , useSsl(useSsl) + , sslVerify(sslVerify) + , proxyType(QNetworkProxy::Socks5Proxy) + , proxyHost("localhost") + , proxyPort(8080) + {} + + bool operator==(const Server& other) const; + bool operator!=(const Server& other) const; }; using ServerList = QList; - Network(const NetworkId &networkid, QObject *parent = nullptr); + Network(const NetworkId& networkid, QObject* parent = nullptr); ~Network() override; inline NetworkId networkId() const { return _networkId; } - inline SignalProxy *proxy() const { return _proxy; } - inline void setProxy(SignalProxy *proxy) { _proxy = proxy; } + inline SignalProxy* proxy() const { return _proxy; } + inline void setProxy(SignalProxy* proxy) { _proxy = proxy; } - inline bool isMyNick(const QString &nick) const { return (myNick().toLower() == nick.toLower()); } - inline bool isMe(IrcUser *ircuser) const { return (ircuser->nick().toLower() == myNick().toLower()); } + inline bool isMyNick(const QString& nick) const { return (myNick().toLower() == nick.toLower()); } + inline bool isMe(IrcUser* ircuser) const { return (ircuser->nick().toLower() == myNick().toLower()); } - bool isChannelName(const QString &channelname) const; + bool isChannelName(const QString& channelname) const; /** * Checks if the target counts as a STATUSMSG @@ -168,10 +179,10 @@ public : * @param[in] target Name of destination, e.g. a channel or query * @returns True if a STATUSMSG, otherwise false */ - bool isStatusMsg(const QString &target) const; + bool isStatusMsg(const QString& target) const; inline bool isConnected() const { return _connected; } - //Network::ConnectionState connectionState() const; + // Network::ConnectionState connectionState() const; inline int connectionState() const { return _connectionState; } /**@{*/ @@ -179,9 +190,10 @@ public : * Translates a user’s prefix to the channelmode associated with it. * @param prefix Prefix to be translated. */ - QString prefixToMode(const QString &prefix) const; - inline QString prefixToMode(const QCharRef &prefix) const { return prefixToMode(QString(prefix)); } - inline QString prefixesToModes(const QString &prefix) const { + QString prefixToMode(const QString& prefix) const; + inline QString prefixToMode(const QCharRef& prefix) const { return prefixToMode(QString(prefix)); } + inline QString prefixesToModes(const QString& prefix) const + { QString modes; for (QChar c : prefix) { modes += prefixToMode(c); @@ -195,9 +207,10 @@ public : * Translates a user’s prefix to the channelmode associated with it. * @param prefix Prefix to be translated. */ - QString modeToPrefix(const QString &mode) const; - inline QString modeToPrefix(const QCharRef &mode) const { return modeToPrefix(QString(mode)); } - inline QString modesToPrefixes(const QString &mode) const { + QString modeToPrefix(const QString& mode) const; + inline QString modeToPrefix(const QCharRef& mode) const { return modeToPrefix(QString(mode)); } + inline QString modesToPrefixes(const QString& mode) const + { QString prefixes; for (QChar c : mode) { prefixes += modeToPrefix(c); @@ -217,7 +230,7 @@ public : * @param modes User channelmodes * @return Priority-sorted user channelmodes */ - QString sortPrefixModes(const QString &modes) const; + QString sortPrefixModes(const QString& modes) const; /**@{*/ /** @@ -230,7 +243,8 @@ public : * @param modesList List of users' channel modes * @return Priority-sorted list of users' channel modes */ - inline QStringList sortPrefixModes(const QStringList &modesList) const { + inline QStringList sortPrefixModes(const QStringList& modesList) const + { QStringList sortedModesList; // Sort each individual mode string, appending back // Must maintain the order received! @@ -241,14 +255,14 @@ public : } /**@}*/ - ChannelModeType channelModeType(const QString &mode); - inline ChannelModeType channelModeType(const QCharRef &mode) { return channelModeType(QString(mode)); } + ChannelModeType channelModeType(const QString& mode); + inline ChannelModeType channelModeType(const QCharRef& mode) { return channelModeType(QString(mode)); } - inline const QString &networkName() const { return _networkName; } - inline const QString ¤tServer() const { return _currentServer; } - inline const QString &myNick() const { return _myNick; } + inline const QString& networkName() const { return _networkName; } + inline const QString& currentServer() const { return _currentServer; } + inline const QString& myNick() const { return _myNick; } inline int latency() const { return _latency; } - inline IrcUser *me() const { return ircUser(myNick()); } + inline IrcUser* me() const { return ircUser(myNick()); } inline IdentityId identity() const { return _identity; } QStringList nicks() const; inline QStringList channels() const { return _ircChannels.keys(); } @@ -264,15 +278,15 @@ public : * @returns QStringList of enabled (acknowledged) capabilities */ inline const QStringList capsEnabled() const { return _capsEnabled; } - inline const ServerList &serverList() const { return _serverList; } + inline const ServerList& serverList() const { return _serverList; } inline bool useRandomServer() const { return _useRandomServer; } - inline const QStringList &perform() const { return _perform; } + inline const QStringList& perform() const { return _perform; } inline bool useAutoIdentify() const { return _useAutoIdentify; } - inline const QString &autoIdentifyService() const { return _autoIdentifyService; } - inline const QString &autoIdentifyPassword() const { return _autoIdentifyPassword; } + inline const QString& autoIdentifyService() const { return _autoIdentifyService; } + inline const QString& autoIdentifyPassword() const { return _autoIdentifyPassword; } inline bool useSasl() const { return _useSasl; } - inline const QString &saslAccount() const { return _saslAccount; } - inline const QString &saslPassword() const { return _saslPassword; } + inline const QString& saslAccount() const { return _saslAccount; } + inline const QString& saslPassword() const { return _saslPassword; } inline bool useAutoReconnect() const { return _useAutoReconnect; } inline quint32 autoReconnectInterval() const { return _autoReconnectInterval; } inline quint16 autoReconnectRetries() const { return _autoReconnectRetries; } @@ -318,14 +332,14 @@ public : inline bool unlimitedMessageRate() const { return _unlimitedMessageRate; } NetworkInfo networkInfo() const; - void setNetworkInfo(const NetworkInfo &); + void setNetworkInfo(const NetworkInfo&); QString prefixes() const; QString prefixModes() const; void determinePrefixes() const; - bool supports(const QString ¶m) const { return _supports.contains(param); } - QString support(const QString ¶m) const; + bool supports(const QString& param) const { return _supports.contains(param); } + QString support(const QString& param) const; /** * Checks if a given capability is advertised by the server. @@ -337,7 +351,7 @@ public : * @param[in] capability Name of capability * @returns True if connected and advertised by the server, otherwise false */ - inline bool capAvailable(const QString &capability) const { return _caps.contains(capability.toLower()); } + inline bool capAvailable(const QString& capability) const { return _caps.contains(capability.toLower()); } // IRCv3 specs all use lowercase capability names /** @@ -346,7 +360,7 @@ public : * @param[in] capability Name of capability * @returns True if acknowledged (active), otherwise false */ - inline bool capEnabled(const QString &capability) const { return _capsEnabled.contains(capability.toLower()); } + inline bool capEnabled(const QString& capability) const { return _capsEnabled.contains(capability.toLower()); } // IRCv3 specs all use lowercase capability names /** @@ -355,7 +369,7 @@ public : * @param[in] capability Name of capability * @returns Value of capability if one was specified, otherwise empty string */ - QString capValue(const QString &capability) const { return _caps.value(capability.toLower()); } + QString capValue(const QString& capability) const { return _caps.value(capability.toLower()); } // IRCv3 specs all use lowercase capability names // QHash returns the default constructed value if not found, in this case, empty string // See: https://doc.qt.io/qt-4.8/qhash.html#value @@ -369,62 +383,62 @@ public : * @param[in] saslMechanism Desired SASL mechanism * @return True if mechanism supported or unknown, otherwise false */ - bool saslMaybeSupports(const QString &saslMechanism) const; + bool saslMaybeSupports(const QString& saslMechanism) const; - IrcUser *newIrcUser(const QString &hostmask, const QVariantMap &initData = QVariantMap()); - inline IrcUser *newIrcUser(const QByteArray &hostmask) { return newIrcUser(decodeServerString(hostmask)); } - IrcUser *ircUser(QString nickname) const; - inline IrcUser *ircUser(const QByteArray &nickname) const { return ircUser(decodeServerString(nickname)); } - inline QList ircUsers() const { return _ircUsers.values(); } + IrcUser* newIrcUser(const QString& hostmask, const QVariantMap& initData = QVariantMap()); + inline IrcUser* newIrcUser(const QByteArray& hostmask) { return newIrcUser(decodeServerString(hostmask)); } + IrcUser* ircUser(QString nickname) const; + inline IrcUser* ircUser(const QByteArray& nickname) const { return ircUser(decodeServerString(nickname)); } + inline QList ircUsers() const { return _ircUsers.values(); } inline quint32 ircUserCount() const { return _ircUsers.count(); } - IrcChannel *newIrcChannel(const QString &channelname, const QVariantMap &initData = QVariantMap()); - inline IrcChannel *newIrcChannel(const QByteArray &channelname) { return newIrcChannel(decodeServerString(channelname)); } - IrcChannel *ircChannel(QString channelname) const; - inline IrcChannel *ircChannel(const QByteArray &channelname) const { return ircChannel(decodeServerString(channelname)); } - inline QList ircChannels() const { return _ircChannels.values(); } + IrcChannel* newIrcChannel(const QString& channelname, const QVariantMap& initData = QVariantMap()); + inline IrcChannel* newIrcChannel(const QByteArray& channelname) { return newIrcChannel(decodeServerString(channelname)); } + IrcChannel* ircChannel(QString channelname) const; + inline IrcChannel* ircChannel(const QByteArray& channelname) const { return ircChannel(decodeServerString(channelname)); } + inline QList ircChannels() const { return _ircChannels.values(); } inline quint32 ircChannelCount() const { return _ircChannels.count(); } QByteArray codecForServer() const; QByteArray codecForEncoding() const; QByteArray codecForDecoding() const; - void setCodecForServer(QTextCodec *codec); - void setCodecForEncoding(QTextCodec *codec); - void setCodecForDecoding(QTextCodec *codec); + void setCodecForServer(QTextCodec* codec); + void setCodecForEncoding(QTextCodec* codec); + void setCodecForDecoding(QTextCodec* codec); - QString decodeString(const QByteArray &text) const; - QByteArray encodeString(const QString &string) const; - QString decodeServerString(const QByteArray &text) const; - QByteArray encodeServerString(const QString &string) const; + QString decodeString(const QByteArray& text) const; + QByteArray encodeString(const QString& string) const; + QString decodeServerString(const QByteArray& text) const; + QByteArray encodeServerString(const QString& string) const; static QByteArray defaultCodecForServer(); static QByteArray defaultCodecForEncoding(); static QByteArray defaultCodecForDecoding(); - static void setDefaultCodecForServer(const QByteArray &name); - static void setDefaultCodecForEncoding(const QByteArray &name); - static void setDefaultCodecForDecoding(const QByteArray &name); + static void setDefaultCodecForServer(const QByteArray& name); + static void setDefaultCodecForEncoding(const QByteArray& name); + static void setDefaultCodecForDecoding(const QByteArray& name); inline bool autoAwayActive() const { return _autoAwayActive; } inline void setAutoAwayActive(bool active) { _autoAwayActive = active; } public slots: - void setNetworkName(const QString &networkName); - void setCurrentServer(const QString ¤tServer); + void setNetworkName(const QString& networkName); + void setCurrentServer(const QString& currentServer); void setConnected(bool isConnected); void setConnectionState(int state); - virtual void setMyNick(const QString &mynick); + virtual void setMyNick(const QString& mynick); void setLatency(int latency); void setIdentity(IdentityId); - void setServerList(const QVariantList &serverList); + void setServerList(const QVariantList& serverList); void setUseRandomServer(bool); - void setPerform(const QStringList &); + void setPerform(const QStringList&); void setUseAutoIdentify(bool); - void setAutoIdentifyService(const QString &); - void setAutoIdentifyPassword(const QString &); + void setAutoIdentifyService(const QString&); + void setAutoIdentifyPassword(const QString&); void setUseSasl(bool); - void setSaslAccount(const QString &); - void setSaslPassword(const QString &); + void setSaslAccount(const QString&); + void setSaslPassword(const QString&); virtual void setUseAutoReconnect(bool); virtual void setAutoReconnectInterval(quint32); virtual void setAutoReconnectRetries(quint16); @@ -473,12 +487,12 @@ public slots: */ void setUnlimitedMessageRate(bool unlimitedRate); - void setCodecForServer(const QByteArray &codecName); - void setCodecForEncoding(const QByteArray &codecName); - void setCodecForDecoding(const QByteArray &codecName); + void setCodecForServer(const QByteArray& codecName); + void setCodecForEncoding(const QByteArray& codecName); + void setCodecForDecoding(const QByteArray& codecName); - void addSupport(const QString ¶m, const QString &value = QString()); - void removeSupport(const QString ¶m); + void addSupport(const QString& param, const QString& value = QString()); + void removeSupport(const QString& param); // IRCv3 capability negotiation (can be connected to signals) @@ -494,14 +508,14 @@ public slots: * Optional value of the capability, e.g. sasl=plain. * @endparblock */ - void addCap(const QString &capability, const QString &value = QString()); + void addCap(const QString& capability, const QString& value = QString()); /** * Marks a capability as acknowledged (enabled by the IRC server). * * @param[in] capability Name of the capability */ - void acknowledgeCap(const QString &capability); + void acknowledgeCap(const QString& capability); /** * Removes a capability from the list of available capabilities. @@ -512,7 +526,7 @@ public slots: * * @param[in] capability Name of the capability */ - void removeCap(const QString &capability); + void removeCap(const QString& capability); /** * Clears all capabilities from the list of available capabilities. @@ -521,10 +535,10 @@ public slots: */ void clearCaps(); - inline void addIrcUser(const QString &hostmask) { newIrcUser(hostmask); } - inline void addIrcChannel(const QString &channel) { newIrcChannel(channel); } + inline void addIrcUser(const QString& hostmask) { newIrcUser(hostmask); } + inline void addIrcChannel(const QString& channel) { newIrcChannel(channel); } - //init geters + // init geters QVariantMap initSupports() const; /** * Get the initial list of available capabilities. @@ -541,22 +555,22 @@ public slots: inline QVariantList initServerList() const { return toVariantList(serverList()); } virtual QVariantMap initIrcUsersAndChannels() const; - //init seters - void initSetSupports(const QVariantMap &supports); + // init seters + void initSetSupports(const QVariantMap& supports); /** * Initialize the list of available capabilities. * * @param[in] caps QVariantMap of indicating available capabilities and values */ - void initSetCaps(const QVariantMap &caps); + void initSetCaps(const QVariantMap& caps); /** * Initialize the list of enabled (acknowledged) capabilities. * * @param[in] caps QVariantList of QString indicating enabled (acknowledged) capabilities and values */ - inline void initSetCapsEnabled(const QVariantList &capsEnabled) { _capsEnabled = fromVariantList(capsEnabled); } - inline void initSetServerList(const QVariantList &serverList) { _serverList = fromVariantList(serverList); } - virtual void initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels); + inline void initSetCapsEnabled(const QVariantList& capsEnabled) { _capsEnabled = fromVariantList(capsEnabled); } + inline void initSetServerList(const QVariantList& serverList) { _serverList = fromVariantList(serverList); } + virtual void initSetIrcUsersAndChannels(const QVariantMap& usersAndChannels); /** * Update IrcUser hostmask and username from mask, creating an IrcUser if one does not exist. @@ -564,7 +578,7 @@ public slots: * @param[in] mask Full nick!user@hostmask string * @return IrcUser of the matching nick if exists, otherwise a new IrcUser */ - IrcUser *updateNickFromMask(const QString &mask); + IrcUser* updateNickFromMask(const QString& mask); // these slots are to keep the hashlists of all users and the // channel lists up to date @@ -572,40 +586,40 @@ public slots: virtual inline void requestConnect() const { REQUEST(NO_ARG) } virtual inline void requestDisconnect() const { REQUEST(NO_ARG) } - virtual inline void requestSetNetworkInfo(const NetworkInfo &info) { REQUEST(ARG(info)) } + virtual inline void requestSetNetworkInfo(const NetworkInfo& info) { REQUEST(ARG(info)) } - void emitConnectionError(const QString &); + void emitConnectionError(const QString&); protected slots: - virtual void removeIrcUser(IrcUser *ircuser); - virtual void removeIrcChannel(IrcChannel *ircChannel); + virtual void removeIrcUser(IrcUser* ircuser); + virtual void removeIrcChannel(IrcChannel* ircChannel); virtual void removeChansAndUsers(); signals: void aboutToBeDestroyed(); - void networkNameSet(const QString &networkName); - void currentServerSet(const QString ¤tServer); + void networkNameSet(const QString& networkName); + void currentServerSet(const QString& currentServer); void connectedSet(bool isConnected); void connectionStateSet(Network::ConnectionState); -// void connectionStateSet(int); - void connectionError(const QString &errorMsg); - void myNickSet(const QString &mynick); -// void latencySet(int latency); + // void connectionStateSet(int); + void connectionError(const QString& errorMsg); + void myNickSet(const QString& mynick); + // void latencySet(int latency); void identitySet(IdentityId); void configChanged(); // void serverListSet(QVariantList serverList); -// void useRandomServerSet(bool); -// void performSet(const QStringList &); -// void useAutoIdentifySet(bool); -// void autoIdentifyServiceSet(const QString &); -// void autoIdentifyPasswordSet(const QString &); -// void useAutoReconnectSet(bool); -// void autoReconnectIntervalSet(quint32); -// void autoReconnectRetriesSet(quint16); -// void unlimitedReconnectRetriesSet(bool); -// void rejoinChannelsSet(bool); + // void useRandomServerSet(bool); + // void performSet(const QStringList &); + // void useAutoIdentifySet(bool); + // void autoIdentifyServiceSet(const QString &); + // void autoIdentifyPasswordSet(const QString &); + // void useAutoReconnectSet(bool); + // void autoReconnectIntervalSet(quint32); + // void autoReconnectRetriesSet(quint16); + // void unlimitedReconnectRetriesSet(bool); + // void rejoinChannelsSet(bool); // Custom rate limiting (can drive other slots) @@ -645,12 +659,12 @@ signals: */ void unlimitedMessageRateSet(const bool unlimitedRate); -// void codecForServerSet(const QByteArray &codecName); -// void codecForEncodingSet(const QByteArray &codecName); -// void codecForDecodingSet(const QByteArray &codecName); + // void codecForServerSet(const QByteArray &codecName); + // void codecForEncodingSet(const QByteArray &codecName); + // void codecForDecodingSet(const QByteArray &codecName); -// void supportAdded(const QString ¶m, const QString &value); -// void supportRemoved(const QString ¶m); + // void supportAdded(const QString ¶m, const QString &value); + // void supportRemoved(const QString ¶m); // IRCv3 capability negotiation (can drive other slots) /** @@ -660,7 +674,7 @@ signals: * * @param[in] capability Name of the capability */ - void capAdded (const QString &capability); + void capAdded(const QString& capability); /** * Indicates a capability was acknowledged (enabled by the IRC server). @@ -669,7 +683,7 @@ signals: * * @param[in] capability Name of the capability */ - void capAcknowledged(const QString &capability); + void capAcknowledged(const QString& capability); /** * Indicates a capability was removed from the list of available capabilities. @@ -678,20 +692,20 @@ signals: * * @param[in] capability Name of the capability */ - void capRemoved(const QString &capability); + void capRemoved(const QString& capability); -// void ircUserAdded(const QString &hostmask); - void ircUserAdded(IrcUser *); -// void ircChannelAdded(const QString &channelname); - void ircChannelAdded(IrcChannel *); + // void ircUserAdded(const QString &hostmask); + void ircUserAdded(IrcUser*); + // void ircChannelAdded(const QString &channelname); + void ircChannelAdded(IrcChannel*); -// void connectRequested() const; -// void disconnectRequested() const; -// void setNetworkInfoRequested(const NetworkInfo &) const; + // void connectRequested() const; + // void disconnectRequested() const; + // void setNetworkInfoRequested(const NetworkInfo &) const; protected: - inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new IrcChannel(channelname, this); } - inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new IrcUser(hostmask, this); } + inline virtual IrcChannel* ircChannelFactory(const QString& channelname) { return new IrcChannel(channelname, this); } + inline virtual IrcUser* ircUserFactory(const QString& hostmask) { return new IrcUser(hostmask, this); } private: QPointer _proxy; @@ -709,15 +723,15 @@ private: mutable QString _prefixes; mutable QString _prefixModes; - QHash _ircUsers; // stores all known nicks for the server - QHash _ircChannels; // stores all known channels - QHash _supports; // stores results from RPL_ISUPPORT + QHash _ircUsers; // stores all known nicks for the server + QHash _ircChannels; // stores all known channels + QHash _supports; // stores results from RPL_ISUPPORT QHash _caps; /// Capabilities supported by the IRC server // By synchronizing the supported capabilities, the client could suggest certain behaviors, e.g. // in the Network settings dialog, recommending SASL instead of using NickServ, or warning if // SASL EXTERNAL isn't available. - QStringList _capsEnabled; /// Enabled capabilities that received 'CAP ACK' + QStringList _capsEnabled; /// Enabled capabilities that received 'CAP ACK' // _capsEnabled uses the same values from the = pairs stored in _caps ServerList _serverList; @@ -739,26 +753,25 @@ private: bool _rejoinChannels; // Custom rate limiting - bool _useCustomMessageRate; /// If true, use custom rate limits, otherwise use defaults - quint32 _messageRateBurstSize; /// Maximum number of messages to send without any delays - quint32 _messageRateDelay; /// Delay in ms. for messages when max. burst messages sent - bool _unlimitedMessageRate; /// If true, disable rate limiting, otherwise apply limits + bool _useCustomMessageRate; /// If true, use custom rate limits, otherwise use defaults + quint32 _messageRateBurstSize; /// Maximum number of messages to send without any delays + quint32 _messageRateDelay; /// Delay in ms. for messages when max. burst messages sent + bool _unlimitedMessageRate; /// If true, disable rate limiting, otherwise apply limits - QTextCodec *_codecForServer; - QTextCodec *_codecForEncoding; - QTextCodec *_codecForDecoding; + QTextCodec* _codecForServer; + QTextCodec* _codecForEncoding; + QTextCodec* _codecForDecoding; - static QTextCodec *_defaultCodecForServer; - static QTextCodec *_defaultCodecForEncoding; - static QTextCodec *_defaultCodecForDecoding; + static QTextCodec* _defaultCodecForServer; + static QTextCodec* _defaultCodecForEncoding; + static QTextCodec* _defaultCodecForDecoding; - bool _autoAwayActive; // when this is active handle305 and handle306 don't trigger any output + bool _autoAwayActive; // when this is active handle305 and handle306 don't trigger any output friend class IrcUser; friend class IrcChannel; }; - //! Stores all editable information about a network (as opposed to runtime state). struct COMMON_EXPORT NetworkInfo { @@ -777,35 +790,35 @@ struct COMMON_EXPORT NetworkInfo QByteArray codecForEncoding; QByteArray codecForDecoding; - NetworkId networkId {0}; - IdentityId identity {1}; + NetworkId networkId{0}; + IdentityId identity{1}; - quint32 messageRateBurstSize {5}; ///< Maximum number of messages to send without any delays - quint32 messageRateDelay {2200}; ///< Delay in ms. for messages when max. burst messages sent + quint32 messageRateBurstSize{5}; ///< Maximum number of messages to send without any delays + quint32 messageRateDelay{2200}; ///< Delay in ms. for messages when max. burst messages sent - quint32 autoReconnectInterval {60}; - quint16 autoReconnectRetries {20}; + quint32 autoReconnectInterval{60}; + quint16 autoReconnectRetries{20}; - bool rejoinChannels {true}; - bool useRandomServer {false}; - bool useAutoIdentify {false}; - bool useSasl {false}; - bool useAutoReconnect {true}; - bool unlimitedReconnectRetries {false}; - bool useCustomMessageRate {false}; ///< If true, use custom rate limits, otherwise use defaults - bool unlimitedMessageRate {false}; ///< If true, disable rate limiting, otherwise apply limits + bool rejoinChannels{true}; + bool useRandomServer{false}; + bool useAutoIdentify{false}; + bool useSasl{false}; + bool useAutoReconnect{true}; + bool unlimitedReconnectRetries{false}; + bool useCustomMessageRate{false}; ///< If true, use custom rate limits, otherwise use defaults + bool unlimitedMessageRate{false}; ///< If true, disable rate limiting, otherwise apply limits public: - bool operator==(const NetworkInfo &other) const; - bool operator!=(const NetworkInfo &other) const; + bool operator==(const NetworkInfo& other) const; + bool operator!=(const NetworkInfo& other) const; }; -COMMON_EXPORT QDataStream &operator<<(QDataStream &out, const NetworkInfo &info); -COMMON_EXPORT QDataStream &operator>>(QDataStream &in, NetworkInfo &info); -COMMON_EXPORT QDebug operator<<(QDebug dbg, const NetworkInfo &i); +COMMON_EXPORT QDataStream& operator<<(QDataStream& out, const NetworkInfo& info); +COMMON_EXPORT QDataStream& operator>>(QDataStream& in, NetworkInfo& info); +COMMON_EXPORT QDebug operator<<(QDebug dbg, const NetworkInfo& i); Q_DECLARE_METATYPE(NetworkInfo) -COMMON_EXPORT QDataStream &operator<<(QDataStream &out, const Network::Server &server); -COMMON_EXPORT QDataStream &operator>>(QDataStream &in, Network::Server &server); -COMMON_EXPORT QDebug operator<<(QDebug dbg, const Network::Server &server); +COMMON_EXPORT QDataStream& operator<<(QDataStream& out, const Network::Server& server); +COMMON_EXPORT QDataStream& operator>>(QDataStream& in, Network::Server& server); +COMMON_EXPORT QDebug operator<<(QDebug dbg, const Network::Server& server); Q_DECLARE_METATYPE(Network::Server) diff --git a/src/common/networkconfig.cpp b/src/common/networkconfig.cpp index 1c0eb379..eb789664 100644 --- a/src/common/networkconfig.cpp +++ b/src/common/networkconfig.cpp @@ -20,11 +20,9 @@ #include "networkconfig.h" -NetworkConfig::NetworkConfig(const QString &objectName, QObject *parent) +NetworkConfig::NetworkConfig(const QString& objectName, QObject* parent) : SyncableObject(objectName, parent) -{ -} - +{} void NetworkConfig::setPingTimeoutEnabled(bool enabled) { @@ -36,7 +34,6 @@ void NetworkConfig::setPingTimeoutEnabled(bool enabled) emit pingTimeoutEnabledSet(enabled); } - void NetworkConfig::setPingInterval(int interval) { if (_pingInterval == interval) @@ -47,7 +44,6 @@ void NetworkConfig::setPingInterval(int interval) emit pingIntervalSet(interval); } - void NetworkConfig::setMaxPingCount(int count) { if (_maxPingCount == count) @@ -57,7 +53,6 @@ void NetworkConfig::setMaxPingCount(int count) SYNC(ARG(count)) } - void NetworkConfig::setAutoWhoEnabled(bool enabled) { if (_autoWhoEnabled == enabled) @@ -68,7 +63,6 @@ void NetworkConfig::setAutoWhoEnabled(bool enabled) emit autoWhoEnabledSet(enabled); } - void NetworkConfig::setAutoWhoInterval(int interval) { if (_autoWhoInterval == interval) @@ -79,7 +73,6 @@ void NetworkConfig::setAutoWhoInterval(int interval) emit autoWhoIntervalSet(interval); } - void NetworkConfig::setAutoWhoNickLimit(int nickLimit) { if (_autoWhoNickLimit == nickLimit) @@ -89,7 +82,6 @@ void NetworkConfig::setAutoWhoNickLimit(int nickLimit) SYNC(ARG(nickLimit)) } - void NetworkConfig::setAutoWhoDelay(int delay) { if (_autoWhoDelay == delay) @@ -100,7 +92,6 @@ void NetworkConfig::setAutoWhoDelay(int delay) emit autoWhoDelaySet(delay); } - void NetworkConfig::setStandardCtcp(bool enabled) { if (_standardCtcp == enabled) diff --git a/src/common/networkconfig.h b/src/common/networkconfig.h index d1d10b96..72b3d5f0 100644 --- a/src/common/networkconfig.h +++ b/src/common/networkconfig.h @@ -38,8 +38,8 @@ class COMMON_EXPORT NetworkConfig : public SyncableObject Q_PROPERTY(int autoWhoDelay READ autoWhoDelay WRITE setAutoWhoDelay) Q_PROPERTY(bool standardCtcp READ standardCtcp WRITE setStandardCtcp) -public : - NetworkConfig(const QString &objectName = "GlobalNetworkConfig", QObject *parent = nullptr); +public: + NetworkConfig(const QString& objectName = "GlobalNetworkConfig", QObject* parent = nullptr); public slots: inline bool pingTimeoutEnabled() const { return _pingTimeoutEnabled; } @@ -72,25 +72,24 @@ public slots: inline bool standardCtcp() const { return _standardCtcp; } void setStandardCtcp(bool); - virtual inline void requestSetStandardCtcp(bool b) { REQUEST(ARG(b)) } + virtual inline void requestSetStandardCtcp(bool b){REQUEST(ARG(b))} -signals: - void pingTimeoutEnabledSet(bool); + signals : void pingTimeoutEnabledSet(bool); void pingIntervalSet(int); -// void maxPingCountSet(int); + // void maxPingCountSet(int); void autoWhoEnabledSet(bool); void autoWhoIntervalSet(int); -// void autoWhoNickLimitSet(int); + // void autoWhoNickLimitSet(int); void autoWhoDelaySet(int); void standardCtcpSet(bool); -// void setPingTimeoutEnabledRequested(bool); -// void setPingIntervalRequested(int); -// void setMaxPingCountRequested(int); -// void setAutoWhoEnabledRequested(bool); -// void setAutoWhoIntervalRequested(int); -// void setAutoWhoNickLimitRequested(int); -// void setAutoWhoDelayRequested(int); + // void setPingTimeoutEnabledRequested(bool); + // void setPingIntervalRequested(int); + // void setMaxPingCountRequested(int); + // void setAutoWhoEnabledRequested(bool); + // void setAutoWhoIntervalRequested(int); + // void setAutoWhoNickLimitRequested(int); + // void setAutoWhoDelayRequested(int); private: bool _pingTimeoutEnabled{true}; diff --git a/src/common/networkevent.cpp b/src/common/networkevent.cpp index eb8d76be..a0b5b4ff 100644 --- a/src/common/networkevent.cpp +++ b/src/common/networkevent.cpp @@ -20,7 +20,7 @@ #include "networkevent.h" -Event *NetworkEvent::create(EventManager::EventType type, QVariantMap &map, Network *network) +Event* NetworkEvent::create(EventManager::EventType type, QVariantMap& map, Network* network) { switch (type) { case EventManager::NetworkIncoming: @@ -43,50 +43,42 @@ Event *NetworkEvent::create(EventManager::EventType type, QVariantMap &map, Netw } } - -NetworkEvent::NetworkEvent(EventManager::EventType type, QVariantMap &map, Network *network) +NetworkEvent::NetworkEvent(EventManager::EventType type, QVariantMap& map, Network* network) : Event(type, map) , _network(network) -{ -} +{} - -void NetworkEvent::toVariantMap(QVariantMap &map) const +void NetworkEvent::toVariantMap(QVariantMap& map) const { Event::toVariantMap(map); map["network"] = networkId().toInt(); } - -NetworkDataEvent::NetworkDataEvent(EventManager::EventType type, QVariantMap &map, Network *network) +NetworkDataEvent::NetworkDataEvent(EventManager::EventType type, QVariantMap& map, Network* network) : NetworkEvent(type, map, network) { _data = map.take("data").toByteArray(); } - -void NetworkDataEvent::toVariantMap(QVariantMap &map) const +void NetworkDataEvent::toVariantMap(QVariantMap& map) const { NetworkEvent::toVariantMap(map); map["data"] = data(); } - -NetworkConnectionEvent::NetworkConnectionEvent(EventManager::EventType type, QVariantMap &map, Network *network) +NetworkConnectionEvent::NetworkConnectionEvent(EventManager::EventType type, QVariantMap& map, Network* network) : NetworkEvent(type, map, network) { - _state = static_cast(map.take("state").toInt()); // FIXME: check enum plausibility + _state = static_cast(map.take("state").toInt()); // FIXME: check enum plausibility } - -void NetworkConnectionEvent::toVariantMap(QVariantMap &map) const +void NetworkConnectionEvent::toVariantMap(QVariantMap& map) const { NetworkEvent::toVariantMap(map); map["state"] = connectionState(); } - -NetworkSplitEvent::NetworkSplitEvent(EventManager::EventType type, QVariantMap &map, Network *network) +NetworkSplitEvent::NetworkSplitEvent(EventManager::EventType type, QVariantMap& map, Network* network) : NetworkEvent(type, map, network) { _channel = map.take("channel").toString(); @@ -94,8 +86,7 @@ NetworkSplitEvent::NetworkSplitEvent(EventManager::EventType type, QVariantMap & _quitMsg = map.take("quitMessage").toString(); } - -void NetworkSplitEvent::toVariantMap(QVariantMap &map) const +void NetworkSplitEvent::toVariantMap(QVariantMap& map) const { NetworkEvent::toVariantMap(map); map["channel"] = channel(); diff --git a/src/common/networkevent.h b/src/common/networkevent.h index 39d48686..f5283318 100644 --- a/src/common/networkevent.h +++ b/src/common/networkevent.h @@ -20,9 +20,10 @@ #pragma once +#include + #include #include -#include #include "event.h" #include "network.h" @@ -30,102 +31,93 @@ class COMMON_EXPORT NetworkEvent : public Event { public: - explicit NetworkEvent(EventManager::EventType type, Network *network) - : Event(type), - _network(network) + explicit NetworkEvent(EventManager::EventType type, Network* network) + : Event(type) + , _network(network) {} inline NetworkId networkId() const { return network() ? network()->networkId() : NetworkId(); } - inline Network *network() const { return _network; } + inline Network* network() const { return _network; } - static Event *create(EventManager::EventType type, QVariantMap &map, Network *network); + static Event* create(EventManager::EventType type, QVariantMap& map, Network* network); protected: - explicit NetworkEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit NetworkEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "NetworkEvent"; } - inline void debugInfo(QDebug &dbg) const override { dbg.nospace() << ", net = " << qPrintable(_network->networkName()); } + inline void debugInfo(QDebug& dbg) const override { dbg.nospace() << ", net = " << qPrintable(_network->networkName()); } private: - Network *_network; + Network* _network; }; - /*****************************************************************************/ class COMMON_EXPORT NetworkConnectionEvent : public NetworkEvent { public: - explicit NetworkConnectionEvent(EventManager::EventType type, Network *network, Network::ConnectionState state) - : NetworkEvent(type, network), - _state(state) + explicit NetworkConnectionEvent(EventManager::EventType type, Network* network, Network::ConnectionState state) + : NetworkEvent(type, network) + , _state(state) {} inline Network::ConnectionState connectionState() const { return _state; } inline void setConnectionState(Network::ConnectionState state) { _state = state; } protected: - explicit NetworkConnectionEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit NetworkConnectionEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "NetworkConnectionEvent"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); dbg.nospace() << ", state = " << qPrintable(QString::number(_state)); } - private: Network::ConnectionState _state; friend class NetworkEvent; }; - class COMMON_EXPORT NetworkDataEvent : public NetworkEvent { public: - explicit NetworkDataEvent(EventManager::EventType type, Network *network, QByteArray data) - : NetworkEvent(type, network), - _data(std::move(data)) + explicit NetworkDataEvent(EventManager::EventType type, Network* network, QByteArray data) + : NetworkEvent(type, network) + , _data(std::move(data)) {} inline QByteArray data() const { return _data; } - inline void setData(const QByteArray &data) { _data = data; } + inline void setData(const QByteArray& data) { _data = data; } protected: - explicit NetworkDataEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit NetworkDataEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "NetworkDataEvent"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); dbg.nospace() << ", data = " << data(); } - private: QByteArray _data; friend class NetworkEvent; }; - class COMMON_EXPORT NetworkSplitEvent : public NetworkEvent { public: - explicit NetworkSplitEvent(EventManager::EventType type, - Network *network, - QString channel, - QStringList users, - QString quitMsg) - : NetworkEvent(type, network), - _channel(std::move(channel)), - _users(std::move(users)), - _quitMsg(std::move(quitMsg)) + explicit NetworkSplitEvent(EventManager::EventType type, Network* network, QString channel, QStringList users, QString quitMsg) + : NetworkEvent(type, network) + , _channel(std::move(channel)) + , _users(std::move(users)) + , _quitMsg(std::move(quitMsg)) {} inline QString channel() const { return _channel; } @@ -133,19 +125,16 @@ public: inline QString quitMessage() const { return _quitMsg; } protected: - explicit NetworkSplitEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit NetworkSplitEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "NetworkSplitEvent"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); - dbg.nospace() << ", channel = " << qPrintable(channel()) - << ", users = " << users() - << ", quitmsg = " << quitMessage(); + dbg.nospace() << ", channel = " << qPrintable(channel()) << ", users = " << users() << ", quitmsg = " << quitMessage(); } - private: QString _channel; QStringList _users; diff --git a/src/common/nickhighlightmatcher.cpp b/src/common/nickhighlightmatcher.cpp index a9459237..726b3dbd 100644 --- a/src/common/nickhighlightmatcher.cpp +++ b/src/common/nickhighlightmatcher.cpp @@ -24,8 +24,7 @@ #include #include -bool NickHighlightMatcher::match(const QString &string, const NetworkId &netId, - const QString ¤tNick, const QStringList &identityNicks) const +bool NickHighlightMatcher::match(const QString& string, const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const { // Never match for no nicknames if (_highlightMode == HighlightNickType::NoNick) { @@ -41,8 +40,7 @@ bool NickHighlightMatcher::match(const QString &string, const NetworkId &netId, determineExpressions(netId, currentNick, identityNicks); // Check for a match - if (_nickMatchCache[netId].matcher.isValid() - && _nickMatchCache[netId].matcher.match(string)) { + if (_nickMatchCache[netId].matcher.isValid() && _nickMatchCache[netId].matcher.match(string)) { // Nick matcher is valid and match found return true; } @@ -50,9 +48,7 @@ bool NickHighlightMatcher::match(const QString &string, const NetworkId &netId, return false; } - -void NickHighlightMatcher::determineExpressions(const NetworkId &netId, const QString ¤tNick, - const QStringList &identityNicks) const +void NickHighlightMatcher::determineExpressions(const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const { // Don't do anything for no nicknames if (_highlightMode == HighlightNickType::NoNick) { @@ -60,9 +56,8 @@ void NickHighlightMatcher::determineExpressions(const NetworkId &netId, const QS } // Only update if needed (check nickname config, current nick, identity nicks for change) - if (_nickMatchCache.contains(netId) - && _nickMatchCache[netId].nickCurrent == currentNick - && _nickMatchCache[netId].identityNicks == identityNicks) { + if (_nickMatchCache.contains(netId) && _nickMatchCache[netId].nickCurrent == currentNick + && _nickMatchCache[netId].identityNicks == identityNicks) { return; } @@ -78,9 +73,7 @@ void NickHighlightMatcher::determineExpressions(const NetworkId &netId, const QS } // Set up phrase matcher, joining with newlines - _nickMatchCache[netId].matcher = - ExpressionMatch(nickList.join("\n"), ExpressionMatch::MatchMode::MatchMultiPhrase, - _isCaseSensitive); + _nickMatchCache[netId].matcher = ExpressionMatch(nickList.join("\n"), ExpressionMatch::MatchMode::MatchMultiPhrase, _isCaseSensitive); _nickMatchCache[netId].nickCurrent = currentNick; _nickMatchCache[netId].identityNicks = identityNicks; diff --git a/src/common/nickhighlightmatcher.h b/src/common/nickhighlightmatcher.h index ec4df0d5..b6dc1e78 100644 --- a/src/common/nickhighlightmatcher.h +++ b/src/common/nickhighlightmatcher.h @@ -36,10 +36,11 @@ class COMMON_EXPORT NickHighlightMatcher { public: /// Nickname highlighting mode - enum class HighlightNickType { - NoNick = 0x00, ///< Don't match any nickname - CurrentNick = 0x01, ///< Match the current nickname - AllNicks = 0x02 ///< Match all configured nicknames in the chosen identity + enum class HighlightNickType + { + NoNick = 0x00, ///< Don't match any nickname + CurrentNick = 0x01, ///< Match the current nickname + AllNicks = 0x02 ///< Match all configured nicknames in the chosen identity }; // NOTE: Keep this in sync with HighlightRuleManager::HighlightNickType and // NotificationSettings::HighlightNickType! @@ -56,8 +57,9 @@ public: * @param isCaseSensitive If true, nick matching is case-sensitive, otherwise case-insensitive */ NickHighlightMatcher(HighlightNickType highlightMode, bool isCaseSensitive) - : _highlightMode(highlightMode), - _isCaseSensitive(isCaseSensitive) {} + : _highlightMode(highlightMode) + , _isCaseSensitive(isCaseSensitive) + {} /** * Gets the nickname highlighting policy @@ -71,7 +73,8 @@ public: * * @param highlightMode Nickname highlighting mode */ - void setHighlightMode(HighlightNickType highlightMode) { + void setHighlightMode(HighlightNickType highlightMode) + { if (_highlightMode != highlightMode) { _highlightMode = highlightMode; invalidateNickCache(); @@ -90,7 +93,8 @@ public: * * @param isCaseSensitive If true, nick matching is case-sensitive, otherwise case-insensitive */ - void setCaseSensitive(bool isCaseSensitive) { + void setCaseSensitive(bool isCaseSensitive) + { if (_isCaseSensitive != isCaseSensitive) { _isCaseSensitive = isCaseSensitive; invalidateNickCache(); @@ -108,8 +112,7 @@ public: * @param identityNicks All nicknames configured for the current identity * @return True if match found, otherwise false */ - bool match(const QString &string, const NetworkId &netId, const QString ¤tNick, - const QStringList &identityNicks) const; + bool match(const QString& string, const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const; public slots: /** @@ -117,7 +120,8 @@ public slots: * * @param netId Network ID of source network */ - void removeNetwork(const NetworkId &netId) { + void removeNetwork(const NetworkId& netId) + { // Remove the network from the cache list if (_nickMatchCache.remove(netId) > 0) { qDebug() << "Cleared nickname matching cache for removed network ID" << netId; @@ -125,7 +129,8 @@ public slots: } private: - struct NickMatchCache { + struct NickMatchCache + { // These represent internal cache and should be safe to mutate in 'const' functions QString nickCurrent = {}; ///< Last cached current nick QStringList identityNicks = {}; ///< Last cached identity nicks @@ -139,15 +144,15 @@ private: * @param currentNick Current nickname * @param identityNicks All nicknames configured for the current identity */ - void determineExpressions(const NetworkId &netId, const QString ¤tNick, - const QStringList &identityNicks) const; + void determineExpressions(const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const; /** * Invalidate all nickname match caches * * Use this after changing global configuration. */ - inline void invalidateNickCache() { + inline void invalidateNickCache() + { // Mark all as invalid if (_nickMatchCache.size() > 0) { _nickMatchCache.clear(); @@ -161,6 +166,5 @@ private: bool _isCaseSensitive = false; ///< If true, match nicknames with exact case // These represent internal cache and should be safe to mutate in 'const' functions - mutable QHash _nickMatchCache; ///< Per-network nick matching cache - + mutable QHash _nickMatchCache; ///< Per-network nick matching cache }; diff --git a/src/common/peer.cpp b/src/common/peer.cpp index 1d459b67..da408b0f 100644 --- a/src/common/peer.cpp +++ b/src/common/peer.cpp @@ -20,44 +20,48 @@ #include "peer.h" -Peer::Peer(AuthHandler *authHandler, QObject *parent) +Peer::Peer(AuthHandler* authHandler, QObject* parent) : QObject(parent) , _authHandler(authHandler) -{ - -} - +{} -AuthHandler *Peer::authHandler() const +AuthHandler* Peer::authHandler() const { return _authHandler; } -QDateTime Peer::connectedSince() const { +QDateTime Peer::connectedSince() const +{ return _connectedSince; } -void Peer::setConnectedSince(const QDateTime &connectedSince) { +void Peer::setConnectedSince(const QDateTime& connectedSince) +{ _connectedSince = connectedSince; } -QString Peer::buildDate() const { +QString Peer::buildDate() const +{ return _buildDate; } -void Peer::setBuildDate(const QString &buildDate) { +void Peer::setBuildDate(const QString& buildDate) +{ _buildDate = buildDate; } -QString Peer::clientVersion() const { +QString Peer::clientVersion() const +{ return _clientVersion; } -void Peer::setClientVersion(const QString &clientVersion) { +void Peer::setClientVersion(const QString& clientVersion) +{ _clientVersion = clientVersion; } -bool Peer::hasFeature(Quassel::Feature feature) const { +bool Peer::hasFeature(Quassel::Feature feature) const +{ return _features.isEnabled(feature); } @@ -66,15 +70,18 @@ Quassel::Features Peer::features() const return _features; } -void Peer::setFeatures(Quassel::Features features) { +void Peer::setFeatures(Quassel::Features features) +{ _features = std::move(features); } -int Peer::id() const { +int Peer::id() const +{ return _id; } -void Peer::setId(int id) { +void Peer::setId(int id) +{ _id = id; } @@ -84,14 +91,14 @@ void Peer::setId(int id) { // received over the network with the actual address of the local Peer // instance. Because the actual value isn't needed on the wire, it is // serialized as null. -QDataStream &operator<<(QDataStream &out, PeerPtr ptr) +QDataStream& operator<<(QDataStream& out, PeerPtr ptr) { Q_UNUSED(ptr); out << static_cast(0); // 64 bit for historic reasons return out; } -QDataStream &operator>>(QDataStream &in, PeerPtr &ptr) +QDataStream& operator>>(QDataStream& in, PeerPtr& ptr) { ptr = nullptr; quint64 value; diff --git a/src/common/peer.h b/src/common/peer.h index 803f15b5..0a0881dd 100644 --- a/src/common/peer.h +++ b/src/common/peer.h @@ -36,22 +36,22 @@ class COMMON_EXPORT Peer : public QObject Q_OBJECT public: - explicit Peer(AuthHandler *authHandler, QObject *parent = nullptr); + explicit Peer(AuthHandler* authHandler, QObject* parent = nullptr); virtual Protocol::Type protocol() const = 0; virtual QString description() const = 0; - virtual SignalProxy *signalProxy() const = 0; - virtual void setSignalProxy(SignalProxy *proxy) = 0; + virtual SignalProxy* signalProxy() const = 0; + virtual void setSignalProxy(SignalProxy* proxy) = 0; QDateTime connectedSince() const; - void setConnectedSince(const QDateTime &connectedSince); + void setConnectedSince(const QDateTime& connectedSince); QString buildDate() const; - void setBuildDate(const QString &buildDate); + void setBuildDate(const QString& buildDate); QString clientVersion() const; - void setClientVersion(const QString &clientVersion); + void setClientVersion(const QString& clientVersion); bool hasFeature(Quassel::Feature feature) const; Quassel::Features features() const; @@ -60,7 +60,7 @@ public: int id() const; void setId(int id); - AuthHandler *authHandler() const; + AuthHandler* authHandler() const; virtual bool isOpen() const = 0; virtual bool isSecure() const = 0; @@ -73,24 +73,24 @@ public: public slots: /* Handshake messages */ - virtual void dispatch(const Protocol::RegisterClient &) = 0; - virtual void dispatch(const Protocol::ClientDenied &) = 0; - virtual void dispatch(const Protocol::ClientRegistered &) = 0; - virtual void dispatch(const Protocol::SetupData &) = 0; - virtual void dispatch(const Protocol::SetupFailed &) = 0; - virtual void dispatch(const Protocol::SetupDone &) = 0; - virtual void dispatch(const Protocol::Login &) = 0; - virtual void dispatch(const Protocol::LoginFailed &) = 0; - virtual void dispatch(const Protocol::LoginSuccess &) = 0; - virtual void dispatch(const Protocol::SessionState &) = 0; + virtual void dispatch(const Protocol::RegisterClient&) = 0; + virtual void dispatch(const Protocol::ClientDenied&) = 0; + virtual void dispatch(const Protocol::ClientRegistered&) = 0; + virtual void dispatch(const Protocol::SetupData&) = 0; + virtual void dispatch(const Protocol::SetupFailed&) = 0; + virtual void dispatch(const Protocol::SetupDone&) = 0; + virtual void dispatch(const Protocol::Login&) = 0; + virtual void dispatch(const Protocol::LoginFailed&) = 0; + virtual void dispatch(const Protocol::LoginSuccess&) = 0; + virtual void dispatch(const Protocol::SessionState&) = 0; /* Sigproxy messages */ - virtual void dispatch(const Protocol::SyncMessage &) = 0; - virtual void dispatch(const Protocol::RpcCall &) = 0; - virtual void dispatch(const Protocol::InitRequest &) = 0; - virtual void dispatch(const Protocol::InitData &) = 0; + virtual void dispatch(const Protocol::SyncMessage&) = 0; + virtual void dispatch(const Protocol::RpcCall&) = 0; + virtual void dispatch(const Protocol::InitRequest&) = 0; + virtual void dispatch(const Protocol::InitData&) = 0; - virtual void close(const QString &reason = QString()) = 0; + virtual void close(const QString& reason = QString()) = 0; signals: void disconnected(); @@ -99,7 +99,7 @@ signals: protected: template - void handle(const T &protoMessage); + void handle(const T& protoMessage); private: QPointer _authHandler; @@ -114,36 +114,35 @@ private: }; // We need to special-case Peer* in attached signals/slots, so typedef it for the meta type system -using PeerPtr = Peer *; +using PeerPtr = Peer*; Q_DECLARE_METATYPE(PeerPtr) -QDataStream &operator<<(QDataStream &out, PeerPtr ptr); -QDataStream &operator>>(QDataStream &in, PeerPtr &ptr); - +QDataStream& operator<<(QDataStream& out, PeerPtr ptr); +QDataStream& operator>>(QDataStream& in, PeerPtr& ptr); // Template method needed in the header -template inline -void Peer::handle(const T &protoMessage) +template +inline void Peer::handle(const T& protoMessage) { - switch(protoMessage.handler()) { - case Protocol::Handler::SignalProxy: - if (!signalProxy()) { - qWarning() << Q_FUNC_INFO << "Cannot handle message without a SignalProxy!"; - return; - } - signalProxy()->handle(this, protoMessage); - break; - - case Protocol::Handler::AuthHandler: - if (!authHandler()) { - qWarning() << Q_FUNC_INFO << "Cannot handle auth messages without an active AuthHandler!"; - return; - } - authHandler()->handle(protoMessage); - break; - - default: - qWarning() << Q_FUNC_INFO << "Unknown handler for protocol message!"; + switch (protoMessage.handler()) { + case Protocol::Handler::SignalProxy: + if (!signalProxy()) { + qWarning() << Q_FUNC_INFO << "Cannot handle message without a SignalProxy!"; + return; + } + signalProxy()->handle(this, protoMessage); + break; + + case Protocol::Handler::AuthHandler: + if (!authHandler()) { + qWarning() << Q_FUNC_INFO << "Cannot handle auth messages without an active AuthHandler!"; return; + } + authHandler()->handle(protoMessage); + break; + + default: + qWarning() << Q_FUNC_INFO << "Unknown handler for protocol message!"; + return; } } diff --git a/src/common/peerfactory.cpp b/src/common/peerfactory.cpp index 37f41755..498495c7 100644 --- a/src/common/peerfactory.cpp +++ b/src/common/peerfactory.cpp @@ -23,7 +23,6 @@ #include "protocols/datastream/datastreampeer.h" #include "protocols/legacy/legacypeer.h" - PeerFactory::ProtoList PeerFactory::supportedProtocols() { ProtoList result; @@ -32,27 +31,27 @@ PeerFactory::ProtoList PeerFactory::supportedProtocols() return result; } - -RemotePeer *PeerFactory::createPeer(const ProtoDescriptor &protocol, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent) +RemotePeer* PeerFactory::createPeer( + const ProtoDescriptor& protocol, AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent) { return createPeer(ProtoList() << protocol, authHandler, socket, level, parent); } - -RemotePeer *PeerFactory::createPeer(const ProtoList &protocols, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent) +RemotePeer* PeerFactory::createPeer( + const ProtoList& protocols, AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent) { - foreach(const ProtoDescriptor &protodesc, protocols) { + foreach (const ProtoDescriptor& protodesc, protocols) { Protocol::Type proto = protodesc.first; quint16 features = protodesc.second; - switch(proto) { - case Protocol::LegacyProtocol: - return new LegacyPeer(authHandler, socket, level, parent); - case Protocol::DataStreamProtocol: - if (DataStreamPeer::acceptsFeatures(features)) - return new DataStreamPeer(authHandler, socket, features, level, parent); - break; - default: - break; + switch (proto) { + case Protocol::LegacyProtocol: + return new LegacyPeer(authHandler, socket, level, parent); + case Protocol::DataStreamProtocol: + if (DataStreamPeer::acceptsFeatures(features)) + return new DataStreamPeer(authHandler, socket, features, level, parent); + break; + default: + break; } } diff --git a/src/common/peerfactory.h b/src/common/peerfactory.h index ca6639aa..cd70ddc7 100644 --- a/src/common/peerfactory.h +++ b/src/common/peerfactory.h @@ -35,7 +35,6 @@ class RemotePeer; class COMMON_EXPORT PeerFactory { - public: // second value is the protocol-specific features using ProtoDescriptor = QPair; @@ -43,7 +42,14 @@ public: static ProtoList supportedProtocols(); - static RemotePeer *createPeer(const ProtoDescriptor &protocol, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr); - static RemotePeer *createPeer(const ProtoList &protocols, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr); - + static RemotePeer* createPeer(const ProtoDescriptor& protocol, + AuthHandler* authHandler, + QTcpSocket* socket, + Compressor::CompressionLevel level, + QObject* parent = nullptr); + static RemotePeer* createPeer(const ProtoList& protocols, + AuthHandler* authHandler, + QTcpSocket* socket, + Compressor::CompressionLevel level, + QObject* parent = nullptr); }; diff --git a/src/common/posixsignalwatcher.cpp b/src/common/posixsignalwatcher.cpp index 4da9539a..eee39183 100644 --- a/src/common/posixsignalwatcher.cpp +++ b/src/common/posixsignalwatcher.cpp @@ -20,10 +20,10 @@ #include "posixsignalwatcher.h" +#include #include -#include #include -#include +#include #include #include @@ -36,7 +36,7 @@ int PosixSignalWatcher::_sockpair[2]; -PosixSignalWatcher::PosixSignalWatcher(QObject *parent) +PosixSignalWatcher::PosixSignalWatcher(QObject* parent) : AbstractSignalWatcher{parent} { if (::socketpair(AF_UNIX, SOCK_STREAM, 0, _sockpair)) { @@ -54,7 +54,7 @@ PosixSignalWatcher::PosixSignalWatcher(QObject *parent) #ifdef HAVE_BACKTRACE // we only handle crashes ourselves if coredumps are disabled - struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit)); + struct rlimit* limit = (rlimit*)malloc(sizeof(struct rlimit)); int rc = getrlimit(RLIMIT_CORE, limit); if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) { registerSignal(SIGABRT); diff --git a/src/common/posixsignalwatcher.h b/src/common/posixsignalwatcher.h index d96760eb..7c9ad4d6 100644 --- a/src/common/posixsignalwatcher.h +++ b/src/common/posixsignalwatcher.h @@ -36,7 +36,7 @@ class PosixSignalWatcher : public AbstractSignalWatcher Q_OBJECT public: - PosixSignalWatcher(QObject *parent = nullptr); + PosixSignalWatcher(QObject* parent = nullptr); private: static void signalHandler(int signal); @@ -48,5 +48,5 @@ private slots: private: static int _sockpair[2]; - QSocketNotifier *_notifier{nullptr}; + QSocketNotifier* _notifier{nullptr}; }; diff --git a/src/common/presetnetworks.cpp b/src/common/presetnetworks.cpp index 9f8b31d8..99ebeee4 100644 --- a/src/common/presetnetworks.cpp +++ b/src/common/presetnetworks.cpp @@ -18,9 +18,10 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "presetnetworks.h" + #include -#include "presetnetworks.h" #include "quassel.h" QString PresetNetworks::_networksIniPath = QString(); @@ -34,7 +35,7 @@ QStringList PresetNetworks::names(bool onlyDefault) if (_networksIniPath.isNull()) { _networksIniPath = Quassel::findDataFilePath("networks.ini"); if (_networksIniPath.isNull()) { - _networksIniPath = ""; // now we won't check again, as it's not null anymore + _networksIniPath = ""; // now we won't check again, as it's not null anymore return QStringList(); } } @@ -44,7 +45,7 @@ QStringList PresetNetworks::names(bool onlyDefault) if (!networks.isEmpty()) { // we sort the list case-insensitive QMap sorted; - foreach(QString net, networks) { + foreach (QString net, networks) { if (onlyDefault && !s.value(QString("%1/Default").arg(net)).toBool()) continue; sorted[net.toLower()] = net; @@ -55,24 +56,22 @@ QStringList PresetNetworks::names(bool onlyDefault) return QStringList(); } - -QStringList PresetNetworks::defaultChannels(const QString &networkName) +QStringList PresetNetworks::defaultChannels(const QString& networkName) { - if (_networksIniPath.isEmpty()) // be sure to have called presetNetworks() first, else this always fails + if (_networksIniPath.isEmpty()) // be sure to have called presetNetworks() first, else this always fails return QStringList(); QSettings s(_networksIniPath, QSettings::IniFormat); return s.value(QString("%1/DefaultChannels").arg(networkName)).toStringList(); } - -NetworkInfo PresetNetworks::networkInfo(const QString &networkName) +NetworkInfo PresetNetworks::networkInfo(const QString& networkName) { NetworkInfo info; if (!_networksIniPath.isEmpty()) { info.networkName = networkName; QSettings s(_networksIniPath, QSettings::IniFormat); s.beginGroup(info.networkName); - foreach(QString server, s.value("Servers").toStringList()) { + foreach (QString server, s.value("Servers").toStringList()) { bool ssl = false; QStringList splitserver = server.split(':', QString::SkipEmptyParts); if (splitserver.count() != 2) { diff --git a/src/common/presetnetworks.h b/src/common/presetnetworks.h index 253e56eb..ff7f092c 100644 --- a/src/common/presetnetworks.h +++ b/src/common/presetnetworks.h @@ -31,8 +31,8 @@ class COMMON_EXPORT PresetNetworks { public: static QStringList names(bool onlyDefault = false); - static QStringList defaultChannels(const QString &networkName); - static NetworkInfo networkInfo(const QString &networkName); + static QStringList defaultChannels(const QString& networkName); + static NetworkInfo networkInfo(const QString& networkName); private: static QString _networksIniPath; diff --git a/src/common/protocol.h b/src/common/protocol.h index dcb7fa6c..8c2a6a6d 100644 --- a/src/common/protocol.h +++ b/src/common/protocol.h @@ -20,10 +20,11 @@ #pragma once +#include + #include #include #include -#include #include "quassel.h" @@ -31,32 +32,32 @@ namespace Protocol { const quint32 magic = 0x42b33f00; -enum Type { +enum Type +{ InternalProtocol = 0x00, LegacyProtocol = 0x01, DataStreamProtocol = 0x02 }; - -enum Feature { +enum Feature +{ Encryption = 0x01, Compression = 0x02 }; - -enum class Handler { +enum class Handler +{ SignalProxy, AuthHandler }; - /*** Handshake, handled by AuthHandler ***/ -struct HandshakeMessage { +struct HandshakeMessage +{ inline Handler handler() const { return Handler::AuthHandler; } }; - struct RegisterClient : public HandshakeMessage { inline RegisterClient(Quassel::Features clientFeatures, QString clientVersion, QString buildDate, bool sslSupported = false) @@ -74,19 +75,19 @@ struct RegisterClient : public HandshakeMessage bool sslSupported; }; - struct ClientDenied : public HandshakeMessage { inline ClientDenied(QString errorString) - : errorString(std::move(errorString)) {} + : errorString(std::move(errorString)) + {} QString errorString; }; - struct ClientRegistered : public HandshakeMessage { - inline ClientRegistered(Quassel::Features coreFeatures, bool coreConfigured, QVariantList backendInfo, QVariantList authenticatorInfo, bool sslSupported) + inline ClientRegistered( + Quassel::Features coreFeatures, bool coreConfigured, QVariantList backendInfo, QVariantList authenticatorInfo, bool sslSupported) : features(std::move(coreFeatures)) , coreConfigured(coreConfigured) , backendInfo(std::move(backendInfo)) @@ -96,7 +97,7 @@ struct ClientRegistered : public HandshakeMessage Quassel::Features features; bool coreConfigured; - QVariantList backendInfo; // TODO: abstract this better + QVariantList backendInfo; // TODO: abstract this better // The authenticatorInfo should be optional! QVariantList authenticatorInfo; @@ -105,18 +106,20 @@ struct ClientRegistered : public HandshakeMessage bool sslSupported; }; - struct SetupData : public HandshakeMessage { - inline SetupData(QString adminUser, QString adminPassword, QString backend, - QVariantMap setupData, QString authenticator = QString(), + inline SetupData(QString adminUser, + QString adminPassword, + QString backend, + QVariantMap setupData, + QString authenticator = QString(), QVariantMap authSetupData = QVariantMap()) - : adminUser(std::move(adminUser)) - , adminPassword(std::move(adminPassword)) - , backend(std::move(backend)) - , setupData(std::move(setupData)) - , authenticator(std::move(authenticator)) - , authSetupData(std::move(authSetupData)) + : adminUser(std::move(adminUser)) + , adminPassword(std::move(adminPassword)) + , backend(std::move(backend)) + , setupData(std::move(setupData)) + , authenticator(std::move(authenticator)) + , authSetupData(std::move(authSetupData)) {} QString adminUser; @@ -127,51 +130,50 @@ struct SetupData : public HandshakeMessage QVariantMap authSetupData; }; - struct SetupFailed : public HandshakeMessage { inline SetupFailed(QString errorString) - : errorString(std::move(errorString)) {} + : errorString(std::move(errorString)) + {} QString errorString; }; - struct SetupDone : public HandshakeMessage -{ -}; - +{}; struct Login : public HandshakeMessage { inline Login(QString user, QString password) - : user(std::move(user)), password(std::move(password)) {} + : user(std::move(user)) + , password(std::move(password)) + {} QString user; QString password; }; - struct LoginFailed : public HandshakeMessage { inline LoginFailed(QString errorString) - : errorString(std::move(errorString)) {} + : errorString(std::move(errorString)) + {} QString errorString; }; - struct LoginSuccess : public HandshakeMessage -{ -}; - +{}; // TODO: more generic format struct SessionState : public HandshakeMessage { - inline SessionState() = default; // needed for QMetaType (for the mono client) + inline SessionState() = default; // needed for QMetaType (for the mono client) inline SessionState(QVariantList identities, QVariantList bufferInfos, QVariantList networkIds) - : identities(std::move(identities)), bufferInfos(std::move(bufferInfos)), networkIds(std::move(networkIds)) {} + : identities(std::move(identities)) + , bufferInfos(std::move(bufferInfos)) + , networkIds(std::move(networkIds)) + {} QVariantList identities; QVariantList bufferInfos; @@ -185,12 +187,15 @@ struct SignalProxyMessage inline Handler handler() const { return Handler::SignalProxy; } }; - struct SyncMessage : public SignalProxyMessage { SyncMessage() = default; SyncMessage(QByteArray className, QString objectName, QByteArray slotName, QVariantList params) - : className(std::move(className)), objectName(std::move(objectName)), slotName(std::move(slotName)), params(std::move(params)) {} + : className(std::move(className)) + , objectName(std::move(objectName)) + , slotName(std::move(slotName)) + , params(std::move(params)) + {} QByteArray className; QString objectName; @@ -198,60 +203,65 @@ struct SyncMessage : public SignalProxyMessage QVariantList params; }; - struct RpcCall : public SignalProxyMessage { RpcCall() = default; RpcCall(QByteArray slotName, QVariantList params) - : slotName(std::move(slotName)), params(std::move(params)) {} + : slotName(std::move(slotName)) + , params(std::move(params)) + {} QByteArray slotName; QVariantList params; }; - struct InitRequest : public SignalProxyMessage { InitRequest() = default; InitRequest(QByteArray className, QString objectName) - : className(std::move(className)), objectName(std::move(objectName)) {} + : className(std::move(className)) + , objectName(std::move(objectName)) + {} QByteArray className; QString objectName; }; - struct InitData : public SignalProxyMessage { InitData() = default; InitData(QByteArray className, QString objectName, QVariantMap initData) - : className(std::move(className)), objectName(std::move(objectName)), initData(std::move(initData)) {} + : className(std::move(className)) + , objectName(std::move(objectName)) + , initData(std::move(initData)) + {} QByteArray className; QString objectName; QVariantMap initData; }; - /*** handled by RemoteConnection ***/ struct HeartBeat { - inline HeartBeat(QDateTime timestamp) : timestamp(std::move(timestamp)) {} + inline HeartBeat(QDateTime timestamp) + : timestamp(std::move(timestamp)) + {} QDateTime timestamp; }; - struct HeartBeatReply { - inline HeartBeatReply(QDateTime timestamp) : timestamp(std::move(timestamp)) {} + inline HeartBeatReply(QDateTime timestamp) + : timestamp(std::move(timestamp)) + {} QDateTime timestamp; }; - -} +} // namespace Protocol // Required for InternalPeer Q_DECLARE_METATYPE(Protocol::SyncMessage) diff --git a/src/common/protocols/datastream/datastreampeer.cpp b/src/common/protocols/datastream/datastreampeer.cpp index 240560da..3eb643b2 100644 --- a/src/common/protocols/datastream/datastreampeer.cpp +++ b/src/common/protocols/datastream/datastreampeer.cpp @@ -18,44 +18,43 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include +#include "datastreampeer.h" + #include #include #include +#include -#include "datastreampeer.h" #include "quassel.h" + #include "serializers/serializers.h" using namespace Protocol; -DataStreamPeer::DataStreamPeer(::AuthHandler *authHandler, QTcpSocket *socket, quint16 features, Compressor::CompressionLevel level, QObject *parent) +DataStreamPeer::DataStreamPeer( + ::AuthHandler* authHandler, QTcpSocket* socket, quint16 features, Compressor::CompressionLevel level, QObject* parent) : RemotePeer(authHandler, socket, level, parent) { Q_UNUSED(features); } - quint16 DataStreamPeer::supportedFeatures() { return 0; } - bool DataStreamPeer::acceptsFeatures(quint16 peerFeatures) { Q_UNUSED(peerFeatures); return true; } - quint16 DataStreamPeer::enabledFeatures() const { return 0; } - -void DataStreamPeer::processMessage(const QByteArray &msg) +void DataStreamPeer::processMessage(const QByteArray& msg) { QDataStream stream(msg); stream.setVersion(QDataStream::Qt_4_2); @@ -74,8 +73,7 @@ void DataStreamPeer::processMessage(const QByteArray &msg) handlePackedFunc(list); } - -void DataStreamPeer::writeMessage(const QVariantMap &handshakeMsg) +void DataStreamPeer::writeMessage(const QVariantMap& handshakeMsg) { QVariantList list; QVariantMap::const_iterator it = handshakeMsg.begin(); @@ -87,8 +85,7 @@ void DataStreamPeer::writeMessage(const QVariantMap &handshakeMsg) writeMessage(list); } - -void DataStreamPeer::writeMessage(const QVariantList &sigProxyMsg) +void DataStreamPeer::writeMessage(const QVariantList& sigProxyMsg) { QByteArray data; QDataStream msgStream(&data, QIODevice::WriteOnly); @@ -98,7 +95,6 @@ void DataStreamPeer::writeMessage(const QVariantList &sigProxyMsg) writeMessage(data); } - /*** Handshake messages ***/ /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have @@ -106,11 +102,11 @@ void DataStreamPeer::writeMessage(const QVariantList &sigProxyMsg) * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here. */ -void DataStreamPeer::handleHandshakeMessage(const QVariantList &mapData) +void DataStreamPeer::handleHandshakeMessage(const QVariantList& mapData) { QVariantMap m; - for (int i = 0; i < mapData.count()/2; ++i) - m[QString::fromUtf8(mapData[2*i].toByteArray())] = mapData[2*i+1]; + for (int i = 0; i < mapData.count() / 2; ++i) + m[QString::fromUtf8(mapData[2 * i].toByteArray())] = mapData[2 * i + 1]; QString msgType = m["MsgType"].toString(); if (msgType.isEmpty()) { @@ -119,11 +115,12 @@ void DataStreamPeer::handleHandshakeMessage(const QVariantList &mapData) } if (msgType == "ClientInit") { - handle(RegisterClient{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["Features"].toUInt())}, - m["ClientVersion"].toString(), - m["ClientDate"].toString(), - false // UseSsl obsolete - }); + handle(RegisterClient{ + Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["Features"].toUInt())}, + m["ClientVersion"].toString(), + m["ClientDate"].toString(), + false // UseSsl obsolete + }); } else if (msgType == "ClientInitReject") { @@ -131,17 +128,23 @@ void DataStreamPeer::handleHandshakeMessage(const QVariantList &mapData) } else if (msgType == "ClientInitAck") { - handle(ClientRegistered{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["CoreFeatures"].toUInt())}, - m["Configured"].toBool(), - m["StorageBackends"].toList(), - m["Authenticators"].toList(), - false // SupportsSsl obsolete - }); + handle(ClientRegistered{ + Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["CoreFeatures"].toUInt())}, + m["Configured"].toBool(), + m["StorageBackends"].toList(), + m["Authenticators"].toList(), + false // SupportsSsl obsolete + }); } else if (msgType == "CoreSetupData") { QVariantMap map = m["SetupData"].toMap(); - handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap())); + handle(SetupData(map["AdminUser"].toString(), + map["AdminPasswd"].toString(), + map["Backend"].toString(), + map["ConnectionProperties"].toMap(), + map["Authenticator"].toString(), + map["AuthProperties"].toMap())); } else if (msgType == "CoreSetupReject") { @@ -174,8 +177,8 @@ void DataStreamPeer::handleHandshakeMessage(const QVariantList &mapData) } } - -void DataStreamPeer::dispatch(const RegisterClient &msg) { +void DataStreamPeer::dispatch(const RegisterClient& msg) +{ QVariantMap m; m["MsgType"] = "ClientInit"; m["Features"] = static_cast(msg.features.toLegacyFeatures()); @@ -186,8 +189,8 @@ void DataStreamPeer::dispatch(const RegisterClient &msg) { writeMessage(m); } - -void DataStreamPeer::dispatch(const ClientDenied &msg) { +void DataStreamPeer::dispatch(const ClientDenied& msg) +{ QVariantMap m; m["MsgType"] = "ClientInitReject"; m["Error"] = msg.errorString; @@ -195,8 +198,8 @@ void DataStreamPeer::dispatch(const ClientDenied &msg) { writeMessage(m); } - -void DataStreamPeer::dispatch(const ClientRegistered &msg) { +void DataStreamPeer::dispatch(const ClientRegistered& msg) +{ QVariantMap m; m["MsgType"] = "ClientInitAck"; if (hasFeature(Quassel::Feature::ExtendedFeatures)) { @@ -214,8 +217,7 @@ void DataStreamPeer::dispatch(const ClientRegistered &msg) { writeMessage(m); } - -void DataStreamPeer::dispatch(const SetupData &msg) +void DataStreamPeer::dispatch(const SetupData& msg) { QVariantMap map; map["AdminUser"] = msg.adminUser; @@ -234,8 +236,7 @@ void DataStreamPeer::dispatch(const SetupData &msg) writeMessage(m); } - -void DataStreamPeer::dispatch(const SetupFailed &msg) +void DataStreamPeer::dispatch(const SetupFailed& msg) { QVariantMap m; m["MsgType"] = "CoreSetupReject"; @@ -244,8 +245,7 @@ void DataStreamPeer::dispatch(const SetupFailed &msg) writeMessage(m); } - -void DataStreamPeer::dispatch(const SetupDone &msg) +void DataStreamPeer::dispatch(const SetupDone& msg) { Q_UNUSED(msg) @@ -255,8 +255,7 @@ void DataStreamPeer::dispatch(const SetupDone &msg) writeMessage(m); } - -void DataStreamPeer::dispatch(const Login &msg) +void DataStreamPeer::dispatch(const Login& msg) { QVariantMap m; m["MsgType"] = "ClientLogin"; @@ -266,8 +265,7 @@ void DataStreamPeer::dispatch(const Login &msg) writeMessage(m); } - -void DataStreamPeer::dispatch(const LoginFailed &msg) +void DataStreamPeer::dispatch(const LoginFailed& msg) { QVariantMap m; m["MsgType"] = "ClientLoginReject"; @@ -276,8 +274,7 @@ void DataStreamPeer::dispatch(const LoginFailed &msg) writeMessage(m); } - -void DataStreamPeer::dispatch(const LoginSuccess &msg) +void DataStreamPeer::dispatch(const LoginSuccess& msg) { Q_UNUSED(msg) @@ -287,8 +284,7 @@ void DataStreamPeer::dispatch(const LoginSuccess &msg) writeMessage(m); } - -void DataStreamPeer::dispatch(const SessionState &msg) +void DataStreamPeer::dispatch(const SessionState& msg) { QVariantMap m; m["MsgType"] = "SessionInit"; @@ -302,10 +298,9 @@ void DataStreamPeer::dispatch(const SessionState &msg) writeMessage(m); } - /*** Standard messages ***/ -void DataStreamPeer::handlePackedFunc(const QVariantList &packedFunc) +void DataStreamPeer::handlePackedFunc(const QVariantList& packedFunc) { QVariantList params(packedFunc); @@ -317,91 +312,86 @@ void DataStreamPeer::handlePackedFunc(const QVariantList &packedFunc) // TODO: make sure that this is a valid request type RequestType requestType = (RequestType)params.takeFirst().value(); switch (requestType) { - case Sync: { - if (params.count() < 3) { - qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params; - return; - } - QByteArray className = params.takeFirst().toByteArray(); - QString objectName = QString::fromUtf8(params.takeFirst().toByteArray()); - QByteArray slotName = params.takeFirst().toByteArray(); - handle(Protocol::SyncMessage(className, objectName, slotName, params)); - break; + case Sync: { + if (params.count() < 3) { + qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params; + return; } - case RpcCall: { - if (params.empty()) { - qWarning() << Q_FUNC_INFO << "Received empty RPC call!"; - return; - } - QByteArray slotName = params.takeFirst().toByteArray(); - handle(Protocol::RpcCall(slotName, params)); - break; + QByteArray className = params.takeFirst().toByteArray(); + QString objectName = QString::fromUtf8(params.takeFirst().toByteArray()); + QByteArray slotName = params.takeFirst().toByteArray(); + handle(Protocol::SyncMessage(className, objectName, slotName, params)); + break; + } + case RpcCall: { + if (params.empty()) { + qWarning() << Q_FUNC_INFO << "Received empty RPC call!"; + return; } - case InitRequest: { - if (params.count() != 2) { - qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params; - return; - } - QByteArray className = params[0].toByteArray(); - QString objectName = QString::fromUtf8(params[1].toByteArray()); - handle(Protocol::InitRequest(className, objectName)); - break; + QByteArray slotName = params.takeFirst().toByteArray(); + handle(Protocol::RpcCall(slotName, params)); + break; + } + case InitRequest: { + if (params.count() != 2) { + qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params; + return; } - case InitData: { - if (params.count() < 2) { - qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params; - return; - } - QByteArray className = params.takeFirst().toByteArray(); - QString objectName = QString::fromUtf8(params.takeFirst().toByteArray()); - QVariantMap initData; - for (int i = 0; i < params.count()/2; ++i) - initData[QString::fromUtf8(params[2*i].toByteArray())] = params[2*i+1]; - handle(Protocol::InitData(className, objectName, initData)); - break; + QByteArray className = params[0].toByteArray(); + QString objectName = QString::fromUtf8(params[1].toByteArray()); + handle(Protocol::InitRequest(className, objectName)); + break; + } + case InitData: { + if (params.count() < 2) { + qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params; + return; } - case HeartBeat: { - if (params.count() != 1) { - qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; - return; - } - // Note: QDateTime instead of QTime as in the legacy protocol! - handle(Protocol::HeartBeat(params[0].toDateTime())); - break; + QByteArray className = params.takeFirst().toByteArray(); + QString objectName = QString::fromUtf8(params.takeFirst().toByteArray()); + QVariantMap initData; + for (int i = 0; i < params.count() / 2; ++i) + initData[QString::fromUtf8(params[2 * i].toByteArray())] = params[2 * i + 1]; + handle(Protocol::InitData(className, objectName, initData)); + break; + } + case HeartBeat: { + if (params.count() != 1) { + qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; + return; } - case HeartBeatReply: { - if (params.count() != 1) { - qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; - return; - } - // Note: QDateTime instead of QTime as in the legacy protocol! - handle(Protocol::HeartBeatReply(params[0].toDateTime())); - break; + // Note: QDateTime instead of QTime as in the legacy protocol! + handle(Protocol::HeartBeat(params[0].toDateTime())); + break; + } + case HeartBeatReply: { + if (params.count() != 1) { + qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; + return; } - + // Note: QDateTime instead of QTime as in the legacy protocol! + handle(Protocol::HeartBeatReply(params[0].toDateTime())); + break; + } } } - -void DataStreamPeer::dispatch(const Protocol::SyncMessage &msg) +void DataStreamPeer::dispatch(const Protocol::SyncMessage& msg) { dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName.toUtf8() << msg.slotName << msg.params); } - -void DataStreamPeer::dispatch(const Protocol::RpcCall &msg) +void DataStreamPeer::dispatch(const Protocol::RpcCall& msg) { dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params); } - -void DataStreamPeer::dispatch(const Protocol::InitRequest &msg) +void DataStreamPeer::dispatch(const Protocol::InitRequest& msg) { dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName.toUtf8()); } - -void DataStreamPeer::dispatch(const Protocol::InitData &msg) +void DataStreamPeer::dispatch(const Protocol::InitData& msg) { QVariantList initData; QVariantMap::const_iterator it = msg.initData.begin(); @@ -412,20 +402,17 @@ void DataStreamPeer::dispatch(const Protocol::InitData &msg) dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName.toUtf8() << initData); } - -void DataStreamPeer::dispatch(const Protocol::HeartBeat &msg) +void DataStreamPeer::dispatch(const Protocol::HeartBeat& msg) { dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp); } - -void DataStreamPeer::dispatch(const Protocol::HeartBeatReply &msg) +void DataStreamPeer::dispatch(const Protocol::HeartBeatReply& msg) { dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp); } - -void DataStreamPeer::dispatchPackedFunc(const QVariantList &packedFunc) +void DataStreamPeer::dispatchPackedFunc(const QVariantList& packedFunc) { writeMessage(packedFunc); } diff --git a/src/common/protocols/datastream/datastreampeer.h b/src/common/protocols/datastream/datastreampeer.h index 5c1a442b..ccb76713 100644 --- a/src/common/protocols/datastream/datastreampeer.h +++ b/src/common/protocols/datastream/datastreampeer.h @@ -30,7 +30,8 @@ class DataStreamPeer : public RemotePeer Q_OBJECT public: - enum RequestType { + enum RequestType + { Sync = 1, RpcCall, InitRequest, @@ -39,7 +40,7 @@ public: HeartBeatReply }; - DataStreamPeer(AuthHandler *authHandler, QTcpSocket *socket, quint16 features, Compressor::CompressionLevel level, QObject *parent = nullptr); + DataStreamPeer(AuthHandler* authHandler, QTcpSocket* socket, quint16 features, Compressor::CompressionLevel level, QObject* parent = nullptr); Protocol::Type protocol() const override { return Protocol::DataStreamProtocol; } QString protocolName() const override { return "the DataStream protocol"; } @@ -48,37 +49,37 @@ public: static bool acceptsFeatures(quint16 peerFeatures); quint16 enabledFeatures() const override; - void dispatch(const Protocol::RegisterClient &msg) override; - void dispatch(const Protocol::ClientDenied &msg) override; - void dispatch(const Protocol::ClientRegistered &msg) override; - void dispatch(const Protocol::SetupData &msg) override; - void dispatch(const Protocol::SetupFailed &msg) override; - void dispatch(const Protocol::SetupDone &msg) override; - void dispatch(const Protocol::Login &msg) override; - void dispatch(const Protocol::LoginFailed &msg) override; - void dispatch(const Protocol::LoginSuccess &msg) override; - void dispatch(const Protocol::SessionState &msg) override; + void dispatch(const Protocol::RegisterClient& msg) override; + void dispatch(const Protocol::ClientDenied& msg) override; + void dispatch(const Protocol::ClientRegistered& msg) override; + void dispatch(const Protocol::SetupData& msg) override; + void dispatch(const Protocol::SetupFailed& msg) override; + void dispatch(const Protocol::SetupDone& msg) override; + void dispatch(const Protocol::Login& msg) override; + void dispatch(const Protocol::LoginFailed& msg) override; + void dispatch(const Protocol::LoginSuccess& msg) override; + void dispatch(const Protocol::SessionState& msg) override; - void dispatch(const Protocol::SyncMessage &msg) override; - void dispatch(const Protocol::RpcCall &msg) override; - void dispatch(const Protocol::InitRequest &msg) override; - void dispatch(const Protocol::InitData &msg) override; + void dispatch(const Protocol::SyncMessage& msg) override; + void dispatch(const Protocol::RpcCall& msg) override; + void dispatch(const Protocol::InitRequest& msg) override; + void dispatch(const Protocol::InitData& msg) override; - void dispatch(const Protocol::HeartBeat &msg) override; - void dispatch(const Protocol::HeartBeatReply &msg) override; + void dispatch(const Protocol::HeartBeat& msg) override; + void dispatch(const Protocol::HeartBeatReply& msg) override; signals: - void protocolError(const QString &errorString); + void protocolError(const QString& errorString); private: using RemotePeer::writeMessage; - void writeMessage(const QVariantMap &handshakeMsg); - void writeMessage(const QVariantList &sigProxyMsg); - void processMessage(const QByteArray &msg) override; + void writeMessage(const QVariantMap& handshakeMsg); + void writeMessage(const QVariantList& sigProxyMsg); + void processMessage(const QByteArray& msg) override; - void handleHandshakeMessage(const QVariantList &mapData); - void handlePackedFunc(const QVariantList &packedFunc); - void dispatchPackedFunc(const QVariantList &packedFunc); + void handleHandshakeMessage(const QVariantList& mapData); + void handlePackedFunc(const QVariantList& packedFunc); + void dispatchPackedFunc(const QVariantList& packedFunc); }; #endif diff --git a/src/common/protocols/legacy/legacypeer.cpp b/src/common/protocols/legacy/legacypeer.cpp index caf1bb22..027c3333 100644 --- a/src/common/protocols/legacy/legacypeer.cpp +++ b/src/common/protocols/legacy/legacypeer.cpp @@ -18,12 +18,14 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include +#include "legacypeer.h" + #include +#include #include -#include "legacypeer.h" #include "quassel.h" + #include "serializers/serializers.h" /* version.inc is no longer used for this */ @@ -33,15 +35,12 @@ const uint clientNeedsProtocol = protocolVersion; using namespace Protocol; -LegacyPeer::LegacyPeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent) - : RemotePeer(authHandler, socket, level, parent), - _useCompression(false) -{ - -} - +LegacyPeer::LegacyPeer(::AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent) + : RemotePeer(authHandler, socket, level, parent) + , _useCompression(false) +{} -void LegacyPeer::setSignalProxy(::SignalProxy *proxy) +void LegacyPeer::setSignalProxy(::SignalProxy* proxy) { RemotePeer::setSignalProxy(proxy); @@ -52,11 +51,9 @@ void LegacyPeer::setSignalProxy(::SignalProxy *proxy) if (_useCompression) qDebug() << "Using compression for peer:" << qPrintable(socket()->peerAddress().toString()); } - } - -void LegacyPeer::processMessage(const QByteArray &msg) +void LegacyPeer::processMessage(const QByteArray& msg) { QDataStream stream(msg); stream.setVersion(QDataStream::Qt_4_2); @@ -71,7 +68,7 @@ void LegacyPeer::processMessage(const QByteArray &msg) int nbytes = rawItem.size(); if (nbytes <= 4) { - const char *data = rawItem.constData(); + const char* data = rawItem.constData(); if (nbytes < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) { close("Peer sent corrupted compressed data!"); return; @@ -86,7 +83,8 @@ void LegacyPeer::processMessage(const QByteArray &msg) close("Peer sent corrupt data: unable to load QVariant!"); return; } - } else { + } + else { if (!Serializers::deserialize(stream, features(), item)) { close("Peer sent corrupt data: unable to load QVariant!"); return; @@ -105,8 +103,7 @@ void LegacyPeer::processMessage(const QByteArray &msg) handlePackedFunc(item); } - -void LegacyPeer::writeMessage(const QVariant &item) +void LegacyPeer::writeMessage(const QVariant& item) { QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); @@ -129,7 +126,6 @@ void LegacyPeer::writeMessage(const QVariant &item) writeMessage(block); } - /*** Handshake messages ***/ /* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have @@ -137,7 +133,7 @@ void LegacyPeer::writeMessage(const QVariant &item) * Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here. */ -void LegacyPeer::handleHandshakeMessage(const QVariant &msg) +void LegacyPeer::handleHandshakeMessage(const QVariant& msg) { QVariantMap m = msg.toMap(); @@ -173,7 +169,7 @@ void LegacyPeer::handleHandshakeMessage(const QVariant &msg) else if (msgType == "ClientInitAck") { // FIXME only in compat mode - uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt + uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt if (ver < clientNeedsProtocol) { emit protocolVersionMismatch((int)ver, (int)clientNeedsProtocol); return; @@ -192,7 +188,12 @@ void LegacyPeer::handleHandshakeMessage(const QVariant &msg) else if (msgType == "CoreSetupData") { QVariantMap map = m["SetupData"].toMap(); - handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap())); + handle(SetupData(map["AdminUser"].toString(), + map["AdminPasswd"].toString(), + map["Backend"].toString(), + map["ConnectionProperties"].toMap(), + map["Authenticator"].toString(), + map["AuthProperties"].toMap())); } else if (msgType == "CoreSetupReject") { @@ -225,8 +226,8 @@ void LegacyPeer::handleHandshakeMessage(const QVariant &msg) } } - -void LegacyPeer::dispatch(const RegisterClient &msg) { +void LegacyPeer::dispatch(const RegisterClient& msg) +{ QVariantMap m; m["MsgType"] = "ClientInit"; m["Features"] = static_cast(msg.features.toLegacyFeatures()); @@ -246,8 +247,8 @@ void LegacyPeer::dispatch(const RegisterClient &msg) { writeMessage(m); } - -void LegacyPeer::dispatch(const ClientDenied &msg) { +void LegacyPeer::dispatch(const ClientDenied& msg) +{ QVariantMap m; m["MsgType"] = "ClientInitReject"; m["Error"] = msg.errorString; @@ -255,8 +256,8 @@ void LegacyPeer::dispatch(const ClientDenied &msg) { writeMessage(m); } - -void LegacyPeer::dispatch(const ClientRegistered &msg) { +void LegacyPeer::dispatch(const ClientRegistered& msg) +{ QVariantMap m; m["MsgType"] = "ClientInitAck"; if (hasFeature(Quassel::Feature::ExtendedFeatures)) { @@ -273,7 +274,7 @@ void LegacyPeer::dispatch(const ClientRegistered &msg) { // FIXME only in compat mode m["ProtocolVersion"] = protocolVersion; m["SupportSsl"] = msg.sslSupported; - m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler + m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler // This is only used for display by really old v10 clients (pre-0.5), and we no longer set this m["CoreInfo"] = QString(); @@ -283,8 +284,7 @@ void LegacyPeer::dispatch(const ClientRegistered &msg) { writeMessage(m); } - -void LegacyPeer::dispatch(const SetupData &msg) +void LegacyPeer::dispatch(const SetupData& msg) { QVariantMap map; map["AdminUser"] = msg.adminUser; @@ -302,8 +302,7 @@ void LegacyPeer::dispatch(const SetupData &msg) writeMessage(m); } - -void LegacyPeer::dispatch(const SetupFailed &msg) +void LegacyPeer::dispatch(const SetupFailed& msg) { QVariantMap m; m["MsgType"] = "CoreSetupReject"; @@ -312,8 +311,7 @@ void LegacyPeer::dispatch(const SetupFailed &msg) writeMessage(m); } - -void LegacyPeer::dispatch(const SetupDone &msg) +void LegacyPeer::dispatch(const SetupDone& msg) { Q_UNUSED(msg) @@ -323,8 +321,7 @@ void LegacyPeer::dispatch(const SetupDone &msg) writeMessage(m); } - -void LegacyPeer::dispatch(const Login &msg) +void LegacyPeer::dispatch(const Login& msg) { QVariantMap m; m["MsgType"] = "ClientLogin"; @@ -334,8 +331,7 @@ void LegacyPeer::dispatch(const Login &msg) writeMessage(m); } - -void LegacyPeer::dispatch(const LoginFailed &msg) +void LegacyPeer::dispatch(const LoginFailed& msg) { QVariantMap m; m["MsgType"] = "ClientLoginReject"; @@ -344,8 +340,7 @@ void LegacyPeer::dispatch(const LoginFailed &msg) writeMessage(m); } - -void LegacyPeer::dispatch(const LoginSuccess &msg) +void LegacyPeer::dispatch(const LoginSuccess& msg) { Q_UNUSED(msg) @@ -355,8 +350,7 @@ void LegacyPeer::dispatch(const LoginSuccess &msg) writeMessage(m); } - -void LegacyPeer::dispatch(const SessionState &msg) +void LegacyPeer::dispatch(const SessionState& msg) { QVariantMap m; m["MsgType"] = "SessionInit"; @@ -370,10 +364,9 @@ void LegacyPeer::dispatch(const SessionState &msg) writeMessage(m); } - /*** Standard messages ***/ -void LegacyPeer::handlePackedFunc(const QVariant &packedFunc) +void LegacyPeer::handlePackedFunc(const QVariant& packedFunc) { QVariantList params(packedFunc.toList()); @@ -385,99 +378,94 @@ void LegacyPeer::handlePackedFunc(const QVariant &packedFunc) // TODO: make sure that this is a valid request type RequestType requestType = (RequestType)params.takeFirst().value(); switch (requestType) { - case Sync: { - if (params.count() < 3) { - qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params; - return; - } - QByteArray className = params.takeFirst().toByteArray(); - QString objectName = params.takeFirst().toString(); - QByteArray slotName = params.takeFirst().toByteArray(); - handle(Protocol::SyncMessage(className, objectName, slotName, params)); - break; + case Sync: { + if (params.count() < 3) { + qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params; + return; } - case RpcCall: { - if (params.empty()) { - qWarning() << Q_FUNC_INFO << "Received empty RPC call!"; - return; - } - QByteArray slotName = params.takeFirst().toByteArray(); - handle(Protocol::RpcCall(slotName, params)); - break; + QByteArray className = params.takeFirst().toByteArray(); + QString objectName = params.takeFirst().toString(); + QByteArray slotName = params.takeFirst().toByteArray(); + handle(Protocol::SyncMessage(className, objectName, slotName, params)); + break; + } + case RpcCall: { + if (params.empty()) { + qWarning() << Q_FUNC_INFO << "Received empty RPC call!"; + return; } - case InitRequest: { - if (params.count() != 2) { - qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params; - return; - } - QByteArray className = params[0].toByteArray(); - QString objectName = params[1].toString(); - handle(Protocol::InitRequest(className, objectName)); - break; + QByteArray slotName = params.takeFirst().toByteArray(); + handle(Protocol::RpcCall(slotName, params)); + break; + } + case InitRequest: { + if (params.count() != 2) { + qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params; + return; } - case InitData: { - if (params.count() != 3) { - qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params; - return; - } - QByteArray className = params[0].toByteArray(); - QString objectName = params[1].toString(); - QVariantMap initData = params[2].toMap(); - - // we need to special-case IrcUsersAndChannels here, since the format changed - if (className == "Network") - fromLegacyIrcUsersAndChannels(initData); - handle(Protocol::InitData(className, objectName, initData)); - break; + QByteArray className = params[0].toByteArray(); + QString objectName = params[1].toString(); + handle(Protocol::InitRequest(className, objectName)); + break; + } + case InitData: { + if (params.count() != 3) { + qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params; + return; } - case HeartBeat: { - if (params.count() != 1) { - qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; - return; - } - // The legacy protocol would only send a QTime, no QDateTime - // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation - QDateTime dateTime = QDateTime::currentDateTime().toUTC(); - dateTime.setTime(params[0].toTime()); - handle(Protocol::HeartBeat(dateTime)); - break; + QByteArray className = params[0].toByteArray(); + QString objectName = params[1].toString(); + QVariantMap initData = params[2].toMap(); + + // we need to special-case IrcUsersAndChannels here, since the format changed + if (className == "Network") + fromLegacyIrcUsersAndChannels(initData); + handle(Protocol::InitData(className, objectName, initData)); + break; + } + case HeartBeat: { + if (params.count() != 1) { + qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; + return; } - case HeartBeatReply: { - if (params.count() != 1) { - qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; - return; - } - // The legacy protocol would only send a QTime, no QDateTime - // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation - QDateTime dateTime = QDateTime::currentDateTime().toUTC(); - dateTime.setTime(params[0].toTime()); - handle(Protocol::HeartBeatReply(dateTime)); - break; + // The legacy protocol would only send a QTime, no QDateTime + // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation + QDateTime dateTime = QDateTime::currentDateTime().toUTC(); + dateTime.setTime(params[0].toTime()); + handle(Protocol::HeartBeat(dateTime)); + break; + } + case HeartBeatReply: { + if (params.count() != 1) { + qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params; + return; } - + // The legacy protocol would only send a QTime, no QDateTime + // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation + QDateTime dateTime = QDateTime::currentDateTime().toUTC(); + dateTime.setTime(params[0].toTime()); + handle(Protocol::HeartBeatReply(dateTime)); + break; + } } } - -void LegacyPeer::dispatch(const Protocol::SyncMessage &msg) +void LegacyPeer::dispatch(const Protocol::SyncMessage& msg) { dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params); } - -void LegacyPeer::dispatch(const Protocol::RpcCall &msg) +void LegacyPeer::dispatch(const Protocol::RpcCall& msg) { dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params); } - -void LegacyPeer::dispatch(const Protocol::InitRequest &msg) +void LegacyPeer::dispatch(const Protocol::InitRequest& msg) { dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName); } - -void LegacyPeer::dispatch(const Protocol::InitData &msg) +void LegacyPeer::dispatch(const Protocol::InitData& msg) { // We need to special-case IrcUsersAndChannels, as the format changed if (msg.className == "Network") { @@ -489,72 +477,67 @@ void LegacyPeer::dispatch(const Protocol::InitData &msg) dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData); } - -void LegacyPeer::dispatch(const Protocol::HeartBeat &msg) +void LegacyPeer::dispatch(const Protocol::HeartBeat& msg) { dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time()); } - -void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg) +void LegacyPeer::dispatch(const Protocol::HeartBeatReply& msg) { dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time()); } - -void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc) +void LegacyPeer::dispatchPackedFunc(const QVariantList& packedFunc) { writeMessage(QVariant(packedFunc)); } - // Handle the changed format for Network's initData // cf. Network::initIrcUsersAndChannels() -void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData) +void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap& initData) { - const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap(); + const QVariantMap& legacyMap = initData["IrcUsersAndChannels"].toMap(); QVariantMap newMap; QHash users; - foreach(const QVariant &v, legacyMap["users"].toMap().values()) { - const QVariantMap &map = v.toMap(); - foreach(const QString &key, map.keys()) + foreach (const QVariant& v, legacyMap["users"].toMap().values()) { + const QVariantMap& map = v.toMap(); + foreach (const QString& key, map.keys()) users[key] << map[key]; } QVariantMap userMap; - foreach(const QString &key, users.keys()) + foreach (const QString& key, users.keys()) userMap[key] = users[key]; newMap["Users"] = userMap; QHash channels; - foreach(const QVariant &v, legacyMap["channels"].toMap().values()) { - const QVariantMap &map = v.toMap(); - foreach(const QString &key, map.keys()) + foreach (const QVariant& v, legacyMap["channels"].toMap().values()) { + const QVariantMap& map = v.toMap(); + foreach (const QString& key, map.keys()) channels[key] << map[key]; } QVariantMap channelMap; - foreach(const QString &key, channels.keys()) + foreach (const QString& key, channels.keys()) channelMap[key] = channels[key]; newMap["Channels"] = channelMap; initData["IrcUsersAndChannels"] = newMap; } - -void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData) +void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap& initData) { - const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap(); + const QVariantMap& usersAndChannels = initData["IrcUsersAndChannels"].toMap(); QVariantMap legacyMap; // toMap() and toList() are cheap, so no need to copy to a hash QVariantMap userMap; - const QVariantMap &users = usersAndChannels["Users"].toMap(); + const QVariantMap& users = usersAndChannels["Users"].toMap(); - int size = users["nick"].toList().size(); // we know this key exists - for(int i = 0; i < size; i++) { + int size = users["nick"].toList().size(); // we know this key exists + for (int i = 0; i < size; i++) { QVariantMap map; - foreach(const QString &key, users.keys()) + foreach (const QString& key, users.keys()) map[key] = users[key].toList().at(i); QString hostmask = QString("%1!%2@%3").arg(map["nick"].toString(), map["user"].toString(), map["host"].toString()); userMap[hostmask.toLower()] = map; @@ -562,12 +545,12 @@ void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData) legacyMap["users"] = userMap; QVariantMap channelMap; - const QVariantMap &channels = usersAndChannels["Channels"].toMap(); + const QVariantMap& channels = usersAndChannels["Channels"].toMap(); size = channels["name"].toList().size(); - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { QVariantMap map; - foreach(const QString &key, channels.keys()) + foreach (const QString& key, channels.keys()) map[key] = channels[key].toList().at(i); channelMap[map["name"].toString().toLower()] = map; } diff --git a/src/common/protocols/legacy/legacypeer.h b/src/common/protocols/legacy/legacypeer.h index 47cadcc1..35114c47 100644 --- a/src/common/protocols/legacy/legacypeer.h +++ b/src/common/protocols/legacy/legacypeer.h @@ -28,7 +28,8 @@ class LegacyPeer : public RemotePeer Q_OBJECT public: - enum RequestType { + enum RequestType + { Sync = 1, RpcCall, InitRequest, @@ -37,46 +38,46 @@ public: HeartBeatReply }; - LegacyPeer(AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr); + LegacyPeer(AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent = nullptr); Protocol::Type protocol() const override { return Protocol::LegacyProtocol; } QString protocolName() const override { return "the legacy protocol"; } - void setSignalProxy(SignalProxy *proxy) override; + void setSignalProxy(SignalProxy* proxy) override; - void dispatch(const Protocol::RegisterClient &msg) override; - void dispatch(const Protocol::ClientDenied &msg) override; - void dispatch(const Protocol::ClientRegistered &msg) override; - void dispatch(const Protocol::SetupData &msg) override; - void dispatch(const Protocol::SetupFailed &msg) override; - void dispatch(const Protocol::SetupDone &msg) override; - void dispatch(const Protocol::Login &msg) override; - void dispatch(const Protocol::LoginFailed &msg) override; - void dispatch(const Protocol::LoginSuccess &msg) override; - void dispatch(const Protocol::SessionState &msg) override; + void dispatch(const Protocol::RegisterClient& msg) override; + void dispatch(const Protocol::ClientDenied& msg) override; + void dispatch(const Protocol::ClientRegistered& msg) override; + void dispatch(const Protocol::SetupData& msg) override; + void dispatch(const Protocol::SetupFailed& msg) override; + void dispatch(const Protocol::SetupDone& msg) override; + void dispatch(const Protocol::Login& msg) override; + void dispatch(const Protocol::LoginFailed& msg) override; + void dispatch(const Protocol::LoginSuccess& msg) override; + void dispatch(const Protocol::SessionState& msg) override; - void dispatch(const Protocol::SyncMessage &msg) override; - void dispatch(const Protocol::RpcCall &msg) override; - void dispatch(const Protocol::InitRequest &msg) override; - void dispatch(const Protocol::InitData &msg) override; + void dispatch(const Protocol::SyncMessage& msg) override; + void dispatch(const Protocol::RpcCall& msg) override; + void dispatch(const Protocol::InitRequest& msg) override; + void dispatch(const Protocol::InitData& msg) override; - void dispatch(const Protocol::HeartBeat &msg) override; - void dispatch(const Protocol::HeartBeatReply &msg) override; + void dispatch(const Protocol::HeartBeat& msg) override; + void dispatch(const Protocol::HeartBeatReply& msg) override; signals: - void protocolError(const QString &errorString); + void protocolError(const QString& errorString); private: using RemotePeer::writeMessage; - void writeMessage(const QVariant &item); - void processMessage(const QByteArray &msg) override; + void writeMessage(const QVariant& item); + void processMessage(const QByteArray& msg) override; - void handleHandshakeMessage(const QVariant &msg); - void handlePackedFunc(const QVariant &packedFunc); - void dispatchPackedFunc(const QVariantList &packedFunc); + void handleHandshakeMessage(const QVariant& msg); + void handlePackedFunc(const QVariant& packedFunc); + void dispatchPackedFunc(const QVariantList& packedFunc); - void toLegacyIrcUsersAndChannels(QVariantMap &initData); - void fromLegacyIrcUsersAndChannels(QVariantMap &initData); + void toLegacyIrcUsersAndChannels(QVariantMap& initData); + void fromLegacyIrcUsersAndChannels(QVariantMap& initData); bool _useCompression; }; diff --git a/src/common/quassel.cpp b/src/common/quassel.cpp index 14d6a639..fdcd0527 100644 --- a/src/common/quassel.cpp +++ b/src/common/quassel.cpp @@ -61,7 +61,6 @@ Quassel::Quassel() #endif } - void Quassel::init(RunMode runMode) { _runMode = runMode; @@ -85,13 +84,11 @@ void Quassel::init(RunMode runMode) Network::setDefaultCodecForDecoding("ISO-8859-15"); } - -Logger *Quassel::logger() const +Logger* Quassel::logger() const { return _logger; } - void Quassel::registerQuitHandler(QuitHandler handler) { instance()->_quitHandlers.emplace_back(std::move(handler)); @@ -108,34 +105,31 @@ void Quassel::quit() } else { // Note: We expect one of the registered handlers to call QCoreApplication::quit() - for (auto &&handler : _quitHandlers) { + for (auto&& handler : _quitHandlers) { handler(); } } } } - void Quassel::registerReloadHandler(ReloadHandler handler) { instance()->_reloadHandlers.emplace_back(std::move(handler)); } - bool Quassel::reloadConfig() { bool result{true}; - for (auto &&handler : _reloadHandlers) { + for (auto&& handler : _reloadHandlers) { result = result && handler(); } return result; } - //! Register our custom types with Qt's Meta Object System. /** This makes them available for QVariant and in signals/slots, among other things. -* -*/ + * + */ void Quassel::registerMetaTypes() { // Complex types @@ -181,7 +175,6 @@ void Quassel::registerMetaTypes() } } - void Quassel::setupEnvironment() { // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This @@ -191,7 +184,7 @@ void Quassel::setupEnvironment() #ifdef Q_OS_UNIX QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS")); if (xdgDataVar.isEmpty()) - xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults + xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts); @@ -203,7 +196,8 @@ void Quassel::setupEnvironment() xdgDirs.append(appDir); // Also append apps/quassel, this is only for QIconLoader to find icons there xdgDirs.append(appDir + "/apps/quassel"); - } else + } + else xdgDirs.append(appDir); // build directory is always the last fallback xdgDirs.removeDuplicates(); @@ -212,7 +206,6 @@ void Quassel::setupEnvironment() #endif } - void Quassel::setupBuildInfo() { BuildInfo buildInfo; @@ -222,7 +215,7 @@ void Quassel::setupBuildInfo() buildInfo.organizationName = "Quassel Project"; buildInfo.organizationDomain = "quassel-irc.org"; - buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed + buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed buildInfo.baseVersion = QUASSEL_VERSION_STRING; buildInfo.generatedVersion = GIT_DESCRIBE; @@ -244,9 +237,7 @@ void Quassel::setupBuildInfo() if (buildInfo.generatedVersion.isEmpty()) { if (!buildInfo.commitHash.isEmpty()) { // dist version - buildInfo.plainVersionString = QString{"v%1 (dist-%2)"} - .arg(buildInfo.baseVersion) - .arg(buildInfo.commitHash.left(7)); + buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}.arg(buildInfo.baseVersion).arg(buildInfo.commitHash.left(7)); buildInfo.fancyVersionString = QString{"v%1 (dist-%2)"} .arg(buildInfo.baseVersion) .arg(buildInfo.commitHash.left(7)) @@ -279,13 +270,11 @@ void Quassel::setupBuildInfo() instance()->_buildInfo = std::move(buildInfo); } - -const Quassel::BuildInfo &Quassel::buildInfo() +const Quassel::BuildInfo& Quassel::buildInfo() { return instance()->_buildInfo; } - void Quassel::setupSignalHandling() { #ifndef Q_OS_WIN @@ -296,7 +285,6 @@ void Quassel::setupSignalHandling() connect(_signalWatcher, &AbstractSignalWatcher::handleSignal, this, &Quassel::handleSignal); } - void Quassel::handleSignal(AbstractSignalWatcher::Action action) { switch (action) { @@ -323,12 +311,11 @@ void Quassel::handleSignal(AbstractSignalWatcher::Action action) } } - -Quassel::RunMode Quassel::runMode() { +Quassel::RunMode Quassel::runMode() +{ return instance()->_runMode; } - void Quassel::setupCliParser() { QList options; @@ -339,7 +326,9 @@ void Quassel::setupCliParser() options += {{"c", "configdir"}, tr("Specify the directory holding the client configuration."), tr("path")}; } else { - options += {{"c", "configdir"}, tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."), tr("path")}; + options += {{"c", "configdir"}, + tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."), + tr("path")}; } // Client options @@ -361,10 +350,15 @@ void Quassel::setupCliParser() {"select-backend", tr("Switch storage backend (migrating data if possible)."), tr("backendidentifier")}, {"select-authenticator", tr("Select authentication backend."), tr("authidentifier")}, {"add-user", tr("Starts an interactive session to add a new core user.")}, - {"change-userpass", tr("Starts an interactive session to change the password of the user identified by ."), tr("username")}, + {"change-userpass", + tr("Starts an interactive session to change the password of the user identified by ."), + tr("username")}, {"strict-ident", tr("Use users' quasselcore username as ident reply. Ignores each user's configured ident setting.")}, {"ident-daemon", tr("Enable internal ident daemon.")}, - {"ident-port", tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."), tr("port"), "10113"}, + {"ident-port", + tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."), + tr("port"), + "10113"}, {"oidentd", tr("Enable oidentd integration. In most cases you should also enable --strict-ident.")}, {"oidentd-conffile", tr("Set path to oidentd configuration file."), tr("file")}, #ifdef HAVE_SSL @@ -408,24 +402,22 @@ void Quassel::setupCliParser() _cliParser.process(*QCoreApplication::instance()); } - -QString Quassel::optionValue(const QString &key) +QString Quassel::optionValue(const QString& key) { return instance()->_cliParser.value(key); } - -bool Quassel::isOptionSet(const QString &key) +bool Quassel::isOptionSet(const QString& key) { return instance()->_cliParser.isSet(key); } - -const QString &Quassel::coreDumpFileName() +const QString& Quassel::coreDumpFileName() { if (_coreDumpFileName.isEmpty()) { QDir configDir(configDirPath()); - _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm"))); + _coreDumpFileName = configDir.absoluteFilePath( + QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm"))); QFile dumpFile(_coreDumpFileName); dumpFile.open(QIODevice::Append); QTextStream dumpStream(&dumpFile); @@ -437,7 +429,6 @@ const QString &Quassel::coreDumpFileName() return _coreDumpFileName; } - QString Quassel::configDirPath() { if (!instance()->_configDirPath.isEmpty()) @@ -453,12 +444,12 @@ QString Quassel::configDirPath() path = QDir::homePath() + "/Library/Application Support/Quassel/"; #else // We abuse QSettings to find us a sensible path on the other platforms -# ifdef Q_OS_WIN +# ifdef Q_OS_WIN // don't use the registry QSettings::Format format = QSettings::IniFormat; -# else +# else QSettings::Format format = QSettings::NativeFormat; -# endif +# endif QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName); QFileInfo fileInfo(s.fileName()); path = fileInfo.dir().absolutePath(); @@ -482,7 +473,6 @@ QString Quassel::configDirPath() return path; } - QStringList Quassel::dataDirPaths() { if (!instance()->_dataDirPaths.isEmpty()) @@ -494,11 +484,9 @@ QStringList Quassel::dataDirPaths() QStringList dataDirNames; #ifdef Q_OS_WIN dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/" - << qgetenv("APPDATA") + QCoreApplication::organizationDomain() - << QCoreApplication::applicationDirPath(); + << qgetenv("APPDATA") + QCoreApplication::organizationDomain() << QCoreApplication::applicationDirPath(); #elif defined Q_OS_MAC - dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" - << QCoreApplication::applicationDirPath(); + dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" << QCoreApplication::applicationDirPath(); #else // Linux et al @@ -512,7 +500,8 @@ QStringList Quassel::dataDirPaths() // Now whatever is configured through XDG_DATA_DIRS QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS")); if (xdgDataDirs.isEmpty()) - dataDirNames << "/usr/local/share" << "/usr/share"; + dataDirNames << "/usr/local/share" + << "/usr/share"; else dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts); @@ -547,11 +536,10 @@ QStringList Quassel::dataDirPaths() return dataDirNames; } - -QString Quassel::findDataFilePath(const QString &fileName) +QString Quassel::findDataFilePath(const QString& fileName) { QStringList dataDirs = dataDirPaths(); - foreach(QString dataDir, dataDirs) { + foreach (QString dataDir, dataDirs) { QString path = dataDir + fileName; if (QFile::exists(path)) return path; @@ -559,22 +547,20 @@ QString Quassel::findDataFilePath(const QString &fileName) return QString(); } - QStringList Quassel::scriptDirPaths() { QStringList res(configDirPath() + "scripts/"); - foreach(QString path, dataDirPaths()) - res << path + "scripts/"; + foreach (QString path, dataDirPaths()) + res << path + "scripts/"; return res; } - QString Quassel::translationDirPath() { if (instance()->_translationDirPath.isEmpty()) { // We support only one translation dir; fallback mechanisms wouldn't work else. // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered. - foreach(const QString &dir, dataDirPaths()) { + foreach (const QString& dir, dataDirPaths()) { if (QFile::exists(dir + "translations/")) { instance()->_translationDirPath = dir + "translations/"; break; @@ -586,11 +572,10 @@ QString Quassel::translationDirPath() return instance()->_translationDirPath; } - -void Quassel::loadTranslation(const QLocale &locale) +void Quassel::loadTranslation(const QLocale& locale) { - auto *qtTranslator = QCoreApplication::instance()->findChild("QtTr"); - auto *quasselTranslator = QCoreApplication::instance()->findChild("QuasselTr"); + auto* qtTranslator = QCoreApplication::instance()->findChild("QtTr"); + auto* quasselTranslator = QCoreApplication::instance()->findChild("QuasselTr"); if (qtTranslator) qApp->removeTranslator(qtTranslator); @@ -623,7 +608,6 @@ void Quassel::loadTranslation(const QLocale &locale) qApp->installTranslator(qtTranslator); } - // ---- Quassel::Features --------------------------------------------------------------------------------------------- Quassel::Features::Features() @@ -635,14 +619,13 @@ Quassel::Features::Features() _features.resize(featureEnum.keyCount(), true); // enable all known features to true } - -Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures) +Quassel::Features::Features(const QStringList& features, LegacyFeatures legacyFeatures) { // TODO Qt5: Use QMetaEnum::fromType() auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature")); _features.resize(featureEnum.keyCount(), false); - for (auto &&feature : features) { + for (auto&& feature : features) { int i = featureEnum.keyToValue(qPrintable(feature)); if (i >= 0) { _features[i] = true; @@ -655,7 +638,7 @@ Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFe if (legacyFeatures) { // TODO Qt5: Use QMetaEnum::fromType() auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature")); - for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) { + for (quint32 mask = 0x0001; mask <= 0x8000; mask <<= 1) { if (static_cast(legacyFeatures) & mask) { int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask)); if (i >= 0) { @@ -666,14 +649,12 @@ Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFe } } - bool Quassel::Features::isEnabled(Feature feature) const { auto i = static_cast(feature); return i < _features.size() ? _features[i] : false; } - QStringList Quassel::Features::toStringList(bool enabled) const { // Check if any feature is enabled @@ -693,7 +674,6 @@ QStringList Quassel::Features::toStringList(bool enabled) const return result; } - Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const { // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4) @@ -713,7 +693,6 @@ Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const return static_cast(result); } - QStringList Quassel::Features::unknownFeatures() const { return _unknownFeatures; diff --git a/src/common/quassel.h b/src/common/quassel.h index fd1dfd79..60976222 100644 --- a/src/common/quassel.h +++ b/src/common/quassel.h @@ -46,22 +46,24 @@ class COMMON_EXPORT Quassel : public QObject, public Singleton Q_OBJECT public: - enum RunMode { + enum RunMode + { Monolithic, ClientOnly, CoreOnly }; - struct BuildInfo { - QString fancyVersionString; // clickable rev - QString plainVersionString; // no tag + struct BuildInfo + { + QString fancyVersionString; // clickable rev + QString plainVersionString; // no tag QString baseVersion; QString generatedVersion; QString commitHash; QString commitDate; - uint protocolVersion; // deprecated + uint protocolVersion; // deprecated QString applicationName; QString coreApplicationName; @@ -83,7 +85,8 @@ public: * * @sa Feature */ - enum class LegacyFeature : quint32 { + enum class LegacyFeature : quint32 + { SynchronizedMarkerLine = 0x0001, SaslAuthentication = 0x0002, SaslExternal = 0x0004, @@ -116,28 +119,29 @@ public: * * This list should be cleaned up after every protocol break, as we can assume them to be present then. */ - enum class Feature : uint32_t { + enum class Feature : uint32_t + { SynchronizedMarkerLine, SaslAuthentication, SaslExternal, HideInactiveNetworks, - PasswordChange, ///< Remote password change - CapNegotiation, ///< IRCv3 capability negotiation, account tracking - VerifyServerSSL, ///< IRC server SSL validation - CustomRateLimits, ///< IRC server custom message rate limits - AwayFormatTimestamp, ///< Timestamp formatting in away (e.g. %%hh:mm%%) - Authenticators, ///< Whether or not the core supports auth backends - BufferActivitySync, ///< Sync buffer activity status - CoreSideHighlights, ///< Core-Side highlight configuration and matching - SenderPrefixes, ///< Show prefixes for senders in backlog - RemoteDisconnect, ///< Allow this peer to be remotely disconnected - ExtendedFeatures, ///< Extended features - LongTime, ///< Serialize time as 64-bit values - RichMessages, ///< Real Name and Avatar URL in backlog - BacklogFilterType, ///< BacklogManager supports filtering backlog by MessageType - EcdsaCertfpKeys, ///< ECDSA keys for CertFP in identities - LongMessageId, ///< 64-bit IDs for messages - SyncedCoreInfo, ///< CoreInfo dynamically updated using signals + PasswordChange, ///< Remote password change + CapNegotiation, ///< IRCv3 capability negotiation, account tracking + VerifyServerSSL, ///< IRC server SSL validation + CustomRateLimits, ///< IRC server custom message rate limits + AwayFormatTimestamp, ///< Timestamp formatting in away (e.g. %%hh:mm%%) + Authenticators, ///< Whether or not the core supports auth backends + BufferActivitySync, ///< Sync buffer activity status + CoreSideHighlights, ///< Core-Side highlight configuration and matching + SenderPrefixes, ///< Show prefixes for senders in backlog + RemoteDisconnect, ///< Allow this peer to be remotely disconnected + ExtendedFeatures, ///< Extended features + LongTime, ///< Serialize time as 64-bit values + RichMessages, ///< Real Name and Avatar URL in backlog + BacklogFilterType, ///< BacklogManager supports filtering backlog by MessageType + EcdsaCertfpKeys, ///< ECDSA keys for CertFP in identities + LongMessageId, ///< 64-bit IDs for messages + SyncedCoreInfo, ///< CoreInfo dynamically updated using signals }; Q_ENUMS(Feature) @@ -152,42 +156,42 @@ public: * * @returns The Logger instance */ - Logger *logger() const; + Logger* logger() const; static void setupBuildInfo(); - static const BuildInfo &buildInfo(); + static const BuildInfo& buildInfo(); static RunMode runMode(); static QString configDirPath(); //! Returns a list of data directory paths /** There are several locations for applications to install their data files in. On Unix, - * a common location is /usr/share; others include $PREFIX/share and additional directories - * specified in the env variable XDG_DATA_DIRS. - * \return A list of directory paths to look for data files in - */ + * a common location is /usr/share; others include $PREFIX/share and additional directories + * specified in the env variable XDG_DATA_DIRS. + * \return A list of directory paths to look for data files in + */ static QStringList dataDirPaths(); //! Searches for a data file in the possible data directories /** Data files can reside in $DATA_DIR/apps/quassel, where $DATA_DIR is one of the directories - * returned by \sa dataDirPaths(). - * \Note With KDE integration enabled, files are searched (only) in KDE's appdata dirs. - * \return The full path to the data file if found; a null QString else - */ - static QString findDataFilePath(const QString &filename); + * returned by \sa dataDirPaths(). + * \Note With KDE integration enabled, files are searched (only) in KDE's appdata dirs. + * \return The full path to the data file if found; a null QString else + */ + static QString findDataFilePath(const QString& filename); static QString translationDirPath(); //! Returns a list of directories we look for scripts in /** We look for a subdirectory named "scripts" in the configdir and in all datadir paths. - * \return A list of directory paths containing executable scripts for /exec - */ + * \return A list of directory paths containing executable scripts for /exec + */ static QStringList scriptDirPaths(); - static void loadTranslation(const QLocale &locale); + static void loadTranslation(const QLocale& locale); - static QString optionValue(const QString &option); - static bool isOptionSet(const QString &option); + static QString optionValue(const QString& option); + static bool isOptionSet(const QString& option); using ReloadHandler = std::function; @@ -205,7 +209,7 @@ public: */ static void registerQuitHandler(QuitHandler quitHandler); - const QString &coreDumpFileName(); + const QString& coreDumpFileName(); public slots: /** @@ -216,7 +220,7 @@ public slots: void quit(); signals: - void messageLogged(const QDateTime &timeStamp, const QString &msg); + void messageLogged(const QDateTime& timeStamp, const QString& msg); private: void registerMetaTypes(); @@ -234,7 +238,7 @@ private: */ bool reloadConfig(); - void logBacktrace(const QString &filename); + void logBacktrace(const QString& filename); private slots: void handleSignal(AbstractSignalWatcher::Action action); @@ -251,8 +255,8 @@ private: QCommandLineParser _cliParser; - Logger *_logger; - AbstractSignalWatcher *_signalWatcher{nullptr}; + Logger* _logger; + AbstractSignalWatcher* _signalWatcher{nullptr}; std::vector _reloadHandlers; std::vector _quitHandlers; @@ -287,7 +291,7 @@ public: * @param legacyFeatures Holds a bit-wise combination of LegacyFeature flag values, which are each added to the list of * features represented by this Features instance. */ - Features(const QStringList &features, LegacyFeatures legacyFeatures); + Features(const QStringList& features, LegacyFeatures legacyFeatures); /** * Check if a given feature is marked as enabled in this Features instance. diff --git a/src/common/remotepeer.cpp b/src/common/remotepeer.cpp index c3ad24f0..0541856b 100644 --- a/src/common/remotepeer.cpp +++ b/src/common/remotepeer.cpp @@ -18,15 +18,14 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include - #include #include +#include #ifdef HAVE_SSL -# include +# include #else -# include +# include #endif #include "remotepeer.h" @@ -34,17 +33,18 @@ using namespace Protocol; -const quint32 maxMessageSize = 64 * 1024 * 1024; // This is uncompressed size. 64 MB should be enough for any sort of initData or backlog chunk - -RemotePeer::RemotePeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent) - : Peer(authHandler, parent), - _socket(socket), - _compressor(new Compressor(socket, level, this)), - _signalProxy(nullptr), - _heartBeatTimer(new QTimer(this)), - _heartBeatCount(0), - _lag(0), - _msgSize(0) +const quint32 maxMessageSize = 64 * 1024 + * 1024; // This is uncompressed size. 64 MB should be enough for any sort of initData or backlog chunk + +RemotePeer::RemotePeer(::AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent) + : Peer(authHandler, parent) + , _socket(socket) + , _compressor(new Compressor(socket, level, this)) + , _signalProxy(nullptr) + , _heartBeatTimer(new QTimer(this)) + , _heartBeatCount(0) + , _lag(0) + , _msgSize(0) { socket->setParent(this); connect(socket, &QAbstractSocket::stateChanged, this, &RemotePeer::onSocketStateChanged); @@ -52,7 +52,7 @@ RemotePeer::RemotePeer(::AuthHandler *authHandler, QTcpSocket *socket, Compresso connect(socket, &QAbstractSocket::disconnected, this, &Peer::disconnected); #ifdef HAVE_SSL - auto *sslSocket = qobject_cast(socket); + auto* sslSocket = qobject_cast(socket); if (sslSocket) { connect(sslSocket, &QSslSocket::encrypted, this, [this]() { emit secureStateChanged(true); }); } @@ -64,7 +64,6 @@ RemotePeer::RemotePeer(::AuthHandler *authHandler, QTcpSocket *socket, Compresso connect(_heartBeatTimer, &QTimer::timeout, this, &RemotePeer::sendHeartBeat); } - void RemotePeer::onSocketStateChanged(QAbstractSocket::SocketState state) { if (state == QAbstractSocket::ClosingState) { @@ -72,19 +71,16 @@ void RemotePeer::onSocketStateChanged(QAbstractSocket::SocketState state) } } - void RemotePeer::onSocketError(QAbstractSocket::SocketError error) { emit socketError(error, socket()->errorString()); } - void RemotePeer::onCompressionError(Compressor::Error error) { close(QString("Compression error %1").arg(error)); } - QString RemotePeer::description() const { if (socket()) @@ -109,14 +105,12 @@ quint16 RemotePeer::port() const return 0; } - -::SignalProxy *RemotePeer::signalProxy() const +::SignalProxy* RemotePeer::signalProxy() const { return _signalProxy; } - -void RemotePeer::setSignalProxy(::SignalProxy *proxy) +void RemotePeer::setSignalProxy(::SignalProxy* proxy) { if (proxy == _signalProxy) return; @@ -140,10 +134,9 @@ void RemotePeer::setSignalProxy(::SignalProxy *proxy) } } - void RemotePeer::changeHeartBeatInterval(int secs) { - if(secs <= 0) + if (secs <= 0) _heartBeatTimer->stop(); else { _heartBeatTimer->setInterval(secs * 1000); @@ -151,26 +144,23 @@ void RemotePeer::changeHeartBeatInterval(int secs) } } - int RemotePeer::lag() const { return _lag; } - -QTcpSocket *RemotePeer::socket() const +QTcpSocket* RemotePeer::socket() const { return _socket; } - bool RemotePeer::isSecure() const { if (socket()) { if (isLocal()) return true; #ifdef HAVE_SSL - auto *sslSocket = qobject_cast(socket()); + auto* sslSocket = qobject_cast(socket()); if (sslSocket && sslSocket->isEncrypted()) return true; #endif @@ -178,7 +168,6 @@ bool RemotePeer::isSecure() const return false; } - bool RemotePeer::isLocal() const { if (socket()) { @@ -188,14 +177,12 @@ bool RemotePeer::isLocal() const return false; } - bool RemotePeer::isOpen() const { return socket() && socket()->state() == QTcpSocket::ConnectedState; } - -void RemotePeer::close(const QString &reason) +void RemotePeer::close(const QString& reason) { if (!reason.isEmpty()) { qWarning() << "Disconnecting:" << reason; @@ -206,7 +193,6 @@ void RemotePeer::close(const QString &reason) } } - void RemotePeer::onReadyRead() { QByteArray msg; @@ -221,8 +207,7 @@ void RemotePeer::onReadyRead() } } - -bool RemotePeer::readMessage(QByteArray &msg) +bool RemotePeer::readMessage(QByteArray& msg) { if (_msgSize == 0) { if (_compressor->bytesAvailable() < 4) @@ -259,33 +244,29 @@ bool RemotePeer::readMessage(QByteArray &msg) return true; } - -void RemotePeer::writeMessage(const QByteArray &msg) +void RemotePeer::writeMessage(const QByteArray& msg) { auto size = qToBigEndian(msg.size()); _compressor->write((const char*)&size, 4, Compressor::NoFlush); _compressor->write(msg.constData(), msg.size()); } - -void RemotePeer::handle(const HeartBeat &heartBeat) +void RemotePeer::handle(const HeartBeat& heartBeat) { dispatch(HeartBeatReply(heartBeat.timestamp)); } - -void RemotePeer::handle(const HeartBeatReply &heartBeatReply) +void RemotePeer::handle(const HeartBeatReply& heartBeatReply) { _heartBeatCount = 0; emit lagUpdated(heartBeatReply.timestamp.msecsTo(QDateTime::currentDateTime().toUTC()) / 2); } - void RemotePeer::sendHeartBeat() { if (signalProxy()->maxHeartBeatCount() > 0 && _heartBeatCount >= signalProxy()->maxHeartBeatCount()) { - qWarning() << "Disconnecting peer:" << description() - << "(didn't receive a heartbeat for over" << _heartBeatCount *_heartBeatTimer->interval() / 1000 << "seconds)"; + qWarning() << "Disconnecting peer:" << description() << "(didn't receive a heartbeat for over" + << _heartBeatCount * _heartBeatTimer->interval() / 1000 << "seconds)"; socket()->close(); _heartBeatTimer->stop(); return; diff --git a/src/common/remotepeer.h b/src/common/remotepeer.h index 5e064252..a8ca3b27 100644 --- a/src/common/remotepeer.h +++ b/src/common/remotepeer.h @@ -39,12 +39,12 @@ class COMMON_EXPORT RemotePeer : public Peer public: // import the virtuals from the baseclass - using Peer::handle; using Peer::dispatch; + using Peer::handle; - RemotePeer(AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr); + RemotePeer(AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent = nullptr); - void setSignalProxy(SignalProxy *proxy) override; + void setSignalProxy(SignalProxy* proxy) override; virtual QString protocolName() const = 0; QString description() const override; @@ -62,30 +62,30 @@ public: bool compressionEnabled() const; void setCompressionEnabled(bool enabled); - QTcpSocket *socket() const; + QTcpSocket* socket() const; public slots: - void close(const QString &reason = QString()) override; + void close(const QString& reason = QString()) override; signals: void transferProgress(int current, int max); - void socketError(QAbstractSocket::SocketError error, const QString &errorString); - void statusMessage(const QString &msg); + void socketError(QAbstractSocket::SocketError error, const QString& errorString); + void statusMessage(const QString& msg); // Only used by LegacyPeer void protocolVersionMismatch(int actual, int expected); protected: - SignalProxy *signalProxy() const override; + SignalProxy* signalProxy() const override; - void writeMessage(const QByteArray &msg); - virtual void processMessage(const QByteArray &msg) = 0; + void writeMessage(const QByteArray& msg); + virtual void processMessage(const QByteArray& msg) = 0; // These protocol messages get handled internally and won't reach SignalProxy - void handle(const Protocol::HeartBeat &heartBeat); - void handle(const Protocol::HeartBeatReply &heartBeatReply); - virtual void dispatch(const Protocol::HeartBeat &msg) = 0; - virtual void dispatch(const Protocol::HeartBeatReply &msg) = 0; + void handle(const Protocol::HeartBeat& heartBeat); + void handle(const Protocol::HeartBeatReply& heartBeatReply); + virtual void dispatch(const Protocol::HeartBeat& msg) = 0; + virtual void dispatch(const Protocol::HeartBeatReply& msg) = 0; protected slots: virtual void onSocketStateChanged(QAbstractSocket::SocketState state); @@ -99,13 +99,13 @@ private slots: void changeHeartBeatInterval(int secs); private: - bool readMessage(QByteArray &msg); + bool readMessage(QByteArray& msg); private: - QTcpSocket *_socket; - Compressor *_compressor; - SignalProxy *_signalProxy; - QTimer *_heartBeatTimer; + QTcpSocket* _socket; + Compressor* _compressor; + SignalProxy* _signalProxy; + QTimer* _heartBeatTimer; int _heartBeatCount; int _lag; quint32 _msgSize; diff --git a/src/common/serializers/serializers.cpp b/src/common/serializers/serializers.cpp index 50509407..21ca92fd 100644 --- a/src/common/serializers/serializers.cpp +++ b/src/common/serializers/serializers.cpp @@ -20,7 +20,7 @@ #include "serializers.h" -bool checkStreamValid(QDataStream &stream) +bool checkStreamValid(QDataStream& stream) { if (stream.status() != QDataStream::Ok) { qWarning() << "Peer sent corrupt data"; @@ -30,7 +30,7 @@ bool checkStreamValid(QDataStream &stream) return true; } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariantList &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariantList& data) { uint32_t size; if (!deserialize(stream, features, size)) @@ -48,7 +48,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariantMap &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariantMap& data) { uint32_t size; if (!deserialize(stream, features, size)) @@ -69,7 +69,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data) { Types::VariantType type; int8_t isNull; @@ -85,240 +85,241 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat name.chop(1); if (!deserialize(stream, features, data, Types::fromName(name))) return false; - } else { + } + else { if (!deserialize(stream, features, data, type)) return false; } return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::VariantType type) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::VariantType type) { switch (type) { - case Types::VariantType::Void: { - return true; - } - case Types::VariantType::Bool: { - bool content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::Int: { - int32_t content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::UInt: { - uint32_t content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QChar: { - QChar content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QVariantMap: { - QVariantMap content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QVariantList: { - QVariantList content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QString: { - QString content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QStringList: { - QStringList content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QByteArray: { - QByteArray content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QDate: { - QDate content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QTime: { - QTime content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QDateTime: { - QDateTime content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::Long: { - qlonglong content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::Short: { - int16_t content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::Char: { - int8_t content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::ULong: { - qulonglong content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::UShort: { - uint16_t content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::UChar: { - uint8_t content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - case Types::VariantType::QVariant: { - QVariant content; - if (!deserialize(stream, features, content)) - return false; - data = QVariant(content); - return true; - } - default: { - qWarning() << "Usertype should have been caught earlier already"; + case Types::VariantType::Void: { + return true; + } + case Types::VariantType::Bool: { + bool content; + if (!deserialize(stream, features, content)) return false; - } + data = QVariant(content); + return true; + } + case Types::VariantType::Int: { + int32_t content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::UInt: { + uint32_t content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QChar: { + QChar content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QVariantMap: { + QVariantMap content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QVariantList: { + QVariantList content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QString: { + QString content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QStringList: { + QStringList content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QByteArray: { + QByteArray content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QDate: { + QDate content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QTime: { + QTime content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QDateTime: { + QDateTime content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::Long: { + qlonglong content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::Short: { + int16_t content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::Char: { + int8_t content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::ULong: { + qulonglong content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::UShort: { + uint16_t content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::UChar: { + uint8_t content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + case Types::VariantType::QVariant: { + QVariant content; + if (!deserialize(stream, features, content)) + return false; + data = QVariant(content); + return true; + } + default: { + qWarning() << "Usertype should have been caught earlier already"; + return false; + } } } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::QuasselType type) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::QuasselType type) { switch (type) { - case Types::QuasselType::BufferId: { - BufferId content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::BufferInfo: { - BufferInfo content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::Identity: { - Identity content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::IdentityId: { - IdentityId content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::Message: { - Message content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::MsgId: { - MsgId content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::NetworkId: { - NetworkId content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::NetworkInfo: { - NetworkInfo content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::Network_Server: { - Network::Server content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - case Types::QuasselType::PeerPtr: { - PeerPtr content; - if (!deserialize(stream, features, content)) - return false; - data = qVariantFromValue(content); - return true; - } - default: { - qWarning() << "Invalid QType"; + case Types::QuasselType::BufferId: { + BufferId content; + if (!deserialize(stream, features, content)) return false; - } + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::BufferInfo: { + BufferInfo content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::Identity: { + Identity content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::IdentityId: { + IdentityId content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::Message: { + Message content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::MsgId: { + MsgId content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::NetworkId: { + NetworkId content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::NetworkInfo: { + NetworkInfo content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::Network_Server: { + Network::Server content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + case Types::QuasselType::PeerPtr: { + PeerPtr content; + if (!deserialize(stream, features, content)) + return false; + data = qVariantFromValue(content); + return true; + } + default: { + qWarning() << "Invalid QType"; + return false; + } } } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Types::VariantType &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Types::VariantType& data) { uint32_t raw; if (!deserialize(stream, features, raw)) @@ -327,7 +328,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QStringList &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QStringList& data) { uint32_t size; if (!deserialize(stream, features, size)) @@ -341,7 +342,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Network::Server &server) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Network::Server& server) { Q_UNUSED(features); QVariantMap serverMap; @@ -362,7 +363,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Identity &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Identity& data) { Q_UNUSED(features); QVariantMap raw; @@ -372,7 +373,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, NetworkInfo &info) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, NetworkInfo& info) { Q_UNUSED(features); QVariantMap i; @@ -406,14 +407,14 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, PeerPtr &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, PeerPtr& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QByteArray &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QByteArray& data) { Q_UNUSED(features); data.clear(); @@ -446,7 +447,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QString &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QString& data) { Q_UNUSED(features); uint32_t bytes = 0; @@ -482,7 +483,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat while (allocated < length) { int blockSize = std::min(step, length - allocated); data.resize(allocated + blockSize); - if (stream.readRawData(reinterpret_cast(data.data()) + allocated * 2, blockSize * 2) != blockSize * 2) { + if (stream.readRawData(reinterpret_cast(data.data()) + allocated * 2, blockSize * 2) != blockSize * 2) { data.clear(); qWarning() << "BufferUnderFlow while reading QString"; return false; @@ -490,7 +491,7 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat allocated += blockSize; } if ((stream.byteOrder() == QDataStream::BigEndian) != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) { - auto *rawData = reinterpret_cast(data.data()); + auto* rawData = reinterpret_cast(data.data()); while (length--) { *rawData = qbswap(*rawData); ++rawData; @@ -499,133 +500,133 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QChar &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QChar& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QDate &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QDate& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QTime &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QTime& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QDateTime &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QDateTime& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, int32_t &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, int32_t& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, uint32_t &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, uint32_t& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, int16_t &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, int16_t& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, uint16_t &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, uint16_t& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, int8_t &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, int8_t& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, uint8_t &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, uint8_t& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, qlonglong &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, qlonglong& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, qulonglong &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, qulonglong& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, bool &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, bool& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, BufferInfo &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, BufferInfo& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Message &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Message& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, NetworkId &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, NetworkId& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, IdentityId &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, IdentityId& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, BufferId &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, BufferId& data) { Q_UNUSED(features); stream >> data; return checkStreamValid(stream); } -bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, MsgId &data) +bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, MsgId& data) { Q_UNUSED(features); stream >> data; @@ -635,71 +636,81 @@ bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &feat Serializers::Types::VariantType Serializers::Types::variantType(Serializers::Types::QuasselType type) { switch (type) { - case QuasselType::BufferId: - return VariantType::UserType; - case QuasselType::BufferInfo: - return VariantType::UserType; - case QuasselType::Identity: - return VariantType::UserType; - case QuasselType::IdentityId: - return VariantType::UserType; - case QuasselType::Message: - return VariantType::UserType; - case QuasselType::MsgId: - return VariantType::UserType; - case QuasselType::NetworkId: - return VariantType::UserType; - case QuasselType::NetworkInfo: - return VariantType::UserType; - case QuasselType::Network_Server: - return VariantType::UserType; - case QuasselType::PeerPtr: - return VariantType::Long; - default: - return VariantType::UserType; + case QuasselType::BufferId: + return VariantType::UserType; + case QuasselType::BufferInfo: + return VariantType::UserType; + case QuasselType::Identity: + return VariantType::UserType; + case QuasselType::IdentityId: + return VariantType::UserType; + case QuasselType::Message: + return VariantType::UserType; + case QuasselType::MsgId: + return VariantType::UserType; + case QuasselType::NetworkId: + return VariantType::UserType; + case QuasselType::NetworkInfo: + return VariantType::UserType; + case QuasselType::Network_Server: + return VariantType::UserType; + case QuasselType::PeerPtr: + return VariantType::Long; + default: + return VariantType::UserType; } } QString Serializers::Types::toName(Serializers::Types::QuasselType type) { switch (type) { - case QuasselType::BufferId: - return QString("BufferId"); - case QuasselType::BufferInfo: - return QString("BufferInfo"); - case QuasselType::Identity: - return QString("Identity"); - case QuasselType::IdentityId: - return QString("IdentityId"); - case QuasselType::Message: - return QString("Message"); - case QuasselType::MsgId: - return QString("MsgId"); - case QuasselType::NetworkId: - return QString("NetworkId"); - case QuasselType::NetworkInfo: - return QString("NetworkInfo"); - case QuasselType::Network_Server: - return QString("Network::Server"); - case QuasselType::PeerPtr: - return QString("PeerPtr"); - default: - return QString("Invalid Type"); - } -} - -Serializers::Types::QuasselType Serializers::Types::fromName(::QByteArray &name) -{ - if (qstrcmp(name, "BufferId") == 0) return QuasselType::BufferId; - else if (qstrcmp(name, "BufferInfo") == 0) return QuasselType::BufferInfo; - else if (qstrcmp(name, "Identity") == 0) return QuasselType::Identity; - else if (qstrcmp(name, "IdentityId") == 0) return QuasselType::IdentityId; - else if (qstrcmp(name, "Message") == 0) return QuasselType::Message; - else if (qstrcmp(name, "MsgId") == 0) return QuasselType::MsgId; - else if (qstrcmp(name, "NetworkId") == 0) return QuasselType::NetworkId; - else if (qstrcmp(name, "NetworkInfo") == 0) return QuasselType::NetworkInfo; - else if (qstrcmp(name, "Network::Server") == 0) return QuasselType::Network_Server; - else if (qstrcmp(name, "PeerPtr") == 0) return QuasselType::PeerPtr; + case QuasselType::BufferId: + return QString("BufferId"); + case QuasselType::BufferInfo: + return QString("BufferInfo"); + case QuasselType::Identity: + return QString("Identity"); + case QuasselType::IdentityId: + return QString("IdentityId"); + case QuasselType::Message: + return QString("Message"); + case QuasselType::MsgId: + return QString("MsgId"); + case QuasselType::NetworkId: + return QString("NetworkId"); + case QuasselType::NetworkInfo: + return QString("NetworkInfo"); + case QuasselType::Network_Server: + return QString("Network::Server"); + case QuasselType::PeerPtr: + return QString("PeerPtr"); + default: + return QString("Invalid Type"); + } +} + +Serializers::Types::QuasselType Serializers::Types::fromName(::QByteArray& name) +{ + if (qstrcmp(name, "BufferId") == 0) + return QuasselType::BufferId; + else if (qstrcmp(name, "BufferInfo") == 0) + return QuasselType::BufferInfo; + else if (qstrcmp(name, "Identity") == 0) + return QuasselType::Identity; + else if (qstrcmp(name, "IdentityId") == 0) + return QuasselType::IdentityId; + else if (qstrcmp(name, "Message") == 0) + return QuasselType::Message; + else if (qstrcmp(name, "MsgId") == 0) + return QuasselType::MsgId; + else if (qstrcmp(name, "NetworkId") == 0) + return QuasselType::NetworkId; + else if (qstrcmp(name, "NetworkInfo") == 0) + return QuasselType::NetworkInfo; + else if (qstrcmp(name, "Network::Server") == 0) + return QuasselType::Network_Server; + else if (qstrcmp(name, "PeerPtr") == 0) + return QuasselType::PeerPtr; else { qWarning() << "Type name is not valid: " << name; return QuasselType::Invalid; diff --git a/src/common/serializers/serializers.h b/src/common/serializers/serializers.h index 61af769b..5f3dea88 100644 --- a/src/common/serializers/serializers.h +++ b/src/common/serializers/serializers.h @@ -33,85 +33,87 @@ #include "peer.h" namespace Serializers { - namespace Types { - enum class VariantType : quint32 { - Void = 0, - Bool = 1, - Int = 2, - UInt = 3, +namespace Types { +enum class VariantType : quint32 +{ + Void = 0, + Bool = 1, + Int = 2, + UInt = 3, - QChar = 7, - QVariantMap = 8, - QVariantList = 9, - QString = 10, - QStringList = 11, - QByteArray = 12, + QChar = 7, + QVariantMap = 8, + QVariantList = 9, + QString = 10, + QStringList = 11, + QByteArray = 12, - QDate = 14, - QTime = 15, - QDateTime = 16, + QDate = 14, + QTime = 15, + QDateTime = 16, - Long = 129, - Short = 130, - Char = 131, - ULong = 132, - UShort = 133, - UChar = 134, + Long = 129, + Short = 130, + Char = 131, + ULong = 132, + UShort = 133, + UChar = 134, - QVariant = 138, + QVariant = 138, - UserType = 127 - }; + UserType = 127 +}; - enum class QuasselType { - Invalid, - BufferId, - BufferInfo, - Identity, - IdentityId, - Message, - MsgId, - NetworkId, - NetworkInfo, - Network_Server, - PeerPtr - }; +enum class QuasselType +{ + Invalid, + BufferId, + BufferInfo, + Identity, + IdentityId, + Message, + MsgId, + NetworkId, + NetworkInfo, + Network_Server, + PeerPtr +}; - VariantType variantType(QuasselType type); - QString toName(QuasselType type); - Types::QuasselType fromName(::QByteArray &name); - } +VariantType variantType(QuasselType type); +QString toName(QuasselType type); +Types::QuasselType fromName(::QByteArray& name); +} // namespace Types - bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariantList &list); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariantMap &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::VariantType type); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::QuasselType type); - bool deserialize(QDataStream &stream, const Quassel::Features &features, bool &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, int8_t &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, uint8_t &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, int16_t &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, uint16_t &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, int32_t &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, uint32_t &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, qlonglong &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, qulonglong &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, Types::VariantType &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QChar &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QString &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QTime &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QDate &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QDateTime &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QByteArray &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, QStringList &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, Message &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, BufferInfo &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, BufferId &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, IdentityId &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, NetworkId &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, MsgId &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, PeerPtr &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, NetworkInfo &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, Identity &data); - bool deserialize(QDataStream &stream, const Quassel::Features &features, Network::Server &data); -} +bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariantList& list); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariantMap& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::VariantType type); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::QuasselType type); +bool deserialize(QDataStream& stream, const Quassel::Features& features, bool& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, int8_t& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, uint8_t& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, int16_t& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, uint16_t& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, int32_t& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, uint32_t& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, qlonglong& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, qulonglong& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, Types::VariantType& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QChar& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QString& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QTime& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QDate& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QDateTime& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QByteArray& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, QStringList& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, Message& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, BufferInfo& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, BufferId& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, IdentityId& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, NetworkId& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, MsgId& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, PeerPtr& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, NetworkInfo& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, Identity& data); +bool deserialize(QDataStream& stream, const Quassel::Features& features, Network::Server& data); +} // namespace Serializers diff --git a/src/common/settings.cpp b/src/common/settings.cpp index f157d357..b350e726 100644 --- a/src/common/settings.cpp +++ b/src/common/settings.cpp @@ -18,43 +18,42 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include - #include "settings.h" -const int VERSION = 1; /// Settings version for backwords/forwards incompatible changes +#include + +const int VERSION = 1; /// Settings version for backwords/forwards incompatible changes // This is used if no VersionMinor key exists, e.g. upgrading from a Quassel version before this // change. This shouldn't be increased from 1; instead, change the logic in Core::Core() and // QtUiApplication::init() to handle upgrading and downgrading. -const int VERSION_MINOR_INITIAL = 1; /// Initial settings version for compatible changes +const int VERSION_MINOR_INITIAL = 1; /// Initial settings version for compatible changes QHash Settings::_settingsCache; QHash Settings::_settingsKeyPersistedCache; QHash> Settings::_settingsChangeNotifier; #ifdef Q_OS_MAC -# define create_qsettings QSettings s(QCoreApplication::organizationDomain(), _appName) +# define create_qsettings QSettings s(QCoreApplication::organizationDomain(), _appName) #else -# define create_qsettings QSettings s(fileName(), format()) +# define create_qsettings QSettings s(fileName(), format()) #endif Settings::Settings(QString group, QString appName) - : _group(std::move(group)), _appName(std::move(appName)) + : _group(std::move(group)) + , _appName(std::move(appName)) {} - -void Settings::setGroup(QString group) { +void Settings::setGroup(QString group) +{ _group = std::move(group); } - -QString Settings::keyForNotify(const QString &key) const +QString Settings::keyForNotify(const QString& key) const { return key; } - uint Settings::version() const { // we don't cache this value, and we ignore the group @@ -68,7 +67,6 @@ uint Settings::version() const return ver; } - uint Settings::versionMinor() const { // Don't cache this value; ignore the group @@ -85,12 +83,12 @@ uint Settings::versionMinor() const // const_cast is ok, because setVersionMinor() doesn't actually change this instance const_cast(this)->setVersionMinor(VERSION_MINOR_INITIAL); return VERSION_MINOR_INITIAL; - } else { + } + else { return verMinor; } } - void Settings::setVersionMinor(const uint versionMinor) { // Don't cache this value; ignore the group @@ -99,7 +97,6 @@ void Settings::setVersionMinor(const uint versionMinor) s.setValue("Config/VersionMinor", versionMinor); } - QSettings::Format Settings::format() const { #ifdef Q_OS_WIN @@ -109,27 +106,24 @@ QSettings::Format Settings::format() const #endif } - bool Settings::sync() { create_qsettings; s.sync(); switch (s.status()) { - case QSettings::NoError: - return true; - default: - return false; + case QSettings::NoError: + return true; + default: + return false; } } - bool Settings::isWritable() const { create_qsettings; return s.isWritable(); } - QStringList Settings::allLocalKeys() const { create_qsettings; @@ -139,8 +133,7 @@ QStringList Settings::allLocalKeys() const return res; } - -QStringList Settings::localChildKeys(const QString &rootkey) const +QStringList Settings::localChildKeys(const QString& rootkey) const { QString g; if (rootkey.isEmpty()) @@ -155,8 +148,7 @@ QStringList Settings::localChildKeys(const QString &rootkey) const return res; } - -QStringList Settings::localChildGroups(const QString &rootkey) const +QStringList Settings::localChildGroups(const QString& rootkey) const { QString g; if (rootkey.isEmpty()) @@ -171,8 +163,7 @@ QStringList Settings::localChildGroups(const QString &rootkey) const return res; } - -void Settings::setLocalValue(const QString &key, const QVariant &data) +void Settings::setLocalValue(const QString& key, const QVariant& data) { QString normKey = normalizedKey(_group, key); create_qsettings; @@ -184,8 +175,7 @@ void Settings::setLocalValue(const QString &key, const QVariant &data) } } - -QVariant Settings::localValue(const QString &key, const QVariant &def) const +QVariant Settings::localValue(const QString& key, const QVariant& def) const { QString normKey = normalizedKey(_group, key); if (!isCached(normKey)) { @@ -203,8 +193,7 @@ QVariant Settings::localValue(const QString &key, const QVariant &def) const return def; } - -bool Settings::localKeyExists(const QString &key) const +bool Settings::localKeyExists(const QString& key) const { QString normKey = normalizedKey(_group, key); if (!isKeyPersistedCached(normKey)) { @@ -217,8 +206,7 @@ bool Settings::localKeyExists(const QString &key) const return cacheKeyPersisted(normKey); } - -void Settings::removeLocalKey(const QString &key) +void Settings::removeLocalKey(const QString& key) { create_qsettings; s.beginGroup(_group); @@ -236,67 +224,56 @@ void Settings::removeLocalKey(const QString &key) } } - QString Settings::fileName() const { - return Quassel::configDirPath() + _appName - + ((format() == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini")); + return Quassel::configDirPath() + _appName + ((format() == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini")); } - -QString Settings::normalizedKey(const QString &group, const QString &key) const +QString Settings::normalizedKey(const QString& group, const QString& key) const { if (group.isEmpty()) return key; return group + '/' + key; } - -void Settings::setCacheKeyPersisted(const QString &normKey, bool exists) const +void Settings::setCacheKeyPersisted(const QString& normKey, bool exists) const { _settingsKeyPersistedCache[normKey] = exists; } - -bool Settings::cacheKeyPersisted(const QString &normKey) const +bool Settings::cacheKeyPersisted(const QString& normKey) const { return _settingsKeyPersistedCache[normKey]; } - -bool Settings::isKeyPersistedCached(const QString &normKey) const +bool Settings::isKeyPersistedCached(const QString& normKey) const { return _settingsKeyPersistedCache.contains(normKey); } - -void Settings::setCacheValue(const QString &normKey, const QVariant &data) const +void Settings::setCacheValue(const QString& normKey, const QVariant& data) const { _settingsCache[normKey] = data; } - -QVariant Settings::cacheValue(const QString &normKey) const +QVariant Settings::cacheValue(const QString& normKey) const { return _settingsCache[normKey]; } - -bool Settings::isCached(const QString &normKey) const +bool Settings::isCached(const QString& normKey) const { return _settingsCache.contains(normKey); } - -SettingsChangeNotifier *Settings::notifier(const QString &normKey) const +SettingsChangeNotifier* Settings::notifier(const QString& normKey) const { if (!hasNotifier(normKey)) _settingsChangeNotifier[normKey] = std::make_shared(); return _settingsChangeNotifier[normKey].get(); } - -bool Settings::hasNotifier(const QString &normKey) const +bool Settings::hasNotifier(const QString& normKey) const { return _settingsChangeNotifier.contains(normKey); } diff --git a/src/common/settings.h b/src/common/settings.h index 64bc4620..a4653771 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -24,13 +24,13 @@ #include #include +#include #include #include #include #include #include -#include #include "quassel.h" @@ -39,22 +39,25 @@ class COMMON_EXPORT SettingsChangeNotifier : public QObject Q_OBJECT signals: - void valueChanged(const QVariant &newValue); + void valueChanged(const QVariant& newValue); private: friend class Settings; }; - class COMMON_EXPORT Settings { public: - enum Mode { Default, Custom }; + enum Mode + { + Default, + Custom + }; public: //! Calls the given slot on change of the given key template - void notify(const QString &key, const Receiver *receiver, Slot slot) const + void notify(const QString& key, const Receiver* receiver, Slot slot) const { static_assert(!std::is_same::value, "Old-style slots not supported"); QObject::connect(notifier(normalizedKey(_group, keyForNotify(key))), &SettingsChangeNotifier::valueChanged, receiver, slot); @@ -62,7 +65,7 @@ public: //! Sets up notification and calls the given slot to set the initial value template - void initAndNotify(const QString &key, const Receiver *receiver, Slot slot, const QVariant &defaultValue = {}) const + void initAndNotify(const QString& key, const Receiver* receiver, Slot slot, const QVariant& defaultValue = {}) const { notify(key, receiver, std::move(slot)); auto notifyKey = keyForNotify(key); @@ -127,14 +130,14 @@ protected: * @param key Key given to notify() * @returns Key that should be used for notfication */ - virtual QString keyForNotify(const QString &key) const; + virtual QString keyForNotify(const QString& key) const; virtual QStringList allLocalKeys() const; - virtual QStringList localChildKeys(const QString &rootkey = QString()) const; - virtual QStringList localChildGroups(const QString &rootkey = QString()) const; + virtual QStringList localChildKeys(const QString& rootkey = QString()) const; + virtual QStringList localChildGroups(const QString& rootkey = QString()) const; - virtual void setLocalValue(const QString &key, const QVariant &data); - virtual QVariant localValue(const QString &key, const QVariant &def = QVariant()) const; + virtual void setLocalValue(const QString& key, const QVariant& data); + virtual QVariant localValue(const QString& key, const QVariant& def = QVariant()) const; /** * Gets if a key exists in settings @@ -142,9 +145,9 @@ protected: * @param[in] key ID of local settings key * @returns True if key exists in settings, otherwise false */ - virtual bool localKeyExists(const QString &key) const; + virtual bool localKeyExists(const QString& key) const; - virtual void removeLocalKey(const QString &key); + virtual void removeLocalKey(const QString& key); QString _group; QString _appName; @@ -154,7 +157,7 @@ private: QString fileName() const; - QString normalizedKey(const QString &group, const QString &key) const; + QString normalizedKey(const QString& group, const QString& key) const; /** * Update the cache of whether or not a given settings key persists on disk @@ -162,7 +165,7 @@ private: * @param normKey Normalized settings key ID * @param exists True if key exists, otherwise false */ - void setCacheKeyPersisted(const QString &normKey, bool exists) const; + void setCacheKeyPersisted(const QString& normKey, bool exists) const; /** * Check if the given settings key ID persists on disk (rather than being a default value) @@ -172,7 +175,7 @@ private: * @param normKey Normalized settings key ID * @return True if key exists and persistence has been cached, otherwise false */ - bool cacheKeyPersisted(const QString &normKey) const; + bool cacheKeyPersisted(const QString& normKey) const; /** * Check if the persistence of the given settings key ID has been cached @@ -180,20 +183,20 @@ private: * @param normKey Normalized settings key ID * @return True if key persistence has been cached, otherwise false */ - bool isKeyPersistedCached(const QString &normKey) const; + bool isKeyPersistedCached(const QString& normKey) const; - void setCacheValue(const QString &normKey, const QVariant &data) const; + void setCacheValue(const QString& normKey, const QVariant& data) const; - QVariant cacheValue(const QString &normKey) const; + QVariant cacheValue(const QString& normKey) const; - bool isCached(const QString &normKey) const; + bool isCached(const QString& normKey) const; - SettingsChangeNotifier *notifier(const QString &normKey) const; + SettingsChangeNotifier* notifier(const QString& normKey) const; - bool hasNotifier(const QString &normKey) const; + bool hasNotifier(const QString& normKey) const; private: - static QHash _settingsCache; ///< Cached settings values - static QHash _settingsKeyPersistedCache; ///< Cached settings key exists on disk + static QHash _settingsCache; ///< Cached settings values + static QHash _settingsKeyPersistedCache; ///< Cached settings key exists on disk static QHash> _settingsChangeNotifier; }; diff --git a/src/common/signalproxy.cpp b/src/common/signalproxy.cpp index a629551c..9e47dd38 100644 --- a/src/common/signalproxy.cpp +++ b/src/common/signalproxy.cpp @@ -27,60 +27,68 @@ #include #ifdef HAVE_SSL - #include +# include #endif -#include "signalproxy.h" - #include "peer.h" #include "protocol.h" +#include "signalproxy.h" #include "syncableobject.h" -#include "util.h" #include "types.h" +#include "util.h" using namespace Protocol; class RemovePeerEvent : public QEvent { public: - RemovePeerEvent(Peer *peer) : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)), peer(peer) {} - Peer *peer; + RemovePeerEvent(Peer* peer) + : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)) + , peer(peer) + {} + Peer* peer; }; - // ================================================== // SignalRelay // ================================================== class SignalProxy::SignalRelay : public QObject { -/* Q_OBJECT is not necessary or even allowed, because we implement - qt_metacall ourselves (and don't use any other features of the meta - object system) -*/ + /* Q_OBJECT is not necessary or even allowed, because we implement + qt_metacall ourselves (and don't use any other features of the meta + object system) + */ public: - SignalRelay(SignalProxy *parent) : QObject(parent), _proxy(parent) {} - inline SignalProxy *proxy() const { return _proxy; } + SignalRelay(SignalProxy* parent) + : QObject(parent) + , _proxy(parent) + {} + inline SignalProxy* proxy() const { return _proxy; } - int qt_metacall(QMetaObject::Call _c, int _id, void **_a) override; + int qt_metacall(QMetaObject::Call _c, int _id, void** _a) override; - void attachSignal(QObject *sender, int signalId, const QByteArray &funcName); - void detachSignal(QObject *sender, int signalId = -1); + void attachSignal(QObject* sender, int signalId, const QByteArray& funcName); + void detachSignal(QObject* sender, int signalId = -1); private: - struct Signal { - QObject *sender{nullptr}; + struct Signal + { + QObject* sender{nullptr}; int signalId{-1}; QByteArray signature; - Signal(QObject *sender, int sigId, QByteArray signature) : sender(sender), signalId(sigId), signature(std::move(signature)) {} + Signal(QObject* sender, int sigId, QByteArray signature) + : sender(sender) + , signalId(sigId) + , signature(std::move(signature)) + {} Signal() = default; }; - SignalProxy *_proxy; + SignalProxy* _proxy; QHash _slots; }; - -void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QByteArray &funcName) +void SignalProxy::SignalRelay::attachSignal(QObject* sender, int signalId, const QByteArray& funcName) { // we ride without safetybelts here... all checking for valid method etc pp has to be done by the caller // all connected methodIds are offset by the standard methodCount of QObject @@ -106,8 +114,7 @@ void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QMetaObject::connect(sender, signalId, this, QObject::staticMetaObject.methodCount() + slotId); } - -void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId) +void SignalProxy::SignalRelay::detachSignal(QObject* sender, int signalId) { QHash::iterator slotIter = _slots.begin(); while (slotIter != _slots.end()) { @@ -122,8 +129,7 @@ void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId) } } - -int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void** _a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) @@ -131,23 +137,26 @@ int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void ** if (_c == QMetaObject::InvokeMetaMethod) { if (_slots.contains(_id)) { - QObject *caller = sender(); + QObject* caller = sender(); - SignalProxy::ExtendedMetaObject *eMeta = proxy()->extendedMetaObject(caller->metaObject()); + SignalProxy::ExtendedMetaObject* eMeta = proxy()->extendedMetaObject(caller->metaObject()); Q_ASSERT(eMeta); - const Signal &signal = _slots[_id]; + const Signal& signal = _slots[_id]; QVariantList params; - const QList &argTypes = eMeta->argTypes(signal.signalId); + const QList& argTypes = eMeta->argTypes(signal.signalId); for (int i = 0; i < argTypes.size(); i++) { if (argTypes[i] == 0) { - qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(caller->metaObject()->className()).arg(caller->metaObject()->method(signal.signalId).methodSignature().constData()); + qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" + << QString("%1::%2") + .arg(caller->metaObject()->className()) + .arg(caller->metaObject()->method(signal.signalId).methodSignature().constData()); qWarning() << " - make sure all your data types are known by the Qt MetaSystem"; return _id; } - params << QVariant(argTypes[i], _a[i+1]); + params << QVariant(argTypes[i], _a[i + 1]); } if (proxy()->_restrictMessageTarget) { @@ -155,7 +164,8 @@ int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void ** if (peer != nullptr) proxy()->dispatch(peer, RpcCall(signal.signature, params)); } - } else + } + else proxy()->dispatch(RpcCall(signal.signature, params)); } _id -= _slots.count(); @@ -163,38 +173,35 @@ int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void ** return _id; } - // ================================================== // SignalProxy // ================================================== namespace { -thread_local SignalProxy *_current{nullptr}; +thread_local SignalProxy* _current{nullptr}; } -SignalProxy::SignalProxy(QObject *parent) +SignalProxy::SignalProxy(QObject* parent) : QObject(parent) { setProxyMode(Client); init(); } - -SignalProxy::SignalProxy(ProxyMode mode, QObject *parent) +SignalProxy::SignalProxy(ProxyMode mode, QObject* parent) : QObject(parent) { setProxyMode(mode); init(); } - SignalProxy::~SignalProxy() { QHash::iterator classIter = _syncSlave.begin(); while (classIter != _syncSlave.end()) { ObjectId::iterator objIter = classIter->begin(); while (objIter != classIter->end()) { - SyncableObject *obj = objIter.value(); + SyncableObject* obj = objIter.value(); objIter = classIter->erase(objIter); obj->stopSynchronize(this); } @@ -207,13 +214,11 @@ SignalProxy::~SignalProxy() _current = nullptr; } - -SignalProxy *SignalProxy::current() +SignalProxy* SignalProxy::current() { return _current; } - void SignalProxy::setProxyMode(ProxyMode mode) { if (!_peerMap.empty()) { @@ -240,18 +245,13 @@ void SignalProxy::init() updateSecureState(); } - -void SignalProxy::initServer() -{ -} - +void SignalProxy::initServer() {} void SignalProxy::initClient() { - attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray,QString,QString))); + attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray, QString, QString))); } - void SignalProxy::setHeartBeatInterval(int secs) { if (_heartBeatInterval != secs) { @@ -260,7 +260,6 @@ void SignalProxy::setHeartBeatInterval(int secs) } } - void SignalProxy::setMaxHeartBeatCount(int max) { if (_maxHeartBeatCount != max) { @@ -269,8 +268,7 @@ void SignalProxy::setMaxHeartBeatCount(int max) } } - -bool SignalProxy::addPeer(Peer *peer) +bool SignalProxy::addPeer(Peer* peer) { if (!peer) return false; @@ -313,19 +311,17 @@ bool SignalProxy::addPeer(Peer *peer) return true; } - void SignalProxy::removeAllPeers() { Q_ASSERT(proxyMode() == Server || peerCount() <= 1); // wee need to copy that list since we modify it in the loop - QList peers = _peerMap.values(); + QList peers = _peerMap.values(); for (auto peer : peers) { removePeer(peer); } } - -void SignalProxy::removePeer(Peer *peer) +void SignalProxy::removePeer(Peer* peer) { if (!peer) { qWarning() << Q_FUNC_INFO << "Trying to remove a null peer!"; @@ -357,45 +353,40 @@ void SignalProxy::removePeer(Peer *peer) emit disconnected(); } - void SignalProxy::removePeerBySender() { - removePeer(qobject_cast(sender())); + removePeer(qobject_cast(sender())); } - -void SignalProxy::renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname) +void SignalProxy::renameObject(const SyncableObject* obj, const QString& newname, const QString& oldname) { if (proxyMode() == Client) return; - const QMetaObject *meta = obj->syncMetaObject(); + const QMetaObject* meta = obj->syncMetaObject(); const QByteArray className(meta->className()); objectRenamed(className, newname, oldname); dispatch(RpcCall("__objectRenamed__", QVariantList() << className << newname << oldname)); } - -void SignalProxy::objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname) +void SignalProxy::objectRenamed(const QByteArray& classname, const QString& newname, const QString& oldname) { if (_syncSlave.contains(classname) && _syncSlave[classname].contains(oldname) && oldname != newname) { - SyncableObject *obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname); + SyncableObject* obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname); requestInit(obj); } } - -const QMetaObject *SignalProxy::metaObject(const QObject *obj) +const QMetaObject* SignalProxy::metaObject(const QObject* obj) { - if (const auto *syncObject = qobject_cast(obj)) + if (const auto* syncObject = qobject_cast(obj)) return syncObject->syncMetaObject(); else return obj->metaObject(); } - -SignalProxy::ExtendedMetaObject *SignalProxy::extendedMetaObject(const QMetaObject *meta) const +SignalProxy::ExtendedMetaObject* SignalProxy::extendedMetaObject(const QMetaObject* meta) const { if (_extendedMetaObjects.contains(meta)) return _extendedMetaObjects[meta]; @@ -403,8 +394,7 @@ SignalProxy::ExtendedMetaObject *SignalProxy::extendedMetaObject(const QMetaObje return nullptr; } - -SignalProxy::ExtendedMetaObject *SignalProxy::createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts) +SignalProxy::ExtendedMetaObject* SignalProxy::createExtendedMetaObject(const QMetaObject* meta, bool checkConflicts) { if (!_extendedMetaObjects.contains(meta)) { _extendedMetaObjects[meta] = new ExtendedMetaObject(meta, checkConflicts); @@ -412,10 +402,9 @@ SignalProxy::ExtendedMetaObject *SignalProxy::createExtendedMetaObject(const QMe return _extendedMetaObjects[meta]; } - -bool SignalProxy::attachSignal(QObject *sender, const char *signal, const QByteArray &sigName) +bool SignalProxy::attachSignal(QObject* sender, const char* signal, const QByteArray& sigName) { - const QMetaObject *meta = sender->metaObject(); + const QMetaObject* meta = sender->metaObject(); QByteArray sig(meta->normalizedSignature(signal).mid(1)); int methodId = meta->indexOfMethod(sig.constData()); if (methodId == -1 || meta->method(methodId).methodType() != QMetaMethod::Signal) { @@ -431,10 +420,9 @@ bool SignalProxy::attachSignal(QObject *sender, const char *signal, const QByteA return true; } - -bool SignalProxy::attachSlot(const QByteArray &sigName, QObject *recv, const char *slot) +bool SignalProxy::attachSlot(const QByteArray& sigName, QObject* recv, const char* slot) { - const QMetaObject *meta = recv->metaObject(); + const QMetaObject* meta = recv->metaObject(); int methodId = meta->indexOfMethod(meta->normalizedSignature(slot).mid(1)); if (methodId == -1 || meta->method(methodId).methodType() == QMetaMethod::Method) { qWarning() << "SignalProxy::attachSlot(): No such slot" << slot; @@ -451,8 +439,7 @@ bool SignalProxy::attachSlot(const QByteArray &sigName, QObject *recv, const cha return true; } - -void SignalProxy::synchronize(SyncableObject *obj) +void SignalProxy::synchronize(SyncableObject* obj) { createExtendedMetaObject(obj, true); @@ -474,8 +461,7 @@ void SignalProxy::synchronize(SyncableObject *obj) obj->synchronize(this); } - -void SignalProxy::detachObject(QObject *obj) +void SignalProxy::detachObject(QObject* obj) { // Don't try to connect SignalProxy from itself on shutdown if (obj != this) { @@ -484,14 +470,12 @@ void SignalProxy::detachObject(QObject *obj) } } - -void SignalProxy::detachSignals(QObject *sender) +void SignalProxy::detachSignals(QObject* sender) { _signalRelay->detachSignal(sender); } - -void SignalProxy::detachSlots(QObject *receiver) +void SignalProxy::detachSlots(QObject* receiver) { SlotHash::iterator slotIter = _attachedSlots.begin(); while (slotIter != _attachedSlots.end()) { @@ -503,8 +487,7 @@ void SignalProxy::detachSlots(QObject *receiver) } } - -void SignalProxy::stopSynchronize(SyncableObject *obj) +void SignalProxy::stopSynchronize(SyncableObject* obj) { // we can't use a className here, since it might be effed up, if we receive the call as a result of a decon // gladly the objectName() is still valid. So we have only to iterate over the classes not each instance! *sigh* @@ -519,18 +502,16 @@ void SignalProxy::stopSynchronize(SyncableObject *obj) obj->stopSynchronize(this); } - template -void SignalProxy::dispatch(const T &protoMessage) +void SignalProxy::dispatch(const T& protoMessage) { for (auto&& peer : _peerMap.values()) { dispatch(peer, protoMessage); } } - template -void SignalProxy::dispatch(Peer *peer, const T &protoMessage) +void SignalProxy::dispatch(Peer* peer, const T& protoMessage) { _targetPeer = peer; @@ -542,19 +523,20 @@ void SignalProxy::dispatch(Peer *peer, const T &protoMessage) _targetPeer = nullptr; } - -void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage) +void SignalProxy::handle(Peer* peer, const SyncMessage& syncMessage) { if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) { - qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName) + qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:") + .arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName) << syncMessage.params; return; } - SyncableObject *receiver = _syncSlave[syncMessage.className][syncMessage.objectName]; - ExtendedMetaObject *eMeta = extendedMetaObject(receiver); + SyncableObject* receiver = _syncSlave[syncMessage.className][syncMessage.objectName]; + ExtendedMetaObject* eMeta = extendedMetaObject(receiver); if (!eMeta->slotMap().contains(syncMessage.slotName)) { - qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName) + qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:") + .arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName) << syncMessage.params; return; } @@ -591,87 +573,89 @@ void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage) invokeSlot(receiver, eMeta->updatedRemotelyId()); } - -void SignalProxy::handle(Peer *peer, const InitRequest &initRequest) +void SignalProxy::handle(Peer* peer, const InitRequest& initRequest) { - if (!_syncSlave.contains(initRequest.className)) { - qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:" - << initRequest.className; + if (!_syncSlave.contains(initRequest.className)) { + qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:" << initRequest.className; return; } if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) { - qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:" - << initRequest.className << initRequest.objectName; + qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:" << initRequest.className + << initRequest.objectName; return; } - SyncableObject *obj = _syncSlave[initRequest.className][initRequest.objectName]; + SyncableObject* obj = _syncSlave[initRequest.className][initRequest.objectName]; _targetPeer = peer; peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj))); _targetPeer = nullptr; } - -void SignalProxy::handle(Peer *peer, const InitData &initData) +void SignalProxy::handle(Peer* peer, const InitData& initData) { Q_UNUSED(peer) if (!_syncSlave.contains(initData.className)) { - qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:" - << initData.className; + qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:" << initData.className; return; } if (!_syncSlave[initData.className].contains(initData.objectName)) { - qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:" - << initData.className << initData.objectName; + qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:" << initData.className << initData.objectName; return; } - SyncableObject *obj = _syncSlave[initData.className][initData.objectName]; + SyncableObject* obj = _syncSlave[initData.className][initData.objectName]; setInitData(obj, initData.initData); } - -void SignalProxy::handle(Peer *peer, const RpcCall &rpcCall) +void SignalProxy::handle(Peer* peer, const RpcCall& rpcCall) { - QObject *receiver; + QObject* receiver; int methodId; SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName); while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) { receiver = (*slot).first; methodId = (*slot).second; if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) { - ExtendedMetaObject *eMeta = extendedMetaObject(receiver); + ExtendedMetaObject* eMeta = extendedMetaObject(receiver); qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData()); } ++slot; } } - -bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, QVariant &returnValue, Peer *peer) +bool SignalProxy::invokeSlot(QObject* receiver, int methodId, const QVariantList& params, QVariant& returnValue, Peer* peer) { - ExtendedMetaObject *eMeta = extendedMetaObject(receiver); + ExtendedMetaObject* eMeta = extendedMetaObject(receiver); const QList args = eMeta->argTypes(methodId); - const int numArgs = params.count() < args.count() - ? params.count() - : args.count(); + const int numArgs = params.count() < args.count() ? params.count() : args.count(); if (eMeta->minArgCount(methodId) > params.count()) { qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId); return false; } - void *_a[] = { nullptr, // return type... - nullptr, nullptr, nullptr, nullptr, nullptr, // and 10 args - that's the max size qt can handle with signals and slots - nullptr, nullptr, nullptr, nullptr, nullptr }; + void* _a[] = {nullptr, // return type... + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, // and 10 args - that's the max size qt can handle with signals and slots + nullptr, + nullptr, + nullptr, + nullptr, + nullptr}; // check for argument compatibility and build params array for (int i = 0; i < numArgs; i++) { if (!params[i].isValid()) { - qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method" << QString("%1::%2()").arg(receiver->metaObject()->className()).arg(receiver->metaObject()->method(methodId).methodSignature().constData()); + qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method" + << QString("%1::%2()") + .arg(receiver->metaObject()->className()) + .arg(receiver->metaObject()->method(methodId).methodSignature().constData()); qWarning() << " - make sure all your data types are known by the Qt MetaSystem"; return false; } @@ -680,37 +664,34 @@ bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList return false; } - _a[i+1] = const_cast(params[i].constData()); + _a[i + 1] = const_cast(params[i].constData()); } if (returnValue.type() != QVariant::Invalid) - _a[0] = const_cast(returnValue.constData()); + _a[0] = const_cast(returnValue.constData()); - Qt::ConnectionType type = QThread::currentThread() == receiver->thread() - ? Qt::DirectConnection - : Qt::QueuedConnection; + Qt::ConnectionType type = QThread::currentThread() == receiver->thread() ? Qt::DirectConnection : Qt::QueuedConnection; if (type == Qt::DirectConnection) { _sourcePeer = peer; auto result = receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0; _sourcePeer = nullptr; return result; - } else { + } + else { qWarning() << "Queued Connections are not implemented yet"; // note to self: qmetaobject.cpp:990 ff return false; } } - -bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, Peer *peer) +bool SignalProxy::invokeSlot(QObject* receiver, int methodId, const QVariantList& params, Peer* peer) { QVariant ret; return invokeSlot(receiver, methodId, params, ret, peer); } - -void SignalProxy::requestInit(SyncableObject *obj) +void SignalProxy::requestInit(SyncableObject* obj) { if (proxyMode() == Server || obj->isInitialized()) return; @@ -718,14 +699,12 @@ void SignalProxy::requestInit(SyncableObject *obj) dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName())); } - -QVariantMap SignalProxy::initData(SyncableObject *obj) const +QVariantMap SignalProxy::initData(SyncableObject* obj) const { return obj->toVariantMap(); } - -void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties) +void SignalProxy::setInitData(SyncableObject* obj, const QVariantMap& properties) { if (obj->isInitialized()) return; @@ -735,12 +714,11 @@ void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId()); } - -void SignalProxy::customEvent(QEvent *event) +void SignalProxy::customEvent(QEvent* event) { switch ((int)event->type()) { case RemovePeerEvent: { - auto *e = static_cast< ::RemovePeerEvent *>(event); + auto* e = static_cast<::RemovePeerEvent*>(event); removePeer(e->peer); event->accept(); break; @@ -752,26 +730,26 @@ void SignalProxy::customEvent(QEvent *event) } } - -void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap) +void SignalProxy::sync_call__(const SyncableObject* obj, SignalProxy::ProxyMode modeType, const char* funcname, va_list ap) { // qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname; if (modeType != _proxyMode) return; - ExtendedMetaObject *eMeta = extendedMetaObject(obj); + ExtendedMetaObject* eMeta = extendedMetaObject(obj); QVariantList params; - const QList &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname))); + const QList& argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname))); for (int i = 0; i < argTypes.size(); i++) { if (argTypes[i] == 0) { - qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname); + qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" + << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname); qWarning() << " - make sure all your data types are known by the Qt MetaSystem"; return; } - params << QVariant(argTypes[i], va_arg(ap, void *)); + params << QVariant(argTypes[i], va_arg(ap, void*)); } if (_restrictMessageTarget) { @@ -779,22 +757,21 @@ void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode if (peer != nullptr) dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params)); } - } else + } + else dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params)); } - -void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason) +void SignalProxy::disconnectDevice(QIODevice* dev, const QString& reason) { if (!reason.isEmpty()) qWarning() << qPrintable(reason); - auto *sock = qobject_cast(dev); + auto* sock = qobject_cast(dev); if (sock) qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString()); dev->close(); } - void SignalProxy::dumpProxyStats() { QString mode; @@ -804,8 +781,8 @@ void SignalProxy::dumpProxyStats() mode = "Client"; int slaveCount = 0; - foreach(ObjectId oid, _syncSlave.values()) - slaveCount += oid.count(); + foreach (ObjectId oid, _syncSlave.values()) + slaveCount += oid.count(); qDebug() << this; qDebug() << " Proxy Mode:" << mode; @@ -814,13 +791,12 @@ void SignalProxy::dumpProxyStats() qDebug() << "number of Classes cached:" << _extendedMetaObjects.count(); } - void SignalProxy::updateSecureState() { bool wasSecure = _secure; _secure = !_peerMap.isEmpty(); - for (auto peer : _peerMap.values()) { + for (auto peer : _peerMap.values()) { _secure &= peer->isSecure(); } @@ -828,9 +804,10 @@ void SignalProxy::updateSecureState() emit secureStateChanged(_secure); } -QVariantList SignalProxy::peerData() { +QVariantList SignalProxy::peerData() +{ QVariantList result; - for (auto &&peer : _peerMap.values()) { + for (auto&& peer : _peerMap.values()) { QVariantMap data; data["id"] = peer->id(); data["clientVersion"] = peer->clientVersion(); @@ -847,7 +824,8 @@ QVariantList SignalProxy::peerData() { return result; } -Peer *SignalProxy::peerById(int peerId) { +Peer* SignalProxy::peerById(int peerId) +{ // We use ::value() here instead of the [] operator because the latter has the side-effect // of automatically inserting a null value with the passed key into the map. See // https://doc.qt.io/qt-5/qhash.html#operator-5b-5d and https://doc.qt.io/qt-5/qhash.html#value. @@ -867,28 +845,32 @@ void SignalProxy::restrictTargetPeers(QSet peers, std::function c _restrictedTargets = previousRestrictedTargets; } -Peer *SignalProxy::sourcePeer() { +Peer* SignalProxy::sourcePeer() +{ return _sourcePeer; } -void SignalProxy::setSourcePeer(Peer *sourcePeer) { +void SignalProxy::setSourcePeer(Peer* sourcePeer) +{ _sourcePeer = sourcePeer; } -Peer *SignalProxy::targetPeer() { +Peer* SignalProxy::targetPeer() +{ return _targetPeer; } -void SignalProxy::setTargetPeer(Peer *targetPeer) { +void SignalProxy::setTargetPeer(Peer* targetPeer) +{ _targetPeer = targetPeer; } // ================================================== // ExtendedMetaObject // ================================================== -SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts) - : _meta(meta), - _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()")) +SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject* meta, bool checkConflicts) + : _meta(meta) + , _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()")) { for (int i = 0; i < _meta->methodCount(); i++) { if (_meta->method(i).methodType() != QMetaMethod::Slot) @@ -905,8 +887,8 @@ SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, boo /* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds. we don't care... we just need the full fledged version */ - const QMetaMethod ¤t = _meta->method(_methodIds[method]); - const QMetaMethod &candidate = _meta->method(i); + const QMetaMethod& current = _meta->method(_methodIds[method]); + const QMetaMethod& candidate = _meta->method(i); if (current.parameterTypes().count() > candidate.parameterTypes().count()) { int minCount = candidate.parameterTypes().count(); QList commonParams = current.parameterTypes().mid(0, minCount); @@ -917,13 +899,14 @@ SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, boo int minCount = current.parameterTypes().count(); QList commonParams = candidate.parameterTypes().mid(0, minCount); if (commonParams == current.parameterTypes()) { - _methodIds[method] = i; // use the new one + _methodIds[method] = i; // use the new one continue; } } if (checkConflicts) { qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!"; - qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with" << _meta->method(_methodIds[method]).methodSignature(); + qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with" + << _meta->method(_methodIds[method]).methodSignature(); } continue; } @@ -931,8 +914,7 @@ SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, boo } } - -const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId) +const SignalProxy::ExtendedMetaObject::MethodDescriptor& SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId) { if (!_methods.contains(methodId)) { _methods[methodId] = MethodDescriptor(_meta->method(methodId)); @@ -940,8 +922,7 @@ const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMe return _methods[methodId]; } - -const QHash &SignalProxy::ExtendedMetaObject::receiveMap() +const QHash& SignalProxy::ExtendedMetaObject::receiveMap() { if (_receiveMap.isEmpty()) { QHash receiveMap; @@ -994,15 +975,13 @@ const QHash &SignalProxy::ExtendedMetaObject::receiveMap() return _receiveMap; } - -QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method) +QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod& method) { QByteArray sig(method.methodSignature()); return sig.left(sig.indexOf("(")); } - -QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method) +QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod& method) { QString methodname = QString(method.methodSignature()).section("(", 0, 0); @@ -1028,10 +1007,9 @@ QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &metho return methodname; } - -SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method) - : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)), - _returnType(QMetaType::type(method.typeName())) +SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod& method) + : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)) + , _returnType(QMetaType::type(method.typeName())) { // determine argTypes QList paramTypes = method.parameterTypes(); @@ -1045,7 +1023,5 @@ SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaM QString signature(method.methodSignature()); _minArgCount = method.parameterTypes().count() - signature.count("="); - _receiverMode = (_methodName.startsWith("request")) - ? SignalProxy::Server - : SignalProxy::Client; + _receiverMode = (_methodName.startsWith("request")) ? SignalProxy::Server : SignalProxy::Client; } diff --git a/src/common/signalproxy.h b/src/common/signalproxy.h index 6cab74ae..49033cdf 100644 --- a/src/common/signalproxy.h +++ b/src/common/signalproxy.h @@ -22,12 +22,12 @@ #include "common-export.h" -#include -#include - #include #include +#include +#include + #include "protocol.h" struct QMetaObject; @@ -43,17 +43,19 @@ class COMMON_EXPORT SignalProxy : public QObject class SignalRelay; public: - enum ProxyMode { + enum ProxyMode + { Server, Client }; - enum EventType { + enum EventType + { RemovePeerEvent = QEvent::User }; - SignalProxy(QObject *parent); - SignalProxy(ProxyMode mode, QObject *parent); + SignalProxy(QObject* parent); + SignalProxy(ProxyMode mode, QObject* parent); ~SignalProxy() override; void setProxyMode(ProxyMode mode); @@ -64,25 +66,28 @@ public: void setMaxHeartBeatCount(int max); inline int maxHeartBeatCount() const { return _maxHeartBeatCount; } - bool addPeer(Peer *peer); + bool addPeer(Peer* peer); - bool attachSignal(QObject *sender, const char *signal, const QByteArray &sigName = QByteArray()); - bool attachSlot(const QByteArray &sigName, QObject *recv, const char *slot); + bool attachSignal(QObject* sender, const char* signal, const QByteArray& sigName = QByteArray()); + bool attachSlot(const QByteArray& sigName, QObject* recv, const char* slot); - void synchronize(SyncableObject *obj); - void stopSynchronize(SyncableObject *obj); + void synchronize(SyncableObject* obj); + void stopSynchronize(SyncableObject* obj); class ExtendedMetaObject; - ExtendedMetaObject *extendedMetaObject(const QMetaObject *meta) const; - ExtendedMetaObject *createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts = false); - inline ExtendedMetaObject *extendedMetaObject(const QObject *obj) const { return extendedMetaObject(metaObject(obj)); } - inline ExtendedMetaObject *createExtendedMetaObject(const QObject *obj, bool checkConflicts = false) { return createExtendedMetaObject(metaObject(obj), checkConflicts); } + ExtendedMetaObject* extendedMetaObject(const QMetaObject* meta) const; + ExtendedMetaObject* createExtendedMetaObject(const QMetaObject* meta, bool checkConflicts = false); + inline ExtendedMetaObject* extendedMetaObject(const QObject* obj) const { return extendedMetaObject(metaObject(obj)); } + inline ExtendedMetaObject* createExtendedMetaObject(const QObject* obj, bool checkConflicts = false) + { + return createExtendedMetaObject(metaObject(obj), checkConflicts); + } bool isSecure() const { return _secure; } void dumpProxyStats(); - void dumpSyncMap(SyncableObject *object); + void dumpSyncMap(SyncableObject* object); - static SignalProxy *current(); + static SignalProxy* current(); /**@{*/ /** @@ -91,15 +96,17 @@ public: * @param closure Code you want to execute within of that restricted environment */ void restrictTargetPeers(QSet peers, std::function closure); - void restrictTargetPeers(Peer *peer, std::function closure) { + void restrictTargetPeers(Peer* peer, std::function closure) + { QSet set; set.insert(peer); restrictTargetPeers(set, std::move(closure)); } - //A better version, but only implemented on Qt5 if Initializer Lists exist + // A better version, but only implemented on Qt5 if Initializer Lists exist #ifdef Q_COMPILER_INITIALIZER_LISTS - void restrictTargetPeers(std::initializer_list peers, std::function closure) { + void restrictTargetPeers(std::initializer_list peers, std::function closure) + { restrictTargetPeers(QSet(peers), std::move(closure)); } #endif @@ -108,40 +115,40 @@ public: inline int peerCount() const { return _peerMap.size(); } QVariantList peerData(); - Peer *peerById(int peerId); + Peer* peerById(int peerId); /** * @return If handling a signal, the Peer from which the current signal originates */ - Peer *sourcePeer(); - void setSourcePeer(Peer *sourcePeer); + Peer* sourcePeer(); + void setSourcePeer(Peer* sourcePeer); /** * @return If sending a signal, the Peer to which the current signal is directed */ - Peer *targetPeer(); - void setTargetPeer(Peer *targetPeer); + Peer* targetPeer(); + void setTargetPeer(Peer* targetPeer); public slots: - void detachObject(QObject *obj); - void detachSignals(QObject *sender); - void detachSlots(QObject *receiver); + void detachObject(QObject* obj); + void detachSignals(QObject* sender); + void detachSlots(QObject* receiver); protected: - void customEvent(QEvent *event) override; - void sync_call__(const SyncableObject *obj, ProxyMode modeType, const char *funcname, va_list ap); - void renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname); + void customEvent(QEvent* event) override; + void sync_call__(const SyncableObject* obj, ProxyMode modeType, const char* funcname, va_list ap); + void renameObject(const SyncableObject* obj, const QString& newname, const QString& oldname); private slots: void removePeerBySender(); - void objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname); + void objectRenamed(const QByteArray& classname, const QString& newname, const QString& oldname); void updateSecureState(); signals: - void peerRemoved(Peer *peer); + void peerRemoved(Peer* peer); void connected(); void disconnected(); - void objectInitialized(SyncableObject *); + void objectInitialized(SyncableObject*); void heartBeatIntervalChanged(int secs); void maxHeartBeatCountChanged(int max); void lagUpdated(int lag); @@ -155,74 +162,74 @@ private: void initServer(); void initClient(); - static const QMetaObject *metaObject(const QObject *obj); + static const QMetaObject* metaObject(const QObject* obj); - void removePeer(Peer *peer); + void removePeer(Peer* peer); void removeAllPeers(); - int nextPeerId() { - return _lastPeerId++; - } + int nextPeerId() { return _lastPeerId++; } template - void dispatch(const T &protoMessage); + void dispatch(const T& protoMessage); template - void dispatch(Peer *peer, const T &protoMessage); + void dispatch(Peer* peer, const T& protoMessage); - void handle(Peer *peer, const Protocol::SyncMessage &syncMessage); - void handle(Peer *peer, const Protocol::RpcCall &rpcCall); - void handle(Peer *peer, const Protocol::InitRequest &initRequest); - void handle(Peer *peer, const Protocol::InitData &initData); + void handle(Peer* peer, const Protocol::SyncMessage& syncMessage); + void handle(Peer* peer, const Protocol::RpcCall& rpcCall); + void handle(Peer* peer, const Protocol::InitRequest& initRequest); + void handle(Peer* peer, const Protocol::InitData& initData); template - void handle(Peer *, T) { Q_ASSERT(0); } + void handle(Peer*, T) + { + Q_ASSERT(0); + } - bool invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, QVariant &returnValue, Peer *peer = nullptr); - bool invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms = QVariantList(), Peer *peer = nullptr); + bool invokeSlot(QObject* receiver, int methodId, const QVariantList& params, QVariant& returnValue, Peer* peer = nullptr); + bool invokeSlot(QObject* receiver, int methodId, const QVariantList& params = QVariantList(), Peer* peer = nullptr); - void requestInit(SyncableObject *obj); - QVariantMap initData(SyncableObject *obj) const; - void setInitData(SyncableObject *obj, const QVariantMap &properties); + void requestInit(SyncableObject* obj); + QVariantMap initData(SyncableObject* obj) const; + void setInitData(SyncableObject* obj, const QVariantMap& properties); - static void disconnectDevice(QIODevice *dev, const QString &reason = QString()); + static void disconnectDevice(QIODevice* dev, const QString& reason = QString()); QHash _peerMap; // containg a list of argtypes for fast access - QHash _extendedMetaObjects; + QHash _extendedMetaObjects; // SignalRelay for all manually attached signals - SignalRelay *_signalRelay; + SignalRelay* _signalRelay; // RPC function -> (object, slot ID) - using MethodId = QPair; + using MethodId = QPair; using SlotHash = QMultiHash; SlotHash _attachedSlots; // slaves for sync - using ObjectId = QHash; + using ObjectId = QHash; QHash _syncSlave; ProxyMode _proxyMode; int _heartBeatInterval; int _maxHeartBeatCount; - bool _secure; // determines if all connections are in a secured state (using ssl or internal connections) + bool _secure; // determines if all connections are in a secured state (using ssl or internal connections) int _lastPeerId = 0; - QSet _restrictedTargets; + QSet _restrictedTargets; bool _restrictMessageTarget = false; - Peer *_sourcePeer = nullptr; - Peer *_targetPeer = nullptr; + Peer* _sourcePeer = nullptr; + Peer* _targetPeer = nullptr; friend class SignalRelay; friend class SyncableObject; friend class Peer; }; - // ================================================== // ExtendedMetaObject // ================================================== @@ -231,11 +238,11 @@ class SignalProxy::ExtendedMetaObject class MethodDescriptor { public: - MethodDescriptor(const QMetaMethod &method); + MethodDescriptor(const QMetaMethod& method); MethodDescriptor() = default; - inline const QByteArray &methodName() const { return _methodName; } - inline const QList &argTypes() const { return _argTypes; } + inline const QByteArray& methodName() const { return _methodName; } + inline const QList& argTypes() const { return _argTypes; } inline int returnType() const { return _returnType; } inline int minArgCount() const { return _minArgCount; } inline SignalProxy::ProxyMode receiverMode() const { return _receiverMode; } @@ -245,38 +252,38 @@ class SignalProxy::ExtendedMetaObject QList _argTypes; int _returnType{-1}; int _minArgCount{-1}; - SignalProxy::ProxyMode _receiverMode{SignalProxy::Client}; // Only acceptable as a Sync Call if the receiving SignalProxy is in this mode. + SignalProxy::ProxyMode _receiverMode{ + SignalProxy::Client}; // Only acceptable as a Sync Call if the receiving SignalProxy is in this mode. }; - public: - ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts); + ExtendedMetaObject(const QMetaObject* meta, bool checkConflicts); - inline const QByteArray &methodName(int methodId) { return methodDescriptor(methodId).methodName(); } - inline const QList &argTypes(int methodId) { return methodDescriptor(methodId).argTypes(); } + inline const QByteArray& methodName(int methodId) { return methodDescriptor(methodId).methodName(); } + inline const QList& argTypes(int methodId) { return methodDescriptor(methodId).argTypes(); } inline int returnType(int methodId) { return methodDescriptor(methodId).returnType(); } inline int minArgCount(int methodId) { return methodDescriptor(methodId).minArgCount(); } inline SignalProxy::ProxyMode receiverMode(int methodId) { return methodDescriptor(methodId).receiverMode(); } - inline int methodId(const QByteArray &methodName) { return _methodIds.contains(methodName) ? _methodIds[methodName] : -1; } + inline int methodId(const QByteArray& methodName) { return _methodIds.contains(methodName) ? _methodIds[methodName] : -1; } inline int updatedRemotelyId() { return _updatedRemotelyId; } - inline const QHash &slotMap() { return _methodIds; } - const QHash &receiveMap(); + inline const QHash& slotMap() { return _methodIds; } + const QHash& receiveMap(); - const QMetaObject *metaObject() const { return _meta; } + const QMetaObject* metaObject() const { return _meta; } - static QByteArray methodName(const QMetaMethod &method); - static QString methodBaseName(const QMetaMethod &method); + static QByteArray methodName(const QMetaMethod& method); + static QString methodBaseName(const QMetaMethod& method); private: - const MethodDescriptor &methodDescriptor(int methodId); + const MethodDescriptor& methodDescriptor(int methodId); - const QMetaObject *_meta; - int _updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster + const QMetaObject* _meta; + int _updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster QHash _methods; QHash _methodIds; - QHash _receiveMap; // if slot x is called then hand over the result to slot y + QHash _receiveMap; // if slot x is called then hand over the result to slot y }; diff --git a/src/common/singleton.h b/src/common/singleton.h index a3c96524..1bf68a2a 100644 --- a/src/common/singleton.h +++ b/src/common/singleton.h @@ -40,9 +40,9 @@ namespace detail { // We need to export the function on anything not using Windows DLLs, otherwise local static members don't // work across library boundaries. template -QUASSEL_SINGLETON_EXPORT T *getOrSetInstance(T *instance = nullptr, bool destroyed = false) +QUASSEL_SINGLETON_EXPORT T* getOrSetInstance(T* instance = nullptr, bool destroyed = false) { - static T *_instance = instance; + static T* _instance = instance; static bool _destroyed = destroyed; if (destroyed) { @@ -93,16 +93,16 @@ public: * * @param instance Pointer to the instance being created, i.e. the 'this' pointer of the parent class */ - Singleton(T *instance) + Singleton(T* instance) { detail::getOrSetInstance(instance); } // Satisfy Rule of Five - Singleton(const Singleton &) = delete; - Singleton(Singleton &&) = delete; - Singleton &operator=(const Singleton &) = delete; - Singleton &operator=(Singleton &&) = delete; + Singleton(const Singleton&) = delete; + Singleton(Singleton&&) = delete; + Singleton& operator=(const Singleton&) = delete; + Singleton& operator=(Singleton&&) = delete; /** * Destructor. @@ -122,7 +122,7 @@ public: * * @returns A pointer to the instance */ - static T *instance() + static T* instance() { return detail::getOrSetInstance(); } diff --git a/src/common/syncableobject.cpp b/src/common/syncableobject.cpp index f43a155c..9fd7704f 100644 --- a/src/common/syncableobject.cpp +++ b/src/common/syncableobject.cpp @@ -18,48 +18,41 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include +#include "syncableobject.h" #include - -#include "syncableobject.h" +#include #include "signalproxy.h" #include "util.h" -SyncableObject::SyncableObject(QObject *parent) +SyncableObject::SyncableObject(QObject* parent) : QObject(parent) -{ -} +{} - -SyncableObject::SyncableObject(const QString &objectName, QObject *parent) +SyncableObject::SyncableObject(const QString& objectName, QObject* parent) : QObject(parent) { setObjectName(objectName); } - -SyncableObject::SyncableObject(const SyncableObject &other, QObject *parent) - : QObject(parent), - _initialized(other._initialized), - _allowClientUpdates(other._allowClientUpdates) -{ -} - +SyncableObject::SyncableObject(const SyncableObject& other, QObject* parent) + : QObject(parent) + , _initialized(other._initialized) + , _allowClientUpdates(other._allowClientUpdates) +{} SyncableObject::~SyncableObject() { - QList::iterator proxyIter = _signalProxies.begin(); + QList::iterator proxyIter = _signalProxies.begin(); while (proxyIter != _signalProxies.end()) { - SignalProxy *proxy = (*proxyIter); + SignalProxy* proxy = (*proxyIter); proxyIter = _signalProxies.erase(proxyIter); proxy->stopSynchronize(this); } } - -SyncableObject &SyncableObject::operator=(const SyncableObject &other) +SyncableObject& SyncableObject::operator=(const SyncableObject& other) { if (this == &other) return *this; @@ -69,25 +62,22 @@ SyncableObject &SyncableObject::operator=(const SyncableObject &other) return *this; } - bool SyncableObject::isInitialized() const { return _initialized; } - void SyncableObject::setInitialized() { _initialized = true; emit initDone(); } - QVariantMap SyncableObject::toVariantMap() { QVariantMap properties; - const QMetaObject *meta = metaObject(); + const QMetaObject* meta = metaObject(); // we collect data from properties QMetaProperty prop; @@ -109,11 +99,12 @@ QVariantMap SyncableObject::toVariantMap() QVariant::Type variantType = QVariant::nameToType(method.typeName()); if (variantType == QVariant::Invalid && !QByteArray(method.typeName()).isEmpty()) { - qWarning() << "SyncableObject::toVariantMap(): cannot fetch init data for:" << this << method.methodSignature() << "- Returntype is unknown to Qt's MetaSystem:" << QByteArray(method.typeName()); + qWarning() << "SyncableObject::toVariantMap(): cannot fetch init data for:" << this << method.methodSignature() + << "- Returntype is unknown to Qt's MetaSystem:" << QByteArray(method.typeName()); continue; } - QVariant value(variantType, (const void *)nullptr); + QVariant value(variantType, (const void*)nullptr); QGenericReturnArgument genericvalue = QGenericReturnArgument(method.typeName(), value.data()); QMetaObject::invokeMethod(this, methodname.toLatin1(), genericvalue); @@ -122,10 +113,9 @@ QVariantMap SyncableObject::toVariantMap() return properties; } - -void SyncableObject::fromVariantMap(const QVariantMap &properties) +void SyncableObject::fromVariantMap(const QVariantMap& properties) { - const QMetaObject *meta = metaObject(); + const QMetaObject* meta = metaObject(); QVariantMap::const_iterator iterator = properties.constBegin(); QString propName; @@ -147,15 +137,14 @@ void SyncableObject::fromVariantMap(const QVariantMap &properties) } } - -bool SyncableObject::setInitValue(const QString &property, const QVariant &value) +bool SyncableObject::setInitValue(const QString& property, const QVariant& value) { QString handlername = QString("initSet") + property; handlername[7] = handlername[7].toUpper(); QString methodSignature = QString("%1(%2)").arg(handlername).arg(value.typeName()); int methodIdx = metaObject()->indexOfMethod(methodSignature.toLatin1().constData()); - if (methodIdx < 0) { + if (methodIdx < 0) { QByteArray normedMethodName = QMetaObject::normalizedSignature(methodSignature.toLatin1().constData()); methodIdx = metaObject()->indexOfMethod(normedMethodName.constData()); } @@ -167,28 +156,25 @@ bool SyncableObject::setInitValue(const QString &property, const QVariant &value return QMetaObject::invokeMethod(this, handlername.toLatin1(), param); } - -void SyncableObject::renameObject(const QString &newName) +void SyncableObject::renameObject(const QString& newName) { const QString oldName = objectName(); if (oldName != newName) { setObjectName(newName); - foreach(SignalProxy *proxy, _signalProxies) { + foreach (SignalProxy* proxy, _signalProxies) { proxy->renameObject(this, newName, oldName); } } } - -void SyncableObject::update(const QVariantMap &properties) +void SyncableObject::update(const QVariantMap& properties) { fromVariantMap(properties); SYNC(ARG(properties)) emit updated(); } - -void SyncableObject::requestUpdate(const QVariantMap &properties) +void SyncableObject::requestUpdate(const QVariantMap& properties) { if (allowClientUpdates()) { update(properties); @@ -196,11 +182,10 @@ void SyncableObject::requestUpdate(const QVariantMap &properties) REQUEST(ARG(properties)) } - -void SyncableObject::sync_call__(SignalProxy::ProxyMode modeType, const char *funcname, ...) const +void SyncableObject::sync_call__(SignalProxy::ProxyMode modeType, const char* funcname, ...) const { - //qDebug() << Q_FUNC_INFO << modeType << funcname; - foreach(SignalProxy *proxy, _signalProxies) { + // qDebug() << Q_FUNC_INFO << modeType << funcname; + foreach (SignalProxy* proxy, _signalProxies) { va_list ap; va_start(ap, funcname); proxy->sync_call__(this, modeType, funcname, ap); @@ -208,16 +193,14 @@ void SyncableObject::sync_call__(SignalProxy::ProxyMode modeType, const char *fu } } - -void SyncableObject::synchronize(SignalProxy *proxy) +void SyncableObject::synchronize(SignalProxy* proxy) { if (_signalProxies.contains(proxy)) return; _signalProxies << proxy; } - -void SyncableObject::stopSynchronize(SignalProxy *proxy) +void SyncableObject::stopSynchronize(SignalProxy* proxy) { for (int i = 0; i < _signalProxies.count(); i++) { if (_signalProxies[i] == proxy) { diff --git a/src/common/syncableobject.h b/src/common/syncableobject.h index 9031f136..7d5242b1 100644 --- a/src/common/syncableobject.h +++ b/src/common/syncableobject.h @@ -36,12 +36,11 @@ * i.e., if you have Foo, ClientFoo and/or CoreFoo, the SYNCABLE_OBJECT macro would * only be declared in the class declaration of Foo. */ -#define SYNCABLE_OBJECT \ - public: \ - const QMetaObject *syncMetaObject() const final override { \ - return &staticMetaObject; \ - } \ - private: \ +#define SYNCABLE_OBJECT \ +public: \ + const QMetaObject* syncMetaObject() const final override { return &staticMetaObject; } \ + \ +private: #define SYNC(...) sync_call__(SignalProxy::Server, __func__, __VA_ARGS__); #define REQUEST(...) sync_call__(SignalProxy::Client, __func__, __VA_ARGS__); @@ -49,7 +48,7 @@ #define SYNC_OTHER(x, ...) sync_call__(SignalProxy::Server, #x, __VA_ARGS__); #define REQUEST_OTHER(x, ...) sync_call__(SignalProxy::Client, #x, __VA_ARGS__); -#define ARG(x) const_cast(reinterpret_cast(&x)) +#define ARG(x) const_cast(reinterpret_cast(&x)) #define NO_ARG 0 class COMMON_EXPORT SyncableObject : public QObject @@ -57,9 +56,9 @@ class COMMON_EXPORT SyncableObject : public QObject Q_OBJECT public: - SyncableObject(QObject *parent = nullptr); - SyncableObject(const QString &objectName, QObject *parent = nullptr); - SyncableObject(const SyncableObject &other, QObject *parent = nullptr); + SyncableObject(QObject* parent = nullptr); + SyncableObject(const QString& objectName, QObject* parent = nullptr); + SyncableObject(const SyncableObject& other, QObject* parent = nullptr); ~SyncableObject() override; //! Stores the object's state into a QVariantMap. @@ -78,25 +77,25 @@ public: //! Initialize the object's state from a given QVariantMap. /** \see toVariantMap() for important information concerning this method. */ - virtual void fromVariantMap(const QVariantMap &properties); + virtual void fromVariantMap(const QVariantMap& properties); virtual bool isInitialized() const; - virtual const QMetaObject *syncMetaObject() const { return metaObject(); } + virtual const QMetaObject* syncMetaObject() const { return metaObject(); } inline void setAllowClientUpdates(bool allow) { _allowClientUpdates = allow; } inline bool allowClientUpdates() const { return _allowClientUpdates; } public slots: virtual void setInitialized(); - void requestUpdate(const QVariantMap &properties); - virtual void update(const QVariantMap &properties); + void requestUpdate(const QVariantMap& properties); + virtual void update(const QVariantMap& properties); protected: - void sync_call__(SignalProxy::ProxyMode modeType, const char *funcname, ...) const; + void sync_call__(SignalProxy::ProxyMode modeType, const char* funcname, ...) const; - void renameObject(const QString &newName); - SyncableObject &operator=(const SyncableObject &other); + void renameObject(const QString& newName); + SyncableObject& operator=(const SyncableObject& other); signals: void initDone(); @@ -104,15 +103,15 @@ signals: void updated(); private: - void synchronize(SignalProxy *proxy); - void stopSynchronize(SignalProxy *proxy); + void synchronize(SignalProxy* proxy); + void stopSynchronize(SignalProxy* proxy); - bool setInitValue(const QString &property, const QVariant &value); + bool setInitValue(const QString& property, const QVariant& value); bool _initialized{false}; bool _allowClientUpdates{false}; - QList _signalProxies; + QList _signalProxies; friend class SignalProxy; }; diff --git a/src/common/transfer.cpp b/src/common/transfer.cpp index cf07f29d..d33a9a37 100644 --- a/src/common/transfer.cpp +++ b/src/common/transfer.cpp @@ -22,32 +22,32 @@ #include -Transfer::Transfer(const QUuid &uuid, QObject *parent) - : SyncableObject(parent), - _status(Status::New), - _direction(Direction::Receive), - _port(0), - _fileSize(0), - _uuid(uuid) +Transfer::Transfer(const QUuid& uuid, QObject* parent) + : SyncableObject(parent) + , _status(Status::New) + , _direction(Direction::Receive) + , _port(0) + , _fileSize(0) + , _uuid(uuid) { init(); } -Transfer::Transfer(Direction direction, QString nick, QString fileName, const QHostAddress &address, quint16 port, quint64 fileSize, QObject *parent) - : SyncableObject(parent), - _status(Status::New), - _direction(direction), - _fileName(std::move(fileName)), - _address(address), - _port(port), - _fileSize(fileSize), - _nick(std::move(nick)), - _uuid(QUuid::createUuid()) +Transfer::Transfer( + Direction direction, QString nick, QString fileName, const QHostAddress& address, quint16 port, quint64 fileSize, QObject* parent) + : SyncableObject(parent) + , _status(Status::New) + , _direction(direction) + , _fileName(std::move(fileName)) + , _address(address) + , _port(port) + , _fileSize(fileSize) + , _nick(std::move(nick)) + , _uuid(QUuid::createUuid()) { init(); } - void Transfer::init() { static auto regTypes = []() -> bool { @@ -63,19 +63,16 @@ void Transfer::init() setAllowClientUpdates(true); } - QUuid Transfer::uuid() const { return _uuid; } - Transfer::Status Transfer::status() const { return _status; } - void Transfer::setStatus(Transfer::Status status) { if (_status != status) { @@ -88,39 +85,35 @@ void Transfer::setStatus(Transfer::Status status) } } - QString Transfer::prettyStatus() const { - switch(status()) { - case Status::New: - return tr("New"); - case Status::Pending: - return tr("Pending"); - case Status::Connecting: - return tr("Connecting"); - case Status::Transferring: - return tr("Transferring"); - case Status::Paused: - return tr("Paused"); - case Status::Completed: - return tr("Completed"); - case Status::Failed: - return tr("Failed"); - case Status::Rejected: - return tr("Rejected"); + switch (status()) { + case Status::New: + return tr("New"); + case Status::Pending: + return tr("Pending"); + case Status::Connecting: + return tr("Connecting"); + case Status::Transferring: + return tr("Transferring"); + case Status::Paused: + return tr("Paused"); + case Status::Completed: + return tr("Completed"); + case Status::Failed: + return tr("Failed"); + case Status::Rejected: + return tr("Rejected"); } return QString(); } - - Transfer::Direction Transfer::direction() const { return _direction; } - void Transfer::setDirection(Transfer::Direction direction) { if (_direction != direction) { @@ -130,14 +123,12 @@ void Transfer::setDirection(Transfer::Direction direction) } } - QHostAddress Transfer::address() const { return _address; } - -void Transfer::setAddress(const QHostAddress &address) +void Transfer::setAddress(const QHostAddress& address) { if (_address != address) { _address = address; @@ -146,13 +137,11 @@ void Transfer::setAddress(const QHostAddress &address) } } - quint16 Transfer::port() const { return _port; } - void Transfer::setPort(quint16 port) { if (_port != port) { @@ -162,14 +151,12 @@ void Transfer::setPort(quint16 port) } } - QString Transfer::fileName() const { return _fileName; } - -void Transfer::setFileName(const QString &fileName) +void Transfer::setFileName(const QString& fileName) { if (_fileName != fileName) { _fileName = fileName; @@ -178,13 +165,11 @@ void Transfer::setFileName(const QString &fileName) } } - quint64 Transfer::fileSize() const { return _fileSize; } - void Transfer::setFileSize(quint64 fileSize) { if (_fileSize != fileSize) { @@ -194,14 +179,12 @@ void Transfer::setFileSize(quint64 fileSize) } } - QString Transfer::nick() const { return _nick; } - -void Transfer::setNick(const QString &nick) +void Transfer::setNick(const QString& nick) { if (_nick != nick) { _nick = nick; @@ -210,33 +193,35 @@ void Transfer::setNick(const QString &nick) } } - -void Transfer::setError(const QString &errorString) +void Transfer::setError(const QString& errorString) { qWarning() << Q_FUNC_INFO << errorString; emit error(errorString); setStatus(Status::Failed); } - -QDataStream &operator<<(QDataStream &out, Transfer::Status state) { +QDataStream& operator<<(QDataStream& out, Transfer::Status state) +{ out << static_cast(state); return out; } -QDataStream &operator>>(QDataStream &in, Transfer::Status &state) { +QDataStream& operator>>(QDataStream& in, Transfer::Status& state) +{ qint8 s; in >> s; state = static_cast(s); return in; } -QDataStream &operator<<(QDataStream &out, Transfer::Direction direction) { +QDataStream& operator<<(QDataStream& out, Transfer::Direction direction) +{ out << static_cast(direction); return out; } -QDataStream &operator>>(QDataStream &in, Transfer::Direction &direction) { +QDataStream& operator>>(QDataStream& in, Transfer::Direction& direction) +{ qint8 d; in >> d; direction = static_cast(d); diff --git a/src/common/transfer.h b/src/common/transfer.h index 66e01e28..52e81df6 100644 --- a/src/common/transfer.h +++ b/src/common/transfer.h @@ -43,7 +43,8 @@ class COMMON_EXPORT Transfer : public SyncableObject Q_PROPERTY(QString nick READ nick WRITE setNick NOTIFY nickChanged) public: - enum class Status { + enum class Status + { New, Pending, Connecting, @@ -55,14 +56,21 @@ public: }; Q_ENUMS(State) - enum class Direction { + enum class Direction + { Send, Receive }; Q_ENUMS(Direction) - Transfer(const QUuid &uuid, QObject *parent = nullptr); // for creating a syncable object client-side - Transfer(Direction direction, QString nick, QString fileName, const QHostAddress &address, quint16 port, quint64 size = 0, QObject *parent = nullptr); + Transfer(const QUuid& uuid, QObject* parent = nullptr); // for creating a syncable object client-side + Transfer(Direction direction, + QString nick, + QString fileName, + const QHostAddress& address, + quint16 port, + quint64 size = 0, + QObject* parent = nullptr); QUuid uuid() const; Status status() const; @@ -78,7 +86,7 @@ public: public slots: // called on the client side - virtual void accept(const QString &savePath) const { Q_UNUSED(savePath); } + virtual void accept(const QString& savePath) const { Q_UNUSED(savePath); } virtual void reject() const {} // called on the core side through sync calls @@ -88,24 +96,24 @@ public slots: signals: void statusChanged(Transfer::Status state); void directionChanged(Transfer::Direction direction); - void addressChanged(const QHostAddress &address); + void addressChanged(const QHostAddress& address); void portChanged(quint16 port); - void fileNameChanged(const QString &fileName); + void fileNameChanged(const QString& fileName); void fileSizeChanged(quint64 fileSize); void transferredChanged(quint64 transferred); - void nickChanged(const QString &nick); + void nickChanged(const QString& nick); - void error(const QString &errorString); + void error(const QString& errorString); void accepted(PeerPtr peer = nullptr) const; void rejected(PeerPtr peer = nullptr) const; protected slots: void setStatus(Transfer::Status status); - void setError(const QString &errorString); + void setError(const QString& errorString); // called on the client side through sync calls - virtual void dataReceived(PeerPtr, const QByteArray &data) { Q_UNUSED(data); } + virtual void dataReceived(PeerPtr, const QByteArray& data) { Q_UNUSED(data); } virtual void cleanUp() = 0; @@ -113,12 +121,11 @@ private: void init(); void setDirection(Direction direction); - void setAddress(const QHostAddress &address); + void setAddress(const QHostAddress& address); void setPort(quint16 port); - void setFileName(const QString &fileName); + void setFileName(const QString& fileName); void setFileSize(quint64 fileSize); - void setNick(const QString &nick); - + void setNick(const QString& nick); Status _status; Direction _direction; @@ -133,7 +140,7 @@ private: Q_DECLARE_METATYPE(Transfer::Status) Q_DECLARE_METATYPE(Transfer::Direction) -QDataStream &operator<<(QDataStream &out, Transfer::Status state); -QDataStream &operator>>(QDataStream &in, Transfer::Status &state); -QDataStream &operator<<(QDataStream &out, Transfer::Direction direction); -QDataStream &operator>>(QDataStream &in, Transfer::Direction &direction); +QDataStream& operator<<(QDataStream& out, Transfer::Status state); +QDataStream& operator>>(QDataStream& in, Transfer::Status& state); +QDataStream& operator<<(QDataStream& out, Transfer::Direction direction); +QDataStream& operator>>(QDataStream& in, Transfer::Direction& direction); diff --git a/src/common/transfermanager.cpp b/src/common/transfermanager.cpp index 7df24fe9..4df5589a 100644 --- a/src/common/transfermanager.cpp +++ b/src/common/transfermanager.cpp @@ -22,7 +22,7 @@ #include "transfer.h" -TransferManager::TransferManager(QObject *parent) +TransferManager::TransferManager(QObject* parent) : SyncableObject(parent) { static auto regTypes = []() -> bool { @@ -34,20 +34,17 @@ TransferManager::TransferManager(QObject *parent) renameObject("TransferManager"); } - -Transfer *TransferManager::transfer(const QUuid &uuid) const +Transfer* TransferManager::transfer(const QUuid& uuid) const { return _transfers.value(uuid, nullptr); } - TransferManager::TransferIdList TransferManager::transferIds() const { return _transfers.keys(); } - -void TransferManager::addTransfer(Transfer *transfer) +void TransferManager::addTransfer(Transfer* transfer) { QUuid uuid = transfer->uuid(); if (_transfers.contains(uuid)) { @@ -62,8 +59,7 @@ void TransferManager::addTransfer(Transfer *transfer) emit transferAdded(uuid); } - -void TransferManager::removeTransfer(const QUuid &uuid) +void TransferManager::removeTransfer(const QUuid& uuid) { if (!_transfers.contains(uuid)) { qWarning() << "Can not find transfer" << uuid << "to remove!"; @@ -74,18 +70,16 @@ void TransferManager::removeTransfer(const QUuid &uuid) transfer->deleteLater(); } - -QDataStream &operator<<(QDataStream &out, const TransferManager::TransferIdList &transferIds) +QDataStream& operator<<(QDataStream& out, const TransferManager::TransferIdList& transferIds) { out << static_cast(transferIds.size()); - for (auto &&id : transferIds) { + for (auto&& id : transferIds) { out << id; } return out; } - -QDataStream &operator>>(QDataStream &in, TransferManager::TransferIdList &transferIds) +QDataStream& operator>>(QDataStream& in, TransferManager::TransferIdList& transferIds) { quint32 count; in >> count; diff --git a/src/common/transfermanager.h b/src/common/transfermanager.h index 49f04c68..9069fe0d 100644 --- a/src/common/transfermanager.h +++ b/src/common/transfermanager.h @@ -40,26 +40,26 @@ class COMMON_EXPORT TransferManager : public SyncableObject public: using TransferIdList = QList; - TransferManager(QObject *parent = nullptr); + TransferManager(QObject* parent = nullptr); - Transfer *transfer(const QUuid &uuid) const; + Transfer* transfer(const QUuid& uuid) const; TransferIdList transferIds() const; signals: - void transferAdded(const QUuid &uuid); - void transferRemoved(const QUuid &uuid); + void transferAdded(const QUuid& uuid); + void transferRemoved(const QUuid& uuid); protected: - void addTransfer(Transfer *transfer); - void removeTransfer(const QUuid &uuid); + void addTransfer(Transfer* transfer); + void removeTransfer(const QUuid& uuid); protected slots: - virtual void setTransferIds(const TransferIdList &transferIds) { Q_UNUSED(transferIds) }; - virtual void onCoreTransferAdded(const QUuid &transferId) { Q_UNUSED(transferId) }; + virtual void setTransferIds(const TransferIdList& transferIds){Q_UNUSED(transferIds)}; + virtual void onCoreTransferAdded(const QUuid& transferId){Q_UNUSED(transferId)}; private: - QHash _transfers; + QHash _transfers; }; -QDataStream &operator<<(QDataStream &out, const TransferManager::TransferIdList &transferIds); -QDataStream &operator>>(QDataStream &in, TransferManager::TransferIdList &state); +QDataStream& operator<<(QDataStream& out, const TransferManager::TransferIdList& transferIds); +QDataStream& operator>>(QDataStream& in, TransferManager::TransferIdList& state); diff --git a/src/common/types.cpp b/src/common/types.cpp index 1974c588..24784d48 100644 --- a/src/common/types.cpp +++ b/src/common/types.cpp @@ -18,28 +18,33 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include "peer.h" #include "types.h" -QDataStream &operator<<(QDataStream &out, const SignedId64 &signedId) { +#include "peer.h" + +QDataStream& operator<<(QDataStream& out, const SignedId64& signedId) +{ Q_ASSERT(SignalProxy::current()); Q_ASSERT(SignalProxy::current()->targetPeer()); if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::LongMessageId)) { out << signedId.toQint64(); - } else { - out << (qint32) signedId.toQint64(); + } + else { + out << (qint32)signedId.toQint64(); } return out; } -QDataStream &operator>>(QDataStream &in, SignedId64 &signedId) { +QDataStream& operator>>(QDataStream& in, SignedId64& signedId) +{ Q_ASSERT(SignalProxy::current()); Q_ASSERT(SignalProxy::current()->sourcePeer()); if (SignalProxy::current()->sourcePeer()->hasFeature(Quassel::Feature::LongMessageId)) { in >> signedId.id; - } else { + } + else { qint32 id; in >> id; signedId.id = id; diff --git a/src/common/types.h b/src/common/types.h index fb85012d..a806c58f 100644 --- a/src/common/types.h +++ b/src/common/types.h @@ -22,13 +22,12 @@ #include +#include #include +#include #include -#include -#include #include -#include -#include +#include class SignedId { @@ -40,29 +39,52 @@ public: inline qint32 toInt() const { return id; } inline bool isValid() const { return id > 0; } - inline bool operator==(const SignedId &other) const { return id == other.id; } - inline bool operator!=(const SignedId &other) const { return id != other.id; } - inline bool operator<(const SignedId &other) const { return id < other.id; } - inline bool operator<=(const SignedId &other) const { return id <= other.id; } - inline bool operator>(const SignedId &other) const { return id > other.id; } - inline bool operator>=(const SignedId &other) const { return id >= other.id; } + inline bool operator==(const SignedId& other) const { return id == other.id; } + inline bool operator!=(const SignedId& other) const { return id != other.id; } + inline bool operator<(const SignedId& other) const { return id < other.id; } + inline bool operator<=(const SignedId& other) const { return id <= other.id; } + inline bool operator>(const SignedId& other) const { return id > other.id; } + inline bool operator>=(const SignedId& other) const { return id >= other.id; } inline bool operator==(int i) const { return id == i; } inline bool operator!=(int i) const { return id != i; } inline bool operator<(int i) const { return id < i; } inline bool operator>(int i) const { return id > i; } inline bool operator<=(int i) const { return id <= i; } - inline SignedId operator++(int) { id++; return *this; } - //inline operator int() const { return toInt(); } // no automatic conversion! + inline SignedId operator++(int) + { + id++; + return *this; + } + // inline operator int() const { return toInt(); } // no automatic conversion! - friend QDataStream &operator>>(QDataStream &in, SignedId &signedId); + friend QDataStream& operator>>(QDataStream& in, SignedId& signedId); }; -inline QDataStream &operator<<(QDataStream &out, const SignedId &signedId) { out << signedId.toInt(); return out; } -inline QDataStream &operator>>(QDataStream &in, SignedId &signedId) { in >> signedId.id; return in; } -inline QTextStream &operator<<(QTextStream &out, const SignedId &signedId) { out << QString::number(signedId.toInt()); return out; } -inline QDebug operator<<(QDebug dbg, const SignedId &signedId) { dbg.space() << signedId.toInt(); return dbg; } -inline uint qHash(const SignedId &id) { return qHash(id.toInt()); } +inline QDataStream& operator<<(QDataStream& out, const SignedId& signedId) +{ + out << signedId.toInt(); + return out; +} +inline QDataStream& operator>>(QDataStream& in, SignedId& signedId) +{ + in >> signedId.id; + return in; +} +inline QTextStream& operator<<(QTextStream& out, const SignedId& signedId) +{ + out << QString::number(signedId.toInt()); + return out; +} +inline QDebug operator<<(QDebug dbg, const SignedId& signedId) +{ + dbg.space() << signedId.toInt(); + return dbg; +} +inline uint qHash(const SignedId& id) +{ + return qHash(id.toInt()); +} class SignedId64 { @@ -74,57 +96,90 @@ public: inline qint64 toQint64() const { return id; } inline bool isValid() const { return id > 0; } - inline bool operator==(const SignedId64 &other) const { return id == other.id; } - inline bool operator!=(const SignedId64 &other) const { return id != other.id; } - inline bool operator<(const SignedId64 &other) const { return id < other.id; } - inline bool operator<=(const SignedId64 &other) const { return id <= other.id; } - inline bool operator>(const SignedId64 &other) const { return id > other.id; } - inline bool operator>=(const SignedId64 &other) const { return id >= other.id; } + inline bool operator==(const SignedId64& other) const { return id == other.id; } + inline bool operator!=(const SignedId64& other) const { return id != other.id; } + inline bool operator<(const SignedId64& other) const { return id < other.id; } + inline bool operator<=(const SignedId64& other) const { return id <= other.id; } + inline bool operator>(const SignedId64& other) const { return id > other.id; } + inline bool operator>=(const SignedId64& other) const { return id >= other.id; } inline bool operator==(qint64 i) const { return id == i; } inline bool operator!=(qint64 i) const { return id != i; } inline bool operator<(qint64 i) const { return id < i; } inline bool operator>(qint64 i) const { return id > i; } inline bool operator<=(qint64 i) const { return id <= i; } - inline SignedId64 operator++(int) { id++; return *this; } - //inline operator int() const { return toQint64(); } // no automatic conversion! + inline SignedId64 operator++(int) + { + id++; + return *this; + } + // inline operator int() const { return toQint64(); } // no automatic conversion! - friend QDataStream &operator>>(QDataStream &in, SignedId64 &signedId); + friend QDataStream& operator>>(QDataStream& in, SignedId64& signedId); }; -QDataStream &operator<<(QDataStream &out, const SignedId64 &signedId); -QDataStream &operator>>(QDataStream &in, SignedId64 &signedId); -inline QTextStream &operator<<(QTextStream &out, const SignedId64 &signedId) { out << QString::number(signedId.toQint64()); return out; } -inline QDebug operator<<(QDebug dbg, const SignedId64 &signedId) { dbg.space() << signedId.toQint64(); return dbg; } -inline uint qHash(const SignedId64 &id) { return qHash(id.toQint64()); } +QDataStream& operator<<(QDataStream& out, const SignedId64& signedId); +QDataStream& operator>>(QDataStream& in, SignedId64& signedId); +inline QTextStream& operator<<(QTextStream& out, const SignedId64& signedId) +{ + out << QString::number(signedId.toQint64()); + return out; +} +inline QDebug operator<<(QDebug dbg, const SignedId64& signedId) +{ + dbg.space() << signedId.toQint64(); + return dbg; +} +inline uint qHash(const SignedId64& id) +{ + return qHash(id.toQint64()); +} -struct UserId : public SignedId { - inline UserId(int _id = 0) : SignedId(_id) {} - //inline operator QVariant() const { return QVariant::fromValue(*this); } // no automatic conversion! +struct UserId : public SignedId +{ + inline UserId(int _id = 0) + : SignedId(_id) + {} + // inline operator QVariant() const { return QVariant::fromValue(*this); } // no automatic conversion! }; -struct MsgId : public SignedId64 { - inline MsgId(qint64 _id = 0) : SignedId64(_id) {} - //inline operator QVariant() const { return QVariant::fromValue(*this); } +struct MsgId : public SignedId64 +{ + inline MsgId(qint64 _id = 0) + : SignedId64(_id) + {} + // inline operator QVariant() const { return QVariant::fromValue(*this); } }; -struct BufferId : public SignedId { - inline BufferId(int _id = 0) : SignedId(_id) {} - //inline operator QVariant() const { return QVariant::fromValue(*this); } +struct BufferId : public SignedId +{ + inline BufferId(int _id = 0) + : SignedId(_id) + {} + // inline operator QVariant() const { return QVariant::fromValue(*this); } }; -struct NetworkId : public SignedId { - inline NetworkId(int _id = 0) : SignedId(_id) {} - //inline operator QVariant() const { return QVariant::fromValue(*this); } +struct NetworkId : public SignedId +{ + inline NetworkId(int _id = 0) + : SignedId(_id) + {} + // inline operator QVariant() const { return QVariant::fromValue(*this); } }; -struct IdentityId : public SignedId { - inline IdentityId(int _id = 0) : SignedId(_id) {} - //inline operator QVariant() const { return QVariant::fromValue(*this); } +struct IdentityId : public SignedId +{ + inline IdentityId(int _id = 0) + : SignedId(_id) + {} + // inline operator QVariant() const { return QVariant::fromValue(*this); } }; -struct AccountId : public SignedId { - inline AccountId(int _id = 0) : SignedId(_id) {} +struct AccountId : public SignedId +{ + inline AccountId(int _id = 0) + : SignedId(_id) + {} }; Q_DECLARE_METATYPE(UserId) @@ -147,9 +202,9 @@ using BufferIdList = QList; * @param[in] value Value to serialize * @returns A reference to the stream */ -template::value>::type> -QDataStream &operator<<(QDataStream &out, T value) { +template::value>::type> +QDataStream& operator<<(QDataStream& out, T value) +{ out << static_cast::type>(value); return out; } @@ -161,9 +216,9 @@ QDataStream &operator<<(QDataStream &out, T value) { * @param[out] value Value to deserialize into * @returns A reference to the stream */ -template::value>::type> -QDataStream &operator>>(QDataStream &in, T &value) { +template::value>::type> +QDataStream& operator>>(QDataStream& in, T& value) +{ typename std::underlying_type::type v; in >> v; value = static_cast(v); @@ -181,5 +236,7 @@ struct ExitException QString errorString; ExitException(int code = EXIT_FAILURE, QString error = {}) - : exitCode(code), errorString(std::move(error)) {} + : exitCode(code) + , errorString(std::move(error)) + {} }; diff --git a/src/common/util.cpp b/src/common/util.cpp index c6d50c11..2b1bd8d9 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -33,16 +33,14 @@ #include "quassel.h" // MIBenum values from http://www.iana.org/assignments/character-sets/character-sets.xml#table-character-sets-1 -static QList utf8DetectionBlacklist = QList() - << 39 /* ISO-2022-JP */; +static QList utf8DetectionBlacklist = QList() << 39 /* ISO-2022-JP */; -QString nickFromMask(const QString &mask) +QString nickFromMask(const QString& mask) { return mask.left(mask.indexOf('!')); } - -QString userFromMask(const QString &mask) +QString userFromMask(const QString& mask) { const int offset = mask.indexOf('!') + 1; if (offset <= 0) @@ -51,8 +49,7 @@ QString userFromMask(const QString &mask) return mask.mid(offset, length >= 0 ? length : -1); } - -QString hostFromMask(const QString &mask) +QString hostFromMask(const QString& mask) { const int excl = mask.indexOf('!'); if (excl < 0) @@ -61,8 +58,7 @@ QString hostFromMask(const QString &mask) return offset > 0 && offset < mask.size() ? mask.mid(offset) : QString{}; } - -bool isChannelName(const QString &str) +bool isChannelName(const QString& str) { if (str.isEmpty()) return false; @@ -70,19 +66,18 @@ bool isChannelName(const QString &str) return std::any_of(prefixes.cbegin(), prefixes.cend(), [&str](quint8 c) { return c == str[0]; }); } - QString stripFormatCodes(QString message) { static QRegExp regEx{"\x03(\\d\\d?(,\\d\\d?)?)?|\x04([\\da-fA-F]{6}(,[\\da-fA-F]{6})?)?|[\x02\x0f\x11\x12\x16\x1d\x1e\x1f]"}; return message.remove(regEx); } - -QString stripAcceleratorMarkers(const QString &label_) +QString stripAcceleratorMarkers(const QString& label_) { QString label = label_; int p = 0; - forever { + forever + { p = label.indexOf('&', p); if (p < 0 || p + 1 >= label.length()) break; @@ -95,8 +90,7 @@ QString stripAcceleratorMarkers(const QString &label_) return label; } - -QString decodeString(const QByteArray &input, QTextCodec *codec) +QString decodeString(const QByteArray& input, QTextCodec* codec) { if (codec && utf8DetectionBlacklist.contains(codec->mibEnum())) return codec->toUnicode(input); @@ -110,32 +104,46 @@ QString decodeString(const QByteArray &input, QTextCodec *codec) for (uchar c : input) { if (cnt) { // We check a part of a multibyte char. These need to be of the form 10yyyyyy. - if ((c & 0xc0) != 0x80) { isUtf8 = false; break; } + if ((c & 0xc0) != 0x80) { + isUtf8 = false; + break; + } cnt--; continue; } - if ((c & 0x80) == 0x00) continue; // 7 bit is always ok - if ((c & 0xf8) == 0xf0) { cnt = 3; continue; } // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv - if ((c & 0xf0) == 0xe0) { cnt = 2; continue; } // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz - if ((c & 0xe0) == 0xc0) { cnt = 1; continue; } // 2-byte char 110xxxxx 10yyyyyy - isUtf8 = false; break; // 8 bit char, but not utf8! + if ((c & 0x80) == 0x00) + continue; // 7 bit is always ok + if ((c & 0xf8) == 0xf0) { + cnt = 3; + continue; + } // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv + if ((c & 0xf0) == 0xe0) { + cnt = 2; + continue; + } // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz + if ((c & 0xe0) == 0xc0) { + cnt = 1; + continue; + } // 2-byte char 110xxxxx 10yyyyyy + isUtf8 = false; + break; // 8 bit char, but not utf8! } if (isUtf8 && cnt == 0) { QString s = QString::fromUtf8(input); - //qDebug() << "Detected utf8:" << s; + // qDebug() << "Detected utf8:" << s; return s; } - //QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1()); - if (!codec) return QString::fromLatin1(input); + // QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1()); + if (!codec) + return QString::fromLatin1(input); return codec->toUnicode(input); } - -uint editingDistance(const QString &s1, const QString &s2) +uint editingDistance(const QString& s1, const QString& s2) { - uint n = s1.size()+1; - uint m = s2.size()+1; - QVector > matrix(n, QVector(m, 0)); + uint n = s1.size() + 1; + uint m = s2.size() + 1; + QVector> matrix(n, QVector(m, 0)); for (uint i = 0; i < n; i++) matrix[i][0] = i; @@ -146,16 +154,16 @@ uint editingDistance(const QString &s1, const QString &s2) uint min; for (uint i = 1; i < n; i++) { for (uint j = 1; j < m; j++) { - uint deleteChar = matrix[i-1][j] + 1; - uint insertChar = matrix[i][j-1] + 1; + uint deleteChar = matrix[i - 1][j] + 1; + uint insertChar = matrix[i][j - 1] + 1; if (deleteChar < insertChar) min = deleteChar; else min = insertChar; - if (s1[i-1] == s2[j-1]) { - uint inheritChar = matrix[i-1][j-1]; + if (s1[i - 1] == s2[j - 1]) { + uint inheritChar = matrix[i - 1][j - 1]; if (inheritChar < min) min = inheritChar; } @@ -163,23 +171,22 @@ uint editingDistance(const QString &s1, const QString &s2) matrix[i][j] = min; } } - return matrix[n-1][m-1]; + return matrix[n - 1][m - 1]; } - QString secondsToString(int timeInSeconds) { - static QVector> timeUnit { - std::make_pair(365*24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "year")), - std::make_pair(24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "day")), - std::make_pair(60*60, QCoreApplication::translate("Quassel::secondsToString()", "h")), - std::make_pair(60, QCoreApplication::translate("Quassel::secondsToString()", "min")), - std::make_pair(1, QCoreApplication::translate("Quassel::secondsToString()", "sec")) - }; + static QVector> timeUnit{std::make_pair(365 * 24 * 60 * 60, + QCoreApplication::translate("Quassel::secondsToString()", "year")), + std::make_pair(24 * 60 * 60, + QCoreApplication::translate("Quassel::secondsToString()", "day")), + std::make_pair(60 * 60, QCoreApplication::translate("Quassel::secondsToString()", "h")), + std::make_pair(60, QCoreApplication::translate("Quassel::secondsToString()", "min")), + std::make_pair(1, QCoreApplication::translate("Quassel::secondsToString()", "sec"))}; if (timeInSeconds != 0) { QStringList returnString; - for (const auto &tu : timeUnit) { + for (const auto& tu : timeUnit) { int n = timeInSeconds / tu.first; if (n > 0) { returnString += QString("%1 %2").arg(QString::number(n), tu.second); @@ -192,8 +199,7 @@ QString secondsToString(int timeInSeconds) return QString("%1 %2").arg(QString::number(timeInSeconds), timeUnit.last().second); } - -QByteArray prettyDigest(const QByteArray &digest) +QByteArray prettyDigest(const QByteArray& digest) { QByteArray hexDigest = digest.toHex().toUpper(); QByteArray prettyDigest; @@ -205,8 +211,7 @@ QByteArray prettyDigest(const QByteArray &digest) return prettyDigest; } - -QString formatCurrentDateTimeInString(const QString &formatStr) +QString formatCurrentDateTimeInString(const QString& formatStr) { // Work on a copy of the string to avoid modifying the input string QString formattedStr = QString(formatStr); @@ -255,21 +260,23 @@ QString formatCurrentDateTimeInString(const QString &formatStr) if (matchedFormat.length() > 0) { // Format the string according to the current date and time. Invalid time format // strings are ignored. - formattedStr.replace(index, matchLength, - QDateTime::currentDateTime().toString(matchedFormat)); + formattedStr.replace(index, matchLength, QDateTime::currentDateTime().toString(matchedFormat)); // Subtract the length of the removed % signs // E.g. "%%h:mm ap%%" turns into "h:mm ap", removing four % signs, thus -4. This is // used below to determine how far to advance when looking for the next formatting code. matchLength -= 4; - } else if (matchLength == 4) { + } + else if (matchLength == 4) { // Remove two of the four percent signs, so '%%%%' escapes to '%%' formattedStr.remove(index, 2); // Subtract the length of the removed % signs, this time removing two % signs, thus -2. matchLength -= 2; - } else { + } + else { // If neither of these match, something went wrong. Don't modify it to be safe. qDebug() << "Unexpected time format when parsing string, no matchedFormat, matchLength " - "should be 4, actually is" << matchLength; + "should be 4, actually is" + << matchLength; } // Find the next group of %%text here%% starting from where the last group ended @@ -280,8 +287,7 @@ QString formatCurrentDateTimeInString(const QString &formatStr) return formattedStr; } - -QString tryFormatUnixEpoch(const QString &possibleEpochDate, Qt::DateFormat dateFormat, bool useUTC) +QString tryFormatUnixEpoch(const QString& possibleEpochDate, Qt::DateFormat dateFormat, bool useUTC) { // Does the string resemble a Unix epoch? Parse as 64-bit time qint64 secsSinceEpoch = possibleEpochDate.toLongLong(); @@ -317,21 +323,23 @@ QString tryFormatUnixEpoch(const QString &possibleEpochDate, Qt::DateFormat date // See https://en.wikipedia.org/wiki/ISO_8601#cite_note-32 // And https://www.ietf.org/rfc/rfc3339.txt return date.toUTC().toString(dateFormat).replace(10, 1, " "); - } else { + } + else { return date.toUTC().toString(dateFormat); } - } else if (dateFormat == Qt::DateFormat::ISODate) { + } + else if (dateFormat == Qt::DateFormat::ISODate) { // Add in ISO local timezone information via special handling below // formatDateTimeToOffsetISO() handles converting "T" to " " return formatDateTimeToOffsetISO(date); - } else { + } + else { // Return local time return date.toString(dateFormat); } } - -QString formatDateTimeToOffsetISO(const QDateTime &dateTime) +QString formatDateTimeToOffsetISO(const QDateTime& dateTime) { if (!dateTime.isValid()) { // Don't try to do anything with invalid date/time diff --git a/src/common/util.h b/src/common/util.h index cead16fa..6b29ea5c 100644 --- a/src/common/util.h +++ b/src/common/util.h @@ -26,16 +26,16 @@ #include #include -COMMON_EXPORT QString nickFromMask(const QString &mask); -COMMON_EXPORT QString userFromMask(const QString &mask); -COMMON_EXPORT QString hostFromMask(const QString &mask); -COMMON_EXPORT bool isChannelName(const QString &str); +COMMON_EXPORT QString nickFromMask(const QString& mask); +COMMON_EXPORT QString userFromMask(const QString& mask); +COMMON_EXPORT QString hostFromMask(const QString& mask); +COMMON_EXPORT bool isChannelName(const QString& str); //! Strip mIRC format codes COMMON_EXPORT QString stripFormatCodes(QString); //! Remove accelerator markers (&) from the string -COMMON_EXPORT QString stripAcceleratorMarkers(const QString &); +COMMON_EXPORT QString stripAcceleratorMarkers(const QString&); COMMON_EXPORT QString secondsToString(int timeInSeconds); @@ -46,12 +46,12 @@ COMMON_EXPORT QString secondsToString(int timeInSeconds); * \param codec The text codec we use if the input is not utf8 * \return The decoded string. */ -COMMON_EXPORT QString decodeString(const QByteArray &input, QTextCodec *codec = nullptr); +COMMON_EXPORT QString decodeString(const QByteArray& input, QTextCodec* codec = nullptr); -COMMON_EXPORT uint editingDistance(const QString &s1, const QString &s2); +COMMON_EXPORT uint editingDistance(const QString& s1, const QString& s2); template -QVariantList toVariantList(const QList &list) +QVariantList toVariantList(const QList& list) { QVariantList variants; for (int i = 0; i < list.count(); i++) { @@ -60,9 +60,8 @@ QVariantList toVariantList(const QList &list) return variants; } - template -QList fromVariantList(const QVariantList &variants) +QList fromVariantList(const QVariantList& variants) { QList list; for (int i = 0; i < variants.count(); i++) { @@ -71,8 +70,7 @@ QList fromVariantList(const QVariantList &variants) return list; } - -COMMON_EXPORT QByteArray prettyDigest(const QByteArray &digest); +COMMON_EXPORT QByteArray prettyDigest(const QByteArray& digest); /** * Format a string with %%%% to current date/timestamp via QDateTime. @@ -80,7 +78,7 @@ COMMON_EXPORT QByteArray prettyDigest(const QByteArray &digest); * @param[in] formatStr String with format codes * @return String with current date/time substituted in via formatting codes */ -COMMON_EXPORT QString formatCurrentDateTimeInString(const QString &formatStr); +COMMON_EXPORT QString formatCurrentDateTimeInString(const QString& formatStr); /** * Try to localize a given date/time in seconds from Unix epoch, pass through string if invalid @@ -93,29 +91,31 @@ COMMON_EXPORT QString formatCurrentDateTimeInString(const QString &formatStr); * @param useUTC If true, use UTC timezone, otherwise use local time * @return Localized date/time if parse succeeded, otherwise the source string */ -COMMON_EXPORT QString tryFormatUnixEpoch(const QString &possibleEpochDate, +COMMON_EXPORT QString tryFormatUnixEpoch(const QString& possibleEpochDate, Qt::DateFormat dateFormat = Qt::DateFormat::TextDate, bool useUTC = false); - /** * Format the given date/time in ISO 8601 format with timezone offset * * @param dateTime Date/time of interest * @return Date/time in ISO 8601 format with timezone offset */ -COMMON_EXPORT QString formatDateTimeToOffsetISO(const QDateTime &dateTime); +COMMON_EXPORT QString formatDateTimeToOffsetISO(const QDateTime& dateTime); namespace detail { -template +template struct SelectOverloadHelper { - template - constexpr auto operator()(R(C::*func)(Args...)) const noexcept -> decltype(func) { return func; } + template + constexpr auto operator()(R (C::*func)(Args...)) const noexcept -> decltype(func) + { + return func; + } }; -} // detail +} // namespace detail /** * Helper for resolving ambiguous overloads when using the member function-based connect syntax. @@ -127,5 +127,5 @@ struct SelectOverloadHelper * * @tparam Args Argument types of the desired signature */ -template +template constexpr Q_DECL_UNUSED detail::SelectOverloadHelper selectOverload = {}; diff --git a/src/common/windowssignalwatcher.cpp b/src/common/windowssignalwatcher.cpp index 5c9a4815..f31e0383 100644 --- a/src/common/windowssignalwatcher.cpp +++ b/src/common/windowssignalwatcher.cpp @@ -33,17 +33,17 @@ // condition variable once shutdown is complete... static BOOL WINAPI consoleCtrlHandler(DWORD ctrlType) { - switch (ctrlType) { - case CTRL_C_EVENT: // Ctrl+C - case CTRL_CLOSE_EVENT: // Closing the console window - WindowsSignalWatcher::signalHandler(SIGTERM); - return TRUE; - default: - return FALSE; - } + switch (ctrlType) { + case CTRL_C_EVENT: // Ctrl+C + case CTRL_CLOSE_EVENT: // Closing the console window + WindowsSignalWatcher::signalHandler(SIGTERM); + return TRUE; + default: + return FALSE; + } } -WindowsSignalWatcher::WindowsSignalWatcher(QObject *parent) +WindowsSignalWatcher::WindowsSignalWatcher(QObject* parent) : AbstractSignalWatcher{parent} , Singleton{this} { diff --git a/src/common/windowssignalwatcher.h b/src/common/windowssignalwatcher.h index 923d3341..e6c3ddfc 100644 --- a/src/common/windowssignalwatcher.h +++ b/src/common/windowssignalwatcher.h @@ -30,7 +30,7 @@ class WindowsSignalWatcher : public AbstractSignalWatcher, private Singleton::iterator conIter; + QHash::iterator conIter; for (conIter = _connectionPool.begin(); conIter != _connectionPool.end(); ++conIter) { QSqlDatabase::removeDatabase(conIter.value()->name()); disconnect(conIter.value(), nullptr, this, nullptr); } } - QSqlDatabase AbstractSqlStorage::logDb() { if (!_connectionPool.contains(QThread::currentThread())) addConnectionToPool(); - QSqlDatabase db = QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name(),false); + QSqlDatabase db = QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name(), false); if (!db.isOpen()) { - qWarning() << "Database connection" << displayName() << "for thread" << QThread::currentThread() << "was lost, attempting to reconnect..."; + qWarning() << "Database connection" << displayName() << "for thread" << QThread::currentThread() + << "was lost, attempting to reconnect..."; dbConnect(db); } return db; } - void AbstractSqlStorage::addConnectionToPool() { QMutexLocker locker(&_connectionPoolMutex); @@ -71,11 +68,11 @@ void AbstractSqlStorage::addConnectionToPool() if (_connectionPool.contains(QThread::currentThread())) return; - QThread *currentThread = QThread::currentThread(); + QThread* currentThread = QThread::currentThread(); int connectionId = _nextConnectionId++; - Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1())); + Connection* connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1())); connection->moveToThread(currentThread); connect(this, &QObject::destroyed, connection, &QObject::deleteLater); connect(currentThread, &QObject::destroyed, connection, &QObject::deleteLater); @@ -99,8 +96,7 @@ void AbstractSqlStorage::addConnectionToPool() dbConnect(db); } - -void AbstractSqlStorage::dbConnect(QSqlDatabase &db) +void AbstractSqlStorage::dbConnect(QSqlDatabase& db) { if (!db.open()) { quWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread(); @@ -114,10 +110,7 @@ void AbstractSqlStorage::dbConnect(QSqlDatabase &db) } } - -Storage::State AbstractSqlStorage::init(const QVariantMap &settings, - const QProcessEnvironment &environment, - bool loadFromEnvironment) +Storage::State AbstractSqlStorage::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) { setConnectionProperties(settings, environment, loadFromEnvironment); @@ -139,8 +132,9 @@ Storage::State AbstractSqlStorage::init(const QVariantMap &settings, if (installedSchemaVersion() < schemaVersion()) { quInfo() << qPrintable(tr("Installed database schema (version %1) is not up to date. Upgrading to " - "version %2... This may take a while for major upgrades." - ).arg(installedSchemaVersion()).arg(schemaVersion())); + "version %2... This may take a while for major upgrades.") + .arg(installedSchemaVersion()) + .arg(schemaVersion())); emit dbUpgradeInProgress(true); auto upgradeResult = upgradeDb(); emit dbUpgradeInProgress(false); @@ -157,8 +151,7 @@ Storage::State AbstractSqlStorage::init(const QVariantMap &settings, return IsReady; } - -QString AbstractSqlStorage::queryString(const QString &queryName, int version) +QString AbstractSqlStorage::queryString(const QString& queryName, int version) { QFileInfo queryInfo; @@ -168,10 +161,10 @@ QString AbstractSqlStorage::queryString(const QString &queryName, int version) // Use the current SQL schema, not a versioned request queryInfo = QFileInfo(QString(":/SQL/%1/%2.sql").arg(displayName()).arg(queryName)); // If version is needed later, get it via version = schemaVersion(); - } else { + } + else { // Use the specified schema version, not the general folder - queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql") - .arg(displayName()).arg(version).arg(queryName)); + queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql").arg(displayName()).arg(version).arg(queryName)); } if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) { @@ -188,21 +181,18 @@ QString AbstractSqlStorage::queryString(const QString &queryName, int version) return query.trimmed(); } - QStringList AbstractSqlStorage::setupQueries() { QStringList queries; // The current schema is stored in the root folder, including setup scripts. QDir dir = QDir(QString(":/SQL/%1/").arg(displayName())); - foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) { + foreach (QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) { queries << queryString(fileInfo.baseName()); } return queries; } - -bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnvironment &environment, - bool loadFromEnvironment) +bool AbstractSqlStorage::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) { setConnectionProperties(settings, environment, loadFromEnvironment); QSqlDatabase db = logDb(); @@ -212,7 +202,7 @@ bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnviro } db.transaction(); - foreach(QString queryString, setupQueries()) { + foreach (QString queryString, setupQueries()) { QSqlQuery query = db.exec(queryString); if (!watchQuery(query)) { qCritical() << "Unable to setup Logging Backend!"; @@ -228,19 +218,17 @@ bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnviro return success; } - QStringList AbstractSqlStorage::upgradeQueries(int version) { QStringList queries; // Upgrade queries are stored in the 'version/##' subfolders. QDir dir = QDir(QString(":/SQL/%1/version/%2/").arg(displayName()).arg(version)); - foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) { + foreach (QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) { queries << queryString(fileInfo.baseName(), version); } return queries; } - bool AbstractSqlStorage::upgradeDb() { if (schemaVersion() <= installedSchemaVersion()) @@ -253,12 +241,11 @@ bool AbstractSqlStorage::upgradeDb() // any database modifications that might not be allowed in a transaction. for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) { - foreach(QString queryString, upgradeQueries(ver)) { + foreach (QString queryString, upgradeQueries(ver)) { QSqlQuery query = db.exec(queryString); if (!watchQuery(query)) { // Individual upgrade query failed, bail out - qCritical() << "Unable to upgrade Logging Backend! Upgrade query in schema version" - << ver << "failed."; + qCritical() << "Unable to upgrade Logging Backend! Upgrade query in schema version" << ver << "failed."; return false; } } @@ -272,8 +259,7 @@ bool AbstractSqlStorage::upgradeDb() // version. if (!updateSchemaVersion(ver)) { // Updating the schema version failed, bail out - qCritical() << "Unable to upgrade Logging Backend! Setting schema version" - << ver << "failed."; + qCritical() << "Unable to upgrade Logging Backend! Setting schema version" << ver << "failed."; return false; } } @@ -282,8 +268,7 @@ bool AbstractSqlStorage::upgradeDb() // logging (though setting schema version really should not fail). if (!updateSchemaVersion(schemaVersion())) { // Updating the final schema version failed, bail out - qCritical() << "Unable to upgrade Logging Backend! Setting final schema version" - << schemaVersion() << "failed."; + qCritical() << "Unable to upgrade Logging Backend! Setting final schema version" << schemaVersion() << "failed."; return false; } @@ -291,7 +276,6 @@ bool AbstractSqlStorage::upgradeDb() return true; } - int AbstractSqlStorage::schemaVersion() { // returns the newest Schema Version! @@ -303,7 +287,7 @@ int AbstractSqlStorage::schemaVersion() bool ok; // Schema versions are stored in the 'version/##' subfolders. QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName())); - foreach(QFileInfo fileInfo, dir.entryInfoList()) { + foreach (QFileInfo fileInfo, dir.entryInfoList()) { if (!fileInfo.isDir()) continue; @@ -317,8 +301,7 @@ int AbstractSqlStorage::schemaVersion() return _schemaVersion; } - -bool AbstractSqlStorage::watchQuery(QSqlQuery &query) +bool AbstractSqlStorage::watchQuery(QSqlQuery& query) { bool queryError = query.lastError().isValid(); if (queryError || _debug) { @@ -339,7 +322,7 @@ bool AbstractSqlStorage::watchQuery(QSqlQuery &query) field.clear(); else field.setValue(iter.value()); - value = query.driver()->formatValue(field); + value = query.driver()->formatValue(field); } else { switch (iter.value().type()) { @@ -366,23 +349,19 @@ bool AbstractSqlStorage::watchQuery(QSqlQuery &query) return true; } - void AbstractSqlStorage::connectionDestroyed() { QMutexLocker locker(&_connectionPoolMutex); _connectionPool.remove(sender()->thread()); } - // ======================================== // AbstractSqlStorage::Connection // ======================================== -AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent) - : QObject(parent), - _name(name.toLatin1()) -{ -} - +AbstractSqlStorage::Connection::Connection(const QString& name, QObject* parent) + : QObject(parent) + , _name(name.toLatin1()) +{} AbstractSqlStorage::Connection::~Connection() { @@ -396,26 +375,23 @@ AbstractSqlStorage::Connection::~Connection() QSqlDatabase::removeDatabase(name()); } - // ======================================== // AbstractSqlMigrator // ======================================== -void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db) +void AbstractSqlMigrator::newQuery(const QString& query, QSqlDatabase db) { Q_ASSERT(!_query); _query = new QSqlQuery(db); _query->prepare(query); } - void AbstractSqlMigrator::resetQuery() { delete _query; _query = nullptr; } - bool AbstractSqlMigrator::exec() { Q_ASSERT(_query); @@ -423,7 +399,6 @@ bool AbstractSqlMigrator::exec() return !_query->lastError().isValid(); } - QString AbstractSqlMigrator::migrationObject(MigrationObject moType) { switch (moType) { @@ -451,7 +426,6 @@ QString AbstractSqlMigrator::migrationObject(MigrationObject moType) return QString(); } - QVariantList AbstractSqlMigrator::boundValues() { QVariantList values; @@ -465,7 +439,6 @@ QVariantList AbstractSqlMigrator::boundValues() return values; } - void AbstractSqlMigrator::dumpStatus() { qWarning() << " executed Query:"; @@ -474,21 +447,18 @@ void AbstractSqlMigrator::dumpStatus() QList list = boundValues(); for (int i = 0; i < list.size(); ++i) qWarning() << i << ": " << list.at(i).toString().toLatin1().data(); - qWarning() << " Error Number:" << lastError().number(); - qWarning() << " Error Message:" << lastError().text(); + qWarning() << " Error Number:" << lastError().number(); + qWarning() << " Error Message:" << lastError().text(); } - // ======================================== // AbstractSqlMigrationReader // ======================================== AbstractSqlMigrationReader::AbstractSqlMigrationReader() : AbstractSqlMigrator() -{ -} +{} - -bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) +bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter* writer) { if (!transaction()) { qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!"; @@ -496,7 +466,7 @@ bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) } if (!writer->transaction()) { qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!"; - rollback(); // close the reader transaction; + rollback(); // close the reader transaction; return false; } @@ -548,8 +518,7 @@ bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) return finalizeMigration(); } - -void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) +void AbstractSqlMigrationReader::abortMigration(const QString& errorMsg) { qWarning() << "Migration Failed!"; if (!errorMsg.isNull()) { @@ -570,7 +539,6 @@ void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) _writer = nullptr; } - bool AbstractSqlMigrationReader::finalizeMigration() { resetQuery(); @@ -585,19 +553,20 @@ bool AbstractSqlMigrationReader::finalizeMigration() return true; } - template -bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) +bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T& mo) { resetQuery(); _writer->resetQuery(); if (!prepareQuery(moType)) { - abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType))); + abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!") + .arg(AbstractSqlMigrator::migrationObject(moType))); return false; } if (!_writer->prepareQuery(moType)) { - abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType))); + abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!") + .arg(AbstractSqlMigrator::migrationObject(moType))); return false; } @@ -608,7 +577,8 @@ bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) while (readMo(mo)) { if (!_writer->writeMo(mo)) { - abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType))); + abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!") + .arg(AbstractSqlMigrator::migrationObject(moType))); return false; } i++; @@ -626,12 +596,12 @@ bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) return true; } -uint qHash(const SenderData &key) { +uint qHash(const SenderData& key) +{ return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl)); } -bool operator==(const SenderData &a, const SenderData &b) { - return a.sender == b.sender && - a.realname == b.realname && - a.avatarurl == b.avatarurl; +bool operator==(const SenderData& a, const SenderData& b) +{ + return a.sender == b.sender && a.realname == b.realname && a.avatarurl == b.avatarurl; } diff --git a/src/core/abstractsqlstorage.h b/src/core/abstractsqlstorage.h index efd1ce39..7075db96 100644 --- a/src/core/abstractsqlstorage.h +++ b/src/core/abstractsqlstorage.h @@ -20,13 +20,13 @@ #pragma once -#include "storage.h" - #include #include -#include #include +#include + +#include "storage.h" class AbstractSqlMigrationReader; class AbstractSqlMigrationWriter; @@ -36,22 +36,22 @@ class AbstractSqlStorage : public Storage Q_OBJECT public: - AbstractSqlStorage(QObject *parent = nullptr); + AbstractSqlStorage(QObject* parent = nullptr); ~AbstractSqlStorage() override; virtual std::unique_ptr createMigrationReader() { return {}; } virtual std::unique_ptr createMigrationWriter() { return {}; } public slots: - State init(const QVariantMap &settings = QVariantMap(), - const QProcessEnvironment &environment = {}, - bool loadFromEnvironment = false) override; - bool setup(const QVariantMap &settings = QVariantMap(), - const QProcessEnvironment &environment = {}, - bool loadFromEnvironment = false) override; + State init(const QVariantMap& settings = QVariantMap(), + const QProcessEnvironment& environment = {}, + bool loadFromEnvironment = false) override; + bool setup(const QVariantMap& settings = QVariantMap(), + const QProcessEnvironment& environment = {}, + bool loadFromEnvironment = false) override; protected: - inline void sync() override {}; + inline void sync() override{}; QSqlDatabase logDb(); @@ -72,23 +72,21 @@ protected: * @endparblock * @return String with the requested SQL query, ready for parameter substitution */ - QString queryString(const QString &queryName, int version = 0); + QString queryString(const QString& queryName, int version = 0); QStringList setupQueries(); QStringList upgradeQueries(int ver); bool upgradeDb(); - bool watchQuery(QSqlQuery &query); + bool watchQuery(QSqlQuery& query); int schemaVersion(); virtual int installedSchemaVersion() { return -1; }; virtual bool updateSchemaVersion(int newVersion) = 0; virtual bool setupSchemaVersion(int version) = 0; - virtual void setConnectionProperties(const QVariantMap &properties, - const QProcessEnvironment &environment, - bool loadFromEnvironment) = 0; + virtual void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) = 0; virtual QString driverName() = 0; inline virtual QString hostName() { return QString(); } inline virtual int port() { return -1; } @@ -103,14 +101,14 @@ protected: * When reimplementing this method, don't use logDB() inside this function as * this would cause as we're just about to initialize that DB connection. */ - inline virtual bool initDbSession(QSqlDatabase & /* db */) { return true; } + inline virtual bool initDbSession(QSqlDatabase& /* db */) { return true; } private slots: void connectionDestroyed(); private: void addConnectionToPool(); - void dbConnect(QSqlDatabase &db); + void dbConnect(QSqlDatabase& db); int _schemaVersion{0}; bool _debug; @@ -121,16 +119,17 @@ private: // those objects reside in the thread the connection belongs to // which allows us thread safe termination of a connection class Connection; - QHash _connectionPool; + QHash _connectionPool; }; -struct SenderData { +struct SenderData +{ QString sender; QString realname; QString avatarurl; - friend uint qHash(const SenderData &key); - friend bool operator==(const SenderData &a, const SenderData &b); + friend uint qHash(const SenderData& key); + friend bool operator==(const SenderData& a, const SenderData& b); }; // ======================================== @@ -141,7 +140,7 @@ class AbstractSqlStorage::Connection : public QObject Q_OBJECT public: - Connection(const QString &name, QObject *parent = nullptr); + Connection(const QString& name, QObject* parent = nullptr); ~Connection() override; inline QLatin1String name() const { return QLatin1String(_name); } @@ -150,7 +149,6 @@ private: QByteArray _name; }; - // ======================================== // AbstractSqlMigrator // ======================================== @@ -158,7 +156,8 @@ class AbstractSqlMigrator { public: // migration objects - struct QuasselUserMO { + struct QuasselUserMO + { UserId id; QString username; QString password; @@ -166,14 +165,16 @@ public: QString authenticator; }; - struct SenderMO { + struct SenderMO + { qint64 senderId{0}; QString sender; QString realname; QString avatarurl; }; - struct IdentityMO { + struct IdentityMO + { IdentityId id; UserId userid; QString identityname; @@ -197,13 +198,15 @@ public: QByteArray sslKey; }; - struct IdentityNickMO { + struct IdentityNickMO + { int nickid; IdentityId identityId; QString nick; }; - struct NetworkMO { + struct NetworkMO + { UserId userid; QString networkname; QString perform; @@ -235,7 +238,8 @@ public: bool connected; }; - struct BufferMO { + struct BufferMO + { BufferId bufferid; UserId userid; int groupid; @@ -253,9 +257,10 @@ public: QString cipher; }; - struct BacklogMO { + struct BacklogMO + { MsgId messageid; - QDateTime time; // has to be in UTC! + QDateTime time; // has to be in UTC! BufferId bufferid; int type; int flags; @@ -264,7 +269,8 @@ public: QString message; }; - struct IrcServerMO { + struct IrcServerMO + { int serverid; UserId userid; NetworkId networkid; @@ -272,7 +278,7 @@ public: int port; QString password; bool ssl; - bool sslverify; /// If true, validate SSL certificates + bool sslverify; /// If true, validate SSL certificates int sslversion; bool useproxy; int proxytype; @@ -282,18 +288,21 @@ public: QString proxypass; }; - struct UserSettingMO { + struct UserSettingMO + { UserId userid; QString settingname; QByteArray settingvalue; }; - struct CoreStateMO { + struct CoreStateMO + { QString key; QByteArray value; }; - enum MigrationObject { + enum MigrationObject + { QuasselUser, Sender, Identity, @@ -311,14 +320,14 @@ public: static QString migrationObject(MigrationObject moType); protected: - void newQuery(const QString &query, QSqlDatabase db); + void newQuery(const QString& query, QSqlDatabase db); virtual void resetQuery(); virtual bool prepareQuery(MigrationObject mo) = 0; bool exec(); inline bool next() { return _query->next(); } inline QVariant value(int index) { return _query->value(index); } - inline void bindValue(const QString &placeholder, const QVariant &val) { _query->bindValue(placeholder, val); } - inline void bindValue(int pos, const QVariant &val) { _query->bindValue(pos, val); } + inline void bindValue(const QString& placeholder, const QVariant& val) { _query->bindValue(placeholder, val); } + inline void bindValue(int pos, const QVariant& val) { _query->bindValue(pos, val); } inline QSqlError lastError() { return _query ? _query->lastError() : QSqlError(); } void dumpStatus(); @@ -330,53 +339,52 @@ protected: virtual bool commit() = 0; private: - QSqlQuery *_query{nullptr}; + QSqlQuery* _query{nullptr}; }; - class AbstractSqlMigrationReader : public AbstractSqlMigrator { public: AbstractSqlMigrationReader(); - virtual bool readMo(QuasselUserMO &user) = 0; - virtual bool readMo(IdentityMO &identity) = 0; - virtual bool readMo(IdentityNickMO &identityNick) = 0; - virtual bool readMo(NetworkMO &network) = 0; - virtual bool readMo(BufferMO &buffer) = 0; - virtual bool readMo(SenderMO &sender) = 0; - virtual bool readMo(BacklogMO &backlog) = 0; - virtual bool readMo(IrcServerMO &ircserver) = 0; - virtual bool readMo(UserSettingMO &userSetting) = 0; - virtual bool readMo(CoreStateMO &coreState) = 0; + virtual bool readMo(QuasselUserMO& user) = 0; + virtual bool readMo(IdentityMO& identity) = 0; + virtual bool readMo(IdentityNickMO& identityNick) = 0; + virtual bool readMo(NetworkMO& network) = 0; + virtual bool readMo(BufferMO& buffer) = 0; + virtual bool readMo(SenderMO& sender) = 0; + virtual bool readMo(BacklogMO& backlog) = 0; + virtual bool readMo(IrcServerMO& ircserver) = 0; + virtual bool readMo(UserSettingMO& userSetting) = 0; + virtual bool readMo(CoreStateMO& coreState) = 0; - bool migrateTo(AbstractSqlMigrationWriter *writer); + bool migrateTo(AbstractSqlMigrationWriter* writer); private: - void abortMigration(const QString &errorMsg = QString()); + void abortMigration(const QString& errorMsg = QString()); bool finalizeMigration(); - template bool transferMo(MigrationObject moType, T &mo); + template + bool transferMo(MigrationObject moType, T& mo); - AbstractSqlMigrationWriter *_writer{nullptr}; + AbstractSqlMigrationWriter* _writer{nullptr}; }; - class AbstractSqlMigrationWriter : public AbstractSqlMigrator { public: - virtual bool writeMo(const QuasselUserMO &user) = 0; - virtual bool writeMo(const IdentityMO &identity) = 0; - virtual bool writeMo(const IdentityNickMO &identityNick) = 0; - virtual bool writeMo(const NetworkMO &network) = 0; - virtual bool writeMo(const BufferMO &buffer) = 0; - virtual bool writeMo(const SenderMO &sender) = 0; - virtual bool writeMo(const BacklogMO &backlog) = 0; - virtual bool writeMo(const IrcServerMO &ircserver) = 0; - virtual bool writeMo(const UserSettingMO &userSetting) = 0; - virtual bool writeMo(const CoreStateMO &coreState) = 0; - - inline bool migrateFrom(AbstractSqlMigrationReader *reader) { return reader->migrateTo(this); } + virtual bool writeMo(const QuasselUserMO& user) = 0; + virtual bool writeMo(const IdentityMO& identity) = 0; + virtual bool writeMo(const IdentityNickMO& identityNick) = 0; + virtual bool writeMo(const NetworkMO& network) = 0; + virtual bool writeMo(const BufferMO& buffer) = 0; + virtual bool writeMo(const SenderMO& sender) = 0; + virtual bool writeMo(const BacklogMO& backlog) = 0; + virtual bool writeMo(const IrcServerMO& ircserver) = 0; + virtual bool writeMo(const UserSettingMO& userSetting) = 0; + virtual bool writeMo(const CoreStateMO& coreState) = 0; + + inline bool migrateFrom(AbstractSqlMigrationReader* reader) { return reader->migrateTo(this); } // called after migration process virtual inline bool postProcess() { return true; } diff --git a/src/core/authenticator.cpp b/src/core/authenticator.cpp index 4707bc72..fb8ceb03 100644 --- a/src/core/authenticator.cpp +++ b/src/core/authenticator.cpp @@ -20,4 +20,5 @@ // Make moc happy #include "authenticator.h" + #include "moc_authenticator.cpp" diff --git a/src/core/authenticator.h b/src/core/authenticator.h index ebea4c94..1e32cd51 100644 --- a/src/core/authenticator.h +++ b/src/core/authenticator.h @@ -28,21 +28,21 @@ #include "types.h" -class Authenticator : public QObject { - +class Authenticator : public QObject +{ Q_OBJECT public: using QObject::QObject; ~Authenticator() override = default; - enum State { + enum State + { IsReady, // ready to go NeedsSetup, // need basic setup (ask the user for input) NotAvailable // remove the authenticator backend from the list of avaliable authenticators. }; - public slots: // General @@ -82,22 +82,24 @@ public slots: * \param settings Hostname, port, username, password, ... * \return True if and only if the authenticator provider was initialized successfully. */ - virtual bool setup(const QVariantMap &settings = QVariantMap(), - const QProcessEnvironment &environment = {}, - bool loadFromEnvironment = false) = 0; + virtual bool setup(const QVariantMap& settings = QVariantMap(), + const QProcessEnvironment& environment = {}, + bool loadFromEnvironment = false) + = 0; //! Initialize the authenticator provider /** \param settings Hostname, port, username, password, ... * \return the State the authenticator backend is now in (see authenticator::State) */ - virtual State init(const QVariantMap &settings = QVariantMap(), - const QProcessEnvironment &environment = {}, - bool loadFromEnvironment = false) = 0; + virtual State init(const QVariantMap& settings = QVariantMap(), + const QProcessEnvironment& environment = {}, + bool loadFromEnvironment = false) + = 0; //! Validate a username with a given password. /** \param user The username to validate * \param password The user's alleged password * \return A valid UserId if the password matches the username; 0 else */ - virtual UserId validateUser(const QString &user, const QString &password) = 0; + virtual UserId validateUser(const QString& user, const QString& password) = 0; }; diff --git a/src/core/cipher.cpp b/src/core/cipher.cpp index c5a40c21..2d9bff42 100644 --- a/src/core/cipher.cpp +++ b/src/core/cipher.cpp @@ -13,23 +13,28 @@ */ #include "cipher.h" + #include "logmessage.h" Cipher::Cipher() { - m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923"); + m_primeNum = QCA::BigInteger( + "1274521622976118676957500994394419861914916474683157971994114042507645662182483432285325880488323284287731172324978281860867705095" + "6745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862" + "335062591404043092163187352352197487303798807791605274487594646923"); setType("blowfish"); } - Cipher::Cipher(QByteArray key, QString cipherType) { - m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923"); + m_primeNum = QCA::BigInteger( + "1274521622976118676957500994394419861914916474683157971994114042507645662182483432285325880488323284287731172324978281860867705095" + "6745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862" + "335062591404043092163187352352197487303798807791605274487594646923"); setKey(key); setType(cipherType); } - bool Cipher::setKey(QByteArray key) { if (key.isEmpty()) { @@ -37,102 +42,88 @@ bool Cipher::setKey(QByteArray key) return false; } - if (key.mid(0, 4).toLower() == "ecb:") - { + if (key.mid(0, 4).toLower() == "ecb:") { m_cbc = false; m_key = key.mid(4); } - //strip cbc: if included - else if (key.mid(0, 4).toLower() == "cbc:") - { + // strip cbc: if included + else if (key.mid(0, 4).toLower() == "cbc:") { m_cbc = true; m_key = key.mid(4); } - else - { -// if(Preferences::self()->encryptionType()) -// m_cbc = true; -// else -// default to CBC + else { + // if(Preferences::self()->encryptionType()) + // m_cbc = true; + // else + // default to CBC m_cbc = true; m_key = key; } return true; } - -bool Cipher::setType(const QString &type) +bool Cipher::setType(const QString& type) { - //TODO check QCA::isSupported() + // TODO check QCA::isSupported() m_type = type; return true; } - QByteArray Cipher::decrypt(QByteArray cipherText) { QByteArray pfx = ""; - bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type + bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type - //if we get cbc - if (cipherText.mid(0, 5) == "+OK *") - { - //if we have cbc + // if we get cbc + if (cipherText.mid(0, 5) == "+OK *") { + // if we have cbc if (m_cbc) cipherText = cipherText.mid(5); - //if we don't - else - { + // if we don't + else { cipherText = cipherText.mid(5); pfx = "ERROR_NONECB: "; error = true; } } - //if we get ecb - else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ") - { - //if we had cbc - if (m_cbc) - { + // if we get ecb + else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ") { + // if we had cbc + if (m_cbc) { cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5); pfx = "ERROR_NONCBC: "; error = true; } - //if we don't - else - { + // if we don't + else { if (cipherText.mid(0, 4) == "+OK ") cipherText = cipherText.mid(4); else cipherText = cipherText.mid(5); } } - //all other cases we fail + // all other cases we fail else return cipherText; QByteArray temp; // (if cbc and no error we parse cbc) || (if ecb and error we parse cbc) - if ((m_cbc && !error) || (!m_cbc && error)) - { + if ((m_cbc && !error) || (!m_cbc && error)) { temp = blowfishCBC(cipherText, false); - if (temp == cipherText) - { + if (temp == cipherText) { // kDebug("Decryption from CBC Failed"); - return cipherText+' '+'\n'; + return cipherText + ' ' + '\n'; } else cipherText = temp; } - else - { + else { temp = blowfishECB(cipherText, false); - if (temp == cipherText) - { + if (temp == cipherText) { // kDebug("Decryption from ECB Failed"); - return cipherText+' '+'\n'; + return cipherText + ' ' + '\n'; } else cipherText = temp; @@ -141,11 +132,10 @@ QByteArray Cipher::decrypt(QByteArray cipherText) // don't hate me for the mircryption reference there. if (cipherText.at(0) == 1) pfx = "\x0"; - cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here? + cipherText = pfx + cipherText + ' ' + '\n'; // FIXME(??) why is there an added space here? return cipherText; } - QByteArray Cipher::initKeyExchange() { QCA::Initializer init; @@ -156,21 +146,19 @@ QByteArray Cipher::initKeyExchange() QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray(); - //remove leading 0 + // remove leading 0 if (publicKey.length() > 135 && publicKey.at(0) == '\0') publicKey = publicKey.mid(1); return publicKey.toBase64().append('A'); } - QByteArray Cipher::parseInitKeyX(QByteArray key) { QCA::Initializer init; bool isCBC = false; - if (key.endsWith(" CBC")) - { + if (key.endsWith(" CBC")) { isCBC = true; key.chop(4); } @@ -187,7 +175,7 @@ QByteArray Cipher::parseInitKeyX(QByteArray key) QByteArray publicKey = privateKey.y().toArray().toByteArray(); - //remove leading 0 + // remove leading 0 if (publicKey.length() > 135 && publicKey.at(0) == '\0') publicKey = publicKey.mid(1); @@ -199,8 +187,9 @@ QByteArray Cipher::parseInitKeyX(QByteArray key) QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); - //remove trailing = because mircryption and fish think it's a swell idea. - while (sharedKey.endsWith('=')) sharedKey.chop(1); + // remove trailing = because mircryption and fish think it's a swell idea. + while (sharedKey.endsWith('=')) + sharedKey.chop(1); if (isCBC) sharedKey.prepend("cbc:"); @@ -213,7 +202,6 @@ QByteArray Cipher::parseInitKeyX(QByteArray key) return publicKey.toBase64().append('A'); } - bool Cipher::parseFinishKeyX(QByteArray key) { QCA::Initializer init; @@ -235,34 +223,33 @@ bool Cipher::parseFinishKeyX(QByteArray key) QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); - //remove trailng = because mircryption and fish think it's a swell idea. - while (sharedKey.endsWith('=')) sharedKey.chop(1); + // remove trailng = because mircryption and fish think it's a swell idea. + while (sharedKey.endsWith('=')) + sharedKey.chop(1); bool success = setKey(sharedKey); return success; } - QByteArray Cipher::decryptTopic(QByteArray cipherText) { - if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic + if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic cipherText = cipherText.mid(4); else if (cipherText.left(5) == "«m«") - cipherText = cipherText.mid(5, cipherText.length()-10); + cipherText = cipherText.mid(5, cipherText.length() - 10); else return cipherText; QByteArray temp; - //TODO currently no backwards sanity checks for topic, it seems to use different standards - //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings + // TODO currently no backwards sanity checks for topic, it seems to use different standards + // if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings if (m_cbc) temp = blowfishCBC(cipherText.mid(1), false); else temp = blowfishECB(cipherText, false); - if (temp == cipherText) - { + if (temp == cipherText) { return cipherText; } else @@ -274,31 +261,26 @@ QByteArray Cipher::decryptTopic(QByteArray cipherText) return cipherText; } - -bool Cipher::encrypt(QByteArray &cipherText) +bool Cipher::encrypt(QByteArray& cipherText) { - if (cipherText.left(3) == "+p ") //don't encode if...? + if (cipherText.left(3) == "+p ") // don't encode if...? cipherText = cipherText.mid(3); - else - { - if (m_cbc) //encode in ecb or cbc decide how to determine later + else { + if (m_cbc) // encode in ecb or cbc decide how to determine later { QByteArray temp = blowfishCBC(cipherText, true); - if (temp == cipherText) - { + if (temp == cipherText) { // kDebug("CBC Encoding Failed"); return false; } cipherText = "+OK *" + temp; } - else - { + else { QByteArray temp = blowfishECB(cipherText, true); - if (temp == cipherText) - { + if (temp == cipherText) { // kDebug("ECB Encoding Failed"); return false; } @@ -309,27 +291,26 @@ bool Cipher::encrypt(QByteArray &cipherText) return true; } - -//THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING +// THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; - if (direction) - { + if (direction) { // make sure cipherText is an interval of 8 bits. We do this before so that we // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail - while ((temp.length() % 8) != 0) temp.append('\0'); + while ((temp.length() % 8) != 0) + temp.append('\0'); QCA::InitializationVector iv(8); - temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation + temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation } - else - { + else { temp = QByteArray::fromBase64(temp); - //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy' - //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES - while ((temp.length() % 8) != 0) temp.append('\0'); + // supposedly nescessary if we get a truncated message also allows for decryption of 'crazy' + // en/decoding clients that use STANDARDIZED PADDING TECHNIQUES + while ((temp.length() % 8) != 0) + temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; @@ -340,33 +321,32 @@ QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction) if (!cipher.ok()) return cipherText; - if (direction) //send in base64 + if (direction) // send in base64 temp2 = temp2.toBase64(); - else //cut off the 8bits of IV + else // cut off the 8bits of IV temp2 = temp2.remove(0, 8); return temp2; } - QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; - //do padding ourselves - if (direction) - { - while ((temp.length() % 8) != 0) temp.append('\0'); + // do padding ourselves + if (direction) { + while ((temp.length() % 8) != 0) + temp.append('\0'); } - else - { + else { // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input if ((temp.length() % 12) != 0) return cipherText; temp = b64ToByte(temp); - while ((temp.length() % 8) != 0) temp.append('\0'); + while ((temp.length() % 8) != 0) + temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; @@ -388,8 +368,7 @@ QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) return temp2; } - -//Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility +// Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility QByteArray Cipher::byteToB64(QByteArray text) { int left = 0; @@ -400,29 +379,45 @@ QByteArray Cipher::byteToB64(QByteArray text) QByteArray encoded; while (k < (text.length() - 1)) { k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; left = v << 24; k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; left += v << 16; k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; left += v << 8; k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; left += v; k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; right = v << 24; k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; right += v << 16; k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; right += v << 8; k++; - v = text.at(k); if (v < 0) v += 256; + v = text.at(k); + if (v < 0) + v += 256; right += v; for (int i = 0; i < 6; i++) { @@ -430,7 +425,7 @@ QByteArray Cipher::byteToB64(QByteArray text) right = right >> 6; } - //TODO make sure the .toLatin1 doesn't break anything + // TODO make sure the .toLatin1 doesn't break anything for (int i = 0; i < 6; i++) { encoded.append(base64.at(left & 0x3F).toLatin1()); left = left >> 6; @@ -439,7 +434,6 @@ QByteArray Cipher::byteToB64(QByteArray text) return encoded; } - QByteArray Cipher::b64ToByte(QByteArray text) { QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -467,21 +461,24 @@ QByteArray Cipher::b64ToByte(QByteArray text) for (int i = 0; i < 4; i++) { w = ((left & (0xFF << ((3 - i) * 8)))); z = w >> ((3 - i) * 8); - if (z < 0) { z = z + 256; } + if (z < 0) { + z = z + 256; + } decoded.append(z); } for (int i = 0; i < 4; i++) { w = ((right & (0xFF << ((3 - i) * 8)))); z = w >> ((3 - i) * 8); - if (z < 0) { z = z + 256; } + if (z < 0) { + z = z + 256; + } decoded.append(z); } } return decoded; } - bool Cipher::neededFeaturesAvailable() { QCA::Initializer init; diff --git a/src/core/cipher.h b/src/core/cipher.h index e873ff7d..01cf9ddc 100644 --- a/src/core/cipher.h +++ b/src/core/cipher.h @@ -24,19 +24,19 @@ public: explicit Cipher(QByteArray key, QString cipherType = QString("blowfish")); QByteArray decrypt(QByteArray cipher); QByteArray decryptTopic(QByteArray cipher); - bool encrypt(QByteArray &cipher); + bool encrypt(QByteArray& cipher); QByteArray initKeyExchange(); QByteArray parseInitKeyX(QByteArray key); bool parseFinishKeyX(QByteArray key); bool setKey(QByteArray key); QByteArray key() { return m_key; } - bool setType(const QString &type); + bool setType(const QString& type); QString type() { return m_type; } static bool neededFeaturesAvailable(); inline bool usesCBC() { return m_cbc; } private: - //direction is true for encrypt, false for decrypt + // direction is true for encrypt, false for decrypt QByteArray blowfishCBC(QByteArray cipherText, bool direction); QByteArray blowfishECB(QByteArray cipherText, bool direction); QByteArray b64ToByte(QByteArray text); @@ -50,5 +50,4 @@ private: bool m_cbc; }; - -#endif // CIPHER_H +#endif // CIPHER_H diff --git a/src/core/core.cpp b/src/core/core.cpp index 556eec67..a59d8972 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -18,11 +18,12 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "core.h" + #include #include -#include "core.h" #include "coreauthhandler.h" #include "coresession.h" #include "coresettings.h" @@ -37,16 +38,16 @@ #include "util.h" #ifdef HAVE_LDAP -# include "ldapauthenticator.h" +# include "ldapauthenticator.h" #endif // migration related #include #ifdef Q_OS_WIN -# include +# include #else -# include -# include +# include +# include #endif /* Q_OS_WIN */ // ============================== @@ -57,12 +58,15 @@ const int Core::AddClientEventId = QEvent::registerEventType(); class AddClientEvent : public QEvent { public: - AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {} - RemotePeer *peer; + AddClientEvent(RemotePeer* p, UserId uid) + : QEvent(QEvent::Type(Core::AddClientEventId)) + , peer(p) + , userId(uid) + {} + RemotePeer* peer; UserId userId; }; - // ============================== // Core // ============================== @@ -79,7 +83,6 @@ Core::Core() _storageSyncTimer.setParent(this); } - Core::~Core() { qDeleteAll(_connectingClients); @@ -87,10 +90,9 @@ Core::~Core() syncStorage(); } - void Core::init() { - _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :) + _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :) // check settings version // so far, we only have 1 @@ -206,7 +208,6 @@ void Core::init() _oidentdConfigGenerator = new OidentdConfigGenerator(this); } - if (Quassel::isOptionSet("ident-daemon")) { _identServer = new IdentServer(this); } @@ -222,7 +223,7 @@ void Core::init() }); connect(&_storageSyncTimer, &QTimer::timeout, this, &Core::syncStorage); - _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes + _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes } connect(&_server, &QTcpServer::newConnection, this, &Core::incomingConnection); @@ -244,7 +245,6 @@ void Core::init() } } - void Core::initAsync() { try { @@ -255,14 +255,13 @@ void Core::initAsync() } } - void Core::shutdown() { quInfo() << "Core shutting down..."; saveState(); - for (auto &&client : _connectingClients) { + for (auto&& client : _connectingClients) { client->deleteLater(); } _connectingClients.clear(); @@ -272,14 +271,13 @@ void Core::shutdown() return; } - for (auto &&session : _sessions) { + for (auto&& session : _sessions) { connect(session, &SessionThread::shutdownComplete, this, &Core::onSessionShutdown); session->shutdown(); } } - -void Core::onSessionShutdown(SessionThread *session) +void Core::onSessionShutdown(SessionThread* session) { _sessions.take(_sessions.key(session))->deleteLater(); if (_sessions.isEmpty()) { @@ -288,20 +286,18 @@ void Core::onSessionShutdown(SessionThread *session) } } - /*** Session Restore ***/ void Core::saveState() { if (_storage) { QVariantList activeSessions; - for (auto &&user : instance()->_sessions.keys()) + for (auto&& user : instance()->_sessions.keys()) activeSessions << QVariant::fromValue(user); _storage->setCoreState(activeSessions); } } - void Core::restoreState() { if (!_configured) { @@ -322,28 +318,36 @@ void Core::restoreState() } */ - const QList &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList(); + const QList& activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList(); QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback); if (activeSessions.count() > 0) { quInfo() << "Restoring previous core state..."; - for(auto &&v : activeSessions) { + for (auto&& v : activeSessions) { UserId user = v.value(); sessionForUser(user, true); } } } - /*** Core Setup ***/ -QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData) +QString Core::setup(const QString& adminUser, + const QString& adminPassword, + const QString& backend, + const QVariantMap& setupData, + const QString& authenticator, + const QVariantMap& authSetupData) { return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData); } - -QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData) +QString Core::setupCore(const QString& adminUser, + const QString& adminPassword, + const QString& backend, + const QVariantMap& setupData, + const QString& authenticator, + const QVariantMap& authSetupData) { if (_configured) return tr("Core is already configured! Not configuring again..."); @@ -357,8 +361,7 @@ QString Core::setupCore(const QString &adminUser, const QString &adminPassword, } quInfo() << "Selected authenticator:" << authenticator; - if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true))) - { + if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true))) { return tr("Could not setup authenticator!"); } } @@ -376,11 +379,10 @@ QString Core::setupCore(const QString &adminUser, const QString &adminPassword, quInfo() << qPrintable(tr("Creating admin user...")); _storage->addUser(adminUser, adminPassword); cacheSysIdent(); - startListening(); // TODO check when we need this + startListening(); // TODO check when we need this return QString(); } - QString Core::setupCoreForInternalUsage() { Q_ASSERT(!_registeredStorageBackends.empty()); @@ -396,7 +398,6 @@ QString Core::setupCoreForInternalUsage() return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap()); } - /*** Storage Handling ***/ template @@ -409,7 +410,6 @@ void Core::registerStorageBackend() backend->deleteLater(); } - void Core::registerStorageBackends() { if (_registeredStorageBackends.empty()) { @@ -418,19 +418,16 @@ void Core::registerStorageBackends() } } - -DeferredSharedPtr Core::storageBackend(const QString &backendId) const +DeferredSharedPtr Core::storageBackend(const QString& backendId) const { - auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(), - [backendId](const DeferredSharedPtr &backend) { - return backend->displayName() == backendId; - }); + auto it = std::find_if(_registeredStorageBackends.begin(), + _registeredStorageBackends.end(), + [backendId](const DeferredSharedPtr& backend) { return backend->displayName() == backendId; }); return it != _registeredStorageBackends.end() ? *it : nullptr; } - -bool Core::initStorage(const QString &backend, const QVariantMap &settings, - const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup) +bool Core::initStorage( + const QString& backend, const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment, bool setup) { if (backend.isEmpty()) { quWarning() << "No storage backend selected!"; @@ -465,24 +462,21 @@ bool Core::initStorage(const QString &backend, const QVariantMap &settings, case Storage::IsReady: // delete all other backends _registeredStorageBackends.clear(); - connect(storage.get(), &Storage::bufferInfoUpdated, - this, &Core::bufferInfoUpdated); + connect(storage.get(), &Storage::bufferInfoUpdated, this, &Core::bufferInfoUpdated); break; } _storage = std::move(storage); return true; } - void Core::syncStorage() { if (_storage) _storage->sync(); } - /*** Storage Access ***/ -bool Core::createNetwork(UserId user, NetworkInfo &info) +bool Core::createNetwork(UserId user, NetworkInfo& info) { NetworkId networkId = instance()->_storage->createNetwork(user, info); if (!networkId.isValid()) @@ -492,7 +486,6 @@ bool Core::createNetwork(UserId user, NetworkInfo &info) return true; } - /*** Authenticators ***/ // Authentication handling, now independent from storage. @@ -506,7 +499,6 @@ void Core::registerAuthenticator() authenticator->deleteLater(); } - void Core::registerAuthenticators() { if (_registeredAuthenticators.empty()) { @@ -517,22 +509,20 @@ void Core::registerAuthenticators() } } - -DeferredSharedPtr Core::authenticator(const QString &backendId) const +DeferredSharedPtr Core::authenticator(const QString& backendId) const { - auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(), - [backendId](const DeferredSharedPtr &authenticator) { + auto it = std::find_if(_registeredAuthenticators.begin(), + _registeredAuthenticators.end(), + [backendId](const DeferredSharedPtr& authenticator) { return authenticator->backendId() == backendId; }); return it != _registeredAuthenticators.end() ? *it : nullptr; } - // FIXME: Apparently, this is the legacy way of initting storage backends? // If there's a not-legacy way, it should be used here -bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings, - const QProcessEnvironment &environment, bool loadFromEnvironment, - bool setup) +bool Core::initAuthenticator( + const QString& backend, const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment, bool setup) { if (backend.isEmpty()) { quWarning() << "No authenticator selected!"; @@ -571,27 +561,25 @@ bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings return true; } - /*** Network Management ***/ bool Core::sslSupported() { #ifdef HAVE_SSL - auto *sslServer = qobject_cast(&instance()->_server); + auto* sslServer = qobject_cast(&instance()->_server); return sslServer && sslServer->isCertValid(); #else return false; #endif } - bool Core::reloadCerts() { #ifdef HAVE_SSL - auto *sslServerv4 = qobject_cast(&_server); + auto* sslServerv4 = qobject_cast(&_server); bool retv4 = sslServerv4->reloadCerts(); - auto *sslServerv6 = qobject_cast(&_v6server); + auto* sslServerv6 = qobject_cast(&_v6server); bool retv6 = sslServerv6->reloadCerts(); return retv4 && retv6; @@ -601,7 +589,6 @@ bool Core::reloadCerts() #endif } - void Core::cacheSysIdent() { if (isConfigured()) { @@ -609,7 +596,6 @@ void Core::cacheSysIdent() } } - QString Core::strictSysIdent(UserId user) const { if (_authUserNames.contains(user)) { @@ -626,10 +612,9 @@ QString Core::strictSysIdent(UserId user) const // ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?) qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!"; - return "unknown"; // Should we just terminate the program instead? + return "unknown"; // Should we just terminate the program instead? } - bool Core::startListening() { // in mono mode we only start a local port if a port is specified in the cli call @@ -642,58 +627,42 @@ bool Core::startListening() const QString listen = Quassel::optionValue("listen"); const QStringList listen_list = listen.split(",", QString::SkipEmptyParts); if (listen_list.size() > 0) { - foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully + foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully QHostAddress addr; if (!addr.setAddress(listen_term)) { - qCritical() << qPrintable( - tr("Invalid listen address %1") - .arg(listen_term) - ); + qCritical() << qPrintable(tr("Invalid listen address %1").arg(listen_term)); } else { switch (addr.protocol()) { case QAbstractSocket::IPv6Protocol: if (_v6server.listen(addr, port)) { - quInfo() << qPrintable( - tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3") - .arg(addr.toString()) - .arg(_v6server.serverPort()) - .arg(Quassel::buildInfo().protocolVersion) - ); + quInfo() << qPrintable(tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3") + .arg(addr.toString()) + .arg(_v6server.serverPort()) + .arg(Quassel::buildInfo().protocolVersion)); success = true; } else quWarning() << qPrintable( - tr("Could not open IPv6 interface %1:%2: %3") - .arg(addr.toString()) - .arg(port) - .arg(_v6server.errorString())); + tr("Could not open IPv6 interface %1:%2: %3").arg(addr.toString()).arg(port).arg(_v6server.errorString())); break; case QAbstractSocket::IPv4Protocol: if (_server.listen(addr, port)) { - quInfo() << qPrintable( - tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3") - .arg(addr.toString()) - .arg(_server.serverPort()) - .arg(Quassel::buildInfo().protocolVersion) - ); + quInfo() << qPrintable(tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3") + .arg(addr.toString()) + .arg(_server.serverPort()) + .arg(Quassel::buildInfo().protocolVersion)); success = true; } else { // if v6 succeeded on Any, the port will be already in use - don't display the error then if (!success || _server.serverError() != QAbstractSocket::AddressInUseError) quWarning() << qPrintable( - tr("Could not open IPv4 interface %1:%2: %3") - .arg(addr.toString()) - .arg(port) - .arg(_server.errorString())); + tr("Could not open IPv4 interface %1:%2: %3").arg(addr.toString()).arg(port).arg(_server.errorString())); } break; default: - qCritical() << qPrintable( - tr("Invalid listen address %1, unknown network protocol") - .arg(listen_term) - ); + qCritical() << qPrintable(tr("Invalid listen address %1, unknown network protocol").arg(listen_term)); break; } } @@ -709,8 +678,7 @@ bool Core::startListening() return success; } - -void Core::stopListening(const QString &reason) +void Core::stopListening(const QString& reason) { if (_identServer) { _identServer->stopListening(reason); @@ -733,22 +701,21 @@ void Core::stopListening(const QString &reason) } } - void Core::incomingConnection() { - auto *server = qobject_cast(sender()); + auto* server = qobject_cast(sender()); Q_ASSERT(server); while (server->hasPendingConnections()) { - QTcpSocket *socket = server->nextPendingConnection(); + QTcpSocket* socket = server->nextPendingConnection(); - auto *handler = new CoreAuthHandler(socket, this); + auto* handler = new CoreAuthHandler(socket, this); _connectingClients.insert(handler); connect(handler, &AuthHandler::disconnected, this, &Core::clientDisconnected); connect(handler, &AuthHandler::socketError, this, &Core::socketError); connect(handler, &CoreAuthHandler::handshakeComplete, this, &Core::setupClientSession); - quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString()); + quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString()); if (!_configured) { stopListening(tr("Closing server for basic setup.")); @@ -756,11 +723,10 @@ void Core::incomingConnection() } } - // Potentially called during the initialization phase (before handing the connection off to the session) void Core::clientDisconnected() { - auto *handler = qobject_cast(sender()); + auto* handler = qobject_cast(sender()); Q_ASSERT(handler); quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString()); @@ -776,10 +742,9 @@ void Core::clientDisconnected() // Suggestion: kill sessions if they are not connected to any network and client. } - -void Core::setupClientSession(RemotePeer *peer, UserId uid) +void Core::setupClientSession(RemotePeer* peer, UserId uid) { - auto *handler = qobject_cast(sender()); + auto* handler = qobject_cast(sender()); Q_ASSERT(handler); // From now on everything is handled by the client session @@ -795,25 +760,22 @@ void Core::setupClientSession(RemotePeer *peer, UserId uid) QCoreApplication::postEvent(this, new AddClientEvent(peer, uid)); } - -void Core::customEvent(QEvent *event) +void Core::customEvent(QEvent* event) { if (event->type() == AddClientEventId) { - auto *addClientEvent = static_cast(event); + auto* addClientEvent = static_cast(event); addClientHelper(addClientEvent->peer, addClientEvent->userId); return; } } - -void Core::addClientHelper(RemotePeer *peer, UserId uid) +void Core::addClientHelper(RemotePeer* peer, UserId uid) { // Find or create session for validated user - SessionThread *session = sessionForUser(uid); + SessionThread* session = sessionForUser(uid); session->addClient(peer); } - void Core::connectInternalPeer(QPointer peer) { if (_initialized && peer) { @@ -824,7 +786,6 @@ void Core::connectInternalPeer(QPointer peer) } } - void Core::setupInternalClientSession(QPointer clientPeer) { if (!_configured) { @@ -851,17 +812,16 @@ void Core::setupInternalClientSession(QPointer clientPeer) return; } - auto *corePeer = new InternalPeer(this); + auto* corePeer = new InternalPeer(this); corePeer->setPeer(clientPeer); clientPeer->setPeer(corePeer); // Find or create session for validated user - SessionThread *sessionThread = sessionForUser(uid); + SessionThread* sessionThread = sessionForUser(uid); sessionThread->addClient(corePeer); } - -SessionThread *Core::sessionForUser(UserId uid, bool restore) +SessionThread* Core::sessionForUser(UserId uid, bool restore) { if (_sessions.contains(uid)) return _sessions[uid]; @@ -869,72 +829,69 @@ SessionThread *Core::sessionForUser(UserId uid, bool restore) return (_sessions[uid] = new SessionThread(uid, restore, strictIdentEnabled(), this)); } - -void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString) +void Core::socketError(QAbstractSocket::SocketError err, const QString& errorString) { quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString); } - QVariantList Core::backendInfo() { instance()->registerStorageBackends(); QVariantList backendInfos; - for (auto &&backend : instance()->_registeredStorageBackends) { + for (auto&& backend : instance()->_registeredStorageBackends) { QVariantMap v; - v["BackendId"] = backend->backendId(); + v["BackendId"] = backend->backendId(); v["DisplayName"] = backend->displayName(); v["Description"] = backend->description(); - v["SetupData"] = backend->setupData(); // ignored by legacy clients + v["SetupData"] = backend->setupData(); // ignored by legacy clients // TODO Protocol Break: Remove legacy (cf. authenticatorInfo()) - const auto &setupData = backend->setupData(); + const auto& setupData = backend->setupData(); QStringList setupKeys; QVariantMap setupDefaults; for (int i = 0; i + 2 < setupData.size(); i += 3) { setupKeys << setupData[i].toString(); setupDefaults[setupData[i].toString()] = setupData[i + 2]; } - v["SetupKeys"] = setupKeys; + v["SetupKeys"] = setupKeys; v["SetupDefaults"] = setupDefaults; // TODO Protocol Break: Remove - v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list + v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list backendInfos << v; } return backendInfos; } - QVariantList Core::authenticatorInfo() { instance()->registerAuthenticators(); QVariantList authInfos; - for(auto &&backend : instance()->_registeredAuthenticators) { + for (auto&& backend : instance()->_registeredAuthenticators) { QVariantMap v; - v["BackendId"] = backend->backendId(); + v["BackendId"] = backend->backendId(); v["DisplayName"] = backend->displayName(); v["Description"] = backend->description(); - v["SetupData"] = backend->setupData(); + v["SetupData"] = backend->setupData(); authInfos << v; } return authInfos; } // migration / backend selection -bool Core::selectBackend(const QString &backend) +bool Core::selectBackend(const QString& backend) { // reregister all storage backends registerStorageBackends(); auto storage = storageBackend(backend); if (!storage) { QStringList backends; - std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(), - std::back_inserter(backends), [](const DeferredSharedPtr& backend) { - return backend->displayName(); - }); + std::transform(_registeredStorageBackends.begin(), + _registeredStorageBackends.end(), + std::back_inserter(backends), + [](const DeferredSharedPtr& backend) { return backend->displayName(); }); quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend)); quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", ")); return false; @@ -1011,17 +968,17 @@ bool Core::selectBackend(const QString &backend) // TODO: I am not sure if this function is implemented correctly. // There is currently no concept of migraiton between auth backends. -bool Core::selectAuthenticator(const QString &backend) +bool Core::selectAuthenticator(const QString& backend) { // Register all authentication backends. registerAuthenticators(); auto auther = authenticator(backend); if (!auther) { QStringList authenticators; - std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(), - std::back_inserter(authenticators), [](const DeferredSharedPtr& authenticator) { - return authenticator->displayName(); - }); + std::transform(_registeredAuthenticators.begin(), + _registeredAuthenticators.end(), + std::back_inserter(authenticators), + [](const DeferredSharedPtr& authenticator) { return authenticator->displayName(); }); quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend)); quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", ")); return false; @@ -1057,7 +1014,6 @@ bool Core::selectAuthenticator(const QString &backend) return true; } - bool Core::createUser() { QTextStream out(stdout); @@ -1097,8 +1053,7 @@ bool Core::createUser() } } - -bool Core::changeUserPass(const QString &username) +bool Core::changeUserPass(const QString& username) { QTextStream out(stdout); QTextStream in(stdin); @@ -1145,8 +1100,7 @@ bool Core::changeUserPass(const QString &username) } } - -bool Core::changeUserPassword(UserId userId, const QString &password) +bool Core::changeUserPassword(UserId userId, const QString& password) { if (!isConfigured() || !userId.isValid()) return false; @@ -1175,13 +1129,12 @@ bool Core::canChangeUserPassword(UserId userId) return true; } - -std::unique_ptr Core::getMigrationReader(Storage *storage) +std::unique_ptr Core::getMigrationReader(Storage* storage) { if (!storage) return nullptr; - auto *sqlStorage = qobject_cast(storage); + auto* sqlStorage = qobject_cast(storage); if (!sqlStorage) { qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!"; return nullptr; @@ -1190,13 +1143,12 @@ std::unique_ptr Core::getMigrationReader(Storage *st return sqlStorage->createMigrationReader(); } - -std::unique_ptr Core::getMigrationWriter(Storage *storage) +std::unique_ptr Core::getMigrationWriter(Storage* storage) { if (!storage) return nullptr; - auto *sqlStorage = qobject_cast(storage); + auto* sqlStorage = qobject_cast(storage); if (!sqlStorage) { qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!"; return nullptr; @@ -1205,8 +1157,7 @@ std::unique_ptr Core::getMigrationWriter(Storage *st return sqlStorage->createMigrationWriter(); } - -bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings) +bool Core::saveBackendSettings(const QString& backend, const QVariantMap& settings) { QVariantMap dbsettings; dbsettings["Backend"] = backend; @@ -1216,8 +1167,7 @@ bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settin return s.sync(); } - -void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings) +void Core::saveAuthenticatorSettings(const QString& backend, const QVariantMap& settings) { QVariantMap dbsettings; dbsettings["Authenticator"] = backend; @@ -1228,7 +1178,7 @@ void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap & // Generic version of promptForSettings that doesn't care what *type* of // backend it runs over. template -QVariantMap Core::promptForSettings(const Backend *backend) +QVariantMap Core::promptForSettings(const Backend* backend) { QVariantMap settings; const QVariantList& setupData = backend->setupData(); @@ -1242,7 +1192,7 @@ QVariantMap Core::promptForSettings(const Backend *backend) for (int i = 0; i + 2 < setupData.size(); i += 3) { QString key = setupData[i].toString(); - out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush; + out << setupData[i + 1].toString() << " [" << setupData[i + 2].toString() << "]: " << flush; bool noEcho = key.toLower().contains("password"); if (noEcho) { @@ -1254,7 +1204,7 @@ QVariantMap Core::promptForSettings(const Backend *backend) enableStdInEcho(); } - QVariant value{setupData[i+2]}; + QVariant value{setupData[i + 2]}; if (!input.isEmpty()) { switch (value.type()) { case QVariant::Int: @@ -1269,7 +1219,6 @@ QVariantMap Core::promptForSettings(const Backend *backend) return settings; } - #ifdef Q_OS_WIN void Core::stdInEcho(bool on) { diff --git a/src/core/core.h b/src/core/core.h index aa94725e..b5ca2c1c 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -28,15 +28,16 @@ #include #include #include -#include #include +#include #ifdef HAVE_SSL -# include -# include "sslserver.h" +# include + +# include "sslserver.h" #else -# include -# include +# include +# include #endif #include "authenticator.h" @@ -76,7 +77,6 @@ public: */ void shutdown(); - /*** Storage access ***/ // These methods are threadsafe. @@ -86,7 +86,8 @@ public: * \param password The user's uncrypted password * \return The user's ID if valid; 0 otherwise */ - static inline UserId validateUser(const QString &userName, const QString &password) { + static inline UserId validateUser(const QString& userName, const QString& password) + { return instance()->_storage->validateUser(userName, password); } @@ -96,7 +97,8 @@ public: * \param password The user's uncrypted password * \return The user's ID if valid; 0 otherwise */ - static inline UserId authenticateUser(const QString &userName, const QString &password) { + static inline UserId authenticateUser(const QString& userName, const QString& password) + { return instance()->_authenticator->validateUser(userName, password); } @@ -107,7 +109,8 @@ public: * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database". * \return The user's ID if valid; 0 otherwise */ - static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") { + static inline UserId addUser(const QString& userName, const QString& password, const QString& authenticator = "Database") + { return instance()->_storage->addUser(userName, password, authenticator); } @@ -117,7 +120,8 @@ public: * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database". * \return True if the userid was configured with the passed authenticator, false otherwise. */ - static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) { + static inline bool checkAuthProvider(const UserId userid, const QString& authenticator) + { return instance()->_storage->getUserAuthenticator(userid) == authenticator; } @@ -127,7 +131,7 @@ public: * \param password The user's unencrypted new password * \return true, if the password change was successful */ - static bool changeUserPassword(UserId userId, const QString &password); + static bool changeUserPassword(UserId userId, const QString& password); //! Check if we can change a user password. /** @@ -142,12 +146,11 @@ public: * \param settingName The Name of the Setting * \param data The Value */ - static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) + static inline void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) { instance()->_storage->setUserSetting(userId, settingName, data); } - //! Retrieve a persistent user setting /** * \param userId The users Id @@ -155,36 +158,22 @@ public: * \param defaultValue Value to return in case it's unset. * \return the Value of the Setting or the default value if it is unset. */ - static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant()) + static inline QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultValue = QVariant()) { return instance()->_storage->getUserSetting(userId, settingName, defaultValue); } - /* Identity handling */ - static inline IdentityId createIdentity(UserId user, CoreIdentity &identity) + static inline IdentityId createIdentity(UserId user, CoreIdentity& identity) { return instance()->_storage->createIdentity(user, identity); } + static bool updateIdentity(UserId user, const CoreIdentity& identity) { return instance()->_storage->updateIdentity(user, identity); } - static bool updateIdentity(UserId user, const CoreIdentity &identity) - { - return instance()->_storage->updateIdentity(user, identity); - } - - - static void removeIdentity(UserId user, IdentityId identityId) - { - instance()->_storage->removeIdentity(user, identityId); - } - - - static QList identities(UserId user) - { - return instance()->_storage->identities(user); - } + static void removeIdentity(UserId user, IdentityId identityId) { instance()->_storage->removeIdentity(user, identityId); } + static QList identities(UserId user) { return instance()->_storage->identities(user); } //! Create a Network in the Storage and store it's Id in the given NetworkInfo /** \note This method is thredsafe. @@ -193,7 +182,7 @@ public: * \param networkInfo a NetworkInfo definition to store the newly created ID in * \return true if successfull. */ - static bool createNetwork(UserId user, NetworkInfo &info); + static bool createNetwork(UserId user, NetworkInfo& info); //! Apply the changes to NetworkInfo info to the storage engine /** \note This method is thredsafe. @@ -202,11 +191,7 @@ public: * \param networkInfo The Updated NetworkInfo * \return true if successfull. */ - static inline bool updateNetwork(UserId user, const NetworkInfo &info) - { - return instance()->_storage->updateNetwork(user, info); - } - + static inline bool updateNetwork(UserId user, const NetworkInfo& info) { return instance()->_storage->updateNetwork(user, info); } //! Permanently remove a Network and all the data associated with it. /** \note This method is thredsafe. @@ -215,23 +200,18 @@ public: * \param networkId The network to delete * \return true if successfull. */ - static inline bool removeNetwork(UserId user, const NetworkId &networkId) + static inline bool removeNetwork(UserId user, const NetworkId& networkId) { return instance()->_storage->removeNetwork(user, networkId); } - //! Returns a list of all NetworkInfos for the given UserId user /** \note This method is thredsafe. * * \param user The core user * \return QList. */ - static inline QList networks(UserId user) - { - return instance()->_storage->networks(user); - } - + static inline QList networks(UserId user) { return instance()->_storage->networks(user); } //! Get a list of Networks to restore /** Return a list of networks the user was connected at the time of core shutdown @@ -239,11 +219,7 @@ public: * * \param user The User Id in question */ - static inline QList connectedNetworks(UserId user) - { - return instance()->_storage->connectedNetworks(user); - } - + static inline QList connectedNetworks(UserId user) { return instance()->_storage->connectedNetworks(user); } //! Update the connected state of a network /** \note This method is threadsafe @@ -252,12 +228,11 @@ public: * \param networkId The Id of the network * \param isConnected whether the network is connected or not */ - static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) + static inline void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) { return instance()->_storage->setNetworkConnected(user, networkId, isConnected); } - //! Get a hash of channels with their channel keys for a given network /** The keys are channel names and values are passwords (possibly empty) * \note This method is threadsafe @@ -265,12 +240,11 @@ public: * \param user The id of the networks owner * \param networkId The Id of the network */ - static inline QHash persistentChannels(UserId user, const NetworkId &networkId) + static inline QHash persistentChannels(UserId user, const NetworkId& networkId) { return instance()->_storage->persistentChannels(user, networkId); } - //! Update the connected state of a channel /** \note This method is threadsafe * @@ -279,12 +253,11 @@ public: * \param channel The name of the channel * \param isJoined whether the channel is connected or not */ - static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) + static inline void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) { return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined); } - //! Get a hash of buffers with their ciphers for a given network /** The keys are channel names and values are ciphers (possibly empty) * \note This method is threadsafe @@ -292,12 +265,11 @@ public: * \param user The id of the networks owner * \param networkId The Id of the network */ - static inline QHash bufferCiphers(UserId user, const NetworkId &networkId) + static inline QHash bufferCiphers(UserId user, const NetworkId& networkId) { return instance()->_storage->bufferCiphers(user, networkId); } - //! Update the cipher of a buffer /** \note This method is threadsafe * @@ -306,12 +278,11 @@ public: * \param bufferName The Cname of the buffer * \param cipher The cipher for the buffer */ - static inline void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) + static inline void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) { return instance()->_storage->setBufferCipher(user, networkId, bufferName, cipher); } - //! Update the key of a channel /** \note This method is threadsafe * @@ -320,23 +291,18 @@ public: * \param channel The name of the channel * \param key The key of the channel (possibly empty) */ - static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) + static inline void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) { return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key); } - //! retrieve last known away message for session restore /** \note This method is threadsafe * * \param user The Id of the networks owner * \param networkId The Id of the network */ - static inline QString awayMessage(UserId user, NetworkId networkId) - { - return instance()->_storage->awayMessage(user, networkId); - } - + static inline QString awayMessage(UserId user, NetworkId networkId) { return instance()->_storage->awayMessage(user, networkId); } //! Make away message persistent for session restore /** \note This method is threadsafe @@ -345,23 +311,18 @@ public: * \param networkId The Id of the network * \param awayMsg The current away message of own user */ - static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) + static inline void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) { return instance()->_storage->setAwayMessage(user, networkId, awayMsg); } - //! retrieve last known user mode for session restore /** \note This method is threadsafe * * \param user The Id of the networks owner * \param networkId The Id of the network */ - static inline QString userModes(UserId user, NetworkId networkId) - { - return instance()->_storage->userModes(user, networkId); - } - + static inline QString userModes(UserId user, NetworkId networkId) { return instance()->_storage->userModes(user, networkId); } //! Make our user modes persistent for session restore /** \note This method is threadsafe @@ -370,12 +331,11 @@ public: * \param networkId The Id of the network * \param userModes The current user modes of own user */ - static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes) + static inline void setUserModes(UserId user, NetworkId networkId, const QString& userModes) { return instance()->_storage->setUserModes(user, networkId, userModes); } - //! Get the unique BufferInfo for the given combination of network and buffername for a user. /** \note This method is threadsafe. * @@ -386,35 +346,30 @@ public: * \param create Whether or not the buffer should be created if it doesnt exist * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found */ - static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) + static inline BufferInfo bufferInfo( + UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true) { return instance()->_storage->bufferInfo(user, networkId, type, buffer, create); } - //! Get the unique BufferInfo for a bufferId /** \note This method is threadsafe * \param user The core user who owns this buffername * \param bufferId The id of the buffer * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found. */ - static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) + static inline BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) { return instance()->_storage->getBufferInfo(user, bufferId); } - //! Store a Message in the storage backend and set it's unique Id. /** \note This method is threadsafe. * * \param message The message object to be stored * \return true on success */ - static inline bool storeMessage(Message &message) - { - return instance()->_storage->logMessage(message); - } - + static inline bool storeMessage(Message& message) { return instance()->_storage->logMessage(message); } //! Store a list of Messages in the storage backend and set their unique Id. /** \note This method is threadsafe. @@ -422,11 +377,7 @@ public: * \param messages The list message objects to be stored * \return true on success */ - static inline bool storeMessages(MessageList &messages) - { - return instance()->_storage->logMessages(messages); - } - + static inline bool storeMessages(MessageList& messages) { return instance()->_storage->logMessages(messages); } //! Request a certain number messages stored in a given buffer. /** \param buffer The buffer we request messages from @@ -440,7 +391,6 @@ public: return instance()->_storage->requestMsgs(user, bufferId, first, last, limit); } - //! Request a certain number messages stored in a given buffer, matching certain filters /** \param buffer The buffer we request messages from * \param first if != -1 return only messages with a MsgId >= first @@ -449,14 +399,17 @@ public: * \param type The Message::Types that should be returned * \return The requested list of messages */ - static inline QList requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, - int limit = -1, Message::Types type = Message::Types{-1}, + static inline QList requestMsgsFiltered(UserId user, + BufferId bufferId, + MsgId first = -1, + MsgId last = -1, + int limit = -1, + Message::Types type = Message::Types{-1}, Message::Flags flags = Message::Flags{-1}) { return instance()->_storage->requestMsgsFiltered(user, bufferId, first, last, limit, type, flags); } - //! Request a certain number of messages across all buffers /** \param first if != -1 return only messages with a MsgId >= first * \param last if != -1 return only messages with a MsgId < last @@ -468,7 +421,6 @@ public: return instance()->_storage->requestAllMsgs(user, first, last, limit); } - //! Request a certain number of messages across all buffers, matching certain filters /** \param first if != -1 return only messages with a MsgId >= first * \param last if != -1 return only messages with a MsgId < last @@ -476,14 +428,16 @@ public: * \param type The Message::Types that should be returned * \return The requested list of messages */ - static inline QList requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1, + static inline QList requestAllMsgsFiltered(UserId user, + MsgId first = -1, + MsgId last = -1, + int limit = -1, Message::Types type = Message::Types{-1}, Message::Flags flags = Message::Flags{-1}) { return instance()->_storage->requestAllMsgsFiltered(user, first, last, limit, type, flags); } - //! Request a list of all buffers known to a user. /** This method is used to get a list of all buffers we have stored a backlog from. * \note This method is threadsafe. @@ -491,11 +445,7 @@ public: * \param user The user whose buffers we request * \return A list of the BufferInfos for all buffers as requested */ - static inline QList requestBuffers(UserId user) - { - return instance()->_storage->requestBuffers(user); - } - + static inline QList requestBuffers(UserId user) { return instance()->_storage->requestBuffers(user); } //! Request a list of BufferIds for a given NetworkId /** \note This method is threadsafe. @@ -509,7 +459,6 @@ public: return instance()->_storage->requestBufferIdsForNetwork(user, networkId); } - //! Remove permanently a buffer and it's content from the storage backend /** This call cannot be reverted! * \note This method is threadsafe. @@ -518,12 +467,11 @@ public: * \param bufferId The bufferId * \return true if successfull */ - static inline bool removeBuffer(const UserId &user, const BufferId &bufferId) + static inline bool removeBuffer(const UserId& user, const BufferId& bufferId) { return instance()->_storage->removeBuffer(user, bufferId); } - //! Rename a Buffer /** \note This method is threadsafe. * \param user The id of the buffer owner @@ -531,12 +479,11 @@ public: * \param newName The new name of the buffer * \return true if successfull */ - static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) + static inline bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) { return instance()->_storage->renameBuffer(user, bufferId, newName); } - //! Merge the content of two Buffers permanently. This cannot be reversed! /** \note This method is threadsafe. * \param user The id of the buffer owner @@ -544,12 +491,11 @@ public: * \param bufferId2 The buffer that is about to be removed * \return true if successfulln */ - static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) + static inline bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) { return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2); } - //! Update the LastSeenDate for a Buffer /** This Method is used to make the LastSeenDate of a Buffer persistent * \note This method is threadsafe. @@ -558,30 +504,24 @@ public: * \param bufferId The buffer id * \param MsgId The Message id of the message that has been just seen */ - static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) + static inline void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) { return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId); } - //! Get a usable sysident for the given user in oidentd-strict mode /** \param user The user to retrieve the sysident for * \return The authusername */ QString strictSysIdent(UserId user) const; - //! Get a Hash of all last seen message ids /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds * \note This method is threadsafe. * * \param user The Owner of the buffers */ - static inline QHash bufferLastSeenMsgIds(UserId user) - { - return instance()->_storage->bufferLastSeenMsgIds(user); - } - + static inline QHash bufferLastSeenMsgIds(UserId user) { return instance()->_storage->bufferLastSeenMsgIds(user); } //! Update the MarkerLineMsgId for a Buffer /** This Method is used to make the marker line position of a Buffer persistent @@ -591,22 +531,18 @@ public: * \param bufferId The buffer id * \param MsgId The Message id where the marker line should be placed */ - static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) + static inline void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) { return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId); } - //! Get a Hash of all marker line message ids /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds * \note This method is threadsafe. * * \param user The Owner of the buffers */ - static inline QHash bufferMarkerLineMsgIds(UserId user) - { - return instance()->_storage->bufferMarkerLineMsgIds(user); - } + static inline QHash bufferMarkerLineMsgIds(UserId user) { return instance()->_storage->bufferMarkerLineMsgIds(user); } //! Update the BufferActivity for a Buffer /** This Method is used to make the activity state of a Buffer persistent @@ -616,20 +552,18 @@ public: * \param bufferId The buffer id * \param MsgId The Message id where the marker line should be placed */ - static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) { + static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) + { return instance()->_storage->setBufferActivity(user, bufferId, activity); } - //! Get a Hash of all buffer activity states /** This Method is called when the Quassel Core is started to restore the BufferActivity * \note This method is threadsafe. * * \param user The Owner of the buffers */ - static inline QHash bufferActivities(UserId user) { - return instance()->_storage->bufferActivities(user); - } + static inline QHash bufferActivities(UserId user) { return instance()->_storage->bufferActivities(user); } //! Get the bitset of buffer activity states for a buffer /** This method is used to load the activity state of a buffer when its last seen message changes. @@ -638,7 +572,8 @@ public: * \param bufferId The buffer * \param lastSeenMsgId The last seen message */ - static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) { + static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) + { return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId); } @@ -650,20 +585,18 @@ public: * \param bufferId The buffer id * \param MsgId The Message id where the marker line should be placed */ - static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount) { + static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount) + { return instance()->_storage->setHighlightCount(user, bufferId, highlightCount); } - //! Get a Hash of all highlight count states /** This Method is called when the Quassel Core is started to restore the highlight count * \note This method is threadsafe. * * \param user The Owner of the buffers */ - static inline QHash highlightCounts(UserId user) { - return instance()->_storage->highlightCounts(user); - } + static inline QHash highlightCounts(UserId user) { return instance()->_storage->highlightCounts(user); } //! Get the highlight count states for a buffer /** This method is used to load the highlight count of a buffer when its last seen message changes. * \note This method is threadsafe. @@ -671,7 +604,8 @@ public: * \param bufferId The buffer * \param lastSeenMsgId The last seen message */ - static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) { + static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) + { return instance()->_storage->highlightCount(bufferId, lastSeenMsgId); } @@ -690,27 +624,32 @@ public: static QVariantList backendInfo(); static QVariantList authenticatorInfo(); - static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap); + static QString setup(const QString& adminUser, + const QString& adminPassword, + const QString& backend, + const QVariantMap& setupData, + const QString& authenticator, + const QVariantMap& authSetupMap); - static inline QTimer *syncTimer() { return &instance()->_storageSyncTimer; } + static inline QTimer* syncTimer() { return &instance()->_storageSyncTimer; } - inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; } - inline IdentServer *identServer() const { return _identServer; } + inline OidentdConfigGenerator* oidentdConfigGenerator() const { return _oidentdConfigGenerator; } + inline IdentServer* identServer() const { return _identServer; } static const int AddClientEventId; signals: //! Sent when a BufferInfo is updated in storage. - void bufferInfoUpdated(UserId user, const BufferInfo &info); + void bufferInfoUpdated(UserId user, const BufferInfo& info); //! Relay from CoreSession::sessionState(). Used for internal connection only - void sessionStateReceived(const Protocol::SessionState &sessionState); + void sessionStateReceived(const Protocol::SessionState& sessionState); //! Emitted when database schema upgrade starts or ends void dbUpgradeInProgress(bool inProgress); //! Emitted when a fatal error was encountered during async initialization - void exitRequested(int exitCode, const QString &reason); + void exitRequested(int exitCode, const QString& reason); //! Emitted once core shutdown is complete void shutdownComplete(); @@ -733,37 +672,46 @@ public slots: void cacheSysIdent(); - QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap); + QString setupCore(const QString& adminUser, + const QString& adminPassword, + const QString& backend, + const QVariantMap& setupData, + const QString& authenticator, + const QVariantMap& authSetupMap); void connectInternalPeer(QPointer peer); protected: - void customEvent(QEvent *event) override; + void customEvent(QEvent* event) override; private slots: bool startListening(); - void stopListening(const QString &msg = QString()); + void stopListening(const QString& msg = QString()); void incomingConnection(); void clientDisconnected(); - bool initStorage(const QString &backend, const QVariantMap &settings, - const QProcessEnvironment &environment, bool loadFromEnvironment, + bool initStorage(const QString& backend, + const QVariantMap& settings, + const QProcessEnvironment& environment, + bool loadFromEnvironment, bool setup = false); - bool initAuthenticator(const QString &backend, const QVariantMap &settings, - const QProcessEnvironment &environment, bool loadFromEnvironment, + bool initAuthenticator(const QString& backend, + const QVariantMap& settings, + const QProcessEnvironment& environment, + bool loadFromEnvironment, bool setup = false); - void socketError(QAbstractSocket::SocketError err, const QString &errorString); - void setupClientSession(RemotePeer *, UserId); + void socketError(QAbstractSocket::SocketError err, const QString& errorString); + void setupClientSession(RemotePeer*, UserId); - bool changeUserPass(const QString &username); + bool changeUserPass(const QString& username); - void onSessionShutdown(SessionThread *session); + void onSessionShutdown(SessionThread* session); private: - SessionThread *sessionForUser(UserId userId, bool restoreState = false); - void addClientHelper(RemotePeer *peer, UserId uid); - //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg); + SessionThread* sessionForUser(UserId userId, bool restoreState = false); + void addClientHelper(RemotePeer* peer, UserId uid); + // void processCoreSetup(QTcpSocket *socket, QVariantMap &msg); QString setupCoreForInternalUsage(); void setupInternalClientSession(QPointer peer); @@ -778,26 +726,26 @@ private: void registerStorageBackends(); void registerAuthenticators(); - DeferredSharedPtr storageBackend(const QString& backendId) const; + DeferredSharedPtr storageBackend(const QString& backendId) const; DeferredSharedPtr authenticator(const QString& authenticatorId) const; - bool selectBackend(const QString &backend); - bool selectAuthenticator(const QString &backend); + bool selectBackend(const QString& backend); + bool selectAuthenticator(const QString& backend); - bool saveBackendSettings(const QString &backend, const QVariantMap &settings); - void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings); + bool saveBackendSettings(const QString& backend, const QVariantMap& settings); + void saveAuthenticatorSettings(const QString& backend, const QVariantMap& settings); void saveState(); void restoreState(); template - QVariantMap promptForSettings(const Backend *backend); + QVariantMap promptForSettings(const Backend* backend); private: - static Core *_instance; - QSet _connectingClients; - QHash _sessions; - DeferredSharedPtr _storage; ///< Active storage backend + static Core* _instance; + QSet _connectingClients; + QHash _sessions; + DeferredSharedPtr _storage; ///< Active storage backend DeferredSharedPtr _authenticator; ///< Active authenticator QMap _authUserNames; @@ -809,14 +757,14 @@ private: QTcpServer _server, _v6server; #endif - OidentdConfigGenerator *_oidentdConfigGenerator {nullptr}; + OidentdConfigGenerator* _oidentdConfigGenerator{nullptr}; - std::vector> _registeredStorageBackends; + std::vector> _registeredStorageBackends; std::vector> _registeredAuthenticators; QDateTime _startTime; - IdentServer *_identServer {nullptr}; + IdentServer* _identServer{nullptr}; bool _initialized{false}; bool _configured{false}; @@ -826,8 +774,8 @@ private: /// Whether or not strict ident mode is enabled, locking users' idents to Quassel username bool _strictIdentEnabled; - static std::unique_ptr getMigrationReader(Storage *storage); - static std::unique_ptr getMigrationWriter(Storage *storage); + static std::unique_ptr getMigrationReader(Storage* storage); + static std::unique_ptr getMigrationWriter(Storage* storage); static void stdInEcho(bool on); static inline void enableStdInEcho() { stdInEcho(true); } static inline void disableStdInEcho() { stdInEcho(false); } diff --git a/src/core/corealiasmanager.cpp b/src/core/corealiasmanager.cpp index 07006686..5739fb22 100644 --- a/src/core/corealiasmanager.cpp +++ b/src/core/corealiasmanager.cpp @@ -24,10 +24,10 @@ #include "corenetwork.h" #include "coresession.h" -CoreAliasManager::CoreAliasManager(CoreSession *parent) +CoreAliasManager::CoreAliasManager(CoreSession* parent) : AliasManager(parent) { - auto *session = qobject_cast(parent); + auto* session = qobject_cast(parent); if (!session) { qWarning() << "CoreAliasManager: unable to load Aliases. Parent is not a Coresession!"; loadDefaults(); @@ -42,10 +42,9 @@ CoreAliasManager::CoreAliasManager(CoreSession *parent) connect(this, &SyncableObject::updatedRemotely, this, &CoreAliasManager::save); } - void CoreAliasManager::save() const { - auto *session = qobject_cast(parent()); + auto* session = qobject_cast(parent()); if (!session) { qWarning() << "CoreAliasManager: unable to save Aliases. Parent is not a Coresession!"; return; @@ -54,16 +53,14 @@ void CoreAliasManager::save() const Core::setUserSetting(session->user(), "Aliases", initAliases()); } - -const Network *CoreAliasManager::network(NetworkId id) const +const Network* CoreAliasManager::network(NetworkId id) const { - return qobject_cast(parent())->network(id); + return qobject_cast(parent())->network(id); } - void CoreAliasManager::loadDefaults() { - foreach(Alias alias, AliasManager::defaults()) { + foreach (Alias alias, AliasManager::defaults()) { addAlias(alias.name, alias.expansion); } } diff --git a/src/core/corealiasmanager.h b/src/core/corealiasmanager.h index 68a0b968..7c9097c6 100644 --- a/src/core/corealiasmanager.h +++ b/src/core/corealiasmanager.h @@ -29,10 +29,10 @@ class CoreAliasManager : public AliasManager Q_OBJECT public: - explicit CoreAliasManager(CoreSession *parent); + explicit CoreAliasManager(CoreSession* parent); protected: - const Network *network(NetworkId) const override; + const Network* network(NetworkId) const override; private slots: void save() const; diff --git a/src/core/coreapplication.cpp b/src/core/coreapplication.cpp index c8171dc2..9e7f03fd 100644 --- a/src/core/coreapplication.cpp +++ b/src/core/coreapplication.cpp @@ -20,7 +20,7 @@ #include "coreapplication.h" -CoreApplication::CoreApplication(int &argc, char **argv) +CoreApplication::CoreApplication(int& argc, char** argv) : QCoreApplication(argc, argv) { Quassel::registerQuitHandler([this]() { @@ -29,14 +29,12 @@ CoreApplication::CoreApplication(int &argc, char **argv) }); } - void CoreApplication::init() { _core = std::make_unique(); _core->init(); } - void CoreApplication::onShutdownComplete() { connect(_core.get(), &QObject::destroyed, QCoreApplication::instance(), &QCoreApplication::quit); diff --git a/src/core/coreapplication.h b/src/core/coreapplication.h index 6f9e9baa..f2f076fc 100644 --- a/src/core/coreapplication.h +++ b/src/core/coreapplication.h @@ -36,7 +36,7 @@ class CORE_EXPORT CoreApplication : public QCoreApplication Q_OBJECT public: - CoreApplication(int &argc, char **argv); + CoreApplication(int& argc, char** argv); void init(); diff --git a/src/core/coreauthhandler.cpp b/src/core/coreauthhandler.cpp index ade356ee..d559e44e 100644 --- a/src/core/coreauthhandler.cpp +++ b/src/core/coreauthhandler.cpp @@ -21,7 +21,7 @@ #include "coreauthhandler.h" #ifdef HAVE_SSL -# include +# include #endif #include "core.h" @@ -29,22 +29,20 @@ using namespace Protocol; -CoreAuthHandler::CoreAuthHandler(QTcpSocket *socket, QObject *parent) - : AuthHandler(parent), - _peer(nullptr), - _magicReceived(false), - _legacy(false), - _clientRegistered(false), - _connectionFeatures(0) +CoreAuthHandler::CoreAuthHandler(QTcpSocket* socket, QObject* parent) + : AuthHandler(parent) + , _peer(nullptr) + , _magicReceived(false) + , _legacy(false) + , _clientRegistered(false) + , _connectionFeatures(0) { setSocket(socket); connect(socket, &QIODevice::readyRead, this, &CoreAuthHandler::onReadyRead); // TODO: Timeout for the handshake phase - } - void CoreAuthHandler::onReadyRead() { if (socket()->bytesAvailable() < 4) @@ -63,7 +61,11 @@ void CoreAuthHandler::onReadyRead() // no magic, assume legacy protocol qDebug() << "Legacy client detected, switching to compatibility mode"; _legacy = true; - RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this); + RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), + this, + socket(), + Compressor::NoCompression, + this); connect(peer, &RemotePeer::protocolVersionMismatch, this, &CoreAuthHandler::onProtocolVersionMismatch); setPeer(peer); return; @@ -77,27 +79,27 @@ void CoreAuthHandler::onReadyRead() if (features & Protocol::Compression) _connectionFeatures |= Protocol::Compression; - socket()->read((char*)&magic, 4); // read the 4 bytes we've just peeked at + socket()->read((char*)&magic, 4); // read the 4 bytes we've just peeked at } // read the list of protocols supported by the client - while (socket()->bytesAvailable() >= 4 && _supportedProtos.size() < 16) { // sanity check + while (socket()->bytesAvailable() >= 4 && _supportedProtos.size() < 16) { // sanity check quint32 data; socket()->read((char*)&data, 4); data = qFromBigEndian(data); auto type = static_cast(data & 0xff); - auto protoFeatures = static_cast(data>>8 & 0xffff); + auto protoFeatures = static_cast(data >> 8 & 0xffff); _supportedProtos.append(PeerFactory::ProtoDescriptor(type, protoFeatures)); - if (data >= 0x80000000) { // last protocol + if (data >= 0x80000000) { // last protocol Compressor::CompressionLevel level; if (_connectionFeatures & Protocol::Compression) level = Compressor::BestCompression; else level = Compressor::NoCompression; - RemotePeer *peer = PeerFactory::createPeer(_supportedProtos, this, socket(), level, this); + RemotePeer* peer = PeerFactory::createPeer(_supportedProtos, this, socket(), level, this); if (!peer) { qWarning() << "Received invalid handshake data from client" << socket()->peerAddress().toString(); close(); @@ -111,20 +113,19 @@ void CoreAuthHandler::onReadyRead() setPeer(peer); // inform the client - quint32 reply = peer->protocol() | peer->enabledFeatures()<<8 | _connectionFeatures<<24; + quint32 reply = peer->protocol() | peer->enabledFeatures() << 8 | _connectionFeatures << 24; reply = qToBigEndian(reply); socket()->write((char*)&reply, 4); socket()->flush(); if (!_legacy && (_connectionFeatures & Protocol::Encryption)) - startSsl(); // legacy peer enables it later + startSsl(); // legacy peer enables it later return; } } } - -void CoreAuthHandler::setPeer(RemotePeer *peer) +void CoreAuthHandler::setPeer(RemotePeer* peer) { qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "..."; @@ -138,25 +139,26 @@ void CoreAuthHandler::onProtocolVersionMismatch(int actual, int expected) qWarning() << qPrintable(tr("Client")) << _peer->description() << qPrintable(tr("too old, rejecting.")); QString errorString = tr("Your Quassel Client is too old!
" "This core needs at least client/core protocol version %1 (got: %2).
" - "Please consider upgrading your client.").arg(expected, actual); + "Please consider upgrading your client.") + .arg(expected, actual); _peer->dispatch(ClientDenied(errorString)); _peer->close(); } - bool CoreAuthHandler::checkClientRegistered() { if (!_clientRegistered) { - qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString()) << qPrintable(tr("did not send a registration message before trying to login, rejecting.")); - _peer->dispatch(ClientDenied(tr("Client not initialized!
You need to send a registration message before trying to login."))); + qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString()) + << qPrintable(tr("did not send a registration message before trying to login, rejecting.")); + _peer->dispatch( + ClientDenied(tr("Client not initialized!
You need to send a registration message before trying to login."))); _peer->close(); return false; } return true; } - -void CoreAuthHandler::handle(const RegisterClient &msg) +void CoreAuthHandler::handle(const RegisterClient& msg) { bool useSsl; if (_legacy) @@ -194,8 +196,7 @@ void CoreAuthHandler::handle(const RegisterClient &msg) _clientRegistered = true; } - -void CoreAuthHandler::handle(const SetupData &msg) +void CoreAuthHandler::handle(const SetupData& msg) { if (!checkClientRegistered()) return; @@ -215,15 +216,16 @@ void CoreAuthHandler::handle(const SetupData &msg) _peer->dispatch(SetupDone()); } - -void CoreAuthHandler::handle(const Login &msg) +void CoreAuthHandler::handle(const Login& msg) { if (!checkClientRegistered()) return; if (!Core::isConfigured()) { - qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString()) << qPrintable(tr("attempted to login before the core was configured, rejecting.")); - _peer->dispatch(ClientDenied(tr("Attempted to login before core was configured!
The core must be configured before attempting to login."))); + qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString()) + << qPrintable(tr("attempted to login before the core was configured, rejecting.")); + _peer->dispatch(ClientDenied( + tr("Attempted to login before core was configured!
The core must be configured before attempting to login."))); return; } @@ -236,14 +238,16 @@ void CoreAuthHandler::handle(const Login &msg) if (uid == 0) { quInfo() << qPrintable(tr("Invalid login attempt from %1 as \"%2\"").arg(socket()->peerAddress().toString(), msg.user)); - _peer->dispatch(LoginFailed(tr("Invalid username or password!
The username/password combination you supplied could not be found in the database."))); + _peer->dispatch(LoginFailed(tr( + "Invalid username or password!
The username/password combination you supplied could not be found in the database."))); return; } _peer->dispatch(LoginSuccess()); - quInfo() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).").arg(socket()->peerAddress().toString(), msg.user, QString::number(uid.toInt()))); + quInfo() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).") + .arg(socket()->peerAddress().toString(), msg.user, QString::number(uid.toInt()))); - const auto &clientFeatures = _peer->features(); + const auto& clientFeatures = _peer->features(); auto unsupported = clientFeatures.toStringList(false); if (!unsupported.isEmpty()) { if (unsupported.contains("NoFeatures")) @@ -258,35 +262,32 @@ void CoreAuthHandler::handle(const Login &msg) disconnect(socket(), nullptr, this, nullptr); disconnect(_peer, nullptr, this, nullptr); - _peer->setParent(nullptr); // Core needs to take care of this one now! + _peer->setParent(nullptr); // Core needs to take care of this one now! - socket()->flush(); // Make sure all data is sent before handing over the peer (and socket) to the session thread (bug 682) + socket()->flush(); // Make sure all data is sent before handing over the peer (and socket) to the session thread (bug 682) emit handshakeComplete(_peer, uid); } - /*** SSL Stuff ***/ void CoreAuthHandler::startSsl() { - #ifdef HAVE_SSL - auto *sslSocket = qobject_cast(socket()); +#ifdef HAVE_SSL + auto* sslSocket = qobject_cast(socket()); Q_ASSERT(sslSocket); - qDebug() << qPrintable(tr("Starting encryption for Client:")) << _peer->description(); - connect(sslSocket, selectOverload &>(&QSslSocket::sslErrors), this, &CoreAuthHandler::onSslErrors); - sslSocket->flush(); // ensure that the write cache is flushed before we switch to ssl (bug 682) + qDebug() << qPrintable(tr("Starting encryption for Client:")) << _peer->description(); + connect(sslSocket, selectOverload&>(&QSslSocket::sslErrors), this, &CoreAuthHandler::onSslErrors); + sslSocket->flush(); // ensure that the write cache is flushed before we switch to ssl (bug 682) sslSocket->startServerEncryption(); - #endif /* HAVE_SSL */ +#endif /* HAVE_SSL */ } - #ifdef HAVE_SSL void CoreAuthHandler::onSslErrors() { - auto *sslSocket = qobject_cast(socket()); + auto* sslSocket = qobject_cast(socket()); Q_ASSERT(sslSocket); sslSocket->ignoreSslErrors(); } #endif - diff --git a/src/core/coreauthhandler.h b/src/core/coreauthhandler.h index e26e94c0..9a420af6 100644 --- a/src/core/coreauthhandler.h +++ b/src/core/coreauthhandler.h @@ -31,19 +31,19 @@ class CoreAuthHandler : public AuthHandler Q_OBJECT public: - CoreAuthHandler(QTcpSocket *socket, QObject *parent = nullptr); + CoreAuthHandler(QTcpSocket* socket, QObject* parent = nullptr); signals: - void handshakeComplete(RemotePeer *peer, UserId uid); + void handshakeComplete(RemotePeer* peer, UserId uid); private: using AuthHandler::handle; - void handle(const Protocol::RegisterClient &msg) override; - void handle(const Protocol::SetupData &msg) override; - void handle(const Protocol::Login &msg) override; + void handle(const Protocol::RegisterClient& msg) override; + void handle(const Protocol::SetupData& msg) override; + void handle(const Protocol::Login& msg) override; - void setPeer(RemotePeer *peer); + void setPeer(RemotePeer* peer); void startSsl(); bool checkClientRegistered(); @@ -59,7 +59,7 @@ private slots: void onProtocolVersionMismatch(int actual, int expected); private: - RemotePeer *_peer; + RemotePeer* _peer; bool _magicReceived; bool _legacy; diff --git a/src/core/corebacklogmanager.cpp b/src/core/corebacklogmanager.cpp index 8a974a19..e1466da4 100644 --- a/src/core/corebacklogmanager.cpp +++ b/src/core/corebacklogmanager.cpp @@ -19,17 +19,16 @@ ***************************************************************************/ #include "corebacklogmanager.h" -#include "core.h" -#include "coresession.h" #include -CoreBacklogManager::CoreBacklogManager(CoreSession *coreSession) - : BacklogManager(coreSession), - _coreSession(coreSession) -{ -} +#include "core.h" +#include "coresession.h" +CoreBacklogManager::CoreBacklogManager(CoreSession* coreSession) + : BacklogManager(coreSession) + , _coreSession(coreSession) +{} QVariantList CoreBacklogManager::requestBacklog(BufferId bufferId, MsgId first, MsgId last, int limit, int additional) { @@ -76,7 +75,6 @@ QVariantList CoreBacklogManager::requestBacklog(BufferId bufferId, MsgId first, return backlog; } - QVariantList CoreBacklogManager::requestBacklogFiltered(BufferId bufferId, MsgId first, MsgId last, int limit, int additional, int type, int flags) { QVariantList backlog; @@ -122,7 +120,6 @@ QVariantList CoreBacklogManager::requestBacklogFiltered(BufferId bufferId, MsgId return backlog; } - QVariantList CoreBacklogManager::requestBacklogAll(MsgId first, MsgId last, int limit, int additional) { QVariantList backlog; @@ -161,9 +158,7 @@ QVariantList CoreBacklogManager::requestBacklogAll(MsgId first, MsgId last, int return backlog; } - -QVariantList CoreBacklogManager::requestBacklogAllFiltered(MsgId first, MsgId last, int limit, int additional, int type, - int flags) +QVariantList CoreBacklogManager::requestBacklogAllFiltered(MsgId first, MsgId last, int limit, int additional, int type, int flags) { QVariantList backlog; QList msgList; diff --git a/src/core/corebacklogmanager.h b/src/core/corebacklogmanager.h index 356660bd..0226e39c 100644 --- a/src/core/corebacklogmanager.h +++ b/src/core/corebacklogmanager.h @@ -29,18 +29,18 @@ class CoreBacklogManager : public BacklogManager Q_OBJECT public: - CoreBacklogManager(CoreSession *coreSession = nullptr); + CoreBacklogManager(CoreSession* coreSession = nullptr); - CoreSession *coreSession() { return _coreSession; } + CoreSession* coreSession() { return _coreSession; } public slots: QVariantList requestBacklog(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0) override; - QVariantList requestBacklogFiltered(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, - int additional = 0, int type = -1, int flags = -1) override; + QVariantList requestBacklogFiltered( + BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1) override; QVariantList requestBacklogAll(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0) override; - QVariantList requestBacklogAllFiltered(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, - int type = -1, int flags = -1) override; + QVariantList requestBacklogAllFiltered( + MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1) override; private: - CoreSession *_coreSession; + CoreSession* _coreSession; }; diff --git a/src/core/corebasichandler.cpp b/src/core/corebasichandler.cpp index a458b79a..38b510e5 100644 --- a/src/core/corebasichandler.cpp +++ b/src/core/corebasichandler.cpp @@ -20,112 +20,109 @@ #include "corebasichandler.h" -#include "util.h" #include "logmessage.h" +#include "util.h" -CoreBasicHandler::CoreBasicHandler(CoreNetwork *parent) - : BasicHandler(parent), - _network(parent) +CoreBasicHandler::CoreBasicHandler(CoreNetwork* parent) + : BasicHandler(parent) + , _network(parent) { connect(this, &CoreBasicHandler::displayMsg, network(), &CoreNetwork::onDisplayMsg); connect(this, &CoreBasicHandler::putRawLine, network(), &CoreNetwork::putRawLine); - connect(this, selectOverload&, const QByteArray&, bool>(&CoreBasicHandler::putCmd), - network(), selectOverload&, const QByteArray&, bool>(&CoreNetwork::putCmd)); - connect(this, selectOverload>&, const QByteArray&, bool>(&CoreBasicHandler::putCmd), - network(), selectOverload>&, const QByteArray&, bool>(&CoreNetwork::putCmd)); + connect(this, + selectOverload&, const QByteArray&, bool>(&CoreBasicHandler::putCmd), + network(), + selectOverload&, const QByteArray&, bool>(&CoreNetwork::putCmd)); + connect(this, + selectOverload>&, const QByteArray&, bool>(&CoreBasicHandler::putCmd), + network(), + selectOverload>&, const QByteArray&, bool>(&CoreNetwork::putCmd)); } - -QString CoreBasicHandler::serverDecode(const QByteArray &string) +QString CoreBasicHandler::serverDecode(const QByteArray& string) { return network()->serverDecode(string); } - -QStringList CoreBasicHandler::serverDecode(const QList &stringlist) +QStringList CoreBasicHandler::serverDecode(const QList& stringlist) { QStringList list; - foreach(QByteArray s, stringlist) list << network()->serverDecode(s); + foreach (QByteArray s, stringlist) + list << network()->serverDecode(s); return list; } - -QString CoreBasicHandler::channelDecode(const QString &bufferName, const QByteArray &string) +QString CoreBasicHandler::channelDecode(const QString& bufferName, const QByteArray& string) { return network()->channelDecode(bufferName, string); } - -QStringList CoreBasicHandler::channelDecode(const QString &bufferName, const QList &stringlist) +QStringList CoreBasicHandler::channelDecode(const QString& bufferName, const QList& stringlist) { QStringList list; - foreach(QByteArray s, stringlist) list << network()->channelDecode(bufferName, s); + foreach (QByteArray s, stringlist) + list << network()->channelDecode(bufferName, s); return list; } - -QString CoreBasicHandler::userDecode(const QString &userNick, const QByteArray &string) +QString CoreBasicHandler::userDecode(const QString& userNick, const QByteArray& string) { return network()->userDecode(userNick, string); } - -QStringList CoreBasicHandler::userDecode(const QString &userNick, const QList &stringlist) +QStringList CoreBasicHandler::userDecode(const QString& userNick, const QList& stringlist) { QStringList list; - foreach(QByteArray s, stringlist) list << network()->userDecode(userNick, s); + foreach (QByteArray s, stringlist) + list << network()->userDecode(userNick, s); return list; } - /*** ***/ -QByteArray CoreBasicHandler::serverEncode(const QString &string) +QByteArray CoreBasicHandler::serverEncode(const QString& string) { return network()->serverEncode(string); } - -QList CoreBasicHandler::serverEncode(const QStringList &stringlist) +QList CoreBasicHandler::serverEncode(const QStringList& stringlist) { QList list; - foreach(QString s, stringlist) list << network()->serverEncode(s); + foreach (QString s, stringlist) + list << network()->serverEncode(s); return list; } - -QByteArray CoreBasicHandler::channelEncode(const QString &bufferName, const QString &string) +QByteArray CoreBasicHandler::channelEncode(const QString& bufferName, const QString& string) { return network()->channelEncode(bufferName, string); } - -QList CoreBasicHandler::channelEncode(const QString &bufferName, const QStringList &stringlist) +QList CoreBasicHandler::channelEncode(const QString& bufferName, const QStringList& stringlist) { QList list; - foreach(QString s, stringlist) list << network()->channelEncode(bufferName, s); + foreach (QString s, stringlist) + list << network()->channelEncode(bufferName, s); return list; } - -QByteArray CoreBasicHandler::userEncode(const QString &userNick, const QString &string) +QByteArray CoreBasicHandler::userEncode(const QString& userNick, const QString& string) { return network()->userEncode(userNick, string); } - -QList CoreBasicHandler::userEncode(const QString &userNick, const QStringList &stringlist) +QList CoreBasicHandler::userEncode(const QString& userNick, const QStringList& stringlist) { QList list; - foreach(QString s, stringlist) list << network()->userEncode(userNick, s); + foreach (QString s, stringlist) + list << network()->userEncode(userNick, s); return list; } - // ==================== // protected: // ==================== -BufferInfo::Type CoreBasicHandler::typeByTarget(const QString &target) const +BufferInfo::Type CoreBasicHandler::typeByTarget(const QString& target) const { if (target.isEmpty()) return BufferInfo::StatusBuffer; @@ -136,8 +133,7 @@ BufferInfo::Type CoreBasicHandler::typeByTarget(const QString &target) const return BufferInfo::QueryBuffer; } - -void CoreBasicHandler::putCmd(const QString &cmd, const QByteArray ¶m, const QByteArray &prefix, const bool prepend) +void CoreBasicHandler::putCmd(const QString& cmd, const QByteArray& param, const QByteArray& prefix, const bool prepend) { QList list; list << param; diff --git a/src/core/corebasichandler.h b/src/core/corebasichandler.h index f741112e..b55052e5 100644 --- a/src/core/corebasichandler.h +++ b/src/core/corebasichandler.h @@ -25,9 +25,8 @@ #include #include "basichandler.h" -#include "message.h" - #include "corenetwork.h" +#include "message.h" class CoreSession; @@ -36,45 +35,52 @@ class CoreBasicHandler : public BasicHandler Q_OBJECT public: - CoreBasicHandler(CoreNetwork *parent = nullptr); - - QString serverDecode(const QByteArray &string); - QStringList serverDecode(const QList &stringlist); - QString channelDecode(const QString &bufferName, const QByteArray &string); - QStringList channelDecode(const QString &bufferName, const QList &stringlist); - QString userDecode(const QString &userNick, const QByteArray &string); - QStringList userDecode(const QString &userNick, const QList &stringlist); - - QByteArray serverEncode(const QString &string); - QList serverEncode(const QStringList &stringlist); - QByteArray channelEncode(const QString &bufferName, const QString &string); - QList channelEncode(const QString &bufferName, const QStringList &stringlist); - QByteArray userEncode(const QString &userNick, const QString &string); - QList userEncode(const QString &userNick, const QStringList &stringlist); + CoreBasicHandler(CoreNetwork* parent = nullptr); + + QString serverDecode(const QByteArray& string); + QStringList serverDecode(const QList& stringlist); + QString channelDecode(const QString& bufferName, const QByteArray& string); + QStringList channelDecode(const QString& bufferName, const QList& stringlist); + QString userDecode(const QString& userNick, const QByteArray& string); + QStringList userDecode(const QString& userNick, const QList& stringlist); + + QByteArray serverEncode(const QString& string); + QList serverEncode(const QStringList& stringlist); + QByteArray channelEncode(const QString& bufferName, const QString& string); + QList channelEncode(const QString& bufferName, const QStringList& stringlist); + QByteArray userEncode(const QString& userNick, const QString& string); + QList userEncode(const QString& userNick, const QStringList& stringlist); signals: - void displayMsg(Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None); + void displayMsg(Message::Type, + BufferInfo::Type, + const QString& target, + const QString& text, + const QString& sender = "", + Message::Flags flags = Message::None); /** * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority. * * @see CoreNetwork::putRawLine() */ - void putRawLine(const QByteArray &msg, const bool prepend = false); + void putRawLine(const QByteArray& msg, const bool prepend = false); /** * Sends the command with encoded parameters, with optional prefix or high priority. * - * @see CoreNetwork::putCmd(const QString &cmd, const QList ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false) + * @see CoreNetwork::putCmd(const QString &cmd, const QList ¶ms, const QByteArray &prefix = QByteArray(), const bool + * prepend = false) */ - void putCmd(const QString &cmd, const QList ¶ms, const QByteArray &prefix = {}, bool prepend = false); + void putCmd(const QString& cmd, const QList& params, const QByteArray& prefix = {}, bool prepend = false); /** * Sends the command for each set of encoded parameters, with optional prefix or high priority. * - * @see CoreNetwork::putCmd(const QString &cmd, const QList> ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false) + * @see CoreNetwork::putCmd(const QString &cmd, const QList> ¶ms, const QByteArray &prefix = QByteArray(), const + * bool prepend = false) */ - void putCmd(const QString &cmd, const QList> ¶ms, const QByteArray &prefix = {}, bool prepend = false); + void putCmd(const QString& cmd, const QList>& params, const QByteArray& prefix = {}, bool prepend = false); protected: /** @@ -90,16 +96,15 @@ protected: * maintain PING/PONG replies, the other side will close the connection. * @endparmblock */ - void putCmd(const QString &cmd, const QByteArray ¶m, const QByteArray &prefix = QByteArray(), const bool prepend = false); + void putCmd(const QString& cmd, const QByteArray& param, const QByteArray& prefix = QByteArray(), const bool prepend = false); - inline CoreNetwork *network() const { return _network; } - inline CoreSession *coreSession() const { return _network->coreSession(); } + inline CoreNetwork* network() const { return _network; } + inline CoreSession* coreSession() const { return _network->coreSession(); } - BufferInfo::Type typeByTarget(const QString &target) const; + BufferInfo::Type typeByTarget(const QString& target) const; private: - CoreNetwork *_network; + CoreNetwork* _network; }; - #endif diff --git a/src/core/corebuffersyncer.cpp b/src/core/corebuffersyncer.cpp index d7d5be9a..a493160b 100644 --- a/src/core/corebuffersyncer.cpp +++ b/src/core/corebuffersyncer.cpp @@ -21,27 +21,32 @@ #include "corebuffersyncer.h" #include "core.h" -#include "coresession.h" #include "corenetwork.h" +#include "coresession.h" #include "ircchannel.h" class PurgeEvent : public QEvent { public: - PurgeEvent() : QEvent(QEvent::User) {} + PurgeEvent() + : QEvent(QEvent::User) + {} }; -CoreBufferSyncer::CoreBufferSyncer(CoreSession *parent) - : BufferSyncer(Core::bufferLastSeenMsgIds(parent->user()), Core::bufferMarkerLineMsgIds(parent->user()), Core::bufferActivities(parent->user()), Core::highlightCounts(parent->user()), parent), - _coreSession(parent), - _purgeBuffers(false) +CoreBufferSyncer::CoreBufferSyncer(CoreSession* parent) + : BufferSyncer(Core::bufferLastSeenMsgIds(parent->user()), + Core::bufferMarkerLineMsgIds(parent->user()), + Core::bufferActivities(parent->user()), + Core::highlightCounts(parent->user()), + parent) + , _coreSession(parent) + , _purgeBuffers(false) { connect(parent, &CoreSession::displayMsg, this, &CoreBufferSyncer::addBufferActivity); connect(parent, &CoreSession::displayMsg, this, &CoreBufferSyncer::addCoreHighlight); } - -void CoreBufferSyncer::requestSetLastSeenMsg(BufferId buffer, const MsgId &msgId) +void CoreBufferSyncer::requestSetLastSeenMsg(BufferId buffer, const MsgId& msgId) { if (setLastSeenMsg(buffer, msgId)) { int activity = Core::bufferActivity(buffer, msgId); @@ -54,35 +59,33 @@ void CoreBufferSyncer::requestSetLastSeenMsg(BufferId buffer, const MsgId &msgId } } - -void CoreBufferSyncer::requestSetMarkerLine(BufferId buffer, const MsgId &msgId) +void CoreBufferSyncer::requestSetMarkerLine(BufferId buffer, const MsgId& msgId) { if (setMarkerLine(buffer, msgId)) dirtyMarkerLineBuffers << buffer; } - void CoreBufferSyncer::storeDirtyIds() { UserId userId = _coreSession->user(); MsgId msgId; - foreach(BufferId bufferId, dirtyLastSeenBuffers) { + foreach (BufferId bufferId, dirtyLastSeenBuffers) { msgId = lastSeenMsg(bufferId); if (msgId.isValid()) Core::setBufferLastSeenMsg(userId, bufferId, msgId); } - foreach(BufferId bufferId, dirtyMarkerLineBuffers) { + foreach (BufferId bufferId, dirtyMarkerLineBuffers) { msgId = markerLine(bufferId); if (msgId.isValid()) Core::setBufferMarkerLineMsg(userId, bufferId, msgId); } - foreach(BufferId bufferId, dirtyActivities) { + foreach (BufferId bufferId, dirtyActivities) { Core::setBufferActivity(userId, bufferId, activity(bufferId)); } - foreach(BufferId bufferId, dirtyHighlights) { + foreach (BufferId bufferId, dirtyHighlights) { Core::setHighlightCount(userId, bufferId, highlightCount(bufferId)); } @@ -92,7 +95,6 @@ void CoreBufferSyncer::storeDirtyIds() dirtyHighlights.clear(); } - void CoreBufferSyncer::removeBuffer(BufferId bufferId) { BufferInfo bufferInfo = Core::getBufferInfo(_coreSession->user(), bufferId); @@ -107,12 +109,12 @@ void CoreBufferSyncer::removeBuffer(BufferId bufferId) } if (bufferInfo.type() == BufferInfo::ChannelBuffer) { - CoreNetwork *net = _coreSession->network(bufferInfo.networkId()); + CoreNetwork* net = _coreSession->network(bufferInfo.networkId()); if (!net) { qWarning() << "CoreBufferSyncer::removeBuffer(): Received BufferInfo with unknown networkId!"; return; } - IrcChannel *chan = net->ircChannel(bufferInfo.bufferName()); + IrcChannel* chan = net->ircChannel(bufferInfo.bufferName()); if (chan) { qWarning() << "CoreBufferSyncer::removeBuffer(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName(); return; @@ -122,7 +124,6 @@ void CoreBufferSyncer::removeBuffer(BufferId bufferId) BufferSyncer::removeBuffer(bufferId); } - void CoreBufferSyncer::renameBuffer(BufferId bufferId, QString newName) { BufferInfo bufferInfo = Core::getBufferInfo(_coreSession->user(), bufferId); @@ -140,20 +141,21 @@ void CoreBufferSyncer::renameBuffer(BufferId bufferId, QString newName) BufferSyncer::renameBuffer(bufferId, newName); } - void CoreBufferSyncer::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) { BufferInfo bufferInfo1 = Core::getBufferInfo(_coreSession->user(), bufferId1); BufferInfo bufferInfo2 = Core::getBufferInfo(_coreSession->user(), bufferId2); if (!bufferInfo1.isValid() || !bufferInfo2.isValid()) { - qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): invalid BufferIds:" << bufferId1 << bufferId2 << "for User:" << _coreSession->user(); + qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): invalid BufferIds:" << bufferId1 << bufferId2 + << "for User:" << _coreSession->user(); return; } if ((bufferInfo1.type() != BufferInfo::QueryBuffer && bufferInfo1.type() != BufferInfo::ChannelBuffer) || (bufferInfo2.type() != BufferInfo::QueryBuffer && bufferInfo2.type() != BufferInfo::ChannelBuffer)) { - qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): only QueryBuffers and/or ChannelBuffers can be merged!" << bufferId1 << bufferId2; - return; + qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): only QueryBuffers and/or ChannelBuffers can be merged!" << bufferId1 + << bufferId2; + return; } if (Core::mergeBuffersPermanently(_coreSession->user(), bufferId1, bufferId2)) { @@ -161,8 +163,7 @@ void CoreBufferSyncer::mergeBuffersPermanently(BufferId bufferId1, BufferId buff } } - -void CoreBufferSyncer::customEvent(QEvent *event) +void CoreBufferSyncer::customEvent(QEvent* event) { if (event->type() != QEvent::User) return; @@ -171,7 +172,6 @@ void CoreBufferSyncer::customEvent(QEvent *event) event->accept(); } - void CoreBufferSyncer::requestPurgeBufferIds() { if (_purgeBuffers) @@ -181,30 +181,31 @@ void CoreBufferSyncer::requestPurgeBufferIds() QCoreApplication::postEvent(this, new PurgeEvent()); } - void CoreBufferSyncer::purgeBufferIds() { _purgeBuffers = false; QList bufferInfos = Core::requestBuffers(_coreSession->user()); QSet actualBuffers; - foreach(BufferInfo bufferInfo, bufferInfos) { + foreach (BufferInfo bufferInfo, bufferInfos) { actualBuffers << bufferInfo.bufferId(); } QSet storedIds = lastSeenBufferIds().toSet() + markerLineBufferIds().toSet(); - foreach(BufferId bufferId, storedIds) { + foreach (BufferId bufferId, storedIds) { if (!actualBuffers.contains(bufferId)) { BufferSyncer::removeBuffer(bufferId); } } } -void CoreBufferSyncer::setBufferActivity(BufferId buffer, int activity) { +void CoreBufferSyncer::setBufferActivity(BufferId buffer, int activity) +{ BufferSyncer::setBufferActivity(buffer, activity); dirtyActivities << buffer; } -void CoreBufferSyncer::setHighlightCount(BufferId buffer, int highlightCount) { +void CoreBufferSyncer::setHighlightCount(BufferId buffer, int highlightCount) +{ BufferSyncer::setHighlightCount(buffer, highlightCount); dirtyHighlights << buffer; } diff --git a/src/core/corebuffersyncer.h b/src/core/corebuffersyncer.h index 3fba1c75..3f031cf1 100644 --- a/src/core/corebuffersyncer.h +++ b/src/core/corebuffersyncer.h @@ -29,23 +29,25 @@ class CoreBufferSyncer : public BufferSyncer Q_OBJECT public: - explicit CoreBufferSyncer(CoreSession *parent); + explicit CoreBufferSyncer(CoreSession* parent); public slots: - void requestSetLastSeenMsg(BufferId buffer, const MsgId &msgId) override; - void requestSetMarkerLine(BufferId buffer, const MsgId &msgId) override; + void requestSetLastSeenMsg(BufferId buffer, const MsgId& msgId) override; + void requestSetMarkerLine(BufferId buffer, const MsgId& msgId) override; inline void requestRemoveBuffer(BufferId buffer) override { removeBuffer(buffer); } void removeBuffer(BufferId bufferId) override; - void addBufferActivity(const Message &message) { + void addBufferActivity(const Message& message) + { auto oldActivity = activity(message.bufferId()); if (!oldActivity.testFlag(message.type())) { - setBufferActivity(message.bufferId(), (int) (oldActivity | message.type())); + setBufferActivity(message.bufferId(), (int)(oldActivity | message.type())); } } - void addCoreHighlight(const Message &message) { + void addCoreHighlight(const Message& message) + { auto oldHighlightCount = highlightCount(message.bufferId()); if (message.flags().testFlag(Message::Flag::Highlight) && !message.flags().testFlag(Message::Flag::Self)) { setHighlightCount(message.bufferId(), oldHighlightCount + 1); @@ -64,7 +66,8 @@ public slots: void requestPurgeBufferIds() override; - inline void requestMarkBufferAsRead(BufferId buffer) override { + inline void requestMarkBufferAsRead(BufferId buffer) override + { int activity = Message::Types(); setBufferActivity(buffer, activity); setHighlightCount(buffer, 0); @@ -74,10 +77,10 @@ public slots: void storeDirtyIds(); protected: - void customEvent(QEvent *event) override; + void customEvent(QEvent* event) override; private: - CoreSession *_coreSession; + CoreSession* _coreSession; bool _purgeBuffers; QSet dirtyLastSeenBuffers; diff --git a/src/core/corebufferviewconfig.cpp b/src/core/corebufferviewconfig.cpp index c8908d30..a41a955f 100644 --- a/src/core/corebufferviewconfig.cpp +++ b/src/core/corebufferviewconfig.cpp @@ -20,14 +20,13 @@ #include "corebufferviewconfig.h" -CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, QObject *parent) +CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, QObject* parent) : BufferViewConfig(bufferViewId, parent) { setAllowClientUpdates(true); } - -CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent) +CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent) : BufferViewConfig(bufferViewId, properties, parent) { setAllowClientUpdates(true); diff --git a/src/core/corebufferviewconfig.h b/src/core/corebufferviewconfig.h index 3cb0b100..c4122362 100644 --- a/src/core/corebufferviewconfig.h +++ b/src/core/corebufferviewconfig.h @@ -27,13 +27,13 @@ class CoreBufferViewConfig : public BufferViewConfig Q_OBJECT public: - CoreBufferViewConfig(int bufferViewId, QObject *parent = nullptr); - CoreBufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent = nullptr); + CoreBufferViewConfig(int bufferViewId, QObject* parent = nullptr); + CoreBufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent = nullptr); public slots: - inline void requestSetBufferViewName(const QString &bufferViewName) override { setBufferViewName(bufferViewName); } - inline void requestRemoveBuffer(const BufferId &bufferId) override { removeBuffer(bufferId); } - inline void requestRemoveBufferPermanently(const BufferId &bufferId) override { removeBufferPermanently(bufferId); } - inline void requestAddBuffer(const BufferId &bufferId, int pos) override { addBuffer(bufferId, pos); } - inline void requestMoveBuffer(const BufferId &bufferId, int pos) override { moveBuffer(bufferId, pos); } + inline void requestSetBufferViewName(const QString& bufferViewName) override { setBufferViewName(bufferViewName); } + inline void requestRemoveBuffer(const BufferId& bufferId) override { removeBuffer(bufferId); } + inline void requestRemoveBufferPermanently(const BufferId& bufferId) override { removeBufferPermanently(bufferId); } + inline void requestAddBuffer(const BufferId& bufferId, int pos) override { addBuffer(bufferId, pos); } + inline void requestMoveBuffer(const BufferId& bufferId, int pos) override { moveBuffer(bufferId, pos); } }; diff --git a/src/core/corebufferviewmanager.cpp b/src/core/corebufferviewmanager.cpp index 76157552..96ebc6a8 100644 --- a/src/core/corebufferviewmanager.cpp +++ b/src/core/corebufferviewmanager.cpp @@ -20,19 +20,18 @@ #include "corebufferviewmanager.h" -#include "corebufferviewconfig.h" - #include "core.h" +#include "corebufferviewconfig.h" #include "coresession.h" -CoreBufferViewManager::CoreBufferViewManager(SignalProxy *proxy, CoreSession *parent) - : BufferViewManager(proxy, parent), - _coreSession(parent) +CoreBufferViewManager::CoreBufferViewManager(SignalProxy* proxy, CoreSession* parent) + : BufferViewManager(proxy, parent) + , _coreSession(parent) { QVariantMap views = Core::getUserSetting(_coreSession->user(), "BufferViews").toMap(); QVariantMap::iterator iter = views.begin(); QVariantMap::iterator iterEnd = views.end(); - CoreBufferViewConfig *config = nullptr; + CoreBufferViewConfig* config = nullptr; while (iter != iterEnd) { config = new CoreBufferViewConfig(iter.key().toInt(), iter.value().toMap(), this); addBufferViewConfig(config); @@ -40,7 +39,6 @@ CoreBufferViewManager::CoreBufferViewManager(SignalProxy *proxy, CoreSession *pa } } - void CoreBufferViewManager::saveBufferViews() { QVariantMap views; @@ -55,8 +53,7 @@ void CoreBufferViewManager::saveBufferViews() Core::setUserSetting(_coreSession->user(), "BufferViews", views); } - -void CoreBufferViewManager::requestCreateBufferView(const QVariantMap &properties) +void CoreBufferViewManager::requestCreateBufferView(const QVariantMap& properties) { QString bufferViewName = properties["bufferViewName"].toString(); int maxId = -1; @@ -76,8 +73,7 @@ void CoreBufferViewManager::requestCreateBufferView(const QVariantMap &propertie addBufferViewConfig(new CoreBufferViewConfig(maxId, properties, this)); } - -void CoreBufferViewManager::requestCreateBufferViews(const QVariantList &properties) +void CoreBufferViewManager::requestCreateBufferViews(const QVariantList& properties) { QVariantList::const_iterator iter = properties.constBegin(); QVariantList::const_iterator iterEnd = properties.constEnd(); @@ -87,16 +83,14 @@ void CoreBufferViewManager::requestCreateBufferViews(const QVariantList &propert } } - void CoreBufferViewManager::requestDeleteBufferView(int bufferViewId) { deleteBufferViewConfig(bufferViewId); } - -void CoreBufferViewManager::requestDeleteBufferViews(const QVariantList &bufferViews) +void CoreBufferViewManager::requestDeleteBufferViews(const QVariantList& bufferViews) { - foreach(QVariant bufferView, bufferViews) { + foreach (QVariant bufferView, bufferViews) { deleteBufferViewConfig(bufferView.toInt()); } } diff --git a/src/core/corebufferviewmanager.h b/src/core/corebufferviewmanager.h index e24f2e65..b35c08ec 100644 --- a/src/core/corebufferviewmanager.h +++ b/src/core/corebufferviewmanager.h @@ -29,16 +29,16 @@ class CoreBufferViewManager : public BufferViewManager Q_OBJECT public: - CoreBufferViewManager(SignalProxy *proxy, CoreSession *parent); + CoreBufferViewManager(SignalProxy* proxy, CoreSession* parent); public slots: - void requestCreateBufferView(const QVariantMap &properties) override; - void requestCreateBufferViews(const QVariantList &properties) override; + void requestCreateBufferView(const QVariantMap& properties) override; + void requestCreateBufferViews(const QVariantList& properties) override; void requestDeleteBufferView(int bufferViewId) override; - void requestDeleteBufferViews(const QVariantList &bufferViews) override; + void requestDeleteBufferViews(const QVariantList& bufferViews) override; void saveBufferViews(); private: - CoreSession *_coreSession; + CoreSession* _coreSession; }; diff --git a/src/core/coredccconfig.cpp b/src/core/coredccconfig.cpp index 077bb68a..01578403 100644 --- a/src/core/coredccconfig.cpp +++ b/src/core/coredccconfig.cpp @@ -25,7 +25,7 @@ constexpr auto settingsKey = "DccConfig"; -CoreDccConfig::CoreDccConfig(CoreSession *session) +CoreDccConfig::CoreDccConfig(CoreSession* session) : DccConfig(session) , _coreSession{session} { @@ -39,7 +39,6 @@ CoreDccConfig::CoreDccConfig(CoreSession *session) connect(this, &SyncableObject::updatedRemotely, this, &CoreDccConfig::save); } - void CoreDccConfig::save() { Core::setUserSetting(_coreSession->user(), settingsKey, toVariantMap()); diff --git a/src/core/coredccconfig.h b/src/core/coredccconfig.h index dfffda57..e86102f5 100644 --- a/src/core/coredccconfig.h +++ b/src/core/coredccconfig.h @@ -38,7 +38,7 @@ public: * * @param[in] session Pointer to the parent CoreSession (takes ownership) */ - CoreDccConfig(CoreSession *session); + CoreDccConfig(CoreSession* session); public slots: /** @@ -47,5 +47,5 @@ public slots: void save(); private: - CoreSession *_coreSession {nullptr}; ///< Pointer to the parent CoreSession + CoreSession* _coreSession{nullptr}; ///< Pointer to the parent CoreSession }; diff --git a/src/core/coreeventmanager.h b/src/core/coreeventmanager.h index 90c38382..e4c5ff80 100644 --- a/src/core/coreeventmanager.h +++ b/src/core/coreeventmanager.h @@ -30,16 +30,16 @@ class CoreEventManager : public EventManager Q_OBJECT public: - CoreEventManager(CoreSession *session) + CoreEventManager(CoreSession* session) : EventManager(session) , _coreSession(session) {} protected: - inline Network *networkById(NetworkId id) const override { return _coreSession->network(id); } + inline Network* networkById(NetworkId id) const override { return _coreSession->network(id); } private: - CoreSession *_coreSession; + CoreSession* _coreSession; }; #endif diff --git a/src/core/corehighlightrulemanager.cpp b/src/core/corehighlightrulemanager.cpp index 99a046f3..66e9dc5e 100644 --- a/src/core/corehighlightrulemanager.cpp +++ b/src/core/corehighlightrulemanager.cpp @@ -25,7 +25,7 @@ constexpr auto settingsKey = "HighlightRuleList"; -CoreHighlightRuleManager::CoreHighlightRuleManager(CoreSession *session) +CoreHighlightRuleManager::CoreHighlightRuleManager(CoreSession* session) : HighlightRuleManager(session) , _coreSession{session} { @@ -44,9 +44,7 @@ void CoreHighlightRuleManager::save() Core::setUserSetting(_coreSession->user(), settingsKey, toVariantMap()); } -bool CoreHighlightRuleManager::match(const RawMessage &msg, const QString ¤tNick, - const QStringList &identityNicks) +bool CoreHighlightRuleManager::match(const RawMessage& msg, const QString& currentNick, const QStringList& identityNicks) { - return match(msg.networkId, msg.text, msg.sender, msg.type, msg.flags, msg.target, currentNick, - identityNicks); + return match(msg.networkId, msg.text, msg.sender, msg.type, msg.flags, msg.target, currentNick, identityNicks); } diff --git a/src/core/corehighlightrulemanager.h b/src/core/corehighlightrulemanager.h index 06485249..e8ae4014 100644 --- a/src/core/corehighlightrulemanager.h +++ b/src/core/corehighlightrulemanager.h @@ -42,16 +42,21 @@ public: * * @param[in] session Pointer to the parent CoreSession (takes ownership) */ - explicit CoreHighlightRuleManager(CoreSession *session); + explicit CoreHighlightRuleManager(CoreSession* session); - bool match(const RawMessage &msg, const QString ¤tNick, const QStringList &identityNicks); + bool match(const RawMessage& msg, const QString& currentNick, const QStringList& identityNicks); public slots: inline void requestToggleHighlightRule(int highlightRule) override { toggleHighlightRule(highlightRule); } inline void requestRemoveHighlightRule(int highlightRule) override { removeHighlightRule(highlightRule); } - inline void requestAddHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive, - bool isEnabled, bool isInverse, const QString &sender, - const QString &chanName) override + inline void requestAddHighlightRule(int id, + const QString& name, + bool isRegEx, + bool isCaseSensitive, + bool isEnabled, + bool isInverse, + const QString& sender, + const QString& chanName) override { addHighlightRule(id, name, isRegEx, isCaseSensitive, isEnabled, isInverse, sender, chanName); } @@ -63,5 +68,5 @@ private slots: void save(); private: - CoreSession *_coreSession {nullptr}; ///< Pointer to the parent CoreSession + CoreSession* _coreSession{nullptr}; ///< Pointer to the parent CoreSession }; diff --git a/src/core/coreidentity.cpp b/src/core/coreidentity.cpp index 9e6618a0..f0b75b05 100644 --- a/src/core/coreidentity.cpp +++ b/src/core/coreidentity.cpp @@ -22,7 +22,7 @@ #include "signalproxy.h" -CoreIdentity::CoreIdentity(IdentityId id, QObject *parent) +CoreIdentity::CoreIdentity(IdentityId id, QObject* parent) : Identity(id, parent) #ifdef HAVE_SSL , _certManager(*this) @@ -34,8 +34,7 @@ CoreIdentity::CoreIdentity(IdentityId id, QObject *parent) #endif } - -CoreIdentity::CoreIdentity(const Identity &other, QObject *parent) +CoreIdentity::CoreIdentity(const Identity& other, QObject* parent) : Identity(other, parent) #ifdef HAVE_SSL , _certManager(*this) @@ -47,13 +46,12 @@ CoreIdentity::CoreIdentity(const Identity &other, QObject *parent) #endif } - -CoreIdentity::CoreIdentity(const CoreIdentity &other, QObject *parent) +CoreIdentity::CoreIdentity(const CoreIdentity& other, QObject* parent) : Identity(other, parent) #ifdef HAVE_SSL - , _sslKey(other._sslKey), - _sslCert(other._sslCert), - _certManager(*this) + , _sslKey(other._sslKey) + , _sslCert(other._sslCert) + , _certManager(*this) #endif { #ifdef HAVE_SSL @@ -62,8 +60,7 @@ CoreIdentity::CoreIdentity(const CoreIdentity &other, QObject *parent) #endif } - -void CoreIdentity::synchronize(SignalProxy *proxy) +void CoreIdentity::synchronize(SignalProxy* proxy) { proxy->synchronize(this); #ifdef HAVE_SSL @@ -71,9 +68,8 @@ void CoreIdentity::synchronize(SignalProxy *proxy) #endif } - #ifdef HAVE_SSL -void CoreIdentity::setSslKey(const QByteArray &encoded) +void CoreIdentity::setSslKey(const QByteArray& encoded) { QSslKey key(encoded, QSsl::Rsa); if (key.isNull()) @@ -83,16 +79,14 @@ void CoreIdentity::setSslKey(const QByteArray &encoded) setSslKey(key); } - -void CoreIdentity::setSslCert(const QByteArray &encoded) +void CoreIdentity::setSslCert(const QByteArray& encoded) { setSslCert(QSslCertificate(encoded)); } - #endif -CoreIdentity &CoreIdentity::operator=(const CoreIdentity &identity) +CoreIdentity& CoreIdentity::operator=(const CoreIdentity& identity) { Identity::operator=(identity); #ifdef HAVE_SSL @@ -102,38 +96,33 @@ CoreIdentity &CoreIdentity::operator=(const CoreIdentity &identity) return *this; } - #ifdef HAVE_SSL // ======================================== // CoreCertManager // ======================================== -CoreCertManager::CoreCertManager(CoreIdentity &identity) - : CertManager(identity.id()), - identity(identity) +CoreCertManager::CoreCertManager(CoreIdentity& identity) + : CertManager(identity.id()) + , identity(identity) { setAllowClientUpdates(true); } - void CoreCertManager::setId(IdentityId id) { renameObject(QString::number(id.toInt())); } - -void CoreCertManager::setSslKey(const QByteArray &encoded) +void CoreCertManager::setSslKey(const QByteArray& encoded) { identity.setSslKey(encoded); CertManager::setSslKey(encoded); } - -void CoreCertManager::setSslCert(const QByteArray &encoded) +void CoreCertManager::setSslCert(const QByteArray& encoded) { identity.setSslCert(encoded); CertManager::setSslCert(encoded); } - -#endif //HAVE_SSL +#endif // HAVE_SSL diff --git a/src/core/coreidentity.h b/src/core/coreidentity.h index 8c65146e..72d331c6 100644 --- a/src/core/coreidentity.h +++ b/src/core/coreidentity.h @@ -23,9 +23,9 @@ #include "identity.h" #ifdef HAVE_SSL -#include -#include -#endif //HAVE_SSL +# include +# include +#endif // HAVE_SSL class SignalProxy; @@ -39,25 +39,24 @@ class CoreCertManager : public CertManager Q_OBJECT public: - CoreCertManager(CoreIdentity &identity); + CoreCertManager(CoreIdentity& identity); -#ifdef HAVE_SSL - const QSslKey &sslKey() const override; - const QSslCertificate &sslCert() const override; +# ifdef HAVE_SSL + const QSslKey& sslKey() const override; + const QSslCertificate& sslCert() const override; public slots: - void setSslKey(const QByteArray &encoded) override; - void setSslCert(const QByteArray &encoded) override; -#endif + void setSslKey(const QByteArray& encoded) override; + void setSslCert(const QByteArray& encoded) override; +# endif void setId(IdentityId id); private: - CoreIdentity &identity; + CoreIdentity& identity; }; - -#endif //HAVE_SSL +#endif // HAVE_SSL // ========================================= // CoreIdentity @@ -67,22 +66,22 @@ class CoreIdentity : public Identity Q_OBJECT public: - CoreIdentity(IdentityId id, QObject *parent = nullptr); - CoreIdentity(const Identity &other, QObject *parent = nullptr); - CoreIdentity(const CoreIdentity &other, QObject *parent = nullptr); + CoreIdentity(IdentityId id, QObject* parent = nullptr); + CoreIdentity(const Identity& other, QObject* parent = nullptr); + CoreIdentity(const CoreIdentity& other, QObject* parent = nullptr); - void synchronize(SignalProxy *proxy); + void synchronize(SignalProxy* proxy); #ifdef HAVE_SSL - inline const QSslKey &sslKey() const { return _sslKey; } - inline void setSslKey(const QSslKey &key) { _sslKey = key; } - void setSslKey(const QByteArray &encoded); - inline const QSslCertificate &sslCert() const { return _sslCert; } - inline void setSslCert(const QSslCertificate &cert) { _sslCert = cert; } - void setSslCert(const QByteArray &encoded); + inline const QSslKey& sslKey() const { return _sslKey; } + inline void setSslKey(const QSslKey& key) { _sslKey = key; } + void setSslKey(const QByteArray& encoded); + inline const QSslCertificate& sslCert() const { return _sslCert; } + inline void setSslCert(const QSslCertificate& cert) { _sslCert = cert; } + void setSslCert(const QByteArray& encoded); #endif /* HAVE_SSL */ - CoreIdentity &operator=(const CoreIdentity &identity); + CoreIdentity& operator=(const CoreIdentity& identity); private: #ifdef HAVE_SSL @@ -93,15 +92,13 @@ private: #endif }; - #ifdef HAVE_SSL -inline const QSslKey &CoreCertManager::sslKey() const +inline const QSslKey& CoreCertManager::sslKey() const { return identity.sslKey(); } - -inline const QSslCertificate &CoreCertManager::sslCert() const +inline const QSslCertificate& CoreCertManager::sslCert() const { return identity.sslCert(); } diff --git a/src/core/coreignorelistmanager.cpp b/src/core/coreignorelistmanager.cpp index 1dac9617..30173171 100644 --- a/src/core/coreignorelistmanager.cpp +++ b/src/core/coreignorelistmanager.cpp @@ -23,13 +23,13 @@ #include "core.h" #include "coresession.h" -CoreIgnoreListManager::CoreIgnoreListManager(CoreSession *parent) +CoreIgnoreListManager::CoreIgnoreListManager(CoreSession* parent) : IgnoreListManager(parent) { - auto *session = qobject_cast(parent); + auto* session = qobject_cast(parent); if (!session) { qWarning() << "CoreIgnoreListManager: unable to load IgnoreList. Parent is not a Coresession!"; - //loadDefaults(); + // loadDefaults(); return; } @@ -38,21 +38,19 @@ CoreIgnoreListManager::CoreIgnoreListManager(CoreSession *parent) // we store our settings whenever they change connect(this, &SyncableObject::updatedRemotely, this, &CoreIgnoreListManager::save); - //if(isEmpty()) - //loadDefaults(); + // if(isEmpty()) + // loadDefaults(); } - -IgnoreListManager::StrictnessType CoreIgnoreListManager::match(const RawMessage &rawMsg, const QString &networkName) +IgnoreListManager::StrictnessType CoreIgnoreListManager::match(const RawMessage& rawMsg, const QString& networkName) { - //StrictnessType _match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName); + // StrictnessType _match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName); return _match(rawMsg.text, rawMsg.sender, rawMsg.type, networkName, rawMsg.target); } - void CoreIgnoreListManager::save() const { - auto *session = qobject_cast(parent()); + auto* session = qobject_cast(parent()); if (!session) { qWarning() << "CoreIgnoreListManager: unable to save IgnoreList. Parent is not a Coresession!"; return; @@ -61,8 +59,7 @@ void CoreIgnoreListManager::save() const Core::setUserSetting(session->user(), "IgnoreList", initIgnoreList()); } - -//void CoreIgnoreListManager::loadDefaults() { +// void CoreIgnoreListManager::loadDefaults() { // foreach(IgnoreListItem item, IgnoreListManager::defaults()) { // addIgnoreListItem(item.contents(), item.isRegEx(), item.strictness(), item.scope(), // item.scopeRule()); diff --git a/src/core/coreignorelistmanager.h b/src/core/coreignorelistmanager.h index e7665ca7..204ce1e5 100644 --- a/src/core/coreignorelistmanager.h +++ b/src/core/coreignorelistmanager.h @@ -30,23 +30,22 @@ class CoreIgnoreListManager : public IgnoreListManager Q_OBJECT public: - explicit CoreIgnoreListManager(CoreSession *parent); + explicit CoreIgnoreListManager(CoreSession* parent); - StrictnessType match(const RawMessage &rawMsg, const QString &networkName); + StrictnessType match(const RawMessage& rawMsg, const QString& networkName); public slots: - inline void requestToggleIgnoreRule(const QString &ignoreRule) override { toggleIgnoreRule(ignoreRule); } - inline void requestRemoveIgnoreListItem(const QString &ignoreRule) override { removeIgnoreListItem(ignoreRule); } - inline void requestAddIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness, - int scope, const QString &scopeRule, bool isActive) override + inline void requestToggleIgnoreRule(const QString& ignoreRule) override { toggleIgnoreRule(ignoreRule); } + inline void requestRemoveIgnoreListItem(const QString& ignoreRule) override { removeIgnoreListItem(ignoreRule); } + inline void requestAddIgnoreListItem( + int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive) override { addIgnoreListItem(type, ignoreRule, isRegEx, strictness, scope, scopeRule, isActive); } - private slots: void save() const; -//private: -// void loadDefaults(); + // private: + // void loadDefaults(); }; diff --git a/src/core/coreircchannel.cpp b/src/core/coreircchannel.cpp index faf249de..7d7388a0 100644 --- a/src/core/coreircchannel.cpp +++ b/src/core/coreircchannel.cpp @@ -19,17 +19,18 @@ ***************************************************************************/ #include "coreircchannel.h" + #include "corenetwork.h" -CoreIrcChannel::CoreIrcChannel(const QString &channelname, Network *network) - : IrcChannel(channelname, network), - _receivedWelcomeMsg(false) +CoreIrcChannel::CoreIrcChannel(const QString& channelname, Network* network) + : IrcChannel(channelname, network) + , _receivedWelcomeMsg(false) { #ifdef HAVE_QCA2 _cipher = nullptr; // Get the cipher key from CoreNetwork if present - auto *coreNetwork = qobject_cast(network); + auto* coreNetwork = qobject_cast(network); if (coreNetwork) { QByteArray key = coreNetwork->readChannelCipherKey(channelname); if (!key.isEmpty()) { @@ -39,7 +40,6 @@ CoreIrcChannel::CoreIrcChannel(const QString &channelname, Network *network) #endif } - CoreIrcChannel::~CoreIrcChannel() { #ifdef HAVE_QCA2 @@ -47,7 +47,7 @@ CoreIrcChannel::~CoreIrcChannel() // exists. There is no need to store the empty key if no cipher exists; no // key was present when instantiating and no key was set during the // channel's lifetime. - auto *coreNetwork = qobject_cast(network()); + auto* coreNetwork = qobject_cast(network()); if (coreNetwork && _cipher) { coreNetwork->storeChannelCipherKey(name(), _cipher->key()); } @@ -56,9 +56,8 @@ CoreIrcChannel::~CoreIrcChannel() #endif } - #ifdef HAVE_QCA2 -Cipher *CoreIrcChannel::cipher() const +Cipher* CoreIrcChannel::cipher() const { if (!_cipher) _cipher = new Cipher(); @@ -66,7 +65,6 @@ Cipher *CoreIrcChannel::cipher() const return _cipher; } - void CoreIrcChannel::setEncrypted(bool e) { IrcChannel::setEncrypted(e); @@ -83,5 +81,4 @@ void CoreIrcChannel::setEncrypted(bool e) } } - #endif diff --git a/src/core/coreircchannel.h b/src/core/coreircchannel.h index b1b586b9..7cf2ae3f 100644 --- a/src/core/coreircchannel.h +++ b/src/core/coreircchannel.h @@ -23,7 +23,7 @@ #include "ircchannel.h" #ifdef HAVE_QCA2 -# include "cipher.h" +# include "cipher.h" #endif class CoreIrcChannel : public IrcChannel @@ -31,11 +31,11 @@ class CoreIrcChannel : public IrcChannel Q_OBJECT public: - CoreIrcChannel(const QString &channelname, Network *network); + CoreIrcChannel(const QString& channelname, Network* network); ~CoreIrcChannel() override; #ifdef HAVE_QCA2 - Cipher *cipher() const; + Cipher* cipher() const; void setEncrypted(bool); #endif @@ -46,6 +46,6 @@ private: bool _receivedWelcomeMsg; #ifdef HAVE_QCA2 - mutable Cipher *_cipher; + mutable Cipher* _cipher; #endif }; diff --git a/src/core/coreirclisthelper.cpp b/src/core/coreirclisthelper.cpp index 9ff68fae..1e81d603 100644 --- a/src/core/coreirclisthelper.cpp +++ b/src/core/coreirclisthelper.cpp @@ -25,7 +25,7 @@ constexpr auto kTimeoutMs = 5000; -QVariantList CoreIrcListHelper::requestChannelList(const NetworkId &netId, const QStringList &channelFilters) +QVariantList CoreIrcListHelper::requestChannelList(const NetworkId& netId, const QStringList& channelFilters) { if (_finishedChannelLists.contains(netId)) return _finishedChannelLists.take(netId); @@ -39,8 +39,7 @@ QVariantList CoreIrcListHelper::requestChannelList(const NetworkId &netId, const return QVariantList(); } - -bool CoreIrcListHelper::addChannel(const NetworkId &netId, const QString &channelName, quint32 userCount, const QString &topic) +bool CoreIrcListHelper::addChannel(const NetworkId& netId, const QString& channelName, quint32 userCount, const QString& topic) { if (!_channelLists.contains(netId)) return false; @@ -52,10 +51,9 @@ bool CoreIrcListHelper::addChannel(const NetworkId &netId, const QString &channe return true; } - -bool CoreIrcListHelper::dispatchQuery(const NetworkId &netId, const QString &query) +bool CoreIrcListHelper::dispatchQuery(const NetworkId& netId, const QString& query) { - CoreNetwork *network = coreSession()->network(netId); + CoreNetwork* network = coreSession()->network(netId); if (network) { _channelLists[netId] = QList(); network->userInputHandler()->handleList(BufferInfo(), query); @@ -72,8 +70,7 @@ bool CoreIrcListHelper::dispatchQuery(const NetworkId &netId, const QString &que } } - -bool CoreIrcListHelper::endOfChannelList(const NetworkId &netId) +bool CoreIrcListHelper::endOfChannelList(const NetworkId& netId) { if (_queryTimeoutByNetId.contains(netId)) { // If we recieved an actual RPL_LISTEND, remove the timer @@ -87,11 +84,9 @@ bool CoreIrcListHelper::endOfChannelList(const NetworkId &netId) } else if (_channelLists.contains(netId)) { QVariantList channelList; - foreach(ChannelDescription channel, _channelLists[netId]) { + foreach (ChannelDescription channel, _channelLists[netId]) { QVariantList channelVariant; - channelVariant << channel.channelName - << channel.userCount - << channel.topic; + channelVariant << channel.channelName << channel.userCount << channel.topic; channelList << qVariantFromValue(channelVariant); } _finishedChannelLists[netId] = channelList; @@ -104,8 +99,7 @@ bool CoreIrcListHelper::endOfChannelList(const NetworkId &netId) } } - -void CoreIrcListHelper::timerEvent(QTimerEvent *event) +void CoreIrcListHelper::timerEvent(QTimerEvent* event) { if (!_queryTimeoutByTimerId.contains(event->timerId())) { IrcListHelper::timerEvent(event); diff --git a/src/core/coreirclisthelper.h b/src/core/coreirclisthelper.h index 8cb7c628..e0a0c82b 100644 --- a/src/core/coreirclisthelper.h +++ b/src/core/coreirclisthelper.h @@ -22,9 +22,8 @@ #include -#include "irclisthelper.h" - #include "coresession.h" +#include "irclisthelper.h" class QBasicTimer; class QTimerEvent; @@ -34,28 +33,30 @@ class CoreIrcListHelper : public IrcListHelper Q_OBJECT public: - inline CoreIrcListHelper(CoreSession *coreSession) : IrcListHelper(coreSession), _coreSession(coreSession) {}; + inline CoreIrcListHelper(CoreSession* coreSession) + : IrcListHelper(coreSession) + , _coreSession(coreSession){}; - inline CoreSession *coreSession() const { return _coreSession; } + inline CoreSession* coreSession() const { return _coreSession; } - inline bool requestInProgress(const NetworkId &netId) const { return _channelLists.contains(netId); } + inline bool requestInProgress(const NetworkId& netId) const { return _channelLists.contains(netId); } public slots: - QVariantList requestChannelList(const NetworkId &netId, const QStringList &channelFilters) override; - bool addChannel(const NetworkId &netId, const QString &channelName, quint32 userCount, const QString &topic); - bool endOfChannelList(const NetworkId &netId); + QVariantList requestChannelList(const NetworkId& netId, const QStringList& channelFilters) override; + bool addChannel(const NetworkId& netId, const QString& channelName, quint32 userCount, const QString& topic); + bool endOfChannelList(const NetworkId& netId); protected: - void timerEvent(QTimerEvent *event) override; + void timerEvent(QTimerEvent* event) override; private: - bool dispatchQuery(const NetworkId &netId, const QString &query); + bool dispatchQuery(const NetworkId& netId, const QString& query); private: - CoreSession *_coreSession; + CoreSession* _coreSession; QHash _queuedQuery; - QHash > _channelLists; + QHash> _channelLists; QHash _finishedChannelLists; QHash _queryTimeoutByTimerId; QHash> _queryTimeoutByNetId; diff --git a/src/core/coreircuser.cpp b/src/core/coreircuser.cpp index 12ead6d2..0d598994 100644 --- a/src/core/coreircuser.cpp +++ b/src/core/coreircuser.cpp @@ -19,15 +19,17 @@ ***************************************************************************/ #include "coreircuser.h" + #include "corenetwork.h" -CoreIrcUser::CoreIrcUser(const QString &hostmask, Network *network) : IrcUser(hostmask, network) +CoreIrcUser::CoreIrcUser(const QString& hostmask, Network* network) + : IrcUser(hostmask, network) { #ifdef HAVE_QCA2 _cipher = nullptr; // Get the cipher key from CoreNetwork if present - auto *coreNetwork = qobject_cast(network); + auto* coreNetwork = qobject_cast(network); if (coreNetwork) { QByteArray key = coreNetwork->readChannelCipherKey(nick().toLower()); if (!key.isEmpty()) { @@ -40,7 +42,6 @@ CoreIrcUser::CoreIrcUser(const QString &hostmask, Network *network) : IrcUser(ho #endif } - CoreIrcUser::~CoreIrcUser() { #ifdef HAVE_QCA2 @@ -48,7 +49,7 @@ CoreIrcUser::~CoreIrcUser() // exists. There is no need to store the empty key if no cipher exists; no // key was present when instantiating and no key was set during the // channel's lifetime. - auto *coreNetwork = qobject_cast(network()); + auto* coreNetwork = qobject_cast(network()); if (coreNetwork && _cipher) { coreNetwork->storeChannelCipherKey(nick().toLower(), _cipher->key()); } @@ -57,9 +58,8 @@ CoreIrcUser::~CoreIrcUser() #endif } - #ifdef HAVE_QCA2 -Cipher *CoreIrcUser::cipher() const +Cipher* CoreIrcUser::cipher() const { if (!_cipher) _cipher = new Cipher(); @@ -67,5 +67,4 @@ Cipher *CoreIrcUser::cipher() const return _cipher; } - #endif diff --git a/src/core/coreircuser.h b/src/core/coreircuser.h index 5acb930a..2a422eb2 100644 --- a/src/core/coreircuser.h +++ b/src/core/coreircuser.h @@ -23,7 +23,7 @@ #include "ircuser.h" #ifdef HAVE_QCA2 -# include "cipher.h" +# include "cipher.h" #endif class CoreIrcUser : public IrcUser @@ -31,15 +31,15 @@ class CoreIrcUser : public IrcUser Q_OBJECT public: - CoreIrcUser(const QString &hostmask, Network *network); + CoreIrcUser(const QString& hostmask, Network* network); ~CoreIrcUser() override; #ifdef HAVE_QCA2 - Cipher *cipher() const; + Cipher* cipher() const; #endif #ifdef HAVE_QCA2 private: - mutable Cipher *_cipher; + mutable Cipher* _cipher; #endif }; diff --git a/src/core/corenetwork.cpp b/src/core/corenetwork.cpp index 81e1b5ed..7176389e 100644 --- a/src/core/corenetwork.cpp +++ b/src/core/corenetwork.cpp @@ -33,16 +33,18 @@ // IRCv3 capabilities #include "irccap.h" -CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session) - : Network(networkid, session), - _coreSession(session), - _userInputHandler(new CoreUserInputHandler(this)), - _autoReconnectCount(0), - _quitRequested(false), - _disconnectExpected(false), - - _previousConnectionAttemptFailed(false), - _lastUsedServerIndex(0), +CoreNetwork::CoreNetwork(const NetworkId& networkid, CoreSession* session) + : Network(networkid, session) + , _coreSession(session) + , _userInputHandler(new CoreUserInputHandler(this)) + , _autoReconnectCount(0) + , _quitRequested(false) + , _disconnectExpected(false) + , + + _previousConnectionAttemptFailed(false) + , _lastUsedServerIndex(0) + , _requestedUserModes('-') { @@ -60,12 +62,12 @@ CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session) setAutoWhoInterval(networkConfig()->autoWhoInterval()); QHash channels = coreSession()->persistentChannels(networkId()); - foreach(QString chan, channels.keys()) { + foreach (QString chan, channels.keys()) { _channelKeys[chan.toLower()] = channels[chan]; } QHash bufferCiphers = coreSession()->bufferCiphers(networkId()); - foreach(QString buffer, bufferCiphers.keys()) { + foreach (QString buffer, bufferCiphers.keys()) { storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]); } @@ -114,18 +116,18 @@ CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session) } } - CoreNetwork::~CoreNetwork() { // Ensure we don't get any more signals from the socket while shutting down disconnect(&socket, nullptr, this, nullptr); if (!forceDisconnect()) { qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"} - .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt()); + .arg(networkName()) + .arg(networkId().toInt()) + .arg(userId().toInt()); } } - bool CoreNetwork::forceDisconnect(int msecs) { if (socket.state() == QAbstractSocket::UnconnectedState) { @@ -140,47 +142,42 @@ bool CoreNetwork::forceDisconnect(int msecs) return true; } - -QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const +QString CoreNetwork::channelDecode(const QString& bufferName, const QByteArray& string) const { if (!bufferName.isEmpty()) { - IrcChannel *channel = ircChannel(bufferName); + IrcChannel* channel = ircChannel(bufferName); if (channel) return channel->decodeString(string); } return decodeString(string); } - -QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const +QString CoreNetwork::userDecode(const QString& userNick, const QByteArray& string) const { - IrcUser *user = ircUser(userNick); + IrcUser* user = ircUser(userNick); if (user) return user->decodeString(string); return decodeString(string); } - -QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const +QByteArray CoreNetwork::channelEncode(const QString& bufferName, const QString& string) const { if (!bufferName.isEmpty()) { - IrcChannel *channel = ircChannel(bufferName); + IrcChannel* channel = ircChannel(bufferName); if (channel) return channel->encodeString(string); } return encodeString(string); } - -QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const +QByteArray CoreNetwork::userEncode(const QString& userNick, const QString& string) const { - IrcUser *user = ircUser(userNick); + IrcUser* user = ircUser(userNick); if (user) return user->encodeString(string); return encodeString(string); } - void CoreNetwork::connectToIrc(bool reconnecting) { if (_shuttingDown) { @@ -202,7 +199,7 @@ void CoreNetwork::connectToIrc(bool reconnecting) qWarning() << "Server list empty, ignoring connect request!"; return; } - CoreIdentity *identity = identityPtr(); + CoreIdentity* identity = identityPtr(); if (!identity) { qWarning() << "Invalid identity configures, ignoring connect request!"; return; @@ -254,14 +251,14 @@ void CoreNetwork::connectToIrc(bool reconnecting) // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry. - if (! server.useProxy) { - //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS - //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry. + if (!server.useProxy) { + // Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS + // hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry. QHostInfo::fromName(server.host); } #ifdef HAVE_SSL if (server.useSsl) { - CoreIdentity *identity = identityPtr(); + CoreIdentity* identity = identityPtr(); if (identity) { socket.setLocalCertificate(identity->sslCert()); socket.setPrivateKey(identity->sslKey()); @@ -276,20 +273,19 @@ void CoreNetwork::connectToIrc(bool reconnecting) #endif } - -void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) +void CoreNetwork::disconnectFromIrc(bool requested, const QString& reason, bool withReconnect) { // Disconnecting from the network, should expect a socket close or error _disconnectExpected = true; - _quitRequested = requested; // see socketDisconnected(); + _quitRequested = requested; // see socketDisconnected(); if (!withReconnect) { _autoReconnectTimer.stop(); - _autoReconnectCount = 0; // prohibiting auto reconnect + _autoReconnectCount = 0; // prohibiting auto reconnect } disablePingTimeout(); _msgQueue.clear(); - IrcUser *me_ = me(); + IrcUser* me_ = me(); if (me_) { QString awayMsg; if (me_->isAway()) @@ -302,7 +298,10 @@ void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool else _quitReason = reason; - showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)); + showMessage(Message::Server, + BufferInfo::StatusBuffer, + "", + tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)); if (socket.state() == QAbstractSocket::UnconnectedState) { onSocketDisconnected(); } @@ -321,49 +320,48 @@ void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool } } - void CoreNetwork::onSocketCloseTimeout() { qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"} - .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt()); + .arg(networkName()) + .arg(networkId().toInt()) + .arg(userId().toInt()); socket.abort(); } - void CoreNetwork::shutdown() { _shuttingDown = true; disconnectFromIrc(false, {}, false); } - -void CoreNetwork::userInput(const BufferInfo &buf, QString msg) +void CoreNetwork::userInput(const BufferInfo& buf, QString msg) { userInputHandler()->handleUserInput(buf, msg); } - -void CoreNetwork::putRawLine(const QByteArray &s, bool prepend) +void CoreNetwork::putRawLine(const QByteArray& s, bool prepend) { if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) { // If there's tokens remaining, ... // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ... // Send the message now. writeToSocket(s); - } else { + } + else { // Otherwise, queue the message for later if (prepend) { // Jump to the start, skipping other messages _msgQueue.prepend(s); - } else { + } + else { // Add to back, waiting in order _msgQueue.append(s); } } } - -void CoreNetwork::putCmd(const QString &cmd, const QList ¶ms, const QByteArray &prefix, const bool prepend) +void CoreNetwork::putCmd(const QString& cmd, const QList& params, const QByteArray& prefix, const bool prepend) { QByteArray msg; @@ -383,8 +381,7 @@ void CoreNetwork::putCmd(const QString &cmd, const QList ¶ms, co putRawLine(msg, prepend); } - -void CoreNetwork::putCmd(const QString &cmd, const QList> ¶ms, const QByteArray &prefix, const bool prependAll) +void CoreNetwork::putCmd(const QString& cmd, const QList>& params, const QByteArray& prefix, const bool prependAll) { QListIterator> i(params); while (i.hasNext()) { @@ -393,17 +390,15 @@ void CoreNetwork::putCmd(const QString &cmd, const QList> &par } } - -void CoreNetwork::setChannelJoined(const QString &channel) +void CoreNetwork::setChannelJoined(const QString& channel) { - queueAutoWhoOneshot(channel); // check this new channel first + queueAutoWhoOneshot(channel); // check this new channel first Core::setChannelPersistent(userId(), networkId(), channel, true); Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]); } - -void CoreNetwork::setChannelParted(const QString &channel) +void CoreNetwork::setChannelParted(const QString& channel) { removeChannelKey(channel); _autoWhoQueue.removeAll(channel.toLower()); @@ -412,8 +407,7 @@ void CoreNetwork::setChannelParted(const QString &channel) Core::setChannelPersistent(userId(), networkId(), channel, false); } - -void CoreNetwork::addChannelKey(const QString &channel, const QString &key) +void CoreNetwork::addChannelKey(const QString& channel, const QString& key) { if (key.isEmpty()) { removeChannelKey(channel); @@ -423,15 +417,13 @@ void CoreNetwork::addChannelKey(const QString &channel, const QString &key) } } - -void CoreNetwork::removeChannelKey(const QString &channel) +void CoreNetwork::removeChannelKey(const QString& channel) { _channelKeys.remove(channel.toLower()); } - #ifdef HAVE_QCA2 -Cipher *CoreNetwork::cipher(const QString &target) +Cipher* CoreNetwork::cipher(const QString& target) { if (target.isEmpty()) return nullptr; @@ -439,44 +431,43 @@ Cipher *CoreNetwork::cipher(const QString &target) if (!Cipher::neededFeaturesAvailable()) return nullptr; - auto *channel = qobject_cast(ircChannel(target)); + auto* channel = qobject_cast(ircChannel(target)); if (channel) { return channel->cipher(); } - auto *user = qobject_cast(ircUser(target)); + auto* user = qobject_cast(ircUser(target)); if (user) { return user->cipher(); - } else if (!isChannelName(target)) { + } + else if (!isChannelName(target)) { return qobject_cast(newIrcUser(target))->cipher(); } return nullptr; } - -QByteArray CoreNetwork::cipherKey(const QString &target) const +QByteArray CoreNetwork::cipherKey(const QString& target) const { - auto *c = qobject_cast(ircChannel(target)); + auto* c = qobject_cast(ircChannel(target)); if (c) return c->cipher()->key(); - auto *u = qobject_cast(ircUser(target)); + auto* u = qobject_cast(ircUser(target)); if (u) return u->cipher()->key(); return QByteArray(); } - -void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key) +void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key) { - auto *c = qobject_cast(ircChannel(target)); + auto* c = qobject_cast(ircChannel(target)); if (c) { c->setEncrypted(c->cipher()->setKey(key)); coreSession()->setBufferCipher(networkId(), target, key); return; } - auto *u = qobject_cast(ircUser(target)); + auto* u = qobject_cast(ircUser(target)); if (!u && !isChannelName(target)) u = qobject_cast(newIrcUser(target)); @@ -487,13 +478,12 @@ void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key) } } - -bool CoreNetwork::cipherUsesCBC(const QString &target) +bool CoreNetwork::cipherUsesCBC(const QString& target) { - auto *c = qobject_cast(ircChannel(target)); + auto* c = qobject_cast(ircChannel(target)); if (c) return c->cipher()->usesCBC(); - auto *u = qobject_cast(ircUser(target)); + auto* u = qobject_cast(ircUser(target)); if (u) return u->cipher()->usesCBC(); @@ -501,7 +491,7 @@ bool CoreNetwork::cipherUsesCBC(const QString &target) } #endif /* HAVE_QCA2 */ -bool CoreNetwork::setAutoWhoDone(const QString &name) +bool CoreNetwork::setAutoWhoDone(const QString& name) { QString chanOrNick = name.toLower(); if (_autoWhoPending.value(chanOrNick, 0) <= 0) @@ -511,15 +501,13 @@ bool CoreNetwork::setAutoWhoDone(const QString &name) return true; } - -void CoreNetwork::setMyNick(const QString &mynick) +void CoreNetwork::setMyNick(const QString& mynick) { Network::setMyNick(mynick); if (connectionState() == Network::Initializing) networkInitialized(); } - void CoreNetwork::onSocketHasData() { while (socket.canReadLine()) { @@ -528,13 +516,12 @@ void CoreNetwork::onSocketHasData() s.chop(2); else if (s.endsWith("\n")) s.chop(1); - NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s); + NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s); event->setTimestamp(QDateTime::currentDateTimeUtc()); emit newEvent(event); } } - void CoreNetwork::onSocketError(QAbstractSocket::SocketError error) { // Ignore socket closed errors if expected @@ -552,10 +539,9 @@ void CoreNetwork::onSocketError(QAbstractSocket::SocketError error) } } - void CoreNetwork::onSocketInitialized() { - CoreIdentity *identity = identityPtr(); + CoreIdentity* identity = identityPtr(); if (!identity) { qCritical() << "Identity invalid!"; disconnectFromIrc(); @@ -609,12 +595,9 @@ void CoreNetwork::onSocketInitialized() } putRawLine(serverEncode(QString("NICK %1").arg(nick))); // Only allow strict-compliant idents when strict mode is enabled - putRawLine(serverEncode(QString("USER %1 8 * :%2").arg( - coreSession()->strictCompliantIdent(identity), - identity->realName()))); + putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName()))); } - void CoreNetwork::onSocketDisconnected() { disablePingTimeout(); @@ -629,10 +612,10 @@ void CoreNetwork::onSocketDisconnected() _tokenBucketTimer.stop(); - IrcUser *me_ = me(); + IrcUser* me_ = me(); if (me_) { - foreach(QString channel, me_->channels()) - showMessage(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask()); + foreach (QString channel, me_->channels()) + showMessage(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask()); } setConnected(false); @@ -654,7 +637,6 @@ void CoreNetwork::onSocketDisconnected() } } - void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState) { Network::ConnectionState state; @@ -679,7 +661,6 @@ void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState) setConnectionState(state); } - void CoreNetwork::networkInitialized() { setConnectionState(Network::Initialized); @@ -711,14 +692,13 @@ void CoreNetwork::networkInitialized() if (networkConfig()->autoWhoEnabled()) { _autoWhoCycleTimer.start(); _autoWhoTimer.start(); - startAutoWhoCycle(); // FIXME wait for autojoin to be completed + startAutoWhoCycle(); // FIXME wait for autojoin to be completed } - Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer + Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer Core::setNetworkConnected(userId(), networkId(), true); } - void CoreNetwork::sendPerform() { BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId()); @@ -729,7 +709,7 @@ void CoreNetwork::sendPerform() } // restore old user modes if server default mode is set. - IrcUser *me_ = me(); + IrcUser* me_ = me(); if (me_) { if (!me_->userModes().isEmpty()) { restoreUserModes(); @@ -741,14 +721,15 @@ void CoreNetwork::sendPerform() } // send perform list - foreach(QString line, perform()) { - if (!line.isEmpty()) userInput(statusBuf, line); + foreach (QString line, perform()) { + if (!line.isEmpty()) + userInput(statusBuf, line); } // rejoin channels we've been in if (rejoinChannels()) { QStringList channels, keys; - foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) { + foreach (QString chan, coreSession()->persistentChannels(networkId()).keys()) { QString key = channelKey(chan); if (!key.isEmpty()) { channels.prepend(chan); @@ -764,10 +745,9 @@ void CoreNetwork::sendPerform() } } - void CoreNetwork::restoreUserModes() { - IrcUser *me_ = me(); + IrcUser* me_ = me(); Q_ASSERT(me_); disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes); @@ -803,8 +783,7 @@ void CoreNetwork::restoreUserModes() putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes))); } - -void CoreNetwork::updateIssuedModes(const QString &requestedModes) +void CoreNetwork::updateIssuedModes(const QString& requestedModes) { QString addModes; QString removeModes; @@ -830,18 +809,17 @@ void CoreNetwork::updateIssuedModes(const QString &requestedModes) QString addModesOld = _requestedUserModes.section('-', 0, 0); QString removeModesOld = _requestedUserModes.section('-', 1); - addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate - addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update + addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate + addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update addModes += addModesOld; - removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate - removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update + removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate + removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update removeModes += removeModesOld; _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes); } - void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) { QString persistentUserModes = Core::userModes(userId(), networkId()); @@ -887,14 +865,12 @@ void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove)); } - void CoreNetwork::resetPersistentModes() { _requestedUserModes = QString('-'); Core::setUserModes(userId(), networkId(), QString()); } - void CoreNetwork::setUseAutoReconnect(bool use) { Network::setUseAutoReconnect(use); @@ -902,14 +878,12 @@ void CoreNetwork::setUseAutoReconnect(bool use) _autoReconnectTimer.stop(); } - void CoreNetwork::setAutoReconnectInterval(quint32 interval) { Network::setAutoReconnectInterval(interval); _autoReconnectTimer.setInterval(interval * 1000); } - void CoreNetwork::setAutoReconnectRetries(quint16 retries) { Network::setAutoReconnectRetries(retries); @@ -921,7 +895,6 @@ void CoreNetwork::setAutoReconnectRetries(quint16 retries) } } - void CoreNetwork::doAutoReconnect() { if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) { @@ -933,7 +906,6 @@ void CoreNetwork::doAutoReconnect() connectToIrc(true); } - void CoreNetwork::sendPing() { qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch(); @@ -941,8 +913,7 @@ void CoreNetwork::sendPing() qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings." << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite(); } - if ((int)_pingCount >= networkConfig()->maxPingCount() - && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) { + if ((int)_pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) { // In transitioning to 64-bit time, the interval no longer needs converted down to seconds. // However, to reduce the risk of breaking things by changing past behavior, we still allow // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance. @@ -950,13 +921,15 @@ void CoreNetwork::sendPing() // the second check compares the actual elapsed time since the last ping and the pingTimer interval // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked // and unable to even handle a ping answer. So we ignore those misses. - disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */); + disconnectFromIrc(false, + QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), + true /* withReconnect */); } else { _lastPingTime = now; _pingCount++; // Don't send pings until the network is initialized - if(_sendPings) { + if (_sendPings) { // Mark as waiting for a reply _pongReplyPending = true; // Send default timestamp ping @@ -965,7 +938,6 @@ void CoreNetwork::sendPing() } } - void CoreNetwork::enablePingTimeout(bool enable) { if (!enable) @@ -978,7 +950,6 @@ void CoreNetwork::enablePingTimeout(bool enable) } } - void CoreNetwork::disablePingTimeout() { _pingTimer.stop(); @@ -987,19 +958,16 @@ void CoreNetwork::disablePingTimeout() resetPongReplyPending(); } - void CoreNetwork::setPingInterval(int interval) { _pingTimer.setInterval(interval * 1000); } - void CoreNetwork::setPongTimestampValid(bool validTimestamp) { _pongTimestampValid = validTimestamp; } - /******** Custom Rate Limiting ********/ void CoreNetwork::updateRateLimiting(const bool forceUnlimited) @@ -1015,8 +983,7 @@ void CoreNetwork::updateRateLimiting(const bool forceUnlimited) _burstSize = messageRateBurstSize(); if (_burstSize < 1) { - qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" - << _burstSize; + qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize; // Can't go slower than one message at a time _burstSize = 1; } @@ -1047,15 +1014,18 @@ void CoreNetwork::updateRateLimiting(const bool forceUnlimited) // TODO If testing shows this isn't needed, it can be simplified to a direct call. // Hesitant to change it without a wide variety of situations to verify behavior. _tokenBucketTimer.start(100); - } else { + } + else { // No rate limiting, disable the timer _tokenBucketTimer.stop(); } - } else { + } + else { // Rate limiting enabled, enable the timer _tokenBucketTimer.start(_messageDelay); } - } else { + } + else { // Custom message rates disabled. Go for the default. _skipMessageRates = false; // Enable rate-limiting by default @@ -1080,10 +1050,9 @@ void CoreNetwork::resetTokenBucket() _tokenBucket = _burstSize; } - /******** IRCv3 Capability Negotiation ********/ -void CoreNetwork::serverCapAdded(const QString &capability) +void CoreNetwork::serverCapAdded(const QString& capability) { // Check if it's a known capability; if so, add it to the list // Handle special cases first @@ -1091,13 +1060,14 @@ void CoreNetwork::serverCapAdded(const QString &capability) // Only request SASL if it's enabled if (networkInfo().useSasl) queueCap(capability); - } else if (IrcCap::knownCaps.contains(capability)) { + } + else if (IrcCap::knownCaps.contains(capability)) { // Handling for general known capabilities queueCap(capability); } } -void CoreNetwork::serverCapAcknowledged(const QString &capability) +void CoreNetwork::serverCapAcknowledged(const QString& capability) { // This may be called multiple times in certain situations. @@ -1118,17 +1088,20 @@ void CoreNetwork::serverCapAcknowledged(const QString &capability) if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) { // EXTERNAL authentication supported, send request putRawLine(serverEncode("AUTHENTICATE EXTERNAL")); - } else { + } + else { showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL EXTERNAL authentication not supported")); sendNextCap(); } - } else { + } + else { #endif if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) { // PLAIN authentication supported, send request // Only working with PLAIN atm, blowfish later putRawLine(serverEncode("AUTHENTICATE PLAIN")); - } else { + } + else { showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL PLAIN authentication not supported")); sendNextCap(); } @@ -1138,7 +1111,7 @@ void CoreNetwork::serverCapAcknowledged(const QString &capability) } } -void CoreNetwork::serverCapRemoved(const QString &capability) +void CoreNetwork::serverCapRemoved(const QString& capability) { // This may be called multiple times in certain situations. @@ -1149,19 +1122,20 @@ void CoreNetwork::serverCapRemoved(const QString &capability) } } -void CoreNetwork::queueCap(const QString &capability) +void CoreNetwork::queueCap(const QString& capability) { // IRCv3 specs all use lowercase capability names QString _capLowercase = capability.toLower(); - if(capsRequiringConfiguration.contains(_capLowercase)) { + if (capsRequiringConfiguration.contains(_capLowercase)) { // The capability requires additional configuration before being acknowledged (e.g. SASL), // so we should negotiate it separately from all other capabilities. Otherwise new // capabilities will be requested while still configuring the previous one. if (!_capsQueuedIndividual.contains(_capLowercase)) { _capsQueuedIndividual.append(_capLowercase); } - } else { + } + else { // The capability doesn't need any special configuration, so it should be safe to try // bundling together with others. "Should" being the imperative word, as IRC servers can do // anything. @@ -1181,7 +1155,8 @@ QString CoreNetwork::takeQueuedCaps() if (!_capsQueuedIndividual.empty()) { // We have an individual capability available. Take the first and pass it back. return _capsQueuedIndividual.takeFirst(); - } else if (!_capsQueuedBundled.empty()) { + } + else if (!_capsQueuedBundled.empty()) { // We have capabilities available that can be grouped. Try to fit in as many as within the // maximum length. // See CoreNetwork::maxCapRequestLength @@ -1201,14 +1176,16 @@ QString CoreNetwork::takeQueuedCaps() _capsQueuedLastBundle.append(nextCap); // Then remove it from the queue _capsQueuedBundled.removeFirst(); - } else { + } + else { // We've reached the length limit for a single capability request, stop adding more break; } } // Return this space-separated set of capabilities, removing any extra spaces return capBundle.trimmed(); - } else { + } + else { // No capabilities left to negotiate, return an empty string. return QString(); } @@ -1234,9 +1211,10 @@ void CoreNetwork::retryCapsIndividually() // Add most recently tried capability set to individual list, re-requesting them one at a time _capsQueuedIndividual.append(_capsQueuedLastBundle); // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this. - showMessage(Message::Server, BufferInfo::StatusBuffer, "", - tr("Could not negotiate some capabilities, retrying individually (%1)...") - .arg(_capsQueuedLastBundle.join(", "))); + showMessage(Message::Server, + BufferInfo::StatusBuffer, + "", + tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", "))); // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no // need to remove them here. // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying @@ -1260,10 +1238,9 @@ void CoreNetwork::beginCapNegotiation() // Build a list of queued capabilities, starting with individual, then bundled, only adding the // comma separator between the two if needed (both individual and bundled caps exist). - QString queuedCapsDisplay = - _capsQueuedIndividual.join(", ") - + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "") - + _capsQueuedBundled.join(", "); + QString queuedCapsDisplay = _capsQueuedIndividual.join(", ") + + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "") + + _capsQueuedBundled.join(", "); showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay)); sendNextCap(); @@ -1274,14 +1251,18 @@ void CoreNetwork::sendNextCap() if (capNegotiationInProgress()) { // Request the next set of capabilities and remove them from the list putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps()))); - } else { + } + else { // No pending desired capabilities, capability negotiation finished // If SASL requested but not available, print a warning if (networkInfo().useSasl && !capEnabled(IrcCap::SASL)) showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL authentication currently not supported by server")); if (_capNegotiationActive) { - showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", "))); + showMessage(Message::Server, + BufferInfo::StatusBuffer, + "", + tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", "))); _capNegotiationActive = false; } @@ -1309,7 +1290,7 @@ void CoreNetwork::startAutoWhoCycle() _autoWhoQueue = channels(); } -void CoreNetwork::queueAutoWhoOneshot(const QString &name) +void CoreNetwork::queueAutoWhoOneshot(const QString& name) { // Prepend so these new channels/nicks are the first to be checked // Don't allow duplicates @@ -1322,19 +1303,16 @@ void CoreNetwork::queueAutoWhoOneshot(const QString &name) } } - void CoreNetwork::setAutoWhoDelay(int delay) { _autoWhoTimer.setInterval(delay * 1000); } - void CoreNetwork::setAutoWhoInterval(int interval) { _autoWhoCycleTimer.setInterval(interval * 1000); } - void CoreNetwork::setAutoWhoEnabled(bool enabled) { if (enabled && isConnected() && !_autoWhoTimer.isActive()) @@ -1345,7 +1323,6 @@ void CoreNetwork::setAutoWhoEnabled(bool enabled) } } - void CoreNetwork::sendAutoWho() { // Don't send autowho if there are still some pending @@ -1355,21 +1332,22 @@ void CoreNetwork::sendAutoWho() while (!_autoWhoQueue.isEmpty()) { QString chanOrNick = _autoWhoQueue.takeFirst(); // Check if it's a known channel or nick - IrcChannel *ircchan = ircChannel(chanOrNick); - IrcUser *ircuser = ircUser(chanOrNick); + IrcChannel* ircchan = ircChannel(chanOrNick); + IrcUser* ircuser = ircUser(chanOrNick); if (ircchan) { // Apply channel limiting rules // If using away-notify, don't impose channel size limits in order to capture away // state of everyone. Auto-who won't run on a timer so network impact is minimal. - if (networkConfig()->autoWhoNickLimit() > 0 - && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit() + if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit() && !capEnabled(IrcCap::AWAY_NOTIFY)) continue; _autoWhoPending[chanOrNick.toLower()]++; - } else if (ircuser) { + } + else if (ircuser) { // Checking a nick, add it to the pending list _autoWhoPending[ircuser->nick().toLower()]++; - } else { + } + else { // Not a channel or a nick, skip it qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick; continue; @@ -1383,10 +1361,10 @@ void CoreNetwork::sendAutoWho() // See http://faerion.sourceforge.net/doc/irc/whox.var // And https://github.com/quakenet/snircd/blob/master/doc/readme.who // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752 - putRawLine(serverEncode(QString("WHO %1 n%chtsunfra,%2") - .arg(serverEncode(chanOrNick), - QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM)))); - } else { + putRawLine(serverEncode( + QString("WHO %1 n%chtsunfra,%2").arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM)))); + } + else { // Fall back to normal WHO // // Note: According to RFC 1459, "WHO " can fall back to searching realname, @@ -1398,21 +1376,20 @@ void CoreNetwork::sendAutoWho() break; } - if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() - && !capEnabled(IrcCap::AWAY_NOTIFY)) { + if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) { // Timer was stopped, means a new cycle is due immediately // Don't run a new cycle if using away-notify; server will notify as appropriate _autoWhoCycleTimer.start(); startAutoWhoCycle(); - } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) { + } + else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) { // Don't run another who cycle if away-notify is enabled _autoWhoCycleTimer.stop(); } } - #ifdef HAVE_SSL -void CoreNetwork::onSslErrors(const QList &sslErrors) +void CoreNetwork::onSslErrors(const QList& sslErrors) { Server server = usedServer(); if (server.sslVerify) { @@ -1428,7 +1405,8 @@ void CoreNetwork::onSslErrors(const QList &sslErrors) // Disconnect, triggering a reconnect in case it's a temporary issue with certificate // validity, network trouble, etc. disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */); - } else { + } + else { // Treat the SSL error as a warning, continue to connect anyways QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing " "since verification is not required"); @@ -1443,7 +1421,6 @@ void CoreNetwork::onSslErrors(const QList &sslErrors) } } - #endif // HAVE_SSL void CoreNetwork::checkTokenBucket() @@ -1461,7 +1438,6 @@ void CoreNetwork::checkTokenBucket() fillBucketAndProcessQueue(); } - void CoreNetwork::fillBucketAndProcessQueue() { // If there's less tokens than burst size, refill the token bucket by 1 @@ -1475,12 +1451,10 @@ void CoreNetwork::fillBucketAndProcessQueue() } } - -void CoreNetwork::writeToSocket(const QByteArray &data) +void CoreNetwork::writeToSocket(const QByteArray& data) { // Log the message if enabled and network ID matches or allows all - if (_debugLogRawIrc - && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) { + if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) { // Include network ID qDebug() << "IRC net" << networkId() << ">>" << data; } @@ -1492,7 +1466,6 @@ void CoreNetwork::writeToSocket(const QByteArray &data) } } - Network::Server CoreNetwork::usedServer() const { if (_lastUsedServerIndex < serverList().count()) @@ -1504,7 +1477,6 @@ Network::Server CoreNetwork::usedServer() const return Network::Server(); } - void CoreNetwork::requestConnect() const { if (_shuttingDown) { @@ -1514,10 +1486,9 @@ void CoreNetwork::requestConnect() const qWarning() << "Requesting connect while already being connected!"; return; } - QMetaObject::invokeMethod(const_cast(this), "connectToIrc", Qt::QueuedConnection); + QMetaObject::invokeMethod(const_cast(this), "connectToIrc", Qt::QueuedConnection); } - void CoreNetwork::requestDisconnect() const { if (_shuttingDown) { @@ -1530,8 +1501,7 @@ void CoreNetwork::requestDisconnect() const userInputHandler()->handleQuit(BufferInfo(), QString()); } - -void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) +void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info) { Network::Server currentServer = usedServer(); setNetworkInfo(info); @@ -1549,8 +1519,9 @@ void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) } } - -QList> CoreNetwork::splitMessage(const QString &cmd, const QString &message, const std::function(QString &)> &cmdGenerator) +QList> CoreNetwork::splitMessage(const QString& cmd, + const QString& message, + const std::function(QString&)>& cmdGenerator) { QString wrkMsg(message); QList> msgsToSend; @@ -1614,7 +1585,7 @@ QList> CoreNetwork::splitMessage(const QString &cmd, const QSt wrkMsg.remove(0, splitPos); msgsToSend.append(splitMsgEnc); } - else{ + else { // If the entire remaining message is short enough to be sent all at once, remove // it from the wrkMsg and add it to the list of messages to be sent. wrkMsg.remove(0, splitPos); diff --git a/src/core/corenetwork.h b/src/core/corenetwork.h index c67d4792..b185264b 100644 --- a/src/core/corenetwork.h +++ b/src/core/corenetwork.h @@ -20,30 +20,30 @@ #pragma once -#include "network.h" #include "coreircchannel.h" #include "coreircuser.h" +#include "network.h" // IRCv3 capabilities -#include "irccap.h" - #include +#include "irccap.h" + #ifdef HAVE_SSL -# include -# include +# include +# include #else -# include +# include #endif #ifdef HAVE_QCA2 -# include "cipher.h" +# include "cipher.h" #endif -#include "coresession.h" - #include +#include "coresession.h" + class CoreIdentity; class CoreUserInputHandler; class CoreIgnoreListManager; @@ -54,38 +54,38 @@ class CoreNetwork : public Network Q_OBJECT public: - CoreNetwork(const NetworkId &networkid, CoreSession *session); + CoreNetwork(const NetworkId& networkid, CoreSession* session); ~CoreNetwork() override; - inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); } - inline CoreSession *coreSession() const { return _coreSession; } - inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); } + inline CoreIdentity* identityPtr() const { return coreSession()->identity(identity()); } + inline CoreSession* coreSession() const { return _coreSession; } + inline CoreNetworkConfig* networkConfig() const { return coreSession()->networkConfig(); } - inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; } - inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); } + inline CoreUserInputHandler* userInputHandler() const { return _userInputHandler; } + inline CoreIgnoreListManager* ignoreListManager() { return coreSession()->ignoreListManager(); } //! Decode a string using the server (network) decoding. - inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); } + inline QString serverDecode(const QByteArray& string) const { return decodeServerString(string); } //! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else). - QString channelDecode(const QString &channelName, const QByteArray &string) const; + QString channelDecode(const QString& channelName, const QByteArray& string) const; //! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else). - QString userDecode(const QString &userNick, const QByteArray &string) const; + QString userDecode(const QString& userNick, const QByteArray& string) const; //! Encode a string using the server (network) encoding. - inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); } + inline QByteArray serverEncode(const QString& string) const { return encodeServerString(string); } //! Encode a string using the channel-specific encoding, if set, and use the standard encoding else. - QByteArray channelEncode(const QString &channelName, const QString &string) const; + QByteArray channelEncode(const QString& channelName, const QString& string) const; //! Encode a string using the user-specific encoding, if set, and use the standard encoding else. - QByteArray userEncode(const QString &userNick, const QString &string) const; + QByteArray userEncode(const QString& userNick, const QString& string) const; - inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); } + inline QString channelKey(const QString& channel) const { return _channelKeys.value(channel.toLower(), QString()); } - inline QByteArray readChannelCipherKey(const QString &channel) const { return _cipherKeys.value(channel.toLower()); } - inline void storeChannelCipherKey(const QString &channel, const QByteArray &key) { _cipherKeys[channel.toLower()] = key; } + inline QByteArray readChannelCipherKey(const QString& channel) const { return _cipherKeys.value(channel.toLower()); } + inline void storeChannelCipherKey(const QString& channel, const QByteArray& key) { _cipherKeys[channel.toLower()] = key; } /** * Checks if the given target has an automatic WHO in progress @@ -93,10 +93,7 @@ public: * @param name Channel or nickname * @return True if an automatic WHO is in progress, otherwise false */ - inline bool isAutoWhoInProgress(const QString &name) const - { - return _autoWhoPending.value(name.toLower(), 0); - } + inline bool isAutoWhoInProgress(const QString& name) const { return _autoWhoPending.value(name.toLower(), 0); } inline UserId userId() const { return _coreSession->user(); } @@ -135,7 +132,9 @@ public: */ inline bool isPongReplyPending() const { return _pongReplyPending; } - QList> splitMessage(const QString &cmd, const QString &message, const std::function(QString &)> &cmdGenerator); + QList> splitMessage(const QString& cmd, + const QString& message, + const std::function(QString&)>& cmdGenerator); // IRCv3 capability negotiation @@ -154,7 +153,7 @@ public: * * @param[in] capability Name of the capability */ - void queueCap(const QString &capability); + void queueCap(const QString& capability); /** * Begins capability negotiation if capabilities are queued, otherwise returns. @@ -197,16 +196,14 @@ public: * * See: http://ircv3.net/specs/extensions/sasl-3.2.html */ - const QStringList capsRequiringConfiguration = QStringList { - IrcCap::SASL - }; + const QStringList capsRequiringConfiguration = QStringList{IrcCap::SASL}; public slots: - void setMyNick(const QString &mynick) override; + void setMyNick(const QString& mynick) override; void requestConnect() const override; void requestDisconnect() const override; - void requestSetNetworkInfo(const NetworkInfo &info) override; + void requestSetNetworkInfo(const NetworkInfo& info) override; void setUseAutoReconnect(bool) override; void setAutoReconnectInterval(quint32) override; @@ -242,7 +239,7 @@ public slots: * @param reason Reason for quitting, defaulting to the user-configured quit reason * @param withReconnect Reconnect to the network after disconnecting (e.g. ping timeout) */ - void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false); + void disconnectFromIrc(bool requested = true, const QString& reason = QString(), bool withReconnect = false); /** * Forcibly close the IRC server socket, waiting for it to close. @@ -255,7 +252,7 @@ public slots: */ bool forceDisconnect(int msecs = 1000); - void userInput(const BufferInfo &bufferInfo, QString msg); + void userInput(const BufferInfo& bufferInfo, QString msg); /** * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority. @@ -268,7 +265,7 @@ public slots: * PING/PONG replies, the other side will close the connection. * @endparmblock */ - void putRawLine(const QByteArray &input, bool prepend = false); + void putRawLine(const QByteArray& input, bool prepend = false); /** * Sends the command with encoded parameters, with optional prefix or high priority. @@ -283,7 +280,7 @@ public slots: * maintain PING/PONG replies, the other side will close the connection. * @endparmblock */ - void putCmd(const QString &cmd, const QList ¶ms, const QByteArray &prefix = {}, bool prepend = false); + void putCmd(const QString& cmd, const QList& params, const QByteArray& prefix = {}, bool prepend = false); /** * Sends the command for each set of encoded parameters, with optional prefix or high priority. @@ -302,19 +299,19 @@ public slots: * cannot maintain PING/PONG replies, the other side will close the connection. * @endparmblock */ - void putCmd(const QString &cmd, const QList> ¶ms, const QByteArray &prefix = {}, bool prependAll = false); + void putCmd(const QString& cmd, const QList>& params, const QByteArray& prefix = {}, bool prependAll = false); - void setChannelJoined(const QString &channel); - void setChannelParted(const QString &channel); - void addChannelKey(const QString &channel, const QString &key); - void removeChannelKey(const QString &channel); + void setChannelJoined(const QString& channel); + void setChannelParted(const QString& channel); + void addChannelKey(const QString& channel, const QString& key); + void removeChannelKey(const QString& channel); // Blowfish stuff #ifdef HAVE_QCA2 - Cipher *cipher(const QString &recipient); - QByteArray cipherKey(const QString &recipient) const; - void setCipherKey(const QString &recipient, const QByteArray &key); - bool cipherUsesCBC(const QString &target); + Cipher* cipher(const QString& recipient); + QByteArray cipherKey(const QString& recipient) const; + void setCipherKey(const QString& recipient, const QByteArray& key); + bool cipherUsesCBC(const QString& target); #endif // Custom rate limiting (can be connected to signals) @@ -360,7 +357,7 @@ public slots: * * @param[in] capability Name of the capability */ - void serverCapAdded(const QString &capability); + void serverCapAdded(const QString& capability); /** * Indicates a capability was acknowledged (enabled by the IRC server). @@ -369,7 +366,7 @@ public slots: * * @param[in] capability Name of the capability */ - void serverCapAcknowledged(const QString &capability); + void serverCapAcknowledged(const QString& capability); /** * Indicates a capability was removed from the list of available capabilities. @@ -378,7 +375,7 @@ public slots: * * @param[in] capability Name of the capability */ - void serverCapRemoved(const QString &capability); + void serverCapRemoved(const QString& capability); /** * Sends the next capability from the queue. @@ -400,7 +397,7 @@ public slots: * * @param[in] name Channel or nickname */ - void queueAutoWhoOneshot(const QString &name); + void queueAutoWhoOneshot(const QString& name); /** * Checks if the given target has an automatic WHO in progress, and sets it as done if so @@ -408,9 +405,9 @@ public slots: * @param name Channel or nickname * @return True if an automatic WHO is in progress (and should be silenced), otherwise false */ - bool setAutoWhoDone(const QString &name); + bool setAutoWhoDone(const QString& name); - void updateIssuedModes(const QString &requestedModes); + void updateIssuedModes(const QString& requestedModes); void updatePersistentModes(QString addModes, QString removeModes); void resetPersistentModes(); @@ -423,35 +420,50 @@ public slots: */ inline void resetPongReplyPending() { _pongReplyPending = false; } - void onDisplayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender, Message::Flags flags) + void onDisplayMsg(Message::Type msgType, + BufferInfo::Type bufferType, + const QString& target, + const QString& text, + const QString& sender, + Message::Flags flags) { emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags); } - signals: void recvRawServerMsg(QString); void displayStatusMsg(QString); - void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender, Message::Flags flags); + void displayMsg( + NetworkId, Message::Type, BufferInfo::Type, const QString& target, const QString& text, const QString& sender, Message::Flags flags); void disconnected(NetworkId networkId); - void connectionError(const QString &errorMsg); + void connectionError(const QString& errorMsg); void quitRequested(NetworkId networkId); - void sslErrors(const QVariant &errorData); - - void newEvent(Event *event); - void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId); - void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId); + void sslErrors(const QVariant& errorData); + + void newEvent(Event* event); + void socketInitialized(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, + qint64 socketId); + void socketDisconnected(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, + qint64 socketId); protected: - inline IrcChannel *ircChannelFactory(const QString &channelname) override { return new CoreIrcChannel(channelname, this); } - inline IrcUser *ircUserFactory(const QString &hostmask) override { return new CoreIrcUser(hostmask, this); } + inline IrcChannel* ircChannelFactory(const QString& channelname) override { return new CoreIrcChannel(channelname, this); } + inline IrcUser* ircUserFactory(const QString& hostmask) override { return new CoreIrcUser(hostmask, this); } protected slots: // TODO: remove cached cipher keys, when appropriate - //virtual void removeIrcUser(IrcUser *ircuser); - //virtual void removeIrcChannel(IrcChannel *ircChannel); - //virtual void removeChansAndUsers(); + // virtual void removeIrcUser(IrcUser *ircuser); + // virtual void removeIrcChannel(IrcChannel *ircChannel); + // virtual void removeChansAndUsers(); private slots: void onSocketHasData(); @@ -473,7 +485,7 @@ private slots: void startAutoWhoCycle(); #ifdef HAVE_SSL - void onSslErrors(const QList &errors); + void onSslErrors(const QList& errors); #endif /** @@ -495,24 +507,24 @@ private slots: */ void fillBucketAndProcessQueue(); - void writeToSocket(const QByteArray &data); + void writeToSocket(const QByteArray& data); private: void showMessage(Message::Type msgType, BufferInfo::Type bufferType, - const QString &target, - const QString &text, - const QString &sender = "", + const QString& target, + const QString& text, + const QString& sender = "", Message::Flags flags = Message::None) { emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags); } private: - CoreSession *_coreSession; + CoreSession* _coreSession; - bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log - qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all + bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log + qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all #ifdef HAVE_SSL QSslSocket socket; @@ -521,9 +533,9 @@ private: #endif qint64 _socketId{0}; - CoreUserInputHandler *_userInputHandler; + CoreUserInputHandler* _userInputHandler; - QHash _channelKeys; // stores persistent channels and their passwords, if any + QHash _channelKeys; // stores persistent channels and their passwords, if any QTimer _autoReconnectTimer; int _autoReconnectCount; @@ -552,7 +564,7 @@ private: bool _pongTimestampValid = false; ///< If true, IRC server responds to PING by quoting in PONG // This tracks whether or not a server responds to PING with a PONG of what was sent, or if it // does something else. If false, PING reply hiding should be more aggressive. - bool _pongReplyPending = false; ///< If true, at least one PING sent without a PONG reply + bool _pongReplyPending = false; ///< If true, at least one PING sent without a PONG reply QStringList _autoWhoQueue; QHash _autoWhoPending; @@ -570,9 +582,9 @@ private: // If this happens, we need a way to retry each capability individually in order to avoid having // one failing capability (e.g. SASL) block all other capabilities. - bool _capNegotiationActive; /// Whether or not full capability negotiation was started + bool _capNegotiationActive; /// Whether or not full capability negotiation was started // Avoid displaying repeat "negotiation finished" messages - bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished + bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished // Avoid sending repeat "CAP END" replies when registration is already ended /** @@ -597,13 +609,13 @@ private: QTimer _tokenBucketTimer; // No need for int type as one cannot travel into the past (at least not yet, Doc) - quint32 _messageDelay; /// Token refill speed in ms - quint32 _burstSize; /// Size of the token bucket - quint32 _tokenBucket; /// The virtual bucket that holds the tokens - QList _msgQueue; /// Queue of messages waiting to be sent - bool _skipMessageRates; /// If true, skip all message rate limits + quint32 _messageDelay; /// Token refill speed in ms + quint32 _burstSize; /// Size of the token bucket + quint32 _tokenBucket; /// The virtual bucket that holds the tokens + QList _msgQueue; /// Queue of messages waiting to be sent + bool _skipMessageRates; /// If true, skip all message rate limits - QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove + QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove // List of blowfish keys for channels QHash _cipherKeys; diff --git a/src/core/corenetworkconfig.cpp b/src/core/corenetworkconfig.cpp index faab93ed..e1c141f7 100644 --- a/src/core/corenetworkconfig.cpp +++ b/src/core/corenetworkconfig.cpp @@ -18,11 +18,12 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "corenetworkconfig.h" + #include "core.h" #include "coresession.h" -#include "corenetworkconfig.h" -CoreNetworkConfig::CoreNetworkConfig(const QString &objectName, CoreSession *session) +CoreNetworkConfig::CoreNetworkConfig(const QString& objectName, CoreSession* session) : NetworkConfig(objectName, session) { setAllowClientUpdates(true); @@ -35,10 +36,9 @@ CoreNetworkConfig::CoreNetworkConfig(const QString &objectName, CoreSession *ses fromVariantMap(Core::getUserSetting(session->user(), objectName).toMap()); } - void CoreNetworkConfig::save() { - auto *session = qobject_cast(parent()); + auto* session = qobject_cast(parent()); if (!session) { qWarning() << Q_FUNC_INFO << "No CoreSession set, cannot save network configuration!"; return; diff --git a/src/core/corenetworkconfig.h b/src/core/corenetworkconfig.h index bed9e1ee..4ae63007 100644 --- a/src/core/corenetworkconfig.h +++ b/src/core/corenetworkconfig.h @@ -29,7 +29,7 @@ class CoreNetworkConfig : public NetworkConfig Q_OBJECT public: - CoreNetworkConfig(const QString &objectName, CoreSession *parent); + CoreNetworkConfig(const QString& objectName, CoreSession* parent); void save(); diff --git a/src/core/coresession.cpp b/src/core/coresession.cpp index d258df7f..b5de50ed 100644 --- a/src/core/coresession.cpp +++ b/src/core/coresession.cpp @@ -23,9 +23,8 @@ #include #include "core.h" -#include "coreuserinputhandler.h" -#include "corebuffersyncer.h" #include "corebacklogmanager.h" +#include "corebuffersyncer.h" #include "corebufferviewmanager.h" #include "coredccconfig.h" #include "coreeventmanager.h" @@ -37,6 +36,7 @@ #include "corenetworkconfig.h" #include "coresessioneventprocessor.h" #include "coretransfermanager.h" +#include "coreuserinputhandler.h" #include "coreusersettings.h" #include "ctcpparser.h" #include "eventstringifier.h" @@ -50,41 +50,41 @@ #include "storage.h" #include "util.h" - class ProcessMessagesEvent : public QEvent { public: - ProcessMessagesEvent() : QEvent(QEvent::User) {} + ProcessMessagesEvent() + : QEvent(QEvent::User) + {} }; - -CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, QObject *parent) - : QObject(parent), - _user(uid), - _strictIdentEnabled(strictIdentEnabled), - _signalProxy(new SignalProxy(SignalProxy::Server, this)), - _aliasManager(this), - _bufferSyncer(new CoreBufferSyncer(this)), - _backlogManager(new CoreBacklogManager(this)), - _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)), - _dccConfig(new CoreDccConfig(this)), - _ircListHelper(new CoreIrcListHelper(this)), - _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)), - _coreInfo(new CoreInfo(this)), - _transferManager(new CoreTransferManager(this)), - _eventManager(new CoreEventManager(this)), - _eventStringifier(new EventStringifier(this)), - _sessionEventProcessor(new CoreSessionEventProcessor(this)), - _ctcpParser(new CtcpParser(this)), - _ircParser(new IrcParser(this)), - scriptEngine(new QScriptEngine(this)), - _processMessages(false), - _ignoreListManager(this), - _highlightRuleManager(this) -{ - SignalProxy *p = signalProxy(); +CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, QObject* parent) + : QObject(parent) + , _user(uid) + , _strictIdentEnabled(strictIdentEnabled) + , _signalProxy(new SignalProxy(SignalProxy::Server, this)) + , _aliasManager(this) + , _bufferSyncer(new CoreBufferSyncer(this)) + , _backlogManager(new CoreBacklogManager(this)) + , _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)) + , _dccConfig(new CoreDccConfig(this)) + , _ircListHelper(new CoreIrcListHelper(this)) + , _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)) + , _coreInfo(new CoreInfo(this)) + , _transferManager(new CoreTransferManager(this)) + , _eventManager(new CoreEventManager(this)) + , _eventStringifier(new EventStringifier(this)) + , _sessionEventProcessor(new CoreSessionEventProcessor(this)) + , _ctcpParser(new CtcpParser(this)) + , _ircParser(new IrcParser(this)) + , scriptEngine(new QScriptEngine(this)) + , _processMessages(false) + , _ignoreListManager(this) + , _highlightRuleManager(this) +{ + SignalProxy* p = signalProxy(); p->setHeartBeatInterval(30); - p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out + p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out connect(p, &SignalProxy::peerRemoved, this, &CoreSession::removeClient); @@ -95,25 +95,29 @@ CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, p->attachSignal(this, SIGNAL(displayMsg(Message))); p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString))); - p->attachSignal(this, SIGNAL(identityCreated(const Identity &))); + p->attachSignal(this, SIGNAL(identityCreated(const Identity&))); p->attachSignal(this, SIGNAL(identityRemoved(IdentityId))); - p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &))); + p->attachSlot(SIGNAL(createIdentity(const Identity&, const QVariantMap&)), + this, + SLOT(createIdentity(const Identity&, const QVariantMap&))); p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId))); p->attachSignal(this, SIGNAL(networkCreated(NetworkId))); p->attachSignal(this, SIGNAL(networkRemoved(NetworkId))); - p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &))); + p->attachSlot(SIGNAL(createNetwork(const NetworkInfo&, const QStringList&)), + this, + SLOT(createNetwork(const NetworkInfo&, const QStringList&))); p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId))); - p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString))); - p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool))); + p->attachSlot(SIGNAL(changePassword(PeerPtr, QString, QString, QString)), this, SLOT(changePassword(PeerPtr, QString, QString, QString))); + p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr, bool))); p->attachSlot(SIGNAL(kickClient(int)), this, SLOT(kickClient(int))); p->attachSignal(this, SIGNAL(disconnectFromCore())); QVariantMap data; data["quasselVersion"] = Quassel::buildInfo().fancyVersionString; - data["quasselBuildDate"] = Quassel::buildInfo().commitDate; // "BuildDate" for compatibility + data["quasselBuildDate"] = Quassel::buildInfo().commitDate; // "BuildDate" for compatibility data["startTime"] = Core::instance()->startTime(); data["sessionConnectedClients"] = 0; _coreInfo->setCoreData(data); @@ -122,10 +126,10 @@ CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, initScriptEngine(); eventManager()->registerObject(ircParser(), EventManager::NormalPriority); - eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier! + eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier! eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority); eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority); - eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client + eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client // some events need to be handled after msg generation eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess"); eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send"); @@ -143,8 +147,7 @@ CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, p->synchronize(&_ignoreListManager); p->synchronize(&_highlightRuleManager); // Listen to network removed events - connect(this, &CoreSession::networkRemoved, - &_highlightRuleManager, &HighlightRuleManager::networkRemoved); + connect(this, &CoreSession::networkRemoved, &_highlightRuleManager, &HighlightRuleManager::networkRemoved); p->synchronize(transferManager()); // Restore session state if (restoreState) @@ -153,14 +156,13 @@ CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, emit initialized(); } - void CoreSession::shutdown() { saveSessionState(); // Request disconnect from all connected networks in parallel, and wait until every network // has emitted the disconnected() signal before deleting the session itself - for (CoreNetwork *net : _networks.values()) { + for (CoreNetwork* net : _networks.values()) { if (net->socketState() != QAbstractSocket::UnconnectedState) { _networksPendingDisconnect.insert(net->networkId()); connect(net, &CoreNetwork::disconnected, this, &CoreSession::onNetworkDisconnected); @@ -174,7 +176,6 @@ void CoreSession::shutdown() } } - void CoreSession::onNetworkDisconnected(NetworkId networkId) { _networksPendingDisconnect.remove(networkId); @@ -184,21 +185,20 @@ void CoreSession::onNetworkDisconnected(NetworkId networkId) } } - -CoreNetwork *CoreSession::network(NetworkId id) const +CoreNetwork* CoreSession::network(NetworkId id) const { - if (_networks.contains(id)) return _networks[id]; + if (_networks.contains(id)) + return _networks[id]; return nullptr; } - -CoreIdentity *CoreSession::identity(IdentityId id) const +CoreIdentity* CoreSession::identity(IdentityId id) const { - if (_identities.contains(id)) return _identities[id]; + if (_identities.contains(id)) + return _identities[id]; return nullptr; } - void CoreSession::loadSettings() { CoreUserSettings s(user()); @@ -206,7 +206,7 @@ void CoreSession::loadSettings() // migrate to db QList ids = s.identityIds(); QList networkInfos = Core::networks(user()); - foreach(IdentityId id, ids) { + foreach (IdentityId id, ids) { CoreIdentity identity(s.identity(id)); IdentityId newId = Core::createIdentity(user(), identity); QList::iterator networkIter = networkInfos.begin(); @@ -224,16 +224,15 @@ void CoreSession::loadSettings() } // end of migration - foreach(CoreIdentity identity, Core::identities(user())) { + foreach (CoreIdentity identity, Core::identities(user())) { createIdentity(identity); } - foreach(NetworkInfo info, Core::networks(user())) { + foreach (NetworkInfo info, Core::networks(user())) { createNetwork(info); } } - void CoreSession::saveSessionState() const { _bufferSyncer->storeDirtyIds(); @@ -241,20 +240,18 @@ void CoreSession::saveSessionState() const _networkConfig->save(); } - void CoreSession::restoreSessionState() { QList nets = Core::connectedNetworks(user()); - CoreNetwork *net = nullptr; - foreach(NetworkId id, nets) { + CoreNetwork* net = nullptr; + foreach (NetworkId id, nets) { net = network(id); Q_ASSERT(net); net->connectToIrc(); } } - -void CoreSession::addClient(RemotePeer *peer) +void CoreSession::addClient(RemotePeer* peer) { signalProxy()->setTargetPeer(peer); @@ -265,44 +262,39 @@ void CoreSession::addClient(RemotePeer *peer) signalProxy()->setTargetPeer(nullptr); } - -void CoreSession::addClient(InternalPeer *peer) +void CoreSession::addClient(InternalPeer* peer) { signalProxy()->addPeer(peer); emit sessionStateReceived(sessionState()); } - -void CoreSession::removeClient(Peer *peer) +void CoreSession::removeClient(Peer* peer) { - auto *p = qobject_cast(peer); + auto* p = qobject_cast(peer); if (p) quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt())); _coreInfo->setConnectedClientData(signalProxy()->peerCount(), signalProxy()->peerData()); } - QHash CoreSession::persistentChannels(NetworkId id) const { return Core::persistentChannels(user(), id); } - QHash CoreSession::bufferCiphers(NetworkId id) const { return Core::bufferCiphers(user(), id); } -void CoreSession::setBufferCipher(NetworkId id, const QString &bufferName, const QByteArray &cipher) const +void CoreSession::setBufferCipher(NetworkId id, const QString& bufferName, const QByteArray& cipher) const { Core::setBufferCipher(user(), id, bufferName, cipher); } - // FIXME switch to BufferId void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) { - CoreNetwork *net = network(bufinfo.networkId()); + CoreNetwork* net = network(bufinfo.networkId()); if (net) { net->userInput(bufinfo, msg); } @@ -311,11 +303,15 @@ void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) } } - // ALL messages coming pass through these functions before going to the GUI. // So this is the perfect place for storing the backlog and log stuff. -void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType, - const QString &target, const QString &text_, const QString &sender, Message::Flags flags) +void CoreSession::recvMessageFromServer(NetworkId networkId, + Message::Type type, + BufferInfo::Type bufferType, + const QString& target, + const QString& text_, + const QString& sender, + Message::Flags flags) { // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as @@ -325,12 +321,11 @@ void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags); // check for HardStrictness ignore - CoreNetwork *currentNetwork = network(networkId); + CoreNetwork* currentNetwork = network(networkId); QString networkName = currentNetwork ? currentNetwork->networkName() : QString(""); if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness) return; - if (currentNetwork && _highlightRuleManager.match(rawMsg, currentNetwork->myNick(), currentNetwork->identityPtr()->nicks())) rawMsg.flags |= Message::Flag::Highlight; @@ -341,32 +336,30 @@ void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, } } - void CoreSession::recvStatusMsgFromServer(QString msg) { - auto *net = qobject_cast(sender()); + auto* net = qobject_cast(sender()); Q_ASSERT(net); emit displayStatusMsg(net->networkName(), msg); } - -void CoreSession::processMessageEvent(MessageEvent *event) +void CoreSession::processMessageEvent(MessageEvent* event) { - recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(), - event->target().isNull() ? "" : event->target(), - event->text().isNull() ? "" : event->text(), - event->sender().isNull() ? "" : event->sender(), - event->msgFlags()); + recvMessageFromServer(event->networkId(), + event->msgType(), + event->bufferType(), + event->target().isNull() ? "" : event->target(), + event->text().isNull() ? "" : event->text(), + event->sender().isNull() ? "" : event->sender(), + event->msgFlags()); } - QList CoreSession::buffers() const { return Core::requestBuffers(user()); } - -void CoreSession::customEvent(QEvent *event) +void CoreSession::customEvent(QEvent* event) { if (event->type() != QEvent::User) return; @@ -375,30 +368,34 @@ void CoreSession::customEvent(QEvent *event) event->accept(); } - void CoreSession::processMessages() { if (_messageQueue.count() == 1) { - const RawMessage &rawMsg = _messageQueue.first(); + const RawMessage& rawMsg = _messageQueue.first(); bool createBuffer = !(rawMsg.flags & Message::Redirected); BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer); if (!bufferInfo.isValid()) { Q_ASSERT(!createBuffer); bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, ""); } - Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo), - realName(rawMsg.sender, rawMsg.networkId), avatarUrl(rawMsg.sender, rawMsg.networkId), + Message msg(bufferInfo, + rawMsg.type, + rawMsg.text, + rawMsg.sender, + senderPrefixes(rawMsg.sender, bufferInfo), + realName(rawMsg.sender, rawMsg.networkId), + avatarUrl(rawMsg.sender, rawMsg.networkId), rawMsg.flags); - if(Core::storeMessage(msg)) + if (Core::storeMessage(msg)) emit displayMsg(msg); } else { - QHash > bufferInfoCache; + QHash> bufferInfoCache; MessageList messages; - QList redirectedMessages; // list of Messages which don't enforce a buffer creation + QList redirectedMessages; // list of Messages which don't enforce a buffer creation BufferInfo bufferInfo; for (int i = 0; i < _messageQueue.count(); i++) { - const RawMessage &rawMsg = _messageQueue.at(i); + const RawMessage& rawMsg = _messageQueue.at(i); if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) { bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target]; } @@ -412,15 +409,20 @@ void CoreSession::processMessages() } bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo; } - Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo), - realName(rawMsg.sender, rawMsg.networkId), avatarUrl(rawMsg.sender, rawMsg.networkId), + Message msg(bufferInfo, + rawMsg.type, + rawMsg.text, + rawMsg.sender, + senderPrefixes(rawMsg.sender, bufferInfo), + realName(rawMsg.sender, rawMsg.networkId), + avatarUrl(rawMsg.sender, rawMsg.networkId), rawMsg.flags); messages << msg; } // recheck if there exists a buffer to store a redirected message in for (int i = 0; i < redirectedMessages.count(); i++) { - const RawMessage &rawMsg = redirectedMessages.at(i); + const RawMessage& rawMsg = redirectedMessages.at(i); if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) { bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target]; } @@ -430,13 +432,18 @@ void CoreSession::processMessages() // add the StatusBuffer to the Cache in case there are more Messages for the original target bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo; } - Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo), - realName(rawMsg.sender, rawMsg.networkId), avatarUrl(rawMsg.sender, rawMsg.networkId), + Message msg(bufferInfo, + rawMsg.type, + rawMsg.text, + rawMsg.sender, + senderPrefixes(rawMsg.sender, bufferInfo), + realName(rawMsg.sender, rawMsg.networkId), + avatarUrl(rawMsg.sender, rawMsg.networkId), rawMsg.flags); messages << msg; } - if(Core::storeMessages(messages)) { + if (Core::storeMessages(messages)) { // FIXME: extend protocol to a displayMessages(MessageList) for (int i = 0; i < messages.count(); i++) { emit displayMsg(messages[i]); @@ -447,9 +454,9 @@ void CoreSession::processMessages() _messageQueue.clear(); } -QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const +QString CoreSession::senderPrefixes(const QString& sender, const BufferInfo& bufferInfo) const { - CoreNetwork *currentNetwork = network(bufferInfo.networkId()); + CoreNetwork* currentNetwork = network(bufferInfo.networkId()); if (!currentNetwork) { return {}; } @@ -458,7 +465,7 @@ QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &buf return {}; } - IrcChannel *currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName()); + IrcChannel* currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName()); if (!currentChannel) { return {}; } @@ -467,14 +474,14 @@ QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &buf return currentNetwork->modesToPrefixes(modes); } -QString CoreSession::realName(const QString &sender, NetworkId networkId) const +QString CoreSession::realName(const QString& sender, NetworkId networkId) const { - CoreNetwork *currentNetwork = network(networkId); + CoreNetwork* currentNetwork = network(networkId); if (!currentNetwork) { return {}; } - IrcUser *currentUser = currentNetwork->ircUser(nickFromMask(sender)); + IrcUser* currentUser = currentNetwork->ircUser(nickFromMask(sender)); if (!currentUser) { return {}; } @@ -482,7 +489,7 @@ QString CoreSession::realName(const QString &sender, NetworkId networkId) const return currentUser->realName(); } -QString CoreSession::avatarUrl(const QString &sender, NetworkId networkId) const +QString CoreSession::avatarUrl(const QString& sender, NetworkId networkId) const { Q_UNUSED(sender); Q_UNUSED(networkId); @@ -500,36 +507,33 @@ Protocol::SessionState CoreSession::sessionState() const QVariantList networkIds; QVariantList identities; - foreach(const BufferInfo &id, buffers()) + foreach (const BufferInfo& id, buffers()) bufferInfos << QVariant::fromValue(id); - foreach(const NetworkId &id, _networks.keys()) + foreach (const NetworkId& id, _networks.keys()) networkIds << QVariant::fromValue(id); - foreach(const Identity *i, _identities.values()) + foreach (const Identity* i, _identities.values()) identities << QVariant::fromValue(*i); return Protocol::SessionState(identities, bufferInfos, networkIds); } - void CoreSession::initScriptEngine() { signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString))); signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString))); // FIXME - //QScriptValue storage_ = scriptEngine->newQObject(storage); - //scriptEngine->globalObject().setProperty("storage", storage_); + // QScriptValue storage_ = scriptEngine->newQObject(storage); + // scriptEngine->globalObject().setProperty("storage", storage_); } - void CoreSession::scriptRequest(QString script) { emit scriptResult(scriptEngine->evaluate(script).toString()); } - /*** Identity Handling ***/ -void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional) +void CoreSession::createIdentity(const Identity& identity, const QVariantMap& additional) { #ifndef HAVE_SSL Q_UNUSED(additional) @@ -550,19 +554,21 @@ void CoreSession::createIdentity(const Identity &identity, const QVariantMap &ad createIdentity(coreIdentity); } -const QString CoreSession::strictCompliantIdent(const CoreIdentity *identity) { +const QString CoreSession::strictCompliantIdent(const CoreIdentity* identity) +{ if (_strictIdentEnabled) { // Strict mode enabled: only allow the user's Quassel username as an ident return Core::instance()->strictSysIdent(_user); - } else { + } + else { // Strict mode disabled: allow any identity specified return identity->ident(); } } -void CoreSession::createIdentity(const CoreIdentity &identity) +void CoreSession::createIdentity(const CoreIdentity& identity) { - auto *coreIdentity = new CoreIdentity(identity, this); + auto* coreIdentity = new CoreIdentity(identity, this); _identities[identity.id()] = coreIdentity; // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well coreIdentity->synchronize(signalProxy()); @@ -570,19 +576,17 @@ void CoreSession::createIdentity(const CoreIdentity &identity) emit identityCreated(*coreIdentity); } - void CoreSession::updateIdentityBySender() { - auto *identity = qobject_cast(sender()); + auto* identity = qobject_cast(sender()); if (!identity) return; Core::updateIdentity(user(), *identity); } - void CoreSession::removeIdentity(IdentityId id) { - CoreIdentity *identity = _identities.take(id); + CoreIdentity* identity = _identities.take(id); if (identity) { emit identityRemoved(id); Core::removeIdentity(user(), id); @@ -590,10 +594,9 @@ void CoreSession::removeIdentity(IdentityId id) } } - /*** Network Handling ***/ -void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans) +void CoreSession::createNetwork(const NetworkInfo& info_, const QStringList& persistentChans) { NetworkInfo info = info_; int id; @@ -602,7 +605,8 @@ void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &per Core::createNetwork(user(), info); if (!info.networkId.isValid()) { - qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName)); + qWarning() << qPrintable( + tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName)); return; } @@ -610,7 +614,7 @@ void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &per if (!_networks.contains(id)) { // create persistent chans QRegExp rx(R"(\s*(\S+)(?:\s*(\S+))?\s*)"); - foreach(QString channel, persistentChans) { + foreach (QString channel, persistentChans) { if (!rx.exactMatch(channel)) { qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel); continue; @@ -621,7 +625,7 @@ void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &per Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2)); } - CoreNetwork *net = new CoreNetwork(id, this); + CoreNetwork* net = new CoreNetwork(id, this); connect(net, &CoreNetwork::displayMsg, this, &CoreSession::recvMessageFromServer); connect(net, &CoreNetwork::displayStatusMsg, this, &CoreSession::recvStatusMsgFromServer); connect(net, &CoreNetwork::disconnected, this, &CoreSession::networkDisconnected); @@ -638,11 +642,10 @@ void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &per } } - void CoreSession::removeNetwork(NetworkId id) { // Make sure the network is disconnected! - CoreNetwork *net = network(id); + CoreNetwork* net = network(id); if (!net) return; @@ -658,11 +661,10 @@ void CoreSession::removeNetwork(NetworkId id) } } - void CoreSession::destroyNetwork(NetworkId id) { QList removedBuffers = Core::requestBufferIdsForNetwork(user(), id); - Network *net = _networks.take(id); + Network* net = _networks.take(id); if (net && Core::removeNetwork(user(), id)) { // make sure that all unprocessed RawMessages from this network are removed QList::iterator messageIter = _messageQueue.begin(); @@ -675,7 +677,7 @@ void CoreSession::destroyNetwork(NetworkId id) } } // remove buffers from syncer - foreach(BufferId bufferId, removedBuffers) { + foreach (BufferId bufferId, removedBuffers) { _bufferSyncer->removeBuffer(bufferId); } emit networkRemoved(id); @@ -683,8 +685,7 @@ void CoreSession::destroyNetwork(NetworkId id) } } - -void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName) +void CoreSession::renameBuffer(const NetworkId& networkId, const QString& newName, const QString& oldName) { BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false); if (bufferInfo.isValid()) { @@ -692,13 +693,12 @@ void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newNam } } - void CoreSession::clientsConnected() { - QHash::iterator netIter = _networks.begin(); - Identity *identity = nullptr; - CoreNetwork *net = nullptr; - IrcUser *me = nullptr; + QHash::iterator netIter = _networks.begin(); + Identity* identity = nullptr; + CoreNetwork* net = nullptr; + IrcUser* me = nullptr; while (netIter != _networks.end()) { net = *netIter; ++netIter; @@ -718,13 +718,12 @@ void CoreSession::clientsConnected() } } - void CoreSession::clientsDisconnected() { - QHash::iterator netIter = _networks.begin(); - Identity *identity = nullptr; - CoreNetwork *net = nullptr; - IrcUser *me = nullptr; + QHash::iterator netIter = _networks.begin(); + Identity* identity = nullptr; + CoreNetwork* net = nullptr; + IrcUser* me = nullptr; QString awayReason; while (netIter != _networks.end()) { net = *netIter; @@ -750,11 +749,10 @@ void CoreSession::clientsDisconnected() } } - -void CoreSession::globalAway(const QString &msg, const bool skipFormatting) +void CoreSession::globalAway(const QString& msg, const bool skipFormatting) { - QHash::iterator netIter = _networks.begin(); - CoreNetwork *net = nullptr; + QHash::iterator netIter = _networks.begin(); + CoreNetwork* net = nullptr; while (netIter != _networks.end()) { net = *netIter; ++netIter; @@ -766,7 +764,8 @@ void CoreSession::globalAway(const QString &msg, const bool skipFormatting) } } -void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword) { +void CoreSession::changePassword(PeerPtr peer, const QString& userName, const QString& oldPassword, const QString& newPassword) +{ Q_UNUSED(peer); bool success = false; @@ -774,18 +773,15 @@ void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QS if (uid.isValid() && uid == user()) success = Core::changeUserPassword(uid, newPassword); - signalProxy()->restrictTargetPeers(signalProxy()->sourcePeer(), [&]{ - emit passwordChanged(nullptr, success); - }); + signalProxy()->restrictTargetPeers(signalProxy()->sourcePeer(), [&] { emit passwordChanged(nullptr, success); }); } -void CoreSession::kickClient(int peerId) { +void CoreSession::kickClient(int peerId) +{ auto peer = signalProxy()->peerById(peerId); if (peer == nullptr) { qWarning() << "Invalid peer Id: " << peerId; return; } - signalProxy()->restrictTargetPeers(peer, [&]{ - emit disconnectFromCore(); - }); + signalProxy()->restrictTargetPeers(peer, [&] { emit disconnectFromCore(); }); } diff --git a/src/core/coresession.h b/src/core/coresession.h index dade24b3..b8da03c5 100644 --- a/src/core/coresession.h +++ b/src/core/coresession.h @@ -20,19 +20,20 @@ #pragma once +#include + #include #include #include #include -#include -#include "coreinfo.h" #include "corealiasmanager.h" #include "corehighlightrulemanager.h" #include "coreignorelistmanager.h" +#include "coreinfo.h" +#include "message.h" #include "peer.h" #include "protocol.h" -#include "message.h" #include "storage.h" class CoreBacklogManager; @@ -64,12 +65,12 @@ class CoreSession : public QObject Q_OBJECT public: - CoreSession(UserId, bool restoreState, bool strictIdentEnabled, QObject *parent = nullptr); + CoreSession(UserId, bool restoreState, bool strictIdentEnabled, QObject* parent = nullptr); QList buffers() const; inline UserId user() const { return _user; } - CoreNetwork *network(NetworkId) const; - CoreIdentity *identity(IdentityId) const; + CoreNetwork* network(NetworkId) const; + CoreIdentity* identity(IdentityId) const; /** * Returns the optionally strict-compliant ident for the given user identity @@ -79,39 +80,39 @@ public: * * @return The user's ident, compliant with strict mode (when enabled) */ - const QString strictCompliantIdent(const CoreIdentity *identity); + const QString strictCompliantIdent(const CoreIdentity* identity); - inline CoreNetworkConfig *networkConfig() const { return _networkConfig; } - NetworkConnection *networkConnection(NetworkId) const; + inline CoreNetworkConfig* networkConfig() const { return _networkConfig; } + NetworkConnection* networkConnection(NetworkId) const; Protocol::SessionState sessionState() const; - inline SignalProxy *signalProxy() const { return _signalProxy; } + inline SignalProxy* signalProxy() const { return _signalProxy; } - const AliasManager &aliasManager() const { return _aliasManager; } - AliasManager &aliasManager() { return _aliasManager; } + const AliasManager& aliasManager() const { return _aliasManager; } + AliasManager& aliasManager() { return _aliasManager; } - inline EventManager *eventManager() const { return _eventManager; } - inline EventStringifier *eventStringifier() const { return _eventStringifier; } - inline CoreSessionEventProcessor *sessionEventProcessor() const { return _sessionEventProcessor; } - inline CtcpParser *ctcpParser() const { return _ctcpParser; } - inline IrcParser *ircParser() const { return _ircParser; } + inline EventManager* eventManager() const { return _eventManager; } + inline EventStringifier* eventStringifier() const { return _eventStringifier; } + inline CoreSessionEventProcessor* sessionEventProcessor() const { return _sessionEventProcessor; } + inline CtcpParser* ctcpParser() const { return _ctcpParser; } + inline IrcParser* ircParser() const { return _ircParser; } - inline CoreIrcListHelper *ircListHelper() const { return _ircListHelper; } + inline CoreIrcListHelper* ircListHelper() const { return _ircListHelper; } - inline CoreIgnoreListManager *ignoreListManager() { return &_ignoreListManager; } - inline HighlightRuleManager *highlightRuleManager() { return &_highlightRuleManager; } - inline CoreTransferManager *transferManager() const { return _transferManager; } - inline CoreDccConfig *dccConfig() const { return _dccConfig; } + inline CoreIgnoreListManager* ignoreListManager() { return &_ignoreListManager; } + inline HighlightRuleManager* highlightRuleManager() { return &_highlightRuleManager; } + inline CoreTransferManager* transferManager() const { return _transferManager; } + inline CoreDccConfig* dccConfig() const { return _dccConfig; } -// void attachNetworkConnection(NetworkConnection *conn); + // void attachNetworkConnection(NetworkConnection *conn); //! Return necessary data for restoring the session after restarting the core void restoreSessionState(); public slots: - void addClient(RemotePeer *peer); - void addClient(InternalPeer *peer); + void addClient(RemotePeer* peer); + void addClient(InternalPeer* peer); /** * Shuts down the session and deletes itself afterwards. @@ -123,8 +124,8 @@ public slots: //! Create an identity and propagate the changes to the clients. /** \param identity The identity to be created. */ - void createIdentity(const Identity &identity, const QVariantMap &additional); - void createIdentity(const CoreIdentity &identity); + void createIdentity(const Identity& identity, const QVariantMap& additional); + void createIdentity(const CoreIdentity& identity); //! Remove identity and propagate that fact to the clients. /** \param identity The identity to be removed. @@ -134,7 +135,7 @@ public slots: //! Create a network and propagate the changes to the clients. /** \param info The network's settings. */ - void createNetwork(const NetworkInfo &info, const QStringList &persistentChannels = QStringList()); + void createNetwork(const NetworkInfo& info, const QStringList& persistentChannels = QStringList()); //! Remove network and propagate that fact to the clients. /** \param network The id of the network to be removed. @@ -146,16 +147,16 @@ public slots: * \param newName The new name of the buffer * \param oldName The old name of the buffer */ - void renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName); + void renameBuffer(const NetworkId& networkId, const QString& newName, const QString& oldName); - void changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword); + void changePassword(PeerPtr peer, const QString& userName, const QString& oldPassword, const QString& newPassword); void kickClient(int peerId); QHash persistentChannels(NetworkId) const; QHash bufferCiphers(NetworkId id) const; - void setBufferCipher(NetworkId id, const QString &bufferName, const QByteArray &cipher) const; + void setBufferCipher(NetworkId id, const QString& bufferName, const QByteArray& cipher) const; /** * Marks us away (or unaway) on all networks @@ -163,13 +164,13 @@ public slots: * @param[in] msg Away message, or blank to set unaway * @param[in] skipFormatting If true, skip timestamp formatting codes (e.g. if already done) */ - void globalAway(const QString &msg = QString(), const bool skipFormatting = false); + void globalAway(const QString& msg = QString(), const bool skipFormatting = false); signals: void initialized(); - void sessionStateReceived(const Protocol::SessionState &sessionState); + void sessionStateReceived(const Protocol::SessionState& sessionState); - //void msgFromGui(uint netid, QString buf, QString message); + // void msgFromGui(uint netid, QString buf, QString message); void displayMsg(Message message); void displayStatusMsg(QString, QString); @@ -179,7 +180,7 @@ signals: /** This signal is propagated to the clients to tell them that the given identity has been created. * \param identity The new identity. */ - void identityCreated(const Identity &identity); + void identityCreated(const Identity& identity); //! Identity has been removed. /** This signal is propagated to the clients to inform them about the removal of the given identity. @@ -196,13 +197,19 @@ signals: void disconnectFromCore(); protected: - void customEvent(QEvent *event) override; + void customEvent(QEvent* event) override; private slots: - void removeClient(Peer *peer); + void removeClient(Peer* peer); void recvStatusMsgFromServer(QString msg); - void recvMessageFromServer(NetworkId networkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None); + void recvMessageFromServer(NetworkId networkId, + Message::Type, + BufferInfo::Type, + const QString& target, + const QString& text, + const QString& sender = "", + Message::Flags flags = Message::None); void destroyNetwork(NetworkId); @@ -224,36 +231,36 @@ private: void initScriptEngine(); /// Hook for converting events to the old displayMsg() handlers - Q_INVOKABLE void processMessageEvent(MessageEvent *event); + Q_INVOKABLE void processMessageEvent(MessageEvent* event); UserId _user; /// Whether or not strict ident mode is enabled, locking users' idents to Quassel username bool _strictIdentEnabled; - SignalProxy *_signalProxy; + SignalProxy* _signalProxy; CoreAliasManager _aliasManager; - QHash _identities; - QHash _networks; + QHash _identities; + QHash _networks; QSet _networksPendingDisconnect; - CoreBufferSyncer *_bufferSyncer; - CoreBacklogManager *_backlogManager; - CoreBufferViewManager *_bufferViewManager; - CoreDccConfig *_dccConfig; - CoreIrcListHelper *_ircListHelper; - CoreNetworkConfig *_networkConfig; - CoreInfo *_coreInfo; - CoreTransferManager *_transferManager; + CoreBufferSyncer* _bufferSyncer; + CoreBacklogManager* _backlogManager; + CoreBufferViewManager* _bufferViewManager; + CoreDccConfig* _dccConfig; + CoreIrcListHelper* _ircListHelper; + CoreNetworkConfig* _networkConfig; + CoreInfo* _coreInfo; + CoreTransferManager* _transferManager; - EventManager *_eventManager; - EventStringifier *_eventStringifier; // should eventually move into client - CoreSessionEventProcessor *_sessionEventProcessor; - CtcpParser *_ctcpParser; - IrcParser *_ircParser; + EventManager* _eventManager; + EventStringifier* _eventStringifier; // should eventually move into client + CoreSessionEventProcessor* _sessionEventProcessor; + CtcpParser* _ctcpParser; + IrcParser* _ircParser; - QScriptEngine *scriptEngine; + QScriptEngine* scriptEngine; /** * This method obtains the prefixes of the message's sender within a channel, by looking up their channelmodes, and @@ -261,29 +268,29 @@ private: * @param sender The hostmask of the sender * @param bufferInfo The BufferInfo object of the buffer */ - QString senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const; + QString senderPrefixes(const QString& sender, const BufferInfo& bufferInfo) const; /** * This method obtains the realname of the message's sender. * @param sender The hostmask of the sender * @param networkId The network the user is on */ - QString realName(const QString &sender, NetworkId networkId) const; + QString realName(const QString& sender, NetworkId networkId) const; /** * This method obtains the avatar of the message's sender. * @param sender The hostmask of the sender * @param networkId The network the user is on */ - QString avatarUrl(const QString &sender, NetworkId networkId) const; + QString avatarUrl(const QString& sender, NetworkId networkId) const; QList _messageQueue; bool _processMessages; CoreIgnoreListManager _ignoreListManager; CoreHighlightRuleManager _highlightRuleManager; }; - -struct RawMessage { +struct RawMessage +{ NetworkId networkId; Message::Type type; BufferInfo::Type bufferType; @@ -291,6 +298,14 @@ struct RawMessage { QString text; QString sender; Message::Flags flags; - RawMessage(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, Message::Flags flags) - : networkId(networkId), type(type), bufferType(bufferType), target(std::move(target)), text(std::move(text)), sender(std::move(sender)), flags(flags) {} + RawMessage( + NetworkId networkId, Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, Message::Flags flags) + : networkId(networkId) + , type(type) + , bufferType(bufferType) + , target(std::move(target)) + , text(std::move(text)) + , sender(std::move(sender)) + , flags(flags) + {} }; diff --git a/src/core/coresessioneventprocessor.cpp b/src/core/coresessioneventprocessor.cpp index 99913ad3..df4a4091 100644 --- a/src/core/coresessioneventprocessor.cpp +++ b/src/core/coresessioneventprocessor.cpp @@ -34,26 +34,26 @@ #include "quassel.h" #ifdef HAVE_QCA2 -# include "keyevent.h" +# include "keyevent.h" #endif // IRCv3 capabilities #include "irccap.h" -CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession *session) - : BasicHandler("handleCtcp", session), - _coreSession(session) +CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession* session) + : BasicHandler("handleCtcp", session) + , _coreSession(session) { connect(coreSession(), &CoreSession::networkDisconnected, this, &CoreSessionEventProcessor::destroyNetsplits); connect(this, &CoreSessionEventProcessor::newEvent, coreSession()->eventManager(), &EventManager::postEvent); } - -bool CoreSessionEventProcessor::checkParamCount(IrcEvent *e, int minParams) +bool CoreSessionEventProcessor::checkParamCount(IrcEvent* e, int minParams) { if (e->params().count() < minParams) { if (e->type() == EventManager::IrcEventNumeric) { - qWarning() << "Command " << static_cast(e)->number() << " requires " << minParams << "params, got: " << e->params(); + qWarning() << "Command " << static_cast(e)->number() << " requires " << minParams + << "params, got: " << e->params(); } else { QString name = coreSession()->eventManager()->enumName(e->type()); @@ -65,8 +65,7 @@ bool CoreSessionEventProcessor::checkParamCount(IrcEvent *e, int minParams) return true; } - -void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneus) +void CoreSessionEventProcessor::tryNextNick(NetworkEvent* e, const QString& errnick, bool erroneus) { QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks(); int nextNickIdx = desiredNicks.indexOf(errnick) + 1; @@ -77,9 +76,13 @@ void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errn else { if (erroneus) { // FIXME Make this an ErrorEvent or something like that, so it's translated in the client - MessageEvent *msgEvent = new MessageEvent(Message::Error, e->network(), - tr("No free and valid nicks in nicklist found. use: /nick to continue"), - QString(), QString(), Message::None, e->timestamp()); + MessageEvent* msgEvent = new MessageEvent(Message::Error, + e->network(), + tr("No free and valid nicks in nicklist found. use: /nick to continue"), + QString(), + QString(), + Message::None, + e->timestamp()); emit newEvent(msgEvent); return; } @@ -91,15 +94,14 @@ void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errn coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick)); } - -void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e) +void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric* e) { switch (e->number()) { // SASL authentication replies // See: http://ircv3.net/specs/extensions/sasl-3.1.html - //case 900: // RPL_LOGGEDIN - //case 901: // RPL_LOGGEDOUT + // case 900: // RPL_LOGGEDIN + // case 901: // RPL_LOGGEDOUT // Don't use 900 or 901 for updating the local hostmask. Unreal 3.2 gives it as the IP address // even when cloaked. // Every other reply should result in moving on @@ -119,8 +121,7 @@ void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e) } } - -void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -130,7 +131,7 @@ void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e) return; } - CoreNetwork *net = coreNetwork(e); + CoreNetwork* net = coreNetwork(e); #ifdef HAVE_SSL if (net->identityPtr()->sslCert().isNull()) { @@ -144,13 +145,14 @@ void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e) saslData.prepend("AUTHENTICATE "); net->putRawLine(saslData); #ifdef HAVE_SSL - } else { + } + else { net->putRawLine("AUTHENTICATE +"); } #endif } -void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventCap(IrcEvent* e) { // Handle capability negotiation // See: http://ircv3.net/specs/core/capability-negotiation-3.2.html @@ -160,7 +162,7 @@ void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) if (!checkParamCount(e, 2)) return; - CoreNetwork *coreNet = coreNetwork(e); + CoreNetwork* coreNet = coreNetwork(e); QString capCommand = e->params().at(1).trimmed().toUpper(); if (capCommand == "LS" || capCommand == "NEW") { // Either we've gotten a list of capabilities, or new capabilities we may want @@ -173,13 +175,15 @@ void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) // Middle of multi-line reply, ignore the asterisk capListFinished = false; availableCaps = e->params().at(3).split(' '); - } else { + } + else { // Single line reply capListFinished = true; if (e->params().count() >= 3) { // Some capabilities are specified, add them availableCaps = e->params().at(2).split(' '); - } else { + } + else { // No capabilities available, add an empty list availableCaps = QStringList(); } @@ -209,7 +213,8 @@ void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) // Begin capability requests when capability listing complete if (capListFinished) coreNet->beginCapNegotiation(); - } else if (capCommand == "ACK") { + } + else if (capCommand == "ACK") { // CAP ACK requires at least 3 parameters (no empty response allowed) if (!checkParamCount(e, 3)) { // If an invalid reply is sent, try to continue rather than getting stuck. @@ -234,8 +239,7 @@ void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) acceptedCap = acceptedCaps[i].trimmed().toLower(); // Mark this cap as accepted coreNet->acknowledgeCap(acceptedCap); - if (!capsRequireConfiguration && - coreNet->capsRequiringConfiguration.contains(acceptedCap)) { + if (!capsRequireConfiguration && coreNet->capsRequiringConfiguration.contains(acceptedCap)) { capsRequireConfiguration = true; // Some capabilities (e.g. SASL) require further messages to finish. If so, do NOT // send the next capability; it will be handled elsewhere in CoreNetwork. @@ -247,7 +251,8 @@ void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) // No additional configuration required, move on to the next capability coreNet->sendNextCap(); } - } else if (capCommand == "NAK" || capCommand == "DEL") { + } + else if (capCommand == "NAK" || capCommand == "DEL") { // CAP NAK/DEL require at least 3 parameters (no empty response allowed) if (!checkParamCount(e, 3)) { if (capCommand == "NAK") { @@ -299,23 +304,24 @@ void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e) /* IRCv3 account-notify * Log in: ":nick!user@host ACCOUNT accountname" * Log out: ":nick!user@host ACCOUNT *" */ -void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent* e) { if (!checkParamCount(e, 1)) return; - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (ircuser) { // WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'. // As '*' is used internally to represent logged-out, no need to handle that differently. ircuser->setAccount(e->params().at(0)); - } else { + } + else { qDebug() << "Received account-notify data for unknown user" << e->prefix(); } } /* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */ -void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventAway(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -323,39 +329,42 @@ void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e) // that it counts as two parameters, but we shouldn't rely on that. // Nick is sent as part of parameters in order to split user/server decoding - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) { // If two parameters are sent -and- the second parameter isn't empty, then user is away. // Otherwise, mark them as not away. if (e->params().count() >= 2 && !e->params().at(1).isEmpty()) { ircuser->setAway(true); ircuser->setAwayMessage(e->params().at(1)); - } else { + } + else { ircuser->setAway(false); } - } else { + } + else { qDebug() << "Received away-notify data for unknown user" << e->params().at(0); } } /* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */ -void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent* e) { if (!checkParamCount(e, 2)) return; - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (ircuser) { // Update with new user/hostname information. setUser/setHost handles checking what // actually changed. ircuser->setUser(e->params().at(0)); ircuser->setHost(e->params().at(1)); - } else { + } + else { qDebug() << "Received chghost data for unknown user" << e->prefix(); } } -void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent* e) { if (checkParamCount(e, 2)) { e->network()->updateNickFromMask(e->prefix()); @@ -363,26 +372,28 @@ void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e) } /* JOIN: ": JOIN " */ -void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent* e) { - if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin + if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin return; if (!checkParamCount(e, 1)) return; - CoreNetwork *net = coreNetwork(e); + CoreNetwork* net = coreNetwork(e); QString channel = e->params()[0]; - IrcUser *ircuser = net->updateNickFromMask(e->prefix()); + IrcUser* ircuser = net->updateNickFromMask(e->prefix()); if (net->capEnabled(IrcCap::EXTENDED_JOIN)) { if (e->params().count() < 3) { // Some IRC servers don't send extended-join events in all situations. Rather than // ignore the join entirely, treat it as a regular join with a debug-level log entry. // See: https://github.com/inspircd/inspircd/issues/821 - qDebug() << "extended-join requires 3 params, got:" << e->params() << ", handling as a " + qDebug() << "extended-join requires 3 params, got:" << e->params() + << ", handling as a " "regular join"; - } else { + } + else { // If logged in, :nick!user@host JOIN #channelname accountname :Real Name // If logged out, :nick!user@host JOIN #channelname * :Real Name // See: http://ircv3.net/specs/extensions/extended-join-3.1.html @@ -396,7 +407,7 @@ void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e) // Else :nick!user@host JOIN #channelname bool handledByNetsplit = false; - foreach(Netsplit* n, _netsplits.value(e->network())) { + foreach (Netsplit* n, _netsplits.value(e->network())) { handledByNetsplit = n->userJoined(e->prefix(), channel); if (handledByNetsplit) break; @@ -423,25 +434,23 @@ void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e) // Mark the message as Self e->setFlag(EventManager::Self); // FIXME use event - net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely + net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely } } - -void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e) +void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent* e) { if (checkParamCount(e, 2)) { e->network()->updateNickFromMask(e->prefix()); - IrcUser *victim = e->network()->ircUser(e->params().at(1)); + IrcUser* victim = e->network()->ircUser(e->params().at(1)); if (victim) { victim->partChannel(e->params().at(0)); - //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel); + // if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel); } } } - -void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventMode(IrcEvent* e) { if (!checkParamCount(e, 2)) return; @@ -449,10 +458,10 @@ void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e) if (e->network()->isChannelName(e->params().first())) { // Channel Modes - IrcChannel *channel = e->network()->ircChannel(e->params()[0]); + IrcChannel* channel = e->network()->ircChannel(e->params()[0]); if (!channel) { - // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that - // anyways: we don't have a place to store the data --> discard the info. + // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like + // that anyways: we don't have a place to store the data --> discard the info. return; } @@ -472,15 +481,15 @@ void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e) if (e->network()->prefixModes().contains(mode)) { // user channel modes (op, voice, etc...) if (paramOffset < e->params().count()) { - IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]); + IrcUser* ircUser = e->network()->ircUser(e->params()[paramOffset]); if (!ircUser) { qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset]; } else { if (add) { bool handledByNetsplit = false; - QHash splits = _netsplits.value(e->network()); - foreach(Netsplit* n, _netsplits.value(e->network())) { + QHash splits = _netsplits.value(e->network()); + foreach (Netsplit* n, _netsplits.value(e->network())) { handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name()); if (handledByNetsplit) { n->addMode(ircUser->hostmask(), channel->name(), QString(mode)); @@ -522,7 +531,7 @@ void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e) } else { // pure User Modes - IrcUser *ircUser = e->network()->newIrcUser(e->params().first()); + IrcUser* ircUser = e->network()->newIrcUser(e->params().first()); QString modeString(e->params()[1]); QString addModes; QString removeModes; @@ -554,11 +563,10 @@ void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e) } } - -void CoreSessionEventProcessor::processIrcEventNick(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventNick(IrcEvent* e) { if (checkParamCount(e, 1)) { - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) { qWarning() << Q_FUNC_INFO << "Unknown IrcUser!"; return; @@ -573,11 +581,10 @@ void CoreSessionEventProcessor::processIrcEventNick(IrcEvent *e) } } - -void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e) +void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent* e) { if (checkParamCount(e, 1)) { - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) { qWarning() << Q_FUNC_INFO << "Unknown IrcUser!"; return; @@ -593,13 +600,12 @@ void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e) } } - -void CoreSessionEventProcessor::processIrcEventPart(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventPart(IrcEvent* e) { if (checkParamCount(e, 1)) { - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) { - qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!"; + qWarning() << Q_FUNC_INFO << "Unknown IrcUser!"; return; } @@ -612,25 +618,23 @@ void CoreSessionEventProcessor::processIrcEventPart(IrcEvent *e) } } - -void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e) +void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent* e) { if (checkParamCount(e, 1)) { - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) { - qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!"; + qWarning() << Q_FUNC_INFO << "Unknown IrcUser!"; return; } QString channel = e->params().at(0); ircuser->partChannel(channel); if (e->network()->isMe(ircuser)) { - qobject_cast(e->network())->setChannelParted(channel); + qobject_cast(e->network())->setChannelParted(channel); } } } - -void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventPing(IrcEvent* e) { QString param = e->params().count() ? e->params().first() : QString(); // FIXME use events @@ -638,8 +642,7 @@ void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e) coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true); } - -void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventPong(IrcEvent* e) { // Ensure we get at least one parameter if (!checkParamCount(e, 1)) @@ -652,7 +655,8 @@ void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e) // Only one parameter received // :localhost PONG 02:43:49.565 timestamp = e->params().at(0); - } else { + } + else { // Two parameters received, pick the second // :localhost PONG localhost :02:43:49.565 timestamp = e->params().at(1); @@ -672,8 +676,8 @@ void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e) // Add a message the first time it happens qDebug().nospace() << "Received PONG with valid timestamp, marking pong replies on " "network " - << "\"" << qPrintable(e->network()->networkName()) << "\" (ID: " - << qPrintable(QString::number(e->network()->networkId().toInt())) + << "\"" << qPrintable(e->network()->networkName()) + << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt())) << ") as usable for latency measurement"; } // Remove pending flag @@ -689,7 +693,8 @@ void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e) // Calculate latency from time difference, divided by 2 to account for round-trip time e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2); - } else if (coreNetwork(e)->isPongReplyPending() && !coreNetwork(e)->isPongTimestampValid()) { + } + else if (coreNetwork(e)->isPongReplyPending() && !coreNetwork(e)->isPongTimestampValid()) { // There's an auto-PING reply pending and we've not yet received a PONG reply with a valid // timestamp. It's possible this server will never respond with a valid timestamp, and thus // any automated PINGs will result in unwanted spamming of the server buffer. @@ -701,17 +706,16 @@ void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e) // Log a message qDebug().nospace() << "Received PONG with invalid timestamp from network " - << "\"" << qPrintable(e->network()->networkName()) << "\" (ID: " - << qPrintable(QString::number(e->network()->networkId().toInt())) + << "\"" << qPrintable(e->network()->networkName()) + << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt())) << "), silencing, parameters are " << e->params(); } // else: We're not expecting a PONG reply and timestamp is not valid, assume it's from the user } - -void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent* e) { - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) return; @@ -726,16 +730,13 @@ void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e) // check if netsplit if (Netsplit::isNetsplit(msg)) { - Netsplit *n; + Netsplit* n; if (!_netsplits[e->network()].contains(msg)) { n = new Netsplit(e->network(), this); connect(n, &Netsplit::finished, this, &CoreSessionEventProcessor::handleNetsplitFinished); - connect(n, &Netsplit::netsplitJoin, - this, &CoreSessionEventProcessor::handleNetsplitJoin); - connect(n, &Netsplit::netsplitQuit, - this, &CoreSessionEventProcessor::handleNetsplitQuit); - connect(n, &Netsplit::earlyJoin, - this, &CoreSessionEventProcessor::handleEarlyNetsplitJoin); + connect(n, &Netsplit::netsplitJoin, this, &CoreSessionEventProcessor::handleNetsplitJoin); + connect(n, &Netsplit::netsplitQuit, this, &CoreSessionEventProcessor::handleNetsplitQuit); + connect(n, &Netsplit::earlyJoin, this, &CoreSessionEventProcessor::handleEarlyNetsplitJoin); _netsplits[e->network()].insert(msg, n); } else { @@ -748,31 +749,29 @@ void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e) // normal quit is handled in lateProcessIrcEventQuit() } - -void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e) +void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent* e) { if (e->testFlag(EventManager::Netsplit)) return; - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) return; ircuser->quit(); } - -void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent* e) { if (checkParamCount(e, 2)) { - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (e->network()->isMe(ircuser)) { // Mark the message as Self e->setFlag(EventManager::Self); } - IrcChannel *channel = e->network()->ircChannel(e->params().at(0)); + IrcChannel* channel = e->network()->ircChannel(e->params().at(0)); if (channel) channel->setTopic(e->params().at(1)); } @@ -781,7 +780,7 @@ void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e) /* ERROR - "ERROR :reason" Example: ERROR :Closing Link: nickname[xxx.xxx.xxx.xxx] (Large base64 image paste.) See https://tools.ietf.org/html/rfc2812#section-3.7.4 */ -void CoreSessionEventProcessor::processIrcEventError(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEventError(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -793,54 +792,84 @@ void CoreSessionEventProcessor::processIrcEventError(IrcEvent *e) } } - #ifdef HAVE_QCA2 -void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e) +void CoreSessionEventProcessor::processKeyEvent(KeyEvent* e) { if (!Cipher::neededFeaturesAvailable()) { - emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Unable to perform key exchange, missing qca-ossl plugin."), e->prefix(), e->target(), Message::None, e->timestamp())); + emit newEvent(new MessageEvent(Message::Error, + e->network(), + tr("Unable to perform key exchange, missing qca-ossl plugin."), + e->prefix(), + e->target(), + Message::None, + e->timestamp())); return; } - auto *net = qobject_cast(e->network()); - Cipher *c = net->cipher(e->target()); - if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?) + auto* net = qobject_cast(e->network()); + Cipher* c = net->cipher(e->target()); + if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?) return; if (e->exchangeType() == KeyEvent::Init) { QByteArray pubKey = c->parseInitKeyX(e->key()); if (pubKey.isEmpty()) { - emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Unable to parse the DH1080_INIT. Key exchange failed."), e->prefix(), e->target(), Message::None, e->timestamp())); + emit newEvent(new MessageEvent(Message::Error, + e->network(), + tr("Unable to parse the DH1080_INIT. Key exchange failed."), + e->prefix(), + e->target(), + Message::None, + e->timestamp())); return; - } else { + } + else { net->setCipherKey(e->target(), c->key()); - emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Your key is set and messages will be encrypted."), e->prefix(), e->target(), Message::None, e->timestamp())); + emit newEvent(new MessageEvent(Message::Info, + e->network(), + tr("Your key is set and messages will be encrypted."), + e->prefix(), + e->target(), + Message::None, + e->timestamp())); QList p; - p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey; + p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ") + pubKey; net->putCmd("NOTICE", p); } - } else { + } + else { if (c->parseFinishKeyX(e->key())) { net->setCipherKey(e->target(), c->key()); - emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Your key is set and messages will be encrypted."), e->prefix(), e->target(), Message::None, e->timestamp())); - } else { - emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Failed to parse DH1080_FINISH. Key exchange failed."), e->prefix(), e->target(), Message::None, e->timestamp())); + emit newEvent(new MessageEvent(Message::Info, + e->network(), + tr("Your key is set and messages will be encrypted."), + e->prefix(), + e->target(), + Message::None, + e->timestamp())); + } + else { + emit newEvent(new MessageEvent(Message::Info, + e->network(), + tr("Failed to parse DH1080_FINISH. Key exchange failed."), + e->prefix(), + e->target(), + Message::None, + e->timestamp())); } } } #endif - /* RPL_WELCOME */ -void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e) +void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric* e) { e->network()->setCurrentServer(e->prefix()); e->network()->setMyNick(e->target()); } - /* RPL_ISUPPORT */ // TODO Complete 005 handling, also use sensible defaults for non-sent stuff -void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent005(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -856,35 +885,30 @@ void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e) e->network()->determinePrefixes(); } - /* RPL_UMODEIS - " []" */ -void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *) +void CoreSessionEventProcessor::processIrcEvent221(IrcEvent*) { // TODO: save information in network object } - /* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */ -void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *) +void CoreSessionEventProcessor::processIrcEvent250(IrcEvent*) { // TODO: save information in network object } - /* RPL_LOCALUSERS - "Current local user: 5024 Max: 7999 */ -void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *) +void CoreSessionEventProcessor::processIrcEvent265(IrcEvent*) { // TODO: save information in network object } - /* RPL_GLOBALUSERS - "Current global users: 46093 Max: 47650" */ -void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *) +void CoreSessionEventProcessor::processIrcEvent266(IrcEvent*) { // TODO: save information in network object } - /* WHOIS-Message: Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message. @@ -899,26 +923,25 @@ WHOWAS-Message: */ /* RPL_AWAY - " :" */ -void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent301(IrcEvent* e) { if (!checkParamCount(e, 2)) return; - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) { ircuser->setAway(true); ircuser->setAwayMessage(e->params().at(1)); // lastAwayMessageTime is set in EventStringifier::processIrcEvent301(), no need to set it // here too - //ircuser->setLastAwayMessageTime(now); + // ircuser->setLastAwayMessageTime(now); } } - /* RPL_UNAWAY - ":You are no longer marked as being away" */ -void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent305(IrcEvent* e) { - IrcUser *me = e->network()->me(); + IrcUser* me = e->network()->me(); if (me) me->setAway(false); @@ -928,47 +951,43 @@ void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e) } } - /* RPL_NOWAWAY - ":You have been marked as being away" */ -void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent306(IrcEvent* e) { - IrcUser *me = e->network()->me(); + IrcUser* me = e->network()->me(); if (me) me->setAway(true); } - /* RPL_WHOISSERVICE - " is registered nick" */ -void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent307(IrcEvent* e) { if (!checkParamCount(e, 1)) return; - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) ircuser->setWhoisServiceReply(e->params().join(" ")); } - /* RPL_SUSERHOST - " is available for help." */ -void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent310(IrcEvent* e) { if (!checkParamCount(e, 1)) return; - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) ircuser->setSuserHost(e->params().join(" ")); } - /* RPL_WHOISUSER - " * :" */ -void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent311(IrcEvent* e) { if (!checkParamCount(e, 3)) return; - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) { ircuser->setUser(e->params().at(1)); ircuser->setHost(e->params().at(2)); @@ -976,33 +995,30 @@ void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e) } } - /* RPL_WHOISSERVER - " :" */ -void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent312(IrcEvent* e) { if (!checkParamCount(e, 2)) return; - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) ircuser->setServer(e->params().at(1)); } - /* RPL_WHOISOPERATOR - " :is an IRC operator" */ -void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent313(IrcEvent* e) { if (!checkParamCount(e, 1)) return; - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) ircuser->setIrcOperator(e->params().last()); } - /* RPL_ENDOFWHO: " :End of WHO list" */ -void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent315(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -1011,10 +1027,9 @@ void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e) e->setFlag(EventManager::Silent); } - /* RPL_WHOISIDLE - " :seconds idle" (real life: " :seconds idle, signon time) */ -void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent317(IrcEvent* e) { if (!checkParamCount(e, 2)) return; @@ -1022,7 +1037,7 @@ void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e) QDateTime loginTime; int idleSecs = e->params()[1].toInt(); - if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation + if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation // Allow for 64-bit time qint64 logintime = e->params()[2].toLongLong(); // Time in IRC protocol is defined as seconds. Convert from seconds instead. @@ -1037,7 +1052,7 @@ void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e) #endif } - IrcUser *ircuser = e->network()->ircUser(e->params()[0]); + IrcUser* ircuser = e->network()->ircUser(e->params()[0]); if (ircuser) { ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs)); if (loginTime.isValid()) @@ -1045,9 +1060,8 @@ void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e) } } - /* RPL_LIST - " <# visible> :" */ -void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent322(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -1073,9 +1087,8 @@ void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e) e->stop(); // consumed by IrcListHelper, so don't further process/show this event } - /* RPL_LISTEND ":End of LIST" */ -void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent323(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -1084,70 +1097,71 @@ void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e) e->stop(); // consumed by IrcListHelper, so don't further process/show this event } - /* RPL_CHANNELMODEIS - " " */ -void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent324(IrcEvent* e) { processIrcEventMode(e); } - /* RPL_WHOISACCOUNT - " :is authed as" */ -void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent330(IrcEvent* e) { // Though the ":is authed as" remark should always be there, we should handle cases when it's // not included, too. if (!checkParamCount(e, 2)) return; - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) { ircuser->setAccount(e->params().at(1)); } } - /* RPL_NOTOPIC */ -void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent331(IrcEvent* e) { if (!checkParamCount(e, 1)) return; - IrcChannel *chan = e->network()->ircChannel(e->params()[0]); + IrcChannel* chan = e->network()->ircChannel(e->params()[0]); if (chan) chan->setTopic(QString()); } - /* RPL_TOPIC */ -void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent332(IrcEvent* e) { if (!checkParamCount(e, 2)) return; - IrcChannel *chan = e->network()->ircChannel(e->params()[0]); + IrcChannel* chan = e->network()->ircChannel(e->params()[0]); if (chan) chan->setTopic(e->params()[1]); } - /* RPL_WHOREPLY: " ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] : " */ -void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent352(IrcEvent* e) { if (!checkParamCount(e, 6)) return; QString channel = e->params()[0]; - IrcUser *ircuser = e->network()->ircUser(e->params()[4]); + IrcUser* ircuser = e->network()->ircUser(e->params()[4]); if (ircuser) { // Only process the WHO information if an IRC user exists. Don't create an IRC user here; // there's no way to track when the user quits, which would leave a phantom IrcUser lying // around. // NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an // RPL_MONONLINE numeric before any WHO commands are run. - processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1], - e->params()[2], e->params()[5], e->params().last().section(" ", 1)); + processWhoInformation(e->network(), + channel, + ircuser, + e->params()[3], + e->params()[1], + e->params()[2], + e->params()[5], + e->params().last().section(" ", 1)); } // Check if channel name has a who in progress. @@ -1156,9 +1170,8 @@ void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e) } } - /* RPL_NAMREPLY */ -void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent353(IrcEvent* e) { if (!checkParamCount(e, 3)) return; @@ -1167,7 +1180,7 @@ void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e) // we don't use this information at the time beeing QString channelname = e->params()[1]; - IrcChannel *channel = e->network()->ircChannel(channelname); + IrcChannel* channel = e->network()->ircChannel(channelname); if (!channel) { qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname; return; @@ -1179,7 +1192,7 @@ void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e) // Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration. bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX); - foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) { + foreach (QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) { QString mode; if (_useCapMultiPrefix) { @@ -1194,7 +1207,8 @@ void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e) // Remove this mode from the nick nick = nick.remove(0, 1); } - } else if (e->network()->prefixes().contains(nick[0])) { + } + else if (e->network()->prefixes().contains(nick[0])) { // Multi-prefix is disabled and a mode prefix was found. mode = e->network()->prefixToMode(nick[0]); nick = nick.mid(1); @@ -1212,7 +1226,6 @@ void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e) channel->joinIrcUsers(nicks, modes); } - /* RPL_WHOSPCRPL: " 152 # ~ ("H"/ "G") :" is * if not specific to any channel @@ -1220,7 +1233,7 @@ void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e) Follows HexChat's usage of 'whox' See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750 And http://faerion.sourceforge.net/doc/irc/whox.var*/ -void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e) +void CoreSessionEventProcessor::processIrcEvent354(IrcEvent* e) { // First only check if at least one parameter exists. Otherwise, it'll stop the result from // being shown if the user chooses different parameters. @@ -1238,15 +1251,14 @@ void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e) return; QString channel = e->params()[1]; - IrcUser *ircuser = e->network()->ircUser(e->params()[5]); + IrcUser* ircuser = e->network()->ircUser(e->params()[5]); if (ircuser) { // Only process the WHO information if an IRC user exists. Don't create an IRC user here; // there's no way to track when the user quits, which would leave a phantom IrcUser lying // around. // NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an // RPL_MONONLINE numeric before any WHO commands are run. - processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2], - e->params()[3], e->params()[6], e->params().last()); + processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2], e->params()[3], e->params()[6], e->params().last()); // Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out // As part of IRCv3 account-notify, check account name @@ -1255,7 +1267,8 @@ void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e) if (newAccount != "0") { // Account logged in, set account name ircuser->setAccount(newAccount); - } else { + } + else { // Account logged out, set account name to logged-out ircuser->setAccount("*"); } @@ -1267,10 +1280,14 @@ void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e) } } - -void CoreSessionEventProcessor::processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser, - const QString &server, const QString &user, const QString &host, - const QString &awayStateAndModes, const QString &realname) +void CoreSessionEventProcessor::processWhoInformation(Network* net, + const QString& targetChannel, + IrcUser* ircUser, + const QString& server, + const QString& user, + const QString& host, + const QString& awayStateAndModes, + const QString& realname) { ircUser->setUser(user); ircUser->setHost(host); @@ -1301,7 +1318,7 @@ void CoreSessionEventProcessor::processWhoInformation (Network *net, const QStri if (!validModes.isEmpty()) { if (targetChannel != "*") { // Channel-specific modes received, apply to given channel only - IrcChannel *ircChan = net->ircChannel(targetChannel); + IrcChannel* ircChan = net->ircChannel(targetChannel); if (ircChan) { // Do one mode at a time // TODO Better way of syncing this without breaking protocol? @@ -1309,7 +1326,8 @@ void CoreSessionEventProcessor::processWhoInformation (Network *net, const QStri ircChan->addUserMode(ircUser, validModes.at(i)); } } - } else { + } + else { // Modes apply to the user everywhere ircUser->addUserModes(validModes); } @@ -1317,9 +1335,8 @@ void CoreSessionEventProcessor::processWhoInformation (Network *net, const QStri } } - /* ERR_NOSUCHCHANNEL - " :No such channel" */ -void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e) +void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric* e) { // If this is the result of an AutoWho, hide it. It's confusing to show to the user. // Though the ":No such channel" remark should always be there, we should handle cases when it's @@ -1337,7 +1354,7 @@ void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e) } /* ERR_ERRONEUSNICKNAME */ -void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e) +void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric* e) { if (!checkParamCount(e, 1)) return; @@ -1357,9 +1374,8 @@ void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e) tryNextNick(e, errnick, true /* erroneus */); } - /* ERR_NICKNAMEINUSE */ -void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e) +void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric* e) { if (!checkParamCount(e, 1)) return; @@ -1374,9 +1390,8 @@ void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e) tryNextNick(e, errnick); } - /* ERR_UNAVAILRESOURCE */ -void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e) +void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric* e) { if (!checkParamCount(e, 1)) return; @@ -1392,7 +1407,6 @@ void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e) tryNextNick(e, errnick); } - /* template void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) { if(!checkParamCount(e, 1)) @@ -1403,25 +1417,22 @@ void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) { /* Handle signals from Netsplit objects */ -void CoreSessionEventProcessor::handleNetsplitJoin(Network *net, - const QString &channel, - const QStringList &users, - const QStringList &modes, - const QString &quitMessage) +void CoreSessionEventProcessor::handleNetsplitJoin( + Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage) { - IrcChannel *ircChannel = net->ircChannel(channel); + IrcChannel* ircChannel = net->ircChannel(channel); if (!ircChannel) { return; } - QList ircUsers; + QList ircUsers; QStringList newModes = modes; QStringList newUsers = users; - foreach(const QString &user, users) { - IrcUser *iu = net->ircUser(nickFromMask(user)); + foreach (const QString& user, users) { + IrcUser* iu = net->ircUser(nickFromMask(user)); if (iu) ircUsers.append(iu); - else { // the user already quit + else { // the user already quit int idx = users.indexOf(user); newUsers.removeAt(idx); newModes.removeAt(idx); @@ -1429,36 +1440,34 @@ void CoreSessionEventProcessor::handleNetsplitJoin(Network *net, } ircChannel->joinIrcUsers(ircUsers, newModes); - NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage); + NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage); emit newEvent(event); } - -void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage) +void CoreSessionEventProcessor::handleNetsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage) { - NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage); + NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage); emit newEvent(event); - foreach(QString user, users) { - IrcUser *iu = net->ircUser(nickFromMask(user)); + foreach (QString user, users) { + IrcUser* iu = net->ircUser(nickFromMask(user)); if (iu) iu->quit(); } } - -void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes) +void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes) { - IrcChannel *ircChannel = net->ircChannel(channel); + IrcChannel* ircChannel = net->ircChannel(channel); if (!ircChannel) { qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid"; return; } - QList events; - QList ircUsers; + QList events; + QList ircUsers; QStringList newModes = modes; - foreach(QString user, users) { - IrcUser *iu = net->updateNickFromMask(user); + foreach (QString user, users) { + IrcUser* iu = net->updateNickFromMask(user); if (iu) { ircUsers.append(iu); // fake event for scripts that consume join events @@ -1469,41 +1478,38 @@ void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QStr } } ircChannel->joinIrcUsers(ircUsers, newModes); - foreach(NetworkEvent *event, events) { - event->setFlag(EventManager::Fake); // ignore this in here! + foreach (NetworkEvent* event, events) { + event->setFlag(EventManager::Fake); // ignore this in here! emit newEvent(event); } } - void CoreSessionEventProcessor::handleNetsplitFinished() { - auto *n = qobject_cast(sender()); + auto* n = qobject_cast(sender()); Q_ASSERT(n); - QHash splithash = _netsplits.take(n->network()); + QHash splithash = _netsplits.take(n->network()); splithash.remove(splithash.key(n)); if (splithash.count()) _netsplits[n->network()] = splithash; n->deleteLater(); } - void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId) { - Network *net = coreSession()->network(netId); + Network* net = coreSession()->network(netId); if (!net) return; - QHash splits = _netsplits.take(net); + QHash splits = _netsplits.take(net); qDeleteAll(splits); } - /*******************************/ /******** CTCP HANDLING ********/ /*******************************/ -void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e) +void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent* e) { if (e->testFlag(EventManager::Self)) return; // ignore ctcp events generated by user input @@ -1511,38 +1517,34 @@ void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e) if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query) return; - handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e)); + handle(e->ctcpCmd(), Q_ARG(CtcpEvent*, e)); } - -void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e) +void CoreSessionEventProcessor::defaultHandler(const QString& ctcpCmd, CtcpEvent* e) { // This handler is only there to avoid warnings for unknown CTCPs Q_UNUSED(e); Q_UNUSED(ctcpCmd); } - -void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e) +void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent* e) { // This handler is only there to feed CLIENTINFO Q_UNUSED(e); } - -void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e) +void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent* e) { QStringList supportedHandlers; - foreach(QString handler, providesHandlers()) - supportedHandlers << handler.toUpper(); + foreach (QString handler, providesHandlers()) + supportedHandlers << handler.toUpper(); qSort(supportedHandlers); e->setReply(supportedHandlers.join(" ")); } - // http://www.irchelp.org/irchelp/rfc/ctcpspec.html // http://en.wikipedia.org/wiki/Direct_Client-to-Client -void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e) +void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent* e) { // DCC support is unfinished, experimental and potentially dangerous, so make it opt-in if (!Quassel::isOptionSet("enable-experimental-dcc")) { @@ -1564,8 +1566,8 @@ void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e) QHostAddress address; quint16 port = params[3].toUShort(); quint64 size = 0; - QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon) - if (numIp.contains(':')) { // IPv6 + QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon) + if (numIp.contains(':')) { // IPv6 if (!address.setAddress(numIp)) { qWarning() << "Invalid IPv6:" << numIp; return; @@ -1575,39 +1577,48 @@ void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e) address.setAddress(numIp.toUInt()); } - if (port == 0) { // Reverse DCC is indicated by a 0 port - emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp())); + if (port == 0) { // Reverse DCC is indicated by a 0 port + emit newEvent(new MessageEvent(Message::Error, + e->network(), + tr("Reverse DCC SEND not supported"), + e->prefix(), + e->target(), + Message::None, + e->timestamp())); return; } if (port < 1024) { - qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok + qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok } - - if (params.count() > 4) { // filesize is optional + if (params.count() > 4) { // filesize is optional size = params[4].toULong(); } // TODO: check if target is the right thing to use for the partner - CoreTransfer *transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this); + CoreTransfer* transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this); coreSession()->signalProxy()->synchronize(transfer); coreSession()->transferManager()->addTransfer(transfer); } else { - emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp())); + emit newEvent(new MessageEvent(Message::Error, + e->network(), + tr("DCC %1 not supported").arg(cmd), + e->prefix(), + e->target(), + Message::None, + e->timestamp())); return; } } } - -void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e) +void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent* e) { e->setReply(e->param().isNull() ? "" : e->param()); } - -void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e) +void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent* e) { // Use the ISO standard to avoid locale-specific translated names // Include timezone offset data to show which timezone a user's in, otherwise we're providing @@ -1615,16 +1626,15 @@ void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e) e->setReply(formatDateTimeToOffsetISO(QDateTime::currentDateTime())); } - -void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e) +void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent* e) { // Deliberately do not translate project name // Use the ISO standard to avoid locale-specific translated names // Use UTC time to provide a consistent string regardless of timezone // (Statistics tracking tools usually only group client versions by exact string matching) e->setReply(QString("Quassel IRC %1 (version date %2) -- https://www.quassel-irc.org") - .arg(Quassel::buildInfo().plainVersionString) - .arg(Quassel::buildInfo().commitDate.isEmpty() ? - "unknown" : tryFormatUnixEpoch(Quassel::buildInfo().commitDate, - Qt::DateFormat::ISODate, true))); + .arg(Quassel::buildInfo().plainVersionString) + .arg(Quassel::buildInfo().commitDate.isEmpty() + ? "unknown" + : tryFormatUnixEpoch(Quassel::buildInfo().commitDate, Qt::DateFormat::ISODate, true))); } diff --git a/src/core/coresessioneventprocessor.h b/src/core/coresessioneventprocessor.h index e1d015bc..ff32574d 100644 --- a/src/core/coresessioneventprocessor.h +++ b/src/core/coresessioneventprocessor.h @@ -40,127 +40,127 @@ class CoreSessionEventProcessor : public BasicHandler Q_OBJECT public: - CoreSessionEventProcessor(CoreSession *session); - - inline CoreSession *coreSession() const { return _coreSession; } - - Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric *event); - - Q_INVOKABLE void processIrcEventAuthenticate(IrcEvent *event); /// SASL authentication - Q_INVOKABLE void processIrcEventCap(IrcEvent *event); /// CAP framework negotiation - Q_INVOKABLE void processIrcEventAccount(IrcEvent *event); /// account-notify received - Q_INVOKABLE void processIrcEventAway(IrcEvent *event); /// away-notify received - Q_INVOKABLE void processIrcEventChghost(IrcEvent *event); /// chghost received - Q_INVOKABLE void processIrcEventInvite(IrcEvent *event); - Q_INVOKABLE void processIrcEventJoin(IrcEvent *event); - Q_INVOKABLE void lateProcessIrcEventKick(IrcEvent *event); - Q_INVOKABLE void processIrcEventMode(IrcEvent *event); - Q_INVOKABLE void processIrcEventNick(IrcEvent *event); /// Nickname changes - Q_INVOKABLE void lateProcessIrcEventNick(IrcEvent *event); - Q_INVOKABLE void processIrcEventPart(IrcEvent *event); /// Leaving a channel - Q_INVOKABLE void lateProcessIrcEventPart(IrcEvent *event); - Q_INVOKABLE void processIrcEventPing(IrcEvent *event); - Q_INVOKABLE void processIrcEventPong(IrcEvent *event); - Q_INVOKABLE void processIrcEventQuit(IrcEvent *event); - Q_INVOKABLE void lateProcessIrcEventQuit(IrcEvent *event); - Q_INVOKABLE void processIrcEventTopic(IrcEvent *event); - Q_INVOKABLE void processIrcEventError(IrcEvent *event); /// ERROR message from server + CoreSessionEventProcessor(CoreSession* session); + + inline CoreSession* coreSession() const { return _coreSession; } + + Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric* event); + + Q_INVOKABLE void processIrcEventAuthenticate(IrcEvent* event); /// SASL authentication + Q_INVOKABLE void processIrcEventCap(IrcEvent* event); /// CAP framework negotiation + Q_INVOKABLE void processIrcEventAccount(IrcEvent* event); /// account-notify received + Q_INVOKABLE void processIrcEventAway(IrcEvent* event); /// away-notify received + Q_INVOKABLE void processIrcEventChghost(IrcEvent* event); /// chghost received + Q_INVOKABLE void processIrcEventInvite(IrcEvent* event); + Q_INVOKABLE void processIrcEventJoin(IrcEvent* event); + Q_INVOKABLE void lateProcessIrcEventKick(IrcEvent* event); + Q_INVOKABLE void processIrcEventMode(IrcEvent* event); + Q_INVOKABLE void processIrcEventNick(IrcEvent* event); /// Nickname changes + Q_INVOKABLE void lateProcessIrcEventNick(IrcEvent* event); + Q_INVOKABLE void processIrcEventPart(IrcEvent* event); /// Leaving a channel + Q_INVOKABLE void lateProcessIrcEventPart(IrcEvent* event); + Q_INVOKABLE void processIrcEventPing(IrcEvent* event); + Q_INVOKABLE void processIrcEventPong(IrcEvent* event); + Q_INVOKABLE void processIrcEventQuit(IrcEvent* event); + Q_INVOKABLE void lateProcessIrcEventQuit(IrcEvent* event); + Q_INVOKABLE void processIrcEventTopic(IrcEvent* event); + Q_INVOKABLE void processIrcEventError(IrcEvent* event); /// ERROR message from server #ifdef HAVE_QCA2 - Q_INVOKABLE void processKeyEvent(KeyEvent *event); + Q_INVOKABLE void processKeyEvent(KeyEvent* event); #endif - Q_INVOKABLE void processIrcEvent001(IrcEventNumeric *event); // RPL_WELCOME - Q_INVOKABLE void processIrcEvent005(IrcEvent *event); // RPL_ISUPPORT - Q_INVOKABLE void processIrcEvent221(IrcEvent *event); // RPL_UMODEIS - Q_INVOKABLE void processIrcEvent250(IrcEvent *event); // RPL_STATSCONN - Q_INVOKABLE void processIrcEvent265(IrcEvent *event); // RPL_LOCALUSERS - Q_INVOKABLE void processIrcEvent266(IrcEvent *event); // RPL_GLOBALUSERS - Q_INVOKABLE void processIrcEvent301(IrcEvent *event); // RPL_AWAY - Q_INVOKABLE void processIrcEvent305(IrcEvent *event); // RPL_UNAWAY - Q_INVOKABLE void processIrcEvent306(IrcEvent *event); // RPL_NOWAWAY - Q_INVOKABLE void processIrcEvent307(IrcEvent *event); // RPL_WHOISSERVICE - Q_INVOKABLE void processIrcEvent310(IrcEvent *event); // RPL_SUSERHOST - Q_INVOKABLE void processIrcEvent311(IrcEvent *event); // RPL_WHOISUSER - Q_INVOKABLE void processIrcEvent312(IrcEvent *event); // RPL_WHOISSERVER - Q_INVOKABLE void processIrcEvent313(IrcEvent *event); // RPL_WHOISOPERATOR - Q_INVOKABLE void processIrcEvent315(IrcEvent *event); // RPL_ENDOFWHO - Q_INVOKABLE void processIrcEvent317(IrcEvent *event); // RPL_WHOISIDLE - Q_INVOKABLE void processIrcEvent322(IrcEvent *event); // RPL_LIST - Q_INVOKABLE void processIrcEvent323(IrcEvent *event); // RPL_LISTEND - Q_INVOKABLE void processIrcEvent324(IrcEvent *event); // RPL_CHANNELMODEIS - Q_INVOKABLE void processIrcEvent330(IrcEvent *event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet) - Q_INVOKABLE void processIrcEvent331(IrcEvent *event); // RPL_NOTOPIC - Q_INVOKABLE void processIrcEvent332(IrcEvent *event); // RPL_TOPIC - Q_INVOKABLE void processIrcEvent352(IrcEvent *event); // RPL_WHOREPLY - Q_INVOKABLE void processIrcEvent353(IrcEvent *event); // RPL_NAMREPLY - Q_INVOKABLE void processIrcEvent354(IrcEvent *event); // RPL_WHOSPCRPL - Q_INVOKABLE void processIrcEvent403(IrcEventNumeric *event); // ERR_NOSUCHCHANNEL - Q_INVOKABLE void processIrcEvent432(IrcEventNumeric *event); // ERR_ERRONEUSNICKNAME - Q_INVOKABLE void processIrcEvent433(IrcEventNumeric *event); // ERR_NICKNAMEINUSE - Q_INVOKABLE void processIrcEvent437(IrcEventNumeric *event); // ERR_UNAVAILRESOURCE + Q_INVOKABLE void processIrcEvent001(IrcEventNumeric* event); // RPL_WELCOME + Q_INVOKABLE void processIrcEvent005(IrcEvent* event); // RPL_ISUPPORT + Q_INVOKABLE void processIrcEvent221(IrcEvent* event); // RPL_UMODEIS + Q_INVOKABLE void processIrcEvent250(IrcEvent* event); // RPL_STATSCONN + Q_INVOKABLE void processIrcEvent265(IrcEvent* event); // RPL_LOCALUSERS + Q_INVOKABLE void processIrcEvent266(IrcEvent* event); // RPL_GLOBALUSERS + Q_INVOKABLE void processIrcEvent301(IrcEvent* event); // RPL_AWAY + Q_INVOKABLE void processIrcEvent305(IrcEvent* event); // RPL_UNAWAY + Q_INVOKABLE void processIrcEvent306(IrcEvent* event); // RPL_NOWAWAY + Q_INVOKABLE void processIrcEvent307(IrcEvent* event); // RPL_WHOISSERVICE + Q_INVOKABLE void processIrcEvent310(IrcEvent* event); // RPL_SUSERHOST + Q_INVOKABLE void processIrcEvent311(IrcEvent* event); // RPL_WHOISUSER + Q_INVOKABLE void processIrcEvent312(IrcEvent* event); // RPL_WHOISSERVER + Q_INVOKABLE void processIrcEvent313(IrcEvent* event); // RPL_WHOISOPERATOR + Q_INVOKABLE void processIrcEvent315(IrcEvent* event); // RPL_ENDOFWHO + Q_INVOKABLE void processIrcEvent317(IrcEvent* event); // RPL_WHOISIDLE + Q_INVOKABLE void processIrcEvent322(IrcEvent* event); // RPL_LIST + Q_INVOKABLE void processIrcEvent323(IrcEvent* event); // RPL_LISTEND + Q_INVOKABLE void processIrcEvent324(IrcEvent* event); // RPL_CHANNELMODEIS + Q_INVOKABLE void processIrcEvent330(IrcEvent* event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet) + Q_INVOKABLE void processIrcEvent331(IrcEvent* event); // RPL_NOTOPIC + Q_INVOKABLE void processIrcEvent332(IrcEvent* event); // RPL_TOPIC + Q_INVOKABLE void processIrcEvent352(IrcEvent* event); // RPL_WHOREPLY + Q_INVOKABLE void processIrcEvent353(IrcEvent* event); // RPL_NAMREPLY + Q_INVOKABLE void processIrcEvent354(IrcEvent* event); // RPL_WHOSPCRPL + Q_INVOKABLE void processIrcEvent403(IrcEventNumeric* event); // ERR_NOSUCHCHANNEL + Q_INVOKABLE void processIrcEvent432(IrcEventNumeric* event); // ERR_ERRONEUSNICKNAME + Q_INVOKABLE void processIrcEvent433(IrcEventNumeric* event); // ERR_NICKNAMEINUSE + Q_INVOKABLE void processIrcEvent437(IrcEventNumeric* event); // ERR_UNAVAILRESOURCE // Q_INVOKABLE void processIrcEvent(IrcEvent *event); /* CTCP handlers */ - Q_INVOKABLE void processCtcpEvent(CtcpEvent *event); + Q_INVOKABLE void processCtcpEvent(CtcpEvent* event); - Q_INVOKABLE void handleCtcpAction(CtcpEvent *event); - Q_INVOKABLE void handleCtcpClientinfo(CtcpEvent *event); - Q_INVOKABLE void handleCtcpDcc(CtcpEvent *event); - Q_INVOKABLE void handleCtcpPing(CtcpEvent *event); - Q_INVOKABLE void handleCtcpTime(CtcpEvent *event); - Q_INVOKABLE void handleCtcpVersion(CtcpEvent *event); - Q_INVOKABLE void defaultHandler(const QString &ctcpCmd, CtcpEvent *event); + Q_INVOKABLE void handleCtcpAction(CtcpEvent* event); + Q_INVOKABLE void handleCtcpClientinfo(CtcpEvent* event); + Q_INVOKABLE void handleCtcpDcc(CtcpEvent* event); + Q_INVOKABLE void handleCtcpPing(CtcpEvent* event); + Q_INVOKABLE void handleCtcpTime(CtcpEvent* event); + Q_INVOKABLE void handleCtcpVersion(CtcpEvent* event); + Q_INVOKABLE void defaultHandler(const QString& ctcpCmd, CtcpEvent* event); signals: - void newEvent(Event *event); + void newEvent(Event* event); protected: - bool checkParamCount(IrcEvent *event, int minParams); - inline CoreNetwork *coreNetwork(NetworkEvent *e) const { return qobject_cast(e->network()); } - void tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneous = false); + bool checkParamCount(IrcEvent* event, int minParams); + inline CoreNetwork* coreNetwork(NetworkEvent* e) const { return qobject_cast(e->network()); } + void tryNextNick(NetworkEvent* e, const QString& errnick, bool erroneous = false); private slots: //! Joins after a netsplit /** This slot handles a bulk-join after a netsplit is over - * \param net The network - * \param channel The channel the users joined - * \param users The list of users that joind the channel - * \param modes The list of modes the users get set - * \param quitMessage The message we received when the netsplit occured - */ - void handleNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes, const QString &quitMessage); + * \param net The network + * \param channel The channel the users joined + * \param users The list of users that joind the channel + * \param modes The list of modes the users get set + * \param quitMessage The message we received when the netsplit occured + */ + void handleNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage); //! Quits after a netsplit /** This slot handles a bulk-quit after a netsplit occured - * \param net The network - * \param channel The channel the users quitted - * \param users The list of users that got split - * \param quitMessage The message we received when the netsplit occured - */ - void handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage); + * \param net The network + * \param channel The channel the users quitted + * \param users The list of users that got split + * \param quitMessage The message we received when the netsplit occured + */ + void handleNetsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage); //! Netsplit finished /** This slot deletes the netsplit object that sent the finished() signal - */ + */ void handleNetsplitFinished(); - void handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes); + void handleEarlyNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes); //! Destroy any existing netsplits /** This slot deletes all netsplit objects - * Used to get rid of existing netsplits on network reconnect - * \param network The network we want to clear - */ + * Used to get rid of existing netsplits on network reconnect + * \param network The network we want to clear + */ void destroyNetsplits(NetworkId network); private: - CoreSession *_coreSession; + CoreSession* _coreSession; // structure to organize netsplits // key: quit message // value: the corresponding netsplit object - QHash > _netsplits; + QHash> _netsplits; /** * Process given WHO reply information, updating user data, channel modes, etc as needed @@ -177,10 +177,14 @@ private: * @param[in] awayStateAndModes Nick away-state and modes (e.g. G@) * @param[in] realname Nick realname */ - void processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser, - const QString &server, const QString &user, const QString &host, - const QString &awayStateAndModes, const QString &realname); + void processWhoInformation(Network* net, + const QString& targetChannel, + IrcUser* ircUser, + const QString& server, + const QString& user, + const QString& host, + const QString& awayStateAndModes, + const QString& realname); }; - #endif diff --git a/src/core/coresettings.cpp b/src/core/coresettings.cpp index 8ba20c51..1878f684 100644 --- a/src/core/coresettings.cpp +++ b/src/core/coresettings.cpp @@ -24,29 +24,24 @@ CoreSettings::CoreSettings(QString group) : Settings(std::move(group), Quassel::buildInfo().coreApplicationName) -{ -} +{} - -void CoreSettings::setStorageSettings(const QVariant &data) +void CoreSettings::setStorageSettings(const QVariant& data) { setLocalValue("StorageSettings", data); } - -QVariant CoreSettings::storageSettings(const QVariant &def) const +QVariant CoreSettings::storageSettings(const QVariant& def) const { return localValue("StorageSettings", def); } - -void CoreSettings::setAuthSettings(const QVariant &data) +void CoreSettings::setAuthSettings(const QVariant& data) { setLocalValue("AuthSettings", data); } - -QVariant CoreSettings::authSettings(const QVariant &def) const +QVariant CoreSettings::authSettings(const QVariant& def) const { return localValue("AuthSettings", def); } @@ -57,14 +52,12 @@ QVariant CoreSettings::oldDbSettings() const return localValue("DatabaseSettings"); } - -void CoreSettings::setCoreState(const QVariant &data) +void CoreSettings::setCoreState(const QVariant& data) { setLocalValue("CoreState", data); } - -QVariant CoreSettings::coreState(const QVariant &def) const +QVariant CoreSettings::coreState(const QVariant& def) const { return localValue("CoreState", def); } diff --git a/src/core/coresettings.h b/src/core/coresettings.h index 3c05ba16..70512525 100644 --- a/src/core/coresettings.h +++ b/src/core/coresettings.h @@ -27,14 +27,14 @@ class CoreSettings : public Settings public: CoreSettings(QString group = "Core"); - void setStorageSettings(const QVariant &data); - QVariant storageSettings(const QVariant &def = {}) const; + void setStorageSettings(const QVariant& data); + QVariant storageSettings(const QVariant& def = {}) const; - void setAuthSettings(const QVariant &data); - QVariant authSettings(const QVariant &def = {}) const; + void setAuthSettings(const QVariant& data); + QVariant authSettings(const QVariant& def = {}) const; QVariant oldDbSettings() const; // FIXME remove - void setCoreState(const QVariant &data); - QVariant coreState(const QVariant &def = {}) const; + void setCoreState(const QVariant& data); + QVariant coreState(const QVariant& def = {}) const; }; diff --git a/src/core/coretransfer.cpp b/src/core/coretransfer.cpp index e178cdab..b2993b73 100644 --- a/src/core/coretransfer.cpp +++ b/src/core/coretransfer.cpp @@ -18,32 +18,34 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include +#include "coretransfer.h" #include #include +#include -#include "coretransfer.h" #include "util.h" const qint64 chunkSize = 16 * 1024; -CoreTransfer::CoreTransfer(Direction direction, const QString &nick, const QString &fileName, const QHostAddress &address, quint16 port, quint64 fileSize, QObject *parent) - : Transfer(direction, nick, fileName, address, port, fileSize, parent), - _socket(nullptr), - _pos(0), - _reading(false) -{ - -} - +CoreTransfer::CoreTransfer(Direction direction, + const QString& nick, + const QString& fileName, + const QHostAddress& address, + quint16 port, + quint64 fileSize, + QObject* parent) + : Transfer(direction, nick, fileName, address, port, fileSize, parent) + , _socket(nullptr) + , _pos(0) + , _reading(false) +{} quint64 CoreTransfer::transferred() const { return _pos; } - void CoreTransfer::cleanUp() { if (_socket) { @@ -56,7 +58,6 @@ void CoreTransfer::cleanUp() _reading = false; } - void CoreTransfer::onSocketDisconnected() { if (status() == Status::Connecting || status() == Status::Transferring) { @@ -66,7 +67,6 @@ void CoreTransfer::onSocketDisconnected() cleanUp(); } - void CoreTransfer::onSocketError(QAbstractSocket::SocketError error) { Q_UNUSED(error) @@ -76,11 +76,10 @@ void CoreTransfer::onSocketError(QAbstractSocket::SocketError error) } } - void CoreTransfer::requestAccepted(PeerPtr peer) { if (_peer || !peer || status() != Status::New) - return; // transfer was already accepted + return; // transfer was already accepted _peer = peer; setStatus(Status::Pending); @@ -91,7 +90,6 @@ void CoreTransfer::requestAccepted(PeerPtr peer) start(); } - void CoreTransfer::requestRejected(PeerPtr peer) { if (_peer || status() != Status::New) @@ -103,7 +101,6 @@ void CoreTransfer::requestRejected(PeerPtr peer) emit rejected(peer); } - void CoreTransfer::start() { if (!_peer || status() != Status::Pending || direction() != Direction::Receive) @@ -112,7 +109,6 @@ void CoreTransfer::start() setupConnectionForReceive(); } - void CoreTransfer::setupConnectionForReceive() { if (port() == 0) { @@ -131,16 +127,14 @@ void CoreTransfer::setupConnectionForReceive() _socket->connectToHost(address(), port()); } - void CoreTransfer::startReceiving() { setStatus(Status::Transferring); } - void CoreTransfer::onDataReceived() { - if (_reading) // since we're spinning the event loop, we may get another readyRead() and thus reentrancy + if (_reading) // since we're spinning the event loop, we may get another readyRead() and thus reentrancy return; _reading = true; @@ -152,14 +146,14 @@ void CoreTransfer::onDataReceived() return; QCoreApplication::processEvents(); // don't block the rest of the core/client communication - if (!_socket) // just in case something happened during spinning the event loop that killed our socket + if (!_socket) // just in case something happened during spinning the event loop that killed our socket return; } // Send ack to sender. The DCC protocol only specifies 32 bit values, but modern clients (i.e. those who can send files // larger than 4 GB) will ignore this anyway... - quint32 ack = qToBigEndian((quint32)_pos);// qDebug() << Q_FUNC_INFO << _pos; - _socket->write((char *)&ack, 4); + quint32 ack = qToBigEndian((quint32)_pos); // qDebug() << Q_FUNC_INFO << _pos; + _socket->write((char*)&ack, 4); if (_pos > fileSize()) { qWarning() << "DCC Receive: Got more data than expected!"; @@ -167,15 +161,14 @@ void CoreTransfer::onDataReceived() } else if (_pos == fileSize()) { qDebug() << "DCC Receive: Transfer finished"; - if (relayData(QByteArray(), false)) // empty buffer + if (relayData(QByteArray(), false)) // empty buffer setStatus(Status::Completed); } _reading = false; } - -bool CoreTransfer::relayData(const QByteArray &data, bool requireChunkSize) +bool CoreTransfer::relayData(const QByteArray& data, bool requireChunkSize) { // safeguard against a disconnecting quasselclient if (!_peer) { @@ -186,7 +179,7 @@ bool CoreTransfer::relayData(const QByteArray &data, bool requireChunkSize) // we only want to send data to the client once we have reached the chunksize if (_buffer.size() > 0 && (_buffer.size() >= chunkSize || !requireChunkSize)) { - Peer *p = _peer.data(); + Peer* p = _peer.data(); SYNC_OTHER(dataReceived, ARG(p), ARG(_buffer)); _buffer.clear(); } diff --git a/src/core/coretransfer.h b/src/core/coretransfer.h index 02c21c88..831c5600 100644 --- a/src/core/coretransfer.h +++ b/src/core/coretransfer.h @@ -22,8 +22,8 @@ #include -#include "transfer.h" #include "peer.h" +#include "transfer.h" class QTcpSocket; @@ -32,7 +32,13 @@ class CoreTransfer : public Transfer Q_OBJECT public: - CoreTransfer(Direction direction, const QString &nick, const QString &fileName, const QHostAddress &address, quint16 port, quint64 size = 0, QObject *parent = nullptr); + CoreTransfer(Direction direction, + const QString& nick, + const QString& fileName, + const QHostAddress& address, + quint16 port, + quint64 size = 0, + QObject* parent = nullptr); quint64 transferred() const override; @@ -51,11 +57,11 @@ private slots: private: void setupConnectionForReceive(); - bool relayData(const QByteArray &data, bool requireChunkSize); + bool relayData(const QByteArray& data, bool requireChunkSize); void cleanUp() override; QPointer _peer; - QTcpSocket *_socket; + QTcpSocket* _socket; quint64 _pos; QByteArray _buffer; bool _reading; diff --git a/src/core/coreuserinputhandler.cpp b/src/core/coreuserinputhandler.cpp index 0b3b2b0a..c17ea809 100644 --- a/src/core/coreuserinputhandler.cpp +++ b/src/core/coreuserinputhandler.cpp @@ -20,23 +20,20 @@ #include "coreuserinputhandler.h" -#include "util.h" +#include #include "ctcpparser.h" - -#include +#include "util.h" #ifdef HAVE_QCA2 -# include "cipher.h" +# include "cipher.h" #endif -CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent) +CoreUserInputHandler::CoreUserInputHandler(CoreNetwork* parent) : CoreBasicHandler(parent) -{ -} - +{} -void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleUserInput(const BufferInfo& bufferInfo, const QString& msg) { if (msg.isEmpty()) return; @@ -50,12 +47,10 @@ void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const Q } } - // ==================== // Public Slots // ==================== -void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg, - const bool skipFormatting) +void CoreUserInputHandler::handleAway(const BufferInfo& bufferInfo, const QString& msg, const bool skipFormatting) { Q_UNUSED(bufferInfo) if (msg.startsWith("-all")) { @@ -72,11 +67,10 @@ void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QStrin issueAway(msg, true /* force away */, skipFormatting); } - -void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck, const bool skipFormatting) +void CoreUserInputHandler::issueAway(const QString& msg, bool autoCheck, const bool skipFormatting) { QString awayMsg = msg; - IrcUser *me = network()->me(); + IrcUser* me = network()->me(); // Only apply timestamp formatting when requested // This avoids re-processing any existing away message when the core restarts, so chained escape @@ -89,7 +83,7 @@ void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck, const b // if there is no message supplied we have to check if we are already away or not if (autoCheck && msg.isEmpty()) { if (me && !me->isAway()) { - Identity *identity = network()->identityPtr(); + Identity* identity = network()->identityPtr(); if (identity) { awayMsg = formatCurrentDateTimeInString(identity->awayReason()); } @@ -104,20 +98,17 @@ void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck, const b putCmd("AWAY", serverEncode(awayMsg)); } - -void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleBan(const BufferInfo& bufferInfo, const QString& msg) { banOrUnban(bufferInfo, msg, true); } - -void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleUnban(const BufferInfo& bufferInfo, const QString& msg) { banOrUnban(bufferInfo, msg, false); } - -void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) +void CoreUserInputHandler::banOrUnban(const BufferInfo& bufferInfo, const QString& msg, bool ban) { QString banChannel; QString banUser; @@ -136,7 +127,7 @@ void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QStrin } if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) { - IrcUser *ircuser = network()->ircUser(params[0]); + IrcUser* ircuser = network()->ircUser(params[0]); // generalizedHost changes to *!ident@*.sld.tld. QString generalizedHost = ircuser->host(); if (generalizedHost.isEmpty()) { @@ -145,12 +136,12 @@ void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QStrin } static QRegExp ipAddress(R"(\d+\.\d+\.\d+\.\d+)"); - if (ipAddress.exactMatch(generalizedHost)) { + if (ipAddress.exactMatch(generalizedHost)) { int lastDotPos = generalizedHost.lastIndexOf('.') + 1; generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*'); } - else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) { - int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1); + else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".") - 1) != -1) { + int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".") - 1); generalizedHost.replace(0, secondLastPeriodPosition, "*"); } banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost); @@ -164,8 +155,7 @@ void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QStrin emit putRawLine(serverEncode(banMsg)); } - -void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleCtcp(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) @@ -183,12 +173,10 @@ void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QStrin // FIXME make this a proper event coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message); - emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, - network()->myNick(), Message::Flag::Self); + emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick(), Message::Flag::Self); } - -void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleDelkey(const BufferInfo& bufferInfo, const QString& msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 @@ -196,7 +184,10 @@ void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QStr return; if (!Cipher::neededFeaturesAvailable()) { - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } @@ -206,8 +197,11 @@ void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QStr parms.prepend(bufferInfo.bufferName()); if (parms.isEmpty()) { - emit displayMsg(Message::Info, typeByTarget(bufname), bufname, - tr("[usage] /delkey deletes the encryption key for nick or channel or just /delkey when in a channel or query.")); + emit displayMsg(Message::Info, + typeByTarget(bufname), + bufname, + tr("[usage] /delkey deletes the encryption key for nick or channel or just /delkey when in a " + "channel or query.")); return; } @@ -223,81 +217,86 @@ void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QStr #else Q_UNUSED(msg) - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " - "with support for the Qt Cryptographic Architecture (QCA2) library. " - "Contact your distributor about a Quassel package with QCA2 " - "support, or rebuild Quassel with QCA2 present.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: Setting an encryption key requires Quassel to have been built " + "with support for the Qt Cryptographic Architecture (QCA2) library. " + "Contact your distributor about a Quassel package with QCA2 " + "support, or rebuild Quassel with QCA2 present.")); #endif } -void CoreUserInputHandler::doMode(const BufferInfo &bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString &nicks) +void CoreUserInputHandler::doMode(const BufferInfo& bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString& nicks) { QString m; bool isNumber; int maxModes = network()->support("MODES").toInt(&isNumber); - if (!isNumber || maxModes == 0) maxModes = 1; + if (!isNumber || maxModes == 0) + maxModes = 1; QStringList nickList; - if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) { // All users in channel + if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) { // All users in channel const QList users = network()->ircChannel(bufferInfo.bufferName())->ircUsers(); - foreach(IrcUser *user, users) { + foreach (IrcUser* user, users) { if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)) || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))) nickList.append(user->nick()); } - } else { + } + else { nickList = nicks.split(' ', QString::SkipEmptyParts); } - if (nickList.count() == 0) return; + if (nickList.count() == 0) + return; while (!nickList.isEmpty()) { int amount = qMin(nickList.count(), maxModes); - QString m = addOrRemove; for(int i = 0; i < amount; i++) m += mode; + QString m = addOrRemove; + for (int i = 0; i < amount; i++) + m += mode; QStringList params; params << bufferInfo.bufferName() << m; - for(int i = 0; i < amount; i++) params << nickList.takeFirst(); + for (int i = 0; i < amount; i++) + params << nickList.takeFirst(); emit putCmd("MODE", serverEncode(params)); } } - -void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &nicks) +void CoreUserInputHandler::handleDeop(const BufferInfo& bufferInfo, const QString& nicks) { doMode(bufferInfo, '-', 'o', nicks); } - -void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &nicks) +void CoreUserInputHandler::handleDehalfop(const BufferInfo& bufferInfo, const QString& nicks) { doMode(bufferInfo, '-', 'h', nicks); } - -void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &nicks) +void CoreUserInputHandler::handleDevoice(const BufferInfo& bufferInfo, const QString& nicks) { doMode(bufferInfo, '-', 'v', nicks); } -void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &nicks) +void CoreUserInputHandler::handleHalfop(const BufferInfo& bufferInfo, const QString& nicks) { doMode(bufferInfo, '+', 'h', nicks); } -void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &nicks) { - doMode(bufferInfo, '+', 'o', nicks); +void CoreUserInputHandler::handleOp(const BufferInfo& bufferInfo, const QString& nicks) +{ + doMode(bufferInfo, '+', 'o', nicks); } - -void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleInvite(const BufferInfo& bufferInfo, const QString& msg) { QStringList params; params << msg << bufferInfo.bufferName(); emit putCmd("INVITE", serverEncode(params)); } - -void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleJoin(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo); @@ -324,7 +323,7 @@ void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QStrin } } - static const char *cmd = "JOIN"; + static const char* cmd = "JOIN"; i = 0; QStringList joinChans, joinKeys; int slicesize = chans.count(); @@ -358,8 +357,7 @@ void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QStrin } } - -void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleKeyx(const BufferInfo& bufferInfo, const QString& msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 @@ -367,7 +365,10 @@ void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QStrin return; if (!Cipher::neededFeaturesAvailable()) { - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } @@ -376,8 +377,10 @@ void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QStrin if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); else if (parms.count() != 1) { - emit displayMsg(Message::Info, typeByTarget(bufname), bufname, - tr("[usage] /keyx [] Initiates a DH1080 key exchange with the target.")); + emit displayMsg(Message::Info, + typeByTarget(bufname), + bufname, + tr("[usage] /keyx [] Initiates a DH1080 key exchange with the target.")); return; } @@ -388,8 +391,8 @@ void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QStrin return; } - Cipher *cipher = network()->cipher(target); - if (!cipher) // happens when there is no CoreIrcChannel for the target + Cipher* cipher = network()->cipher(target); + if (!cipher) // happens when there is no CoreIrcChannel for the target return; QByteArray pubKey = cipher->initKeyExchange(); @@ -403,15 +406,17 @@ void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QStrin } #else Q_UNUSED(msg) - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " - "with support for the Qt Cryptographic Architecture (QCA) library. " - "Contact your distributor about a Quassel package with QCA " - "support, or rebuild Quassel with QCA present.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: Setting an encryption key requires Quassel to have been built " + "with support for the Qt Cryptographic Architecture (QCA) library. " + "Contact your distributor about a Quassel package with QCA " + "support, or rebuild Quassel with QCA present.")); #endif } - -void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleKick(const BufferInfo& bufferInfo, const QString& msg) { QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty); QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed(); @@ -423,8 +428,7 @@ void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QStrin emit putCmd("KICK", params); } - -void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleKill(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty); @@ -434,15 +438,13 @@ void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QStrin emit putCmd("KILL", params); } - -void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleList(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts))); } - -void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleMe(const BufferInfo& bufferInfo, const QString& msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer @@ -454,15 +456,12 @@ void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString foreach (auto message, messages) { // Handle each separated message independently - coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), - "ACTION", message); - emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), message, - network()->myNick(), Message::Self); + coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", message); + emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), message, network()->myNick(), Message::Self); } } - -void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleMode(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) @@ -470,16 +469,14 @@ void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QStrin if (!params.isEmpty()) { if (params[0] == "-reset" && params.count() == 1) { network()->resetPersistentModes(); - emit displayMsg(Message::Info, BufferInfo::StatusBuffer, "", - tr("Your persistent modes have been reset.")); + emit displayMsg(Message::Info, BufferInfo::StatusBuffer, "", tr("Your persistent modes have been reset.")); return; } if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0])) // If the first argument is neither a channel nor us (user modes are only to oneself) // the current buffer is assumed to be the target. // If the current buffer returns no name (e.g. status buffer), assume target is us. - params.prepend(!bufferInfo.bufferName().isEmpty() ? - bufferInfo.bufferName() : network()->myNick()); + params.prepend(!bufferInfo.bufferName().isEmpty() ? bufferInfo.bufferName() : network()->myNick()); if (network()->isMyNick(params[0]) && params.count() == 2) network()->updateIssuedModes(params[1]); } @@ -488,9 +485,8 @@ void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QStrin emit putCmd("MODE", serverEncode(params)); } - // TODO: show privmsgs -void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleMsg(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo); if (!msg.contains(' ')) @@ -499,9 +495,8 @@ void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString QString target = msg.section(' ', 0, 0); QString msgSection = msg.section(' ', 1); - std::function encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray { - return userEncode(target, message); - }; + std::function encodeFunc = + [this](const QString& target, const QString& message) -> QByteArray { return userEncode(target, message); }; #ifdef HAVE_QCA2 putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target)); @@ -510,16 +505,14 @@ void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString #endif } - -void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleNick(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0); emit putCmd("NICK", serverEncode(nick)); } - -void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleNotice(const BufferInfo& bufferInfo, const QString& msg) { QString bufferName = msg.section(' ', 0, 0); QList params; @@ -532,21 +525,17 @@ void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QStr params.clear(); params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message); emit putCmd("NOTICE", params); - emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, message, - network()->myNick(), Message::Self); + emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, message, network()->myNick(), Message::Self); } } - - -void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleOper(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) emit putRawLine(serverEncode(QString("OPER %1").arg(msg))); } - -void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handlePart(const BufferInfo& bufferInfo, const QString& msg) { QList params; QString partReason; @@ -568,8 +557,7 @@ void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QStrin emit putCmd("PART", params); } - -void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handlePing(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) @@ -581,8 +569,7 @@ void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QStrin putCmd("PING", serverEncode(param), QByteArray(), true); } - -void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handlePrint(const BufferInfo& bufferInfo, const QString& msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer @@ -591,9 +578,8 @@ void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QStri emit displayMsg(Message::Info, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); } - // TODO: implement queries -void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleQuery(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) QString target = msg.section(' ', 0, 0); @@ -604,49 +590,47 @@ void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QStri foreach (auto message, messages) { // Handle each separated message independently if (message.isEmpty()) { - emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, - tr("Starting query with %1").arg(target), network()->myNick(), + emit displayMsg(Message::Server, + BufferInfo::QueryBuffer, + target, + tr("Starting query with %1").arg(target), + network()->myNick(), Message::Self); // handleMsg is a no-op if message is empty - } else { - emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, - network()->myNick(), Message::Self); + } + else { + emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self); // handleMsg needs the target specified at the beginning of the message handleMsg(bufferInfo, target + " " + message); } } } - -void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleQuit(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) network()->disconnectFromIrc(true, msg); } - -void CoreUserInputHandler::issueQuit(const QString &reason, bool forceImmediate) +void CoreUserInputHandler::issueQuit(const QString& reason, bool forceImmediate) { // If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue emit putCmd("QUIT", serverEncode(reason), QByteArray(), forceImmediate); } - -void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleQuote(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) emit putRawLine(serverEncode(msg)); } - -void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleSay(const BufferInfo& bufferInfo, const QString& msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer - std::function encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray { - return channelEncode(target, message); - }; + std::function encodeFunc = + [this](const QString& target, const QString& message) -> QByteArray { return channelEncode(target, message); }; // Split apart messages at line feeds. The IRC protocol uses those to separate commands, so // they need to be split into multiple messages. @@ -655,18 +639,15 @@ void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString foreach (auto message, messages) { // Handle each separated message independently #ifdef HAVE_QCA2 - putPrivmsg(bufferInfo.bufferName(), message, encodeFunc, - network()->cipher(bufferInfo.bufferName())); + putPrivmsg(bufferInfo.bufferName(), message, encodeFunc, network()->cipher(bufferInfo.bufferName())); #else putPrivmsg(bufferInfo.bufferName(), message, encodeFunc); #endif - emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), message, - network()->myNick(), Message::Self); + emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), message, network()->myNick(), Message::Self); } } - -void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleSetkey(const BufferInfo& bufferInfo, const QString& msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 @@ -674,7 +655,10 @@ void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QStr return; if (!Cipher::neededFeaturesAvailable()) { - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } @@ -683,9 +667,11 @@ void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QStr if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); else if (parms.count() != 2) { - emit displayMsg(Message::Info, typeByTarget(bufname), bufname, - tr("[usage] /setkey sets the encryption key for nick or channel. " - "/setkey when in a channel or query buffer sets the key for it.")); + emit displayMsg(Message::Info, + typeByTarget(bufname), + bufname, + tr("[usage] /setkey sets the encryption key for nick or channel. " + "/setkey when in a channel or query buffer sets the key for it.")); return; } @@ -696,15 +682,17 @@ void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QStr emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target)); #else Q_UNUSED(msg) - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " - "with support for the Qt Cryptographic Architecture (QCA) library. " - "Contact your distributor about a Quassel package with QCA " - "support, or rebuild Quassel with QCA present.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: Setting an encryption key requires Quassel to have been built " + "with support for the Qt Cryptographic Architecture (QCA) library. " + "Contact your distributor about a Quassel package with QCA " + "support, or rebuild Quassel with QCA present.")); #endif } - -void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleShowkey(const BufferInfo& bufferInfo, const QString& msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 @@ -712,7 +700,10 @@ void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QSt return; if (!Cipher::neededFeaturesAvailable()) { - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } @@ -722,7 +713,11 @@ void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QSt parms.prepend(bufferInfo.bufferName()); if (parms.isEmpty()) { - emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /showkey shows the encryption key for nick or channel or just /showkey when in a channel or query.")); + emit displayMsg(Message::Info, + typeByTarget(bufname), + bufname, + tr("[usage] /showkey shows the encryption key for nick or channel or just /showkey when in a " + "channel or query.")); return; } @@ -734,19 +729,24 @@ void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QSt return; } - emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))); + emit displayMsg(Message::Info, + typeByTarget(bufname), + bufname, + tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))); #else Q_UNUSED(msg) - emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " - "with support for the Qt Cryptographic Architecture (QCA2) library. " - "Contact your distributor about a Quassel package with QCA2 " - "support, or rebuild Quassel with QCA2 present.")); + emit displayMsg(Message::Error, + typeByTarget(bufname), + bufname, + tr("Error: Setting an encryption key requires Quassel to have been built " + "with support for the Qt Cryptographic Architecture (QCA2) library. " + "Contact your distributor about a Quassel package with QCA2 " + "support, or rebuild Quassel with QCA2 present.")); #endif } - -void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleTopic(const BufferInfo& bufferInfo, const QString& msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; @@ -755,28 +755,28 @@ void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QStri params << serverEncode(bufferInfo.bufferName()); if (!msg.isEmpty()) { -# ifdef HAVE_QCA2 +#ifdef HAVE_QCA2 params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg)); -# else +#else params << channelEncode(bufferInfo.bufferName(), msg); -# endif +#endif } emit putCmd("TOPIC", params); } - -void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleVoice(const BufferInfo& bufferInfo, const QString& msg) { QStringList nicks = msg.split(' ', QString::SkipEmptyParts); - QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v'; + QString m = "+"; + for (int i = 0; i < nicks.count(); i++) + m += 'v'; QStringList params; params << bufferInfo.bufferName() << m << nicks; emit putCmd("MODE", serverEncode(params)); } - -void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleWait(const BufferInfo& bufferInfo, const QString& msg) { int splitPos = msg.indexOf(';'); if (splitPos <= 0) @@ -796,42 +796,40 @@ void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QStrin _delayedCommands[startTimer(delay)] = Command(bufferInfo, command); } - -void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleWho(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) emit putCmd("WHO", serverEncode(msg.split(' '))); } - -void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleWhois(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) emit putCmd("WHOIS", serverEncode(msg.split(' '))); } - -void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::handleWhowas(const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo) emit putCmd("WHOWAS", serverEncode(msg.split(' '))); } - -void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) +void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& msg) { Q_UNUSED(bufferInfo); emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" "))); } - -void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function encodeFunc, Cipher *cipher) +void CoreUserInputHandler::putPrivmsg(const QString& target, + const QString& message, + std::function encodeFunc, + Cipher* cipher) { Q_UNUSED(cipher); QString cmd("PRIVMSG"); QByteArray targetEnc = serverEncode(target); - std::function(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList { + std::function(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList { QByteArray splitMsgEnc = encodeFunc(target, splitMsg); #ifdef HAVE_QCA2 @@ -845,26 +843,27 @@ void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &mess putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator)); } - // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long -int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList ¶ms) +int CoreUserInputHandler::lastParamOverrun(const QString& cmd, const QList& params) { // the server will pass our message truncated to 512 bytes including CRLF with the following format: // ":prefix COMMAND param0 param1 :lastparam" // where prefix = "nickname!user@host" // that means that the last message can be as long as: - // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param) - IrcUser *me = network()->me(); - int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?) + // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and + // command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param) + IrcUser* me = network()->me(); + int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?) if (me) - maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toLatin1().count() - 6; + maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() + - cmd.toLatin1().count() - 6; if (!params.isEmpty()) { for (int i = 0; i < params.count() - 1; i++) { maxLen -= (params[i].count() + 1); } - maxLen -= 2; // " :" last param separator; + maxLen -= 2; // " :" last param separator; if (params.last().count() > maxLen) { return params.last().count() - maxLen; @@ -878,9 +877,8 @@ int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QListcipher(target); + Cipher* cipher = network()->cipher(target); if (!cipher || cipher->key().isEmpty()) return message_; @@ -903,10 +901,9 @@ QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray return message; } - #endif -void CoreUserInputHandler::timerEvent(QTimerEvent *event) +void CoreUserInputHandler::timerEvent(QTimerEvent* event) { if (!_delayedCommands.contains(event->timerId())) { QObject::timerEvent(event); @@ -919,7 +916,7 @@ void CoreUserInputHandler::timerEvent(QTimerEvent *event) // the stored command might be the result of an alias expansion, so we need to split it up again QStringList commands = rawCommand.split(QRegExp("; ?")); - foreach(QString command, commands) { + foreach (QString command, commands) { handleUserInput(bufferInfo, command); } } diff --git a/src/core/coreuserinputhandler.h b/src/core/coreuserinputhandler.h index a45fcaec..0c1be566 100644 --- a/src/core/coreuserinputhandler.h +++ b/src/core/coreuserinputhandler.h @@ -34,11 +34,11 @@ class CoreUserInputHandler : public CoreBasicHandler Q_OBJECT public: - CoreUserInputHandler(CoreNetwork *parent = nullptr); - inline CoreNetwork *coreNetwork() const { return qobject_cast(parent()); } + CoreUserInputHandler(CoreNetwork* parent = nullptr); + inline CoreNetwork* coreNetwork() const { return qobject_cast(parent()); } - void handleUserInput(const BufferInfo &bufferInfo, const QString &text); - int lastParamOverrun(const QString &cmd, const QList ¶ms); + void handleUserInput(const BufferInfo& bufferInfo, const QString& text); + int lastParamOverrun(const QString& cmd, const QList& params); public slots: /** @@ -50,46 +50,45 @@ public slots: * @param[in] text Away message, or blank to set unaway * @param[in] skipFormatting If true, skip timestamp formatting codes (e.g. if already done) */ - void handleAway(const BufferInfo &bufferInfo, const QString &text, - const bool skipFormatting = false); - void handleBan(const BufferInfo &bufferInfo, const QString &text); - void handleUnban(const BufferInfo &bufferInfo, const QString &text); - void handleCtcp(const BufferInfo &bufferInfo, const QString &text); - void handleDelkey(const BufferInfo &bufferInfo, const QString &text); - void handleDeop(const BufferInfo& bufferInfo, const QString &nicks); - void handleDehalfop(const BufferInfo& bufferInfo, const QString &nicks); - void handleDevoice(const BufferInfo& bufferInfo, const QString &nicks); - void handleInvite(const BufferInfo &bufferInfo, const QString &text); - void handleJoin(const BufferInfo &bufferInfo, const QString &text); - void handleKeyx(const BufferInfo &bufferInfo, const QString &text); - void handleKick(const BufferInfo &bufferInfo, const QString &text); - void handleKill(const BufferInfo &bufferInfo, const QString &text); - void handleList(const BufferInfo &bufferInfo, const QString &text); - void handleMe(const BufferInfo &bufferInfo, const QString &text); - void handleMode(const BufferInfo &bufferInfo, const QString &text); - void handleMsg(const BufferInfo &bufferInfo, const QString &text); - void handleNick(const BufferInfo &bufferInfo, const QString &text); - void handleNotice(const BufferInfo &bufferInfo, const QString &text); - void handleOper(const BufferInfo &bufferInfo, const QString &text); - void handleOp(const BufferInfo& bufferInfo, const QString &nicks); - void handleHalfop(const BufferInfo& bufferInfo, const QString &nicks); - void handlePart(const BufferInfo &bufferInfo, const QString &text); - void handlePing(const BufferInfo &bufferInfo, const QString &text); - void handlePrint(const BufferInfo &bufferInfo, const QString &text); - void handleQuery(const BufferInfo &bufferInfo, const QString &text); - void handleQuit(const BufferInfo &bufferInfo, const QString &text); - void handleQuote(const BufferInfo &bufferInfo, const QString &text); - void handleSay(const BufferInfo &bufferInfo, const QString &text); - void handleSetkey(const BufferInfo &bufferInfo, const QString &text); - void handleShowkey(const BufferInfo &bufferInfo, const QString &text); - void handleTopic(const BufferInfo &bufferInfo, const QString &text); - void handleVoice(const BufferInfo &bufferInfo, const QString &text); - void handleWait(const BufferInfo &bufferInfo, const QString &text); - void handleWho(const BufferInfo &bufferInfo, const QString &text); - void handleWhois(const BufferInfo &bufferInfo, const QString &text); - void handleWhowas(const BufferInfo &bufferInfo, const QString &text); - - void defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &text); + void handleAway(const BufferInfo& bufferInfo, const QString& text, const bool skipFormatting = false); + void handleBan(const BufferInfo& bufferInfo, const QString& text); + void handleUnban(const BufferInfo& bufferInfo, const QString& text); + void handleCtcp(const BufferInfo& bufferInfo, const QString& text); + void handleDelkey(const BufferInfo& bufferInfo, const QString& text); + void handleDeop(const BufferInfo& bufferInfo, const QString& nicks); + void handleDehalfop(const BufferInfo& bufferInfo, const QString& nicks); + void handleDevoice(const BufferInfo& bufferInfo, const QString& nicks); + void handleInvite(const BufferInfo& bufferInfo, const QString& text); + void handleJoin(const BufferInfo& bufferInfo, const QString& text); + void handleKeyx(const BufferInfo& bufferInfo, const QString& text); + void handleKick(const BufferInfo& bufferInfo, const QString& text); + void handleKill(const BufferInfo& bufferInfo, const QString& text); + void handleList(const BufferInfo& bufferInfo, const QString& text); + void handleMe(const BufferInfo& bufferInfo, const QString& text); + void handleMode(const BufferInfo& bufferInfo, const QString& text); + void handleMsg(const BufferInfo& bufferInfo, const QString& text); + void handleNick(const BufferInfo& bufferInfo, const QString& text); + void handleNotice(const BufferInfo& bufferInfo, const QString& text); + void handleOper(const BufferInfo& bufferInfo, const QString& text); + void handleOp(const BufferInfo& bufferInfo, const QString& nicks); + void handleHalfop(const BufferInfo& bufferInfo, const QString& nicks); + void handlePart(const BufferInfo& bufferInfo, const QString& text); + void handlePing(const BufferInfo& bufferInfo, const QString& text); + void handlePrint(const BufferInfo& bufferInfo, const QString& text); + void handleQuery(const BufferInfo& bufferInfo, const QString& text); + void handleQuit(const BufferInfo& bufferInfo, const QString& text); + void handleQuote(const BufferInfo& bufferInfo, const QString& text); + void handleSay(const BufferInfo& bufferInfo, const QString& text); + void handleSetkey(const BufferInfo& bufferInfo, const QString& text); + void handleShowkey(const BufferInfo& bufferInfo, const QString& text); + void handleTopic(const BufferInfo& bufferInfo, const QString& text); + void handleVoice(const BufferInfo& bufferInfo, const QString& text); + void handleWait(const BufferInfo& bufferInfo, const QString& text); + void handleWho(const BufferInfo& bufferInfo, const QString& text); + void handleWhois(const BufferInfo& bufferInfo, const QString& text); + void handleWhowas(const BufferInfo& bufferInfo, const QString& text); + + void defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& text); /** * Send a QUIT to the IRC server, optionally skipping the command queue. @@ -97,7 +96,7 @@ public slots: * @param reason Reason for quitting, often displayed to other IRC clients * @param forceImmediate Immediately quit, skipping queue of other commands */ - void issueQuit(const QString &reason, bool forceImmediate = false); + void issueQuit(const QString& reason, bool forceImmediate = false); /** * Issues the away command, marking as away or unaway on the current network @@ -106,29 +105,35 @@ public slots: * @param[in] autoCheck If true, always set away, defaulting to the identity away message * @param[in] skipFormatting If true, skip timestamp formatting codes (e.g. if already done) */ - void issueAway(const QString &msg, bool autoCheck = true, const bool skipFormatting = false); + void issueAway(const QString& msg, bool autoCheck = true, const bool skipFormatting = false); protected: - void timerEvent(QTimerEvent *event) override; + void timerEvent(QTimerEvent* event) override; private: - void doMode(const BufferInfo& bufferInfo, const QChar &addOrRemove, const QChar &mode, const QString &nickList); - void banOrUnban(const BufferInfo &bufferInfo, const QString &text, bool ban); - void putPrivmsg(const QString &target, const QString &message, std::function encodeFunc, Cipher *cipher = nullptr); + void doMode(const BufferInfo& bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString& nickList); + void banOrUnban(const BufferInfo& bufferInfo, const QString& text, bool ban); + void putPrivmsg(const QString& target, + const QString& message, + std::function encodeFunc, + Cipher* cipher = nullptr); #ifdef HAVE_QCA2 - QByteArray encrypt(const QString &target, const QByteArray &message, bool *didEncrypt = nullptr) const; + QByteArray encrypt(const QString& target, const QByteArray& message, bool* didEncrypt = nullptr) const; #endif - struct Command { + struct Command + { BufferInfo bufferInfo; QString command; - Command(BufferInfo info, QString command) : bufferInfo(std::move(info)), command(std::move(command)) {} + Command(BufferInfo info, QString command) + : bufferInfo(std::move(info)) + , command(std::move(command)) + {} Command() = default; }; QHash _delayedCommands; }; - #endif diff --git a/src/core/coreusersettings.cpp b/src/core/coreusersettings.cpp index 93408674..ed840c70 100644 --- a/src/core/coreusersettings.cpp +++ b/src/core/coreusersettings.cpp @@ -21,10 +21,9 @@ #include "coreusersettings.h" CoreUserSettings::CoreUserSettings(UserId uid) - : CoreSettings(QString("CoreUser/%1").arg(uid.toInt())), user(uid) -{ -} - + : CoreSettings(QString("CoreUser/%1").arg(uid.toInt())) + , user(uid) +{} Identity CoreUserSettings::identity(IdentityId id) const { @@ -35,58 +34,50 @@ Identity CoreUserSettings::identity(IdentityId id) const return Identity(); } - QList CoreUserSettings::identityIds() const { QList res; - foreach(QString id, localChildKeys("Identities")) { + foreach (QString id, localChildKeys("Identities")) { res << id.toInt(); } return res; } - -void CoreUserSettings::storeIdentity(const Identity &identity) +void CoreUserSettings::storeIdentity(const Identity& identity) { setLocalValue(QString("Identities/%1").arg(identity.id().toInt()), qVariantFromValue(identity)); } - void CoreUserSettings::removeIdentity(IdentityId id) { removeLocalKey(QString("Identities/%1").arg(id.toInt())); } - -void CoreUserSettings::setSessionState(const QVariant &data) +void CoreUserSettings::setSessionState(const QVariant& data) { setLocalValue("SessionState", data); } - -QVariant CoreUserSettings::sessionState(const QVariant &def) const +QVariant CoreUserSettings::sessionState(const QVariant& def) const { return localValue("SessionState", def); } - QVariantMap CoreUserSettings::sessionData() const { QVariantMap res; - foreach(QString key, localChildKeys(QString("SessionData"))) { + foreach (QString key, localChildKeys(QString("SessionData"))) { res[key] = localValue(QString("SessionData/%1").arg(key)); } return res; } - -void CoreUserSettings::setSessionValue(const QString &key, const QVariant &data) +void CoreUserSettings::setSessionValue(const QString& key, const QVariant& data) { setLocalValue(QString("SessionData/%1").arg(key), data); } - -QVariant CoreUserSettings::sessionValue(const QString &key, const QVariant &def) const +QVariant CoreUserSettings::sessionValue(const QString& key, const QVariant& def) const { return localValue(QString("SessionData/%1").arg(key), def); } diff --git a/src/core/coreusersettings.h b/src/core/coreusersettings.h index c89f9387..405c2e4a 100644 --- a/src/core/coreusersettings.h +++ b/src/core/coreusersettings.h @@ -20,13 +20,13 @@ #pragma once +#include + #include "coresettings.h" #include "identity.h" #include "network.h" #include "types.h" -#include - class CoreUserSettings : public CoreSettings { public: @@ -34,17 +34,17 @@ public: Identity identity(IdentityId id) const; QList identityIds() const; - void storeIdentity(const Identity &identity); + void storeIdentity(const Identity& identity); void removeIdentity(IdentityId id); - void setSessionState(const QVariant &data); - QVariant sessionState(const QVariant &def = {}) const; + void setSessionState(const QVariant& data); + QVariant sessionState(const QVariant& def = {}) const; private: // this stuff should only be accessed by CoreSession! QVariantMap sessionData() const; - QVariant sessionValue(const QString &key, const QVariant &def = {}) const; - void setSessionValue(const QString &key, const QVariant &value); + QVariant sessionValue(const QString& key, const QVariant& def = {}) const; + void setSessionValue(const QString& key, const QVariant& value); UserId user; diff --git a/src/core/ctcpparser.cpp b/src/core/ctcpparser.cpp index f60311c7..9b3773a4 100644 --- a/src/core/ctcpparser.cpp +++ b/src/core/ctcpparser.cpp @@ -22,15 +22,15 @@ #include "corenetworkconfig.h" #include "coresession.h" +#include "coreuserinputhandler.h" #include "ctcpevent.h" #include "messageevent.h" -#include "coreuserinputhandler.h" const QByteArray XDELIM = "\001"; -CtcpParser::CtcpParser(CoreSession *coreSession, QObject *parent) - : QObject(parent), - _coreSession(coreSession) +CtcpParser::CtcpParser(CoreSession* coreSession, QObject* parent) + : QObject(parent) + , _coreSession(coreSession) { QByteArray MQUOTE = QByteArray("\020"); _ctcpMDequoteHash[MQUOTE + '0'] = QByteArray(1, '\000'); @@ -44,7 +44,6 @@ CtcpParser::CtcpParser(CoreSession *coreSession, QObject *parent) connect(this, &CtcpParser::newEvent, _coreSession->eventManager(), &EventManager::postEvent); } - void CtcpParser::setStandardCtcp(bool enabled) { QByteArray XQUOTE = QByteArray(R"(\)"); @@ -55,21 +54,19 @@ void CtcpParser::setStandardCtcp(bool enabled) _ctcpXDelimDequoteHash[XQUOTE + QByteArray("a")] = XDELIM; } - -void CtcpParser::displayMsg(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender, - const QString &target, Message::Flags msgFlags) +void CtcpParser::displayMsg( + NetworkEvent* event, Message::Type msgType, const QString& msg, const QString& sender, const QString& target, Message::Flags msgFlags) { if (event->testFlag(EventManager::Silent)) return; - MessageEvent *msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags); + MessageEvent* msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags); msgEvent->setTimestamp(event->timestamp()); emit newEvent(msgEvent); } - -QByteArray CtcpParser::lowLevelQuote(const QByteArray &message) +QByteArray CtcpParser::lowLevelQuote(const QByteArray& message) { QByteArray quotedMessage = message; @@ -86,8 +83,7 @@ QByteArray CtcpParser::lowLevelQuote(const QByteArray &message) return quotedMessage; } - -QByteArray CtcpParser::lowLevelDequote(const QByteArray &message) +QByteArray CtcpParser::lowLevelDequote(const QByteArray& message) { QByteArray dequotedMessage; QByteArray messagepart; @@ -96,7 +92,7 @@ QByteArray CtcpParser::lowLevelDequote(const QByteArray &message) // copy dequote Message for (int i = 0; i < message.size(); i++) { messagepart = message.mid(i, 1); - if (i+1 < message.size()) { + if (i + 1 < message.size()) { for (ctcpquote = _ctcpMDequoteHash.begin(); ctcpquote != _ctcpMDequoteHash.end(); ++ctcpquote) { if (message.mid(i, 2) == ctcpquote.key()) { messagepart = ctcpquote.value(); @@ -110,8 +106,7 @@ QByteArray CtcpParser::lowLevelDequote(const QByteArray &message) return dequotedMessage; } - -QByteArray CtcpParser::xdelimQuote(const QByteArray &message) +QByteArray CtcpParser::xdelimQuote(const QByteArray& message) { QByteArray quotedMessage = message; QHash::const_iterator quoteIter = _ctcpXDelimDequoteHash.constBegin(); @@ -122,8 +117,7 @@ QByteArray CtcpParser::xdelimQuote(const QByteArray &message) return quotedMessage; } - -QByteArray CtcpParser::xdelimDequote(const QByteArray &message) +QByteArray CtcpParser::xdelimDequote(const QByteArray& message) { QByteArray dequotedMessage; QByteArray messagepart; @@ -131,7 +125,7 @@ QByteArray CtcpParser::xdelimDequote(const QByteArray &message) for (int i = 0; i < message.size(); i++) { messagepart = message.mid(i, 1); - if (i+1 < message.size()) { + if (i + 1 < message.size()) { for (xdelimquote = _ctcpXDelimDequoteHash.begin(); xdelimquote != _ctcpXDelimDequoteHash.end(); ++xdelimquote) { if (message.mid(i, 2) == xdelimquote.key()) { messagepart = xdelimquote.value(); @@ -145,31 +139,24 @@ QByteArray CtcpParser::xdelimDequote(const QByteArray &message) return dequotedMessage; } - -void CtcpParser::processIrcEventRawNotice(IrcEventRawMessage *event) +void CtcpParser::processIrcEventRawNotice(IrcEventRawMessage* event) { parse(event, Message::Notice); } - -void CtcpParser::processIrcEventRawPrivmsg(IrcEventRawMessage *event) +void CtcpParser::processIrcEventRawPrivmsg(IrcEventRawMessage* event) { parse(event, Message::Plain); } - -void CtcpParser::parse(IrcEventRawMessage *e, Message::Type messagetype) +void CtcpParser::parse(IrcEventRawMessage* e, Message::Type messagetype) { - //lowlevel message dequote + // lowlevel message dequote QByteArray dequotedMessage = lowLevelDequote(e->rawMessage()); - CtcpEvent::CtcpType ctcptype = e->type() == EventManager::IrcEventRawNotice - ? CtcpEvent::Reply - : CtcpEvent::Query; + CtcpEvent::CtcpType ctcptype = e->type() == EventManager::IrcEventRawNotice ? CtcpEvent::Reply : CtcpEvent::Query; - Message::Flags flags = (ctcptype == CtcpEvent::Reply && !e->network()->isChannelName(e->target())) - ? Message::Redirected - : Message::None; + Message::Flags flags = (ctcptype == CtcpEvent::Reply && !e->network()->isChannelName(e->target())) ? Message::Redirected : Message::None; bool isStatusMsg = false; @@ -203,14 +190,15 @@ void CtcpParser::parse(IrcEventRawMessage *e, Message::Type messagetype) parseSimple(e, messagetype, dequotedMessage, ctcptype, flags); } - // only accept CTCPs in their simplest form, i.e. one ctcp, from start to // end, no text around it; not as per the 'specs', but makes people happier -void CtcpParser::parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) +void CtcpParser::parseSimple( + IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) { - if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() -1] != '\001') { + if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() - 1] != '\001') { displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags); - } else { + } + else { int spacePos; QString ctcpcmd, ctcpparam; @@ -219,33 +207,49 @@ void CtcpParser::parseSimple(IrcEventRawMessage *e, Message::Type messagetype, Q if (spacePos != -1) { ctcpcmd = targetDecode(e, ctcp.left(spacePos)); ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); - } else { + } + else { ctcpcmd = targetDecode(e, ctcp); ctcpparam = QString(); } ctcpcmd = ctcpcmd.toUpper(); // we don't want to block /me messages by the CTCP ignore list - if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { + if (ctcpcmd == QLatin1String("ACTION") + || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { QUuid uuid = QUuid::createUuid(); _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix()))); - CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(), - ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid); + CtcpEvent* event = new CtcpEvent(EventManager::CtcpEvent, + e->network(), + e->prefix(), + e->target(), + ctcptype, + ctcpcmd, + ctcpparam, + e->timestamp(), + uuid); emit newEvent(event); - CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(), - ctcptype, "INVALID", QString(), e->timestamp(), uuid); + CtcpEvent* flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, + e->network(), + e->prefix(), + e->target(), + ctcptype, + "INVALID", + QString(), + e->timestamp(), + uuid); emit newEvent(flushEvent); } } } - -void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) +void CtcpParser::parseStandard( + IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) { QByteArray ctcp; - QList ctcpEvents; - QUuid uuid; // needed to group all replies together + QList ctcpEvents; + QUuid uuid; // needed to group all replies together // extract tagged / extended data int xdelimPos = -1; @@ -263,7 +267,7 @@ void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1)); dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1); - //dispatch the ctcp command + // dispatch the ctcp command QString ctcpcmd = targetDecode(e, ctcp.left(spacePos)); QString ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); @@ -280,21 +284,36 @@ void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, ctcpcmd = ctcpcmd.toUpper(); // we don't want to block /me messages by the CTCP ignore list - if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { + if (ctcpcmd == QLatin1String("ACTION") + || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { if (uuid.isNull()) uuid = QUuid::createUuid(); - CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(), - ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid); + CtcpEvent* event = new CtcpEvent(EventManager::CtcpEvent, + e->network(), + e->prefix(), + e->target(), + ctcptype, + ctcpcmd, + ctcpparam, + e->timestamp(), + uuid); ctcpEvents << event; } } if (!ctcpEvents.isEmpty()) { _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix()))); - CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(), - ctcptype, "INVALID", QString(), e->timestamp(), uuid); + CtcpEvent* flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, + e->network(), + e->prefix(), + e->target(), + ctcptype, + "INVALID", + QString(), + e->timestamp(), + uuid); ctcpEvents << flushEvent; - foreach(CtcpEvent *event, ctcpEvents) { + foreach (CtcpEvent* event, ctcpEvents) { emit newEvent(event); } } @@ -303,17 +322,15 @@ void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags); } - -void CtcpParser::sendCtcpEvent(CtcpEvent *e) +void CtcpParser::sendCtcpEvent(CtcpEvent* e) { - CoreNetwork *net = coreNetwork(e); + CoreNetwork* net = coreNetwork(e); if (e->type() == EventManager::CtcpEvent) { QByteArray quotedReply; QString bufname = nickFromMask(e->prefix()); if (e->ctcpType() == CtcpEvent::Query && !e->reply().isNull()) { if (_replies.contains(e->uuid())) - _replies[e->uuid()].replies << lowLevelQuote(pack(net->serverEncode(e->ctcpCmd()), - net->userEncode(bufname, e->reply()))); + _replies[e->uuid()].replies << lowLevelQuote(pack(net->serverEncode(e->ctcpCmd()), net->userEncode(bufname, e->reply()))); else // reply not caused by a request processed in here, so send it off immediately reply(net, bufname, e->ctcpCmd(), e->reply()); @@ -326,8 +343,7 @@ void CtcpParser::sendCtcpEvent(CtcpEvent *e) } } - -QByteArray CtcpParser::pack(const QByteArray &ctcpTag, const QByteArray &message) +QByteArray CtcpParser::pack(const QByteArray& ctcpTag, const QByteArray& message) { if (message.isEmpty()) return XDELIM + ctcpTag + XDELIM; @@ -335,28 +351,26 @@ QByteArray CtcpParser::pack(const QByteArray &ctcpTag, const QByteArray &message return XDELIM + ctcpTag + ' ' + xdelimQuote(message) + XDELIM; } - -void CtcpParser::query(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message) +void CtcpParser::query(CoreNetwork* net, const QString& bufname, const QString& ctcpTag, const QString& message) { QString cmd("PRIVMSG"); - std::function(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList { - return QList() << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, splitMsg))); + std::function(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList { + return QList() << net->serverEncode(bufname) + << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, splitMsg))); }; net->putCmd(cmd, net->splitMessage(cmd, message, cmdGenerator)); } - -void CtcpParser::reply(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message) +void CtcpParser::reply(CoreNetwork* net, const QString& bufname, const QString& ctcpTag, const QString& message) { QList params; params << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message))); net->putCmd("NOTICE", params); } - -void CtcpParser::packedReply(CoreNetwork *net, const QString &bufname, const QList &replies) +void CtcpParser::packedReply(CoreNetwork* net, const QString& bufname, const QList& replies) { QList params; diff --git a/src/core/ctcpparser.h b/src/core/ctcpparser.h index 0118be24..145742dd 100644 --- a/src/core/ctcpparser.h +++ b/src/core/ctcpparser.h @@ -21,13 +21,14 @@ #ifndef CTCPPARSER_H #define CTCPPARSER_H -#include #include +#include + #include "corenetwork.h" +#include "ctcpevent.h" #include "eventmanager.h" #include "ircevent.h" -#include "ctcpevent.h" class CoreSession; class CtcpEvent; @@ -37,60 +38,66 @@ class CtcpParser : public QObject Q_OBJECT public: - CtcpParser(CoreSession *coreSession, QObject *parent = nullptr); + CtcpParser(CoreSession* coreSession, QObject* parent = nullptr); - inline CoreSession *coreSession() const { return _coreSession; } + inline CoreSession* coreSession() const { return _coreSession; } - void query(CoreNetwork *network, const QString &bufname, const QString &ctcpTag, const QString &message); - void reply(CoreNetwork *network, const QString &bufname, const QString &ctcpTag, const QString &message); + void query(CoreNetwork* network, const QString& bufname, const QString& ctcpTag, const QString& message); + void reply(CoreNetwork* network, const QString& bufname, const QString& ctcpTag, const QString& message); - Q_INVOKABLE void processIrcEventRawNotice(IrcEventRawMessage *event); - Q_INVOKABLE void processIrcEventRawPrivmsg(IrcEventRawMessage *event); + Q_INVOKABLE void processIrcEventRawNotice(IrcEventRawMessage* event); + Q_INVOKABLE void processIrcEventRawPrivmsg(IrcEventRawMessage* event); - Q_INVOKABLE void sendCtcpEvent(CtcpEvent *event); + Q_INVOKABLE void sendCtcpEvent(CtcpEvent* event); signals: - void newEvent(Event *event); + void newEvent(Event* event); protected: - inline CoreNetwork *coreNetwork(NetworkEvent *e) const { return qobject_cast(e->network()); } + inline CoreNetwork* coreNetwork(NetworkEvent* e) const { return qobject_cast(e->network()); } // FIXME duplicates functionality in EventStringifier, maybe want to put that in something common //! Creates and sends a MessageEvent - void displayMsg(NetworkEvent *event, - Message::Type msgType, - const QString &msg, - const QString &sender = QString(), - const QString &target = QString(), - Message::Flags msgFlags = Message::None); - - void parse(IrcEventRawMessage *event, Message::Type msgType); - void parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags); - void parseStandard(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags); - - QByteArray lowLevelQuote(const QByteArray &); - QByteArray lowLevelDequote(const QByteArray &); - QByteArray xdelimQuote(const QByteArray &); - QByteArray xdelimDequote(const QByteArray &); - - QByteArray pack(const QByteArray &ctcpTag, const QByteArray &message); - void packedReply(CoreNetwork *network, const QString &bufname, const QList &replies); + void displayMsg(NetworkEvent* event, + Message::Type msgType, + const QString& msg, + const QString& sender = QString(), + const QString& target = QString(), + Message::Flags msgFlags = Message::None); + + void parse(IrcEventRawMessage* event, Message::Type msgType); + void parseSimple( + IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags); + void parseStandard( + IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags); + + QByteArray lowLevelQuote(const QByteArray&); + QByteArray lowLevelDequote(const QByteArray&); + QByteArray xdelimQuote(const QByteArray&); + QByteArray xdelimDequote(const QByteArray&); + + QByteArray pack(const QByteArray& ctcpTag, const QByteArray& message); + void packedReply(CoreNetwork* network, const QString& bufname, const QList& replies); private slots: void setStandardCtcp(bool enabled); private: - inline QString targetDecode(IrcEventRawMessage *e, const QByteArray &msg) { return coreNetwork(e)->userDecode(e->target(), msg); } + inline QString targetDecode(IrcEventRawMessage* e, const QByteArray& msg) { return coreNetwork(e)->userDecode(e->target(), msg); } - CoreSession *_coreSession; + CoreSession* _coreSession; - struct CtcpReply { - CoreNetwork *network{nullptr}; + struct CtcpReply + { + CoreNetwork* network{nullptr}; QString bufferName; QList replies; CtcpReply() = default; - CtcpReply(CoreNetwork *net, QString buf) : network(net), bufferName(std::move(buf)) {} + CtcpReply(CoreNetwork* net, QString buf) + : network(net) + , bufferName(std::move(buf)) + {} }; QHash _replies; @@ -99,5 +106,4 @@ private: QHash _ctcpXDelimDequoteHash; }; - #endif diff --git a/src/core/eventstringifier.cpp b/src/core/eventstringifier.cpp index ed11d306..41108a71 100644 --- a/src/core/eventstringifier.cpp +++ b/src/core/eventstringifier.cpp @@ -24,40 +24,39 @@ #include "ctcpevent.h" #include "messageevent.h" -EventStringifier::EventStringifier(CoreSession *parent) : BasicHandler("handleCtcp", parent), - _coreSession(parent), - _whois(false) +EventStringifier::EventStringifier(CoreSession* parent) + : BasicHandler("handleCtcp", parent) + , _coreSession(parent) + , _whois(false) { connect(this, &EventStringifier::newMessageEvent, coreSession()->eventManager(), &EventManager::postEvent); } - -void EventStringifier::displayMsg(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender, - const QString &target, Message::Flags msgFlags) +void EventStringifier::displayMsg( + NetworkEvent* event, Message::Type msgType, const QString& msg, const QString& sender, const QString& target, Message::Flags msgFlags) { if (event->flags().testFlag(EventManager::Silent)) return; - MessageEvent *msgEvent = createMessageEvent(event, msgType, msg, sender, target, msgFlags); - //sendMessageEvent(msgEvent); + MessageEvent* msgEvent = createMessageEvent(event, msgType, msg, sender, target, msgFlags); + // sendMessageEvent(msgEvent); emit newMessageEvent(msgEvent); } - -MessageEvent *EventStringifier::createMessageEvent(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender, - const QString &target, Message::Flags msgFlags) +MessageEvent* EventStringifier::createMessageEvent( + NetworkEvent* event, Message::Type msgType, const QString& msg, const QString& sender, const QString& target, Message::Flags msgFlags) { - MessageEvent *msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags); + MessageEvent* msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags); msgEvent->setTimestamp(event->timestamp()); return msgEvent; } - -bool EventStringifier::checkParamCount(IrcEvent *e, int minParams) +bool EventStringifier::checkParamCount(IrcEvent* e, int minParams) { if (e->params().count() < minParams) { if (e->type() == EventManager::IrcEventNumeric) { - qWarning() << "Command " << static_cast(e)->number() << " requires " << minParams << "params, got: " << e->params(); + qWarning() << "Command " << static_cast(e)->number() << " requires " << minParams + << "params, got: " << e->params(); } else { QString name = coreSession()->eventManager()->enumName(e->type()); @@ -69,27 +68,24 @@ bool EventStringifier::checkParamCount(IrcEvent *e, int minParams) return true; } - /* These are only for legacy reasons; remove as soon as we handle NetworkSplitEvents properly */ -void EventStringifier::processNetworkSplitJoin(NetworkSplitEvent *e) +void EventStringifier::processNetworkSplitJoin(NetworkSplitEvent* e) { QString msg = e->users().join("#:#") + "#:#" + e->quitMessage(); displayMsg(e, Message::NetsplitJoin, msg, QString(), e->channel()); } - -void EventStringifier::processNetworkSplitQuit(NetworkSplitEvent *e) +void EventStringifier::processNetworkSplitQuit(NetworkSplitEvent* e) { QString msg = e->users().join("#:#") + "#:#" + e->quitMessage(); displayMsg(e, Message::NetsplitQuit, msg, QString(), e->channel()); } - /* End legacy */ -void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e) +void EventStringifier::processIrcEventNumeric(IrcEventNumeric* e) { - //qDebug() << e->number(); + // qDebug() << e->number(); switch (e->number()) { // Welcome, status, info messages. Just display these. case 1: @@ -137,13 +133,12 @@ void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e) case 491: case 501: case 502: - case 431: // ERR_NONICKNAMEGIVEN + case 431: // ERR_NONICKNAMEGIVEN displayMsg(e, Message::Error, e->params().join(" "), e->prefix()); break; // Server error messages, display them in red. Colon between first param and rest. - case 401: - { + case 401: { if (!checkParamCount(e, 1)) return; @@ -160,8 +155,7 @@ void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e) case 408: case 415: case 421: - case 442: - { + case 442: { if (!checkParamCount(e, 1)) return; @@ -177,7 +171,7 @@ void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e) case 423: case 441: case 444: - case 461: // FIXME see below for the 47x codes + case 461: // FIXME see below for the 47x codes case 467: case 471: case 473: @@ -187,7 +181,7 @@ void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e) case 477: case 478: case 482: - case 436: // ERR_NICKCOLLISION + case 436: // ERR_NICKCOLLISION { if (!checkParamCount(e, 1)) return; @@ -239,22 +233,20 @@ void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e) } else { // FIXME figure out how/where to do this in the future - //if(coreSession()->ircListHelper()->requestInProgress(network()->networkId())) + // if(coreSession()->ircListHelper()->requestInProgress(network()->networkId())) // coreSession()->ircListHelper()->reportError(params.join(" ")); - //else + // else displayMsg(e, Message::Error, QString("%1 %2").arg(e->number(), 3, 10, QLatin1Char('0')).arg(e->params().join(" ")), e->prefix()); } } } - -void EventStringifier::processIrcEventInvite(IrcEvent *e) +void EventStringifier::processIrcEventInvite(IrcEvent* e) { displayMsg(e, Message::Invite, tr("%1 invited you to channel %2").arg(e->nick(), e->params().at(1))); } - -void EventStringifier::processIrcEventJoin(IrcEvent *e) +void EventStringifier::processIrcEventJoin(IrcEvent* e) { if (e->testFlag(EventManager::Netsplit)) return; @@ -268,13 +260,12 @@ void EventStringifier::processIrcEventJoin(IrcEvent *e) displayMsg(e, Message::Join, e->params()[0], e->prefix(), e->params()[0], msgFlags); } - -void EventStringifier::processIrcEventKick(IrcEvent *e) +void EventStringifier::processIrcEventKick(IrcEvent* e) { if (!checkParamCount(e, 2)) return; - IrcUser *victim = e->network()->ircUser(e->params().at(1)); + IrcUser* victim = e->network()->ircUser(e->params().at(1)); if (victim) { QString channel = e->params().at(0); QString msg = victim->nick(); @@ -291,8 +282,7 @@ void EventStringifier::processIrcEventKick(IrcEvent *e) } } - -void EventStringifier::processIrcEventMode(IrcEvent *e) +void EventStringifier::processIrcEventMode(IrcEvent* e) { if (e->network()->isChannelName(e->params().first())) { // Channel Modes @@ -311,14 +301,13 @@ void EventStringifier::processIrcEventMode(IrcEvent *e) } } - // this needs to be called before the ircuser is renamed! -void EventStringifier::processIrcEventNick(IrcEvent *e) +void EventStringifier::processIrcEventNick(IrcEvent* e) { if (!checkParamCount(e, 1)) return; - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) { qWarning() << Q_FUNC_INFO << "Unknown IrcUser!"; return; @@ -332,19 +321,19 @@ void EventStringifier::processIrcEventNick(IrcEvent *e) // Treat the sender as the new nickname, mark the message as Self sender = newnick; msgFlags = Message::Self; - } else { + } + else { // Take the sender from the event prefix, don't mark the message sender = e->prefix(); } // Announce to all channels the IrcUser is in - foreach(const QString &channel, ircuser->channels()) { + foreach (const QString& channel, ircuser->channels()) { displayMsg(e, Message::Nick, newnick, sender, channel, msgFlags); } } - -void EventStringifier::processIrcEventPart(IrcEvent *e) +void EventStringifier::processIrcEventPart(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -352,7 +341,6 @@ void EventStringifier::processIrcEventPart(IrcEvent *e) QString channel = e->params().at(0); QString msg = e->params().count() > 1 ? e->params().at(1) : QString(); - Message::Flag msgFlags = Message::Flag::None; if (e->testFlag(EventManager::Self)) { // Mark the message as Self @@ -362,8 +350,7 @@ void EventStringifier::processIrcEventPart(IrcEvent *e) displayMsg(e, Message::Part, msg, e->prefix(), channel, msgFlags); } - -void EventStringifier::processIrcEventPong(IrcEvent *e) +void EventStringifier::processIrcEventPong(IrcEvent* e) { // CoreSessionEventProcessor will flag automated PONG replies as EventManager::Silent. There's // no need to handle that specially here. @@ -372,17 +359,15 @@ void EventStringifier::processIrcEventPong(IrcEvent *e) displayMsg(e, Message::Server, "PONG " + e->params().join(" "), e->prefix()); } - -void EventStringifier::processIrcEventQuit(IrcEvent *e) +void EventStringifier::processIrcEventQuit(IrcEvent* e) { if (e->testFlag(EventManager::Netsplit)) return; - IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix()); + IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix()); if (!ircuser) return; - Message::Flag msgFlags = Message::Flag::None; if (e->testFlag(EventManager::Self)) { // Mark the message as Self @@ -390,14 +375,12 @@ void EventStringifier::processIrcEventQuit(IrcEvent *e) } // Announce to all channels the IrcUser is in - foreach(const QString &channel, ircuser->channels()) { - displayMsg(e, Message::Quit, e->params().count() ? e->params().first() : QString(), - e->prefix(), channel, msgFlags); + foreach (const QString& channel, ircuser->channels()) { + displayMsg(e, Message::Quit, e->params().count() ? e->params().first() : QString(), e->prefix(), channel, msgFlags); } } - -void EventStringifier::processIrcEventTopic(IrcEvent *e) +void EventStringifier::processIrcEventTopic(IrcEvent* e) { Message::Flag msgFlags = Message::Flag::None; if (e->testFlag(EventManager::Self)) { @@ -405,12 +388,15 @@ void EventStringifier::processIrcEventTopic(IrcEvent *e) msgFlags = Message::Self; } - displayMsg(e, Message::Topic, tr("%1 has changed topic for %2 to: \"%3\"") - .arg(e->nick(), e->params().at(0), e->params().at(1)), QString(), e->params().at(0), + displayMsg(e, + Message::Topic, + tr("%1 has changed topic for %2 to: \"%3\"").arg(e->nick(), e->params().at(0), e->params().at(1)), + QString(), + e->params().at(0), msgFlags); } -void EventStringifier::processIrcEventError(IrcEvent *e) +void EventStringifier::processIrcEventError(IrcEvent* e) { // Need an error reason if (!checkParamCount(e, 1)) @@ -419,23 +405,21 @@ void EventStringifier::processIrcEventError(IrcEvent *e) displayMsg(e, Message::Server, tr("Error from server: ") + e->params().join("")); } -void EventStringifier::processIrcEventWallops(IrcEvent *e) +void EventStringifier::processIrcEventWallops(IrcEvent* e) { displayMsg(e, Message::Server, tr("[Operwall] %1: %2").arg(e->nick(), e->params().join(" "))); } - /* RPL_ISUPPORT */ -void EventStringifier::processIrcEvent005(IrcEvent *e) +void EventStringifier::processIrcEvent005(IrcEvent* e) { if (!e->params().last().contains(QRegExp("are supported (by|on) this server"))) displayMsg(e, Message::Error, tr("Received non-RFC-compliant RPL_ISUPPORT: this can lead to unexpected behavior!"), e->prefix()); displayMsg(e, Message::Server, e->params().join(" "), e->prefix()); } - /* RPL_AWAY - " :" */ -void EventStringifier::processIrcEvent301(IrcEvent *e) +void EventStringifier::processIrcEvent301(IrcEvent* e) { QString nick = e->params().at(0); QString awayMsg = e->params().at(1); @@ -448,7 +432,7 @@ void EventStringifier::processIrcEvent301(IrcEvent *e) } else { target = nick; - IrcUser *ircuser = e->network()->ircUser(nick); + IrcUser* ircuser = e->network()->ircUser(nick); if (ircuser) { QDateTime now = QDateTime::currentDateTime(); now.setTimeSpec(Qt::UTC); @@ -456,8 +440,7 @@ void EventStringifier::processIrcEvent301(IrcEvent *e) // 1 hour = 60 min * 60 sec const int silenceTime = 60 * 60; // Check if away state has NOT changed and silence time hasn't yet elapsed - if (!ircuser->hasAwayChanged() - && ircuser->lastAwayMessageTime().addSecs(silenceTime) >= now) { + if (!ircuser->hasAwayChanged() && ircuser->lastAwayMessageTime().addSecs(silenceTime) >= now) { // Away message hasn't changed and we're still within the period of silence; don't // repeat the message send = false; @@ -471,22 +454,19 @@ void EventStringifier::processIrcEvent301(IrcEvent *e) displayMsg(e, Message::Server, msg + tr("%1 is away: \"%2\"").arg(nick, awayMsg), QString(), target); } - /* RPL_UNAWAY - ":You are no longer marked as being away" */ -void EventStringifier::processIrcEvent305(IrcEvent *e) +void EventStringifier::processIrcEvent305(IrcEvent* e) { displayMsg(e, Message::Server, tr("You are no longer marked as being away")); } - /* RPL_NOWAWAY - ":You have been marked as being away" */ -void EventStringifier::processIrcEvent306(IrcEvent *e) +void EventStringifier::processIrcEvent306(IrcEvent* e) { if (!e->network()->autoAwayActive()) displayMsg(e, Message::Server, tr("You have been marked as being away")); } - /* WHOIS-Message: Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message. @@ -501,13 +481,13 @@ WHOWAS-Message: */ /* RPL_WHOISUSER - " * :" */ -void EventStringifier::processIrcEvent311(IrcEvent *e) +void EventStringifier::processIrcEvent311(IrcEvent* e) { _whois = true; const QString whoisUserString = tr("[Whois] %1 is %2 (%3)"); - IrcUser *ircuser = e->network()->ircUser(e->params().at(0)); + IrcUser* ircuser = e->network()->ircUser(e->params().at(0)); if (ircuser) displayMsg(e, Message::Server, whoisUserString.arg(ircuser->nick(), ircuser->hostmask(), ircuser->realName())); else { @@ -516,9 +496,8 @@ void EventStringifier::processIrcEvent311(IrcEvent *e) } } - /* RPL_WHOISSERVER - " :" */ -void EventStringifier::processIrcEvent312(IrcEvent *e) +void EventStringifier::processIrcEvent312(IrcEvent* e) { if (_whois) displayMsg(e, Message::Server, tr("[Whois] %1 is online via %2 (%3)").arg(e->params().at(0), e->params().at(1), e->params().last())); @@ -526,9 +505,8 @@ void EventStringifier::processIrcEvent312(IrcEvent *e) displayMsg(e, Message::Server, tr("[Whowas] %1 was online via %2 (%3)").arg(e->params().at(0), e->params().at(1), e->params().last())); } - /* RPL_WHOWASUSER - " * :" */ -void EventStringifier::processIrcEvent314(IrcEvent *e) +void EventStringifier::processIrcEvent314(IrcEvent* e) { if (!checkParamCount(e, 3)) return; @@ -536,53 +514,50 @@ void EventStringifier::processIrcEvent314(IrcEvent *e) displayMsg(e, Message::Server, tr("[Whowas] %1 was %2@%3 (%4)").arg(e->params()[0], e->params()[1], e->params()[2], e->params().last())); } - /* RPL_ENDOFWHO: " :End of WHO list" */ -void EventStringifier::processIrcEvent315(IrcEvent *e) +void EventStringifier::processIrcEvent315(IrcEvent* e) { QStringList p = e->params(); - p.takeLast(); // should be "End of WHO list" + p.takeLast(); // should be "End of WHO list" displayMsg(e, Message::Server, tr("[Who] End of /WHO list for %1").arg(p.join(" "))); } - /* RPL_WHOISIDLE - " :seconds idle" (real life: " :seconds idle, signon time) */ -void EventStringifier::processIrcEvent317(IrcEvent *e) +void EventStringifier::processIrcEvent317(IrcEvent* e) { int idleSecs = e->params()[1].toInt(); - if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation - // Time in IRC protocol is defined as seconds. Convert from seconds instead. - // See https://doc.qt.io/qt-5/qdatetime.html#fromSecsSinceEpoch + if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation + // Time in IRC protocol is defined as seconds. Convert from seconds instead. + // See https://doc.qt.io/qt-5/qdatetime.html#fromSecsSinceEpoch #if QT_VERSION >= 0x050800 QDateTime loginTime = QDateTime::fromSecsSinceEpoch(e->params()[2].toLongLong()).toUTC(); #else // fromSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now. // See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch - QDateTime loginTime = QDateTime::fromMSecsSinceEpoch( - (qint64)(e->params()[2].toLongLong() * 1000)).toUTC(); + QDateTime loginTime = QDateTime::fromMSecsSinceEpoch((qint64)(e->params()[2].toLongLong() * 1000)).toUTC(); #endif - displayMsg(e, Message::Server, tr("[Whois] %1 is logged in since %2") - .arg(e->params()[0], loginTime.toString("yyyy-MM-dd hh:mm:ss UTC"))); + displayMsg(e, + Message::Server, + tr("[Whois] %1 is logged in since %2").arg(e->params()[0], loginTime.toString("yyyy-MM-dd hh:mm:ss UTC"))); } QDateTime idlingSince = e->timestamp().toLocalTime().addSecs(-idleSecs).toUTC(); - displayMsg(e, Message::Server, tr("[Whois] %1 is idling for %2 (since %3)") - .arg(e->params()[0], secondsToString(idleSecs), - idlingSince.toString("yyyy-MM-dd hh:mm:ss UTC"))); + displayMsg(e, + Message::Server, + tr("[Whois] %1 is idling for %2 (since %3)") + .arg(e->params()[0], secondsToString(idleSecs), idlingSince.toString("yyyy-MM-dd hh:mm:ss UTC"))); } - /* RPL_ENDOFWHOIS - " :End of WHOIS list" */ -void EventStringifier::processIrcEvent318(IrcEvent *e) +void EventStringifier::processIrcEvent318(IrcEvent* e) { _whois = false; displayMsg(e, Message::Server, tr("[Whois] End of /WHOIS list")); } - /* RPL_WHOISCHANNELS - " :*( ( "@" / "+" ) " " )" */ -void EventStringifier::processIrcEvent319(IrcEvent *e) +void EventStringifier::processIrcEvent319(IrcEvent* e) { if (!checkParamCount(e, 2)) return; @@ -591,7 +566,7 @@ void EventStringifier::processIrcEvent319(IrcEvent *e) QStringList op; QStringList voice; QStringList user; - foreach(QString channel, e->params().last().split(" ")) { + foreach (QString channel, e->params().last().split(" ")) { if (channel.startsWith("@")) op.append(channel.remove(0, 1)); else if (channel.startsWith("+")) @@ -607,9 +582,8 @@ void EventStringifier::processIrcEvent319(IrcEvent *e) displayMsg(e, Message::Server, tr("[Whois] %1 is an operator on channels: %2").arg(nick, op.join(" "))); } - /* RPL_LIST - " <# visible> :" */ -void EventStringifier::processIrcEvent322(IrcEvent *e) +void EventStringifier::processIrcEvent322(IrcEvent* e) { QString channelName; quint32 userCount = 0; @@ -628,27 +602,23 @@ void EventStringifier::processIrcEvent322(IrcEvent *e) default: break; } - displayMsg(e, Message::Server, tr("Channel %1 has %2 users. Topic is: \"%3\"") - .arg(channelName).arg(userCount).arg(topic)); + displayMsg(e, Message::Server, tr("Channel %1 has %2 users. Topic is: \"%3\"").arg(channelName).arg(userCount).arg(topic)); } - /* RPL_LISTEND ":End of LIST" */ -void EventStringifier::processIrcEvent323(IrcEvent *e) +void EventStringifier::processIrcEvent323(IrcEvent* e) { displayMsg(e, Message::Server, tr("End of channel list")); } - /* RPL_CHANNELMODEIS - " " */ -void EventStringifier::processIrcEvent324(IrcEvent *e) +void EventStringifier::processIrcEvent324(IrcEvent* e) { processIrcEventMode(e); } - /* RPL_??? - " */ -void EventStringifier::processIrcEvent328(IrcEvent *e) +void EventStringifier::processIrcEvent328(IrcEvent* e) { if (!checkParamCount(e, 2)) return; @@ -657,9 +627,8 @@ void EventStringifier::processIrcEvent328(IrcEvent *e) displayMsg(e, Message::Topic, tr("Homepage for %1 is %2").arg(channel, e->params()[1]), QString(), channel); } - /* RPL_??? - " " */ -void EventStringifier::processIrcEvent329(IrcEvent *e) +void EventStringifier::processIrcEvent329(IrcEvent* e) { if (!checkParamCount(e, 2)) return; @@ -680,14 +649,11 @@ void EventStringifier::processIrcEvent329(IrcEvent *e) // See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch QDateTime time = QDateTime::fromMSecsSinceEpoch((qint64)(unixtime * 1000)).toUTC(); #endif - displayMsg(e, Message::Topic, tr("Channel %1 created on %2") - .arg(channel, time.toString("yyyy-MM-dd hh:mm:ss UTC")), - QString(), channel); + displayMsg(e, Message::Topic, tr("Channel %1 created on %2").arg(channel, time.toString("yyyy-MM-dd hh:mm:ss UTC")), QString(), channel); } - /* RPL_WHOISACCOUNT: " :is authed as */ -void EventStringifier::processIrcEvent330(IrcEvent *e) +void EventStringifier::processIrcEvent330(IrcEvent* e) { if (e->params().count() < 3) return; @@ -701,25 +667,22 @@ void EventStringifier::processIrcEvent330(IrcEvent *e) } } - /* RPL_NOTOPIC */ -void EventStringifier::processIrcEvent331(IrcEvent *e) +void EventStringifier::processIrcEvent331(IrcEvent* e) { QString channel = e->params().first(); displayMsg(e, Message::Topic, tr("No topic is set for %1.").arg(channel), QString(), channel); } - /* RPL_TOPIC */ -void EventStringifier::processIrcEvent332(IrcEvent *e) +void EventStringifier::processIrcEvent332(IrcEvent* e) { QString channel = e->params().first(); displayMsg(e, Message::Topic, tr("Topic for %1 is \"%2\"").arg(channel, e->params()[1]), QString(), channel); } - /* Topic set by... */ -void EventStringifier::processIrcEvent333(IrcEvent *e) +void EventStringifier::processIrcEvent333(IrcEvent* e) { if (!checkParamCount(e, 3)) return; @@ -732,17 +695,17 @@ void EventStringifier::processIrcEvent333(IrcEvent *e) #else // fromSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now. // See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch - QDateTime topicSetTime = QDateTime::fromMSecsSinceEpoch( - (qint64)(e->params()[2].toLongLong() * 1000)).toUTC(); + QDateTime topicSetTime = QDateTime::fromMSecsSinceEpoch((qint64)(e->params()[2].toLongLong() * 1000)).toUTC(); #endif - displayMsg(e, Message::Topic, tr("Topic set by %1 on %2") - .arg(e->params()[1], - topicSetTime.toString("yyyy-MM-dd hh:mm:ss UTC")), QString(), channel); + displayMsg(e, + Message::Topic, + tr("Topic set by %1 on %2").arg(e->params()[1], topicSetTime.toString("yyyy-MM-dd hh:mm:ss UTC")), + QString(), + channel); } - /* RPL_INVITING - " */ -void EventStringifier::processIrcEvent341(IrcEvent *e) +void EventStringifier::processIrcEvent341(IrcEvent* e) { if (!checkParamCount(e, 2)) return; @@ -751,34 +714,30 @@ void EventStringifier::processIrcEvent341(IrcEvent *e) displayMsg(e, Message::Server, tr("%1 has been invited to %2").arg(e->params().first(), channel), QString(), channel); } - /* RPL_WHOREPLY: " ( "H" / "G" > ["*"] [ ( "@" / "+" ) ] : " */ -void EventStringifier::processIrcEvent352(IrcEvent *e) +void EventStringifier::processIrcEvent352(IrcEvent* e) { displayMsg(e, Message::Server, tr("[Who] %1").arg(e->params().join(" "))); } - /* RPL_WHOSPCRPL: " # ~ ("H"/ "G") :" Could be anything else, though. User-specified fields. See http://faerion.sourceforge.net/doc/irc/whox.var */ -void EventStringifier::processIrcEvent354(IrcEvent *e) +void EventStringifier::processIrcEvent354(IrcEvent* e) { displayMsg(e, Message::Server, tr("[WhoX] %1").arg(e->params().join(" "))); } - /* RPL_ENDOFWHOWAS - " :End of WHOWAS" */ -void EventStringifier::processIrcEvent369(IrcEvent *e) +void EventStringifier::processIrcEvent369(IrcEvent* e) { displayMsg(e, Message::Server, tr("End of /WHOWAS")); } - /* ERR_ERRONEUSNICKNAME */ -void EventStringifier::processIrcEvent432(IrcEvent *e) +void EventStringifier::processIrcEvent432(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -786,9 +745,8 @@ void EventStringifier::processIrcEvent432(IrcEvent *e) displayMsg(e, Message::Error, tr("Nick %1 contains illegal characters").arg(e->params()[0])); } - /* ERR_NICKNAMEINUSE */ -void EventStringifier::processIrcEvent433(IrcEvent *e) +void EventStringifier::processIrcEvent433(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -796,9 +754,8 @@ void EventStringifier::processIrcEvent433(IrcEvent *e) displayMsg(e, Message::Error, tr("Nick already in use: %1").arg(e->params()[0])); } - /* ERR_UNAVAILRESOURCE */ -void EventStringifier::processIrcEvent437(IrcEvent *e) +void EventStringifier::processIrcEvent437(IrcEvent* e) { if (!checkParamCount(e, 1)) return; @@ -806,7 +763,6 @@ void EventStringifier::processIrcEvent437(IrcEvent *e) displayMsg(e, Message::Error, tr("Nick/channel is temporarily unavailable: %1").arg(e->params()[0])); } - // template /* @@ -820,28 +776,30 @@ void EventStringifier::processIrcEvent(IrcEvent *e) { /******** CTCP HANDLING ********/ /*******************************/ -void EventStringifier::processCtcpEvent(CtcpEvent *e) +void EventStringifier::processCtcpEvent(CtcpEvent* e) { if (e->type() != EventManager::CtcpEvent) return; if (e->testFlag(EventManager::Self)) { - displayMsg(e, Message::Action, + displayMsg(e, + Message::Action, tr("sending CTCP-%1 request to %2").arg(e->ctcpCmd(), e->target()), - e->network()->myNick(), QString(), Message::Flag::Self); + e->network()->myNick(), + QString(), + Message::Flag::Self); return; } - handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e)); + handle(e->ctcpCmd(), Q_ARG(CtcpEvent*, e)); } - -void EventStringifier::defaultHandler(const QString &ctcpCmd, CtcpEvent *e) +void EventStringifier::defaultHandler(const QString& ctcpCmd, CtcpEvent* e) { Q_UNUSED(ctcpCmd); if (e->ctcpType() == CtcpEvent::Query) { QString unknown; - if (e->reply().isNull()) // all known core-side handlers (except for ACTION) set a reply! + if (e->reply().isNull()) // all known core-side handlers (except for ACTION) set a reply! //: Optional "unknown" in "Received unknown CTCP-FOO request by bar" unknown = tr("unknown") + ' '; displayMsg(e, Message::Server, tr("Received %1CTCP-%2 request by %3").arg(unknown, e->ctcpCmd(), e->prefix())); @@ -850,19 +808,20 @@ void EventStringifier::defaultHandler(const QString &ctcpCmd, CtcpEvent *e) displayMsg(e, Message::Server, tr("Received CTCP-%1 answer from %2: %3").arg(e->ctcpCmd(), nickFromMask(e->prefix()), e->param())); } - -void EventStringifier::handleCtcpAction(CtcpEvent *e) +void EventStringifier::handleCtcpAction(CtcpEvent* e) { displayMsg(e, Message::Action, e->param(), e->prefix(), e->target()); } - -void EventStringifier::handleCtcpPing(CtcpEvent *e) +void EventStringifier::handleCtcpPing(CtcpEvent* e) { if (e->ctcpType() == CtcpEvent::Query) defaultHandler(e->ctcpCmd(), e); else { - displayMsg(e, Message::Server, tr("Received CTCP-PING answer from %1 with %2 milliseconds round trip time") - .arg(nickFromMask(e->prefix())).arg(QDateTime::fromMSecsSinceEpoch(e->param().toULongLong()).msecsTo(e->timestamp()))); + displayMsg(e, + Message::Server, + tr("Received CTCP-PING answer from %1 with %2 milliseconds round trip time") + .arg(nickFromMask(e->prefix())) + .arg(QDateTime::fromMSecsSinceEpoch(e->param().toULongLong()).msecsTo(e->timestamp()))); } } diff --git a/src/core/eventstringifier.h b/src/core/eventstringifier.h index 67dbc56f..56160f4a 100644 --- a/src/core/eventstringifier.h +++ b/src/core/eventstringifier.h @@ -37,91 +37,90 @@ class EventStringifier : public BasicHandler Q_OBJECT public: - explicit EventStringifier(CoreSession *parent); + explicit EventStringifier(CoreSession* parent); - inline CoreSession *coreSession() const { return _coreSession; } + inline CoreSession* coreSession() const { return _coreSession; } - MessageEvent *createMessageEvent(NetworkEvent *event, - Message::Type msgType, - const QString &msg, - const QString &sender = QString(), - const QString &target = QString(), - Message::Flags msgFlags = Message::None); + MessageEvent* createMessageEvent(NetworkEvent* event, + Message::Type msgType, + const QString& msg, + const QString& sender = QString(), + const QString& target = QString(), + Message::Flags msgFlags = Message::None); // legacy handlers - Q_INVOKABLE void processNetworkSplitJoin(NetworkSplitEvent *event); - Q_INVOKABLE void processNetworkSplitQuit(NetworkSplitEvent *event); + Q_INVOKABLE void processNetworkSplitJoin(NetworkSplitEvent* event); + Q_INVOKABLE void processNetworkSplitQuit(NetworkSplitEvent* event); //! Handle generic numeric events - Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric *event); - - Q_INVOKABLE void processIrcEventInvite(IrcEvent *event); - Q_INVOKABLE void processIrcEventJoin(IrcEvent *event); - Q_INVOKABLE void processIrcEventKick(IrcEvent *event); - Q_INVOKABLE void processIrcEventMode(IrcEvent *event); - Q_INVOKABLE void processIrcEventNick(IrcEvent *event); - Q_INVOKABLE void processIrcEventPart(IrcEvent *event); - Q_INVOKABLE void processIrcEventPong(IrcEvent *event); - Q_INVOKABLE void processIrcEventQuit(IrcEvent *event); - Q_INVOKABLE void processIrcEventTopic(IrcEvent *event); - Q_INVOKABLE void processIrcEventError(IrcEvent *event); /// ERROR message from server - Q_INVOKABLE void processIrcEventWallops(IrcEvent *event); - - Q_INVOKABLE void processIrcEvent005(IrcEvent *event); // RPL_ISUPPORT - Q_INVOKABLE void processIrcEvent301(IrcEvent *event); // RPL_AWAY - Q_INVOKABLE void processIrcEvent305(IrcEvent *event); // RPL_UNAWAY - Q_INVOKABLE void processIrcEvent306(IrcEvent *event); // RPL_NOWAWAY - Q_INVOKABLE void processIrcEvent311(IrcEvent *event); // RPL_WHOISUSER - Q_INVOKABLE void processIrcEvent312(IrcEvent *event); // RPL_WHOISSERVER - Q_INVOKABLE void processIrcEvent314(IrcEvent *event); // RPL_WHOWASUSER - Q_INVOKABLE void processIrcEvent315(IrcEvent *event); // RPL_ENDOFWHO - Q_INVOKABLE void processIrcEvent317(IrcEvent *event); // RPL_WHOISIDLE - Q_INVOKABLE void processIrcEvent318(IrcEvent *event); // RPL_ENDOFWHOIS - Q_INVOKABLE void processIrcEvent319(IrcEvent *event); // RPL_WHOISCHANNELS - Q_INVOKABLE void processIrcEvent322(IrcEvent *event); // RPL_LIST - Q_INVOKABLE void processIrcEvent323(IrcEvent *event); // RPL_LISTEND - Q_INVOKABLE void processIrcEvent324(IrcEvent *event); // RPL_CHANNELMODEIS - Q_INVOKABLE void processIrcEvent328(IrcEvent *event); // RPL_??? (channel creation time) - Q_INVOKABLE void processIrcEvent329(IrcEvent *event); // RPL_??? (channel homepage) - Q_INVOKABLE void processIrcEvent330(IrcEvent *event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet) - Q_INVOKABLE void processIrcEvent331(IrcEvent *event); // RPL_NOTOPIC - Q_INVOKABLE void processIrcEvent332(IrcEvent *event); // RPL_TOPIC - Q_INVOKABLE void processIrcEvent333(IrcEvent *event); // RPL_??? (topic set by) - Q_INVOKABLE void processIrcEvent341(IrcEvent *event); // RPL_INVITING - Q_INVOKABLE void processIrcEvent352(IrcEvent *event); // RPL_WHOREPLY - Q_INVOKABLE void processIrcEvent354(IrcEvent *event); // RPL_WHOSPCRPL - Q_INVOKABLE void processIrcEvent369(IrcEvent *event); // RPL_ENDOFWHOWAS - Q_INVOKABLE void processIrcEvent432(IrcEvent *event); // ERR_ERRONEUSNICKNAME - Q_INVOKABLE void processIrcEvent433(IrcEvent *event); // ERR_NICKNAMEINUSE - Q_INVOKABLE void processIrcEvent437(IrcEvent *event); // ERR_UNAVAILRESOURCE + Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric* event); + + Q_INVOKABLE void processIrcEventInvite(IrcEvent* event); + Q_INVOKABLE void processIrcEventJoin(IrcEvent* event); + Q_INVOKABLE void processIrcEventKick(IrcEvent* event); + Q_INVOKABLE void processIrcEventMode(IrcEvent* event); + Q_INVOKABLE void processIrcEventNick(IrcEvent* event); + Q_INVOKABLE void processIrcEventPart(IrcEvent* event); + Q_INVOKABLE void processIrcEventPong(IrcEvent* event); + Q_INVOKABLE void processIrcEventQuit(IrcEvent* event); + Q_INVOKABLE void processIrcEventTopic(IrcEvent* event); + Q_INVOKABLE void processIrcEventError(IrcEvent* event); /// ERROR message from server + Q_INVOKABLE void processIrcEventWallops(IrcEvent* event); + + Q_INVOKABLE void processIrcEvent005(IrcEvent* event); // RPL_ISUPPORT + Q_INVOKABLE void processIrcEvent301(IrcEvent* event); // RPL_AWAY + Q_INVOKABLE void processIrcEvent305(IrcEvent* event); // RPL_UNAWAY + Q_INVOKABLE void processIrcEvent306(IrcEvent* event); // RPL_NOWAWAY + Q_INVOKABLE void processIrcEvent311(IrcEvent* event); // RPL_WHOISUSER + Q_INVOKABLE void processIrcEvent312(IrcEvent* event); // RPL_WHOISSERVER + Q_INVOKABLE void processIrcEvent314(IrcEvent* event); // RPL_WHOWASUSER + Q_INVOKABLE void processIrcEvent315(IrcEvent* event); // RPL_ENDOFWHO + Q_INVOKABLE void processIrcEvent317(IrcEvent* event); // RPL_WHOISIDLE + Q_INVOKABLE void processIrcEvent318(IrcEvent* event); // RPL_ENDOFWHOIS + Q_INVOKABLE void processIrcEvent319(IrcEvent* event); // RPL_WHOISCHANNELS + Q_INVOKABLE void processIrcEvent322(IrcEvent* event); // RPL_LIST + Q_INVOKABLE void processIrcEvent323(IrcEvent* event); // RPL_LISTEND + Q_INVOKABLE void processIrcEvent324(IrcEvent* event); // RPL_CHANNELMODEIS + Q_INVOKABLE void processIrcEvent328(IrcEvent* event); // RPL_??? (channel creation time) + Q_INVOKABLE void processIrcEvent329(IrcEvent* event); // RPL_??? (channel homepage) + Q_INVOKABLE void processIrcEvent330(IrcEvent* event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet) + Q_INVOKABLE void processIrcEvent331(IrcEvent* event); // RPL_NOTOPIC + Q_INVOKABLE void processIrcEvent332(IrcEvent* event); // RPL_TOPIC + Q_INVOKABLE void processIrcEvent333(IrcEvent* event); // RPL_??? (topic set by) + Q_INVOKABLE void processIrcEvent341(IrcEvent* event); // RPL_INVITING + Q_INVOKABLE void processIrcEvent352(IrcEvent* event); // RPL_WHOREPLY + Q_INVOKABLE void processIrcEvent354(IrcEvent* event); // RPL_WHOSPCRPL + Q_INVOKABLE void processIrcEvent369(IrcEvent* event); // RPL_ENDOFWHOWAS + Q_INVOKABLE void processIrcEvent432(IrcEvent* event); // ERR_ERRONEUSNICKNAME + Q_INVOKABLE void processIrcEvent433(IrcEvent* event); // ERR_NICKNAMEINUSE + Q_INVOKABLE void processIrcEvent437(IrcEvent* event); // ERR_UNAVAILRESOURCE // Q_INVOKABLE void processIrcEvent(IrcEvent *event); /* CTCP handlers */ - Q_INVOKABLE void processCtcpEvent(CtcpEvent *event); + Q_INVOKABLE void processCtcpEvent(CtcpEvent* event); - Q_INVOKABLE void handleCtcpAction(CtcpEvent *event); - Q_INVOKABLE void handleCtcpPing(CtcpEvent *event); - Q_INVOKABLE void defaultHandler(const QString &cmd, CtcpEvent *event); + Q_INVOKABLE void handleCtcpAction(CtcpEvent* event); + Q_INVOKABLE void handleCtcpPing(CtcpEvent* event); + Q_INVOKABLE void defaultHandler(const QString& cmd, CtcpEvent* event); public slots: //! Creates and sends a MessageEvent - void displayMsg(NetworkEvent *event, - Message::Type msgType, - const QString &msg, - const QString &sender = QString(), - const QString &target = QString(), - Message::Flags msgFlags = Message::None); + void displayMsg(NetworkEvent* event, + Message::Type msgType, + const QString& msg, + const QString& sender = QString(), + const QString& target = QString(), + Message::Flags msgFlags = Message::None); signals: - void newMessageEvent(Event *event); + void newMessageEvent(Event* event); private: - bool checkParamCount(IrcEvent *event, int minParams); + bool checkParamCount(IrcEvent* event, int minParams); - CoreSession *_coreSession; + CoreSession* _coreSession; bool _whois; }; - #endif diff --git a/src/core/identserver.cpp b/src/core/identserver.cpp index 18411562..bd81e163 100644 --- a/src/core/identserver.cpp +++ b/src/core/identserver.cpp @@ -18,41 +18,33 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "identserver.h" + #include #include "corenetwork.h" -#include "identserver.h" #include "logmessage.h" -IdentServer::IdentServer(QObject *parent) +IdentServer::IdentServer(QObject* parent) : QObject(parent) { connect(&_server, &QTcpServer::newConnection, this, &IdentServer::incomingConnection); connect(&_v6server, &QTcpServer::newConnection, this, &IdentServer::incomingConnection); } - bool IdentServer::startListening() { uint16_t port = Quassel::optionValue("ident-port").toUShort(); bool success = false; if (_v6server.listen(QHostAddress("::1"), port)) { - quInfo() << qPrintable( - tr("Listening for identd clients on IPv6 %1 port %2") - .arg("::1") - .arg(_v6server.serverPort()) - ); + quInfo() << qPrintable(tr("Listening for identd clients on IPv6 %1 port %2").arg("::1").arg(_v6server.serverPort())); success = true; } if (_server.listen(QHostAddress("127.0.0.1"), port)) { - quInfo() << qPrintable( - tr("Listening for identd clients on IPv4 %1 port %2") - .arg("127.0.0.1") - .arg(_server.serverPort()) - ); + quInfo() << qPrintable(tr("Listening for identd clients on IPv4 %1 port %2").arg("127.0.0.1").arg(_server.serverPort())); success = true; } @@ -64,8 +56,7 @@ bool IdentServer::startListening() return success; } - -void IdentServer::stopListening(const QString &msg) +void IdentServer::stopListening(const QString& msg) { bool wasListening = false; @@ -86,22 +77,20 @@ void IdentServer::stopListening(const QString &msg) } } - void IdentServer::incomingConnection() { - auto server = qobject_cast(sender()); + auto server = qobject_cast(sender()); Q_ASSERT(server); while (server->hasPendingConnections()) { - QTcpSocket *socket = server->nextPendingConnection(); + QTcpSocket* socket = server->nextPendingConnection(); connect(socket, &QIODevice::readyRead, this, &IdentServer::respond); connect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater); } } - void IdentServer::respond() { - auto *socket = qobject_cast(sender()); + auto* socket = qobject_cast(sender()); Q_ASSERT(socket); qint64 transactionId = _socketId; @@ -140,8 +129,7 @@ void IdentServer::respond() } } - -void Request::respondSuccess(const QString &user) +void Request::respondSuccess(const QString& user) { if (socket) { QString data = query + " : USERID : Quassel : " + user + "\r\n"; @@ -151,8 +139,7 @@ void Request::respondSuccess(const QString &user) } } - -void Request::respondError(const QString &error) +void Request::respondError(const QString& error) { if (socket) { QString data = query + " : ERROR : " + error + "\r\n"; @@ -162,7 +149,6 @@ void Request::respondError(const QString &error) } } - bool IdentServer::responseAvailable(Request request) const { if (!_connections.contains(request.localPort)) { @@ -173,22 +159,29 @@ bool IdentServer::responseAvailable(Request request) const return true; } - -void IdentServer::addSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, - const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId) +void IdentServer::addSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, + qint64 socketId) { Q_UNUSED(localAddress) Q_UNUSED(peerAddress) Q_UNUSED(peerPort) - const CoreNetwork *network = qobject_cast(sender()); - _connections[localPort] = network->coreSession()->strictCompliantIdent(identity);; + const CoreNetwork* network = qobject_cast(sender()); + _connections[localPort] = network->coreSession()->strictCompliantIdent(identity); + ; processWaiting(socketId); } - -void IdentServer::removeSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, - const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId) +void IdentServer::removeSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, + qint64 socketId) { Q_UNUSED(identity) Q_UNUSED(localAddress) @@ -199,7 +192,6 @@ void IdentServer::removeSocket(const CoreIdentity *identity, const QHostAddress processWaiting(socketId); } - qint64 IdentServer::addWaitingSocket() { qint64 newSocketId = _socketId++; @@ -207,7 +199,6 @@ qint64 IdentServer::addWaitingSocket() return newSocketId; } - qint64 IdentServer::lowestSocketId() const { if (_waiting.empty()) { @@ -217,13 +208,11 @@ qint64 IdentServer::lowestSocketId() const return _waiting.front(); } - void IdentServer::removeWaitingSocket(qint64 socketId) { _waiting.remove(socketId); } - void IdentServer::processWaiting(qint64 socketId) { removeWaitingSocket(socketId); @@ -242,8 +231,7 @@ void IdentServer::processWaiting(qint64 socketId) }); } - -bool operator==(const Request &a, const Request &b) +bool operator==(const Request& a, const Request& b) { return a.requestId == b.requestId; } diff --git a/src/core/identserver.h b/src/core/identserver.h index 3723c252..f9f26a77 100644 --- a/src/core/identserver.h +++ b/src/core/identserver.h @@ -39,27 +39,36 @@ struct Request qint64 transactionId; qint64 requestId; - friend bool operator==(const Request &a, const Request &b); + friend bool operator==(const Request& a, const Request& b); - void respondSuccess(const QString &user); - void respondError(const QString &error); + void respondSuccess(const QString& user); + void respondError(const QString& error); }; - class IdentServer : public QObject { Q_OBJECT public: - IdentServer(QObject *parent = nullptr); + IdentServer(QObject* parent = nullptr); bool startListening(); - void stopListening(const QString &msg); + void stopListening(const QString& msg); qint64 addWaitingSocket(); public slots: - void addSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId); - void removeSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId); + void addSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, + qint64 socketId); + void removeSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, + qint64 socketId); private slots: void incomingConnection(); diff --git a/src/core/ircparser.cpp b/src/core/ircparser.cpp index ea18c00e..75399fb1 100644 --- a/src/core/ircparser.cpp +++ b/src/core/ircparser.cpp @@ -29,13 +29,13 @@ #include "networkevent.h" #ifdef HAVE_QCA2 -# include "cipher.h" -# include "keyevent.h" +# include "cipher.h" +# include "keyevent.h" #endif -IrcParser::IrcParser(CoreSession *session) : - QObject(session), - _coreSession(session) +IrcParser::IrcParser(CoreSession* session) + : QObject(session) + , _coreSession(session) { // Check if raw IRC logging is enabled _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id")); @@ -44,8 +44,7 @@ IrcParser::IrcParser(CoreSession *session) : connect(this, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent); } - -bool IrcParser::checkParamCount(const QString &cmd, const QList ¶ms, int minParams) +bool IrcParser::checkParamCount(const QString& cmd, const QList& params, int minParams) { if (params.count() < minParams) { qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params; @@ -54,8 +53,7 @@ bool IrcParser::checkParamCount(const QString &cmd, const QList &par return true; } - -QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const QByteArray &message, bool isTopic) +QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic) { #ifdef HAVE_QCA2 if (message.isEmpty()) @@ -64,7 +62,7 @@ QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const if (!Cipher::neededFeaturesAvailable()) return message; - Cipher *cipher = qobject_cast(network)->cipher(bufferName); + Cipher* cipher = qobject_cast(network)->cipher(bufferName); if (!cipher || cipher->key().isEmpty()) return message; @@ -77,12 +75,11 @@ QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const #endif } - /* parse the raw server string and generate an appropriate event */ /* used to be handleServerMsg() */ -void IrcParser::processNetworkIncoming(NetworkDataEvent *e) +void IrcParser::processNetworkIncoming(NetworkDataEvent* e) { - auto *net = qobject_cast(e->network()); + auto* net = qobject_cast(e->network()); if (!net) { qWarning() << "Received network event without valid network pointer!"; return; @@ -98,8 +95,7 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) } // Log the message if enabled and network ID matches or allows all - if (_debugLogRawIrc - && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) { + if (_debugLogRawIrc && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) { // Include network ID qDebug() << "IRC net" << net->networkId() << "<<" << msg; } @@ -153,7 +149,7 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) // next string without a whitespace is the command cmd = foo.trimmed(); - QList events; + QList events; EventManager::EventType type = EventManager::Invalid; uint num = cmd.toUInt(); @@ -185,11 +181,11 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) // nice pre-parsed events that the CTCP handler can consume. QStringList decParams; - bool defaultHandling = true; // whether to automatically copy the remaining params and send the event + bool defaultHandling = true; // whether to automatically copy the remaining params and send the event switch (type) { case EventManager::IrcEventPrivmsg: - defaultHandling = false; // this might create a list of events + defaultHandling = false; // this might create a list of events if (checkParamCount(cmd, params, 1)) { QString senderNick = nickFromMask(prefix); @@ -211,7 +207,12 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) // consider including this within an if (!isSelfMessage) block msg = decrypt(net, target, msg); - IrcEventRawMessage *rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, net, msg, prefix, target, e->timestamp()); + IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, + net, + msg, + prefix, + target, + e->timestamp()); if (isSelfMessage) { // Self-messages need processed differently, tag as such via flag. rawMessage->setFlag(EventManager::Self); @@ -236,14 +237,16 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) QString target = *targetIter; // special treatment for welcome messages like: - // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message. This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68 + // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message. + // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68 if (!net->isChannelName(target)) { QString decMsg = net->serverDecode(params.at(1)); QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )"); if (welcomeRegExp.indexIn(decMsg) != -1) { QString channelname = welcomeRegExp.cap(1); decMsg = decMsg.mid(welcomeRegExp.matchedLength()); - CoreIrcChannel *chan = static_cast(net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe + CoreIrcChannel* chan = static_cast( + net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe if (chan && !chan->receivedWelcomeMsg()) { chan->setReceivedWelcomeMsg(); events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp()); @@ -274,12 +277,19 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage); if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) { events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12)); - } else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) { + } + else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) { events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14)); - } else + } + else #endif { - IrcEventRawMessage *rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice, net, params[1], prefix, target, e->timestamp()); + IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice, + net, + params[1], + prefix, + target, + e->timestamp()); if (isSelfMessage) { // Self-messages need processed differently, tag as such via flag. rawMessage->setFlag(EventManager::Self); @@ -292,9 +302,9 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) // the following events need only special casing for param decoding case EventManager::IrcEventKick: - if (params.count() >= 3) { // we have a reason + if (params.count() >= 3) { // we have a reason decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1)); - decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason + decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason } break; @@ -322,17 +332,15 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) } break; - case EventManager::IrcEventAway: - { - // Update hostmask info first. This will create the nick if it doesn't exist, e.g. - // away-notify data being sent before JOIN messages. - net->updateNickFromMask(prefix); - // Separate nick in order to separate server and user decoding - QString nick = nickFromMask(prefix); - decParams << nick; - decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString()); - } - break; + case EventManager::IrcEventAway: { + // Update hostmask info first. This will create the nick if it doesn't exist, e.g. + // away-notify data being sent before JOIN messages. + net->updateNickFromMask(prefix); + // Separate nick in order to separate server and user decoding + QString nick = nickFromMask(prefix); + decParams << nick; + decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString()); + } break; case EventManager::IrcEventNumeric: switch (num) { @@ -365,9 +373,13 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) // If server doesn't support capabilities, it will report this message. Turn it // into a nicer message since it's not a real error. defaultHandling = false; - events << new MessageEvent(Message::Server, e->network(), + events << new MessageEvent(Message::Server, + e->network(), tr("Capability negotiation not supported"), - QString(), QString(), Message::None, e->timestamp()); + QString(), + QString(), + Message::None, + e->timestamp()); } break; } @@ -385,7 +397,7 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) if (!decParams.isEmpty() && decParams.last().endsWith(' ')) decParams.append(decParams.takeLast().trimmed()); - IrcEvent *event; + IrcEvent* event; if (type == EventManager::IrcEventNumeric) event = new IrcEventNumeric(num, net, prefix, target); else @@ -395,7 +407,7 @@ void IrcParser::processNetworkIncoming(NetworkDataEvent *e) events << event; } - foreach(Event *event, events) { + foreach (Event* event, events) { emit newEvent(event); } } diff --git a/src/core/ircparser.h b/src/core/ircparser.h index c0b17eaf..76d30fb3 100644 --- a/src/core/ircparser.h +++ b/src/core/ircparser.h @@ -33,28 +33,27 @@ class IrcParser : public QObject Q_OBJECT public: - IrcParser(CoreSession *session); + IrcParser(CoreSession* session); - inline CoreSession *coreSession() const { return _coreSession; } - inline EventManager *eventManager() const { return coreSession()->eventManager(); } + inline CoreSession* coreSession() const { return _coreSession; } + inline EventManager* eventManager() const { return coreSession()->eventManager(); } signals: - void newEvent(Event *); + void newEvent(Event*); protected: - Q_INVOKABLE void processNetworkIncoming(NetworkDataEvent *e); + Q_INVOKABLE void processNetworkIncoming(NetworkDataEvent* e); - bool checkParamCount(const QString &cmd, const QList ¶ms, int minParams); + bool checkParamCount(const QString& cmd, const QList& params, int minParams); // no-op if we don't have crypto support! - QByteArray decrypt(Network *network, const QString &target, const QByteArray &message, bool isTopic = false); + QByteArray decrypt(Network* network, const QString& target, const QByteArray& message, bool isTopic = false); private: - CoreSession *_coreSession; + CoreSession* _coreSession; - bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log - qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all + bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log + qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all }; - #endif diff --git a/src/core/keyevent.cpp b/src/core/keyevent.cpp index ab923255..412c4c28 100644 --- a/src/core/keyevent.cpp +++ b/src/core/keyevent.cpp @@ -20,7 +20,7 @@ #include "keyevent.h" -Event *KeyEvent::create(EventManager::EventType type, QVariantMap &map, Network *network) +Event* KeyEvent::create(EventManager::EventType type, QVariantMap& map, Network* network) { if (type == EventManager::KeyEvent) return new KeyEvent(type, map, network); @@ -28,8 +28,7 @@ Event *KeyEvent::create(EventManager::EventType type, QVariantMap &map, Network return nullptr; } - -KeyEvent::KeyEvent(EventManager::EventType type, QVariantMap &map, Network *network) +KeyEvent::KeyEvent(EventManager::EventType type, QVariantMap& map, Network* network) : IrcEvent(type, map, network) { _exchangeType = static_cast(map.take("exchangeType").toInt()); @@ -37,8 +36,7 @@ KeyEvent::KeyEvent(EventManager::EventType type, QVariantMap &map, Network *netw _key = map.take("key").toByteArray(); } - -void KeyEvent::toVariantMap(QVariantMap &map) const +void KeyEvent::toVariantMap(QVariantMap& map) const { IrcEvent::toVariantMap(map); map["exchangeType"] = exchangeType(); diff --git a/src/core/keyevent.h b/src/core/keyevent.h index 65db084a..1985a948 100644 --- a/src/core/keyevent.h +++ b/src/core/keyevent.h @@ -28,54 +28,54 @@ class KeyEvent : public IrcEvent { public: - enum ExchangeType { + enum ExchangeType + { Init, Finish }; - explicit KeyEvent(EventManager::EventType type, Network *network, const QString &prefix, QString target, - ExchangeType exchangeType, QByteArray key, - const QDateTime ×tamp = QDateTime()) - : IrcEvent(type, network, prefix), - _exchangeType(exchangeType), - _target(std::move(target)), - _key(std::move(key)) + explicit KeyEvent(EventManager::EventType type, + Network* network, + const QString& prefix, + QString target, + ExchangeType exchangeType, + QByteArray key, + const QDateTime& timestamp = QDateTime()) + : IrcEvent(type, network, prefix) + , _exchangeType(exchangeType) + , _target(std::move(target)) + , _key(std::move(key)) { setTimestamp(timestamp); } - inline ExchangeType exchangeType() const { return _exchangeType; } inline void setExchangeType(ExchangeType type) { _exchangeType = type; } inline QString target() const { return _target; } - inline void setTarget(const QString &target) { _target = target; } + inline void setTarget(const QString& target) { _target = target; } inline QByteArray key() const { return _key; } - inline void setKey(const QByteArray &key) { _key = key; } + inline void setKey(const QByteArray& key) { _key = key; } - static Event *create(EventManager::EventType type, QVariantMap &map, Network *network); + static Event* create(EventManager::EventType type, QVariantMap& map, Network* network); protected: - explicit KeyEvent(EventManager::EventType type, QVariantMap &map, Network *network); - void toVariantMap(QVariantMap &map) const override; + explicit KeyEvent(EventManager::EventType type, QVariantMap& map, Network* network); + void toVariantMap(QVariantMap& map) const override; inline QString className() const override { return "KeyEvent"; } - inline void debugInfo(QDebug &dbg) const override + inline void debugInfo(QDebug& dbg) const override { NetworkEvent::debugInfo(dbg); - dbg << ", prefix = " << qPrintable(prefix()) - << ", target = " << qPrintable(target()) - << ", exchangetype = " << (exchangeType() == Init ? "init" : "finish") - << ", key = " << key(); + dbg << ", prefix = " << qPrintable(prefix()) << ", target = " << qPrintable(target()) + << ", exchangetype = " << (exchangeType() == Init ? "init" : "finish") << ", key = " << key(); } - private: ExchangeType _exchangeType; QString _target; QByteArray _key; }; - #endif diff --git a/src/core/ldapauthenticator.cpp b/src/core/ldapauthenticator.cpp index 7448396b..31221fd7 100644 --- a/src/core/ldapauthenticator.cpp +++ b/src/core/ldapauthenticator.cpp @@ -41,12 +41,10 @@ #include //#endif -LdapAuthenticator::LdapAuthenticator(QObject *parent) - : Authenticator(parent), - _connection(nullptr) -{ -} - +LdapAuthenticator::LdapAuthenticator(QObject* parent) + : Authenticator(parent) + , _connection(nullptr) +{} LdapAuthenticator::~LdapAuthenticator() { @@ -55,14 +53,12 @@ LdapAuthenticator::~LdapAuthenticator() } } - bool LdapAuthenticator::isAvailable() const { // FIXME: probably this should test if we can speak to the LDAP server. return true; } - QString LdapAuthenticator::backendId() const { // We identify the backend to use for the monolithic core by this identifier. @@ -71,38 +67,27 @@ QString LdapAuthenticator::backendId() const return QString("LDAP"); } - QString LdapAuthenticator::displayName() const { return tr("LDAP"); } - QString LdapAuthenticator::description() const { return tr("Authenticate users using an LDAP server."); } - QVariantList LdapAuthenticator::setupData() const { // The parameters needed for LDAP. QVariantList data; - data << "Hostname" << tr("Hostname") << QString{"ldap://localhost"} - << "Port" << tr("Port") << DEFAULT_LDAP_PORT - << "BindDN" << tr("Bind DN") << QString{} - << "BindPassword" << tr("Bind Password") << QString{} - << "BaseDN" << tr("Base DN") << QString{} - << "Filter" << tr("Filter") << QString{} - << "UidAttribute" << tr("UID Attribute") << QString{"uid"} - ; + data << "Hostname" << tr("Hostname") << QString{"ldap://localhost"} << "Port" << tr("Port") << DEFAULT_LDAP_PORT << "BindDN" + << tr("Bind DN") << QString{} << "BindPassword" << tr("Bind Password") << QString{} << "BaseDN" << tr("Base DN") << QString{} + << "Filter" << tr("Filter") << QString{} << "UidAttribute" << tr("UID Attribute") << QString{"uid"}; return data; } - -void LdapAuthenticator::setAuthProperties(const QVariantMap &properties, - const QProcessEnvironment &environment, - bool loadFromEnvironment) +void LdapAuthenticator::setAuthProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) { if (loadFromEnvironment) { _hostName = environment.value("AUTH_LDAP_HOSTNAME"); @@ -112,7 +97,8 @@ void LdapAuthenticator::setAuthProperties(const QVariantMap &properties, _baseDN = environment.value("AUTH_LDAP_BASE_DN"); _filter = environment.value("AUTH_LDAP_FILTER"); _uidAttribute = environment.value("AUTH_LDAP_UID_ATTRIBUTE"); - } else { + } + else { _hostName = properties["Hostname"].toString(); _port = properties["Port"].toInt(); _bindDN = properties["BindDN"].toString(); @@ -127,7 +113,7 @@ void LdapAuthenticator::setAuthProperties(const QVariantMap &properties, // class should be created implementing it. // i.e. a provider that does its own thing and then pokes at the current storage // through the default core method. -UserId LdapAuthenticator::validateUser(const QString &username, const QString &password) +UserId LdapAuthenticator::validateUser(const QString& username, const QString& password) { bool result = ldapAuth(username, password); if (!result) { @@ -153,20 +139,14 @@ UserId LdapAuthenticator::validateUser(const QString &username, const QString &p return quasselId; } - -bool LdapAuthenticator::setup(const QVariantMap &settings, - const QProcessEnvironment &environment, - bool loadFromEnvironment) +bool LdapAuthenticator::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) { setAuthProperties(settings, environment, loadFromEnvironment); bool status = ldapConnect(); return status; } - -Authenticator::State LdapAuthenticator::init(const QVariantMap &settings, - const QProcessEnvironment &environment, - bool loadFromEnvironment) +Authenticator::State LdapAuthenticator::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) { setAuthProperties(settings, environment, loadFromEnvironment); @@ -216,7 +196,6 @@ bool LdapAuthenticator::ldapConnect() return true; } - void LdapAuthenticator::ldapDisconnect() { if (_connection == nullptr) { @@ -227,8 +206,7 @@ void LdapAuthenticator::ldapDisconnect() _connection = nullptr; } - -bool LdapAuthenticator::ldapAuth(const QString &username, const QString &password) +bool LdapAuthenticator::ldapAuth(const QString& username, const QString& password) { if (password.isEmpty()) { return false; @@ -266,7 +244,17 @@ bool LdapAuthenticator::ldapAuth(const QString &username, const QString &passwor const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + username.toLocal8Bit() + ")" + _filter.toLocal8Bit() + ")"; - res = ldap_search_ext_s(_connection, baseDN.constData(), LDAP_SCOPE_SUBTREE, ldapQuery.constData(), nullptr, 0, nullptr, nullptr, nullptr, 0, &msg); + res = ldap_search_ext_s(_connection, + baseDN.constData(), + LDAP_SCOPE_SUBTREE, + ldapQuery.constData(), + nullptr, + 0, + nullptr, + nullptr, + nullptr, + 0, + &msg); if (res != LDAP_SUCCESS) { qWarning() << "Refusing connection from" << username << "(LDAP search failed:" << ldap_err2string(res) << ")"; @@ -291,7 +279,7 @@ bool LdapAuthenticator::ldapAuth(const QString &username, const QString &passwor cred.bv_val = passwordArray.data(); cred.bv_len = password.size(); - char *userDN = ldap_get_dn(_connection, entry); + char* userDN = ldap_get_dn(_connection, entry); res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr); diff --git a/src/core/ldapauthenticator.h b/src/core/ldapauthenticator.h index c46b76cc..81847380 100644 --- a/src/core/ldapauthenticator.h +++ b/src/core/ldapauthenticator.h @@ -29,7 +29,6 @@ #pragma once #include "authenticator.h" - #include "core.h" // Link against LDAP. @@ -50,7 +49,7 @@ class LdapAuthenticator : public Authenticator Q_OBJECT public: - LdapAuthenticator(QObject *parent = nullptr); + LdapAuthenticator(QObject* parent = nullptr); ~LdapAuthenticator() override; public slots: @@ -63,18 +62,15 @@ public slots: bool canChangePassword() const override { return false; } - bool setup(const QVariantMap &settings, const QProcessEnvironment &environment, - bool loadFromEnvironment) override; - State init(const QVariantMap &settings, const QProcessEnvironment &environment, - bool loadFromEnvironment) override; - UserId validateUser(const QString &user, const QString &password) override; + bool setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override; + State init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override; + UserId validateUser(const QString& user, const QString& password) override; protected: - void setAuthProperties(const QVariantMap &properties, const QProcessEnvironment &environment, - bool loadFromEnvironment); + void setAuthProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment); bool ldapConnect(); void ldapDisconnect(); - bool ldapAuth(const QString &username, const QString &password); + bool ldapAuth(const QString& username, const QString& password); // Protected methods for retrieving info about the LDAP connection. QString hostName() const { return _hostName; } @@ -92,5 +88,5 @@ private: QString _uidAttribute; // The actual connection object. - LDAP *_connection {nullptr}; + LDAP* _connection{nullptr}; }; diff --git a/src/core/netsplit.cpp b/src/core/netsplit.cpp index f71a29c0..0b409bd0 100644 --- a/src/core/netsplit.cpp +++ b/src/core/netsplit.cpp @@ -19,14 +19,19 @@ ***************************************************************************/ #include "netsplit.h" -#include "network.h" -#include "util.h" #include -Netsplit::Netsplit(Network *network, QObject *parent) - : QObject(parent), - _network(network), _quitMsg(""), _sentQuit(false), _joinCounter(0), _quitCounter(0) +#include "network.h" +#include "util.h" + +Netsplit::Netsplit(Network* network, QObject* parent) + : QObject(parent) + , _network(network) + , _quitMsg("") + , _sentQuit(false) + , _joinCounter(0) + , _quitCounter(0) { _discardTimer.setSingleShot(true); _joinTimer.setSingleShot(true); @@ -41,12 +46,11 @@ Netsplit::Netsplit(Network *network, QObject *parent) _discardTimer.start(3600000); } - -void Netsplit::userQuit(const QString &sender, const QStringList &channels, const QString &msg) +void Netsplit::userQuit(const QString& sender, const QStringList& channels, const QString& msg) { if (_quitMsg.isEmpty()) _quitMsg = msg; - foreach(QString channel, channels) { + foreach (QString channel, channels) { _quits[channel].append(sender); } _quitCounter++; @@ -54,13 +58,12 @@ void Netsplit::userQuit(const QString &sender, const QStringList &channels, cons _quitTimer.start(10000); } - -bool Netsplit::userJoined(const QString &sender, const QString &channel) +bool Netsplit::userJoined(const QString& sender, const QString& channel) { if (!_quits.contains(channel)) return false; - QStringList &users = _quits[channel]; + QStringList& users = _quits[channel]; QStringList::iterator userIter; const QString senderNick = nickFromMask(sender); @@ -81,24 +84,22 @@ bool Netsplit::userJoined(const QString &sender, const QString &channel) _joinCounter++; - if (_quits.empty()) // all users joined already - no need to wait + if (_quits.empty()) // all users joined already - no need to wait _joinTimer.start(0); - else // wait 30s to finish the netsplit-join + else // wait 30s to finish the netsplit-join _joinTimer.start(30000); return true; } - -bool Netsplit::userAlreadyJoined(const QString &sender, const QString &channel) +bool Netsplit::userAlreadyJoined(const QString& sender, const QString& channel) { if (_joins.value(channel).first.contains(sender)) return true; return false; } - -void Netsplit::addMode(const QString &sender, const QString &channel, const QString &mode) +void Netsplit::addMode(const QString& sender, const QString& channel, const QString& mode) { if (!_joins.contains(channel)) return; @@ -108,8 +109,7 @@ void Netsplit::addMode(const QString &sender, const QString &channel, const QStr _joins[channel].second[idx].append(mode); } - -bool Netsplit::isNetsplit(const QString &quitMessage) +bool Netsplit::isNetsplit(const QString& quitMessage) { // check if we find some common chars that disqualify the netsplit as such if (quitMessage.contains(':') || quitMessage.contains('/')) @@ -124,7 +124,6 @@ bool Netsplit::isNetsplit(const QString &quitMessage) return false; } - void Netsplit::joinTimeout() { if (!_sentQuit) { @@ -132,7 +131,7 @@ void Netsplit::joinTimeout() quitTimeout(); } - QHash >::iterator it; + QHash>::iterator it; /* Try to catch server jumpers. @@ -142,7 +141,7 @@ void Netsplit::joinTimeout() A netsplit is assumed over only if at least 1/3 of all quits had their corresponding join again. */ - if (_joinCounter < _quitCounter/3) { + if (_joinCounter < _quitCounter / 3) { for (it = _joins.begin(); it != _joins.end(); ++it) emit earlyJoin(network(), it.key(), it.value().first, it.value().second); @@ -164,7 +163,6 @@ void Netsplit::joinTimeout() emit finished(); } - void Netsplit::quitTimeout() { // send netsplitQuit for every recorded channel @@ -172,7 +170,7 @@ void Netsplit::quitTimeout() for (channelIter = _quits.begin(); channelIter != _quits.end(); ++channelIter) { QStringList usersToSend; - foreach(QString user, channelIter.value()) { + foreach (QString user, channelIter.value()) { if (!_quitsWithMessageSent.value(channelIter.key()).contains(user)) { usersToSend << user; _quitsWithMessageSent[channelIter.key()].append(user); diff --git a/src/core/netsplit.h b/src/core/netsplit.h index a5aa9955..84328105 100644 --- a/src/core/netsplit.h +++ b/src/core/netsplit.h @@ -21,10 +21,10 @@ #ifndef NETSPLIT_H #define NETSPLIT_H -#include #include #include #include +#include class Network; @@ -32,91 +32,91 @@ class Netsplit : public QObject { Q_OBJECT public: - Netsplit(Network *network, QObject *parent = nullptr); + Netsplit(Network* network, QObject* parent = nullptr); - inline Network *network() const { return _network; } + inline Network* network() const { return _network; } //! Add a user to the netsplit /** Call this method if you noticed a netsplit. - * \note This method doesn't check if it really is a netsplit. - * \note Check with isNetsplit(const QString &quitMessage) before calling it! - * - * \param sender The sender string of the quitting user - * \param channels The channels that user shared with us - * \param msg The quit message - */ - void userQuit(const QString &sender, const QStringList &channels, const QString &msg); + * \note This method doesn't check if it really is a netsplit. + * \note Check with isNetsplit(const QString &quitMessage) before calling it! + * + * \param sender The sender string of the quitting user + * \param channels The channels that user shared with us + * \param msg The quit message + */ + void userQuit(const QString& sender, const QStringList& channels, const QString& msg); //! Remove a user from the netsplit /** Call this method if a user joined after a netsplit occured. - * - * \param sender The sender string of the joined user - * \param channel The channel that user shares with us - * \return true if user was found in the netsplit - */ - bool userJoined(const QString &sender, const QString &channel); + * + * \param sender The sender string of the joined user + * \param channel The channel that user shares with us + * \return true if user was found in the netsplit + */ + bool userJoined(const QString& sender, const QString& channel); //! Check if user has joined since netsplit /** This method shows if a user has already joined after being hit by netsplit - * \note The method doesn't check if the user was recorded in the netsplit! - * - * \param sender The sender string of the user - * \param channel The channel the user shares with us - * \return true if user joined after a netsplit - */ - bool userAlreadyJoined(const QString &sender, const QString &channel); + * \note The method doesn't check if the user was recorded in the netsplit! + * + * \param sender The sender string of the user + * \param channel The channel the user shares with us + * \return true if user joined after a netsplit + */ + bool userAlreadyJoined(const QString& sender, const QString& channel); //! Add mode to user /** Use this method to buffer userspecific channel modes until netsplitJoin is emitted. - * - * \param sender The sender string of the user - * \param channel The channel the user shares with us - * \return true if user joined after a netsplit - */ - void addMode(const QString &sender, const QString &channel, const QString &mode); + * + * \param sender The sender string of the user + * \param channel The channel the user shares with us + * \return true if user joined after a netsplit + */ + void addMode(const QString& sender, const QString& channel, const QString& mode); //! Check if a string matches the criteria for a netsplit /** \param quitMessage The message to be checked - * \return true if the message is a netsplit - */ - static bool isNetsplit(const QString &quitMessage); + * \return true if the message is a netsplit + */ + static bool isNetsplit(const QString& quitMessage); signals: //! A bulk-join of netsplitted users timed out /** Whenever the internal join-timer times out, we consider the bulk-join to be finished and emit that signal - * for every channel. This is the end of a netsplit. - * \param net The network - * \param channel The IRC channel - * \param users A list of all users that joined that channel - * \param modes A list of all modes the users got set after joining again - * \param quitMessage The Quitmessage and thus the servers that got split - */ - void netsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes, const QString &quitMessage); + * for every channel. This is the end of a netsplit. + * \param net The network + * \param channel The IRC channel + * \param users A list of all users that joined that channel + * \param modes A list of all modes the users got set after joining again + * \param quitMessage The Quitmessage and thus the servers that got split + */ + void netsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage); //! A (probably bulk-) join of netsplitted users. /** If users hit by the split joined before the netsplit is considered over, join the users with a normal join. - * \param net The network - * \param channel The IRC channel - * \param users A list of all users that joined that channel - * \param modes A list of all modes the users got set after joining again - */ - void earlyJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes); + * \param net The network + * \param channel The IRC channel + * \param users A list of all users that joined that channel + * \param modes A list of all modes the users got set after joining again + */ + void earlyJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes); //! A bulk-quit of netsplitted users timed out /** Whenever the internal quit-timer times out, we consider the bulk-quit to be finished and emit that signal - * for every channel. - * \param net The network - * \param channel The IRC channel - * \param users A list of all users that quitted in that channel - * \param quitMessage The Quitmessage and thus the servers that got split - */ - void netsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage); + * for every channel. + * \param net The network + * \param channel The IRC channel + * \param users A list of all users that quitted in that channel + * \param quitMessage The Quitmessage and thus the servers that got split + */ + void netsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage); //! The Netsplit is considered finished /** This signal is emitted right after all netsplitJoin signals have been sent or whenever the - * internal timer signals a timeout. - * Simply delete the object and remove it from structures when you receive that signal. - */ + * internal timer signals a timeout. + * Simply delete the object and remove it from structures when you receive that signal. + */ void finished(); private slots: @@ -124,11 +124,11 @@ private slots: void quitTimeout(); private: - Network *_network; + Network* _network; QString _quitMsg; // key: channel name // value: senderstring, list of modes - QHash > _joins; + QHash> _joins; QHash _quits; QHash _quitsWithMessageSent; bool _sentQuit; @@ -139,5 +139,4 @@ private: int _quitCounter; }; - -#endif // NETSPLIT_H +#endif // NETSPLIT_H diff --git a/src/core/oidentdconfiggenerator.cpp b/src/core/oidentdconfiggenerator.cpp index 7e758710..e69f76f2 100644 --- a/src/core/oidentdconfiggenerator.cpp +++ b/src/core/oidentdconfiggenerator.cpp @@ -19,8 +19,8 @@ ***************************************************************************/ #ifdef HAVE_UMASK -# include -# include +# include +# include #endif /* HAVE_UMASK */ #include @@ -28,14 +28,13 @@ #include "corenetwork.h" #include "oidentdconfiggenerator.h" -OidentdConfigGenerator::OidentdConfigGenerator(QObject *parent) : - QObject(parent) +OidentdConfigGenerator::OidentdConfigGenerator(QObject* parent) + : QObject(parent) { if (!_initialized) init(); } - OidentdConfigGenerator::~OidentdConfigGenerator() { _quasselConfig.clear(); @@ -43,7 +42,6 @@ OidentdConfigGenerator::~OidentdConfigGenerator() _configFile->deleteLater(); } - bool OidentdConfigGenerator::init() { _configDir = QDir::homePath(); @@ -72,17 +70,18 @@ bool OidentdConfigGenerator::init() return _initialized; } - -QString OidentdConfigGenerator::sysIdentForIdentity(const CoreIdentity *identity) const { +QString OidentdConfigGenerator::sysIdentForIdentity(const CoreIdentity* identity) const +{ // Make sure the identity's ident complies with strict mode if enabled - const CoreNetwork *network = qobject_cast(sender()); + const CoreNetwork* network = qobject_cast(sender()); return network->coreSession()->strictCompliantIdent(identity); } - -bool OidentdConfigGenerator::addSocket(const CoreIdentity *identity, - const QHostAddress &localAddress, quint16 localPort, - const QHostAddress &peerAddress, quint16 peerPort, +bool OidentdConfigGenerator::addSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, qint64 socketId) { Q_UNUSED(localAddress) @@ -99,11 +98,12 @@ bool OidentdConfigGenerator::addSocket(const CoreIdentity *identity, return ret; } - //! not yet implemented -bool OidentdConfigGenerator::removeSocket(const CoreIdentity *identity, - const QHostAddress &localAddress, quint16 localPort, - const QHostAddress &peerAddress, quint16 peerPort, +bool OidentdConfigGenerator::removeSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, qint64 socketId) { Q_UNUSED(identity) @@ -116,7 +116,6 @@ bool OidentdConfigGenerator::removeSocket(const CoreIdentity *identity, return true; } - bool OidentdConfigGenerator::parseConfig(bool readQuasselStanzas) { if (!_configFile->exists()) @@ -142,11 +141,10 @@ bool OidentdConfigGenerator::parseConfig(bool readQuasselStanzas) return true; } - bool OidentdConfigGenerator::writeConfig() { #ifdef HAVE_UMASK - mode_t prev_umask = umask(S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH); // == 0133, rw-r--r-- + mode_t prev_umask = umask(S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH); // == 0133, rw-r--r-- #endif bool not_open = (!_configFile->isOpen() && !_configFile->open(QIODevice::ReadWrite | QIODevice::Text)); #ifdef HAVE_UMASK @@ -168,8 +166,7 @@ bool OidentdConfigGenerator::writeConfig() return true; } - -bool OidentdConfigGenerator::lineByUs(const QByteArray &line) +bool OidentdConfigGenerator::lineByUs(const QByteArray& line) { return _quasselStanzaRx.exactMatch(line); } diff --git a/src/core/oidentdconfiggenerator.h b/src/core/oidentdconfiggenerator.h index ee3e53c3..8a71b53d 100644 --- a/src/core/oidentdconfiggenerator.h +++ b/src/core/oidentdconfiggenerator.h @@ -21,17 +21,17 @@ #ifndef OIDENTDCONFIGGENERATOR_H #define OIDENTDCONFIGGENERATOR_H -#include -#include +#include +#include #include #include -#include #include #include -#include +#include +#include -#include "quassel.h" #include "coreidentity.h" +#include "quassel.h" //! Produces oidentd configuration files /*! @@ -54,28 +54,34 @@ class OidentdConfigGenerator : public QObject { Q_OBJECT public: - explicit OidentdConfigGenerator(QObject *parent = nullptr); + explicit OidentdConfigGenerator(QObject* parent = nullptr); ~OidentdConfigGenerator() override; public slots: - bool addSocket(const CoreIdentity *identity, const QHostAddress &localAddress, - quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, + bool addSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, qint64 socketId); - bool removeSocket(const CoreIdentity *identity, const QHostAddress &localAddress, - quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, + bool removeSocket(const CoreIdentity* identity, + const QHostAddress& localAddress, + quint16 localPort, + const QHostAddress& peerAddress, + quint16 peerPort, qint64 socketId); private: - QString sysIdentForIdentity(const CoreIdentity *identity) const; + QString sysIdentForIdentity(const CoreIdentity* identity) const; bool init(); bool writeConfig(); bool parseConfig(bool readQuasselStanzas = false); - bool lineByUs(const QByteArray &line); + bool lineByUs(const QByteArray& line); bool _initialized{false}; bool _strict; QDateTime _lastSync; - QFile *_configFile; + QFile* _configFile; QByteArray _parsedConfig; QByteArray _quasselConfig; // Mutex isn't strictly necessary at the moment, since with the current invocation in Core only one instance at a time exists @@ -89,5 +95,4 @@ private: QString _quasselStanzaTemplate; }; - -#endif // OIDENTDCONFIGGENERATOR_H +#endif // OIDENTDCONFIGGENERATOR_H diff --git a/src/core/postgresqlstorage.cpp b/src/core/postgresqlstorage.cpp index 391e2ac3..200fd14c 100644 --- a/src/core/postgresqlstorage.cpp +++ b/src/core/postgresqlstorage.cpp @@ -26,11 +26,9 @@ #include "network.h" #include "quassel.h" -PostgreSqlStorage::PostgreSqlStorage(QObject *parent) +PostgreSqlStorage::PostgreSqlStorage(QObject* parent) : AbstractSqlStorage(parent) -{ -} - +{} std::unique_ptr PostgreSqlStorage::createMigrationWriter() { @@ -45,7 +43,6 @@ std::unique_ptr PostgreSqlStorage::createMigrationWr return std::unique_ptr{writer}; } - bool PostgreSqlStorage::isAvailable() const { if (!QSqlDatabase::isDriverAvailable("QPSQL")) { @@ -56,40 +53,31 @@ bool PostgreSqlStorage::isAvailable() const return true; } - QString PostgreSqlStorage::backendId() const { return QString("PostgreSQL"); } - QString PostgreSqlStorage::displayName() const { - return backendId(); // Note: Pre-0.13 clients use the displayName property for backend idenfication + return backendId(); // Note: Pre-0.13 clients use the displayName property for backend idenfication } - QString PostgreSqlStorage::description() const { // FIXME: proper description return tr("PostgreSQL Turbo Bomber HD!"); } - QVariantList PostgreSqlStorage::setupData() const { QVariantList data; - data << "Username" << tr("Username") << QString("quassel") - << "Password" << tr("Password") << QString() - << "Hostname" << tr("Hostname") << QString("localhost") - << "Port" << tr("Port") << 5432 - << "Database" << tr("Database") << QString("quassel") - ; + data << "Username" << tr("Username") << QString("quassel") << "Password" << tr("Password") << QString() << "Hostname" << tr("Hostname") + << QString("localhost") << "Port" << tr("Port") << 5432 << "Database" << tr("Database") << QString("quassel"); return data; } - -bool PostgreSqlStorage::initDbSession(QSqlDatabase &db) +bool PostgreSqlStorage::initDbSession(QSqlDatabase& db) { // check whether the Qt driver performs string escaping or not. // i.e. test if it doubles slashes. @@ -97,7 +85,7 @@ bool PostgreSqlStorage::initDbSession(QSqlDatabase &db) testField.setType(QVariant::String); testField.setValue("\\"); QString formattedString = db.driver()->formatValue(testField); - switch(formattedString.count('\\')) { + switch (formattedString.count('\\')) { case 2: // yes it does... and we cannot do anything to change the behavior of Qt. // If this is a legacy DB (Postgres < 8.2), then everything is already ok, @@ -140,10 +128,7 @@ bool PostgreSqlStorage::initDbSession(QSqlDatabase &db) return true; } - -void PostgreSqlStorage::setConnectionProperties(const QVariantMap &properties, - const QProcessEnvironment &environment, - bool loadFromEnvironment) +void PostgreSqlStorage::setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) { if (loadFromEnvironment) { _userName = environment.value("DB_PGSQL_USERNAME"); @@ -151,7 +136,8 @@ void PostgreSqlStorage::setConnectionProperties(const QVariantMap &properties, _hostName = environment.value("DB_PGSQL_HOSTNAME"); _port = environment.value("DB_PGSQL_PORT").toInt(); _databaseName = environment.value("DB_PGSQL_DATABASE"); - } else { + } + else { _userName = properties["Username"].toString(); _password = properties["Password"].toString(); _hostName = properties["Hostname"].toString(); @@ -160,7 +146,6 @@ void PostgreSqlStorage::setConnectionProperties(const QVariantMap &properties, } } - int PostgreSqlStorage::installedSchemaVersion() { QSqlQuery query(logDb()); @@ -180,7 +165,6 @@ int PostgreSqlStorage::installedSchemaVersion() return AbstractSqlStorage::installedSchemaVersion(); } - bool PostgreSqlStorage::updateSchemaVersion(int newVersion) { QSqlQuery query(logDb()); @@ -196,7 +180,6 @@ bool PostgreSqlStorage::updateSchemaVersion(int newVersion) return success; } - bool PostgreSqlStorage::setupSchemaVersion(int version) { QSqlQuery query(logDb()); @@ -212,8 +195,7 @@ bool PostgreSqlStorage::setupSchemaVersion(int version) return success; } - -UserId PostgreSqlStorage::addUser(const QString &user, const QString &password, const QString &authenticator) +UserId PostgreSqlStorage::addUser(const QString& user, const QString& password, const QString& authenticator) { QSqlQuery query(logDb()); query.prepare(queryString("insert_quasseluser")); @@ -231,8 +213,7 @@ UserId PostgreSqlStorage::addUser(const QString &user, const QString &password, return uid; } - -bool PostgreSqlStorage::updateUser(UserId user, const QString &password) +bool PostgreSqlStorage::updateUser(UserId user, const QString& password) { QSqlQuery query(logDb()); query.prepare(queryString("update_userpassword")); @@ -244,8 +225,7 @@ bool PostgreSqlStorage::updateUser(UserId user, const QString &password) return query.numRowsAffected() != 0; } - -void PostgreSqlStorage::renameUser(UserId user, const QString &newName) +void PostgreSqlStorage::renameUser(UserId user, const QString& newName) { QSqlQuery query(logDb()); query.prepare(queryString("update_username")); @@ -256,8 +236,7 @@ void PostgreSqlStorage::renameUser(UserId user, const QString &newName) emit userRenamed(user, newName); } - -UserId PostgreSqlStorage::validateUser(const QString &user, const QString &password) +UserId PostgreSqlStorage::validateUser(const QString& user, const QString& password) { QSqlQuery query(logDb()); query.prepare(queryString("select_authuser")); @@ -265,7 +244,11 @@ UserId PostgreSqlStorage::validateUser(const QString &user, const QString &passw safeExec(query); watchQuery(query); - if (query.first() && checkHashedPassword(query.value(0).toInt(), password, query.value(1).toString(), static_cast(query.value(2).toInt()))) { + if (query.first() + && checkHashedPassword(query.value(0).toInt(), + password, + query.value(1).toString(), + static_cast(query.value(2).toInt()))) { return query.value(0).toInt(); } else { @@ -273,8 +256,7 @@ UserId PostgreSqlStorage::validateUser(const QString &user, const QString &passw } } - -UserId PostgreSqlStorage::getUserId(const QString &user) +UserId PostgreSqlStorage::getUserId(const QString& user) { QSqlQuery query(logDb()); query.prepare(queryString("select_userid")); @@ -321,7 +303,6 @@ UserId PostgreSqlStorage::internalUser() } } - void PostgreSqlStorage::delUser(UserId user) { QSqlDatabase db = logDb(); @@ -344,8 +325,7 @@ void PostgreSqlStorage::delUser(UserId user) } } - -void PostgreSqlStorage::setUserSetting(UserId userId, const QString &settingName, const QVariant &data) +void PostgreSqlStorage::setUserSetting(UserId userId, const QString& settingName, const QVariant& data) { QByteArray rawData; QDataStream out(&rawData, QIODevice::WriteOnly); @@ -377,8 +357,7 @@ void PostgreSqlStorage::setUserSetting(UserId userId, const QString &settingName watchQuery(setQuery); } - -QVariant PostgreSqlStorage::getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData) +QVariant PostgreSqlStorage::getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData) { QSqlQuery query(logDb()); query.prepare(queryString("select_user_setting")); @@ -400,8 +379,7 @@ QVariant PostgreSqlStorage::getUserSetting(UserId userId, const QString &setting } } - -void PostgreSqlStorage::setCoreState(const QVariantList &data) +void PostgreSqlStorage::setCoreState(const QVariantList& data) { QByteArray rawData; QDataStream out(&rawData, QIODevice::WriteOnly); @@ -431,8 +409,7 @@ void PostgreSqlStorage::setCoreState(const QVariantList &data) watchQuery(setQuery); } - -QVariantList PostgreSqlStorage::getCoreState(const QVariantList &defaultData) +QVariantList PostgreSqlStorage::getCoreState(const QVariantList& defaultData) { QSqlQuery query(logDb()); query.prepare(queryString("select_core_state")); @@ -447,13 +424,13 @@ QVariantList PostgreSqlStorage::getCoreState(const QVariantList &defaultData) in.setVersion(QDataStream::Qt_4_2); in >> data; return data; - } else { + } + else { return defaultData; } } - -IdentityId PostgreSqlStorage::createIdentity(UserId user, CoreIdentity &identity) +IdentityId PostgreSqlStorage::createIdentity(UserId user, CoreIdentity& identity) { IdentityId identityId; @@ -508,7 +485,7 @@ IdentityId PostgreSqlStorage::createIdentity(UserId user, CoreIdentity &identity QSqlQuery insertNickQuery(db); insertNickQuery.prepare(queryString("insert_nick")); - foreach(QString nick, identity.nicks()) { + foreach (QString nick, identity.nicks()) { insertNickQuery.bindValue(":identityid", identityId.toInt()); insertNickQuery.bindValue(":nick", nick); safeExec(insertNickQuery); @@ -526,8 +503,7 @@ IdentityId PostgreSqlStorage::createIdentity(UserId user, CoreIdentity &identity return identityId; } - -bool PostgreSqlStorage::updateIdentity(UserId user, const CoreIdentity &identity) +bool PostgreSqlStorage::updateIdentity(UserId user, const CoreIdentity& identity) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -594,7 +570,7 @@ bool PostgreSqlStorage::updateIdentity(UserId user, const CoreIdentity &identity QSqlQuery insertNickQuery(db); insertNickQuery.prepare(queryString("insert_nick")); - foreach(QString nick, identity.nicks()) { + foreach (QString nick, identity.nicks()) { insertNickQuery.bindValue(":identityid", identity.id().toInt()); insertNickQuery.bindValue(":nick", nick); safeExec(insertNickQuery); @@ -612,7 +588,6 @@ bool PostgreSqlStorage::updateIdentity(UserId user, const CoreIdentity &identity return true; } - void PostgreSqlStorage::removeIdentity(UserId user, IdentityId identityId) { QSqlDatabase db = logDb(); @@ -635,7 +610,6 @@ void PostgreSqlStorage::removeIdentity(UserId user, IdentityId identityId) } } - QList PostgreSqlStorage::identities(UserId user) { QList identities; @@ -696,8 +670,7 @@ QList PostgreSqlStorage::identities(UserId user) return identities; } - -NetworkId PostgreSqlStorage::createNetwork(UserId user, const NetworkInfo &info) +NetworkId PostgreSqlStorage::createNetwork(UserId user, const NetworkInfo& info) { NetworkId networkId; @@ -728,7 +701,7 @@ NetworkId PostgreSqlStorage::createNetwork(UserId user, const NetworkInfo &info) QSqlQuery insertServersQuery(db); insertServersQuery.prepare(queryString("insert_server")); - foreach(Network::Server server, info.serverList) { + foreach (Network::Server server, info.serverList) { insertServersQuery.bindValue(":userid", user.toInt()); insertServersQuery.bindValue(":networkid", networkId.toInt()); bindServerInfo(insertServersQuery, server); @@ -747,8 +720,7 @@ NetworkId PostgreSqlStorage::createNetwork(UserId user, const NetworkInfo &info) return networkId; } - -void PostgreSqlStorage::bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info) +void PostgreSqlStorage::bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info) { query.bindValue(":networkname", info.networkName); query.bindValue(":identityid", info.identity.isValid() ? info.identity.toInt() : QVariant()); @@ -777,8 +749,7 @@ void PostgreSqlStorage::bindNetworkInfo(QSqlQuery &query, const NetworkInfo &inf query.bindValue(":networkid", info.networkId.toInt()); } - -void PostgreSqlStorage::bindServerInfo(QSqlQuery &query, const Network::Server &server) +void PostgreSqlStorage::bindServerInfo(QSqlQuery& query, const Network::Server& server) { query.bindValue(":hostname", server.host); query.bindValue(":port", server.port); @@ -794,8 +765,7 @@ void PostgreSqlStorage::bindServerInfo(QSqlQuery &query, const Network::Server & query.bindValue(":sslverify", server.sslVerify); } - -bool PostgreSqlStorage::updateNetwork(UserId user, const NetworkInfo &info) +bool PostgreSqlStorage::updateNetwork(UserId user, const NetworkInfo& info) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -830,7 +800,7 @@ bool PostgreSqlStorage::updateNetwork(UserId user, const NetworkInfo &info) QSqlQuery insertServersQuery(db); insertServersQuery.prepare(queryString("insert_server")); - foreach(Network::Server server, info.serverList) { + foreach (Network::Server server, info.serverList) { insertServersQuery.bindValue(":userid", user.toInt()); insertServersQuery.bindValue(":networkid", info.networkId.toInt()); bindServerInfo(insertServersQuery, server); @@ -849,8 +819,7 @@ bool PostgreSqlStorage::updateNetwork(UserId user, const NetworkInfo &info) return true; } - -bool PostgreSqlStorage::removeNetwork(UserId user, const NetworkId &networkId) +bool PostgreSqlStorage::removeNetwork(UserId user, const NetworkId& networkId) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -873,7 +842,6 @@ bool PostgreSqlStorage::removeNetwork(UserId user, const NetworkId &networkId) return true; } - QList PostgreSqlStorage::networks(UserId user) { QList nets; @@ -956,7 +924,6 @@ QList PostgreSqlStorage::networks(UserId user) return nets; } - QList PostgreSqlStorage::connectedNetworks(UserId user) { QList connectedNets; @@ -982,8 +949,7 @@ QList PostgreSqlStorage::connectedNetworks(UserId user) return connectedNets; } - -void PostgreSqlStorage::setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) +void PostgreSqlStorage::setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) { QSqlQuery query(logDb()); query.prepare(queryString("update_network_connected")); @@ -994,8 +960,7 @@ void PostgreSqlStorage::setNetworkConnected(UserId user, const NetworkId &networ watchQuery(query); } - -QHash PostgreSqlStorage::persistentChannels(UserId user, const NetworkId &networkId) +QHash PostgreSqlStorage::persistentChannels(UserId user, const NetworkId& networkId) { QHash persistentChans; @@ -1021,8 +986,7 @@ QHash PostgreSqlStorage::persistentChannels(UserId user, const return persistentChans; } - -void PostgreSqlStorage::setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) +void PostgreSqlStorage::setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) { QSqlQuery query(logDb()); query.prepare(queryString("update_buffer_persistent_channel")); @@ -1034,8 +998,7 @@ void PostgreSqlStorage::setChannelPersistent(UserId user, const NetworkId &netwo watchQuery(query); } - -void PostgreSqlStorage::setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) +void PostgreSqlStorage::setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) { QSqlQuery query(logDb()); query.prepare(queryString("update_buffer_set_channel_key")); @@ -1047,7 +1010,6 @@ void PostgreSqlStorage::setPersistentChannelKey(UserId user, const NetworkId &ne watchQuery(query); } - QString PostgreSqlStorage::awayMessage(UserId user, NetworkId networkId) { QSqlQuery query(logDb()); @@ -1062,8 +1024,7 @@ QString PostgreSqlStorage::awayMessage(UserId user, NetworkId networkId) return awayMsg; } - -void PostgreSqlStorage::setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) +void PostgreSqlStorage::setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) { QSqlQuery query(logDb()); query.prepare(queryString("update_network_set_awaymsg")); @@ -1074,7 +1035,6 @@ void PostgreSqlStorage::setAwayMessage(UserId user, NetworkId networkId, const Q watchQuery(query); } - QString PostgreSqlStorage::userModes(UserId user, NetworkId networkId) { QSqlQuery query(logDb()); @@ -1089,8 +1049,7 @@ QString PostgreSqlStorage::userModes(UserId user, NetworkId networkId) return modes; } - -void PostgreSqlStorage::setUserModes(UserId user, NetworkId networkId, const QString &userModes) +void PostgreSqlStorage::setUserModes(UserId user, NetworkId networkId, const QString& userModes) { QSqlQuery query(logDb()); query.prepare(queryString("update_network_set_usermode")); @@ -1101,8 +1060,7 @@ void PostgreSqlStorage::setUserModes(UserId user, NetworkId networkId, const QSt watchQuery(query); } - -BufferInfo PostgreSqlStorage::bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer, bool create) +BufferInfo PostgreSqlStorage::bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer, bool create) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -1163,8 +1121,7 @@ BufferInfo PostgreSqlStorage::bufferInfo(UserId user, const NetworkId &networkId return bufferInfo; } - -BufferInfo PostgreSqlStorage::getBufferInfo(UserId user, const BufferId &bufferId) +BufferInfo PostgreSqlStorage::getBufferInfo(UserId user, const BufferId& bufferId) { QSqlQuery query(logDb()); query.prepare(queryString("select_buffer_by_id")); @@ -1177,13 +1134,16 @@ BufferInfo PostgreSqlStorage::getBufferInfo(UserId user, const BufferId &bufferI if (!query.first()) return {}; - BufferInfo bufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), 0, query.value(4).toString()); + BufferInfo bufferInfo(query.value(0).toInt(), + query.value(1).toInt(), + (BufferInfo::Type)query.value(2).toInt(), + 0, + query.value(4).toString()); Q_ASSERT(!query.next()); return bufferInfo; } - QList PostgreSqlStorage::requestBuffers(UserId user) { QList bufferlist; @@ -1202,13 +1162,16 @@ QList PostgreSqlStorage::requestBuffers(UserId user) safeExec(query); watchQuery(query); while (query.next()) { - bufferlist << BufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), query.value(3).toInt(), query.value(4).toString()); + bufferlist << BufferInfo(query.value(0).toInt(), + query.value(1).toInt(), + (BufferInfo::Type)query.value(2).toInt(), + query.value(3).toInt(), + query.value(4).toString()); } db.commit(); return bufferlist; } - QList PostgreSqlStorage::requestBufferIdsForNetwork(UserId user, NetworkId networkId) { QList bufferList; @@ -1234,8 +1197,7 @@ QList PostgreSqlStorage::requestBufferIdsForNetwork(UserId user, Netwo return bufferList; } - -bool PostgreSqlStorage::removeBuffer(const UserId &user, const BufferId &bufferId) +bool PostgreSqlStorage::removeBuffer(const UserId& user, const BufferId& bufferId) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -1263,14 +1225,14 @@ bool PostgreSqlStorage::removeBuffer(const UserId &user, const BufferId &bufferI return true; default: // there was more then one buffer deleted... - qWarning() << "PostgreSqlStorage::removeBuffer(): Userid" << user << "BufferId" << "caused deletion of" << numRows << "Buffers! Rolling back transaction..."; + qWarning() << "PostgreSqlStorage::removeBuffer(): Userid" << user << "BufferId" + << "caused deletion of" << numRows << "Buffers! Rolling back transaction..."; db.rollback(); return false; } } - -bool PostgreSqlStorage::renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) +bool PostgreSqlStorage::renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -1300,14 +1262,14 @@ bool PostgreSqlStorage::renameBuffer(const UserId &user, const BufferId &bufferI return true; default: // there was more then one buffer deleted... - qWarning() << "PostgreSqlStorage::renameBuffer(): Userid" << user << "BufferId" << "affected" << numRows << "Buffers! Rolling back transaction..."; + qWarning() << "PostgreSqlStorage::renameBuffer(): Userid" << user << "BufferId" + << "affected" << numRows << "Buffers! Rolling back transaction..."; db.rollback(); return false; } } - -bool PostgreSqlStorage::mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) +bool PostgreSqlStorage::mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -1357,8 +1319,7 @@ bool PostgreSqlStorage::mergeBuffersPermanently(const UserId &user, const Buffer return true; } - -void PostgreSqlStorage::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) +void PostgreSqlStorage::setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) { QSqlQuery query(logDb()); query.prepare(queryString("update_buffer_lastseen")); @@ -1370,7 +1331,6 @@ void PostgreSqlStorage::setBufferLastSeenMsg(UserId user, const BufferId &buffer watchQuery(query); } - QHash PostgreSqlStorage::bufferLastSeenMsgIds(UserId user) { QHash lastSeenHash; @@ -1399,8 +1359,7 @@ QHash PostgreSqlStorage::bufferLastSeenMsgIds(UserId user) return lastSeenHash; } - -void PostgreSqlStorage::setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) +void PostgreSqlStorage::setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) { QSqlQuery query(logDb()); query.prepare(queryString("update_buffer_markerlinemsgid")); @@ -1412,7 +1371,6 @@ void PostgreSqlStorage::setBufferMarkerLineMsg(UserId user, const BufferId &buff watchQuery(query); } - QHash PostgreSqlStorage::bufferMarkerLineMsgIds(UserId user) { QHash markerLineHash; @@ -1441,7 +1399,6 @@ QHash PostgreSqlStorage::bufferMarkerLineMsgIds(UserId user) return markerLineHash; } - void PostgreSqlStorage::setBufferActivity(UserId user, BufferId bufferId, Message::Types bufferActivity) { QSqlQuery query(logDb()); @@ -1449,7 +1406,7 @@ void PostgreSqlStorage::setBufferActivity(UserId user, BufferId bufferId, Messag query.bindValue(":userid", user.toInt()); query.bindValue(":bufferid", bufferId.toInt()); - query.bindValue(":bufferactivity", (int) bufferActivity); + query.bindValue(":bufferactivity", (int)bufferActivity); safeExec(query); watchQuery(query); } @@ -1496,7 +1453,7 @@ Message::Types PostgreSqlStorage::bufferActivity(BufferId bufferId, MsgId lastSe return result; } -QHash PostgreSqlStorage::bufferCiphers(UserId user, const NetworkId &networkId) +QHash PostgreSqlStorage::bufferCiphers(UserId user, const NetworkId& networkId) { QHash bufferCiphers; @@ -1522,7 +1479,7 @@ QHash PostgreSqlStorage::bufferCiphers(UserId user, const N return bufferCiphers; } -void PostgreSqlStorage::setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) +void PostgreSqlStorage::setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) { QSqlQuery query(logDb()); query.prepare(queryString("update_buffer_cipher")); @@ -1534,7 +1491,6 @@ void PostgreSqlStorage::setBufferCipher(UserId user, const NetworkId &networkId, watchQuery(query); } - void PostgreSqlStorage::setHighlightCount(UserId user, BufferId bufferId, int highlightcount) { QSqlQuery query(logDb()); @@ -1589,7 +1545,7 @@ int PostgreSqlStorage::highlightCount(BufferId bufferId, MsgId lastSeenMsgId) return result; } -bool PostgreSqlStorage::logMessage(Message &msg) +bool PostgreSqlStorage::logMessage(Message& msg) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -1599,9 +1555,7 @@ bool PostgreSqlStorage::logMessage(Message &msg) } QVariantList senderParams; - senderParams << msg.sender() - << msg.realName() - << msg.avatarUrl(); + senderParams << msg.sender() << msg.realName() << msg.avatarUrl(); QSqlQuery getSenderIdQuery = executePreparedQuery("select_senderid", senderParams, db); qint64 senderId; if (getSenderIdQuery.first()) { @@ -1630,12 +1584,7 @@ bool PostgreSqlStorage::logMessage(Message &msg) QVariantList params; // PostgreSQL handles QDateTime()'s serialized format by default, and QDateTime() serializes // to a 64-bit time compatible format by default. - params << msg.timestamp() - << msg.bufferInfo().bufferId().toInt() - << msg.type() - << (int)msg.flags() - << senderId - << msg.senderPrefixes() + params << msg.timestamp() << msg.bufferInfo().bufferId().toInt() << msg.type() << (int)msg.flags() << senderId << msg.senderPrefixes() << msg.contents(); QSqlQuery logMessageQuery = executePreparedQuery("insert_message", params, db); @@ -1656,8 +1605,7 @@ bool PostgreSqlStorage::logMessage(Message &msg) } } - -bool PostgreSqlStorage::logMessages(MessageList &msgs) +bool PostgreSqlStorage::logMessages(MessageList& msgs) { QSqlDatabase db = logDb(); if (!beginTransaction(db)) { @@ -1669,19 +1617,18 @@ bool PostgreSqlStorage::logMessages(MessageList &msgs) QList senderIdList; QHash senderIds; QSqlQuery addSenderQuery; - QSqlQuery selectSenderQuery;; + QSqlQuery selectSenderQuery; + ; for (int i = 0; i < msgs.count(); i++) { - auto &msg = msgs.at(i); - SenderData sender = { msg.sender(), msg.realName(), msg.avatarUrl() }; + auto& msg = msgs.at(i); + SenderData sender = {msg.sender(), msg.realName(), msg.avatarUrl()}; if (senderIds.contains(sender)) { senderIdList << senderIds[sender]; continue; } QVariantList senderParams; - senderParams << sender.sender - << sender.realname - << sender.avatarurl; + senderParams << sender.sender << sender.realname << sender.avatarurl; selectSenderQuery = executePreparedQuery("select_senderid", senderParams, db); if (selectSenderQuery.first()) { @@ -1712,17 +1659,12 @@ bool PostgreSqlStorage::logMessages(MessageList &msgs) // yes we loop twice over the same list. This avoids alternating queries. bool error = false; for (int i = 0; i < msgs.count(); i++) { - Message &msg = msgs[i]; + Message& msg = msgs[i]; QVariantList params; // PostgreSQL handles QDateTime()'s serialized format by default, and QDateTime() serializes // to a 64-bit time compatible format by default. - params << msg.timestamp() - << msg.bufferInfo().bufferId().toInt() - << msg.type() - << (int)msg.flags() - << senderIdList.at(i) - << msg.senderPrefixes() - << msg.contents(); + params << msg.timestamp() << msg.bufferInfo().bufferId().toInt() << msg.type() << (int)msg.flags() << senderIdList.at(i) + << msg.senderPrefixes() << msg.contents(); QSqlQuery logMessageQuery = executePreparedQuery("insert_message", params, db); if (!watchQuery(logMessageQuery)) { db.rollback(); @@ -1747,7 +1689,6 @@ bool PostgreSqlStorage::logMessages(MessageList &msgs) return true; } - QList PostgreSqlStorage::requestMsgs(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit) { QList messagelist; @@ -1800,14 +1741,14 @@ QList PostgreSqlStorage::requestMsgs(UserId user, BufferId bufferId, Ms timestamp = query.value(1).toDateTime(); timestamp.setTimeSpec(Qt::UTC); Message msg(timestamp, - bufferInfo, - (Message::Type)query.value(2).toInt(), - query.value(8).toString(), - query.value(4).toString(), - query.value(5).toString(), - query.value(6).toString(), - query.value(7).toString(), - (Message::Flags)query.value(3).toInt()); + bufferInfo, + (Message::Type)query.value(2).toInt(), + query.value(8).toString(), + query.value(4).toString(), + query.value(5).toString(), + query.value(6).toString(), + query.value(7).toString(), + (Message::Flags)query.value(3).toInt()); msg.setMsgId(query.value(0).toLongLong()); messagelist << msg; } @@ -1816,8 +1757,8 @@ QList PostgreSqlStorage::requestMsgs(UserId user, BufferId bufferId, Ms return messagelist; } - -QList PostgreSqlStorage::requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags) +QList PostgreSqlStorage::requestMsgsFiltered( + UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags) { QList messagelist; @@ -1837,10 +1778,12 @@ QList PostgreSqlStorage::requestMsgsFiltered(UserId user, BufferId buff QSqlQuery query(db); if (last == -1 && first == -1) { query.prepare(queryString("select_messagesNewestK_filtered")); - } else if (last == -1) { + } + else if (last == -1) { query.prepare(queryString("select_messagesNewerThan_filtered")); query.bindValue(":first", first.toQint64()); - } else { + } + else { query.prepare(queryString("select_messagesRange_filtered")); query.bindValue(":last", last.toQint64()); query.bindValue(":first", first.toQint64()); @@ -1882,14 +1825,13 @@ QList PostgreSqlStorage::requestMsgsFiltered(UserId user, BufferId buff return messagelist; } - QList PostgreSqlStorage::requestAllMsgs(UserId user, MsgId first, MsgId last, int limit) { QList messagelist; // requestBuffers uses it's own transaction. QHash bufferInfoHash; - foreach(BufferInfo bufferInfo, requestBuffers(user)) { + foreach (BufferInfo bufferInfo, requestBuffers(user)) { bufferInfoHash[bufferInfo.bufferId()] = bufferInfo; } @@ -1923,14 +1865,14 @@ QList PostgreSqlStorage::requestAllMsgs(UserId user, MsgId first, MsgId timestamp = query.value(2).toDateTime(); timestamp.setTimeSpec(Qt::UTC); Message msg(timestamp, - bufferInfoHash[query.value(1).toInt()], - (Message::Type)query.value(3).toInt(), - query.value(9).toString(), - query.value(5).toString(), - query.value(6).toString(), - query.value(7).toString(), - query.value(8).toString(), - (Message::Flags)query.value(4).toInt()); + bufferInfoHash[query.value(1).toInt()], + (Message::Type)query.value(3).toInt(), + query.value(9).toString(), + query.value(5).toString(), + query.value(6).toString(), + query.value(7).toString(), + query.value(8).toString(), + (Message::Flags)query.value(4).toInt()); msg.setMsgId(query.value(0).toLongLong()); messagelist << msg; } @@ -1939,16 +1881,16 @@ QList PostgreSqlStorage::requestAllMsgs(UserId user, MsgId first, MsgId return messagelist; } - -QList PostgreSqlStorage::requestAllMsgsFiltered(UserId user, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags) +QList PostgreSqlStorage::requestAllMsgsFiltered( + UserId user, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags) { QList messagelist; // requestBuffers uses it's own transaction. QHash bufferInfoHash; - foreach(BufferInfo bufferInfo, requestBuffers(user)) { - bufferInfoHash[bufferInfo.bufferId()] = bufferInfo; - } + foreach (BufferInfo bufferInfo, requestBuffers(user)) { + bufferInfoHash[bufferInfo.bufferId()] = bufferInfo; + } QSqlDatabase db = logDb(); if (!beginReadOnlyTransaction(db)) { @@ -2017,7 +1959,6 @@ QMap PostgreSqlStorage::getAllAuthUserNames() return authusernames; } - // void PostgreSqlStorage::safeExec(QSqlQuery &query) { // qDebug() << "PostgreSqlStorage::safeExec"; // qDebug() << " executing:\n" << query.executedQuery(); @@ -2041,8 +1982,7 @@ QMap PostgreSqlStorage::getAllAuthUserNames() // return; // } - -bool PostgreSqlStorage::beginTransaction(QSqlDatabase &db) +bool PostgreSqlStorage::beginTransaction(QSqlDatabase& db) { bool result = db.transaction(); if (!db.isOpen()) { @@ -2052,7 +1992,7 @@ bool PostgreSqlStorage::beginTransaction(QSqlDatabase &db) return result; } -bool PostgreSqlStorage::beginReadOnlyTransaction(QSqlDatabase &db) +bool PostgreSqlStorage::beginReadOnlyTransaction(QSqlDatabase& db) { QSqlQuery query = db.exec("BEGIN TRANSACTION READ ONLY"); if (!db.isOpen()) { @@ -2062,8 +2002,7 @@ bool PostgreSqlStorage::beginReadOnlyTransaction(QSqlDatabase &db) return !query.lastError().isValid(); } - -QSqlQuery PostgreSqlStorage::prepareAndExecuteQuery(const QString &queryname, const QString ¶mstring, QSqlDatabase &db) +QSqlQuery PostgreSqlStorage::prepareAndExecuteQuery(const QString& queryname, const QString& paramstring, QSqlDatabase& db) { // Query preparing is done lazily. That means that instead of always checking if the query is already prepared // we just EXECUTE and catch the error @@ -2082,18 +2021,21 @@ QSqlQuery PostgreSqlStorage::prepareAndExecuteQuery(const QString &queryname, co if (!db.isOpen()) { db = logDb(); if (!beginTransaction(db)) { - qWarning() << "PostgreSqlStorage::prepareAndExecuteQuery(): cannot start transaction while recovering from connection loss!"; + qWarning() + << "PostgreSqlStorage::prepareAndExecuteQuery(): cannot start transaction while recovering from connection loss!"; qWarning() << " -" << qPrintable(db.lastError().text()); return query; } db.exec("SAVEPOINT quassel_prepare_query"); - } else { + } + else { db.exec("ROLLBACK TO SAVEPOINT quassel_prepare_query"); } // and once again: Qt leaves us without error codes so we either parse (language dependent(!)) strings // or we just guess the error. As we're only interested in unprepared queries, this will be our guess. :) - QSqlQuery checkQuery = db.exec(QString("SELECT count(name) FROM pg_prepared_statements WHERE name = 'quassel_%1' AND from_sql = TRUE").arg(queryname.toLower())); + QSqlQuery checkQuery = db.exec( + QString("SELECT count(name) FROM pg_prepared_statements WHERE name = 'quassel_%1' AND from_sql = TRUE").arg(queryname.toLower())); checkQuery.first(); if (checkQuery.value(0).toInt() == 0) { db.exec(QString("PREPARE quassel_%1 AS %2").arg(queryname).arg(queryString(queryname))); @@ -2121,15 +2063,14 @@ QSqlQuery PostgreSqlStorage::prepareAndExecuteQuery(const QString &queryname, co return query; } - -QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString &queryname, const QVariantList ¶ms, QSqlDatabase &db) +QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString& queryname, const QVariantList& params, QSqlDatabase& db) { - QSqlDriver *driver = db.driver(); + QSqlDriver* driver = db.driver(); QStringList paramStrings; QSqlField field; for (int i = 0; i < params.count(); i++) { - const QVariant &value = params.at(i); + const QVariant& value = params.at(i); field.setType(value.type()); if (value.isNull()) field.clear(); @@ -2147,8 +2088,7 @@ QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString &queryname, cons } } - -QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString &queryname, const QVariant ¶m, QSqlDatabase &db) +QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString& queryname, const QVariant& param, QSqlDatabase& db) { QSqlField field; field.setType(param.type()); @@ -2161,27 +2101,23 @@ QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString &queryname, cons return prepareAndExecuteQuery(queryname, paramString, db); } - -void PostgreSqlStorage::deallocateQuery(const QString &queryname, const QSqlDatabase &db) +void PostgreSqlStorage::deallocateQuery(const QString& queryname, const QSqlDatabase& db) { db.exec(QString("DEALLOCATE quassel_%1").arg(queryname)); } - -void PostgreSqlStorage::safeExec(QSqlQuery &query) +void PostgreSqlStorage::safeExec(QSqlQuery& query) { // If the query fails due to the connection being gone, it seems to cause // exec() to return false but no lastError to be set - if(!query.exec() && !query.lastError().isValid()) - { + if (!query.exec() && !query.lastError().isValid()) { QSqlDatabase db = logDb(); QSqlQuery retryQuery(db); retryQuery.prepare(query.lastQuery()); QMapIterator i(query.boundValues()); - while (i.hasNext()) - { + while (i.hasNext()) { i.next(); - retryQuery.bindValue(i.key(),i.value()); + retryQuery.bindValue(i.key(), i.value()); } query = retryQuery; query.exec(); @@ -2193,9 +2129,7 @@ void PostgreSqlStorage::safeExec(QSqlQuery &query) // ======================================== PostgreSqlMigrationWriter::PostgreSqlMigrationWriter() : PostgreSqlStorage() -{ -} - +{} bool PostgreSqlMigrationWriter::prepareQuery(MigrationObject mo) { @@ -2237,9 +2171,8 @@ bool PostgreSqlMigrationWriter::prepareQuery(MigrationObject mo) return true; } - -//bool PostgreSqlMigrationWriter::writeUser(const QuasselUserMO &user) { -bool PostgreSqlMigrationWriter::writeMo(const QuasselUserMO &user) +// bool PostgreSqlMigrationWriter::writeUser(const QuasselUserMO &user) { +bool PostgreSqlMigrationWriter::writeMo(const QuasselUserMO& user) { bindValue(0, user.id.toInt()); bindValue(1, user.username); @@ -2249,9 +2182,8 @@ bool PostgreSqlMigrationWriter::writeMo(const QuasselUserMO &user) return exec(); } - -//bool PostgreSqlMigrationWriter::writeSender(const SenderMO &sender) { -bool PostgreSqlMigrationWriter::writeMo(const SenderMO &sender) +// bool PostgreSqlMigrationWriter::writeSender(const SenderMO &sender) { +bool PostgreSqlMigrationWriter::writeMo(const SenderMO& sender) { bindValue(0, sender.senderId); bindValue(1, sender.sender); @@ -2260,9 +2192,8 @@ bool PostgreSqlMigrationWriter::writeMo(const SenderMO &sender) return exec(); } - -//bool PostgreSqlMigrationWriter::writeIdentity(const IdentityMO &identity) { -bool PostgreSqlMigrationWriter::writeMo(const IdentityMO &identity) +// bool PostgreSqlMigrationWriter::writeIdentity(const IdentityMO &identity) { +bool PostgreSqlMigrationWriter::writeMo(const IdentityMO& identity) { _validIdentities << identity.id.toInt(); bindValue(0, identity.id.toInt()); @@ -2289,9 +2220,8 @@ bool PostgreSqlMigrationWriter::writeMo(const IdentityMO &identity) return exec(); } - -//bool PostgreSqlMigrationWriter::writeIdentityNick(const IdentityNickMO &identityNick) { -bool PostgreSqlMigrationWriter::writeMo(const IdentityNickMO &identityNick) +// bool PostgreSqlMigrationWriter::writeIdentityNick(const IdentityNickMO &identityNick) { +bool PostgreSqlMigrationWriter::writeMo(const IdentityNickMO& identityNick) { bindValue(0, identityNick.nickid); bindValue(1, identityNick.identityId.toInt()); @@ -2299,9 +2229,8 @@ bool PostgreSqlMigrationWriter::writeMo(const IdentityNickMO &identityNick) return exec(); } - -//bool PostgreSqlMigrationWriter::writeNetwork(const NetworkMO &network) { -bool PostgreSqlMigrationWriter::writeMo(const NetworkMO &network) +// bool PostgreSqlMigrationWriter::writeNetwork(const NetworkMO &network) { +bool PostgreSqlMigrationWriter::writeMo(const NetworkMO& network) { bindValue(0, network.networkid.toInt()); bindValue(1, network.userid.toInt()); @@ -2339,9 +2268,8 @@ bool PostgreSqlMigrationWriter::writeMo(const NetworkMO &network) return exec(); } - -//bool PostgreSqlMigrationWriter::writeBuffer(const BufferMO &buffer) { -bool PostgreSqlMigrationWriter::writeMo(const BufferMO &buffer) +// bool PostgreSqlMigrationWriter::writeBuffer(const BufferMO &buffer) { +bool PostgreSqlMigrationWriter::writeMo(const BufferMO& buffer) { bindValue(0, buffer.bufferid.toInt()); bindValue(1, buffer.userid.toInt()); @@ -2361,9 +2289,8 @@ bool PostgreSqlMigrationWriter::writeMo(const BufferMO &buffer) return exec(); } - -//bool PostgreSqlMigrationWriter::writeBacklog(const BacklogMO &backlog) { -bool PostgreSqlMigrationWriter::writeMo(const BacklogMO &backlog) +// bool PostgreSqlMigrationWriter::writeBacklog(const BacklogMO &backlog) { +bool PostgreSqlMigrationWriter::writeMo(const BacklogMO& backlog) { bindValue(0, backlog.messageid.toQint64()); bindValue(1, backlog.time); @@ -2376,9 +2303,8 @@ bool PostgreSqlMigrationWriter::writeMo(const BacklogMO &backlog) return exec(); } - -//bool PostgreSqlMigrationWriter::writeIrcServer(const IrcServerMO &ircserver) { -bool PostgreSqlMigrationWriter::writeMo(const IrcServerMO &ircserver) +// bool PostgreSqlMigrationWriter::writeIrcServer(const IrcServerMO &ircserver) { +bool PostgreSqlMigrationWriter::writeMo(const IrcServerMO& ircserver) { bindValue(0, ircserver.serverid); bindValue(1, ircserver.userid.toInt()); @@ -2398,9 +2324,8 @@ bool PostgreSqlMigrationWriter::writeMo(const IrcServerMO &ircserver) return exec(); } - -//bool PostgreSqlMigrationWriter::writeUserSetting(const UserSettingMO &userSetting) { -bool PostgreSqlMigrationWriter::writeMo(const UserSettingMO &userSetting) +// bool PostgreSqlMigrationWriter::writeUserSetting(const UserSettingMO &userSetting) { +bool PostgreSqlMigrationWriter::writeMo(const UserSettingMO& userSetting) { bindValue(0, userSetting.userid.toInt()); bindValue(1, userSetting.settingname); @@ -2408,26 +2333,20 @@ bool PostgreSqlMigrationWriter::writeMo(const UserSettingMO &userSetting) return exec(); } -bool PostgreSqlMigrationWriter::writeMo(const CoreStateMO &coreState) +bool PostgreSqlMigrationWriter::writeMo(const CoreStateMO& coreState) { bindValue(0, coreState.key); bindValue(1, coreState.value); return exec(); } - bool PostgreSqlMigrationWriter::postProcess() { QSqlDatabase db = logDb(); QList sequences; - sequences << Sequence("backlog", "messageid") - << Sequence("buffer", "bufferid") - << Sequence("identity", "identityid") - << Sequence("identity_nick", "nickid") - << Sequence("ircserver", "serverid") - << Sequence("network", "networkid") - << Sequence("quasseluser", "userid") - << Sequence("sender", "senderid"); + sequences << Sequence("backlog", "messageid") << Sequence("buffer", "bufferid") << Sequence("identity", "identityid") + << Sequence("identity_nick", "nickid") << Sequence("ircserver", "serverid") << Sequence("network", "networkid") + << Sequence("quasseluser", "userid") << Sequence("sender", "senderid"); QList::const_iterator iter; for (iter = sequences.constBegin(); iter != sequences.constEnd(); ++iter) { resetQuery(); diff --git a/src/core/postgresqlstorage.h b/src/core/postgresqlstorage.h index 2ea1e284..a90c8815 100644 --- a/src/core/postgresqlstorage.h +++ b/src/core/postgresqlstorage.h @@ -20,17 +20,17 @@ #pragma once -#include "abstractsqlstorage.h" - #include #include +#include "abstractsqlstorage.h" + class PostgreSqlStorage : public AbstractSqlStorage { Q_OBJECT public: - PostgreSqlStorage(QObject *parent = nullptr); + PostgreSqlStorage(QObject* parent = nullptr); std::unique_ptr createMigrationWriter() override; @@ -46,55 +46,55 @@ public slots: /* User handling */ - UserId addUser(const QString &user, const QString &password, const QString &authenticator = "Database") override; - bool updateUser(UserId user, const QString &password) override; - void renameUser(UserId user, const QString &newName) override; - UserId validateUser(const QString &user, const QString &password) override; - UserId getUserId(const QString &username) override; + UserId addUser(const QString& user, const QString& password, const QString& authenticator = "Database") override; + bool updateUser(UserId user, const QString& password) override; + void renameUser(UserId user, const QString& newName) override; + UserId validateUser(const QString& user, const QString& password) override; + UserId getUserId(const QString& username) override; QString getUserAuthenticator(const UserId userid) override; UserId internalUser() override; void delUser(UserId user) override; - void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) override; - QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData = QVariant()) override; - void setCoreState(const QVariantList &data) override; - QVariantList getCoreState(const QVariantList &data) override; + void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) override; + QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData = QVariant()) override; + void setCoreState(const QVariantList& data) override; + QVariantList getCoreState(const QVariantList& data) override; /* Identity handling */ - IdentityId createIdentity(UserId user, CoreIdentity &identity) override; - bool updateIdentity(UserId user, const CoreIdentity &identity) override; + IdentityId createIdentity(UserId user, CoreIdentity& identity) override; + bool updateIdentity(UserId user, const CoreIdentity& identity) override; void removeIdentity(UserId user, IdentityId identityId) override; QList identities(UserId user) override; /* Network handling */ - NetworkId createNetwork(UserId user, const NetworkInfo &info) override; - bool updateNetwork(UserId user, const NetworkInfo &info) override; - bool removeNetwork(UserId user, const NetworkId &networkId) override; + NetworkId createNetwork(UserId user, const NetworkInfo& info) override; + bool updateNetwork(UserId user, const NetworkInfo& info) override; + bool removeNetwork(UserId user, const NetworkId& networkId) override; QList networks(UserId user) override; QList connectedNetworks(UserId user) override; - void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) override; + void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) override; /* persistent channels */ - QHash persistentChannels(UserId user, const NetworkId &networkId) override; - void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) override; - void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) override; + QHash persistentChannels(UserId user, const NetworkId& networkId) override; + void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) override; + void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) override; /* persistent user states */ QString awayMessage(UserId user, NetworkId networkId) override; - void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) override; + void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) override; QString userModes(UserId user, NetworkId networkId) override; - void setUserModes(UserId user, NetworkId networkId, const QString &userModes) override; + void setUserModes(UserId user, NetworkId networkId, const QString& userModes) override; /* Buffer handling */ - BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) override; - BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) override; + BufferInfo bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true) override; + BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) override; QList requestBuffers(UserId user) override; QList requestBufferIdsForNetwork(UserId user, NetworkId networkId) override; - bool removeBuffer(const UserId &user, const BufferId &bufferId) override; - bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) override; - bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) override; - void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override; + bool removeBuffer(const UserId& user, const BufferId& bufferId) override; + bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) override; + bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) override; + void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override; QHash bufferLastSeenMsgIds(UserId user) override; - void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override; + void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override; QHash bufferMarkerLineMsgIds(UserId user) override; void setBufferActivity(UserId id, BufferId bufferId, Message::Types type) override; QHash bufferActivities(UserId id) override; @@ -102,18 +102,25 @@ public slots: void setHighlightCount(UserId id, BufferId bufferId, int count) override; QHash highlightCounts(UserId id) override; int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) override; - QHash bufferCiphers(UserId user, const NetworkId &networkId) override; - void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) override; + QHash bufferCiphers(UserId user, const NetworkId& networkId) override; + void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) override; /* Message handling */ - bool logMessage(Message &msg) override; - bool logMessages(MessageList &msgs) override; + bool logMessage(Message& msg) override; + bool logMessages(MessageList& msgs) override; QList requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1) override; - QList requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, - int limit = -1, Message::Types type = Message::Types{-1}, + QList requestMsgsFiltered(UserId user, + BufferId bufferId, + MsgId first = -1, + MsgId last = -1, + int limit = -1, + Message::Types type = Message::Types{-1}, Message::Flags flags = Message::Flags{-1}) override; QList requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1) override; - QList requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1, + QList requestAllMsgsFiltered(UserId user, + MsgId first = -1, + MsgId last = -1, + int limit = -1, Message::Types type = Message::Types{-1}, Message::Flags flags = Message::Flags{-1}) override; @@ -121,37 +128,38 @@ public slots: QMap getAllAuthUserNames() override; protected: - bool initDbSession(QSqlDatabase &db) override; - void setConnectionProperties(const QVariantMap &properties, - const QProcessEnvironment &environment, - bool loadFromEnvironment) override; - QString driverName() override { return "QPSQL"; } - QString hostName() override { return _hostName; } - int port() override { return _port; } - QString databaseName() override { return _databaseName; } - QString userName() override { return _userName; } - QString password() override { return _password; } + bool initDbSession(QSqlDatabase& db) override; + void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) override; + QString driverName() override { return "QPSQL"; } + QString hostName() override { return _hostName; } + int port() override { return _port; } + QString databaseName() override { return _databaseName; } + QString userName() override { return _userName; } + QString password() override { return _password; } int installedSchemaVersion() override; bool updateSchemaVersion(int newVersion) override; bool setupSchemaVersion(int version) override; - void safeExec(QSqlQuery &query); + void safeExec(QSqlQuery& query); - bool beginTransaction(QSqlDatabase &db); - bool beginReadOnlyTransaction(QSqlDatabase &db); + bool beginTransaction(QSqlDatabase& db); + bool beginReadOnlyTransaction(QSqlDatabase& db); - QSqlQuery executePreparedQuery(const QString &queryname, const QVariantList ¶ms, QSqlDatabase &db); - QSqlQuery executePreparedQuery(const QString &queryname, const QVariant ¶m, QSqlDatabase &db); - void deallocateQuery(const QString &queryname, const QSqlDatabase &db); + QSqlQuery executePreparedQuery(const QString& queryname, const QVariantList& params, QSqlDatabase& db); + QSqlQuery executePreparedQuery(const QString& queryname, const QVariant& param, QSqlDatabase& db); + void deallocateQuery(const QString& queryname, const QSqlDatabase& db); - void savePoint(const QString &handle, const QSqlDatabase &db) { db.exec(QString("SAVEPOINT %1").arg(handle)); } - void rollbackSavePoint(const QString &handle, const QSqlDatabase &db) { db.exec(QString("ROLLBACK TO SAVEPOINT %1").arg(handle)); } - void releaseSavePoint(const QString &handle, const QSqlDatabase &db) { db.exec(QString("RELEASE SAVEPOINT %1").arg(handle)); } + void savePoint(const QString& handle, const QSqlDatabase& db) { db.exec(QString("SAVEPOINT %1").arg(handle)); } + void rollbackSavePoint(const QString& handle, const QSqlDatabase& db) { db.exec(QString("ROLLBACK TO SAVEPOINT %1").arg(handle)); } + void releaseSavePoint(const QString& handle, const QSqlDatabase& db) { db.exec(QString("RELEASE SAVEPOINT %1").arg(handle)); } private: - void bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info); - void bindServerInfo(QSqlQuery &query, const Network::Server &server); - QSqlQuery prepareAndExecuteQuery(const QString &queryname, const QString ¶mstring, QSqlDatabase &db); - QSqlQuery prepareAndExecuteQuery(const QString &queryname, QSqlDatabase &db) { return prepareAndExecuteQuery(queryname, QString(), db); } + void bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info); + void bindServerInfo(QSqlQuery& query, const Network::Server& server); + QSqlQuery prepareAndExecuteQuery(const QString& queryname, const QString& paramstring, QSqlDatabase& db); + QSqlQuery prepareAndExecuteQuery(const QString& queryname, QSqlDatabase& db) + { + return prepareAndExecuteQuery(queryname, QString(), db); + } QString _hostName; int _port{-1}; @@ -160,7 +168,6 @@ private: QString _password; }; - // ======================================== // PostgreSqlMigration // ======================================== @@ -171,32 +178,36 @@ class PostgreSqlMigrationWriter : public PostgreSqlStorage, public AbstractSqlMi public: PostgreSqlMigrationWriter(); - bool writeMo(const QuasselUserMO &user) override; - bool writeMo(const SenderMO &sender) override; - bool writeMo(const IdentityMO &identity) override; - bool writeMo(const IdentityNickMO &identityNick) override; - bool writeMo(const NetworkMO &network) override; - bool writeMo(const BufferMO &buffer) override; - bool writeMo(const BacklogMO &backlog) override; - bool writeMo(const IrcServerMO &ircserver) override; - bool writeMo(const UserSettingMO &userSetting) override; - bool writeMo(const CoreStateMO &coreState) override; + bool writeMo(const QuasselUserMO& user) override; + bool writeMo(const SenderMO& sender) override; + bool writeMo(const IdentityMO& identity) override; + bool writeMo(const IdentityNickMO& identityNick) override; + bool writeMo(const NetworkMO& network) override; + bool writeMo(const BufferMO& buffer) override; + bool writeMo(const BacklogMO& backlog) override; + bool writeMo(const IrcServerMO& ircserver) override; + bool writeMo(const UserSettingMO& userSetting) override; + bool writeMo(const CoreStateMO& coreState) override; bool prepareQuery(MigrationObject mo) override; bool postProcess() override; protected: - inline bool transaction() override { return logDb().transaction(); } - inline void rollback() override { logDb().rollback(); } - inline bool commit() override { return logDb().commit(); } + inline bool transaction() override { return logDb().transaction(); } + inline void rollback() override { logDb().rollback(); } + inline bool commit() override { return logDb().commit(); } private: // helper struct - struct Sequence { + struct Sequence + { QLatin1String table; QLatin1String field; - Sequence(const char *table, const char *field) : table(table), field(field) {} + Sequence(const char* table, const char* field) + : table(table) + , field(field) + {} }; QSet _validIdentities; diff --git a/src/core/sessionthread.cpp b/src/core/sessionthread.cpp index 80ecdd39..6dc47cf7 100644 --- a/src/core/sessionthread.cpp +++ b/src/core/sessionthread.cpp @@ -18,6 +18,8 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include "sessionthread.h" + #include #include @@ -25,7 +27,6 @@ #include "coresession.h" #include "internalpeer.h" #include "remotepeer.h" -#include "sessionthread.h" #include "signalproxy.h" namespace { @@ -39,8 +40,7 @@ public: : _userId{userId} , _restoreState{restoreState} , _strictIdentEnabled{strictIdentEnabled} - { - } + {} public slots: void initialize() @@ -58,7 +58,7 @@ public slots: } } - void addClient(Peer *peer) + void addClient(Peer* peer) { if (!_session) { qWarning() << "Session not initialized!"; @@ -89,9 +89,9 @@ private: QPointer _session; }; -} // anon +} // namespace -SessionThread::SessionThread(UserId uid, bool restoreState, bool strictIdentEnabled, QObject *parent) +SessionThread::SessionThread(UserId uid, bool restoreState, bool strictIdentEnabled, QObject* parent) : QObject(parent) { auto worker = new Worker(uid, restoreState, strictIdentEnabled); @@ -108,7 +108,6 @@ SessionThread::SessionThread(UserId uid, bool restoreState, bool strictIdentEnab QTimer::singleShot(0, &_sessionThread, SLOT(start())); } - SessionThread::~SessionThread() { // shut down thread gracefully @@ -116,17 +115,15 @@ SessionThread::~SessionThread() _sessionThread.wait(30000); } - void SessionThread::shutdown() { emit shutdownSession(); } - void SessionThread::onSessionInitialized() { _sessionInitialized = true; - for (auto &&peer : _clientQueue) { + for (auto&& peer : _clientQueue) { peer->setParent(nullptr); peer->moveToThread(&_sessionThread); emit addClientToWorker(peer); @@ -134,13 +131,12 @@ void SessionThread::onSessionInitialized() _clientQueue.clear(); } - void SessionThread::onSessionDestroyed() { emit shutdownComplete(this); } -void SessionThread::addClient(Peer *peer) +void SessionThread::addClient(Peer* peer) { if (_sessionInitialized) { peer->setParent(nullptr); diff --git a/src/core/sessionthread.h b/src/core/sessionthread.h index e3607545..e0778e35 100644 --- a/src/core/sessionthread.h +++ b/src/core/sessionthread.h @@ -36,11 +36,11 @@ class SessionThread : public QObject Q_OBJECT public: - SessionThread(UserId user, bool restoreState, bool strictIdentEnabled, QObject *parent = nullptr); + SessionThread(UserId user, bool restoreState, bool strictIdentEnabled, QObject* parent = nullptr); ~SessionThread() override; public slots: - void addClient(Peer *peer); + void addClient(Peer* peer); void shutdown(); private slots: @@ -50,13 +50,13 @@ private slots: signals: void initialized(); void shutdownSession(); - void shutdownComplete(SessionThread *); + void shutdownComplete(SessionThread*); - void addClientToWorker(Peer *peer); + void addClientToWorker(Peer* peer); private: QThread _sessionThread; bool _sessionInitialized{false}; - std::vector _clientQueue; + std::vector _clientQueue; }; diff --git a/src/core/sqlauthenticator.cpp b/src/core/sqlauthenticator.cpp index 969f2d02..94c759c4 100644 --- a/src/core/sqlauthenticator.cpp +++ b/src/core/sqlauthenticator.cpp @@ -20,17 +20,14 @@ #include "sqlauthenticator.h" +#include "core.h" #include "logmessage.h" #include "network.h" #include "quassel.h" -#include "core.h" - -SqlAuthenticator::SqlAuthenticator(QObject *parent) +SqlAuthenticator::SqlAuthenticator(QObject* parent) : Authenticator(parent) -{ -} - +{} bool SqlAuthenticator::isAvailable() const { @@ -38,7 +35,6 @@ bool SqlAuthenticator::isAvailable() const return true; } - QString SqlAuthenticator::backendId() const { // We identify the backend to use for the monolithic core by this identifier. @@ -47,28 +43,23 @@ QString SqlAuthenticator::backendId() const return QString("Database"); } - QString SqlAuthenticator::displayName() const { return tr("Database"); } - QString SqlAuthenticator::description() const { return tr("Do not authenticate against any remote service, but instead save a hashed and salted password " "in the database selected in the next step."); } - -UserId SqlAuthenticator::validateUser(const QString &user, const QString &password) +UserId SqlAuthenticator::validateUser(const QString& user, const QString& password) { return Core::validateUser(user, password); } - -bool SqlAuthenticator::setup(const QVariantMap &settings, const QProcessEnvironment &environment, - bool loadFromEnvironment) +bool SqlAuthenticator::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) { Q_UNUSED(settings) Q_UNUSED(environment) @@ -76,10 +67,7 @@ bool SqlAuthenticator::setup(const QVariantMap &settings, const QProcessEnvironm return true; } - -Authenticator::State SqlAuthenticator::init(const QVariantMap &settings, - const QProcessEnvironment &environment, - bool loadFromEnvironment) +Authenticator::State SqlAuthenticator::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) { Q_UNUSED(settings) Q_UNUSED(environment) diff --git a/src/core/sqlauthenticator.h b/src/core/sqlauthenticator.h index 8336151b..c94aaca9 100644 --- a/src/core/sqlauthenticator.h +++ b/src/core/sqlauthenticator.h @@ -27,7 +27,7 @@ class SqlAuthenticator : public Authenticator Q_OBJECT public: - SqlAuthenticator(QObject *parent = nullptr); + SqlAuthenticator(QObject* parent = nullptr); public slots: /* General */ @@ -39,12 +39,10 @@ public slots: inline bool canChangePassword() const override { return true; } - bool setup(const QVariantMap &settings, const QProcessEnvironment &environment, - bool loadFromEnvironment) override; - State init(const QVariantMap &settings, const QProcessEnvironment &environment, - bool loadFromEnvironment) override; - UserId validateUser(const QString &user, const QString &password) override; + bool setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override; + State init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override; + UserId validateUser(const QString& user, const QString& password) override; /* User handling */ - //virtual UserId getUserId(const QString &username); + // virtual UserId getUserId(const QString &username); }; diff --git a/src/core/sqlitestorage.cpp b/src/core/sqlitestorage.cpp index ad5b7f2b..2d06421e 100644 --- a/src/core/sqlitestorage.cpp +++ b/src/core/sqlitestorage.cpp @@ -28,25 +28,22 @@ int SqliteStorage::_maxRetryCount = 150; -SqliteStorage::SqliteStorage(QObject *parent) +SqliteStorage::SqliteStorage(QObject* parent) : AbstractSqlStorage(parent) -{ -} - +{} bool SqliteStorage::isAvailable() const { - if (!QSqlDatabase::isDriverAvailable("QSQLITE")) return false; + if (!QSqlDatabase::isDriverAvailable("QSQLITE")) + return false; return true; } - QString SqliteStorage::backendId() const { return QString("SQLite"); } - QString SqliteStorage::displayName() const { // Note: Pre-0.13 clients use the displayName property for backend idenfication @@ -56,7 +53,6 @@ QString SqliteStorage::displayName() const return backendId(); } - QString SqliteStorage::description() const { return tr("SQLite is a file-based database engine that does not require any setup. It is suitable for small and medium-sized " @@ -64,7 +60,6 @@ QString SqliteStorage::description() const "it is running on, and if you only expect a few users to use your core."); } - int SqliteStorage::installedSchemaVersion() { // only used when there is a singlethread (during startup) @@ -81,7 +76,6 @@ int SqliteStorage::installedSchemaVersion() return AbstractSqlStorage::installedSchemaVersion(); } - bool SqliteStorage::updateSchemaVersion(int newVersion) { // only used when there is a singlethread (during startup) @@ -99,7 +93,6 @@ bool SqliteStorage::updateSchemaVersion(int newVersion) return success; } - bool SqliteStorage::setupSchemaVersion(int version) { // only used when there is a singlethread (during startup) @@ -117,8 +110,7 @@ bool SqliteStorage::setupSchemaVersion(int version) return success; } - -UserId SqliteStorage::addUser(const QString &user, const QString &password, const QString &authenticator) +UserId SqliteStorage::addUser(const QString& user, const QString& password, const QString& authenticator) { QSqlDatabase db = logDb(); UserId uid; @@ -136,7 +128,8 @@ UserId SqliteStorage::addUser(const QString &user, const QString &password, cons query.bindValue(":authenticator", authenticator); lockForWrite(); safeExec(query); - if (query.lastError().isValid() && query.lastError().number() == 19) { // user already exists - sadly 19 seems to be the general constraint violation error... + if (query.lastError().isValid() + && query.lastError().number() == 19) { // user already exists - sadly 19 seems to be the general constraint violation error... db.rollback(); } else { @@ -151,8 +144,7 @@ UserId SqliteStorage::addUser(const QString &user, const QString &password, cons return uid; } - -bool SqliteStorage::updateUser(UserId user, const QString &password) +bool SqliteStorage::updateUser(UserId user, const QString& password) { QSqlDatabase db = logDb(); bool success = false; @@ -173,8 +165,7 @@ bool SqliteStorage::updateUser(UserId user, const QString &password) return success; } - -void SqliteStorage::renameUser(UserId user, const QString &newName) +void SqliteStorage::renameUser(UserId user, const QString& newName) { QSqlDatabase db = logDb(); db.transaction(); @@ -191,8 +182,7 @@ void SqliteStorage::renameUser(UserId user, const QString &newName) emit userRenamed(user, newName); } - -UserId SqliteStorage::validateUser(const QString &user, const QString &password) +UserId SqliteStorage::validateUser(const QString& user, const QString& password) { UserId userId; QString hashedPassword; @@ -221,8 +211,7 @@ UserId SqliteStorage::validateUser(const QString &user, const QString &password) return returnUserId; } - -UserId SqliteStorage::getUserId(const QString &username) +UserId SqliteStorage::getUserId(const QString& username) { UserId userId; @@ -283,7 +272,6 @@ UserId SqliteStorage::internalUser() return userId; } - void SqliteStorage::delUser(UserId user) { QSqlDatabase db = logDb(); @@ -315,8 +303,7 @@ void SqliteStorage::delUser(UserId user) emit userRemoved(user); } - -void SqliteStorage::setUserSetting(UserId userId, const QString &settingName, const QVariant &data) +void SqliteStorage::setUserSetting(UserId userId, const QString& settingName, const QVariant& data) { QByteArray rawData; QDataStream out(&rawData, QIODevice::WriteOnly); @@ -347,8 +334,7 @@ void SqliteStorage::setUserSetting(UserId userId, const QString &settingName, co unlock(); } - -QVariant SqliteStorage::getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData) +QVariant SqliteStorage::getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData) { QVariant data = defaultData; { @@ -370,8 +356,7 @@ QVariant SqliteStorage::getUserSetting(UserId userId, const QString &settingName return data; } - -void SqliteStorage::setCoreState(const QVariantList &data) +void SqliteStorage::setCoreState(const QVariantList& data) { QByteArray rawData; QDataStream out(&rawData, QIODevice::WriteOnly); @@ -400,8 +385,7 @@ void SqliteStorage::setCoreState(const QVariantList &data) unlock(); } - -QVariantList SqliteStorage::getCoreState(const QVariantList &defaultData) +QVariantList SqliteStorage::getCoreState(const QVariantList& defaultData) { QVariantList data; { @@ -416,7 +400,8 @@ QVariantList SqliteStorage::getCoreState(const QVariantList &defaultData) QDataStream in(&rawData, QIODevice::ReadOnly); in.setVersion(QDataStream::Qt_4_2); in >> data; - } else { + } + else { data = defaultData; } } @@ -424,8 +409,7 @@ QVariantList SqliteStorage::getCoreState(const QVariantList &defaultData) return data; } - -IdentityId SqliteStorage::createIdentity(UserId user, CoreIdentity &identity) +IdentityId SqliteStorage::createIdentity(UserId user, CoreIdentity& identity) { IdentityId identityId; @@ -476,7 +460,7 @@ IdentityId SqliteStorage::createIdentity(UserId user, CoreIdentity &identity) QSqlQuery insertNickQuery(db); insertNickQuery.prepare(queryString("insert_nick")); - foreach(QString nick, identity.nicks()) { + foreach (QString nick, identity.nicks()) { insertNickQuery.bindValue(":identityid", identityId.toInt()); insertNickQuery.bindValue(":nick", nick); safeExec(insertNickQuery); @@ -489,8 +473,7 @@ IdentityId SqliteStorage::createIdentity(UserId user, CoreIdentity &identity) return identityId; } - -bool SqliteStorage::updateIdentity(UserId user, const CoreIdentity &identity) +bool SqliteStorage::updateIdentity(UserId user, const CoreIdentity& identity) { QSqlDatabase db = logDb(); bool error = false; @@ -551,7 +534,7 @@ bool SqliteStorage::updateIdentity(UserId user, const CoreIdentity &identity) QSqlQuery insertNickQuery(db); insertNickQuery.prepare(queryString("insert_nick")); - foreach(QString nick, identity.nicks()) { + foreach (QString nick, identity.nicks()) { insertNickQuery.bindValue(":identityid", identity.id().toInt()); insertNickQuery.bindValue(":nick", nick); safeExec(insertNickQuery); @@ -563,7 +546,6 @@ bool SqliteStorage::updateIdentity(UserId user, const CoreIdentity &identity) return true; } - void SqliteStorage::removeIdentity(UserId user, IdentityId identityId) { QSqlDatabase db = logDb(); @@ -602,7 +584,6 @@ void SqliteStorage::removeIdentity(UserId user, IdentityId identityId) unlock(); } - QList SqliteStorage::identities(UserId user) { QList identities; @@ -661,8 +642,7 @@ QList SqliteStorage::identities(UserId user) return identities; } - -NetworkId SqliteStorage::createNetwork(UserId user, const NetworkInfo &info) +NetworkId SqliteStorage::createNetwork(UserId user, const NetworkInfo& info) { NetworkId networkId; @@ -693,7 +673,7 @@ NetworkId SqliteStorage::createNetwork(UserId user, const NetworkInfo &info) { QSqlQuery insertServersQuery(db); insertServersQuery.prepare(queryString("insert_server")); - foreach(Network::Server server, info.serverList) { + foreach (Network::Server server, info.serverList) { insertServersQuery.bindValue(":userid", user.toInt()); insertServersQuery.bindValue(":networkid", networkId.toInt()); bindServerInfo(insertServersQuery, server); @@ -714,8 +694,7 @@ NetworkId SqliteStorage::createNetwork(UserId user, const NetworkInfo &info) return networkId; } - -void SqliteStorage::bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info) +void SqliteStorage::bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info) { query.bindValue(":networkname", info.networkName); query.bindValue(":identityid", info.identity.toInt()); @@ -744,8 +723,7 @@ void SqliteStorage::bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info) query.bindValue(":networkid", info.networkId.toInt()); } - -void SqliteStorage::bindServerInfo(QSqlQuery &query, const Network::Server &server) +void SqliteStorage::bindServerInfo(QSqlQuery& query, const Network::Server& server) { query.bindValue(":hostname", server.host); query.bindValue(":port", server.port); @@ -761,8 +739,7 @@ void SqliteStorage::bindServerInfo(QSqlQuery &query, const Network::Server &serv query.bindValue(":sslverify", server.sslVerify ? 1 : 0); } - -bool SqliteStorage::updateNetwork(UserId user, const NetworkInfo &info) +bool SqliteStorage::updateNetwork(UserId user, const NetworkInfo& info) { QSqlDatabase db = logDb(); bool error = false; @@ -804,7 +781,7 @@ bool SqliteStorage::updateNetwork(UserId user, const NetworkInfo &info) { QSqlQuery insertServersQuery(db); insertServersQuery.prepare(queryString("insert_server")); - foreach(Network::Server server, info.serverList) { + foreach (Network::Server server, info.serverList) { insertServersQuery.bindValue(":userid", user.toInt()); insertServersQuery.bindValue(":networkid", info.networkId.toInt()); bindServerInfo(insertServersQuery, server); @@ -822,8 +799,7 @@ bool SqliteStorage::updateNetwork(UserId user, const NetworkInfo &info) return !error; } - -bool SqliteStorage::removeNetwork(UserId user, const NetworkId &networkId) +bool SqliteStorage::removeNetwork(UserId user, const NetworkId& networkId) { QSqlDatabase db = logDb(); bool error = false; @@ -896,7 +872,6 @@ bool SqliteStorage::removeNetwork(UserId user, const NetworkId &networkId) return true; } - QList SqliteStorage::networks(UserId user) { QList nets; @@ -977,7 +952,6 @@ QList SqliteStorage::networks(UserId user) return nets; } - QList SqliteStorage::connectedNetworks(UserId user) { QList connectedNets; @@ -1002,8 +976,7 @@ QList SqliteStorage::connectedNetworks(UserId user) return connectedNets; } - -void SqliteStorage::setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) +void SqliteStorage::setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) { QSqlDatabase db = logDb(); db.transaction(); @@ -1023,8 +996,7 @@ void SqliteStorage::setNetworkConnected(UserId user, const NetworkId &networkId, unlock(); } - -QHash SqliteStorage::persistentChannels(UserId user, const NetworkId &networkId) +QHash SqliteStorage::persistentChannels(UserId user, const NetworkId& networkId) { QHash persistentChans; @@ -1047,8 +1019,7 @@ QHash SqliteStorage::persistentChannels(UserId user, const Net return persistentChans; } - -void SqliteStorage::setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) +void SqliteStorage::setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) { QSqlDatabase db = logDb(); db.transaction(); @@ -1069,8 +1040,7 @@ void SqliteStorage::setChannelPersistent(UserId user, const NetworkId &networkId unlock(); } - -void SqliteStorage::setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) +void SqliteStorage::setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) { QSqlDatabase db = logDb(); db.transaction(); @@ -1091,7 +1061,6 @@ void SqliteStorage::setPersistentChannelKey(UserId user, const NetworkId &networ unlock(); } - QString SqliteStorage::awayMessage(UserId user, NetworkId networkId) { QSqlDatabase db = logDb(); @@ -1116,8 +1085,7 @@ QString SqliteStorage::awayMessage(UserId user, NetworkId networkId) return awayMsg; } - -void SqliteStorage::setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) +void SqliteStorage::setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) { QSqlDatabase db = logDb(); db.transaction(); @@ -1137,7 +1105,6 @@ void SqliteStorage::setAwayMessage(UserId user, NetworkId networkId, const QStri unlock(); } - QString SqliteStorage::userModes(UserId user, NetworkId networkId) { QSqlDatabase db = logDb(); @@ -1162,8 +1129,7 @@ QString SqliteStorage::userModes(UserId user, NetworkId networkId) return modes; } - -void SqliteStorage::setUserModes(UserId user, NetworkId networkId, const QString &userModes) +void SqliteStorage::setUserModes(UserId user, NetworkId networkId, const QString& userModes) { QSqlDatabase db = logDb(); db.transaction(); @@ -1183,8 +1149,7 @@ void SqliteStorage::setUserModes(UserId user, NetworkId networkId, const QString unlock(); } - -BufferInfo SqliteStorage::bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer, bool create) +BufferInfo SqliteStorage::bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer, bool create) { QSqlDatabase db = logDb(); db.transaction(); @@ -1235,8 +1200,7 @@ BufferInfo SqliteStorage::bufferInfo(UserId user, const NetworkId &networkId, Bu return bufferInfo; } - -BufferInfo SqliteStorage::getBufferInfo(UserId user, const BufferId &bufferId) +BufferInfo SqliteStorage::getBufferInfo(UserId user, const BufferId& bufferId) { QSqlDatabase db = logDb(); db.transaction(); @@ -1252,7 +1216,11 @@ BufferInfo SqliteStorage::getBufferInfo(UserId user, const BufferId &bufferId) safeExec(query); if (watchQuery(query) && query.first()) { - bufferInfo = BufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), 0, query.value(4).toString()); + bufferInfo = BufferInfo(query.value(0).toInt(), + query.value(1).toInt(), + (BufferInfo::Type)query.value(2).toInt(), + 0, + query.value(4).toString()); Q_ASSERT(!query.next()); } db.commit(); @@ -1261,7 +1229,6 @@ BufferInfo SqliteStorage::getBufferInfo(UserId user, const BufferId &bufferId) return bufferInfo; } - QList SqliteStorage::requestBuffers(UserId user) { QList bufferlist; @@ -1278,7 +1245,11 @@ QList SqliteStorage::requestBuffers(UserId user) safeExec(query); watchQuery(query); while (query.next()) { - bufferlist << BufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), query.value(3).toInt(), query.value(4).toString()); + bufferlist << BufferInfo(query.value(0).toInt(), + query.value(1).toInt(), + (BufferInfo::Type)query.value(2).toInt(), + query.value(3).toInt(), + query.value(4).toString()); } db.commit(); } @@ -1287,7 +1258,6 @@ QList SqliteStorage::requestBuffers(UserId user) return bufferlist; } - QList SqliteStorage::requestBufferIdsForNetwork(UserId user, NetworkId networkId) { QList bufferList; @@ -1314,8 +1284,7 @@ QList SqliteStorage::requestBufferIdsForNetwork(UserId user, NetworkId return bufferList; } - -bool SqliteStorage::removeBuffer(const UserId &user, const BufferId &bufferId) +bool SqliteStorage::removeBuffer(const UserId& user, const BufferId& bufferId) { QSqlDatabase db = logDb(); db.transaction(); @@ -1358,8 +1327,7 @@ bool SqliteStorage::removeBuffer(const UserId &user, const BufferId &bufferId) return !error; } - -bool SqliteStorage::renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) +bool SqliteStorage::renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) { QSqlDatabase db = logDb(); db.transaction(); @@ -1395,8 +1363,7 @@ bool SqliteStorage::renameBuffer(const UserId &user, const BufferId &bufferId, c return !error; } - -bool SqliteStorage::mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) +bool SqliteStorage::mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) { QSqlDatabase db = logDb(); db.transaction(); @@ -1452,8 +1419,7 @@ bool SqliteStorage::mergeBuffersPermanently(const UserId &user, const BufferId & return !error; } - -void SqliteStorage::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) +void SqliteStorage::setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) { QSqlDatabase db = logDb(); db.transaction(); @@ -1473,7 +1439,6 @@ void SqliteStorage::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, unlock(); } - QHash SqliteStorage::bufferLastSeenMsgIds(UserId user) { QHash lastSeenHash; @@ -1502,8 +1467,7 @@ QHash SqliteStorage::bufferLastSeenMsgIds(UserId user) return lastSeenHash; } - -void SqliteStorage::setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) +void SqliteStorage::setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) { QSqlDatabase db = logDb(); db.transaction(); @@ -1523,7 +1487,6 @@ void SqliteStorage::setBufferMarkerLineMsg(UserId user, const BufferId &bufferId unlock(); } - QHash SqliteStorage::bufferMarkerLineMsgIds(UserId user) { QHash markerLineHash; @@ -1562,7 +1525,7 @@ void SqliteStorage::setBufferActivity(UserId user, BufferId bufferId, Message::T query.prepare(queryString("update_buffer_bufferactivity")); query.bindValue(":userid", user.toInt()); query.bindValue(":bufferid", bufferId.toInt()); - query.bindValue(":bufferactivity", (int) bufferActivity); + query.bindValue(":bufferactivity", (int)bufferActivity); lockForWrite(); safeExec(query); @@ -1572,7 +1535,6 @@ void SqliteStorage::setBufferActivity(UserId user, BufferId bufferId, Message::T unlock(); } - QHash SqliteStorage::bufferActivities(UserId user) { QHash bufferActivityHash; @@ -1601,7 +1563,6 @@ QHash SqliteStorage::bufferActivities(UserId user) return bufferActivityHash; } - Message::Types SqliteStorage::bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) { QSqlDatabase db = logDb(); @@ -1625,7 +1586,7 @@ Message::Types SqliteStorage::bufferActivity(BufferId bufferId, MsgId lastSeenMs return result; } -QHash SqliteStorage::bufferCiphers(UserId user, const NetworkId &networkId) +QHash SqliteStorage::bufferCiphers(UserId user, const NetworkId& networkId) { QHash bufferCiphers; @@ -1648,7 +1609,7 @@ QHash SqliteStorage::bufferCiphers(UserId user, const Netwo return bufferCiphers; } -void SqliteStorage::setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) +void SqliteStorage::setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) { QSqlDatabase db = logDb(); db.transaction(); @@ -1689,7 +1650,6 @@ void SqliteStorage::setHighlightCount(UserId user, BufferId bufferId, int count) unlock(); } - QHash SqliteStorage::highlightCounts(UserId user) { QHash highlightCountHash; @@ -1718,7 +1678,6 @@ QHash SqliteStorage::highlightCounts(UserId user) return highlightCountHash; } - int SqliteStorage::highlightCount(BufferId bufferId, MsgId lastSeenMsgId) { QSqlDatabase db = logDb(); @@ -1742,7 +1701,7 @@ int SqliteStorage::highlightCount(BufferId bufferId, MsgId lastSeenMsgId) return result; } -bool SqliteStorage::logMessage(Message &msg) +bool SqliteStorage::logMessage(Message& msg) { QSqlDatabase db = logDb(); db.transaction(); @@ -1804,8 +1763,7 @@ bool SqliteStorage::logMessage(Message &msg) return !error; } - -bool SqliteStorage::logMessages(MessageList &msgs) +bool SqliteStorage::logMessages(MessageList& msgs) { QSqlDatabase db = logDb(); db.transaction(); @@ -1816,8 +1774,8 @@ bool SqliteStorage::logMessages(MessageList &msgs) addSenderQuery.prepare(queryString("insert_sender")); lockForWrite(); for (int i = 0; i < msgs.count(); i++) { - auto &msg = msgs.at(i); - SenderData sender = { msg.sender(), msg.realName(), msg.avatarUrl() }; + auto& msg = msgs.at(i); + SenderData sender = {msg.sender(), msg.realName(), msg.avatarUrl()}; if (senders.contains(sender)) continue; senders << sender; @@ -1834,7 +1792,7 @@ bool SqliteStorage::logMessages(MessageList &msgs) QSqlQuery logMessageQuery(db); logMessageQuery.prepare(queryString("insert_message")); for (int i = 0; i < msgs.count(); i++) { - Message &msg = msgs[i]; + Message& msg = msgs[i]; // As of SQLite schema version 31, timestamps are stored in milliseconds instead of // seconds. This nets us more precision as well as simplifying 64-bit time. logMessageQuery.bindValue(":time", msg.timestamp().toMSecsSinceEpoch()); @@ -1873,7 +1831,6 @@ bool SqliteStorage::logMessages(MessageList &msgs) return !error; } - QList SqliteStorage::requestMsgs(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit) { QList messagelist; @@ -1895,7 +1852,11 @@ QList SqliteStorage::requestMsgs(UserId user, BufferId bufferId, MsgId safeExec(bufferInfoQuery); error = !watchQuery(bufferInfoQuery) || !bufferInfoQuery.first(); if (!error) { - bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), 0, bufferInfoQuery.value(4).toString()); + bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), + bufferInfoQuery.value(1).toInt(), + (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), + 0, + bufferInfoQuery.value(4).toString()); error = !bufferInfo.isValid(); } } @@ -1948,8 +1909,8 @@ QList SqliteStorage::requestMsgs(UserId user, BufferId bufferId, MsgId return messagelist; } - -QList SqliteStorage::requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags) +QList SqliteStorage::requestMsgsFiltered( + UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags) { QList messagelist; @@ -1970,7 +1931,11 @@ QList SqliteStorage::requestMsgsFiltered(UserId user, BufferId bufferId safeExec(bufferInfoQuery); error = !watchQuery(bufferInfoQuery) || !bufferInfoQuery.first(); if (!error) { - bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), 0, bufferInfoQuery.value(4).toString()); + bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), + bufferInfoQuery.value(1).toInt(), + (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), + 0, + bufferInfoQuery.value(4).toString()); error = !bufferInfo.isValid(); } } @@ -2006,18 +1971,18 @@ QList SqliteStorage::requestMsgsFiltered(UserId user, BufferId bufferId while (query.next()) { Message msg( - // As of SQLite schema version 31, timestamps are stored in milliseconds - // instead of seconds. This nets us more precision as well as simplifying - // 64-bit time. - QDateTime::fromMSecsSinceEpoch(query.value(1).toLongLong()), - bufferInfo, - (Message::Type)query.value(2).toInt(), - query.value(8).toString(), - query.value(4).toString(), - query.value(5).toString(), - query.value(6).toString(), - query.value(7).toString(), - Message::Flags{query.value(3).toInt()}); + // As of SQLite schema version 31, timestamps are stored in milliseconds + // instead of seconds. This nets us more precision as well as simplifying + // 64-bit time. + QDateTime::fromMSecsSinceEpoch(query.value(1).toLongLong()), + bufferInfo, + (Message::Type)query.value(2).toInt(), + query.value(8).toString(), + query.value(4).toString(), + query.value(5).toString(), + query.value(6).toString(), + query.value(7).toString(), + Message::Flags{query.value(3).toInt()}); msg.setMsgId(query.value(0).toLongLong()); messagelist << msg; } @@ -2028,7 +1993,6 @@ QList SqliteStorage::requestMsgsFiltered(UserId user, BufferId bufferId return messagelist; } - QList SqliteStorage::requestAllMsgs(UserId user, MsgId first, MsgId last, int limit) { QList messagelist; @@ -2046,7 +2010,11 @@ QList SqliteStorage::requestAllMsgs(UserId user, MsgId first, MsgId las safeExec(bufferInfoQuery); watchQuery(bufferInfoQuery); while (bufferInfoQuery.next()) { - BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), bufferInfoQuery.value(3).toInt(), bufferInfoQuery.value(4).toString()); + BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), + bufferInfoQuery.value(1).toInt(), + (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), + bufferInfoQuery.value(3).toInt(), + bufferInfoQuery.value(4).toString()); bufferInfoHash[bufferInfo.bufferId()] = bufferInfo; } @@ -2104,7 +2072,11 @@ QList SqliteStorage::requestAllMsgsFiltered(UserId user, MsgId first, M safeExec(bufferInfoQuery); watchQuery(bufferInfoQuery); while (bufferInfoQuery.next()) { - BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), bufferInfoQuery.value(3).toInt(), bufferInfoQuery.value(4).toString()); + BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), + bufferInfoQuery.value(1).toInt(), + (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), + bufferInfoQuery.value(3).toInt(), + bufferInfoQuery.value(4).toString()); bufferInfoHash[bufferInfo.bufferId()] = bufferInfo; } @@ -2129,18 +2101,18 @@ QList SqliteStorage::requestAllMsgsFiltered(UserId user, MsgId first, M while (query.next()) { Message msg( - // As of SQLite schema version 31, timestamps are stored in milliseconds - // instead of seconds. This nets us more precision as well as simplifying - // 64-bit time. - QDateTime::fromMSecsSinceEpoch(query.value(2).toLongLong()), - bufferInfoHash[query.value(1).toInt()], - (Message::Type)query.value(3).toInt(), - query.value(9).toString(), - query.value(5).toString(), - query.value(6).toString(), - query.value(7).toString(), - query.value(8).toString(), - Message::Flags{query.value(4).toInt()}); + // As of SQLite schema version 31, timestamps are stored in milliseconds + // instead of seconds. This nets us more precision as well as simplifying + // 64-bit time. + QDateTime::fromMSecsSinceEpoch(query.value(2).toLongLong()), + bufferInfoHash[query.value(1).toInt()], + (Message::Type)query.value(3).toInt(), + query.value(9).toString(), + query.value(5).toString(), + query.value(6).toString(), + query.value(7).toString(), + query.value(8).toString(), + Message::Flags{query.value(4).toInt()}); msg.setMsgId(query.value(0).toLongLong()); messagelist << msg; } @@ -2172,14 +2144,12 @@ QMap SqliteStorage::getAllAuthUserNames() return authusernames; } - QString SqliteStorage::backlogFile() { return Quassel::configDirPath() + "quassel-storage.sqlite"; } - -bool SqliteStorage::safeExec(QSqlQuery &query, int retryCount) +bool SqliteStorage::safeExec(QSqlQuery& query, int retryCount) { query.exec(); @@ -2187,9 +2157,9 @@ bool SqliteStorage::safeExec(QSqlQuery &query, int retryCount) return true; switch (query.lastError().number()) { - case 5: // SQLITE_BUSY 5 /* The database file is locked */ - // fallthrough - case 6: // SQLITE_LOCKED 6 /* A table in the database is locked */ + case 5: // SQLITE_BUSY 5 /* The database file is locked */ + // fallthrough + case 6: // SQLITE_LOCKED 6 /* A table in the database is locked */ if (retryCount < _maxRetryCount) return safeExec(query, retryCount + 1); break; @@ -2199,15 +2169,12 @@ bool SqliteStorage::safeExec(QSqlQuery &query, int retryCount) return false; } - // ======================================== // SqliteMigration // ======================================== SqliteMigrationReader::SqliteMigrationReader() : SqliteStorage() -{ -} - +{} void SqliteMigrationReader::setMaxId(MigrationObject mo) { @@ -2228,7 +2195,6 @@ void SqliteMigrationReader::setMaxId(MigrationObject mo) _maxId = query.value(0).toLongLong(); } - bool SqliteMigrationReader::prepareQuery(MigrationObject mo) { setMaxId(mo); @@ -2272,8 +2238,7 @@ bool SqliteMigrationReader::prepareQuery(MigrationObject mo) return exec(); } - -bool SqliteMigrationReader::readMo(QuasselUserMO &user) +bool SqliteMigrationReader::readMo(QuasselUserMO& user) { if (!next()) return false; @@ -2286,8 +2251,7 @@ bool SqliteMigrationReader::readMo(QuasselUserMO &user) return true; } - -bool SqliteMigrationReader::readMo(IdentityMO &identity) +bool SqliteMigrationReader::readMo(IdentityMO& identity) { if (!next()) return false; @@ -2316,8 +2280,7 @@ bool SqliteMigrationReader::readMo(IdentityMO &identity) return true; } - -bool SqliteMigrationReader::readMo(IdentityNickMO &identityNick) +bool SqliteMigrationReader::readMo(IdentityNickMO& identityNick) { if (!next()) return false; @@ -2328,8 +2291,7 @@ bool SqliteMigrationReader::readMo(IdentityNickMO &identityNick) return true; } - -bool SqliteMigrationReader::readMo(NetworkMO &network) +bool SqliteMigrationReader::readMo(NetworkMO& network) { if (!next()) return false; @@ -2367,8 +2329,7 @@ bool SqliteMigrationReader::readMo(NetworkMO &network) return true; } - -bool SqliteMigrationReader::readMo(BufferMO &buffer) +bool SqliteMigrationReader::readMo(BufferMO& buffer) { if (!next()) return false; @@ -2391,8 +2352,7 @@ bool SqliteMigrationReader::readMo(BufferMO &buffer) return true; } - -bool SqliteMigrationReader::readMo(SenderMO &sender) +bool SqliteMigrationReader::readMo(SenderMO& sender) { int skipSteps = 0; while (!next()) { @@ -2415,8 +2375,7 @@ bool SqliteMigrationReader::readMo(SenderMO &sender) return true; } - -bool SqliteMigrationReader::readMo(BacklogMO &backlog) +bool SqliteMigrationReader::readMo(BacklogMO& backlog) { qint64 skipSteps = 0; while (!next()) { @@ -2445,8 +2404,7 @@ bool SqliteMigrationReader::readMo(BacklogMO &backlog) return true; } - -bool SqliteMigrationReader::readMo(IrcServerMO &ircserver) +bool SqliteMigrationReader::readMo(IrcServerMO& ircserver) { if (!next()) return false; @@ -2469,8 +2427,7 @@ bool SqliteMigrationReader::readMo(IrcServerMO &ircserver) return true; } - -bool SqliteMigrationReader::readMo(UserSettingMO &userSetting) +bool SqliteMigrationReader::readMo(UserSettingMO& userSetting) { if (!next()) return false; @@ -2482,8 +2439,7 @@ bool SqliteMigrationReader::readMo(UserSettingMO &userSetting) return true; } - -bool SqliteMigrationReader::readMo(CoreStateMO &coreState) +bool SqliteMigrationReader::readMo(CoreStateMO& coreState) { if (!next()) return false; diff --git a/src/core/sqlitestorage.h b/src/core/sqlitestorage.h index 58ae08c8..902953b9 100644 --- a/src/core/sqlitestorage.h +++ b/src/core/sqlitestorage.h @@ -20,10 +20,10 @@ #pragma once -#include "abstractsqlstorage.h" - #include +#include "abstractsqlstorage.h" + class QSqlQuery; class SqliteStorage : public AbstractSqlStorage @@ -31,71 +31,71 @@ class SqliteStorage : public AbstractSqlStorage Q_OBJECT public: - SqliteStorage(QObject *parent = nullptr); + SqliteStorage(QObject* parent = nullptr); std::unique_ptr createMigrationReader() override; public slots: /* General */ - bool isAvailable() const override; + bool isAvailable() const override; QString backendId() const override; QString displayName() const override; - QVariantList setupData() const override { return {}; } + QVariantList setupData() const override { return {}; } QString description() const override; // TODO: Add functions for configuring the backlog handling, i.e. defining auto-cleanup settings etc /* User handling */ - UserId addUser(const QString &user, const QString &password, const QString &authenticator = "Database") override; - bool updateUser(UserId user, const QString &password) override; - void renameUser(UserId user, const QString &newName) override; - UserId validateUser(const QString &user, const QString &password) override; - UserId getUserId(const QString &username) override; + UserId addUser(const QString& user, const QString& password, const QString& authenticator = "Database") override; + bool updateUser(UserId user, const QString& password) override; + void renameUser(UserId user, const QString& newName) override; + UserId validateUser(const QString& user, const QString& password) override; + UserId getUserId(const QString& username) override; QString getUserAuthenticator(const UserId userid) override; UserId internalUser() override; void delUser(UserId user) override; - void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) override; - QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData = QVariant()) override; - void setCoreState(const QVariantList &data) override; - QVariantList getCoreState(const QVariantList &data) override; + void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) override; + QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData = QVariant()) override; + void setCoreState(const QVariantList& data) override; + QVariantList getCoreState(const QVariantList& data) override; /* Identity handling */ - IdentityId createIdentity(UserId user, CoreIdentity &identity) override; - bool updateIdentity(UserId user, const CoreIdentity &identity) override; + IdentityId createIdentity(UserId user, CoreIdentity& identity) override; + bool updateIdentity(UserId user, const CoreIdentity& identity) override; void removeIdentity(UserId user, IdentityId identityId) override; QList identities(UserId user) override; /* Network handling */ - NetworkId createNetwork(UserId user, const NetworkInfo &info) override; - bool updateNetwork(UserId user, const NetworkInfo &info) override; - bool removeNetwork(UserId user, const NetworkId &networkId) override; + NetworkId createNetwork(UserId user, const NetworkInfo& info) override; + bool updateNetwork(UserId user, const NetworkInfo& info) override; + bool removeNetwork(UserId user, const NetworkId& networkId) override; QList networks(UserId user) override; QList connectedNetworks(UserId user) override; - void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) override; + void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) override; /* persistent channels */ - QHash persistentChannels(UserId user, const NetworkId &networkId) override; - void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) override; - void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) override; + QHash persistentChannels(UserId user, const NetworkId& networkId) override; + void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) override; + void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) override; /* persistent user states */ QString awayMessage(UserId user, NetworkId networkId) override; - void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) override; + void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) override; QString userModes(UserId user, NetworkId networkId) override; - void setUserModes(UserId user, NetworkId networkId, const QString &userModes) override; + void setUserModes(UserId user, NetworkId networkId, const QString& userModes) override; /* Buffer handling */ - BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) override; - BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) override; + BufferInfo bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true) override; + BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) override; QList requestBuffers(UserId user) override; QList requestBufferIdsForNetwork(UserId user, NetworkId networkId) override; - bool removeBuffer(const UserId &user, const BufferId &bufferId) override; - bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) override; - bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) override; - void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override; + bool removeBuffer(const UserId& user, const BufferId& bufferId) override; + bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) override; + bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) override; + void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override; QHash bufferLastSeenMsgIds(UserId user) override; - void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override; + void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override; QHash bufferMarkerLineMsgIds(UserId user) override; void setBufferActivity(UserId id, BufferId bufferId, Message::Types type) override; QHash bufferActivities(UserId id) override; @@ -103,18 +103,25 @@ public slots: void setHighlightCount(UserId id, BufferId bufferId, int count) override; QHash highlightCounts(UserId id) override; int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) override; - QHash bufferCiphers(UserId user, const NetworkId &networkId) override; - void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) override; + QHash bufferCiphers(UserId user, const NetworkId& networkId) override; + void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) override; /* Message handling */ - bool logMessage(Message &msg) override; - bool logMessages(MessageList &msgs) override; + bool logMessage(Message& msg) override; + bool logMessages(MessageList& msgs) override; QList requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1) override; - QList requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, - int limit = -1, Message::Types type = Message::Types{-1}, + QList requestMsgsFiltered(UserId user, + BufferId bufferId, + MsgId first = -1, + MsgId last = -1, + int limit = -1, + Message::Types type = Message::Types{-1}, Message::Flags flags = Message::Flags{-1}) override; QList requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1) override; - QList requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1, + QList requestAllMsgsFiltered(UserId user, + MsgId first = -1, + MsgId last = -1, + int limit = -1, Message::Types type = Message::Types{-1}, Message::Flags flags = Message::Flags{-1}) override; @@ -122,25 +129,24 @@ public slots: QMap getAllAuthUserNames() override; protected: - void setConnectionProperties(const QVariantMap &properties, - const QProcessEnvironment &environment, - bool loadFromEnvironment) override { + void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) override + { Q_UNUSED(properties); Q_UNUSED(environment); Q_UNUSED(loadFromEnvironment); } // SQLite does not have any connection properties to set - QString driverName() override { return "QSQLITE"; } - QString databaseName() override { return backlogFile(); } + QString driverName() override { return "QSQLITE"; } + QString databaseName() override { return backlogFile(); } int installedSchemaVersion() override; bool updateSchemaVersion(int newVersion) override; bool setupSchemaVersion(int version) override; - bool safeExec(QSqlQuery &query, int retryCount = 0); + bool safeExec(QSqlQuery& query, int retryCount = 0); private: static QString backlogFile(); - void bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info); - void bindServerInfo(QSqlQuery &query, const Network::Server &server); + void bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info); + void bindServerInfo(QSqlQuery& query, const Network::Server& server); inline void lockForRead() { _dbLock.lockForRead(); } inline void lockForWrite() { _dbLock.lockForWrite(); } @@ -149,7 +155,6 @@ private: static int _maxRetryCount; }; - // ======================================== // SqliteMigration // ======================================== @@ -160,32 +165,31 @@ class SqliteMigrationReader : public SqliteStorage, public AbstractSqlMigrationR public: SqliteMigrationReader(); - bool readMo(QuasselUserMO &user) override; - bool readMo(SenderMO &sender) override; - bool readMo(IdentityMO &identity) override; - bool readMo(IdentityNickMO &identityNick) override; - bool readMo(NetworkMO &network) override; - bool readMo(BufferMO &buffer) override; - bool readMo(BacklogMO &backlog) override; - bool readMo(IrcServerMO &ircserver) override; - bool readMo(UserSettingMO &userSetting) override; - bool readMo(CoreStateMO &coreState) override; + bool readMo(QuasselUserMO& user) override; + bool readMo(SenderMO& sender) override; + bool readMo(IdentityMO& identity) override; + bool readMo(IdentityNickMO& identityNick) override; + bool readMo(NetworkMO& network) override; + bool readMo(BufferMO& buffer) override; + bool readMo(BacklogMO& backlog) override; + bool readMo(IrcServerMO& ircserver) override; + bool readMo(UserSettingMO& userSetting) override; + bool readMo(CoreStateMO& coreState) override; bool prepareQuery(MigrationObject mo) override; qint64 stepSize() { return 50000; } protected: - bool transaction() override { return logDb().transaction(); } - void rollback() override { logDb().rollback(); } - bool commit() override { return logDb().commit(); } + bool transaction() override { return logDb().transaction(); } + void rollback() override { logDb().rollback(); } + bool commit() override { return logDb().commit(); } private: void setMaxId(MigrationObject mo); qint64 _maxId{0}; }; - inline std::unique_ptr SqliteStorage::createMigrationReader() { return std::unique_ptr{new SqliteMigrationReader()}; diff --git a/src/core/sslserver.cpp b/src/core/sslserver.cpp index b8c010fa..c076a5fe 100644 --- a/src/core/sslserver.cpp +++ b/src/core/sslserver.cpp @@ -21,48 +21,48 @@ #include "sslserver.h" #ifdef HAVE_SSL -# include +# include #endif #include -#include "quassel.h" #include "logmessage.h" +#include "quassel.h" #ifdef HAVE_SSL -SslServer::SslServer(QObject *parent) +SslServer::SslServer(QObject* parent) : QTcpServer(parent) { // Keep track if the SSL warning has been mentioned at least once before static bool sslWarningShown = false; - if(Quassel::isOptionSet("ssl-cert")) { + if (Quassel::isOptionSet("ssl-cert")) { _sslCertPath = Quassel::optionValue("ssl-cert"); - } else { + } + else { _sslCertPath = Quassel::configDirPath() + "quasselCert.pem"; } - if(Quassel::isOptionSet("ssl-key")) { + if (Quassel::isOptionSet("ssl-key")) { _sslKeyPath = Quassel::optionValue("ssl-key"); - } else { + } + else { _sslKeyPath = _sslCertPath; } // Initialize the certificates for first-time usage if (!loadCerts()) { if (!sslWarningShown) { - quWarning() - << "SslServer: Unable to set certificate file\n" - << " Quassel Core will still work, but cannot provide SSL for client connections.\n" - << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support."; + quWarning() << "SslServer: Unable to set certificate file\n" + << " Quassel Core will still work, but cannot provide SSL for client connections.\n" + << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support."; sslWarningShown = true; } } } - -QTcpSocket *SslServer::nextPendingConnection() +QTcpSocket* SslServer::nextPendingConnection() { if (_pendingConnections.isEmpty()) return nullptr; @@ -70,10 +70,9 @@ QTcpSocket *SslServer::nextPendingConnection() return _pendingConnections.takeFirst(); } - void SslServer::incomingConnection(qintptr socketDescriptor) { - auto *serverSocket = new QSslSocket(this); + auto* serverSocket = new QSslSocket(this); if (serverSocket->setSocketDescriptor(socketDescriptor)) { if (isCertValid()) { serverSocket->setLocalCertificate(_cert); @@ -88,38 +87,35 @@ void SslServer::incomingConnection(qintptr socketDescriptor) } } - bool SslServer::loadCerts() { // Load the certificates specified in the path. If needed, other prep work can be done here. return setCertificate(_sslCertPath, _sslKeyPath); } - bool SslServer::reloadCerts() { if (loadCerts()) { return true; - } else { + } + else { // Reloading certificates currently only occur in response to a request. Always print an // error if something goes wrong, in order to simplify checking if it's working. if (isCertValid()) { - quWarning() - << "SslServer: Unable to reload certificate file, reverting\n" - << " Quassel Core will use the previous key to provide SSL for client connections.\n" - << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support."; - } else { - quWarning() - << "SslServer: Unable to reload certificate file\n" - << " Quassel Core will still work, but cannot provide SSL for client connections.\n" - << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support."; + quWarning() << "SslServer: Unable to reload certificate file, reverting\n" + << " Quassel Core will use the previous key to provide SSL for client connections.\n" + << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support."; + } + else { + quWarning() << "SslServer: Unable to reload certificate file\n" + << " Quassel Core will still work, but cannot provide SSL for client connections.\n" + << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support."; } return false; } } - -bool SslServer::setCertificate(const QString &path, const QString &keyPath) +bool SslServer::setCertificate(const QString& path, const QString& keyPath) { // Don't reset _isCertValid here, in case an older but valid certificate is still loaded. // Use temporary variables in order to avoid overwriting the existing certificates until @@ -138,9 +134,7 @@ bool SslServer::setCertificate(const QString &path, const QString &keyPath) } if (!certFile.open(QIODevice::ReadOnly)) { - quWarning() - << "SslServer: Failed to open certificate file" << qPrintable(path) - << "error:" << certFile.error(); + quWarning() << "SslServer: Failed to open certificate file" << qPrintable(path) << "error:" << certFile.error(); return false; } @@ -152,7 +146,7 @@ bool SslServer::setCertificate(const QString &path, const QString &keyPath) } untestedCert = certList[0]; - certList.removeFirst(); // remove server cert + certList.removeFirst(); // remove server cert // store CA and intermediates certs untestedCA = certList; @@ -163,23 +157,22 @@ bool SslServer::setCertificate(const QString &path, const QString &keyPath) } // load key from keyPath if it differs from path, otherwise load key from path - if(path != keyPath) { + if (path != keyPath) { QFile keyFile(keyPath); - if(!keyFile.exists()) { + if (!keyFile.exists()) { quWarning() << "SslServer: Key file" << qPrintable(keyPath) << "does not exist"; return false; } if (!keyFile.open(QIODevice::ReadOnly)) { - quWarning() - << "SslServer: Failed to open key file" << qPrintable(keyPath) - << "error:" << keyFile.error(); + quWarning() << "SslServer: Failed to open key file" << qPrintable(keyPath) << "error:" << keyFile.error(); return false; } untestedKey = loadKey(&keyFile); keyFile.close(); - } else { + } + else { untestedKey = loadKey(&certFile); } @@ -217,8 +210,7 @@ bool SslServer::setCertificate(const QString &path, const QString &keyPath) return _isCertValid; } - -QSslKey SslServer::loadKey(QFile *keyFile) +QSslKey SslServer::loadKey(QFile* keyFile) { QSslKey key; key = QSslKey(keyFile, QSsl::Rsa); @@ -232,5 +224,4 @@ QSslKey SslServer::loadKey(QFile *keyFile) return key; } - -#endif // HAVE_SSL +#endif // HAVE_SSL diff --git a/src/core/sslserver.h b/src/core/sslserver.h index 6ca1b915..61cc2223 100644 --- a/src/core/sslserver.h +++ b/src/core/sslserver.h @@ -22,24 +22,24 @@ #ifdef HAVE_SSL -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include class SslServer : public QTcpServer { Q_OBJECT public: - SslServer(QObject *parent = nullptr); + SslServer(QObject* parent = nullptr); bool hasPendingConnections() const override { return !_pendingConnections.isEmpty(); } - QTcpSocket *nextPendingConnection() override; + QTcpSocket* nextPendingConnection() override; - const QSslCertificate &certificate() const { return _cert; } - const QSslKey &key() const { return _key; } + const QSslCertificate& certificate() const { return _cert; } + const QSslKey& key() const { return _key; } bool isCertValid() const { return _isCertValid; } /** @@ -55,7 +55,7 @@ public: protected: void incomingConnection(qintptr socketDescriptor) override; - bool setCertificate(const QString &path, const QString &keyPath); + bool setCertificate(const QString& path, const QString& keyPath); private: /** @@ -67,18 +67,17 @@ private: * @return True if certificates loaded successfully, otherwise false. */ bool loadCerts(); - QSslKey loadKey(QFile *keyFile); + QSslKey loadKey(QFile* keyFile); - QLinkedList _pendingConnections; + QLinkedList _pendingConnections; QSslCertificate _cert; QSslKey _key; QList _ca; bool _isCertValid{false}; // Used when reloading certificates later - QString _sslCertPath; /// Path to the certificate file - QString _sslKeyPath; /// Path to the private key file (may be in same file as above) + QString _sslCertPath; /// Path to the certificate file + QString _sslKeyPath; /// Path to the private key file (may be in same file as above) }; - -#endif //HAVE_SSL +#endif // HAVE_SSL diff --git a/src/core/storage.cpp b/src/core/storage.cpp index 92892563..98ae9680 100644 --- a/src/core/storage.cpp +++ b/src/core/storage.cpp @@ -24,17 +24,16 @@ #include -Storage::Storage(QObject *parent) +Storage::Storage(QObject* parent) : QObject(parent) -{ -} +{} -QString Storage::hashPassword(const QString &password) +QString Storage::hashPassword(const QString& password) { return hashPasswordSha2_512(password); } -bool Storage::checkHashedPassword(const UserId user, const QString &password, const QString &hashedPassword, const Storage::HashVersion version) +bool Storage::checkHashedPassword(const UserId user, const QString& password, const QString& hashedPassword, const Storage::HashVersion version) { bool passwordCorrect = false; @@ -58,17 +57,17 @@ bool Storage::checkHashedPassword(const UserId user, const QString &password, co return passwordCorrect; } -QString Storage::hashPasswordSha1(const QString &password) +QString Storage::hashPasswordSha1(const QString& password) { return QString(QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha1).toHex()); } -bool Storage::checkHashedPasswordSha1(const QString &password, const QString &hashedPassword) +bool Storage::checkHashedPasswordSha1(const QString& password, const QString& hashedPassword) { return hashPasswordSha1(password) == hashedPassword; } -QString Storage::hashPasswordSha2_512(const QString &password) +QString Storage::hashPasswordSha2_512(const QString& password) { // Generate a salt of 512 bits (64 bytes) using the Mersenne Twister std::random_device seed; @@ -77,7 +76,7 @@ QString Storage::hashPasswordSha2_512(const QString &password) QByteArray saltBytes; saltBytes.resize(64); for (int i = 0; i < 64; i++) { - saltBytes[i] = (unsigned char) distribution(generator); + saltBytes[i] = (unsigned char)distribution(generator); } QString salt(saltBytes.toHex()); @@ -85,12 +84,12 @@ QString Storage::hashPasswordSha2_512(const QString &password) return sha2_512(password + salt) + ":" + salt; } -bool Storage::checkHashedPasswordSha2_512(const QString &password, const QString &hashedPassword) +bool Storage::checkHashedPasswordSha2_512(const QString& password, const QString& hashedPassword) { QRegExp colonSplitter("\\:"); QStringList hashedPasswordAndSalt = hashedPassword.split(colonSplitter); - if (hashedPasswordAndSalt.size() == 2){ + if (hashedPasswordAndSalt.size() == 2) { return sha2_512(password + hashedPasswordAndSalt[1]) == hashedPasswordAndSalt[0]; } else { @@ -99,7 +98,7 @@ bool Storage::checkHashedPasswordSha2_512(const QString &password, const QString } } -QString Storage::sha2_512(const QString &input) +QString Storage::sha2_512(const QString& input) { return QString(QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha512).toHex()); } diff --git a/src/core/storage.h b/src/core/storage.h index 85d2cad1..6ac0bfec 100644 --- a/src/core/storage.h +++ b/src/core/storage.h @@ -23,28 +23,30 @@ #include -#include "types.h" #include "coreidentity.h" #include "message.h" #include "network.h" +#include "types.h" class Storage : public QObject { Q_OBJECT public: - Storage(QObject *parent = nullptr); + Storage(QObject* parent = nullptr); - enum State { - IsReady, // ready to go - NeedsSetup, // need basic setup (ask the user for input) - NotAvailable // remove the storage backend from the list of avaliable backends + enum State + { + IsReady, // ready to go + NeedsSetup, // need basic setup (ask the user for input) + NotAvailable // remove the storage backend from the list of avaliable backends }; - enum HashVersion { + enum HashVersion + { Sha1, Sha2_512, - Latest=Sha2_512 + Latest = Sha2_512 }; @@ -84,17 +86,19 @@ public slots: * \param settings Hostname, port, username, password, ... * \return True if and only if the storage provider was initialized successfully. */ - virtual bool setup(const QVariantMap &settings = QVariantMap(), - const QProcessEnvironment &environment = {}, - bool loadFromEnvironment = false) = 0; + virtual bool setup(const QVariantMap& settings = QVariantMap(), + const QProcessEnvironment& environment = {}, + bool loadFromEnvironment = false) + = 0; //! Initialize the storage provider /** \param settings Hostname, port, username, password, ... * \return the State the storage backend is now in (see Storage::State) */ - virtual State init(const QVariantMap &settings = QVariantMap(), - const QProcessEnvironment &environment = {}, - bool loadFromEnvironment = false) = 0; + virtual State init(const QVariantMap& settings = QVariantMap(), + const QProcessEnvironment& environment = {}, + bool loadFromEnvironment = false) + = 0; //! Makes temp data persistent /** This Method is periodically called by the Quassel Core to make temporary @@ -112,33 +116,33 @@ public slots: * \param password The cleartext password for the new user * \return The new user's UserId */ - virtual UserId addUser(const QString &user, const QString &password, const QString &authenticator = "Database") = 0; + virtual UserId addUser(const QString& user, const QString& password, const QString& authenticator = "Database") = 0; //! Update a core user's password. /** \param user The user's id * \param password The user's new password * \return true on success. */ - virtual bool updateUser(UserId user, const QString &password) = 0; + virtual bool updateUser(UserId user, const QString& password) = 0; //! Rename a user /** \param user The user's id * \param newName The user's new name */ - virtual void renameUser(UserId user, const QString &newName) = 0; + virtual void renameUser(UserId user, const QString& newName) = 0; //! Validate a username with a given password. /** \param user The username to validate * \param password The user's alleged password * \return A valid UserId if the password matches the username; 0 else */ - virtual UserId validateUser(const QString &user, const QString &password) = 0; + virtual UserId validateUser(const QString& user, const QString& password) = 0; //! Check if a user with given username exists. Do not use for login purposes! /** \param username The username to validate * \return A valid UserId if the user exists; 0 else */ - virtual UserId getUserId(const QString &username) = 0; + virtual UserId getUserId(const QString& username) = 0; //! Get the authentication provider for a given user. /** \param username The username to validate @@ -146,7 +150,6 @@ public slots: */ virtual QString getUserAuthenticator(const UserId userid) = 0; - //! Determine the UserId of the internal user /** \return A valid UserId if the password matches the username; 0 else */ @@ -163,7 +166,7 @@ public slots: * \param settingName The Name of the Setting * \param data The Value */ - virtual void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) = 0; + virtual void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) = 0; //! Retrieve a persistent user setting /** @@ -172,24 +175,24 @@ public slots: * \param default Value to return in case it's unset. * \return the Value of the Setting or the default value if it is unset. */ - virtual QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &data = QVariant()) = 0; + virtual QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& data = QVariant()) = 0; //! Store core state /** * \param data Active Sessions */ - virtual void setCoreState(const QVariantList &data) = 0; + virtual void setCoreState(const QVariantList& data) = 0; //! Retrieve core state /** * \param default Value to return in case it's unset. * \return Active Sessions */ - virtual QVariantList getCoreState(const QVariantList &data = QVariantList()) = 0; + virtual QVariantList getCoreState(const QVariantList& data = QVariantList()) = 0; /* Identity handling */ - virtual IdentityId createIdentity(UserId user, CoreIdentity &identity) = 0; - virtual bool updateIdentity(UserId user, const CoreIdentity &identity) = 0; + virtual IdentityId createIdentity(UserId user, CoreIdentity& identity) = 0; + virtual bool updateIdentity(UserId user, const CoreIdentity& identity) = 0; virtual void removeIdentity(UserId user, IdentityId identityId) = 0; virtual QList identities(UserId user) = 0; @@ -200,7 +203,7 @@ public slots: * \param networkInfo The networkInfo holding the network definition * \return the NetworkId of the newly created Network. Possibly invalid. */ - virtual NetworkId createNetwork(UserId user, const NetworkInfo &info) = 0; + virtual NetworkId createNetwork(UserId user, const NetworkInfo& info) = 0; //! Apply the changes to NetworkInfo info to the storage engine /** @@ -208,7 +211,7 @@ public slots: * \param networkInfo The Updated NetworkInfo * \return true if successfull. */ - virtual bool updateNetwork(UserId user, const NetworkInfo &info) = 0; + virtual bool updateNetwork(UserId user, const NetworkInfo& info) = 0; //! Permanently remove a Network and all the data associated with it. /** \note This method is thredsafe. @@ -217,7 +220,7 @@ public slots: * \param networkId The network to delete * \return true if successfull. */ - virtual bool removeNetwork(UserId user, const NetworkId &networkId) = 0; + virtual bool removeNetwork(UserId user, const NetworkId& networkId) = 0; //! Returns a list of all NetworkInfos for the given UserId user /** \note This method is thredsafe. @@ -242,7 +245,7 @@ public slots: * \param networkId The Id of the network * \param isConnected whether the network is connected or not */ - virtual void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) = 0; + virtual void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) = 0; //! Get a hash of channels with their channel keys for a given network /** The keys are channel names and values are passwords (possibly empty) @@ -251,7 +254,7 @@ public slots: * \param user The id of the networks owner * \param networkId The Id of the network */ - virtual QHash persistentChannels(UserId user, const NetworkId &networkId) = 0; + virtual QHash persistentChannels(UserId user, const NetworkId& networkId) = 0; //! Update the connected state of a channel /** \note This method is threadsafe @@ -261,7 +264,7 @@ public slots: * \param channel The name of the channel * \param isJoined whether the channel is connected or not */ - virtual void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) = 0; + virtual void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) = 0; //! Update the key of a channel /** \note This method is threadsafe @@ -271,7 +274,7 @@ public slots: * \param channel The name of the channel * \param key The key of the channel (possibly empty) */ - virtual void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) = 0; + virtual void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) = 0; //! retrieve last known away message for session restore /** \note This method is threadsafe @@ -288,7 +291,7 @@ public slots: * \param networkId The Id of the network * \param awayMsg The current away message of own user */ - virtual void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) = 0; + virtual void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) = 0; //! retrieve last known user mode for session restore /** \note This method is threadsafe @@ -305,7 +308,7 @@ public slots: * \param networkId The Id of the network * \param userModes The current user modes of own user */ - virtual void setUserModes(UserId user, NetworkId networkId, const QString &userModes) = 0; + virtual void setUserModes(UserId user, NetworkId networkId, const QString& userModes) = 0; /* Buffer handling */ @@ -317,14 +320,15 @@ public slots: * \param create Whether or not the buffer should be created if it doesnt exist * \return The BufferInfo corresponding to the given network and buffer name, or an invalid BufferInfo if not found */ - virtual BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) = 0; + virtual BufferInfo bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true) + = 0; //! Get the unique BufferInfo for a bufferId /** \param user The core user who owns this buffername * \param bufferId The id of the buffer * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found. */ - virtual BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) = 0; + virtual BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) = 0; //! Request a list of all buffers known to a user. /** This method is used to get a list of all buffers we have stored a backlog from. @@ -348,7 +352,7 @@ public slots: * \param bufferId The bufferId * \return true if successfull */ - virtual bool removeBuffer(const UserId &user, const BufferId &bufferId) = 0; + virtual bool removeBuffer(const UserId& user, const BufferId& bufferId) = 0; //! Rename a Buffer /** \note This method is threadsafe. @@ -357,7 +361,7 @@ public slots: * \param newName The new name of the buffer * \return true if successfull */ - virtual bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) = 0; + virtual bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) = 0; //! Merge the content of two Buffers permanently. This cannot be reversed! /** \note This method is threadsafe. @@ -366,7 +370,7 @@ public slots: * \param bufferId2 The buffer that is about to be removed * \return true if successfull */ - virtual bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) = 0; + virtual bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) = 0; //! Update the LastSeenDate for a Buffer /** This Method is used to make the LastSeenDate of a Buffer persistent @@ -374,7 +378,7 @@ public slots: * \param bufferId The buffer id * \param MsgId The Message id of the message that has been just seen */ - virtual void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) = 0; + virtual void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) = 0; //! Get a Hash of all last seen message ids /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds @@ -390,7 +394,7 @@ public slots: * \param bufferId The buffer id * \param MsgId The Message id where the marker line should be placed */ - virtual void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) = 0; + virtual void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) = 0; //! Get a Hash of all marker line message ids /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds @@ -434,7 +438,7 @@ public slots: * \param user The id of the networks owner * \param networkId The Id of the network */ - virtual QHash bufferCiphers(UserId user, const NetworkId &networkId) = 0; + virtual QHash bufferCiphers(UserId user, const NetworkId& networkId) = 0; //! Update the cipher of a buffer /** \note This method is threadsafe @@ -444,7 +448,7 @@ public slots: * \param bufferName The Cname of the buffer * \param cipher The cipher for the buffer */ - virtual void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) = 0; + virtual void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) = 0; //! Update the highlight count for a Buffer /** This Method is used to make the activity state of a Buffer persistent @@ -479,13 +483,13 @@ public slots: /** \param msg The message object to be stored * \return true on success */ - virtual bool logMessage(Message &msg) = 0; + virtual bool logMessage(Message& msg) = 0; //! Store a list of Messages in the storage backend and set their unique Id. /** \param msgs The list message objects to be stored * \return true on success */ - virtual bool logMessages(MessageList &msgs) = 0; + virtual bool logMessages(MessageList& msgs) = 0; //! Request a certain number messages stored in a given buffer. /** \param buffer The buffer we request messages from @@ -504,9 +508,14 @@ public slots: * \param type The Message::Types that should be returned * \return The requested list of messages */ - virtual QList requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, - int limit = -1, Message::Types type = Message::Types{-1}, - Message::Flags flags = Message::Flags{-1}) = 0; + virtual QList requestMsgsFiltered(UserId user, + BufferId bufferId, + MsgId first = -1, + MsgId last = -1, + int limit = -1, + Message::Types type = Message::Types{-1}, + Message::Flags flags = Message::Flags{-1}) + = 0; //! Request a certain number of messages across all buffers /** \param first if != -1 return only messages with a MsgId >= first @@ -523,9 +532,13 @@ public slots: * \param type The Message::Types that should be returned * \return The requested list of messages */ - virtual QList requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1, + virtual QList requestAllMsgsFiltered(UserId user, + MsgId first = -1, + MsgId last = -1, + int limit = -1, Message::Types type = Message::Types{-1}, - Message::Flags flags = Message::Flags{-1}) = 0; + Message::Flags flags = Message::Flags{-1}) + = 0; //! Fetch all authusernames /** \return Map of all current UserIds to permitted idents @@ -534,13 +547,13 @@ public slots: signals: //! Sent when a new BufferInfo is created, or an existing one changed somehow. - void bufferInfoUpdated(UserId user, const BufferInfo &); + void bufferInfoUpdated(UserId user, const BufferInfo&); //! Sent when a Buffer was renamed - void bufferRenamed(const QString &newName, const QString &oldName); + void bufferRenamed(const QString& newName, const QString& oldName); //! Sent when a new user has been added - void userAdded(UserId, const QString &username); + void userAdded(UserId, const QString& username); //! Sent when a user has been renamed - void userRenamed(UserId, const QString &newname); + void userRenamed(UserId, const QString& newname); //! Sent when a user has been removed void userRemoved(UserId); @@ -548,17 +561,16 @@ signals: void dbUpgradeInProgress(bool inProgress); protected: - QString hashPassword(const QString &password); - bool checkHashedPassword(const UserId user, const QString &password, const QString &hashedPassword, const Storage::HashVersion version); + QString hashPassword(const QString& password); + bool checkHashedPassword(const UserId user, const QString& password, const QString& hashedPassword, const Storage::HashVersion version); private: - QString hashPasswordSha1(const QString &password); - bool checkHashedPasswordSha1(const QString &password, const QString &hashedPassword); + QString hashPasswordSha1(const QString& password); + bool checkHashedPasswordSha1(const QString& password, const QString& hashedPassword); - QString hashPasswordSha2_512(const QString &password); - bool checkHashedPasswordSha2_512(const QString &password, const QString &hashedPassword); - QString sha2_512(const QString &input); + QString hashPasswordSha2_512(const QString& password); + bool checkHashedPasswordSha2_512(const QString& password, const QString& hashedPassword); + QString sha2_512(const QString& input); }; - #endif diff --git a/src/main/main.cpp b/src/main/main.cpp index 5ec89c55..117e0ed0 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -22,40 +22,40 @@ #include #ifdef HAVE_UMASK -# include -# include +# include +# include #endif /* HAVE_UMASK */ #include #include #ifdef BUILD_CORE -# include "coreapplication.h" +# include "coreapplication.h" #elif defined BUILD_QTUI -# include "aboutdata.h" -# include "qtuiapplication.h" +# include "aboutdata.h" +# include "qtuiapplication.h" #elif defined BUILD_MONO -# include "aboutdata.h" -# include "monoapplication.h" +# include "aboutdata.h" +# include "monoapplication.h" #else -#error "Something is wrong - you need to #define a build mode!" +# error "Something is wrong - you need to #define a build mode!" #endif // We don't want quasselcore to depend on KDE #if defined HAVE_KF5 && defined BUILD_CORE -# undef HAVE_KF5 +# undef HAVE_KF5 #endif #if defined HAVE_KF5 -# include -# include +# include +# include #endif #include "quassel.h" #include "types.h" -int main(int argc, char **argv) +int main(int argc, char** argv) { // Set umask so files are created with restricted permissions #ifdef HAVE_UMASK @@ -74,13 +74,14 @@ int main(int argc, char **argv) // Migrate settings from KDE4 to KF5 if appropriate #ifdef HAVE_KF5 Kdelibs4ConfigMigrator migrator(QCoreApplication::applicationName()); - migrator.setConfigFiles(QStringList() << "quasselrc" << "quassel.notifyrc"); + migrator.setConfigFiles(QStringList() << "quasselrc" + << "quassel.notifyrc"); migrator.migrate(); #endif - //Setup the High-DPI settings -# if QT_VERSION >= 0x050600 && defined(Q_OS_WIN) - QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); //Added in Qt 5.6 + // Setup the High-DPI settings +#if QT_VERSION >= 0x050600 && defined(Q_OS_WIN) + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // Added in Qt 5.6 #endif QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); diff --git a/src/main/monoapplication.cpp b/src/main/monoapplication.cpp index f6dc5221..beee2cd8 100644 --- a/src/main/monoapplication.cpp +++ b/src/main/monoapplication.cpp @@ -19,20 +19,19 @@ ***************************************************************************/ #include "monoapplication.h" -#include "coreapplication.h" + #include "client.h" #include "core.h" +#include "coreapplication.h" #include "internalpeer.h" #include "logmessage.h" #include "qtui.h" class InternalPeer; -MonolithicApplication::MonolithicApplication(int &argc, char **argv) +MonolithicApplication::MonolithicApplication(int& argc, char** argv) : QtUiApplication(argc, argv) -{ -} - +{} void MonolithicApplication::init() { @@ -48,7 +47,6 @@ void MonolithicApplication::init() } } - Quassel::QuitHandler MonolithicApplication::quitHandler() { return [this]() { @@ -58,7 +56,6 @@ Quassel::QuitHandler MonolithicApplication::quitHandler() }; } - void MonolithicApplication::onClientDestroyed() { if (_core) { @@ -70,7 +67,6 @@ void MonolithicApplication::onClientDestroyed() } } - void MonolithicApplication::onCoreShutdown() { if (_core) { @@ -83,7 +79,6 @@ void MonolithicApplication::onCoreShutdown() } } - void MonolithicApplication::startInternalCore() { if (_core) { @@ -106,7 +101,6 @@ void MonolithicApplication::startInternalCore() _coreThread.start(); } - void MonolithicApplication::onConnectionRequest(QPointer peer) { if (!_core) { diff --git a/src/main/monoapplication.h b/src/main/monoapplication.h index a63dfe07..6e29b1bb 100644 --- a/src/main/monoapplication.h +++ b/src/main/monoapplication.h @@ -33,7 +33,7 @@ class MonolithicApplication : public QtUiApplication Q_OBJECT public: - MonolithicApplication(int &, char **); + MonolithicApplication(int&, char**); void init() override; diff --git a/src/qtui/aboutdlg.cpp b/src/qtui/aboutdlg.cpp index 840da62f..326c8f3e 100644 --- a/src/qtui/aboutdlg.cpp +++ b/src/qtui/aboutdlg.cpp @@ -28,7 +28,7 @@ #include "quassel.h" #include "util.h" -AboutDlg::AboutDlg(QWidget *parent) +AboutDlg::AboutDlg(QWidget* parent) : QDialog(parent) , _aboutData(new AboutData(this)) { @@ -44,15 +44,14 @@ AboutDlg::AboutDlg(QWidget *parent) versionDate = QString("%1").arg(tr("Unknown date")); } else { - versionDate = tryFormatUnixEpoch(Quassel::buildInfo().commitDate, - Qt::DateFormat::DefaultLocaleShortDate); + versionDate = tryFormatUnixEpoch(Quassel::buildInfo().commitDate, Qt::DateFormat::DefaultLocaleShortDate); } ui.versionLabel->setText(QString(tr("Version: %1
" "Version date: %2
" "Protocol version: %3")) - .arg(Quassel::buildInfo().fancyVersionString) - .arg(versionDate) - .arg(Quassel::buildInfo().protocolVersion)); + .arg(Quassel::buildInfo().fancyVersionString) + .arg(versionDate) + .arg(Quassel::buildInfo().protocolVersion)); ui.aboutTextBrowser->setHtml(about()); ui.authorTextBrowser->setHtml(authors()); ui.contributorTextBrowser->setHtml(contributors()); @@ -61,31 +60,30 @@ AboutDlg::AboutDlg(QWidget *parent) setWindowIcon(icon::get("quassel")); } - QString AboutDlg::about() const { - QString res {tr("A modern, distributed IRC Client

" - "©%1 by the Quassel Project
" - "
https://quassel-irc.org
" - "#quassel on Freenode

" - "Quassel IRC is dual-licensed under GPLv2 and " - "GPLv3.
" - "Breeze icon theme © Uri Herrera and others, licensed under the " - "LGPLv3.
" - "Oxygen icon theme © Nuno Pinheiro and others, licensed under the " - "LGPLv3.

" - "Please use https://bugs.quassel-irc.org to report bugs." - ).arg("2005-2018") - }; + QString res{tr("A modern, distributed IRC Client

" + "©%1 by the Quassel Project
" + "https://quassel-irc.org
" + "#quassel on Freenode

" + "Quassel IRC is dual-licensed under GPLv2 and " + "GPLv3.
" + "Breeze icon theme © Uri Herrera and others, " + "licensed under the " + "LGPLv3.
" + "Oxygen icon theme © Nuno Pinheiro and others, " + "licensed under the " + "LGPLv3.

" + "Please use https://bugs.quassel-irc.org to report bugs.") + .arg("2005-2018")}; return res; } - QString AboutDlg::authors() const { - QString res {tr("Quassel IRC is mainly developed by:") + "
"}; - for (auto &&person : _aboutData->authors()) { + QString res{tr("Quassel IRC is mainly developed by:") + "
"}; + for (auto&& person : _aboutData->authors()) { res.append("
" + person.prettyName() + "
"); if (!person.emailAddress().isEmpty()) res.append("" + person.emailAddress() + "
"); @@ -95,39 +93,47 @@ QString AboutDlg::authors() const return res; } - QString AboutDlg::contributors() const { - QString res {tr("We would like to thank the following contributors (in alphabetical order) and everybody we forgot to mention here:") + "
"}; - for (auto &&person : _aboutData->credits()) { + QString res{tr("We would like to thank the following contributors (in alphabetical order) and everybody we forgot to mention here:") + + "
"}; + for (auto&& person : _aboutData->credits()) { res.append("
" + person.prettyName() + "
" + person.task() + "
"); } - res.append("
" + tr("...and anybody else finding and reporting bugs, giving feedback, helping others and being part of the community!")); + res.append("
" + + tr("...and anybody else finding and reporting bugs, giving feedback, helping others and being part of the community!")); return res; } - QString AboutDlg::thanksTo() const { - QString res {tr("Special thanks goes to:") + "
" - "
" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
 John \"nox\" Hand
" + tr("for the original Quassel logo - The All-Seeing Eye") + "
Nuno Pinheiro
" + tr("for the Oxygen Quassel logo") + "
The KDE Visual Design Group
" + tr("for the amazing Breeze and Oxygen icon themes") + "
The Qt Company (formerly known as Qt Software, Nokia, Trolltech)
" + tr("for creating an awesome framework, and for sponsoring development with Greenphones, N810s, N950s and more") + "
" - }; + QString res{tr("Special thanks goes to:") + + "
" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
 John \"nox\" Hand
" + + tr("for the original Quassel logo - The All-Seeing Eye") + + "
Nuno Pinheiro
" + + tr("for the Oxygen Quassel logo") + + "
The KDE Visual Design Group
" + + tr("for the amazing Breeze and Oxygen icon themes") + + "
The Qt Company (formerly known as Qt Software, Nokia, Trolltech)
" + + tr("for creating an awesome framework, and for sponsoring development with Greenphones, N810s, N950s and more") + + "
"}; return res; } diff --git a/src/qtui/aboutdlg.h b/src/qtui/aboutdlg.h index 9a4eeddc..bd9311af 100644 --- a/src/qtui/aboutdlg.h +++ b/src/qtui/aboutdlg.h @@ -32,7 +32,7 @@ class AboutDlg : public QDialog Q_OBJECT public: - AboutDlg(QWidget *parent = nullptr); + AboutDlg(QWidget* parent = nullptr); private: Ui::AboutDlg ui; @@ -42,8 +42,7 @@ private: QString contributors() const; QString thanksTo() const; - AboutData *_aboutData; + AboutData* _aboutData; }; - #endif diff --git a/src/qtui/awaylogfilter.cpp b/src/qtui/awaylogfilter.cpp index 882a7af9..69694cda 100644 --- a/src/qtui/awaylogfilter.cpp +++ b/src/qtui/awaylogfilter.cpp @@ -19,15 +19,14 @@ ***************************************************************************/ #include "awaylogfilter.h" + #include "clientignorelistmanager.h" -AwayLogFilter::AwayLogFilter(MessageModel *model, QObject *parent) +AwayLogFilter::AwayLogFilter(MessageModel* model, QObject* parent) : ChatMonitorFilter(model, parent) -{ -} +{} - -bool AwayLogFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const +bool AwayLogFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { Q_UNUSED(sourceParent) @@ -53,15 +52,15 @@ bool AwayLogFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourcePar // ignorelist handling // only match if message is not flagged as server msg if (!(flags & Message::ServerMsg) && Client::ignoreListManager() - && Client::ignoreListManager()->match(source_index.data(MessageModel::MessageRole).value(), Client::networkModel()->networkName(bufferId))) { + && Client::ignoreListManager()->match(source_index.data(MessageModel::MessageRole).value(), + Client::networkModel()->networkName(bufferId))) { return false; } return true; } - -QVariant AwayLogFilter::data(const QModelIndex &index, int role) const +QVariant AwayLogFilter::data(const QModelIndex& index, int role) const { if (role != MessageModel::FlagsRole) return ChatMonitorFilter::data(index, role); diff --git a/src/qtui/awaylogfilter.h b/src/qtui/awaylogfilter.h index 5ade7f00..560f904b 100644 --- a/src/qtui/awaylogfilter.h +++ b/src/qtui/awaylogfilter.h @@ -28,12 +28,11 @@ class AwayLogFilter : public ChatMonitorFilter Q_OBJECT public: - AwayLogFilter(MessageModel *model, QObject *parent = nullptr); + AwayLogFilter(MessageModel* model, QObject* parent = nullptr); - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; QString idString() const override { return "AwayLog"; } - QVariant data(const QModelIndex &index, int role) const override; + QVariant data(const QModelIndex& index, int role) const override; }; - -#endif //AWAYLOGFILTER_H +#endif // AWAYLOGFILTER_H diff --git a/src/qtui/awaylogview.cpp b/src/qtui/awaylogview.cpp index 4a6bacc2..4bd0bcc8 100644 --- a/src/qtui/awaylogview.cpp +++ b/src/qtui/awaylogview.cpp @@ -28,14 +28,13 @@ #include "chatlinemodel.h" #include "chatscene.h" -AwayLogView::AwayLogView(AwayLogFilter *filter, QWidget *parent) +AwayLogView::AwayLogView(AwayLogFilter* filter, QWidget* parent) : ChatMonitorView(filter, parent) { setWindowTitle(tr("Away Log")); } - -void AwayLogView::addActionsToMenu(QMenu *menu, const QPointF &pos) +void AwayLogView::addActionsToMenu(QMenu* menu, const QPointF& pos) { ChatView::addActionsToMenu(menu, pos); if (!menu->isEmpty()) @@ -44,13 +43,13 @@ void AwayLogView::addActionsToMenu(QMenu *menu, const QPointF &pos) if (scene()->columnByScenePos(pos) == ChatLineModel::SenderColumn) { menu->addSeparator(); - auto *showNetworkAction = new Action(tr("Show Network Name"), menu, this, &AwayLogView::showFieldsChanged); + auto* showNetworkAction = new Action(tr("Show Network Name"), menu, this, &AwayLogView::showFieldsChanged); showNetworkAction->setCheckable(true); showNetworkAction->setChecked(filter()->showFields() & ChatMonitorFilter::NetworkField); showNetworkAction->setData(ChatMonitorFilter::NetworkField); menu->addAction(showNetworkAction); - auto *showBufferAction = new Action(tr("Show Buffer Name"), menu, this, &AwayLogView::showFieldsChanged); + auto* showBufferAction = new Action(tr("Show Buffer Name"), menu, this, &AwayLogView::showFieldsChanged); showBufferAction->setCheckable(true); showBufferAction->setChecked(filter()->showFields() & ChatMonitorFilter::BufferField); showBufferAction->setData(ChatMonitorFilter::BufferField); diff --git a/src/qtui/awaylogview.h b/src/qtui/awaylogview.h index d634690c..99de9064 100644 --- a/src/qtui/awaylogview.h +++ b/src/qtui/awaylogview.h @@ -30,9 +30,8 @@ class AwayLogView : public ChatMonitorView Q_OBJECT public: - AwayLogView(AwayLogFilter *filter, QWidget *parent = nullptr); - void addActionsToMenu(QMenu *menu, const QPointF &pos) override; + AwayLogView(AwayLogFilter* filter, QWidget* parent = nullptr); + void addActionsToMenu(QMenu* menu, const QPointF& pos) override; }; - -#endif //AWAYLOGVIEW_H +#endif // AWAYLOGVIEW_H diff --git a/src/qtui/bufferwidget.cpp b/src/qtui/bufferwidget.cpp index 3da66caf..1df7ec4e 100644 --- a/src/qtui/bufferwidget.cpp +++ b/src/qtui/bufferwidget.cpp @@ -18,14 +18,15 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ -#include +#include "bufferwidget.h" + #include +#include #include #include #include "action.h" #include "actioncollection.h" -#include "bufferwidget.h" #include "chatline.h" #include "chatview.h" #include "chatviewsearchbar.h" @@ -37,11 +38,11 @@ #include "qtui.h" #include "settings.h" -BufferWidget::BufferWidget(QWidget *parent) - : AbstractBufferContainer(parent), - _chatViewSearchController(new ChatViewSearchController(this)), - _autoMarkerLine(true), - _autoMarkerLineOnLostFocus(true) +BufferWidget::BufferWidget(QWidget* parent) + : AbstractBufferContainer(parent) + , _chatViewSearchController(new ChatViewSearchController(this)) + , _autoMarkerLine(true) + , _autoMarkerLineOnLostFocus(true) { ui.setupUi(this); layout()->setContentsMargins(0, 0, 0, 0); @@ -53,63 +54,56 @@ BufferWidget::BufferWidget(QWidget *parent) _chatViewSearchController->setSearchMsgs(ui.searchBar->searchMsgsBox()->isChecked()); _chatViewSearchController->setSearchOnlyRegularMsgs(ui.searchBar->searchOnlyRegularMsgsBox()->isChecked()); - connect(ui.searchBar, &ChatViewSearchBar::searchChanged, - _chatViewSearchController, &ChatViewSearchController::setSearchString); - connect(ui.searchBar->caseSensitiveBox(), &QAbstractButton::toggled, - _chatViewSearchController, &ChatViewSearchController::setCaseSensitive); - connect(ui.searchBar->searchSendersBox(), &QAbstractButton::toggled, - _chatViewSearchController, &ChatViewSearchController::setSearchSenders); - connect(ui.searchBar->searchMsgsBox(), &QAbstractButton::toggled, - _chatViewSearchController, &ChatViewSearchController::setSearchMsgs); - connect(ui.searchBar->searchOnlyRegularMsgsBox(), &QAbstractButton::toggled, - _chatViewSearchController, &ChatViewSearchController::setSearchOnlyRegularMsgs); - connect(ui.searchBar->searchUpButton(), &QAbstractButton::clicked, - _chatViewSearchController, &ChatViewSearchController::highlightPrev); - connect(ui.searchBar->searchDownButton(), &QAbstractButton::clicked, - _chatViewSearchController, &ChatViewSearchController::highlightNext); + connect(ui.searchBar, &ChatViewSearchBar::searchChanged, _chatViewSearchController, &ChatViewSearchController::setSearchString); + connect(ui.searchBar->caseSensitiveBox(), &QAbstractButton::toggled, _chatViewSearchController, &ChatViewSearchController::setCaseSensitive); + connect(ui.searchBar->searchSendersBox(), &QAbstractButton::toggled, _chatViewSearchController, &ChatViewSearchController::setSearchSenders); + connect(ui.searchBar->searchMsgsBox(), &QAbstractButton::toggled, _chatViewSearchController, &ChatViewSearchController::setSearchMsgs); + connect(ui.searchBar->searchOnlyRegularMsgsBox(), + &QAbstractButton::toggled, + _chatViewSearchController, + &ChatViewSearchController::setSearchOnlyRegularMsgs); + connect(ui.searchBar->searchUpButton(), &QAbstractButton::clicked, _chatViewSearchController, &ChatViewSearchController::highlightPrev); + connect(ui.searchBar->searchDownButton(), &QAbstractButton::clicked, _chatViewSearchController, &ChatViewSearchController::highlightNext); connect(ui.searchBar, &ChatViewSearchBar::hidden, this, selectOverload<>(&QWidget::setFocus)); - connect(_chatViewSearchController, &ChatViewSearchController::newCurrentHighlight, - this, &BufferWidget::scrollToHighlight); + connect(_chatViewSearchController, &ChatViewSearchController::newCurrentHighlight, this, &BufferWidget::scrollToHighlight); - ActionCollection *coll = QtUi::actionCollection(); - coll->addActions({ - {"ZoomInChatView", new Action{icon::get("zoom-in"), tr("Zoom In"), coll, this, &BufferWidget::zoomIn, QKeySequence::ZoomIn}}, - {"ZoomOutChatView", new Action{icon::get("zoom-out"), tr("Zoom Out"), coll, this, &BufferWidget::zoomOut, QKeySequence::ZoomOut}}, - {"ZoomOriginalChatView", new Action{icon::get("zoom-original"), tr("Actual Size"), coll, this, &BufferWidget::zoomOriginal}}, - {"SetMarkerLineToBottom", new Action{tr("Set Marker Line"), coll, this, [this]() { setMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_R)}} - }); + ActionCollection* coll = QtUi::actionCollection(); + coll->addActions( + {{"ZoomInChatView", new Action{icon::get("zoom-in"), tr("Zoom In"), coll, this, &BufferWidget::zoomIn, QKeySequence::ZoomIn}}, + {"ZoomOutChatView", new Action{icon::get("zoom-out"), tr("Zoom Out"), coll, this, &BufferWidget::zoomOut, QKeySequence::ZoomOut}}, + {"ZoomOriginalChatView", new Action{icon::get("zoom-original"), tr("Actual Size"), coll, this, &BufferWidget::zoomOriginal}}, + {"SetMarkerLineToBottom", + new Action{tr("Set Marker Line"), coll, this, [this]() { setMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_R)}}}); coll = QtUi::actionCollection("Navigation"); - coll->addAction("JumpToMarkerLine", new Action{tr("Go to Marker Line"), coll, this, [this]() { jumpToMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_K)}); + coll->addAction("JumpToMarkerLine", + new Action{tr("Go to Marker Line"), coll, this, [this]() { jumpToMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_K)}); ChatViewSettings s; s.initAndNotify("AutoMarkerLine", this, &BufferWidget::setAutoMarkerLine, true); s.initAndNotify("AutoMarkerLineOnLostFocus", this, &BufferWidget::setAutoMarkerLineOnLostFocus, true); } - BufferWidget::~BufferWidget() { delete _chatViewSearchController; _chatViewSearchController = nullptr; } - -void BufferWidget::setAutoMarkerLine(const QVariant &v) +void BufferWidget::setAutoMarkerLine(const QVariant& v) { _autoMarkerLine = v.toBool(); } -void BufferWidget::setAutoMarkerLineOnLostFocus(const QVariant &v) +void BufferWidget::setAutoMarkerLineOnLostFocus(const QVariant& v) { _autoMarkerLineOnLostFocus = v.toBool(); } - -AbstractChatView *BufferWidget::createChatView(BufferId id) +AbstractChatView* BufferWidget::createChatView(BufferId id) { - ChatView *chatView; + ChatView* chatView; chatView = new ChatView(id, this); chatView->setBufferContainer(this); _chatViews[id] = chatView; @@ -118,83 +112,76 @@ AbstractChatView *BufferWidget::createChatView(BufferId id) return chatView; } - void BufferWidget::removeChatView(BufferId id) { - QWidget *view = _chatViews.value(id, 0); - if (!view) return; + QWidget* view = _chatViews.value(id, 0); + if (!view) + return; ui.stackedWidget->removeWidget(view); view->deleteLater(); _chatViews.take(id); } - void BufferWidget::showChatView(BufferId id) { if (!id.isValid()) { ui.stackedWidget->setCurrentWidget(ui.page); } else { - auto *view = qobject_cast(_chatViews.value(id)); + auto* view = qobject_cast(_chatViews.value(id)); Q_ASSERT(view); ui.stackedWidget->setCurrentWidget(view); _chatViewSearchController->setScene(view->scene()); } } - -void BufferWidget::scrollToHighlight(QGraphicsItem *highlightItem) +void BufferWidget::scrollToHighlight(QGraphicsItem* highlightItem) { - auto *view = qobject_cast(ui.stackedWidget->currentWidget()); + auto* view = qobject_cast(ui.stackedWidget->currentWidget()); if (view) { view->centerOn(highlightItem); } } - void BufferWidget::zoomIn() { - auto *view = qobject_cast(ui.stackedWidget->currentWidget()); + auto* view = qobject_cast(ui.stackedWidget->currentWidget()); if (view) view->zoomIn(); } - void BufferWidget::zoomOut() { - auto *view = qobject_cast(ui.stackedWidget->currentWidget()); + auto* view = qobject_cast(ui.stackedWidget->currentWidget()); if (view) view->zoomOut(); } - void BufferWidget::zoomOriginal() { - auto *view = qobject_cast(ui.stackedWidget->currentWidget()); + auto* view = qobject_cast(ui.stackedWidget->currentWidget()); if (view) view->zoomOriginal(); } - -void BufferWidget::addActionsToMenu(QMenu *menu, const QPointF &pos) +void BufferWidget::addActionsToMenu(QMenu* menu, const QPointF& pos) { Q_UNUSED(pos); - ActionCollection *coll = QtUi::actionCollection(); + ActionCollection* coll = QtUi::actionCollection(); menu->addSeparator(); menu->addAction(coll->action("ZoomInChatView")); menu->addAction(coll->action("ZoomOutChatView")); menu->addAction(coll->action("ZoomOriginalChatView")); } - -bool BufferWidget::eventFilter(QObject *watched, QEvent *event) +bool BufferWidget::eventFilter(QObject* watched, QEvent* event) { if (event->type() != QEvent::KeyPress) return false; - auto *keyEvent = static_cast(event); + auto* keyEvent = static_cast(event); - auto *inputLine = qobject_cast(watched); + auto* inputLine = qobject_cast(watched); if (!inputLine) return false; @@ -202,7 +189,7 @@ bool BufferWidget::eventFilter(QObject *watched, QEvent *event) if (keyEvent == QKeySequence::Copy) { if (inputLine->hasSelectedText()) return false; - auto *view = qobject_cast(ui.stackedWidget->currentWidget()); + auto* view = qobject_cast(ui.stackedWidget->currentWidget()); if (view) view->scene()->selectionToClipboard(); return true; @@ -221,21 +208,20 @@ bool BufferWidget::eventFilter(QObject *watched, QEvent *event) case Qt::Key_PageUp: case Qt::Key_PageDown: // static cast to access public qobject::event - return static_cast(ui.stackedWidget->currentWidget())->event(event); + return static_cast(ui.stackedWidget->currentWidget())->event(event); default: return false; } } - -void BufferWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) +void BufferWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous) { - auto *prevView = qobject_cast(ui.stackedWidget->currentWidget()); + auto* prevView = qobject_cast(ui.stackedWidget->currentWidget()); - AbstractBufferContainer::currentChanged(current, previous); // switch first to avoid a redraw + AbstractBufferContainer::currentChanged(current, previous); // switch first to avoid a redraw // we need to hide the marker line if it's already/still at the bottom of the view (and not scrolled up) - auto *curView = qobject_cast(ui.stackedWidget->currentWidget()); + auto* curView = qobject_cast(ui.stackedWidget->currentWidget()); if (curView) { BufferId curBufferId = current.data(NetworkModel::BufferIdRole).value(); if (curBufferId.isValid()) { @@ -251,15 +237,14 @@ void BufferWidget::currentChanged(const QModelIndex ¤t, const QModelIndex setMarkerLine(prevView, false); } - -void BufferWidget::setMarkerLine(ChatView *view, bool allowGoingBack) +void BufferWidget::setMarkerLine(ChatView* view, bool allowGoingBack) { if (!view) - view = qobject_cast(ui.stackedWidget->currentWidget()); + view = qobject_cast(ui.stackedWidget->currentWidget()); if (!view) return; - ChatLine *lastLine = view->lastVisibleChatLine(); + ChatLine* lastLine = view->lastVisibleChatLine(); if (lastLine) { QModelIndex idx = lastLine->index(); MsgId msgId = idx.data(MessageModel::MsgIdRole).value(); @@ -274,11 +259,10 @@ void BufferWidget::setMarkerLine(ChatView *view, bool allowGoingBack) } } - -void BufferWidget::jumpToMarkerLine(ChatView *view, bool requestBacklog) +void BufferWidget::jumpToMarkerLine(ChatView* view, bool requestBacklog) { if (!view) - view = qobject_cast(ui.stackedWidget->currentWidget()); + view = qobject_cast(ui.stackedWidget->currentWidget()); if (!view) return; diff --git a/src/qtui/bufferwidget.h b/src/qtui/bufferwidget.h index 35494957..a26040bd 100644 --- a/src/qtui/bufferwidget.h +++ b/src/qtui/bufferwidget.h @@ -20,10 +20,10 @@ #pragma once -#include "ui_bufferwidget.h" - #include "abstractbuffercontainer.h" +#include "ui_bufferwidget.h" + class QGraphicsItem; class ChatView; class ChatViewSearchBar; @@ -34,42 +34,42 @@ class BufferWidget : public AbstractBufferContainer Q_OBJECT public: - BufferWidget(QWidget *parent); + BufferWidget(QWidget* parent); ~BufferWidget() override; - bool eventFilter(QObject *watched, QEvent *event) override; + bool eventFilter(QObject* watched, QEvent* event) override; - inline ChatViewSearchBar *searchBar() const { return ui.searchBar; } - void addActionsToMenu(QMenu *, const QPointF &pos); + inline ChatViewSearchBar* searchBar() const { return ui.searchBar; } + void addActionsToMenu(QMenu*, const QPointF& pos); virtual inline bool autoMarkerLineOnLostFocus() const { return _autoMarkerLineOnLostFocus; } public slots: - virtual void setMarkerLine(ChatView *view = nullptr, bool allowGoingBack = true); - virtual void jumpToMarkerLine(ChatView *view = nullptr, bool requestBacklog = true); + virtual void setMarkerLine(ChatView* view = nullptr, bool allowGoingBack = true); + virtual void jumpToMarkerLine(ChatView* view = nullptr, bool requestBacklog = true); protected: - AbstractChatView *createChatView(BufferId) override; + AbstractChatView* createChatView(BufferId) override; void removeChatView(BufferId) override; inline bool autoMarkerLine() const override { return _autoMarkerLine; } protected slots: - void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override; + void currentChanged(const QModelIndex& current, const QModelIndex& previous) override; void showChatView(BufferId) override; private slots: - void scrollToHighlight(QGraphicsItem *highlightItem); + void scrollToHighlight(QGraphicsItem* highlightItem); void zoomIn(); void zoomOut(); void zoomOriginal(); - void setAutoMarkerLine(const QVariant &); - void setAutoMarkerLineOnLostFocus(const QVariant &); + void setAutoMarkerLine(const QVariant&); + void setAutoMarkerLineOnLostFocus(const QVariant&); private: Ui::BufferWidget ui; - QHash _chatViews; + QHash _chatViews; - ChatViewSearchController *_chatViewSearchController; + ChatViewSearchController* _chatViewSearchController; bool _autoMarkerLine; bool _autoMarkerLineOnLostFocus; diff --git a/src/qtui/channellistdlg.cpp b/src/qtui/channellistdlg.cpp index f5654c5b..afa7b172 100644 --- a/src/qtui/channellistdlg.cpp +++ b/src/qtui/channellistdlg.cpp @@ -20,18 +20,18 @@ #include "channellistdlg.h" -#include #include +#include #include #include "client.h" #include "clientirclisthelper.h" #include "icon.h" -ChannelListDlg::ChannelListDlg(QWidget *parent) - : QDialog(parent), - _ircListModel(this), - _sortFilter(this) +ChannelListDlg::ChannelListDlg(QWidget* parent) + : QDialog(parent) + , _ircListModel(this) + , _sortFilter(this) { _sortFilter.setSourceModel(&_ircListModel); _sortFilter.setFilterCaseSensitivity(Qt::CaseInsensitive); @@ -59,8 +59,7 @@ ChannelListDlg::ChannelListDlg(QWidget *parent) connect(ui.searchChannelsButton, &QAbstractButton::clicked, this, &ChannelListDlg::requestSearch); connect(ui.channelNameLineEdit, &QLineEdit::returnPressed, this, &ChannelListDlg::requestSearch); connect(ui.filterLineEdit, &QLineEdit::textChanged, &_sortFilter, &QSortFilterProxyModel::setFilterFixedString); - connect(Client::ircListHelper(), &ClientIrcListHelper::channelListReceived, - this, &ChannelListDlg::receiveChannelList); + connect(Client::ircListHelper(), &ClientIrcListHelper::channelListReceived, this, &ChannelListDlg::receiveChannelList); connect(Client::ircListHelper(), &ClientIrcListHelper::finishedListReported, this, &ChannelListDlg::reportFinishedList); connect(Client::ircListHelper(), &ClientIrcListHelper::errorReported, this, &ChannelListDlg::showError); connect(ui.channelListView, &QAbstractItemView::activated, this, &ChannelListDlg::joinChannel); @@ -74,7 +73,6 @@ ChannelListDlg::ChannelListDlg(QWidget *parent) updateInputFocus(); } - void ChannelListDlg::setNetwork(NetworkId netId) { if (_netId == netId) @@ -85,8 +83,7 @@ void ChannelListDlg::setNetwork(NetworkId netId) showFilterLine(false); } - -void ChannelListDlg::setChannelFilters(const QString &channelFilters) +void ChannelListDlg::setChannelFilters(const QString& channelFilters) { // Enable advanced mode if searching setAdvancedMode(!channelFilters.isEmpty()); @@ -94,7 +91,6 @@ void ChannelListDlg::setChannelFilters(const QString &channelFilters) ui.channelNameLineEdit->setText(channelFilters.trimmed()); } - void ChannelListDlg::requestSearch() { if (!_netId.isValid()) { @@ -110,8 +106,9 @@ void ChannelListDlg::requestSearch() Client::ircListHelper()->requestChannelList(_netId, channelFilters); } - -void ChannelListDlg::receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QList &channelList) +void ChannelListDlg::receiveChannelList(const NetworkId& netId, + const QStringList& channelFilters, + const QList& channelList) { Q_UNUSED(channelFilters) if (netId != _netId) @@ -124,7 +121,6 @@ void ChannelListDlg::receiveChannelList(const NetworkId &netId, const QStringLis updateInputFocus(); } - void ChannelListDlg::showFilterLine(bool show) { ui.line->setVisible(show); @@ -132,14 +128,12 @@ void ChannelListDlg::showFilterLine(bool show) ui.filterLineEdit->setVisible(show); } - void ChannelListDlg::enableQuery(bool enable) { ui.channelNameLineEdit->setEnabled(enable); ui.searchChannelsButton->setEnabled(enable); } - void ChannelListDlg::setAdvancedMode(bool advanced) { _advancedMode = advanced; @@ -165,19 +159,18 @@ void ChannelListDlg::setAdvancedMode(bool advanced) ui.searchPatternLabel->setVisible(advanced); } - void ChannelListDlg::updateInputFocus() { // Update keyboard focus to match what options are available. Prioritize the channel name // editor as one likely won't need to filter when already limiting the list. if (ui.channelNameLineEdit->isVisible()) { ui.channelNameLineEdit->setFocus(); - } else if (ui.filterLineEdit->isVisible()) { + } + else if (ui.filterLineEdit->isVisible()) { ui.filterLineEdit->setFocus(); } } - void ChannelListDlg::showErrors(bool show) { if (!show) { @@ -187,22 +180,20 @@ void ChannelListDlg::showErrors(bool show) ui.errorTextEdit->setVisible(show); } - void ChannelListDlg::reportFinishedList() { _listFinished = true; } - -void ChannelListDlg::showError(const QString &error) +void ChannelListDlg::showError(const QString& error) { showErrors(true); ui.errorTextEdit->moveCursor(QTextCursor::End); ui.errorTextEdit->insertPlainText(error + "\n"); } - -void ChannelListDlg::joinChannel(const QModelIndex &index) +void ChannelListDlg::joinChannel(const QModelIndex& index) { - Client::instance()->userInput(BufferInfo::fakeStatusBuffer(_netId), QString("/JOIN %1").arg(index.sibling(index.row(), 0).data().toString())); + Client::instance()->userInput(BufferInfo::fakeStatusBuffer(_netId), + QString("/JOIN %1").arg(index.sibling(index.row(), 0).data().toString())); } diff --git a/src/qtui/channellistdlg.h b/src/qtui/channellistdlg.h index cfa45a3d..7c7c6320 100644 --- a/src/qtui/channellistdlg.h +++ b/src/qtui/channellistdlg.h @@ -21,13 +21,13 @@ #ifndef CHANNELLISTDLG_H #define CHANNELLISTDLG_H -#include "ui_channellistdlg.h" +#include #include "irclisthelper.h" #include "irclistmodel.h" #include "types.h" -#include +#include "ui_channellistdlg.h" class QSpacerItem; @@ -36,7 +36,7 @@ class ChannelListDlg : public QDialog Q_OBJECT public: - ChannelListDlg(QWidget *parent = nullptr); + ChannelListDlg(QWidget* parent = nullptr); void setNetwork(NetworkId netId); @@ -48,7 +48,7 @@ public: * * @param channelFilters Partial channel name to search for, or empty to not filter by name */ - void setChannelFilters(const QString &channelFilters); + void setChannelFilters(const QString& channelFilters); public slots: /** @@ -57,13 +57,15 @@ public slots: void requestSearch(); protected slots: - void receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QList &channelList); + void receiveChannelList(const NetworkId& netId, + const QStringList& channelFilters, + const QList& channelList); void reportFinishedList(); - void joinChannel(const QModelIndex &); + void joinChannel(const QModelIndex&); private slots: inline void toggleMode() { setAdvancedMode(!_advancedMode); } - void showError(const QString &error); + void showError(const QString& error); private: void showFilterLine(bool show); @@ -82,9 +84,8 @@ private: NetworkId _netId; IrcListModel _ircListModel; QSortFilterProxyModel _sortFilter; - QSpacerItem *_simpleModeSpacer{nullptr}; + QSpacerItem* _simpleModeSpacer{nullptr}; bool _advancedMode{false}; }; - -#endif //CHANNELLIST_H +#endif // CHANNELLIST_H diff --git a/src/qtui/chatitem.cpp b/src/qtui/chatitem.cpp index 8063a972..fc0f9016 100644 --- a/src/qtui/chatitem.cpp +++ b/src/qtui/chatitem.cpp @@ -28,10 +28,10 @@ #include #include #include +#include #include #include #include -#include #include "action.h" #include "buffermodel.h" @@ -45,77 +45,65 @@ #include "qtui.h" #include "qtuistyle.h" -ChatItem::ChatItem(const QRectF &boundingRect, ChatLine *parent) - : _parent(parent), - _boundingRect(boundingRect), - _selectionMode(NoSelection), - _selectionStart(-1), - _cachedLayout(nullptr) -{ -} - +ChatItem::ChatItem(const QRectF& boundingRect, ChatLine* parent) + : _parent(parent) + , _boundingRect(boundingRect) + , _selectionMode(NoSelection) + , _selectionStart(-1) + , _cachedLayout(nullptr) +{} ChatItem::~ChatItem() { delete _cachedLayout; } - -ChatLine *ChatItem::chatLine() const +ChatLine* ChatItem::chatLine() const { return _parent; } - -ChatScene *ChatItem::chatScene() const +ChatScene* ChatItem::chatScene() const { return chatLine()->chatScene(); } - -ChatView *ChatItem::chatView() const +ChatView* ChatItem::chatView() const { return chatScene()->chatView(); } - -const QAbstractItemModel *ChatItem::model() const +const QAbstractItemModel* ChatItem::model() const { return chatLine()->model(); } - int ChatItem::row() const { return chatLine()->row(); } - -QPointF ChatItem::mapToLine(const QPointF &p) const +QPointF ChatItem::mapToLine(const QPointF& p) const { return p + pos(); } - -QPointF ChatItem::mapFromLine(const QPointF &p) const +QPointF ChatItem::mapFromLine(const QPointF& p) const { return p - pos(); } - // relative to the ChatLine -QPointF ChatItem::mapToScene(const QPointF &p) const +QPointF ChatItem::mapToScene(const QPointF& p) const { return chatLine()->mapToScene(p /* + pos() */); } - -QPointF ChatItem::mapFromScene(const QPointF &p) const +QPointF ChatItem::mapFromScene(const QPointF& p) const { return chatLine()->mapFromScene(p) /* - pos() */; } - QVariant ChatItem::data(int role) const { QModelIndex index = model()->index(row(), column()); @@ -126,8 +114,7 @@ QVariant ChatItem::data(int role) const return model()->data(index, role); } - -QTextLayout *ChatItem::layout() const +QTextLayout* ChatItem::layout() const { if (_cachedLayout) return _cachedLayout; @@ -138,15 +125,13 @@ QTextLayout *ChatItem::layout() const return _cachedLayout; } - void ChatItem::clearCache() { delete _cachedLayout; _cachedLayout = nullptr; } - -void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const +void ChatItem::initLayoutHelper(QTextLayout* layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const { Q_ASSERT(layout); @@ -157,20 +142,20 @@ void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapM option.setAlignment(alignment); layout->setTextOption(option); - QList formatRanges - = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).value()); + QList formatRanges = QtUi::style() + ->toTextLayoutList(formatList(), + layout->text().length(), + data(ChatLineModel::MsgLabelRole).value()); layout->setAdditionalFormats(formatRanges); } - -void ChatItem::initLayout(QTextLayout *layout) const +void ChatItem::initLayout(QTextLayout* layout) const { initLayoutHelper(layout, QTextOption::NoWrap); doLayout(layout); } - -void ChatItem::doLayout(QTextLayout *layout) const +void ChatItem::doLayout(QTextLayout* layout) const { layout->beginLayout(); QTextLine line = layout->createLine(); @@ -181,14 +166,12 @@ void ChatItem::doLayout(QTextLayout *layout) const layout->endLayout(); } - UiStyle::FormatList ChatItem::formatList() const { return data(MessageModel::FormatRole).value(); } - -qint16 ChatItem::posToCursor(const QPointF &posInLine) const +qint16 ChatItem::posToCursor(const QPointF& posInLine) const { QPointF pos = mapFromLine(posInLine); if (pos.y() > height()) @@ -205,8 +188,7 @@ qint16 ChatItem::posToCursor(const QPointF &posInLine) const return 0; } - -void ChatItem::paintBackground(QPainter *painter) +void ChatItem::paintBackground(QPainter* painter) { QVariant bgBrush; if (_selectionMode == FullSelection) @@ -217,12 +199,12 @@ void ChatItem::paintBackground(QPainter *painter) painter->fillRect(boundingRect(), bgBrush.value()); } - // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data // This is a deliberate trade-off. (-> selectFmt creation, data() call) -void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void ChatItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { - Q_UNUSED(option); Q_UNUSED(widget); + Q_UNUSED(option); + Q_UNUSED(widget); painter->save(); painter->setClipRect(boundingRect()); paintBackground(painter); @@ -235,38 +217,37 @@ void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, // uncomment partially or all of the following stuff: // // 0) alternativ painter color for debug stuff -// if(row() % 2) -// painter->setPen(Qt::red); -// else -// painter->setPen(Qt::blue); -// 1) draw wordwrap points in the first line -// if(column() == 2) { -// ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value(); -// foreach(ChatLineModel::Word word, wrapList) { -// if(word.endX > width()) -// break; -// painter->drawLine(word.endX, 0, word.endX, height()); -// } -// } -// 2) draw MsgId over the time column -// if(column() == 0) { -// QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value().toLongLong()); -// QPointF bottomPoint = boundingRect().bottomLeft(); -// bottomPoint.ry() -= 2; -// painter->drawText(bottomPoint, msgIdString); -// } -// 3) draw bounding rect -// painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1)); + // if(row() % 2) + // painter->setPen(Qt::red); + // else + // painter->setPen(Qt::blue); + // 1) draw wordwrap points in the first line + // if(column() == 2) { + // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value(); + // foreach(ChatLineModel::Word word, wrapList) { + // if(word.endX > width()) + // break; + // painter->drawLine(word.endX, 0, word.endX, height()); + // } + // } + // 2) draw MsgId over the time column + // if(column() == 0) { + // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value().toLongLong()); + // QPointF bottomPoint = boundingRect().bottomLeft(); + // bottomPoint.ry() -= 2; + // painter->drawText(bottomPoint, msgIdString); + // } + // 3) draw bounding rect + // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1)); painter->restore(); } - -void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const +void ChatItem::overlayFormat(UiStyle::FormatList& fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const { for (size_t i = 0; i < fmtList.size(); i++) { int fmtStart = fmtList.at(i).first; - int fmtEnd = (i < fmtList.size()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length()); + int fmtEnd = (i < fmtList.size() - 1 ? fmtList.at(i + 1).first : data(MessageModel::DisplayRole).toString().length()); if (fmtEnd <= start) continue; @@ -280,14 +261,13 @@ void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, quint16 start, quint1 } if (end < fmtEnd) { fmtList.insert(fmtList.begin() + i, fmtList.at(i)); - fmtList[i+1].first = end; + fmtList[i + 1].first = end; } fmtList[i].second.type |= overlayFmt; } } - QVector ChatItem::additionalFormats() const { // Calculate formats to overlay (only) if there's a selection, and/or a hovered clickable @@ -299,9 +279,10 @@ QVector ChatItem::additionalFormats() const using Format = UiStyle::Format; auto itemLabel = data(ChatLineModel::MsgLabelRole).value