summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTobias Markmann <tm@ayena.de>2016-03-31 14:57:35 (GMT)
committerTobias Markmann <tm@ayena.de>2016-03-31 14:57:35 (GMT)
commitcfbdb43d2cadd40aa87338d41548e4bf89e146e6 (patch)
tree18d94153a302445196fc0c18586abf44a1ce4a38 /Swift/QtUI
parent1d545a4a7fb877f021508094b88c1f17b30d8b4e (diff)
downloadswift-cfbdb43d2cadd40aa87338d41548e4bf89e146e6.zip
swift-cfbdb43d2cadd40aa87338d41548e4bf89e146e6.tar.bz2
Convert tabs to 4 spaces for all source files
Removed trailing spaces and whitespace on empty lines in the process. Changed CheckTabs.py tool to disallow hard tabs in source files. Test-Information: Manually checked 30 random files that the conversion worked as expected. Change-Id: I874f99d617bd3d2bb55f02d58f22f58f9b094480
Diffstat (limited to 'Swift/QtUI')
-rw-r--r--Swift/QtUI/ApplicationTest/main.cpp44
-rw-r--r--Swift/QtUI/CAPICertificateSelector.cpp114
-rw-r--r--Swift/QtUI/CAPICertificateSelector.h4
-rw-r--r--Swift/QtUI/ChatList/ChatListDelegate.cpp184
-rw-r--r--Swift/QtUI/ChatList/ChatListDelegate.h42
-rw-r--r--Swift/QtUI/ChatList/ChatListGroupItem.h58
-rw-r--r--Swift/QtUI/ChatList/ChatListItem.h20
-rw-r--r--Swift/QtUI/ChatList/ChatListMUCItem.cpp24
-rw-r--r--Swift/QtUI/ChatList/ChatListMUCItem.h30
-rw-r--r--Swift/QtUI/ChatList/ChatListModel.cpp228
-rw-r--r--Swift/QtUI/ChatList/ChatListModel.h66
-rw-r--r--Swift/QtUI/ChatList/ChatListRecentItem.cpp26
-rw-r--r--Swift/QtUI/ChatList/ChatListRecentItem.h32
-rw-r--r--Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp50
-rw-r--r--Swift/QtUI/ChatList/ChatListWhiteboardItem.h30
-rw-r--r--Swift/QtUI/ChatList/QtChatListWindow.cpp248
-rw-r--r--Swift/QtUI/ChatList/QtChatListWindow.h84
-rw-r--r--Swift/QtUI/ChatSnippet.cpp116
-rw-r--r--Swift/QtUI/ChatSnippet.h100
-rw-r--r--Swift/QtUI/ChatView/main.cpp260
-rw-r--r--Swift/QtUI/CocoaApplicationActivateHelper.h28
-rw-r--r--Swift/QtUI/CocoaApplicationActivateHelper.mm32
-rw-r--r--Swift/QtUI/CocoaUIHelpers.h2
-rw-r--r--Swift/QtUI/CocoaUIHelpers.mm34
-rw-r--r--Swift/QtUI/EventViewer/EventDelegate.cpp106
-rw-r--r--Swift/QtUI/EventViewer/EventDelegate.h32
-rw-r--r--Swift/QtUI/EventViewer/EventModel.cpp126
-rw-r--r--Swift/QtUI/EventViewer/EventModel.h30
-rw-r--r--Swift/QtUI/EventViewer/EventView.cpp2
-rw-r--r--Swift/QtUI/EventViewer/EventView.h10
-rw-r--r--Swift/QtUI/EventViewer/QtEvent.cpp128
-rw-r--r--Swift/QtUI/EventViewer/QtEvent.h28
-rw-r--r--Swift/QtUI/EventViewer/QtEventWindow.cpp140
-rw-r--r--Swift/QtUI/EventViewer/QtEventWindow.h42
-rw-r--r--Swift/QtUI/EventViewer/TwoLineDelegate.cpp70
-rw-r--r--Swift/QtUI/EventViewer/TwoLineDelegate.h24
-rw-r--r--Swift/QtUI/EventViewer/main.cpp26
-rw-r--r--Swift/QtUI/FreeDesktopNotifier.cpp62
-rw-r--r--Swift/QtUI/FreeDesktopNotifier.h18
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp96
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchDelegate.h22
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp30
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h18
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchItem.h10
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchModel.cpp104
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchModel.h34
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp12
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchRoomItem.h22
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchServiceItem.h34
-rw-r--r--Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp238
-rw-r--r--Swift/QtUI/MUCSearch/QtMUCSearchWindow.h74
-rw-r--r--Swift/QtUI/MessageSnippet.cpp54
-rw-r--r--Swift/QtUI/MessageSnippet.h26
-rw-r--r--Swift/QtUI/NotifierTest/NotifierTest.cpp10
-rw-r--r--Swift/QtUI/QtAboutWidget.cpp98
-rw-r--r--Swift/QtUI/QtAboutWidget.h14
-rw-r--r--Swift/QtUI/QtAdHocCommandWindow.cpp222
-rw-r--r--Swift/QtUI/QtAdHocCommandWindow.h74
-rw-r--r--Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp46
-rw-r--r--Swift/QtUI/QtAdHocCommandWithJIDWindow.h30
-rw-r--r--Swift/QtUI/QtAddBookmarkWindow.cpp22
-rw-r--r--Swift/QtUI/QtAddBookmarkWindow.h18
-rw-r--r--Swift/QtUI/QtAffiliationEditor.cpp78
-rw-r--r--Swift/QtUI/QtAffiliationEditor.h36
-rw-r--r--Swift/QtUI/QtAvatarWidget.cpp146
-rw-r--r--Swift/QtUI/QtAvatarWidget.h64
-rw-r--r--Swift/QtUI/QtBlockListEditorWindow.cpp290
-rw-r--r--Swift/QtUI/QtBlockListEditorWindow.h48
-rw-r--r--Swift/QtUI/QtBookmarkDetailWindow.cpp94
-rw-r--r--Swift/QtUI/QtBookmarkDetailWindow.h26
-rw-r--r--Swift/QtUI/QtCachedImageScaler.cpp38
-rw-r--r--Swift/QtUI/QtCachedImageScaler.h10
-rw-r--r--Swift/QtUI/QtCertificateViewerDialog.cpp178
-rw-r--r--Swift/QtUI/QtCertificateViewerDialog.h28
-rw-r--r--Swift/QtUI/QtChatTabs.cpp618
-rw-r--r--Swift/QtUI/QtChatTabs.h114
-rw-r--r--Swift/QtUI/QtChatTabsBase.h8
-rw-r--r--Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp98
-rw-r--r--Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h28
-rw-r--r--Swift/QtUI/QtChatTheme.cpp88
-rw-r--r--Swift/QtUI/QtChatTheme.h54
-rw-r--r--Swift/QtUI/QtChatView.cpp2
-rw-r--r--Swift/QtUI/QtChatView.h76
-rw-r--r--Swift/QtUI/QtChatWindow.cpp1270
-rw-r--r--Swift/QtUI/QtChatWindow.h398
-rw-r--r--Swift/QtUI/QtChatWindowFactory.cpp88
-rw-r--r--Swift/QtUI/QtChatWindowFactory.h48
-rw-r--r--Swift/QtUI/QtChatWindowJSBridge.cpp4
-rw-r--r--Swift/QtUI/QtChatWindowJSBridge.h8
-rw-r--r--Swift/QtUI/QtClickableLabel.cpp2
-rw-r--r--Swift/QtUI/QtClickableLabel.h16
-rw-r--r--Swift/QtUI/QtClosableLineEdit.cpp48
-rw-r--r--Swift/QtUI/QtClosableLineEdit.h22
-rw-r--r--Swift/QtUI/QtColorToolButton.cpp30
-rw-r--r--Swift/QtUI/QtColorToolButton.h36
-rw-r--r--Swift/QtUI/QtConnectionSettingsWindow.cpp260
-rw-r--r--Swift/QtUI/QtConnectionSettingsWindow.h42
-rw-r--r--Swift/QtUI/QtContactEditWidget.cpp248
-rw-r--r--Swift/QtUI/QtContactEditWidget.h64
-rw-r--r--Swift/QtUI/QtContactEditWindow.cpp102
-rw-r--r--Swift/QtUI/QtContactEditWindow.h42
-rw-r--r--Swift/QtUI/QtDBUSURIHandler.cpp38
-rw-r--r--Swift/QtUI/QtDBUSURIHandler.h8
-rw-r--r--Swift/QtUI/QtEditBookmarkWindow.cpp22
-rw-r--r--Swift/QtUI/QtEditBookmarkWindow.h20
-rw-r--r--Swift/QtUI/QtElidingLabel.cpp56
-rw-r--r--Swift/QtUI/QtElidingLabel.h34
-rw-r--r--Swift/QtUI/QtEmoticonCell.cpp14
-rw-r--r--Swift/QtUI/QtEmoticonCell.h26
-rw-r--r--Swift/QtUI/QtEmoticonsGrid.cpp50
-rw-r--r--Swift/QtUI/QtEmoticonsGrid.h26
-rw-r--r--Swift/QtUI/QtFileTransferListItemModel.cpp152
-rw-r--r--Swift/QtUI/QtFileTransferListItemModel.h46
-rw-r--r--Swift/QtUI/QtFileTransferListWidget.cpp94
-rw-r--r--Swift/QtUI/QtFileTransferListWidget.h30
-rw-r--r--Swift/QtUI/QtFormResultItemModel.cpp80
-rw-r--r--Swift/QtUI/QtFormResultItemModel.h28
-rw-r--r--Swift/QtUI/QtFormWidget.cpp374
-rw-r--r--Swift/QtUI/QtFormWidget.h26
-rw-r--r--Swift/QtUI/QtHighlightEditor.cpp782
-rw-r--r--Swift/QtUI/QtHighlightEditor.h90
-rw-r--r--Swift/QtUI/QtHistoryWindow.cpp312
-rw-r--r--Swift/QtUI/QtHistoryWindow.h114
-rw-r--r--Swift/QtUI/QtJoinMUCWindow.cpp66
-rw-r--r--Swift/QtUI/QtJoinMUCWindow.h112
-rw-r--r--Swift/QtUI/QtLineEdit.cpp8
-rw-r--r--Swift/QtUI/QtLineEdit.h18
-rw-r--r--Swift/QtUI/QtLoginWindow.cpp750
-rw-r--r--Swift/QtUI/QtLoginWindow.h156
-rw-r--r--Swift/QtUI/QtMUCConfigurationWindow.cpp62
-rw-r--r--Swift/QtUI/QtMUCConfigurationWindow.h38
-rw-r--r--Swift/QtUI/QtMainWindow.cpp496
-rw-r--r--Swift/QtUI/QtMainWindow.h154
-rw-r--r--Swift/QtUI/QtNameWidget.cpp114
-rw-r--r--Swift/QtUI/QtNameWidget.h66
-rw-r--r--Swift/QtUI/QtPlainChatView.cpp598
-rw-r--r--Swift/QtUI/QtPlainChatView.h216
-rw-r--r--Swift/QtUI/QtProfileWindow.cpp174
-rw-r--r--Swift/QtUI/QtProfileWindow.h50
-rw-r--r--Swift/QtUI/QtResourceHelper.cpp20
-rw-r--r--Swift/QtUI/QtRosterHeader.cpp152
-rw-r--r--Swift/QtUI/QtRosterHeader.h72
-rw-r--r--Swift/QtUI/QtScaledAvatarCache.cpp66
-rw-r--r--Swift/QtUI/QtScaledAvatarCache.h14
-rw-r--r--Swift/QtUI/QtSettingsProvider.cpp120
-rw-r--r--Swift/QtUI/QtSettingsProvider.h44
-rw-r--r--Swift/QtUI/QtSingleWindow.cpp60
-rw-r--r--Swift/QtUI/QtSingleWindow.h46
-rw-r--r--Swift/QtUI/QtSoundPlayer.cpp32
-rw-r--r--Swift/QtUI/QtSoundPlayer.h24
-rw-r--r--Swift/QtUI/QtSpellCheckHighlighter.cpp20
-rw-r--r--Swift/QtUI/QtSpellCheckHighlighter.h14
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.cpp120
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.h40
-rw-r--r--Swift/QtUI/QtStatusWidget.cpp424
-rw-r--r--Swift/QtUI/QtStatusWidget.h98
-rw-r--r--Swift/QtUI/QtSubscriptionRequestWindow.cpp98
-rw-r--r--Swift/QtUI/QtSubscriptionRequestWindow.h36
-rw-r--r--Swift/QtUI/QtSwift.cpp332
-rw-r--r--Swift/QtUI/QtSwift.h118
-rw-r--r--Swift/QtUI/QtSystemTray.cpp86
-rw-r--r--Swift/QtUI/QtSystemTray.h60
-rw-r--r--Swift/QtUI/QtTabWidget.cpp4
-rw-r--r--Swift/QtUI/QtTabWidget.h16
-rw-r--r--Swift/QtUI/QtTabbable.cpp58
-rw-r--r--Swift/QtUI/QtTabbable.h46
-rw-r--r--Swift/QtUI/QtTextEdit.cpp290
-rw-r--r--Swift/QtUI/QtTextEdit.h86
-rw-r--r--Swift/QtUI/QtTranslator.h14
-rw-r--r--Swift/QtUI/QtUIFactory.cpp150
-rw-r--r--Swift/QtUI/QtUIFactory.h122
-rw-r--r--Swift/QtUI/QtUISettingConstants.h24
-rw-r--r--Swift/QtUI/QtURIHandler.cpp18
-rw-r--r--Swift/QtUI/QtURIHandler.h12
-rw-r--r--Swift/QtUI/QtURLValidator.cpp8
-rw-r--r--Swift/QtUI/QtURLValidator.h12
-rw-r--r--Swift/QtUI/QtUtilities.cpp20
-rw-r--r--Swift/QtUI/QtUtilities.h14
-rw-r--r--Swift/QtUI/QtVCardWidget/QtCloseButton.cpp32
-rw-r--r--Swift/QtUI/QtVCardWidget/QtCloseButton.h18
-rw-r--r--Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp50
-rw-r--r--Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h18
-rw-r--r--Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp38
-rw-r--r--Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp104
-rw-r--r--Swift/QtUI/QtVCardWidget/QtTagComboBox.h40
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp234
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressField.h72
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp106
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h36
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp40
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp50
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h64
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp172
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h122
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp14
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h20
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp78
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp60
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardJIDField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp172
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h44
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp120
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h60
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp24
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardRoleField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp122
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp26
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTitleField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp60
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardURLField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp666
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardWidget.h82
-rw-r--r--Swift/QtUI/QtWebKitChatView.cpp1344
-rw-r--r--Swift/QtUI/QtWebKitChatView.h328
-rw-r--r--Swift/QtUI/QtWebView.cpp102
-rw-r--r--Swift/QtUI/QtWebView.h44
-rw-r--r--Swift/QtUI/QtWin32NotifierWindow.h26
-rw-r--r--Swift/QtUI/QtXMLConsoleWidget.cpp116
-rw-r--r--Swift/QtUI/QtXMLConsoleWidget.h36
-rw-r--r--Swift/QtUI/Roster/DelegateCommons.cpp168
-rw-r--r--Swift/QtUI/Roster/DelegateCommons.h44
-rw-r--r--Swift/QtUI/Roster/GroupItemDelegate.cpp164
-rw-r--r--Swift/QtUI/Roster/GroupItemDelegate.h26
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.cpp210
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.h52
-rw-r--r--Swift/QtUI/Roster/QtOccupantListWidget.cpp74
-rw-r--r--Swift/QtUI/Roster/QtOccupantListWidget.h20
-rw-r--r--Swift/QtUI/Roster/QtRosterWidget.cpp208
-rw-r--r--Swift/QtUI/Roster/QtRosterWidget.h20
-rw-r--r--Swift/QtUI/Roster/QtTreeWidget.cpp300
-rw-r--r--Swift/QtUI/Roster/QtTreeWidget.h92
-rw-r--r--Swift/QtUI/Roster/RosterDelegate.cpp66
-rw-r--r--Swift/QtUI/Roster/RosterDelegate.h36
-rw-r--r--Swift/QtUI/Roster/RosterModel.cpp332
-rw-r--r--Swift/QtUI/Roster/RosterModel.h102
-rw-r--r--Swift/QtUI/Roster/RosterTooltip.cpp260
-rw-r--r--Swift/QtUI/Roster/RosterTooltip.h10
-rw-r--r--Swift/QtUI/Roster/main.cpp88
-rw-r--r--Swift/QtUI/SystemMessageSnippet.cpp20
-rw-r--r--Swift/QtUI/SystemMessageSnippet.h22
-rw-r--r--Swift/QtUI/Trellis/QtDNDTabBar.cpp218
-rw-r--r--Swift/QtUI/Trellis/QtDNDTabBar.h50
-rw-r--r--Swift/QtUI/Trellis/QtDynamicGridLayout.cpp748
-rw-r--r--Swift/QtUI/Trellis/QtDynamicGridLayout.h94
-rw-r--r--Swift/QtUI/Trellis/QtGridSelectionDialog.cpp188
-rw-r--r--Swift/QtUI/Trellis/QtGridSelectionDialog.h86
-rw-r--r--Swift/QtUI/UserSearch/ContactListDelegate.cpp34
-rw-r--r--Swift/QtUI/UserSearch/ContactListDelegate.h20
-rw-r--r--Swift/QtUI/UserSearch/ContactListModel.cpp140
-rw-r--r--Swift/QtUI/UserSearch/ContactListModel.h72
-rw-r--r--Swift/QtUI/UserSearch/QtContactListWidget.cpp80
-rw-r--r--Swift/QtUI/UserSearch/QtContactListWidget.h34
-rw-r--r--Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp274
-rw-r--r--Swift/QtUI/UserSearch/QtSuggestingJIDInput.h56
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp20
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h36
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp32
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h24
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp108
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h62
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp50
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstPage.h30
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp32
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchResultsPage.h22
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchWindow.cpp888
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchWindow.h160
-rw-r--r--Swift/QtUI/UserSearch/UserSearchDelegate.cpp72
-rw-r--r--Swift/QtUI/UserSearch/UserSearchDelegate.h24
-rw-r--r--Swift/QtUI/UserSearch/UserSearchModel.cpp86
-rw-r--r--Swift/QtUI/UserSearch/UserSearchModel.h46
-rw-r--r--Swift/QtUI/Whiteboard/ColorWidget.cpp46
-rw-r--r--Swift/QtUI/Whiteboard/ColorWidget.h30
-rw-r--r--Swift/QtUI/Whiteboard/FreehandLineItem.cpp150
-rw-r--r--Swift/QtUI/Whiteboard/FreehandLineItem.h36
-rw-r--r--Swift/QtUI/Whiteboard/GView.cpp970
-rw-r--r--Swift/QtUI/Whiteboard/GView.h102
-rw-r--r--Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp730
-rw-r--r--Swift/QtUI/Whiteboard/QtWhiteboardWindow.h106
-rw-r--r--Swift/QtUI/Whiteboard/TextDialog.cpp84
-rw-r--r--Swift/QtUI/Whiteboard/TextDialog.h44
-rw-r--r--Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h336
-rw-r--r--Swift/QtUI/WinUIHelpers.cpp66
-rw-r--r--Swift/QtUI/WinUIHelpers.h2
-rw-r--r--Swift/QtUI/WindowsNotifier.cpp40
-rw-r--r--Swift/QtUI/WindowsNotifier.h30
-rw-r--r--Swift/QtUI/main.cpp96
-rw-r--r--Swift/QtUI/swift-open-uri.cpp26
292 files changed, 15671 insertions, 15671 deletions
diff --git a/Swift/QtUI/ApplicationTest/main.cpp b/Swift/QtUI/ApplicationTest/main.cpp
index 489865e..782bbf1 100644
--- a/Swift/QtUI/ApplicationTest/main.cpp
+++ b/Swift/QtUI/ApplicationTest/main.cpp
@@ -18,31 +18,31 @@
using namespace Swift;
class MyWidget : public QWidget {
- Q_OBJECT
-
- public:
- MyWidget() : application_("MyApplication") {
- QVBoxLayout *layout = new QVBoxLayout(this);
- input_ = new QLineEdit(this);
- layout->addWidget(input_);
- connect(input_, SIGNAL(returnPressed()), SLOT(handleReturnPressed()));
- }
-
- private slots:
- void handleReturnPressed() {
- application_.getApplicationMessageDisplay()->setMessage(Q2PSTRING(input_->text()));
- }
-
- private:
- PlatformApplication application_;
- QLineEdit* input_;
+ Q_OBJECT
+
+ public:
+ MyWidget() : application_("MyApplication") {
+ QVBoxLayout *layout = new QVBoxLayout(this);
+ input_ = new QLineEdit(this);
+ layout->addWidget(input_);
+ connect(input_, SIGNAL(returnPressed()), SLOT(handleReturnPressed()));
+ }
+
+ private slots:
+ void handleReturnPressed() {
+ application_.getApplicationMessageDisplay()->setMessage(Q2PSTRING(input_->text()));
+ }
+
+ private:
+ PlatformApplication application_;
+ QLineEdit* input_;
};
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
- MyWidget widget;
- widget.show();
- return app.exec();
+ QApplication app(argc, argv);
+ MyWidget widget;
+ widget.show();
+ return app.exec();
}
#include "main.moc"
diff --git a/Swift/QtUI/CAPICertificateSelector.cpp b/Swift/QtUI/CAPICertificateSelector.cpp
index 953051b..36d8c54 100644
--- a/Swift/QtUI/CAPICertificateSelector.cpp
+++ b/Swift/QtUI/CAPICertificateSelector.cpp
@@ -23,94 +23,94 @@
namespace Swift {
/////Hmm, maybe we should not exlude the "location" column
-#define exclude_columns CRYPTUI_SELECT_LOCATION_COLUMN | CRYPTUI_SELECT_INTENDEDUSE_COLUMN
+#define exclude_columns CRYPTUI_SELECT_LOCATION_COLUMN | CRYPTUI_SELECT_INTENDEDUSE_COLUMN
#define SHA1_HASH_LENGTH 20
static std::string getCertUri(PCCERT_CONTEXT cert, const char * cert_store_name) {
- DWORD cbHash = SHA1_HASH_LENGTH;
- BYTE aHash[SHA1_HASH_LENGTH];
- std::string result("certstore:");
+ DWORD cbHash = SHA1_HASH_LENGTH;
+ BYTE aHash[SHA1_HASH_LENGTH];
+ std::string result("certstore:");
- result += cert_store_name;
- result += ":sha1:";
+ result += cert_store_name;
+ result += ":sha1:";
- if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, aHash, &cbHash) == FALSE ) {
- return "";
- }
+ if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, aHash, &cbHash) == FALSE ) {
+ return "";
+ }
- ByteArray byteArray = createByteArray((char *)(&aHash[0]), cbHash);
- result += Hexify::hexify(byteArray);
+ ByteArray byteArray = createByteArray((char *)(&aHash[0]), cbHash);
+ result += Hexify::hexify(byteArray);
- return result;
+ return result;
}
std::string selectCAPICertificate() {
- const char* certStoreName = "MY";
+ const char* certStoreName = "MY";
- DWORD storeFlags = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
+ DWORD storeFlags = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
- HCERTSTORE hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, storeFlags, certStoreName);
- if (!hstore) {
- return "";
- }
+ HCERTSTORE hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, storeFlags, certStoreName);
+ if (!hstore) {
+ return "";
+ }
- HWND hwnd = GetForegroundWindow();
- if (!hwnd) {
- hwnd = GetActiveWindow();
- }
+ HWND hwnd = GetForegroundWindow();
+ if (!hwnd) {
+ hwnd = GetActiveWindow();
+ }
- std::string certificateDialogTitle = QT_TRANSLATE_NOOP("", "TLS Client Certificate Selection");
- std::string certificateDialogPrompt = QT_TRANSLATE_NOOP("", "Select a certificate to use for authentication");
+ std::string certificateDialogTitle = QT_TRANSLATE_NOOP("", "TLS Client Certificate Selection");
+ std::string certificateDialogPrompt = QT_TRANSLATE_NOOP("", "Select a certificate to use for authentication");
- int titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, NULL, 0);
- int promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, NULL, 0);
+ int titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, NULL, 0);
+ int promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, NULL, 0);
- wchar_t* titleChars = new wchar_t[titleLength];
- wchar_t* promptChars = new wchar_t[promptLength];
+ wchar_t* titleChars = new wchar_t[titleLength];
+ wchar_t* promptChars = new wchar_t[promptLength];
- //titleChars[titleLength] = '\0';
- //promptChars[promptLength] = '\0';
+ //titleChars[titleLength] = '\0';
+ //promptChars[promptLength] = '\0';
- titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, titleChars, titleLength);
- promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, promptChars, promptLength);
+ titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, titleChars, titleLength);
+ promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, promptChars, promptLength);
- if (titleLength == 0 || promptLength == 0) {
- int error = GetLastError();
- switch (error) {
- case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog" << std::endl;break;
- case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog" << std::endl;break;
- case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog" << std::endl;break;
- case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog" << std::endl;break;
- default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode" << std::endl;
+ if (titleLength == 0 || promptLength == 0) {
+ int error = GetLastError();
+ switch (error) {
+ case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog" << std::endl;break;
+ case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog" << std::endl;break;
+ case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog" << std::endl;break;
+ case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog" << std::endl;break;
+ default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode" << std::endl;
- }
- }
+ }
+ }
-
- /* Call Windows dialog to select a suitable certificate */
- PCCERT_CONTEXT cert = CryptUIDlgSelectCertificateFromStore(hstore, hwnd, titleChars, promptChars, exclude_columns, 0, NULL);
- delete[] titleChars;
- delete[] promptChars;
+ /* Call Windows dialog to select a suitable certificate */
+ PCCERT_CONTEXT cert = CryptUIDlgSelectCertificateFromStore(hstore, hwnd, titleChars, promptChars, exclude_columns, 0, NULL);
- if (hstore) {
- CertCloseStore(hstore, 0);
- }
+ delete[] titleChars;
+ delete[] promptChars;
- std::string result;
+ if (hstore) {
+ CertCloseStore(hstore, 0);
+ }
- if (cert) {
- result = getCertUri(cert, certStoreName);
- CertFreeCertificateContext(cert);
- }
+ std::string result;
- return result;
+ if (cert) {
+ result = getCertUri(cert, certStoreName);
+ CertFreeCertificateContext(cert);
+ }
+
+ return result;
}
bool isCAPIURI(std::string uri) {
- return (boost::iequals(uri.substr(0, 10), "certstore:"));
+ return (boost::iequals(uri.substr(0, 10), "certstore:"));
}
}
diff --git a/Swift/QtUI/CAPICertificateSelector.h b/Swift/QtUI/CAPICertificateSelector.h
index 714f1c5..8273c78 100644
--- a/Swift/QtUI/CAPICertificateSelector.h
+++ b/Swift/QtUI/CAPICertificateSelector.h
@@ -9,6 +9,6 @@
#include <string>
namespace Swift {
- std::string selectCAPICertificate();
- bool isCAPIURI(std::string uri);
+ std::string selectCAPICertificate();
+ bool isCAPIURI(std::string uri);
}
diff --git a/Swift/QtUI/ChatList/ChatListDelegate.cpp b/Swift/QtUI/ChatList/ChatListDelegate.cpp
index 5fa4e23..29eb29a 100644
--- a/Swift/QtUI/ChatList/ChatListDelegate.cpp
+++ b/Swift/QtUI/ChatList/ChatListDelegate.cpp
@@ -19,125 +19,125 @@
namespace Swift {
ChatListDelegate::ChatListDelegate(bool compact) : compact_(compact) {
- groupDelegate_ = new GroupItemDelegate();
+ groupDelegate_ = new GroupItemDelegate();
}
ChatListDelegate::~ChatListDelegate() {
- delete groupDelegate_;
+ delete groupDelegate_;
}
void ChatListDelegate::setCompact(bool compact) {
- compact_ = compact;
- emit sizeHintChanged(QModelIndex());
+ compact_ = compact;
+ emit sizeHintChanged(QModelIndex());
}
QSize ChatListDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
- if (item && dynamic_cast<ChatListMUCItem*>(item)) {
- return mucSizeHint(option, index);
- }
- else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
- return common_.contactSizeHint(option, index, compact_);
- }
- else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
- return groupDelegate_->sizeHint(option, index);
- }
- else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
- return common_.contactSizeHint(option, index, compact_);
- }
- return QStyledItemDelegate::sizeHint(option, index);
+ ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
+ if (item && dynamic_cast<ChatListMUCItem*>(item)) {
+ return mucSizeHint(option, index);
+ }
+ else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
+ return common_.contactSizeHint(option, index, compact_);
+ }
+ else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
+ return groupDelegate_->sizeHint(option, index);
+ }
+ else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
+ return common_.contactSizeHint(option, index, compact_);
+ }
+ return QStyledItemDelegate::sizeHint(option, index);
}
QSize ChatListDelegate::mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
QSize ChatListDelegate::recentSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const {
- return mucSizeHint(option, index);
+ return mucSizeHint(option, index);
}
void ChatListDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
- if (item && dynamic_cast<ChatListMUCItem*>(item)) {
- paintMUC(painter, option, dynamic_cast<ChatListMUCItem*>(item));
- }
- else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
- paintRecent(painter, option, dynamic_cast<ChatListRecentItem*>(item));
- }
- else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
- ChatListGroupItem* group = dynamic_cast<ChatListGroupItem*>(item);
- groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
- }
- else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
- paintWhiteboard(painter, option, dynamic_cast<ChatListWhiteboardItem*>(item));
- }
- else {
- QStyledItemDelegate::paint(painter, option, index);
- }
+ ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
+ if (item && dynamic_cast<ChatListMUCItem*>(item)) {
+ paintMUC(painter, option, dynamic_cast<ChatListMUCItem*>(item));
+ }
+ else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
+ paintRecent(painter, option, dynamic_cast<ChatListRecentItem*>(item));
+ }
+ else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
+ ChatListGroupItem* group = dynamic_cast<ChatListGroupItem*>(item);
+ groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
+ }
+ else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
+ paintWhiteboard(painter, option, dynamic_cast<ChatListWhiteboardItem*>(item));
+ }
+ else {
+ QStyledItemDelegate::paint(painter, option, index);
+ }
}
void ChatListDelegate::paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const {
- painter->save();
- QRect fullRegion(option.rect);
- if ( option.state & QStyle::State_Selected ) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- } else {
- QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
- painter->setPen(QPen(nameColor));
- }
-
- QFontMetrics nameMetrics(common_.nameFont);
- painter->setFont(common_.nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
- int nameHeight = nameMetrics.height() + common_.verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
- DelegateCommons::drawElidedText(painter, nameRegion, item->data(Qt::DisplayRole).toString());
-
- painter->setFont(common_.detailFont);
- painter->setPen(QPen(QColor(160,160,160)));
-
- QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- DelegateCommons::drawElidedText(painter, detailRegion, item->data(ChatListMUCItem::DetailTextRole).toString());
-
- painter->restore();
+ painter->save();
+ QRect fullRegion(option.rect);
+ if ( option.state & QStyle::State_Selected ) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ } else {
+ QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+ painter->setPen(QPen(nameColor));
+ }
+
+ QFontMetrics nameMetrics(common_.nameFont);
+ painter->setFont(common_.nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+ int nameHeight = nameMetrics.height() + common_.verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+ DelegateCommons::drawElidedText(painter, nameRegion, item->data(Qt::DisplayRole).toString());
+
+ painter->setFont(common_.detailFont);
+ painter->setPen(QPen(QColor(160,160,160)));
+
+ QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ DelegateCommons::drawElidedText(painter, detailRegion, item->data(ChatListMUCItem::DetailTextRole).toString());
+
+ painter->restore();
}
void ChatListDelegate::paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const {
- QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
- QString avatarPath;
- if (item->data(ChatListRecentItem::AvatarRole).isValid() && !item->data(ChatListRecentItem::AvatarRole).value<QString>().isNull()) {
- avatarPath = item->data(ChatListRecentItem::AvatarRole).value<QString>();
- }
- QIcon presenceIcon = item->data(ChatListRecentItem::PresenceIconRole).isValid() && !item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
- ? item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");
- QString name = item->data(Qt::DisplayRole).toString();
- //qDebug() << "Avatar for " << name << " = " << avatarPath;
- QString statusText = item->data(ChatListRecentItem::DetailTextRole).toString();
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
+ QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath;
+ if (item->data(ChatListRecentItem::AvatarRole).isValid() && !item->data(ChatListRecentItem::AvatarRole).value<QString>().isNull()) {
+ avatarPath = item->data(ChatListRecentItem::AvatarRole).value<QString>();
+ }
+ QIcon presenceIcon = item->data(ChatListRecentItem::PresenceIconRole).isValid() && !item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
+ ? item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");
+ QString name = item->data(Qt::DisplayRole).toString();
+ //qDebug() << "Avatar for " << name << " = " << avatarPath;
+ QString statusText = item->data(ChatListRecentItem::DetailTextRole).toString();
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
}
void ChatListDelegate::paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const {
- QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
- QString avatarPath;
- if (item->data(ChatListWhiteboardItem::AvatarRole).isValid() && !item->data(ChatListWhiteboardItem::AvatarRole).value<QString>().isNull()) {
- avatarPath = item->data(ChatListWhiteboardItem::AvatarRole).value<QString>();
- }
- QIcon presenceIcon;/* = item->data(ChatListWhiteboardItem::PresenceIconRole).isValid() && !item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>().isNull()
- ? item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");*/
- QString name = item->data(Qt::DisplayRole).toString();
- //qDebug() << "Avatar for " << name << " = " << avatarPath;
- QString statusText = item->data(ChatListWhiteboardItem::DetailTextRole).toString();
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
+ QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath;
+ if (item->data(ChatListWhiteboardItem::AvatarRole).isValid() && !item->data(ChatListWhiteboardItem::AvatarRole).value<QString>().isNull()) {
+ avatarPath = item->data(ChatListWhiteboardItem::AvatarRole).value<QString>();
+ }
+ QIcon presenceIcon;/* = item->data(ChatListWhiteboardItem::PresenceIconRole).isValid() && !item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>().isNull()
+ ? item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");*/
+ QString name = item->data(Qt::DisplayRole).toString();
+ //qDebug() << "Avatar for " << name << " = " << avatarPath;
+ QString statusText = item->data(ChatListWhiteboardItem::DetailTextRole).toString();
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
}
diff --git a/Swift/QtUI/ChatList/ChatListDelegate.h b/Swift/QtUI/ChatList/ChatListDelegate.h
index 2de209d..44ca947 100644
--- a/Swift/QtUI/ChatList/ChatListDelegate.h
+++ b/Swift/QtUI/ChatList/ChatListDelegate.h
@@ -11,28 +11,28 @@
#include <Swift/QtUI/Roster/GroupItemDelegate.h>
namespace Swift {
- class ChatListMUCItem;
- class ChatListRecentItem;
- class ChatListWhiteboardItem;
- class ChatListDelegate : public QStyledItemDelegate {
- public:
- ChatListDelegate(bool compact);
- ~ChatListDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- public slots:
- void setCompact(bool compact);
- private:
- void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const;
- void paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const;
- void paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const;
- QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
- QSize recentSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
+ class ChatListMUCItem;
+ class ChatListRecentItem;
+ class ChatListWhiteboardItem;
+ class ChatListDelegate : public QStyledItemDelegate {
+ public:
+ ChatListDelegate(bool compact);
+ ~ChatListDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ public slots:
+ void setCompact(bool compact);
+ private:
+ void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const;
+ void paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const;
+ void paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const;
+ QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
+ QSize recentSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
- bool compact_;
- DelegateCommons common_;
- GroupItemDelegate* groupDelegate_;
- };
+ bool compact_;
+ DelegateCommons common_;
+ GroupItemDelegate* groupDelegate_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListGroupItem.h b/Swift/QtUI/ChatList/ChatListGroupItem.h
index 9330505..427f00b 100644
--- a/Swift/QtUI/ChatList/ChatListGroupItem.h
+++ b/Swift/QtUI/ChatList/ChatListGroupItem.h
@@ -13,33 +13,33 @@
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListGroupItem : public ChatListItem {
- public:
- ChatListGroupItem(const QString& name, ChatListGroupItem* parent, bool sorted = true) : ChatListItem(parent), name_(name), sorted_(sorted) {}
- virtual ~ChatListGroupItem() {clear();}
- void addItem(ChatListItem* item) {items_.push_back(item); if (sorted_) {qStableSort(items_.begin(), items_.end(), pointerItemLessThan);}}
- void remove(int index) {items_.removeAt(index);}
- int rowCount() {return items_.size();}
- ChatListItem* item(int i) {return items_[i];}
- int row(ChatListItem* item) {return items_.indexOf(item);}
- QVariant data(int role) const {return (role == Qt::DisplayRole) ? name_ : QVariant();}
- void clear() {
- foreach (ChatListItem* item, items_) {
- delete item;
- }
- items_.clear();
- }
-
-
- private:
- static bool pointerItemLessThan(const ChatListItem* first, const ChatListItem* second) {
- QString myName = first->data(Qt::DisplayRole).toString().toLower();
- QString theirName = second->data(Qt::DisplayRole).toString().toLower();
- return myName < theirName;
- }
-
- QString name_;
- QList<ChatListItem*> items_;
- bool sorted_;
- };
+ class ChatListGroupItem : public ChatListItem {
+ public:
+ ChatListGroupItem(const QString& name, ChatListGroupItem* parent, bool sorted = true) : ChatListItem(parent), name_(name), sorted_(sorted) {}
+ virtual ~ChatListGroupItem() {clear();}
+ void addItem(ChatListItem* item) {items_.push_back(item); if (sorted_) {qStableSort(items_.begin(), items_.end(), pointerItemLessThan);}}
+ void remove(int index) {items_.removeAt(index);}
+ int rowCount() {return items_.size();}
+ ChatListItem* item(int i) {return items_[i];}
+ int row(ChatListItem* item) {return items_.indexOf(item);}
+ QVariant data(int role) const {return (role == Qt::DisplayRole) ? name_ : QVariant();}
+ void clear() {
+ foreach (ChatListItem* item, items_) {
+ delete item;
+ }
+ items_.clear();
+ }
+
+
+ private:
+ static bool pointerItemLessThan(const ChatListItem* first, const ChatListItem* second) {
+ QString myName = first->data(Qt::DisplayRole).toString().toLower();
+ QString theirName = second->data(Qt::DisplayRole).toString().toLower();
+ return myName < theirName;
+ }
+
+ QString name_;
+ QList<ChatListItem*> items_;
+ bool sorted_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListItem.h b/Swift/QtUI/ChatList/ChatListItem.h
index fa8b18a..c6fd762 100644
--- a/Swift/QtUI/ChatList/ChatListItem.h
+++ b/Swift/QtUI/ChatList/ChatListItem.h
@@ -11,16 +11,16 @@
#include <qdebug.h>
namespace Swift {
- class ChatListGroupItem;
- class ChatListItem {
- public:
- ChatListItem(ChatListGroupItem* parent) {parent_ = parent;}
- virtual ~ChatListItem() {}
+ class ChatListGroupItem;
+ class ChatListItem {
+ public:
+ ChatListItem(ChatListGroupItem* parent) {parent_ = parent;}
+ virtual ~ChatListItem() {}
- ChatListGroupItem* parent() {return parent_;}
- virtual QVariant data(int role) const = 0;
+ ChatListGroupItem* parent() {return parent_;}
+ virtual QVariant data(int role) const = 0;
- private:
- ChatListGroupItem* parent_;
- };
+ private:
+ ChatListGroupItem* parent_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListMUCItem.cpp b/Swift/QtUI/ChatList/ChatListMUCItem.cpp
index 1ad622d..7d072df 100644
--- a/Swift/QtUI/ChatList/ChatListMUCItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListMUCItem.cpp
@@ -14,21 +14,21 @@ ChatListMUCItem::ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem*
}
const MUCBookmark& ChatListMUCItem::getBookmark() const {
- return bookmark_;
+ return bookmark_;
}
QVariant ChatListMUCItem::data(int role) const {
- switch (role) {
- case Qt::DisplayRole: return P2QSTRING(bookmark_.getName());
- case DetailTextRole: return P2QSTRING(bookmark_.getRoom().toString());
- /*case Qt::TextColorRole: return textColor_;
- case Qt::BackgroundColorRole: return backgroundColor_;
- case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
- case StatusTextRole: return statusText_;
- case AvatarRole: return avatar_;
- case PresenceIconRole: return getPresenceIcon();*/
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return P2QSTRING(bookmark_.getName());
+ case DetailTextRole: return P2QSTRING(bookmark_.getRoom().toString());
+ /*case Qt::TextColorRole: return textColor_;
+ case Qt::BackgroundColorRole: return backgroundColor_;
+ case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
+ case StatusTextRole: return statusText_;
+ case AvatarRole: return avatar_;
+ case PresenceIconRole: return getPresenceIcon();*/
+ default: return QVariant();
+ }
}
}
diff --git a/Swift/QtUI/ChatList/ChatListMUCItem.h b/Swift/QtUI/ChatList/ChatListMUCItem.h
index fb90b88..4e93600 100644
--- a/Swift/QtUI/ChatList/ChatListMUCItem.h
+++ b/Swift/QtUI/ChatList/ChatListMUCItem.h
@@ -15,19 +15,19 @@
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListMUCItem : public ChatListItem {
- public:
- enum MUCItemRoles {
- DetailTextRole = Qt::UserRole/*,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2,
- StatusShowTypeRole = Qt::UserRole + 3*/
- };
- ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* parent);
- const MUCBookmark& getBookmark() const;
- QVariant data(int role) const;
- private:
- MUCBookmark bookmark_;
- QList<ChatListItem*> items_;
- };
+ class ChatListMUCItem : public ChatListItem {
+ public:
+ enum MUCItemRoles {
+ DetailTextRole = Qt::UserRole/*,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2,
+ StatusShowTypeRole = Qt::UserRole + 3*/
+ };
+ ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* parent);
+ const MUCBookmark& getBookmark() const;
+ QVariant data(int role) const;
+ private:
+ MUCBookmark bookmark_;
+ QList<ChatListItem*> items_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListModel.cpp b/Swift/QtUI/ChatList/ChatListModel.cpp
index 2447aa1..307cdea 100644
--- a/Swift/QtUI/ChatList/ChatListModel.cpp
+++ b/Swift/QtUI/ChatList/ChatListModel.cpp
@@ -17,172 +17,172 @@
namespace Swift {
ChatListModel::ChatListModel() : whiteboards_(NULL) {
- root_ = new ChatListGroupItem("", NULL, false);
- mucBookmarks_ = new ChatListGroupItem(tr("Bookmarked Rooms"), root_);
- recents_ = new ChatListGroupItem(tr("Recent Chats"), root_, false);
+ root_ = new ChatListGroupItem("", NULL, false);
+ mucBookmarks_ = new ChatListGroupItem(tr("Bookmarked Rooms"), root_);
+ recents_ = new ChatListGroupItem(tr("Recent Chats"), root_, false);
#ifdef SWIFT_EXPERIMENTAL_WB
- whiteboards_ = new ChatListGroupItem(tr("Opened Whiteboards"), root_, false);
- root_->addItem(whiteboards_);
+ whiteboards_ = new ChatListGroupItem(tr("Opened Whiteboards"), root_, false);
+ root_->addItem(whiteboards_);
#endif
- root_->addItem(recents_);
- root_->addItem(mucBookmarks_);
+ root_->addItem(recents_);
+ root_->addItem(mucBookmarks_);
- QModelIndex idx = index(0, 0, QModelIndex());
- while (idx.isValid()) {
- if (idx.internalPointer() == mucBookmarks_) {
- mucBookmarksIndex_ = idx;
- } else if (idx.internalPointer() == recents_) {
- recentsIndex_ = idx;
- } else if (idx.internalPointer() == whiteboards_) {
- whiteboardsIndex_ = idx;
- }
- idx = index(idx.row() + 1, 0, QModelIndex());
- }
+ QModelIndex idx = index(0, 0, QModelIndex());
+ while (idx.isValid()) {
+ if (idx.internalPointer() == mucBookmarks_) {
+ mucBookmarksIndex_ = idx;
+ } else if (idx.internalPointer() == recents_) {
+ recentsIndex_ = idx;
+ } else if (idx.internalPointer() == whiteboards_) {
+ whiteboardsIndex_ = idx;
+ }
+ idx = index(idx.row() + 1, 0, QModelIndex());
+ }
}
Qt::ItemFlags ChatListModel::flags(const QModelIndex& index) const {
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (dynamic_cast<ChatListRecentItem*>(getItemForIndex(index))) {
- flags |= Qt::ItemIsDragEnabled;
- }
- return flags;
+ Qt::ItemFlags flags = QAbstractItemModel::flags(index);
+ if (dynamic_cast<ChatListRecentItem*>(getItemForIndex(index))) {
+ flags |= Qt::ItemIsDragEnabled;
+ }
+ return flags;
}
void ChatListModel::clearBookmarks() {
- beginRemoveRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
- mucBookmarks_->clear();
- endRemoveRows();
+ beginRemoveRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
+ mucBookmarks_->clear();
+ endRemoveRows();
}
void ChatListModel::addMUCBookmark(const Swift::MUCBookmark& bookmark) {
- beginInsertRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
- mucBookmarks_->addItem(new ChatListMUCItem(bookmark, mucBookmarks_));
- endInsertRows();
+ beginInsertRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
+ mucBookmarks_->addItem(new ChatListMUCItem(bookmark, mucBookmarks_));
+ endInsertRows();
}
void ChatListModel::removeMUCBookmark(const Swift::MUCBookmark& bookmark) {
- for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
- ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
- if (item->getBookmark() == bookmark) {
- beginRemoveRows(mucBookmarksIndex_, i, i+1);
- mucBookmarks_->remove(i);
- endRemoveRows();
- break;
- }
- }
+ for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
+ ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
+ if (item->getBookmark() == bookmark) {
+ beginRemoveRows(mucBookmarksIndex_, i, i+1);
+ mucBookmarks_->remove(i);
+ endRemoveRows();
+ break;
+ }
+ }
}
void ChatListModel::addWhiteboardSession(const ChatListWindow::Chat& chat) {
- beginInsertRows(whiteboardsIndex_, 0, whiteboards_->rowCount());
- whiteboards_->addItem(new ChatListWhiteboardItem(chat, whiteboards_));
- endInsertRows();
+ beginInsertRows(whiteboardsIndex_, 0, whiteboards_->rowCount());
+ whiteboards_->addItem(new ChatListWhiteboardItem(chat, whiteboards_));
+ endInsertRows();
}
void ChatListModel::removeWhiteboardSession(const JID& jid) {
- for (int i = 0; i < whiteboards_->rowCount(); i++) {
- ChatListWhiteboardItem* item = dynamic_cast<ChatListWhiteboardItem*>(whiteboards_->item(i));
- if (item->getChat().jid == jid) {
- beginRemoveRows(whiteboardsIndex_, i, i+1);
- whiteboards_->remove(i);
- endRemoveRows();
- break;
- }
- }
+ for (int i = 0; i < whiteboards_->rowCount(); i++) {
+ ChatListWhiteboardItem* item = dynamic_cast<ChatListWhiteboardItem*>(whiteboards_->item(i));
+ if (item->getChat().jid == jid) {
+ beginRemoveRows(whiteboardsIndex_, i, i+1);
+ whiteboards_->remove(i);
+ endRemoveRows();
+ break;
+ }
+ }
}
void ChatListModel::setRecents(const std::list<ChatListWindow::Chat>& recents) {
- beginRemoveRows(recentsIndex_, 0, recents_->rowCount());
- recents_->clear();
- endRemoveRows();
- beginInsertRows(recentsIndex_, 0, recents.size());
- foreach (const ChatListWindow::Chat chat, recents) {
- recents_->addItem(new ChatListRecentItem(chat, recents_));
+ beginRemoveRows(recentsIndex_, 0, recents_->rowCount());
+ recents_->clear();
+ endRemoveRows();
+ beginInsertRows(recentsIndex_, 0, recents.size());
+ foreach (const ChatListWindow::Chat chat, recents) {
+ recents_->addItem(new ChatListRecentItem(chat, recents_));
//whiteboards_->addItem(new ChatListRecentItem(chat, whiteboards_));
- }
- endInsertRows();
+ }
+ endInsertRows();
}
QMimeData* ChatListModel::mimeData(const QModelIndexList& indexes) const {
- QMimeData* data = QAbstractItemModel::mimeData(indexes);
- ChatListRecentItem *item = dynamic_cast<ChatListRecentItem*>(getItemForIndex(indexes.first()));
- if (item == NULL) {
- return data;
- }
-
- QByteArray itemData;
- QDataStream dataStream(&itemData, QIODevice::WriteOnly);
- const ChatListWindow::Chat& chat = item->getChat();
-
- QString mimeType = "application/vnd.swift.contact-jid-list";
- if (!chat.impromptuJIDs.size()) {
- if (chat.isMUC) {
- mimeType = "application/vnd.swift.contact-jid-muc";
- }
- dataStream << P2QSTRING(chat.jid.toString());
- } else {
- typedef std::map<std::string, JID> JIDMap;
- foreach (const JIDMap::value_type& jid, chat.impromptuJIDs) {
- dataStream << P2QSTRING(jid.second.toString());
- }
- }
-
- data->setData(mimeType, itemData);
- return data;
+ QMimeData* data = QAbstractItemModel::mimeData(indexes);
+ ChatListRecentItem *item = dynamic_cast<ChatListRecentItem*>(getItemForIndex(indexes.first()));
+ if (item == NULL) {
+ return data;
+ }
+
+ QByteArray itemData;
+ QDataStream dataStream(&itemData, QIODevice::WriteOnly);
+ const ChatListWindow::Chat& chat = item->getChat();
+
+ QString mimeType = "application/vnd.swift.contact-jid-list";
+ if (!chat.impromptuJIDs.size()) {
+ if (chat.isMUC) {
+ mimeType = "application/vnd.swift.contact-jid-muc";
+ }
+ dataStream << P2QSTRING(chat.jid.toString());
+ } else {
+ typedef std::map<std::string, JID> JIDMap;
+ foreach (const JIDMap::value_type& jid, chat.impromptuJIDs) {
+ dataStream << P2QSTRING(jid.second.toString());
+ }
+ }
+
+ data->setData(mimeType, itemData);
+ return data;
}
const ChatListMUCItem* ChatListModel::getChatListMUCItem(const JID& roomJID) const {
- const ChatListMUCItem* mucItem = NULL;
- for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
- ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
- if (item->getBookmark().getRoom() == roomJID) {
- mucItem = item;
- break;
- }
- }
- return mucItem;
+ const ChatListMUCItem* mucItem = NULL;
+ for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
+ ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
+ if (item->getBookmark().getRoom() == roomJID) {
+ mucItem = item;
+ break;
+ }
+ }
+ return mucItem;
}
int ChatListModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ return 1;
}
ChatListItem* ChatListModel::getItemForIndex(const QModelIndex& index) const {
- return index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : NULL;
+ return index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : NULL;
}
QVariant ChatListModel::data(const QModelIndex& index, int role) const {
- ChatListItem* item = getItemForIndex(index);
- return item ? item->data(role) : QVariant();
+ ChatListItem* item = getItemForIndex(index);
+ return item ? item->data(role) : QVariant();
}
QModelIndex ChatListModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
- ChatListGroupItem *parentItem = parent.isValid() ? static_cast<ChatListGroupItem*>(parent.internalPointer()) : root_;
+ ChatListGroupItem *parentItem = parent.isValid() ? static_cast<ChatListGroupItem*>(parent.internalPointer()) : root_;
- return row < parentItem->rowCount() ? createIndex(row, column, parentItem->item(row)) : QModelIndex();
+ return row < parentItem->rowCount() ? createIndex(row, column, parentItem->item(row)) : QModelIndex();
}
QModelIndex ChatListModel::parent(const QModelIndex& index) const {
- if (!index.isValid()) {
- return QModelIndex();
- }
- ChatListGroupItem* parent = static_cast<ChatListGroupItem*>(index.internalPointer())->parent();
- return (parent == root_) ? QModelIndex() : createIndex(parent->parent()->row(parent), 0, parent);
+ if (!index.isValid()) {
+ return QModelIndex();
+ }
+ ChatListGroupItem* parent = static_cast<ChatListGroupItem*>(index.internalPointer())->parent();
+ return (parent == root_) ? QModelIndex() : createIndex(parent->parent()->row(parent), 0, parent);
}
int ChatListModel::rowCount(const QModelIndex& parentIndex) const {
- ChatListGroupItem* parent = NULL;
- if (parentIndex.isValid()) {
- parent = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(parentIndex.internalPointer()));
- } else {
- parent = root_;
- }
- int count = (parent ? parent->rowCount() : 0);
- return count;
+ ChatListGroupItem* parent = NULL;
+ if (parentIndex.isValid()) {
+ parent = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(parentIndex.internalPointer()));
+ } else {
+ parent = root_;
+ }
+ int count = (parent ? parent->rowCount() : 0);
+ return count;
}
}
diff --git a/Swift/QtUI/ChatList/ChatListModel.h b/Swift/QtUI/ChatList/ChatListModel.h
index ea85efb..363b2e6 100644
--- a/Swift/QtUI/ChatList/ChatListModel.h
+++ b/Swift/QtUI/ChatList/ChatListModel.h
@@ -16,38 +16,38 @@
#include <Swift/QtUI/ChatList/ChatListGroupItem.h>
namespace Swift {
- class ChatListMUCItem;
-
- class ChatListModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- ChatListModel();
- Qt::ItemFlags flags(const QModelIndex& index) const;
- void addMUCBookmark(const MUCBookmark& bookmark);
- void removeMUCBookmark(const MUCBookmark& bookmark);
- void addWhiteboardSession(const ChatListWindow::Chat& chat);
- void removeWhiteboardSession(const JID& jid);
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- ChatListItem* getItemForIndex(const QModelIndex& index) const;
- void clearBookmarks();
- void setRecents(const std::list<ChatListWindow::Chat>& recents);
- QMimeData* mimeData(const QModelIndexList& indexes) const;
-
- const ChatListMUCItem* getChatListMUCItem(const JID& roomJID) const;
-
- private:
- ChatListGroupItem* mucBookmarks_;
- ChatListGroupItem* recents_;
- ChatListGroupItem* whiteboards_;
- ChatListGroupItem* root_;
-
- QPersistentModelIndex mucBookmarksIndex_;
- QPersistentModelIndex recentsIndex_;
- QPersistentModelIndex whiteboardsIndex_;
- };
+ class ChatListMUCItem;
+
+ class ChatListModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ ChatListModel();
+ Qt::ItemFlags flags(const QModelIndex& index) const;
+ void addMUCBookmark(const MUCBookmark& bookmark);
+ void removeMUCBookmark(const MUCBookmark& bookmark);
+ void addWhiteboardSession(const ChatListWindow::Chat& chat);
+ void removeWhiteboardSession(const JID& jid);
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ ChatListItem* getItemForIndex(const QModelIndex& index) const;
+ void clearBookmarks();
+ void setRecents(const std::list<ChatListWindow::Chat>& recents);
+ QMimeData* mimeData(const QModelIndexList& indexes) const;
+
+ const ChatListMUCItem* getChatListMUCItem(const JID& roomJID) const;
+
+ private:
+ ChatListGroupItem* mucBookmarks_;
+ ChatListGroupItem* recents_;
+ ChatListGroupItem* whiteboards_;
+ ChatListGroupItem* root_;
+
+ QPersistentModelIndex mucBookmarksIndex_;
+ QPersistentModelIndex recentsIndex_;
+ QPersistentModelIndex whiteboardsIndex_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListRecentItem.cpp b/Swift/QtUI/ChatList/ChatListRecentItem.cpp
index dc40855..383f312 100644
--- a/Swift/QtUI/ChatList/ChatListRecentItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListRecentItem.cpp
@@ -17,25 +17,25 @@ ChatListRecentItem::ChatListRecentItem(const ChatListWindow::Chat& chat, ChatLis
}
const ChatListWindow::Chat& ChatListRecentItem::getChat() const {
- return chat_;
+ return chat_;
}
QVariant ChatListRecentItem::data(int role) const {
- switch (role) {
- case Qt::DisplayRole: return chat_.impromptuJIDs.empty() ? P2QSTRING(chat_.chatName) : P2QSTRING(chat_.getImpromptuTitle());
- case DetailTextRole: return P2QSTRING(chat_.activity);
- /*case Qt::TextColorRole: return textColor_;
- case Qt::BackgroundColorRole: return backgroundColor_;
- case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
- case StatusTextRole: return statusText_;*/
- case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
- case PresenceIconRole: return getPresenceIcon();
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return chat_.impromptuJIDs.empty() ? P2QSTRING(chat_.chatName) : P2QSTRING(chat_.getImpromptuTitle());
+ case DetailTextRole: return P2QSTRING(chat_.activity);
+ /*case Qt::TextColorRole: return textColor_;
+ case Qt::BackgroundColorRole: return backgroundColor_;
+ case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
+ case StatusTextRole: return statusText_;*/
+ case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
+ case PresenceIconRole: return getPresenceIcon();
+ default: return QVariant();
+ }
}
QIcon ChatListRecentItem::getPresenceIcon() const {
- return QIcon(statusShowTypeToIconPath(chat_.statusType));
+ return QIcon(statusShowTypeToIconPath(chat_.statusType));
}
}
diff --git a/Swift/QtUI/ChatList/ChatListRecentItem.h b/Swift/QtUI/ChatList/ChatListRecentItem.h
index 338bc43..4f0a363 100644
--- a/Swift/QtUI/ChatList/ChatListRecentItem.h
+++ b/Swift/QtUI/ChatList/ChatListRecentItem.h
@@ -18,20 +18,20 @@
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListRecentItem : public ChatListItem {
- public:
- enum RecentItemRoles {
- DetailTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2/*,
- StatusShowTypeRole = Qt::UserRole + 3,
- IdleRole = Qt::UserRole + 4*/
- };
- ChatListRecentItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
- const ChatListWindow::Chat& getChat() const;
- QVariant data(int role) const;
- private:
- QIcon getPresenceIcon() const;
- ChatListWindow::Chat chat_;
- };
+ class ChatListRecentItem : public ChatListItem {
+ public:
+ enum RecentItemRoles {
+ DetailTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2/*,
+ StatusShowTypeRole = Qt::UserRole + 3,
+ IdleRole = Qt::UserRole + 4*/
+ };
+ ChatListRecentItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
+ const ChatListWindow::Chat& getChat() const;
+ QVariant data(int role) const;
+ private:
+ QIcon getPresenceIcon() const;
+ ChatListWindow::Chat chat_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp b/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
index f6ecec1..b6f8951 100644
--- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
@@ -18,30 +18,30 @@
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
- ChatListWhiteboardItem::ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent) : ChatListItem(parent), chat_(chat) {
-
- }
-
- const ChatListWindow::Chat& ChatListWhiteboardItem::getChat() const {
- return chat_;
- }
-
- QVariant ChatListWhiteboardItem::data(int role) const {
- switch (role) {
- case Qt::DisplayRole: return P2QSTRING(chat_.chatName);
- case DetailTextRole: return P2QSTRING(chat_.activity);
- /*case Qt::TextColorRole: return textColor_;
- case Qt::BackgroundColorRole: return backgroundColor_;
- case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
- case StatusTextRole: return statusText_;*/
- case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
- case PresenceIconRole: return getPresenceIcon();
- default: return QVariant();
- }
- }
-
- QIcon ChatListWhiteboardItem::getPresenceIcon() const {
- return QIcon(statusShowTypeToIconPath(chat_.statusType));
- }
+ ChatListWhiteboardItem::ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent) : ChatListItem(parent), chat_(chat) {
+
+ }
+
+ const ChatListWindow::Chat& ChatListWhiteboardItem::getChat() const {
+ return chat_;
+ }
+
+ QVariant ChatListWhiteboardItem::data(int role) const {
+ switch (role) {
+ case Qt::DisplayRole: return P2QSTRING(chat_.chatName);
+ case DetailTextRole: return P2QSTRING(chat_.activity);
+ /*case Qt::TextColorRole: return textColor_;
+ case Qt::BackgroundColorRole: return backgroundColor_;
+ case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
+ case StatusTextRole: return statusText_;*/
+ case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
+ case PresenceIconRole: return getPresenceIcon();
+ default: return QVariant();
+ }
+ }
+
+ QIcon ChatListWhiteboardItem::getPresenceIcon() const {
+ return QIcon(statusShowTypeToIconPath(chat_.statusType));
+ }
}
diff --git a/Swift/QtUI/ChatList/ChatListWhiteboardItem.h b/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
index fbbe7c5..92acb1c 100644
--- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
+++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
@@ -18,19 +18,19 @@
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListWhiteboardItem : public ChatListItem {
- public:
- enum RecentItemRoles {
- DetailTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2/*,
- StatusShowTypeRole = Qt::UserRole + 3*/
- };
- ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
- const ChatListWindow::Chat& getChat() const;
- QVariant data(int role) const;
- private:
- QIcon getPresenceIcon() const;
- ChatListWindow::Chat chat_;
- };
+ class ChatListWhiteboardItem : public ChatListItem {
+ public:
+ enum RecentItemRoles {
+ DetailTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2/*,
+ StatusShowTypeRole = Qt::UserRole + 3*/
+ };
+ ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
+ const ChatListWindow::Chat& getChat() const;
+ QVariant data(int role) const;
+ private:
+ QIcon getPresenceIcon() const;
+ ChatListWindow::Chat chat_;
+ };
}
diff --git a/Swift/QtUI/ChatList/QtChatListWindow.cpp b/Swift/QtUI/ChatList/QtChatListWindow.cpp
index b990b84..eddd0cd 100644
--- a/Swift/QtUI/ChatList/QtChatListWindow.cpp
+++ b/Swift/QtUI/ChatList/QtChatListWindow.cpp
@@ -31,197 +31,197 @@
namespace Swift {
QtChatListWindow::QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent) : QTreeView(parent), isOnline_(false) {
- eventStream_ = uiEventStream;
- settings_ = settings;
- bookmarksEnabled_ = false;
- model_ = new ChatListModel();
- setModel(model_);
- delegate_ = new ChatListDelegate(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- setItemDelegate(delegate_);
- setHeaderHidden(true);
+ eventStream_ = uiEventStream;
+ settings_ = settings;
+ bookmarksEnabled_ = false;
+ model_ = new ChatListModel();
+ setModel(model_);
+ delegate_ = new ChatListDelegate(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ setItemDelegate(delegate_);
+ setHeaderHidden(true);
#ifdef SWIFT_PLATFORM_MACOSX
- setAlternatingRowColors(true);
+ setAlternatingRowColors(true);
#endif
- expandAll();
- setAnimated(true);
- setIndentation(0);
- setDragEnabled(true);
- setRootIsDecorated(true);
- setupContextMenus();
- connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
- connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
+ expandAll();
+ setAnimated(true);
+ setIndentation(0);
+ setDragEnabled(true);
+ setRootIsDecorated(true);
+ setupContextMenus();
+ connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
+ connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
- settings_->onSettingChanged.connect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
+ settings_->onSettingChanged.connect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
}
QtChatListWindow::~QtChatListWindow() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
- delete model_;
- delete delegate_;
- delete mucMenu_;
- delete emptyMenu_;
+ settings_->onSettingChanged.disconnect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
+ delete model_;
+ delete delegate_;
+ delete mucMenu_;
+ delete emptyMenu_;
}
void QtChatListWindow::handleSettingChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- repaint();
- }
+ if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ repaint();
+ }
}
void QtChatListWindow::handleClearRecentsRequested() {
- onClearRecentsRequested();
+ onClearRecentsRequested();
}
void QtChatListWindow::setBookmarksEnabled(bool enabled) {
- bookmarksEnabled_ = enabled;
+ bookmarksEnabled_ = enabled;
}
void QtChatListWindow::handleClicked(const QModelIndex& index) {
- ChatListGroupItem* item = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(index.internalPointer()));
- if (item) {
- setExpanded(index, !isExpanded(index));
- }
+ ChatListGroupItem* item = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(index.internalPointer()));
+ if (item) {
+ setExpanded(index, !isExpanded(index));
+ }
}
void QtChatListWindow::setupContextMenus() {
- mucMenu_ = new QMenu();
- onlineOnlyActions_ << mucMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
- onlineOnlyActions_ << mucMenu_->addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
- onlineOnlyActions_ << mucMenu_->addAction(tr("Remove Bookmark"), this, SLOT(handleRemoveBookmark()));
- emptyMenu_ = new QMenu();
- onlineOnlyActions_ << emptyMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
+ mucMenu_ = new QMenu();
+ onlineOnlyActions_ << mucMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
+ onlineOnlyActions_ << mucMenu_->addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
+ onlineOnlyActions_ << mucMenu_->addAction(tr("Remove Bookmark"), this, SLOT(handleRemoveBookmark()));
+ emptyMenu_ = new QMenu();
+ onlineOnlyActions_ << emptyMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
}
void QtChatListWindow::handleItemActivated(const QModelIndex& index) {
- ChatListItem* item = model_->getItemForIndex(index);
- if (ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(item)) {
- onMUCBookmarkActivated(mucItem->getBookmark());
- }
- else if (ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(item)) {
- onRecentActivated(recentItem->getChat());
- }
- else if (ChatListWhiteboardItem* whiteboardItem = dynamic_cast<ChatListWhiteboardItem*>(item)) {
- if (!whiteboardItem->getChat().isMUC || bookmarksEnabled_) {
- eventStream_->send(boost::make_shared<ShowWhiteboardUIEvent>(whiteboardItem->getChat().jid));
- }
- }
+ ChatListItem* item = model_->getItemForIndex(index);
+ if (ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(item)) {
+ onMUCBookmarkActivated(mucItem->getBookmark());
+ }
+ else if (ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(item)) {
+ onRecentActivated(recentItem->getChat());
+ }
+ else if (ChatListWhiteboardItem* whiteboardItem = dynamic_cast<ChatListWhiteboardItem*>(item)) {
+ if (!whiteboardItem->getChat().isMUC || bookmarksEnabled_) {
+ eventStream_->send(boost::make_shared<ShowWhiteboardUIEvent>(whiteboardItem->getChat().jid));
+ }
+ }
}
void QtChatListWindow::clearBookmarks() {
- model_->clearBookmarks();
+ model_->clearBookmarks();
}
void QtChatListWindow::addMUCBookmark(const MUCBookmark& bookmark) {
- model_->addMUCBookmark(bookmark);
+ model_->addMUCBookmark(bookmark);
}
void QtChatListWindow::removeMUCBookmark(const MUCBookmark& bookmark) {
- model_->removeMUCBookmark(bookmark);
+ model_->removeMUCBookmark(bookmark);
}
void QtChatListWindow::addWhiteboardSession(const ChatListWindow::Chat& chat) {
- model_->addWhiteboardSession(chat);
+ model_->addWhiteboardSession(chat);
}
void QtChatListWindow::removeWhiteboardSession(const JID& jid) {
- model_->removeWhiteboardSession(jid);
+ model_->removeWhiteboardSession(jid);
}
void QtChatListWindow::setRecents(const std::list<ChatListWindow::Chat>& recents) {
- model_->setRecents(recents);
+ model_->setRecents(recents);
}
void QtChatListWindow::setUnreadCount(int unread) {
- emit onCountUpdated(unread);
+ emit onCountUpdated(unread);
}
void QtChatListWindow::setOnline(bool isOnline) {
- isOnline_ = isOnline;
+ isOnline_ = isOnline;
}
void QtChatListWindow::handleRemoveBookmark() {
- const ChatListMUCItem* mucItem = dynamic_cast<const ChatListMUCItem*>(contextMenuItem_);
- if (!mucItem) return;
- eventStream_->send(boost::shared_ptr<UIEvent>(new RemoveMUCBookmarkUIEvent(mucItem->getBookmark())));
+ const ChatListMUCItem* mucItem = dynamic_cast<const ChatListMUCItem*>(contextMenuItem_);
+ if (!mucItem) return;
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RemoveMUCBookmarkUIEvent(mucItem->getBookmark())));
}
void QtChatListWindow::handleAddBookmarkFromRecents() {
- const ChatListRecentItem* item = dynamic_cast<const ChatListRecentItem*>(contextMenuItem_);
- if (item) {
- const ChatListWindow::Chat& chat = item->getChat();
- MUCBookmark bookmark(chat.jid, chat.jid.toBare().toString());
- bookmark.setNick(chat.nick);
- bookmark.setPassword(chat.password);
- eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(bookmark)));
- }
+ const ChatListRecentItem* item = dynamic_cast<const ChatListRecentItem*>(contextMenuItem_);
+ if (item) {
+ const ChatListWindow::Chat& chat = item->getChat();
+ MUCBookmark bookmark(chat.jid, chat.jid.toBare().toString());
+ bookmark.setNick(chat.nick);
+ bookmark.setPassword(chat.password);
+ eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(bookmark)));
+ }
}
void QtChatListWindow::handleAddBookmark() {
- (new QtAddBookmarkWindow(eventStream_))->show();
+ (new QtAddBookmarkWindow(eventStream_))->show();
}
void QtChatListWindow::handleEditBookmark() {
- const ChatListMUCItem* mucItem = dynamic_cast<const ChatListMUCItem*>(contextMenuItem_);
- if (!mucItem) return;
- QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, mucItem->getBookmark());
- window->show();
+ const ChatListMUCItem* mucItem = dynamic_cast<const ChatListMUCItem*>(contextMenuItem_);
+ if (!mucItem) return;
+ QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, mucItem->getBookmark());
+ window->show();
}
void QtChatListWindow::dragEnterEvent(QDragEnterEvent *event) {
- if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
- event->acceptProposedAction();
- }
+ if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
+ event->acceptProposedAction();
+ }
}
void QtChatListWindow::contextMenuEvent(QContextMenuEvent* event) {
- QModelIndex index = indexAt(event->pos());
- ChatListItem* baseItem = index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : NULL;
- contextMenuItem_ = baseItem;
-
- foreach(QAction* action, onlineOnlyActions_) {
- action->setEnabled(isOnline_);
- }
-
- if (!baseItem) {
- emptyMenu_->exec(QCursor::pos());
- return;
- }
-
- ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(baseItem);
- if (mucItem) {
- if (!bookmarksEnabled_) {
- return;
- }
- mucMenu_->exec(QCursor::pos());
- return;
- }
-
- ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(baseItem);
- if (recentItem) {
- const ChatListWindow::Chat& chat = recentItem->getChat();
- if (chat.isMUC) {
- QMenu mucRecentsMenu;
- QAction* bookmarkAction = NULL;
- const ChatListMUCItem* mucItem = model_->getChatListMUCItem(chat.jid);
- if (mucItem) {
- contextMenuItem_ = mucItem;
- bookmarkAction = mucRecentsMenu.addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
- }
- else {
- bookmarkAction = mucRecentsMenu.addAction(tr("Add to Bookmarks"), this, SLOT(handleAddBookmarkFromRecents()));
- }
- bookmarkAction->setEnabled(isOnline_);
- mucRecentsMenu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
- mucRecentsMenu.exec(QCursor::pos());
- return;
- }
- }
-
- QMenu menu;
- menu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
- menu.exec(event->globalPos());
+ QModelIndex index = indexAt(event->pos());
+ ChatListItem* baseItem = index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : NULL;
+ contextMenuItem_ = baseItem;
+
+ foreach(QAction* action, onlineOnlyActions_) {
+ action->setEnabled(isOnline_);
+ }
+
+ if (!baseItem) {
+ emptyMenu_->exec(QCursor::pos());
+ return;
+ }
+
+ ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(baseItem);
+ if (mucItem) {
+ if (!bookmarksEnabled_) {
+ return;
+ }
+ mucMenu_->exec(QCursor::pos());
+ return;
+ }
+
+ ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(baseItem);
+ if (recentItem) {
+ const ChatListWindow::Chat& chat = recentItem->getChat();
+ if (chat.isMUC) {
+ QMenu mucRecentsMenu;
+ QAction* bookmarkAction = NULL;
+ const ChatListMUCItem* mucItem = model_->getChatListMUCItem(chat.jid);
+ if (mucItem) {
+ contextMenuItem_ = mucItem;
+ bookmarkAction = mucRecentsMenu.addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
+ }
+ else {
+ bookmarkAction = mucRecentsMenu.addAction(tr("Add to Bookmarks"), this, SLOT(handleAddBookmarkFromRecents()));
+ }
+ bookmarkAction->setEnabled(isOnline_);
+ mucRecentsMenu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
+ mucRecentsMenu.exec(QCursor::pos());
+ return;
+ }
+ }
+
+ QMenu menu;
+ menu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
+ menu.exec(event->globalPos());
}
}
diff --git a/Swift/QtUI/ChatList/QtChatListWindow.h b/Swift/QtUI/ChatList/QtChatListWindow.h
index 627dcd4..61f8391 100644
--- a/Swift/QtUI/ChatList/QtChatListWindow.h
+++ b/Swift/QtUI/ChatList/QtChatListWindow.h
@@ -15,50 +15,50 @@
#include <Swift/QtUI/ChatList/ChatListModel.h>
namespace Swift {
- class SettingsProvider;
- class QtChatListWindow : public QTreeView, public ChatListWindow {
- Q_OBJECT
- public:
- QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent = NULL);
- virtual ~QtChatListWindow();
- void addMUCBookmark(const MUCBookmark& bookmark);
- void removeMUCBookmark(const MUCBookmark& bookmark);
- void addWhiteboardSession(const ChatListWindow::Chat& chat);
- void removeWhiteboardSession(const JID& jid);
- void setBookmarksEnabled(bool enabled);
- void setRecents(const std::list<ChatListWindow::Chat>& recents);
- void setUnreadCount(int unread);
- void clearBookmarks();
- virtual void setOnline(bool isOnline);
+ class SettingsProvider;
+ class QtChatListWindow : public QTreeView, public ChatListWindow {
+ Q_OBJECT
+ public:
+ QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent = NULL);
+ virtual ~QtChatListWindow();
+ void addMUCBookmark(const MUCBookmark& bookmark);
+ void removeMUCBookmark(const MUCBookmark& bookmark);
+ void addWhiteboardSession(const ChatListWindow::Chat& chat);
+ void removeWhiteboardSession(const JID& jid);
+ void setBookmarksEnabled(bool enabled);
+ void setRecents(const std::list<ChatListWindow::Chat>& recents);
+ void setUnreadCount(int unread);
+ void clearBookmarks();
+ virtual void setOnline(bool isOnline);
- signals:
- void onCountUpdated(int count);
- private slots:
- void handleItemActivated(const QModelIndex&);
- void handleAddBookmark();
- void handleEditBookmark();
- void handleRemoveBookmark();
- void handleAddBookmarkFromRecents();
- void handleClicked(const QModelIndex& index);
- void handleSettingChanged(const std::string& setting);
- void handleClearRecentsRequested();
+ signals:
+ void onCountUpdated(int count);
+ private slots:
+ void handleItemActivated(const QModelIndex&);
+ void handleAddBookmark();
+ void handleEditBookmark();
+ void handleRemoveBookmark();
+ void handleAddBookmarkFromRecents();
+ void handleClicked(const QModelIndex& index);
+ void handleSettingChanged(const std::string& setting);
+ void handleClearRecentsRequested();
- protected:
- void dragEnterEvent(QDragEnterEvent* event);
- void contextMenuEvent(QContextMenuEvent* event);
+ protected:
+ void dragEnterEvent(QDragEnterEvent* event);
+ void contextMenuEvent(QContextMenuEvent* event);
- private:
- void setupContextMenus();
- bool bookmarksEnabled_;
- UIEventStream* eventStream_;
- ChatListModel* model_;
- ChatListDelegate* delegate_;
- QMenu* mucMenu_;
- QMenu* emptyMenu_;
- const ChatListItem* contextMenuItem_;
- SettingsProvider* settings_;
- QList<QAction*> onlineOnlyActions_;
- bool isOnline_;
- };
+ private:
+ void setupContextMenus();
+ bool bookmarksEnabled_;
+ UIEventStream* eventStream_;
+ ChatListModel* model_;
+ ChatListDelegate* delegate_;
+ QMenu* mucMenu_;
+ QMenu* emptyMenu_;
+ const ChatListItem* contextMenuItem_;
+ SettingsProvider* settings_;
+ QList<QAction*> onlineOnlyActions_;
+ bool isOnline_;
+ };
}
diff --git a/Swift/QtUI/ChatSnippet.cpp b/Swift/QtUI/ChatSnippet.cpp
index d8b64c1..14e4674 100644
--- a/Swift/QtUI/ChatSnippet.cpp
+++ b/Swift/QtUI/ChatSnippet.cpp
@@ -19,79 +19,79 @@ ChatSnippet::~ChatSnippet() {
}
QString ChatSnippet::timeToEscapedString(const QDateTime& time) {
- QDate now(QDate::currentDate());
- QString date = "";
- if (time.date().daysTo(now) > 0) {
- date = "ddd ";
- }
- if (time.date().month() != now.month()) {
- date = date + "MMMM ";
- }
- if (time.date().daysTo(now) > 6) {
- date = date + "d ";
- }
- if (time.date().year() != now.year()) {
- date = date + "yy ";
- }
- date += "h:mm";
- return escape(time.toString(date));
+ QDate now(QDate::currentDate());
+ QString date = "";
+ if (time.date().daysTo(now) > 0) {
+ date = "ddd ";
+ }
+ if (time.date().month() != now.month()) {
+ date = date + "MMMM ";
+ }
+ if (time.date().daysTo(now) > 6) {
+ date = date + "d ";
+ }
+ if (time.date().year() != now.year()) {
+ date = date + "yy ";
+ }
+ date += "h:mm";
+ return escape(time.toString(date));
}
QString ChatSnippet::wrapResizable(const QString& text) {
- return "<span class='swift_resizable'>" + text + "</span>";
+ return "<span class='swift_resizable'>" + text + "</span>";
}
QString ChatSnippet::directionToCSS(Direction direction) {
- return direction == RTL ? QString("rtl") : QString("ltr");
+ return direction == RTL ? QString("rtl") : QString("ltr");
}
ChatSnippet::Direction ChatSnippet::getDirection(const ChatWindow::ChatMessage& message) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- std::string text = "";
- foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- text = textPart->text;
- break;
- }
- }
- return getDirection(text);
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ std::string text = "";
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ text = textPart->text;
+ break;
+ }
+ }
+ return getDirection(text);
}
ChatSnippet::Direction ChatSnippet::getDirection(const std::string& message) {
- return getDirection(P2QSTRING(message));
+ return getDirection(P2QSTRING(message));
}
ChatSnippet::Direction ChatSnippet::getDirection(const QString& message) {
- /*
- for (int i = 0; i < message.size(); ++i) {
- switch (message.at(i).direction()) {
- case QChar::DirL:
- case QChar::DirLRE:
- case QChar::DirLRO:
- return ChatSnippet::LTR;
- case QChar::DirR:
- case QChar::DirAL:
- case QChar::DirRLE:
- case QChar::DirRLO:
- return ChatSnippet::RTL;
- case QChar::DirEN:
- case QChar::DirES:
- case QChar::DirET:
- case QChar::DirAN:
- case QChar::DirCS:
- case QChar::DirB:
- case QChar::DirWS:
- case QChar::DirON:
- case QChar::DirS:
- case QChar::DirPDF:
- case QChar::DirNSM:
- case QChar::DirBN:
- break;
- }
- }
- return ChatSnippet::LTR;
- */
- return message.isRightToLeft() ? ChatSnippet::RTL : ChatSnippet::LTR;
+ /*
+ for (int i = 0; i < message.size(); ++i) {
+ switch (message.at(i).direction()) {
+ case QChar::DirL:
+ case QChar::DirLRE:
+ case QChar::DirLRO:
+ return ChatSnippet::LTR;
+ case QChar::DirR:
+ case QChar::DirAL:
+ case QChar::DirRLE:
+ case QChar::DirRLO:
+ return ChatSnippet::RTL;
+ case QChar::DirEN:
+ case QChar::DirES:
+ case QChar::DirET:
+ case QChar::DirAN:
+ case QChar::DirCS:
+ case QChar::DirB:
+ case QChar::DirWS:
+ case QChar::DirON:
+ case QChar::DirS:
+ case QChar::DirPDF:
+ case QChar::DirNSM:
+ case QChar::DirBN:
+ break;
+ }
+ }
+ return ChatSnippet::LTR;
+ */
+ return message.isRightToLeft() ? ChatSnippet::RTL : ChatSnippet::LTR;
}
diff --git a/Swift/QtUI/ChatSnippet.h b/Swift/QtUI/ChatSnippet.h
index 7c99928..bf2d6d2 100644
--- a/Swift/QtUI/ChatSnippet.h
+++ b/Swift/QtUI/ChatSnippet.h
@@ -18,55 +18,55 @@
#include <Swift/QtUI/QtChatTheme.h>
namespace Swift {
- class ChatSnippet {
- public:
- enum Direction {
- RTL,
- LTR
- };
-
- ChatSnippet(bool appendToPrevious);
- virtual ~ChatSnippet();
-
- virtual const QString& getContent() const = 0;
- virtual QString getContinuationElementID() const { return ""; }
-
- boost::shared_ptr<ChatSnippet> getContinuationFallbackSnippet() const {return continuationFallback_;}
-
- bool getAppendToPrevious() const {
- return appendToPrevious_;
- }
-
- static QString escape(const QString& original) {
- QString result(original);
- result.replace("%message%", "&#37;message&#37;");
- result.replace("%sender%", "&#37;sender&#37;");
- result.replace("%wrapped_sender%", "&#37;wrapped_sender&#37;");
- result.replace("%time%", "%&#37;time&#37;");
- result.replace("%shortTime%", "%&#37;shortTime&#37;");
- result.replace("%userIconPath%", "&#37;userIconPath&#37;");
- result.replace("%id%", "&#37;id&#37;");
- result.replace("\t", " ");
- result.replace(" ", "&nbsp;&nbsp;");
- return result;
- }
-
- static QString timeToEscapedString(const QDateTime& time);
-
- static Direction getDirection(const std::string& message);
- static Direction getDirection(const ChatWindow::ChatMessage& message);
- static Direction getDirection(const QString& message);
-
- protected:
- static QString directionToCSS(Direction direction);
-
- QString wrapResizable(const QString& text);
- void setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet> continuationFallback) {
- continuationFallback_ = continuationFallback;
- }
- private:
- bool appendToPrevious_;
- boost::shared_ptr<ChatSnippet> continuationFallback_;
- };
+ class ChatSnippet {
+ public:
+ enum Direction {
+ RTL,
+ LTR
+ };
+
+ ChatSnippet(bool appendToPrevious);
+ virtual ~ChatSnippet();
+
+ virtual const QString& getContent() const = 0;
+ virtual QString getContinuationElementID() const { return ""; }
+
+ boost::shared_ptr<ChatSnippet> getContinuationFallbackSnippet() const {return continuationFallback_;}
+
+ bool getAppendToPrevious() const {
+ return appendToPrevious_;
+ }
+
+ static QString escape(const QString& original) {
+ QString result(original);
+ result.replace("%message%", "&#37;message&#37;");
+ result.replace("%sender%", "&#37;sender&#37;");
+ result.replace("%wrapped_sender%", "&#37;wrapped_sender&#37;");
+ result.replace("%time%", "%&#37;time&#37;");
+ result.replace("%shortTime%", "%&#37;shortTime&#37;");
+ result.replace("%userIconPath%", "&#37;userIconPath&#37;");
+ result.replace("%id%", "&#37;id&#37;");
+ result.replace("\t", " ");
+ result.replace(" ", "&nbsp;&nbsp;");
+ return result;
+ }
+
+ static QString timeToEscapedString(const QDateTime& time);
+
+ static Direction getDirection(const std::string& message);
+ static Direction getDirection(const ChatWindow::ChatMessage& message);
+ static Direction getDirection(const QString& message);
+
+ protected:
+ static QString directionToCSS(Direction direction);
+
+ QString wrapResizable(const QString& text);
+ void setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet> continuationFallback) {
+ continuationFallback_ = continuationFallback;
+ }
+ private:
+ bool appendToPrevious_;
+ boost::shared_ptr<ChatSnippet> continuationFallback_;
+ };
}
diff --git a/Swift/QtUI/ChatView/main.cpp b/Swift/QtUI/ChatView/main.cpp
index 4bde1ef..aa3255e 100644
--- a/Swift/QtUI/ChatView/main.cpp
+++ b/Swift/QtUI/ChatView/main.cpp
@@ -27,154 +27,154 @@ using namespace Swift;
/*
class MyNetworkReply : public QNetworkReply {
- public:
- MyNetworkReply() {
- }
-
- qint64 readData(char*, qint64) {
- return 0;
- }
-
- virtual void abort() {
- }
+ public:
+ MyNetworkReply() {
+ }
+
+ qint64 readData(char*, qint64) {
+ return 0;
+ }
+
+ virtual void abort() {
+ }
};
class MyNetworkAccessManager : public QNetworkAccessManager {
- public:
- MyNetworkAccessManager() {
- }
-
- QNetworkReply * createRequest (Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) {
- assert(op == QNetworkAccessManager::GetOperation);
- qDebug() << "Requesting: " << request.url();
- return QNetworkAccessManager::createRequest(op, request, outgoingData);
- //return new MyNetworkReply();
- }
+ public:
+ MyNetworkAccessManager() {
+ }
+
+ QNetworkReply * createRequest (Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) {
+ assert(op == QNetworkAccessManager::GetOperation);
+ qDebug() << "Requesting: " << request.url();
+ return QNetworkAccessManager::createRequest(op, request, outgoingData);
+ //return new MyNetworkReply();
+ }
};
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- webView_ = new QWebView(this);
-
- QFile file(":/themes/Stockholm/Contents/Resources/Incoming/Content.html");
- file.open(QIODevice::ReadOnly);
- QString content = QString::fromUtf8(file.readAll());
-
- webPage_ = new QWebPage(this);
- webPage_->setNetworkAccessManager(new MyNetworkAccessManager());
- webView_->setPage(webPage_);
- QString pagehtml =
- "<head>"
- //"<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
- "<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
- "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"/>"
- "<link rel=\"stylesheet\" type=\"text/css\" href=\"Variants/Alt Blue - Blue.css\"/>"
- "</head><body>" + content + "</body>";
- qDebug() << pagehtml;
- webPage_->mainFrame()->setHtml(pagehtml);
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ webView_ = new QWebView(this);
+
+ QFile file(":/themes/Stockholm/Contents/Resources/Incoming/Content.html");
+ file.open(QIODevice::ReadOnly);
+ QString content = QString::fromUtf8(file.readAll());
+
+ webPage_ = new QWebPage(this);
+ webPage_->setNetworkAccessManager(new MyNetworkAccessManager());
+ webView_->setPage(webPage_);
+ QString pagehtml =
+ "<head>"
+ //"<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
+ "<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"/>"
+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"Variants/Alt Blue - Blue.css\"/>"
+ "</head><body>" + content + "</body>";
+ qDebug() << pagehtml;
+ webPage_->mainFrame()->setHtml(pagehtml);
*/
/*
class ChatView : public QWidget {
- public:
- ChatView(QWidget* parent) : QWidget(parent) {
- setFocusPolicy(Qt::NoFocus);
-
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
-
- webView_ = new QWebView(this);
- webView_->setFocusPolicy(Qt::NoFocus);
- mainLayout->addWidget(webView_);
-
- webPage_ = new QWebPage(this);
- webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
- webView_->setPage(webPage_);
- connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
-
- QString pageHTML = "<head></head><body><div id=\"chat\"></div></body>";
- webPage_->mainFrame()->setHtml(pageHTML);
- }
-
- void appendHTML(const QString& html) {
- webPage_->mainFrame()->evaluateJavaScript(
- "newNode = document.createElement(\"div\");"
- "newNode.innerHTML = \"" + html + "\";"
- "chatElement = document.getElementById(\"chat\");"
- "chatElement.appendChild(newNode);");
- webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
- }
-
- private:
- QWebView* webView_;
- QWebPage* webPage_;
+ public:
+ ChatView(QWidget* parent) : QWidget(parent) {
+ setFocusPolicy(Qt::NoFocus);
+
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
+
+ webView_ = new QWebView(this);
+ webView_->setFocusPolicy(Qt::NoFocus);
+ mainLayout->addWidget(webView_);
+
+ webPage_ = new QWebPage(this);
+ webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
+ webView_->setPage(webPage_);
+ connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
+
+ QString pageHTML = "<head></head><body><div id=\"chat\"></div></body>";
+ webPage_->mainFrame()->setHtml(pageHTML);
+ }
+
+ void appendHTML(const QString& html) {
+ webPage_->mainFrame()->evaluateJavaScript(
+ "newNode = document.createElement(\"div\");"
+ "newNode.innerHTML = \"" + html + "\";"
+ "chatElement = document.getElementById(\"chat\");"
+ "chatElement.appendChild(newNode);");
+ webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
+ }
+
+ private:
+ QWebView* webView_;
+ QWebPage* webPage_;
};
*/
class MyWidget : public QWidget {
- Q_OBJECT
-
- public:
- MyWidget() : previousWasIncoming_(false), previousWasOutgoing_(false), previousWasSystem_(false) {
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- chatView_ = new QtChatView(this);
- mainLayout->addWidget(chatView_);
- input1_ = new QLineEdit(this);
- connect(input1_, SIGNAL(returnPressed()), SLOT(addIncoming()));
- mainLayout->addWidget(input1_);
- input2_ = new QLineEdit(this);
- connect(input2_, SIGNAL(returnPressed()), SLOT(addOutgoing()));
- mainLayout->addWidget(input2_);
- input3_ = new QLineEdit(this);
- connect(input3_, SIGNAL(returnPressed()), SLOT(addSystem()));
- mainLayout->addWidget(input3_);
-
- resize(300,200);
- }
-
- public slots:
- void addIncoming() {
- chatView_->addMessage(MessageSnippet(input1_->text(), "Me", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", true, previousWasIncoming_));
- previousWasIncoming_ = true;
- previousWasOutgoing_ = false;
- previousWasSystem_ = false;
- input1_->clear();
- }
-
- void addOutgoing() {
- chatView_->addMessage(MessageSnippet(input2_->text(), "You", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", false, previousWasOutgoing_));
- previousWasIncoming_ = false;
- previousWasOutgoing_ = true;
- previousWasSystem_ = false;
- input2_->clear();
- }
-
- void addSystem() {
- chatView_->addMessage(SystemMessageSnippet(input3_->text(), QDateTime::currentDateTime(), previousWasSystem_));
- previousWasIncoming_ = false;
- previousWasOutgoing_ = false;
- previousWasSystem_ = true;
- input3_->clear();
- }
-
- private:
- bool previousWasIncoming_;
- bool previousWasOutgoing_;
- bool previousWasSystem_;
- QtChatView* chatView_;
- QLineEdit* input1_;
- QLineEdit* input2_;
- QLineEdit* input3_;
+ Q_OBJECT
+
+ public:
+ MyWidget() : previousWasIncoming_(false), previousWasOutgoing_(false), previousWasSystem_(false) {
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ chatView_ = new QtChatView(this);
+ mainLayout->addWidget(chatView_);
+ input1_ = new QLineEdit(this);
+ connect(input1_, SIGNAL(returnPressed()), SLOT(addIncoming()));
+ mainLayout->addWidget(input1_);
+ input2_ = new QLineEdit(this);
+ connect(input2_, SIGNAL(returnPressed()), SLOT(addOutgoing()));
+ mainLayout->addWidget(input2_);
+ input3_ = new QLineEdit(this);
+ connect(input3_, SIGNAL(returnPressed()), SLOT(addSystem()));
+ mainLayout->addWidget(input3_);
+
+ resize(300,200);
+ }
+
+ public slots:
+ void addIncoming() {
+ chatView_->addMessage(MessageSnippet(input1_->text(), "Me", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", true, previousWasIncoming_));
+ previousWasIncoming_ = true;
+ previousWasOutgoing_ = false;
+ previousWasSystem_ = false;
+ input1_->clear();
+ }
+
+ void addOutgoing() {
+ chatView_->addMessage(MessageSnippet(input2_->text(), "You", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", false, previousWasOutgoing_));
+ previousWasIncoming_ = false;
+ previousWasOutgoing_ = true;
+ previousWasSystem_ = false;
+ input2_->clear();
+ }
+
+ void addSystem() {
+ chatView_->addMessage(SystemMessageSnippet(input3_->text(), QDateTime::currentDateTime(), previousWasSystem_));
+ previousWasIncoming_ = false;
+ previousWasOutgoing_ = false;
+ previousWasSystem_ = true;
+ input3_->clear();
+ }
+
+ private:
+ bool previousWasIncoming_;
+ bool previousWasOutgoing_;
+ bool previousWasSystem_;
+ QtChatView* chatView_;
+ QLineEdit* input1_;
+ QLineEdit* input2_;
+ QLineEdit* input3_;
};
-
+
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
- MyWidget w;
- w.show();
- return app.exec();
+ QApplication app(argc, argv);
+ MyWidget w;
+ w.show();
+ return app.exec();
}
#include "main.moc"
diff --git a/Swift/QtUI/CocoaApplicationActivateHelper.h b/Swift/QtUI/CocoaApplicationActivateHelper.h
index 2b166e2..c7aa5b3 100644
--- a/Swift/QtUI/CocoaApplicationActivateHelper.h
+++ b/Swift/QtUI/CocoaApplicationActivateHelper.h
@@ -9,20 +9,20 @@
#include <QObject>
namespace Swift {
- /**
- * This class is here as a workaround for a bug in Qt.
- * See Case #501.
- */
- class CocoaApplicationActivateHelper : public QObject {
- public:
- CocoaApplicationActivateHelper();
- virtual ~CocoaApplicationActivateHelper();
+ /**
+ * This class is here as a workaround for a bug in Qt.
+ * See Case #501.
+ */
+ class CocoaApplicationActivateHelper : public QObject {
+ public:
+ CocoaApplicationActivateHelper();
+ virtual ~CocoaApplicationActivateHelper();
- private:
- bool eventFilter(QObject* o, QEvent* e);
+ private:
+ bool eventFilter(QObject* o, QEvent* e);
- private:
- struct Private;
- Private* p;
- };
+ private:
+ struct Private;
+ Private* p;
+ };
}
diff --git a/Swift/QtUI/CocoaApplicationActivateHelper.mm b/Swift/QtUI/CocoaApplicationActivateHelper.mm
index f9c455c..4d4409d 100644
--- a/Swift/QtUI/CocoaApplicationActivateHelper.mm
+++ b/Swift/QtUI/CocoaApplicationActivateHelper.mm
@@ -19,37 +19,37 @@
@implementation CocoaApplicationActivateHelperDelegate
- (void) handleActivate: (NSAppleEventDescriptor*) event withReply: (NSAppleEventDescriptor*) reply {
- (void) event; (void) reply;
- QApplication::postEvent(qApp, new QEvent(QEvent::ApplicationActivate));
+ (void) event; (void) reply;
+ QApplication::postEvent(qApp, new QEvent(QEvent::ApplicationActivate));
}
@end
namespace Swift {
struct CocoaApplicationActivateHelper::Private {
- CocoaApplicationActivateHelperDelegate* delegate;
- bool initialized;
+ CocoaApplicationActivateHelperDelegate* delegate;
+ bool initialized;
};
CocoaApplicationActivateHelper::CocoaApplicationActivateHelper() {
- p = new Private();
- p->delegate = [[CocoaApplicationActivateHelperDelegate alloc] init];
- p->initialized = false;
- qApp->installEventFilter(this);
+ p = new Private();
+ p->delegate = [[CocoaApplicationActivateHelperDelegate alloc] init];
+ p->initialized = false;
+ qApp->installEventFilter(this);
}
CocoaApplicationActivateHelper::~CocoaApplicationActivateHelper() {
- [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEReopenApplication];
- [p->delegate release];
- delete p;
+ [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEReopenApplication];
+ [p->delegate release];
+ delete p;
}
bool CocoaApplicationActivateHelper::eventFilter(QObject* object, QEvent* event) {
- if (object == qApp && event->type() == QEvent::ApplicationActivate && !p->initialized) {
- [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->delegate andSelector:@selector(handleActivate:withReply:) forEventClass:kCoreEventClass andEventID:kAEReopenApplication];
- p->initialized = true;
- }
- return QObject::eventFilter(object, event);
+ if (object == qApp && event->type() == QEvent::ApplicationActivate && !p->initialized) {
+ [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->delegate andSelector:@selector(handleActivate:withReply:) forEventClass:kCoreEventClass andEventID:kAEReopenApplication];
+ p->initialized = true;
+ }
+ return QObject::eventFilter(object, event);
}
diff --git a/Swift/QtUI/CocoaUIHelpers.h b/Swift/QtUI/CocoaUIHelpers.h
index f5ec457..58cd539 100644
--- a/Swift/QtUI/CocoaUIHelpers.h
+++ b/Swift/QtUI/CocoaUIHelpers.h
@@ -20,7 +20,7 @@ namespace Swift {
class CocoaUIHelpers {
public:
- static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
+ static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
};
}
diff --git a/Swift/QtUI/CocoaUIHelpers.mm b/Swift/QtUI/CocoaUIHelpers.mm
index 3cb62f3..16fe2ce 100644
--- a/Swift/QtUI/CocoaUIHelpers.mm
+++ b/Swift/QtUI/CocoaUIHelpers.mm
@@ -21,23 +21,23 @@
namespace Swift {
void CocoaUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
- NSWindow* parentWindow = [((NSView*)parent->winId()) window];
- NSMutableArray* certificates = [[NSMutableArray alloc] init];
- foreach(Certificate::ref cert, chain) {
- // convert chain to SecCertificateRef
- ByteArray certAsDER = cert->toDER();
- boost::shared_ptr<boost::remove_pointer<CFDataRef>::type> certData(CFDataCreate(NULL, certAsDER.data(), certAsDER.size()), CFRelease);
- boost::shared_ptr<OpaqueSecCertificateRef> macCert(SecCertificateCreateWithData(NULL, certData.get()), CFRelease);
-
- // add to NSMutable array
- [certificates addObject: (id)macCert.get()];
- }
-
-
- SFCertificatePanel* panel = [[SFCertificatePanel alloc] init];
- //[panel setPolicies:(id)policies.get()];
- [panel beginSheetForWindow:parentWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL certificates:certificates showGroup:YES];
- [certificates release];
+ NSWindow* parentWindow = [((NSView*)parent->winId()) window];
+ NSMutableArray* certificates = [[NSMutableArray alloc] init];
+ foreach(Certificate::ref cert, chain) {
+ // convert chain to SecCertificateRef
+ ByteArray certAsDER = cert->toDER();
+ boost::shared_ptr<boost::remove_pointer<CFDataRef>::type> certData(CFDataCreate(NULL, certAsDER.data(), certAsDER.size()), CFRelease);
+ boost::shared_ptr<OpaqueSecCertificateRef> macCert(SecCertificateCreateWithData(NULL, certData.get()), CFRelease);
+
+ // add to NSMutable array
+ [certificates addObject: (id)macCert.get()];
+ }
+
+
+ SFCertificatePanel* panel = [[SFCertificatePanel alloc] init];
+ //[panel setPolicies:(id)policies.get()];
+ [panel beginSheetForWindow:parentWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL certificates:certificates showGroup:YES];
+ [certificates release];
}
}
diff --git a/Swift/QtUI/EventViewer/EventDelegate.cpp b/Swift/QtUI/EventViewer/EventDelegate.cpp
index cd657b8..eff9a7b 100644
--- a/Swift/QtUI/EventViewer/EventDelegate.cpp
+++ b/Swift/QtUI/EventViewer/EventDelegate.cpp
@@ -17,69 +17,69 @@
namespace Swift {
EventDelegate::EventDelegate() : QStyledItemDelegate(),
- messageDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
- subscriptionDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
- errorDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
- mucInviteDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
- incomingFileTransferDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false) {
+ messageDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
+ subscriptionDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
+ errorDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
+ mucInviteDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
+ incomingFileTransferDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false) {
}
QSize EventDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
- if (!item) {
- return QStyledItemDelegate::sizeHint(option, index);
- }
- switch (getEventType(item->getEvent())) {
- case MessageEventType: return messageDelegate_.sizeHint(option, item);
- case SubscriptionEventType: return subscriptionDelegate_.sizeHint(option, item);
- case ErrorEventType: return errorDelegate_.sizeHint(option, item);
- case MUCInviteEventType: return mucInviteDelegate_.sizeHint(option, item);
- case IncomingFileTransferEventType: return incomingFileTransferDelegate_.sizeHint(option, item);
- }
- assert(false);
- return QSize();
+ QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
+ if (!item) {
+ return QStyledItemDelegate::sizeHint(option, index);
+ }
+ switch (getEventType(item->getEvent())) {
+ case MessageEventType: return messageDelegate_.sizeHint(option, item);
+ case SubscriptionEventType: return subscriptionDelegate_.sizeHint(option, item);
+ case ErrorEventType: return errorDelegate_.sizeHint(option, item);
+ case MUCInviteEventType: return mucInviteDelegate_.sizeHint(option, item);
+ case IncomingFileTransferEventType: return incomingFileTransferDelegate_.sizeHint(option, item);
+ }
+ assert(false);
+ return QSize();
}
void EventDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
- if (!item) {
- QStyledItemDelegate::paint(painter, option, index);
- return;
- }
- switch (getEventType(item->getEvent())) {
- case MessageEventType: messageDelegate_.paint(painter, option, item);break;
- case SubscriptionEventType: subscriptionDelegate_.paint(painter, option, item);break;
- case ErrorEventType: errorDelegate_.paint(painter, option, item);break;
- case MUCInviteEventType: mucInviteDelegate_.paint(painter, option, item);break;
- case IncomingFileTransferEventType: incomingFileTransferDelegate_.paint(painter, option, item);break;
- }
+ QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
+ if (!item) {
+ QStyledItemDelegate::paint(painter, option, index);
+ return;
+ }
+ switch (getEventType(item->getEvent())) {
+ case MessageEventType: messageDelegate_.paint(painter, option, item);break;
+ case SubscriptionEventType: subscriptionDelegate_.paint(painter, option, item);break;
+ case ErrorEventType: errorDelegate_.paint(painter, option, item);break;
+ case MUCInviteEventType: mucInviteDelegate_.paint(painter, option, item);break;
+ case IncomingFileTransferEventType: incomingFileTransferDelegate_.paint(painter, option, item);break;
+ }
}
EventType EventDelegate::getEventType(boost::shared_ptr<StanzaEvent> event) const {
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event);
- if (messageEvent) {
- return MessageEventType;
- }
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event);
- if (subscriptionEvent) {
- return SubscriptionEventType;
- }
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event);
- if (errorEvent) {
- return ErrorEventType;
- }
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event);
- if (mucInviteEvent) {
- return MUCInviteEventType;
- }
- boost::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event);
- if (incomingFileTransferEvent) {
- return IncomingFileTransferEventType;
- }
- //I don't know what this is.
- assert(false);
- return MessageEventType;
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event);
+ if (messageEvent) {
+ return MessageEventType;
+ }
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event);
+ if (subscriptionEvent) {
+ return SubscriptionEventType;
+ }
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event);
+ if (errorEvent) {
+ return ErrorEventType;
+ }
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event);
+ if (mucInviteEvent) {
+ return MUCInviteEventType;
+ }
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event);
+ if (incomingFileTransferEvent) {
+ return IncomingFileTransferEventType;
+ }
+ //I don't know what this is.
+ assert(false);
+ return MessageEventType;
}
}
diff --git a/Swift/QtUI/EventViewer/EventDelegate.h b/Swift/QtUI/EventViewer/EventDelegate.h
index 6ab96e4..0804589 100644
--- a/Swift/QtUI/EventViewer/EventDelegate.h
+++ b/Swift/QtUI/EventViewer/EventDelegate.h
@@ -12,21 +12,21 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- enum EventType {MessageEventType, SubscriptionEventType, ErrorEventType, MUCInviteEventType, IncomingFileTransferEventType};
- class EventDelegate : public QStyledItemDelegate {
- Q_OBJECT
- public:
- EventDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- private:
- EventType getEventType(boost::shared_ptr<StanzaEvent> event) const;
- DelegateCommons common_;
- TwoLineDelegate messageDelegate_;
- TwoLineDelegate subscriptionDelegate_;
- TwoLineDelegate errorDelegate_;
- TwoLineDelegate mucInviteDelegate_;
- TwoLineDelegate incomingFileTransferDelegate_;
- };
+ enum EventType {MessageEventType, SubscriptionEventType, ErrorEventType, MUCInviteEventType, IncomingFileTransferEventType};
+ class EventDelegate : public QStyledItemDelegate {
+ Q_OBJECT
+ public:
+ EventDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ private:
+ EventType getEventType(boost::shared_ptr<StanzaEvent> event) const;
+ DelegateCommons common_;
+ TwoLineDelegate messageDelegate_;
+ TwoLineDelegate subscriptionDelegate_;
+ TwoLineDelegate errorDelegate_;
+ TwoLineDelegate mucInviteDelegate_;
+ TwoLineDelegate incomingFileTransferDelegate_;
+ };
}
diff --git a/Swift/QtUI/EventViewer/EventModel.cpp b/Swift/QtUI/EventViewer/EventModel.cpp
index 889bcac..1568ec7 100644
--- a/Swift/QtUI/EventViewer/EventModel.cpp
+++ b/Swift/QtUI/EventViewer/EventModel.cpp
@@ -11,100 +11,100 @@
namespace Swift {
namespace {
- const int inactiveEventsLimit = 50;
+ const int inactiveEventsLimit = 50;
}
EventModel::EventModel() {
-
+
}
EventModel::~EventModel() {
- foreach (QtEvent* event, activeEvents_) {
- delete event;
- }
- foreach (QtEvent* event, inactiveEvents_) {
- delete event;
- }
+ foreach (QtEvent* event, activeEvents_) {
+ delete event;
+ }
+ foreach (QtEvent* event, inactiveEvents_) {
+ delete event;
+ }
}
QtEvent* EventModel::getItem(int row) const {
- QtEvent* event = NULL;
- if (row < activeEvents_.size()) {
- event = activeEvents_[row];
- }
- else {
- int inactiveRow = row - activeEvents_.size();
- if (inactiveRow < inactiveEvents_.size()) {
- event = inactiveEvents_[inactiveRow];
- }
- else {
- SWIFT_LOG(error) << "Misbehaving EventModel requests row index outside of range";
- }
- }
- return event;
+ QtEvent* event = NULL;
+ if (row < activeEvents_.size()) {
+ event = activeEvents_[row];
+ }
+ else {
+ int inactiveRow = row - activeEvents_.size();
+ if (inactiveRow < inactiveEvents_.size()) {
+ event = inactiveEvents_[inactiveRow];
+ }
+ else {
+ SWIFT_LOG(error) << "Misbehaving EventModel requests row index outside of range";
+ }
+ }
+ return event;
}
int EventModel::getNewEventCount() {
- return activeEvents_.size();
+ return activeEvents_.size();
}
QVariant EventModel::data(const QModelIndex& index, int role) const {
- if (!index.isValid()) {
- return QVariant();
- }
- QtEvent* item = getItem(index.row());
- QVariant result = item ? item->data(role) : QVariant();
- return result;
+ if (!index.isValid()) {
+ return QVariant();
+ }
+ QtEvent* item = getItem(index.row());
+ QVariant result = item ? item->data(role) : QVariant();
+ return result;
}
/*
* We only reimplement this to get the pointers inside the indices.
*/
QModelIndex EventModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent) || parent.isValid()) {
- return QModelIndex();
- }
+ if (!hasIndex(row, column, parent) || parent.isValid()) {
+ return QModelIndex();
+ }
- return row < rowCount() ? createIndex(row, column, getItem(row)) : QModelIndex();
+ return row < rowCount() ? createIndex(row, column, getItem(row)) : QModelIndex();
}
int EventModel::rowCount(const QModelIndex& parent) const {
- /* Invalid parent = root, valid parent = child, and we're a list not a tree.*/
- int count = parent.isValid() ? 0 : activeEvents_.size() + inactiveEvents_.size();
- return count;
+ /* Invalid parent = root, valid parent = child, and we're a list not a tree.*/
+ int count = parent.isValid() ? 0 : activeEvents_.size() + inactiveEvents_.size();
+ return count;
}
void EventModel::addEvent(boost::shared_ptr<StanzaEvent> event, bool active) {
- beginResetModel();
- if (active) {
- activeEvents_.push_front(new QtEvent(event, active));
- } else {
- inactiveEvents_.push_front(new QtEvent(event, active));
- if (inactiveEvents_.size() > inactiveEventsLimit) {
- removeEvent(inactiveEvents_[inactiveEventsLimit]->getEvent());
- }
- }
- endResetModel();
+ beginResetModel();
+ if (active) {
+ activeEvents_.push_front(new QtEvent(event, active));
+ } else {
+ inactiveEvents_.push_front(new QtEvent(event, active));
+ if (inactiveEvents_.size() > inactiveEventsLimit) {
+ removeEvent(inactiveEvents_[inactiveEventsLimit]->getEvent());
+ }
+ }
+ endResetModel();
}
void EventModel::removeEvent(boost::shared_ptr<StanzaEvent> event) {
- beginResetModel();
- for (int i = inactiveEvents_.size() - 1; i >= 0; i--) {
- if (event == inactiveEvents_[i]->getEvent()) {
- inactiveEvents_.removeAt(i);
- endResetModel();
- return;
- }
- }
-
- for (int i = 0; i < activeEvents_.size(); i++) {
- if (event == activeEvents_[i]->getEvent()) {
- activeEvents_.removeAt(i);
- endResetModel();
- return;
- }
- }
- endResetModel();
+ beginResetModel();
+ for (int i = inactiveEvents_.size() - 1; i >= 0; i--) {
+ if (event == inactiveEvents_[i]->getEvent()) {
+ inactiveEvents_.removeAt(i);
+ endResetModel();
+ return;
+ }
+ }
+
+ for (int i = 0; i < activeEvents_.size(); i++) {
+ if (event == activeEvents_[i]->getEvent()) {
+ activeEvents_.removeAt(i);
+ endResetModel();
+ return;
+ }
+ }
+ endResetModel();
}
}
diff --git a/Swift/QtUI/EventViewer/EventModel.h b/Swift/QtUI/EventViewer/EventModel.h
index 844e50f..5cd5028 100644
--- a/Swift/QtUI/EventViewer/EventModel.h
+++ b/Swift/QtUI/EventViewer/EventModel.h
@@ -17,21 +17,21 @@
namespace Swift {
class EventModel : public QAbstractListModel {
- Q_OBJECT
- public:
- EventModel();
- virtual ~EventModel();
- void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
- void removeEvent(boost::shared_ptr<StanzaEvent> event);
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- QtEvent* getItem(int row) const;
- int getNewEventCount();
- protected:
- QModelIndex index(int row, int column = 0, const QModelIndex & parent = QModelIndex()) const;
- private:
- QList<QtEvent*> activeEvents_;
- QList<QtEvent*> inactiveEvents_;
+ Q_OBJECT
+ public:
+ EventModel();
+ virtual ~EventModel();
+ void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
+ void removeEvent(boost::shared_ptr<StanzaEvent> event);
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ QtEvent* getItem(int row) const;
+ int getNewEventCount();
+ protected:
+ QModelIndex index(int row, int column = 0, const QModelIndex & parent = QModelIndex()) const;
+ private:
+ QList<QtEvent*> activeEvents_;
+ QList<QtEvent*> inactiveEvents_;
};
}
diff --git a/Swift/QtUI/EventViewer/EventView.cpp b/Swift/QtUI/EventViewer/EventView.cpp
index fe299b8..4d56548 100644
--- a/Swift/QtUI/EventViewer/EventView.cpp
+++ b/Swift/QtUI/EventViewer/EventView.cpp
@@ -8,7 +8,7 @@
namespace Swift {
EventView::EventView(QWidget* parent) : QListView(parent) {
-
+
}
}
diff --git a/Swift/QtUI/EventViewer/EventView.h b/Swift/QtUI/EventViewer/EventView.h
index 36c67f3..83898bd 100644
--- a/Swift/QtUI/EventViewer/EventView.h
+++ b/Swift/QtUI/EventViewer/EventView.h
@@ -9,9 +9,9 @@
#include <QListView>
namespace Swift {
- class EventView : public QListView {
- Q_OBJECT
- public:
- EventView(QWidget* parent);
- };
+ class EventView : public QListView {
+ Q_OBJECT
+ public:
+ EventView(QWidget* parent);
+ };
}
diff --git a/Swift/QtUI/EventViewer/QtEvent.cpp b/Swift/QtUI/EventViewer/QtEvent.cpp
index cc52ba6..c287c66 100644
--- a/Swift/QtUI/EventViewer/QtEvent.cpp
+++ b/Swift/QtUI/EventViewer/QtEvent.cpp
@@ -20,79 +20,79 @@
namespace Swift {
QtEvent::QtEvent(boost::shared_ptr<StanzaEvent> event, bool active) : event_(event) {
- active_ = active;
+ active_ = active;
}
QVariant QtEvent::data(int role) {
- switch (role) {
- case Qt::ToolTipRole: return QVariant(text()).toString() + "\n" + B2QDATE(event_->getTime()).toString();
- case Qt::DisplayRole: return QVariant(text());
- case Qt::TextColorRole: return QColor(active_ ? Qt::black : Qt::darkGray);
- case Qt::BackgroundColorRole: return QColor(active_ ? Qt::white : Qt::lightGray);
- case SenderRole: return QVariant(sender());
- /*case StatusTextRole: return statusText_;
- case AvatarRole: return avatar_;
- case PresenceIconRole: return getPresenceIcon();*/
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::ToolTipRole: return QVariant(text()).toString() + "\n" + B2QDATE(event_->getTime()).toString();
+ case Qt::DisplayRole: return QVariant(text());
+ case Qt::TextColorRole: return QColor(active_ ? Qt::black : Qt::darkGray);
+ case Qt::BackgroundColorRole: return QColor(active_ ? Qt::white : Qt::lightGray);
+ case SenderRole: return QVariant(sender());
+ /*case StatusTextRole: return statusText_;
+ case AvatarRole: return avatar_;
+ case PresenceIconRole: return getPresenceIcon();*/
+ default: return QVariant();
+ }
}
QString QtEvent::sender() {
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
- if (messageEvent) {
- return P2QSTRING(messageEvent->getStanza()->getFrom().toString());
- }
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
- if (subscriptionRequestEvent) {
- return P2QSTRING(subscriptionRequestEvent->getJID().toBare().toString());
- }
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
- if (errorEvent) {
- return P2QSTRING(errorEvent->getJID().toBare().toString());
- }
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
- if (mucInviteEvent) {
- return P2QSTRING(mucInviteEvent->getInviter().toString());
- }
- boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
- if (incomingFTEvent) {
- return P2QSTRING(incomingFTEvent->getSender().toString());
- }
- return "";
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
+ if (messageEvent) {
+ return P2QSTRING(messageEvent->getStanza()->getFrom().toString());
+ }
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
+ if (subscriptionRequestEvent) {
+ return P2QSTRING(subscriptionRequestEvent->getJID().toBare().toString());
+ }
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
+ if (errorEvent) {
+ return P2QSTRING(errorEvent->getJID().toBare().toString());
+ }
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
+ if (mucInviteEvent) {
+ return P2QSTRING(mucInviteEvent->getInviter().toString());
+ }
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
+ if (incomingFTEvent) {
+ return P2QSTRING(incomingFTEvent->getSender().toString());
+ }
+ return "";
}
QString QtEvent::text() {
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
- if (messageEvent) {
- return P2QSTRING(messageEvent->getStanza()->getBody().get_value_or(""));
- }
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
- if (subscriptionRequestEvent) {
- std::string reason = subscriptionRequestEvent->getReason();
- QString message;
- if (reason.empty()) {
- message = QString(QObject::tr("%1 would like to add you to their contact list.")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str());
- }
- else {
- message = QString(QObject::tr("%1 would like to add you to their contact list, saying '%2'")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()).arg(reason.c_str());
- }
- return message;
- }
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
- if (errorEvent) {
- return P2QSTRING(errorEvent->getText());
- }
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
- if (mucInviteEvent) {
- QString message = QString(QObject::tr("%1 has invited you to enter the %2 room.")).arg(P2QSTRING(mucInviteEvent->getInviter().toBare().toString())).arg(P2QSTRING(mucInviteEvent->getRoomJID().toString()));
- return message;
- }
- boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
- if (incomingFTEvent) {
- QString message = QString(QObject::tr("%1 would like to send a file to you.")).arg(P2QSTRING(incomingFTEvent->getSender().toBare().toString()));
- return message;
- }
- return "";
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
+ if (messageEvent) {
+ return P2QSTRING(messageEvent->getStanza()->getBody().get_value_or(""));
+ }
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
+ if (subscriptionRequestEvent) {
+ std::string reason = subscriptionRequestEvent->getReason();
+ QString message;
+ if (reason.empty()) {
+ message = QString(QObject::tr("%1 would like to add you to their contact list.")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str());
+ }
+ else {
+ message = QString(QObject::tr("%1 would like to add you to their contact list, saying '%2'")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()).arg(reason.c_str());
+ }
+ return message;
+ }
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
+ if (errorEvent) {
+ return P2QSTRING(errorEvent->getText());
+ }
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
+ if (mucInviteEvent) {
+ QString message = QString(QObject::tr("%1 has invited you to enter the %2 room.")).arg(P2QSTRING(mucInviteEvent->getInviter().toBare().toString())).arg(P2QSTRING(mucInviteEvent->getRoomJID().toString()));
+ return message;
+ }
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
+ if (incomingFTEvent) {
+ QString message = QString(QObject::tr("%1 would like to send a file to you.")).arg(P2QSTRING(incomingFTEvent->getSender().toBare().toString()));
+ return message;
+ }
+ return "";
}
}
diff --git a/Swift/QtUI/EventViewer/QtEvent.h b/Swift/QtUI/EventViewer/QtEvent.h
index 3be041c..d369255 100644
--- a/Swift/QtUI/EventViewer/QtEvent.h
+++ b/Swift/QtUI/EventViewer/QtEvent.h
@@ -13,20 +13,20 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class QtEvent {
- public:
- QtEvent(boost::shared_ptr<StanzaEvent> event, bool active);
- QVariant data(int role);
- boost::shared_ptr<StanzaEvent> getEvent() { return event_; }
- enum EventRoles {
- SenderRole = Qt::UserRole
+ class QtEvent {
+ public:
+ QtEvent(boost::shared_ptr<StanzaEvent> event, bool active);
+ QVariant data(int role);
+ boost::shared_ptr<StanzaEvent> getEvent() { return event_; }
+ enum EventRoles {
+ SenderRole = Qt::UserRole
- };
+ };
- private:
- QString text();
- QString sender();
- boost::shared_ptr<StanzaEvent> event_;
- bool active_;
- };
+ private:
+ QString text();
+ QString sender();
+ boost::shared_ptr<StanzaEvent> event_;
+ bool active_;
+ };
}
diff --git a/Swift/QtUI/EventViewer/QtEventWindow.cpp b/Swift/QtUI/EventViewer/QtEventWindow.cpp
index f92cd07..8395a6c 100644
--- a/Swift/QtUI/EventViewer/QtEventWindow.cpp
+++ b/Swift/QtUI/EventViewer/QtEventWindow.cpp
@@ -26,97 +26,97 @@
namespace Swift {
QtEventWindow::QtEventWindow(UIEventStream* eventStream) : EventWindow(false) {
- QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout->setContentsMargins(0,0,0,0);
- layout->setSpacing(0);
-
- view_ = new QTreeView(this);
- layout->addWidget(view_);
- eventStream_ = eventStream;
- model_ = new EventModel();
- view_->setModel(model_);
- delegate_ = new EventDelegate();
- view_->setItemDelegate(delegate_);
- view_->setHeaderHidden(true);
+ QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout->setContentsMargins(0,0,0,0);
+ layout->setSpacing(0);
+
+ view_ = new QTreeView(this);
+ layout->addWidget(view_);
+ eventStream_ = eventStream;
+ model_ = new EventModel();
+ view_->setModel(model_);
+ delegate_ = new EventDelegate();
+ view_->setItemDelegate(delegate_);
+ view_->setHeaderHidden(true);
#ifdef SWIFT_PLATFORM_MACOSX
- view_->setAlternatingRowColors(true);
+ view_->setAlternatingRowColors(true);
#endif
- view_->setAnimated(true);
- view_->setIndentation(0);
- view_->setRootIsDecorated(true);
-
- readButton_ = new QPushButton(tr("Display Notice"), this);
- layout->addWidget(readButton_);
- readButton_->setEnabled(false);
- connect(readButton_, SIGNAL(clicked()), this, SLOT(handleReadClicked()));
- connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleItemClicked(const QModelIndex&)));
- connect(view_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
+ view_->setAnimated(true);
+ view_->setIndentation(0);
+ view_->setRootIsDecorated(true);
+
+ readButton_ = new QPushButton(tr("Display Notice"), this);
+ layout->addWidget(readButton_);
+ readButton_->setEnabled(false);
+ connect(readButton_, SIGNAL(clicked()), this, SLOT(handleReadClicked()));
+ connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleItemClicked(const QModelIndex&)));
+ connect(view_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
}
QtEventWindow::~QtEventWindow() {
- delete model_;
- delete delegate_;
- /* Not view_ because this is the parent */
+ delete model_;
+ delete delegate_;
+ /* Not view_ because this is the parent */
}
void QtEventWindow::handleItemClicked(const QModelIndex&) {
- readButton_->setEnabled(true);
+ readButton_->setEnabled(true);
}
void QtEventWindow::handleReadClicked() {
- QModelIndex index = view_->currentIndex();
- if (!index.isValid()) {
- return;
- }
- handleItemActivated(index);
+ QModelIndex index = view_->currentIndex();
+ if (!index.isValid()) {
+ return;
+ }
+ handleItemActivated(index);
}
void QtEventWindow::handleItemActivated(const QModelIndex& item) {
- QtEvent* event = model_->getItem(item.row());
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event->getEvent());
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event->getEvent());
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event->getEvent());
- boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event->getEvent());
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event->getEvent());
-
- if (messageEvent) {
- if (messageEvent->getStanza()->getType() == Message::Groupchat) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new JoinMUCUIEvent(messageEvent->getStanza()->getFrom().toBare(), messageEvent->getStanza()->getTo().getResource())));
- } else {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(messageEvent->getStanza()->getFrom())));
- }
- } else if (subscriptionEvent) {
- QtSubscriptionRequestWindow* window = QtSubscriptionRequestWindow::getWindow(subscriptionEvent, this);
- window->show();
- } else if (mucInviteEvent) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(mucInviteEvent->getInviter())));
- mucInviteEvent->conclude();
- } else if (incomingFTEvent) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(incomingFTEvent->getSender())));
- incomingFTEvent->conclude();
- } else {
- if (errorEvent) {
- errorEvent->conclude();
- }
- QMessageBox msgBox;
- msgBox.setText(model_->data(item, Qt::DisplayRole).toString());
- msgBox.exec();
- }
+ QtEvent* event = model_->getItem(item.row());
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event->getEvent());
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event->getEvent());
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event->getEvent());
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event->getEvent());
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event->getEvent());
+
+ if (messageEvent) {
+ if (messageEvent->getStanza()->getType() == Message::Groupchat) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new JoinMUCUIEvent(messageEvent->getStanza()->getFrom().toBare(), messageEvent->getStanza()->getTo().getResource())));
+ } else {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(messageEvent->getStanza()->getFrom())));
+ }
+ } else if (subscriptionEvent) {
+ QtSubscriptionRequestWindow* window = QtSubscriptionRequestWindow::getWindow(subscriptionEvent, this);
+ window->show();
+ } else if (mucInviteEvent) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(mucInviteEvent->getInviter())));
+ mucInviteEvent->conclude();
+ } else if (incomingFTEvent) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(incomingFTEvent->getSender())));
+ incomingFTEvent->conclude();
+ } else {
+ if (errorEvent) {
+ errorEvent->conclude();
+ }
+ QMessageBox msgBox;
+ msgBox.setText(model_->data(item, Qt::DisplayRole).toString());
+ msgBox.exec();
+ }
}
void QtEventWindow::addEvent(boost::shared_ptr<StanzaEvent> event, bool active) {
- view_->clearSelection();
- model_->addEvent(event, active);
- emit onNewEventCountUpdated(model_->getNewEventCount());
- readButton_->setEnabled(model_->rowCount() > 0);
+ view_->clearSelection();
+ model_->addEvent(event, active);
+ emit onNewEventCountUpdated(model_->getNewEventCount());
+ readButton_->setEnabled(model_->rowCount() > 0);
}
void QtEventWindow::removeEvent(boost::shared_ptr<StanzaEvent> event) {
- view_->clearSelection();
- model_->removeEvent(event);
- emit onNewEventCountUpdated(model_->getNewEventCount());
- readButton_->setEnabled(model_->rowCount() > 0);
+ view_->clearSelection();
+ model_->removeEvent(event);
+ emit onNewEventCountUpdated(model_->getNewEventCount());
+ readButton_->setEnabled(model_->rowCount() > 0);
}
}
diff --git a/Swift/QtUI/EventViewer/QtEventWindow.h b/Swift/QtUI/EventViewer/QtEventWindow.h
index 1591c15..92f8de0 100644
--- a/Swift/QtUI/EventViewer/QtEventWindow.h
+++ b/Swift/QtUI/EventViewer/QtEventWindow.h
@@ -20,26 +20,26 @@
class QPushButton;
namespace Swift {
- class QtEventWindow : public QWidget, public EventWindow {
- Q_OBJECT
- public:
- QtEventWindow(UIEventStream* eventStream);
- ~QtEventWindow();
- void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
- void removeEvent(boost::shared_ptr<StanzaEvent> event);
- signals:
- void onNewEventCountUpdated(int count);
- private slots:
- void handleItemActivated(const QModelIndex& item);
- void handleItemClicked(const QModelIndex& item);
- void handleReadClicked();
- private:
- EventModel* model_;
- EventDelegate* delegate_;
- UIEventStream* eventStream_;
- QTreeView* view_;
- QPushButton* readButton_;
- };
-
+ class QtEventWindow : public QWidget, public EventWindow {
+ Q_OBJECT
+ public:
+ QtEventWindow(UIEventStream* eventStream);
+ ~QtEventWindow();
+ void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
+ void removeEvent(boost::shared_ptr<StanzaEvent> event);
+ signals:
+ void onNewEventCountUpdated(int count);
+ private slots:
+ void handleItemActivated(const QModelIndex& item);
+ void handleItemClicked(const QModelIndex& item);
+ void handleReadClicked();
+ private:
+ EventModel* model_;
+ EventDelegate* delegate_;
+ UIEventStream* eventStream_;
+ QTreeView* view_;
+ QPushButton* readButton_;
+ };
+
}
diff --git a/Swift/QtUI/EventViewer/TwoLineDelegate.cpp b/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
index 586de55..b90acca 100644
--- a/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
+++ b/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
@@ -12,9 +12,9 @@
namespace Swift {
TwoLineDelegate::TwoLineDelegate(int firstRole, int secondRole, bool wrap) {
- firstRole_ = firstRole;
- secondRole_ = secondRole;
- wrap_ = wrap;
+ firstRole_ = firstRole;
+ secondRole_ = secondRole;
+ wrap_ = wrap;
}
TwoLineDelegate::~TwoLineDelegate() {
@@ -22,41 +22,41 @@ TwoLineDelegate::~TwoLineDelegate() {
}
QSize TwoLineDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, QtEvent* /*event*/ ) const {
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
void TwoLineDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const {
- painter->save();
- QRect fullRegion(option.rect);
- if ( option.state & QStyle::State_Selected ) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- } else {
- QColor nameColor = event->data(Qt::TextColorRole).value<QColor>();
- painter->setPen(QPen(nameColor));
- }
-
- QFontMetrics nameMetrics(common_.nameFont);
- painter->setFont(common_.nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
- int nameHeight = nameMetrics.height() + common_.verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
- DelegateCommons::drawElidedText(painter, nameRegion, event->data(firstRole_).toString());
-
- painter->setFont(common_.detailFont);
- painter->setPen(QPen(QColor(160,160,160)));
-
- QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- DelegateCommons::drawElidedText(painter, detailRegion, event->data(secondRole_).toString());
-
- painter->restore();
+ painter->save();
+ QRect fullRegion(option.rect);
+ if ( option.state & QStyle::State_Selected ) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ } else {
+ QColor nameColor = event->data(Qt::TextColorRole).value<QColor>();
+ painter->setPen(QPen(nameColor));
+ }
+
+ QFontMetrics nameMetrics(common_.nameFont);
+ painter->setFont(common_.nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+ int nameHeight = nameMetrics.height() + common_.verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+ DelegateCommons::drawElidedText(painter, nameRegion, event->data(firstRole_).toString());
+
+ painter->setFont(common_.detailFont);
+ painter->setPen(QPen(QColor(160,160,160)));
+
+ QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ DelegateCommons::drawElidedText(painter, detailRegion, event->data(secondRole_).toString());
+
+ painter->restore();
}
}
diff --git a/Swift/QtUI/EventViewer/TwoLineDelegate.h b/Swift/QtUI/EventViewer/TwoLineDelegate.h
index 9eebb68..089f97a 100644
--- a/Swift/QtUI/EventViewer/TwoLineDelegate.h
+++ b/Swift/QtUI/EventViewer/TwoLineDelegate.h
@@ -12,18 +12,18 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class TwoLineDelegate {
- public:
- TwoLineDelegate(int firstRole, int secondRole, bool wrap);
- ~TwoLineDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, QtEvent* event) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const;
- private:
- DelegateCommons common_;
- int firstRole_;
- int secondRole_;
- bool wrap_;
- };
+ class TwoLineDelegate {
+ public:
+ TwoLineDelegate(int firstRole, int secondRole, bool wrap);
+ ~TwoLineDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, QtEvent* event) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const;
+ private:
+ DelegateCommons common_;
+ int firstRole_;
+ int secondRole_;
+ bool wrap_;
+ };
}
diff --git a/Swift/QtUI/EventViewer/main.cpp b/Swift/QtUI/EventViewer/main.cpp
index ba2ab4b..5eddd90 100644
--- a/Swift/QtUI/EventViewer/main.cpp
+++ b/Swift/QtUI/EventViewer/main.cpp
@@ -17,17 +17,17 @@
int main(int argc, char *argv[])
{
- QApplication app(argc, argv);
- Swift::UIEventStream eventStream;
- Swift::QtEventWindow* viewer = new Swift::QtEventWindow(&eventStream);
- viewer->show();
- boost::shared_ptr<Swift::Message> message1(new Swift::Message());
- message1->setBody("Oooh, shiny");
- boost::shared_ptr<Swift::MessageEvent> event1(new Swift::MessageEvent(message1));
- viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), true);
- for (int i = 0; i < 100; i++) {
- viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), false);
- }
- viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(boost::make_shared<Swift::ErrorEvent>(Swift::JID("me@example.com"), "Something bad did happen to you.")), true);
- return app.exec();
+ QApplication app(argc, argv);
+ Swift::UIEventStream eventStream;
+ Swift::QtEventWindow* viewer = new Swift::QtEventWindow(&eventStream);
+ viewer->show();
+ boost::shared_ptr<Swift::Message> message1(new Swift::Message());
+ message1->setBody("Oooh, shiny");
+ boost::shared_ptr<Swift::MessageEvent> event1(new Swift::MessageEvent(message1));
+ viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), true);
+ for (int i = 0; i < 100; i++) {
+ viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), false);
+ }
+ viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(boost::make_shared<Swift::ErrorEvent>(Swift::JID("me@example.com"), "Something bad did happen to you.")), true);
+ return app.exec();
}
diff --git a/Swift/QtUI/FreeDesktopNotifier.cpp b/Swift/QtUI/FreeDesktopNotifier.cpp
index 54e0ccc..16f6a11 100644
--- a/Swift/QtUI/FreeDesktopNotifier.cpp
+++ b/Swift/QtUI/FreeDesktopNotifier.cpp
@@ -23,37 +23,37 @@ FreeDesktopNotifier::FreeDesktopNotifier(const std::string& name) : applicationN
}
void FreeDesktopNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()>) {
- QDBusConnection bus = QDBusConnection::sessionBus();
- if (!bus.isConnected()) {
- return;
- }
- std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
- if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
- return;
- }
-
- QString body = description.c_str();
- body = body.replace("&", "&amp;");
- body = body.replace("<", "&lt;");
- body = body.replace(">", "&gt;");
-
- int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
-
- QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "", "Notify");
-
- QStringList actions;
- QMap<QString, QVariant> hints;
- hints["x-canonical-append"] = QString("allowed");
- msg << applicationName.c_str();
- msg << quint32(0); // ID of previous notification to replace
- msg << P2QSTRING(pathToString(imageScaler.getScaledImage(picture, 48))); // Icon to display
- msg << subject.c_str(); // Summary / Header of the message to display
- msg << body; // Body of the message to display
- msg << actions; // Actions from which the user may choose
- msg << hints; // Hints to the server displaying the message
- msg << qint32(timeout*1000); // Timeout in milliseconds
-
- bus.asyncCall(msg);
+ QDBusConnection bus = QDBusConnection::sessionBus();
+ if (!bus.isConnected()) {
+ return;
+ }
+ std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
+ if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
+ return;
+ }
+
+ QString body = description.c_str();
+ body = body.replace("&", "&amp;");
+ body = body.replace("<", "&lt;");
+ body = body.replace(">", "&gt;");
+
+ int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
+
+ QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "", "Notify");
+
+ QStringList actions;
+ QMap<QString, QVariant> hints;
+ hints["x-canonical-append"] = QString("allowed");
+ msg << applicationName.c_str();
+ msg << quint32(0); // ID of previous notification to replace
+ msg << P2QSTRING(pathToString(imageScaler.getScaledImage(picture, 48))); // Icon to display
+ msg << subject.c_str(); // Summary / Header of the message to display
+ msg << body; // Body of the message to display
+ msg << actions; // Actions from which the user may choose
+ msg << hints; // Hints to the server displaying the message
+ msg << qint32(timeout*1000); // Timeout in milliseconds
+
+ bus.asyncCall(msg);
}
}
diff --git a/Swift/QtUI/FreeDesktopNotifier.h b/Swift/QtUI/FreeDesktopNotifier.h
index 50601a0..dab7e73 100644
--- a/Swift/QtUI/FreeDesktopNotifier.h
+++ b/Swift/QtUI/FreeDesktopNotifier.h
@@ -11,15 +11,15 @@
#include <Swift/QtUI/QtCachedImageScaler.h>
namespace Swift {
- class FreeDesktopNotifier : public Notifier {
- public:
- FreeDesktopNotifier(const std::string& name);
+ class FreeDesktopNotifier : public Notifier {
+ public:
+ FreeDesktopNotifier(const std::string& name);
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
- virtual void purgeCallbacks() {}
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
+ virtual void purgeCallbacks() {}
- private:
- std::string applicationName;
- QtCachedImageScaler imageScaler;
- };
+ private:
+ std::string applicationName;
+ QtCachedImageScaler imageScaler;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp b/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
index c5f4685..0163e03 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
@@ -25,63 +25,63 @@ MUCSearchDelegate::~MUCSearchDelegate() {
}
// QSize MUCSearchDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
-// // MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
-// // if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
-// // return mucSizeHint(option, index);
-// // } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
-// // return groupDelegate_->sizeHint(option, index);
-// // }
-// return QStyledItemDelegate::sizeHint(option, index);
+// // MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
+// // if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
+// // return mucSizeHint(option, index);
+// // } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
+// // return groupDelegate_->sizeHint(option, index);
+// // }
+// return QStyledItemDelegate::sizeHint(option, index);
// }
// QSize MUCSearchDelegate::mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
-// QFontMetrics nameMetrics(common_.nameFont);
-// QFontMetrics statusMetrics(common_.detailFont);
-// int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
-// return QSize(150, sizeByText);
+// QFontMetrics nameMetrics(common_.nameFont);
+// QFontMetrics statusMetrics(common_.detailFont);
+// int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+// return QSize(150, sizeByText);
// }
// void MUCSearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
-// MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
-// if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
-// paintMUC(painter, option, dynamic_cast<MUCSearchMUCItem*>(item));
-// } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
-// MUCSearchGroupItem* group = dynamic_cast<MUCSearchGroupItem*>(item);
-// groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
-// } else {
-// QStyledItemDelegate::paint(painter, option, index);
-// }
+// MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
+// if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
+// paintMUC(painter, option, dynamic_cast<MUCSearchMUCItem*>(item));
+// } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
+// MUCSearchGroupItem* group = dynamic_cast<MUCSearchGroupItem*>(item);
+// groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
+// } else {
+// QStyledItemDelegate::paint(painter, option, index);
+// }
// }
// void MUCSearchDelegate::paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const {
-// painter->save();
-// QRect fullRegion(option.rect);
-// if ( option.state & QStyle::State_Selected ) {
-// painter->fillRect(fullRegion, option.palette.highlight());
-// painter->setPen(option.palette.highlightedText().color());
-// } else {
-// QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
-// painter->setPen(QPen(nameColor));
-// }
-
-// QFontMetrics nameMetrics(common_.nameFont);
-// painter->setFont(common_.nameFont);
-// int extraFontWidth = nameMetrics.width("H");
-// int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
-// QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
-// int nameHeight = nameMetrics.height() + common_.verticalMargin;
-// QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
-// painter->drawText(nameRegion, Qt::AlignTop, item->data(Qt::DisplayRole).toString());
-
-// painter->setFont(common_.detailFont);
-// painter->setPen(QPen(QColor(160,160,160)));
-
-// QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
-// painter->drawText(detailRegion, Qt::AlignTop, item->data(DetailTextRole).toString());
-
-// painter->restore();
+// painter->save();
+// QRect fullRegion(option.rect);
+// if ( option.state & QStyle::State_Selected ) {
+// painter->fillRect(fullRegion, option.palette.highlight());
+// painter->setPen(option.palette.highlightedText().color());
+// } else {
+// QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+// painter->setPen(QPen(nameColor));
+// }
+
+// QFontMetrics nameMetrics(common_.nameFont);
+// painter->setFont(common_.nameFont);
+// int extraFontWidth = nameMetrics.width("H");
+// int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+// QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+// int nameHeight = nameMetrics.height() + common_.verticalMargin;
+// QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+// painter->drawText(nameRegion, Qt::AlignTop, item->data(Qt::DisplayRole).toString());
+
+// painter->setFont(common_.detailFont);
+// painter->setPen(QPen(QColor(160,160,160)));
+
+// QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+// painter->drawText(detailRegion, Qt::AlignTop, item->data(DetailTextRole).toString());
+
+// painter->restore();
// }
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchDelegate.h b/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
index d521d7b..5bf9646 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
@@ -11,18 +11,18 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class MUCSearchDelegate : public QStyledItemDelegate {
- public:
- MUCSearchDelegate();
- ~MUCSearchDelegate();
- /* QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; */
- /* void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; */
- private:
-// void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const;
-// QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
+ class MUCSearchDelegate : public QStyledItemDelegate {
+ public:
+ MUCSearchDelegate();
+ ~MUCSearchDelegate();
+ /* QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; */
+ /* void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; */
+ private:
+// void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const;
+// QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
- DelegateCommons common_;
- };
+ DelegateCommons common_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
index 5ab6391..d95682c 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
@@ -13,27 +13,27 @@
namespace Swift {
MUCSearchEmptyItem::MUCSearchEmptyItem(MUCSearchServiceItem* parent) : parent(parent) {
- parent->addRoom(this);
+ parent->addRoom(this);
}
MUCSearchServiceItem* MUCSearchEmptyItem::getParent() {
- return parent;
+ return parent;
}
QVariant MUCSearchEmptyItem::data(int role) {
- switch (role) {
- case Qt::DisplayRole:
- return QVariant(QObject::tr("No rooms found"));
- case Qt::FontRole: {
- QFont font;
- font.setItalic(true);
- return font;
- }
- case Qt::ForegroundRole:
- return QColor(Qt::gray);
- default:
- return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole:
+ return QVariant(QObject::tr("No rooms found"));
+ case Qt::FontRole: {
+ QFont font;
+ font.setItalic(true);
+ return font;
+ }
+ case Qt::ForegroundRole:
+ return QColor(Qt::gray);
+ default:
+ return QVariant();
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
index 74e0154..ca4b2b2 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
@@ -9,17 +9,17 @@
#include <Swift/QtUI/MUCSearch/MUCSearchItem.h>
namespace Swift {
- class MUCSearchServiceItem;
+ class MUCSearchServiceItem;
- class MUCSearchEmptyItem : public MUCSearchItem {
- public:
- MUCSearchEmptyItem(MUCSearchServiceItem* parent);
+ class MUCSearchEmptyItem : public MUCSearchItem {
+ public:
+ MUCSearchEmptyItem(MUCSearchServiceItem* parent);
- MUCSearchServiceItem* getParent();
+ MUCSearchServiceItem* getParent();
- QVariant data(int role);
+ QVariant data(int role);
- private:
- MUCSearchServiceItem* parent;
- };
+ private:
+ MUCSearchServiceItem* parent;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchItem.h b/Swift/QtUI/MUCSearch/MUCSearchItem.h
index d2a2c2d..c378247 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchItem.h
@@ -9,9 +9,9 @@
#include <QVariant>
namespace Swift {
- class MUCSearchItem {
- public:
- virtual ~MUCSearchItem() {}
- virtual QVariant data(int role) = 0;
- };
+ class MUCSearchItem {
+ public:
+ virtual ~MUCSearchItem() {}
+ virtual QVariant data(int role) = 0;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
index 1a3ccc4..af6f17f 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
@@ -14,78 +14,78 @@ MUCSearchModel::MUCSearchModel() {
}
void MUCSearchModel::clear() {
- emit layoutAboutToBeChanged();
- services_.clear();
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ services_.clear();
+ emit layoutChanged();
}
void MUCSearchModel::addService(MUCSearchServiceItem* service) {
- emit layoutAboutToBeChanged();
- services_.push_back(service);
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ services_.push_back(service);
+ emit layoutChanged();
}
int MUCSearchModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ return 1;
}
QVariant MUCSearchModel::data(const QModelIndex& index, int role) const {
- return index.isValid() ? static_cast<MUCSearchItem*>(index.internalPointer())->data(role) : QVariant();
+ return index.isValid() ? static_cast<MUCSearchItem*>(index.internalPointer())->data(role) : QVariant();
}
QModelIndex MUCSearchModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
-
- if (parent.isValid()) {
- MUCSearchServiceItem* parentItem = static_cast<MUCSearchServiceItem*>(parent.internalPointer());
- return row < parentItem->rowCount() ? createIndex(row, column, parentItem->getItem(row)) : QModelIndex();
- } else {
- return row < services_.size() ? createIndex(row, column, services_[row]) : QModelIndex();
- }
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
+
+ if (parent.isValid()) {
+ MUCSearchServiceItem* parentItem = static_cast<MUCSearchServiceItem*>(parent.internalPointer());
+ return row < parentItem->rowCount() ? createIndex(row, column, parentItem->getItem(row)) : QModelIndex();
+ } else {
+ return row < services_.size() ? createIndex(row, column, services_[row]) : QModelIndex();
+ }
}
QModelIndex MUCSearchModel::parent(const QModelIndex& index) const {
- if (!index.isValid()) {
- return QModelIndex();
- }
- MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
- if (!item) {
- return QModelIndex();
- }
- else if (dynamic_cast<MUCSearchServiceItem*>(item)) {
- return QModelIndex();
- }
-
- MUCSearchServiceItem* parent = NULL;
- if (MUCSearchRoomItem* roomItem = dynamic_cast<MUCSearchRoomItem*>(item)) {
- parent = roomItem->getParent();
- }
- else if (MUCSearchEmptyItem* emptyItem = dynamic_cast<MUCSearchEmptyItem*>(item)) {
- parent = emptyItem->getParent();
- }
- if (parent) {
- int row = services_.indexOf(parent);
- return createIndex(row, 1, parent);
- }
- else {
- return QModelIndex();
- }
+ if (!index.isValid()) {
+ return QModelIndex();
+ }
+ MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
+ if (!item) {
+ return QModelIndex();
+ }
+ else if (dynamic_cast<MUCSearchServiceItem*>(item)) {
+ return QModelIndex();
+ }
+
+ MUCSearchServiceItem* parent = NULL;
+ if (MUCSearchRoomItem* roomItem = dynamic_cast<MUCSearchRoomItem*>(item)) {
+ parent = roomItem->getParent();
+ }
+ else if (MUCSearchEmptyItem* emptyItem = dynamic_cast<MUCSearchEmptyItem*>(item)) {
+ parent = emptyItem->getParent();
+ }
+ if (parent) {
+ int row = services_.indexOf(parent);
+ return createIndex(row, 1, parent);
+ }
+ else {
+ return QModelIndex();
+ }
}
int MUCSearchModel::rowCount(const QModelIndex& parentIndex) const {
- if (!parentIndex.isValid()) {
- return services_.size();
- }
- if (dynamic_cast<MUCSearchServiceItem*>(static_cast<MUCSearchItem*>(parentIndex.internalPointer()))) {
- return services_[parentIndex.row()]->rowCount();
- }
- else {
- return 0;
- }
+ if (!parentIndex.isValid()) {
+ return services_.size();
+ }
+ if (dynamic_cast<MUCSearchServiceItem*>(static_cast<MUCSearchItem*>(parentIndex.internalPointer()))) {
+ return services_[parentIndex.row()]->rowCount();
+ }
+ else {
+ return 0;
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.h b/Swift/QtUI/MUCSearch/MUCSearchModel.h
index 4ea811f..d6a24f3 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchModel.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchModel.h
@@ -14,22 +14,22 @@
#include <Swift/QtUI/MUCSearch/MUCSearchServiceItem.h>
namespace Swift {
- class MUCSearchModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- MUCSearchModel();
- void clear();
- void addService(MUCSearchServiceItem* service);
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
-// ChatListItem* getItemForIndex(const QModelIndex& index) const;
- private:
-// ChatListGroupItem* mucBookmarks_;
-// ChatListGroupItem* root_;
- QList<MUCSearchServiceItem*> services_;
- };
+ class MUCSearchModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ MUCSearchModel();
+ void clear();
+ void addService(MUCSearchServiceItem* service);
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+// ChatListItem* getItemForIndex(const QModelIndex& index) const;
+ private:
+// ChatListGroupItem* mucBookmarks_;
+// ChatListGroupItem* root_;
+ QList<MUCSearchServiceItem*> services_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
index 169ab49..cb7ee2d 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
@@ -10,17 +10,17 @@
namespace Swift {
MUCSearchRoomItem::MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent) : parent_(parent), node_(node) {
- parent_->addRoom(this);
+ parent_->addRoom(this);
}
MUCSearchServiceItem* MUCSearchRoomItem::getParent() {
- return parent_;
+ return parent_;
}
QVariant MUCSearchRoomItem::data(int role) {
- switch (role) {
- case Qt::DisplayRole: return QVariant(node_);
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return QVariant(node_);
+ default: return QVariant();
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
index c853221..d2b88bc 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
@@ -9,15 +9,15 @@
#include <Swift/QtUI/MUCSearch/MUCSearchItem.h>
namespace Swift {
- class MUCSearchServiceItem;
- class MUCSearchRoomItem : public MUCSearchItem {
- public:
- MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent);
- MUCSearchServiceItem* getParent();
- QVariant data(int role);
- QString getNode() const {return node_;}
- private:
- MUCSearchServiceItem* parent_;
- QString node_;
- };
+ class MUCSearchServiceItem;
+ class MUCSearchRoomItem : public MUCSearchItem {
+ public:
+ MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent);
+ MUCSearchServiceItem* getParent();
+ QVariant data(int role);
+ QString getNode() const {return node_;}
+ private:
+ MUCSearchServiceItem* parent_;
+ QString node_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
index 421ac25..cfde071 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
@@ -12,21 +12,21 @@
#include <Swift/QtUI/MUCSearch/MUCSearchRoomItem.h>
namespace Swift {
- class MUCSearchServiceItem : public MUCSearchItem {
- public:
- MUCSearchServiceItem(const QString& jidString) : jidString_(jidString) {}
- void addRoom(MUCSearchItem* room) {rooms_.push_back(room);}
- int rowCount() {return rooms_.count();}
- MUCSearchItem* getItem(int i) {return rooms_[i];}
- QVariant data(int role) {
- switch (role) {
- case Qt::DisplayRole: return QVariant(jidString_);
- default: return QVariant();
- }
- }
- QString getHost() const {return jidString_;}
- private:
- QList<MUCSearchItem*> rooms_;
- QString jidString_;
- };
+ class MUCSearchServiceItem : public MUCSearchItem {
+ public:
+ MUCSearchServiceItem(const QString& jidString) : jidString_(jidString) {}
+ void addRoom(MUCSearchItem* room) {rooms_.push_back(room);}
+ int rowCount() {return rooms_.count();}
+ MUCSearchItem* getItem(int i) {return rooms_[i];}
+ QVariant data(int role) {
+ switch (role) {
+ case Qt::DisplayRole: return QVariant(jidString_);
+ default: return QVariant();
+ }
+ }
+ QString getHost() const {return jidString_;}
+ private:
+ QList<MUCSearchItem*> rooms_;
+ QString jidString_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
index e3bd7f3..03fa582 100644
--- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
+++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
@@ -24,37 +24,37 @@
namespace Swift {
QtMUCSearchWindow::QtMUCSearchWindow() {
- ui_.setupUi(this);
+ ui_.setupUi(this);
#ifndef Q_OS_MAC
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
- setModal(true);
- ui_.filter_->hide();
- model_ = new MUCSearchModel();
- delegate_ = new MUCSearchDelegate();
- ui_.results_->setModel(model_);
- ui_.results_->setItemDelegate(delegate_);
- ui_.results_->setHeaderHidden(true);
- ui_.results_->setRootIsDecorated(true);
- ui_.results_->setAnimated(true);
- ui_.results_->setAlternatingRowColors(true);
- connect(ui_.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
- connect(ui_.service_, SIGNAL(activated(const QString&)), this, SLOT(handleSearch(const QString&)));
- connect(ui_.results_->selectionModel(), SIGNAL(selectionChanged (const QItemSelection&, const QItemSelection&)), this, SLOT(handleSelectionChanged (const QItemSelection&, const QItemSelection&)));
- connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
- connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
- // Not using a button box, because i can't seem to be able to make the ok button non-default (on mac)
- connect(ui_.okButton, SIGNAL(clicked()), this, SLOT(accept()));
- ui_.okButton->setEnabled(false);
- connect(ui_.cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
-
- throbber_ = new QLabel(tr("Searching"), ui_.results_);
- throbber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), throbber_));
- throbber_->setToolTip(tr("Searching"));
-
- hasHadScrollBars_ = false;
- updateThrobberPosition();
- setSearchInProgress(false);
+ setModal(true);
+ ui_.filter_->hide();
+ model_ = new MUCSearchModel();
+ delegate_ = new MUCSearchDelegate();
+ ui_.results_->setModel(model_);
+ ui_.results_->setItemDelegate(delegate_);
+ ui_.results_->setHeaderHidden(true);
+ ui_.results_->setRootIsDecorated(true);
+ ui_.results_->setAnimated(true);
+ ui_.results_->setAlternatingRowColors(true);
+ connect(ui_.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
+ connect(ui_.service_, SIGNAL(activated(const QString&)), this, SLOT(handleSearch(const QString&)));
+ connect(ui_.results_->selectionModel(), SIGNAL(selectionChanged (const QItemSelection&, const QItemSelection&)), this, SLOT(handleSelectionChanged (const QItemSelection&, const QItemSelection&)));
+ connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
+ connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
+ // Not using a button box, because i can't seem to be able to make the ok button non-default (on mac)
+ connect(ui_.okButton, SIGNAL(clicked()), this, SLOT(accept()));
+ ui_.okButton->setEnabled(false);
+ connect(ui_.cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
+
+ throbber_ = new QLabel(tr("Searching"), ui_.results_);
+ throbber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), throbber_));
+ throbber_->setToolTip(tr("Searching"));
+
+ hasHadScrollBars_ = false;
+ updateThrobberPosition();
+ setSearchInProgress(false);
}
QtMUCSearchWindow::~QtMUCSearchWindow() {
@@ -62,136 +62,136 @@ QtMUCSearchWindow::~QtMUCSearchWindow() {
}
void QtMUCSearchWindow::resizeEvent(QResizeEvent* /*event*/) {
- updateThrobberPosition();
+ updateThrobberPosition();
}
void QtMUCSearchWindow::updateThrobberPosition() {
- bool isShown = throbber_->isVisible();
- int resultWidth = ui_.results_->width();
- int resultHeight = ui_.results_->height();
- //throbberWidth = throbber_->movie()->scaledSize().width();
- //throbberHeight = throbber_->movie()->scaledSize().height();
- int throbberWidth = 16; /* This is nasty, but the above doesn't work! */
- int throbberHeight = 16;
- /* It's difficult (or I spent a while trying) to work out whether the scrollbars are currently shown and their appropriate size,
- * because if you listen for the expanded/collapsed signals, you seem to get them before the scrollbars are updated.
- * This seems an acceptable workaround.
- */
- hasHadScrollBars_ |= ui_.results_->verticalScrollBar()->isVisible();
- int hMargin = hasHadScrollBars_ ? ui_.results_->verticalScrollBar()->width() + 2 : 2;
- int vMargin = 2; /* We don't get horizontal scrollbars */
- throbber_->setGeometry(QRect(resultWidth - throbberWidth - hMargin, resultHeight - throbberHeight - vMargin, throbberWidth, throbberHeight)); /* include margins */
- throbber_->setVisible(isShown);
+ bool isShown = throbber_->isVisible();
+ int resultWidth = ui_.results_->width();
+ int resultHeight = ui_.results_->height();
+ //throbberWidth = throbber_->movie()->scaledSize().width();
+ //throbberHeight = throbber_->movie()->scaledSize().height();
+ int throbberWidth = 16; /* This is nasty, but the above doesn't work! */
+ int throbberHeight = 16;
+ /* It's difficult (or I spent a while trying) to work out whether the scrollbars are currently shown and their appropriate size,
+ * because if you listen for the expanded/collapsed signals, you seem to get them before the scrollbars are updated.
+ * This seems an acceptable workaround.
+ */
+ hasHadScrollBars_ |= ui_.results_->verticalScrollBar()->isVisible();
+ int hMargin = hasHadScrollBars_ ? ui_.results_->verticalScrollBar()->width() + 2 : 2;
+ int vMargin = 2; /* We don't get horizontal scrollbars */
+ throbber_->setGeometry(QRect(resultWidth - throbberWidth - hMargin, resultHeight - throbberHeight - vMargin, throbberWidth, throbberHeight)); /* include margins */
+ throbber_->setVisible(isShown);
}
void QtMUCSearchWindow::addSavedServices(const std::list<JID>& services) {
- ui_.service_->clear();
- foreach (const JID& jid, services) {
- ui_.service_->addItem(P2QSTRING(jid.toString()));
- }
- if (!services.empty()) {
- ui_.service_->setEditText(P2QSTRING(services.begin()->toString()));
- }
- else {
- ui_.service_->clearEditText();
- }
+ ui_.service_->clear();
+ foreach (const JID& jid, services) {
+ ui_.service_->addItem(P2QSTRING(jid.toString()));
+ }
+ if (!services.empty()) {
+ ui_.service_->setEditText(P2QSTRING(services.begin()->toString()));
+ }
+ else {
+ ui_.service_->clearEditText();
+ }
}
void QtMUCSearchWindow::handleActivated(const QModelIndex& index) {
- if (!index.isValid()) {
- return;
- }
- if (dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(index.internalPointer()))) {
- accept();
- }
+ if (!index.isValid()) {
+ return;
+ }
+ if (dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(index.internalPointer()))) {
+ accept();
+ }
}
void QtMUCSearchWindow::handleSearch() {
- handleSearch(ui_.service_->currentText());
+ handleSearch(ui_.service_->currentText());
}
void QtMUCSearchWindow::handleSearch(const QString& service) {
- if (!service.isEmpty()) {
- onSearchService(JID(Q2PSTRING(service)));
- }
+ if (!service.isEmpty()) {
+ onSearchService(JID(Q2PSTRING(service)));
+ }
}
void QtMUCSearchWindow::show() {
- QWidget::show();
- QWidget::activateWindow();
+ QWidget::show();
+ QWidget::activateWindow();
}
void QtMUCSearchWindow::clearList() {
- model_->clear();
+ model_->clear();
}
void QtMUCSearchWindow::addService(const MUCService& service) {
- updateThrobberPosition();
- MUCSearchServiceItem* serviceItem = new MUCSearchServiceItem(P2QSTRING(service.getJID().toString()));
- if (service.getRooms().size() > 0) {
- foreach (MUCService::MUCRoom room, service.getRooms()) {
- new MUCSearchRoomItem(P2QSTRING(room.getNode()), serviceItem);
- }
- }
- else {
- new MUCSearchEmptyItem(serviceItem);
- }
- model_->addService(serviceItem);
- ui_.results_->expandAll();
+ updateThrobberPosition();
+ MUCSearchServiceItem* serviceItem = new MUCSearchServiceItem(P2QSTRING(service.getJID().toString()));
+ if (service.getRooms().size() > 0) {
+ foreach (MUCService::MUCRoom room, service.getRooms()) {
+ new MUCSearchRoomItem(P2QSTRING(room.getNode()), serviceItem);
+ }
+ }
+ else {
+ new MUCSearchEmptyItem(serviceItem);
+ }
+ model_->addService(serviceItem);
+ ui_.results_->expandAll();
}
void QtMUCSearchWindow::setSearchInProgress(bool searching) {
- if (searching) {
- throbber_->movie()->start();
- } else {
- throbber_->movie()->stop();
- }
- throbber_->setVisible(searching);
+ if (searching) {
+ throbber_->movie()->start();
+ } else {
+ throbber_->movie()->stop();
+ }
+ throbber_->setVisible(searching);
}
void QtMUCSearchWindow::accept() {
- MUCSearchRoomItem* room = getSelectedRoom();
- if (room) {
- onFinished(JID(Q2PSTRING(room->getNode()), Q2PSTRING(room->getParent()->getHost())));
- }
- else {
- onFinished(boost::optional<JID>());
- }
- QDialog::accept();
+ MUCSearchRoomItem* room = getSelectedRoom();
+ if (room) {
+ onFinished(JID(Q2PSTRING(room->getNode()), Q2PSTRING(room->getParent()->getHost())));
+ }
+ else {
+ onFinished(boost::optional<JID>());
+ }
+ QDialog::accept();
}
void QtMUCSearchWindow::reject() {
- onFinished(boost::optional<JID>());
- QDialog::reject();
+ onFinished(boost::optional<JID>());
+ QDialog::reject();
}
void QtMUCSearchWindow::handleSelectionChanged(const QItemSelection&, const QItemSelection&) {
- ui_.okButton->setEnabled(getSelectedRoom());
+ ui_.okButton->setEnabled(getSelectedRoom());
}
MUCSearchRoomItem* QtMUCSearchWindow::getSelectedRoom() const {
- // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
- // QModelIndexList destructor.
- // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
- // was resolved by linking against the debug libs, ours isn't, and we're not alone)
- QItemSelection ranges = ui_.results_->selectionModel()->selection();
- QModelIndexList lstIndex;
- for (int i = 0; i < ranges.count(); ++i) {
- QModelIndex parent = ranges.at(i).parent();
- int right = ranges.at(i).model()->columnCount(parent) - 1;
- if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
- for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
- lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
- }
- }
- }
- if (lstIndex.isEmpty()) {
- return NULL;
- }
- else {
- return dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(lstIndex.first().internalPointer()));
- }
+ // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
+ // QModelIndexList destructor.
+ // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
+ // was resolved by linking against the debug libs, ours isn't, and we're not alone)
+ QItemSelection ranges = ui_.results_->selectionModel()->selection();
+ QModelIndexList lstIndex;
+ for (int i = 0; i < ranges.count(); ++i) {
+ QModelIndex parent = ranges.at(i).parent();
+ int right = ranges.at(i).model()->columnCount(parent) - 1;
+ if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
+ for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
+ lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
+ }
+ }
+ }
+ if (lstIndex.isEmpty()) {
+ return NULL;
+ }
+ else {
+ return dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(lstIndex.first().internalPointer()));
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
index 4ac845a..b115e6f 100644
--- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
+++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
@@ -11,41 +11,41 @@
#include <Swift/QtUI/MUCSearch/ui_QtMUCSearchWindow.h>
namespace Swift {
- class MUCSearchModel;
- class MUCSearchDelegate;
- class MUCSearchRoomItem;
-
- class QtMUCSearchWindow : public QDialog, public MUCSearchWindow {
- Q_OBJECT
- public:
- QtMUCSearchWindow();
- virtual ~QtMUCSearchWindow();
-
- virtual void clearList();
- virtual void addService(const MUCService& service);
- virtual void addSavedServices(const std::list<JID>& services);
- virtual void setSearchInProgress(bool searching);
-
- virtual void show();
- virtual void accept();
- virtual void reject();
-
- protected:
- virtual void resizeEvent(QResizeEvent* event);
-
- private slots:
- void handleSearch();
- void handleSearch(const QString&);
- void handleActivated(const QModelIndex& index);
- void updateThrobberPosition();
- void handleSelectionChanged (const QItemSelection&, const QItemSelection&);
- MUCSearchRoomItem* getSelectedRoom() const;
-
- private:
- Ui::QtMUCSearchWindow ui_;
- MUCSearchModel* model_;
- MUCSearchDelegate* delegate_;
- QLabel* throbber_;
- bool hasHadScrollBars_;
- };
+ class MUCSearchModel;
+ class MUCSearchDelegate;
+ class MUCSearchRoomItem;
+
+ class QtMUCSearchWindow : public QDialog, public MUCSearchWindow {
+ Q_OBJECT
+ public:
+ QtMUCSearchWindow();
+ virtual ~QtMUCSearchWindow();
+
+ virtual void clearList();
+ virtual void addService(const MUCService& service);
+ virtual void addSavedServices(const std::list<JID>& services);
+ virtual void setSearchInProgress(bool searching);
+
+ virtual void show();
+ virtual void accept();
+ virtual void reject();
+
+ protected:
+ virtual void resizeEvent(QResizeEvent* event);
+
+ private slots:
+ void handleSearch();
+ void handleSearch(const QString&);
+ void handleActivated(const QModelIndex& index);
+ void updateThrobberPosition();
+ void handleSelectionChanged (const QItemSelection&, const QItemSelection&);
+ MUCSearchRoomItem* getSelectedRoom() const;
+
+ private:
+ Ui::QtMUCSearchWindow ui_;
+ MUCSearchModel* model_;
+ MUCSearchDelegate* delegate_;
+ QLabel* throbber_;
+ bool hasHadScrollBars_;
+ };
}
diff --git a/Swift/QtUI/MessageSnippet.cpp b/Swift/QtUI/MessageSnippet.cpp
index c2969cf..85cbdb9 100644
--- a/Swift/QtUI/MessageSnippet.cpp
+++ b/Swift/QtUI/MessageSnippet.cpp
@@ -11,33 +11,33 @@
namespace Swift {
MessageSnippet::MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction) : ChatSnippet(appendToPrevious) {
- if (appendToPrevious) {
- setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new MessageSnippet(message, sender, time, iconURI, isIncoming, false, theme, id, direction)));
- }
- if (isIncoming) {
- if (appendToPrevious) {
- content_ = theme->getIncomingNextContent();
- }
- else {
- content_ = theme->getIncomingContent();
- }
- }
- else {
- if (appendToPrevious) {
- content_ = theme->getOutgoingNextContent();
- }
- else {
- content_ = theme->getOutgoingContent();
- }
- }
-
- content_.replace("%direction%", directionToCSS(direction));
- content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
- content_.replace("%wrapped_sender%", wrapResizable(escape(sender)));
- content_.replace("%sender%", escape(sender));
- content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
- content_.replace("%userIconPath%", escape(iconURI));
- content_.replace("%id%", id);
+ if (appendToPrevious) {
+ setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new MessageSnippet(message, sender, time, iconURI, isIncoming, false, theme, id, direction)));
+ }
+ if (isIncoming) {
+ if (appendToPrevious) {
+ content_ = theme->getIncomingNextContent();
+ }
+ else {
+ content_ = theme->getIncomingContent();
+ }
+ }
+ else {
+ if (appendToPrevious) {
+ content_ = theme->getOutgoingNextContent();
+ }
+ else {
+ content_ = theme->getOutgoingContent();
+ }
+ }
+
+ content_.replace("%direction%", directionToCSS(direction));
+ content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
+ content_.replace("%wrapped_sender%", wrapResizable(escape(sender)));
+ content_.replace("%sender%", escape(sender));
+ content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
+ content_.replace("%userIconPath%", escape(iconURI));
+ content_.replace("%id%", id);
}
MessageSnippet::~MessageSnippet() {
diff --git a/Swift/QtUI/MessageSnippet.h b/Swift/QtUI/MessageSnippet.h
index e6972a1..302785f 100644
--- a/Swift/QtUI/MessageSnippet.h
+++ b/Swift/QtUI/MessageSnippet.h
@@ -13,19 +13,19 @@
class QDateTime;
namespace Swift {
- class MessageSnippet : public ChatSnippet {
- public:
- MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
- virtual ~MessageSnippet();
- const QString& getContent() const {
- return content_;
- }
+ class MessageSnippet : public ChatSnippet {
+ public:
+ MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
+ virtual ~MessageSnippet();
+ const QString& getContent() const {
+ return content_;
+ }
- QString getContinuationElementID() const {
- return "insert";
- }
+ QString getContinuationElementID() const {
+ return "insert";
+ }
- private:
- QString content_;
- };
+ private:
+ QString content_;
+ };
}
diff --git a/Swift/QtUI/NotifierTest/NotifierTest.cpp b/Swift/QtUI/NotifierTest/NotifierTest.cpp
index 56f7985..8d2e467 100644
--- a/Swift/QtUI/NotifierTest/NotifierTest.cpp
+++ b/Swift/QtUI/NotifierTest/NotifierTest.cpp
@@ -17,12 +17,12 @@
using namespace Swift;
void notificationClicked(const std::string& message) {
- std::cout << "Notification clicked: " << message << std::endl;
+ std::cout << "Notification clicked: " << message << std::endl;
}
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
- GrowlNotifier notifier("Swift-NotifierTest");
- notifier.showMessage(Notifier::ContactAvailable, "Contact is available", "The contact has become available", ByteArray(), boost::bind(&notificationClicked, "Message 1"));
- return app.exec();
+ QApplication app(argc, argv);
+ GrowlNotifier notifier("Swift-NotifierTest");
+ notifier.showMessage(Notifier::ContactAvailable, "Contact is available", "The contact has become available", ByteArray(), boost::bind(&notificationClicked, "Message 1"));
+ return app.exec();
}
diff --git a/Swift/QtUI/QtAboutWidget.cpp b/Swift/QtUI/QtAboutWidget.cpp
index 9fb07ed..b69113f 100644
--- a/Swift/QtUI/QtAboutWidget.cpp
+++ b/Swift/QtUI/QtAboutWidget.cpp
@@ -22,67 +22,67 @@ namespace Swift {
QtAboutWidget::QtAboutWidget() : QDialog() {
#ifndef Q_OS_MAC
- setWindowTitle(QString(tr("About %1")).arg("Swift"));
+ setWindowTitle(QString(tr("About %1")).arg("Swift"));
#endif
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
- resize(180, 240);
- QVBoxLayout *mainLayout = new QVBoxLayout(this);
- mainLayout->setAlignment(Qt::AlignHCenter);
- setLayout(mainLayout);
-
- QLabel* iconLabel = new QLabel(this);
- iconLabel->setPixmap(QIcon(":/logo-shaded-text.256.png").pixmap(90, 90));
- iconLabel->setAlignment(Qt::AlignHCenter);
- mainLayout->addWidget(iconLabel);
-
- QLabel* appNameLabel = new QLabel("<center><font size='+1'><b>" + QCoreApplication::applicationName() + "</b></font></center>", this);
- mainLayout->addWidget(appNameLabel);
-
- QLabel* versionLabel = new QLabel((QString("<center><font size='-1'>") + tr("Version %1") + "</font></center><center><font size='-1'><br/>" + QString(tr("Built with Qt %2")) + QString("<br/>") + QString(tr("Running with Qt %3")) + "</font></center>").arg(QCoreApplication::applicationVersion()).arg(QT_VERSION_STR).arg(qVersion()));
- versionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- mainLayout->addWidget(versionLabel);
+ resize(180, 240);
+ QVBoxLayout *mainLayout = new QVBoxLayout(this);
+ mainLayout->setAlignment(Qt::AlignHCenter);
+ setLayout(mainLayout);
- if (QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR") != "TRANSLATION_AUTHOR") {
- mainLayout->addWidget(new QLabel(QString("<center><font size='-1'>") + QString(tr("Using the English translation by\n%1")).arg(QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR")).replace("\n", "<br/>") + "</font></center>", this));
- }
- QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_LICENSE", "This string contains the license under which this translation is licensed. We ask you to license the translation under the BSD license. Please read http://www.opensource.org/licenses/bsd-license.php, and if you agree to release your translation under this license, use the following (untranslated) text: 'This translation is licensed under the BSD License. See http://www.opensource.org/licenses/bsd-license.php'");
+ QLabel* iconLabel = new QLabel(this);
+ iconLabel->setPixmap(QIcon(":/logo-shaded-text.256.png").pixmap(90, 90));
+ iconLabel->setAlignment(Qt::AlignHCenter);
+ mainLayout->addWidget(iconLabel);
+
+ QLabel* appNameLabel = new QLabel("<center><font size='+1'><b>" + QCoreApplication::applicationName() + "</b></font></center>", this);
+ mainLayout->addWidget(appNameLabel);
+
+ QLabel* versionLabel = new QLabel((QString("<center><font size='-1'>") + tr("Version %1") + "</font></center><center><font size='-1'><br/>" + QString(tr("Built with Qt %2")) + QString("<br/>") + QString(tr("Running with Qt %3")) + "</font></center>").arg(QCoreApplication::applicationVersion()).arg(QT_VERSION_STR).arg(qVersion()));
+ versionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ mainLayout->addWidget(versionLabel);
+
+ if (QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR") != "TRANSLATION_AUTHOR") {
+ mainLayout->addWidget(new QLabel(QString("<center><font size='-1'>") + QString(tr("Using the English translation by\n%1")).arg(QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR")).replace("\n", "<br/>") + "</font></center>", this));
+ }
+ QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_LICENSE", "This string contains the license under which this translation is licensed. We ask you to license the translation under the BSD license. Please read http://www.opensource.org/licenses/bsd-license.php, and if you agree to release your translation under this license, use the following (untranslated) text: 'This translation is licensed under the BSD License. See http://www.opensource.org/licenses/bsd-license.php'");
#if defined(SWIFTEN_PLATFORM_WINDOWS) || defined(SWIFTEN_PLATFORM_MACOSX)
- QPushButton* licenseButton = new QPushButton(tr("View License"), this);
- mainLayout->addWidget(licenseButton);
- connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
+ QPushButton* licenseButton = new QPushButton(tr("View License"), this);
+ mainLayout->addWidget(licenseButton);
+ connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
#else
- // Some Linux desktops have dialog window decorations without close window buttons.
- // This code adds a dedicated button to close the about window dialog.
- QHBoxLayout* buttonLayout = new QHBoxLayout();
- mainLayout->addLayout(buttonLayout);
+ // Some Linux desktops have dialog window decorations without close window buttons.
+ // This code adds a dedicated button to close the about window dialog.
+ QHBoxLayout* buttonLayout = new QHBoxLayout();
+ mainLayout->addLayout(buttonLayout);
- QPushButton* licenseButton = new QPushButton(tr("View License"), this);
- buttonLayout->addWidget(licenseButton);
- connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
+ QPushButton* licenseButton = new QPushButton(tr("View License"), this);
+ buttonLayout->addWidget(licenseButton);
+ connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
- buttonLayout->addItem(new QSpacerItem(20,20));
+ buttonLayout->addItem(new QSpacerItem(20,20));
- QPushButton* closeButton = new QPushButton(tr("Close"), this);
- buttonLayout->addWidget(closeButton);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()));
+ QPushButton* closeButton = new QPushButton(tr("Close"), this);
+ buttonLayout->addWidget(closeButton);
+ connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()));
#endif
- setFixedSize(minimumSizeHint());
+ setFixedSize(minimumSizeHint());
}
void QtAboutWidget::handleLicenseClicked() {
- QTextEdit* text = new QTextEdit();
- text->setAttribute(Qt::WA_DeleteOnClose);
- text->setReadOnly(true);
- QFile file(":/COPYING");
- file.open(QIODevice::ReadOnly);
- QTextStream in(&file);
- in.setCodec("UTF-8");
- text->setPlainText(in.readAll());
- file.close();
- text->resize(500, 600);
- text->show();
- text->activateWindow();
+ QTextEdit* text = new QTextEdit();
+ text->setAttribute(Qt::WA_DeleteOnClose);
+ text->setReadOnly(true);
+ QFile file(":/COPYING");
+ file.open(QIODevice::ReadOnly);
+ QTextStream in(&file);
+ in.setCodec("UTF-8");
+ text->setPlainText(in.readAll());
+ file.close();
+ text->resize(500, 600);
+ text->show();
+ text->activateWindow();
}
}
diff --git a/Swift/QtUI/QtAboutWidget.h b/Swift/QtUI/QtAboutWidget.h
index d09010b..7d0d628 100644
--- a/Swift/QtUI/QtAboutWidget.h
+++ b/Swift/QtUI/QtAboutWidget.h
@@ -9,13 +9,13 @@
#include <QDialog>
namespace Swift {
- class QtAboutWidget : public QDialog {
- Q_OBJECT
+ class QtAboutWidget : public QDialog {
+ Q_OBJECT
- public:
- QtAboutWidget();
+ public:
+ QtAboutWidget();
- private slots:
- void handleLicenseClicked();
- };
+ private slots:
+ void handleLicenseClicked();
+ };
}
diff --git a/Swift/QtUI/QtAdHocCommandWindow.cpp b/Swift/QtUI/QtAdHocCommandWindow.cpp
index ef397f4..87b1585 100644
--- a/Swift/QtUI/QtAdHocCommandWindow.cpp
+++ b/Swift/QtUI/QtAdHocCommandWindow.cpp
@@ -20,155 +20,155 @@ const int FormLayoutIndex = 1;
namespace Swift {
QtAdHocCommandWindow::QtAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command) : command_(command) {
- formWidget_ = NULL;
-
- setAttribute(Qt::WA_DeleteOnClose);
- command->onNextStageReceived.connect(boost::bind(&QtAdHocCommandWindow::handleNextStageReceived, this, _1));
- command->onError.connect(boost::bind(&QtAdHocCommandWindow::handleError, this, _1));
- command->start();
-
- layout_ = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout_->setContentsMargins(0,0,0,0);
- layout_->setSpacing(2);
- label_ = new QLabel(this);
- label_->setTextFormat(Qt::PlainText);
- layout_->addWidget(label_);
-
- errorLabel_ = new QLabel(this);
- errorLabel_->setText(QString("<b>%1</b>").arg(tr("Unable to complete the command because you have been disconnected")));
- errorLabel_->setVisible(false);
- errorLabel_->setFrameStyle(QFrame::Box|QFrame::Sunken);
- layout_->addWidget(errorLabel_);
-
- dialogButtons_ = new QDialogButtonBox(this);
- layout_->addWidget(dialogButtons_);
-
- dialogButtons_->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
- okButton_ = dialogButtons_->button(QDialogButtonBox::Ok);
- connect(okButton_, SIGNAL(clicked()), this, SLOT(close()));
- cancelButton_ = dialogButtons_->button(QDialogButtonBox::Cancel);
- connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
- // Buttons appear next to the Ok button, right of Cancel with YesRole
- completeButton_ = dialogButtons_->addButton(tr("Complete"), QDialogButtonBox::YesRole);
- connect(completeButton_, SIGNAL(clicked()), this, SLOT(handleCompleteClicked()));
- nextButton_ = dialogButtons_->addButton(tr("Next"), QDialogButtonBox::YesRole);
- connect(nextButton_, SIGNAL(clicked()), this, SLOT(handleNextClicked()));
- backButton_ = dialogButtons_->addButton(tr("Back"), QDialogButtonBox::YesRole);
- connect(backButton_, SIGNAL(clicked()), this, SLOT(handlePrevClicked()));
-
- okButton_->setEnabled(false);
- okButton_->hide();
-
- nextButton_->setEnabled(false);
- backButton_->setEnabled(false);
- completeButton_->setEnabled(false);
-
- actions_[Command::Next] = nextButton_;
- actions_[Command::Prev] = backButton_;
- actions_[Command::Complete] = completeButton_;
- actions_[Command::Cancel] = cancelButton_;
+ formWidget_ = NULL;
+
+ setAttribute(Qt::WA_DeleteOnClose);
+ command->onNextStageReceived.connect(boost::bind(&QtAdHocCommandWindow::handleNextStageReceived, this, _1));
+ command->onError.connect(boost::bind(&QtAdHocCommandWindow::handleError, this, _1));
+ command->start();
+
+ layout_ = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout_->setContentsMargins(0,0,0,0);
+ layout_->setSpacing(2);
+ label_ = new QLabel(this);
+ label_->setTextFormat(Qt::PlainText);
+ layout_->addWidget(label_);
+
+ errorLabel_ = new QLabel(this);
+ errorLabel_->setText(QString("<b>%1</b>").arg(tr("Unable to complete the command because you have been disconnected")));
+ errorLabel_->setVisible(false);
+ errorLabel_->setFrameStyle(QFrame::Box|QFrame::Sunken);
+ layout_->addWidget(errorLabel_);
+
+ dialogButtons_ = new QDialogButtonBox(this);
+ layout_->addWidget(dialogButtons_);
+
+ dialogButtons_->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
+ okButton_ = dialogButtons_->button(QDialogButtonBox::Ok);
+ connect(okButton_, SIGNAL(clicked()), this, SLOT(close()));
+ cancelButton_ = dialogButtons_->button(QDialogButtonBox::Cancel);
+ connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
+ // Buttons appear next to the Ok button, right of Cancel with YesRole
+ completeButton_ = dialogButtons_->addButton(tr("Complete"), QDialogButtonBox::YesRole);
+ connect(completeButton_, SIGNAL(clicked()), this, SLOT(handleCompleteClicked()));
+ nextButton_ = dialogButtons_->addButton(tr("Next"), QDialogButtonBox::YesRole);
+ connect(nextButton_, SIGNAL(clicked()), this, SLOT(handleNextClicked()));
+ backButton_ = dialogButtons_->addButton(tr("Back"), QDialogButtonBox::YesRole);
+ connect(backButton_, SIGNAL(clicked()), this, SLOT(handlePrevClicked()));
+
+ okButton_->setEnabled(false);
+ okButton_->hide();
+
+ nextButton_->setEnabled(false);
+ backButton_->setEnabled(false);
+ completeButton_->setEnabled(false);
+
+ actions_[Command::Next] = nextButton_;
+ actions_[Command::Prev] = backButton_;
+ actions_[Command::Complete] = completeButton_;
+ actions_[Command::Cancel] = cancelButton_;
}
QtAdHocCommandWindow::~QtAdHocCommandWindow() {
}
void QtAdHocCommandWindow::setOnline(bool online) {
- if (!online) {
- nextButton_->setEnabled(false);
- backButton_->setEnabled(false);
- completeButton_->setEnabled(false);
- errorLabel_->setVisible(true);
- }
+ if (!online) {
+ nextButton_->setEnabled(false);
+ backButton_->setEnabled(false);
+ completeButton_->setEnabled(false);
+ errorLabel_->setVisible(true);
+ }
}
void QtAdHocCommandWindow::closeEvent(QCloseEvent*) {
- onClosing();
+ onClosing();
}
void QtAdHocCommandWindow::handleCancelClicked() {
- command_->cancel();
- close();
+ command_->cancel();
+ close();
}
void QtAdHocCommandWindow::handlePrevClicked() {
- command_->goBack();
+ command_->goBack();
}
void QtAdHocCommandWindow::handleNextClicked() {
- command_->goNext(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
+ command_->goNext(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
}
void QtAdHocCommandWindow::handleCompleteClicked() {
- command_->complete(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
+ command_->complete(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
}
void QtAdHocCommandWindow::handleNextStageReceived(Command::ref command) {
- QString notes;
- foreach (Command::Note note, command->getNotes()) {
- if (!notes.isEmpty()) {
- notes += "\n";
- }
- QString qNote(P2QSTRING(note.note));
- switch (note.type) {
- case Command::Note::Error: notes += tr("Error: %1").arg(qNote); break;
- case Command::Note::Warn: notes += tr("Warning: %1").arg(qNote); break;
- case Command::Note::Info: notes += qNote; break;
- }
- }
- label_->setText(notes);
- if (command->getForm()) {
- setForm(command->getForm());
- } else {
- setNoForm(notes.isEmpty());
- }
- setAvailableActions(command);
+ QString notes;
+ foreach (Command::Note note, command->getNotes()) {
+ if (!notes.isEmpty()) {
+ notes += "\n";
+ }
+ QString qNote(P2QSTRING(note.note));
+ switch (note.type) {
+ case Command::Note::Error: notes += tr("Error: %1").arg(qNote); break;
+ case Command::Note::Warn: notes += tr("Warning: %1").arg(qNote); break;
+ case Command::Note::Info: notes += qNote; break;
+ }
+ }
+ label_->setText(notes);
+ if (command->getForm()) {
+ setForm(command->getForm());
+ } else {
+ setNoForm(notes.isEmpty());
+ }
+ setAvailableActions(command);
}
void QtAdHocCommandWindow::handleError(ErrorPayload::ref /*error*/) {
- nextButton_->setEnabled(false);
- backButton_->setEnabled(false);
- completeButton_->setEnabled(false);
- label_->setText(tr("Error executing command"));
+ nextButton_->setEnabled(false);
+ backButton_->setEnabled(false);
+ completeButton_->setEnabled(false);
+ label_->setText(tr("Error executing command"));
}
void QtAdHocCommandWindow::setForm(Form::ref form) {
- form_ = form;
- delete formWidget_;
- formWidget_ = new QtFormWidget(form, this);
- layout_->insertWidget(FormLayoutIndex, formWidget_);
- show();
+ form_ = form;
+ delete formWidget_;
+ formWidget_ = new QtFormWidget(form, this);
+ layout_->insertWidget(FormLayoutIndex, formWidget_);
+ show();
}
void QtAdHocCommandWindow::setNoForm(bool andHide) {
- form_.reset();
- delete formWidget_;
- formWidget_ = NULL;
- resize(minimumSize());
- setVisible(!andHide);
+ form_.reset();
+ delete formWidget_;
+ formWidget_ = NULL;
+ resize(minimumSize());
+ setVisible(!andHide);
}
typedef std::pair<Command::Action, QPushButton*> ActionButton;
void QtAdHocCommandWindow::setAvailableActions(Command::ref /*commandResult*/) {
- okButton_->show();
- okButton_->setEnabled(true);
- foreach (ActionButton pair, actions_) {
- OutgoingAdHocCommandSession::ActionState state = command_->getActionState(pair.first);
- if (state & OutgoingAdHocCommandSession::Present) {
- okButton_->hide();
- okButton_->setEnabled(false);
- pair.second->show();
- }
- else {
- pair.second->hide();
- }
- if (state & OutgoingAdHocCommandSession::Enabled) {
- pair.second->setEnabled(true);
- }
- else {
- pair.second->setEnabled(false);
- }
- }
+ okButton_->show();
+ okButton_->setEnabled(true);
+ foreach (ActionButton pair, actions_) {
+ OutgoingAdHocCommandSession::ActionState state = command_->getActionState(pair.first);
+ if (state & OutgoingAdHocCommandSession::Present) {
+ okButton_->hide();
+ okButton_->setEnabled(false);
+ pair.second->show();
+ }
+ else {
+ pair.second->hide();
+ }
+ if (state & OutgoingAdHocCommandSession::Enabled) {
+ pair.second->setEnabled(true);
+ }
+ else {
+ pair.second->setEnabled(false);
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtAdHocCommandWindow.h b/Swift/QtUI/QtAdHocCommandWindow.h
index c8d493c..61cd5be 100644
--- a/Swift/QtUI/QtAdHocCommandWindow.h
+++ b/Swift/QtUI/QtAdHocCommandWindow.h
@@ -18,41 +18,41 @@
class QBoxLayout;
namespace Swift {
- class QtFormWidget;
- class QtAdHocCommandWindow : public QWidget, public AdHocCommandWindow {
- Q_OBJECT
- public:
- QtAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
- virtual ~QtAdHocCommandWindow();
- virtual void setOnline(bool online);
-
- private:
- void closeEvent(QCloseEvent* event);
- void handleNextStageReceived(Command::ref command);
- void handleError(ErrorPayload::ref error);
- void setForm(Form::ref);
- void setNoForm(bool andHide);
- void setAvailableActions(Command::ref commandResult);
-
- private slots:
- void handleCancelClicked();
- void handlePrevClicked();
- void handleNextClicked();
- void handleCompleteClicked();
-
- private:
- boost::shared_ptr<OutgoingAdHocCommandSession> command_;
- QtFormWidget* formWidget_;
- Form::ref form_;
- QLabel* label_;
- QLabel* errorLabel_;
- QPushButton* backButton_;
- QPushButton* nextButton_;
- QPushButton* completeButton_;
- QPushButton* cancelButton_;
- QPushButton* okButton_;
- std::map<Command::Action, QPushButton*> actions_;
- QDialogButtonBox* dialogButtons_;
- QBoxLayout* layout_;
- };
+ class QtFormWidget;
+ class QtAdHocCommandWindow : public QWidget, public AdHocCommandWindow {
+ Q_OBJECT
+ public:
+ QtAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
+ virtual ~QtAdHocCommandWindow();
+ virtual void setOnline(bool online);
+
+ private:
+ void closeEvent(QCloseEvent* event);
+ void handleNextStageReceived(Command::ref command);
+ void handleError(ErrorPayload::ref error);
+ void setForm(Form::ref);
+ void setNoForm(bool andHide);
+ void setAvailableActions(Command::ref commandResult);
+
+ private slots:
+ void handleCancelClicked();
+ void handlePrevClicked();
+ void handleNextClicked();
+ void handleCompleteClicked();
+
+ private:
+ boost::shared_ptr<OutgoingAdHocCommandSession> command_;
+ QtFormWidget* formWidget_;
+ Form::ref form_;
+ QLabel* label_;
+ QLabel* errorLabel_;
+ QPushButton* backButton_;
+ QPushButton* nextButton_;
+ QPushButton* completeButton_;
+ QPushButton* cancelButton_;
+ QPushButton* okButton_;
+ std::map<Command::Action, QPushButton*> actions_;
+ QDialogButtonBox* dialogButtons_;
+ QBoxLayout* layout_;
+ };
}
diff --git a/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp b/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
index ac2a603..69e1d68 100644
--- a/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
+++ b/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
@@ -23,42 +23,42 @@
namespace Swift {
QtAdHocCommandWithJIDWindow::QtAdHocCommandWithJIDWindow(UIEventStream* uiEventStream) : uiEventStream_(uiEventStream) {
- QVBoxLayout* hlayout = new QVBoxLayout(this);
+ QVBoxLayout* hlayout = new QVBoxLayout(this);
- QLabel* jidLabel = new QLabel("JID:", this);
- hlayout->addWidget(jidLabel);
- jid_ = new QLineEdit(this);
- hlayout->addWidget(jid_);
+ QLabel* jidLabel = new QLabel("JID:", this);
+ hlayout->addWidget(jidLabel);
+ jid_ = new QLineEdit(this);
+ hlayout->addWidget(jid_);
- QLabel* commandLabel = new QLabel("Command:", this);
- hlayout->addWidget(commandLabel);
- node_ = new QLineEdit(this);
- hlayout->addWidget(node_);
+ QLabel* commandLabel = new QLabel("Command:", this);
+ hlayout->addWidget(commandLabel);
+ node_ = new QLineEdit(this);
+ hlayout->addWidget(node_);
- QDialogButtonBox* buttonBox = new QDialogButtonBox(this);
- QPushButton* rejectButton = buttonBox->addButton("Cancel", QDialogButtonBox::RejectRole);
- connect(rejectButton, SIGNAL(clicked()), this, SLOT(handleRejectClick()));
- QPushButton* acceptButton = buttonBox->addButton("Complete", QDialogButtonBox::AcceptRole);
- connect(acceptButton, SIGNAL(clicked()), this, SLOT(handleAcceptClick()));
- hlayout->addWidget(buttonBox);
+ QDialogButtonBox* buttonBox = new QDialogButtonBox(this);
+ QPushButton* rejectButton = buttonBox->addButton("Cancel", QDialogButtonBox::RejectRole);
+ connect(rejectButton, SIGNAL(clicked()), this, SLOT(handleRejectClick()));
+ QPushButton* acceptButton = buttonBox->addButton("Complete", QDialogButtonBox::AcceptRole);
+ connect(acceptButton, SIGNAL(clicked()), this, SLOT(handleAcceptClick()));
+ hlayout->addWidget(buttonBox);
- setLayout(hlayout);
- show();
+ setLayout(hlayout);
+ show();
}
QtAdHocCommandWithJIDWindow::~QtAdHocCommandWithJIDWindow() {
}
void QtAdHocCommandWithJIDWindow::handleAcceptClick() {
- const JID jid = JID(Q2PSTRING(jid_->text()));
- const std::string node = Q2PSTRING(node_->text());
- boost::shared_ptr<UIEvent> event(new RequestAdHocWithJIDUIEvent(jid, node));
- uiEventStream_->send(event);
- accept();
+ const JID jid = JID(Q2PSTRING(jid_->text()));
+ const std::string node = Q2PSTRING(node_->text());
+ boost::shared_ptr<UIEvent> event(new RequestAdHocWithJIDUIEvent(jid, node));
+ uiEventStream_->send(event);
+ accept();
}
void QtAdHocCommandWithJIDWindow::handleRejectClick() {
- reject();
+ reject();
}
}
diff --git a/Swift/QtUI/QtAdHocCommandWithJIDWindow.h b/Swift/QtUI/QtAdHocCommandWithJIDWindow.h
index e1f7a9c..0e83555 100644
--- a/Swift/QtUI/QtAdHocCommandWithJIDWindow.h
+++ b/Swift/QtUI/QtAdHocCommandWithJIDWindow.h
@@ -14,19 +14,19 @@
class QBoxLayout;
namespace Swift {
- class UIEventStream;
- class QtFormWidget;
- class QtAdHocCommandWithJIDWindow : public QDialog {
- Q_OBJECT
- public:
- QtAdHocCommandWithJIDWindow(UIEventStream* eventStream);
- virtual ~QtAdHocCommandWithJIDWindow();
- public slots:
- void handleAcceptClick();
- void handleRejectClick();
- private:
- UIEventStream* uiEventStream_;
- QLineEdit* jid_;
- QLineEdit* node_;
- };
+ class UIEventStream;
+ class QtFormWidget;
+ class QtAdHocCommandWithJIDWindow : public QDialog {
+ Q_OBJECT
+ public:
+ QtAdHocCommandWithJIDWindow(UIEventStream* eventStream);
+ virtual ~QtAdHocCommandWithJIDWindow();
+ public slots:
+ void handleAcceptClick();
+ void handleRejectClick();
+ private:
+ UIEventStream* uiEventStream_;
+ QLineEdit* jid_;
+ QLineEdit* node_;
+ };
}
diff --git a/Swift/QtUI/QtAddBookmarkWindow.cpp b/Swift/QtUI/QtAddBookmarkWindow.cpp
index 087628d..500b298 100644
--- a/Swift/QtUI/QtAddBookmarkWindow.cpp
+++ b/Swift/QtUI/QtAddBookmarkWindow.cpp
@@ -8,23 +8,23 @@
namespace Swift {
QtAddBookmarkWindow::QtAddBookmarkWindow(UIEventStream* eventStream) : eventStream_(eventStream) {
- setWindowTitle(tr("Add Bookmark Details"));
+ setWindowTitle(tr("Add Bookmark Details"));
}
QtAddBookmarkWindow::QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark) : eventStream_(eventStream) {
- createFormFromBookmark(bookmark);
- setWindowTitle(tr("Add Bookmark Details"));
+ createFormFromBookmark(bookmark);
+ setWindowTitle(tr("Add Bookmark Details"));
}
bool QtAddBookmarkWindow::commit() {
- boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
- if (bookmark) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(*bookmark)));
- return true;
- }
- else {
- return false;
- }
+ boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
+ if (bookmark) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(*bookmark)));
+ return true;
+ }
+ else {
+ return false;
+ }
}
}
diff --git a/Swift/QtUI/QtAddBookmarkWindow.h b/Swift/QtUI/QtAddBookmarkWindow.h
index 7b08b8e..607f647 100644
--- a/Swift/QtUI/QtAddBookmarkWindow.h
+++ b/Swift/QtUI/QtAddBookmarkWindow.h
@@ -12,13 +12,13 @@
#include <Swift/QtUI/QtBookmarkDetailWindow.h>
namespace Swift {
- class QtAddBookmarkWindow : public QtBookmarkDetailWindow {
- Q_OBJECT
- public:
- QtAddBookmarkWindow(UIEventStream* eventStream);
- QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
- bool commit();
- private:
- UIEventStream* eventStream_;
- };
+ class QtAddBookmarkWindow : public QtBookmarkDetailWindow {
+ Q_OBJECT
+ public:
+ QtAddBookmarkWindow(UIEventStream* eventStream);
+ QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
+ bool commit();
+ private:
+ UIEventStream* eventStream_;
+ };
}
diff --git a/Swift/QtUI/QtAffiliationEditor.cpp b/Swift/QtUI/QtAffiliationEditor.cpp
index d732c4e..980b26a 100644
--- a/Swift/QtUI/QtAffiliationEditor.cpp
+++ b/Swift/QtUI/QtAffiliationEditor.cpp
@@ -13,66 +13,66 @@
namespace Swift {
QtAffiliationEditor::QtAffiliationEditor(QWidget* parent) : QDialog(parent){
- ui_.setupUi(this);
- setAttribute(Qt::WA_DeleteOnClose);
- connect(ui_.affiliation, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged(int)));
- connect(ui_.addJID, SIGNAL(clicked()), this, SLOT(handleAddClicked()));
- connect(ui_.removeJID, SIGNAL(clicked()), this, SLOT(handleRemoveClicked()));
+ ui_.setupUi(this);
+ setAttribute(Qt::WA_DeleteOnClose);
+ connect(ui_.affiliation, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged(int)));
+ connect(ui_.addJID, SIGNAL(clicked()), this, SLOT(handleAddClicked()));
+ connect(ui_.removeJID, SIGNAL(clicked()), this, SLOT(handleRemoveClicked()));
}
QtAffiliationEditor::~QtAffiliationEditor() {
-
+
}
void QtAffiliationEditor::setAffiliations(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids) {
- affiliations_[affiliation] = jids;
- if (affiliationFromIndex(ui_.affiliation->currentIndex()) == affiliation) {
- handleCurrentIndexChanged(ui_.affiliation->currentIndex());
- }
+ affiliations_[affiliation] = jids;
+ if (affiliationFromIndex(ui_.affiliation->currentIndex()) == affiliation) {
+ handleCurrentIndexChanged(ui_.affiliation->currentIndex());
+ }
}
const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& QtAffiliationEditor::getChanges() const {
- return changes_;
+ return changes_;
}
void QtAffiliationEditor::handleCurrentIndexChanged(int index) {
- ui_.list->clear();
- foreach (const JID& jid, affiliations_[affiliationFromIndex(index)]) {
- ui_.list->addItem(P2QSTRING(jid.toString()));
- }
+ ui_.list->clear();
+ foreach (const JID& jid, affiliations_[affiliationFromIndex(index)]) {
+ ui_.list->addItem(P2QSTRING(jid.toString()));
+ }
}
void QtAffiliationEditor::handleAddClicked() {
- bool ok = false;
- JID jid = JID(Q2PSTRING(QInputDialog::getText(this, tr("Add User"), tr("Added User's Address:"), QLineEdit::Normal, "", &ok)));
- if (ok && jid.isValid()) {
- //FIXME: validation
- MUCOccupant::Affiliation affiliation = affiliationFromIndex(ui_.affiliation->currentIndex());
- changes_.push_back(ChangePair(affiliation, jid));
- ui_.list->addItem(P2QSTRING(jid.toString()));
- affiliations_[affiliation].push_back(jid);
- }
+ bool ok = false;
+ JID jid = JID(Q2PSTRING(QInputDialog::getText(this, tr("Add User"), tr("Added User's Address:"), QLineEdit::Normal, "", &ok)));
+ if (ok && jid.isValid()) {
+ //FIXME: validation
+ MUCOccupant::Affiliation affiliation = affiliationFromIndex(ui_.affiliation->currentIndex());
+ changes_.push_back(ChangePair(affiliation, jid));
+ ui_.list->addItem(P2QSTRING(jid.toString()));
+ affiliations_[affiliation].push_back(jid);
+ }
}
void QtAffiliationEditor::handleRemoveClicked() {
- QListWidgetItem* item = ui_.list->currentItem();
- if (item) {
- JID jid(Q2PSTRING(item->text()));
- changes_.push_back(ChangePair(MUCOccupant::NoAffiliation, jid));
- std::vector<JID>& jids = affiliations_[affiliationFromIndex(ui_.affiliation->currentIndex())];
- jids.erase(std::remove(jids.begin(), jids.end(), jid), jids.end());
- handleCurrentIndexChanged(ui_.affiliation->currentIndex());
- }
+ QListWidgetItem* item = ui_.list->currentItem();
+ if (item) {
+ JID jid(Q2PSTRING(item->text()));
+ changes_.push_back(ChangePair(MUCOccupant::NoAffiliation, jid));
+ std::vector<JID>& jids = affiliations_[affiliationFromIndex(ui_.affiliation->currentIndex())];
+ jids.erase(std::remove(jids.begin(), jids.end(), jid), jids.end());
+ handleCurrentIndexChanged(ui_.affiliation->currentIndex());
+ }
}
MUCOccupant::Affiliation QtAffiliationEditor::affiliationFromIndex(int affiliation) {
- switch (affiliation) {
- case 0: return MUCOccupant::Owner;
- case 1: return MUCOccupant::Admin;
- case 2: return MUCOccupant::Member;
- case 3: return MUCOccupant::Outcast;
- default: return MUCOccupant::Outcast;
- }
+ switch (affiliation) {
+ case 0: return MUCOccupant::Owner;
+ case 1: return MUCOccupant::Admin;
+ case 2: return MUCOccupant::Member;
+ case 3: return MUCOccupant::Outcast;
+ default: return MUCOccupant::Outcast;
+ }
}
}
diff --git a/Swift/QtUI/QtAffiliationEditor.h b/Swift/QtUI/QtAffiliationEditor.h
index d706926..3b7e548 100644
--- a/Swift/QtUI/QtAffiliationEditor.h
+++ b/Swift/QtUI/QtAffiliationEditor.h
@@ -17,22 +17,22 @@
#include <Swift/QtUI/ui_QtAffiliationEditor.h>
namespace Swift {
- class QtAffiliationEditor : public QDialog {
- Q_OBJECT
- public:
- QtAffiliationEditor(QWidget* parent = NULL);
- ~QtAffiliationEditor();
- void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>& jids);
- const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& getChanges() const;
- private slots:
- void handleCurrentIndexChanged(int);
- void handleAddClicked();
- void handleRemoveClicked();
- private:
- typedef std::pair<MUCOccupant::Affiliation, JID> ChangePair;
- MUCOccupant::Affiliation affiliationFromIndex(int affiliation);
- Ui::QtAffiliationEditor ui_;
- std::map<MUCOccupant::Affiliation, std::vector<JID> > affiliations_;
- std::vector<ChangePair> changes_;
- };
+ class QtAffiliationEditor : public QDialog {
+ Q_OBJECT
+ public:
+ QtAffiliationEditor(QWidget* parent = NULL);
+ ~QtAffiliationEditor();
+ void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>& jids);
+ const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& getChanges() const;
+ private slots:
+ void handleCurrentIndexChanged(int);
+ void handleAddClicked();
+ void handleRemoveClicked();
+ private:
+ typedef std::pair<MUCOccupant::Affiliation, JID> ChangePair;
+ MUCOccupant::Affiliation affiliationFromIndex(int affiliation);
+ Ui::QtAffiliationEditor ui_;
+ std::map<MUCOccupant::Affiliation, std::vector<JID> > affiliations_;
+ std::vector<ChangePair> changes_;
+ };
}
diff --git a/Swift/QtUI/QtAvatarWidget.cpp b/Swift/QtUI/QtAvatarWidget.cpp
index 2474e80..7f6e275 100644
--- a/Swift/QtUI/QtAvatarWidget.cpp
+++ b/Swift/QtUI/QtAvatarWidget.cpp
@@ -27,85 +27,85 @@
namespace Swift {
QtAvatarWidget::QtAvatarWidget(QWidget* parent) : QWidget(parent), editable(false) {
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->setContentsMargins(0,0,0,0);
-
- QSizePolicy sp(QSizePolicy::Fixed, QSizePolicy::Fixed);
- sp.setHorizontalStretch(0);
- sp.setVerticalStretch(0);
- setSizePolicy(sp);
- setMinimumSize(QSize(96, 96));
- setMaximumSize(QSize(96, 96));
-
- label = new QLabel(this);
- label->setWordWrap(true);
- label->setSizePolicy(sp);
- label->setMinimumSize(QSize(96, 96));
- label->setMaximumSize(QSize(96, 96));
- label->setAlignment(Qt::AlignCenter);
- layout->addWidget(label);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->setContentsMargins(0,0,0,0);
+
+ QSizePolicy sp(QSizePolicy::Fixed, QSizePolicy::Fixed);
+ sp.setHorizontalStretch(0);
+ sp.setVerticalStretch(0);
+ setSizePolicy(sp);
+ setMinimumSize(QSize(96, 96));
+ setMaximumSize(QSize(96, 96));
+
+ label = new QLabel(this);
+ label->setWordWrap(true);
+ label->setSizePolicy(sp);
+ label->setMinimumSize(QSize(96, 96));
+ label->setMaximumSize(QSize(96, 96));
+ label->setAlignment(Qt::AlignCenter);
+ layout->addWidget(label);
}
void QtAvatarWidget::setAvatar(const ByteArray& data, const std::string& type) {
- this->data = data;
- this->type = type;
-
- QImage image;
- if (!data.empty()) {
- image.loadFromData(reinterpret_cast<const uchar*>(vecptr(data)), data.size());
- }
-
- if (image.isNull()) {
- image = QImage(":/icons/no-avatar.png");
- QPainter painter(&image);
- painter.setPen(Qt::gray);
- QFont font = painter.font();
- font.setPointSize(14);
- painter.setFont(font);
- painter.drawText(0, 0, image.height(), image.width(), Qt::AlignHCenter | Qt::AlignVCenter, tr("No picture"));
- }
-
- if (image.height() > label->height() || image.width() > label->width()) {
- image = image.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
- label->setPixmap(QPixmap::fromImage(image));
+ this->data = data;
+ this->type = type;
+
+ QImage image;
+ if (!data.empty()) {
+ image.loadFromData(reinterpret_cast<const uchar*>(vecptr(data)), data.size());
+ }
+
+ if (image.isNull()) {
+ image = QImage(":/icons/no-avatar.png");
+ QPainter painter(&image);
+ painter.setPen(Qt::gray);
+ QFont font = painter.font();
+ font.setPointSize(14);
+ painter.setFont(font);
+ painter.drawText(0, 0, image.height(), image.width(), Qt::AlignHCenter | Qt::AlignVCenter, tr("No picture"));
+ }
+
+ if (image.height() > label->height() || image.width() > label->width()) {
+ image = image.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ label->setPixmap(QPixmap::fromImage(image));
}
void QtAvatarWidget::mousePressEvent(QMouseEvent* event) {
- if (!editable) {
- return;
- }
- QMenu menu;
-
- QAction* selectPicture = new QAction(tr("Select picture ..."), this);
- menu.addAction(selectPicture);
-
- QAction* clearPicture = new QAction(tr("Clear picture"), this);
- menu.addAction(clearPicture);
-
- QAction* result = menu.exec(event->globalPos());
- if (result == selectPicture) {
- QString fileName = QFileDialog::getOpenFileName(this, tr("Select picture"), "", tr("Image Files (*.png *.jpg *.jpeg *.gif)"));
- if (!fileName.isEmpty()) {
- ByteArray data;
- readByteArrayFromFile(data, stringToPath(Q2PSTRING(fileName)));
-
- QBuffer buffer;
- buffer.setData(reinterpret_cast<const char*>(vecptr(data)), data.size());
- buffer.open(QIODevice::ReadOnly);
- QString type = QImageReader::imageFormat(&buffer).toLower();
- if (!type.isEmpty()) {
- type = "image/" + type;
- setAvatar(data, Q2PSTRING(type));
- }
- else {
- QMessageBox::critical(this, tr("Error"), tr("The selected picture is in an unrecognized format"));
- }
- }
- }
- else if (result == clearPicture) {
- setAvatar(ByteArray(), "");
- }
+ if (!editable) {
+ return;
+ }
+ QMenu menu;
+
+ QAction* selectPicture = new QAction(tr("Select picture ..."), this);
+ menu.addAction(selectPicture);
+
+ QAction* clearPicture = new QAction(tr("Clear picture"), this);
+ menu.addAction(clearPicture);
+
+ QAction* result = menu.exec(event->globalPos());
+ if (result == selectPicture) {
+ QString fileName = QFileDialog::getOpenFileName(this, tr("Select picture"), "", tr("Image Files (*.png *.jpg *.jpeg *.gif)"));
+ if (!fileName.isEmpty()) {
+ ByteArray data;
+ readByteArrayFromFile(data, stringToPath(Q2PSTRING(fileName)));
+
+ QBuffer buffer;
+ buffer.setData(reinterpret_cast<const char*>(vecptr(data)), data.size());
+ buffer.open(QIODevice::ReadOnly);
+ QString type = QImageReader::imageFormat(&buffer).toLower();
+ if (!type.isEmpty()) {
+ type = "image/" + type;
+ setAvatar(data, Q2PSTRING(type));
+ }
+ else {
+ QMessageBox::critical(this, tr("Error"), tr("The selected picture is in an unrecognized format"));
+ }
+ }
+ }
+ else if (result == clearPicture) {
+ setAvatar(ByteArray(), "");
+ }
}
diff --git a/Swift/QtUI/QtAvatarWidget.h b/Swift/QtUI/QtAvatarWidget.h
index bcdc7be..612c79b 100644
--- a/Swift/QtUI/QtAvatarWidget.h
+++ b/Swift/QtUI/QtAvatarWidget.h
@@ -14,36 +14,36 @@
class QLabel;
namespace Swift {
- class QtAvatarWidget : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- QtAvatarWidget(QWidget* parent);
-
- void setAvatar(const ByteArray& data, const std::string& type);
-
- const ByteArray& getAvatarData() const {
- return data;
- }
-
- const std::string& getAvatarType() const {
- return type;
- }
-
- void setEditable(bool b) {
- editable = b;
- }
-
- bool isEditable() const {
- return editable;
- }
-
- void mousePressEvent(QMouseEvent* event);
-
- private:
- bool editable;
- ByteArray data;
- std::string type;
- QLabel* label;
- };
+ class QtAvatarWidget : public QWidget {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ public:
+ QtAvatarWidget(QWidget* parent);
+
+ void setAvatar(const ByteArray& data, const std::string& type);
+
+ const ByteArray& getAvatarData() const {
+ return data;
+ }
+
+ const std::string& getAvatarType() const {
+ return type;
+ }
+
+ void setEditable(bool b) {
+ editable = b;
+ }
+
+ bool isEditable() const {
+ return editable;
+ }
+
+ void mousePressEvent(QMouseEvent* event);
+
+ private:
+ bool editable;
+ ByteArray data;
+ std::string type;
+ QLabel* label;
+ };
}
diff --git a/Swift/QtUI/QtBlockListEditorWindow.cpp b/Swift/QtUI/QtBlockListEditorWindow.cpp
index 98c9e98..5b04b49 100644
--- a/Swift/QtUI/QtBlockListEditorWindow.cpp
+++ b/Swift/QtUI/QtBlockListEditorWindow.cpp
@@ -31,197 +31,197 @@
namespace Swift {
class QtJIDValidator : public QValidator {
- public:
- QtJIDValidator(QObject* parent) : QValidator(parent) {}
- virtual ~QtJIDValidator() {}
- virtual QValidator::State validate(QString& input, int&) const {
- return JID(Q2PSTRING(input)).isValid() ? Acceptable : Intermediate;
- }
+ public:
+ QtJIDValidator(QObject* parent) : QValidator(parent) {}
+ virtual ~QtJIDValidator() {}
+ virtual QValidator::State validate(QString& input, int&) const {
+ return JID(Q2PSTRING(input)).isValid() ? Acceptable : Intermediate;
+ }
};
class QtJIDValidatedItemDelegate : public QItemDelegate {
- public:
- QtJIDValidatedItemDelegate(QObject* parent) : QItemDelegate(parent) {}
- virtual ~QtJIDValidatedItemDelegate() {}
-
- virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const {
- QLineEdit *editor = new QLineEdit(parent);
- editor->setValidator(new QtJIDValidator(editor));
- return editor;
- }
-
- void setEditorData(QWidget *editor, const QModelIndex &index) const {
- QString value = index.model()->data(index, Qt::EditRole).toString();
-
- QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
- lineEdit->setText(value);
- }
-
- void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
- QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
- QString currentValue = lineEdit->text();
- int pos = 0;
- if (lineEdit->validator()->validate(currentValue, pos) == QValidator::Acceptable) {
- model->setData(index, lineEdit->text(), Qt::EditRole);
- } else {
- model->setData(index, QString(), Qt::EditRole);
- }
- }
-
- void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const {
- editor->setGeometry(option.rect);
- }
+ public:
+ QtJIDValidatedItemDelegate(QObject* parent) : QItemDelegate(parent) {}
+ virtual ~QtJIDValidatedItemDelegate() {}
+
+ virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const {
+ QLineEdit *editor = new QLineEdit(parent);
+ editor->setValidator(new QtJIDValidator(editor));
+ return editor;
+ }
+
+ void setEditorData(QWidget *editor, const QModelIndex &index) const {
+ QString value = index.model()->data(index, Qt::EditRole).toString();
+
+ QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
+ lineEdit->setText(value);
+ }
+
+ void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
+ QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
+ QString currentValue = lineEdit->text();
+ int pos = 0;
+ if (lineEdit->validator()->validate(currentValue, pos) == QValidator::Acceptable) {
+ model->setData(index, lineEdit->text(), Qt::EditRole);
+ } else {
+ model->setData(index, QString(), Qt::EditRole);
+ }
+ }
+
+ void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const {
+ editor->setGeometry(option.rect);
+ }
};
QtBlockListEditorWindow::QtBlockListEditorWindow() : QWidget(), ui(new Ui::QtBlockListEditorWindow), removeItemDelegate(0), editItemDelegate(0) {
- ui->setupUi(this);
+ ui->setupUi(this);
- freshBlockListTemplate = tr("Double-click to add contact");
+ freshBlockListTemplate = tr("Double-click to add contact");
- new QShortcut(QKeySequence::Close, this, SLOT(close()));
- ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
+ new QShortcut(QKeySequence::Close, this, SLOT(close()));
+ ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
- removeItemDelegate = new QtRemovableItemDelegate(style());
- editItemDelegate = new QtJIDValidatedItemDelegate(this);
+ removeItemDelegate = new QtRemovableItemDelegate(style());
+ editItemDelegate = new QtJIDValidatedItemDelegate(this);
- connect(ui->savePushButton, SIGNAL(clicked()), SLOT(applyChanges()));
+ connect(ui->savePushButton, SIGNAL(clicked()), SLOT(applyChanges()));
- ui->blockListTreeWidget->setColumnCount(2);
- ui->blockListTreeWidget->header()->setStretchLastSection(false);
- ui->blockListTreeWidget->header()->resizeSection(1, removeItemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
+ ui->blockListTreeWidget->setColumnCount(2);
+ ui->blockListTreeWidget->header()->setStretchLastSection(false);
+ ui->blockListTreeWidget->header()->resizeSection(1, removeItemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
#if QT_VERSION >= 0x050000
- ui->blockListTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
+ ui->blockListTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
- ui->blockListTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
+ ui->blockListTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
#endif
- ui->blockListTreeWidget->setHeaderHidden(true);
- ui->blockListTreeWidget->setRootIsDecorated(false);
- ui->blockListTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
- ui->blockListTreeWidget->setItemDelegateForColumn(0, editItemDelegate);
- ui->blockListTreeWidget->setItemDelegateForColumn(1, removeItemDelegate);
- connect(ui->blockListTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int)));
- ui->blockListTreeWidget->installEventFilter(this);
-
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- ui->blockListTreeWidget->addTopLevelItem(item);
+ ui->blockListTreeWidget->setHeaderHidden(true);
+ ui->blockListTreeWidget->setRootIsDecorated(false);
+ ui->blockListTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
+ ui->blockListTreeWidget->setItemDelegateForColumn(0, editItemDelegate);
+ ui->blockListTreeWidget->setItemDelegateForColumn(1, removeItemDelegate);
+ connect(ui->blockListTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int)));
+ ui->blockListTreeWidget->installEventFilter(this);
+
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ ui->blockListTreeWidget->addTopLevelItem(item);
}
QtBlockListEditorWindow::~QtBlockListEditorWindow() {
}
void QtBlockListEditorWindow::show() {
- QWidget::showNormal();
- QWidget::activateWindow();
- QWidget::raise();
+ QWidget::showNormal();
+ QWidget::activateWindow();
+ QWidget::raise();
}
void QtBlockListEditorWindow::hide() {
- QWidget::hide();
+ QWidget::hide();
}
void QtBlockListEditorWindow::handleItemChanged(QTreeWidgetItem *item, int) {
- // check whether changed item contains a valid JID and make it removable
- if (item && item->text(0) != freshBlockListTemplate) {
- item->setText(1, "");
- }
-
- // check for empty rows and add an empty one so the user can add items
- bool hasEmptyRow = false;
- for( int i = 0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i ) {
- QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i);
- if (row->text(0) == freshBlockListTemplate) {
- hasEmptyRow = true;
- }
- else if (row->text(0).isEmpty()) {
- ui->blockListTreeWidget->removeItemWidget(row, 0);
- }
- }
-
- if (!hasEmptyRow) {
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- ui->blockListTreeWidget->addTopLevelItem(item);
- }
-
- if (!item) {
- ui->blockListTreeWidget->setCurrentItem(ui->blockListTreeWidget->topLevelItem(0));
- }
+ // check whether changed item contains a valid JID and make it removable
+ if (item && item->text(0) != freshBlockListTemplate) {
+ item->setText(1, "");
+ }
+
+ // check for empty rows and add an empty one so the user can add items
+ bool hasEmptyRow = false;
+ for( int i = 0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i ) {
+ QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i);
+ if (row->text(0) == freshBlockListTemplate) {
+ hasEmptyRow = true;
+ }
+ else if (row->text(0).isEmpty()) {
+ ui->blockListTreeWidget->removeItemWidget(row, 0);
+ }
+ }
+
+ if (!hasEmptyRow) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ ui->blockListTreeWidget->addTopLevelItem(item);
+ }
+
+ if (!item) {
+ ui->blockListTreeWidget->setCurrentItem(ui->blockListTreeWidget->topLevelItem(0));
+ }
}
void QtBlockListEditorWindow::applyChanges() {
- onSetNewBlockList(getCurrentBlockList());
+ onSetNewBlockList(getCurrentBlockList());
}
void QtBlockListEditorWindow::setCurrentBlockList(const std::vector<JID> &blockedJIDs) {
- ui->blockListTreeWidget->clear();
-
- foreach(const JID& jid, blockedJIDs) {
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << "");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- ui->blockListTreeWidget->addTopLevelItem(item);
- }
- handleItemChanged(0,0);
+ ui->blockListTreeWidget->clear();
+
+ foreach(const JID& jid, blockedJIDs) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ ui->blockListTreeWidget->addTopLevelItem(item);
+ }
+ handleItemChanged(0,0);
}
void QtBlockListEditorWindow::setBusy(bool isBusy) {
- if (isBusy) {
- ui->throbberLabel->movie()->start();
- ui->throbberLabel->show();
- ui->blockListTreeWidget->setEnabled(false);
- ui->savePushButton->setEnabled(false);
- } else {
- ui->throbberLabel->movie()->stop();
- ui->throbberLabel->hide();
- ui->blockListTreeWidget->setEnabled(true);
- ui->savePushButton->setEnabled(true);
- }
+ if (isBusy) {
+ ui->throbberLabel->movie()->start();
+ ui->throbberLabel->show();
+ ui->blockListTreeWidget->setEnabled(false);
+ ui->savePushButton->setEnabled(false);
+ } else {
+ ui->throbberLabel->movie()->stop();
+ ui->throbberLabel->hide();
+ ui->blockListTreeWidget->setEnabled(true);
+ ui->savePushButton->setEnabled(true);
+ }
}
void QtBlockListEditorWindow::setError(const std::string& error) {
- if (!error.empty()) {
- ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
- }
- else {
- ui->errorLabel->setText("");
- }
+ if (!error.empty()) {
+ ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
+ }
+ else {
+ ui->errorLabel->setText("");
+ }
}
std::vector<JID> Swift::QtBlockListEditorWindow::getCurrentBlockList() const {
- std::vector<JID> futureBlockedJIDs;
-
- for(int i=0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i) {
- QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i);
- JID jid = JID(Q2PSTRING(row->text(0)));
- if (!jid.toString().empty() && jid.isValid()) {
- futureBlockedJIDs.push_back(jid);
- }
- }
- return futureBlockedJIDs;
+ std::vector<JID> futureBlockedJIDs;
+
+ for(int i=0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i) {
+ QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i);
+ JID jid = JID(Q2PSTRING(row->text(0)));
+ if (!jid.toString().empty() && jid.isValid()) {
+ futureBlockedJIDs.push_back(jid);
+ }
+ }
+ return futureBlockedJIDs;
}
bool QtBlockListEditorWindow::eventFilter(QObject* target, QEvent* event) {
- if (target == ui->blockListTreeWidget) {
- if (event->type() == QEvent::KeyPress) {
- QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
- if (keyEvent->key() == Qt::Key_Backspace) {
- // remove currently selected item
- QTreeWidgetItem* currentItem = ui->blockListTreeWidget->currentItem();
- if (currentItem->text(0) != freshBlockListTemplate) {
- ui->blockListTreeWidget->takeTopLevelItem(ui->blockListTreeWidget->indexOfTopLevelItem(currentItem));
- return true;
- }
- }
- else if (keyEvent->key() == Qt::Key_Return) {
- // open editor for return key d
- ui->blockListTreeWidget->editItem(ui->blockListTreeWidget->currentItem(), 0);
- return true;
- }
- }
- }
- return QWidget::eventFilter(target, event);
+ if (target == ui->blockListTreeWidget) {
+ if (event->type() == QEvent::KeyPress) {
+ QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
+ if (keyEvent->key() == Qt::Key_Backspace) {
+ // remove currently selected item
+ QTreeWidgetItem* currentItem = ui->blockListTreeWidget->currentItem();
+ if (currentItem->text(0) != freshBlockListTemplate) {
+ ui->blockListTreeWidget->takeTopLevelItem(ui->blockListTreeWidget->indexOfTopLevelItem(currentItem));
+ return true;
+ }
+ }
+ else if (keyEvent->key() == Qt::Key_Return) {
+ // open editor for return key d
+ ui->blockListTreeWidget->editItem(ui->blockListTreeWidget->currentItem(), 0);
+ return true;
+ }
+ }
+ }
+ return QWidget::eventFilter(target, event);
}
}
diff --git a/Swift/QtUI/QtBlockListEditorWindow.h b/Swift/QtUI/QtBlockListEditorWindow.h
index a594210..dc900ab 100644
--- a/Swift/QtUI/QtBlockListEditorWindow.h
+++ b/Swift/QtUI/QtBlockListEditorWindow.h
@@ -20,7 +20,7 @@
#include <Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h>
namespace Ui {
- class QtBlockListEditorWindow;
+ class QtBlockListEditorWindow;
}
namespace Swift {
@@ -28,29 +28,29 @@ namespace Swift {
class QtJIDValidatedItemDelegate;
class QtBlockListEditorWindow : public QWidget, public BlockListEditorWidget {
- Q_OBJECT
-
- public:
- QtBlockListEditorWindow();
- virtual ~QtBlockListEditorWindow();
-
- virtual void show();
- virtual void hide();
- virtual void setCurrentBlockList(const std::vector<JID>& blockedJIDs);
- virtual void setBusy(bool isBusy);
- virtual void setError(const std::string& error);
- virtual std::vector<JID> getCurrentBlockList() const;
- virtual bool eventFilter(QObject* target, QEvent* event);
-
- private slots:
- void handleItemChanged(QTreeWidgetItem*, int);
- void applyChanges();
-
- private:
- Ui::QtBlockListEditorWindow* ui;
- QtRemovableItemDelegate* removeItemDelegate;
- QtJIDValidatedItemDelegate* editItemDelegate;
- QString freshBlockListTemplate;
+ Q_OBJECT
+
+ public:
+ QtBlockListEditorWindow();
+ virtual ~QtBlockListEditorWindow();
+
+ virtual void show();
+ virtual void hide();
+ virtual void setCurrentBlockList(const std::vector<JID>& blockedJIDs);
+ virtual void setBusy(bool isBusy);
+ virtual void setError(const std::string& error);
+ virtual std::vector<JID> getCurrentBlockList() const;
+ virtual bool eventFilter(QObject* target, QEvent* event);
+
+ private slots:
+ void handleItemChanged(QTreeWidgetItem*, int);
+ void applyChanges();
+
+ private:
+ Ui::QtBlockListEditorWindow* ui;
+ QtRemovableItemDelegate* removeItemDelegate;
+ QtJIDValidatedItemDelegate* editItemDelegate;
+ QString freshBlockListTemplate;
};
}
diff --git a/Swift/QtUI/QtBookmarkDetailWindow.cpp b/Swift/QtUI/QtBookmarkDetailWindow.cpp
index ea5b217..920e94e 100644
--- a/Swift/QtUI/QtBookmarkDetailWindow.cpp
+++ b/Swift/QtUI/QtBookmarkDetailWindow.cpp
@@ -13,67 +13,67 @@
namespace Swift {
QtBookmarkDetailWindow::QtBookmarkDetailWindow(QWidget* parent) : QDialog(parent) {
- setupUi(this);
- setAttribute(Qt::WA_DeleteOnClose, true);
- //connect(buttons_, SIGNAL(accepted()), SLOT(accept()));
- //connect(buttons_, SIGNAL(rejected()), SLOT(reject()));
- setFixedHeight(sizeHint().height());
+ setupUi(this);
+ setAttribute(Qt::WA_DeleteOnClose, true);
+ //connect(buttons_, SIGNAL(accepted()), SLOT(accept()));
+ //connect(buttons_, SIGNAL(rejected()), SLOT(reject()));
+ setFixedHeight(sizeHint().height());
}
void QtBookmarkDetailWindow::accept() {
- if (commit()) {
- QDialog::accept();
- }
+ if (commit()) {
+ QDialog::accept();
+ }
}
boost::optional<MUCBookmark> QtBookmarkDetailWindow::createBookmarkFromForm() {
- //check room
- //check bookmarkName
- JID room(Q2PSTRING(room_->text()));
- if (!room.isValid() || room.getNode().empty() || !room.getResource().empty()) {
- QMessageBox::warning(this, tr("Bookmark not valid"), tr("You must specify a valid room address (e.g. someroom@rooms.example.com)."));
- return boost::optional<MUCBookmark>();
- }
- std::string name(Q2PSTRING(name_->text()));
- if (name.empty()) {
- name = room.toString();
- }
+ //check room
+ //check bookmarkName
+ JID room(Q2PSTRING(room_->text()));
+ if (!room.isValid() || room.getNode().empty() || !room.getResource().empty()) {
+ QMessageBox::warning(this, tr("Bookmark not valid"), tr("You must specify a valid room address (e.g. someroom@rooms.example.com)."));
+ return boost::optional<MUCBookmark>();
+ }
+ std::string name(Q2PSTRING(name_->text()));
+ if (name.empty()) {
+ name = room.toString();
+ }
- MUCBookmark bookmark(room, name);
- std::string nick(Q2PSTRING(nick_->text()));
- std::string password(Q2PSTRING(password_->text()));
- bookmark.setAutojoin(autojoin_->isChecked());
- if (!nick.empty()) {
- bookmark.setNick(nick);
- }
- if (!password.empty()) {
- bookmark.setPassword(password);
- }
- return bookmark;
+ MUCBookmark bookmark(room, name);
+ std::string nick(Q2PSTRING(nick_->text()));
+ std::string password(Q2PSTRING(password_->text()));
+ bookmark.setAutojoin(autojoin_->isChecked());
+ if (!nick.empty()) {
+ bookmark.setNick(nick);
+ }
+ if (!password.empty()) {
+ bookmark.setPassword(password);
+ }
+ return bookmark;
}
void QtBookmarkDetailWindow::createFormFromBookmark(const MUCBookmark& bookmark) {
- if (bookmark.getRoom().isValid()) {
- room_->setText(P2QSTRING(bookmark.getRoom().toString()));
- }
+ if (bookmark.getRoom().isValid()) {
+ room_->setText(P2QSTRING(bookmark.getRoom().toString()));
+ }
- if (!bookmark.getName().empty()) {
- name_->setText(P2QSTRING(bookmark.getName()));
- }
+ if (!bookmark.getName().empty()) {
+ name_->setText(P2QSTRING(bookmark.getName()));
+ }
- if (bookmark.getNick()) {
- nick_->setText(P2QSTRING((*bookmark.getNick())));
- }
+ if (bookmark.getNick()) {
+ nick_->setText(P2QSTRING((*bookmark.getNick())));
+ }
- if (bookmark.getPassword()) {
- password_->setText(P2QSTRING((*bookmark.getPassword())));
- }
+ if (bookmark.getPassword()) {
+ password_->setText(P2QSTRING((*bookmark.getPassword())));
+ }
- if (bookmark.getAutojoin()) {
- autojoin_->setCheckState(Qt::Checked);
- } else {
- autojoin_->setCheckState(Qt::Unchecked);
- }
+ if (bookmark.getAutojoin()) {
+ autojoin_->setCheckState(Qt::Checked);
+ } else {
+ autojoin_->setCheckState(Qt::Unchecked);
+ }
}
}
diff --git a/Swift/QtUI/QtBookmarkDetailWindow.h b/Swift/QtUI/QtBookmarkDetailWindow.h
index 427614a..19c6462 100644
--- a/Swift/QtUI/QtBookmarkDetailWindow.h
+++ b/Swift/QtUI/QtBookmarkDetailWindow.h
@@ -15,18 +15,18 @@
#include <Swift/QtUI/ui_QtBookmarkDetailWindow.h>
namespace Swift {
- class QtBookmarkDetailWindow : public QDialog, protected Ui::QtBookmarkDetailWindow {
- Q_OBJECT
- public:
- QtBookmarkDetailWindow(QWidget* parent = NULL);
- virtual bool commit() = 0;
- boost::optional<MUCBookmark> createBookmarkFromForm();
-
- protected:
- void createFormFromBookmark(const MUCBookmark& bookmark);
-
- public slots:
- void accept();
- };
+ class QtBookmarkDetailWindow : public QDialog, protected Ui::QtBookmarkDetailWindow {
+ Q_OBJECT
+ public:
+ QtBookmarkDetailWindow(QWidget* parent = NULL);
+ virtual bool commit() = 0;
+ boost::optional<MUCBookmark> createBookmarkFromForm();
+
+ protected:
+ void createFormFromBookmark(const MUCBookmark& bookmark);
+
+ public slots:
+ void accept();
+ };
}
diff --git a/Swift/QtUI/QtCachedImageScaler.cpp b/Swift/QtUI/QtCachedImageScaler.cpp
index 0e10062..e1f540b 100644
--- a/Swift/QtUI/QtCachedImageScaler.cpp
+++ b/Swift/QtUI/QtCachedImageScaler.cpp
@@ -20,25 +20,25 @@ QtCachedImageScaler::QtCachedImageScaler() {
}
boost::filesystem::path QtCachedImageScaler::getScaledImage(const boost::filesystem::path& imagePath, int size) {
- boost::filesystem::path scaledImagePath(imagePath);
- std::string suffix = "." + boost::lexical_cast<std::string>(size);
- scaledImagePath = stringToPath(pathToString(scaledImagePath) + suffix);
- if (!boost::filesystem::exists(scaledImagePath)) {
- QImage image(P2QSTRING(pathToString(imagePath)));
- if (!image.isNull()) {
- if (image.width() > size || image.height() > size) {
- QImage scaledImage = image.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
- scaledImage.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
- }
- else {
- image.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
- }
- }
- else {
- return imagePath;
- }
- }
- return scaledImagePath;
+ boost::filesystem::path scaledImagePath(imagePath);
+ std::string suffix = "." + boost::lexical_cast<std::string>(size);
+ scaledImagePath = stringToPath(pathToString(scaledImagePath) + suffix);
+ if (!boost::filesystem::exists(scaledImagePath)) {
+ QImage image(P2QSTRING(pathToString(imagePath)));
+ if (!image.isNull()) {
+ if (image.width() > size || image.height() > size) {
+ QImage scaledImage = image.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ scaledImage.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
+ }
+ else {
+ image.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
+ }
+ }
+ else {
+ return imagePath;
+ }
+ }
+ return scaledImagePath;
}
diff --git a/Swift/QtUI/QtCachedImageScaler.h b/Swift/QtUI/QtCachedImageScaler.h
index fcc2a2d..15d868e 100644
--- a/Swift/QtUI/QtCachedImageScaler.h
+++ b/Swift/QtUI/QtCachedImageScaler.h
@@ -9,11 +9,11 @@
#include <boost/filesystem.hpp>
namespace Swift {
- class QtCachedImageScaler {
- public:
- QtCachedImageScaler();
+ class QtCachedImageScaler {
+ public:
+ QtCachedImageScaler();
- boost::filesystem::path getScaledImage(const boost::filesystem::path& image, int size);
- };
+ boost::filesystem::path getScaledImage(const boost::filesystem::path& image, int size);
+ };
}
diff --git a/Swift/QtUI/QtCertificateViewerDialog.cpp b/Swift/QtUI/QtCertificateViewerDialog.cpp
index 4b8b0cb..a99c29a 100644
--- a/Swift/QtUI/QtCertificateViewerDialog.cpp
+++ b/Swift/QtUI/QtCertificateViewerDialog.cpp
@@ -25,126 +25,126 @@
namespace Swift {
QtCertificateViewerDialog::QtCertificateViewerDialog(QWidget* parent) : QDialog(parent), ui(new Ui::QtCertificateViewerDialog) {
- ui->setupUi(this);
- connect(ui->certChainTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
+ ui->setupUi(this);
+ connect(ui->certChainTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
- setAttribute(Qt::WA_DeleteOnClose);
+ setAttribute(Qt::WA_DeleteOnClose);
}
QtCertificateViewerDialog::~QtCertificateViewerDialog() {
- delete ui;
+ delete ui;
}
void QtCertificateViewerDialog::setCertificateChain(const std::vector<Certificate::ref>& chain) {
- // clean widgets
- ui->certChainTreeWidget->clear();
-
- if (chain.empty()) return;
-
- // convert Swift certificate chain to qt certificate chain (root goes first)
- currentChain.clear();
- foreach(Certificate::ref cert, chain) {
- ByteArray certAsDer = cert->toDER();
- QByteArray dataArray(reinterpret_cast<const char*>(certAsDer.data()), certAsDer.size());
- currentChain.push_front(QSslCertificate(dataArray, QSsl::Der));
- }
-
- // fill treeWidget
- QTreeWidgetItem* root = new QTreeWidgetItem(ui->certChainTreeWidget, QStringList(currentChain.at(0).subjectInfo(QSslCertificate::CommonName)));
- root->setData(0, Qt::UserRole, QVariant(0));
- root->setExpanded(true);
- ui->certChainTreeWidget->addTopLevelItem(root);
- if (currentChain.size() > 1) {
- QTreeWidgetItem* parent = root;
- for (int n = 1; n < currentChain.size(); n++) {
- QTreeWidgetItem* link = new QTreeWidgetItem(parent, QStringList(QString("↳ ") + (QStringList(currentChain.at(n).subjectInfo(QSslCertificate::CommonName)).join(", "))));
- link->setExpanded(true);
- link->setData(0, Qt::UserRole, QVariant(n));
- parent = link;
- }
- ui->certChainTreeWidget->setCurrentItem(parent);
- } else {
- ui->certChainTreeWidget->setCurrentItem(root);
- }
+ // clean widgets
+ ui->certChainTreeWidget->clear();
+
+ if (chain.empty()) return;
+
+ // convert Swift certificate chain to qt certificate chain (root goes first)
+ currentChain.clear();
+ foreach(Certificate::ref cert, chain) {
+ ByteArray certAsDer = cert->toDER();
+ QByteArray dataArray(reinterpret_cast<const char*>(certAsDer.data()), certAsDer.size());
+ currentChain.push_front(QSslCertificate(dataArray, QSsl::Der));
+ }
+
+ // fill treeWidget
+ QTreeWidgetItem* root = new QTreeWidgetItem(ui->certChainTreeWidget, QStringList(currentChain.at(0).subjectInfo(QSslCertificate::CommonName)));
+ root->setData(0, Qt::UserRole, QVariant(0));
+ root->setExpanded(true);
+ ui->certChainTreeWidget->addTopLevelItem(root);
+ if (currentChain.size() > 1) {
+ QTreeWidgetItem* parent = root;
+ for (int n = 1; n < currentChain.size(); n++) {
+ QTreeWidgetItem* link = new QTreeWidgetItem(parent, QStringList(QString("↳ ") + (QStringList(currentChain.at(n).subjectInfo(QSslCertificate::CommonName)).join(", "))));
+ link->setExpanded(true);
+ link->setData(0, Qt::UserRole, QVariant(n));
+ parent = link;
+ }
+ ui->certChainTreeWidget->setCurrentItem(parent);
+ } else {
+ ui->certChainTreeWidget->setCurrentItem(root);
+ }
}
void QtCertificateViewerDialog::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
- QtCertificateViewerDialog* dialog = new QtCertificateViewerDialog(parent);
- dialog->setCertificateChain(chain);
- dialog->show();
+ QtCertificateViewerDialog* dialog = new QtCertificateViewerDialog(parent);
+ dialog->setCertificateChain(chain);
+ dialog->show();
}
void QtCertificateViewerDialog::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem*) {
- setCertificateDetails(currentChain.at(current->data(0, Qt::UserRole).toInt()));
+ setCertificateDetails(currentChain.at(current->data(0, Qt::UserRole).toInt()));
}
#define ADD_SECTION( TITLE ) \
- ui->certGridLayout->addWidget(new QLabel("<strong>" + TITLE + "</strong>"), rowCount++, 0, 1, 2);
+ ui->certGridLayout->addWidget(new QLabel("<strong>" + TITLE + "</strong>"), rowCount++, 0, 1, 2);
#define ADD_FIELD( TITLE, VALUE) \
- ui->certGridLayout->addWidget(new QLabel(TITLE), rowCount, 0, 1, 1, Qt::AlignRight); \
- valueLabel = new QLabel(); \
- valueLabel->setText(QStringList(VALUE).join(", ")); \
- valueLabel->setTextFormat(Qt::PlainText); \
- valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); \
- ui->certGridLayout->addWidget(valueLabel, rowCount++, 1, 1, 1, Qt::AlignLeft);
+ ui->certGridLayout->addWidget(new QLabel(TITLE), rowCount, 0, 1, 1, Qt::AlignRight); \
+ valueLabel = new QLabel(); \
+ valueLabel->setText(QStringList(VALUE).join(", ")); \
+ valueLabel->setTextFormat(Qt::PlainText); \
+ valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); \
+ ui->certGridLayout->addWidget(valueLabel, rowCount++, 1, 1, 1, Qt::AlignLeft);
void QtCertificateViewerDialog::setCertificateDetails(const QSslCertificate& cert) {
- QLayoutItem* item;
- while ((item = ui->certGridLayout->takeAt(0)) != NULL ) {
- delete item->widget();
- delete item;
- }
+ QLayoutItem* item;
+ while ((item = ui->certGridLayout->takeAt(0)) != NULL ) {
+ delete item->widget();
+ delete item;
+ }
- int rowCount = 0;
+ int rowCount = 0;
- ui->certGridLayout->setColumnStretch(2, 1);
+ ui->certGridLayout->setColumnStretch(2, 1);
- QLabel* valueLabel = 0;
+ QLabel* valueLabel = 0;
- ADD_SECTION(tr("General"));
- ADD_FIELD(tr("Valid From"), cert.effectiveDate().toString(Qt::TextDate));
- ADD_FIELD(tr("Valid To"), cert.expiryDate().toString(Qt::TextDate));
- ADD_FIELD(tr("Serial Number"), QString(cert.serialNumber().toHex()));
- ADD_FIELD(tr("Version"), QString(cert.version()));
+ ADD_SECTION(tr("General"));
+ ADD_FIELD(tr("Valid From"), cert.effectiveDate().toString(Qt::TextDate));
+ ADD_FIELD(tr("Valid To"), cert.expiryDate().toString(Qt::TextDate));
+ ADD_FIELD(tr("Serial Number"), QString(cert.serialNumber().toHex()));
+ ADD_FIELD(tr("Version"), QString(cert.version()));
- ADD_SECTION(tr("Subject"));
- ADD_FIELD(tr("Organization"), cert.subjectInfo(QSslCertificate::Organization));
- ADD_FIELD(tr("Common Name"), cert.subjectInfo(QSslCertificate::CommonName));
- ADD_FIELD(tr("Locality"), cert.subjectInfo(QSslCertificate::LocalityName));
- ADD_FIELD(tr("Organizational Unit"), cert.subjectInfo(QSslCertificate::OrganizationalUnitName));
- ADD_FIELD(tr("Country"), cert.subjectInfo(QSslCertificate::CountryName));
- ADD_FIELD(tr("State"), cert.subjectInfo(QSslCertificate::StateOrProvinceName));
+ ADD_SECTION(tr("Subject"));
+ ADD_FIELD(tr("Organization"), cert.subjectInfo(QSslCertificate::Organization));
+ ADD_FIELD(tr("Common Name"), cert.subjectInfo(QSslCertificate::CommonName));
+ ADD_FIELD(tr("Locality"), cert.subjectInfo(QSslCertificate::LocalityName));
+ ADD_FIELD(tr("Organizational Unit"), cert.subjectInfo(QSslCertificate::OrganizationalUnitName));
+ ADD_FIELD(tr("Country"), cert.subjectInfo(QSslCertificate::CountryName));
+ ADD_FIELD(tr("State"), cert.subjectInfo(QSslCertificate::StateOrProvinceName));
#if QT_VERSION < 0x050000
- QMultiMap<QSsl::AlternateNameEntryType, QString> altNames = cert.alternateSubjectNames();
+ QMultiMap<QSsl::AlternateNameEntryType, QString> altNames = cert.alternateSubjectNames();
#define SANTYPE QSsl::AlternateNameEntryType
#else
- QMultiMap<QSsl::AlternativeNameEntryType, QString> altNames = cert.subjectAlternativeNames();
+ QMultiMap<QSsl::AlternativeNameEntryType, QString> altNames = cert.subjectAlternativeNames();
#define SANTYPE QSsl::AlternativeNameEntryType
#endif
- if (!altNames.empty()) {
- ADD_SECTION(tr("Alternate Subject Names"));
- foreach (const SANTYPE &type, altNames.uniqueKeys()) {
- foreach (QString name, altNames.values(type)) {
- if (type == QSsl::EmailEntry) {
- ADD_FIELD(tr("E-mail Address"), name);
- } else {
- ADD_FIELD(tr("DNS Name"), name);
- }
- }
- }
- }
-
- ADD_SECTION(tr("Issuer"));
- ADD_FIELD(tr("Organization"), cert.issuerInfo(QSslCertificate::Organization));
- ADD_FIELD(tr("Common Name"), cert.issuerInfo(QSslCertificate::CommonName));
- ADD_FIELD(tr("Locality"), cert.issuerInfo(QSslCertificate::LocalityName));
- ADD_FIELD(tr("Organizational Unit"), cert.issuerInfo(QSslCertificate::OrganizationalUnitName));
- ADD_FIELD(tr("Country"), cert.issuerInfo(QSslCertificate::CountryName));
- ADD_FIELD(tr("State"), cert.issuerInfo(QSslCertificate::StateOrProvinceName));
-
- ui->certGridLayout->setRowStretch(rowCount + 1, 1);
+ if (!altNames.empty()) {
+ ADD_SECTION(tr("Alternate Subject Names"));
+ foreach (const SANTYPE &type, altNames.uniqueKeys()) {
+ foreach (QString name, altNames.values(type)) {
+ if (type == QSsl::EmailEntry) {
+ ADD_FIELD(tr("E-mail Address"), name);
+ } else {
+ ADD_FIELD(tr("DNS Name"), name);
+ }
+ }
+ }
+ }
+
+ ADD_SECTION(tr("Issuer"));
+ ADD_FIELD(tr("Organization"), cert.issuerInfo(QSslCertificate::Organization));
+ ADD_FIELD(tr("Common Name"), cert.issuerInfo(QSslCertificate::CommonName));
+ ADD_FIELD(tr("Locality"), cert.issuerInfo(QSslCertificate::LocalityName));
+ ADD_FIELD(tr("Organizational Unit"), cert.issuerInfo(QSslCertificate::OrganizationalUnitName));
+ ADD_FIELD(tr("Country"), cert.issuerInfo(QSslCertificate::CountryName));
+ ADD_FIELD(tr("State"), cert.issuerInfo(QSslCertificate::StateOrProvinceName));
+
+ ui->certGridLayout->setRowStretch(rowCount + 1, 1);
}
}
diff --git a/Swift/QtUI/QtCertificateViewerDialog.h b/Swift/QtUI/QtCertificateViewerDialog.h
index 9475a83..7b72f1d 100644
--- a/Swift/QtUI/QtCertificateViewerDialog.h
+++ b/Swift/QtUI/QtCertificateViewerDialog.h
@@ -20,25 +20,25 @@ class QtCertificateViewerDialog;
namespace Swift {
class QtCertificateViewerDialog : public QDialog {
- Q_OBJECT
-
- public:
- explicit QtCertificateViewerDialog(QWidget* parent = 0);
- ~QtCertificateViewerDialog();
+ Q_OBJECT
- void setCertificateChain(const std::vector<Certificate::ref>& chain);
+ public:
+ explicit QtCertificateViewerDialog(QWidget* parent = 0);
+ ~QtCertificateViewerDialog();
- static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
+ void setCertificateChain(const std::vector<Certificate::ref>& chain);
- private slots:
- void currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*);
+ static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
- private:
- void setCertificateDetails(const QSslCertificate& cert);
+ private slots:
+ void currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*);
- private:
- Ui::QtCertificateViewerDialog *ui;
- QList<QSslCertificate> currentChain;
+ private:
+ void setCertificateDetails(const QSslCertificate& cert);
+
+ private:
+ Ui::QtCertificateViewerDialog *ui;
+ QList<QSslCertificate> currentChain;
};
}
diff --git a/Swift/QtUI/QtChatTabs.cpp b/Swift/QtUI/QtChatTabs.cpp
index f22d869..4a77ffd 100644
--- a/Swift/QtUI/QtChatTabs.cpp
+++ b/Swift/QtUI/QtChatTabs.cpp
@@ -35,389 +35,389 @@
namespace Swift {
QtChatTabs::QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode) : QWidget(), singleWindow_(singleWindow), settingsProvider_(settingsProvider), trellisMode_(trellisMode), dynamicGrid_(NULL), gridSelectionDialog_(NULL) {
#ifndef Q_OS_MAC
- setWindowIcon(QIcon(":/logo-chat-16.png"));
+ setWindowIcon(QIcon(":/logo-chat-16.png"));
#else
- setAttribute(Qt::WA_ShowWithoutActivating);
+ setAttribute(Qt::WA_ShowWithoutActivating);
#endif
- dynamicGrid_ = new QtDynamicGridLayout(this, trellisMode);
- connect(dynamicGrid_, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
- connect(dynamicGrid_, SIGNAL(onCurrentIndexChanged(int)), this, SLOT(handleCurrentTabIndexChanged(int)));
-
- QVBoxLayout *layout = new QVBoxLayout;
- layout->setSpacing(0);
- layout->setContentsMargins(0, 0, 0, 0);
- layout->addWidget(dynamicGrid_);
- setLayout(layout);
-
- if (trellisMode) {
- // restore size
- std::string gridSizeString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_SIZE);
- if (!gridSizeString.empty()) {
- QByteArray gridSizeData = QByteArray::fromBase64(P2QSTRING(gridSizeString).toUtf8());
- QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
- QSize gridSize(1,1);
- dataStreamGridSize >> gridSize;
- dynamicGrid_->setDimensions(gridSize);
- }
-
- // restore positions
- std::string tabPositionsString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_POSITIONS);
- if (!tabPositionsString.empty()) {
- QByteArray tabPositionsData = QByteArray::fromBase64(P2QSTRING(tabPositionsString).toUtf8());
- QDataStream inTabPositions(&tabPositionsData, QIODevice::ReadWrite);
- QHash<QString, QPoint> tabPositions;
- inTabPositions >> tabPositions;
- dynamicGrid_->setTabPositions(tabPositions);
- }
- }
-
- gridSelectionDialog_ = new QtGridSelectionDialog();
-
- // setup shortcuts
- shortcuts_ << new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), window(), SLOT(handleCloseTabShortcut()));
- shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), window(), SLOT(handleRequestedPreviousTab()));
- shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), window(), SLOT(handleRequestedNextTab()));
- shortcuts_ << new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), window(), SLOT(handleRequestedActiveTab()));
+ dynamicGrid_ = new QtDynamicGridLayout(this, trellisMode);
+ connect(dynamicGrid_, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
+ connect(dynamicGrid_, SIGNAL(onCurrentIndexChanged(int)), this, SLOT(handleCurrentTabIndexChanged(int)));
+
+ QVBoxLayout *layout = new QVBoxLayout;
+ layout->setSpacing(0);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->addWidget(dynamicGrid_);
+ setLayout(layout);
+
+ if (trellisMode) {
+ // restore size
+ std::string gridSizeString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_SIZE);
+ if (!gridSizeString.empty()) {
+ QByteArray gridSizeData = QByteArray::fromBase64(P2QSTRING(gridSizeString).toUtf8());
+ QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
+ QSize gridSize(1,1);
+ dataStreamGridSize >> gridSize;
+ dynamicGrid_->setDimensions(gridSize);
+ }
+
+ // restore positions
+ std::string tabPositionsString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_POSITIONS);
+ if (!tabPositionsString.empty()) {
+ QByteArray tabPositionsData = QByteArray::fromBase64(P2QSTRING(tabPositionsString).toUtf8());
+ QDataStream inTabPositions(&tabPositionsData, QIODevice::ReadWrite);
+ QHash<QString, QPoint> tabPositions;
+ inTabPositions >> tabPositions;
+ dynamicGrid_->setTabPositions(tabPositions);
+ }
+ }
+
+ gridSelectionDialog_ = new QtGridSelectionDialog();
+
+ // setup shortcuts
+ shortcuts_ << new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), window(), SLOT(handleCloseTabShortcut()));
+ shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), window(), SLOT(handleRequestedPreviousTab()));
+ shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), window(), SLOT(handleRequestedNextTab()));
+ shortcuts_ << new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), window(), SLOT(handleRequestedActiveTab()));
}
QtChatTabs::~QtChatTabs() {
- foreach (QShortcut* shortcut, shortcuts_) {
- delete shortcut;
- }
-
- if (trellisMode_) {
- storeTabPositions();
- }
- delete gridSelectionDialog_;
+ foreach (QShortcut* shortcut, shortcuts_) {
+ delete shortcut;
+ }
+
+ if (trellisMode_) {
+ storeTabPositions();
+ }
+ delete gridSelectionDialog_;
}
void QtChatTabs::closeEvent(QCloseEvent* event) {
- //Hide first to prevent flickering as each tab is removed.
- hide();
- if (trellisMode_) {
- storeTabPositions();
- }
-
- for (int i = dynamicGrid_->count() - 1; i >= 0; i--) {
- dynamicGrid_->widget(i)->close();
- }
- event->accept();
+ //Hide first to prevent flickering as each tab is removed.
+ hide();
+ if (trellisMode_) {
+ storeTabPositions();
+ }
+
+ for (int i = dynamicGrid_->count() - 1; i >= 0; i--) {
+ dynamicGrid_->widget(i)->close();
+ }
+ event->accept();
}
QtTabbable* QtChatTabs::getCurrentTab() {
- return qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget());
+ return qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget());
}
void QtChatTabs::setViewMenu(QMenu* viewMenu) {
- if (trellisMode_) {
- viewMenu->addSeparator();
- QAction* action = new QAction(tr("Change &layout"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Alt+L")));
- connect(action, SIGNAL(triggered()), this, SLOT(handleOpenLayoutChangeDialog()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab right"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgDown")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabRight()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab left"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgUp")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabLeft()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab to next group"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgDown")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToNextGroup()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab to previous group"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgUp")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToPreviousGroup()));
- viewMenu->addAction(action);
- }
+ if (trellisMode_) {
+ viewMenu->addSeparator();
+ QAction* action = new QAction(tr("Change &layout"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Alt+L")));
+ connect(action, SIGNAL(triggered()), this, SLOT(handleOpenLayoutChangeDialog()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab right"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgDown")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabRight()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab left"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgUp")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabLeft()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab to next group"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgDown")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToNextGroup()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab to previous group"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgUp")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToPreviousGroup()));
+ viewMenu->addAction(action);
+ }
}
void QtChatTabs::addTab(QtTabbable* tab) {
- QSizePolicy policy = sizePolicy();
- /* Chat windows like to grow - don't let them */
- setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- dynamicGrid_->addTab(tab, tab->windowTitle());
- connect(tab, SIGNAL(titleUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
- connect(tab, SIGNAL(countUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
- connect(tab, SIGNAL(windowClosing()), this, SLOT(handleTabClosing()), Qt::UniqueConnection);
- connect(tab, SIGNAL(windowOpening()), this, SLOT(handleWidgetShown()), Qt::UniqueConnection);
- connect(tab, SIGNAL(wantsToActivate()), this, SLOT(handleWantsToActivate()), Qt::UniqueConnection);
- connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection);
- connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection);
- connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection);
- connect(tab, SIGNAL(requestFlash()), this, SLOT(flash()), Qt::UniqueConnection);
- setSizePolicy(policy);
+ QSizePolicy policy = sizePolicy();
+ /* Chat windows like to grow - don't let them */
+ setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
+ dynamicGrid_->addTab(tab, tab->windowTitle());
+ connect(tab, SIGNAL(titleUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(countUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(windowClosing()), this, SLOT(handleTabClosing()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(windowOpening()), this, SLOT(handleWidgetShown()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(wantsToActivate()), this, SLOT(handleWantsToActivate()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(requestFlash()), this, SLOT(flash()), Qt::UniqueConnection);
+ setSizePolicy(policy);
}
void QtChatTabs::handleWidgetShown() {
- QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
- if (!widget) {
- return;
- }
- checkForFirstShow();
- if (dynamicGrid_->indexOf(widget) >= 0) {
- handleTabTitleUpdated(widget);
- return;
- }
- widget->blockSignals(true);
- addTab(widget);
- widget->blockSignals(false);
- show();
+ QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
+ if (!widget) {
+ return;
+ }
+ checkForFirstShow();
+ if (dynamicGrid_->indexOf(widget) >= 0) {
+ handleTabTitleUpdated(widget);
+ return;
+ }
+ widget->blockSignals(true);
+ addTab(widget);
+ widget->blockSignals(false);
+ show();
}
void QtChatTabs::handleCurrentTabIndexChanged(int newIndex) {
- handleTabTitleUpdated(dynamicGrid_->widget(newIndex));
+ handleTabTitleUpdated(dynamicGrid_->widget(newIndex));
}
void QtChatTabs::handleWantsToActivate() {
- QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
- Q_ASSERT(widget);
- //Un-minimize and bring to front.
- setWindowState(windowState() & ~Qt::WindowMinimized);
- setWindowState(windowState() | Qt::WindowActive);
- show();
- widget->show();
- dynamicGrid_->setCurrentWidget(widget);
- handleTabTitleUpdated(widget);
- widget->setFocus();
- raise();
- activateWindow();
+ QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
+ Q_ASSERT(widget);
+ //Un-minimize and bring to front.
+ setWindowState(windowState() & ~Qt::WindowMinimized);
+ setWindowState(windowState() | Qt::WindowActive);
+ show();
+ widget->show();
+ dynamicGrid_->setCurrentWidget(widget);
+ handleTabTitleUpdated(widget);
+ widget->setFocus();
+ raise();
+ activateWindow();
}
void QtChatTabs::handleTabClosing() {
- QWidget* widget = qobject_cast<QWidget*>(sender());
- int index;
- if (widget && ((index = dynamicGrid_->indexOf(widget)) >= 0)) {
- dynamicGrid_->removeTab(index);
- if (dynamicGrid_->count() == 0) {
- if (!singleWindow_) {
- hide();
- }
- else {
- setWindowTitle("");
- onTitleChanged("");
- }
- }
- else {
- handleTabTitleUpdated(dynamicGrid_->currentWidget());
- }
- }
+ QWidget* widget = qobject_cast<QWidget*>(sender());
+ int index;
+ if (widget && ((index = dynamicGrid_->indexOf(widget)) >= 0)) {
+ dynamicGrid_->removeTab(index);
+ if (dynamicGrid_->count() == 0) {
+ if (!singleWindow_) {
+ hide();
+ }
+ else {
+ setWindowTitle("");
+ onTitleChanged("");
+ }
+ }
+ else {
+ handleTabTitleUpdated(dynamicGrid_->currentWidget());
+ }
+ }
}
void QtChatTabs::handleRequestedPreviousTab() {
- int newIndex = dynamicGrid_->currentIndex() - 1;
- dynamicGrid_->setCurrentIndex(newIndex >= 0 ? newIndex : dynamicGrid_->count() - 1);
+ int newIndex = dynamicGrid_->currentIndex() - 1;
+ dynamicGrid_->setCurrentIndex(newIndex >= 0 ? newIndex : dynamicGrid_->count() - 1);
}
void QtChatTabs::handleRequestedNextTab() {
- int newIndex = dynamicGrid_->currentIndex() + 1;
- dynamicGrid_->setCurrentIndex(newIndex < dynamicGrid_->count() ? newIndex : 0);
+ int newIndex = dynamicGrid_->currentIndex() + 1;
+ dynamicGrid_->setCurrentIndex(newIndex < dynamicGrid_->count() ? newIndex : 0);
}
void QtChatTabs::handleRequestedActiveTab() {
- QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
- bool finished = false;
- for (int j = 0; j < 2; j++) {
- bool looped = false;
- for (int i = dynamicGrid_->currentIndex() + 1; !finished && i != dynamicGrid_->currentIndex(); i++) {
- if (i >= dynamicGrid_->count()) {
- if (looped) {
- break;
- }
- looped = true;
- i = 0;
- }
- if (qobject_cast<QtTabbable*>(dynamicGrid_->widget(i))->getWidgetAlertState() == types[j]) {
- dynamicGrid_->setCurrentIndex(i);
- finished = true;
- break;
- }
- }
- }
+ QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
+ bool finished = false;
+ for (int j = 0; j < 2; j++) {
+ bool looped = false;
+ for (int i = dynamicGrid_->currentIndex() + 1; !finished && i != dynamicGrid_->currentIndex(); i++) {
+ if (i >= dynamicGrid_->count()) {
+ if (looped) {
+ break;
+ }
+ looped = true;
+ i = 0;
+ }
+ if (qobject_cast<QtTabbable*>(dynamicGrid_->widget(i))->getWidgetAlertState() == types[j]) {
+ dynamicGrid_->setCurrentIndex(i);
+ finished = true;
+ break;
+ }
+ }
+ }
}
void QtChatTabs::handleCloseTabShortcut() {
- QWidget* currentWidget = dynamicGrid_->currentWidget();
- if (currentWidget) {
- currentWidget->close();
- }
+ QWidget* currentWidget = dynamicGrid_->currentWidget();
+ if (currentWidget) {
+ currentWidget->close();
+ }
}
void QtChatTabs::handleTabCloseRequested(int index) {
- if (trellisMode_) {
- storeTabPositions();
- }
-
- assert(index < dynamicGrid_->count());
- QWidget* widget = dynamicGrid_->widget(index);
- assert(widget);
- widget->close();
+ if (trellisMode_) {
+ storeTabPositions();
+ }
+
+ assert(index < dynamicGrid_->count());
+ QWidget* widget = dynamicGrid_->widget(index);
+ assert(widget);
+ widget->close();
}
void QtChatTabs::handleTabTitleUpdated() {
- QWidget* widget = qobject_cast<QWidget*>(sender());
- handleTabTitleUpdated(widget);
+ QWidget* widget = qobject_cast<QWidget*>(sender());
+ handleTabTitleUpdated(widget);
}
void QtChatTabs::handleTabTitleUpdated(QWidget* widget) {
- if (!widget) {
- return;
- }
- QtTabbable* tabbable = qobject_cast<QtTabbable*>(widget);
- int index = dynamicGrid_->indexOf(widget);
- if (index < 0) {
- return;
- }
-
- QString tabText = tabbable->windowTitle().simplified();
- // look for spectrum-generated and other long JID localparts, and
- // try to abbreviate the resulting long tab texts
- QRegExp hasTrailingGarbage("^(.[-\\w\\s,&]+)([^\\s\\,w].*)$");
- if (hasTrailingGarbage.exactMatch(tabText) &&
- hasTrailingGarbage.cap(1).simplified().length() >= 2 &&
- hasTrailingGarbage.cap(2).length() >= 7) {
- // there may be some trailing garbage, and it's long
- // enough to be worth removing, and we'd leave at
- // least a couple of characters.
- tabText = hasTrailingGarbage.cap(1).simplified();
- }
- // QTabBar interprets &, so escape that
- tabText.replace("&", "&&");
- // see which alt[a-z] keys other tabs use
- bool accelsTaken[26];
- int i = 0;
- while (i < 26) {
- accelsTaken[i] = (i == 0); //A is used for 'switch to active tab'
- i++;
- }
-
- int other = dynamicGrid_->count();
- while (other >= 0) {
- other--;
- if (other != index) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(other, tabIndex);
- QString t = tabWidget->tabBar()->tabText(tabIndex).toLower();
- int r = t.indexOf('&');
- if (r >= 0 && t[r+1] >= 'a' && t[r+1] <= 'z') {
- accelsTaken[t[r+1].unicode()-'a'] = true;
- }
- }
- }
- // then look to see which letters in tabText may be used
- i = 0;
- int accelPos = -1;
- while (i < tabText.length() && accelPos < 0) {
- if (tabText[i] >= 'A' && tabText[i] <= 'Z' &&
- !accelsTaken[tabText[i].unicode()-'A']) {
- accelPos = i;
- }
- if (tabText[i] >= 'a' && tabText[i] <= 'z' &&
- !accelsTaken[tabText[i].unicode()-'a']) {
- accelPos = i;
- }
- ++i;
- }
- if (accelPos >= 0) {
- tabText = tabText.mid(0, accelPos) + "&" + tabText.mid(accelPos);
- }
- // this could be improved on some european keyboards, such as
- // the German one (where alt-Sz-Ligature is available) and basically
- // doesn't work on Arabic/Indic keyboards (where Latin letters
- // aren't available), but I don't care to deal with those.
-
- int tabIndex = -1;
- QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(index, tabIndex);
- tabWidget->setTabText(tabIndex, tabbable->getCount() > 0 ? QString("(%1) %2").arg(tabbable->getCount()).arg(tabText) : tabText);
- QColor tabTextColor;
- switch (tabbable->getWidgetAlertState()) {
- case QtTabbable::WaitingActivity : tabTextColor = QColor(217, 20, 43); break;
- case QtTabbable::ImpendingActivity : tabTextColor = QColor(27, 171, 32); break;
- case QtTabbable::NoActivity : tabTextColor = QColor(); break;
- }
- tabWidget->tabBar()->setTabTextColor(tabIndex, tabTextColor);
-
- std::vector<std::pair<std::string, int> > unreads;
- for (int i = 0; i < dynamicGrid_->count(); i++) {
- QtTabbable* tab = qobject_cast<QtTabbable*>(dynamicGrid_->widget(i));
- if (tab) {
- unreads.push_back(std::pair<std::string, int>(Q2PSTRING(tab->windowTitle()), tab->getCount()));
- }
- }
-
- std::string current(Q2PSTRING(qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget())->windowTitle()));
- ChatMessageSummarizer summary;
- QString title = summary.getSummary(current, unreads).c_str();
- setWindowTitle(title);
- emit onTitleChanged(title);
+ if (!widget) {
+ return;
+ }
+ QtTabbable* tabbable = qobject_cast<QtTabbable*>(widget);
+ int index = dynamicGrid_->indexOf(widget);
+ if (index < 0) {
+ return;
+ }
+
+ QString tabText = tabbable->windowTitle().simplified();
+ // look for spectrum-generated and other long JID localparts, and
+ // try to abbreviate the resulting long tab texts
+ QRegExp hasTrailingGarbage("^(.[-\\w\\s,&]+)([^\\s\\,w].*)$");
+ if (hasTrailingGarbage.exactMatch(tabText) &&
+ hasTrailingGarbage.cap(1).simplified().length() >= 2 &&
+ hasTrailingGarbage.cap(2).length() >= 7) {
+ // there may be some trailing garbage, and it's long
+ // enough to be worth removing, and we'd leave at
+ // least a couple of characters.
+ tabText = hasTrailingGarbage.cap(1).simplified();
+ }
+ // QTabBar interprets &, so escape that
+ tabText.replace("&", "&&");
+ // see which alt[a-z] keys other tabs use
+ bool accelsTaken[26];
+ int i = 0;
+ while (i < 26) {
+ accelsTaken[i] = (i == 0); //A is used for 'switch to active tab'
+ i++;
+ }
+
+ int other = dynamicGrid_->count();
+ while (other >= 0) {
+ other--;
+ if (other != index) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(other, tabIndex);
+ QString t = tabWidget->tabBar()->tabText(tabIndex).toLower();
+ int r = t.indexOf('&');
+ if (r >= 0 && t[r+1] >= 'a' && t[r+1] <= 'z') {
+ accelsTaken[t[r+1].unicode()-'a'] = true;
+ }
+ }
+ }
+ // then look to see which letters in tabText may be used
+ i = 0;
+ int accelPos = -1;
+ while (i < tabText.length() && accelPos < 0) {
+ if (tabText[i] >= 'A' && tabText[i] <= 'Z' &&
+ !accelsTaken[tabText[i].unicode()-'A']) {
+ accelPos = i;
+ }
+ if (tabText[i] >= 'a' && tabText[i] <= 'z' &&
+ !accelsTaken[tabText[i].unicode()-'a']) {
+ accelPos = i;
+ }
+ ++i;
+ }
+ if (accelPos >= 0) {
+ tabText = tabText.mid(0, accelPos) + "&" + tabText.mid(accelPos);
+ }
+ // this could be improved on some european keyboards, such as
+ // the German one (where alt-Sz-Ligature is available) and basically
+ // doesn't work on Arabic/Indic keyboards (where Latin letters
+ // aren't available), but I don't care to deal with those.
+
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(index, tabIndex);
+ tabWidget->setTabText(tabIndex, tabbable->getCount() > 0 ? QString("(%1) %2").arg(tabbable->getCount()).arg(tabText) : tabText);
+ QColor tabTextColor;
+ switch (tabbable->getWidgetAlertState()) {
+ case QtTabbable::WaitingActivity : tabTextColor = QColor(217, 20, 43); break;
+ case QtTabbable::ImpendingActivity : tabTextColor = QColor(27, 171, 32); break;
+ case QtTabbable::NoActivity : tabTextColor = QColor(); break;
+ }
+ tabWidget->tabBar()->setTabTextColor(tabIndex, tabTextColor);
+
+ std::vector<std::pair<std::string, int> > unreads;
+ for (int i = 0; i < dynamicGrid_->count(); i++) {
+ QtTabbable* tab = qobject_cast<QtTabbable*>(dynamicGrid_->widget(i));
+ if (tab) {
+ unreads.push_back(std::pair<std::string, int>(Q2PSTRING(tab->windowTitle()), tab->getCount()));
+ }
+ }
+
+ std::string current(Q2PSTRING(qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget())->windowTitle()));
+ ChatMessageSummarizer summary;
+ QString title = summary.getSummary(current, unreads).c_str();
+ setWindowTitle(title);
+ emit onTitleChanged(title);
}
void QtChatTabs::flash() {
#ifndef SWIFTEN_PLATFORM_MACOSX
- QApplication::alert(this, 0);
+ QApplication::alert(this, 0);
#endif
}
void QtChatTabs::handleOpenLayoutChangeDialog() {
- disconnect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
- gridSelectionDialog_->setCurrentGridSize(dynamicGrid_->getDimension());
- gridSelectionDialog_->move(QCursor::pos());
- connect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
- gridSelectionDialog_->show();
+ disconnect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
+ gridSelectionDialog_->setCurrentGridSize(dynamicGrid_->getDimension());
+ gridSelectionDialog_->move(QCursor::pos());
+ connect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
+ gridSelectionDialog_->show();
}
void QtChatTabs::storeTabPositions() {
- // save size
- QByteArray gridSizeData;
- QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
- dataStreamGridSize << dynamicGrid_->getDimension();
- settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_SIZE, Q2PSTRING(QString(gridSizeData.toBase64())));
-
- // save positions
- QByteArray tabPositionsData;
- QDataStream dataStreamTabPositions(&tabPositionsData, QIODevice::ReadWrite);
- dynamicGrid_->updateTabPositions();
- dataStreamTabPositions << dynamicGrid_->getTabPositions();
- settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_POSITIONS, Q2PSTRING(QString(tabPositionsData.toBase64())));
+ // save size
+ QByteArray gridSizeData;
+ QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
+ dataStreamGridSize << dynamicGrid_->getDimension();
+ settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_SIZE, Q2PSTRING(QString(gridSizeData.toBase64())));
+
+ // save positions
+ QByteArray tabPositionsData;
+ QDataStream dataStreamTabPositions(&tabPositionsData, QIODevice::ReadWrite);
+ dynamicGrid_->updateTabPositions();
+ dataStreamTabPositions << dynamicGrid_->getTabPositions();
+ settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_POSITIONS, Q2PSTRING(QString(tabPositionsData.toBase64())));
}
void QtChatTabs::resizeEvent(QResizeEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatTabs::moveEvent(QMoveEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatTabs::checkForFirstShow() {
- if (!isVisible()) {
+ if (!isVisible()) {
#ifndef Q_OS_MAC
- showMinimized();
+ showMinimized();
#else
- /* https://bugreports.qt-project.org/browse/QTBUG-19194
- * ^ When the above is fixed we can swap the below for just show();
- * WA_ShowWithoutActivating seems to helpfully not work, so... */
-
- QWidget* currentWindow = QApplication::activeWindow(); /* Remember who had focus if we're the current application*/
- show();
- QCoreApplication::processEvents(); /* Run through the eventloop to clear the show() */
- if (currentWindow) {
- currentWindow->activateWindow(); /* Set focus back */
- }
+ /* https://bugreports.qt-project.org/browse/QTBUG-19194
+ * ^ When the above is fixed we can swap the below for just show();
+ * WA_ShowWithoutActivating seems to helpfully not work, so... */
+
+ QWidget* currentWindow = QApplication::activeWindow(); /* Remember who had focus if we're the current application*/
+ show();
+ QCoreApplication::processEvents(); /* Run through the eventloop to clear the show() */
+ if (currentWindow) {
+ currentWindow->activateWindow(); /* Set focus back */
+ }
#endif
- }
+ }
}
}
diff --git a/Swift/QtUI/QtChatTabs.h b/Swift/QtUI/QtChatTabs.h
index 8fcbf4a..0c12d96 100644
--- a/Swift/QtUI/QtChatTabs.h
+++ b/Swift/QtUI/QtChatTabs.h
@@ -16,62 +16,62 @@ class QTabWidget;
class QMenu;
namespace Swift {
- class SettingsProvider;
-
- class QtTabbable;
- class QtTabWidget;
- class QtDynamicGridLayout;
- class QtGridSelectionDialog;
-
- class QtChatTabs : public QWidget, public QtChatTabsBase {
- Q_OBJECT
- public:
- QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode);
- virtual ~QtChatTabs();
-
- virtual void addTab(QtTabbable* tab);
- void minimise();
- QtTabbable* getCurrentTab();
- void setViewMenu(QMenu* viewMenu);
-
- signals:
- void geometryChanged();
- void onTitleChanged(const QString& title);
-
- protected slots:
- void closeEvent(QCloseEvent* event);
- void resizeEvent(QResizeEvent* event);
- void moveEvent(QMoveEvent* event);
-
- private slots:
- void handleCurrentTabIndexChanged(int newIndex);
- void handleTabClosing();
- void handleTabTitleUpdated();
- void handleTabTitleUpdated(QWidget* widget);
- void handleTabCloseRequested(int index);
- void handleWidgetShown();
- void handleWantsToActivate();
- void handleRequestedPreviousTab();
- void handleRequestedNextTab();
- void handleRequestedActiveTab();
- void flash();
-
- void handleOpenLayoutChangeDialog();
-
- void handleCloseTabShortcut();
-
- private:
- void storeTabPositions();
- void checkForFirstShow();
-
- private:
- bool singleWindow_;
- SettingsProvider* settingsProvider_;
- bool trellisMode_;
- QtDynamicGridLayout* dynamicGrid_;
- QtGridSelectionDialog* gridSelectionDialog_;
-
- QList<QShortcut*> shortcuts_;
- };
+ class SettingsProvider;
+
+ class QtTabbable;
+ class QtTabWidget;
+ class QtDynamicGridLayout;
+ class QtGridSelectionDialog;
+
+ class QtChatTabs : public QWidget, public QtChatTabsBase {
+ Q_OBJECT
+ public:
+ QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode);
+ virtual ~QtChatTabs();
+
+ virtual void addTab(QtTabbable* tab);
+ void minimise();
+ QtTabbable* getCurrentTab();
+ void setViewMenu(QMenu* viewMenu);
+
+ signals:
+ void geometryChanged();
+ void onTitleChanged(const QString& title);
+
+ protected slots:
+ void closeEvent(QCloseEvent* event);
+ void resizeEvent(QResizeEvent* event);
+ void moveEvent(QMoveEvent* event);
+
+ private slots:
+ void handleCurrentTabIndexChanged(int newIndex);
+ void handleTabClosing();
+ void handleTabTitleUpdated();
+ void handleTabTitleUpdated(QWidget* widget);
+ void handleTabCloseRequested(int index);
+ void handleWidgetShown();
+ void handleWantsToActivate();
+ void handleRequestedPreviousTab();
+ void handleRequestedNextTab();
+ void handleRequestedActiveTab();
+ void flash();
+
+ void handleOpenLayoutChangeDialog();
+
+ void handleCloseTabShortcut();
+
+ private:
+ void storeTabPositions();
+ void checkForFirstShow();
+
+ private:
+ bool singleWindow_;
+ SettingsProvider* settingsProvider_;
+ bool trellisMode_;
+ QtDynamicGridLayout* dynamicGrid_;
+ QtGridSelectionDialog* gridSelectionDialog_;
+
+ QList<QShortcut*> shortcuts_;
+ };
}
diff --git a/Swift/QtUI/QtChatTabsBase.h b/Swift/QtUI/QtChatTabsBase.h
index 753b706..b49bb10 100644
--- a/Swift/QtUI/QtChatTabsBase.h
+++ b/Swift/QtUI/QtChatTabsBase.h
@@ -11,11 +11,11 @@ namespace Swift {
class QtTabbable;
class QtChatTabsBase {
- public:
- QtChatTabsBase();
- virtual ~QtChatTabsBase();
+ public:
+ QtChatTabsBase();
+ virtual ~QtChatTabsBase();
- virtual void addTab(QtTabbable* tab) = 0;
+ virtual void addTab(QtTabbable* tab) = 0;
};
}
diff --git a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
index 7f44177..2c064f8 100644
--- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
+++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
@@ -27,82 +27,82 @@ QtChatTabsShortcutOnlySubstitute::~QtChatTabsShortcutOnlySubstitute() {
}
void QtChatTabsShortcutOnlySubstitute::addTab(QtTabbable* tab) {
- connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection);
- connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection);
- connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection);
-
- connect(new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), tab), SIGNAL(activated()), this, SLOT(handleCloseTabShortcut()));
- connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), tab), SIGNAL(activated()), tab, SIGNAL(requestPreviousTab()));
- connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), tab), SIGNAL(activated()), tab, SIGNAL(requestNextTab()));
- connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), tab), SIGNAL(activated()), tab, SIGNAL(requestActiveTab()));
+ connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection);
+
+ connect(new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), tab), SIGNAL(activated()), this, SLOT(handleCloseTabShortcut()));
+ connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), tab), SIGNAL(activated()), tab, SIGNAL(requestPreviousTab()));
+ connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), tab), SIGNAL(activated()), tab, SIGNAL(requestNextTab()));
+ connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), tab), SIGNAL(activated()), tab, SIGNAL(requestActiveTab()));
}
void QtChatTabsShortcutOnlySubstitute::handleCloseTabShortcut() {
- QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender()->parent());
- SWIFT_LOG_ASSERT(senderTab, debug) << "No window to close." << std::endl;
- if (senderTab) {
- senderTab->close();
- }
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender()->parent());
+ SWIFT_LOG_ASSERT(senderTab, debug) << "No window to close." << std::endl;
+ if (senderTab) {
+ senderTab->close();
+ }
}
void QtChatTabsShortcutOnlySubstitute::handleRequestedNextTab() {
- QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
- QList<QtTabbable*> tabs = tabbableWindows();
+ QList<QtTabbable*> tabs = tabbableWindows();
- int currentIndex = tabs.indexOf(senderTab);
- assert(currentIndex >= 0);
+ int currentIndex = tabs.indexOf(senderTab);
+ assert(currentIndex >= 0);
- QtTabbable* nextTab = tabs.at((currentIndex + 1) % tabs.size());
- nextTab->activateWindow();
+ QtTabbable* nextTab = tabs.at((currentIndex + 1) % tabs.size());
+ nextTab->activateWindow();
}
void QtChatTabsShortcutOnlySubstitute::handleRequestedActiveTab() {
- QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
- QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
+ QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
- QList<QtTabbable*> tabs = tabbableWindows();
+ QList<QtTabbable*> tabs = tabbableWindows();
- for (int j = 0; j < 2; j++) {
- int startIndex = tabs.indexOf(senderTab);
- int currentIndex = startIndex;
+ for (int j = 0; j < 2; j++) {
+ int startIndex = tabs.indexOf(senderTab);
+ int currentIndex = startIndex;
- do {
- currentIndex = (currentIndex + 1) % tabs.size();
- QtTabbable* currentTab = tabs.at(currentIndex);
- if (currentTab->getWidgetAlertState() == types[j]) {
- currentTab->activateWindow();
- return;
- }
- } while (startIndex != currentIndex);
- }
+ do {
+ currentIndex = (currentIndex + 1) % tabs.size();
+ QtTabbable* currentTab = tabs.at(currentIndex);
+ if (currentTab->getWidgetAlertState() == types[j]) {
+ currentTab->activateWindow();
+ return;
+ }
+ } while (startIndex != currentIndex);
+ }
}
void QtChatTabsShortcutOnlySubstitute::handleRequestedPreviousTab() {
- QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
- QList<QtTabbable*> tabs = tabbableWindows();
+ QList<QtTabbable*> tabs = tabbableWindows();
- int currentIndex = tabs.indexOf(senderTab);
- assert(currentIndex >= 0);
+ int currentIndex = tabs.indexOf(senderTab);
+ assert(currentIndex >= 0);
- QtTabbable* previousTab = tabs.at((currentIndex + tabs.size() - 1) % tabs.size());
- previousTab->activateWindow();
+ QtTabbable* previousTab = tabs.at((currentIndex + tabs.size() - 1) % tabs.size());
+ previousTab->activateWindow();
}
QList<QtTabbable*> QtChatTabsShortcutOnlySubstitute::tabbableWindows() const {
- QList<QWidget*> windows = qApp->topLevelWidgets();
+ QList<QWidget*> windows = qApp->topLevelWidgets();
- QList<QtTabbable*> tabbables;
- foreach(QWidget* topLevelWidget, windows) {
- QtTabbable* tabbable = dynamic_cast<QtTabbable*>(topLevelWidget);
- if (tabbable) {
- tabbables << tabbable;
- }
- }
+ QList<QtTabbable*> tabbables;
+ foreach(QWidget* topLevelWidget, windows) {
+ QtTabbable* tabbable = dynamic_cast<QtTabbable*>(topLevelWidget);
+ if (tabbable) {
+ tabbables << tabbable;
+ }
+ }
- return tabbables;
+ return tabbables;
}
}
diff --git a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
index 80af008..b330fe7 100644
--- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
+++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
@@ -16,25 +16,25 @@ class QShortcut;
namespace Swift {
class QtChatTabsShortcutOnlySubstitute : public QWidget, public QtChatTabsBase {
- Q_OBJECT
+ Q_OBJECT
- public:
- QtChatTabsShortcutOnlySubstitute();
- virtual ~QtChatTabsShortcutOnlySubstitute();
+ public:
+ QtChatTabsShortcutOnlySubstitute();
+ virtual ~QtChatTabsShortcutOnlySubstitute();
- virtual void addTab(QtTabbable* tab);
+ virtual void addTab(QtTabbable* tab);
- private slots:
- void handleCloseTabShortcut();
- void handleRequestedNextTab();
- void handleRequestedActiveTab();
- void handleRequestedPreviousTab();
+ private slots:
+ void handleCloseTabShortcut();
+ void handleRequestedNextTab();
+ void handleRequestedActiveTab();
+ void handleRequestedPreviousTab();
- private:
- QList<QtTabbable*> tabbableWindows() const;
+ private:
+ QList<QtTabbable*> tabbableWindows() const;
- private:
- QList<QShortcut*> shortcuts_;
+ private:
+ QList<QShortcut*> shortcuts_;
};
}
diff --git a/Swift/QtUI/QtChatTheme.cpp b/Swift/QtUI/QtChatTheme.cpp
index a7628d9..e73f8ac 100644
--- a/Swift/QtUI/QtChatTheme.cpp
+++ b/Swift/QtUI/QtChatTheme.cpp
@@ -14,58 +14,58 @@ namespace Swift {
* Load Adium themes, as http://trac.adium.im/wiki/CreatingMessageStyles
*/
QtChatTheme::QtChatTheme(const QString& themePath) : qrc_(themePath[0] == ':'), themePath_(qrc_ ? themePath : themePath + "/Contents/Resources/") {
- QString fileNames[EndMarker];
- fileNames[Header] = "Header.html";
- fileNames[Footer] = "Footer.html";
- fileNames[Content] = "Content.html";
- fileNames[Status] = "Status.html";
- fileNames[Topic] = "Topic.html";
- fileNames[FileTransferRequest] = "FileTransferRequest.html";
- fileNames[IncomingContent] = "Incoming/Content.html";
- fileNames[IncomingNextContent] = "Incoming/NextContent.html";
- fileNames[IncomingContext] = "Incoming/Context.html";
- fileNames[IncomingNextContext] = "Incoming/NextContext.html";
- fileNames[OutgoingContent] = "Outgoing/Content.html";
- fileNames[OutgoingNextContent] = "Outgoing/NextContent.html";
- fileNames[OutgoingContext] = "Outgoing/Context.html";
- fileNames[OutgoingNextContext] = "Outgoing/NextContext.html";
- fileNames[Template] = "Template.html";
- fileNames[MainCSS] = "main.css";
- fileNames[Unread] = "Unread.html";
- fileNames[TemplateDefault] = ":/themes/Template.html";
- for (int i = 0; i < EndMarker; i++) {
- QString source;
- QFile sourceFile((i != TemplateDefault ? themePath_ : "") + fileNames[i]);
- if (sourceFile.exists() && sourceFile.open(QIODevice::ReadOnly)) {
- source = sourceFile.readAll();
- sourceFile.close();
- } else {
- //qWarning() << "Couldn't load file " << sourceFile.fileName();
- }
- fileContents_.append(source);
- }
+ QString fileNames[EndMarker];
+ fileNames[Header] = "Header.html";
+ fileNames[Footer] = "Footer.html";
+ fileNames[Content] = "Content.html";
+ fileNames[Status] = "Status.html";
+ fileNames[Topic] = "Topic.html";
+ fileNames[FileTransferRequest] = "FileTransferRequest.html";
+ fileNames[IncomingContent] = "Incoming/Content.html";
+ fileNames[IncomingNextContent] = "Incoming/NextContent.html";
+ fileNames[IncomingContext] = "Incoming/Context.html";
+ fileNames[IncomingNextContext] = "Incoming/NextContext.html";
+ fileNames[OutgoingContent] = "Outgoing/Content.html";
+ fileNames[OutgoingNextContent] = "Outgoing/NextContent.html";
+ fileNames[OutgoingContext] = "Outgoing/Context.html";
+ fileNames[OutgoingNextContext] = "Outgoing/NextContext.html";
+ fileNames[Template] = "Template.html";
+ fileNames[MainCSS] = "main.css";
+ fileNames[Unread] = "Unread.html";
+ fileNames[TemplateDefault] = ":/themes/Template.html";
+ for (int i = 0; i < EndMarker; i++) {
+ QString source;
+ QFile sourceFile((i != TemplateDefault ? themePath_ : "") + fileNames[i]);
+ if (sourceFile.exists() && sourceFile.open(QIODevice::ReadOnly)) {
+ source = sourceFile.readAll();
+ sourceFile.close();
+ } else {
+ //qWarning() << "Couldn't load file " << sourceFile.fileName();
+ }
+ fileContents_.append(source);
+ }
- /* Fallbacks */
- if (fileContents_[Template].isEmpty()) fileContents_[Template] = fileContents_[TemplateDefault];
- if (fileContents_[Status].isEmpty()) fileContents_[Status] = fileContents_[Content];
- if (fileContents_[IncomingContent].isEmpty()) fileContents_[IncomingContent] = fileContents_[Content];
- if (fileContents_[IncomingNextContent].isEmpty()) fileContents_[IncomingNextContent] = fileContents_[IncomingContent];
- if (fileContents_[FileTransferRequest].isEmpty()) fileContents_[FileTransferRequest] = fileContents_[Status];
- if (fileContents_[IncomingContext].isEmpty()) fileContents_[IncomingContext] = fileContents_[IncomingContent];
- if (fileContents_[IncomingNextContext].isEmpty()) fileContents_[IncomingNextContext] = fileContents_[IncomingNextContent];
- if (fileContents_[OutgoingContent].isEmpty()) fileContents_[OutgoingContent] = fileContents_[IncomingContent];
- if (fileContents_[OutgoingContext].isEmpty()) fileContents_[OutgoingContext] = fileContents_[OutgoingContent];
- if (fileContents_[OutgoingNextContent].isEmpty()) fileContents_[OutgoingNextContent] = fileContents_[OutgoingContent];
- if (fileContents_[OutgoingNextContext].isEmpty()) fileContents_[OutgoingNextContext] = fileContents_[OutgoingNextContent];
+ /* Fallbacks */
+ if (fileContents_[Template].isEmpty()) fileContents_[Template] = fileContents_[TemplateDefault];
+ if (fileContents_[Status].isEmpty()) fileContents_[Status] = fileContents_[Content];
+ if (fileContents_[IncomingContent].isEmpty()) fileContents_[IncomingContent] = fileContents_[Content];
+ if (fileContents_[IncomingNextContent].isEmpty()) fileContents_[IncomingNextContent] = fileContents_[IncomingContent];
+ if (fileContents_[FileTransferRequest].isEmpty()) fileContents_[FileTransferRequest] = fileContents_[Status];
+ if (fileContents_[IncomingContext].isEmpty()) fileContents_[IncomingContext] = fileContents_[IncomingContent];
+ if (fileContents_[IncomingNextContext].isEmpty()) fileContents_[IncomingNextContext] = fileContents_[IncomingNextContent];
+ if (fileContents_[OutgoingContent].isEmpty()) fileContents_[OutgoingContent] = fileContents_[IncomingContent];
+ if (fileContents_[OutgoingContext].isEmpty()) fileContents_[OutgoingContext] = fileContents_[OutgoingContent];
+ if (fileContents_[OutgoingNextContent].isEmpty()) fileContents_[OutgoingNextContent] = fileContents_[OutgoingContent];
+ if (fileContents_[OutgoingNextContext].isEmpty()) fileContents_[OutgoingNextContext] = fileContents_[OutgoingNextContent];
}
QString QtChatTheme::getBase() const {
- return qrc_ ? "qrc" + themePath_ : "file://" + themePath_;
+ return qrc_ ? "qrc" + themePath_ : "file://" + themePath_;
}
QString QtChatTheme::getUnread() const {
- return fileContents_[Unread].isEmpty() ? "<hr/>" : fileContents_[Unread];
+ return fileContents_[Unread].isEmpty() ? "<hr/>" : fileContents_[Unread];
}
}
diff --git a/Swift/QtUI/QtChatTheme.h b/Swift/QtUI/QtChatTheme.h
index 2997de0..8db662f 100644
--- a/Swift/QtUI/QtChatTheme.h
+++ b/Swift/QtUI/QtChatTheme.h
@@ -10,32 +10,32 @@
#include <QString>
namespace Swift {
- class QtChatTheme {
- public:
- QtChatTheme(const QString& themePath);
- QString getHeader() const {return fileContents_[Header];}
- QString getFooter() const {return fileContents_[Footer];}
- QString getContent() const {return fileContents_[Content];}
- QString getStatus() const {return fileContents_[Status];}
- QString getTopic() const {return fileContents_[Topic];}
- QString getFileTransferRequest() const {return fileContents_[FileTransferRequest];}
- QString getIncomingContent() const {return fileContents_[IncomingContent];}
- QString getIncomingNextContent() const {return fileContents_[IncomingNextContent];}
- QString getIncomingContext() const {return fileContents_[IncomingContext];}
- QString getIncomingNextContext() const {return fileContents_[IncomingNextContext];}
- QString getOutgoingContent() const {return fileContents_[OutgoingContent];}
- QString getOutgoingNextContent() const {return fileContents_[OutgoingNextContent];}
- QString getOutgoingContext() const {return fileContents_[OutgoingContext];}
- QString getOutgoingNextContext() const {return fileContents_[OutgoingNextContext];}
- QString getTemplate() const {return fileContents_[Template];}
- QString getMainCSS() const {return fileContents_[MainCSS];}
- QString getBase() const;
- QString getUnread() const;
+ class QtChatTheme {
+ public:
+ QtChatTheme(const QString& themePath);
+ QString getHeader() const {return fileContents_[Header];}
+ QString getFooter() const {return fileContents_[Footer];}
+ QString getContent() const {return fileContents_[Content];}
+ QString getStatus() const {return fileContents_[Status];}
+ QString getTopic() const {return fileContents_[Topic];}
+ QString getFileTransferRequest() const {return fileContents_[FileTransferRequest];}
+ QString getIncomingContent() const {return fileContents_[IncomingContent];}
+ QString getIncomingNextContent() const {return fileContents_[IncomingNextContent];}
+ QString getIncomingContext() const {return fileContents_[IncomingContext];}
+ QString getIncomingNextContext() const {return fileContents_[IncomingNextContext];}
+ QString getOutgoingContent() const {return fileContents_[OutgoingContent];}
+ QString getOutgoingNextContent() const {return fileContents_[OutgoingNextContent];}
+ QString getOutgoingContext() const {return fileContents_[OutgoingContext];}
+ QString getOutgoingNextContext() const {return fileContents_[OutgoingNextContext];}
+ QString getTemplate() const {return fileContents_[Template];}
+ QString getMainCSS() const {return fileContents_[MainCSS];}
+ QString getBase() const;
+ QString getUnread() const;
- private:
- enum files {Header = 0, Footer, Content, Status, Topic, FileTransferRequest, IncomingContent, IncomingNextContent, IncomingContext, IncomingNextContext, OutgoingContent, OutgoingNextContent, OutgoingContext, OutgoingNextContext, Template, MainCSS, TemplateDefault, Unread, /*Must be last!*/EndMarker};
- bool qrc_;
- QList<QString> fileContents_;
- QString themePath_;
- };
+ private:
+ enum files {Header = 0, Footer, Content, Status, Topic, FileTransferRequest, IncomingContent, IncomingNextContent, IncomingContext, IncomingNextContext, OutgoingContent, OutgoingNextContent, OutgoingContext, OutgoingNextContext, Template, MainCSS, TemplateDefault, Unread, /*Must be last!*/EndMarker};
+ bool qrc_;
+ QList<QString> fileContents_;
+ QString themePath_;
+ };
}
diff --git a/Swift/QtUI/QtChatView.cpp b/Swift/QtUI/QtChatView.cpp
index 05366c1..6d9a17d 100644
--- a/Swift/QtUI/QtChatView.cpp
+++ b/Swift/QtUI/QtChatView.cpp
@@ -13,7 +13,7 @@ QtChatView::QtChatView(QWidget* parent) : QWidget(parent) {
}
QtChatView::~QtChatView() {
-
+
}
}
diff --git a/Swift/QtUI/QtChatView.h b/Swift/QtUI/QtChatView.h
index 9f0df44..cca3bdf 100644
--- a/Swift/QtUI/QtChatView.h
+++ b/Swift/QtUI/QtChatView.h
@@ -16,49 +16,49 @@
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
namespace Swift {
- class HighlightAction;
- class SecurityLabel;
+ class HighlightAction;
+ class SecurityLabel;
- class QtChatView : public QWidget {
- Q_OBJECT
- public:
- QtChatView(QWidget* parent);
- virtual ~QtChatView();
+ class QtChatView : public QWidget {
+ Q_OBJECT
+ public:
+ QtChatView(QWidget* parent);
+ virtual ~QtChatView();
- /** Add message to window.
- * @return id of added message (for acks).
- */
- virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
- /** Adds action to window.
- * @return id of added message (for acks);
- */
- virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
+ /** Add message to window.
+ * @return id of added message (for acks).
+ */
+ virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
+ /** Adds action to window.
+ * @return id of added message (for acks);
+ */
+ virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
- virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
- virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
+ virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
+ virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
- virtual void addErrorMessage(const ChatWindow::ChatMessage& message) = 0;
- virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
- virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
- virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
- virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
- virtual void setAckState(const std::string& id, ChatWindow::AckState state) = 0;
-
- virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0;
- virtual void setFileTransferProgress(std::string, const int percentageDone) = 0;
- virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") = 0;
- virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) = 0;
- virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) = 0;
- virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) = 0;
- virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0;
+ virtual void addErrorMessage(const ChatWindow::ChatMessage& message) = 0;
+ virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
+ virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
+ virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
+ virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
+ virtual void setAckState(const std::string& id, ChatWindow::AckState state) = 0;
- virtual void showEmoticons(bool show) = 0;
- virtual void addLastSeenLine() = 0;
+ virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0;
+ virtual void setFileTransferProgress(std::string, const int percentageDone) = 0;
+ virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") = 0;
+ virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) = 0;
+ virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) = 0;
+ virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) = 0;
+ virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0;
- public slots:
- virtual void resizeFont(int fontSizeSteps) = 0;
- virtual void scrollToBottom() = 0;
- virtual void handleKeyPressEvent(QKeyEvent* event) = 0;
+ virtual void showEmoticons(bool show) = 0;
+ virtual void addLastSeenLine() = 0;
- };
+ public slots:
+ virtual void resizeFont(int fontSizeSteps) = 0;
+ virtual void scrollToBottom() = 0;
+ virtual void handleKeyPressEvent(QKeyEvent* event) = 0;
+
+ };
}
diff --git a/Swift/QtUI/QtChatWindow.cpp b/Swift/QtUI/QtChatWindow.cpp
index 7649256..95d643c 100644
--- a/Swift/QtUI/QtChatWindow.cpp
+++ b/Swift/QtUI/QtChatWindow.cpp
@@ -62,883 +62,883 @@
namespace Swift {
QtChatWindow::QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map<std::string, std::string>& emoticons) : QtTabbable(), id_(Q2PSTRING(contact)), contact_(contact), nextAlertId_(0), eventStream_(eventStream), blockingState_(BlockingUnsupported), isMUC_(false), supportsImpromptuChat_(false), roomBookmarkState_(RoomNotBookmarked) {
- settings_ = settings;
- unreadCount_ = 0;
- isOnline_ = true;
- completer_ = NULL;
- affiliationEditor_ = NULL;
- theme_ = theme;
- isCorrection_ = false;
- labelModel_ = NULL;
- correctionEnabled_ = Maybe;
- fileTransferEnabled_ = Maybe;
- updateTitleWithUnreadCount();
- assert(settings);
- setAcceptDrops(true);
-
- alertStyleSheet_ = ".QWidget, QTextEdit { background: rgb(255, 255, 153); color: black }";
-
- QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout->setContentsMargins(0,0,0,0);
- layout->setSpacing(2);
-
- alertLayout_ = new QVBoxLayout();
- layout->addLayout(alertLayout_);
-
- subjectLayout_ = new QBoxLayout(QBoxLayout::LeftToRight);
- subject_ = new QLineEdit(this);
- subjectLayout_->addWidget(subject_);
- setSubject("");
- subject_->setReadOnly(true);
-
- QPushButton* actionButton_ = new QPushButton(this);
- actionButton_->setIcon(QIcon(":/icons/actions.png"));
- connect(actionButton_, SIGNAL(clicked()), this, SLOT(handleActionButtonClicked()));
- subject_->hide();
-
- layout->addLayout(subjectLayout_);
-
- logRosterSplitter_ = new QSplitter(this);
- logRosterSplitter_->setAutoFillBackground(true);
- layout->addWidget(logRosterSplitter_);
- if (settings_->getSetting(QtUISettingConstants::USE_PLAIN_CHATS) || settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
- messageLog_ = new QtPlainChatView(this, eventStream_);
- }
- else {
- messageLog_ = new QtWebKitChatView(this, eventStream_, theme, this); // I accept that passing the ChatWindow in so that the view can call the signals is somewhat inelegant, but it saves a lot of boilerplate. This patch is unpleasant enough already. So let's fix this soon (it at least needs fixing by the time history is sorted), but not now.
- }
- logRosterSplitter_->addWidget(messageLog_);
-
- treeWidget_ = new QtOccupantListWidget(eventStream_, settings_, QtTreeWidget::MessageDefaultJID, this);
- treeWidget_->hide();
- logRosterSplitter_->addWidget(treeWidget_);
- logRosterSplitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- connect(logRosterSplitter_, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int)));
-
- midBar_ = new QWidget(this);
- //layout->addWidget(midBar);
- midBar_->setAutoFillBackground(true);
- QHBoxLayout *midBarLayout = new QHBoxLayout(midBar_);
- midBarLayout->setContentsMargins(0,0,0,0);
- midBarLayout->setSpacing(2);
- //midBarLayout->addStretch();
-
- labelsWidget_ = new QComboBox(this);
- labelsWidget_->setFocusPolicy(Qt::NoFocus);
- labelsWidget_->hide();
- labelsWidget_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
- midBarLayout->addWidget(labelsWidget_,0);
- connect(labelsWidget_, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentLabelChanged(int)));
- defaultLabelsPalette_ = labelsWidget_->palette();
-
- QHBoxLayout* inputBarLayout = new QHBoxLayout();
- inputBarLayout->setContentsMargins(0,0,0,0);
- inputBarLayout->setSpacing(2);
- input_ = new QtTextEdit(settings_, this);
- input_->setAcceptRichText(false);
- inputBarLayout->addWidget(midBar_);
- inputBarLayout->addWidget(input_);
- correctingLabel_ = new QLabel(tr("Correcting"), this);
- inputBarLayout->addWidget(correctingLabel_);
- correctingLabel_->hide();
-
- connect(input_, SIGNAL(receivedFocus()), this, SLOT(handleTextInputReceivedFocus()));
- connect(input_, SIGNAL(lostFocus()), this, SLOT(handleTextInputLostFocus()));
- QPushButton* emoticonsButton_ = new QPushButton(this);
- emoticonsButton_->setIcon(QIcon(":/emoticons/smile.png"));
- connect(emoticonsButton_, SIGNAL(clicked()), this, SLOT(handleEmoticonsButtonClicked()));
-
- emoticonsMenu_ = new QMenu(this);
- QtEmoticonsGrid* emoticonsGrid = new QtEmoticonsGrid(emoticons, emoticonsMenu_);
- connect(emoticonsGrid, SIGNAL(emoticonClicked(QString)), this, SLOT(handleEmoticonClicked(QString)));
-
- // using an extra layout to work around Qt margin glitches on OS X
- QHBoxLayout* actionLayout = new QHBoxLayout();
- actionLayout->addWidget(emoticonsButton_);
- actionLayout->addWidget(actionButton_);
-
- inputBarLayout->addLayout(actionLayout);
- layout->addLayout(inputBarLayout);
-
- inputClearing_ = false;
- contactIsTyping_ = false;
- tabCompletion_ = false;
-
- connect(input_, SIGNAL(unhandledKeyPressEvent(QKeyEvent*)), this, SLOT(handleKeyPressEvent(QKeyEvent*)));
- connect(input_, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
- connect(input_, SIGNAL(textChanged()), this, SLOT(handleInputChanged()));
- connect(input_, SIGNAL(cursorPositionChanged()), this, SLOT(handleCursorPositionChanged()));
- setFocusProxy(input_);
- logRosterSplitter_->setFocusProxy(input_);
- midBar_->setFocusProxy(input_);
- messageLog_->setFocusProxy(input_);
- connect(messageLog_, SIGNAL(gotFocus()), input_, SLOT(setFocus()));
- resize(400,300);
- connect(messageLog_, SIGNAL(fontResized(int)), this, SIGNAL(fontResized(int)));
- connect(messageLog_, SIGNAL(logCleared()), this, SLOT(handleLogCleared()));
-
- treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtChatWindow::handleOccupantSelectionChanged, this, _1));
- treeWidget_->onOccupantActionSelected.connect(boost::bind(boost::ref(onOccupantActionSelected), _1, _2));
-
- settings_->onSettingChanged.connect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
- messageLog_->showEmoticons(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
- setMinimumSize(100, 100);
+ settings_ = settings;
+ unreadCount_ = 0;
+ isOnline_ = true;
+ completer_ = NULL;
+ affiliationEditor_ = NULL;
+ theme_ = theme;
+ isCorrection_ = false;
+ labelModel_ = NULL;
+ correctionEnabled_ = Maybe;
+ fileTransferEnabled_ = Maybe;
+ updateTitleWithUnreadCount();
+ assert(settings);
+ setAcceptDrops(true);
+
+ alertStyleSheet_ = ".QWidget, QTextEdit { background: rgb(255, 255, 153); color: black }";
+
+ QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout->setContentsMargins(0,0,0,0);
+ layout->setSpacing(2);
+
+ alertLayout_ = new QVBoxLayout();
+ layout->addLayout(alertLayout_);
+
+ subjectLayout_ = new QBoxLayout(QBoxLayout::LeftToRight);
+ subject_ = new QLineEdit(this);
+ subjectLayout_->addWidget(subject_);
+ setSubject("");
+ subject_->setReadOnly(true);
+
+ QPushButton* actionButton_ = new QPushButton(this);
+ actionButton_->setIcon(QIcon(":/icons/actions.png"));
+ connect(actionButton_, SIGNAL(clicked()), this, SLOT(handleActionButtonClicked()));
+ subject_->hide();
+
+ layout->addLayout(subjectLayout_);
+
+ logRosterSplitter_ = new QSplitter(this);
+ logRosterSplitter_->setAutoFillBackground(true);
+ layout->addWidget(logRosterSplitter_);
+ if (settings_->getSetting(QtUISettingConstants::USE_PLAIN_CHATS) || settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
+ messageLog_ = new QtPlainChatView(this, eventStream_);
+ }
+ else {
+ messageLog_ = new QtWebKitChatView(this, eventStream_, theme, this); // I accept that passing the ChatWindow in so that the view can call the signals is somewhat inelegant, but it saves a lot of boilerplate. This patch is unpleasant enough already. So let's fix this soon (it at least needs fixing by the time history is sorted), but not now.
+ }
+ logRosterSplitter_->addWidget(messageLog_);
+
+ treeWidget_ = new QtOccupantListWidget(eventStream_, settings_, QtTreeWidget::MessageDefaultJID, this);
+ treeWidget_->hide();
+ logRosterSplitter_->addWidget(treeWidget_);
+ logRosterSplitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+ connect(logRosterSplitter_, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int)));
+
+ midBar_ = new QWidget(this);
+ //layout->addWidget(midBar);
+ midBar_->setAutoFillBackground(true);
+ QHBoxLayout *midBarLayout = new QHBoxLayout(midBar_);
+ midBarLayout->setContentsMargins(0,0,0,0);
+ midBarLayout->setSpacing(2);
+ //midBarLayout->addStretch();
+
+ labelsWidget_ = new QComboBox(this);
+ labelsWidget_->setFocusPolicy(Qt::NoFocus);
+ labelsWidget_->hide();
+ labelsWidget_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
+ midBarLayout->addWidget(labelsWidget_,0);
+ connect(labelsWidget_, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentLabelChanged(int)));
+ defaultLabelsPalette_ = labelsWidget_->palette();
+
+ QHBoxLayout* inputBarLayout = new QHBoxLayout();
+ inputBarLayout->setContentsMargins(0,0,0,0);
+ inputBarLayout->setSpacing(2);
+ input_ = new QtTextEdit(settings_, this);
+ input_->setAcceptRichText(false);
+ inputBarLayout->addWidget(midBar_);
+ inputBarLayout->addWidget(input_);
+ correctingLabel_ = new QLabel(tr("Correcting"), this);
+ inputBarLayout->addWidget(correctingLabel_);
+ correctingLabel_->hide();
+
+ connect(input_, SIGNAL(receivedFocus()), this, SLOT(handleTextInputReceivedFocus()));
+ connect(input_, SIGNAL(lostFocus()), this, SLOT(handleTextInputLostFocus()));
+ QPushButton* emoticonsButton_ = new QPushButton(this);
+ emoticonsButton_->setIcon(QIcon(":/emoticons/smile.png"));
+ connect(emoticonsButton_, SIGNAL(clicked()), this, SLOT(handleEmoticonsButtonClicked()));
+
+ emoticonsMenu_ = new QMenu(this);
+ QtEmoticonsGrid* emoticonsGrid = new QtEmoticonsGrid(emoticons, emoticonsMenu_);
+ connect(emoticonsGrid, SIGNAL(emoticonClicked(QString)), this, SLOT(handleEmoticonClicked(QString)));
+
+ // using an extra layout to work around Qt margin glitches on OS X
+ QHBoxLayout* actionLayout = new QHBoxLayout();
+ actionLayout->addWidget(emoticonsButton_);
+ actionLayout->addWidget(actionButton_);
+
+ inputBarLayout->addLayout(actionLayout);
+ layout->addLayout(inputBarLayout);
+
+ inputClearing_ = false;
+ contactIsTyping_ = false;
+ tabCompletion_ = false;
+
+ connect(input_, SIGNAL(unhandledKeyPressEvent(QKeyEvent*)), this, SLOT(handleKeyPressEvent(QKeyEvent*)));
+ connect(input_, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
+ connect(input_, SIGNAL(textChanged()), this, SLOT(handleInputChanged()));
+ connect(input_, SIGNAL(cursorPositionChanged()), this, SLOT(handleCursorPositionChanged()));
+ setFocusProxy(input_);
+ logRosterSplitter_->setFocusProxy(input_);
+ midBar_->setFocusProxy(input_);
+ messageLog_->setFocusProxy(input_);
+ connect(messageLog_, SIGNAL(gotFocus()), input_, SLOT(setFocus()));
+ resize(400,300);
+ connect(messageLog_, SIGNAL(fontResized(int)), this, SIGNAL(fontResized(int)));
+ connect(messageLog_, SIGNAL(logCleared()), this, SLOT(handleLogCleared()));
+
+ treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtChatWindow::handleOccupantSelectionChanged, this, _1));
+ treeWidget_->onOccupantActionSelected.connect(boost::bind(boost::ref(onOccupantActionSelected), _1, _2));
+
+ settings_->onSettingChanged.connect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
+ messageLog_->showEmoticons(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ setMinimumSize(100, 100);
}
QtChatWindow::~QtChatWindow() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
- if (mucConfigurationWindow_) {
- delete mucConfigurationWindow_.data();
- }
+ settings_->onSettingChanged.disconnect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
+ if (mucConfigurationWindow_) {
+ delete mucConfigurationWindow_.data();
+ }
}
void QtChatWindow::handleSettingChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
- bool showEmoticons = settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS);
- messageLog_->showEmoticons(showEmoticons);
- }
+ if (setting == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
+ bool showEmoticons = settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS);
+ messageLog_->showEmoticons(showEmoticons);
+ }
}
void QtChatWindow::handleLogCleared() {
- onLogCleared();
+ onLogCleared();
}
void QtChatWindow::handleOccupantSelectionChanged(RosterItem* item) {
- onOccupantSelectionChanged(dynamic_cast<ContactRosterItem*>(item));
+ onOccupantSelectionChanged(dynamic_cast<ContactRosterItem*>(item));
}
void QtChatWindow::handleFontResized(int fontSizeSteps) {
- messageLog_->resizeFont(fontSizeSteps);
+ messageLog_->resizeFont(fontSizeSteps);
}
void QtChatWindow::handleAlertButtonClicked() {
- const QObject* alertWidget = QObject::sender()->parent();
- std::map<AlertID, QWidget*>::const_iterator i = alertWidgets_.begin();
- for ( ; i != alertWidgets_.end(); ++i) {
- if (i->second == alertWidget) {
- removeAlert(i->first);
- break;
- }
- }
+ const QObject* alertWidget = QObject::sender()->parent();
+ std::map<AlertID, QWidget*>::const_iterator i = alertWidgets_.begin();
+ for ( ; i != alertWidgets_.end(); ++i) {
+ if (i->second == alertWidget) {
+ removeAlert(i->first);
+ break;
+ }
+ }
}
QtChatWindow::AlertID QtChatWindow::addAlert(const std::string& alertText) {
- QWidget* alertWidget = new QWidget(this);
- QHBoxLayout* alertLayout = new QHBoxLayout(alertWidget);
- alertLayout_->addWidget(alertWidget);
- QLabel* alertLabel = new QLabel(this);
- alertLabel->setText(alertText.c_str());
- alertLayout->addWidget(alertLabel);
-
- QToolButton* closeButton = new QToolButton(alertWidget);
- closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
- closeButton->setIconSize(QSize(16,16));
- closeButton->setCursor(Qt::ArrowCursor);
- closeButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
- connect (closeButton, SIGNAL(clicked()), this, SLOT(handleAlertButtonClicked()));
-
- alertLayout->addWidget(closeButton);
- QPalette palette = alertWidget->palette();
- palette.setColor(QPalette::Window, QColor(Qt::yellow));
- palette.setColor(QPalette::WindowText, QColor(Qt::black));
- alertWidget->setStyleSheet(alertStyleSheet_);
- alertLabel->setStyleSheet(alertStyleSheet_);
-
- AlertID id = nextAlertId_++;
- alertWidgets_[id] = alertWidget;
- return id;
+ QWidget* alertWidget = new QWidget(this);
+ QHBoxLayout* alertLayout = new QHBoxLayout(alertWidget);
+ alertLayout_->addWidget(alertWidget);
+ QLabel* alertLabel = new QLabel(this);
+ alertLabel->setText(alertText.c_str());
+ alertLayout->addWidget(alertLabel);
+
+ QToolButton* closeButton = new QToolButton(alertWidget);
+ closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
+ closeButton->setIconSize(QSize(16,16));
+ closeButton->setCursor(Qt::ArrowCursor);
+ closeButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
+ connect (closeButton, SIGNAL(clicked()), this, SLOT(handleAlertButtonClicked()));
+
+ alertLayout->addWidget(closeButton);
+ QPalette palette = alertWidget->palette();
+ palette.setColor(QPalette::Window, QColor(Qt::yellow));
+ palette.setColor(QPalette::WindowText, QColor(Qt::black));
+ alertWidget->setStyleSheet(alertStyleSheet_);
+ alertLabel->setStyleSheet(alertStyleSheet_);
+
+ AlertID id = nextAlertId_++;
+ alertWidgets_[id] = alertWidget;
+ return id;
}
void QtChatWindow::removeAlert(const AlertID id) {
- std::map<AlertID, QWidget*>::iterator i = alertWidgets_.find(id);
- if (i != alertWidgets_.end()) {
- alertLayout_->removeWidget(i->second);
- delete i->second;
- alertWidgets_.erase(i);
- }
+ std::map<AlertID, QWidget*>::iterator i = alertWidgets_.find(id);
+ if (i != alertWidgets_.end()) {
+ alertLayout_->removeWidget(i->second);
+ delete i->second;
+ alertWidgets_.erase(i);
+ }
}
void QtChatWindow::setTabComplete(TabComplete* completer) {
- completer_ = completer;
+ completer_ = completer;
}
void QtChatWindow::handleKeyPressEvent(QKeyEvent* event) {
- event->ignore();
- if (event->isAccepted()) {
- return;
- }
- event->accept();
-
- int key = event->key();
- if (key == Qt::Key_Tab) {
- tabComplete();
- }
- else if ((key == Qt::Key_Up) && input_->toPlainText().isEmpty() && !(lastSentMessage_.isEmpty())) {
- beginCorrection();
- }
- else if (key == Qt::Key_Down && isCorrection_ && input_->textCursor().atBlockEnd()) {
- cancelCorrection();
- }
- else if (key == Qt::Key_Down || key == Qt::Key_Up) {
- event->ignore();
- }
- else {
- messageLog_->handleKeyPressEvent(event);
- }
+ event->ignore();
+ if (event->isAccepted()) {
+ return;
+ }
+ event->accept();
+
+ int key = event->key();
+ if (key == Qt::Key_Tab) {
+ tabComplete();
+ }
+ else if ((key == Qt::Key_Up) && input_->toPlainText().isEmpty() && !(lastSentMessage_.isEmpty())) {
+ beginCorrection();
+ }
+ else if (key == Qt::Key_Down && isCorrection_ && input_->textCursor().atBlockEnd()) {
+ cancelCorrection();
+ }
+ else if (key == Qt::Key_Down || key == Qt::Key_Up) {
+ event->ignore();
+ }
+ else {
+ messageLog_->handleKeyPressEvent(event);
+ }
}
void QtChatWindow::beginCorrection() {
- boost::optional<AlertID> newCorrectingAlert;
- if (correctionEnabled_ == Maybe) {
- newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat may not support message correction. If you send a correction anyway, it may appear as a duplicate message")));
- }
- else if (correctionEnabled_ == No) {
- newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat does not support message correction. If you send a correction anyway, it will appear as a duplicate message")));
- }
-
- if (newCorrectingAlert) {
- if (correctingAlert_) {
- removeAlert(*correctingAlert_);
- }
- correctingAlert_ = newCorrectingAlert;
- }
-
- QTextCursor cursor = input_->textCursor();
- cursor.select(QTextCursor::Document);
- cursor.beginEditBlock();
- cursor.insertText(QString(lastSentMessage_));
- cursor.endEditBlock();
- isCorrection_ = true;
- correctingLabel_->show();
- input_->setStyleSheet(alertStyleSheet_);
- labelsWidget_->setEnabled(false);
+ boost::optional<AlertID> newCorrectingAlert;
+ if (correctionEnabled_ == Maybe) {
+ newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat may not support message correction. If you send a correction anyway, it may appear as a duplicate message")));
+ }
+ else if (correctionEnabled_ == No) {
+ newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat does not support message correction. If you send a correction anyway, it will appear as a duplicate message")));
+ }
+
+ if (newCorrectingAlert) {
+ if (correctingAlert_) {
+ removeAlert(*correctingAlert_);
+ }
+ correctingAlert_ = newCorrectingAlert;
+ }
+
+ QTextCursor cursor = input_->textCursor();
+ cursor.select(QTextCursor::Document);
+ cursor.beginEditBlock();
+ cursor.insertText(QString(lastSentMessage_));
+ cursor.endEditBlock();
+ isCorrection_ = true;
+ correctingLabel_->show();
+ input_->setStyleSheet(alertStyleSheet_);
+ labelsWidget_->setEnabled(false);
}
void QtChatWindow::cancelCorrection() {
- if (correctingAlert_) {
- removeAlert(*correctingAlert_);
- correctingAlert_.reset();
- }
- QTextCursor cursor = input_->textCursor();
- cursor.select(QTextCursor::Document);
- cursor.removeSelectedText();
- isCorrection_ = false;
- correctingLabel_->hide();
- input_->setStyleSheet(qApp->styleSheet());
- labelsWidget_->setEnabled(true);
+ if (correctingAlert_) {
+ removeAlert(*correctingAlert_);
+ correctingAlert_.reset();
+ }
+ QTextCursor cursor = input_->textCursor();
+ cursor.select(QTextCursor::Document);
+ cursor.removeSelectedText();
+ isCorrection_ = false;
+ correctingLabel_->hide();
+ input_->setStyleSheet(qApp->styleSheet());
+ labelsWidget_->setEnabled(true);
}
QByteArray QtChatWindow::getSplitterState() {
- return logRosterSplitter_->saveState();
+ return logRosterSplitter_->saveState();
}
void QtChatWindow::handleChangeSplitterState(QByteArray state) {
- logRosterSplitter_->restoreState(state);
+ logRosterSplitter_->restoreState(state);
}
void QtChatWindow::handleSplitterMoved(int, int) {
- emit splitterMoved();
+ emit splitterMoved();
}
void QtChatWindow::tabComplete() {
- if (!completer_) {
- return;
- }
-
- QTextCursor cursor;
- if (tabCompleteCursor_.hasSelection()) {
- cursor = tabCompleteCursor_;
- }
- else {
- cursor = input_->textCursor();
- while(cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor) && cursor.document()->characterAt(cursor.position() - 1) != ' ') { }
- }
- QString root = cursor.selectedText();
- if (root.isEmpty()) {
- return;
- }
- QString suggestion = P2QSTRING(completer_->completeWord(Q2PSTRING(root)));
- if (root == suggestion) {
- return;
- }
- tabCompletion_ = true;
- cursor.beginEditBlock();
- cursor.removeSelectedText();
- int oldPosition = cursor.position();
-
- cursor.insertText(suggestion);
- tabCompleteCursor_ = cursor;
- tabCompleteCursor_.setPosition(oldPosition, QTextCursor::KeepAnchor);
-
- cursor.endEditBlock();
- tabCompletion_ = false;
+ if (!completer_) {
+ return;
+ }
+
+ QTextCursor cursor;
+ if (tabCompleteCursor_.hasSelection()) {
+ cursor = tabCompleteCursor_;
+ }
+ else {
+ cursor = input_->textCursor();
+ while(cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor) && cursor.document()->characterAt(cursor.position() - 1) != ' ') { }
+ }
+ QString root = cursor.selectedText();
+ if (root.isEmpty()) {
+ return;
+ }
+ QString suggestion = P2QSTRING(completer_->completeWord(Q2PSTRING(root)));
+ if (root == suggestion) {
+ return;
+ }
+ tabCompletion_ = true;
+ cursor.beginEditBlock();
+ cursor.removeSelectedText();
+ int oldPosition = cursor.position();
+
+ cursor.insertText(suggestion);
+ tabCompleteCursor_ = cursor;
+ tabCompleteCursor_.setPosition(oldPosition, QTextCursor::KeepAnchor);
+
+ cursor.endEditBlock();
+ tabCompletion_ = false;
}
void QtChatWindow::setRosterModel(Roster* roster) {
- treeWidget_->setRosterModel(roster);
+ treeWidget_->setRosterModel(roster);
}
void QtChatWindow::setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels) {
- delete labelModel_;
- labelModel_ = new LabelModel();
- labelModel_->availableLabels_ = labels;
- int i = 0;
- int defaultIndex = 0;
- labelsWidget_->setModel(labelModel_);
- foreach (SecurityLabelsCatalog::Item label, labels) {
- if (label.getIsDefault()) {
- defaultIndex = i;
- break;
- }
- i++;
- }
- labelsWidget_->setCurrentIndex(defaultIndex);
+ delete labelModel_;
+ labelModel_ = new LabelModel();
+ labelModel_->availableLabels_ = labels;
+ int i = 0;
+ int defaultIndex = 0;
+ labelsWidget_->setModel(labelModel_);
+ foreach (SecurityLabelsCatalog::Item label, labels) {
+ if (label.getIsDefault()) {
+ defaultIndex = i;
+ break;
+ }
+ i++;
+ }
+ labelsWidget_->setCurrentIndex(defaultIndex);
}
void QtChatWindow::handleCurrentLabelChanged(int index) {
- if (static_cast<size_t>(index) >= labelModel_->availableLabels_.size()) {
- SWIFT_LOG(debug) << "User selected a label that doesn't exist";
- return;
- }
- const SecurityLabelsCatalog::Item& label = labelModel_->availableLabels_[index];
- if (label.getLabel()) {
- QPalette palette = labelsWidget_->palette();
- //palette.setColor(QPalette::Base, P2QSTRING(label.getLabel()->getBackgroundColor()));
- palette.setColor(labelsWidget_->backgroundRole(), P2QSTRING(label.getLabel()->getBackgroundColor()));
- palette.setColor(labelsWidget_->foregroundRole(), P2QSTRING(label.getLabel()->getForegroundColor()));
- labelsWidget_->setPalette(palette);
- midBar_->setPalette(palette);
- labelsWidget_->setAutoFillBackground(true);
- }
- else {
- labelsWidget_->setAutoFillBackground(false);
- labelsWidget_->setPalette(defaultLabelsPalette_);
- midBar_->setPalette(defaultLabelsPalette_);
- }
+ if (static_cast<size_t>(index) >= labelModel_->availableLabels_.size()) {
+ SWIFT_LOG(debug) << "User selected a label that doesn't exist";
+ return;
+ }
+ const SecurityLabelsCatalog::Item& label = labelModel_->availableLabels_[index];
+ if (label.getLabel()) {
+ QPalette palette = labelsWidget_->palette();
+ //palette.setColor(QPalette::Base, P2QSTRING(label.getLabel()->getBackgroundColor()));
+ palette.setColor(labelsWidget_->backgroundRole(), P2QSTRING(label.getLabel()->getBackgroundColor()));
+ palette.setColor(labelsWidget_->foregroundRole(), P2QSTRING(label.getLabel()->getForegroundColor()));
+ labelsWidget_->setPalette(palette);
+ midBar_->setPalette(palette);
+ labelsWidget_->setAutoFillBackground(true);
+ }
+ else {
+ labelsWidget_->setAutoFillBackground(false);
+ labelsWidget_->setPalette(defaultLabelsPalette_);
+ midBar_->setPalette(defaultLabelsPalette_);
+ }
}
void QtChatWindow::setSecurityLabelsError() {
- labelsWidget_->setEnabled(false);
+ labelsWidget_->setEnabled(false);
}
void QtChatWindow::setSecurityLabelsEnabled(bool enabled) {
- if (enabled) {
- labelsWidget_->setEnabled(true);
- labelsWidget_->show();
- }
- else {
- labelsWidget_->hide();
- }
+ if (enabled) {
+ labelsWidget_->setEnabled(true);
+ labelsWidget_->show();
+ }
+ else {
+ labelsWidget_->hide();
+ }
}
void QtChatWindow::setCorrectionEnabled(Tristate enabled) {
- correctionEnabled_ = enabled;
+ correctionEnabled_ = enabled;
}
void QtChatWindow::setFileTransferEnabled(Tristate enabled) {
- fileTransferEnabled_ = enabled;
+ fileTransferEnabled_ = enabled;
}
SecurityLabelsCatalog::Item QtChatWindow::getSelectedSecurityLabel() {
- assert(labelsWidget_->isEnabled());
- assert(labelsWidget_->currentIndex() >= 0 && static_cast<size_t>(labelsWidget_->currentIndex()) < labelModel_->availableLabels_.size());
- return labelModel_->availableLabels_[labelsWidget_->currentIndex()];
+ assert(labelsWidget_->isEnabled());
+ assert(labelsWidget_->currentIndex() >= 0 && static_cast<size_t>(labelsWidget_->currentIndex()) < labelModel_->availableLabels_.size());
+ return labelModel_->availableLabels_[labelsWidget_->currentIndex()];
}
void QtChatWindow::closeEvent(QCloseEvent* event) {
- event->accept();
- emit windowClosing();
- onClosed();
+ event->accept();
+ emit windowClosing();
+ onClosed();
}
void QtChatWindow::convertToMUC(MUCType mucType) {
- impromptu_ = (mucType == ImpromptuMUC);
- treeWidget_->setMessageTarget(impromptu_ ? QtTreeWidget::MessageDisplayJID : QtTreeWidget::MessageDefaultJID);
- isMUC_ = true;
- treeWidget_->show();
- subject_->setVisible(!impromptu_);
+ impromptu_ = (mucType == ImpromptuMUC);
+ treeWidget_->setMessageTarget(impromptu_ ? QtTreeWidget::MessageDisplayJID : QtTreeWidget::MessageDefaultJID);
+ isMUC_ = true;
+ treeWidget_->show();
+ subject_->setVisible(!impromptu_);
}
void QtChatWindow::setOnline(bool online) {
- isOnline_ = online;
- if (!online) {
- if (mucConfigurationWindow_) {
- delete mucConfigurationWindow_.data();
- }
- if (affiliationEditor_) {
- delete affiliationEditor_.data();
- }
- }
+ isOnline_ = online;
+ if (!online) {
+ if (mucConfigurationWindow_) {
+ delete mucConfigurationWindow_.data();
+ }
+ if (affiliationEditor_) {
+ delete affiliationEditor_.data();
+ }
+ }
}
void QtChatWindow::showEvent(QShowEvent* event) {
- emit windowOpening();
- QWidget::showEvent(event);
+ emit windowOpening();
+ QWidget::showEvent(event);
}
void QtChatWindow::setUnreadMessageCount(int count) {
- if (unreadCount_ != count) {
- unreadCount_ = count;
- updateTitleWithUnreadCount();
- emit countUpdated();
- }
+ if (unreadCount_ != count) {
+ unreadCount_ = count;
+ updateTitleWithUnreadCount();
+ emit countUpdated();
+ }
}
void QtChatWindow::setContactChatState(ChatState::ChatStateType state) {
- contactIsTyping_ = (state == ChatState::Composing);
- emit titleUpdated();
+ contactIsTyping_ = (state == ChatState::Composing);
+ emit titleUpdated();
}
QtTabbable::AlertType QtChatWindow::getWidgetAlertState() {
- if (contactIsTyping_) {
- return ImpendingActivity;
- }
- if (unreadCount_ > 0) {
- return WaitingActivity;
- }
- return NoActivity;
+ if (contactIsTyping_) {
+ return ImpendingActivity;
+ }
+ if (unreadCount_ > 0) {
+ return WaitingActivity;
+ }
+ return NoActivity;
}
void QtChatWindow::setName(const std::string& name) {
- contact_ = P2QSTRING(name);
- updateTitleWithUnreadCount();
+ contact_ = P2QSTRING(name);
+ updateTitleWithUnreadCount();
}
void QtChatWindow::updateTitleWithUnreadCount() {
- if (isWindow()) {
- setWindowTitle(unreadCount_ > 0 ? QString("(%1) %2").arg(unreadCount_).arg(contact_) : contact_);
- }
- else {
- setWindowTitle(contact_);
- }
- emit titleUpdated();
+ if (isWindow()) {
+ setWindowTitle(unreadCount_ > 0 ? QString("(%1) %2").arg(unreadCount_).arg(contact_) : contact_);
+ }
+ else {
+ setWindowTitle(contact_);
+ }
+ emit titleUpdated();
}
void QtChatWindow::flash() {
- emit requestFlash();
+ emit requestFlash();
}
int QtChatWindow::getCount() {
- return unreadCount_;
+ return unreadCount_;
}
void QtChatWindow::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- messageLog_->replaceSystemMessage(message, id, timestampBehaviour);
+ messageLog_->replaceSystemMessage(message, id, timestampBehaviour);
}
void QtChatWindow::returnPressed() {
- if (!isOnline_ || (blockingState_ == IsBlocked)) {
- return;
- }
- messageLog_->scrollToBottom();
- lastSentMessage_ = QString(input_->toPlainText());
- onSendMessageRequest(Q2PSTRING(input_->toPlainText()), isCorrection_);
- inputClearing_ = true;
- input_->clear();
- cancelCorrection();
- inputClearing_ = false;
+ if (!isOnline_ || (blockingState_ == IsBlocked)) {
+ return;
+ }
+ messageLog_->scrollToBottom();
+ lastSentMessage_ = QString(input_->toPlainText());
+ onSendMessageRequest(Q2PSTRING(input_->toPlainText()), isCorrection_);
+ inputClearing_ = true;
+ input_->clear();
+ cancelCorrection();
+ inputClearing_ = false;
}
void QtChatWindow::handleInputChanged() {
- if (inputClearing_) {
- return;
- }
- if (input_->toPlainText().isEmpty()) {
- onUserCancelsTyping();
- }
- else {
- onUserTyping();
- }
+ if (inputClearing_) {
+ return;
+ }
+ if (input_->toPlainText().isEmpty()) {
+ onUserCancelsTyping();
+ }
+ else {
+ onUserTyping();
+ }
}
void QtChatWindow::handleCursorPositionChanged() {
- if (tabCompletion_) {
- return;
- }
- tabCompleteCursor_.clearSelection();
+ if (tabCompletion_) {
+ return;
+ }
+ tabCompleteCursor_.clearSelection();
}
void QtChatWindow::show() {
- if (parentWidget() == NULL) {
- QWidget::show();
- }
- emit windowOpening();
+ if (parentWidget() == NULL) {
+ QWidget::show();
+ }
+ emit windowOpening();
}
bool QtChatWindow::isVisible() const {
- return QWidget::isVisible();
+ return QWidget::isVisible();
}
void QtChatWindow::activate() {
- if (isWindow()) {
- QWidget::show();
- }
- emit wantsToActivate();
- input_->setFocus();
+ if (isWindow()) {
+ QWidget::show();
+ }
+ emit wantsToActivate();
+ input_->setFocus();
}
void QtChatWindow::resizeEvent(QResizeEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatWindow::moveEvent(QMoveEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatWindow::dragEnterEvent(QDragEnterEvent *event) {
- if (isOnline_ && (blockingState_ != IsBlocked)) {
- if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
- if (!isMUC_ && fileTransferEnabled_ == Yes) {
- event->acceptProposedAction();
- }
- }
- else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
- if (isMUC_ || supportsImpromptuChat_) {
- // Prevent invitations or impromptu initializations for contacts that you are already chatting to.
- std::vector<JID> droppedJIDs =jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
- std::set<JID> conversationJIDs;
- if (isMUC_) {
- conversationJIDs = treeWidget_->getRoster()->getJIDs();
- }
-
- for (std::vector<JID>::iterator i = droppedJIDs.begin(); i != droppedJIDs.end(); ) {
- const JID& droppedJID = *i;
- if (conversationJIDs.find(droppedJID) != conversationJIDs.end()) {
- i = droppedJIDs.erase(i);
- }
- else {
- ++i;
- }
- }
-
- if (droppedJIDs.empty()) {
- event->ignore();
- }
- else {
- event->acceptProposedAction();
- }
- }
- }
- }
+ if (isOnline_ && (blockingState_ != IsBlocked)) {
+ if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
+ if (!isMUC_ && fileTransferEnabled_ == Yes) {
+ event->acceptProposedAction();
+ }
+ }
+ else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
+ if (isMUC_ || supportsImpromptuChat_) {
+ // Prevent invitations or impromptu initializations for contacts that you are already chatting to.
+ std::vector<JID> droppedJIDs =jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
+ std::set<JID> conversationJIDs;
+ if (isMUC_) {
+ conversationJIDs = treeWidget_->getRoster()->getJIDs();
+ }
+
+ for (std::vector<JID>::iterator i = droppedJIDs.begin(); i != droppedJIDs.end(); ) {
+ const JID& droppedJID = *i;
+ if (conversationJIDs.find(droppedJID) != conversationJIDs.end()) {
+ i = droppedJIDs.erase(i);
+ }
+ else {
+ ++i;
+ }
+ }
+
+ if (droppedJIDs.empty()) {
+ event->ignore();
+ }
+ else {
+ event->acceptProposedAction();
+ }
+ }
+ }
+ }
}
void QtChatWindow::dropEvent(QDropEvent *event) {
- if (fileTransferEnabled_ == Yes && event->mimeData()->hasUrls()) {
- if (event->mimeData()->urls().size() == 1) {
- onSendFileRequest(Q2PSTRING(event->mimeData()->urls().at(0).toLocalFile()));
- }
- else {
- std::string messageText(Q2PSTRING(tr("Sending of multiple files at once isn't supported at this time.")));
- ChatMessage message;
- message.append(boost::make_shared<ChatTextMessagePart>(messageText));
- addSystemMessage(message, DefaultDirection);
- }
- }
- else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
- std::vector<JID> invites = jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
- onInviteToChat(invites);
- }
+ if (fileTransferEnabled_ == Yes && event->mimeData()->hasUrls()) {
+ if (event->mimeData()->urls().size() == 1) {
+ onSendFileRequest(Q2PSTRING(event->mimeData()->urls().at(0).toLocalFile()));
+ }
+ else {
+ std::string messageText(Q2PSTRING(tr("Sending of multiple files at once isn't supported at this time.")));
+ ChatMessage message;
+ message.append(boost::make_shared<ChatTextMessagePart>(messageText));
+ addSystemMessage(message, DefaultDirection);
+ }
+ }
+ else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
+ std::vector<JID> invites = jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
+ onInviteToChat(invites);
+ }
}
std::vector<JID> QtChatWindow::jidListFromQByteArray(const QByteArray& dataBytes) {
- QDataStream dataStream(dataBytes);
- std::vector<JID> invites;
- while (!dataStream.atEnd()) {
- QString jidString;
- dataStream >> jidString;
- invites.push_back(Q2PSTRING(jidString));
- }
- return invites;
+ QDataStream dataStream(dataBytes);
+ std::vector<JID> invites;
+ while (!dataStream.atEnd()) {
+ QString jidString;
+ dataStream >> jidString;
+ invites.push_back(Q2PSTRING(jidString));
+ }
+ return invites;
}
void QtChatWindow::setAvailableOccupantActions(const std::vector<OccupantAction>& actions) {
- treeWidget_->setAvailableOccupantActions(actions);
+ treeWidget_->setAvailableOccupantActions(actions);
}
void QtChatWindow::setSubject(const std::string& subject) {
- //subject_->setVisible(!subject.empty());
- subject_->setText(P2QSTRING(subject));
- subject_->setToolTip(P2QSTRING(subject));
- subject_->setCursorPosition(0);
+ //subject_->setVisible(!subject.empty());
+ subject_->setText(P2QSTRING(subject));
+ subject_->setToolTip(P2QSTRING(subject));
+ subject_->setCursorPosition(0);
}
void QtChatWindow::handleEmoticonsButtonClicked() {
- emoticonsMenu_->adjustSize();
- QSize menuSize = emoticonsMenu_->size();
- emoticonsMenu_->exec(QPoint(QCursor::pos().x() - menuSize.width(), QCursor::pos().y() - menuSize.height()));
+ emoticonsMenu_->adjustSize();
+ QSize menuSize = emoticonsMenu_->size();
+ emoticonsMenu_->exec(QPoint(QCursor::pos().x() - menuSize.width(), QCursor::pos().y() - menuSize.height()));
}
void QtChatWindow::handleEmoticonClicked(QString emoticonAsText) {
- input_->textCursor().insertText(emoticonAsText);
- input_->setFocus();
+ input_->textCursor().insertText(emoticonAsText);
+ input_->setFocus();
}
void QtChatWindow::handleTextInputReceivedFocus() {
- lastLineTracker_.setHasFocus(true);
- input_->setFocus();
- onAllMessagesRead();
+ lastLineTracker_.setHasFocus(true);
+ input_->setFocus();
+ onAllMessagesRead();
}
void QtChatWindow::handleTextInputLostFocus() {
- lastLineTracker_.setHasFocus(false);
+ lastLineTracker_.setHasFocus(false);
}
void QtChatWindow::handleActionButtonClicked() {
- QMenu contextMenu;
- QAction* changeSubject = NULL;
- QAction* configure = NULL;
- QAction* affiliations = NULL;
- QAction* destroy = NULL;
- QAction* invite = NULL;
-
- QAction* block = NULL;
- QAction* unblock = NULL;
-
- if (availableRoomActions_.empty()) {
- if (blockingState_ == IsBlocked) {
- unblock = contextMenu.addAction(tr("Unblock"));
- unblock->setEnabled(isOnline_);
- }
- else if (!isMUC_ && blockingState_ == IsUnblocked) {
- block = contextMenu.addAction(tr("Block"));
- block->setEnabled(isOnline_);
- }
-
- if (supportsImpromptuChat_) {
- invite = contextMenu.addAction(tr("Invite person to this chat…"));
- invite->setEnabled(isOnline_ && (blockingState_ != IsBlocked));
- }
-
- }
- else {
- foreach(ChatWindow::RoomAction availableAction, availableRoomActions_)
- {
- if (impromptu_) {
- // hide options we don't need in impromptu chats
- if (availableAction == ChatWindow::ChangeSubject ||
- availableAction == ChatWindow::Configure ||
- availableAction == ChatWindow::Affiliations ||
- availableAction == ChatWindow::Destroy) {
- continue;
- }
- }
- switch(availableAction)
- {
- case ChatWindow::ChangeSubject:
- changeSubject = contextMenu.addAction(tr("Change subject…"));
- changeSubject->setEnabled(isOnline_);
- break;
- case ChatWindow::Configure:
- configure = contextMenu.addAction(tr("Configure room…"));
- configure->setEnabled(isOnline_);
- break;
- case ChatWindow::Affiliations:
- affiliations = contextMenu.addAction(tr("Edit affiliations…"));
- affiliations->setEnabled(isOnline_);
- break;
- case ChatWindow::Destroy:
- destroy = contextMenu.addAction(tr("Destroy room"));
- destroy->setEnabled(isOnline_);
- break;
- case ChatWindow::Invite:
- invite = contextMenu.addAction(tr("Invite person to this room…"));
- invite->setEnabled(isOnline_);
- break;
- }
- }
- }
-
- QAction* bookmark = NULL;
- if (isMUC_) {
- if (roomBookmarkState_ == RoomNotBookmarked) {
- bookmark = contextMenu.addAction(tr("Bookmark this room..."));
- }
- else {
- bookmark = contextMenu.addAction(tr("Edit bookmark..."));
- }
- bookmark->setEnabled(isOnline_);
- }
-
- QAction* result = contextMenu.exec(QCursor::pos());
- if (result == NULL) {
- /* Skip processing. Note that otherwise, because the actions could be null they could match */
- }
- else if (result == changeSubject) {
- bool ok;
- QString subject = QInputDialog::getText(this, tr("Change room subject"), tr("New subject:"), QLineEdit::Normal, subject_->text(), &ok);
- if (ok) {
- onChangeSubjectRequest(Q2PSTRING(subject));
- }
- }
- else if (result == configure) {
- onConfigureRequest(Form::ref());
- }
- else if (result == affiliations) {
- if (!affiliationEditor_) {
- onGetAffiliationsRequest();
- affiliationEditor_ = new QtAffiliationEditor(this);
- connect(affiliationEditor_, SIGNAL(accepted()), this, SLOT(handleAffiliationEditorAccepted()));
- }
- affiliationEditor_->show();
- }
- else if (result == destroy) {
- QMessageBox msgBox;
- msgBox.setWindowTitle(tr("Confirm room destruction"));
- msgBox.setText(tr("Are you sure you want to destroy the room?"));
- msgBox.setInformativeText(tr("This will destroy the room."));
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::No);
- if (msgBox.exec() == QMessageBox::Yes) {
- onDestroyRequest();
- }
- }
- else if (result == invite) {
- onInviteToChat(std::vector<JID>());
- }
- else if (result == block) {
- onBlockUserRequest();
- }
- else if (result == unblock) {
- onUnblockUserRequest();
- }
- else if (result == bookmark) {
- onBookmarkRequest();
- }
+ QMenu contextMenu;
+ QAction* changeSubject = NULL;
+ QAction* configure = NULL;
+ QAction* affiliations = NULL;
+ QAction* destroy = NULL;
+ QAction* invite = NULL;
+
+ QAction* block = NULL;
+ QAction* unblock = NULL;
+
+ if (availableRoomActions_.empty()) {
+ if (blockingState_ == IsBlocked) {
+ unblock = contextMenu.addAction(tr("Unblock"));
+ unblock->setEnabled(isOnline_);
+ }
+ else if (!isMUC_ && blockingState_ == IsUnblocked) {
+ block = contextMenu.addAction(tr("Block"));
+ block->setEnabled(isOnline_);
+ }
+
+ if (supportsImpromptuChat_) {
+ invite = contextMenu.addAction(tr("Invite person to this chat…"));
+ invite->setEnabled(isOnline_ && (blockingState_ != IsBlocked));
+ }
+
+ }
+ else {
+ foreach(ChatWindow::RoomAction availableAction, availableRoomActions_)
+ {
+ if (impromptu_) {
+ // hide options we don't need in impromptu chats
+ if (availableAction == ChatWindow::ChangeSubject ||
+ availableAction == ChatWindow::Configure ||
+ availableAction == ChatWindow::Affiliations ||
+ availableAction == ChatWindow::Destroy) {
+ continue;
+ }
+ }
+ switch(availableAction)
+ {
+ case ChatWindow::ChangeSubject:
+ changeSubject = contextMenu.addAction(tr("Change subject…"));
+ changeSubject->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Configure:
+ configure = contextMenu.addAction(tr("Configure room…"));
+ configure->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Affiliations:
+ affiliations = contextMenu.addAction(tr("Edit affiliations…"));
+ affiliations->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Destroy:
+ destroy = contextMenu.addAction(tr("Destroy room"));
+ destroy->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Invite:
+ invite = contextMenu.addAction(tr("Invite person to this room…"));
+ invite->setEnabled(isOnline_);
+ break;
+ }
+ }
+ }
+
+ QAction* bookmark = NULL;
+ if (isMUC_) {
+ if (roomBookmarkState_ == RoomNotBookmarked) {
+ bookmark = contextMenu.addAction(tr("Bookmark this room..."));
+ }
+ else {
+ bookmark = contextMenu.addAction(tr("Edit bookmark..."));
+ }
+ bookmark->setEnabled(isOnline_);
+ }
+
+ QAction* result = contextMenu.exec(QCursor::pos());
+ if (result == NULL) {
+ /* Skip processing. Note that otherwise, because the actions could be null they could match */
+ }
+ else if (result == changeSubject) {
+ bool ok;
+ QString subject = QInputDialog::getText(this, tr("Change room subject"), tr("New subject:"), QLineEdit::Normal, subject_->text(), &ok);
+ if (ok) {
+ onChangeSubjectRequest(Q2PSTRING(subject));
+ }
+ }
+ else if (result == configure) {
+ onConfigureRequest(Form::ref());
+ }
+ else if (result == affiliations) {
+ if (!affiliationEditor_) {
+ onGetAffiliationsRequest();
+ affiliationEditor_ = new QtAffiliationEditor(this);
+ connect(affiliationEditor_, SIGNAL(accepted()), this, SLOT(handleAffiliationEditorAccepted()));
+ }
+ affiliationEditor_->show();
+ }
+ else if (result == destroy) {
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(tr("Confirm room destruction"));
+ msgBox.setText(tr("Are you sure you want to destroy the room?"));
+ msgBox.setInformativeText(tr("This will destroy the room."));
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::No);
+ if (msgBox.exec() == QMessageBox::Yes) {
+ onDestroyRequest();
+ }
+ }
+ else if (result == invite) {
+ onInviteToChat(std::vector<JID>());
+ }
+ else if (result == block) {
+ onBlockUserRequest();
+ }
+ else if (result == unblock) {
+ onUnblockUserRequest();
+ }
+ else if (result == bookmark) {
+ onBookmarkRequest();
+ }
}
void QtChatWindow::handleAffiliationEditorAccepted() {
- onChangeAffiliationsRequest(affiliationEditor_->getChanges());
+ onChangeAffiliationsRequest(affiliationEditor_->getChanges());
}
void QtChatWindow::setAffiliations(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids) {
- if (!affiliationEditor_) return;
- affiliationEditor_->setAffiliations(affiliation, jids);
+ if (!affiliationEditor_) return;
+ affiliationEditor_->setAffiliations(affiliation, jids);
}
void QtChatWindow::setAvailableRoomActions(const std::vector<RoomAction>& actions) {
- availableRoomActions_ = actions;
+ availableRoomActions_ = actions;
}
void QtChatWindow::setBlockingState(BlockingState state) {
- blockingState_ = state;
+ blockingState_ = state;
}
void QtChatWindow::setCanInitiateImpromptuChats(bool supportsImpromptu) {
- supportsImpromptuChat_ = supportsImpromptu;
+ supportsImpromptuChat_ = supportsImpromptu;
}
void QtChatWindow::showBookmarkWindow(const MUCBookmark& bookmark) {
- if (roomBookmarkState_ == RoomNotBookmarked) {
- QtAddBookmarkWindow* window = new QtAddBookmarkWindow(eventStream_, bookmark);
- window->show();
- }
- else {
- QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, bookmark);
- window->show();
- }
+ if (roomBookmarkState_ == RoomNotBookmarked) {
+ QtAddBookmarkWindow* window = new QtAddBookmarkWindow(eventStream_, bookmark);
+ window->show();
+ }
+ else {
+ QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, bookmark);
+ window->show();
+ }
}
std::string QtChatWindow::getID() const {
- return id_;
+ return id_;
}
void QtChatWindow::showRoomConfigurationForm(Form::ref form) {
- if (mucConfigurationWindow_) {
- delete mucConfigurationWindow_.data();
- }
- mucConfigurationWindow_ = new QtMUCConfigurationWindow(form);
- mucConfigurationWindow_->onFormComplete.connect(boost::bind(boost::ref(onConfigureRequest), _1));
- mucConfigurationWindow_->onFormCancelled.connect(boost::bind(boost::ref(onConfigurationFormCancelled)));
+ if (mucConfigurationWindow_) {
+ delete mucConfigurationWindow_.data();
+ }
+ mucConfigurationWindow_ = new QtMUCConfigurationWindow(form);
+ mucConfigurationWindow_->onFormComplete.connect(boost::bind(boost::ref(onConfigureRequest), _1));
+ mucConfigurationWindow_->onFormCancelled.connect(boost::bind(boost::ref(onConfigurationFormCancelled)));
}
void QtChatWindow::handleAppendedToLog() {
- if (lastLineTracker_.getShouldMoveLastLine()) {
- /* should this be queued? */
- messageLog_->addLastSeenLine();
- }
- if (isWidgetSelected()) {
- onAllMessagesRead();
- }
+ if (lastLineTracker_.getShouldMoveLastLine()) {
+ /* should this be queued? */
+ messageLog_->addLastSeenLine();
+ }
+ if (isWidgetSelected()) {
+ onAllMessagesRead();
+ }
}
void QtChatWindow::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) {
- handleAppendedToLog();
- messageLog_->addMUCInvitation(senderName, jid, reason, password, direct, isImpromptu, isContinuation);
+ handleAppendedToLog();
+ messageLog_->addMUCInvitation(senderName, jid, reason, password, direct, isImpromptu, isContinuation);
}
std::string QtChatWindow::addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- return messageLog_->addMessage(message, senderName, senderIsSelf, label, avatarPath, time);
+ handleAppendedToLog();
+ return messageLog_->addMessage(message, senderName, senderIsSelf, label, avatarPath, time);
}
std::string QtChatWindow::addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- return messageLog_->addAction(message, senderName, senderIsSelf, label, avatarPath, time);
+ handleAppendedToLog();
+ return messageLog_->addAction(message, senderName, senderIsSelf, label, avatarPath, time);
}
std::string QtChatWindow::addSystemMessage(const ChatMessage& message, Direction direction) {
- handleAppendedToLog();
- return messageLog_->addSystemMessage(message, direction);
+ handleAppendedToLog();
+ return messageLog_->addSystemMessage(message, direction);
}
void QtChatWindow::addPresenceMessage(const ChatMessage& message, Direction direction) {
- handleAppendedToLog();
- messageLog_->addPresenceMessage(message, direction);
+ handleAppendedToLog();
+ messageLog_->addPresenceMessage(message, direction);
}
void QtChatWindow::addErrorMessage(const ChatMessage& message) {
- handleAppendedToLog();
- messageLog_->addErrorMessage(message);
+ handleAppendedToLog();
+ messageLog_->addErrorMessage(message);
}
void QtChatWindow::replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- messageLog_->replaceMessage(message, id, time);
+ handleAppendedToLog();
+ messageLog_->replaceMessage(message, id, time);
}
void QtChatWindow::replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- messageLog_->replaceWithAction(message, id, time);
+ handleAppendedToLog();
+ messageLog_->replaceWithAction(message, id, time);
}
std::string QtChatWindow::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) {
- handleAppendedToLog();
- return messageLog_->addFileTransfer(senderName, senderIsSelf, filename, sizeInBytes, description);
+ handleAppendedToLog();
+ return messageLog_->addFileTransfer(senderName, senderIsSelf, filename, sizeInBytes, description);
}
void QtChatWindow::setFileTransferProgress(std::string id, const int percentageDone) {
- messageLog_->setFileTransferProgress(id, percentageDone);
+ messageLog_->setFileTransferProgress(id, percentageDone);
}
void QtChatWindow::setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg) {
- messageLog_->setFileTransferStatus(id, state, msg);
+ messageLog_->setFileTransferStatus(id, state, msg);
}
std::string QtChatWindow::addWhiteboardRequest(bool senderIsSelf) {
- handleAppendedToLog();
- return messageLog_->addWhiteboardRequest(contact_, senderIsSelf);
+ handleAppendedToLog();
+ return messageLog_->addWhiteboardRequest(contact_, senderIsSelf);
}
void QtChatWindow::setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state) {
- messageLog_->setWhiteboardSessionStatus(id, state);
+ messageLog_->setWhiteboardSessionStatus(id, state);
}
void QtChatWindow::replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour) {
- messageLog_->replaceLastMessage(message, timestampBehaviour);
+ messageLog_->replaceLastMessage(message, timestampBehaviour);
}
void QtChatWindow::setAckState(const std::string& id, AckState state) {
- messageLog_->setAckState(id, state);
+ messageLog_->setAckState(id, state);
}
void QtChatWindow::setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) {
- messageLog_->setMessageReceiptState(id, state);
+ messageLog_->setMessageReceiptState(id, state);
}
void QtChatWindow::setBookmarkState(RoomBookmarkState bookmarkState) {
- roomBookmarkState_ = bookmarkState;
+ roomBookmarkState_ = bookmarkState;
}
}
diff --git a/Swift/QtUI/QtChatWindow.h b/Swift/QtUI/QtChatWindow.h
index 8acb10c..2a23f5f 100644
--- a/Swift/QtUI/QtChatWindow.h
+++ b/Swift/QtUI/QtChatWindow.h
@@ -32,203 +32,203 @@ class QSplitter;
class QPushButton;
namespace Swift {
- class QtChatView;
- class QtOccupantListWidget;
- class QtChatTheme;
- class TreeWidget;
- class QtTextEdit;
- class UIEventStream;
- class QtChatWindowJSBridge;
- class SettingsProvider;
- class QtEmoticonsGrid;
-
- class LabelModel : public QAbstractListModel {
- Q_OBJECT
- public:
- LabelModel(QObject* parent = NULL) : QAbstractListModel(parent) {}
-
- virtual int rowCount(const QModelIndex& /*index*/) const {
- return static_cast<int>(availableLabels_.size());
- }
-
- virtual QVariant data(const QModelIndex& index, int role) const {
- if (!index.isValid()) {
- return QVariant();
- }
- boost::shared_ptr<SecurityLabel> label = availableLabels_[index.row()].getLabel();
- if (label && role == Qt::TextColorRole) {
- return P2QSTRING(label->getForegroundColor());
- }
- if (label && role == Qt::TextColorRole) {
- return P2QSTRING(label->getBackgroundColor());
- }
- if (role == Qt::DisplayRole) {
- std::string selector = availableLabels_[index.row()].getSelector();
- std::string displayMarking = label ? label->getDisplayMarking() : "";
- QString labelName = selector.empty() ? displayMarking.c_str() : selector.c_str();
- return labelName;
- }
- return QVariant();
- }
-
- std::vector<SecurityLabelsCatalog::Item> availableLabels_;
- };
-
- class QtChatWindow : public QtTabbable, public ChatWindow {
- Q_OBJECT
-
- public:
- QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map<std::string, std::string>& emoticons);
- virtual ~QtChatWindow();
- std::string addMessage(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
- std::string addAction(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
-
- std::string addSystemMessage(const ChatMessage& message, Direction direction);
- void addPresenceMessage(const ChatMessage& message, Direction direction);
- void addErrorMessage(const ChatMessage& message);
-
- void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
- void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
- // File transfer related stuff
- std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description);
- void setFileTransferProgress(std::string id, const int percentageDone);
- void setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg);
-
- std::string addWhiteboardRequest(bool senderIsSelf);
- void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state);
-
- void show();
- bool isVisible() const;
- void activate();
- void setUnreadMessageCount(int count);
- void convertToMUC(MUCType mucType);
-// TreeWidget *getTreeWidget();
- void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels);
- void setSecurityLabelsEnabled(bool enabled);
- void setSecurityLabelsError();
- SecurityLabelsCatalog::Item getSelectedSecurityLabel();
- void setName(const std::string& name);
- void setOnline(bool online);
- QtTabbable::AlertType getWidgetAlertState();
- void setContactChatState(ChatState::ChatStateType state);
- void setRosterModel(Roster* roster);
- void setTabComplete(TabComplete* completer);
- int getCount();
- virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour);
- void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour);
- void setAckState(const std::string& id, AckState state);
-
- // message receipts
- void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state);
-
- void flash();
- QByteArray getSplitterState();
- virtual void setAvailableOccupantActions(const std::vector<OccupantAction>& actions);
- void setSubject(const std::string& subject);
- void showRoomConfigurationForm(Form::ref);
- void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false);
- void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&);
- void setAvailableRoomActions(const std::vector<RoomAction>& actions);
- void setBlockingState(BlockingState state);
- virtual void setCanInitiateImpromptuChats(bool supportsImpromptu);
- virtual void showBookmarkWindow(const MUCBookmark& bookmark);
- virtual void setBookmarkState(RoomBookmarkState bookmarkState);
- virtual std::string getID() const;
-
- public slots:
- void handleChangeSplitterState(QByteArray state);
- void handleFontResized(int fontSizeSteps);
- AlertID addAlert(const std::string& alertText);
- void removeAlert(const AlertID id);
- void setCorrectionEnabled(Tristate enabled);
- void setFileTransferEnabled(Tristate enabled);
-
- signals:
- void geometryChanged();
- void splitterMoved();
- void fontResized(int);
-
- protected slots:
- void closeEvent(QCloseEvent* event);
- void resizeEvent(QResizeEvent* event);
- void moveEvent(QMoveEvent* event);
-
- void dragEnterEvent(QDragEnterEvent *event);
- void dropEvent(QDropEvent *event);
-
- protected:
- void showEvent(QShowEvent* event);
-
- private slots:
- void handleLogCleared();
- void returnPressed();
- void handleInputChanged();
- void handleCursorPositionChanged();
- void handleKeyPressEvent(QKeyEvent* event);
- void handleSplitterMoved(int pos, int index);
- void handleAlertButtonClicked();
- void handleActionButtonClicked();
- void handleAffiliationEditorAccepted();
- void handleCurrentLabelChanged(int);
- void handleEmoticonsButtonClicked();
- void handleEmoticonClicked(QString emoticonAsText);
- void handleTextInputReceivedFocus();
- void handleTextInputLostFocus();
-
- private:
- void updateTitleWithUnreadCount();
- void tabComplete();
- void beginCorrection();
- void cancelCorrection();
- void handleSettingChanged(const std::string& setting);
-
- void handleOccupantSelectionChanged(RosterItem* item);
- void handleAppendedToLog();
-
- static std::vector<JID> jidListFromQByteArray(const QByteArray& dataBytes);
-
- private:
- int unreadCount_;
- bool contactIsTyping_;
- LastLineTracker lastLineTracker_;
- std::string id_;
- QString contact_;
- QString lastSentMessage_;
- QTextCursor tabCompleteCursor_;
- QtChatView* messageLog_;
- QtChatTheme* theme_;
- QtTextEdit* input_;
- QWidget* midBar_;
- QBoxLayout* subjectLayout_;
- QComboBox* labelsWidget_;
- QtOccupantListWidget* treeWidget_;
- QLabel* correctingLabel_;
- boost::optional<AlertID> correctingAlert_;
- QVBoxLayout* alertLayout_;
- std::map<AlertID, QWidget*> alertWidgets_;
- AlertID nextAlertId_;
- TabComplete* completer_;
- QLineEdit* subject_;
- bool isCorrection_;
- bool inputClearing_;
- bool tabCompletion_;
- UIEventStream* eventStream_;
- bool isOnline_;
- QSplitter *logRosterSplitter_;
- Tristate correctionEnabled_;
- Tristate fileTransferEnabled_;
- QString alertStyleSheet_;
- QPointer<QtMUCConfigurationWindow> mucConfigurationWindow_;
- QPointer<QtAffiliationEditor> affiliationEditor_;
- SettingsProvider* settings_;
- std::vector<ChatWindow::RoomAction> availableRoomActions_;
- QPalette defaultLabelsPalette_;
- LabelModel* labelModel_;
- BlockingState blockingState_;
- bool impromptu_;
- bool isMUC_;
- bool supportsImpromptuChat_;
- RoomBookmarkState roomBookmarkState_;
- QMenu* emoticonsMenu_;
- };
+ class QtChatView;
+ class QtOccupantListWidget;
+ class QtChatTheme;
+ class TreeWidget;
+ class QtTextEdit;
+ class UIEventStream;
+ class QtChatWindowJSBridge;
+ class SettingsProvider;
+ class QtEmoticonsGrid;
+
+ class LabelModel : public QAbstractListModel {
+ Q_OBJECT
+ public:
+ LabelModel(QObject* parent = NULL) : QAbstractListModel(parent) {}
+
+ virtual int rowCount(const QModelIndex& /*index*/) const {
+ return static_cast<int>(availableLabels_.size());
+ }
+
+ virtual QVariant data(const QModelIndex& index, int role) const {
+ if (!index.isValid()) {
+ return QVariant();
+ }
+ boost::shared_ptr<SecurityLabel> label = availableLabels_[index.row()].getLabel();
+ if (label && role == Qt::TextColorRole) {
+ return P2QSTRING(label->getForegroundColor());
+ }
+ if (label && role == Qt::TextColorRole) {
+ return P2QSTRING(label->getBackgroundColor());
+ }
+ if (role == Qt::DisplayRole) {
+ std::string selector = availableLabels_[index.row()].getSelector();
+ std::string displayMarking = label ? label->getDisplayMarking() : "";
+ QString labelName = selector.empty() ? displayMarking.c_str() : selector.c_str();
+ return labelName;
+ }
+ return QVariant();
+ }
+
+ std::vector<SecurityLabelsCatalog::Item> availableLabels_;
+ };
+
+ class QtChatWindow : public QtTabbable, public ChatWindow {
+ Q_OBJECT
+
+ public:
+ QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map<std::string, std::string>& emoticons);
+ virtual ~QtChatWindow();
+ std::string addMessage(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
+ std::string addAction(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
+
+ std::string addSystemMessage(const ChatMessage& message, Direction direction);
+ void addPresenceMessage(const ChatMessage& message, Direction direction);
+ void addErrorMessage(const ChatMessage& message);
+
+ void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
+ void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
+ // File transfer related stuff
+ std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description);
+ void setFileTransferProgress(std::string id, const int percentageDone);
+ void setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg);
+
+ std::string addWhiteboardRequest(bool senderIsSelf);
+ void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state);
+
+ void show();
+ bool isVisible() const;
+ void activate();
+ void setUnreadMessageCount(int count);
+ void convertToMUC(MUCType mucType);
+// TreeWidget *getTreeWidget();
+ void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels);
+ void setSecurityLabelsEnabled(bool enabled);
+ void setSecurityLabelsError();
+ SecurityLabelsCatalog::Item getSelectedSecurityLabel();
+ void setName(const std::string& name);
+ void setOnline(bool online);
+ QtTabbable::AlertType getWidgetAlertState();
+ void setContactChatState(ChatState::ChatStateType state);
+ void setRosterModel(Roster* roster);
+ void setTabComplete(TabComplete* completer);
+ int getCount();
+ virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour);
+ void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour);
+ void setAckState(const std::string& id, AckState state);
+
+ // message receipts
+ void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state);
+
+ void flash();
+ QByteArray getSplitterState();
+ virtual void setAvailableOccupantActions(const std::vector<OccupantAction>& actions);
+ void setSubject(const std::string& subject);
+ void showRoomConfigurationForm(Form::ref);
+ void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false);
+ void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&);
+ void setAvailableRoomActions(const std::vector<RoomAction>& actions);
+ void setBlockingState(BlockingState state);
+ virtual void setCanInitiateImpromptuChats(bool supportsImpromptu);
+ virtual void showBookmarkWindow(const MUCBookmark& bookmark);
+ virtual void setBookmarkState(RoomBookmarkState bookmarkState);
+ virtual std::string getID() const;
+
+ public slots:
+ void handleChangeSplitterState(QByteArray state);
+ void handleFontResized(int fontSizeSteps);
+ AlertID addAlert(const std::string& alertText);
+ void removeAlert(const AlertID id);
+ void setCorrectionEnabled(Tristate enabled);
+ void setFileTransferEnabled(Tristate enabled);
+
+ signals:
+ void geometryChanged();
+ void splitterMoved();
+ void fontResized(int);
+
+ protected slots:
+ void closeEvent(QCloseEvent* event);
+ void resizeEvent(QResizeEvent* event);
+ void moveEvent(QMoveEvent* event);
+
+ void dragEnterEvent(QDragEnterEvent *event);
+ void dropEvent(QDropEvent *event);
+
+ protected:
+ void showEvent(QShowEvent* event);
+
+ private slots:
+ void handleLogCleared();
+ void returnPressed();
+ void handleInputChanged();
+ void handleCursorPositionChanged();
+ void handleKeyPressEvent(QKeyEvent* event);
+ void handleSplitterMoved(int pos, int index);
+ void handleAlertButtonClicked();
+ void handleActionButtonClicked();
+ void handleAffiliationEditorAccepted();
+ void handleCurrentLabelChanged(int);
+ void handleEmoticonsButtonClicked();
+ void handleEmoticonClicked(QString emoticonAsText);
+ void handleTextInputReceivedFocus();
+ void handleTextInputLostFocus();
+
+ private:
+ void updateTitleWithUnreadCount();
+ void tabComplete();
+ void beginCorrection();
+ void cancelCorrection();
+ void handleSettingChanged(const std::string& setting);
+
+ void handleOccupantSelectionChanged(RosterItem* item);
+ void handleAppendedToLog();
+
+ static std::vector<JID> jidListFromQByteArray(const QByteArray& dataBytes);
+
+ private:
+ int unreadCount_;
+ bool contactIsTyping_;
+ LastLineTracker lastLineTracker_;
+ std::string id_;
+ QString contact_;
+ QString lastSentMessage_;
+ QTextCursor tabCompleteCursor_;
+ QtChatView* messageLog_;
+ QtChatTheme* theme_;
+ QtTextEdit* input_;
+ QWidget* midBar_;
+ QBoxLayout* subjectLayout_;
+ QComboBox* labelsWidget_;
+ QtOccupantListWidget* treeWidget_;
+ QLabel* correctingLabel_;
+ boost::optional<AlertID> correctingAlert_;
+ QVBoxLayout* alertLayout_;
+ std::map<AlertID, QWidget*> alertWidgets_;
+ AlertID nextAlertId_;
+ TabComplete* completer_;
+ QLineEdit* subject_;
+ bool isCorrection_;
+ bool inputClearing_;
+ bool tabCompletion_;
+ UIEventStream* eventStream_;
+ bool isOnline_;
+ QSplitter *logRosterSplitter_;
+ Tristate correctionEnabled_;
+ Tristate fileTransferEnabled_;
+ QString alertStyleSheet_;
+ QPointer<QtMUCConfigurationWindow> mucConfigurationWindow_;
+ QPointer<QtAffiliationEditor> affiliationEditor_;
+ SettingsProvider* settings_;
+ std::vector<ChatWindow::RoomAction> availableRoomActions_;
+ QPalette defaultLabelsPalette_;
+ LabelModel* labelModel_;
+ BlockingState blockingState_;
+ bool impromptu_;
+ bool isMUC_;
+ bool supportsImpromptuChat_;
+ RoomBookmarkState roomBookmarkState_;
+ QMenu* emoticonsMenu_;
+ };
}
diff --git a/Swift/QtUI/QtChatWindowFactory.cpp b/Swift/QtUI/QtChatWindowFactory.cpp
index 019eb21..a97fd7c 100644
--- a/Swift/QtUI/QtChatWindowFactory.cpp
+++ b/Swift/QtUI/QtChatWindowFactory.cpp
@@ -23,65 +23,65 @@ static const QString SPLITTER_STATE = "mucSplitterState";
static const QString CHAT_TABS_GEOMETRY = "chatTabsGeometry";
QtChatWindowFactory::QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map<std::string, std::string>& emoticons) : themePath_(themePath), emoticons_(emoticons) {
- qtOnlySettings_ = qtSettings;
- settings_ = settings;
- tabs_ = tabs;
- theme_ = NULL;
- QtChatTabs* fullTabs = dynamic_cast<QtChatTabs*>(tabs_);
- if (splitter) {
- assert(fullTabs && "Netbook mode and no-tabs interface is not supported!");
- splitter->addWidget(fullTabs);
- } else if (fullTabs) {
- QVariant chatTabsGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
- if (chatTabsGeometryVariant.isValid()) {
- fullTabs->restoreGeometry(chatTabsGeometryVariant.toByteArray());
- }
- connect(fullTabs, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
- }
+ qtOnlySettings_ = qtSettings;
+ settings_ = settings;
+ tabs_ = tabs;
+ theme_ = NULL;
+ QtChatTabs* fullTabs = dynamic_cast<QtChatTabs*>(tabs_);
+ if (splitter) {
+ assert(fullTabs && "Netbook mode and no-tabs interface is not supported!");
+ splitter->addWidget(fullTabs);
+ } else if (fullTabs) {
+ QVariant chatTabsGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
+ if (chatTabsGeometryVariant.isValid()) {
+ fullTabs->restoreGeometry(chatTabsGeometryVariant.toByteArray());
+ }
+ connect(fullTabs, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
+ }
}
QtChatWindowFactory::~QtChatWindowFactory() {
- delete theme_;
+ delete theme_;
}
ChatWindow* QtChatWindowFactory::createChatWindow(const JID &contact,UIEventStream* eventStream) {
- if (!theme_) {
- theme_ = new QtChatTheme(themePath_);
- if (theme_->getIncomingContent().isEmpty()) {
- delete theme_;
- theme_ = new QtChatTheme(":/themes/Default/"); /* Use the inbuilt theme */
- }
- }
+ if (!theme_) {
+ theme_ = new QtChatTheme(themePath_);
+ if (theme_->getIncomingContent().isEmpty()) {
+ delete theme_;
+ theme_ = new QtChatTheme(":/themes/Default/"); /* Use the inbuilt theme */
+ }
+ }
- QtChatWindow* chatWindow = new QtChatWindow(P2QSTRING(contact.toString()), theme_, eventStream, settings_, emoticons_);
- connect(chatWindow, SIGNAL(splitterMoved()), this, SLOT(handleSplitterMoved()));
- connect(this, SIGNAL(changeSplitterState(QByteArray)), chatWindow, SLOT(handleChangeSplitterState(QByteArray)));
+ QtChatWindow* chatWindow = new QtChatWindow(P2QSTRING(contact.toString()), theme_, eventStream, settings_, emoticons_);
+ connect(chatWindow, SIGNAL(splitterMoved()), this, SLOT(handleSplitterMoved()));
+ connect(this, SIGNAL(changeSplitterState(QByteArray)), chatWindow, SLOT(handleChangeSplitterState(QByteArray)));
- QVariant splitterState = qtOnlySettings_->getQSettings()->value(SPLITTER_STATE);
- if(splitterState.isValid()) {
- chatWindow->handleChangeSplitterState(splitterState.toByteArray());
- }
+ QVariant splitterState = qtOnlySettings_->getQSettings()->value(SPLITTER_STATE);
+ if(splitterState.isValid()) {
+ chatWindow->handleChangeSplitterState(splitterState.toByteArray());
+ }
- if (tabs_) {
- tabs_->addTab(chatWindow);
- } else {
- QVariant chatGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
- if (chatGeometryVariant.isValid()) {
- chatWindow->restoreGeometry(chatGeometryVariant.toByteArray());
- }
- connect(chatWindow, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
- }
- return chatWindow;
+ if (tabs_) {
+ tabs_->addTab(chatWindow);
+ } else {
+ QVariant chatGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
+ if (chatGeometryVariant.isValid()) {
+ chatWindow->restoreGeometry(chatGeometryVariant.toByteArray());
+ }
+ connect(chatWindow, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
+ }
+ return chatWindow;
}
void QtChatWindowFactory::handleWindowGeometryChanged() {
- qtOnlySettings_->getQSettings()->setValue(CHAT_TABS_GEOMETRY, qobject_cast<QWidget*>(sender())->saveGeometry());
+ qtOnlySettings_->getQSettings()->setValue(CHAT_TABS_GEOMETRY, qobject_cast<QWidget*>(sender())->saveGeometry());
}
void QtChatWindowFactory::handleSplitterMoved() {
- QByteArray splitterState = qobject_cast<QtChatWindow*>(sender())->getSplitterState();
- qtOnlySettings_->getQSettings()->setValue(SPLITTER_STATE, QVariant(splitterState));
- emit changeSplitterState(splitterState);
+ QByteArray splitterState = qobject_cast<QtChatWindow*>(sender())->getSplitterState();
+ qtOnlySettings_->getQSettings()->setValue(SPLITTER_STATE, QVariant(splitterState));
+ emit changeSplitterState(splitterState);
}
}
diff --git a/Swift/QtUI/QtChatWindowFactory.h b/Swift/QtUI/QtChatWindowFactory.h
index 6b1f0a1..29bc5bc 100644
--- a/Swift/QtUI/QtChatWindowFactory.h
+++ b/Swift/QtUI/QtChatWindowFactory.h
@@ -19,29 +19,29 @@
#include <Swift/QtUI/QtSettingsProvider.h>
namespace Swift {
- class QtChatTabsBase;
- class QtChatTheme;
- class UIEventStream;
- class QtUIPreferences;
- class QtSingleWindow;
- class QtChatWindowFactory : public QObject, public ChatWindowFactory {
- Q_OBJECT
- public:
- QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map<std::string, std::string>& emoticons);
- ~QtChatWindowFactory();
- ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
- signals:
- void changeSplitterState(QByteArray);
- private slots:
- void handleWindowGeometryChanged();
- void handleSplitterMoved();
- private:
- QString themePath_;
- SettingsProvider* settings_;
- QtSettingsProvider* qtOnlySettings_;
- QtChatTabsBase* tabs_;
- QtChatTheme* theme_;
- std::map<std::string, std::string> emoticons_;
- };
+ class QtChatTabsBase;
+ class QtChatTheme;
+ class UIEventStream;
+ class QtUIPreferences;
+ class QtSingleWindow;
+ class QtChatWindowFactory : public QObject, public ChatWindowFactory {
+ Q_OBJECT
+ public:
+ QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map<std::string, std::string>& emoticons);
+ ~QtChatWindowFactory();
+ ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
+ signals:
+ void changeSplitterState(QByteArray);
+ private slots:
+ void handleWindowGeometryChanged();
+ void handleSplitterMoved();
+ private:
+ QString themePath_;
+ SettingsProvider* settings_;
+ QtSettingsProvider* qtOnlySettings_;
+ QtChatTabsBase* tabs_;
+ QtChatTheme* theme_;
+ std::map<std::string, std::string> emoticons_;
+ };
}
diff --git a/Swift/QtUI/QtChatWindowJSBridge.cpp b/Swift/QtUI/QtChatWindowJSBridge.cpp
index fa6f906..3030689 100644
--- a/Swift/QtUI/QtChatWindowJSBridge.cpp
+++ b/Swift/QtUI/QtChatWindowJSBridge.cpp
@@ -15,11 +15,11 @@
namespace Swift {
QtChatWindowJSBridge::QtChatWindowJSBridge() {
-
+
}
QtChatWindowJSBridge::~QtChatWindowJSBridge() {
-
+
}
}
diff --git a/Swift/QtUI/QtChatWindowJSBridge.h b/Swift/QtUI/QtChatWindowJSBridge.h
index db01abb..bedf6a4 100644
--- a/Swift/QtUI/QtChatWindowJSBridge.h
+++ b/Swift/QtUI/QtChatWindowJSBridge.h
@@ -21,12 +21,12 @@ namespace Swift {
class FileTransferController;
class QtChatWindowJSBridge : public QObject {
- Q_OBJECT
+ Q_OBJECT
public:
- QtChatWindowJSBridge();
- virtual ~QtChatWindowJSBridge();
+ QtChatWindowJSBridge();
+ virtual ~QtChatWindowJSBridge();
signals:
- void buttonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
+ void buttonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
};
}
diff --git a/Swift/QtUI/QtClickableLabel.cpp b/Swift/QtUI/QtClickableLabel.cpp
index 3749cfe..7ce3325 100644
--- a/Swift/QtUI/QtClickableLabel.cpp
+++ b/Swift/QtUI/QtClickableLabel.cpp
@@ -12,7 +12,7 @@ QtClickableLabel::QtClickableLabel(QWidget* parent) : QLabel(parent) {
}
void QtClickableLabel::mousePressEvent(QMouseEvent*) {
- emit clicked();
+ emit clicked();
}
}
diff --git a/Swift/QtUI/QtClickableLabel.h b/Swift/QtUI/QtClickableLabel.h
index deaf646..83ed3f1 100644
--- a/Swift/QtUI/QtClickableLabel.h
+++ b/Swift/QtUI/QtClickableLabel.h
@@ -9,14 +9,14 @@
#include <QLabel>
namespace Swift {
- class QtClickableLabel : public QLabel {
- Q_OBJECT
- public:
- QtClickableLabel(QWidget* parent);
+ class QtClickableLabel : public QLabel {
+ Q_OBJECT
+ public:
+ QtClickableLabel(QWidget* parent);
- void mousePressEvent(QMouseEvent* event);
+ void mousePressEvent(QMouseEvent* event);
- signals:
- void clicked();
- };
+ signals:
+ void clicked();
+ };
}
diff --git a/Swift/QtUI/QtClosableLineEdit.cpp b/Swift/QtUI/QtClosableLineEdit.cpp
index 414463a..033db78 100644
--- a/Swift/QtUI/QtClosableLineEdit.cpp
+++ b/Swift/QtUI/QtClosableLineEdit.cpp
@@ -27,40 +27,40 @@ namespace Swift {
const int QtClosableLineEdit::clearButtonPadding = 2;
QtClosableLineEdit::QtClosableLineEdit(QWidget *parent) : QLineEdit(parent) {
- clearButton = new QToolButton(this);
- clearButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
- clearButton->setIconSize(QSize(16,16));
- clearButton->setCursor(Qt::ArrowCursor);
- clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
- clearButton->hide();
- connect(clearButton, SIGNAL(clicked()), this, SLOT(handleCloseButtonClicked()));
- connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));
- int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
- setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1));
- QSize minimumSize = minimumSizeHint();
- setMinimumSize(qMax(minimumSize.width(), clearButton->sizeHint().width() + frameWidth * 2 + clearButtonPadding),
- qMax(minimumSize.height(), clearButton->sizeHint().height() + frameWidth * 2 + clearButtonPadding));
+ clearButton = new QToolButton(this);
+ clearButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
+ clearButton->setIconSize(QSize(16,16));
+ clearButton->setCursor(Qt::ArrowCursor);
+ clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
+ clearButton->hide();
+ connect(clearButton, SIGNAL(clicked()), this, SLOT(handleCloseButtonClicked()));
+ connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));
+ int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+ setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1));
+ QSize minimumSize = minimumSizeHint();
+ setMinimumSize(qMax(minimumSize.width(), clearButton->sizeHint().width() + frameWidth * 2 + clearButtonPadding),
+ qMax(minimumSize.height(), clearButton->sizeHint().height() + frameWidth * 2 + clearButtonPadding));
}
void QtClosableLineEdit::resizeEvent(QResizeEvent *) {
- QSize size = clearButton->sizeHint();
- int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
- int verticalAdjustment = 1;
+ QSize size = clearButton->sizeHint();
+ int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+ int verticalAdjustment = 1;
#if defined(Q_OS_WIN32)
- // This vertical adjustment is required on Windows so the close button is vertically centered in the line edit.
- verticalAdjustment += 2;
-#endif
- clearButton->move(rect().right() - frameWidth - size.width(), (rect().bottom() + verticalAdjustment - size.height())/2);
+ // This vertical adjustment is required on Windows so the close button is vertically centered in the line edit.
+ verticalAdjustment += 2;
+#endif
+ clearButton->move(rect().right() - frameWidth - size.width(), (rect().bottom() + verticalAdjustment - size.height())/2);
}
void QtClosableLineEdit::updateCloseButton(const QString& text) {
- clearButton->setVisible(!text.isEmpty());
+ clearButton->setVisible(!text.isEmpty());
}
void QtClosableLineEdit::handleCloseButtonClicked() {
- clear();
- QApplication::postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier));
- QApplication::postEvent(this, new QKeyEvent(QEvent::KeyRelease, Qt::Key_Escape, Qt::NoModifier));
+ clear();
+ QApplication::postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier));
+ QApplication::postEvent(this, new QKeyEvent(QEvent::KeyRelease, Qt::Key_Escape, Qt::NoModifier));
}
}
diff --git a/Swift/QtUI/QtClosableLineEdit.h b/Swift/QtUI/QtClosableLineEdit.h
index da9f5a8..206851b 100644
--- a/Swift/QtUI/QtClosableLineEdit.h
+++ b/Swift/QtUI/QtClosableLineEdit.h
@@ -24,20 +24,20 @@ namespace Swift {
class QtClosableLineEdit : public QLineEdit
{
- Q_OBJECT
- public:
- QtClosableLineEdit(QWidget *parent = 0);
+ Q_OBJECT
+ public:
+ QtClosableLineEdit(QWidget *parent = 0);
- protected:
- void resizeEvent(QResizeEvent *);
+ protected:
+ void resizeEvent(QResizeEvent *);
- private slots:
- void updateCloseButton(const QString &text);
- void handleCloseButtonClicked();
+ private slots:
+ void updateCloseButton(const QString &text);
+ void handleCloseButtonClicked();
- private:
- static const int clearButtonPadding;
- QToolButton *clearButton;
+ private:
+ static const int clearButtonPadding;
+ QToolButton *clearButton;
};
}
diff --git a/Swift/QtUI/QtColorToolButton.cpp b/Swift/QtUI/QtColorToolButton.cpp
index a91fe0e..b349a47 100644
--- a/Swift/QtUI/QtColorToolButton.cpp
+++ b/Swift/QtUI/QtColorToolButton.cpp
@@ -18,34 +18,34 @@
namespace Swift {
QtColorToolButton::QtColorToolButton(QWidget* parent) :
- QToolButton(parent)
+ QToolButton(parent)
{
- connect(this, SIGNAL(clicked()), SLOT(onClicked()));
- setColorIcon(Qt::transparent);
+ connect(this, SIGNAL(clicked()), SLOT(onClicked()));
+ setColorIcon(Qt::transparent);
}
void QtColorToolButton::setColor(const QColor& color)
{
- if (color.isValid() != color_.isValid() || (color.isValid() && color != color_)) {
- color_ = color;
- setColorIcon(color_);
- emit colorChanged(color_);
- }
+ if (color.isValid() != color_.isValid() || (color.isValid() && color != color_)) {
+ color_ = color;
+ setColorIcon(color_);
+ emit colorChanged(color_);
+ }
}
void QtColorToolButton::onClicked()
{
- QColor c = QColorDialog::getColor(color_, this);
- if (c.isValid()) {
- setColor(c);
- }
+ QColor c = QColorDialog::getColor(color_, this);
+ if (c.isValid()) {
+ setColor(c);
+ }
}
void QtColorToolButton::setColorIcon(const QColor& color)
{
- QPixmap pix(iconSize());
- pix.fill(color.isValid() ? color : Qt::transparent);
- setIcon(pix);
+ QPixmap pix(iconSize());
+ pix.fill(color.isValid() ? color : Qt::transparent);
+ setIcon(pix);
}
}
diff --git a/Swift/QtUI/QtColorToolButton.h b/Swift/QtUI/QtColorToolButton.h
index 33d195d..5260048 100644
--- a/Swift/QtUI/QtColorToolButton.h
+++ b/Swift/QtUI/QtColorToolButton.h
@@ -10,23 +10,23 @@
namespace Swift {
- class QtColorToolButton : public QToolButton {
- Q_OBJECT
- Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged)
- public:
- explicit QtColorToolButton(QWidget* parent = NULL);
- void setColor(const QColor& color);
- const QColor& getColor() const { return color_; }
-
- signals:
- void colorChanged(const QColor&);
-
- private slots:
- void onClicked();
-
- private:
- void setColorIcon(const QColor& color);
- QColor color_;
- };
+ class QtColorToolButton : public QToolButton {
+ Q_OBJECT
+ Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged)
+ public:
+ explicit QtColorToolButton(QWidget* parent = NULL);
+ void setColor(const QColor& color);
+ const QColor& getColor() const { return color_; }
+
+ signals:
+ void colorChanged(const QColor&);
+
+ private slots:
+ void onClicked();
+
+ private:
+ void setColorIcon(const QColor& color);
+ QColor color_;
+ };
}
diff --git a/Swift/QtUI/QtConnectionSettingsWindow.cpp b/Swift/QtUI/QtConnectionSettingsWindow.cpp
index 940625b..a58bc5c 100644
--- a/Swift/QtUI/QtConnectionSettingsWindow.cpp
+++ b/Swift/QtUI/QtConnectionSettingsWindow.cpp
@@ -25,147 +25,147 @@
namespace Swift {
QtConnectionSettingsWindow::QtConnectionSettingsWindow(const ClientOptions& options) : QDialog() {
- ui.setupUi(this);
-
- connect(ui.connectionMethod, SIGNAL(currentIndexChanged(int)), ui.stackedWidget, SLOT(setCurrentIndex(int)));
-
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostNameLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostName, SLOT(setEnabled(bool)));
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPortLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPort, SLOT(setEnabled(bool)));
-
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHostLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHost, SLOT(setEnabled(bool)));
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPortLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPort, SLOT(setEnabled(bool)));
-
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHostLabel, SLOT(setEnabled(bool)));
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHost, SLOT(setEnabled(bool)));
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPortLabel, SLOT(setEnabled(bool)));
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPort, SLOT(setEnabled(bool)));
-
- connect(ui.manual_proxyType, SIGNAL(currentIndexChanged(int)), SLOT(handleProxyTypeChanged(int)));
-
- connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(handleAcceptRequested()));
-
- QtURLValidator* urlValidator = new QtURLValidator(this);
- ui.bosh_uri->setValidator(urlValidator);
-
- ui.manual_useTLS->setCurrentIndex(2);
-
- ui.manual_proxyType->setCurrentIndex(0);
-
- ClientOptions defaults;
- if (options.boshURL.isEmpty()) {
- bool isDefault = options.useStreamCompression == defaults.useStreamCompression;
- isDefault &= options.useTLS == defaults.useTLS;
- isDefault &= options.allowPLAINWithoutTLS == defaults.allowPLAINWithoutTLS;
- isDefault &= options.useStreamCompression == defaults.useStreamCompression;
- isDefault &= options.useAcks == defaults.useAcks;
- isDefault &= options.manualHostname == defaults.manualHostname;
- isDefault &= options.manualPort == defaults.manualPort;
- isDefault &= options.proxyType == defaults.proxyType;
- isDefault &= options.manualProxyHostname == defaults.manualProxyHostname;
- isDefault &= options.manualProxyPort == defaults.manualProxyPort;
- isDefault &= options.tlsOptions.schannelTLS1_0Workaround == defaults.tlsOptions.schannelTLS1_0Workaround;
- if (isDefault) {
- ui.connectionMethod->setCurrentIndex(0);
- }
- else {
- ui.connectionMethod->setCurrentIndex(1);
- ui.manual_useTLS->setCurrentIndex(options.useTLS);
- ui.manual_allowPLAINWithoutTLS->setChecked(options.allowPLAINWithoutTLS);
- ui.manual_allowCompression->setChecked(options.useStreamCompression);
- if (!options.manualHostname.empty()) {
- ui.manual_manualHost->setChecked(true);
- ui.manual_manualHostName->setText(P2QSTRING(options.manualHostname));
- if (options.manualPort >=0) {
- ui.manual_manualHostPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualPort)));
- }
- }
- ui.manual_proxyType->setCurrentIndex(options.proxyType);
- if (!options.manualProxyHostname.empty()) {
- ui.manual_manualProxy->setChecked(true);
- ui.manual_manualProxyHost->setText(P2QSTRING(options.manualProxyHostname));
- ui.manual_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualProxyPort)));
- }
- ui.manual_forceTLS1_0->setChecked(options.tlsOptions.schannelTLS1_0Workaround);
- }
- } else {
- ui.connectionMethod->setCurrentIndex(2);
- ui.bosh_uri->setText(P2QSTRING(options.boshURL.toString()));
- if (!options.boshHTTPConnectProxyURL.isEmpty()) {
- ui.bosh_manualProxy->setChecked(true);
- ui.bosh_manualProxyHost->setText(P2QSTRING(options.boshHTTPConnectProxyURL.getHost()));
- if (options.boshHTTPConnectProxyURL.getPort()) {
- ui.bosh_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(*options.boshHTTPConnectProxyURL.getPort())));
- }
- }
- }
+ ui.setupUi(this);
+
+ connect(ui.connectionMethod, SIGNAL(currentIndexChanged(int)), ui.stackedWidget, SLOT(setCurrentIndex(int)));
+
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostNameLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostName, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPortLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPort, SLOT(setEnabled(bool)));
+
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHostLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHost, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPortLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPort, SLOT(setEnabled(bool)));
+
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHostLabel, SLOT(setEnabled(bool)));
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHost, SLOT(setEnabled(bool)));
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPortLabel, SLOT(setEnabled(bool)));
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPort, SLOT(setEnabled(bool)));
+
+ connect(ui.manual_proxyType, SIGNAL(currentIndexChanged(int)), SLOT(handleProxyTypeChanged(int)));
+
+ connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(handleAcceptRequested()));
+
+ QtURLValidator* urlValidator = new QtURLValidator(this);
+ ui.bosh_uri->setValidator(urlValidator);
+
+ ui.manual_useTLS->setCurrentIndex(2);
+
+ ui.manual_proxyType->setCurrentIndex(0);
+
+ ClientOptions defaults;
+ if (options.boshURL.isEmpty()) {
+ bool isDefault = options.useStreamCompression == defaults.useStreamCompression;
+ isDefault &= options.useTLS == defaults.useTLS;
+ isDefault &= options.allowPLAINWithoutTLS == defaults.allowPLAINWithoutTLS;
+ isDefault &= options.useStreamCompression == defaults.useStreamCompression;
+ isDefault &= options.useAcks == defaults.useAcks;
+ isDefault &= options.manualHostname == defaults.manualHostname;
+ isDefault &= options.manualPort == defaults.manualPort;
+ isDefault &= options.proxyType == defaults.proxyType;
+ isDefault &= options.manualProxyHostname == defaults.manualProxyHostname;
+ isDefault &= options.manualProxyPort == defaults.manualProxyPort;
+ isDefault &= options.tlsOptions.schannelTLS1_0Workaround == defaults.tlsOptions.schannelTLS1_0Workaround;
+ if (isDefault) {
+ ui.connectionMethod->setCurrentIndex(0);
+ }
+ else {
+ ui.connectionMethod->setCurrentIndex(1);
+ ui.manual_useTLS->setCurrentIndex(options.useTLS);
+ ui.manual_allowPLAINWithoutTLS->setChecked(options.allowPLAINWithoutTLS);
+ ui.manual_allowCompression->setChecked(options.useStreamCompression);
+ if (!options.manualHostname.empty()) {
+ ui.manual_manualHost->setChecked(true);
+ ui.manual_manualHostName->setText(P2QSTRING(options.manualHostname));
+ if (options.manualPort >=0) {
+ ui.manual_manualHostPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualPort)));
+ }
+ }
+ ui.manual_proxyType->setCurrentIndex(options.proxyType);
+ if (!options.manualProxyHostname.empty()) {
+ ui.manual_manualProxy->setChecked(true);
+ ui.manual_manualProxyHost->setText(P2QSTRING(options.manualProxyHostname));
+ ui.manual_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualProxyPort)));
+ }
+ ui.manual_forceTLS1_0->setChecked(options.tlsOptions.schannelTLS1_0Workaround);
+ }
+ } else {
+ ui.connectionMethod->setCurrentIndex(2);
+ ui.bosh_uri->setText(P2QSTRING(options.boshURL.toString()));
+ if (!options.boshHTTPConnectProxyURL.isEmpty()) {
+ ui.bosh_manualProxy->setChecked(true);
+ ui.bosh_manualProxyHost->setText(P2QSTRING(options.boshHTTPConnectProxyURL.getHost()));
+ if (options.boshHTTPConnectProxyURL.getPort()) {
+ ui.bosh_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(*options.boshHTTPConnectProxyURL.getPort())));
+ }
+ }
+ }
#ifndef HAVE_SCHANNEL
- ui.manual_forceTLS1_0->hide();
+ ui.manual_forceTLS1_0->hide();
#endif
}
void QtConnectionSettingsWindow::handleProxyTypeChanged(int index) {
- bool proxySettingsVisible = index != NoProxy && index != SystemProxy;
- ui.manual_manualProxy->setVisible(proxySettingsVisible);
- ui.manual_manualProxyHostLabel->setVisible(proxySettingsVisible);
- ui.manual_manualProxyHost->setVisible(proxySettingsVisible);
- ui.manual_manualProxyPortLabel->setVisible(proxySettingsVisible);
- ui.manual_manualProxyPort->setVisible(proxySettingsVisible);
+ bool proxySettingsVisible = index != NoProxy && index != SystemProxy;
+ ui.manual_manualProxy->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyHostLabel->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyHost->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyPortLabel->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyPort->setVisible(proxySettingsVisible);
}
void QtConnectionSettingsWindow::handleAcceptRequested() {
- if (ui.connectionMethod->currentIndex() != 2 || ui.bosh_uri->hasAcceptableInput()) {
- accept();
- }
- else {
- QMessageBox::critical(this, tr("Configuration invalid"), tr("The provided BOSH URL is not valid."));
- }
+ if (ui.connectionMethod->currentIndex() != 2 || ui.bosh_uri->hasAcceptableInput()) {
+ accept();
+ }
+ else {
+ QMessageBox::critical(this, tr("Configuration invalid"), tr("The provided BOSH URL is not valid."));
+ }
}
ClientOptions QtConnectionSettingsWindow::getOptions() {
- ClientOptions options;
- if (ui.connectionMethod->currentIndex() > 0) {
- /* Not automatic */
- if (ui.connectionMethod->currentIndex() == 1) {
- /* Manual */
- options.useTLS = static_cast<ClientOptions::UseTLS>(ui.manual_useTLS->currentIndex());
- options.useStreamCompression = ui.manual_allowCompression->isChecked();
- options.allowPLAINWithoutTLS = ui.manual_allowPLAINWithoutTLS->isChecked();
- options.tlsOptions.schannelTLS1_0Workaround = ui.manual_forceTLS1_0->isChecked();
- if (ui.manual_manualHost->isChecked()) {
- options.manualHostname = Q2PSTRING(ui.manual_manualHostName->text());
- try {
- options.manualPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualHostPort->text()));
- } catch (const boost::bad_lexical_cast&) {
- options.manualPort = -1;
- }
- }
- options.proxyType = static_cast<ClientOptions::ProxyType>(ui.manual_proxyType->currentIndex());
- if (ui.manual_manualProxy->isChecked()) {
- options.manualProxyHostname = Q2PSTRING(ui.manual_manualProxyHost->text());
- try {
- options.manualProxyPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualProxyPort->text()));
- } catch (const boost::bad_lexical_cast&) {}
- }
- }
- else {
- /* BOSH */
- options.boshURL = URL::fromString(Q2PSTRING(ui.bosh_uri->text()));
- if (ui.bosh_manualProxy->isChecked()) {
- std::string host = Q2PSTRING(ui.bosh_manualProxyHost->text());
- try {
- int port = boost::lexical_cast<int>(Q2PSTRING(ui.bosh_manualProxyPort->text()));
- options.boshHTTPConnectProxyURL = URL("http", host, port, "");
- } catch (const boost::bad_lexical_cast&) {
- options.boshHTTPConnectProxyURL = URL("http", host, "");
- }
- }
- }
- }
- return options;
+ ClientOptions options;
+ if (ui.connectionMethod->currentIndex() > 0) {
+ /* Not automatic */
+ if (ui.connectionMethod->currentIndex() == 1) {
+ /* Manual */
+ options.useTLS = static_cast<ClientOptions::UseTLS>(ui.manual_useTLS->currentIndex());
+ options.useStreamCompression = ui.manual_allowCompression->isChecked();
+ options.allowPLAINWithoutTLS = ui.manual_allowPLAINWithoutTLS->isChecked();
+ options.tlsOptions.schannelTLS1_0Workaround = ui.manual_forceTLS1_0->isChecked();
+ if (ui.manual_manualHost->isChecked()) {
+ options.manualHostname = Q2PSTRING(ui.manual_manualHostName->text());
+ try {
+ options.manualPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualHostPort->text()));
+ } catch (const boost::bad_lexical_cast&) {
+ options.manualPort = -1;
+ }
+ }
+ options.proxyType = static_cast<ClientOptions::ProxyType>(ui.manual_proxyType->currentIndex());
+ if (ui.manual_manualProxy->isChecked()) {
+ options.manualProxyHostname = Q2PSTRING(ui.manual_manualProxyHost->text());
+ try {
+ options.manualProxyPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualProxyPort->text()));
+ } catch (const boost::bad_lexical_cast&) {}
+ }
+ }
+ else {
+ /* BOSH */
+ options.boshURL = URL::fromString(Q2PSTRING(ui.bosh_uri->text()));
+ if (ui.bosh_manualProxy->isChecked()) {
+ std::string host = Q2PSTRING(ui.bosh_manualProxyHost->text());
+ try {
+ int port = boost::lexical_cast<int>(Q2PSTRING(ui.bosh_manualProxyPort->text()));
+ options.boshHTTPConnectProxyURL = URL("http", host, port, "");
+ } catch (const boost::bad_lexical_cast&) {
+ options.boshHTTPConnectProxyURL = URL("http", host, "");
+ }
+ }
+ }
+ }
+ return options;
}
}
diff --git a/Swift/QtUI/QtConnectionSettingsWindow.h b/Swift/QtUI/QtConnectionSettingsWindow.h
index a1d4739..f9fad84 100644
--- a/Swift/QtUI/QtConnectionSettingsWindow.h
+++ b/Swift/QtUI/QtConnectionSettingsWindow.h
@@ -13,25 +13,25 @@
#include <Swift/QtUI/ui_QtConnectionSettings.h>
namespace Swift {
- class QtConnectionSettingsWindow : public QDialog {
- Q_OBJECT
-
- public:
- QtConnectionSettingsWindow(const ClientOptions& options);
-
- ClientOptions getOptions();
-
- private slots:
- void handleProxyTypeChanged(int);
- void handleAcceptRequested();
-
- private:
- enum {
- NoProxy = 0,
- SystemProxy = 1,
- SOCKS5Proxy = 2,
- HTTPProxy = 3
- };
- Ui::QtConnectionSettings ui;
- };
+ class QtConnectionSettingsWindow : public QDialog {
+ Q_OBJECT
+
+ public:
+ QtConnectionSettingsWindow(const ClientOptions& options);
+
+ ClientOptions getOptions();
+
+ private slots:
+ void handleProxyTypeChanged(int);
+ void handleAcceptRequested();
+
+ private:
+ enum {
+ NoProxy = 0,
+ SystemProxy = 1,
+ SOCKS5Proxy = 2,
+ HTTPProxy = 3
+ };
+ Ui::QtConnectionSettings ui;
+ };
}
diff --git a/Swift/QtUI/QtContactEditWidget.cpp b/Swift/QtUI/QtContactEditWidget.cpp
index ad02bf9..ced9157 100644
--- a/Swift/QtUI/QtContactEditWidget.cpp
+++ b/Swift/QtUI/QtContactEditWidget.cpp
@@ -21,155 +21,155 @@
namespace Swift {
QtContactEditWidget::QtContactEditWidget(const std::set<std::string>& allGroups, QWidget* parent) : QWidget(parent), nameRadioButton_(NULL), groups_(NULL) {
- QBoxLayout* layout = new QVBoxLayout(this);
- setContentsMargins(0,0,0,0);
- layout->setContentsMargins(0,0,0,0);
-
- nameLayout_ = new QHBoxLayout();
- suggestionsLayout_ = new QHBoxLayout();
- nameLayout_->addLayout(suggestionsLayout_);
-
- name_ = new QLineEdit(this);
- nameLayout_->addWidget(name_);
-
- throbberLabel_ = new QLabel(this);
- throbberLabel_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
- throbberLabel_->movie()->start();
- nameLayout_->addWidget(throbberLabel_);
-
- layout->addLayout(nameLayout_);
-
- layout->addWidget(new QLabel(tr("Groups:"), this));
-
- QScrollArea* groupsArea = new QScrollArea(this);
- layout->addWidget(groupsArea);
- groupsArea->setWidgetResizable(true);
- groupsArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- groupsArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
-
- QWidget* groups = new QWidget(groupsArea);
- groupsArea->setWidget(groups);
- QVBoxLayout* scrollLayout = new QVBoxLayout(groups);
-
- foreach (std::string group, allGroups) {
- QString groupName = doubleAmpersand(group);
- QCheckBox* check = new QCheckBox(groups);
- check->setText(groupName);
- check->setCheckState(Qt::Unchecked);
- checkBoxes_[group] = check;
- scrollLayout->addWidget(check);
- }
-
- QHBoxLayout* newGroupLayout = new QHBoxLayout();
- newGroup_ = new QCheckBox(groups);
- newGroup_->setText(tr("New Group:"));
- newGroup_->setCheckState(Qt::Unchecked);
- newGroupLayout->addWidget(newGroup_);
- newGroupName_ = new QLineEdit(groups);
- newGroupLayout->addWidget(newGroupName_);
- scrollLayout->addLayout(newGroupLayout);
-
- scrollLayout->addItem(new QSpacerItem(20, 73, QSizePolicy::Minimum, QSizePolicy::Expanding));
+ QBoxLayout* layout = new QVBoxLayout(this);
+ setContentsMargins(0,0,0,0);
+ layout->setContentsMargins(0,0,0,0);
+
+ nameLayout_ = new QHBoxLayout();
+ suggestionsLayout_ = new QHBoxLayout();
+ nameLayout_->addLayout(suggestionsLayout_);
+
+ name_ = new QLineEdit(this);
+ nameLayout_->addWidget(name_);
+
+ throbberLabel_ = new QLabel(this);
+ throbberLabel_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
+ throbberLabel_->movie()->start();
+ nameLayout_->addWidget(throbberLabel_);
+
+ layout->addLayout(nameLayout_);
+
+ layout->addWidget(new QLabel(tr("Groups:"), this));
+
+ QScrollArea* groupsArea = new QScrollArea(this);
+ layout->addWidget(groupsArea);
+ groupsArea->setWidgetResizable(true);
+ groupsArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ groupsArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+
+ QWidget* groups = new QWidget(groupsArea);
+ groupsArea->setWidget(groups);
+ QVBoxLayout* scrollLayout = new QVBoxLayout(groups);
+
+ foreach (std::string group, allGroups) {
+ QString groupName = doubleAmpersand(group);
+ QCheckBox* check = new QCheckBox(groups);
+ check->setText(groupName);
+ check->setCheckState(Qt::Unchecked);
+ checkBoxes_[group] = check;
+ scrollLayout->addWidget(check);
+ }
+
+ QHBoxLayout* newGroupLayout = new QHBoxLayout();
+ newGroup_ = new QCheckBox(groups);
+ newGroup_->setText(tr("New Group:"));
+ newGroup_->setCheckState(Qt::Unchecked);
+ newGroupLayout->addWidget(newGroup_);
+ newGroupName_ = new QLineEdit(groups);
+ newGroupLayout->addWidget(newGroupName_);
+ scrollLayout->addLayout(newGroupLayout);
+
+ scrollLayout->addItem(new QSpacerItem(20, 73, QSizePolicy::Minimum, QSizePolicy::Expanding));
}
void QtContactEditWidget::setName(const std::string& name) {
- name_->setText(P2QSTRING(name));
+ name_->setText(P2QSTRING(name));
}
std::string QtContactEditWidget::getName() const {
- std::string name = Q2PSTRING(name_->text());
- QList<QRadioButton*> buttons = findChildren<QRadioButton*>();
- foreach(const QRadioButton* button, buttons) {
- if (button->isChecked()) {
- if (button == nameRadioButton_) {
- name = Q2PSTRING(name_->text());
- } else {
- name = singleAmpersand(button->text());
- }
- break;
- }
- }
- return name;
+ std::string name = Q2PSTRING(name_->text());
+ QList<QRadioButton*> buttons = findChildren<QRadioButton*>();
+ foreach(const QRadioButton* button, buttons) {
+ if (button->isChecked()) {
+ if (button == nameRadioButton_) {
+ name = Q2PSTRING(name_->text());
+ } else {
+ name = singleAmpersand(button->text());
+ }
+ break;
+ }
+ }
+ return name;
}
void QtContactEditWidget::setSelectedGroups(const std::vector<std::string>& groups) {
- foreach (std::string group, groups) {
- checkBoxes_[group]->setCheckState(Qt::Checked);
- }
+ foreach (std::string group, groups) {
+ checkBoxes_[group]->setCheckState(Qt::Checked);
+ }
}
std::set<std::string> QtContactEditWidget::getSelectedGroups() const {
- std::set<std::string> groups;
- foreach(const CheckBoxMap::value_type& group, checkBoxes_) {
- if (group.second->checkState() == Qt::Checked) {
- groups.insert(group.first);
- }
- }
- if (newGroup_->checkState() == Qt::Checked && !newGroupName_->text().isEmpty()) {
- groups.insert(Q2PSTRING(newGroupName_->text()));
- }
- return groups;
+ std::set<std::string> groups;
+ foreach(const CheckBoxMap::value_type& group, checkBoxes_) {
+ if (group.second->checkState() == Qt::Checked) {
+ groups.insert(group.first);
+ }
+ }
+ if (newGroup_->checkState() == Qt::Checked && !newGroupName_->text().isEmpty()) {
+ groups.insert(Q2PSTRING(newGroupName_->text()));
+ }
+ return groups;
}
void QtContactEditWidget::setNameSuggestions(const std::vector<std::string>& suggestions) {
- throbberLabel_->movie()->stop();
- throbberLabel_->hide();
-
- // remove old suggestions except for the user input text field
- QLayoutItem* suggestionItem = NULL;
- while ((suggestionItem = suggestionsLayout_->itemAt(0)) && suggestionItem->widget() != name_) {
- QWidget* suggestionWidget = suggestionItem->widget();
- suggestionsLayout_->removeWidget(suggestionWidget);
- delete suggestionWidget;
- }
-
- // populate new suggestions
- foreach(const std::string& name, suggestions) {
- suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this));
- }
-
- nameRadioButton_ = new QRadioButton(tr("Name:"), this);
- suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_);
-
- QRadioButton* suggestedRadioButton = 0;
- QList<QRadioButton*> radioButtons = findChildren<QRadioButton*>();
- foreach (QRadioButton* candidate, radioButtons) {
- if (candidate->text() == name_->text()) {
- suggestedRadioButton = candidate;
- break;
- }
- }
- if (suggestedRadioButton) {
- suggestedRadioButton->setChecked(true);
- } else {
- nameRadioButton_->setChecked(true);
- }
+ throbberLabel_->movie()->stop();
+ throbberLabel_->hide();
+
+ // remove old suggestions except for the user input text field
+ QLayoutItem* suggestionItem = NULL;
+ while ((suggestionItem = suggestionsLayout_->itemAt(0)) && suggestionItem->widget() != name_) {
+ QWidget* suggestionWidget = suggestionItem->widget();
+ suggestionsLayout_->removeWidget(suggestionWidget);
+ delete suggestionWidget;
+ }
+
+ // populate new suggestions
+ foreach(const std::string& name, suggestions) {
+ suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this));
+ }
+
+ nameRadioButton_ = new QRadioButton(tr("Name:"), this);
+ suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_);
+
+ QRadioButton* suggestedRadioButton = 0;
+ QList<QRadioButton*> radioButtons = findChildren<QRadioButton*>();
+ foreach (QRadioButton* candidate, radioButtons) {
+ if (candidate->text() == name_->text()) {
+ suggestedRadioButton = candidate;
+ break;
+ }
+ }
+ if (suggestedRadioButton) {
+ suggestedRadioButton->setChecked(true);
+ } else {
+ nameRadioButton_->setChecked(true);
+ }
}
QString QtContactEditWidget::doubleAmpersand(const std::string& name) const {
- return P2QSTRING(name).replace("&", "&&");
+ return P2QSTRING(name).replace("&", "&&");
}
std::string QtContactEditWidget::singleAmpersand(const QString& name) const {
- return Q2PSTRING(QString(name).replace("&&", "&"));
+ return Q2PSTRING(QString(name).replace("&&", "&"));
}
void QtContactEditWidget::clear() {
- name_->clear();
- setSelectedGroups(std::vector<std::string>());
- newGroup_->setChecked(false);
- newGroupName_->clear();
- throbberLabel_->movie()->start();
- throbberLabel_->show();
-
- // clear suggestions
- while(suggestionsLayout_->count() != 0) {
- QLayoutItem *layoutItem = suggestionsLayout_->takeAt(0);
- delete layoutItem->widget();
- delete layoutItem;
- }
- nameRadioButton_ = NULL;
+ name_->clear();
+ setSelectedGroups(std::vector<std::string>());
+ newGroup_->setChecked(false);
+ newGroupName_->clear();
+ throbberLabel_->movie()->start();
+ throbberLabel_->show();
+
+ // clear suggestions
+ while(suggestionsLayout_->count() != 0) {
+ QLayoutItem *layoutItem = suggestionsLayout_->takeAt(0);
+ delete layoutItem->widget();
+ delete layoutItem;
+ }
+ nameRadioButton_ = NULL;
}
}
diff --git a/Swift/QtUI/QtContactEditWidget.h b/Swift/QtUI/QtContactEditWidget.h
index a9f1305..5c081e9 100644
--- a/Swift/QtUI/QtContactEditWidget.h
+++ b/Swift/QtUI/QtContactEditWidget.h
@@ -22,37 +22,37 @@ class QHBoxLayout;
class QRadioButton;
namespace Swift {
- class QtContactEditWidget : public QWidget {
- Q_OBJECT
-
- public:
- QtContactEditWidget(const std::set<std::string>& allGroups, QWidget* parent);
-
- void setName(const std::string&);
- std::string getName() const;
-
- void setSelectedGroups(const std::vector<std::string>& groups);
- std::set<std::string> getSelectedGroups() const;
-
- void setNameSuggestions(const std::vector<std::string>& suggestions);
-
- void clear();
-
-
- private:
- QString doubleAmpersand(const std::string& name) const;
- std::string singleAmpersand(const QString& name) const;
- private:
- typedef std::map<std::string, QCheckBox*> CheckBoxMap;
- CheckBoxMap checkBoxes_;
- QHBoxLayout* nameLayout_;
- QHBoxLayout* suggestionsLayout_;
- QRadioButton* nameRadioButton_;
- QLineEdit* name_;
- QWidget* groups_;
- QCheckBox* newGroup_;
- QLineEdit* newGroupName_;
- QLabel* throbberLabel_;
- };
+ class QtContactEditWidget : public QWidget {
+ Q_OBJECT
+
+ public:
+ QtContactEditWidget(const std::set<std::string>& allGroups, QWidget* parent);
+
+ void setName(const std::string&);
+ std::string getName() const;
+
+ void setSelectedGroups(const std::vector<std::string>& groups);
+ std::set<std::string> getSelectedGroups() const;
+
+ void setNameSuggestions(const std::vector<std::string>& suggestions);
+
+ void clear();
+
+
+ private:
+ QString doubleAmpersand(const std::string& name) const;
+ std::string singleAmpersand(const QString& name) const;
+ private:
+ typedef std::map<std::string, QCheckBox*> CheckBoxMap;
+ CheckBoxMap checkBoxes_;
+ QHBoxLayout* nameLayout_;
+ QHBoxLayout* suggestionsLayout_;
+ QRadioButton* nameRadioButton_;
+ QLineEdit* name_;
+ QWidget* groups_;
+ QCheckBox* newGroup_;
+ QLineEdit* newGroupName_;
+ QLabel* throbberLabel_;
+ };
}
diff --git a/Swift/QtUI/QtContactEditWindow.cpp b/Swift/QtUI/QtContactEditWindow.cpp
index abd247a..214f256 100644
--- a/Swift/QtUI/QtContactEditWindow.cpp
+++ b/Swift/QtUI/QtContactEditWindow.cpp
@@ -24,84 +24,84 @@
namespace Swift {
QtContactEditWindow::QtContactEditWindow() : contactEditWidget_(NULL) {
- resize(400,300);
- setWindowTitle(tr("Edit contact"));
- setContentsMargins(0,0,0,0);
-
- QBoxLayout* layout = new QVBoxLayout(this);
-
- jidLabel_ = new QLabel(this);
- jidLabel_->setAlignment(Qt::AlignHCenter);
- layout->addWidget(jidLabel_);
-
- groupsLayout_ = new QVBoxLayout();
- groupsLayout_->setContentsMargins(0,0,0,0);
- layout->addLayout(groupsLayout_);
-
- QHBoxLayout* buttonLayout = new QHBoxLayout();
- layout->addLayout(buttonLayout);
- QPushButton* removeButton = new QPushButton(tr("Remove contact"), this);
- connect(removeButton, SIGNAL(clicked()), this, SLOT(handleRemoveContact()));
- buttonLayout->addWidget(removeButton);
- QPushButton* okButton = new QPushButton(tr("OK"), this);
- okButton->setDefault( true );
- connect(okButton, SIGNAL(clicked()), this, SLOT(handleUpdateContact()));
- buttonLayout->addStretch();
- buttonLayout->addWidget(okButton);
+ resize(400,300);
+ setWindowTitle(tr("Edit contact"));
+ setContentsMargins(0,0,0,0);
+
+ QBoxLayout* layout = new QVBoxLayout(this);
+
+ jidLabel_ = new QLabel(this);
+ jidLabel_->setAlignment(Qt::AlignHCenter);
+ layout->addWidget(jidLabel_);
+
+ groupsLayout_ = new QVBoxLayout();
+ groupsLayout_->setContentsMargins(0,0,0,0);
+ layout->addLayout(groupsLayout_);
+
+ QHBoxLayout* buttonLayout = new QHBoxLayout();
+ layout->addLayout(buttonLayout);
+ QPushButton* removeButton = new QPushButton(tr("Remove contact"), this);
+ connect(removeButton, SIGNAL(clicked()), this, SLOT(handleRemoveContact()));
+ buttonLayout->addWidget(removeButton);
+ QPushButton* okButton = new QPushButton(tr("OK"), this);
+ okButton->setDefault( true );
+ connect(okButton, SIGNAL(clicked()), this, SLOT(handleUpdateContact()));
+ buttonLayout->addStretch();
+ buttonLayout->addWidget(okButton);
}
QtContactEditWindow::~QtContactEditWindow() {
}
void QtContactEditWindow::setNameSuggestions(const std::vector<std::string>& nameSuggestions) {
- if (contactEditWidget_) {
- contactEditWidget_->setNameSuggestions(nameSuggestions);
- }
+ if (contactEditWidget_) {
+ contactEditWidget_->setNameSuggestions(nameSuggestions);
+ }
}
void QtContactEditWindow::setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups) {
- delete contactEditWidget_;
- jid_ = jid;
- jidLabel_->setText("<b>" + P2QSTRING(jid.toString()) + "</b>");
-
- contactEditWidget_ = new QtContactEditWidget(allGroups, this);
- groupsLayout_->addWidget(contactEditWidget_);
- contactEditWidget_->setName(name);
- contactEditWidget_->setSelectedGroups(groups);
+ delete contactEditWidget_;
+ jid_ = jid;
+ jidLabel_->setText("<b>" + P2QSTRING(jid.toString()) + "</b>");
+
+ contactEditWidget_ = new QtContactEditWidget(allGroups, this);
+ groupsLayout_->addWidget(contactEditWidget_);
+ contactEditWidget_->setName(name);
+ contactEditWidget_->setSelectedGroups(groups);
}
void QtContactEditWindow::setEnabled(bool b) {
- QWidget::setEnabled(b);
+ QWidget::setEnabled(b);
}
void QtContactEditWindow::show() {
- QWidget::showNormal();
- QWidget::activateWindow();
- QWidget::raise();
+ QWidget::showNormal();
+ QWidget::activateWindow();
+ QWidget::raise();
}
void QtContactEditWindow::hide() {
- QWidget::hide();
+ QWidget::hide();
}
void QtContactEditWindow::handleRemoveContact() {
- if (confirmContactDeletion(jid_)) {
- onRemoveContactRequest();
- }
+ if (confirmContactDeletion(jid_)) {
+ onRemoveContactRequest();
+ }
}
bool QtContactEditWindow::confirmContactDeletion(const JID& jid) {
- QMessageBox msgBox;
- msgBox.setWindowTitle(tr("Confirm contact deletion"));
- msgBox.setText(tr("Are you sure you want to delete this contact?"));
- msgBox.setInformativeText(QString(tr("This will remove the contact '%1' from all groups they may be in.")).arg(P2QSTRING(jid.toString())));
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::Yes);
- return msgBox.exec() == QMessageBox::Yes;
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(tr("Confirm contact deletion"));
+ msgBox.setText(tr("Are you sure you want to delete this contact?"));
+ msgBox.setInformativeText(QString(tr("This will remove the contact '%1' from all groups they may be in.")).arg(P2QSTRING(jid.toString())));
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::Yes);
+ return msgBox.exec() == QMessageBox::Yes;
}
void QtContactEditWindow::handleUpdateContact() {
- onChangeContactRequest(contactEditWidget_->getName(), contactEditWidget_->getSelectedGroups());
+ onChangeContactRequest(contactEditWidget_->getName(), contactEditWidget_->getSelectedGroups());
}
}
diff --git a/Swift/QtUI/QtContactEditWindow.h b/Swift/QtUI/QtContactEditWindow.h
index a6c73b9..655fbb4 100644
--- a/Swift/QtUI/QtContactEditWindow.h
+++ b/Swift/QtUI/QtContactEditWindow.h
@@ -19,33 +19,33 @@ class QLabel;
class QVBoxLayout;
namespace Swift {
- class QtContactEditWidget;
+ class QtContactEditWidget;
- class QtContactEditWindow : public QWidget, public ContactEditWindow {
- Q_OBJECT
+ class QtContactEditWindow : public QWidget, public ContactEditWindow {
+ Q_OBJECT
- public:
- QtContactEditWindow();
- virtual ~QtContactEditWindow();
+ public:
+ QtContactEditWindow();
+ virtual ~QtContactEditWindow();
- virtual void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
- virtual void setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups);
+ virtual void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
+ virtual void setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups);
- void setEnabled(bool);
- void show();
- void hide();
+ void setEnabled(bool);
+ void show();
+ void hide();
- static bool confirmContactDeletion(const JID& jid);
+ static bool confirmContactDeletion(const JID& jid);
- private slots:
- void handleRemoveContact();
- void handleUpdateContact();
+ private slots:
+ void handleRemoveContact();
+ void handleUpdateContact();
- private:
- JID jid_;
- QVBoxLayout* groupsLayout_;
- QLabel* jidLabel_;
- QtContactEditWidget* contactEditWidget_;
- };
+ private:
+ JID jid_;
+ QVBoxLayout* groupsLayout_;
+ QLabel* jidLabel_;
+ QtContactEditWidget* contactEditWidget_;
+ };
}
diff --git a/Swift/QtUI/QtDBUSURIHandler.cpp b/Swift/QtUI/QtDBUSURIHandler.cpp
index 71a7016..c873676 100644
--- a/Swift/QtUI/QtDBUSURIHandler.cpp
+++ b/Swift/QtUI/QtDBUSURIHandler.cpp
@@ -14,28 +14,28 @@
using namespace Swift;
namespace {
- class DBUSAdaptor: public QDBusAbstractAdaptor {
- Q_OBJECT
- Q_CLASSINFO("D-Bus Interface", "im.swift.Swift.URIHandler");
- public:
- DBUSAdaptor(QtDBUSURIHandler* uriHandler) : QDBusAbstractAdaptor(uriHandler), uriHandler(uriHandler) {
- }
-
- public slots:
- void openURI(const QString& uri) {
- uriHandler->onURI(Q2PSTRING(uri));
- }
-
- private:
- QtDBUSURIHandler* uriHandler;
- };
+ class DBUSAdaptor: public QDBusAbstractAdaptor {
+ Q_OBJECT
+ Q_CLASSINFO("D-Bus Interface", "im.swift.Swift.URIHandler");
+ public:
+ DBUSAdaptor(QtDBUSURIHandler* uriHandler) : QDBusAbstractAdaptor(uriHandler), uriHandler(uriHandler) {
+ }
+
+ public slots:
+ void openURI(const QString& uri) {
+ uriHandler->onURI(Q2PSTRING(uri));
+ }
+
+ private:
+ QtDBUSURIHandler* uriHandler;
+ };
}
QtDBUSURIHandler::QtDBUSURIHandler() {
- new DBUSAdaptor(this);
- QDBusConnection connection = QDBusConnection::sessionBus();
- connection.registerService("im.swift.Swift.URIHandler");
- connection.registerObject("/", this);
+ new DBUSAdaptor(this);
+ QDBusConnection connection = QDBusConnection::sessionBus();
+ connection.registerService("im.swift.Swift.URIHandler");
+ connection.registerObject("/", this);
}
#include "QtDBUSURIHandler.moc"
diff --git a/Swift/QtUI/QtDBUSURIHandler.h b/Swift/QtUI/QtDBUSURIHandler.h
index cb16892..3cd12f7 100644
--- a/Swift/QtUI/QtDBUSURIHandler.h
+++ b/Swift/QtUI/QtDBUSURIHandler.h
@@ -11,8 +11,8 @@
#include <SwifTools/URIHandler/URIHandler.h>
namespace Swift {
- class QtDBUSURIHandler : public QObject, public URIHandler {
- public:
- QtDBUSURIHandler();
- };
+ class QtDBUSURIHandler : public QObject, public URIHandler {
+ public:
+ QtDBUSURIHandler();
+ };
}
diff --git a/Swift/QtUI/QtEditBookmarkWindow.cpp b/Swift/QtUI/QtEditBookmarkWindow.cpp
index 756e377..a17b1aa 100644
--- a/Swift/QtUI/QtEditBookmarkWindow.cpp
+++ b/Swift/QtUI/QtEditBookmarkWindow.cpp
@@ -10,20 +10,20 @@
namespace Swift {
QtEditBookmarkWindow::QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark) : eventStream_(eventStream), bookmark_(bookmark) {
- name_->setText(P2QSTRING(bookmark.getName()));
- room_->setText(P2QSTRING(bookmark.getRoom().toString()));
- autojoin_->setChecked(bookmark.getAutojoin());
- nick_->setText(bookmark.getNick() ? P2QSTRING(bookmark.getNick().get()) : "");
- password_->setText(bookmark.getPassword() ? P2QSTRING(bookmark.getPassword().get()) : "");
+ name_->setText(P2QSTRING(bookmark.getName()));
+ room_->setText(P2QSTRING(bookmark.getRoom().toString()));
+ autojoin_->setChecked(bookmark.getAutojoin());
+ nick_->setText(bookmark.getNick() ? P2QSTRING(bookmark.getNick().get()) : "");
+ password_->setText(bookmark.getPassword() ? P2QSTRING(bookmark.getPassword().get()) : "");
}
bool QtEditBookmarkWindow::commit() {
- boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
- if (!bookmark) {
- return false;
- }
- eventStream_->send(boost::shared_ptr<UIEvent>(new EditMUCBookmarkUIEvent(bookmark_, *bookmark)));
- return true;
+ boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
+ if (!bookmark) {
+ return false;
+ }
+ eventStream_->send(boost::shared_ptr<UIEvent>(new EditMUCBookmarkUIEvent(bookmark_, *bookmark)));
+ return true;
}
}
diff --git a/Swift/QtUI/QtEditBookmarkWindow.h b/Swift/QtUI/QtEditBookmarkWindow.h
index 1d7d08b..337ba1f 100644
--- a/Swift/QtUI/QtEditBookmarkWindow.h
+++ b/Swift/QtUI/QtEditBookmarkWindow.h
@@ -12,14 +12,14 @@
#include <Swift/QtUI/QtBookmarkDetailWindow.h>
namespace Swift {
- class QtEditBookmarkWindow : public QtBookmarkDetailWindow {
- Q_OBJECT
- public:
- QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
- bool commit();
-
- private:
- UIEventStream* eventStream_;
- MUCBookmark bookmark_;
- };
+ class QtEditBookmarkWindow : public QtBookmarkDetailWindow {
+ Q_OBJECT
+ public:
+ QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
+ bool commit();
+
+ private:
+ UIEventStream* eventStream_;
+ MUCBookmark bookmark_;
+ };
}
diff --git a/Swift/QtUI/QtElidingLabel.cpp b/Swift/QtUI/QtElidingLabel.cpp
index f5a39f0..4707f9f 100644
--- a/Swift/QtUI/QtElidingLabel.cpp
+++ b/Swift/QtUI/QtElidingLabel.cpp
@@ -8,17 +8,17 @@
namespace Swift {
QtElidingLabel::QtElidingLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f) {
- fullText_ = "";
- dirty_ = true;
- setSizes();
- setTextFormat(Qt::PlainText);
+ fullText_ = "";
+ dirty_ = true;
+ setSizes();
+ setTextFormat(Qt::PlainText);
}
QtElidingLabel::QtElidingLabel(const QString& text, QWidget* parent, Qt::WindowFlags f) : QLabel(text, parent, f) {
- fullText_ = text;
- dirty_ = true;
- setSizes();
- setTextFormat(Qt::PlainText);
+ fullText_ = text;
+ dirty_ = true;
+ setSizes();
+ setTextFormat(Qt::PlainText);
}
QtElidingLabel::~QtElidingLabel() {
@@ -26,35 +26,35 @@ QtElidingLabel::~QtElidingLabel() {
}
QSize QtElidingLabel::sizeHint() const {
- return sizeHint_;
+ return sizeHint_;
}
void QtElidingLabel::setSizes() {
- setMinimumSize(1, minimumHeight());
+ setMinimumSize(1, minimumHeight());
}
void QtElidingLabel::setText(const QString& text) {
- fullText_ = text;
- QLabel::setText(text);
- sizeHint_ = QLabel::sizeHint();
- dirty_ = true;
+ fullText_ = text;
+ QLabel::setText(text);
+ sizeHint_ = QLabel::sizeHint();
+ dirty_ = true;
}
void QtElidingLabel::paintEvent(QPaintEvent* event) {
- QRect rect = contentsRect();
- dirty_ = dirty_ || rect != lastRect_;
- if (dirty_) {
- lastRect_ = rect;
- int fontWidth = fontMetrics().width(fullText_);
- if (fontWidth > rect.width()) {
- QString elidedText(fontMetrics().elidedText(fullText_, Qt::ElideRight, rect.width(), Qt::TextShowMnemonic));
- QLabel::setText(elidedText);
- } else {
- QLabel::setText(fullText_);
- }
- dirty_ = false;
- }
- QLabel::paintEvent(event);
+ QRect rect = contentsRect();
+ dirty_ = dirty_ || rect != lastRect_;
+ if (dirty_) {
+ lastRect_ = rect;
+ int fontWidth = fontMetrics().width(fullText_);
+ if (fontWidth > rect.width()) {
+ QString elidedText(fontMetrics().elidedText(fullText_, Qt::ElideRight, rect.width(), Qt::TextShowMnemonic));
+ QLabel::setText(elidedText);
+ } else {
+ QLabel::setText(fullText_);
+ }
+ dirty_ = false;
+ }
+ QLabel::paintEvent(event);
}
}
diff --git a/Swift/QtUI/QtElidingLabel.h b/Swift/QtUI/QtElidingLabel.h
index 84fa00f..9f590a8 100644
--- a/Swift/QtUI/QtElidingLabel.h
+++ b/Swift/QtUI/QtElidingLabel.h
@@ -9,23 +9,23 @@
#include <QLabel>
namespace Swift {
- class QtElidingLabel : public QLabel {
- Q_OBJECT
- public:
- QtElidingLabel(QWidget* parent = NULL, Qt::WindowFlags f = 0);
- QtElidingLabel(const QString &text, QWidget* parent = NULL, Qt::WindowFlags f = 0);
- void setText(const QString& text);
- virtual ~QtElidingLabel();
-
- virtual QSize sizeHint() const;
+ class QtElidingLabel : public QLabel {
+ Q_OBJECT
+ public:
+ QtElidingLabel(QWidget* parent = NULL, Qt::WindowFlags f = 0);
+ QtElidingLabel(const QString &text, QWidget* parent = NULL, Qt::WindowFlags f = 0);
+ void setText(const QString& text);
+ virtual ~QtElidingLabel();
- virtual void paintEvent(QPaintEvent* event);
+ virtual QSize sizeHint() const;
- private:
- void setSizes();
- bool dirty_;
- QString fullText_;
- QRect lastRect_;
- QSize sizeHint_;
- };
+ virtual void paintEvent(QPaintEvent* event);
+
+ private:
+ void setSizes();
+ bool dirty_;
+ QString fullText_;
+ QRect lastRect_;
+ QSize sizeHint_;
+ };
}
diff --git a/Swift/QtUI/QtEmoticonCell.cpp b/Swift/QtUI/QtEmoticonCell.cpp
index a781876..fe580aa 100644
--- a/Swift/QtUI/QtEmoticonCell.cpp
+++ b/Swift/QtUI/QtEmoticonCell.cpp
@@ -15,11 +15,11 @@
namespace Swift {
QtEmoticonCell::QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent) : QLabel(parent), emoticonAsText_(emoticonAsText) {
- if (filePath.startsWith("qrc:/")) {
- filePath.remove(0, 3);
- }
- setPixmap(QPixmap(filePath));
- setToolTip(emoticonAsText_);
+ if (filePath.startsWith("qrc:/")) {
+ filePath.remove(0, 3);
+ }
+ setPixmap(QPixmap(filePath));
+ setToolTip(emoticonAsText_);
}
QtEmoticonCell::~QtEmoticonCell() {
@@ -27,8 +27,8 @@ QtEmoticonCell::~QtEmoticonCell() {
}
void QtEmoticonCell::mousePressEvent (QMouseEvent* event) {
- emit emoticonClicked(emoticonAsText_);
- QLabel::mousePressEvent(event);
+ emit emoticonClicked(emoticonAsText_);
+ QLabel::mousePressEvent(event);
}
}
diff --git a/Swift/QtUI/QtEmoticonCell.h b/Swift/QtUI/QtEmoticonCell.h
index 379f5d6..e408a83 100644
--- a/Swift/QtUI/QtEmoticonCell.h
+++ b/Swift/QtUI/QtEmoticonCell.h
@@ -18,17 +18,17 @@ class QMouseEvent;
namespace Swift {
- class QtEmoticonCell : public QLabel {
- Q_OBJECT
- public:
- QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent = 0);
- ~QtEmoticonCell();
- virtual void mousePressEvent(QMouseEvent* event);
-
- signals:
- void emoticonClicked(QString emoticonAsText);
-
- private:
- QString emoticonAsText_;
- };
+ class QtEmoticonCell : public QLabel {
+ Q_OBJECT
+ public:
+ QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent = 0);
+ ~QtEmoticonCell();
+ virtual void mousePressEvent(QMouseEvent* event);
+
+ signals:
+ void emoticonClicked(QString emoticonAsText);
+
+ private:
+ QString emoticonAsText_;
+ };
}
diff --git a/Swift/QtUI/QtEmoticonsGrid.cpp b/Swift/QtUI/QtEmoticonsGrid.cpp
index 82fb7e8..a81f516 100644
--- a/Swift/QtUI/QtEmoticonsGrid.cpp
+++ b/Swift/QtUI/QtEmoticonsGrid.cpp
@@ -25,23 +25,23 @@ namespace Swift {
typedef std::map<std::string, std::string> EmoticonsMap; // Without this typedef compiler complains when using foreach
QtEmoticonsGrid::QtEmoticonsGrid(const std::map<std::string, std::string>& emoticons, QWidget* parent) : QGridLayout(parent) {
- makeUniqueEmoticonsMap(emoticons);
-
- // Create grid: 3 columns, [uniqueEmoticons_.size()/3] rows
- int row = 0;
- int column = 0;
-
- foreach(EmoticonsMap::value_type emoticon, uniqueEmoticons_) {
- QtEmoticonCell* newCell = new QtEmoticonCell(P2QSTRING(emoticon.first), P2QSTRING(emoticon.second));
- addWidget(newCell, row, column);
- connect(newCell, SIGNAL(emoticonClicked(QString)), this, SLOT(emoticonClickedSlot(QString)));
-
- column++;
- if (column >= 3) {
- column = 0;
- row++;
- }
- }
+ makeUniqueEmoticonsMap(emoticons);
+
+ // Create grid: 3 columns, [uniqueEmoticons_.size()/3] rows
+ int row = 0;
+ int column = 0;
+
+ foreach(EmoticonsMap::value_type emoticon, uniqueEmoticons_) {
+ QtEmoticonCell* newCell = new QtEmoticonCell(P2QSTRING(emoticon.first), P2QSTRING(emoticon.second));
+ addWidget(newCell, row, column);
+ connect(newCell, SIGNAL(emoticonClicked(QString)), this, SLOT(emoticonClickedSlot(QString)));
+
+ column++;
+ if (column >= 3) {
+ column = 0;
+ row++;
+ }
+ }
}
QtEmoticonsGrid::~QtEmoticonsGrid() {
@@ -49,17 +49,17 @@ QtEmoticonsGrid::~QtEmoticonsGrid() {
}
void QtEmoticonsGrid::makeUniqueEmoticonsMap(const std::map<std::string, std::string>& emoticons) {
- std::set<std::string> paths;
- reverse_foreach(EmoticonsMap::value_type emoticon, emoticons) {
- if (paths.find(emoticon.second) == paths.end()) {
- uniqueEmoticons_.insert(emoticon);
- paths.insert(emoticon.second);
- }
- }
+ std::set<std::string> paths;
+ reverse_foreach(EmoticonsMap::value_type emoticon, emoticons) {
+ if (paths.find(emoticon.second) == paths.end()) {
+ uniqueEmoticons_.insert(emoticon);
+ paths.insert(emoticon.second);
+ }
+ }
}
void QtEmoticonsGrid::emoticonClickedSlot(QString emoticonAsText) {
- emit emoticonClicked(emoticonAsText);
+ emit emoticonClicked(emoticonAsText);
}
}
diff --git a/Swift/QtUI/QtEmoticonsGrid.h b/Swift/QtUI/QtEmoticonsGrid.h
index b045b26..0cae9ab 100644
--- a/Swift/QtUI/QtEmoticonsGrid.h
+++ b/Swift/QtUI/QtEmoticonsGrid.h
@@ -20,21 +20,21 @@ class QWidget;
namespace Swift {
- class QtEmoticonsGrid : public QGridLayout {
- Q_OBJECT
- public:
- explicit QtEmoticonsGrid(const std::map<std::string, std::string>& emoticons, QWidget* parent = 0);
- virtual ~QtEmoticonsGrid();
+ class QtEmoticonsGrid : public QGridLayout {
+ Q_OBJECT
+ public:
+ explicit QtEmoticonsGrid(const std::map<std::string, std::string>& emoticons, QWidget* parent = 0);
+ virtual ~QtEmoticonsGrid();
- signals:
- void emoticonClicked(QString emoticonAsText);
+ signals:
+ void emoticonClicked(QString emoticonAsText);
- public slots:
- void emoticonClickedSlot(QString emoticonAsText);
+ public slots:
+ void emoticonClickedSlot(QString emoticonAsText);
- private:
- void makeUniqueEmoticonsMap(const std::map<std::string, std::string>& emoticons);
+ private:
+ void makeUniqueEmoticonsMap(const std::map<std::string, std::string>& emoticons);
- std::map<std::string, std::string> uniqueEmoticons_;
- };
+ std::map<std::string, std::string> uniqueEmoticons_;
+ };
}
diff --git a/Swift/QtUI/QtFileTransferListItemModel.cpp b/Swift/QtUI/QtFileTransferListItemModel.cpp
index ef73f4f..d26733b 100644
--- a/Swift/QtUI/QtFileTransferListItemModel.cpp
+++ b/Swift/QtUI/QtFileTransferListItemModel.cpp
@@ -29,115 +29,115 @@ QtFileTransferListItemModel::QtFileTransferListItemModel(QObject *parent) : QAbs
}
QtFileTransferListItemModel::~QtFileTransferListItemModel() {
- if (fileTransferOverview) {
- fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
- }
+ if (fileTransferOverview) {
+ fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
+ }
}
void QtFileTransferListItemModel::setFileTransferOverview(FileTransferOverview *overview) {
- if (fileTransferOverview) {
- fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
- }
- fileTransferOverview = overview;
- if (fileTransferOverview) {
- fileTransferOverview->onNewFileTransferController.connect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
- fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
- }
- emit layoutAboutToBeChanged();
- emit layoutChanged();
+ if (fileTransferOverview) {
+ fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
+ }
+ fileTransferOverview = overview;
+ if (fileTransferOverview) {
+ fileTransferOverview->onNewFileTransferController.connect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
+ fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
+ }
+ emit layoutAboutToBeChanged();
+ emit layoutChanged();
}
void QtFileTransferListItemModel::handleNewFileTransferController(FileTransferController* newController) {
- emit layoutAboutToBeChanged();
- emit layoutChanged();
- dataChanged(createIndex(0,0), createIndex(fileTransferOverview->getFileTransfers().size(),4));
- newController->onStateChanged.connect(boost::bind(&QtFileTransferListItemModel::handleStateChange, this, fileTransferOverview->getFileTransfers().size() - 1));
- newController->onProgressChange.connect(boost::bind(&QtFileTransferListItemModel::handleProgressChange, this, fileTransferOverview->getFileTransfers().size() - 1));
+ emit layoutAboutToBeChanged();
+ emit layoutChanged();
+ dataChanged(createIndex(0,0), createIndex(fileTransferOverview->getFileTransfers().size(),4));
+ newController->onStateChanged.connect(boost::bind(&QtFileTransferListItemModel::handleStateChange, this, fileTransferOverview->getFileTransfers().size() - 1));
+ newController->onProgressChange.connect(boost::bind(&QtFileTransferListItemModel::handleProgressChange, this, fileTransferOverview->getFileTransfers().size() - 1));
}
void QtFileTransferListItemModel::handleFileTransferListChanged() {
- emit layoutAboutToBeChanged();
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ emit layoutChanged();
}
void QtFileTransferListItemModel::handleStateChange(int index) {
- emit dataChanged(createIndex(index, 2), createIndex(index, 2));
+ emit dataChanged(createIndex(index, 2), createIndex(index, 2));
}
void QtFileTransferListItemModel::handleProgressChange(int index) {
- emit dataChanged(createIndex(index, 3), createIndex(index, 3));
+ emit dataChanged(createIndex(index, 3), createIndex(index, 3));
}
QVariant QtFileTransferListItemModel::headerData(int section, Qt::Orientation /* orientation */, int role) const {
- if (role != Qt::DisplayRole) return QVariant();
- if (section == Direction) return QVariant(QObject::tr("Direction"));
- if (section == OtherParty) return QVariant(QObject::tr("Other Party"));
- if (section == State) return QVariant(QObject::tr("State"));
- if (section == Progress) return QVariant(QObject::tr("Progress"));
- if (section == OverallSize) return QVariant(QObject::tr("Size"));
- return QVariant();
+ if (role != Qt::DisplayRole) return QVariant();
+ if (section == Direction) return QVariant(QObject::tr("Direction"));
+ if (section == OtherParty) return QVariant(QObject::tr("Other Party"));
+ if (section == State) return QVariant(QObject::tr("State"));
+ if (section == Progress) return QVariant(QObject::tr("Progress"));
+ if (section == OverallSize) return QVariant(QObject::tr("Size"));
+ return QVariant();
}
int QtFileTransferListItemModel::columnCount(const QModelIndex& /* parent */) const {
- return NoOfColumns;
+ return NoOfColumns;
}
QVariant QtFileTransferListItemModel::data(const QModelIndex &index, int role) const {
- if (role != Qt::DisplayRole || !index.isValid() ||
- !fileTransferOverview || static_cast<size_t>(index.row()) >= fileTransferOverview->getFileTransfers().size()) {
- return QVariant();
- }
- FileTransferController* controller = fileTransferOverview->getFileTransfers().at(index.row());
- if (index.column() == Direction) {
- return controller->isIncoming() ? QVariant(QObject::tr("Incoming")) : QVariant(QObject::tr("Outgoing"));
- }
- if (index.column() == OtherParty) {
- return QVariant(P2QSTRING(controller->getOtherParty().toString()));
- }
- if (index.column() == State) {
- FileTransfer::State state = controller->getState();
- switch(state.type) {
- case FileTransfer::State::Initial:
- assert(false);
- return QVariant("");
- case FileTransfer::State::WaitingForStart:
- return QVariant(QObject::tr("Waiting for start"));
- case FileTransfer::State::WaitingForAccept:
- return QVariant(QObject::tr("Waiting for other side to accept"));
- case FileTransfer::State::Negotiating:
- return QVariant(QObject::tr("Negotiating"));
- case FileTransfer::State::Transferring:
- return QVariant(QObject::tr("Transferring"));
- case FileTransfer::State::Finished:
- return QVariant(QObject::tr("Finished"));
- case FileTransfer::State::Failed:
- return QVariant(QObject::tr("Failed"));
- case FileTransfer::State::Canceled:
- return QVariant(QObject::tr("Canceled"));
- }
- }
-
- if (index.column() == Progress) {
- return QVariant(QString::number(controller->getProgress()));
- }
- if (index.column() == OverallSize) {
- return QVariant(P2QSTRING(formatSize((controller->getSize()))));
- }
- return QVariant();
+ if (role != Qt::DisplayRole || !index.isValid() ||
+ !fileTransferOverview || static_cast<size_t>(index.row()) >= fileTransferOverview->getFileTransfers().size()) {
+ return QVariant();
+ }
+ FileTransferController* controller = fileTransferOverview->getFileTransfers().at(index.row());
+ if (index.column() == Direction) {
+ return controller->isIncoming() ? QVariant(QObject::tr("Incoming")) : QVariant(QObject::tr("Outgoing"));
+ }
+ if (index.column() == OtherParty) {
+ return QVariant(P2QSTRING(controller->getOtherParty().toString()));
+ }
+ if (index.column() == State) {
+ FileTransfer::State state = controller->getState();
+ switch(state.type) {
+ case FileTransfer::State::Initial:
+ assert(false);
+ return QVariant("");
+ case FileTransfer::State::WaitingForStart:
+ return QVariant(QObject::tr("Waiting for start"));
+ case FileTransfer::State::WaitingForAccept:
+ return QVariant(QObject::tr("Waiting for other side to accept"));
+ case FileTransfer::State::Negotiating:
+ return QVariant(QObject::tr("Negotiating"));
+ case FileTransfer::State::Transferring:
+ return QVariant(QObject::tr("Transferring"));
+ case FileTransfer::State::Finished:
+ return QVariant(QObject::tr("Finished"));
+ case FileTransfer::State::Failed:
+ return QVariant(QObject::tr("Failed"));
+ case FileTransfer::State::Canceled:
+ return QVariant(QObject::tr("Canceled"));
+ }
+ }
+
+ if (index.column() == Progress) {
+ return QVariant(QString::number(controller->getProgress()));
+ }
+ if (index.column() == OverallSize) {
+ return QVariant(P2QSTRING(formatSize((controller->getSize()))));
+ }
+ return QVariant();
}
QModelIndex QtFileTransferListItemModel::parent(const QModelIndex& /* child */) const {
- return createIndex(0,0);
+ return createIndex(0,0);
}
int QtFileTransferListItemModel::rowCount(const QModelIndex& /* parent */) const {
- return fileTransferOverview ? fileTransferOverview->getFileTransfers().size() : 0;
+ return fileTransferOverview ? fileTransferOverview->getFileTransfers().size() : 0;
}
QModelIndex QtFileTransferListItemModel::index(int row, int column, const QModelIndex& /* parent */) const {
- return createIndex(row, column, static_cast<void*>(0));
+ return createIndex(row, column, static_cast<void*>(0));
}
}
diff --git a/Swift/QtUI/QtFileTransferListItemModel.h b/Swift/QtUI/QtFileTransferListItemModel.h
index 64cdca4..d0e0e42 100644
--- a/Swift/QtUI/QtFileTransferListItemModel.h
+++ b/Swift/QtUI/QtFileTransferListItemModel.h
@@ -20,42 +20,42 @@ class FileTransferController;
class FileTransferOverview;
class QtFileTransferListItemModel : public QAbstractItemModel {
- Q_OBJECT
+ Q_OBJECT
public:
- explicit QtFileTransferListItemModel(QObject *parent = 0);
- virtual ~QtFileTransferListItemModel();
+ explicit QtFileTransferListItemModel(QObject *parent = 0);
+ virtual ~QtFileTransferListItemModel();
- void setFileTransferOverview(FileTransferOverview*);
+ void setFileTransferOverview(FileTransferOverview*);
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- int columnCount(const QModelIndex &parent) const;
- QVariant data(const QModelIndex &index, int role) const;
- QModelIndex parent(const QModelIndex &child) const;
- int rowCount(const QModelIndex &parent) const;
- QModelIndex index(int row, int column, const QModelIndex &parent) const;
+ QVariant headerData(int section, Qt::Orientation orientation, int role) const;
+ int columnCount(const QModelIndex &parent) const;
+ QVariant data(const QModelIndex &index, int role) const;
+ QModelIndex parent(const QModelIndex &child) const;
+ int rowCount(const QModelIndex &parent) const;
+ QModelIndex index(int row, int column, const QModelIndex &parent) const;
private:
- enum Columns {
- Direction = 0,
- OtherParty,
- State,
- Progress,
- OverallSize,
- NoOfColumns
- };
+ enum Columns {
+ Direction = 0,
+ OtherParty,
+ State,
+ Progress,
+ OverallSize,
+ NoOfColumns
+ };
private:
- void handleNewFileTransferController(FileTransferController*);
- void handleFileTransferListChanged();
- void handleStateChange(int index);
- void handleProgressChange(int index);
+ void handleNewFileTransferController(FileTransferController*);
+ void handleFileTransferListChanged();
+ void handleStateChange(int index);
+ void handleProgressChange(int index);
signals:
public slots:
private:
- FileTransferOverview *fileTransferOverview;
+ FileTransferOverview *fileTransferOverview;
};
diff --git a/Swift/QtUI/QtFileTransferListWidget.cpp b/Swift/QtUI/QtFileTransferListWidget.cpp
index d95cd06..f67b510 100644
--- a/Swift/QtUI/QtFileTransferListWidget.cpp
+++ b/Swift/QtUI/QtFileTransferListWidget.cpp
@@ -26,86 +26,86 @@
namespace Swift {
QtFileTransferListWidget::QtFileTransferListWidget() : fileTransferOverview(0) {
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->setSpacing(0);
- layout->setContentsMargins(0,0,0,0);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->setSpacing(0);
+ layout->setContentsMargins(0,0,0,0);
- treeView = new QTreeView(this);
- treeView->setRootIsDecorated(false);
- treeView->setItemsExpandable(false);
- layout->addWidget(treeView);
+ treeView = new QTreeView(this);
+ treeView->setRootIsDecorated(false);
+ treeView->setItemsExpandable(false);
+ layout->addWidget(treeView);
- itemModel = new QtFileTransferListItemModel();
- treeView->setModel(itemModel);
+ itemModel = new QtFileTransferListItemModel();
+ treeView->setModel(itemModel);
- QWidget* bottom = new QWidget(this);
- layout->addWidget(bottom);
- bottom->setAutoFillBackground(true);
+ QWidget* bottom = new QWidget(this);
+ layout->addWidget(bottom);
+ bottom->setAutoFillBackground(true);
- QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
- buttonLayout->setContentsMargins(10,0,20,0);
- buttonLayout->setSpacing(0);
+ QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
+ buttonLayout->setContentsMargins(10,0,20,0);
+ buttonLayout->setSpacing(0);
- clearFinished = new QPushButton(tr("Clear all"), bottom);
- clearFinished->setEnabled(false);
- connect(clearFinished, SIGNAL(clicked()), this, SLOT(clearInactiveTransfers()));
- buttonLayout->addWidget(clearFinished);
+ clearFinished = new QPushButton(tr("Clear all"), bottom);
+ clearFinished->setEnabled(false);
+ connect(clearFinished, SIGNAL(clicked()), this, SLOT(clearInactiveTransfers()));
+ buttonLayout->addWidget(clearFinished);
- setWindowTitle(tr("File Transfer List"));
- emit titleUpdated();
+ setWindowTitle(tr("File Transfer List"));
+ emit titleUpdated();
}
QtFileTransferListWidget::~QtFileTransferListWidget() {
- if (fileTransferOverview) {
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
- fileTransferOverview = NULL;
- }
- delete itemModel;
+ if (fileTransferOverview) {
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
+ fileTransferOverview = NULL;
+ }
+ delete itemModel;
}
void QtFileTransferListWidget::showEvent(QShowEvent* event) {
- emit windowOpening();
- emit titleUpdated(); /* This just needs to be somewhere after construction */
- QWidget::showEvent(event);
+ emit windowOpening();
+ emit titleUpdated(); /* This just needs to be somewhere after construction */
+ QWidget::showEvent(event);
}
void QtFileTransferListWidget::handleFileTransferListChanged() {
- clearFinished->setEnabled(fileTransferOverview->isClearable());
+ clearFinished->setEnabled(fileTransferOverview->isClearable());
}
void QtFileTransferListWidget::clearInactiveTransfers() {
- fileTransferOverview->clearFinished();
+ fileTransferOverview->clearFinished();
}
void QtFileTransferListWidget::show() {
- QWidget::show();
- emit windowOpening();
+ QWidget::show();
+ emit windowOpening();
}
void QtFileTransferListWidget::activate() {
- emit wantsToActivate();
+ emit wantsToActivate();
}
void QtFileTransferListWidget::setFileTransferOverview(FileTransferOverview *overview) {
- if (fileTransferOverview) {
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
- fileTransferOverview = NULL;
- }
- if (overview) {
- fileTransferOverview = overview;
- fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
- clearFinished->setEnabled(fileTransferOverview->isClearable());
- }
- itemModel->setFileTransferOverview(overview);
+ if (fileTransferOverview) {
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
+ fileTransferOverview = NULL;
+ }
+ if (overview) {
+ fileTransferOverview = overview;
+ fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
+ clearFinished->setEnabled(fileTransferOverview->isClearable());
+ }
+ itemModel->setFileTransferOverview(overview);
}
std::string QtFileTransferListWidget::getID() const {
- return "QtFileTransferListWidget";
+ return "QtFileTransferListWidget";
}
void QtFileTransferListWidget::closeEvent(QCloseEvent* event) {
- emit windowClosing();
- event->accept();
+ emit windowClosing();
+ event->accept();
}
}
diff --git a/Swift/QtUI/QtFileTransferListWidget.h b/Swift/QtUI/QtFileTransferListWidget.h
index 740eb15..cfc7dd2 100644
--- a/Swift/QtUI/QtFileTransferListWidget.h
+++ b/Swift/QtUI/QtFileTransferListWidget.h
@@ -27,33 +27,33 @@ class FileTransferOverview;
class QtFileTransferListItemModel;
class QtFileTransferListWidget : public QtTabbable, public FileTransferListWidget {
- Q_OBJECT
+ Q_OBJECT
public:
- QtFileTransferListWidget();
- virtual ~QtFileTransferListWidget();
+ QtFileTransferListWidget();
+ virtual ~QtFileTransferListWidget();
- void show();
- void activate();
+ void show();
+ void activate();
- void setFileTransferOverview(FileTransferOverview *);
+ void setFileTransferOverview(FileTransferOverview *);
- virtual std::string getID() const;
+ virtual std::string getID() const;
private:
- virtual void closeEvent(QCloseEvent* event);
- virtual void showEvent(QShowEvent* event);
- void handleFileTransferListChanged();
+ virtual void closeEvent(QCloseEvent* event);
+ virtual void showEvent(QShowEvent* event);
+ void handleFileTransferListChanged();
private slots:
- void clearInactiveTransfers();
+ void clearInactiveTransfers();
private:
- QTreeView* treeView;
+ QTreeView* treeView;
- QtFileTransferListItemModel* itemModel;
- FileTransferOverview* fileTransferOverview;
- QPushButton* clearFinished;
+ QtFileTransferListItemModel* itemModel;
+ FileTransferOverview* fileTransferOverview;
+ QPushButton* clearFinished;
};
}
diff --git a/Swift/QtUI/QtFormResultItemModel.cpp b/Swift/QtUI/QtFormResultItemModel.cpp
index 6a48bc5..60cf0c0 100644
--- a/Swift/QtUI/QtFormResultItemModel.cpp
+++ b/Swift/QtUI/QtFormResultItemModel.cpp
@@ -29,67 +29,67 @@ QtFormResultItemModel::QtFormResultItemModel(QObject* parent, Form::ref formResu
}
void QtFormResultItemModel::setForm(Form::ref formResult) {
- emit layoutAboutToBeChanged();
- formResult_ = formResult;
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ formResult_ = formResult;
+ emit layoutChanged();
}
const Form::ref QtFormResultItemModel::getForm() const {
- return formResult_;
+ return formResult_;
}
QVariant QtFormResultItemModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const {
- if (!formResult_) return QVariant();
- if (role != Qt::DisplayRole) return QVariant();
- if (static_cast<size_t>(section) >= formResult_->getReportedFields().size()) return QVariant();
- return QVariant(P2QSTRING(formResult_->getReportedFields().at(section)->getLabel()));
+ if (!formResult_) return QVariant();
+ if (role != Qt::DisplayRole) return QVariant();
+ if (static_cast<size_t>(section) >= formResult_->getReportedFields().size()) return QVariant();
+ return QVariant(P2QSTRING(formResult_->getReportedFields().at(section)->getLabel()));
}
int QtFormResultItemModel::rowCount(const QModelIndex &/*parent*/) const {
- if (!formResult_) return 0;
- return formResult_->getItems().size();
+ if (!formResult_) return 0;
+ return formResult_->getItems().size();
}
int QtFormResultItemModel::columnCount(const QModelIndex &/*parent*/) const {
- if (!formResult_) return 0;
- return formResult_->getReportedFields().size();
+ if (!formResult_) return 0;
+ return formResult_->getReportedFields().size();
}
QVariant QtFormResultItemModel::data(const QModelIndex &index, int role) const {
- if (!formResult_) return QVariant();
- if (role != Qt::DisplayRole || !index.isValid()) {
- return QVariant();
- }
+ if (!formResult_) return QVariant();
+ if (role != Qt::DisplayRole || !index.isValid()) {
+ return QVariant();
+ }
- if (static_cast<size_t>(index.row()) >= formResult_->getItems().size()) return QVariant();
- if (static_cast<size_t>(index.column()) >= formResult_->getReportedFields().size()) return QVariant();
+ if (static_cast<size_t>(index.row()) >= formResult_->getItems().size()) return QVariant();
+ if (static_cast<size_t>(index.column()) >= formResult_->getReportedFields().size()) return QVariant();
- Form::FormItem item = formResult_->getItems().at(index.row());
+ Form::FormItem item = formResult_->getItems().at(index.row());
- return QVariant(P2QSTRING(getFieldValue(item, index.column())));
+ return QVariant(P2QSTRING(getFieldValue(item, index.column())));
}
const std::string QtFormResultItemModel::getFieldValue(const Form::FormItem& item, const int column) const {
- // determine field name
- std::string name = formResult_->getReportedFields().at(column)->getName();
-
- foreach(FormField::ref field, item) {
- if (field->getName() == name) {
- std::string delimiter = "";
- if (field->getType() == FormField::TextMultiType) {
- delimiter = "\n";
- }
- else if (field->getType() == FormField::JIDMultiType) {
- delimiter = ", ";
- }
- else if (field->getType() == FormField::ListMultiType) {
- delimiter = ", ";
- }
- return boost::algorithm::join(field->getValues(), delimiter);
- }
- }
-
- return "";
+ // determine field name
+ std::string name = formResult_->getReportedFields().at(column)->getName();
+
+ foreach(FormField::ref field, item) {
+ if (field->getName() == name) {
+ std::string delimiter = "";
+ if (field->getType() == FormField::TextMultiType) {
+ delimiter = "\n";
+ }
+ else if (field->getType() == FormField::JIDMultiType) {
+ delimiter = ", ";
+ }
+ else if (field->getType() == FormField::ListMultiType) {
+ delimiter = ", ";
+ }
+ return boost::algorithm::join(field->getValues(), delimiter);
+ }
+ }
+
+ return "";
}
}
diff --git a/Swift/QtUI/QtFormResultItemModel.h b/Swift/QtUI/QtFormResultItemModel.h
index f383f74..47f3549 100644
--- a/Swift/QtUI/QtFormResultItemModel.h
+++ b/Swift/QtUI/QtFormResultItemModel.h
@@ -13,24 +13,24 @@
namespace Swift {
class QtFormResultItemModel : public QAbstractTableModel {
- Q_OBJECT
- public:
- QtFormResultItemModel(QObject* parent);
- QtFormResultItemModel(QObject* parent, Form::ref formResult);
+ Q_OBJECT
+ public:
+ QtFormResultItemModel(QObject* parent);
+ QtFormResultItemModel(QObject* parent, Form::ref formResult);
- void setForm(Form::ref formResult);
- const Form::ref getForm() const;
+ void setForm(Form::ref formResult);
+ const Form::ref getForm() const;
- virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
- virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
- virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const;
+ virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
+ virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- private:
- const std::string getFieldValue(const Form::FormItem& item, const int column) const;
+ private:
+ const std::string getFieldValue(const Form::FormItem& item, const int column) const;
- private:
- Form::ref formResult_;
+ private:
+ Form::ref formResult_;
};
}
diff --git a/Swift/QtUI/QtFormWidget.cpp b/Swift/QtUI/QtFormWidget.cpp
index ea452dc..13049ca 100644
--- a/Swift/QtUI/QtFormWidget.cpp
+++ b/Swift/QtUI/QtFormWidget.cpp
@@ -26,46 +26,46 @@
namespace Swift {
QtFormWidget::QtFormWidget(Form::ref form, QWidget* parent) : QWidget(parent), form_(form) {
- QGridLayout* thisLayout = new QGridLayout(this);
- int row = 0;
- if (!form->getTitle().empty()) {
- QLabel* instructions = new QLabel(("<b>" + form->getTitle() + "</b>").c_str(), this);
- thisLayout->addWidget(instructions, row++, 0, 1, 2);
- }
- if (!form->getInstructions().empty()) {
- QLabel* instructions = new QLabel(form->getInstructions().c_str(), this);
- thisLayout->addWidget(instructions, row++, 0, 1, 2);
- }
- QScrollArea* scrollArea = new QScrollArea(this);
- thisLayout->addWidget(scrollArea);
- QWidget* scroll = new QWidget(this);
- QGridLayout* layout = new QGridLayout(scroll);
- const std::vector<Form::FormItem> items = form->getItems();
- if (items.empty()) { /* single item forms */
- foreach (FormField::ref field, form->getFields()) {
- QWidget* widget = createWidget(field, field->getType(), 0);
- if (widget) {
- layout->addWidget(new QLabel(field->getLabel().c_str(), this), row, 0);
- layout->addWidget(widget, row++, 1);
- }
- }
- } else { /* multi-item forms */
- const Form::FormItem& headers = form->getFields();
- for (size_t i = 0; i < items.size(); ++i) {
- const Form::FormItem& item = items[i];
- assert(item.size() == headers.size());
- for (size_t j = 0; j < item.size(); ++j) {
- QWidget* widget = createWidget(item[j], headers[j]->getType(), i);
- if (widget) {
- layout->addWidget(new QLabel(item[j]->getLabel().c_str(), this), row, 0);
- layout->addWidget(widget, row++, 1);
- }
- }
- }
- }
- scrollArea->setWidget(scroll);
- scrollArea->setWidgetResizable(true);
- setEditable(form->getType() != Form::CancelType && form->getType() != Form::ResultType);
+ QGridLayout* thisLayout = new QGridLayout(this);
+ int row = 0;
+ if (!form->getTitle().empty()) {
+ QLabel* instructions = new QLabel(("<b>" + form->getTitle() + "</b>").c_str(), this);
+ thisLayout->addWidget(instructions, row++, 0, 1, 2);
+ }
+ if (!form->getInstructions().empty()) {
+ QLabel* instructions = new QLabel(form->getInstructions().c_str(), this);
+ thisLayout->addWidget(instructions, row++, 0, 1, 2);
+ }
+ QScrollArea* scrollArea = new QScrollArea(this);
+ thisLayout->addWidget(scrollArea);
+ QWidget* scroll = new QWidget(this);
+ QGridLayout* layout = new QGridLayout(scroll);
+ const std::vector<Form::FormItem> items = form->getItems();
+ if (items.empty()) { /* single item forms */
+ foreach (FormField::ref field, form->getFields()) {
+ QWidget* widget = createWidget(field, field->getType(), 0);
+ if (widget) {
+ layout->addWidget(new QLabel(field->getLabel().c_str(), this), row, 0);
+ layout->addWidget(widget, row++, 1);
+ }
+ }
+ } else { /* multi-item forms */
+ const Form::FormItem& headers = form->getFields();
+ for (size_t i = 0; i < items.size(); ++i) {
+ const Form::FormItem& item = items[i];
+ assert(item.size() == headers.size());
+ for (size_t j = 0; j < item.size(); ++j) {
+ QWidget* widget = createWidget(item[j], headers[j]->getType(), i);
+ if (widget) {
+ layout->addWidget(new QLabel(item[j]->getLabel().c_str(), this), row, 0);
+ layout->addWidget(widget, row++, 1);
+ }
+ }
+ }
+ }
+ scrollArea->setWidget(scroll);
+ scrollArea->setWidgetResizable(true);
+ setEditable(form->getType() != Form::CancelType && form->getType() != Form::ResultType);
}
QtFormWidget::~QtFormWidget() {
@@ -73,168 +73,168 @@ QtFormWidget::~QtFormWidget() {
}
QListWidget* QtFormWidget::createList(FormField::ref field) {
- QListWidget* listWidget = new QListWidget(this);
- listWidget->setSortingEnabled(false);
- listWidget->setSelectionMode(field->getType() == FormField::ListMultiType ? QAbstractItemView::MultiSelection : QAbstractItemView::SingleSelection);
- std::vector<bool> selected;
- /* if this is an editable form, use the 'options' list, otherwise use the 'values' list */
- if (form_->getType() != Form::FormType) {
- foreach (const std::string& value, field->getValues()) {
- listWidget->addItem(P2QSTRING(value));
- selected.push_back(false);
- }
- } else {
- foreach (FormField::Option option, field->getOptions()) {
- listWidget->addItem(option.label.c_str());
- if (field->getType() == FormField::ListSingleType) {
- selected.push_back(!field->getValues().empty() && option.value == field->getValues()[0]);
- }
- else if (field->getType() == FormField::ListMultiType) {
- std::string text = option.value;
- selected.push_back(std::find(field->getValues().begin(), field->getValues().end(), text) != field->getValues().end());
- }
- }
- }
- for (int i = 0; i < listWidget->count(); i++) {
- QListWidgetItem* item = listWidget->item(i);
- item->setSelected(selected[i]);
- }
- return listWidget;
+ QListWidget* listWidget = new QListWidget(this);
+ listWidget->setSortingEnabled(false);
+ listWidget->setSelectionMode(field->getType() == FormField::ListMultiType ? QAbstractItemView::MultiSelection : QAbstractItemView::SingleSelection);
+ std::vector<bool> selected;
+ /* if this is an editable form, use the 'options' list, otherwise use the 'values' list */
+ if (form_->getType() != Form::FormType) {
+ foreach (const std::string& value, field->getValues()) {
+ listWidget->addItem(P2QSTRING(value));
+ selected.push_back(false);
+ }
+ } else {
+ foreach (FormField::Option option, field->getOptions()) {
+ listWidget->addItem(option.label.c_str());
+ if (field->getType() == FormField::ListSingleType) {
+ selected.push_back(!field->getValues().empty() && option.value == field->getValues()[0]);
+ }
+ else if (field->getType() == FormField::ListMultiType) {
+ std::string text = option.value;
+ selected.push_back(std::find(field->getValues().begin(), field->getValues().end(), text) != field->getValues().end());
+ }
+ }
+ }
+ for (int i = 0; i < listWidget->count(); i++) {
+ QListWidgetItem* item = listWidget->item(i);
+ item->setSelected(selected[i]);
+ }
+ return listWidget;
}
QWidget* QtFormWidget::createWidget(FormField::ref field, const FormField::Type type, const size_t index) {
- QWidget* widget = NULL;
- if (type == FormField::BooleanType) {
- QCheckBox* checkWidget = new QCheckBox(this);
- checkWidget->setCheckState(field->getBoolValue() ? Qt::Checked : Qt::Unchecked);
- widget = checkWidget;
- }
- if (type == FormField::FixedType) {
- QString value = field->getFixedValue().c_str();
- widget = new QLabel(value, this);
- }
- if (type == FormField::ListSingleType) {
- widget = createList(field);
- }
- if (type == FormField::TextMultiType) {
- QString value = field->getTextMultiValue().c_str();
- QTextEdit* textWidget = new QTextEdit(this);
- textWidget->setPlainText(value);
- widget = textWidget;
- }
- if (type == FormField::TextPrivateType) {
- QString value = field->getTextPrivateValue().c_str();
- QLineEdit* lineWidget = new QLineEdit(value, this);
- lineWidget->setEchoMode(QLineEdit::Password);
- widget = lineWidget;
- }
- if (type == FormField::TextSingleType) {
- QString value = field->getTextSingleValue().c_str();
- widget = new QLineEdit(value, this);
- }
- if (type == FormField::JIDSingleType) {
- QString value = field->getJIDSingleValue().toString().c_str();
- widget = new QLineEdit(value, this);
- }
- if (type == FormField::JIDMultiType) {
- QString text = boost::join(field->getValues(), "\n").c_str();
- QTextEdit* textWidget = new QTextEdit(this);
- textWidget->setPlainText(text);
- widget = textWidget;
- }
- if (type == FormField::ListMultiType) {
- widget = createList(field);
- }
- std::string indexString;
- if (index) {
- /* for multi-item forms we need to distinguish between the different rows */
- indexString = boost::lexical_cast<std::string>(index);
- }
- fields_[field->getName() + indexString] = widget;
- return widget;
+ QWidget* widget = NULL;
+ if (type == FormField::BooleanType) {
+ QCheckBox* checkWidget = new QCheckBox(this);
+ checkWidget->setCheckState(field->getBoolValue() ? Qt::Checked : Qt::Unchecked);
+ widget = checkWidget;
+ }
+ if (type == FormField::FixedType) {
+ QString value = field->getFixedValue().c_str();
+ widget = new QLabel(value, this);
+ }
+ if (type == FormField::ListSingleType) {
+ widget = createList(field);
+ }
+ if (type == FormField::TextMultiType) {
+ QString value = field->getTextMultiValue().c_str();
+ QTextEdit* textWidget = new QTextEdit(this);
+ textWidget->setPlainText(value);
+ widget = textWidget;
+ }
+ if (type == FormField::TextPrivateType) {
+ QString value = field->getTextPrivateValue().c_str();
+ QLineEdit* lineWidget = new QLineEdit(value, this);
+ lineWidget->setEchoMode(QLineEdit::Password);
+ widget = lineWidget;
+ }
+ if (type == FormField::TextSingleType) {
+ QString value = field->getTextSingleValue().c_str();
+ widget = new QLineEdit(value, this);
+ }
+ if (type == FormField::JIDSingleType) {
+ QString value = field->getJIDSingleValue().toString().c_str();
+ widget = new QLineEdit(value, this);
+ }
+ if (type == FormField::JIDMultiType) {
+ QString text = boost::join(field->getValues(), "\n").c_str();
+ QTextEdit* textWidget = new QTextEdit(this);
+ textWidget->setPlainText(text);
+ widget = textWidget;
+ }
+ if (type == FormField::ListMultiType) {
+ widget = createList(field);
+ }
+ std::string indexString;
+ if (index) {
+ /* for multi-item forms we need to distinguish between the different rows */
+ indexString = boost::lexical_cast<std::string>(index);
+ }
+ fields_[field->getName() + indexString] = widget;
+ return widget;
}
Form::ref QtFormWidget::getCompletedForm() {
- Form::ref result(new Form(Form::SubmitType));
- foreach (boost::shared_ptr<FormField> field, form_->getFields()) {
- boost::shared_ptr<FormField> resultField = boost::make_shared<FormField>(field->getType());
- if (field->getType() == FormField::BooleanType) {
- resultField->setBoolValue(qobject_cast<QCheckBox*>(fields_[field->getName()])->checkState() == Qt::Checked);
- }
- if (field->getType() == FormField::FixedType || field->getType() == FormField::HiddenType) {
- resultField->addValue(field->getValues().empty() ? "" : field->getValues()[0]);
- }
- if (field->getType() == FormField::ListSingleType) {
- QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
- if (listWidget->selectedItems().size() > 0) {
- int i = listWidget->row(listWidget->selectedItems()[0]);
- resultField->addValue(field->getOptions()[i].value);
- }
- }
- if (field->getType() == FormField::TextMultiType) {
- QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
- QString string = widget->toPlainText();
- if (!string.isEmpty()) {
- resultField->setTextMultiValue(Q2PSTRING(string));
- }
- }
- if (field->getType() == FormField::TextPrivateType || field->getType() == FormField::TextSingleType || field->getType() == FormField::JIDSingleType) {
- QLineEdit* widget = qobject_cast<QLineEdit*>(fields_[field->getName()]);
- QString string = widget->text();
- if (!string.isEmpty()) {
- resultField->addValue(Q2PSTRING(string));
- }
- }
- if (field->getType() == FormField::JIDMultiType) {
- QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
- QString string = widget->toPlainText();
- if (!string.isEmpty()) {
- QStringList lines = string.split("\n");
- foreach (QString line, lines) {
- resultField->addValue(Q2PSTRING(line));
- }
- }
- }
- if (field->getType() == FormField::ListMultiType) {
- QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
- foreach (QListWidgetItem* item, listWidget->selectedItems()) {
- resultField->addValue(field->getOptions()[listWidget->row(item)].value);
- }
- }
- resultField->setName(field->getName());
- result->addField(resultField);
- }
- return result;
+ Form::ref result(new Form(Form::SubmitType));
+ foreach (boost::shared_ptr<FormField> field, form_->getFields()) {
+ boost::shared_ptr<FormField> resultField = boost::make_shared<FormField>(field->getType());
+ if (field->getType() == FormField::BooleanType) {
+ resultField->setBoolValue(qobject_cast<QCheckBox*>(fields_[field->getName()])->checkState() == Qt::Checked);
+ }
+ if (field->getType() == FormField::FixedType || field->getType() == FormField::HiddenType) {
+ resultField->addValue(field->getValues().empty() ? "" : field->getValues()[0]);
+ }
+ if (field->getType() == FormField::ListSingleType) {
+ QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
+ if (listWidget->selectedItems().size() > 0) {
+ int i = listWidget->row(listWidget->selectedItems()[0]);
+ resultField->addValue(field->getOptions()[i].value);
+ }
+ }
+ if (field->getType() == FormField::TextMultiType) {
+ QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
+ QString string = widget->toPlainText();
+ if (!string.isEmpty()) {
+ resultField->setTextMultiValue(Q2PSTRING(string));
+ }
+ }
+ if (field->getType() == FormField::TextPrivateType || field->getType() == FormField::TextSingleType || field->getType() == FormField::JIDSingleType) {
+ QLineEdit* widget = qobject_cast<QLineEdit*>(fields_[field->getName()]);
+ QString string = widget->text();
+ if (!string.isEmpty()) {
+ resultField->addValue(Q2PSTRING(string));
+ }
+ }
+ if (field->getType() == FormField::JIDMultiType) {
+ QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
+ QString string = widget->toPlainText();
+ if (!string.isEmpty()) {
+ QStringList lines = string.split("\n");
+ foreach (QString line, lines) {
+ resultField->addValue(Q2PSTRING(line));
+ }
+ }
+ }
+ if (field->getType() == FormField::ListMultiType) {
+ QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
+ foreach (QListWidgetItem* item, listWidget->selectedItems()) {
+ resultField->addValue(field->getOptions()[listWidget->row(item)].value);
+ }
+ }
+ resultField->setName(field->getName());
+ result->addField(resultField);
+ }
+ return result;
}
template<class T> void QtFormWidget::setEnabled(QWidget* rawWidget, bool editable) {
- T* widget = qobject_cast<T*>(rawWidget);
- if (widget) {
- widget->setEnabled(editable);
- }
+ T* widget = qobject_cast<T*>(rawWidget);
+ if (widget) {
+ widget->setEnabled(editable);
+ }
}
template<class T> void QtFormWidget::setEditable(QWidget* rawWidget, bool editable) {
- T* widget = qobject_cast<T*>(rawWidget);
- if (widget) {
- widget->setReadOnly(!editable);
- }
+ T* widget = qobject_cast<T*>(rawWidget);
+ if (widget) {
+ widget->setReadOnly(!editable);
+ }
}
void QtFormWidget::setEditable(bool editable) {
- if (!form_) {
- return;
- }
- foreach (boost::shared_ptr<FormField> field, form_->getFields()) {
- QWidget* widget = NULL;
- if (field) {
- widget = fields_[field->getName()];
- }
- setEnabled<QCheckBox>(widget, editable);
- setEnabled<QListWidget>(widget, editable);
- setEditable<QTextEdit>(widget, editable);
- setEditable<QLineEdit>(widget, editable);
- }
+ if (!form_) {
+ return;
+ }
+ foreach (boost::shared_ptr<FormField> field, form_->getFields()) {
+ QWidget* widget = NULL;
+ if (field) {
+ widget = fields_[field->getName()];
+ }
+ setEnabled<QCheckBox>(widget, editable);
+ setEnabled<QListWidget>(widget, editable);
+ setEditable<QTextEdit>(widget, editable);
+ setEditable<QLineEdit>(widget, editable);
+ }
}
}
diff --git a/Swift/QtUI/QtFormWidget.h b/Swift/QtUI/QtFormWidget.h
index 4c6311c..1eec115 100644
--- a/Swift/QtUI/QtFormWidget.h
+++ b/Swift/QtUI/QtFormWidget.h
@@ -17,19 +17,19 @@ class QListWidget;
namespace Swift {
class QtFormWidget : public QWidget {
- Q_OBJECT
- public:
- QtFormWidget(Form::ref form, QWidget* parent = NULL);
- virtual ~QtFormWidget();
- Form::ref getCompletedForm();
- void setEditable(bool editable);
- private:
- QWidget* createWidget(FormField::ref field, const FormField::Type type, const size_t index);
- QListWidget* createList(FormField::ref field);
- template<class T> void setEnabled(QWidget* rawWidget, bool editable);
- template<class T> void setEditable(QWidget* rawWidget, bool editable);
- std::map<std::string, QWidget*> fields_;
- Form::ref form_;
+ Q_OBJECT
+ public:
+ QtFormWidget(Form::ref form, QWidget* parent = NULL);
+ virtual ~QtFormWidget();
+ Form::ref getCompletedForm();
+ void setEditable(bool editable);
+ private:
+ QWidget* createWidget(FormField::ref field, const FormField::Type type, const size_t index);
+ QListWidget* createList(FormField::ref field);
+ template<class T> void setEnabled(QWidget* rawWidget, bool editable);
+ template<class T> void setEditable(QWidget* rawWidget, bool editable);
+ std::map<std::string, QWidget*> fields_;
+ Form::ref form_;
};
}
diff --git a/Swift/QtUI/QtHighlightEditor.cpp b/Swift/QtUI/QtHighlightEditor.cpp
index 1d47c4e..fdbff9e 100644
--- a/Swift/QtUI/QtHighlightEditor.cpp
+++ b/Swift/QtUI/QtHighlightEditor.cpp
@@ -29,61 +29,61 @@
namespace Swift {
QtHighlightEditor::QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent)
- : QWidget(parent), settings_(settings), previousRow_(-1)
+ : QWidget(parent), settings_(settings), previousRow_(-1)
{
- ui_.setupUi(this);
+ ui_.setupUi(this);
- connect(ui_.listWidget, SIGNAL(currentRowChanged(int)), SLOT(onCurrentRowChanged(int)));
+ connect(ui_.listWidget, SIGNAL(currentRowChanged(int)), SLOT(onCurrentRowChanged(int)));
- connect(ui_.newButton, SIGNAL(clicked()), SLOT(onNewButtonClicked()));
- connect(ui_.deleteButton, SIGNAL(clicked()), SLOT(onDeleteButtonClicked()));
+ connect(ui_.newButton, SIGNAL(clicked()), SLOT(onNewButtonClicked()));
+ connect(ui_.deleteButton, SIGNAL(clicked()), SLOT(onDeleteButtonClicked()));
- connect(ui_.buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApplyButtonClick()));
- connect(ui_.buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), SLOT(onCancelButtonClick()));
- connect(ui_.buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), SLOT(onOkButtonClick()));
- connect(ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), SLOT(onResetToDefaultRulesClicked()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApplyButtonClick()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), SLOT(onCancelButtonClick()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), SLOT(onOkButtonClick()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), SLOT(onResetToDefaultRulesClicked()));
- connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(colorOtherSelect()));
- connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(colorCustomSelect()));
+ connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(colorOtherSelect()));
+ connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(colorCustomSelect()));
- connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
- connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
- connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(soundCustomSelect()));
+ connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
+ connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
+ connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(soundCustomSelect()));
- /* replace the static line-edit control with the roster autocompleter */
- ui_.dummySenderName->setVisible(false);
- jid_ = new QtSuggestingJIDInput(this, settings);
- ui_.senderName->addWidget(jid_);
- jid_->onUserSelected.connect(boost::bind(&QtHighlightEditor::handleOnUserSelected, this, _1));
+ /* replace the static line-edit control with the roster autocompleter */
+ ui_.dummySenderName->setVisible(false);
+ jid_ = new QtSuggestingJIDInput(this, settings);
+ ui_.senderName->addWidget(jid_);
+ jid_->onUserSelected.connect(boost::bind(&QtHighlightEditor::handleOnUserSelected, this, _1));
- /* handle autocomplete */
- connect(jid_, SIGNAL(textEdited(QString)), SLOT(handleContactSuggestionRequested(QString)));
+ /* handle autocomplete */
+ connect(jid_, SIGNAL(textEdited(QString)), SLOT(handleContactSuggestionRequested(QString)));
- /* we need to be notified if any of the state changes so that we can update our textual rule description */
- connect(ui_.chatRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.roomRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.nickIsKeyword, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.allMsgRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.senderRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(jid_, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
- connect(ui_.keywordRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.keyword, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
- connect(ui_.matchPartialWords, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.matchCase, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ /* we need to be notified if any of the state changes so that we can update our textual rule description */
+ connect(ui_.chatRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.roomRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.nickIsKeyword, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.allMsgRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.senderRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(jid_, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
+ connect(ui_.keywordRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.keyword, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
+ connect(ui_.matchPartialWords, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.matchCase, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- /* allow selection of a custom sound file */
- connect(ui_.soundFileButton, SIGNAL(clicked()), SLOT(selectSoundFile()));
+ /* allow selection of a custom sound file */
+ connect(ui_.soundFileButton, SIGNAL(clicked()), SLOT(selectSoundFile()));
- /* allowing reordering items */
- connect(ui_.moveUpButton, SIGNAL(clicked()), this, SLOT(onUpButtonClicked()));
- connect(ui_.moveDownButton, SIGNAL(clicked()), this, SLOT(onDownButtonClicked()));
+ /* allowing reordering items */
+ connect(ui_.moveUpButton, SIGNAL(clicked()), this, SLOT(onUpButtonClicked()));
+ connect(ui_.moveDownButton, SIGNAL(clicked()), this, SLOT(onDownButtonClicked()));
- setWindowTitle(tr("Highlight Rules"));
+ setWindowTitle(tr("Highlight Rules"));
}
QtHighlightEditor::~QtHighlightEditor()
@@ -92,477 +92,477 @@ QtHighlightEditor::~QtHighlightEditor()
std::string formatShortDescription(const HighlightRule &rule)
{
- const std::string chatOrRoom = (rule.getMatchChat() ? "chat" : "room");
+ const std::string chatOrRoom = (rule.getMatchChat() ? "chat" : "room");
- std::vector<std::string> senders = rule.getSenders();
- std::vector<std::string> keywords = rule.getKeywords();
+ std::vector<std::string> senders = rule.getSenders();
+ std::vector<std::string> keywords = rule.getKeywords();
- if (senders.empty() && keywords.empty() && !rule.getNickIsKeyword()) {
- return std::string("All ") + chatOrRoom + " messages.";
- }
+ if (senders.empty() && keywords.empty() && !rule.getNickIsKeyword()) {
+ return std::string("All ") + chatOrRoom + " messages.";
+ }
- if (rule.getNickIsKeyword()) {
- return std::string("All ") + chatOrRoom + " messages that mention my name.";
- }
+ if (rule.getNickIsKeyword()) {
+ return std::string("All ") + chatOrRoom + " messages that mention my name.";
+ }
- if (!senders.empty()) {
- return std::string("All ") + chatOrRoom + " messages from " + senders[0] + ".";
- }
+ if (!senders.empty()) {
+ return std::string("All ") + chatOrRoom + " messages from " + senders[0] + ".";
+ }
- if (!keywords.empty()) {
- return std::string("All ") + chatOrRoom + " messages mentioning the keyword '" + keywords[0] + "'.";
- }
+ if (!keywords.empty()) {
+ return std::string("All ") + chatOrRoom + " messages mentioning the keyword '" + keywords[0] + "'.";
+ }
- return "Unknown Rule";
+ return "Unknown Rule";
}
void QtHighlightEditor::show()
{
- highlightManager_->loadSettings();
+ highlightManager_->loadSettings();
- populateList();
+ populateList();
- if (ui_.listWidget->count()) {
- selectRow(0);
- }
+ if (ui_.listWidget->count()) {
+ selectRow(0);
+ }
- updateResetToDefaultRulesVisibility();
+ updateResetToDefaultRulesVisibility();
- /* prepare default states */
- widgetClick();
+ /* prepare default states */
+ widgetClick();
- QWidget::show();
- QWidget::activateWindow();
+ QWidget::show();
+ QWidget::activateWindow();
}
void QtHighlightEditor::setHighlightManager(HighlightManager* highlightManager)
{
- highlightManager_ = highlightManager;
+ highlightManager_ = highlightManager;
}
void QtHighlightEditor::setContactSuggestions(const std::vector<Contact::ref>& suggestions)
{
- jid_->setSuggestions(suggestions);
+ jid_->setSuggestions(suggestions);
}
void QtHighlightEditor::colorOtherSelect()
{
- ui_.foregroundColor->setEnabled(false);
- ui_.backgroundColor->setEnabled(false);
+ ui_.foregroundColor->setEnabled(false);
+ ui_.backgroundColor->setEnabled(false);
}
void QtHighlightEditor::colorCustomSelect()
{
- ui_.foregroundColor->setEnabled(true);
- ui_.backgroundColor->setEnabled(true);
+ ui_.foregroundColor->setEnabled(true);
+ ui_.backgroundColor->setEnabled(true);
}
void QtHighlightEditor::soundOtherSelect()
{
- ui_.soundFile->setEnabled(false);
- ui_.soundFileButton->setEnabled(false);
+ ui_.soundFile->setEnabled(false);
+ ui_.soundFileButton->setEnabled(false);
}
void QtHighlightEditor::soundCustomSelect()
{
- ui_.soundFile->setEnabled(true);
- ui_.soundFileButton->setEnabled(true);
+ ui_.soundFile->setEnabled(true);
+ ui_.soundFileButton->setEnabled(true);
}
void QtHighlightEditor::onNewButtonClicked()
{
- int row = getSelectedRow() + 1;
- populateList();
- HighlightRule newRule;
- newRule.setMatchMUC(true);
- highlightManager_->insertRule(row, newRule);
- QListWidgetItem *item = new QListWidgetItem();
- item->setText(P2QSTRING(formatShortDescription(newRule)));
- QFont font;
- font.setItalic(true);
- item->setFont(font);
- ui_.listWidget->insertItem(row, item);
- selectRow(row);
+ int row = getSelectedRow() + 1;
+ populateList();
+ HighlightRule newRule;
+ newRule.setMatchMUC(true);
+ highlightManager_->insertRule(row, newRule);
+ QListWidgetItem *item = new QListWidgetItem();
+ item->setText(P2QSTRING(formatShortDescription(newRule)));
+ QFont font;
+ font.setItalic(true);
+ item->setFont(font);
+ ui_.listWidget->insertItem(row, item);
+ selectRow(row);
}
void QtHighlightEditor::onDeleteButtonClicked()
{
- int selectedRow = getSelectedRow();
- assert(selectedRow>=0 && selectedRow<ui_.listWidget->count());
- delete ui_.listWidget->takeItem(selectedRow);
- highlightManager_->removeRule(selectedRow);
-
- if (!ui_.listWidget->count()) {
- disableDialog();
- ui_.deleteButton->setEnabled(false);
- } else {
- if (selectedRow == ui_.listWidget->count()) {
- selectRow(ui_.listWidget->count() - 1);
- } else {
- selectRow(selectedRow);
- }
- }
+ int selectedRow = getSelectedRow();
+ assert(selectedRow>=0 && selectedRow<ui_.listWidget->count());
+ delete ui_.listWidget->takeItem(selectedRow);
+ highlightManager_->removeRule(selectedRow);
+
+ if (!ui_.listWidget->count()) {
+ disableDialog();
+ ui_.deleteButton->setEnabled(false);
+ } else {
+ if (selectedRow == ui_.listWidget->count()) {
+ selectRow(ui_.listWidget->count() - 1);
+ } else {
+ selectRow(selectedRow);
+ }
+ }
}
void QtHighlightEditor::moveRowFromTo(int fromRow, int toRow) {
- int verticalScrollAreaPosition = ui_.scrollArea->verticalScrollBar()->value();
- highlightManager_->swapRules(fromRow, toRow);
- populateList();
- selectRow(toRow);
- ui_.scrollArea->verticalScrollBar()->setValue(verticalScrollAreaPosition);
+ int verticalScrollAreaPosition = ui_.scrollArea->verticalScrollBar()->value();
+ highlightManager_->swapRules(fromRow, toRow);
+ populateList();
+ selectRow(toRow);
+ ui_.scrollArea->verticalScrollBar()->setValue(verticalScrollAreaPosition);
}
void QtHighlightEditor::onUpButtonClicked() {
- const size_t moveFrom = ui_.listWidget->currentRow();
- const size_t moveTo = moveFrom - 1;
- moveRowFromTo(moveFrom, moveTo);
+ const size_t moveFrom = ui_.listWidget->currentRow();
+ const size_t moveTo = moveFrom - 1;
+ moveRowFromTo(moveFrom, moveTo);
}
void QtHighlightEditor::onDownButtonClicked() {
- const size_t moveFrom = ui_.listWidget->currentRow();
- const size_t moveTo = moveFrom + 1;
- moveRowFromTo(moveFrom, moveTo);
+ const size_t moveFrom = ui_.listWidget->currentRow();
+ const size_t moveTo = moveFrom + 1;
+ moveRowFromTo(moveFrom, moveTo);
}
void QtHighlightEditor::onCurrentRowChanged(int currentRow)
{
- ui_.deleteButton->setEnabled(currentRow != -1);
- ui_.moveUpButton->setEnabled(currentRow != -1 && currentRow != 0);
- ui_.moveDownButton->setEnabled(currentRow != -1 && currentRow != (ui_.listWidget->count()-1));
-
- if (previousRow_ != -1) {
- if (ui_.listWidget->count() > previousRow_) {
- QFont font;
- font.setItalic(false);
- ui_.listWidget->item(previousRow_)->setFont(font);
- highlightManager_->setRule(previousRow_, ruleFromDialog());
- }
- }
-
- if (currentRow != -1) {
- HighlightRule rule = highlightManager_->getRule(currentRow);
- ruleToDialog(rule);
- if (ui_.listWidget->currentItem()) {
- QFont font;
- font.setItalic(true);
- ui_.listWidget->currentItem()->setFont(font);
- ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
- }
- }
-
- /* grey the dialog if we have nothing selected */
- if (currentRow == -1) {
- disableDialog();
- }
-
- previousRow_ = currentRow;
-
- updateResetToDefaultRulesVisibility();
+ ui_.deleteButton->setEnabled(currentRow != -1);
+ ui_.moveUpButton->setEnabled(currentRow != -1 && currentRow != 0);
+ ui_.moveDownButton->setEnabled(currentRow != -1 && currentRow != (ui_.listWidget->count()-1));
+
+ if (previousRow_ != -1) {
+ if (ui_.listWidget->count() > previousRow_) {
+ QFont font;
+ font.setItalic(false);
+ ui_.listWidget->item(previousRow_)->setFont(font);
+ highlightManager_->setRule(previousRow_, ruleFromDialog());
+ }
+ }
+
+ if (currentRow != -1) {
+ HighlightRule rule = highlightManager_->getRule(currentRow);
+ ruleToDialog(rule);
+ if (ui_.listWidget->currentItem()) {
+ QFont font;
+ font.setItalic(true);
+ ui_.listWidget->currentItem()->setFont(font);
+ ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
+ }
+ }
+
+ /* grey the dialog if we have nothing selected */
+ if (currentRow == -1) {
+ disableDialog();
+ }
+
+ previousRow_ = currentRow;
+
+ updateResetToDefaultRulesVisibility();
}
void QtHighlightEditor::onApplyButtonClick()
{
- selectRow(getSelectedRow()); /* force save */
- highlightManager_->storeSettings();
+ selectRow(getSelectedRow()); /* force save */
+ highlightManager_->storeSettings();
}
void QtHighlightEditor::onCancelButtonClick()
{
- close();
+ close();
}
void QtHighlightEditor::onOkButtonClick()
{
- onApplyButtonClick();
- close();
+ onApplyButtonClick();
+ close();
}
void QtHighlightEditor::setChildWidgetStates()
{
- /* disable appropriate radio button child widgets */
-
- if (ui_.chatRadio->isChecked()) {
- if (ui_.nickIsKeyword->isChecked()) {
- /* switch to another choice before we disable this button */
- ui_.allMsgRadio->setChecked(true);
- }
- ui_.nickIsKeyword->setEnabled(false);
- } else if (ui_.roomRadio->isChecked()) {
- ui_.nickIsKeyword->setEnabled(true);
- } else { /* chats and rooms */
- ui_.nickIsKeyword->setEnabled(true);
- }
-
- if (ui_.senderRadio->isChecked()) {
- jid_->setEnabled(true);
- } else {
- jid_->setEnabled(false);
- }
-
- if (ui_.keywordRadio->isChecked()) {
- ui_.keyword->setEnabled(true);
- ui_.matchPartialWords->setEnabled(true);
- ui_.matchCase->setEnabled(true);
- } else {
- ui_.keyword->setEnabled(false);
- ui_.matchPartialWords->setEnabled(false);
- ui_.matchCase->setEnabled(false);
- }
-
- if (ui_.chatRadio->isChecked()) {
- ui_.allMsgRadio->setText(tr("Apply to all chat messages"));
- } else {
- ui_.allMsgRadio->setText(tr("Apply to all room messages"));
- }
+ /* disable appropriate radio button child widgets */
+
+ if (ui_.chatRadio->isChecked()) {
+ if (ui_.nickIsKeyword->isChecked()) {
+ /* switch to another choice before we disable this button */
+ ui_.allMsgRadio->setChecked(true);
+ }
+ ui_.nickIsKeyword->setEnabled(false);
+ } else if (ui_.roomRadio->isChecked()) {
+ ui_.nickIsKeyword->setEnabled(true);
+ } else { /* chats and rooms */
+ ui_.nickIsKeyword->setEnabled(true);
+ }
+
+ if (ui_.senderRadio->isChecked()) {
+ jid_->setEnabled(true);
+ } else {
+ jid_->setEnabled(false);
+ }
+
+ if (ui_.keywordRadio->isChecked()) {
+ ui_.keyword->setEnabled(true);
+ ui_.matchPartialWords->setEnabled(true);
+ ui_.matchCase->setEnabled(true);
+ } else {
+ ui_.keyword->setEnabled(false);
+ ui_.matchPartialWords->setEnabled(false);
+ ui_.matchCase->setEnabled(false);
+ }
+
+ if (ui_.chatRadio->isChecked()) {
+ ui_.allMsgRadio->setText(tr("Apply to all chat messages"));
+ } else {
+ ui_.allMsgRadio->setText(tr("Apply to all room messages"));
+ }
}
void QtHighlightEditor::widgetClick()
{
- setChildWidgetStates();
+ setChildWidgetStates();
- HighlightRule rule = ruleFromDialog();
+ HighlightRule rule = ruleFromDialog();
- if (ui_.listWidget->currentItem()) {
- ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
- }
+ if (ui_.listWidget->currentItem()) {
+ ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
+ }
}
void QtHighlightEditor::disableDialog()
{
- ui_.chatRadio->setEnabled(false);
- ui_.roomRadio->setEnabled(false);
- ui_.allMsgRadio->setEnabled(false);
- ui_.nickIsKeyword->setEnabled(false);
- ui_.senderRadio->setEnabled(false);
- ui_.dummySenderName->setEnabled(false);
- ui_.keywordRadio->setEnabled(false);
- ui_.keyword->setEnabled(false);
- ui_.matchPartialWords->setEnabled(false);
- ui_.matchCase->setEnabled(false);
- ui_.noColorRadio->setEnabled(false);
- ui_.customColorRadio->setEnabled(false);
- ui_.foregroundColor->setEnabled(false);
- ui_.backgroundColor->setEnabled(false);
- ui_.noSoundRadio->setEnabled(false);
- ui_.defaultSoundRadio->setEnabled(false);
- ui_.customSoundRadio->setEnabled(false);
- ui_.soundFile->setEnabled(false);
- ui_.soundFileButton->setEnabled(false);
+ ui_.chatRadio->setEnabled(false);
+ ui_.roomRadio->setEnabled(false);
+ ui_.allMsgRadio->setEnabled(false);
+ ui_.nickIsKeyword->setEnabled(false);
+ ui_.senderRadio->setEnabled(false);
+ ui_.dummySenderName->setEnabled(false);
+ ui_.keywordRadio->setEnabled(false);
+ ui_.keyword->setEnabled(false);
+ ui_.matchPartialWords->setEnabled(false);
+ ui_.matchCase->setEnabled(false);
+ ui_.noColorRadio->setEnabled(false);
+ ui_.customColorRadio->setEnabled(false);
+ ui_.foregroundColor->setEnabled(false);
+ ui_.backgroundColor->setEnabled(false);
+ ui_.noSoundRadio->setEnabled(false);
+ ui_.defaultSoundRadio->setEnabled(false);
+ ui_.customSoundRadio->setEnabled(false);
+ ui_.soundFile->setEnabled(false);
+ ui_.soundFileButton->setEnabled(false);
}
void QtHighlightEditor::handleContactSuggestionRequested(const QString& text)
{
- std::string stdText = Q2PSTRING(text);
- onContactSuggestionsRequested(stdText);
+ std::string stdText = Q2PSTRING(text);
+ onContactSuggestionsRequested(stdText);
}
void QtHighlightEditor::selectSoundFile()
{
- QString path = QFileDialog::getOpenFileName(this, tr("Select sound file..."), QString(), "Sounds (*.wav)");
- ui_.soundFile->setText(path);
+ QString path = QFileDialog::getOpenFileName(this, tr("Select sound file..."), QString(), "Sounds (*.wav)");
+ ui_.soundFile->setText(path);
}
void QtHighlightEditor::onResetToDefaultRulesClicked() {
- highlightManager_->resetToDefaultRulesList();
- populateList();
- updateResetToDefaultRulesVisibility();
+ highlightManager_->resetToDefaultRulesList();
+ populateList();
+ updateResetToDefaultRulesVisibility();
}
void QtHighlightEditor::handleOnUserSelected(const Contact::ref& contact) {
- /* this might seem like it should be standard behaviour for the suggesting input box, but is not desirable in all cases */
- if (contact->jid.isValid()) {
- jid_->setText(P2QSTRING(contact->jid.toString()));
- } else {
- jid_->setText(P2QSTRING(contact->name));
- }
+ /* this might seem like it should be standard behaviour for the suggesting input box, but is not desirable in all cases */
+ if (contact->jid.isValid()) {
+ jid_->setText(P2QSTRING(contact->jid.toString()));
+ } else {
+ jid_->setText(P2QSTRING(contact->name));
+ }
}
void QtHighlightEditor::populateList()
{
- previousRow_ = -1;
- ui_.listWidget->clear();
- HighlightRulesListPtr rules = highlightManager_->getRules();
- for (size_t i = 0; i < rules->getSize(); ++i) {
- const HighlightRule& rule = rules->getRule(i);
- QListWidgetItem *item = new QListWidgetItem();
- item->setText(P2QSTRING(formatShortDescription(rule)));
- ui_.listWidget->addItem(item);
- }
+ previousRow_ = -1;
+ ui_.listWidget->clear();
+ HighlightRulesListPtr rules = highlightManager_->getRules();
+ for (size_t i = 0; i < rules->getSize(); ++i) {
+ const HighlightRule& rule = rules->getRule(i);
+ QListWidgetItem *item = new QListWidgetItem();
+ item->setText(P2QSTRING(formatShortDescription(rule)));
+ ui_.listWidget->addItem(item);
+ }
}
void QtHighlightEditor::selectRow(int row)
{
- for (int i = 0; i < ui_.listWidget->count(); ++i) {
- if (i == row) {
- ui_.listWidget->item(i)->setSelected(true);
- onCurrentRowChanged(i);
- } else {
- ui_.listWidget->item(i)->setSelected(false);
- }
- }
- ui_.listWidget->setCurrentRow(row);
+ for (int i = 0; i < ui_.listWidget->count(); ++i) {
+ if (i == row) {
+ ui_.listWidget->item(i)->setSelected(true);
+ onCurrentRowChanged(i);
+ } else {
+ ui_.listWidget->item(i)->setSelected(false);
+ }
+ }
+ ui_.listWidget->setCurrentRow(row);
}
int QtHighlightEditor::getSelectedRow() const
{
- for (int i = 0; i < ui_.listWidget->count(); ++i) {
- if (ui_.listWidget->item(i)->isSelected()) {
- return i;
- }
- }
- return -1;
+ for (int i = 0; i < ui_.listWidget->count(); ++i) {
+ if (ui_.listWidget->item(i)->isSelected()) {
+ return i;
+ }
+ }
+ return -1;
}
HighlightRule QtHighlightEditor::ruleFromDialog()
{
- HighlightRule rule;
- HighlightAction& action = rule.getAction();
-
- if (ui_.chatRadio->isChecked()) {
- rule.setMatchChat(true);
- rule.setMatchMUC(false);
- } else {
- rule.setMatchChat(false);
- rule.setMatchMUC(true);
- }
-
- if (ui_.allMsgRadio->isChecked()) {
- action.setHighlightWholeMessage(true);
- }
-
- if (ui_.senderRadio->isChecked()) {
- QString senderName = jid_->text();
- if (!senderName.isEmpty()) {
- std::vector<std::string> senders;
- senders.push_back(Q2PSTRING(senderName));
- rule.setSenders(senders);
- action.setHighlightWholeMessage(true);
- }
- }
-
- if (ui_.keywordRadio->isChecked()) {
- QString keywordString = ui_.keyword->text();
- if (!keywordString.isEmpty()) {
- std::vector<std::string> keywords;
- keywords.push_back(Q2PSTRING(keywordString));
- rule.setKeywords(keywords);
- }
- }
-
- if (ui_.nickIsKeyword->isChecked()) {
- rule.setNickIsKeyword(true);
- rule.setMatchWholeWords(true);
- rule.setMatchCase(true);
- } else {
- rule.setMatchWholeWords(!ui_.matchPartialWords->isChecked());
- rule.setMatchCase(ui_.matchCase->isChecked());
- }
-
- if (ui_.noColorRadio->isChecked()) {
- action.setTextColor("");
- action.setTextBackground("");
- } else {
- action.setTextColor(Q2PSTRING(ui_.foregroundColor->getColor().name()));
- action.setTextBackground(Q2PSTRING(ui_.backgroundColor->getColor().name()));
- }
-
- if (ui_.noSoundRadio->isChecked()) {
- action.setPlaySound(false);
- } else if (ui_.defaultSoundRadio->isChecked()) {
- action.setPlaySound(true);
- action.setSoundFile("");
- } else {
- action.setPlaySound(true);
- action.setSoundFile(Q2PSTRING(ui_.soundFile->text()));
- }
-
- return rule;
+ HighlightRule rule;
+ HighlightAction& action = rule.getAction();
+
+ if (ui_.chatRadio->isChecked()) {
+ rule.setMatchChat(true);
+ rule.setMatchMUC(false);
+ } else {
+ rule.setMatchChat(false);
+ rule.setMatchMUC(true);
+ }
+
+ if (ui_.allMsgRadio->isChecked()) {
+ action.setHighlightWholeMessage(true);
+ }
+
+ if (ui_.senderRadio->isChecked()) {
+ QString senderName = jid_->text();
+ if (!senderName.isEmpty()) {
+ std::vector<std::string> senders;
+ senders.push_back(Q2PSTRING(senderName));
+ rule.setSenders(senders);
+ action.setHighlightWholeMessage(true);
+ }
+ }
+
+ if (ui_.keywordRadio->isChecked()) {
+ QString keywordString = ui_.keyword->text();
+ if (!keywordString.isEmpty()) {
+ std::vector<std::string> keywords;
+ keywords.push_back(Q2PSTRING(keywordString));
+ rule.setKeywords(keywords);
+ }
+ }
+
+ if (ui_.nickIsKeyword->isChecked()) {
+ rule.setNickIsKeyword(true);
+ rule.setMatchWholeWords(true);
+ rule.setMatchCase(true);
+ } else {
+ rule.setMatchWholeWords(!ui_.matchPartialWords->isChecked());
+ rule.setMatchCase(ui_.matchCase->isChecked());
+ }
+
+ if (ui_.noColorRadio->isChecked()) {
+ action.setTextColor("");
+ action.setTextBackground("");
+ } else {
+ action.setTextColor(Q2PSTRING(ui_.foregroundColor->getColor().name()));
+ action.setTextBackground(Q2PSTRING(ui_.backgroundColor->getColor().name()));
+ }
+
+ if (ui_.noSoundRadio->isChecked()) {
+ action.setPlaySound(false);
+ } else if (ui_.defaultSoundRadio->isChecked()) {
+ action.setPlaySound(true);
+ action.setSoundFile("");
+ } else {
+ action.setPlaySound(true);
+ action.setSoundFile(Q2PSTRING(ui_.soundFile->text()));
+ }
+
+ return rule;
}
void QtHighlightEditor::ruleToDialog(const HighlightRule& rule)
{
- ui_.chatRadio->setEnabled(true);
- ui_.roomRadio->setEnabled(true);
-
- if (rule.getMatchMUC()) {
- ui_.chatRadio->setChecked(false);
- ui_.roomRadio->setChecked(true);
- } else {
- ui_.chatRadio->setChecked(true);
- ui_.roomRadio->setChecked(false);
- }
-
- ui_.allMsgRadio->setEnabled(true);
- ui_.allMsgRadio->setChecked(true); /* this is the default radio button */
- jid_->setText("");
- ui_.keyword->setText("");
- ui_.matchPartialWords->setChecked(false);
- ui_.matchCase->setChecked(false);
-
- ui_.nickIsKeyword->setEnabled(true);
- if (rule.getNickIsKeyword()) {
- ui_.nickIsKeyword->setChecked(true);
- }
-
- ui_.senderRadio->setEnabled(true);
- std::vector<std::string> senders = rule.getSenders();
- if (!senders.empty()) {
- ui_.senderRadio->setChecked(true);
- jid_->setText(P2QSTRING(senders[0]));
- }
-
- ui_.keywordRadio->setEnabled(true);
- std::vector<std::string> keywords = rule.getKeywords();
- if (!keywords.empty()) {
- ui_.keywordRadio->setChecked(true);
- ui_.keyword->setText(P2QSTRING(keywords[0]));
- ui_.matchPartialWords->setChecked(!rule.getMatchWholeWords());
- ui_.matchCase->setChecked(rule.getMatchCase());
- }
-
- const HighlightAction& action = rule.getAction();
-
- ui_.noColorRadio->setEnabled(true);
- ui_.customColorRadio->setEnabled(true);
- if (action.getTextColor().empty() && action.getTextBackground().empty()) {
- ui_.noColorRadio->setChecked(true);
- ui_.foregroundColor->setEnabled(false);
- ui_.backgroundColor->setEnabled(false);
- } else {
- ui_.foregroundColor->setEnabled(true);
- ui_.backgroundColor->setEnabled(true);
- QColor foregroundColor(P2QSTRING(action.getTextColor()));
- ui_.foregroundColor->setColor(foregroundColor);
- QColor backgroundColor(P2QSTRING(action.getTextBackground()));
- ui_.backgroundColor->setColor(backgroundColor);
- ui_.customColorRadio->setChecked(true);
- }
-
- ui_.noSoundRadio->setEnabled(true);
- ui_.defaultSoundRadio->setEnabled(true);
- ui_.customSoundRadio->setEnabled(true);
- ui_.soundFile->setText("");
- ui_.soundFile->setEnabled(false);
- ui_.soundFileButton->setEnabled(false);
- if (action.playSound()) {
- if (action.getSoundFile().empty()) {
- ui_.defaultSoundRadio->setChecked(true);
- } else {
- ui_.customSoundRadio->setChecked(true);
- ui_.soundFile->setText(P2QSTRING(action.getSoundFile()));
- ui_.soundFile->setEnabled(true);
- ui_.soundFileButton->setEnabled(true);
- }
- } else {
- ui_.noSoundRadio->setChecked(true);
- }
-
- /* set radio button child option states */
- setChildWidgetStates();
+ ui_.chatRadio->setEnabled(true);
+ ui_.roomRadio->setEnabled(true);
+
+ if (rule.getMatchMUC()) {
+ ui_.chatRadio->setChecked(false);
+ ui_.roomRadio->setChecked(true);
+ } else {
+ ui_.chatRadio->setChecked(true);
+ ui_.roomRadio->setChecked(false);
+ }
+
+ ui_.allMsgRadio->setEnabled(true);
+ ui_.allMsgRadio->setChecked(true); /* this is the default radio button */
+ jid_->setText("");
+ ui_.keyword->setText("");
+ ui_.matchPartialWords->setChecked(false);
+ ui_.matchCase->setChecked(false);
+
+ ui_.nickIsKeyword->setEnabled(true);
+ if (rule.getNickIsKeyword()) {
+ ui_.nickIsKeyword->setChecked(true);
+ }
+
+ ui_.senderRadio->setEnabled(true);
+ std::vector<std::string> senders = rule.getSenders();
+ if (!senders.empty()) {
+ ui_.senderRadio->setChecked(true);
+ jid_->setText(P2QSTRING(senders[0]));
+ }
+
+ ui_.keywordRadio->setEnabled(true);
+ std::vector<std::string> keywords = rule.getKeywords();
+ if (!keywords.empty()) {
+ ui_.keywordRadio->setChecked(true);
+ ui_.keyword->setText(P2QSTRING(keywords[0]));
+ ui_.matchPartialWords->setChecked(!rule.getMatchWholeWords());
+ ui_.matchCase->setChecked(rule.getMatchCase());
+ }
+
+ const HighlightAction& action = rule.getAction();
+
+ ui_.noColorRadio->setEnabled(true);
+ ui_.customColorRadio->setEnabled(true);
+ if (action.getTextColor().empty() && action.getTextBackground().empty()) {
+ ui_.noColorRadio->setChecked(true);
+ ui_.foregroundColor->setEnabled(false);
+ ui_.backgroundColor->setEnabled(false);
+ } else {
+ ui_.foregroundColor->setEnabled(true);
+ ui_.backgroundColor->setEnabled(true);
+ QColor foregroundColor(P2QSTRING(action.getTextColor()));
+ ui_.foregroundColor->setColor(foregroundColor);
+ QColor backgroundColor(P2QSTRING(action.getTextBackground()));
+ ui_.backgroundColor->setColor(backgroundColor);
+ ui_.customColorRadio->setChecked(true);
+ }
+
+ ui_.noSoundRadio->setEnabled(true);
+ ui_.defaultSoundRadio->setEnabled(true);
+ ui_.customSoundRadio->setEnabled(true);
+ ui_.soundFile->setText("");
+ ui_.soundFile->setEnabled(false);
+ ui_.soundFileButton->setEnabled(false);
+ if (action.playSound()) {
+ if (action.getSoundFile().empty()) {
+ ui_.defaultSoundRadio->setChecked(true);
+ } else {
+ ui_.customSoundRadio->setChecked(true);
+ ui_.soundFile->setText(P2QSTRING(action.getSoundFile()));
+ ui_.soundFile->setEnabled(true);
+ ui_.soundFileButton->setEnabled(true);
+ }
+ } else {
+ ui_.noSoundRadio->setChecked(true);
+ }
+
+ /* set radio button child option states */
+ setChildWidgetStates();
}
void QtHighlightEditor::updateResetToDefaultRulesVisibility() {
- ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setVisible(!highlightManager_->isDefaultRulesList());
+ ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setVisible(!highlightManager_->isDefaultRulesList());
}
}
diff --git a/Swift/QtUI/QtHighlightEditor.h b/Swift/QtUI/QtHighlightEditor.h
index e45963c..2a9f06b 100644
--- a/Swift/QtUI/QtHighlightEditor.h
+++ b/Swift/QtUI/QtHighlightEditor.h
@@ -19,56 +19,56 @@
namespace Swift {
- class QtSettingsProvider;
- class QtSuggestingJIDInput;
- class QtWebKitChatView;
+ class QtSettingsProvider;
+ class QtSuggestingJIDInput;
+ class QtWebKitChatView;
- class QtHighlightEditor : public QWidget, public HighlightEditorWindow {
- Q_OBJECT
+ class QtHighlightEditor : public QWidget, public HighlightEditorWindow {
+ Q_OBJECT
- public:
- QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent = NULL);
- virtual ~QtHighlightEditor();
+ public:
+ QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent = NULL);
+ virtual ~QtHighlightEditor();
- virtual void show();
- virtual void setHighlightManager(HighlightManager* highlightManager);
- virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
+ virtual void show();
+ virtual void setHighlightManager(HighlightManager* highlightManager);
+ virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
- private slots:
- void colorOtherSelect();
- void colorCustomSelect();
- void soundOtherSelect();
- void soundCustomSelect();
- void onNewButtonClicked();
- void onDeleteButtonClicked();
- void onUpButtonClicked();
- void onDownButtonClicked();
- void onCurrentRowChanged(int currentRow);
- void onApplyButtonClick();
- void onCancelButtonClick();
- void onOkButtonClick();
- void setChildWidgetStates();
- void widgetClick();
- void disableDialog();
- void handleContactSuggestionRequested(const QString& text);
- void selectSoundFile();
- void onResetToDefaultRulesClicked();
+ private slots:
+ void colorOtherSelect();
+ void colorCustomSelect();
+ void soundOtherSelect();
+ void soundCustomSelect();
+ void onNewButtonClicked();
+ void onDeleteButtonClicked();
+ void onUpButtonClicked();
+ void onDownButtonClicked();
+ void onCurrentRowChanged(int currentRow);
+ void onApplyButtonClick();
+ void onCancelButtonClick();
+ void onOkButtonClick();
+ void setChildWidgetStates();
+ void widgetClick();
+ void disableDialog();
+ void handleContactSuggestionRequested(const QString& text);
+ void selectSoundFile();
+ void onResetToDefaultRulesClicked();
- private:
- void handleOnUserSelected(const Contact::ref& contact);
- void populateList();
- void selectRow(int row);
- int getSelectedRow() const;
- HighlightRule ruleFromDialog();
- void ruleToDialog(const HighlightRule& rule);
- void updateResetToDefaultRulesVisibility();
- void moveRowFromTo(int fromRow, int toRow);
+ private:
+ void handleOnUserSelected(const Contact::ref& contact);
+ void populateList();
+ void selectRow(int row);
+ int getSelectedRow() const;
+ HighlightRule ruleFromDialog();
+ void ruleToDialog(const HighlightRule& rule);
+ void updateResetToDefaultRulesVisibility();
+ void moveRowFromTo(int fromRow, int toRow);
- Ui::QtHighlightEditor ui_;
- QtSettingsProvider* settings_;
- HighlightManager* highlightManager_;
- QtSuggestingJIDInput* jid_;
- int previousRow_;
- };
+ Ui::QtHighlightEditor ui_;
+ QtSettingsProvider* settings_;
+ HighlightManager* highlightManager_;
+ QtSuggestingJIDInput* jid_;
+ int previousRow_;
+ };
}
diff --git a/Swift/QtUI/QtHistoryWindow.cpp b/Swift/QtUI/QtHistoryWindow.cpp
index 0a1f07a..5ed8114 100644
--- a/Swift/QtUI/QtHistoryWindow.cpp
+++ b/Swift/QtUI/QtHistoryWindow.cpp
@@ -42,227 +42,227 @@
namespace Swift {
QtHistoryWindow::QtHistoryWindow(SettingsProvider* settings, UIEventStream* eventStream) :
- previousTopMessageWasSelf_(false),
- previousBottomMessageWasSelf_(false) {
- ui_.setupUi(this);
-
- theme_ = new QtChatTheme("");
- idCounter_ = 0;
-
- delete ui_.conversation_;
- conversation_ = new QtWebKitChatView(NULL, NULL, theme_, this, true); // Horrible unsafe. Do not do this. FIXME
- QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
- sizePolicy.setHorizontalStretch(80);
- sizePolicy.setVerticalStretch(0);
- conversation_->setSizePolicy(sizePolicy);
-
- ui_.conversation_ = conversation_;
- ui_.bottomLayout_->addWidget(conversation_);
-
- delete ui_.conversationRoster_;
- conversationRoster_ = new QtTreeWidget(eventStream, settings, QtTreeWidget::MessageDefaultJID, this);
- QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Expanding);
- sizePolicy2.setVerticalStretch(80);
- conversationRoster_->setSizePolicy(sizePolicy2);
- ui_.conversationRoster_ = conversationRoster_;
- ui_.bottomLeftLayout_->setDirection(QBoxLayout::BottomToTop);
- ui_.bottomLeftLayout_->addWidget(conversationRoster_);
-
- setWindowTitle(tr("History"));
-
- conversationRoster_->onSomethingSelectedChanged.connect(boost::bind(&QtHistoryWindow::handleSomethingSelectedChanged, this, _1));
- connect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
- connect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
- connect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
- connect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
- connect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
- connect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- connect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- connect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
- connect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
+ previousTopMessageWasSelf_(false),
+ previousBottomMessageWasSelf_(false) {
+ ui_.setupUi(this);
+
+ theme_ = new QtChatTheme("");
+ idCounter_ = 0;
+
+ delete ui_.conversation_;
+ conversation_ = new QtWebKitChatView(NULL, NULL, theme_, this, true); // Horrible unsafe. Do not do this. FIXME
+ QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
+ sizePolicy.setHorizontalStretch(80);
+ sizePolicy.setVerticalStretch(0);
+ conversation_->setSizePolicy(sizePolicy);
+
+ ui_.conversation_ = conversation_;
+ ui_.bottomLayout_->addWidget(conversation_);
+
+ delete ui_.conversationRoster_;
+ conversationRoster_ = new QtTreeWidget(eventStream, settings, QtTreeWidget::MessageDefaultJID, this);
+ QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Expanding);
+ sizePolicy2.setVerticalStretch(80);
+ conversationRoster_->setSizePolicy(sizePolicy2);
+ ui_.conversationRoster_ = conversationRoster_;
+ ui_.bottomLeftLayout_->setDirection(QBoxLayout::BottomToTop);
+ ui_.bottomLeftLayout_->addWidget(conversationRoster_);
+
+ setWindowTitle(tr("History"));
+
+ conversationRoster_->onSomethingSelectedChanged.connect(boost::bind(&QtHistoryWindow::handleSomethingSelectedChanged, this, _1));
+ connect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
+ connect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
+ connect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
+ connect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
+ connect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
+ connect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ connect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ connect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
+ connect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
}
QtHistoryWindow::~QtHistoryWindow() {
- disconnect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
- disconnect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
- disconnect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
- disconnect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
- disconnect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
- disconnect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- disconnect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- disconnect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
- disconnect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
-
- delete theme_;
- delete conversation_;
- // TODO: delete ui_
+ disconnect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
+ disconnect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
+ disconnect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
+ disconnect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
+ disconnect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
+ disconnect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ disconnect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ disconnect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
+ disconnect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
+
+ delete theme_;
+ delete conversation_;
+ // TODO: delete ui_
}
void QtHistoryWindow::activate() {
- emit wantsToActivate();
+ emit wantsToActivate();
}
void QtHistoryWindow::showEvent(QShowEvent* event) {
- emit windowOpening();
- emit titleUpdated();
- QWidget::showEvent(event);
+ emit windowOpening();
+ emit titleUpdated();
+ QWidget::showEvent(event);
}
void QtHistoryWindow::closeEvent(QCloseEvent* event) {
- emit windowClosing();
- event->accept();
+ emit windowClosing();
+ event->accept();
}
void QtHistoryWindow::setRosterModel(Roster* model) {
- conversationRoster_->setRosterModel(model);
+ conversationRoster_->setRosterModel(model);
}
void QtHistoryWindow::addMessage(const std::string &message, const std::string &senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop) {
- QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
-
- QString messageHTML(P2QSTRING(message));
- messageHTML = QtUtilities::htmlEscape(messageHTML);
- QString searchTerm = ui_.searchBox_->lineEdit()->text();
- if (searchTerm.length()) {
- messageHTML.replace(searchTerm, "<span style='background-color: yellow'>" + searchTerm + "</span>");
- }
-
- // note: time uses localtime
- QDate date = QDate(time.date().year(), time.date().month(), time.date().day());
- QTime dayTime = QTime(time.time_of_day().hours(), time.time_of_day().minutes(), time.time_of_day().seconds());
- QDateTime qTime = QDateTime(date, dayTime);
-
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
-
- QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
-
- if (addAtTheTop) {
- bool appendToPrevious = ((senderIsSelf && previousTopMessageWasSelf_) || (!senderIsSelf && !previousTopMessageWasSelf_&& previousTopSenderName_ == P2QSTRING(senderName)));
- conversation_->addMessageTop(boost::shared_ptr<ChatSnippet>(new MessageSnippet(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message))));
-
- previousTopMessageWasSelf_ = senderIsSelf;
- previousTopSenderName_ = P2QSTRING(senderName);
- }
- else {
- bool appendToPrevious = ((senderIsSelf && previousBottomMessageWasSelf_) || (!senderIsSelf && !previousBottomMessageWasSelf_&& previousBottomSenderName_ == P2QSTRING(senderName)));
- conversation_->addMessageBottom(boost::make_shared<MessageSnippet>(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message)));
- previousBottomMessageWasSelf_ = senderIsSelf;
- previousBottomSenderName_ = P2QSTRING(senderName);
- }
-
- // keep track of the days viewable in the chatView
- if (!dates_.count(date)) {
- dates_.insert(date);
- }
+ QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
+
+ QString messageHTML(P2QSTRING(message));
+ messageHTML = QtUtilities::htmlEscape(messageHTML);
+ QString searchTerm = ui_.searchBox_->lineEdit()->text();
+ if (searchTerm.length()) {
+ messageHTML.replace(searchTerm, "<span style='background-color: yellow'>" + searchTerm + "</span>");
+ }
+
+ // note: time uses localtime
+ QDate date = QDate(time.date().year(), time.date().month(), time.date().day());
+ QTime dayTime = QTime(time.time_of_day().hours(), time.time_of_day().minutes(), time.time_of_day().seconds());
+ QDateTime qTime = QDateTime(date, dayTime);
+
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+
+ QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
+
+ if (addAtTheTop) {
+ bool appendToPrevious = ((senderIsSelf && previousTopMessageWasSelf_) || (!senderIsSelf && !previousTopMessageWasSelf_&& previousTopSenderName_ == P2QSTRING(senderName)));
+ conversation_->addMessageTop(boost::shared_ptr<ChatSnippet>(new MessageSnippet(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message))));
+
+ previousTopMessageWasSelf_ = senderIsSelf;
+ previousTopSenderName_ = P2QSTRING(senderName);
+ }
+ else {
+ bool appendToPrevious = ((senderIsSelf && previousBottomMessageWasSelf_) || (!senderIsSelf && !previousBottomMessageWasSelf_&& previousBottomSenderName_ == P2QSTRING(senderName)));
+ conversation_->addMessageBottom(boost::make_shared<MessageSnippet>(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message)));
+ previousBottomMessageWasSelf_ = senderIsSelf;
+ previousBottomSenderName_ = P2QSTRING(senderName);
+ }
+
+ // keep track of the days viewable in the chatView
+ if (!dates_.count(date)) {
+ dates_.insert(date);
+ }
}
void QtHistoryWindow::handleSomethingSelectedChanged(RosterItem* item) {
- onSelectedContactChanged(item);
+ onSelectedContactChanged(item);
}
void QtHistoryWindow::resetConversationView() {
- previousTopMessageWasSelf_ = false;
- previousBottomMessageWasSelf_ = false;
- previousTopSenderName_.clear();
- previousBottomSenderName_.clear();
+ previousTopMessageWasSelf_ = false;
+ previousBottomMessageWasSelf_ = false;
+ previousTopSenderName_.clear();
+ previousBottomSenderName_.clear();
- dates_.clear();
- conversation_->resetView();
+ dates_.clear();
+ conversation_->resetView();
}
void QtHistoryWindow::handleScrollRequested(int pos) {
- // first message starts with offset 5
- if (pos < 5) {
- pos = 5;
- }
-
- QDate currentDate;
- foreach (const QDate& date, dates_) {
- int snippetPosition = conversation_->getSnippetPositionByDate(date);
- if (snippetPosition <= pos) {
- currentDate = date;
- }
- }
-
- if (ui_.calendarWidget_->selectedDate() != currentDate) {
- ui_.calendarWidget_->setSelectedDate(currentDate);
- }
+ // first message starts with offset 5
+ if (pos < 5) {
+ pos = 5;
+ }
+
+ QDate currentDate;
+ foreach (const QDate& date, dates_) {
+ int snippetPosition = conversation_->getSnippetPositionByDate(date);
+ if (snippetPosition <= pos) {
+ currentDate = date;
+ }
+ }
+
+ if (ui_.calendarWidget_->selectedDate() != currentDate) {
+ ui_.calendarWidget_->setSelectedDate(currentDate);
+ }
}
void QtHistoryWindow::handleScrollReachedTop() {
- if (dates_.empty()) {
- return;
- }
-
- int year, month, day;
- QDate firstDate = *dates_.begin();
- firstDate.getDate(&year, &month, &day);
- onScrollReachedTop(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
+ if (dates_.empty()) {
+ return;
+ }
+
+ int year, month, day;
+ QDate firstDate = *dates_.begin();
+ firstDate.getDate(&year, &month, &day);
+ onScrollReachedTop(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
}
void QtHistoryWindow::handleScrollReachedBottom() {
- if (dates_.empty()) {
- return;
- }
-
- int year, month, day;
- QDate lastDate = *dates_.rbegin();
- lastDate.getDate(&year, &month, &day);
- onScrollReachedBottom(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
+ if (dates_.empty()) {
+ return;
+ }
+
+ int year, month, day;
+ QDate lastDate = *dates_.rbegin();
+ lastDate.getDate(&year, &month, &day);
+ onScrollReachedBottom(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
}
void QtHistoryWindow::handleReturnPressed() {
- onReturnPressed(ui_.searchBox_->lineEdit()->text().toStdString());
+ onReturnPressed(ui_.searchBox_->lineEdit()->text().toStdString());
}
void QtHistoryWindow::handleCalendarClicked(const QDate& date) {
- int year, month, day;
- QDate tempDate = date; // getDate discards const qualifier
- tempDate.getDate(&year, &month, &day);
- onCalendarClicked(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
+ int year, month, day;
+ QDate tempDate = date; // getDate discards const qualifier
+ tempDate.getDate(&year, &month, &day);
+ onCalendarClicked(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
}
void QtHistoryWindow::setDate(const boost::gregorian::date& date) {
- ui_.calendarWidget_->setSelectedDate(QDate::fromJulianDay(date.julian_day()));
+ ui_.calendarWidget_->setSelectedDate(QDate::fromJulianDay(date.julian_day()));
}
void QtHistoryWindow::handleNextButtonClicked() {
- onNextButtonClicked();
+ onNextButtonClicked();
}
void QtHistoryWindow::handlePreviousButtonClicked() {
- onPreviousButtonClicked();
+ onPreviousButtonClicked();
}
void QtHistoryWindow::handleFontResized(int fontSizeSteps) {
- conversation_->resizeFont(fontSizeSteps);
+ conversation_->resizeFont(fontSizeSteps);
- emit fontResized(fontSizeSteps);
+ emit fontResized(fontSizeSteps);
}
void QtHistoryWindow::resetConversationViewTopInsertPoint() {
- previousTopMessageWasSelf_ = false;
- previousTopSenderName_ = QString();
- conversation_->resetTopInsertPoint();
+ previousTopMessageWasSelf_ = false;
+ previousTopSenderName_ = QString();
+ conversation_->resetTopInsertPoint();
}
std::string QtHistoryWindow::getSearchBoxText() {
- return ui_.searchBox_->lineEdit()->text().toStdString();
+ return ui_.searchBox_->lineEdit()->text().toStdString();
}
boost::gregorian::date QtHistoryWindow::getLastVisibleDate() {
- if (!dates_.empty()) {
- QDate lastDate = *dates_.rbegin();
- int year, month, day;
- lastDate.getDate(&year, &month, &day);
-
- return boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day));
- }
- return boost::gregorian::date(boost::gregorian::not_a_date_time);
+ if (!dates_.empty()) {
+ QDate lastDate = *dates_.rbegin();
+ int year, month, day;
+ lastDate.getDate(&year, &month, &day);
+
+ return boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day));
+ }
+ return boost::gregorian::date(boost::gregorian::not_a_date_time);
}
std::string QtHistoryWindow::getID() const {
- return "QtHistoryWindow";
+ return "QtHistoryWindow";
}
}
diff --git a/Swift/QtUI/QtHistoryWindow.h b/Swift/QtUI/QtHistoryWindow.h
index 2008079..02d7fb8 100644
--- a/Swift/QtUI/QtHistoryWindow.h
+++ b/Swift/QtUI/QtHistoryWindow.h
@@ -22,61 +22,61 @@
#include <Swift/QtUI/ui_QtHistoryWindow.h>
namespace Swift {
- class QtTabbable;
- class QtTreeWidget;
- class QtWebKitChatView;
- class QtChatTheme;
- class SettingsProvider;
- class UIEventStream;
-
- class QtHistoryWindow : public QtTabbable, public HistoryWindow {
- Q_OBJECT
-
- public:
- QtHistoryWindow(SettingsProvider*, UIEventStream*);
- ~QtHistoryWindow();
- void activate();
- void setRosterModel(Roster*);
- void addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop);
- void resetConversationView();
- void resetConversationViewTopInsertPoint();
- void setDate(const boost::gregorian::date& date);
-
- void closeEvent(QCloseEvent* event);
- void showEvent(QShowEvent* event);
-
- std::string getSearchBoxText();
- boost::gregorian::date getLastVisibleDate();
-
- virtual std::string getID() const;
-
- signals:
- void fontResized(int);
-
- public slots:
- void handleFontResized(int fontSizeSteps);
-
- protected slots:
- void handleScrollRequested(int pos);
- void handleScrollReachedTop();
- void handleScrollReachedBottom();
- void handleReturnPressed();
- void handleCalendarClicked(const QDate& date);
- void handlePreviousButtonClicked();
- void handleNextButtonClicked();
-
- private:
- void handleSomethingSelectedChanged(RosterItem* item);
-
- Ui::QtHistoryWindow ui_;
- QtChatTheme* theme_;
- QtWebKitChatView* conversation_;
- QtTreeWidget* conversationRoster_;
- std::set<QDate> dates_;
- int idCounter_;
- bool previousTopMessageWasSelf_;
- QString previousTopSenderName_;
- bool previousBottomMessageWasSelf_;
- QString previousBottomSenderName_;
- };
+ class QtTabbable;
+ class QtTreeWidget;
+ class QtWebKitChatView;
+ class QtChatTheme;
+ class SettingsProvider;
+ class UIEventStream;
+
+ class QtHistoryWindow : public QtTabbable, public HistoryWindow {
+ Q_OBJECT
+
+ public:
+ QtHistoryWindow(SettingsProvider*, UIEventStream*);
+ ~QtHistoryWindow();
+ void activate();
+ void setRosterModel(Roster*);
+ void addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop);
+ void resetConversationView();
+ void resetConversationViewTopInsertPoint();
+ void setDate(const boost::gregorian::date& date);
+
+ void closeEvent(QCloseEvent* event);
+ void showEvent(QShowEvent* event);
+
+ std::string getSearchBoxText();
+ boost::gregorian::date getLastVisibleDate();
+
+ virtual std::string getID() const;
+
+ signals:
+ void fontResized(int);
+
+ public slots:
+ void handleFontResized(int fontSizeSteps);
+
+ protected slots:
+ void handleScrollRequested(int pos);
+ void handleScrollReachedTop();
+ void handleScrollReachedBottom();
+ void handleReturnPressed();
+ void handleCalendarClicked(const QDate& date);
+ void handlePreviousButtonClicked();
+ void handleNextButtonClicked();
+
+ private:
+ void handleSomethingSelectedChanged(RosterItem* item);
+
+ Ui::QtHistoryWindow ui_;
+ QtChatTheme* theme_;
+ QtWebKitChatView* conversation_;
+ QtTreeWidget* conversationRoster_;
+ std::set<QDate> dates_;
+ int idCounter_;
+ bool previousTopMessageWasSelf_;
+ QString previousTopSenderName_;
+ bool previousBottomMessageWasSelf_;
+ QString previousBottomSenderName_;
+ };
}
diff --git a/Swift/QtUI/QtJoinMUCWindow.cpp b/Swift/QtUI/QtJoinMUCWindow.cpp
index 53944da..7225b06 100644
--- a/Swift/QtUI/QtJoinMUCWindow.cpp
+++ b/Swift/QtUI/QtJoinMUCWindow.cpp
@@ -17,59 +17,59 @@ namespace Swift {
QtJoinMUCWindow::QtJoinMUCWindow(UIEventStream* uiEventStream) : uiEventStream(uiEventStream) {
- ui.setupUi(this);
+ ui.setupUi(this);
#if QT_VERSION >= 0x040700
- ui.room->setPlaceholderText(tr("someroom@rooms.example.com"));
+ ui.room->setPlaceholderText(tr("someroom@rooms.example.com"));
#endif
- connect(ui.room, SIGNAL(returnPressed()), this, SLOT(handleJoin()));
- connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
- connect(ui.joinButton, SIGNAL(clicked()), this, SLOT(handleJoin()));
+ connect(ui.room, SIGNAL(returnPressed()), this, SLOT(handleJoin()));
+ connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
+ connect(ui.joinButton, SIGNAL(clicked()), this, SLOT(handleJoin()));
#if QT_VERSION < 0x050200
- // FIXME: Temporarily set focus on the nickName field first, so that the
- // placeholder for the room is visible. This is just because Qt hides
- // the placeholder when a widget is focused for some reason.
- // Tracked upstream as QTBUG-33237 and fixed with Qt 5.2.0.
- ui.nickName->setFocus();
+ // FIXME: Temporarily set focus on the nickName field first, so that the
+ // placeholder for the room is visible. This is just because Qt hides
+ // the placeholder when a widget is focused for some reason.
+ // Tracked upstream as QTBUG-33237 and fixed with Qt 5.2.0.
+ ui.nickName->setFocus();
#endif
- ui.instantRoom->setChecked(true);
- ui.nickName->setValidator(new NickValidator(this));
- ui.room->setValidator(new RoomJIDValidator(this));
+ ui.instantRoom->setChecked(true);
+ ui.nickName->setValidator(new NickValidator(this));
+ ui.room->setValidator(new RoomJIDValidator(this));
}
void QtJoinMUCWindow::handleJoin() {
- if (ui.room->text().isEmpty() || !ui.room->hasAcceptableInput()) {
- QToolTip::showText(ui.room->mapToGlobal(QPoint()), tr("Please enter a valid room address."), ui.room);
- return;
- }
- if (ui.nickName->text().isEmpty() || !ui.nickName->hasAcceptableInput()) {
- QToolTip::showText(ui.nickName->mapToGlobal(QPoint()), tr("Please enter a valid nickname."), ui.nickName);
- return;
- }
+ if (ui.room->text().isEmpty() || !ui.room->hasAcceptableInput()) {
+ QToolTip::showText(ui.room->mapToGlobal(QPoint()), tr("Please enter a valid room address."), ui.room);
+ return;
+ }
+ if (ui.nickName->text().isEmpty() || !ui.nickName->hasAcceptableInput()) {
+ QToolTip::showText(ui.nickName->mapToGlobal(QPoint()), tr("Please enter a valid nickname."), ui.nickName);
+ return;
+ }
- lastSetNick = Q2PSTRING(ui.nickName->text());
- std::string password = Q2PSTRING(ui.password->text());
- JID room(Q2PSTRING(ui.room->text()));
- uiEventStream->send(boost::make_shared<JoinMUCUIEvent>(room, password, lastSetNick, ui.joinAutomatically->isChecked(), !ui.instantRoom->isChecked()));
- hide();
+ lastSetNick = Q2PSTRING(ui.nickName->text());
+ std::string password = Q2PSTRING(ui.password->text());
+ JID room(Q2PSTRING(ui.room->text()));
+ uiEventStream->send(boost::make_shared<JoinMUCUIEvent>(room, password, lastSetNick, ui.joinAutomatically->isChecked(), !ui.instantRoom->isChecked()));
+ hide();
}
void QtJoinMUCWindow::handleSearch() {
- onSearchMUC();
+ onSearchMUC();
}
void QtJoinMUCWindow::setNick(const std::string& nick) {
- ui.nickName->setText(P2QSTRING(nick));
- lastSetNick = nick;
+ ui.nickName->setText(P2QSTRING(nick));
+ lastSetNick = nick;
}
void QtJoinMUCWindow::setMUC(const std::string& nick) {
- ui.room->setText(P2QSTRING(nick));
+ ui.room->setText(P2QSTRING(nick));
}
void QtJoinMUCWindow::show() {
- QWidget::show();
- QWidget::activateWindow();
- ui.password->setText("");
+ QWidget::show();
+ QWidget::activateWindow();
+ ui.password->setText("");
}
}
diff --git a/Swift/QtUI/QtJoinMUCWindow.h b/Swift/QtUI/QtJoinMUCWindow.h
index 618f2e9..c2e8068 100644
--- a/Swift/QtUI/QtJoinMUCWindow.h
+++ b/Swift/QtUI/QtJoinMUCWindow.h
@@ -16,60 +16,60 @@
#include <Swift/QtUI/ui_QtJoinMUCWindow.h>
namespace Swift {
- class UIEventStream;
- class NickValidator : public QValidator {
- Q_OBJECT
- public:
- NickValidator(QObject* parent) : QValidator(parent) {
- }
-
- virtual QValidator::State validate(QString& input, int& /*pos*/) const {
- if (input.isEmpty()) {
- return QValidator::Intermediate;
- }
- JID test("alice", "wonderland.lit", Q2PSTRING(input));
-
- return test.isValid() ? QValidator::Acceptable : QValidator::Invalid;
- }
- };
-
- class RoomJIDValidator : public QValidator {
- Q_OBJECT
- public:
- RoomJIDValidator(QObject* parent) : QValidator(parent) {
- }
-
- virtual QValidator::State validate(QString& input, int& /*pos*/) const {
- if (input.isEmpty()) {
- return QValidator::Intermediate;
- }
- JID roomJID(Q2PSTRING(input));
-
- if (roomJID.getNode().empty() || roomJID.getDomain().empty()) {
- return QValidator::Intermediate;
- }
-
- return (roomJID.getResource().empty() && !roomJID.getNode().empty() && !roomJID.getDomain().empty() && roomJID.isValid()) ? QValidator::Acceptable : QValidator::Invalid;
- }
- };
-
- class QtJoinMUCWindow : public QWidget, public JoinMUCWindow {
- Q_OBJECT
- public:
- QtJoinMUCWindow(UIEventStream* uiEventStream);
-
- virtual void setNick(const std::string& nick);
- virtual void setMUC(const std::string& nick);
-
- virtual void show();
-
- private slots:
- void handleJoin();
- void handleSearch();
-
- private:
- Ui::QtJoinMUCWindow ui;
- std::string lastSetNick;
- UIEventStream* uiEventStream;
- };
+ class UIEventStream;
+ class NickValidator : public QValidator {
+ Q_OBJECT
+ public:
+ NickValidator(QObject* parent) : QValidator(parent) {
+ }
+
+ virtual QValidator::State validate(QString& input, int& /*pos*/) const {
+ if (input.isEmpty()) {
+ return QValidator::Intermediate;
+ }
+ JID test("alice", "wonderland.lit", Q2PSTRING(input));
+
+ return test.isValid() ? QValidator::Acceptable : QValidator::Invalid;
+ }
+ };
+
+ class RoomJIDValidator : public QValidator {
+ Q_OBJECT
+ public:
+ RoomJIDValidator(QObject* parent) : QValidator(parent) {
+ }
+
+ virtual QValidator::State validate(QString& input, int& /*pos*/) const {
+ if (input.isEmpty()) {
+ return QValidator::Intermediate;
+ }
+ JID roomJID(Q2PSTRING(input));
+
+ if (roomJID.getNode().empty() || roomJID.getDomain().empty()) {
+ return QValidator::Intermediate;
+ }
+
+ return (roomJID.getResource().empty() && !roomJID.getNode().empty() && !roomJID.getDomain().empty() && roomJID.isValid()) ? QValidator::Acceptable : QValidator::Invalid;
+ }
+ };
+
+ class QtJoinMUCWindow : public QWidget, public JoinMUCWindow {
+ Q_OBJECT
+ public:
+ QtJoinMUCWindow(UIEventStream* uiEventStream);
+
+ virtual void setNick(const std::string& nick);
+ virtual void setMUC(const std::string& nick);
+
+ virtual void show();
+
+ private slots:
+ void handleJoin();
+ void handleSearch();
+
+ private:
+ Ui::QtJoinMUCWindow ui;
+ std::string lastSetNick;
+ UIEventStream* uiEventStream;
+ };
}
diff --git a/Swift/QtUI/QtLineEdit.cpp b/Swift/QtUI/QtLineEdit.cpp
index a98663c..d3ec4c4 100644
--- a/Swift/QtUI/QtLineEdit.cpp
+++ b/Swift/QtUI/QtLineEdit.cpp
@@ -14,10 +14,10 @@ QtLineEdit::QtLineEdit(QWidget* parent) : QLineEdit(parent) {
}
void QtLineEdit::keyPressEvent(QKeyEvent* event) {
- if (event->key() == Qt::Key_Escape) {
- emit escapePressed();
- }
- QLineEdit::keyPressEvent(event);
+ if (event->key() == Qt::Key_Escape) {
+ emit escapePressed();
+ }
+ QLineEdit::keyPressEvent(event);
}
}
diff --git a/Swift/QtUI/QtLineEdit.h b/Swift/QtUI/QtLineEdit.h
index 1c7240a..557f025 100644
--- a/Swift/QtUI/QtLineEdit.h
+++ b/Swift/QtUI/QtLineEdit.h
@@ -9,13 +9,13 @@
#include <QLineEdit>
namespace Swift {
- class QtLineEdit : public QLineEdit {
- Q_OBJECT
- public:
- QtLineEdit(QWidget* parent = NULL);
- signals:
- void escapePressed();
- protected:
- virtual void keyPressEvent(QKeyEvent* event);
- };
+ class QtLineEdit : public QLineEdit {
+ Q_OBJECT
+ public:
+ QtLineEdit(QWidget* parent = NULL);
+ signals:
+ void escapePressed();
+ protected:
+ virtual void keyPressEvent(QKeyEvent* event);
+ };
}
diff --git a/Swift/QtUI/QtLoginWindow.cpp b/Swift/QtUI/QtLoginWindow.cpp
index 229df7f..5f15f4c 100644
--- a/Swift/QtUI/QtLoginWindow.cpp
+++ b/Swift/QtUI/QtLoginWindow.cpp
@@ -54,524 +54,524 @@
namespace Swift{
QtLoginWindow::QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory) : QMainWindow(), settings_(settings), timerFactory_(timerFactory) {
- uiEventStream_ = uiEventStream;
+ uiEventStream_ = uiEventStream;
- setWindowTitle("Swift");
+ setWindowTitle("Swift");
#ifndef Q_OS_MAC
#ifdef Q_OS_WIN32
- setWindowIcon(QIcon(":/logo-icon-16-win.png"));
+ setWindowIcon(QIcon(":/logo-icon-16-win.png"));
#else
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
#endif
- QtUtilities::setX11Resource(this, "Main");
- setAccessibleName(tr("Swift Login Window"));
- //setAccessibleDescription(tr("This window is used for providing credentials to log into your XMPP service"));
-
- resize(200, 500);
- setContentsMargins(0,0,0,0);
- QWidget *centralWidget = new QWidget(this);
- setCentralWidget(centralWidget);
- QBoxLayout *topLayout = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget);
- stack_ = new QStackedWidget(centralWidget);
- topLayout->addWidget(stack_);
- topLayout->setMargin(0);
- loginWidgetWrapper_ = new QWidget(this);
- loginWidgetWrapper_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
- QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, loginWidgetWrapper_);
- layout->addStretch(2);
-
- QLabel* logo = new QLabel(this);
- logo->setPixmap(QPixmap(":/logo-shaded-text.256.png"));
- logo->setScaledContents(true);
- logo->setFixedSize(192,192);
-
- QWidget *logoWidget = new QWidget(this);
- QHBoxLayout *logoLayout = new QHBoxLayout();
- logoLayout->setMargin(0);
- logoLayout->addStretch(0);
- logoLayout->addWidget(logo);
- logoLayout->addStretch(0);
- logoWidget->setLayout(logoLayout);
- layout->addWidget(logoWidget);
-
- layout->addStretch(2);
-
- QLabel* jidLabel = new QLabel(this);
- jidLabel->setText("<font size='-1'>" + tr("User address:") + "</font>");
- layout->addWidget(jidLabel);
-
-
- username_ = new QComboBox(this);
- username_->setEditable(true);
- username_->setWhatsThis(tr("User address - looks like someuser@someserver.com"));
- username_->setToolTip(tr("User address - looks like someuser@someserver.com"));
- username_->view()->installEventFilter(this);
- username_->setAccessibleName(tr("User address (of the form someuser@someserver.com)"));
- username_->setAccessibleDescription(tr("This is the user address that you'll be using to log in with"));
- layout->addWidget(username_);
- QLabel* jidHintLabel = new QLabel(this);
- jidHintLabel->setText("<font size='-1' color='grey' >" + tr("Example: alice@wonderland.lit") + "</font>");
- jidHintLabel->setAlignment(Qt::AlignRight);
- layout->addWidget(jidHintLabel);
-
-
- QLabel* passwordLabel = new QLabel();
- passwordLabel->setText("<font size='-1'>" + tr("Password:") + "</font>");
- passwordLabel->setAccessibleName(tr("User password"));
- passwordLabel->setAccessibleDescription(tr("This is the password you'll use to log in to the XMPP service"));
- layout->addWidget(passwordLabel);
-
-
- QWidget* w = new QWidget(this);
- w->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
- layout->addWidget(w);
-
- QHBoxLayout* credentialsLayout = new QHBoxLayout(w);
- credentialsLayout->setMargin(0);
- credentialsLayout->setSpacing(3);
- password_ = new QLineEdit(this);
- password_->setEchoMode(QLineEdit::Password);
- connect(password_, SIGNAL(returnPressed()), this, SLOT(loginClicked()));
- connect(username_->lineEdit(), SIGNAL(returnPressed()), password_, SLOT(setFocus()));
- connect(username_, SIGNAL(editTextChanged(const QString&)), this, SLOT(handleUsernameTextChanged()));
- credentialsLayout->addWidget(password_);
-
- certificateButton_ = new QToolButton(this);
- certificateButton_->setCheckable(true);
- certificateButton_->setIcon(QIcon(":/icons/certificate.png"));
- certificateButton_->setToolTip(tr("Click if you have a personal certificate used for login to the service."));
- certificateButton_->setWhatsThis(tr("Click if you have a personal certificate used for login to the service."));
- certificateButton_->setAccessibleName(tr("Login with certificate"));
- certificateButton_->setAccessibleDescription(tr("Click if you have a personal certificate used for login to the service."));
-
- credentialsLayout->addWidget(certificateButton_);
- connect(certificateButton_, SIGNAL(clicked(bool)), SLOT(handleCertficateChecked(bool)));
-
- loginButton_ = new QPushButton(this);
- loginButton_->setText(tr("Connect"));
- loginButton_->setAutoDefault(true);
- loginButton_->setDefault(true);
- loginButton_->setAccessibleName(tr("Connect now"));
- layout->addWidget(loginButton_);
-
- QLabel* connectionOptionsLabel = new QLabel(this);
- connectionOptionsLabel->setText("<a href=\"#\"><font size='-1'>" + QObject::tr("Connection Options") + "</font></a>");
- connectionOptionsLabel->setTextFormat(Qt::RichText);
- connectionOptionsLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
- layout->addWidget(connectionOptionsLabel);
- connect(connectionOptionsLabel, SIGNAL(linkActivated(const QString&)), SLOT(handleOpenConnectionOptions()));
-
- message_ = new QLabel(this);
- message_->setTextFormat(Qt::RichText);
- message_->setWordWrap(true);
- layout->addWidget(message_);
-
- layout->addStretch(2);
- remember_ = new QCheckBox(tr("Remember Password?"), this);
- layout->addWidget(remember_);
- loginAutomatically_ = new QCheckBox(tr("Login Automatically?"), this);
- layout->addWidget(loginAutomatically_);
-
- connect(loginButton_, SIGNAL(clicked()), SLOT(loginClicked()));
- stack_->addWidget(loginWidgetWrapper_);
+ QtUtilities::setX11Resource(this, "Main");
+ setAccessibleName(tr("Swift Login Window"));
+ //setAccessibleDescription(tr("This window is used for providing credentials to log into your XMPP service"));
+
+ resize(200, 500);
+ setContentsMargins(0,0,0,0);
+ QWidget *centralWidget = new QWidget(this);
+ setCentralWidget(centralWidget);
+ QBoxLayout *topLayout = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget);
+ stack_ = new QStackedWidget(centralWidget);
+ topLayout->addWidget(stack_);
+ topLayout->setMargin(0);
+ loginWidgetWrapper_ = new QWidget(this);
+ loginWidgetWrapper_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+ QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, loginWidgetWrapper_);
+ layout->addStretch(2);
+
+ QLabel* logo = new QLabel(this);
+ logo->setPixmap(QPixmap(":/logo-shaded-text.256.png"));
+ logo->setScaledContents(true);
+ logo->setFixedSize(192,192);
+
+ QWidget *logoWidget = new QWidget(this);
+ QHBoxLayout *logoLayout = new QHBoxLayout();
+ logoLayout->setMargin(0);
+ logoLayout->addStretch(0);
+ logoLayout->addWidget(logo);
+ logoLayout->addStretch(0);
+ logoWidget->setLayout(logoLayout);
+ layout->addWidget(logoWidget);
+
+ layout->addStretch(2);
+
+ QLabel* jidLabel = new QLabel(this);
+ jidLabel->setText("<font size='-1'>" + tr("User address:") + "</font>");
+ layout->addWidget(jidLabel);
+
+
+ username_ = new QComboBox(this);
+ username_->setEditable(true);
+ username_->setWhatsThis(tr("User address - looks like someuser@someserver.com"));
+ username_->setToolTip(tr("User address - looks like someuser@someserver.com"));
+ username_->view()->installEventFilter(this);
+ username_->setAccessibleName(tr("User address (of the form someuser@someserver.com)"));
+ username_->setAccessibleDescription(tr("This is the user address that you'll be using to log in with"));
+ layout->addWidget(username_);
+ QLabel* jidHintLabel = new QLabel(this);
+ jidHintLabel->setText("<font size='-1' color='grey' >" + tr("Example: alice@wonderland.lit") + "</font>");
+ jidHintLabel->setAlignment(Qt::AlignRight);
+ layout->addWidget(jidHintLabel);
+
+
+ QLabel* passwordLabel = new QLabel();
+ passwordLabel->setText("<font size='-1'>" + tr("Password:") + "</font>");
+ passwordLabel->setAccessibleName(tr("User password"));
+ passwordLabel->setAccessibleDescription(tr("This is the password you'll use to log in to the XMPP service"));
+ layout->addWidget(passwordLabel);
+
+
+ QWidget* w = new QWidget(this);
+ w->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+ layout->addWidget(w);
+
+ QHBoxLayout* credentialsLayout = new QHBoxLayout(w);
+ credentialsLayout->setMargin(0);
+ credentialsLayout->setSpacing(3);
+ password_ = new QLineEdit(this);
+ password_->setEchoMode(QLineEdit::Password);
+ connect(password_, SIGNAL(returnPressed()), this, SLOT(loginClicked()));
+ connect(username_->lineEdit(), SIGNAL(returnPressed()), password_, SLOT(setFocus()));
+ connect(username_, SIGNAL(editTextChanged(const QString&)), this, SLOT(handleUsernameTextChanged()));
+ credentialsLayout->addWidget(password_);
+
+ certificateButton_ = new QToolButton(this);
+ certificateButton_->setCheckable(true);
+ certificateButton_->setIcon(QIcon(":/icons/certificate.png"));
+ certificateButton_->setToolTip(tr("Click if you have a personal certificate used for login to the service."));
+ certificateButton_->setWhatsThis(tr("Click if you have a personal certificate used for login to the service."));
+ certificateButton_->setAccessibleName(tr("Login with certificate"));
+ certificateButton_->setAccessibleDescription(tr("Click if you have a personal certificate used for login to the service."));
+
+ credentialsLayout->addWidget(certificateButton_);
+ connect(certificateButton_, SIGNAL(clicked(bool)), SLOT(handleCertficateChecked(bool)));
+
+ loginButton_ = new QPushButton(this);
+ loginButton_->setText(tr("Connect"));
+ loginButton_->setAutoDefault(true);
+ loginButton_->setDefault(true);
+ loginButton_->setAccessibleName(tr("Connect now"));
+ layout->addWidget(loginButton_);
+
+ QLabel* connectionOptionsLabel = new QLabel(this);
+ connectionOptionsLabel->setText("<a href=\"#\"><font size='-1'>" + QObject::tr("Connection Options") + "</font></a>");
+ connectionOptionsLabel->setTextFormat(Qt::RichText);
+ connectionOptionsLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
+ layout->addWidget(connectionOptionsLabel);
+ connect(connectionOptionsLabel, SIGNAL(linkActivated(const QString&)), SLOT(handleOpenConnectionOptions()));
+
+ message_ = new QLabel(this);
+ message_->setTextFormat(Qt::RichText);
+ message_->setWordWrap(true);
+ layout->addWidget(message_);
+
+ layout->addStretch(2);
+ remember_ = new QCheckBox(tr("Remember Password?"), this);
+ layout->addWidget(remember_);
+ loginAutomatically_ = new QCheckBox(tr("Login Automatically?"), this);
+ layout->addWidget(loginAutomatically_);
+
+ connect(loginButton_, SIGNAL(clicked()), SLOT(loginClicked()));
+ stack_->addWidget(loginWidgetWrapper_);
#ifdef SWIFTEN_PLATFORM_MACOSX
- menuBar_ = new QMenuBar(NULL);
+ menuBar_ = new QMenuBar(NULL);
#else
- menuBar_ = menuBar();
+ menuBar_ = menuBar();
#endif
- QApplication::setQuitOnLastWindowClosed(false);
+ QApplication::setQuitOnLastWindowClosed(false);
- swiftMenu_ = new QMenu(tr("&Swift"), this);
+ swiftMenu_ = new QMenu(tr("&Swift"), this);
#ifdef SWIFTEN_PLATFORM_MACOSX
- generalMenu_ = new QMenu(tr("&General"), this);
+ generalMenu_ = new QMenu(tr("&General"), this);
#else
- generalMenu_ = swiftMenu_;
+ generalMenu_ = swiftMenu_;
#endif
#ifdef SWIFTEN_PLATFORM_MACOSX
- QAction* aboutAction = new QAction(QString("&About %1").arg("Swift"), this);
+ QAction* aboutAction = new QAction(QString("&About %1").arg("Swift"), this);
#else
- QAction* aboutAction = new QAction(QString(tr("&About %1")).arg("Swift"), this);
+ QAction* aboutAction = new QAction(QString(tr("&About %1")).arg("Swift"), this);
#endif
- connect(aboutAction, SIGNAL(triggered()), SLOT(handleAbout()));
- swiftMenu_->addAction(aboutAction);
+ connect(aboutAction, SIGNAL(triggered()), SLOT(handleAbout()));
+ swiftMenu_->addAction(aboutAction);
- xmlConsoleAction_ = new QAction(tr("&Show Debug Console"), this);
- connect(xmlConsoleAction_, SIGNAL(triggered()), SLOT(handleShowXMLConsole()));
- generalMenu_->addAction(xmlConsoleAction_);
+ xmlConsoleAction_ = new QAction(tr("&Show Debug Console"), this);
+ connect(xmlConsoleAction_, SIGNAL(triggered()), SLOT(handleShowXMLConsole()));
+ generalMenu_->addAction(xmlConsoleAction_);
#ifdef SWIFT_EXPERIMENTAL_FT
- fileTransferOverviewAction_ = new QAction(tr("Show &File Transfer Overview"), this);
- connect(fileTransferOverviewAction_, SIGNAL(triggered()), SLOT(handleShowFileTransferOverview()));
- generalMenu_->addAction(fileTransferOverviewAction_);
+ fileTransferOverviewAction_ = new QAction(tr("Show &File Transfer Overview"), this);
+ connect(fileTransferOverviewAction_, SIGNAL(triggered()), SLOT(handleShowFileTransferOverview()));
+ generalMenu_->addAction(fileTransferOverviewAction_);
#endif
- highlightEditorAction_ = new QAction(tr("&Edit Highlight Rules"), this);
- connect(highlightEditorAction_, SIGNAL(triggered()), SLOT(handleShowHighlightEditor()));
- generalMenu_->addAction(highlightEditorAction_);
+ highlightEditorAction_ = new QAction(tr("&Edit Highlight Rules"), this);
+ connect(highlightEditorAction_, SIGNAL(triggered()), SLOT(handleShowHighlightEditor()));
+ generalMenu_->addAction(highlightEditorAction_);
- toggleSoundsAction_ = new QAction(tr("&Play Sounds"), this);
- toggleSoundsAction_->setCheckable(true);
- toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
- connect(toggleSoundsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleSounds(bool)));
- generalMenu_->addAction(toggleSoundsAction_);
+ toggleSoundsAction_ = new QAction(tr("&Play Sounds"), this);
+ toggleSoundsAction_->setCheckable(true);
+ toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
+ connect(toggleSoundsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleSounds(bool)));
+ generalMenu_->addAction(toggleSoundsAction_);
- toggleNotificationsAction_ = new QAction(tr("Display Pop-up &Notifications"), this);
- toggleNotificationsAction_->setCheckable(true);
- toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
- connect(toggleNotificationsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleNotifications(bool)));
+ toggleNotificationsAction_ = new QAction(tr("Display Pop-up &Notifications"), this);
+ toggleNotificationsAction_->setCheckable(true);
+ toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
+ connect(toggleNotificationsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleNotifications(bool)));
#ifndef SWIFTEN_PLATFORM_MACOSX
- swiftMenu_->addSeparator();
+ swiftMenu_->addSeparator();
#endif
#ifdef SWIFTEN_PLATFORM_MACOSX
- QAction* quitAction = new QAction("&Quit", this);
+ QAction* quitAction = new QAction("&Quit", this);
#else
- QAction* quitAction = new QAction(tr("&Quit"), this);
+ QAction* quitAction = new QAction(tr("&Quit"), this);
#endif
- connect(quitAction, SIGNAL(triggered()), SLOT(handleQuit()));
- swiftMenu_->addAction(quitAction);
+ connect(quitAction, SIGNAL(triggered()), SLOT(handleQuit()));
+ swiftMenu_->addAction(quitAction);
- setInitialMenus();
- settings_->onSettingChanged.connect(boost::bind(&QtLoginWindow::handleSettingChanged, this, _1));
+ setInitialMenus();
+ settings_->onSettingChanged.connect(boost::bind(&QtLoginWindow::handleSettingChanged, this, _1));
- bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
- remember_->setEnabled(!eagle);
- loginAutomatically_->setEnabled(!eagle);
- xmlConsoleAction_->setEnabled(!eagle);
- if (eagle) {
- remember_->setChecked(false);
- loginAutomatically_->setChecked(false);
- }
+ bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
+ remember_->setEnabled(!eagle);
+ loginAutomatically_->setEnabled(!eagle);
+ xmlConsoleAction_->setEnabled(!eagle);
+ if (eagle) {
+ remember_->setChecked(false);
+ loginAutomatically_->setChecked(false);
+ }
#ifdef SWIFTEN_PLATFORM_MACOSX
- // Temporary workaround for case 501. Could be that this code is still
- // needed when Qt provides a proper fix
- qApp->installEventFilter(this);
+ // Temporary workaround for case 501. Could be that this code is still
+ // needed when Qt provides a proper fix
+ qApp->installEventFilter(this);
#endif
- this->show();
+ this->show();
}
void QtLoginWindow::setShowNotificationToggle(bool toggle) {
- if (toggle) {
- QList< QAction* > generalMenuActions = generalMenu_->actions();
- generalMenu_->insertAction(generalMenuActions.at(generalMenuActions.count()-2), toggleNotificationsAction_);
- }
- else {
- generalMenu_->removeAction(toggleNotificationsAction_);
- }
+ if (toggle) {
+ QList< QAction* > generalMenuActions = generalMenu_->actions();
+ generalMenu_->insertAction(generalMenuActions.at(generalMenuActions.count()-2), toggleNotificationsAction_);
+ }
+ else {
+ generalMenu_->removeAction(toggleNotificationsAction_);
+ }
}
bool QtLoginWindow::eventFilter(QObject *obj, QEvent *event) {
- if (obj == username_->view() && event->type() == QEvent::KeyPress) {
- QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
- if (keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace) {
- QString jid(username_->view()->currentIndex().data().toString());
- int result = QMessageBox::question(this, tr("Remove profile"), tr("Remove the profile '%1'?").arg(jid), QMessageBox::Yes | QMessageBox::No);
- if (result == QMessageBox::Yes) {
- onPurgeSavedLoginRequest(Q2PSTRING(jid));
- }
- return true;
- }
- }
+ if (obj == username_->view() && event->type() == QEvent::KeyPress) {
+ QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
+ if (keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace) {
+ QString jid(username_->view()->currentIndex().data().toString());
+ int result = QMessageBox::question(this, tr("Remove profile"), tr("Remove the profile '%1'?").arg(jid), QMessageBox::Yes | QMessageBox::No);
+ if (result == QMessageBox::Yes) {
+ onPurgeSavedLoginRequest(Q2PSTRING(jid));
+ }
+ return true;
+ }
+ }
#ifdef SWIFTEN_PLATFORM_MACOSX
- // Dock clicked
- // Temporary workaround for case 501. Could be that this code is still
- // needed when Qt provides a proper fix
- if (obj == qApp && event->type() == QEvent::ApplicationActivate && !isVisible()) {
- bringToFront();
- }
+ // Dock clicked
+ // Temporary workaround for case 501. Could be that this code is still
+ // needed when Qt provides a proper fix
+ if (obj == qApp && event->type() == QEvent::ApplicationActivate && !isVisible()) {
+ bringToFront();
+ }
#endif
- return QObject::eventFilter(obj, event);
+ return QObject::eventFilter(obj, event);
}
void QtLoginWindow::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::PLAY_SOUNDS.getKey()) {
- toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
- }
- if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) {
- toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
- }
+ if (settingPath == SettingConstants::PLAY_SOUNDS.getKey()) {
+ toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
+ }
+ if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) {
+ toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
+ }
}
void QtLoginWindow::selectUser(const std::string& username) {
- for (int i = 0; i < usernames_.count(); i++) {
- if (P2QSTRING(username) == usernames_[i]) {
- username_->setCurrentIndex(i);
- password_->setFocus();
- break;
- }
- }
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (P2QSTRING(username) == usernames_[i]) {
+ username_->setCurrentIndex(i);
+ password_->setFocus();
+ break;
+ }
+ }
}
void QtLoginWindow::removeAvailableAccount(const std::string& jid) {
- QString username = P2QSTRING(jid);
- int index = -1;
- for (int i = 0; i < usernames_.count(); i++) {
- if (username == usernames_[i]) {
- index = i;
- }
- }
- if (index >= 0) {
- usernames_.removeAt(index);
- passwords_.removeAt(index);
- certificateFiles_.removeAt(index);
- username_->removeItem(index);
- }
+ QString username = P2QSTRING(jid);
+ int index = -1;
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (username == usernames_[i]) {
+ index = i;
+ }
+ }
+ if (index >= 0) {
+ usernames_.removeAt(index);
+ passwords_.removeAt(index);
+ certificateFiles_.removeAt(index);
+ username_->removeItem(index);
+ }
}
void QtLoginWindow::addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options) {
- QString username = P2QSTRING(defaultJID);
- int index = -1;
- for (int i = 0; i < usernames_.count(); i++) {
- if (username == usernames_[i]) {
- index = i;
- }
- }
- if (index == -1) {
- usernames_.append(username);
- passwords_.append(P2QSTRING(defaultPassword));
- certificateFiles_.append(P2QSTRING(defaultCertificate));
- options_.push_back(options);
- username_->addItem(username);
- } else {
- usernames_[index] = username;
- passwords_[index] = P2QSTRING(defaultPassword);
- certificateFiles_[index] = P2QSTRING(defaultCertificate);
- options_[index] = options;
- }
+ QString username = P2QSTRING(defaultJID);
+ int index = -1;
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (username == usernames_[i]) {
+ index = i;
+ }
+ }
+ if (index == -1) {
+ usernames_.append(username);
+ passwords_.append(P2QSTRING(defaultPassword));
+ certificateFiles_.append(P2QSTRING(defaultCertificate));
+ options_.push_back(options);
+ username_->addItem(username);
+ } else {
+ usernames_[index] = username;
+ passwords_[index] = P2QSTRING(defaultPassword);
+ certificateFiles_[index] = P2QSTRING(defaultCertificate);
+ options_[index] = options;
+ }
}
void QtLoginWindow::handleUsernameTextChanged() {
- QString username = username_->currentText();
- for (int i = 0; i < usernames_.count(); i++) {
- if (username_->currentText() == usernames_[i]) {
- certificateFile_ = certificateFiles_[i];
- password_->setText(passwords_[i]);
- remember_->setChecked(password_->text() != "");
- currentOptions_ = options_[i];
- }
- }
- certificateButton_->setChecked(!certificateFile_.isEmpty());
+ QString username = username_->currentText();
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (username_->currentText() == usernames_[i]) {
+ certificateFile_ = certificateFiles_[i];
+ password_->setText(passwords_[i]);
+ remember_->setChecked(password_->text() != "");
+ currentOptions_ = options_[i];
+ }
+ }
+ certificateButton_->setChecked(!certificateFile_.isEmpty());
}
void QtLoginWindow::loggedOut() {
- stack_->removeWidget(stack_->currentWidget());
- stack_->addWidget(loginWidgetWrapper_);
- stack_->setCurrentWidget(loginWidgetWrapper_);
- setInitialMenus();
- setIsLoggingIn(false);
+ stack_->removeWidget(stack_->currentWidget());
+ stack_->addWidget(loginWidgetWrapper_);
+ stack_->setCurrentWidget(loginWidgetWrapper_);
+ setInitialMenus();
+ setIsLoggingIn(false);
}
void QtLoginWindow::setIsLoggingIn(bool loggingIn) {
- /* Change the for loop as well if you add to this.*/
- QWidget* widgets[5] = {username_, password_, remember_, loginAutomatically_, certificateButton_};
- loginButton_->setText(loggingIn ? tr("Cancel") : tr("Connect"));
- for (int i = 0; i < 5; i++) {
- widgets[i]->setEnabled(!loggingIn);
- }
- bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
- remember_->setEnabled(!eagle);
- loginAutomatically_->setEnabled(!eagle);
+ /* Change the for loop as well if you add to this.*/
+ QWidget* widgets[5] = {username_, password_, remember_, loginAutomatically_, certificateButton_};
+ loginButton_->setText(loggingIn ? tr("Cancel") : tr("Connect"));
+ for (int i = 0; i < 5; i++) {
+ widgets[i]->setEnabled(!loggingIn);
+ }
+ bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
+ remember_->setEnabled(!eagle);
+ loginAutomatically_->setEnabled(!eagle);
}
void QtLoginWindow::loginClicked() {
- if (username_->isEnabled()) {
- std::string banner = settings_->getSetting(QtUISettingConstants::CLICKTHROUGH_BANNER);
- if (!banner.empty()) {
- QMessageBox msgBox;
- msgBox.setWindowTitle(tr("Confirm terms of use"));
- msgBox.setText("");
- msgBox.setInformativeText(P2QSTRING(banner));
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::No);
- if (msgBox.exec() != QMessageBox::Yes) {
- return;
- }
- }
- CertificateWithKey::ref certificate;
- std::string certificateString = Q2PSTRING(certificateFile_);
- if (!certificateString.empty()) {
+ if (username_->isEnabled()) {
+ std::string banner = settings_->getSetting(QtUISettingConstants::CLICKTHROUGH_BANNER);
+ if (!banner.empty()) {
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(tr("Confirm terms of use"));
+ msgBox.setText("");
+ msgBox.setInformativeText(P2QSTRING(banner));
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::No);
+ if (msgBox.exec() != QMessageBox::Yes) {
+ return;
+ }
+ }
+ CertificateWithKey::ref certificate;
+ std::string certificateString = Q2PSTRING(certificateFile_);
+ if (!certificateString.empty()) {
#if defined(HAVE_SCHANNEL)
- if (isCAPIURI(certificateString)) {
- certificate = boost::make_shared<CAPICertificate>(certificateString, timerFactory_);
- } else {
- certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
- }
+ if (isCAPIURI(certificateString)) {
+ certificate = boost::make_shared<CAPICertificate>(certificateString, timerFactory_);
+ } else {
+ certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
+ }
#else
- certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
+ certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
#endif
- }
+ }
- onLoginRequest(Q2PSTRING(username_->currentText()), Q2PSTRING(password_->text()), certificateString, certificate, currentOptions_, remember_->isChecked(), loginAutomatically_->isChecked());
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { /* Mustn't remember logins */
- username_->clearEditText();
- password_->setText("");
- }
- } else {
- onCancelLoginRequest();
- }
+ onLoginRequest(Q2PSTRING(username_->currentText()), Q2PSTRING(password_->text()), certificateString, certificate, currentOptions_, remember_->isChecked(), loginAutomatically_->isChecked());
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { /* Mustn't remember logins */
+ username_->clearEditText();
+ password_->setText("");
+ }
+ } else {
+ onCancelLoginRequest();
+ }
}
void QtLoginWindow::setLoginAutomatically(bool loginAutomatically) {
- loginAutomatically_->setChecked(loginAutomatically);
+ loginAutomatically_->setChecked(loginAutomatically);
}
void QtLoginWindow::handleCertficateChecked(bool checked) {
- if (checked) {
+ if (checked) {
#ifdef HAVE_SCHANNEL
- certificateFile_ = P2QSTRING(selectCAPICertificate());
- if (certificateFile_.isEmpty()) {
- certificateButton_->setChecked(false);
- }
+ certificateFile_ = P2QSTRING(selectCAPICertificate());
+ if (certificateFile_.isEmpty()) {
+ certificateButton_->setChecked(false);
+ }
#else
- certificateFile_ = QFileDialog::getOpenFileName(this, tr("Select an authentication certificate"), QString(), tr("P12 files (*.cert *.p12 *.pfx);;All files (*.*)"));
- if (certificateFile_.isEmpty()) {
- certificateButton_->setChecked(false);
- }
+ certificateFile_ = QFileDialog::getOpenFileName(this, tr("Select an authentication certificate"), QString(), tr("P12 files (*.cert *.p12 *.pfx);;All files (*.*)"));
+ if (certificateFile_.isEmpty()) {
+ certificateButton_->setChecked(false);
+ }
#endif
- }
- else {
- certificateFile_ = "";
- }
+ }
+ else {
+ certificateFile_ = "";
+ }
}
void QtLoginWindow::handleAbout() {
- if (!aboutDialog_) {
- aboutDialog_ = new QtAboutWidget();
- aboutDialog_->show();
- }
- else {
- aboutDialog_->show();
- aboutDialog_->raise();
- aboutDialog_->activateWindow();
- }
+ if (!aboutDialog_) {
+ aboutDialog_ = new QtAboutWidget();
+ aboutDialog_->show();
+ }
+ else {
+ aboutDialog_->show();
+ aboutDialog_->raise();
+ aboutDialog_->activateWindow();
+ }
}
void QtLoginWindow::handleShowXMLConsole() {
- uiEventStream_->send(boost::make_shared<RequestXMLConsoleUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestXMLConsoleUIEvent>());
}
void QtLoginWindow::handleShowFileTransferOverview() {
- uiEventStream_->send(boost::make_shared<RequestFileTransferListUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestFileTransferListUIEvent>());
}
void QtLoginWindow::handleShowHighlightEditor() {
- uiEventStream_->send(boost::make_shared<RequestHighlightEditorUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestHighlightEditorUIEvent>());
}
void QtLoginWindow::handleToggleSounds(bool enabled) {
- settings_->storeSetting(SettingConstants::PLAY_SOUNDS, enabled);
+ settings_->storeSetting(SettingConstants::PLAY_SOUNDS, enabled);
}
void QtLoginWindow::handleToggleNotifications(bool enabled) {
- settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled);
+ settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled);
}
void QtLoginWindow::handleQuit() {
- onQuitRequest();
+ onQuitRequest();
}
void QtLoginWindow::quit() {
- QApplication::quit();
+ QApplication::quit();
}
void QtLoginWindow::setInitialMenus() {
- menuBar_->clear();
- menuBar_->addMenu(swiftMenu_);
+ menuBar_->clear();
+ menuBar_->addMenu(swiftMenu_);
#ifdef SWIFTEN_PLATFORM_MACOSX
- menuBar_->addMenu(generalMenu_);
+ menuBar_->addMenu(generalMenu_);
#endif
}
void QtLoginWindow::morphInto(MainWindow *mainWindow) {
- setEnabled(false);
- QtMainWindow *qtMainWindow = dynamic_cast<QtMainWindow*>(mainWindow);
- assert(qtMainWindow);
- stack_->removeWidget(loginWidgetWrapper_);
- stack_->addWidget(qtMainWindow);
- stack_->setCurrentWidget(qtMainWindow);
- setEnabled(true);
- setInitialMenus();
- std::vector<QMenu*> mainWindowMenus = qtMainWindow->getMenus();
- viewMenu_ = mainWindowMenus[0];
- foreach (QMenu* menu, mainWindowMenus) {
- menuBar_->addMenu(menu);
- }
- setFocus();
+ setEnabled(false);
+ QtMainWindow *qtMainWindow = dynamic_cast<QtMainWindow*>(mainWindow);
+ assert(qtMainWindow);
+ stack_->removeWidget(loginWidgetWrapper_);
+ stack_->addWidget(qtMainWindow);
+ stack_->setCurrentWidget(qtMainWindow);
+ setEnabled(true);
+ setInitialMenus();
+ std::vector<QMenu*> mainWindowMenus = qtMainWindow->getMenus();
+ viewMenu_ = mainWindowMenus[0];
+ foreach (QMenu* menu, mainWindowMenus) {
+ menuBar_->addMenu(menu);
+ }
+ setFocus();
}
void QtLoginWindow::setMessage(const std::string& message) {
- if (!message.empty()) {
- message_->setText("<center><font color=\"red\">" + P2QSTRING(message) + "</font></center>");
- }
- else {
- message_->setText("");
- }
+ if (!message.empty()) {
+ message_->setText("<center><font color=\"red\">" + P2QSTRING(message) + "</font></center>");
+ }
+ else {
+ message_->setText("");
+ }
}
void QtLoginWindow::toggleBringToFront() {
- if (!isVisible()) {
- bringToFront();
- }
- else {
- window()->hide();
- }
+ if (!isVisible()) {
+ bringToFront();
+ }
+ else {
+ window()->hide();
+ }
}
void QtLoginWindow::bringToFront() {
- window()->showNormal();
- window()->raise();
- window()->activateWindow();
+ window()->showNormal();
+ window()->raise();
+ window()->activateWindow();
}
void QtLoginWindow::hide() {
- window()->hide();
+ window()->hide();
}
QtLoginWindow::QtMenus QtLoginWindow::getMenus() const {
- return QtMenus(swiftMenu_, generalMenu_);
+ return QtMenus(swiftMenu_, generalMenu_);
}
void QtLoginWindow::resizeEvent(QResizeEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtLoginWindow::moveEvent(QMoveEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
bool QtLoginWindow::askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificates) {
- QMessageBox dialog(this);
-
- dialog.setText(tr("The certificate presented by the server is not valid."));
- dialog.setInformativeText(P2QSTRING(message) + "\n\n" + tr("Would you like to permanently trust this certificate? This must only be done if you know it is correct."));
-
- dialog.addButton(tr("Show Certificate"), QMessageBox::HelpRole);
- dialog.addButton(QMessageBox::Yes);
- dialog.addButton(QMessageBox::No);
- dialog.setDefaultButton(QMessageBox::No);
- while (true) {
- int result = dialog.exec();
- if (result == QMessageBox::Yes || result == QMessageBox::No) {
- return result == QMessageBox::Yes;
- }
- // FIXME: This isn't very nice, because the dialog disappears every time. We actually need a real
- // dialog with a custom button.
- QtMainWindow::openCertificateDialog(certificates, &dialog);
- }
+ QMessageBox dialog(this);
+
+ dialog.setText(tr("The certificate presented by the server is not valid."));
+ dialog.setInformativeText(P2QSTRING(message) + "\n\n" + tr("Would you like to permanently trust this certificate? This must only be done if you know it is correct."));
+
+ dialog.addButton(tr("Show Certificate"), QMessageBox::HelpRole);
+ dialog.addButton(QMessageBox::Yes);
+ dialog.addButton(QMessageBox::No);
+ dialog.setDefaultButton(QMessageBox::No);
+ while (true) {
+ int result = dialog.exec();
+ if (result == QMessageBox::Yes || result == QMessageBox::No) {
+ return result == QMessageBox::Yes;
+ }
+ // FIXME: This isn't very nice, because the dialog disappears every time. We actually need a real
+ // dialog with a custom button.
+ QtMainWindow::openCertificateDialog(certificates, &dialog);
+ }
}
void QtLoginWindow::handleOpenConnectionOptions() {
- QtConnectionSettingsWindow connectionSettings(currentOptions_);
- if (connectionSettings.exec() == QDialog::Accepted) {
- currentOptions_ = connectionSettings.getOptions();
- }
+ QtConnectionSettingsWindow connectionSettings(currentOptions_);
+ if (connectionSettings.exec() == QDialog::Accepted) {
+ currentOptions_ = connectionSettings.getOptions();
+ }
}
}
diff --git a/Swift/QtUI/QtLoginWindow.h b/Swift/QtUI/QtLoginWindow.h
index e8e2e20..91b21f6 100644
--- a/Swift/QtUI/QtLoginWindow.h
+++ b/Swift/QtUI/QtLoginWindow.h
@@ -25,89 +25,89 @@ class QToolButton;
class QComboBox;
namespace Swift {
- class SettingsProvider;
- class TimerFactory;
+ class SettingsProvider;
+ class TimerFactory;
- class QtLoginWindow : public QMainWindow, public LoginWindow {
- Q_OBJECT
- public:
- struct QtMenus {
- QtMenus(QMenu* swiftMenu, QMenu* generalMenu) : swiftMenu(swiftMenu), generalMenu(generalMenu) {}
- QMenu* swiftMenu;
- QMenu* generalMenu;
- };
+ class QtLoginWindow : public QMainWindow, public LoginWindow {
+ Q_OBJECT
+ public:
+ struct QtMenus {
+ QtMenus(QMenu* swiftMenu, QMenu* generalMenu) : swiftMenu(swiftMenu), generalMenu(generalMenu) {}
+ QMenu* swiftMenu;
+ QMenu* generalMenu;
+ };
- public:
- QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory);
+ public:
+ QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory);
- void morphInto(MainWindow *mainWindow);
- virtual void loggedOut();
- virtual void setShowNotificationToggle(bool);
- virtual void setMessage(const std::string& message);
- virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options);
- virtual void removeAvailableAccount(const std::string& jid);
- virtual void setLoginAutomatically(bool loginAutomatically);
- virtual void setIsLoggingIn(bool loggingIn);
- void selectUser(const std::string& user);
- bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificate);
- void hide();
- QtMenus getMenus() const;
- virtual void quit();
+ void morphInto(MainWindow *mainWindow);
+ virtual void loggedOut();
+ virtual void setShowNotificationToggle(bool);
+ virtual void setMessage(const std::string& message);
+ virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options);
+ virtual void removeAvailableAccount(const std::string& jid);
+ virtual void setLoginAutomatically(bool loginAutomatically);
+ virtual void setIsLoggingIn(bool loggingIn);
+ void selectUser(const std::string& user);
+ bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificate);
+ void hide();
+ QtMenus getMenus() const;
+ virtual void quit();
- signals:
- void geometryChanged();
+ signals:
+ void geometryChanged();
- private slots:
- void loginClicked();
- void handleCertficateChecked(bool);
- void handleQuit();
- void handleShowXMLConsole();
- void handleShowFileTransferOverview();
- void handleShowHighlightEditor();
- void handleToggleSounds(bool enabled);
- void handleToggleNotifications(bool enabled);
- void handleAbout();
- void bringToFront();
- void toggleBringToFront();
- void handleUsernameTextChanged();
- void resizeEvent(QResizeEvent* event);
- void moveEvent(QMoveEvent* event);
- void handleSettingChanged(const std::string& settingPath);
- void handleOpenConnectionOptions();
+ private slots:
+ void loginClicked();
+ void handleCertficateChecked(bool);
+ void handleQuit();
+ void handleShowXMLConsole();
+ void handleShowFileTransferOverview();
+ void handleShowHighlightEditor();
+ void handleToggleSounds(bool enabled);
+ void handleToggleNotifications(bool enabled);
+ void handleAbout();
+ void bringToFront();
+ void toggleBringToFront();
+ void handleUsernameTextChanged();
+ void resizeEvent(QResizeEvent* event);
+ void moveEvent(QMoveEvent* event);
+ void handleSettingChanged(const std::string& settingPath);
+ void handleOpenConnectionOptions();
- protected:
- bool eventFilter(QObject *obj, QEvent *event);
+ protected:
+ bool eventFilter(QObject *obj, QEvent *event);
- private:
- void setInitialMenus();
- QWidget* loginWidgetWrapper_;
- QStringList usernames_;
- QStringList passwords_;
- QStringList certificateFiles_;
- std::vector<ClientOptions> options_;
- QComboBox* username_;
- QLineEdit* password_;
- QPushButton* loginButton_;
- /* If you add a widget here, change setLoggingIn as well.*/
- QCheckBox* remember_;
- QCheckBox* loginAutomatically_;
- QStackedWidget* stack_;
- QLabel* message_;
- QString certificateFile_;
- QToolButton* certificateButton_;
- QMenuBar* menuBar_;
- QMenu* swiftMenu_;
- QMenu* generalMenu_;
- QMenu* viewMenu_;
- QAction* toggleSoundsAction_;
- QAction* toggleNotificationsAction_;
- UIEventStream* uiEventStream_;
- QPointer<QtAboutWidget> aboutDialog_;
- SettingsProvider* settings_;
- QAction* xmlConsoleAction_;
- QAction* fileTransferOverviewAction_;
- QAction* highlightEditorAction_;
- TimerFactory* timerFactory_;
- ClientOptions currentOptions_;
- };
+ private:
+ void setInitialMenus();
+ QWidget* loginWidgetWrapper_;
+ QStringList usernames_;
+ QStringList passwords_;
+ QStringList certificateFiles_;
+ std::vector<ClientOptions> options_;
+ QComboBox* username_;
+ QLineEdit* password_;
+ QPushButton* loginButton_;
+ /* If you add a widget here, change setLoggingIn as well.*/
+ QCheckBox* remember_;
+ QCheckBox* loginAutomatically_;
+ QStackedWidget* stack_;
+ QLabel* message_;
+ QString certificateFile_;
+ QToolButton* certificateButton_;
+ QMenuBar* menuBar_;
+ QMenu* swiftMenu_;
+ QMenu* generalMenu_;
+ QMenu* viewMenu_;
+ QAction* toggleSoundsAction_;
+ QAction* toggleNotificationsAction_;
+ UIEventStream* uiEventStream_;
+ QPointer<QtAboutWidget> aboutDialog_;
+ SettingsProvider* settings_;
+ QAction* xmlConsoleAction_;
+ QAction* fileTransferOverviewAction_;
+ QAction* highlightEditorAction_;
+ TimerFactory* timerFactory_;
+ ClientOptions currentOptions_;
+ };
}
diff --git a/Swift/QtUI/QtMUCConfigurationWindow.cpp b/Swift/QtUI/QtMUCConfigurationWindow.cpp
index a4ef9e3..629e94f 100644
--- a/Swift/QtUI/QtMUCConfigurationWindow.cpp
+++ b/Swift/QtUI/QtMUCConfigurationWindow.cpp
@@ -16,30 +16,30 @@
namespace Swift {
QtMUCConfigurationWindow::QtMUCConfigurationWindow(Form::ref form) : closed_(false) {
- setAttribute(Qt::WA_DeleteOnClose);
-
- QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout->setContentsMargins(0,0,0,0);
- layout->setSpacing(2);
- //QLabel* label = new QLabel(this);
- //label->setText(tr("Room configuration"));
- //layout->addWidget(label);
-
- formWidget_ = NULL;
- formWidget_ = new QtFormWidget(form, this);
- layout->addWidget(formWidget_);
-
- QWidget* buttonsWidget = new QWidget(this);
- layout->addWidget(buttonsWidget);
-
- QBoxLayout* buttonsLayout = new QBoxLayout(QBoxLayout::LeftToRight, buttonsWidget);
- cancelButton_ = new QPushButton(tr("Cancel"), buttonsWidget);
- buttonsLayout->addWidget(cancelButton_);
- connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
- okButton_ = new QPushButton(tr("OK"), buttonsWidget);
- buttonsLayout->addWidget(okButton_);
- connect(okButton_, SIGNAL(clicked()), this, SLOT(handleOKClicked()));
- show();
+ setAttribute(Qt::WA_DeleteOnClose);
+
+ QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout->setContentsMargins(0,0,0,0);
+ layout->setSpacing(2);
+ //QLabel* label = new QLabel(this);
+ //label->setText(tr("Room configuration"));
+ //layout->addWidget(label);
+
+ formWidget_ = NULL;
+ formWidget_ = new QtFormWidget(form, this);
+ layout->addWidget(formWidget_);
+
+ QWidget* buttonsWidget = new QWidget(this);
+ layout->addWidget(buttonsWidget);
+
+ QBoxLayout* buttonsLayout = new QBoxLayout(QBoxLayout::LeftToRight, buttonsWidget);
+ cancelButton_ = new QPushButton(tr("Cancel"), buttonsWidget);
+ buttonsLayout->addWidget(cancelButton_);
+ connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
+ okButton_ = new QPushButton(tr("OK"), buttonsWidget);
+ buttonsLayout->addWidget(okButton_);
+ connect(okButton_, SIGNAL(clicked()), this, SLOT(handleOKClicked()));
+ show();
}
QtMUCConfigurationWindow::~QtMUCConfigurationWindow() {
@@ -47,19 +47,19 @@ QtMUCConfigurationWindow::~QtMUCConfigurationWindow() {
}
void QtMUCConfigurationWindow::closeEvent(QCloseEvent* /*event*/) {
- if (!closed_) {
- onFormCancelled();
- }
+ if (!closed_) {
+ onFormCancelled();
+ }
}
void QtMUCConfigurationWindow::handleCancelClicked() {
- close();
+ close();
}
void QtMUCConfigurationWindow::handleOKClicked() {
- onFormComplete(formWidget_->getCompletedForm());
- closed_ = true;
- close();
+ onFormComplete(formWidget_->getCompletedForm());
+ closed_ = true;
+ close();
}
diff --git a/Swift/QtUI/QtMUCConfigurationWindow.h b/Swift/QtUI/QtMUCConfigurationWindow.h
index bae7556..c8835e4 100644
--- a/Swift/QtUI/QtMUCConfigurationWindow.h
+++ b/Swift/QtUI/QtMUCConfigurationWindow.h
@@ -17,23 +17,23 @@ class QBoxLayout;
class QCloseEvent;
namespace Swift {
- class QtFormWidget;
- class QtMUCConfigurationWindow : public QWidget {
- Q_OBJECT
- public:
- QtMUCConfigurationWindow(Form::ref form);
- virtual ~QtMUCConfigurationWindow();
- boost::signal<void (Form::ref)> onFormComplete;
- boost::signal<void ()> onFormCancelled;
- private slots:
- void handleCancelClicked();
- void handleOKClicked();
- protected:
- virtual void closeEvent(QCloseEvent* event);
- private:
- QtFormWidget* formWidget_;
- QPushButton* okButton_;
- QPushButton* cancelButton_;
- bool closed_;
- };
+ class QtFormWidget;
+ class QtMUCConfigurationWindow : public QWidget {
+ Q_OBJECT
+ public:
+ QtMUCConfigurationWindow(Form::ref form);
+ virtual ~QtMUCConfigurationWindow();
+ boost::signal<void (Form::ref)> onFormComplete;
+ boost::signal<void ()> onFormCancelled;
+ private slots:
+ void handleCancelClicked();
+ void handleOKClicked();
+ protected:
+ virtual void closeEvent(QCloseEvent* event);
+ private:
+ QtFormWidget* formWidget_;
+ QPushButton* okButton_;
+ QPushButton* cancelButton_;
+ bool closed_;
+ };
}
diff --git a/Swift/QtUI/QtMainWindow.cpp b/Swift/QtUI/QtMainWindow.cpp
index e2092f6..d61026a 100644
--- a/Swift/QtUI/QtMainWindow.cpp
+++ b/Swift/QtUI/QtMainWindow.cpp
@@ -52,373 +52,373 @@
namespace Swift {
QtMainWindow::QtMainWindow(SettingsProvider* settings, UIEventStream* uiEventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID) : QWidget(), MainWindow(false), loginMenus_(loginMenus) {
- uiEventStream_ = uiEventStream;
- settings_ = settings;
- setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
- QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- mainLayout->setContentsMargins(0,0,0,0);
- mainLayout->setSpacing(0);
- meView_ = new QtRosterHeader(settings, statusCache, this);
- mainLayout->addWidget(meView_);
- connect(meView_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleStatusChanged(StatusShow::Type, const QString&)));
- connect(meView_, SIGNAL(onEditProfileRequest()), this, SLOT(handleEditProfileRequest()));
- connect(meView_, SIGNAL(onShowCertificateInfo()), this, SLOT(handleShowCertificateInfo()));
-
- tabs_ = new QtTabWidget(this);
+ uiEventStream_ = uiEventStream;
+ settings_ = settings;
+ setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+ QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ mainLayout->setContentsMargins(0,0,0,0);
+ mainLayout->setSpacing(0);
+ meView_ = new QtRosterHeader(settings, statusCache, this);
+ mainLayout->addWidget(meView_);
+ connect(meView_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleStatusChanged(StatusShow::Type, const QString&)));
+ connect(meView_, SIGNAL(onEditProfileRequest()), this, SLOT(handleEditProfileRequest()));
+ connect(meView_, SIGNAL(onShowCertificateInfo()), this, SLOT(handleShowCertificateInfo()));
+
+ tabs_ = new QtTabWidget(this);
#if QT_VERSION >= 0x040500
- tabs_->setDocumentMode(true);
+ tabs_->setDocumentMode(true);
#endif
- tabs_->setTabPosition(QTabWidget::South);
- mainLayout->addWidget(tabs_);
- contactsTabWidget_ = new QWidget(this);
- contactsTabWidget_->setContentsMargins(0, 0, 0, 0);
- QBoxLayout *contactTabLayout = new QBoxLayout(QBoxLayout::TopToBottom, contactsTabWidget_);
- contactsTabWidget_->setLayout(contactTabLayout);
- contactTabLayout->setSpacing(0);
- contactTabLayout->setContentsMargins(0, 0, 0, 0);
-
- treeWidget_ = new QtRosterWidget(uiEventStream_, settings_, this);
-
- contactTabLayout->addWidget(treeWidget_);
- new QtFilterWidget(this, treeWidget_, uiEventStream_, contactTabLayout);
-
- tabs_->addTab(contactsTabWidget_, tr("&Contacts"));
-
- eventWindow_ = new QtEventWindow(uiEventStream_);
- connect(eventWindow_, SIGNAL(onNewEventCountUpdated(int)), this, SLOT(handleEventCountUpdated(int)));
-
- chatListWindow_ = new QtChatListWindow(uiEventStream_, settings_);
- connect(chatListWindow_, SIGNAL(onCountUpdated(int)), this, SLOT(handleChatCountUpdated(int)));
-
- tabs_->addTab(chatListWindow_, tr("C&hats"));
- tabs_->addTab(eventWindow_, tr("&Notices"));
-
- tabs_->setCurrentIndex(settings_->getSetting(QtUISettingConstants::CURRENT_ROSTER_TAB));
-
- connect(tabs_, SIGNAL(currentChanged(int)), this, SLOT(handleTabChanged(int)));
-
- tabBarCombo_ = NULL;
- if (settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
- tabs_->tabBar()->hide();
- tabBarCombo_ = new QComboBox(this);
- tabBarCombo_->setAccessibleName("Current View");
- tabBarCombo_->addItem(tr("Contacts"));
- tabBarCombo_->addItem(tr("Chats"));
- tabBarCombo_->addItem(tr("Notices"));
- tabBarCombo_->setCurrentIndex(tabs_->currentIndex());
- mainLayout->addWidget(tabBarCombo_);
- connect(tabBarCombo_, SIGNAL(currentIndexChanged(int)), tabs_, SLOT(setCurrentIndex(int)));
- }
-
-
- this->setLayout(mainLayout);
-
- QMenu* viewMenu = new QMenu(tr("&View"), this);
- menus_.push_back(viewMenu);
-
- compactRosterAction_ = new QAction(tr("&Compact Roster"), this);
- compactRosterAction_->setCheckable(true);
- compactRosterAction_->setChecked(false);
- connect(compactRosterAction_, SIGNAL(toggled(bool)), SLOT(handleCompactRosterToggled(bool)));
- viewMenu->addAction(compactRosterAction_);
- handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
-
- showOfflineAction_ = new QAction(tr("&Show offline contacts"), this);
- showOfflineAction_->setCheckable(true);
- showOfflineAction_->setChecked(false);
- connect(showOfflineAction_, SIGNAL(toggled(bool)), SLOT(handleShowOfflineToggled(bool)));
- viewMenu->addAction(showOfflineAction_);
- handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
-
- if (emoticonsExist) {
- showEmoticonsAction_ = new QAction(tr("&Show Emoticons"), this);
- showEmoticonsAction_->setCheckable(true);
- showEmoticonsAction_->setChecked(false);
- connect(showEmoticonsAction_, SIGNAL(toggled(bool)), SLOT(handleShowEmoticonsToggled(bool)));
- viewMenu->addAction(showEmoticonsAction_);
- handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
- }
-
- QMenu* actionsMenu = new QMenu(tr("&Actions"), this);
- menus_.push_back(actionsMenu);
- QAction* editProfileAction = new QAction(tr("Edit &Profile…"), this);
- connect(editProfileAction, SIGNAL(triggered()), SLOT(handleEditProfileAction()));
- actionsMenu->addAction(editProfileAction);
- onlineOnlyActions_ << editProfileAction;
- QAction* joinMUCAction = new QAction(tr("Enter &Room…"), this);
- connect(joinMUCAction, SIGNAL(triggered()), SLOT(handleJoinMUCAction()));
- actionsMenu->addAction(joinMUCAction);
- onlineOnlyActions_ << joinMUCAction;
+ tabs_->setTabPosition(QTabWidget::South);
+ mainLayout->addWidget(tabs_);
+ contactsTabWidget_ = new QWidget(this);
+ contactsTabWidget_->setContentsMargins(0, 0, 0, 0);
+ QBoxLayout *contactTabLayout = new QBoxLayout(QBoxLayout::TopToBottom, contactsTabWidget_);
+ contactsTabWidget_->setLayout(contactTabLayout);
+ contactTabLayout->setSpacing(0);
+ contactTabLayout->setContentsMargins(0, 0, 0, 0);
+
+ treeWidget_ = new QtRosterWidget(uiEventStream_, settings_, this);
+
+ contactTabLayout->addWidget(treeWidget_);
+ new QtFilterWidget(this, treeWidget_, uiEventStream_, contactTabLayout);
+
+ tabs_->addTab(contactsTabWidget_, tr("&Contacts"));
+
+ eventWindow_ = new QtEventWindow(uiEventStream_);
+ connect(eventWindow_, SIGNAL(onNewEventCountUpdated(int)), this, SLOT(handleEventCountUpdated(int)));
+
+ chatListWindow_ = new QtChatListWindow(uiEventStream_, settings_);
+ connect(chatListWindow_, SIGNAL(onCountUpdated(int)), this, SLOT(handleChatCountUpdated(int)));
+
+ tabs_->addTab(chatListWindow_, tr("C&hats"));
+ tabs_->addTab(eventWindow_, tr("&Notices"));
+
+ tabs_->setCurrentIndex(settings_->getSetting(QtUISettingConstants::CURRENT_ROSTER_TAB));
+
+ connect(tabs_, SIGNAL(currentChanged(int)), this, SLOT(handleTabChanged(int)));
+
+ tabBarCombo_ = NULL;
+ if (settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
+ tabs_->tabBar()->hide();
+ tabBarCombo_ = new QComboBox(this);
+ tabBarCombo_->setAccessibleName("Current View");
+ tabBarCombo_->addItem(tr("Contacts"));
+ tabBarCombo_->addItem(tr("Chats"));
+ tabBarCombo_->addItem(tr("Notices"));
+ tabBarCombo_->setCurrentIndex(tabs_->currentIndex());
+ mainLayout->addWidget(tabBarCombo_);
+ connect(tabBarCombo_, SIGNAL(currentIndexChanged(int)), tabs_, SLOT(setCurrentIndex(int)));
+ }
+
+
+ this->setLayout(mainLayout);
+
+ QMenu* viewMenu = new QMenu(tr("&View"), this);
+ menus_.push_back(viewMenu);
+
+ compactRosterAction_ = new QAction(tr("&Compact Roster"), this);
+ compactRosterAction_->setCheckable(true);
+ compactRosterAction_->setChecked(false);
+ connect(compactRosterAction_, SIGNAL(toggled(bool)), SLOT(handleCompactRosterToggled(bool)));
+ viewMenu->addAction(compactRosterAction_);
+ handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+
+ showOfflineAction_ = new QAction(tr("&Show offline contacts"), this);
+ showOfflineAction_->setCheckable(true);
+ showOfflineAction_->setChecked(false);
+ connect(showOfflineAction_, SIGNAL(toggled(bool)), SLOT(handleShowOfflineToggled(bool)));
+ viewMenu->addAction(showOfflineAction_);
+ handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+
+ if (emoticonsExist) {
+ showEmoticonsAction_ = new QAction(tr("&Show Emoticons"), this);
+ showEmoticonsAction_->setCheckable(true);
+ showEmoticonsAction_->setChecked(false);
+ connect(showEmoticonsAction_, SIGNAL(toggled(bool)), SLOT(handleShowEmoticonsToggled(bool)));
+ viewMenu->addAction(showEmoticonsAction_);
+ handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ }
+
+ QMenu* actionsMenu = new QMenu(tr("&Actions"), this);
+ menus_.push_back(actionsMenu);
+ QAction* editProfileAction = new QAction(tr("Edit &Profile…"), this);
+ connect(editProfileAction, SIGNAL(triggered()), SLOT(handleEditProfileAction()));
+ actionsMenu->addAction(editProfileAction);
+ onlineOnlyActions_ << editProfileAction;
+ QAction* joinMUCAction = new QAction(tr("Enter &Room…"), this);
+ connect(joinMUCAction, SIGNAL(triggered()), SLOT(handleJoinMUCAction()));
+ actionsMenu->addAction(joinMUCAction);
+ onlineOnlyActions_ << joinMUCAction;
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- QAction* viewLogsAction = new QAction(tr("&View History…"), this);
- connect(viewLogsAction, SIGNAL(triggered()), SLOT(handleViewLogsAction()));
- actionsMenu->addAction(viewLogsAction);
+ QAction* viewLogsAction = new QAction(tr("&View History…"), this);
+ connect(viewLogsAction, SIGNAL(triggered()), SLOT(handleViewLogsAction()));
+ actionsMenu->addAction(viewLogsAction);
#endif
- openBlockingListEditor_ = new QAction(tr("Edit &Blocking List…"), this);
- connect(openBlockingListEditor_, SIGNAL(triggered()), SLOT(handleEditBlockingList()));
- actionsMenu->addAction(openBlockingListEditor_);
- onlineOnlyActions_ << openBlockingListEditor_;
- openBlockingListEditor_->setVisible(false);
- addUserAction_ = new QAction(tr("&Add Contact…"), this);
- addUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
- addUserAction_->setShortcutContext(Qt::ApplicationShortcut);
- connect(addUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleAddUserActionTriggered(bool)));
- actionsMenu->addAction(addUserAction_);
- onlineOnlyActions_ << addUserAction_;
- editUserAction_ = new QAction(tr("&Edit Selected Contact…"), this);
- connect(editUserAction_, SIGNAL(triggered(bool)), treeWidget_, SLOT(handleEditUserActionTriggered(bool)));
- actionsMenu->addAction(editUserAction_);
- onlineOnlyActions_ << editUserAction_;
- editUserAction_->setEnabled(false);
- chatUserAction_ = new QAction(tr("Start &Chat…"), this);
- chatUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N));
- chatUserAction_->setShortcutContext(Qt::ApplicationShortcut);
- connect(chatUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleChatUserActionTriggered(bool)));
- actionsMenu->addAction(chatUserAction_);
- onlineOnlyActions_ << chatUserAction_;
- if (enableAdHocCommandOnJID) {
- otherAdHocAction_ = new QAction(tr("Run Other Command"), this);
- connect(otherAdHocAction_, SIGNAL(triggered()), this, SLOT(handleOtherAdHocActionTriggered()));
- actionsMenu->addAction(otherAdHocAction_);
- onlineOnlyActions_ << otherAdHocAction_;
- }
- serverAdHocMenu_ = new QMenu(tr("Run Server Command"), this);
- actionsMenu->addMenu(serverAdHocMenu_);
- actionsMenu->addSeparator();
- QAction* signOutAction = new QAction(tr("&Sign Out"), this);
- connect(signOutAction, SIGNAL(triggered()), SLOT(handleSignOutAction()));
- actionsMenu->addAction(signOutAction);
-
- toggleRequestDeliveryReceipts_ = new QAction(tr("&Request Delivery Receipts"), this);
- toggleRequestDeliveryReceipts_->setCheckable(true);
- toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
- connect(toggleRequestDeliveryReceipts_, SIGNAL(toggled(bool)), SLOT(handleToggleRequestDeliveryReceipts(bool)));
-
- QList< QAction* > generalMenuActions = loginMenus_.generalMenu->actions();
- loginMenus_.generalMenu->insertAction(generalMenuActions.at(generalMenuActions.count()-2),toggleRequestDeliveryReceipts_);
-
- treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtMainWindow::handleSomethingSelectedChanged, this, _1));
-
- setAvailableAdHocCommands(std::vector<DiscoItems::Item>());
- QAction* adHocAction = new QAction(tr("Collecting commands..."), this);
- adHocAction->setEnabled(false);
- serverAdHocMenu_->addAction(adHocAction);
- serverAdHocCommandActions_.append(adHocAction);
-
- settings_->onSettingChanged.connect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
+ openBlockingListEditor_ = new QAction(tr("Edit &Blocking List…"), this);
+ connect(openBlockingListEditor_, SIGNAL(triggered()), SLOT(handleEditBlockingList()));
+ actionsMenu->addAction(openBlockingListEditor_);
+ onlineOnlyActions_ << openBlockingListEditor_;
+ openBlockingListEditor_->setVisible(false);
+ addUserAction_ = new QAction(tr("&Add Contact…"), this);
+ addUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
+ addUserAction_->setShortcutContext(Qt::ApplicationShortcut);
+ connect(addUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleAddUserActionTriggered(bool)));
+ actionsMenu->addAction(addUserAction_);
+ onlineOnlyActions_ << addUserAction_;
+ editUserAction_ = new QAction(tr("&Edit Selected Contact…"), this);
+ connect(editUserAction_, SIGNAL(triggered(bool)), treeWidget_, SLOT(handleEditUserActionTriggered(bool)));
+ actionsMenu->addAction(editUserAction_);
+ onlineOnlyActions_ << editUserAction_;
+ editUserAction_->setEnabled(false);
+ chatUserAction_ = new QAction(tr("Start &Chat…"), this);
+ chatUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N));
+ chatUserAction_->setShortcutContext(Qt::ApplicationShortcut);
+ connect(chatUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleChatUserActionTriggered(bool)));
+ actionsMenu->addAction(chatUserAction_);
+ onlineOnlyActions_ << chatUserAction_;
+ if (enableAdHocCommandOnJID) {
+ otherAdHocAction_ = new QAction(tr("Run Other Command"), this);
+ connect(otherAdHocAction_, SIGNAL(triggered()), this, SLOT(handleOtherAdHocActionTriggered()));
+ actionsMenu->addAction(otherAdHocAction_);
+ onlineOnlyActions_ << otherAdHocAction_;
+ }
+ serverAdHocMenu_ = new QMenu(tr("Run Server Command"), this);
+ actionsMenu->addMenu(serverAdHocMenu_);
+ actionsMenu->addSeparator();
+ QAction* signOutAction = new QAction(tr("&Sign Out"), this);
+ connect(signOutAction, SIGNAL(triggered()), SLOT(handleSignOutAction()));
+ actionsMenu->addAction(signOutAction);
+
+ toggleRequestDeliveryReceipts_ = new QAction(tr("&Request Delivery Receipts"), this);
+ toggleRequestDeliveryReceipts_->setCheckable(true);
+ toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
+ connect(toggleRequestDeliveryReceipts_, SIGNAL(toggled(bool)), SLOT(handleToggleRequestDeliveryReceipts(bool)));
+
+ QList< QAction* > generalMenuActions = loginMenus_.generalMenu->actions();
+ loginMenus_.generalMenu->insertAction(generalMenuActions.at(generalMenuActions.count()-2),toggleRequestDeliveryReceipts_);
+
+ treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtMainWindow::handleSomethingSelectedChanged, this, _1));
+
+ setAvailableAdHocCommands(std::vector<DiscoItems::Item>());
+ QAction* adHocAction = new QAction(tr("Collecting commands..."), this);
+ adHocAction->setEnabled(false);
+ serverAdHocMenu_->addAction(adHocAction);
+ serverAdHocCommandActions_.append(adHocAction);
+
+ settings_->onSettingChanged.connect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
}
QtMainWindow::~QtMainWindow() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
+ settings_->onSettingChanged.disconnect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
}
void QtMainWindow::handleTabChanged(int index) {
- settings_->storeSetting(QtUISettingConstants::CURRENT_ROSTER_TAB, index);
+ settings_->storeSetting(QtUISettingConstants::CURRENT_ROSTER_TAB, index);
}
void QtMainWindow::handleToggleRequestDeliveryReceipts(bool enabled) {
- settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, enabled);
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, enabled);
}
void QtMainWindow::handleShowCertificateInfo() {
- onShowCertificateRequest();
+ onShowCertificateRequest();
}
void QtMainWindow::handleEditBlockingList() {
- uiEventStream_->send(boost::make_shared<RequestBlockListDialogUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestBlockListDialogUIEvent>());
}
void QtMainWindow::handleSomethingSelectedChanged(bool itemSelected) {
- bool isOnline = addUserAction_->isEnabled();
- editUserAction_->setEnabled(isOnline && itemSelected);
+ bool isOnline = addUserAction_->isEnabled();
+ editUserAction_->setEnabled(isOnline && itemSelected);
}
QtEventWindow* QtMainWindow::getEventWindow() {
- return eventWindow_;
+ return eventWindow_;
}
QtChatListWindow* QtMainWindow::getChatListWindow() {
- return chatListWindow_;
+ return chatListWindow_;
}
void QtMainWindow::setRosterModel(Roster* roster) {
- treeWidget_->setRosterModel(roster);
+ treeWidget_->setRosterModel(roster);
}
void QtMainWindow::handleEditProfileRequest() {
- uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
}
void QtMainWindow::handleEventCountUpdated(int count) {
- QColor eventTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
- int eventIndex = 2;
- tabs_->tabBar()->setTabTextColor(eventIndex, eventTabColor);
- QString text = tr("&Notices");
- if (count > 0) {
- text += QString(" (%1)").arg(count);
- }
- tabs_->setTabText(eventIndex, text);
+ QColor eventTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
+ int eventIndex = 2;
+ tabs_->tabBar()->setTabTextColor(eventIndex, eventTabColor);
+ QString text = tr("&Notices");
+ if (count > 0) {
+ text += QString(" (%1)").arg(count);
+ }
+ tabs_->setTabText(eventIndex, text);
}
void QtMainWindow::handleChatCountUpdated(int count) {
- QColor chatTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
- int chatIndex = 1;
- tabs_->tabBar()->setTabTextColor(chatIndex, chatTabColor);
- QString text = tr("C&hats");
- if (count > 0) {
- text += QString(" (%1)").arg(count);
- }
- tabs_->setTabText(chatIndex, text);
+ QColor chatTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
+ int chatIndex = 1;
+ tabs_->tabBar()->setTabTextColor(chatIndex, chatTabColor);
+ QString text = tr("C&hats");
+ if (count > 0) {
+ text += QString(" (%1)").arg(count);
+ }
+ tabs_->setTabText(chatIndex, text);
}
void QtMainWindow::handleAddUserActionTriggered(bool /*checked*/) {
- boost::shared_ptr<UIEvent> event(new RequestAddUserDialogUIEvent());
- uiEventStream_->send(event);
+ boost::shared_ptr<UIEvent> event(new RequestAddUserDialogUIEvent());
+ uiEventStream_->send(event);
}
void QtMainWindow::handleChatUserActionTriggered(bool /*checked*/) {
- boost::shared_ptr<UIEvent> event(new RequestChatWithUserDialogUIEvent());
- uiEventStream_->send(event);
+ boost::shared_ptr<UIEvent> event(new RequestChatWithUserDialogUIEvent());
+ uiEventStream_->send(event);
}
void QtMainWindow::handleOtherAdHocActionTriggered() {
- new QtAdHocCommandWithJIDWindow(uiEventStream_);
+ new QtAdHocCommandWithJIDWindow(uiEventStream_);
}
void QtMainWindow::handleSignOutAction() {
- loginMenus_.generalMenu->removeAction(toggleRequestDeliveryReceipts_);
- onSignOutRequest();
+ loginMenus_.generalMenu->removeAction(toggleRequestDeliveryReceipts_);
+ onSignOutRequest();
}
void QtMainWindow::handleEditProfileAction() {
- uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
}
void QtMainWindow::handleJoinMUCAction() {
- uiEventStream_->send(boost::make_shared<RequestJoinMUCUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestJoinMUCUIEvent>());
}
void QtMainWindow::handleViewLogsAction() {
- uiEventStream_->send(boost::make_shared<RequestHistoryUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestHistoryUIEvent>());
}
void QtMainWindow::handleStatusChanged(StatusShow::Type showType, const QString &statusMessage) {
- onChangeStatusRequest(showType, Q2PSTRING(statusMessage));
+ onChangeStatusRequest(showType, Q2PSTRING(statusMessage));
}
void QtMainWindow::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
- handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
- }
- if (settingPath == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
- handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
- }
- if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
- toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
- }
- if (settingPath == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- }
+ if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
+ handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+ }
+ if (settingPath == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
+ handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ }
+ if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
+ toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
+ }
+ if (settingPath == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ }
}
void QtMainWindow::handleCompactRosterToggled(bool state) {
- settings_->storeSetting(QtUISettingConstants::COMPACT_ROSTER, state);
- compactRosterAction_->setChecked(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ settings_->storeSetting(QtUISettingConstants::COMPACT_ROSTER, state);
+ compactRosterAction_->setChecked(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
void QtMainWindow::handleShowOfflineToggled(bool state) {
- settings_->storeSetting(SettingConstants::SHOW_OFFLINE, state);
- showOfflineAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+ settings_->storeSetting(SettingConstants::SHOW_OFFLINE, state);
+ showOfflineAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
}
void QtMainWindow::handleShowEmoticonsToggled(bool state) {
- settings_->storeSetting(QtUISettingConstants::SHOW_EMOTICONS, state);
- showEmoticonsAction_->setChecked(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ settings_->storeSetting(QtUISettingConstants::SHOW_EMOTICONS, state);
+ showEmoticonsAction_->setChecked(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
}
void QtMainWindow::setMyNick(const std::string& nick) {
- meView_->setNick(P2QSTRING(nick));
+ meView_->setNick(P2QSTRING(nick));
}
void QtMainWindow::setMyJID(const JID& jid) {
- meView_->setJID(P2QSTRING(jid.toBare().toString()));
+ meView_->setJID(P2QSTRING(jid.toBare().toString()));
}
void QtMainWindow::setMyAvatarPath(const std::string& path) {
- meView_->setAvatar(P2QSTRING(path));
+ meView_->setAvatar(P2QSTRING(path));
}
void QtMainWindow::setMyStatusText(const std::string& status) {
- meView_->setStatusText(P2QSTRING(status));
+ meView_->setStatusText(P2QSTRING(status));
}
void QtMainWindow::setMyStatusType(StatusShow::Type type) {
- meView_->setStatusType(type);
- const bool online = (type != StatusShow::None);
- treeWidget_->setOnline(online);
- chatListWindow_->setOnline(online);
- foreach (QAction *action, onlineOnlyActions_) {
- action->setEnabled(online);
- }
- serverAdHocMenu_->setEnabled(online);
+ meView_->setStatusType(type);
+ const bool online = (type != StatusShow::None);
+ treeWidget_->setOnline(online);
+ chatListWindow_->setOnline(online);
+ foreach (QAction *action, onlineOnlyActions_) {
+ action->setEnabled(online);
+ }
+ serverAdHocMenu_->setEnabled(online);
}
void QtMainWindow::setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) {
- meView_->setContactRosterItem(contact);
+ meView_->setContactRosterItem(contact);
}
void QtMainWindow::setConnecting() {
- meView_->setConnecting();
+ meView_->setConnecting();
}
void QtMainWindow::setStreamEncryptionStatus(bool tlsInPlaceAndValid) {
- meView_->setStreamEncryptionStatus(tlsInPlaceAndValid);
+ meView_->setStreamEncryptionStatus(tlsInPlaceAndValid);
}
void QtMainWindow::openCertificateDialog(const std::vector<Certificate::ref>& chain) {
- openCertificateDialog(chain, this);
+ openCertificateDialog(chain, this);
}
void QtMainWindow::openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent) {
#if defined(SWIFTEN_PLATFORM_MACOSX)
- CocoaUIHelpers::displayCertificateChainAsSheet(parent, chain);
+ CocoaUIHelpers::displayCertificateChainAsSheet(parent, chain);
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
- WinUIHelpers::displayCertificateChainAsSheet(parent, chain);
+ WinUIHelpers::displayCertificateChainAsSheet(parent, chain);
#else
- QtCertificateViewerDialog::displayCertificateChainAsSheet(parent, chain);
+ QtCertificateViewerDialog::displayCertificateChainAsSheet(parent, chain);
#endif
}
void QtMainWindow::handleAdHocActionTriggered(bool /*checked*/) {
- QAction* action = qobject_cast<QAction*>(sender());
- assert(action);
- DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)];
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestAdHocUIEvent(command)));
+ QAction* action = qobject_cast<QAction*>(sender());
+ assert(action);
+ DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)];
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestAdHocUIEvent(command)));
}
void QtMainWindow::setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands) {
- serverAdHocCommands_ = commands;
- foreach (QAction* action, serverAdHocCommandActions_) {
- delete action;
- }
- serverAdHocMenu_->clear();
- serverAdHocCommandActions_.clear();
- foreach (DiscoItems::Item command, commands) {
- QAction* action = new QAction(P2QSTRING(command.getName()), this);
- connect(action, SIGNAL(triggered(bool)), this, SLOT(handleAdHocActionTriggered(bool)));
- serverAdHocMenu_->addAction(action);
- serverAdHocCommandActions_.append(action);
- }
- if (serverAdHocCommandActions_.isEmpty()) {
- QAction* action = new QAction(tr("No Available Commands"), this);
- action->setEnabled(false);
- serverAdHocMenu_->addAction(action);
- serverAdHocCommandActions_.append(action);
- }
+ serverAdHocCommands_ = commands;
+ foreach (QAction* action, serverAdHocCommandActions_) {
+ delete action;
+ }
+ serverAdHocMenu_->clear();
+ serverAdHocCommandActions_.clear();
+ foreach (DiscoItems::Item command, commands) {
+ QAction* action = new QAction(P2QSTRING(command.getName()), this);
+ connect(action, SIGNAL(triggered(bool)), this, SLOT(handleAdHocActionTriggered(bool)));
+ serverAdHocMenu_->addAction(action);
+ serverAdHocCommandActions_.append(action);
+ }
+ if (serverAdHocCommandActions_.isEmpty()) {
+ QAction* action = new QAction(tr("No Available Commands"), this);
+ action->setEnabled(false);
+ serverAdHocMenu_->addAction(action);
+ serverAdHocCommandActions_.append(action);
+ }
}
void QtMainWindow::setBlockingCommandAvailable(bool isAvailable) {
- openBlockingListEditor_->setVisible(isAvailable);
+ openBlockingListEditor_->setVisible(isAvailable);
}
}
diff --git a/Swift/QtUI/QtMainWindow.h b/Swift/QtUI/QtMainWindow.h
index 71a5783..d90dade 100644
--- a/Swift/QtUI/QtMainWindow.h
+++ b/Swift/QtUI/QtMainWindow.h
@@ -28,83 +28,83 @@ class QMenu;
class QTabWidget;
namespace Swift {
- class QtRosterWidget;
- class TreeWidget;
- class UIEventStream;
- class QtTabWidget;
- class SettingsProvider;
- class QtUIPreferences;
- class StatusCache;
+ class QtRosterWidget;
+ class TreeWidget;
+ class UIEventStream;
+ class QtTabWidget;
+ class SettingsProvider;
+ class QtUIPreferences;
+ class StatusCache;
- class QtMainWindow : public QWidget, public MainWindow {
- Q_OBJECT
- public:
- QtMainWindow(SettingsProvider*, UIEventStream* eventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID);
- virtual ~QtMainWindow();
- std::vector<QMenu*> getMenus() {return menus_;}
- void setMyNick(const std::string& name);
- void setMyJID(const JID& jid);
- void setMyAvatarPath(const std::string& path);
- void setMyStatusText(const std::string& status);
- void setMyStatusType(StatusShow::Type type);
- void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
- void setConnecting();
- void setStreamEncryptionStatus(bool tlsInPlaceAndValid);
- void openCertificateDialog(const std::vector<Certificate::ref>& chain);
- static void openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent);
- QtEventWindow* getEventWindow();
- QtChatListWindow* getChatListWindow();
- void setRosterModel(Roster* roster);
- void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands);
- void setBlockingCommandAvailable(bool isAvailable);
- private slots:
- void handleStatusChanged(StatusShow::Type showType, const QString &statusMessage);
- void handleSettingChanged(const std::string& settingPath);
- void handleCompactRosterToggled(bool);
- void handleShowOfflineToggled(bool);
- void handleShowEmoticonsToggled(bool);
- void handleJoinMUCAction();
- void handleViewLogsAction();
- void handleSignOutAction();
- void handleEditProfileAction();
- void handleAddUserActionTriggered(bool checked);
- void handleChatUserActionTriggered(bool checked);
- void handleOtherAdHocActionTriggered();
- void handleAdHocActionTriggered(bool checked);
- void handleEventCountUpdated(int count);
- void handleChatCountUpdated(int count);
- void handleEditProfileRequest();
- void handleTabChanged(int index);
- void handleToggleRequestDeliveryReceipts(bool enabled);
- void handleShowCertificateInfo();
- void handleEditBlockingList();
- void handleSomethingSelectedChanged(bool itemSelected);
+ class QtMainWindow : public QWidget, public MainWindow {
+ Q_OBJECT
+ public:
+ QtMainWindow(SettingsProvider*, UIEventStream* eventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID);
+ virtual ~QtMainWindow();
+ std::vector<QMenu*> getMenus() {return menus_;}
+ void setMyNick(const std::string& name);
+ void setMyJID(const JID& jid);
+ void setMyAvatarPath(const std::string& path);
+ void setMyStatusText(const std::string& status);
+ void setMyStatusType(StatusShow::Type type);
+ void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
+ void setConnecting();
+ void setStreamEncryptionStatus(bool tlsInPlaceAndValid);
+ void openCertificateDialog(const std::vector<Certificate::ref>& chain);
+ static void openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent);
+ QtEventWindow* getEventWindow();
+ QtChatListWindow* getChatListWindow();
+ void setRosterModel(Roster* roster);
+ void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands);
+ void setBlockingCommandAvailable(bool isAvailable);
+ private slots:
+ void handleStatusChanged(StatusShow::Type showType, const QString &statusMessage);
+ void handleSettingChanged(const std::string& settingPath);
+ void handleCompactRosterToggled(bool);
+ void handleShowOfflineToggled(bool);
+ void handleShowEmoticonsToggled(bool);
+ void handleJoinMUCAction();
+ void handleViewLogsAction();
+ void handleSignOutAction();
+ void handleEditProfileAction();
+ void handleAddUserActionTriggered(bool checked);
+ void handleChatUserActionTriggered(bool checked);
+ void handleOtherAdHocActionTriggered();
+ void handleAdHocActionTriggered(bool checked);
+ void handleEventCountUpdated(int count);
+ void handleChatCountUpdated(int count);
+ void handleEditProfileRequest();
+ void handleTabChanged(int index);
+ void handleToggleRequestDeliveryReceipts(bool enabled);
+ void handleShowCertificateInfo();
+ void handleEditBlockingList();
+ void handleSomethingSelectedChanged(bool itemSelected);
- private:
- SettingsProvider* settings_;
- QtLoginWindow::QtMenus loginMenus_;
- std::vector<QMenu*> menus_;
- QtRosterWidget* treeWidget_;
- QtRosterHeader* meView_;
- QAction* addUserAction_;
- QAction* editUserAction_;
- QAction* chatUserAction_;
- QAction* otherAdHocAction_;
- QAction* showOfflineAction_;
- QAction* compactRosterAction_;
- QAction* showEmoticonsAction_;
- QAction* openBlockingListEditor_;
- QAction* toggleRequestDeliveryReceipts_;
- QMenu* serverAdHocMenu_;
- QtTabWidget* tabs_;
- QComboBox* tabBarCombo_;
- QWidget* contactsTabWidget_;
- QWidget* eventsTabWidget_;
- QtEventWindow* eventWindow_;
- QtChatListWindow* chatListWindow_;
- UIEventStream* uiEventStream_;
- std::vector<DiscoItems::Item> serverAdHocCommands_;
- QList<QAction*> serverAdHocCommandActions_;
- QList<QAction*> onlineOnlyActions_;
- };
+ private:
+ SettingsProvider* settings_;
+ QtLoginWindow::QtMenus loginMenus_;
+ std::vector<QMenu*> menus_;
+ QtRosterWidget* treeWidget_;
+ QtRosterHeader* meView_;
+ QAction* addUserAction_;
+ QAction* editUserAction_;
+ QAction* chatUserAction_;
+ QAction* otherAdHocAction_;
+ QAction* showOfflineAction_;
+ QAction* compactRosterAction_;
+ QAction* showEmoticonsAction_;
+ QAction* openBlockingListEditor_;
+ QAction* toggleRequestDeliveryReceipts_;
+ QMenu* serverAdHocMenu_;
+ QtTabWidget* tabs_;
+ QComboBox* tabBarCombo_;
+ QWidget* contactsTabWidget_;
+ QWidget* eventsTabWidget_;
+ QtEventWindow* eventWindow_;
+ QtChatListWindow* chatListWindow_;
+ UIEventStream* uiEventStream_;
+ std::vector<DiscoItems::Item> serverAdHocCommands_;
+ QList<QAction*> serverAdHocCommandActions_;
+ QList<QAction*> onlineOnlyActions_;
+ };
}
diff --git a/Swift/QtUI/QtNameWidget.cpp b/Swift/QtUI/QtNameWidget.cpp
index cf668c8..0610a00 100644
--- a/Swift/QtUI/QtNameWidget.cpp
+++ b/Swift/QtUI/QtNameWidget.cpp
@@ -18,80 +18,80 @@
namespace Swift {
QtNameWidget::QtNameWidget(SettingsProvider* settings, QWidget *parent) : QWidget(parent), settings(settings), isOnline_(false) {
- QHBoxLayout* mainLayout = new QHBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
+ QHBoxLayout* mainLayout = new QHBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
- mode = settings->getSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER) ? ShowNick : ShowJID;
+ mode = settings->getSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER) ? ShowNick : ShowJID;
- textLabel = new QtElidingLabel(this);
- QFont font = textLabel->font();
- font.setBold(true);
- textLabel->setFont(font);
- mainLayout->addWidget(textLabel);
+ textLabel = new QtElidingLabel(this);
+ QFont font = textLabel->font();
+ font.setBold(true);
+ textLabel->setFont(font);
+ mainLayout->addWidget(textLabel);
}
void QtNameWidget::setNick(const QString& nick) {
- this->nick = nick;
- updateText();
+ this->nick = nick;
+ updateText();
}
void QtNameWidget::setJID(const QString& jid) {
- this->jid = jid;
- updateText();
+ this->jid = jid;
+ updateText();
}
void QtNameWidget::setOnline(const bool isOnline) {
- isOnline_ = isOnline;
+ isOnline_ = isOnline;
}
void QtNameWidget::mousePressEvent(QMouseEvent* event) {
- QMenu menu;
- bool hasNick = !nick.isEmpty();
-
- QAction* showAsNick = new QAction(hasNick ? tr("Show Nickname") : tr("(No Nickname Set)"), this);
- showAsNick->setCheckable(true);
- showAsNick->setEnabled(hasNick);
- if (mode == ShowNick && hasNick) {
- showAsNick->setChecked(true);
- }
- menu.addAction(showAsNick);
-
- QAction* showAsJID = new QAction(tr("Show Address"), this);
- showAsJID->setCheckable(true);
- if (mode == ShowJID || !hasNick) {
- showAsJID->setChecked(true);
- }
- menu.addAction(showAsJID);
-
- QAction* editProfile = new QAction(tr("Edit Profile"), this);
- menu.addAction(editProfile);
- editProfile->setEnabled(isOnline_);
-
- QAction* result = menu.exec(event->globalPos());
- if (result == showAsJID) {
- mode = ShowJID;
- }
- else if (result == showAsNick) {
- mode = ShowNick;
- }
- else if (result == editProfile) {
- emit onChangeNickRequest();
- }
- settings->storeSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER, mode == ShowNick);
- updateText();
+ QMenu menu;
+ bool hasNick = !nick.isEmpty();
+
+ QAction* showAsNick = new QAction(hasNick ? tr("Show Nickname") : tr("(No Nickname Set)"), this);
+ showAsNick->setCheckable(true);
+ showAsNick->setEnabled(hasNick);
+ if (mode == ShowNick && hasNick) {
+ showAsNick->setChecked(true);
+ }
+ menu.addAction(showAsNick);
+
+ QAction* showAsJID = new QAction(tr("Show Address"), this);
+ showAsJID->setCheckable(true);
+ if (mode == ShowJID || !hasNick) {
+ showAsJID->setChecked(true);
+ }
+ menu.addAction(showAsJID);
+
+ QAction* editProfile = new QAction(tr("Edit Profile"), this);
+ menu.addAction(editProfile);
+ editProfile->setEnabled(isOnline_);
+
+ QAction* result = menu.exec(event->globalPos());
+ if (result == showAsJID) {
+ mode = ShowJID;
+ }
+ else if (result == showAsNick) {
+ mode = ShowNick;
+ }
+ else if (result == editProfile) {
+ emit onChangeNickRequest();
+ }
+ settings->storeSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER, mode == ShowNick);
+ updateText();
}
void QtNameWidget::updateText() {
- QString text;
- if (mode == ShowNick && !nick.isEmpty()) {
- text = nick;
- }
- else {
- text = jid;
- }
- text.replace("<","&lt;");
- textLabel->setText(text);
+ QString text;
+ if (mode == ShowNick && !nick.isEmpty()) {
+ text = nick;
+ }
+ else {
+ text = jid;
+ }
+ text.replace("<","&lt;");
+ textLabel->setText(text);
}
}
diff --git a/Swift/QtUI/QtNameWidget.h b/Swift/QtUI/QtNameWidget.h
index 5f9962b..0da0ff6 100644
--- a/Swift/QtUI/QtNameWidget.h
+++ b/Swift/QtUI/QtNameWidget.h
@@ -9,38 +9,38 @@
#include <QWidget>
namespace Swift {
- class QtElidingLabel;
- class SettingsProvider;
-
- class QtNameWidget : public QWidget {
- Q_OBJECT
-
- public:
- QtNameWidget(SettingsProvider* settings, QWidget *parent);
-
- void setNick(const QString& text);
- void setJID(const QString& jid);
- void setOnline(const bool isOnline);
-
- signals:
- void onChangeNickRequest();
-
- private:
- void updateText();
- virtual void mousePressEvent(QMouseEvent* event);
-
- private:
- enum Mode {
- ShowNick,
- ShowJID
- };
-
- SettingsProvider* settings;
- Mode mode;
- QtElidingLabel* textLabel;
- QString jid;
- QString nick;
- bool isOnline_;
- };
+ class QtElidingLabel;
+ class SettingsProvider;
+
+ class QtNameWidget : public QWidget {
+ Q_OBJECT
+
+ public:
+ QtNameWidget(SettingsProvider* settings, QWidget *parent);
+
+ void setNick(const QString& text);
+ void setJID(const QString& jid);
+ void setOnline(const bool isOnline);
+
+ signals:
+ void onChangeNickRequest();
+
+ private:
+ void updateText();
+ virtual void mousePressEvent(QMouseEvent* event);
+
+ private:
+ enum Mode {
+ ShowNick,
+ ShowJID
+ };
+
+ SettingsProvider* settings;
+ Mode mode;
+ QtElidingLabel* textLabel;
+ QString jid;
+ QString nick;
+ bool isOnline_;
+ };
}
diff --git a/Swift/QtUI/QtPlainChatView.cpp b/Swift/QtUI/QtPlainChatView.cpp
index 3144080..9dc815a 100644
--- a/Swift/QtUI/QtPlainChatView.cpp
+++ b/Swift/QtUI/QtPlainChatView.cpp
@@ -31,402 +31,402 @@ namespace Swift {
QtPlainChatView::QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream)
: QtChatView(window), window_(window), eventStream_(eventStream), idGenerator_(0) {
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
- log_ = new LogTextEdit(this);
- log_->setReadOnly(true);
- log_->setAccessibleName(tr("Chat Messages"));
- mainLayout->addWidget(log_);
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
+ log_ = new LogTextEdit(this);
+ log_->setReadOnly(true);
+ log_->setAccessibleName(tr("Chat Messages"));
+ mainLayout->addWidget(log_);
}
QtPlainChatView::~QtPlainChatView() {
}
QString chatMessageToString(const ChatWindow::ChatMessage& message) {
- QString result;
- foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
- boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
-
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
- text.replace("\n","<br/>");
- result += text;
- continue;
- }
- if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
- QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
- result += "<a href='" + uri + "' >" + uri + "</a>";
- continue;
- }
- if ((emoticonPart = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
- result += P2QSTRING(emoticonPart->alternativeText);
- continue;
- }
- if ((highlightPart = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
- //FIXME: Maybe do something here. Anything, really.
- continue;
- }
- }
- return result;
+ QString result;
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
+ boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
+ boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
+
+ if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
+ text.replace("\n","<br/>");
+ result += text;
+ continue;
+ }
+ if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
+ QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
+ result += "<a href='" + uri + "' >" + uri + "</a>";
+ continue;
+ }
+ if ((emoticonPart = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
+ result += P2QSTRING(emoticonPart->alternativeText);
+ continue;
+ }
+ if ((highlightPart = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
+ //FIXME: Maybe do something here. Anything, really.
+ continue;
+ }
+ }
+ return result;
}
std::string QtPlainChatView::addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) {
- QString text = "<p>";
- if (label) {
- text += P2QSTRING(label->getLabel()) + "<br/>";
- }
- QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
- text += QString(tr("At %1 %2 said:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
- text += chatMessageToString(message);
- text += "</p>";
- log_->append(text);
- const std::string idx = senderIsSelf ? "" : senderName;
- lastMessageLabel_[idx] = label;
- return idx;
+ QString text = "<p>";
+ if (label) {
+ text += P2QSTRING(label->getLabel()) + "<br/>";
+ }
+ QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
+ text += QString(tr("At %1 %2 said:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
+ text += chatMessageToString(message);
+ text += "</p>";
+ log_->append(text);
+ const std::string idx = senderIsSelf ? "" : senderName;
+ lastMessageLabel_[idx] = label;
+ return idx;
}
std::string QtPlainChatView::addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) {
- QString text = "<p>";
- if (label) {
- text += P2QSTRING(label->getLabel()) + "<br/>";
- }
- QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
- text += QString(tr("At %1 <i>%2 ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
- const std::string idx = senderIsSelf ? "" : senderName;
- lastMessageLabel_[idx] = label;
- return idx;
+ QString text = "<p>";
+ if (label) {
+ text += P2QSTRING(label->getLabel()) + "<br/>";
+ }
+ QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
+ text += QString(tr("At %1 <i>%2 ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
+ const std::string idx = senderIsSelf ? "" : senderName;
+ lastMessageLabel_[idx] = label;
+ return idx;
}
std::string QtPlainChatView::addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction /*direction*/)
{
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
- return "";
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
+ return "";
}
void QtPlainChatView::addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction /*direction*/)
{
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::addErrorMessage(const ChatWindow::ChatMessage& message)
{
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time)
{
- QString text = "<p>";
- if (lastMessageLabel_[id]) {
- text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
- }
- QString name = id.empty() ? "you" : P2QSTRING(id);
- text += QString(tr("At %1 %2 corrected the last message to:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
- text += chatMessageToString(message);
- text += "</p>";
- log_->append(text);
+ QString text = "<p>";
+ if (lastMessageLabel_[id]) {
+ text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
+ }
+ QString name = id.empty() ? "you" : P2QSTRING(id);
+ text += QString(tr("At %1 %2 corrected the last message to:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
+ text += chatMessageToString(message);
+ text += "</p>";
+ log_->append(text);
}
void QtPlainChatView::replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time)
{
- QString text = "<p>";
- if (lastMessageLabel_[id]) {
- text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
- }
- QString name = id.empty() ? "you" : P2QSTRING(id);
- text += QString(tr("At %1 %2 corrected the last action to: <i>")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p>";
+ if (lastMessageLabel_[id]) {
+ text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
+ }
+ QString name = id.empty() ? "you" : P2QSTRING(id);
+ text += QString(tr("At %1 %2 corrected the last action to: <i>")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/)
{
- QString text = "<p>The last message was corrected to:<br/>";
- text += chatMessageToString(message);
- text += "</p>";
- log_->append(text);
+ QString text = "<p>The last message was corrected to:<br/>";
+ text += chatMessageToString(message);
+ text += "</p>";
+ log_->append(text);
}
void QtPlainChatView::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& /*id*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) {
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::setAckState(const std::string& /*id*/, ChatWindow::AckState state)
{
- if (state == ChatWindow::Failed) {
- addSystemMessage(ChatWindow::ChatMessage("Message delivery failed due to disconnection from server."), ChatWindow::DefaultDirection);
- }
+ if (state == ChatWindow::Failed) {
+ addSystemMessage(ChatWindow::ChatMessage("Message delivery failed due to disconnection from server."), ChatWindow::DefaultDirection);
+ }
}
std::string QtPlainChatView::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description)
{
- const std::string ftId = "ft" + boost::lexical_cast<std::string>(idGenerator_++);
- const std::string sizeString = formatSize(sizeInBytes);
-
- FileTransfer* transfer;
- if (senderIsSelf) {
- QString description = QInputDialog::getText(this, tr("File transfer description"),
- tr("Description:"), QLineEdit::Normal, "");
- /* NOTE: it is not possible to abort if description is not provided, since we must always return a valid transfer id */
- const std::string descriptionMessage = description.isEmpty() ? "" : (" \"" + Q2PSTRING(description) + "\"");
- const std::string message = std::string() + "Confirm file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
- transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, Q2PSTRING(description), message, true);
- addSystemMessage(ChatWindow::ChatMessage("Preparing to start file transfer..."), ChatWindow::DefaultDirection);
- } else { /* incoming transfer */
- const std::string descriptionMessage = description.empty() ? "" : (" \"" + description + "\"");
- const std::string message = std::string() + "Incoming file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
- transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, "", message, true);
- addSystemMessage("Incoming file transfer from " + senderName + "...", ChatWindow::DefaultDirection);
- }
-
- fileTransfers_[ftId] = transfer;
- layout()->addWidget(transfer->dialog_);
-
- return ftId;
+ const std::string ftId = "ft" + boost::lexical_cast<std::string>(idGenerator_++);
+ const std::string sizeString = formatSize(sizeInBytes);
+
+ FileTransfer* transfer;
+ if (senderIsSelf) {
+ QString description = QInputDialog::getText(this, tr("File transfer description"),
+ tr("Description:"), QLineEdit::Normal, "");
+ /* NOTE: it is not possible to abort if description is not provided, since we must always return a valid transfer id */
+ const std::string descriptionMessage = description.isEmpty() ? "" : (" \"" + Q2PSTRING(description) + "\"");
+ const std::string message = std::string() + "Confirm file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
+ transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, Q2PSTRING(description), message, true);
+ addSystemMessage(ChatWindow::ChatMessage("Preparing to start file transfer..."), ChatWindow::DefaultDirection);
+ } else { /* incoming transfer */
+ const std::string descriptionMessage = description.empty() ? "" : (" \"" + description + "\"");
+ const std::string message = std::string() + "Incoming file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
+ transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, "", message, true);
+ addSystemMessage("Incoming file transfer from " + senderName + "...", ChatWindow::DefaultDirection);
+ }
+
+ fileTransfers_[ftId] = transfer;
+ layout()->addWidget(transfer->dialog_);
+
+ return ftId;
}
void QtPlainChatView::setFileTransferProgress(std::string id, const int percentageDone)
{
- FileTransferMap::iterator transfer = fileTransfers_.find(id);
- if (transfer != fileTransfers_.end()) {
- transfer->second->bar_->setValue(percentageDone);
- }
+ FileTransferMap::iterator transfer = fileTransfers_.find(id);
+ if (transfer != fileTransfers_.end()) {
+ transfer->second->bar_->setValue(percentageDone);
+ }
}
void QtPlainChatView::setFileTransferStatus(std::string id, const ChatWindow::FileTransferState state, const std::string& msg)
{
- FileTransferMap::iterator transferIter = fileTransfers_.find(id);
- if (transferIter == fileTransfers_.end()) {
- return;
- }
-
- /* store the layout index so we can restore it to the same location */
- FileTransfer* oldTransfer = transferIter->second;
- const int layoutIndex = layout()->indexOf(oldTransfer->dialog_);
- layout()->removeWidget(oldTransfer->dialog_);
- const std::string &label = (!msg.empty() ? msg : oldTransfer->message_);
- FileTransfer* transfer = new FileTransfer(this, oldTransfer->senderIsSelf_, oldTransfer->ftId_, oldTransfer->filename_, state, oldTransfer->description_, label, false);
- fileTransfers_[oldTransfer->ftId_] = transfer; /* replace the transfer object for this file id */
- delete oldTransfer;
-
- /* insert the new dialog at the old position in the layout list */
- QBoxLayout* parentLayout = dynamic_cast<QBoxLayout*>(layout());
- assert(parentLayout);
- parentLayout->insertWidget(layoutIndex, transfer->dialog_);
-
- /* log the transfer end result as a system message */
- if (state == ChatWindow::Finished) {
- addSystemMessage(ChatWindow::ChatMessage("The file transfer completed successfully."), ChatWindow::DefaultDirection);
- } else if (state == ChatWindow::Canceled) {
- addSystemMessage(ChatWindow::ChatMessage("The file transfer was canceled."), ChatWindow::DefaultDirection);
- } else if (state == ChatWindow::FTFailed) {
- addSystemMessage(ChatWindow::ChatMessage("The file transfer failed."), ChatWindow::DefaultDirection);
- }
+ FileTransferMap::iterator transferIter = fileTransfers_.find(id);
+ if (transferIter == fileTransfers_.end()) {
+ return;
+ }
+
+ /* store the layout index so we can restore it to the same location */
+ FileTransfer* oldTransfer = transferIter->second;
+ const int layoutIndex = layout()->indexOf(oldTransfer->dialog_);
+ layout()->removeWidget(oldTransfer->dialog_);
+ const std::string &label = (!msg.empty() ? msg : oldTransfer->message_);
+ FileTransfer* transfer = new FileTransfer(this, oldTransfer->senderIsSelf_, oldTransfer->ftId_, oldTransfer->filename_, state, oldTransfer->description_, label, false);
+ fileTransfers_[oldTransfer->ftId_] = transfer; /* replace the transfer object for this file id */
+ delete oldTransfer;
+
+ /* insert the new dialog at the old position in the layout list */
+ QBoxLayout* parentLayout = dynamic_cast<QBoxLayout*>(layout());
+ assert(parentLayout);
+ parentLayout->insertWidget(layoutIndex, transfer->dialog_);
+
+ /* log the transfer end result as a system message */
+ if (state == ChatWindow::Finished) {
+ addSystemMessage(ChatWindow::ChatMessage("The file transfer completed successfully."), ChatWindow::DefaultDirection);
+ } else if (state == ChatWindow::Canceled) {
+ addSystemMessage(ChatWindow::ChatMessage("The file transfer was canceled."), ChatWindow::DefaultDirection);
+ } else if (state == ChatWindow::FTFailed) {
+ addSystemMessage(ChatWindow::ChatMessage("The file transfer failed."), ChatWindow::DefaultDirection);
+ }
}
void QtPlainChatView::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& /*reason*/, const std::string& password, bool /*direct*/, bool isImpromptu, bool isContinuation)
{
- PopupDialog *invite = new PopupDialog(this);
+ PopupDialog *invite = new PopupDialog(this);
- QLabel* statusLabel = new QLabel;
- std::string msg = senderName + " has invited you to join " + jid.toString() + "...";
- statusLabel->setText(P2QSTRING(msg));
- invite->layout_->addWidget(statusLabel);
- invite->layout_->addWidget(new QLabel); /* padding */
+ QLabel* statusLabel = new QLabel;
+ std::string msg = senderName + " has invited you to join " + jid.toString() + "...";
+ statusLabel->setText(P2QSTRING(msg));
+ invite->layout_->addWidget(statusLabel);
+ invite->layout_->addWidget(new QLabel); /* padding */
- AcceptMUCInviteAction* accept = new AcceptMUCInviteAction(invite, "Accept", jid, senderName, password, isImpromptu, isContinuation);
- connect(accept, SIGNAL(clicked()), SLOT(acceptMUCInvite()));
- invite->layout_->addWidget(accept);
+ AcceptMUCInviteAction* accept = new AcceptMUCInviteAction(invite, "Accept", jid, senderName, password, isImpromptu, isContinuation);
+ connect(accept, SIGNAL(clicked()), SLOT(acceptMUCInvite()));
+ invite->layout_->addWidget(accept);
- AcceptMUCInviteAction* reject = new AcceptMUCInviteAction(invite, "Reject", jid, senderName, password, isImpromptu, isContinuation);
- connect(reject, SIGNAL(clicked()), SLOT(rejectMUCInvite()));
- invite->layout_->addWidget(reject);
- statusLabel->setText(P2QSTRING(msg));
+ AcceptMUCInviteAction* reject = new AcceptMUCInviteAction(invite, "Reject", jid, senderName, password, isImpromptu, isContinuation);
+ connect(reject, SIGNAL(clicked()), SLOT(rejectMUCInvite()));
+ invite->layout_->addWidget(reject);
+ statusLabel->setText(P2QSTRING(msg));
- layout()->addWidget(invite->dialog_);
+ layout()->addWidget(invite->dialog_);
- addSystemMessage(ChatWindow::ChatMessage(msg), ChatWindow::DefaultDirection);
+ addSystemMessage(ChatWindow::ChatMessage(msg), ChatWindow::DefaultDirection);
}
void QtPlainChatView::scrollToBottom()
{
- log_->ensureCursorVisible();
- log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum());
+ log_->ensureCursorVisible();
+ log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum());
}
void QtPlainChatView::fileTransferAccept()
{
- FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
- if (!action) {
- return;
- }
-
- FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
- if (transferIter == fileTransfers_.end()) {
- return;
- }
-
- FileTransfer* transfer = transferIter->second;
-
- const std::string message = transfer->message_;
-
- if (transfer->senderIsSelf_) { /* if we are the sender, kick of the transfer */
- window_->onFileTransferStart(transfer->ftId_, transfer->description_);
- } else { /* ask the user where to save the file first */
- QString path = QFileDialog::getSaveFileName(this, tr("Save File"), P2QSTRING(transfer->filename_));
- if (path.isEmpty()) {
- fileTransferReject(); /* because the user did not select a desintation path */
- return;
- }
- window_->onFileTransferAccept(transfer->ftId_, Q2PSTRING(path));
- }
-
- setFileTransferStatus(transfer->ftId_, ChatWindow::Negotiating, message);
+ FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
+ if (!action) {
+ return;
+ }
+
+ FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
+ if (transferIter == fileTransfers_.end()) {
+ return;
+ }
+
+ FileTransfer* transfer = transferIter->second;
+
+ const std::string message = transfer->message_;
+
+ if (transfer->senderIsSelf_) { /* if we are the sender, kick of the transfer */
+ window_->onFileTransferStart(transfer->ftId_, transfer->description_);
+ } else { /* ask the user where to save the file first */
+ QString path = QFileDialog::getSaveFileName(this, tr("Save File"), P2QSTRING(transfer->filename_));
+ if (path.isEmpty()) {
+ fileTransferReject(); /* because the user did not select a desintation path */
+ return;
+ }
+ window_->onFileTransferAccept(transfer->ftId_, Q2PSTRING(path));
+ }
+
+ setFileTransferStatus(transfer->ftId_, ChatWindow::Negotiating, message);
}
void QtPlainChatView::fileTransferReject()
{
- FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
- if (action) {
- window_->onFileTransferCancel(action->id_);
- fileTransferFinish();
- }
+ FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
+ if (action) {
+ window_->onFileTransferCancel(action->id_);
+ fileTransferFinish();
+ }
}
void QtPlainChatView::fileTransferFinish()
{
- FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
- if (action) {
- FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
- if (transferIter != fileTransfers_.end()) {
- delete transferIter->second; /* cause the dialog to close */
- fileTransfers_.erase(transferIter);
- }
- }
+ FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
+ if (action) {
+ FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
+ if (transferIter != fileTransfers_.end()) {
+ delete transferIter->second; /* cause the dialog to close */
+ fileTransfers_.erase(transferIter);
+ }
+ }
}
void QtPlainChatView::acceptMUCInvite()
{
- AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
- if (action) {
- eventStream_->send(boost::make_shared<JoinMUCUIEvent>(action->jid_.toString(), action->password_, boost::optional<std::string>(), false, false, action->isImpromptu_, action->isContinuation_));
- delete action->parent_;
- }
+ AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
+ if (action) {
+ eventStream_->send(boost::make_shared<JoinMUCUIEvent>(action->jid_.toString(), action->password_, boost::optional<std::string>(), false, false, action->isImpromptu_, action->isContinuation_));
+ delete action->parent_;
+ }
}
void QtPlainChatView::rejectMUCInvite()
{
- AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
- if (action) {
- /* NOTE: no action required to reject an invite? */
- delete action->parent_;
- }
+ AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
+ if (action) {
+ /* NOTE: no action required to reject an invite? */
+ delete action->parent_;
+ }
}
QtPlainChatView::FileTransfer::FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string &desc, const std::string& msg, bool initializing)
: PopupDialog(parent), bar_(0), senderIsSelf_(senderIsSelf), ftId_(ftId), filename_(filename), description_(desc), message_(msg), initializing_(initializing)
{
- QHBoxLayout* layout = new QHBoxLayout;
- QLabel* statusLabel = new QLabel;
- layout_->addWidget(statusLabel);
- layout_->addWidget(new QLabel); /* padding */
-
- if (initializing_) {
- FileTransfer::Action* accept = new FileTransfer::Action(senderIsSelf?"Confirm":"Accept", ftId);
- parent->connect(accept, SIGNAL(clicked()), SLOT(fileTransferAccept()));
- layout_->addWidget(accept);
- FileTransfer::Action* reject = new FileTransfer::Action(senderIsSelf?"Cancel":"Reject", ftId);
- parent->connect(reject, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(reject);
- statusLabel->setText(P2QSTRING(msg));
- return;
- }
-
- std::string status = msg;
-
- switch (state) {
- case ChatWindow::Initialisation: {
- status = "Preparing to send <i>"+ filename + "</i>...";
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::WaitingForAccept: {
- status = "Waiting for user to accept <i>" + filename + "</i>...";
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::Negotiating: {
- status = "Preparing to transfer <i>" + filename + "</i>...";
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::Transferring: {
- status = "Transferring <i>" + filename + "</i>...";
- bar_ = new QProgressBar;
- bar_->setRange(0, 100);
- bar_->setValue(0);
- layout->addWidget(bar_);
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::Canceled: {
- status = "File <i>" + filename + "</i> was canceled.";
- FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
- parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
- layout_->addWidget(finish);
- break;
- }
- case ChatWindow::Finished: {
- status = "File <i>" + filename + "</i> was transfered successfully.";
- FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
- parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
- layout_->addWidget(finish);
- break;
- }
- case ChatWindow::FTFailed: {
- status = "File transfer failed: <i>" + filename + "</i>";
- FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
- parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
- layout_->addWidget(finish);
- break;
- }
- }
-
- statusLabel->setText(P2QSTRING(status));
+ QHBoxLayout* layout = new QHBoxLayout;
+ QLabel* statusLabel = new QLabel;
+ layout_->addWidget(statusLabel);
+ layout_->addWidget(new QLabel); /* padding */
+
+ if (initializing_) {
+ FileTransfer::Action* accept = new FileTransfer::Action(senderIsSelf?"Confirm":"Accept", ftId);
+ parent->connect(accept, SIGNAL(clicked()), SLOT(fileTransferAccept()));
+ layout_->addWidget(accept);
+ FileTransfer::Action* reject = new FileTransfer::Action(senderIsSelf?"Cancel":"Reject", ftId);
+ parent->connect(reject, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(reject);
+ statusLabel->setText(P2QSTRING(msg));
+ return;
+ }
+
+ std::string status = msg;
+
+ switch (state) {
+ case ChatWindow::Initialisation: {
+ status = "Preparing to send <i>"+ filename + "</i>...";
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::WaitingForAccept: {
+ status = "Waiting for user to accept <i>" + filename + "</i>...";
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::Negotiating: {
+ status = "Preparing to transfer <i>" + filename + "</i>...";
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::Transferring: {
+ status = "Transferring <i>" + filename + "</i>...";
+ bar_ = new QProgressBar;
+ bar_->setRange(0, 100);
+ bar_->setValue(0);
+ layout->addWidget(bar_);
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::Canceled: {
+ status = "File <i>" + filename + "</i> was canceled.";
+ FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
+ parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
+ layout_->addWidget(finish);
+ break;
+ }
+ case ChatWindow::Finished: {
+ status = "File <i>" + filename + "</i> was transfered successfully.";
+ FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
+ parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
+ layout_->addWidget(finish);
+ break;
+ }
+ case ChatWindow::FTFailed: {
+ status = "File transfer failed: <i>" + filename + "</i>";
+ FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
+ parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
+ layout_->addWidget(finish);
+ break;
+ }
+ }
+
+ statusLabel->setText(P2QSTRING(status));
}
void QtPlainChatView::LogTextEdit::contextMenuEvent(QContextMenuEvent *event)
{
- QMenu *menu = createStandardContextMenu();
- menu->exec(event->globalPos());
- delete menu;
+ QMenu *menu = createStandardContextMenu();
+ menu->exec(event->globalPos());
+ delete menu;
}
}
diff --git a/Swift/QtUI/QtPlainChatView.h b/Swift/QtUI/QtPlainChatView.h
index fc293ff..cd6ab7e 100644
--- a/Swift/QtUI/QtPlainChatView.h
+++ b/Swift/QtUI/QtPlainChatView.h
@@ -23,112 +23,112 @@ class QTextEdit;
class QProgressBar;
namespace Swift {
- class HighlightAction;
- class SecurityLabel;
-
- class QtPlainChatView : public QtChatView {
- Q_OBJECT
- public:
- QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream);
- virtual ~QtPlainChatView();
-
- /** Add message to window.
- * @return id of added message (for acks).
- */
- virtual std::string addMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
- /** Adds action to window.
- * @return id of added message (for acks);
- */
- virtual std::string addAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
-
- virtual std::string addSystemMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
- virtual void addPresenceMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
- virtual void addErrorMessage(const ChatWindow::ChatMessage& /*message*/);
-
- virtual void replaceMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
- virtual void replaceWithAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
- virtual void replaceLastMessage(const ChatWindow::ChatMessage& /*message*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
- virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
- virtual void setAckState(const std::string& /*id*/, ChatWindow::AckState /*state*/);
-
- virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/, const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/);
- virtual void setFileTransferProgress(std::string, const int /*percentageDone*/);
- virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState /*state*/, const std::string& /*msg*/ = "");
- virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool /*direct*/, bool /*isImpromptu*/, bool /*isContinuation*/);
- virtual std::string addWhiteboardRequest(const QString& /*contact*/, bool /*senderIsSelf*/) {return "";};
- virtual void setWhiteboardSessionStatus(const std::string& /*id*/, const ChatWindow::WhiteboardSessionState /*state*/) {};
- virtual void setMessageReceiptState(const std::string& /*id*/, ChatWindow::ReceiptState /*state*/) {};
-
- virtual void showEmoticons(bool /*show*/) {};
- virtual void addLastSeenLine() {};
-
- public slots:
- virtual void resizeFont(int /*fontSizeSteps*/) {};
- virtual void scrollToBottom();
- virtual void handleKeyPressEvent(QKeyEvent* /*event*/) {};
- virtual void fileTransferAccept();
- virtual void fileTransferReject();
- virtual void fileTransferFinish();
- virtual void acceptMUCInvite();
- virtual void rejectMUCInvite();
-
- private:
- struct PopupDialog {
- PopupDialog(QtPlainChatView* parent) {
- dialog_ = new QFrame(parent);
- dialog_->setFrameShape(QFrame::Panel);
- dialog_->setFrameShadow(QFrame::Raised);
- layout_ = new QHBoxLayout;
- dialog_->setLayout(layout_);
- }
- virtual ~PopupDialog() {
- delete dialog_;
- }
- QFrame* dialog_;
- QHBoxLayout* layout_;
- };
-
- struct AcceptMUCInviteAction : public QPushButton {
- AcceptMUCInviteAction(PopupDialog* parent, const std::string& text, const JID& jid, const std::string& senderName, const std::string& password, bool isImpromptu, bool isContinuation)
- : QPushButton(P2QSTRING(text)), parent_(parent), jid_(jid), senderName_(senderName), password_(password), isImpromptu_(isImpromptu), isContinuation_(isContinuation) {}
- PopupDialog *parent_;
- JID jid_;
- std::string senderName_;
- std::string password_;
- bool isImpromptu_;
- bool isContinuation_;
- };
-
- struct FileTransfer : public PopupDialog {
- struct Action : QPushButton {
- Action(const std::string& text, const std::string& id)
- : QPushButton(P2QSTRING(text)), id_(id) {}
- std::string id_;
- };
- FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string& desc, const std::string& msg, bool initializing);
- QProgressBar* bar_;
- bool senderIsSelf_;
- std::string ftId_;
- std::string filename_;
- std::string description_;
- std::string message_;
- bool initializing_;
- };
-
- class LogTextEdit : public QTextEdit {
- public:
- LogTextEdit(QWidget* parent) : QTextEdit(parent) {}
- virtual ~LogTextEdit() {}
- virtual void contextMenuEvent(QContextMenuEvent *event);
- };
-
- typedef std::map<std::string, FileTransfer*> FileTransferMap;
- QtChatWindow* window_;
- UIEventStream* eventStream_;
- LogTextEdit* log_;
- FileTransferMap fileTransfers_;
- std::map<std::string, boost::shared_ptr<SecurityLabel> > lastMessageLabel_;
- int idGenerator_;
-
- };
+ class HighlightAction;
+ class SecurityLabel;
+
+ class QtPlainChatView : public QtChatView {
+ Q_OBJECT
+ public:
+ QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream);
+ virtual ~QtPlainChatView();
+
+ /** Add message to window.
+ * @return id of added message (for acks).
+ */
+ virtual std::string addMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
+ /** Adds action to window.
+ * @return id of added message (for acks);
+ */
+ virtual std::string addAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
+
+ virtual std::string addSystemMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
+ virtual void addPresenceMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
+ virtual void addErrorMessage(const ChatWindow::ChatMessage& /*message*/);
+
+ virtual void replaceMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
+ virtual void replaceWithAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
+ virtual void replaceLastMessage(const ChatWindow::ChatMessage& /*message*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
+ virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
+ virtual void setAckState(const std::string& /*id*/, ChatWindow::AckState /*state*/);
+
+ virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/, const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/);
+ virtual void setFileTransferProgress(std::string, const int /*percentageDone*/);
+ virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState /*state*/, const std::string& /*msg*/ = "");
+ virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool /*direct*/, bool /*isImpromptu*/, bool /*isContinuation*/);
+ virtual std::string addWhiteboardRequest(const QString& /*contact*/, bool /*senderIsSelf*/) {return "";};
+ virtual void setWhiteboardSessionStatus(const std::string& /*id*/, const ChatWindow::WhiteboardSessionState /*state*/) {};
+ virtual void setMessageReceiptState(const std::string& /*id*/, ChatWindow::ReceiptState /*state*/) {};
+
+ virtual void showEmoticons(bool /*show*/) {};
+ virtual void addLastSeenLine() {};
+
+ public slots:
+ virtual void resizeFont(int /*fontSizeSteps*/) {};
+ virtual void scrollToBottom();
+ virtual void handleKeyPressEvent(QKeyEvent* /*event*/) {};
+ virtual void fileTransferAccept();
+ virtual void fileTransferReject();
+ virtual void fileTransferFinish();
+ virtual void acceptMUCInvite();
+ virtual void rejectMUCInvite();
+
+ private:
+ struct PopupDialog {
+ PopupDialog(QtPlainChatView* parent) {
+ dialog_ = new QFrame(parent);
+ dialog_->setFrameShape(QFrame::Panel);
+ dialog_->setFrameShadow(QFrame::Raised);
+ layout_ = new QHBoxLayout;
+ dialog_->setLayout(layout_);
+ }
+ virtual ~PopupDialog() {
+ delete dialog_;
+ }
+ QFrame* dialog_;
+ QHBoxLayout* layout_;
+ };
+
+ struct AcceptMUCInviteAction : public QPushButton {
+ AcceptMUCInviteAction(PopupDialog* parent, const std::string& text, const JID& jid, const std::string& senderName, const std::string& password, bool isImpromptu, bool isContinuation)
+ : QPushButton(P2QSTRING(text)), parent_(parent), jid_(jid), senderName_(senderName), password_(password), isImpromptu_(isImpromptu), isContinuation_(isContinuation) {}
+ PopupDialog *parent_;
+ JID jid_;
+ std::string senderName_;
+ std::string password_;
+ bool isImpromptu_;
+ bool isContinuation_;
+ };
+
+ struct FileTransfer : public PopupDialog {
+ struct Action : QPushButton {
+ Action(const std::string& text, const std::string& id)
+ : QPushButton(P2QSTRING(text)), id_(id) {}
+ std::string id_;
+ };
+ FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string& desc, const std::string& msg, bool initializing);
+ QProgressBar* bar_;
+ bool senderIsSelf_;
+ std::string ftId_;
+ std::string filename_;
+ std::string description_;
+ std::string message_;
+ bool initializing_;
+ };
+
+ class LogTextEdit : public QTextEdit {
+ public:
+ LogTextEdit(QWidget* parent) : QTextEdit(parent) {}
+ virtual ~LogTextEdit() {}
+ virtual void contextMenuEvent(QContextMenuEvent *event);
+ };
+
+ typedef std::map<std::string, FileTransfer*> FileTransferMap;
+ QtChatWindow* window_;
+ UIEventStream* eventStream_;
+ LogTextEdit* log_;
+ FileTransferMap fileTransfers_;
+ std::map<std::string, boost::shared_ptr<SecurityLabel> > lastMessageLabel_;
+ int idGenerator_;
+
+ };
}
diff --git a/Swift/QtUI/QtProfileWindow.cpp b/Swift/QtUI/QtProfileWindow.cpp
index 8b4b044..461ea38 100644
--- a/Swift/QtUI/QtProfileWindow.cpp
+++ b/Swift/QtUI/QtProfileWindow.cpp
@@ -25,143 +25,143 @@
namespace Swift {
QtProfileWindow::QtProfileWindow() :
- QWidget(),
- ui(new Ui::QtProfileWindow) {
- ui->setupUi(this);
+ QWidget(),
+ ui(new Ui::QtProfileWindow) {
+ ui->setupUi(this);
- ui->statusLabel->setText(tr("Retrieving profile information for this user."));
- ui->statusLabel->setVisible(false);
+ ui->statusLabel->setText(tr("Retrieving profile information for this user."));
+ ui->statusLabel->setVisible(false);
- ui->emptyLabel->setText(tr("No profile information is available for this user."));
- ui->emptyLabel->setVisible(false);
+ ui->emptyLabel->setText(tr("No profile information is available for this user."));
+ ui->emptyLabel->setVisible(false);
- new QShortcut(QKeySequence::Close, this, SLOT(close()));
- ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
- connect(ui->savePushButton, SIGNAL(clicked()), SLOT(handleSave()));
- setEditable(false);
- setAttribute(Qt::WA_DeleteOnClose);
- setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
+ new QShortcut(QKeySequence::Close, this, SLOT(close()));
+ ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
+ connect(ui->savePushButton, SIGNAL(clicked()), SLOT(handleSave()));
+ setEditable(false);
+ setAttribute(Qt::WA_DeleteOnClose);
+ setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
- adjustSizeTimer.setSingleShot(true);
- connect(&adjustSizeTimer, SIGNAL(timeout()), SLOT(handleAdjustSizeTimeout()));
+ adjustSizeTimer.setSingleShot(true);
+ connect(&adjustSizeTimer, SIGNAL(timeout()), SLOT(handleAdjustSizeTimeout()));
}
QtProfileWindow::~QtProfileWindow() {
- delete ui;
+ delete ui;
}
void QtProfileWindow::setJID(const JID& jid) {
- this->jid = jid;
- updateTitle();
+ this->jid = jid;
+ updateTitle();
}
void QtProfileWindow::setVCard(VCard::ref vcard) {
- ui->vcard->setVCard(vcard);
- if (vcard->isEmpty()) {
- ui->vcard->setVisible(false);
- ui->emptyLabel->setVisible(true);
- } else {
- ui->vcard->setVisible(true);
- ui->emptyLabel->setVisible(false);
- }
- updateWindowSize();
+ ui->vcard->setVCard(vcard);
+ if (vcard->isEmpty()) {
+ ui->vcard->setVisible(false);
+ ui->emptyLabel->setVisible(true);
+ } else {
+ ui->vcard->setVisible(true);
+ ui->emptyLabel->setVisible(false);
+ }
+ updateWindowSize();
}
void QtProfileWindow::setEnabled(bool b) {
- ui->vcard->setEnabled(b);
- ui->savePushButton->setEnabled(b);
+ ui->vcard->setEnabled(b);
+ ui->savePushButton->setEnabled(b);
}
void QtProfileWindow::setEditable(bool b) {
- ui->throbberLabel->setVisible(b);
- ui->errorLabel->setVisible(b);
- ui->savePushButton->setVisible(b);
- ui->vcard->setEditable(b);
- updateTitle();
- updateWindowSize();
+ ui->throbberLabel->setVisible(b);
+ ui->errorLabel->setVisible(b);
+ ui->savePushButton->setVisible(b);
+ ui->vcard->setEditable(b);
+ updateTitle();
+ updateWindowSize();
}
void QtProfileWindow::setProcessing(bool processing) {
- if (processing) {
- ui->throbberLabel->movie()->start();
- ui->throbberLabel->show();
- ui->statusLabel->setVisible(true);
- ui->vcard->setVisible(false);
- }
- else {
- ui->throbberLabel->hide();
- ui->throbberLabel->movie()->stop();
- ui->statusLabel->setVisible(false);
- ui->vcard->setVisible(true);
- }
+ if (processing) {
+ ui->throbberLabel->movie()->start();
+ ui->throbberLabel->show();
+ ui->statusLabel->setVisible(true);
+ ui->vcard->setVisible(false);
+ }
+ else {
+ ui->throbberLabel->hide();
+ ui->throbberLabel->movie()->stop();
+ ui->statusLabel->setVisible(false);
+ ui->vcard->setVisible(true);
+ }
}
void QtProfileWindow::setError(const std::string& error) {
- if (!error.empty()) {
- ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
- }
- else {
- ui->errorLabel->setText("");
- }
+ if (!error.empty()) {
+ ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
+ }
+ else {
+ ui->errorLabel->setText("");
+ }
}
void QtProfileWindow::show() {
- QWidget::showNormal();
- QWidget::activateWindow();
- QWidget::raise();
+ QWidget::showNormal();
+ QWidget::activateWindow();
+ QWidget::raise();
}
void QtProfileWindow::hide() {
- QWidget::hide();
+ QWidget::hide();
}
QSize QtProfileWindow::sizeHint() const {
- return QWidget::sizeHint();
+ return QWidget::sizeHint();
}
void QtProfileWindow::updateTitle() {
- QString jidString;
- if (jid.isValid()) {
- jidString = QString(" ( %1 )").arg(P2QSTRING(jid.toString()));
- }
+ QString jidString;
+ if (jid.isValid()) {
+ jidString = QString(" ( %1 )").arg(P2QSTRING(jid.toString()));
+ }
- if (ui->vcard->isEditable()) {
- setWindowTitle(tr("Edit Profile") + jidString);
- } else {
- setWindowTitle(tr("Show Profile") + jidString);
- }
+ if (ui->vcard->isEditable()) {
+ setWindowTitle(tr("Edit Profile") + jidString);
+ } else {
+ setWindowTitle(tr("Show Profile") + jidString);
+ }
}
void QtProfileWindow::updateWindowSize() {
- // Delay resizing to the end of the event loop, because Qt calculates the correct layout asynchronously.
- // Qt will post LayoutRequests for widgets on the event loop on show and widgets will recaluclate their
- // layout as they process these events.
- // We use the complete and correct size hint from the freshly calculated layout by delaying execution of
- // the resize code to the end of Qt's event loop.
- if (!adjustSizeTimer.isActive()) {
- adjustSizeTimer.start(0);
- }
+ // Delay resizing to the end of the event loop, because Qt calculates the correct layout asynchronously.
+ // Qt will post LayoutRequests for widgets on the event loop on show and widgets will recaluclate their
+ // layout as they process these events.
+ // We use the complete and correct size hint from the freshly calculated layout by delaying execution of
+ // the resize code to the end of Qt's event loop.
+ if (!adjustSizeTimer.isActive()) {
+ adjustSizeTimer.start(0);
+ }
}
void QtProfileWindow::closeEvent(QCloseEvent* event) {
- event->accept();
- onWindowAboutToBeClosed(jid);
+ event->accept();
+ onWindowAboutToBeClosed(jid);
}
void QtProfileWindow::handleSave() {
- onVCardChangeRequest(ui->vcard->getVCard());
+ onVCardChangeRequest(ui->vcard->getVCard());
}
void QtProfileWindow::handleAdjustSizeTimeout() {
- // Force recaluclation of all layout geometry in children widgets.
- // This is required on Windows to have the correct size even on first show.
- QList<QWidget *> children = findChildren<QWidget*>();
- foreach(QWidget* child, children) {
- child->updateGeometry();
- }
-
- updateGeometry();
- adjustSize();
+ // Force recaluclation of all layout geometry in children widgets.
+ // This is required on Windows to have the correct size even on first show.
+ QList<QWidget *> children = findChildren<QWidget*>();
+ foreach(QWidget* child, children) {
+ child->updateGeometry();
+ }
+
+ updateGeometry();
+ adjustSize();
}
}
diff --git a/Swift/QtUI/QtProfileWindow.h b/Swift/QtUI/QtProfileWindow.h
index 0821444..7315807 100644
--- a/Swift/QtUI/QtProfileWindow.h
+++ b/Swift/QtUI/QtProfileWindow.h
@@ -20,44 +20,44 @@
#include <Swift/Controllers/UIInterfaces/ProfileWindow.h>
namespace Ui {
- class QtProfileWindow;
+ class QtProfileWindow;
}
namespace Swift {
class QtProfileWindow : public QWidget, public ProfileWindow {
- Q_OBJECT
+ Q_OBJECT
- public:
- QtProfileWindow();
- virtual ~QtProfileWindow();
+ public:
+ QtProfileWindow();
+ virtual ~QtProfileWindow();
- virtual void setJID(const JID& jid);
- virtual void setVCard(VCard::ref vcard);
+ virtual void setJID(const JID& jid);
+ virtual void setVCard(VCard::ref vcard);
- virtual void setEnabled(bool b);
- virtual void setProcessing(bool processing);
- virtual void setError(const std::string& error);
- virtual void setEditable(bool b);
+ virtual void setEnabled(bool b);
+ virtual void setProcessing(bool processing);
+ virtual void setError(const std::string& error);
+ virtual void setEditable(bool b);
- virtual void show();
- virtual void hide();
+ virtual void show();
+ virtual void hide();
- virtual QSize sizeHint() const;
+ virtual QSize sizeHint() const;
- private:
- void updateTitle();
- void updateWindowSize();
- virtual void closeEvent(QCloseEvent* event);
+ private:
+ void updateTitle();
+ void updateWindowSize();
+ virtual void closeEvent(QCloseEvent* event);
- private slots:
- void handleSave();
- void handleAdjustSizeTimeout();
+ private slots:
+ void handleSave();
+ void handleAdjustSizeTimeout();
- private:
- Ui::QtProfileWindow* ui;
- JID jid;
- QTimer adjustSizeTimer;
+ private:
+ Ui::QtProfileWindow* ui;
+ JID jid;
+ QTimer adjustSizeTimer;
};
}
diff --git a/Swift/QtUI/QtResourceHelper.cpp b/Swift/QtUI/QtResourceHelper.cpp
index f76c438..a802b19 100644
--- a/Swift/QtUI/QtResourceHelper.cpp
+++ b/Swift/QtUI/QtResourceHelper.cpp
@@ -9,16 +9,16 @@
namespace Swift {
QString statusShowTypeToIconPath(StatusShow::Type type) {
- QString iconString;
- switch (type) {
- case StatusShow::Online: iconString = "online";break;
- case StatusShow::Away: iconString = "away";break;
- case StatusShow::XA: iconString = "away";break;
- case StatusShow::FFC: iconString = "online";break;
- case StatusShow::DND: iconString = "dnd";break;
- case StatusShow::None: iconString = "offline";break;
- }
- return QString(":/icons/%1.png").arg(iconString);
+ QString iconString;
+ switch (type) {
+ case StatusShow::Online: iconString = "online";break;
+ case StatusShow::Away: iconString = "away";break;
+ case StatusShow::XA: iconString = "away";break;
+ case StatusShow::FFC: iconString = "online";break;
+ case StatusShow::DND: iconString = "dnd";break;
+ case StatusShow::None: iconString = "offline";break;
+ }
+ return QString(":/icons/%1.png").arg(iconString);
}
}
diff --git a/Swift/QtUI/QtRosterHeader.cpp b/Swift/QtUI/QtRosterHeader.cpp
index 4783a64..f8a4cdb 100644
--- a/Swift/QtUI/QtRosterHeader.cpp
+++ b/Swift/QtUI/QtRosterHeader.cpp
@@ -28,112 +28,112 @@
namespace Swift {
QtRosterHeader::QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent) : QWidget(parent), statusEdit_(NULL) {
- QHBoxLayout* topLayout = new QHBoxLayout();
- topLayout->setSpacing(3);
- topLayout->setContentsMargins(4,4,4,4);
- setLayout(topLayout);
- setMinimumHeight(50);
- setMaximumHeight(50);
-
- avatarLabel_ = new QtClickableLabel(this);
- avatarLabel_->setMinimumSize(avatarSize_, avatarSize_);
- avatarLabel_->setMaximumSize(avatarSize_, avatarSize_);
- avatarLabel_->setAlignment(Qt::AlignCenter);
- setAvatar(":/icons/avatar.png");
- avatarLabel_->setScaledContents(false);
- topLayout->addWidget(avatarLabel_);
- connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
-
- QVBoxLayout* rightLayout = new QVBoxLayout();
- rightLayout->setSpacing(4);
- rightLayout->setContentsMargins(4,0,0,0);
- topLayout->addLayout(rightLayout);
-
- QHBoxLayout* nameAndSecurityLayout = new QHBoxLayout();
- nameAndSecurityLayout->setContentsMargins(4,0,0,0);
-
- nameWidget_ = new QtNameWidget(settings, this);
- connect(nameWidget_, SIGNAL(onChangeNickRequest()), this, SIGNAL(onEditProfileRequest()));
- nameAndSecurityLayout->addWidget(nameWidget_);
-
- securityInfoButton_ = new QToolButton(this);
- securityInfoButton_->setStyleSheet("QToolButton { border: none; } QToolButton:hover { border: 1px solid #bebebe; } QToolButton:pressed { border: 1px solid #757575; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777777, stop: 1 #d4d4d4);}");
- //securityInfoButton_->setAutoRaise(true);
- securityInfoButton_->setIcon(QIcon(":/icons/lock.png"));
- securityInfoButton_->setToolTip(tr("Connection is secured"));
- connect(securityInfoButton_, SIGNAL(clicked()), this, SIGNAL(onShowCertificateInfo()));
- nameAndSecurityLayout->addWidget(securityInfoButton_);
-
- rightLayout->addLayout(nameAndSecurityLayout);
-
- statusWidget_ = new QtStatusWidget(statusCache, this);
- connect(statusWidget_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleChangeStatusRequest(StatusShow::Type, const QString&)));
- rightLayout->addWidget(statusWidget_);
-
- show();
+ QHBoxLayout* topLayout = new QHBoxLayout();
+ topLayout->setSpacing(3);
+ topLayout->setContentsMargins(4,4,4,4);
+ setLayout(topLayout);
+ setMinimumHeight(50);
+ setMaximumHeight(50);
+
+ avatarLabel_ = new QtClickableLabel(this);
+ avatarLabel_->setMinimumSize(avatarSize_, avatarSize_);
+ avatarLabel_->setMaximumSize(avatarSize_, avatarSize_);
+ avatarLabel_->setAlignment(Qt::AlignCenter);
+ setAvatar(":/icons/avatar.png");
+ avatarLabel_->setScaledContents(false);
+ topLayout->addWidget(avatarLabel_);
+ connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
+
+ QVBoxLayout* rightLayout = new QVBoxLayout();
+ rightLayout->setSpacing(4);
+ rightLayout->setContentsMargins(4,0,0,0);
+ topLayout->addLayout(rightLayout);
+
+ QHBoxLayout* nameAndSecurityLayout = new QHBoxLayout();
+ nameAndSecurityLayout->setContentsMargins(4,0,0,0);
+
+ nameWidget_ = new QtNameWidget(settings, this);
+ connect(nameWidget_, SIGNAL(onChangeNickRequest()), this, SIGNAL(onEditProfileRequest()));
+ nameAndSecurityLayout->addWidget(nameWidget_);
+
+ securityInfoButton_ = new QToolButton(this);
+ securityInfoButton_->setStyleSheet("QToolButton { border: none; } QToolButton:hover { border: 1px solid #bebebe; } QToolButton:pressed { border: 1px solid #757575; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777777, stop: 1 #d4d4d4);}");
+ //securityInfoButton_->setAutoRaise(true);
+ securityInfoButton_->setIcon(QIcon(":/icons/lock.png"));
+ securityInfoButton_->setToolTip(tr("Connection is secured"));
+ connect(securityInfoButton_, SIGNAL(clicked()), this, SIGNAL(onShowCertificateInfo()));
+ nameAndSecurityLayout->addWidget(securityInfoButton_);
+
+ rightLayout->addLayout(nameAndSecurityLayout);
+
+ statusWidget_ = new QtStatusWidget(statusCache, this);
+ connect(statusWidget_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleChangeStatusRequest(StatusShow::Type, const QString&)));
+ rightLayout->addWidget(statusWidget_);
+
+ show();
}
void QtRosterHeader::handleChangeStatusRequest(StatusShow::Type type, const QString& text) {
- emit onChangeStatusRequest(type, text);
+ emit onChangeStatusRequest(type, text);
}
void QtRosterHeader::setStatusText(const QString& statusMessage) {
- statusWidget_->setStatusText(statusMessage);
+ statusWidget_->setStatusText(statusMessage);
}
void QtRosterHeader::setStatusType(StatusShow::Type type) {
- statusWidget_->setStatusType(type);
- if (type == StatusShow::None) {
- nameWidget_->setOnline(false);
- disconnect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
- }
- else {
- nameWidget_->setOnline(true);
- connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()), Qt::UniqueConnection);
- }
+ statusWidget_->setStatusType(type);
+ if (type == StatusShow::None) {
+ nameWidget_->setOnline(false);
+ disconnect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
+ }
+ else {
+ nameWidget_->setOnline(true);
+ connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()), Qt::UniqueConnection);
+ }
}
void QtRosterHeader::setConnecting() {
- statusWidget_->setConnecting();
+ statusWidget_->setConnecting();
}
void QtRosterHeader::setStreamEncryptionStatus(bool tlsInPlace) {
- securityInfoButton_->setVisible(tlsInPlace);
+ securityInfoButton_->setVisible(tlsInPlace);
}
bool QtRosterHeader::event(QEvent* event) {
- if (event->type() == QEvent::ToolTip) {
- QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
- QtScaledAvatarCache scaledAvatarCache(avatarSize_);
- QString text = RosterTooltip::buildDetailedTooltip(contact_.get(), &scaledAvatarCache);
- QToolTip::showText(helpEvent->globalPos(), text);
- return true;
- }
- return QWidget::event(event);
+ if (event->type() == QEvent::ToolTip) {
+ QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
+ QtScaledAvatarCache scaledAvatarCache(avatarSize_);
+ QString text = RosterTooltip::buildDetailedTooltip(contact_.get(), &scaledAvatarCache);
+ QToolTip::showText(helpEvent->globalPos(), text);
+ return true;
+ }
+ return QWidget::event(event);
}
void QtRosterHeader::setAvatar(const QString& path) {
- QString scaledAvatarPath = QtScaledAvatarCache(avatarSize_).getScaledAvatarPath(path);
- QPixmap avatar;
- if (QFileInfo(scaledAvatarPath).exists()) {
- avatar.load(scaledAvatarPath);
- }
- else {
- avatar = QPixmap(":/icons/avatar.png").scaled(avatarSize_, avatarSize_, Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
- avatarLabel_->setPixmap(avatar);
+ QString scaledAvatarPath = QtScaledAvatarCache(avatarSize_).getScaledAvatarPath(path);
+ QPixmap avatar;
+ if (QFileInfo(scaledAvatarPath).exists()) {
+ avatar.load(scaledAvatarPath);
+ }
+ else {
+ avatar = QPixmap(":/icons/avatar.png").scaled(avatarSize_, avatarSize_, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ avatarLabel_->setPixmap(avatar);
}
void QtRosterHeader::setNick(const QString& nick) {
- nameWidget_->setNick(nick);
+ nameWidget_->setNick(nick);
}
void QtRosterHeader::setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) {
- contact_ = contact;
+ contact_ = contact;
}
void QtRosterHeader::setJID(const QString& jid) {
- nameWidget_->setJID(jid);
+ nameWidget_->setJID(jid);
}
diff --git a/Swift/QtUI/QtRosterHeader.h b/Swift/QtUI/QtRosterHeader.h
index 49c3338..b556504 100644
--- a/Swift/QtUI/QtRosterHeader.h
+++ b/Swift/QtUI/QtRosterHeader.h
@@ -24,43 +24,43 @@
class QHBoxLayout;
namespace Swift {
- class QtClickableLabel;
- class QtStatusWidget;
- class QtNameWidget;
- class SettingsProvider;
- class StatusCache;
-
- class QtRosterHeader : public QWidget {
- Q_OBJECT
- public:
- QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = NULL);
- void setAvatar(const QString& path);
+ class QtClickableLabel;
+ class QtStatusWidget;
+ class QtNameWidget;
+ class SettingsProvider;
+ class StatusCache;
- void setJID(const QString& jid);
- void setNick(const QString& nick);
- void setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
+ class QtRosterHeader : public QWidget {
+ Q_OBJECT
+ public:
+ QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = NULL);
+ void setAvatar(const QString& path);
- void setStatusText(const QString& statusMessage);
- void setStatusType(StatusShow::Type type);
- void setConnecting();
- void setStreamEncryptionStatus(bool tlsInPlace);
- private:
- bool event(QEvent* event);
- signals:
- void onChangeStatusRequest(StatusShow::Type showType, const QString &statusMessage);
- void onEditProfileRequest();
- void onShowCertificateInfo();
+ void setJID(const QString& jid);
+ void setNick(const QString& nick);
+ void setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
- private slots:
- void handleChangeStatusRequest(StatusShow::Type type, const QString &statusMessage);
- private:
- QString name_;
- QtClickableLabel* avatarLabel_;
- QtNameWidget* nameWidget_;
- QtTextEdit* statusEdit_;
- QtStatusWidget* statusWidget_;
- QToolButton* securityInfoButton_;
- static const int avatarSize_;
- boost::shared_ptr<ContactRosterItem> contact_;
- };
+ void setStatusText(const QString& statusMessage);
+ void setStatusType(StatusShow::Type type);
+ void setConnecting();
+ void setStreamEncryptionStatus(bool tlsInPlace);
+ private:
+ bool event(QEvent* event);
+ signals:
+ void onChangeStatusRequest(StatusShow::Type showType, const QString &statusMessage);
+ void onEditProfileRequest();
+ void onShowCertificateInfo();
+
+ private slots:
+ void handleChangeStatusRequest(StatusShow::Type type, const QString &statusMessage);
+ private:
+ QString name_;
+ QtClickableLabel* avatarLabel_;
+ QtNameWidget* nameWidget_;
+ QtTextEdit* statusEdit_;
+ QtStatusWidget* statusWidget_;
+ QToolButton* securityInfoButton_;
+ static const int avatarSize_;
+ boost::shared_ptr<ContactRosterItem> contact_;
+ };
}
diff --git a/Swift/QtUI/QtScaledAvatarCache.cpp b/Swift/QtUI/QtScaledAvatarCache.cpp
index 9668336..6d683bd 100644
--- a/Swift/QtUI/QtScaledAvatarCache.cpp
+++ b/Swift/QtUI/QtScaledAvatarCache.cpp
@@ -24,39 +24,39 @@ QtScaledAvatarCache::QtScaledAvatarCache(int size) : size(size) {
}
QString QtScaledAvatarCache::getScaledAvatarPath(const QString& path) {
- QFileInfo avatarFile(path);
- if (avatarFile.exists()) {
- if (!avatarFile.dir().exists(QString::number(size))) {
- if (!avatarFile.dir().mkdir(QString::number(size))) {
- return path;
- }
- }
- QDir targetDir(avatarFile.dir().absoluteFilePath(QString::number(size)));
- QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName());
- if (!QFileInfo(targetFile).exists()) {
- QPixmap avatarPixmap;
- if (avatarPixmap.load(path)) {
- QPixmap maskedAvatar(avatarPixmap.size());
- maskedAvatar.fill(QColor(0, 0, 0, 0));
- QPainter maskPainter(&maskedAvatar);
- maskPainter.setBrush(Qt::black);
- maskPainter.drawRoundedRect(maskedAvatar.rect(), 25.0, 25.0, Qt::RelativeSize);
- maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
- maskPainter.drawPixmap(0, 0, avatarPixmap);
- maskPainter.end();
-
- if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) {
- return path;
- }
- } else {
- SWIFT_LOG(debug) << "Failed to load " << Q2PSTRING(path) << std::endl;
- }
- }
- return targetFile;
- }
- else {
- return path;
- }
+ QFileInfo avatarFile(path);
+ if (avatarFile.exists()) {
+ if (!avatarFile.dir().exists(QString::number(size))) {
+ if (!avatarFile.dir().mkdir(QString::number(size))) {
+ return path;
+ }
+ }
+ QDir targetDir(avatarFile.dir().absoluteFilePath(QString::number(size)));
+ QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName());
+ if (!QFileInfo(targetFile).exists()) {
+ QPixmap avatarPixmap;
+ if (avatarPixmap.load(path)) {
+ QPixmap maskedAvatar(avatarPixmap.size());
+ maskedAvatar.fill(QColor(0, 0, 0, 0));
+ QPainter maskPainter(&maskedAvatar);
+ maskPainter.setBrush(Qt::black);
+ maskPainter.drawRoundedRect(maskedAvatar.rect(), 25.0, 25.0, Qt::RelativeSize);
+ maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
+ maskPainter.drawPixmap(0, 0, avatarPixmap);
+ maskPainter.end();
+
+ if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) {
+ return path;
+ }
+ } else {
+ SWIFT_LOG(debug) << "Failed to load " << Q2PSTRING(path) << std::endl;
+ }
+ }
+ return targetFile;
+ }
+ else {
+ return path;
+ }
}
diff --git a/Swift/QtUI/QtScaledAvatarCache.h b/Swift/QtUI/QtScaledAvatarCache.h
index 4ee583d..748fb40 100644
--- a/Swift/QtUI/QtScaledAvatarCache.h
+++ b/Swift/QtUI/QtScaledAvatarCache.h
@@ -11,13 +11,13 @@
#include <QString>
namespace Swift {
- class QtScaledAvatarCache {
- public:
- QtScaledAvatarCache(int size);
+ class QtScaledAvatarCache {
+ public:
+ QtScaledAvatarCache(int size);
- QString getScaledAvatarPath(const QString& path);
+ QString getScaledAvatarPath(const QString& path);
- private:
- int size;
- };
+ private:
+ int size;
+ };
}
diff --git a/Swift/QtUI/QtSettingsProvider.cpp b/Swift/QtUI/QtSettingsProvider.cpp
index d60fa2b..3c32dc8 100644
--- a/Swift/QtUI/QtSettingsProvider.cpp
+++ b/Swift/QtUI/QtSettingsProvider.cpp
@@ -19,105 +19,105 @@ QtSettingsProvider::~QtSettingsProvider() {
}
bool QtSettingsProvider::hasSetting(const std::string& key) {
- return !settings_.value(key.c_str()).isNull();
+ return !settings_.value(key.c_str()).isNull();
}
std::string QtSettingsProvider::getSetting(const Setting<std::string>& setting) {
- QVariant variant = settings_.value(setting.getKey().c_str());
- return variant.isNull() ? setting.getDefaultValue() : std::string(variant.toString().toUtf8());
+ QVariant variant = settings_.value(setting.getKey().c_str());
+ return variant.isNull() ? setting.getDefaultValue() : std::string(variant.toString().toUtf8());
}
void QtSettingsProvider::storeSetting(const Setting<std::string>& setting, const std::string& settingValue) {
- bool changed = false;
- if (getSetting(setting) != settingValue) {
- changed = true;
- }
- settings_.setValue(setting.getKey().c_str(), settingValue.c_str());
- if (changed) {
- onSettingChanged(setting.getKey());
- }
- updatePermissions();
+ bool changed = false;
+ if (getSetting(setting) != settingValue) {
+ changed = true;
+ }
+ settings_.setValue(setting.getKey().c_str(), settingValue.c_str());
+ if (changed) {
+ onSettingChanged(setting.getKey());
+ }
+ updatePermissions();
}
bool QtSettingsProvider::getSetting(const Setting<bool>& setting) {
- QVariant variant = settings_.value(setting.getKey().c_str());
- return variant.isNull() ? setting.getDefaultValue() : variant.toBool();
+ QVariant variant = settings_.value(setting.getKey().c_str());
+ return variant.isNull() ? setting.getDefaultValue() : variant.toBool();
}
void QtSettingsProvider::storeSetting(const Setting<bool>& setting, const bool& settingValue) {
- bool changed = false;
- if (getSetting(setting) != settingValue) {
- changed = true;
- }
- settings_.setValue(setting.getKey().c_str(), settingValue);
- if (changed) {
- onSettingChanged(setting.getKey());
- }
- updatePermissions();
+ bool changed = false;
+ if (getSetting(setting) != settingValue) {
+ changed = true;
+ }
+ settings_.setValue(setting.getKey().c_str(), settingValue);
+ if (changed) {
+ onSettingChanged(setting.getKey());
+ }
+ updatePermissions();
}
int QtSettingsProvider::getSetting(const Setting<int>& setting) {
- QVariant variant = settings_.value(setting.getKey().c_str());
- return variant.isNull() ? setting.getDefaultValue() : variant.toInt();
+ QVariant variant = settings_.value(setting.getKey().c_str());
+ return variant.isNull() ? setting.getDefaultValue() : variant.toInt();
}
void QtSettingsProvider::storeSetting(const Setting<int>& setting, const int& settingValue) {
- bool changed = false;
- if (getSetting(setting) != settingValue) {
- changed = true;
- }
- settings_.setValue(setting.getKey().c_str(), settingValue);
- if (changed) {
- onSettingChanged(setting.getKey());
- }
- updatePermissions();
+ bool changed = false;
+ if (getSetting(setting) != settingValue) {
+ changed = true;
+ }
+ settings_.setValue(setting.getKey().c_str(), settingValue);
+ if (changed) {
+ onSettingChanged(setting.getKey());
+ }
+ updatePermissions();
}
std::vector<std::string> QtSettingsProvider::getAvailableProfiles() {
- std::vector<std::string> profiles;
- QVariant profilesVariant = settings_.value("profileList");
- foreach(QString profileQString, profilesVariant.toStringList()) {
- profiles.push_back(std::string(profileQString.toUtf8()));
- }
- return profiles;
+ std::vector<std::string> profiles;
+ QVariant profilesVariant = settings_.value("profileList");
+ foreach(QString profileQString, profilesVariant.toStringList()) {
+ profiles.push_back(std::string(profileQString.toUtf8()));
+ }
+ return profiles;
}
void QtSettingsProvider::createProfile(const std::string& profile) {
- QStringList stringList = settings_.value("profileList").toStringList();
- stringList.append(profile.c_str());
- settings_.setValue("profileList", stringList);
- updatePermissions();
+ QStringList stringList = settings_.value("profileList").toStringList();
+ stringList.append(profile.c_str());
+ settings_.setValue("profileList", stringList);
+ updatePermissions();
}
void QtSettingsProvider::removeProfile(const std::string& profile) {
- QString profileStart(QString(profile.c_str()) + ":");
- foreach (QString key, settings_.allKeys()) {
- if (key.startsWith(profileStart)) {
- settings_.remove(key);
- }
- }
- QStringList stringList = settings_.value("profileList").toStringList();
- stringList.removeAll(profile.c_str());
- settings_.setValue("profileList", stringList);
- updatePermissions();
+ QString profileStart(QString(profile.c_str()) + ":");
+ foreach (QString key, settings_.allKeys()) {
+ if (key.startsWith(profileStart)) {
+ settings_.remove(key);
+ }
+ }
+ QStringList stringList = settings_.value("profileList").toStringList();
+ stringList.removeAll(profile.c_str());
+ settings_.setValue("profileList", stringList);
+ updatePermissions();
}
QSettings* QtSettingsProvider::getQSettings() {
- return &settings_;
+ return &settings_;
}
void QtSettingsProvider::updatePermissions() {
#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
- QFile file(settings_.fileName());
- if (file.exists()) {
- file.setPermissions(QFile::ReadOwner|QFile::WriteOwner);
- }
+ QFile file(settings_.fileName());
+ if (file.exists()) {
+ file.setPermissions(QFile::ReadOwner|QFile::WriteOwner);
+ }
#endif
}
bool QtSettingsProvider::getIsSettingFinal(const std::string& /*settingPath*/) {
- return false;
+ return false;
}
}
diff --git a/Swift/QtUI/QtSettingsProvider.h b/Swift/QtUI/QtSettingsProvider.h
index 06984f5..21e9211 100644
--- a/Swift/QtUI/QtSettingsProvider.h
+++ b/Swift/QtUI/QtSettingsProvider.h
@@ -13,28 +13,28 @@
namespace Swift {
class QtSettingsProvider : public SettingsProvider {
- public:
- QtSettingsProvider();
- virtual ~QtSettingsProvider();
- virtual std::string getSetting(const Setting<std::string>& setting);
- virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
- virtual bool getSetting(const Setting<bool>& setting);
- virtual void storeSetting(const Setting<bool>& setting, const bool& value);
- virtual int getSetting(const Setting<int>& setting);
- virtual void storeSetting(const Setting<int>& setting, const int& value);
- virtual std::vector<std::string> getAvailableProfiles();
- virtual void createProfile(const std::string& profile);
- virtual void removeProfile(const std::string& profile);
- virtual bool hasSetting(const std::string& key);
- QSettings* getQSettings();
- protected:
- virtual bool getIsSettingFinal(const std::string& settingPath);
-
- private:
- void updatePermissions();
-
- private:
- QSettings settings_;
+ public:
+ QtSettingsProvider();
+ virtual ~QtSettingsProvider();
+ virtual std::string getSetting(const Setting<std::string>& setting);
+ virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
+ virtual bool getSetting(const Setting<bool>& setting);
+ virtual void storeSetting(const Setting<bool>& setting, const bool& value);
+ virtual int getSetting(const Setting<int>& setting);
+ virtual void storeSetting(const Setting<int>& setting, const int& value);
+ virtual std::vector<std::string> getAvailableProfiles();
+ virtual void createProfile(const std::string& profile);
+ virtual void removeProfile(const std::string& profile);
+ virtual bool hasSetting(const std::string& key);
+ QSettings* getQSettings();
+ protected:
+ virtual bool getIsSettingFinal(const std::string& settingPath);
+
+ private:
+ void updatePermissions();
+
+ private:
+ QSettings settings_;
};
}
diff --git a/Swift/QtUI/QtSingleWindow.cpp b/Swift/QtUI/QtSingleWindow.cpp
index 8613d62..db7f7dc 100644
--- a/Swift/QtUI/QtSingleWindow.cpp
+++ b/Swift/QtUI/QtSingleWindow.cpp
@@ -17,13 +17,13 @@ static const QString SINGLE_WINDOW_GEOMETRY = QString("SINGLE_WINDOW_GEOMETRY");
static const QString SINGLE_WINDOW_SPLITS = QString("SINGLE_WINDOW_SPLITS");
QtSingleWindow::QtSingleWindow(QtSettingsProvider* settings) : QSplitter() {
- settings_ = settings;
- QVariant geometryVariant = settings_->getQSettings()->value(SINGLE_WINDOW_GEOMETRY);
- if (geometryVariant.isValid()) {
- restoreGeometry(geometryVariant.toByteArray());
- }
- connect(this, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int)));
- restoreSplitters();
+ settings_ = settings;
+ QVariant geometryVariant = settings_->getQSettings()->value(SINGLE_WINDOW_GEOMETRY);
+ if (geometryVariant.isValid()) {
+ restoreGeometry(geometryVariant.toByteArray());
+ }
+ connect(this, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int)));
+ restoreSplitters();
}
QtSingleWindow::~QtSingleWindow() {
@@ -31,51 +31,51 @@ QtSingleWindow::~QtSingleWindow() {
}
void QtSingleWindow::addWidget(QWidget* widget) {
- QtChatTabs* tabs = dynamic_cast<QtChatTabs*>(widget);
- if (tabs) {
- connect(tabs, SIGNAL(onTitleChanged(const QString&)), this, SLOT(handleTabsTitleChanged(const QString&)));
- }
- QSplitter::addWidget(widget);
+ QtChatTabs* tabs = dynamic_cast<QtChatTabs*>(widget);
+ if (tabs) {
+ connect(tabs, SIGNAL(onTitleChanged(const QString&)), this, SLOT(handleTabsTitleChanged(const QString&)));
+ }
+ QSplitter::addWidget(widget);
}
void QtSingleWindow::handleTabsTitleChanged(const QString& title) {
- setWindowTitle(title);
+ setWindowTitle(title);
}
void QtSingleWindow::handleSplitterMoved(int, int) {
- QList<QVariant> variantValues;
- QList<int> intValues = sizes();
- foreach (int value, intValues) {
- variantValues.append(QVariant(value));
- }
- settings_->getQSettings()->setValue(SINGLE_WINDOW_SPLITS, QVariant(variantValues));
+ QList<QVariant> variantValues;
+ QList<int> intValues = sizes();
+ foreach (int value, intValues) {
+ variantValues.append(QVariant(value));
+ }
+ settings_->getQSettings()->setValue(SINGLE_WINDOW_SPLITS, QVariant(variantValues));
}
void QtSingleWindow::restoreSplitters() {
- QList<QVariant> variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList();
- QList<int> intValues;
- foreach (QVariant value, variantValues) {
- intValues.append(value.toInt());
- }
- setSizes(intValues);
+ QList<QVariant> variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList();
+ QList<int> intValues;
+ foreach (QVariant value, variantValues) {
+ intValues.append(value.toInt());
+ }
+ setSizes(intValues);
}
void QtSingleWindow::insertAtFront(QWidget* widget) {
- insertWidget(0, widget);
- restoreSplitters();
+ insertWidget(0, widget);
+ restoreSplitters();
}
void QtSingleWindow::handleGeometryChanged() {
- settings_->getQSettings()->setValue(SINGLE_WINDOW_GEOMETRY, saveGeometry());
+ settings_->getQSettings()->setValue(SINGLE_WINDOW_GEOMETRY, saveGeometry());
}
void QtSingleWindow::resizeEvent(QResizeEvent*) {
- handleGeometryChanged();
+ handleGeometryChanged();
}
void QtSingleWindow::moveEvent(QMoveEvent*) {
- handleGeometryChanged();
+ handleGeometryChanged();
}
}
diff --git a/Swift/QtUI/QtSingleWindow.h b/Swift/QtUI/QtSingleWindow.h
index e430c56..804be65 100644
--- a/Swift/QtUI/QtSingleWindow.h
+++ b/Swift/QtUI/QtSingleWindow.h
@@ -9,29 +9,29 @@
#include <QSplitter>
namespace Swift {
- class QtSettingsProvider;
-
- class QtSingleWindow : public QSplitter {
- Q_OBJECT
- public:
- QtSingleWindow(QtSettingsProvider* settings);
- virtual ~QtSingleWindow();
- void insertAtFront(QWidget* widget);
- void addWidget(QWidget* widget);
- protected:
- void resizeEvent(QResizeEvent*);
- void moveEvent(QMoveEvent*);
- private slots:
- void handleSplitterMoved(int, int);
- void handleTabsTitleChanged(const QString& title);
- private:
- void handleGeometryChanged();
- void restoreSplitters();
-
- private:
-
- QtSettingsProvider* settings_;
- };
+ class QtSettingsProvider;
+
+ class QtSingleWindow : public QSplitter {
+ Q_OBJECT
+ public:
+ QtSingleWindow(QtSettingsProvider* settings);
+ virtual ~QtSingleWindow();
+ void insertAtFront(QWidget* widget);
+ void addWidget(QWidget* widget);
+ protected:
+ void resizeEvent(QResizeEvent*);
+ void moveEvent(QMoveEvent*);
+ private slots:
+ void handleSplitterMoved(int, int);
+ void handleTabsTitleChanged(const QString& title);
+ private:
+ void handleGeometryChanged();
+ void restoreSplitters();
+
+ private:
+
+ QtSettingsProvider* settings_;
+ };
}
diff --git a/Swift/QtUI/QtSoundPlayer.cpp b/Swift/QtUI/QtSoundPlayer.cpp
index f047427..22f544d 100644
--- a/Swift/QtUI/QtSoundPlayer.cpp
+++ b/Swift/QtUI/QtSoundPlayer.cpp
@@ -17,30 +17,30 @@
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
-
+
QtSoundPlayer::QtSoundPlayer(ApplicationPathProvider* applicationPathProvider) : applicationPathProvider(applicationPathProvider) {
}
void QtSoundPlayer::playSound(SoundEffect sound, const std::string& soundResource) {
- switch (sound) {
- case MessageReceived:
- playSound(soundResource.empty() ? "/sounds/message-received.wav" : soundResource);
- break;
- }
+ switch (sound) {
+ case MessageReceived:
+ playSound(soundResource.empty() ? "/sounds/message-received.wav" : soundResource);
+ break;
+ }
}
void QtSoundPlayer::playSound(const std::string& soundResource) {
- boost::filesystem::path resourcePath = applicationPathProvider->getResourcePath(soundResource);
- if (boost::filesystem::exists(resourcePath)) {
- QSound::play(P2QSTRING(pathToString(resourcePath)));
- }
- else if (boost::filesystem::exists(soundResource)) {
- QSound::play(P2QSTRING(soundResource));
- }
- else {
- std::cerr << "Unable to find sound: " << soundResource << std::endl;
- }
+ boost::filesystem::path resourcePath = applicationPathProvider->getResourcePath(soundResource);
+ if (boost::filesystem::exists(resourcePath)) {
+ QSound::play(P2QSTRING(pathToString(resourcePath)));
+ }
+ else if (boost::filesystem::exists(soundResource)) {
+ QSound::play(P2QSTRING(soundResource));
+ }
+ else {
+ std::cerr << "Unable to find sound: " << soundResource << std::endl;
+ }
}
}
diff --git a/Swift/QtUI/QtSoundPlayer.h b/Swift/QtUI/QtSoundPlayer.h
index e34529e..8a0b8fe 100644
--- a/Swift/QtUI/QtSoundPlayer.h
+++ b/Swift/QtUI/QtSoundPlayer.h
@@ -11,20 +11,20 @@
#include <Swift/Controllers/SoundPlayer.h>
namespace Swift {
- class ApplicationPathProvider;
-
+ class ApplicationPathProvider;
- class QtSoundPlayer : public QObject, public SoundPlayer {
- Q_OBJECT
- public:
- QtSoundPlayer(ApplicationPathProvider* applicationPathProvider);
- void playSound(SoundEffect sound, const std::string& soundResource);
+ class QtSoundPlayer : public QObject, public SoundPlayer {
+ Q_OBJECT
+ public:
+ QtSoundPlayer(ApplicationPathProvider* applicationPathProvider);
- private:
- void playSound(const std::string& soundResource);
+ void playSound(SoundEffect sound, const std::string& soundResource);
- private:
- ApplicationPathProvider* applicationPathProvider;
- };
+ private:
+ void playSound(const std::string& soundResource);
+
+ private:
+ ApplicationPathProvider* applicationPathProvider;
+ };
}
diff --git a/Swift/QtUI/QtSpellCheckHighlighter.cpp b/Swift/QtUI/QtSpellCheckHighlighter.cpp
index 0112d7a..6565b06 100644
--- a/Swift/QtUI/QtSpellCheckHighlighter.cpp
+++ b/Swift/QtUI/QtSpellCheckHighlighter.cpp
@@ -21,21 +21,21 @@ QtSpellCheckHighlighter::~QtSpellCheckHighlighter() {
}
void QtSpellCheckHighlighter::highlightBlock(const QString& text) {
- misspelledPositions_.clear();
- std::string fragment = Q2PSTRING(text);
- checker_->checkFragment(fragment, misspelledPositions_);
+ misspelledPositions_.clear();
+ std::string fragment = Q2PSTRING(text);
+ checker_->checkFragment(fragment, misspelledPositions_);
- QTextCharFormat spellingErrorFormat;
- spellingErrorFormat.setUnderlineColor(QColor(Qt::red));
- spellingErrorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline);
+ QTextCharFormat spellingErrorFormat;
+ spellingErrorFormat.setUnderlineColor(QColor(Qt::red));
+ spellingErrorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline);
- foreach (PositionPair position, misspelledPositions_) {
- setFormat(boost::get<0>(position), boost::get<1>(position) - boost::get<0>(position), spellingErrorFormat);
- };
+ foreach (PositionPair position, misspelledPositions_) {
+ setFormat(boost::get<0>(position), boost::get<1>(position) - boost::get<0>(position), spellingErrorFormat);
+ };
}
PositionPairList QtSpellCheckHighlighter::getMisspelledPositions() const {
- return misspelledPositions_;
+ return misspelledPositions_;
}
}
diff --git a/Swift/QtUI/QtSpellCheckHighlighter.h b/Swift/QtUI/QtSpellCheckHighlighter.h
index 7fa48de..5519a1d 100644
--- a/Swift/QtUI/QtSpellCheckHighlighter.h
+++ b/Swift/QtUI/QtSpellCheckHighlighter.h
@@ -18,20 +18,20 @@ namespace Swift {
class SpellChecker;
class QtSpellCheckHighlighter : public QSyntaxHighlighter {
- Q_OBJECT
+ Q_OBJECT
public:
- QtSpellCheckHighlighter(QTextDocument* parent, SpellChecker* spellChecker);
- virtual ~QtSpellCheckHighlighter();
+ QtSpellCheckHighlighter(QTextDocument* parent, SpellChecker* spellChecker);
+ virtual ~QtSpellCheckHighlighter();
- PositionPairList getMisspelledPositions() const;
+ PositionPairList getMisspelledPositions() const;
protected:
- virtual void highlightBlock(const QString& text);
+ virtual void highlightBlock(const QString& text);
private:
- SpellChecker* checker_;
- PositionPairList misspelledPositions_;
+ SpellChecker* checker_;
+ PositionPairList misspelledPositions_;
};
diff --git a/Swift/QtUI/QtSpellCheckerWindow.cpp b/Swift/QtUI/QtSpellCheckerWindow.cpp
index ba4dbd3..9232b19 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.cpp
+++ b/Swift/QtUI/QtSpellCheckerWindow.cpp
@@ -27,96 +27,96 @@
namespace Swift {
QtSpellCheckerWindow::QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent) : QDialog(parent) {
- settings_ = settings;
- ui_.setupUi(this);
+ settings_ = settings;
+ ui_.setupUi(this);
#ifdef HAVE_HUNSPELL
- ui_.hunspellOptions->show();
+ ui_.hunspellOptions->show();
#else
- ui_.hunspellOptions->hide();
- QTimer::singleShot(0, this, SLOT(shrinkWindow()));
+ ui_.hunspellOptions->hide();
+ QTimer::singleShot(0, this, SLOT(shrinkWindow()));
#endif
- connect(ui_.spellChecker, SIGNAL(toggled(bool)), this, SLOT(handleChecker(bool)));
- connect(ui_.cancel, SIGNAL(clicked()), this, SLOT(handleCancel()));
- connect(ui_.apply, SIGNAL(clicked()), this, SLOT(handleApply()));
- connect(ui_.pathButton, SIGNAL(clicked()), this, SLOT(handlePathButton()));
- setFromSettings();
+ connect(ui_.spellChecker, SIGNAL(toggled(bool)), this, SLOT(handleChecker(bool)));
+ connect(ui_.cancel, SIGNAL(clicked()), this, SLOT(handleCancel()));
+ connect(ui_.apply, SIGNAL(clicked()), this, SLOT(handleApply()));
+ connect(ui_.pathButton, SIGNAL(clicked()), this, SLOT(handlePathButton()));
+ setFromSettings();
}
void QtSpellCheckerWindow::shrinkWindow() {
- resize(0,0);
+ resize(0,0);
}
void QtSpellCheckerWindow::setFromSettings() {
- ui_.spellChecker->setChecked(settings_->getSetting(SettingConstants::SPELL_CHECKER));
- ui_.pathContent->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_PATH)));
- ui_.currentLanguageValue->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_FILE)));
- std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
- QString filename = "*.dic";
- QDir dictDirectory = QDir(P2QSTRING(currentPath));
- QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
- showFiles(files);
- setEnabled(settings_->getSetting(SettingConstants::SPELL_CHECKER));
+ ui_.spellChecker->setChecked(settings_->getSetting(SettingConstants::SPELL_CHECKER));
+ ui_.pathContent->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_PATH)));
+ ui_.currentLanguageValue->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_FILE)));
+ std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
+ QString filename = "*.dic";
+ QDir dictDirectory = QDir(P2QSTRING(currentPath));
+ QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
+ showFiles(files);
+ setEnabled(settings_->getSetting(SettingConstants::SPELL_CHECKER));
}
void QtSpellCheckerWindow::handleChecker(bool state) {
- setEnabled(state);
+ setEnabled(state);
}
void QtSpellCheckerWindow::setEnabled(bool state) {
- ui_.pathContent->setEnabled(state);
- ui_.languageView->setEnabled(state);
- ui_.pathButton->setEnabled(state);
- ui_.pathLabel->setEnabled(state);
- ui_.currentLanguage->setEnabled(state);
- ui_.currentLanguageValue->setEnabled(state);
- ui_.language->setEnabled(state);
+ ui_.pathContent->setEnabled(state);
+ ui_.languageView->setEnabled(state);
+ ui_.pathButton->setEnabled(state);
+ ui_.pathLabel->setEnabled(state);
+ ui_.currentLanguage->setEnabled(state);
+ ui_.currentLanguageValue->setEnabled(state);
+ ui_.language->setEnabled(state);
}
void QtSpellCheckerWindow::handleApply() {
- settings_->storeSetting(SettingConstants::SPELL_CHECKER, ui_.spellChecker->isChecked());
- QList<QListWidgetItem* > selectedLanguage = ui_.languageView->selectedItems();
- if (!selectedLanguage.empty()) {
- settings_->storeSetting(SettingConstants::DICT_FILE, Q2PSTRING((selectedLanguage.first())->text()));
- }
- this->done(0);
+ settings_->storeSetting(SettingConstants::SPELL_CHECKER, ui_.spellChecker->isChecked());
+ QList<QListWidgetItem* > selectedLanguage = ui_.languageView->selectedItems();
+ if (!selectedLanguage.empty()) {
+ settings_->storeSetting(SettingConstants::DICT_FILE, Q2PSTRING((selectedLanguage.first())->text()));
+ }
+ this->done(0);
}
void QtSpellCheckerWindow::handleCancel() {
- this->done(0);
+ this->done(0);
}
void QtSpellCheckerWindow::handlePathButton() {
- std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
- QString dirpath = QFileDialog::getExistingDirectory(this, tr("Dictionary Path"), P2QSTRING(currentPath));
- if (dirpath != P2QSTRING(currentPath)) {
- ui_.languageView->clear();
- settings_->storeSetting(SettingConstants::DICT_FILE, "");
- ui_.currentLanguageValue->setText(" ");
- }
- if (!dirpath.isEmpty()) {
- if (!dirpath.endsWith("/")) {
- dirpath.append("/");
- }
- settings_->storeSetting(SettingConstants::DICT_PATH, Q2PSTRING(dirpath));
- QDir dictDirectory = QDir(dirpath);
- ui_.pathContent->setText(dirpath);
- QString filename = "*.dic";
- QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
- showFiles(files);
- }
+ std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
+ QString dirpath = QFileDialog::getExistingDirectory(this, tr("Dictionary Path"), P2QSTRING(currentPath));
+ if (dirpath != P2QSTRING(currentPath)) {
+ ui_.languageView->clear();
+ settings_->storeSetting(SettingConstants::DICT_FILE, "");
+ ui_.currentLanguageValue->setText(" ");
+ }
+ if (!dirpath.isEmpty()) {
+ if (!dirpath.endsWith("/")) {
+ dirpath.append("/");
+ }
+ settings_->storeSetting(SettingConstants::DICT_PATH, Q2PSTRING(dirpath));
+ QDir dictDirectory = QDir(dirpath);
+ ui_.pathContent->setText(dirpath);
+ QString filename = "*.dic";
+ QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
+ showFiles(files);
+ }
}
void QtSpellCheckerWindow::handlePersonalPathButton() {
- std::string currentPath = settings_->getSetting(SettingConstants::PERSONAL_DICT_PATH);
- QString filename = QFileDialog::getOpenFileName(this, tr("Select Personal Dictionary"), P2QSTRING(currentPath), tr("(*.dic"));
- settings_->storeSetting(SettingConstants::PERSONAL_DICT_PATH, Q2PSTRING(filename));
+ std::string currentPath = settings_->getSetting(SettingConstants::PERSONAL_DICT_PATH);
+ QString filename = QFileDialog::getOpenFileName(this, tr("Select Personal Dictionary"), P2QSTRING(currentPath), tr("(*.dic"));
+ settings_->storeSetting(SettingConstants::PERSONAL_DICT_PATH, Q2PSTRING(filename));
}
void QtSpellCheckerWindow::showFiles(const QStringList& files) {
- ui_.languageView->clear();
- for (int i = 0; i < files.size(); ++i) {
- ui_.languageView->insertItem(i, files[i]);
- }
+ ui_.languageView->clear();
+ for (int i = 0; i < files.size(); ++i) {
+ ui_.languageView->insertItem(i, files[i]);
+ }
}
}
diff --git a/Swift/QtUI/QtSpellCheckerWindow.h b/Swift/QtUI/QtSpellCheckerWindow.h
index 0e43ddd..95e0725 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.h
+++ b/Swift/QtUI/QtSpellCheckerWindow.h
@@ -17,24 +17,24 @@
#include <Swift/QtUI/ui_QtSpellCheckerWindow.h>
namespace Swift {
- class SettingsProvider;
- class QtSpellCheckerWindow : public QDialog, protected Ui::QtSpellCheckerWindow {
- Q_OBJECT
- public:
- QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent = NULL);
- public slots:
- void handleChecker(bool state);
- void handleCancel();
- void handlePathButton();
- void handlePersonalPathButton();
- void handleApply();
- private slots:
- void shrinkWindow();
- private:
- void setEnabled(bool state);
- void setFromSettings();
- void showFiles(const QStringList& files);
- SettingsProvider* settings_;
- Ui::QtSpellCheckerWindow ui_;
- };
+ class SettingsProvider;
+ class QtSpellCheckerWindow : public QDialog, protected Ui::QtSpellCheckerWindow {
+ Q_OBJECT
+ public:
+ QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent = NULL);
+ public slots:
+ void handleChecker(bool state);
+ void handleCancel();
+ void handlePathButton();
+ void handlePersonalPathButton();
+ void handleApply();
+ private slots:
+ void shrinkWindow();
+ private:
+ void setEnabled(bool state);
+ void setFromSettings();
+ void showFiles(const QStringList& files);
+ SettingsProvider* settings_;
+ Ui::QtSpellCheckerWindow ui_;
+ };
}
diff --git a/Swift/QtUI/QtStatusWidget.cpp b/Swift/QtUI/QtStatusWidget.cpp
index 78b2c5a..2e9e4cc 100644
--- a/Swift/QtUI/QtStatusWidget.cpp
+++ b/Swift/QtUI/QtStatusWidget.cpp
@@ -37,266 +37,266 @@ namespace lambda = boost::lambda;
namespace Swift {
QtStatusWidget::QtStatusWidget(StatusCache* statusCache, QWidget *parent) : QWidget(parent), statusCache_(statusCache), editCursor_(Qt::IBeamCursor), viewCursor_(Qt::PointingHandCursor) {
- allTypes_.push_back(StatusShow::Online);
- allTypes_.push_back(StatusShow::FFC);
- allTypes_.push_back(StatusShow::Away);
- allTypes_.push_back(StatusShow::XA);
- allTypes_.push_back(StatusShow::DND);
- allTypes_.push_back(StatusShow::None);
-
- isClicking_ = false;
- connecting_ = false;
- setMaximumHeight(24);
-
- connectingMovie_ = new QMovie(":/icons/connecting.mng");
-
- QHBoxLayout* mainLayout = new QHBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
-
- stack_ = new QStackedWidget(this);
- stack_->setLineWidth(2);
- stack_->setFrameShape(QFrame::StyledPanel);
- mainLayout->addWidget(stack_);
-
- QWidget* page1 = new QWidget(this);
- stack_->addWidget(page1);
- QHBoxLayout* page1Layout = new QHBoxLayout(page1);
- page1Layout->setSpacing(0);
- page1Layout->setContentsMargins(0,0,0,0);
- page1->setCursor(viewCursor_);
-
- statusIcon_ = new QLabel(this);
- statusIcon_->setMinimumSize(16, 16);
- statusIcon_->setMaximumSize(16, 16);
- page1Layout->addWidget(statusIcon_);
-
- statusTextLabel_ = new QtElidingLabel(this);
- QFont font = statusTextLabel_->font();
- font.setItalic(true);
- statusTextLabel_->setFont(font);
- page1Layout->addWidget(statusTextLabel_);
-
- icons_[StatusShow::Online] = QIcon(":/icons/online.png");
- icons_[StatusShow::Away] = QIcon(":/icons/away.png");
- icons_[StatusShow::DND] = QIcon(":/icons/dnd.png");
- icons_[StatusShow::None] = QIcon(":/icons/offline.png");
-
- setStatusType(StatusShow::None);
-
- QWidget* page2 = new QWidget(this);
- QHBoxLayout* page2Layout = new QHBoxLayout(page2);
- page2Layout->setSpacing(0);
- page2Layout->setContentsMargins(0,0,0,0);
- stack_->addWidget(page2);
-
- statusEdit_ = new QtLineEdit(this);
- page2Layout->addWidget(statusEdit_);
- connect(statusEdit_, SIGNAL(returnPressed()), this, SLOT(handleEditComplete()));
- connect(statusEdit_, SIGNAL(escapePressed()), this, SLOT(handleEditCancelled()));
- connect(statusEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(generateList()));
-
- setStatusText("");
-
-
- menu_ = new QListWidget();
- menu_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint );
- menu_->setAlternatingRowColors(true);
- menu_->setFocusProxy(statusEdit_);
- menu_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- menu_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- QSizePolicy policy(menu_->sizePolicy());
- policy.setVerticalPolicy(QSizePolicy::Expanding);
- menu_->setSizePolicy(policy);
-
-
- connect(menu_, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(handleItemClicked(QListWidgetItem*)));
-
- viewMode();
+ allTypes_.push_back(StatusShow::Online);
+ allTypes_.push_back(StatusShow::FFC);
+ allTypes_.push_back(StatusShow::Away);
+ allTypes_.push_back(StatusShow::XA);
+ allTypes_.push_back(StatusShow::DND);
+ allTypes_.push_back(StatusShow::None);
+
+ isClicking_ = false;
+ connecting_ = false;
+ setMaximumHeight(24);
+
+ connectingMovie_ = new QMovie(":/icons/connecting.mng");
+
+ QHBoxLayout* mainLayout = new QHBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
+
+ stack_ = new QStackedWidget(this);
+ stack_->setLineWidth(2);
+ stack_->setFrameShape(QFrame::StyledPanel);
+ mainLayout->addWidget(stack_);
+
+ QWidget* page1 = new QWidget(this);
+ stack_->addWidget(page1);
+ QHBoxLayout* page1Layout = new QHBoxLayout(page1);
+ page1Layout->setSpacing(0);
+ page1Layout->setContentsMargins(0,0,0,0);
+ page1->setCursor(viewCursor_);
+
+ statusIcon_ = new QLabel(this);
+ statusIcon_->setMinimumSize(16, 16);
+ statusIcon_->setMaximumSize(16, 16);
+ page1Layout->addWidget(statusIcon_);
+
+ statusTextLabel_ = new QtElidingLabel(this);
+ QFont font = statusTextLabel_->font();
+ font.setItalic(true);
+ statusTextLabel_->setFont(font);
+ page1Layout->addWidget(statusTextLabel_);
+
+ icons_[StatusShow::Online] = QIcon(":/icons/online.png");
+ icons_[StatusShow::Away] = QIcon(":/icons/away.png");
+ icons_[StatusShow::DND] = QIcon(":/icons/dnd.png");
+ icons_[StatusShow::None] = QIcon(":/icons/offline.png");
+
+ setStatusType(StatusShow::None);
+
+ QWidget* page2 = new QWidget(this);
+ QHBoxLayout* page2Layout = new QHBoxLayout(page2);
+ page2Layout->setSpacing(0);
+ page2Layout->setContentsMargins(0,0,0,0);
+ stack_->addWidget(page2);
+
+ statusEdit_ = new QtLineEdit(this);
+ page2Layout->addWidget(statusEdit_);
+ connect(statusEdit_, SIGNAL(returnPressed()), this, SLOT(handleEditComplete()));
+ connect(statusEdit_, SIGNAL(escapePressed()), this, SLOT(handleEditCancelled()));
+ connect(statusEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(generateList()));
+
+ setStatusText("");
+
+
+ menu_ = new QListWidget();
+ menu_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint );
+ menu_->setAlternatingRowColors(true);
+ menu_->setFocusProxy(statusEdit_);
+ menu_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ menu_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ QSizePolicy policy(menu_->sizePolicy());
+ policy.setVerticalPolicy(QSizePolicy::Expanding);
+ menu_->setSizePolicy(policy);
+
+
+ connect(menu_, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(handleItemClicked(QListWidgetItem*)));
+
+ viewMode();
}
QtStatusWidget::~QtStatusWidget() {
- delete menu_;
- delete connectingMovie_;
+ delete menu_;
+ delete connectingMovie_;
}
void QtStatusWidget::handleApplicationFocusChanged(QWidget* /*old*/, QWidget* /*now*/) {
- QWidget* now = qApp->focusWidget();
- if (!editing_ || stack_->currentIndex() == 0) {
- return;
- }
- if (!now || (now != menu_ && now != statusEdit_ && !now->isAncestorOf(statusEdit_) && !now->isAncestorOf(menu_) && !statusEdit_->isAncestorOf(now) && !menu_->isAncestorOf(now))) {
- handleEditCancelled();
- }
-
+ QWidget* now = qApp->focusWidget();
+ if (!editing_ || stack_->currentIndex() == 0) {
+ return;
+ }
+ if (!now || (now != menu_ && now != statusEdit_ && !now->isAncestorOf(statusEdit_) && !now->isAncestorOf(menu_) && !statusEdit_->isAncestorOf(now) && !menu_->isAncestorOf(now))) {
+ handleEditCancelled();
+ }
+
}
void QtStatusWidget::mousePressEvent(QMouseEvent*) {
- if (stack_->currentIndex() == 0) {
- handleClicked();
- }
+ if (stack_->currentIndex() == 0) {
+ handleClicked();
+ }
}
void QtStatusWidget::generateList() {
- if (!editing_) {
- return;
- }
- QString text = statusEdit_->text();
- newStatusText_ = text;
- menu_->clear();
- foreach (StatusShow::Type type, icons_.keys()) {
- QListWidgetItem* item = new QListWidgetItem(text == "" ? getNoMessage() : text, menu_);
- item->setIcon(icons_[type]);
- item->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(type)) + ": " + item->text());
- item->setStatusTip(item->toolTip());
- item->setData(Qt::UserRole, QVariant(type));
- }
- std::vector<StatusCache::PreviousStatus> previousStatuses = statusCache_->getMatches(Q2PSTRING(text), 8);
- foreach (StatusCache::PreviousStatus savedStatus, previousStatuses) {
- if (savedStatus.first.empty() || std::find_if(allTypes_.begin(), allTypes_.end(),
- savedStatus.second == lambda::_1 && savedStatus.first == lambda::bind(&statusShowTypeToFriendlyName, lambda::_1)) != allTypes_.end()) {
- continue;
- }
- QListWidgetItem* item = new QListWidgetItem(P2QSTRING(savedStatus.first), menu_);
- item->setIcon(icons_[savedStatus.second]);
- item->setToolTip(item->text());
- item->setStatusTip(item->toolTip());
- item->setData(Qt::UserRole, QVariant(savedStatus.second));
- }
- foreach (StatusShow::Type type, icons_.keys()) {
- if (Q2PSTRING(text) == statusShowTypeToFriendlyName(type)) {
- continue;
- }
- QListWidgetItem* item = new QListWidgetItem(P2QSTRING(statusShowTypeToFriendlyName(type)), menu_);
- item->setIcon(icons_[type]);
- item->setToolTip(item->text());
- item->setStatusTip(item->toolTip());
- item->setData(Qt::UserRole, QVariant(type));
- }
- resizeMenu();
+ if (!editing_) {
+ return;
+ }
+ QString text = statusEdit_->text();
+ newStatusText_ = text;
+ menu_->clear();
+ foreach (StatusShow::Type type, icons_.keys()) {
+ QListWidgetItem* item = new QListWidgetItem(text == "" ? getNoMessage() : text, menu_);
+ item->setIcon(icons_[type]);
+ item->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(type)) + ": " + item->text());
+ item->setStatusTip(item->toolTip());
+ item->setData(Qt::UserRole, QVariant(type));
+ }
+ std::vector<StatusCache::PreviousStatus> previousStatuses = statusCache_->getMatches(Q2PSTRING(text), 8);
+ foreach (StatusCache::PreviousStatus savedStatus, previousStatuses) {
+ if (savedStatus.first.empty() || std::find_if(allTypes_.begin(), allTypes_.end(),
+ savedStatus.second == lambda::_1 && savedStatus.first == lambda::bind(&statusShowTypeToFriendlyName, lambda::_1)) != allTypes_.end()) {
+ continue;
+ }
+ QListWidgetItem* item = new QListWidgetItem(P2QSTRING(savedStatus.first), menu_);
+ item->setIcon(icons_[savedStatus.second]);
+ item->setToolTip(item->text());
+ item->setStatusTip(item->toolTip());
+ item->setData(Qt::UserRole, QVariant(savedStatus.second));
+ }
+ foreach (StatusShow::Type type, icons_.keys()) {
+ if (Q2PSTRING(text) == statusShowTypeToFriendlyName(type)) {
+ continue;
+ }
+ QListWidgetItem* item = new QListWidgetItem(P2QSTRING(statusShowTypeToFriendlyName(type)), menu_);
+ item->setIcon(icons_[type]);
+ item->setToolTip(item->text());
+ item->setStatusTip(item->toolTip());
+ item->setData(Qt::UserRole, QVariant(type));
+ }
+ resizeMenu();
}
void QtStatusWidget::resizeMenu() {
- int height = menu_->sizeHintForRow(0) * menu_->count();
- int marginLeft;
- int marginTop;
- int marginRight;
- int marginBottom;
- menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
- height += marginTop + marginBottom;
-
- menu_->setGeometry(menu_->x(), menu_->y(), menu_->width(), height);
+ int height = menu_->sizeHintForRow(0) * menu_->count();
+ int marginLeft;
+ int marginTop;
+ int marginRight;
+ int marginBottom;
+ menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
+ height += marginTop + marginBottom;
+
+ menu_->setGeometry(menu_->x(), menu_->y(), menu_->width(), height);
}
void QtStatusWidget::handleClicked() {
- editing_ = true;
- QDesktopWidget* desktop = QApplication::desktop();
- int screen = desktop->screenNumber(this);
- QPoint point = mapToGlobal(QPoint(0, height()));
- QRect geometry = desktop->availableGeometry(screen);
- int x = point.x();
- int y = point.y();
- int width = 200;
- int height = 80;
-
- int screenWidth = geometry.x() + geometry.width();
- if (x + width > screenWidth) {
- x = screenWidth - width;
- }
- //foreach (StatusShow::Type type, allTypes_) {
- // if (statusEdit_->text() == P2QSTRING(statusShowTypeToFriendlyName(type))) {
- statusEdit_->setText("");
- // }
- //}
- generateList();
-
- height = menu_->sizeHintForRow(0) * menu_->count();
- int marginLeft;
- int marginTop;
- int marginRight;
- int marginBottom;
- menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
- height += marginTop + marginBottom;
- width += marginLeft + marginRight;
-
- menu_->setGeometry(x, y, width, height);
- menu_->move(x, y);
- menu_->setMaximumWidth(width);
- menu_->show();
- activateWindow();
- statusEdit_->selectAll();
- stack_->setCurrentIndex(1);
- statusEdit_->setFocus();
- connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
+ editing_ = true;
+ QDesktopWidget* desktop = QApplication::desktop();
+ int screen = desktop->screenNumber(this);
+ QPoint point = mapToGlobal(QPoint(0, height()));
+ QRect geometry = desktop->availableGeometry(screen);
+ int x = point.x();
+ int y = point.y();
+ int width = 200;
+ int height = 80;
+
+ int screenWidth = geometry.x() + geometry.width();
+ if (x + width > screenWidth) {
+ x = screenWidth - width;
+ }
+ //foreach (StatusShow::Type type, allTypes_) {
+ // if (statusEdit_->text() == P2QSTRING(statusShowTypeToFriendlyName(type))) {
+ statusEdit_->setText("");
+ // }
+ //}
+ generateList();
+
+ height = menu_->sizeHintForRow(0) * menu_->count();
+ int marginLeft;
+ int marginTop;
+ int marginRight;
+ int marginBottom;
+ menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
+ height += marginTop + marginBottom;
+ width += marginLeft + marginRight;
+
+ menu_->setGeometry(x, y, width, height);
+ menu_->move(x, y);
+ menu_->setMaximumWidth(width);
+ menu_->show();
+ activateWindow();
+ statusEdit_->selectAll();
+ stack_->setCurrentIndex(1);
+ statusEdit_->setFocus();
+ connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
}
void QtStatusWidget::viewMode() {
- disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
- editing_ = false;
- menu_->hide();
- stack_->setCurrentIndex(0);
+ disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
+ editing_ = false;
+ menu_->hide();
+ stack_->setCurrentIndex(0);
}
void QtStatusWidget::handleEditComplete() {
- editing_ = false;
- statusText_ = newStatusText_;
- viewMode();
- emit onChangeStatusRequest(selectedStatusType_, statusText_);
- statusCache_->addRecent(Q2PSTRING(statusText_), selectedStatusType_);
+ editing_ = false;
+ statusText_ = newStatusText_;
+ viewMode();
+ emit onChangeStatusRequest(selectedStatusType_, statusText_);
+ statusCache_->addRecent(Q2PSTRING(statusText_), selectedStatusType_);
}
void QtStatusWidget::handleEditCancelled() {
- editing_ = false;
- setStatusText(statusText_);
- viewMode();
+ editing_ = false;
+ setStatusText(statusText_);
+ viewMode();
}
StatusShow::Type QtStatusWidget::getSelectedStatusShow() {
- return selectedStatusType_;
+ return selectedStatusType_;
}
void QtStatusWidget::handleItemClicked(QListWidgetItem* item) {
- editing_ = false;
- selectedStatusType_ = static_cast<StatusShow::Type>(item->data(Qt::UserRole).toInt());
- QString message = item->data(Qt::DisplayRole).toString();
- newStatusText_ = message == getNoMessage() ? "" : message;
- statusEdit_->setText(newStatusText_);
- handleEditComplete();
+ editing_ = false;
+ selectedStatusType_ = static_cast<StatusShow::Type>(item->data(Qt::UserRole).toInt());
+ QString message = item->data(Qt::DisplayRole).toString();
+ newStatusText_ = message == getNoMessage() ? "" : message;
+ statusEdit_->setText(newStatusText_);
+ handleEditComplete();
}
void QtStatusWidget::setNewToolTip() {
- if (connecting_) {
- statusTextLabel_->setToolTip(tr("Connecting"));
- } else {
- statusTextLabel_->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(selectedStatusType_)) + ": " + statusTextLabel_->text());
- }
+ if (connecting_) {
+ statusTextLabel_->setToolTip(tr("Connecting"));
+ } else {
+ statusTextLabel_->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(selectedStatusType_)) + ": " + statusTextLabel_->text());
+ }
}
void QtStatusWidget::setStatusText(const QString& text) {
- connectingMovie_->stop();
- statusText_ = text;
- statusEdit_->setText(text);
- QString escapedText(text.isEmpty() ? getNoMessage() : text);
- statusTextLabel_->setText(escapedText);
- setNewToolTip();
+ connectingMovie_->stop();
+ statusText_ = text;
+ statusEdit_->setText(text);
+ QString escapedText(text.isEmpty() ? getNoMessage() : text);
+ statusTextLabel_->setText(escapedText);
+ setNewToolTip();
}
void QtStatusWidget::setConnecting() {
- connecting_ = true;
- statusIcon_->setMovie(connectingMovie_);
- connectingMovie_->start();
- setNewToolTip();
+ connecting_ = true;
+ statusIcon_->setMovie(connectingMovie_);
+ connectingMovie_->start();
+ setNewToolTip();
}
void QtStatusWidget::setStatusType(StatusShow::Type type) {
- connecting_ = false;
- selectedStatusType_ = icons_.contains(type) ? type : StatusShow::Online;
- statusIcon_->setPixmap(icons_[selectedStatusType_].pixmap(16, 16));
- setNewToolTip();
+ connecting_ = false;
+ selectedStatusType_ = icons_.contains(type) ? type : StatusShow::Online;
+ statusIcon_->setPixmap(icons_[selectedStatusType_].pixmap(16, 16));
+ setNewToolTip();
}
QString QtStatusWidget::getNoMessage() {
- return QString(tr("(No message)"));
+ return QString(tr("(No message)"));
}
}
diff --git a/Swift/QtUI/QtStatusWidget.h b/Swift/QtUI/QtStatusWidget.h
index b835490..f346868 100644
--- a/Swift/QtUI/QtStatusWidget.h
+++ b/Swift/QtUI/QtStatusWidget.h
@@ -20,55 +20,55 @@ class QListWidgetItem;
class QMovie;
namespace Swift {
- class QtLineEdit;
- class QtElidingLabel;
- class StatusCache;
+ class QtLineEdit;
+ class QtElidingLabel;
+ class StatusCache;
- class QtStatusWidget : public QWidget {
- Q_OBJECT
- public:
- QtStatusWidget(StatusCache* statusCache, QWidget *parent);
- ~QtStatusWidget();
- StatusShow::Type getSelectedStatusShow();
- void setStatusType(StatusShow::Type type);
- void setConnecting();
- signals:
- void onChangeStatusRequest(StatusShow::Type showType, const QString& text);
- public slots:
- void setStatusText(const QString& text);
- private slots:
- void generateList();
- void handleClicked();
- void handleEditComplete();
- void handleEditCancelled();
- void handleApplicationFocusChanged(QWidget* old, QWidget* now);
- protected slots:
- virtual void mousePressEvent(QMouseEvent* event);
- void handleItemClicked(QListWidgetItem* item);
- static QString getNoMessage();
- private:
- void resizeMenu();
- void viewMode();
- void setNewToolTip();
- //QComboBox *types_;
- StatusCache* statusCache_;
- QStackedWidget* stack_;
- QLabel* statusIcon_;
- QtElidingLabel* statusTextLabel_;
- QtLineEdit* statusEdit_;
- QString statusText_;
- QString newStatusText_;
- QMap<StatusShow::Type, QIcon> icons_;
- StatusShow::Type selectedStatusType_;
- bool isClicking_;
- QListWidget* menu_;
- QCursor editCursor_;
- QCursor viewCursor_;
- bool editing_;
- QMovie* connectingMovie_;
- bool connecting_;
- static const QString NO_MESSAGE;
- std::vector<StatusShow::Type> allTypes_;
- };
+ class QtStatusWidget : public QWidget {
+ Q_OBJECT
+ public:
+ QtStatusWidget(StatusCache* statusCache, QWidget *parent);
+ ~QtStatusWidget();
+ StatusShow::Type getSelectedStatusShow();
+ void setStatusType(StatusShow::Type type);
+ void setConnecting();
+ signals:
+ void onChangeStatusRequest(StatusShow::Type showType, const QString& text);
+ public slots:
+ void setStatusText(const QString& text);
+ private slots:
+ void generateList();
+ void handleClicked();
+ void handleEditComplete();
+ void handleEditCancelled();
+ void handleApplicationFocusChanged(QWidget* old, QWidget* now);
+ protected slots:
+ virtual void mousePressEvent(QMouseEvent* event);
+ void handleItemClicked(QListWidgetItem* item);
+ static QString getNoMessage();
+ private:
+ void resizeMenu();
+ void viewMode();
+ void setNewToolTip();
+ //QComboBox *types_;
+ StatusCache* statusCache_;
+ QStackedWidget* stack_;
+ QLabel* statusIcon_;
+ QtElidingLabel* statusTextLabel_;
+ QtLineEdit* statusEdit_;
+ QString statusText_;
+ QString newStatusText_;
+ QMap<StatusShow::Type, QIcon> icons_;
+ StatusShow::Type selectedStatusType_;
+ bool isClicking_;
+ QListWidget* menu_;
+ QCursor editCursor_;
+ QCursor viewCursor_;
+ bool editing_;
+ QMovie* connectingMovie_;
+ bool connecting_;
+ static const QString NO_MESSAGE;
+ std::vector<StatusShow::Type> allTypes_;
+ };
}
diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.cpp b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
index 43cdb50..9e1fc37 100644
--- a/Swift/QtUI/QtSubscriptionRequestWindow.cpp
+++ b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
@@ -15,76 +15,76 @@
namespace Swift {
QtSubscriptionRequestWindow::QtSubscriptionRequestWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent) : QDialog(parent), event_(event) {
- QString text = QString(tr("%1 would like to add you to their contact list.")).arg(P2QSTRING(event->getJID().toString()));
- QVBoxLayout* layout = new QVBoxLayout();
- QLabel* label = new QLabel(text, this);
- layout->addWidget(label);
- label = new QLabel(tr("Would you like to add them to your contact list and share your status when you're online?"));
- //layout->addWidget(new QLabel);
- layout->addWidget(label);
+ QString text = QString(tr("%1 would like to add you to their contact list.")).arg(P2QSTRING(event->getJID().toString()));
+ QVBoxLayout* layout = new QVBoxLayout();
+ QLabel* label = new QLabel(text, this);
+ layout->addWidget(label);
+ label = new QLabel(tr("Would you like to add them to your contact list and share your status when you're online?"));
+ //layout->addWidget(new QLabel);
+ layout->addWidget(label);
- if (event_->getConcluded()) {
- QLabel* doneLabel = new QLabel(tr("You have already replied to this request"));
- QPushButton* okButton = new QPushButton(tr("OK"), this);
- connect(okButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
- layout->addWidget(doneLabel);
- layout->addWidget(okButton);
- } else {
- QPushButton* yesButton = new QPushButton(tr("Accept"), this);
- yesButton->setDefault(true);
- connect(yesButton, SIGNAL(clicked()), this, SLOT(handleYes()));
- QPushButton* noButton = new QPushButton(tr("Reject"), this);
- connect(noButton, SIGNAL(clicked()), this, SLOT(handleNo()));
- QPushButton* deferButton = new QPushButton(tr("Defer"), this);
- deferButton->setShortcut(QKeySequence(Qt::Key_Escape));
- connect(deferButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
+ if (event_->getConcluded()) {
+ QLabel* doneLabel = new QLabel(tr("You have already replied to this request"));
+ QPushButton* okButton = new QPushButton(tr("OK"), this);
+ connect(okButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
+ layout->addWidget(doneLabel);
+ layout->addWidget(okButton);
+ } else {
+ QPushButton* yesButton = new QPushButton(tr("Accept"), this);
+ yesButton->setDefault(true);
+ connect(yesButton, SIGNAL(clicked()), this, SLOT(handleYes()));
+ QPushButton* noButton = new QPushButton(tr("Reject"), this);
+ connect(noButton, SIGNAL(clicked()), this, SLOT(handleNo()));
+ QPushButton* deferButton = new QPushButton(tr("Defer"), this);
+ deferButton->setShortcut(QKeySequence(Qt::Key_Escape));
+ connect(deferButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
- QHBoxLayout* buttonLayout = new QHBoxLayout();
- buttonLayout->addWidget(yesButton);
- buttonLayout->addWidget(noButton);
- buttonLayout->addWidget(deferButton);
- layout->addWidget(new QLabel);
- layout->addLayout(buttonLayout);
- layout->addWidget(new QLabel);
- QLabel* footer = new QLabel(tr("(If you choose to defer this choice, you will be asked again when you next login.)"));
- layout->addWidget(footer);
- }
+ QHBoxLayout* buttonLayout = new QHBoxLayout();
+ buttonLayout->addWidget(yesButton);
+ buttonLayout->addWidget(noButton);
+ buttonLayout->addWidget(deferButton);
+ layout->addWidget(new QLabel);
+ layout->addLayout(buttonLayout);
+ layout->addWidget(new QLabel);
+ QLabel* footer = new QLabel(tr("(If you choose to defer this choice, you will be asked again when you next login.)"));
+ layout->addWidget(footer);
+ }
- setLayout(layout);
+ setLayout(layout);
}
void QtSubscriptionRequestWindow::handleYes() {
- event_->accept();
- delete this;
+ event_->accept();
+ delete this;
}
void QtSubscriptionRequestWindow::handleNo() {
- event_->decline();
- delete this;
+ event_->decline();
+ delete this;
}
void QtSubscriptionRequestWindow::handleDefer() {
- event_->defer();
- delete this;
+ event_->defer();
+ delete this;
}
QtSubscriptionRequestWindow::~QtSubscriptionRequestWindow() {
- windows_.removeOne(this);
+ windows_.removeOne(this);
}
QtSubscriptionRequestWindow* QtSubscriptionRequestWindow::getWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent) {
- foreach (QtSubscriptionRequestWindow* window, windows_) {
- if (window->getEvent() == event) {
- return window;
- }
- }
- QtSubscriptionRequestWindow* window = new QtSubscriptionRequestWindow(event, parent);
- windows_.append(window);
- return window;
+ foreach (QtSubscriptionRequestWindow* window, windows_) {
+ if (window->getEvent() == event) {
+ return window;
+ }
+ }
+ QtSubscriptionRequestWindow* window = new QtSubscriptionRequestWindow(event, parent);
+ windows_.append(window);
+ return window;
}
boost::shared_ptr<SubscriptionRequestEvent> QtSubscriptionRequestWindow::getEvent() {
- return event_;
+ return event_;
}
QList<QtSubscriptionRequestWindow*> QtSubscriptionRequestWindow::windows_;
diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.h b/Swift/QtUI/QtSubscriptionRequestWindow.h
index 02932af..1a36e19 100644
--- a/Swift/QtUI/QtSubscriptionRequestWindow.h
+++ b/Swift/QtUI/QtSubscriptionRequestWindow.h
@@ -13,22 +13,22 @@
#include <Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h>
namespace Swift {
- class QtSubscriptionRequestWindow : public QDialog {
- Q_OBJECT
- public:
- static QtSubscriptionRequestWindow* getWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
- ~QtSubscriptionRequestWindow();
- boost::shared_ptr<SubscriptionRequestEvent> getEvent();
- private slots:
- void handleYes();
- void handleNo();
- void handleDefer();
- private:
- QtSubscriptionRequestWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
- static QList<QtSubscriptionRequestWindow*> windows_;
- boost::shared_ptr<SubscriptionRequestEvent> event_;
- /*QPushButton* yesButton_;
- QPushButton* noButton_;
- QPushButton* deferButton_;*/
- };
+ class QtSubscriptionRequestWindow : public QDialog {
+ Q_OBJECT
+ public:
+ static QtSubscriptionRequestWindow* getWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
+ ~QtSubscriptionRequestWindow();
+ boost::shared_ptr<SubscriptionRequestEvent> getEvent();
+ private slots:
+ void handleYes();
+ void handleNo();
+ void handleDefer();
+ private:
+ QtSubscriptionRequestWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
+ static QList<QtSubscriptionRequestWindow*> windows_;
+ boost::shared_ptr<SubscriptionRequestEvent> event_;
+ /*QPushButton* yesButton_;
+ QPushButton* noButton_;
+ QPushButton* deferButton_;*/
+ };
}
diff --git a/Swift/QtUI/QtSwift.cpp b/Swift/QtUI/QtSwift.cpp
index 6444e0c..5e8d61c 100644
--- a/Swift/QtUI/QtSwift.cpp
+++ b/Swift/QtUI/QtSwift.cpp
@@ -85,203 +85,203 @@ namespace Swift{
#endif
po::options_description QtSwift::getOptionsDescription() {
- po::options_description result("Options");
- result.add_options()
- ("debug", "Turn on debug logging")
- ("help", "Show this help message")
- ("version", "Show version information")
- ("netbook-mode", "Use netbook mode display (unsupported)")
- ("no-tabs", "Don't manage chat windows in tabs (unsupported)")
- ("latency-debug", "Use latency debugging (unsupported)")
- ("multi-account", po::value<int>()->default_value(1), "Number of accounts to open windows for (unsupported)")
- ("start-minimized", "Don't show the login/roster window at startup")
- ("enable-jid-adhocs", "Enable AdHoc commands to custom JID's.")
- ("trellis", "Enable support for trellis layout")
+ po::options_description result("Options");
+ result.add_options()
+ ("debug", "Turn on debug logging")
+ ("help", "Show this help message")
+ ("version", "Show version information")
+ ("netbook-mode", "Use netbook mode display (unsupported)")
+ ("no-tabs", "Don't manage chat windows in tabs (unsupported)")
+ ("latency-debug", "Use latency debugging (unsupported)")
+ ("multi-account", po::value<int>()->default_value(1), "Number of accounts to open windows for (unsupported)")
+ ("start-minimized", "Don't show the login/roster window at startup")
+ ("enable-jid-adhocs", "Enable AdHoc commands to custom JID's.")
+ ("trellis", "Enable support for trellis layout")
#if QT_VERSION >= 0x040800
- ("language", po::value<std::string>(), "Use a specific language, instead of the system-wide one")
+ ("language", po::value<std::string>(), "Use a specific language, instead of the system-wide one")
#endif
- ;
- return result;
+ ;
+ return result;
}
XMLSettingsProvider* QtSwift::loadSettingsFile(const QString& fileName) {
- QFile configFile(fileName);
- if (configFile.exists() && configFile.open(QIODevice::ReadOnly)) {
- QString xmlString;
- while (!configFile.atEnd()) {
- QByteArray line = configFile.readLine();
- xmlString += line + "\n";
- }
- return new XMLSettingsProvider(Q2PSTRING(xmlString));
- }
- return new XMLSettingsProvider("");
+ QFile configFile(fileName);
+ if (configFile.exists() && configFile.open(QIODevice::ReadOnly)) {
+ QString xmlString;
+ while (!configFile.atEnd()) {
+ QByteArray line = configFile.readLine();
+ xmlString += line + "\n";
+ }
+ return new XMLSettingsProvider(Q2PSTRING(xmlString));
+ }
+ return new XMLSettingsProvider("");
}
void QtSwift::loadEmoticonsFile(const QString& fileName, std::map<std::string, std::string>& emoticons) {
- QFile file(fileName);
- if (file.exists() && file.open(QIODevice::ReadOnly)) {
- while (!file.atEnd()) {
- QString line = file.readLine();
- line.replace("\n", "");
- line.replace("\r", "");
- QStringList tokens = line.split(" ");
- if (tokens.size() == 2) {
- QString emoticonFile = tokens[1];
- if (!emoticonFile.startsWith(":/") && !emoticonFile.startsWith("qrc:/")) {
- emoticonFile = "file://" + emoticonFile;
- }
- emoticons[Q2PSTRING(tokens[0])] = Q2PSTRING(emoticonFile);
- }
- }
- }
+ QFile file(fileName);
+ if (file.exists() && file.open(QIODevice::ReadOnly)) {
+ while (!file.atEnd()) {
+ QString line = file.readLine();
+ line.replace("\n", "");
+ line.replace("\r", "");
+ QStringList tokens = line.split(" ");
+ if (tokens.size() == 2) {
+ QString emoticonFile = tokens[1];
+ if (!emoticonFile.startsWith(":/") && !emoticonFile.startsWith("qrc:/")) {
+ emoticonFile = "file://" + emoticonFile;
+ }
+ emoticons[Q2PSTRING(tokens[0])] = Q2PSTRING(emoticonFile);
+ }
+ }
+ }
}
QtSwift::QtSwift(const po::variables_map& options) : networkFactories_(&clientMainThreadCaller_), autoUpdater_(NULL), idleDetector_(&idleQuerier_, networkFactories_.getTimerFactory(), 1000) {
- QCoreApplication::setApplicationName(SWIFT_APPLICATION_NAME);
- QCoreApplication::setOrganizationName(SWIFT_ORGANIZATION_NAME);
- QCoreApplication::setOrganizationDomain(SWIFT_ORGANIZATION_DOMAIN);
- QCoreApplication::setApplicationVersion(buildVersion);
-
- qtSettings_ = new QtSettingsProvider();
- xmlSettings_ = loadSettingsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "system-settings.xml")));
- settingsHierachy_ = new SettingsProviderHierachy();
- settingsHierachy_->addProviderToTopOfStack(xmlSettings_);
- settingsHierachy_->addProviderToTopOfStack(qtSettings_);
-
- networkFactories_.getTLSContextFactory()->setDisconnectOnCardRemoval(settingsHierachy_->getSetting(SettingConstants::DISCONNECT_ON_CARD_REMOVAL));
-
- std::map<std::string, std::string> emoticons;
- loadEmoticonsFile(":/emoticons/emoticons.txt", emoticons);
- loadEmoticonsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "emoticons.txt")), emoticons);
-
- if (options.count("netbook-mode")) {
- splitter_ = new QtSingleWindow(qtSettings_);
- } else {
- splitter_ = NULL;
- }
-
- int numberOfAccounts = 1;
- try {
- numberOfAccounts = options["multi-account"].as<int>();
- } catch (...) {
- /* This seems to fail on a Mac when the .app is launched directly (the usual path).*/
- numberOfAccounts = 1;
- }
-
- if (options.count("debug")) {
- Log::setLogLevel(Swift::Log::debug);
- }
-
- bool enableAdHocCommandOnJID = options.count("enable-jid-adhocs") > 0;
- tabs_ = NULL;
- if (options.count("no-tabs") && !splitter_) {
- tabs_ = new QtChatTabsShortcutOnlySubstitute();
- }
- else {
- tabs_ = new QtChatTabs(splitter_ != NULL, settingsHierachy_, options.count("trellis"));
- }
- bool startMinimized = options.count("start-minimized") > 0;
- applicationPathProvider_ = new PlatformApplicationPathProvider(SWIFT_APPLICATION_NAME);
- storagesFactory_ = new FileStoragesFactory(applicationPathProvider_->getDataDir(), networkFactories_.getCryptoProvider());
- certificateStorageFactory_ = new CertificateFileStorageFactory(applicationPathProvider_->getDataDir(), tlsFactories_.getCertificateFactory(), networkFactories_.getCryptoProvider());
- chatWindowFactory_ = new QtChatWindowFactory(splitter_, settingsHierachy_, qtSettings_, tabs_, ":/themes/Default/", emoticons);
- soundPlayer_ = new QtSoundPlayer(applicationPathProvider_);
-
- // Ugly, because the dock depends on the tray, but the temporary
- // multi-account hack creates one tray per account.
- QtSystemTray* systemTray = new QtSystemTray();
- systemTrays_.push_back(systemTray);
+ QCoreApplication::setApplicationName(SWIFT_APPLICATION_NAME);
+ QCoreApplication::setOrganizationName(SWIFT_ORGANIZATION_NAME);
+ QCoreApplication::setOrganizationDomain(SWIFT_ORGANIZATION_DOMAIN);
+ QCoreApplication::setApplicationVersion(buildVersion);
+
+ qtSettings_ = new QtSettingsProvider();
+ xmlSettings_ = loadSettingsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "system-settings.xml")));
+ settingsHierachy_ = new SettingsProviderHierachy();
+ settingsHierachy_->addProviderToTopOfStack(xmlSettings_);
+ settingsHierachy_->addProviderToTopOfStack(qtSettings_);
+
+ networkFactories_.getTLSContextFactory()->setDisconnectOnCardRemoval(settingsHierachy_->getSetting(SettingConstants::DISCONNECT_ON_CARD_REMOVAL));
+
+ std::map<std::string, std::string> emoticons;
+ loadEmoticonsFile(":/emoticons/emoticons.txt", emoticons);
+ loadEmoticonsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "emoticons.txt")), emoticons);
+
+ if (options.count("netbook-mode")) {
+ splitter_ = new QtSingleWindow(qtSettings_);
+ } else {
+ splitter_ = NULL;
+ }
+
+ int numberOfAccounts = 1;
+ try {
+ numberOfAccounts = options["multi-account"].as<int>();
+ } catch (...) {
+ /* This seems to fail on a Mac when the .app is launched directly (the usual path).*/
+ numberOfAccounts = 1;
+ }
+
+ if (options.count("debug")) {
+ Log::setLogLevel(Swift::Log::debug);
+ }
+
+ bool enableAdHocCommandOnJID = options.count("enable-jid-adhocs") > 0;
+ tabs_ = NULL;
+ if (options.count("no-tabs") && !splitter_) {
+ tabs_ = new QtChatTabsShortcutOnlySubstitute();
+ }
+ else {
+ tabs_ = new QtChatTabs(splitter_ != NULL, settingsHierachy_, options.count("trellis"));
+ }
+ bool startMinimized = options.count("start-minimized") > 0;
+ applicationPathProvider_ = new PlatformApplicationPathProvider(SWIFT_APPLICATION_NAME);
+ storagesFactory_ = new FileStoragesFactory(applicationPathProvider_->getDataDir(), networkFactories_.getCryptoProvider());
+ certificateStorageFactory_ = new CertificateFileStorageFactory(applicationPathProvider_->getDataDir(), tlsFactories_.getCertificateFactory(), networkFactories_.getCryptoProvider());
+ chatWindowFactory_ = new QtChatWindowFactory(splitter_, settingsHierachy_, qtSettings_, tabs_, ":/themes/Default/", emoticons);
+ soundPlayer_ = new QtSoundPlayer(applicationPathProvider_);
+
+ // Ugly, because the dock depends on the tray, but the temporary
+ // multi-account hack creates one tray per account.
+ QtSystemTray* systemTray = new QtSystemTray();
+ systemTrays_.push_back(systemTray);
#if defined(HAVE_GROWL)
- notifier_ = new GrowlNotifier(SWIFT_APPLICATION_NAME);
+ notifier_ = new GrowlNotifier(SWIFT_APPLICATION_NAME);
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
- notifier_ = new WindowsNotifier(SWIFT_APPLICATION_NAME, applicationPathProvider_->getResourcePath("/images/logo-icon-32.png"), systemTray->getQSystemTrayIcon());
+ notifier_ = new WindowsNotifier(SWIFT_APPLICATION_NAME, applicationPathProvider_->getResourcePath("/images/logo-icon-32.png"), systemTray->getQSystemTrayIcon());
#elif defined(SWIFTEN_PLATFORM_LINUX)
- notifier_ = new FreeDesktopNotifier(SWIFT_APPLICATION_NAME);
+ notifier_ = new FreeDesktopNotifier(SWIFT_APPLICATION_NAME);
#elif defined(SWIFTEN_PLATFORM_MACOSX)
- notifier_ = new NotificationCenterNotifier();
+ notifier_ = new NotificationCenterNotifier();
#else
- notifier_ = new NullNotifier();
+ notifier_ = new NullNotifier();
#endif
#if defined(SWIFTEN_PLATFORM_MACOSX)
- dock_ = new MacOSXDock(&cocoaApplication_);
+ dock_ = new MacOSXDock(&cocoaApplication_);
#else
- dock_ = new NullDock();
+ dock_ = new NullDock();
#endif
#if defined(SWIFTEN_PLATFORM_MACOSX)
- uriHandler_ = new QtURIHandler();
+ uriHandler_ = new QtURIHandler();
#elif defined(SWIFTEN_PLATFORM_WIN32)
- uriHandler_ = new NullURIHandler();
+ uriHandler_ = new NullURIHandler();
#else
- uriHandler_ = new QtDBUSURIHandler();
+ uriHandler_ = new QtDBUSURIHandler();
#endif
- statusCache_ = new StatusCache(applicationPathProvider_);
-
- if (splitter_) {
- splitter_->show();
- }
-
- for (int i = 0; i < numberOfAccounts; i++) {
- if (i > 0) {
- // Don't add the first tray (see note above)
- systemTrays_.push_back(new QtSystemTray());
- }
- QtUIFactory* uiFactory = new QtUIFactory(settingsHierachy_, qtSettings_, tabs_, splitter_, systemTrays_[i], chatWindowFactory_, networkFactories_.getTimerFactory(), statusCache_, startMinimized, !emoticons.empty(), enableAdHocCommandOnJID);
- uiFactories_.push_back(uiFactory);
- MainController* mainController = new MainController(
- &clientMainThreadCaller_,
- &networkFactories_,
- uiFactory,
- settingsHierachy_,
- systemTrays_[i],
- soundPlayer_,
- storagesFactory_,
- certificateStorageFactory_,
- dock_,
- notifier_,
- uriHandler_,
- &idleDetector_,
- emoticons,
- options.count("latency-debug") > 0);
- mainControllers_.push_back(mainController);
- }
-
-
- // PlatformAutoUpdaterFactory autoUpdaterFactory;
- // if (autoUpdaterFactory.isSupported()) {
- // autoUpdater_ = autoUpdaterFactory.createAutoUpdater(SWIFT_APPCAST_URL);
- // autoUpdater_->checkForUpdates();
- // }
+ statusCache_ = new StatusCache(applicationPathProvider_);
+
+ if (splitter_) {
+ splitter_->show();
+ }
+
+ for (int i = 0; i < numberOfAccounts; i++) {
+ if (i > 0) {
+ // Don't add the first tray (see note above)
+ systemTrays_.push_back(new QtSystemTray());
+ }
+ QtUIFactory* uiFactory = new QtUIFactory(settingsHierachy_, qtSettings_, tabs_, splitter_, systemTrays_[i], chatWindowFactory_, networkFactories_.getTimerFactory(), statusCache_, startMinimized, !emoticons.empty(), enableAdHocCommandOnJID);
+ uiFactories_.push_back(uiFactory);
+ MainController* mainController = new MainController(
+ &clientMainThreadCaller_,
+ &networkFactories_,
+ uiFactory,
+ settingsHierachy_,
+ systemTrays_[i],
+ soundPlayer_,
+ storagesFactory_,
+ certificateStorageFactory_,
+ dock_,
+ notifier_,
+ uriHandler_,
+ &idleDetector_,
+ emoticons,
+ options.count("latency-debug") > 0);
+ mainControllers_.push_back(mainController);
+ }
+
+
+ // PlatformAutoUpdaterFactory autoUpdaterFactory;
+ // if (autoUpdaterFactory.isSupported()) {
+ // autoUpdater_ = autoUpdaterFactory.createAutoUpdater(SWIFT_APPCAST_URL);
+ // autoUpdater_->checkForUpdates();
+ // }
}
QtSwift::~QtSwift() {
- delete autoUpdater_;
- foreach (QtUIFactory* factory, uiFactories_) {
- delete factory;
- }
- foreach (MainController* controller, mainControllers_) {
- delete controller;
- }
- delete notifier_;
- foreach (QtSystemTray* tray, systemTrays_) {
- delete tray;
- }
- delete tabs_;
- delete splitter_;
- delete settingsHierachy_;
- delete qtSettings_;
- delete xmlSettings_;
- delete statusCache_;
- delete uriHandler_;
- delete dock_;
- delete soundPlayer_;
- delete chatWindowFactory_;
- delete certificateStorageFactory_;
- delete storagesFactory_;
- delete applicationPathProvider_;
+ delete autoUpdater_;
+ foreach (QtUIFactory* factory, uiFactories_) {
+ delete factory;
+ }
+ foreach (MainController* controller, mainControllers_) {
+ delete controller;
+ }
+ delete notifier_;
+ foreach (QtSystemTray* tray, systemTrays_) {
+ delete tray;
+ }
+ delete tabs_;
+ delete splitter_;
+ delete settingsHierachy_;
+ delete qtSettings_;
+ delete xmlSettings_;
+ delete statusCache_;
+ delete uriHandler_;
+ delete dock_;
+ delete soundPlayer_;
+ delete chatWindowFactory_;
+ delete certificateStorageFactory_;
+ delete storagesFactory_;
+ delete applicationPathProvider_;
}
}
diff --git a/Swift/QtUI/QtSwift.h b/Swift/QtUI/QtSwift.h
index a971324..9932545 100644
--- a/Swift/QtUI/QtSwift.h
+++ b/Swift/QtUI/QtSwift.h
@@ -30,65 +30,65 @@ namespace po = boost::program_options;
class QSplitter;
namespace Swift {
- class QtUIFactory;
- class CertificateStorageFactory;
- class Dock;
- class Notifier;
- class StoragesFactory;
- class AutoUpdater;
- class ApplicationPathProvider;
- class AvatarStorage;
- class CapsStorage;
- class MainController;
- class QtSystemTray;
- class QtChatTabsBase;
- class QtChatWindowFactory;
- class QtSoundPlayer;
- class QtMUCSearchWindowFactory;
- class QtUserSearchWindowFactory;
- class EventLoop;
- class URIHandler;
- class SettingsProviderHierachy;
- class XMLSettingsProvider;
- class StatusCache;
- class QtSingleWindow;
-
- class QtSwift : public QObject {
- Q_OBJECT
- public:
- QtSwift(const po::variables_map& options);
- static po::options_description getOptionsDescription();
- ~QtSwift();
- private:
- XMLSettingsProvider* loadSettingsFile(const QString& fileName);
- void loadEmoticonsFile(const QString& fileName, std::map<std::string, std::string>& emoticons);
- private:
- QtEventLoop clientMainThreadCaller_;
- PlatformTLSFactories tlsFactories_;
- BoostNetworkFactories networkFactories_;
- QtChatWindowFactory* chatWindowFactory_;
- std::vector<MainController*> mainControllers_;
- std::vector<QtSystemTray*> systemTrays_;
- std::vector<QtUIFactory*> uiFactories_;
- QtSettingsProvider* qtSettings_;
- XMLSettingsProvider* xmlSettings_;
- SettingsProviderHierachy* settingsHierachy_;
- QtSingleWindow* splitter_;
- QtSoundPlayer* soundPlayer_;
- Dock* dock_;
- URIHandler* uriHandler_;
- QtChatTabsBase* tabs_;
- ApplicationPathProvider* applicationPathProvider_;
- StoragesFactory* storagesFactory_;
- CertificateStorageFactory* certificateStorageFactory_;
- AutoUpdater* autoUpdater_;
- Notifier* notifier_;
- StatusCache* statusCache_;
- PlatformIdleQuerier idleQuerier_;
- ActualIdleDetector idleDetector_;
+ class QtUIFactory;
+ class CertificateStorageFactory;
+ class Dock;
+ class Notifier;
+ class StoragesFactory;
+ class AutoUpdater;
+ class ApplicationPathProvider;
+ class AvatarStorage;
+ class CapsStorage;
+ class MainController;
+ class QtSystemTray;
+ class QtChatTabsBase;
+ class QtChatWindowFactory;
+ class QtSoundPlayer;
+ class QtMUCSearchWindowFactory;
+ class QtUserSearchWindowFactory;
+ class EventLoop;
+ class URIHandler;
+ class SettingsProviderHierachy;
+ class XMLSettingsProvider;
+ class StatusCache;
+ class QtSingleWindow;
+
+ class QtSwift : public QObject {
+ Q_OBJECT
+ public:
+ QtSwift(const po::variables_map& options);
+ static po::options_description getOptionsDescription();
+ ~QtSwift();
+ private:
+ XMLSettingsProvider* loadSettingsFile(const QString& fileName);
+ void loadEmoticonsFile(const QString& fileName, std::map<std::string, std::string>& emoticons);
+ private:
+ QtEventLoop clientMainThreadCaller_;
+ PlatformTLSFactories tlsFactories_;
+ BoostNetworkFactories networkFactories_;
+ QtChatWindowFactory* chatWindowFactory_;
+ std::vector<MainController*> mainControllers_;
+ std::vector<QtSystemTray*> systemTrays_;
+ std::vector<QtUIFactory*> uiFactories_;
+ QtSettingsProvider* qtSettings_;
+ XMLSettingsProvider* xmlSettings_;
+ SettingsProviderHierachy* settingsHierachy_;
+ QtSingleWindow* splitter_;
+ QtSoundPlayer* soundPlayer_;
+ Dock* dock_;
+ URIHandler* uriHandler_;
+ QtChatTabsBase* tabs_;
+ ApplicationPathProvider* applicationPathProvider_;
+ StoragesFactory* storagesFactory_;
+ CertificateStorageFactory* certificateStorageFactory_;
+ AutoUpdater* autoUpdater_;
+ Notifier* notifier_;
+ StatusCache* statusCache_;
+ PlatformIdleQuerier idleQuerier_;
+ ActualIdleDetector idleDetector_;
#if defined(SWIFTEN_PLATFORM_MACOSX)
- CocoaApplication cocoaApplication_;
- CocoaApplicationActivateHelper cocoaApplicationActivateHelper_;
+ CocoaApplication cocoaApplication_;
+ CocoaApplicationActivateHelper cocoaApplicationActivateHelper_;
#endif
- };
+ };
}
diff --git a/Swift/QtUI/QtSystemTray.cpp b/Swift/QtUI/QtSystemTray.cpp
index d268d16..55a7d43 100644
--- a/Swift/QtUI/QtSystemTray.cpp
+++ b/Swift/QtUI/QtSystemTray.cpp
@@ -20,71 +20,71 @@
namespace Swift {
QtSystemTray::QtSystemTray() : QObject(), statusType_(StatusShow::None), trayMenu_(0), onlineIcon_(":icons/online.png"), awayIcon_(":icons/away.png"), dndIcon_(":icons/dnd.png"), offlineIcon_(":icons/offline.png"), newMessageIcon_(":icons/new-chat.png"), throbberMovie_(":/icons/connecting.mng"), unreadMessages_(false), connecting_(false) {
- trayIcon_ = new QSystemTrayIcon(offlineIcon_);
- trayIcon_->setToolTip("Swift");
- connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(handleIconActivated(QSystemTrayIcon::ActivationReason)));
- connect(&throbberMovie_, SIGNAL(frameChanged(int)), this, SLOT(handleThrobberFrameChanged(int)));
+ trayIcon_ = new QSystemTrayIcon(offlineIcon_);
+ trayIcon_->setToolTip("Swift");
+ connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(handleIconActivated(QSystemTrayIcon::ActivationReason)));
+ connect(&throbberMovie_, SIGNAL(frameChanged(int)), this, SLOT(handleThrobberFrameChanged(int)));
#if defined (Q_OS_UNIX) && !defined(Q_OS_MAC)
- bool isUnity = QDBusInterface("com.canonical.Unity.Launcher", "/com/canonical/Unity/Launcher").isValid();
- if (isUnity) {
- // Add an activation menu, because this is the only way to get the application to the
- // front on Unity. See the README for sni-qt (which handles Qt tray icons for Unity)
- trayMenu_ = new QMenu();
- QAction* showAction = new QAction(QString("Show/Hide"), this);
- connect(showAction, SIGNAL(triggered()), SIGNAL(clicked()));
- trayMenu_->addAction(showAction);
- trayIcon_->setContextMenu(trayMenu_);
- }
+ bool isUnity = QDBusInterface("com.canonical.Unity.Launcher", "/com/canonical/Unity/Launcher").isValid();
+ if (isUnity) {
+ // Add an activation menu, because this is the only way to get the application to the
+ // front on Unity. See the README for sni-qt (which handles Qt tray icons for Unity)
+ trayMenu_ = new QMenu();
+ QAction* showAction = new QAction(QString("Show/Hide"), this);
+ connect(showAction, SIGNAL(triggered()), SIGNAL(clicked()));
+ trayMenu_->addAction(showAction);
+ trayIcon_->setContextMenu(trayMenu_);
+ }
#endif
- trayIcon_->show();
+ trayIcon_->show();
}
QtSystemTray::~QtSystemTray() {
- delete trayMenu_;
- delete trayIcon_;
+ delete trayMenu_;
+ delete trayIcon_;
}
void QtSystemTray::setUnreadMessages(bool some) {
- unreadMessages_ = some;
- updateStatusIcon();
+ unreadMessages_ = some;
+ updateStatusIcon();
}
void QtSystemTray::handleThrobberFrameChanged(int /*frameNumber*/) {
- trayIcon_->setIcon(QIcon(throbberMovie_.currentPixmap()));
+ trayIcon_->setIcon(QIcon(throbberMovie_.currentPixmap()));
}
void QtSystemTray::setConnecting() {
- connecting_ = true;
- updateStatusIcon();
+ connecting_ = true;
+ updateStatusIcon();
}
void QtSystemTray::handleIconActivated(QSystemTrayIcon::ActivationReason reason) {
- if (reason == QSystemTrayIcon::Trigger) {
- emit clicked();
- }
+ if (reason == QSystemTrayIcon::Trigger) {
+ emit clicked();
+ }
}
void QtSystemTray::setStatusType(StatusShow::Type type) {
- connecting_ = false;
- statusType_ = type;
- updateStatusIcon();
+ connecting_ = false;
+ statusType_ = type;
+ updateStatusIcon();
}
void QtSystemTray::updateStatusIcon() {
- throbberMovie_.stop();
- if (unreadMessages_) {
- trayIcon_->setIcon(newMessageIcon_);
- } else if (connecting_) {
- throbberMovie_.start();
- } else {
- switch (statusType_) {
- case StatusShow::Online : trayIcon_->setIcon(onlineIcon_);break;
- case StatusShow::FFC : trayIcon_->setIcon(onlineIcon_);break;
- case StatusShow::Away : trayIcon_->setIcon(awayIcon_);break;
- case StatusShow::XA : trayIcon_->setIcon(awayIcon_);break;
- case StatusShow::DND : trayIcon_->setIcon(dndIcon_);break;
- case StatusShow::None : trayIcon_->setIcon(offlineIcon_);break;
- }
- }
+ throbberMovie_.stop();
+ if (unreadMessages_) {
+ trayIcon_->setIcon(newMessageIcon_);
+ } else if (connecting_) {
+ throbberMovie_.start();
+ } else {
+ switch (statusType_) {
+ case StatusShow::Online : trayIcon_->setIcon(onlineIcon_);break;
+ case StatusShow::FFC : trayIcon_->setIcon(onlineIcon_);break;
+ case StatusShow::Away : trayIcon_->setIcon(awayIcon_);break;
+ case StatusShow::XA : trayIcon_->setIcon(awayIcon_);break;
+ case StatusShow::DND : trayIcon_->setIcon(dndIcon_);break;
+ case StatusShow::None : trayIcon_->setIcon(offlineIcon_);break;
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtSystemTray.h b/Swift/QtUI/QtSystemTray.h
index b1dffd0..ba2c5cb 100644
--- a/Swift/QtUI/QtSystemTray.h
+++ b/Swift/QtUI/QtSystemTray.h
@@ -16,35 +16,35 @@ class QMenu;
namespace Swift {
- class QtSystemTray : public QObject, public SystemTray {
- Q_OBJECT
- public:
- QtSystemTray();
- ~QtSystemTray();
- void setUnreadMessages(bool some);
- void setStatusType(StatusShow::Type type);
- void setConnecting();
- QSystemTrayIcon* getQSystemTrayIcon() {
- return trayIcon_;
- }
+ class QtSystemTray : public QObject, public SystemTray {
+ Q_OBJECT
+ public:
+ QtSystemTray();
+ ~QtSystemTray();
+ void setUnreadMessages(bool some);
+ void setStatusType(StatusShow::Type type);
+ void setConnecting();
+ QSystemTrayIcon* getQSystemTrayIcon() {
+ return trayIcon_;
+ }
- signals:
- void clicked();
- private slots:
- void handleIconActivated(QSystemTrayIcon::ActivationReason reason);
- void handleThrobberFrameChanged(int);
- private:
- void updateStatusIcon();
- StatusShow::Type statusType_;
- QSystemTrayIcon* trayIcon_;
- QMenu* trayMenu_;
- QIcon onlineIcon_;
- QIcon awayIcon_;
- QIcon dndIcon_;
- QIcon offlineIcon_;
- QIcon newMessageIcon_;
- QMovie throbberMovie_;
- bool unreadMessages_;
- bool connecting_;
- };
+ signals:
+ void clicked();
+ private slots:
+ void handleIconActivated(QSystemTrayIcon::ActivationReason reason);
+ void handleThrobberFrameChanged(int);
+ private:
+ void updateStatusIcon();
+ StatusShow::Type statusType_;
+ QSystemTrayIcon* trayIcon_;
+ QMenu* trayMenu_;
+ QIcon onlineIcon_;
+ QIcon awayIcon_;
+ QIcon dndIcon_;
+ QIcon offlineIcon_;
+ QIcon newMessageIcon_;
+ QMovie throbberMovie_;
+ bool unreadMessages_;
+ bool connecting_;
+ };
}
diff --git a/Swift/QtUI/QtTabWidget.cpp b/Swift/QtUI/QtTabWidget.cpp
index ca9ea5d..9f353d7 100644
--- a/Swift/QtUI/QtTabWidget.cpp
+++ b/Swift/QtUI/QtTabWidget.cpp
@@ -17,10 +17,10 @@ QtTabWidget::~QtTabWidget() {
}
QTabBar* QtTabWidget::tabBar() {
- return QTabWidget::tabBar();
+ return QTabWidget::tabBar();
}
void QtTabWidget::setTabBar(QTabBar* tabBar) {
- QTabWidget::setTabBar(tabBar);
+ QTabWidget::setTabBar(tabBar);
}
}
diff --git a/Swift/QtUI/QtTabWidget.h b/Swift/QtUI/QtTabWidget.h
index 0a723e2..de1a846 100644
--- a/Swift/QtUI/QtTabWidget.h
+++ b/Swift/QtUI/QtTabWidget.h
@@ -9,13 +9,13 @@
#include <QTabWidget>
namespace Swift {
- class QtTabWidget : public QTabWidget {
- Q_OBJECT
- public:
- QtTabWidget(QWidget* parent);
- virtual ~QtTabWidget();
+ class QtTabWidget : public QTabWidget {
+ Q_OBJECT
+ public:
+ QtTabWidget(QWidget* parent);
+ virtual ~QtTabWidget();
- QTabBar* tabBar();
- void setTabBar(QTabBar* tabBar);
- };
+ QTabBar* tabBar();
+ void setTabBar(QTabBar* tabBar);
+ };
}
diff --git a/Swift/QtUI/QtTabbable.cpp b/Swift/QtUI/QtTabbable.cpp
index 0e08343..bad6315 100644
--- a/Swift/QtUI/QtTabbable.cpp
+++ b/Swift/QtUI/QtTabbable.cpp
@@ -23,47 +23,47 @@ QtTabbable::QtTabbable() : QWidget() {
}
QtTabbable::~QtTabbable() {
- emit windowClosing();
+ emit windowClosing();
}
bool QtTabbable::isWidgetSelected() {
- /*isActiveWindow() shouldn't be necessary, but I don't trust it as far as I can throw it*/
- if (!isActiveWindow()) {
- return false;
- }
- QtChatTabs* parent = qobject_cast<QtChatTabs*>(window());
- return parent ? parent->getCurrentTab() == this : isAncestorOf(QApplication::focusWidget());
+ /*isActiveWindow() shouldn't be necessary, but I don't trust it as far as I can throw it*/
+ if (!isActiveWindow()) {
+ return false;
+ }
+ QtChatTabs* parent = qobject_cast<QtChatTabs*>(window());
+ return parent ? parent->getCurrentTab() == this : isAncestorOf(QApplication::focusWidget());
}
bool QtTabbable::event(QEvent* event) {
- QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
- if (keyEvent) {
- // According to Qt's focus documentation, one can only override CTRL+TAB via reimplementing QWidget::event().
- if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Tab) {
- // Only handle KeyRelease event as Linux also generate KeyPress event in case of CTRL+TAB being pressed
- // in the roster of a MUC.
- if (keyEvent->type() == QEvent::KeyRelease) {
- emit requestNextTab();
- }
- return true;
- }
+ QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
+ if (keyEvent) {
+ // According to Qt's focus documentation, one can only override CTRL+TAB via reimplementing QWidget::event().
+ if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Tab) {
+ // Only handle KeyRelease event as Linux also generate KeyPress event in case of CTRL+TAB being pressed
+ // in the roster of a MUC.
+ if (keyEvent->type() == QEvent::KeyRelease) {
+ emit requestNextTab();
+ }
+ return true;
+ }
#ifdef SWIFTEN_PLATFORM_LINUX
- else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab && keyEvent->type() != QEvent::KeyRelease) {
+ else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab && keyEvent->type() != QEvent::KeyRelease) {
#else
- else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab) {
+ else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab) {
#endif
#ifdef SWIFTEN_PLATFORM_WINDOWS
- // Windows emits both the KeyPress and KeyRelease events.
- if (keyEvent->type() == QEvent::KeyPress) {
+ // Windows emits both the KeyPress and KeyRelease events.
+ if (keyEvent->type() == QEvent::KeyPress) {
#else
- if (keyEvent->type() != QEvent::ShortcutOverride) {
+ if (keyEvent->type() != QEvent::ShortcutOverride) {
#endif
- emit requestPreviousTab();
- }
- return true;
- }
- }
- return QWidget::event(event);
+ emit requestPreviousTab();
+ }
+ return true;
+ }
+ }
+ return QWidget::event(event);
}
}
diff --git a/Swift/QtUI/QtTabbable.h b/Swift/QtUI/QtTabbable.h
index db83ba9..c2d0961 100644
--- a/Swift/QtUI/QtTabbable.h
+++ b/Swift/QtUI/QtTabbable.h
@@ -11,29 +11,29 @@
#include <QWidget>
namespace Swift {
- class QtTabbable : public QWidget {
- Q_OBJECT
- public:
- enum AlertType {NoActivity, WaitingActivity, ImpendingActivity};
- virtual ~QtTabbable();
- bool isWidgetSelected();
- virtual AlertType getWidgetAlertState() {return NoActivity;}
- virtual int getCount() {return 0;}
- virtual std::string getID() const = 0;
+ class QtTabbable : public QWidget {
+ Q_OBJECT
+ public:
+ enum AlertType {NoActivity, WaitingActivity, ImpendingActivity};
+ virtual ~QtTabbable();
+ bool isWidgetSelected();
+ virtual AlertType getWidgetAlertState() {return NoActivity;}
+ virtual int getCount() {return 0;}
+ virtual std::string getID() const = 0;
- protected:
- QtTabbable();
- bool event(QEvent* event);
+ protected:
+ QtTabbable();
+ bool event(QEvent* event);
- signals:
- void titleUpdated();
- void countUpdated();
- void windowClosing();
- void windowOpening();
- void wantsToActivate();
- void requestPreviousTab();
- void requestNextTab();
- void requestActiveTab();
- void requestFlash();
- };
+ signals:
+ void titleUpdated();
+ void countUpdated();
+ void windowClosing();
+ void windowOpening();
+ void wantsToActivate();
+ void requestPreviousTab();
+ void requestNextTab();
+ void requestActiveTab();
+ void requestFlash();
+ };
}
diff --git a/Swift/QtUI/QtTextEdit.cpp b/Swift/QtUI/QtTextEdit.cpp
index adf3878..d3ba914 100644
--- a/Swift/QtUI/QtTextEdit.cpp
+++ b/Swift/QtUI/QtTextEdit.cpp
@@ -30,202 +30,202 @@
namespace Swift {
QtTextEdit::QtTextEdit(SettingsProvider* settings, QWidget* parent) : QTextEdit(parent), checker_(NULL), highlighter_(NULL) {
- connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged()));
- settings_ = settings;
+ connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged()));
+ settings_ = settings;
#ifdef HAVE_SPELLCHECKER
- setUpSpellChecker();
+ setUpSpellChecker();
#endif
- handleTextChanged();
- QTextOption textOption = document()->defaultTextOption();
- textOption.setWrapMode(QTextOption::WordWrap);
- document()->setDefaultTextOption(textOption);
+ handleTextChanged();
+ QTextOption textOption = document()->defaultTextOption();
+ textOption.setWrapMode(QTextOption::WordWrap);
+ document()->setDefaultTextOption(textOption);
}
QtTextEdit::~QtTextEdit() {
- delete checker_;
+ delete checker_;
}
void QtTextEdit::keyPressEvent(QKeyEvent* event) {
- int key = event->key();
- Qt::KeyboardModifiers modifiers = event->modifiers();
- if ((key == Qt::Key_Enter || key == Qt::Key_Return)
- && (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier)) {
- emit returnPressed();
- }
- else if (((key == Qt::Key_PageUp || key == Qt::Key_PageDown) && modifiers == Qt::ShiftModifier)
- || (key == Qt::Key_C && modifiers == Qt::ControlModifier && textCursor().selectedText().isEmpty())
- || (key == Qt::Key_W && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_PageUp && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_PageDown && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_Tab && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_A && modifiers == Qt::AltModifier)
- || (key == Qt::Key_Tab)
- ) {
- emit unhandledKeyPressEvent(event);
- }
- else if ((key == Qt::Key_Up)
- || (key == Qt::Key_Down)) {
- emit unhandledKeyPressEvent(event);
- QTextEdit::keyPressEvent(event);
- }
- else if ((key == Qt::Key_K && modifiers == QtUtilities::ctrlHardwareKeyModifier)) {
- QTextCursor cursor = textCursor();
- cursor.setPosition(toPlainText().size(), QTextCursor::KeepAnchor);
- cursor.removeSelectedText();
- }
- else {
- QTextEdit::keyPressEvent(event);
- }
+ int key = event->key();
+ Qt::KeyboardModifiers modifiers = event->modifiers();
+ if ((key == Qt::Key_Enter || key == Qt::Key_Return)
+ && (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier)) {
+ emit returnPressed();
+ }
+ else if (((key == Qt::Key_PageUp || key == Qt::Key_PageDown) && modifiers == Qt::ShiftModifier)
+ || (key == Qt::Key_C && modifiers == Qt::ControlModifier && textCursor().selectedText().isEmpty())
+ || (key == Qt::Key_W && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_PageUp && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_PageDown && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_Tab && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_A && modifiers == Qt::AltModifier)
+ || (key == Qt::Key_Tab)
+ ) {
+ emit unhandledKeyPressEvent(event);
+ }
+ else if ((key == Qt::Key_Up)
+ || (key == Qt::Key_Down)) {
+ emit unhandledKeyPressEvent(event);
+ QTextEdit::keyPressEvent(event);
+ }
+ else if ((key == Qt::Key_K && modifiers == QtUtilities::ctrlHardwareKeyModifier)) {
+ QTextCursor cursor = textCursor();
+ cursor.setPosition(toPlainText().size(), QTextCursor::KeepAnchor);
+ cursor.removeSelectedText();
+ }
+ else {
+ QTextEdit::keyPressEvent(event);
+ }
}
void QtTextEdit::focusInEvent(QFocusEvent* event) {
- receivedFocus();
- QTextEdit::focusInEvent(event);
+ receivedFocus();
+ QTextEdit::focusInEvent(event);
}
void QtTextEdit::focusOutEvent(QFocusEvent* event) {
- lostFocus();
- QTextEdit::focusOutEvent(event);
+ lostFocus();
+ QTextEdit::focusOutEvent(event);
}
void QtTextEdit::handleTextChanged() {
- QSize previous(maximumSize());
- setMaximumSize(QSize(maximumWidth(), sizeHint().height()));
- if (previous != maximumSize()) {
- updateGeometry();
- }
+ QSize previous(maximumSize());
+ setMaximumSize(QSize(maximumWidth(), sizeHint().height()));
+ if (previous != maximumSize()) {
+ updateGeometry();
+ }
}
void QtTextEdit::replaceMisspelledWord(const QString& word, int cursorPosition) {
- QTextCursor cursor = textCursor();
- PositionPair wordPosition = getWordFromCursor(cursorPosition);
- cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
- cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
- QTextCharFormat normalFormat;
- cursor.insertText(word, normalFormat);
+ QTextCursor cursor = textCursor();
+ PositionPair wordPosition = getWordFromCursor(cursorPosition);
+ cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
+ cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
+ QTextCharFormat normalFormat;
+ cursor.insertText(word, normalFormat);
}
PositionPair QtTextEdit::getWordFromCursor(int cursorPosition) {
- PositionPairList misspelledPositions = highlighter_->getMisspelledPositions();
- for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end(); ++it) {
- if (cursorPosition >= boost::get<0>(*it) && cursorPosition <= boost::get<1>(*it)) {
- return *it;
- }
- }
- return boost::make_tuple(-1,-1);
+ PositionPairList misspelledPositions = highlighter_->getMisspelledPositions();
+ for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end(); ++it) {
+ if (cursorPosition >= boost::get<0>(*it) && cursorPosition <= boost::get<1>(*it)) {
+ return *it;
+ }
+ }
+ return boost::make_tuple(-1,-1);
}
QSize QtTextEdit::sizeHint() const {
- QSize hint = document()->size().toSize();
- QMargins margins = contentsMargins();
- return hint + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
+ QSize hint = document()->size().toSize();
+ QMargins margins = contentsMargins();
+ return hint + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
}
void QtTextEdit::contextMenuEvent(QContextMenuEvent* event) {
- QMenu* menu = createStandardContextMenu();
- QTextCursor cursor = cursorForPosition(event->pos());
+ QMenu* menu = createStandardContextMenu();
+ QTextCursor cursor = cursorForPosition(event->pos());
#ifdef HAVE_SPELLCHECKER
- QAction* insertPoint = menu->actions().first();
- QAction* settingsAction = new QAction(tr("Spell Checker Options"), menu);
- menu->insertAction(insertPoint, settingsAction);
- menu->insertAction(insertPoint, menu->addSeparator());
- addSuggestions(menu, event);
- QAction* result = menu->exec(event->globalPos());
- if (result == settingsAction) {
- spellCheckerSettingsWindow();
- }
- for (std::vector<QAction*>::iterator it = replaceWordActions_.begin(); it != replaceWordActions_.end(); ++it) {
- if (*it == result) {
- replaceMisspelledWord((*it)->text(), cursor.position());
- }
- }
+ QAction* insertPoint = menu->actions().first();
+ QAction* settingsAction = new QAction(tr("Spell Checker Options"), menu);
+ menu->insertAction(insertPoint, settingsAction);
+ menu->insertAction(insertPoint, menu->addSeparator());
+ addSuggestions(menu, event);
+ QAction* result = menu->exec(event->globalPos());
+ if (result == settingsAction) {
+ spellCheckerSettingsWindow();
+ }
+ for (std::vector<QAction*>::iterator it = replaceWordActions_.begin(); it != replaceWordActions_.end(); ++it) {
+ if (*it == result) {
+ replaceMisspelledWord((*it)->text(), cursor.position());
+ }
+ }
#else
- menu->exec(event->globalPos());
+ menu->exec(event->globalPos());
#endif
- delete menu;
+ delete menu;
}
void QtTextEdit::addSuggestions(QMenu* menu, QContextMenuEvent* event)
{
- replaceWordActions_.clear();
- if (checker_ && highlighter_) {
- QAction* insertPoint = menu->actions().first();
- QTextCursor cursor = cursorForPosition(event->pos());
- PositionPair wordPosition = getWordFromCursor(cursor.position());
- if (boost::get<0>(wordPosition) < 0) {
- // The click was executed outside a spellable word so no
- // suggestions are necessary
- return;
- }
- cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
- cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
- std::vector<std::string> wordList;
- checker_->getSuggestions(Q2PSTRING(cursor.selectedText()), wordList);
- if (wordList.size() == 0) {
- QAction* noSuggestions = new QAction(tr("No Suggestions"), menu);
- noSuggestions->setDisabled(true);
- menu->insertAction(insertPoint, noSuggestions);
- }
- else {
- for (std::vector<std::string>::iterator it = wordList.begin(); it != wordList.end(); ++it) {
- QAction* wordAction = new QAction(it->c_str(), menu);
- menu->insertAction(insertPoint, wordAction);
- replaceWordActions_.push_back(wordAction);
- }
- }
- menu->insertAction(insertPoint, menu->addSeparator());
- }
+ replaceWordActions_.clear();
+ if (checker_ && highlighter_) {
+ QAction* insertPoint = menu->actions().first();
+ QTextCursor cursor = cursorForPosition(event->pos());
+ PositionPair wordPosition = getWordFromCursor(cursor.position());
+ if (boost::get<0>(wordPosition) < 0) {
+ // The click was executed outside a spellable word so no
+ // suggestions are necessary
+ return;
+ }
+ cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
+ cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
+ std::vector<std::string> wordList;
+ checker_->getSuggestions(Q2PSTRING(cursor.selectedText()), wordList);
+ if (wordList.size() == 0) {
+ QAction* noSuggestions = new QAction(tr("No Suggestions"), menu);
+ noSuggestions->setDisabled(true);
+ menu->insertAction(insertPoint, noSuggestions);
+ }
+ else {
+ for (std::vector<std::string>::iterator it = wordList.begin(); it != wordList.end(); ++it) {
+ QAction* wordAction = new QAction(it->c_str(), menu);
+ menu->insertAction(insertPoint, wordAction);
+ replaceWordActions_.push_back(wordAction);
+ }
+ }
+ menu->insertAction(insertPoint, menu->addSeparator());
+ }
}
#ifdef HAVE_SPELLCHECKER
void QtTextEdit::setUpSpellChecker()
{
- delete highlighter_;
- highlighter_ = NULL;
- delete checker_;
- checker_ = NULL;
- if (settings_->getSetting(SettingConstants::SPELL_CHECKER)) {
- std::string dictPath = settings_->getSetting(SettingConstants::DICT_PATH);
- std::string dictFile = settings_->getSetting(SettingConstants::DICT_FILE);
- checker_ = SpellCheckerFactory().createSpellChecker(dictPath + dictFile);
- if (checker_) {
- highlighter_ = new QtSpellCheckHighlighter(document(), checker_);
- }
- else {
- // Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking.
- SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl;
- settings_->storeSetting(SettingConstants::SPELL_CHECKER, false);
- }
-
- }
+ delete highlighter_;
+ highlighter_ = NULL;
+ delete checker_;
+ checker_ = NULL;
+ if (settings_->getSetting(SettingConstants::SPELL_CHECKER)) {
+ std::string dictPath = settings_->getSetting(SettingConstants::DICT_PATH);
+ std::string dictFile = settings_->getSetting(SettingConstants::DICT_FILE);
+ checker_ = SpellCheckerFactory().createSpellChecker(dictPath + dictFile);
+ if (checker_) {
+ highlighter_ = new QtSpellCheckHighlighter(document(), checker_);
+ }
+ else {
+ // Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking.
+ SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl;
+ settings_->storeSetting(SettingConstants::SPELL_CHECKER, false);
+ }
+
+ }
}
#endif
void QtTextEdit::spellCheckerSettingsWindow() {
- if (!spellCheckerWindow_) {
- spellCheckerWindow_ = new QtSpellCheckerWindow(settings_);
- settings_->onSettingChanged.connect(boost::bind(&QtTextEdit::handleSettingChanged, this, _1));
- spellCheckerWindow_->show();
- }
- else {
- spellCheckerWindow_->show();
- spellCheckerWindow_->raise();
- spellCheckerWindow_->activateWindow();
- }
+ if (!spellCheckerWindow_) {
+ spellCheckerWindow_ = new QtSpellCheckerWindow(settings_);
+ settings_->onSettingChanged.connect(boost::bind(&QtTextEdit::handleSettingChanged, this, _1));
+ spellCheckerWindow_->show();
+ }
+ else {
+ spellCheckerWindow_->show();
+ spellCheckerWindow_->raise();
+ spellCheckerWindow_->activateWindow();
+ }
}
void QtTextEdit::handleSettingChanged(const std::string& settings) {
- if (settings == SettingConstants::SPELL_CHECKER.getKey()
- || settings == SettingConstants::DICT_PATH.getKey()
- || settings == SettingConstants::DICT_FILE.getKey()) {
+ if (settings == SettingConstants::SPELL_CHECKER.getKey()
+ || settings == SettingConstants::DICT_PATH.getKey()
+ || settings == SettingConstants::DICT_FILE.getKey()) {
#ifdef HAVE_SPELLCHECKER
- setUpSpellChecker();
- if (highlighter_) {
- highlighter_->rehighlight();
- }
+ setUpSpellChecker();
+ if (highlighter_) {
+ highlighter_->rehighlight();
+ }
#endif
- }
+ }
}
}
diff --git a/Swift/QtUI/QtTextEdit.h b/Swift/QtUI/QtTextEdit.h
index 67826ba..f03699b 100644
--- a/Swift/QtUI/QtTextEdit.h
+++ b/Swift/QtUI/QtTextEdit.h
@@ -17,47 +17,47 @@
#include <Swift/QtUI/QtSpellCheckHighlighter.h>
namespace Swift {
- class SpellChecker;
- class QtSpellCheckerWindow;
-
- class QtTextEdit : public QTextEdit {
- Q_OBJECT
- public:
- QtTextEdit(SettingsProvider* settings, QWidget* parent = 0);
- virtual ~QtTextEdit();
- virtual QSize sizeHint() const;
-
- signals:
- void wordCorrected(QString& word);
- void returnPressed();
- void unhandledKeyPressEvent(QKeyEvent* event);
- void receivedFocus();
- void lostFocus();
-
- public slots:
- void handleSettingChanged(const std::string& settings);
-
- protected:
- virtual void keyPressEvent(QKeyEvent* event);
- virtual void focusInEvent(QFocusEvent* event);
- virtual void focusOutEvent(QFocusEvent* event);
- virtual void contextMenuEvent(QContextMenuEvent* event);
-
- private slots:
- void handleTextChanged();
-
- private:
- void addSuggestions(QMenu* menu, QContextMenuEvent* event);
- void replaceMisspelledWord(const QString& word, int cursorPosition);
- void setUpSpellChecker();
- void spellCheckerSettingsWindow();
- PositionPair getWordFromCursor(int cursorPosition);
-
- private:
- SpellChecker* checker_;
- QtSpellCheckHighlighter* highlighter_;
- std::vector<QAction*> replaceWordActions_;
- SettingsProvider* settings_;
- QPointer<QtSpellCheckerWindow> spellCheckerWindow_;
- };
+ class SpellChecker;
+ class QtSpellCheckerWindow;
+
+ class QtTextEdit : public QTextEdit {
+ Q_OBJECT
+ public:
+ QtTextEdit(SettingsProvider* settings, QWidget* parent = 0);
+ virtual ~QtTextEdit();
+ virtual QSize sizeHint() const;
+
+ signals:
+ void wordCorrected(QString& word);
+ void returnPressed();
+ void unhandledKeyPressEvent(QKeyEvent* event);
+ void receivedFocus();
+ void lostFocus();
+
+ public slots:
+ void handleSettingChanged(const std::string& settings);
+
+ protected:
+ virtual void keyPressEvent(QKeyEvent* event);
+ virtual void focusInEvent(QFocusEvent* event);
+ virtual void focusOutEvent(QFocusEvent* event);
+ virtual void contextMenuEvent(QContextMenuEvent* event);
+
+ private slots:
+ void handleTextChanged();
+
+ private:
+ void addSuggestions(QMenu* menu, QContextMenuEvent* event);
+ void replaceMisspelledWord(const QString& word, int cursorPosition);
+ void setUpSpellChecker();
+ void spellCheckerSettingsWindow();
+ PositionPair getWordFromCursor(int cursorPosition);
+
+ private:
+ SpellChecker* checker_;
+ QtSpellCheckHighlighter* highlighter_;
+ std::vector<QAction*> replaceWordActions_;
+ SettingsProvider* settings_;
+ QPointer<QtSpellCheckerWindow> spellCheckerWindow_;
+ };
}
diff --git a/Swift/QtUI/QtTranslator.h b/Swift/QtUI/QtTranslator.h
index b74ea3e..4254324 100644
--- a/Swift/QtUI/QtTranslator.h
+++ b/Swift/QtUI/QtTranslator.h
@@ -11,15 +11,15 @@
#include <Swift/Controllers/Translator.h>
class QtTranslator : public Swift::Translator {
- public:
- QtTranslator() {
- }
+ public:
+ QtTranslator() {
+ }
- virtual std::string translate(const std::string& text, const std::string& context) {
+ virtual std::string translate(const std::string& text, const std::string& context) {
#if QT_VERSION >= 0x050000
- return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0).toUtf8());
+ return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0).toUtf8());
#else
- return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0, QCoreApplication::UnicodeUTF8).toUtf8());
+ return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0, QCoreApplication::UnicodeUTF8).toUtf8());
#endif
- }
+ }
};
diff --git a/Swift/QtUI/QtUIFactory.cpp b/Swift/QtUI/QtUIFactory.cpp
index 0cde4e1..a1321bd 100644
--- a/Swift/QtUI/QtUIFactory.cpp
+++ b/Swift/QtUI/QtUIFactory.cpp
@@ -39,148 +39,148 @@
namespace Swift {
QtUIFactory::QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID) : settings(settings), qtOnlySettings(qtOnlySettings), tabsBase(tabs), netbookSplitter(netbookSplitter), systemTray(systemTray), chatWindowFactory(chatWindowFactory), timerFactory_(timerFactory), lastMainWindow(NULL), loginWindow(NULL), statusCache(statusCache), startMinimized(startMinimized), emoticonsExist_(emoticonsExist), enableAdHocCommandOnJID_(enableAdHocCommandOnJID) {
- chatFontSize = settings->getSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE);
- historyFontSize_ = settings->getSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE);
- this->tabs = dynamic_cast<QtChatTabs*>(tabsBase);
+ chatFontSize = settings->getSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE);
+ historyFontSize_ = settings->getSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE);
+ this->tabs = dynamic_cast<QtChatTabs*>(tabsBase);
}
XMLConsoleWidget* QtUIFactory::createXMLConsoleWidget() {
- QtXMLConsoleWidget* widget = new QtXMLConsoleWidget();
- tabsBase->addTab(widget);
- showTabs();
- widget->show();
- return widget;
+ QtXMLConsoleWidget* widget = new QtXMLConsoleWidget();
+ tabsBase->addTab(widget);
+ showTabs();
+ widget->show();
+ return widget;
}
HistoryWindow* QtUIFactory::createHistoryWindow(UIEventStream* uiEventStream) {
- QtHistoryWindow* window = new QtHistoryWindow(settings, uiEventStream);
- tabsBase->addTab(window);
- showTabs();
- connect(window, SIGNAL(fontResized(int)), this, SLOT(handleHistoryWindowFontResized(int)));
+ QtHistoryWindow* window = new QtHistoryWindow(settings, uiEventStream);
+ tabsBase->addTab(window);
+ showTabs();
+ connect(window, SIGNAL(fontResized(int)), this, SLOT(handleHistoryWindowFontResized(int)));
- window->handleFontResized(historyFontSize_);
- window->show();
- return window;
+ window->handleFontResized(historyFontSize_);
+ window->show();
+ return window;
}
void QtUIFactory::handleHistoryWindowFontResized(int size) {
- historyFontSize_ = size;
- settings->storeSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE, size);
+ historyFontSize_ = size;
+ settings->storeSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE, size);
}
FileTransferListWidget* QtUIFactory::createFileTransferListWidget() {
- QtFileTransferListWidget* widget = new QtFileTransferListWidget();
- tabsBase->addTab(widget);
- showTabs();
- widget->show();
- return widget;
+ QtFileTransferListWidget* widget = new QtFileTransferListWidget();
+ tabsBase->addTab(widget);
+ showTabs();
+ widget->show();
+ return widget;
}
MainWindow* QtUIFactory::createMainWindow(UIEventStream* eventStream) {
- lastMainWindow = new QtMainWindow(settings, eventStream, loginWindow->getMenus(), statusCache, emoticonsExist_, enableAdHocCommandOnJID_);
- if (tabs) {
- tabs->setViewMenu(lastMainWindow->getMenus()[0]);
- }
- return lastMainWindow;
+ lastMainWindow = new QtMainWindow(settings, eventStream, loginWindow->getMenus(), statusCache, emoticonsExist_, enableAdHocCommandOnJID_);
+ if (tabs) {
+ tabs->setViewMenu(lastMainWindow->getMenus()[0]);
+ }
+ return lastMainWindow;
}
LoginWindow* QtUIFactory::createLoginWindow(UIEventStream* eventStream) {
- loginWindow = new QtLoginWindow(eventStream, settings, timerFactory_);
- if (netbookSplitter) {
- netbookSplitter->insertAtFront(loginWindow);
- }
- connect(systemTray, SIGNAL(clicked()), loginWindow, SLOT(toggleBringToFront()));
+ loginWindow = new QtLoginWindow(eventStream, settings, timerFactory_);
+ if (netbookSplitter) {
+ netbookSplitter->insertAtFront(loginWindow);
+ }
+ connect(systemTray, SIGNAL(clicked()), loginWindow, SLOT(toggleBringToFront()));
#ifndef SWIFT_MOBILE
- QVariant loginWindowGeometryVariant = qtOnlySettings->getQSettings()->value("loginWindowGeometry");
- if (loginWindowGeometryVariant.isValid()) {
- loginWindow->restoreGeometry(loginWindowGeometryVariant.toByteArray());
- }
- connect(loginWindow, SIGNAL(geometryChanged()), this, SLOT(handleLoginWindowGeometryChanged()));
- if (startMinimized) loginWindow->hide();
+ QVariant loginWindowGeometryVariant = qtOnlySettings->getQSettings()->value("loginWindowGeometry");
+ if (loginWindowGeometryVariant.isValid()) {
+ loginWindow->restoreGeometry(loginWindowGeometryVariant.toByteArray());
+ }
+ connect(loginWindow, SIGNAL(geometryChanged()), this, SLOT(handleLoginWindowGeometryChanged()));
+ if (startMinimized) loginWindow->hide();
#endif
- return loginWindow;
+ return loginWindow;
}
void QtUIFactory::handleLoginWindowGeometryChanged() {
- qtOnlySettings->getQSettings()->setValue("loginWindowGeometry", loginWindow->saveGeometry());
+ qtOnlySettings->getQSettings()->setValue("loginWindowGeometry", loginWindow->saveGeometry());
}
EventWindow* QtUIFactory::createEventWindow() {
- return lastMainWindow->getEventWindow();
+ return lastMainWindow->getEventWindow();
}
ChatListWindow* QtUIFactory::createChatListWindow(UIEventStream*) {
- return lastMainWindow->getChatListWindow();
+ return lastMainWindow->getChatListWindow();
}
MUCSearchWindow* QtUIFactory::createMUCSearchWindow() {
- return new QtMUCSearchWindow();
+ return new QtMUCSearchWindow();
}
ChatWindow* QtUIFactory::createChatWindow(const JID& contact, UIEventStream* eventStream) {
- QtChatWindow* window = dynamic_cast<QtChatWindow*>(chatWindowFactory->createChatWindow(contact, eventStream));
- chatWindows.push_back(window);
- std::vector<QPointer<QtChatWindow> > deletions;
- foreach (QPointer<QtChatWindow> existingWindow, chatWindows) {
- if (existingWindow.isNull()) {
- deletions.push_back(existingWindow);
- } else {
- connect(window, SIGNAL(fontResized(int)), existingWindow, SLOT(handleFontResized(int)));
- connect(existingWindow, SIGNAL(fontResized(int)), window, SLOT(handleFontResized(int)));
- }
- }
- foreach (QPointer<QtChatWindow> deletedWindow, deletions) {
- chatWindows.erase(std::remove(chatWindows.begin(), chatWindows.end(), deletedWindow), chatWindows.end());
- }
- connect(window, SIGNAL(fontResized(int)), this, SLOT(handleChatWindowFontResized(int)));
- window->handleFontResized(chatFontSize);
- return window;
+ QtChatWindow* window = dynamic_cast<QtChatWindow*>(chatWindowFactory->createChatWindow(contact, eventStream));
+ chatWindows.push_back(window);
+ std::vector<QPointer<QtChatWindow> > deletions;
+ foreach (QPointer<QtChatWindow> existingWindow, chatWindows) {
+ if (existingWindow.isNull()) {
+ deletions.push_back(existingWindow);
+ } else {
+ connect(window, SIGNAL(fontResized(int)), existingWindow, SLOT(handleFontResized(int)));
+ connect(existingWindow, SIGNAL(fontResized(int)), window, SLOT(handleFontResized(int)));
+ }
+ }
+ foreach (QPointer<QtChatWindow> deletedWindow, deletions) {
+ chatWindows.erase(std::remove(chatWindows.begin(), chatWindows.end(), deletedWindow), chatWindows.end());
+ }
+ connect(window, SIGNAL(fontResized(int)), this, SLOT(handleChatWindowFontResized(int)));
+ window->handleFontResized(chatFontSize);
+ return window;
}
void QtUIFactory::handleChatWindowFontResized(int size) {
- chatFontSize = size;
- settings->storeSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE, size);
+ chatFontSize = size;
+ settings->storeSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE, size);
}
UserSearchWindow* QtUIFactory::createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups) {
- return new QtUserSearchWindow(eventStream, type, groups, qtOnlySettings);
+ return new QtUserSearchWindow(eventStream, type, groups, qtOnlySettings);
}
JoinMUCWindow* QtUIFactory::createJoinMUCWindow(UIEventStream* uiEventStream) {
- return new QtJoinMUCWindow(uiEventStream);
+ return new QtJoinMUCWindow(uiEventStream);
}
ProfileWindow* QtUIFactory::createProfileWindow() {
- return new QtProfileWindow();
+ return new QtProfileWindow();
}
ContactEditWindow* QtUIFactory::createContactEditWindow() {
- return new QtContactEditWindow();
+ return new QtContactEditWindow();
}
WhiteboardWindow* QtUIFactory::createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession) {
- return new QtWhiteboardWindow(whiteboardSession);
+ return new QtWhiteboardWindow(whiteboardSession);
}
HighlightEditorWindow* QtUIFactory::createHighlightEditorWindow() {
- return new QtHighlightEditor(qtOnlySettings);
+ return new QtHighlightEditor(qtOnlySettings);
}
BlockListEditorWidget *QtUIFactory::createBlockListEditorWidget() {
- return new QtBlockListEditorWindow();
+ return new QtBlockListEditorWindow();
}
AdHocCommandWindow* QtUIFactory::createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command) {
- return new QtAdHocCommandWindow(command);
+ return new QtAdHocCommandWindow(command);
}
void QtUIFactory::showTabs() {
- if (tabs) {
- if (!tabs->isVisible()) {
- tabs->show();
- }
- }
+ if (tabs) {
+ if (!tabs->isVisible()) {
+ tabs->show();
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtUIFactory.h b/Swift/QtUI/QtUIFactory.h
index 1d935bc..c72bf63 100644
--- a/Swift/QtUI/QtUIFactory.h
+++ b/Swift/QtUI/QtUIFactory.h
@@ -14,70 +14,70 @@
class QSplitter;
namespace Swift {
- class QtSettingsProvider;
- class SettingsProviderHierachy;
- class QtChatTabsBase;
- class QtChatTabs;
- class QtSystemTray;
- class QtLoginWindow;
- class QtMainWindow;
- class QtChatTheme;
- class QtChatWindowFactory;
- class QtChatWindow;
- class TimerFactory;
- class historyWindow_;
- class WhiteboardSession;
- class StatusCache;
- class QtSingleWindow;
+ class QtSettingsProvider;
+ class SettingsProviderHierachy;
+ class QtChatTabsBase;
+ class QtChatTabs;
+ class QtSystemTray;
+ class QtLoginWindow;
+ class QtMainWindow;
+ class QtChatTheme;
+ class QtChatWindowFactory;
+ class QtChatWindow;
+ class TimerFactory;
+ class historyWindow_;
+ class WhiteboardSession;
+ class StatusCache;
+ class QtSingleWindow;
- class QtUIFactory : public QObject, public UIFactory {
- Q_OBJECT
- public:
- QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID);
+ class QtUIFactory : public QObject, public UIFactory {
+ Q_OBJECT
+ public:
+ QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID);
- virtual XMLConsoleWidget* createXMLConsoleWidget();
- virtual HistoryWindow* createHistoryWindow(UIEventStream*);
- virtual MainWindow* createMainWindow(UIEventStream* eventStream);
- virtual LoginWindow* createLoginWindow(UIEventStream* eventStream);
- virtual EventWindow* createEventWindow();
- virtual ChatListWindow* createChatListWindow(UIEventStream*);
- virtual MUCSearchWindow* createMUCSearchWindow();
- virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
- virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups);
- virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream);
- virtual ProfileWindow* createProfileWindow();
- virtual ContactEditWindow* createContactEditWindow();
- virtual FileTransferListWidget* createFileTransferListWidget();
- virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession);
- virtual HighlightEditorWindow* createHighlightEditorWindow();
- virtual BlockListEditorWidget* createBlockListEditorWidget();
- virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
+ virtual XMLConsoleWidget* createXMLConsoleWidget();
+ virtual HistoryWindow* createHistoryWindow(UIEventStream*);
+ virtual MainWindow* createMainWindow(UIEventStream* eventStream);
+ virtual LoginWindow* createLoginWindow(UIEventStream* eventStream);
+ virtual EventWindow* createEventWindow();
+ virtual ChatListWindow* createChatListWindow(UIEventStream*);
+ virtual MUCSearchWindow* createMUCSearchWindow();
+ virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
+ virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups);
+ virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream);
+ virtual ProfileWindow* createProfileWindow();
+ virtual ContactEditWindow* createContactEditWindow();
+ virtual FileTransferListWidget* createFileTransferListWidget();
+ virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession);
+ virtual HighlightEditorWindow* createHighlightEditorWindow();
+ virtual BlockListEditorWidget* createBlockListEditorWidget();
+ virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
- private slots:
- void handleLoginWindowGeometryChanged();
- void handleChatWindowFontResized(int);
- void handleHistoryWindowFontResized(int);
+ private slots:
+ void handleLoginWindowGeometryChanged();
+ void handleChatWindowFontResized(int);
+ void handleHistoryWindowFontResized(int);
- private:
- void showTabs();
+ private:
+ void showTabs();
- private:
- SettingsProviderHierachy* settings;
- QtSettingsProvider* qtOnlySettings;
- QtChatTabsBase* tabsBase;
- QtChatTabs* tabs;
- QtSingleWindow* netbookSplitter;
- QtSystemTray* systemTray;
- QtChatWindowFactory* chatWindowFactory;
- TimerFactory* timerFactory_;
- QtMainWindow* lastMainWindow;
- QtLoginWindow* loginWindow;
- StatusCache* statusCache;
- std::vector<QPointer<QtChatWindow> > chatWindows;
- bool startMinimized;
- int chatFontSize;
- int historyFontSize_;
- bool emoticonsExist_;
- bool enableAdHocCommandOnJID_;
- };
+ private:
+ SettingsProviderHierachy* settings;
+ QtSettingsProvider* qtOnlySettings;
+ QtChatTabsBase* tabsBase;
+ QtChatTabs* tabs;
+ QtSingleWindow* netbookSplitter;
+ QtSystemTray* systemTray;
+ QtChatWindowFactory* chatWindowFactory;
+ TimerFactory* timerFactory_;
+ QtMainWindow* lastMainWindow;
+ QtLoginWindow* loginWindow;
+ StatusCache* statusCache;
+ std::vector<QPointer<QtChatWindow> > chatWindows;
+ bool startMinimized;
+ int chatFontSize;
+ int historyFontSize_;
+ bool emoticonsExist_;
+ bool enableAdHocCommandOnJID_;
+ };
}
diff --git a/Swift/QtUI/QtUISettingConstants.h b/Swift/QtUI/QtUISettingConstants.h
index 4c17c0d..3e7291f 100644
--- a/Swift/QtUI/QtUISettingConstants.h
+++ b/Swift/QtUI/QtUISettingConstants.h
@@ -9,16 +9,16 @@
#include <Swift/Controllers/Settings/SettingsProvider.h>
namespace Swift {
- class QtUISettingConstants {
- public:
- static const SettingsProvider::Setting<bool> COMPACT_ROSTER;
- static const SettingsProvider::Setting<std::string> CLICKTHROUGH_BANNER;
- static const SettingsProvider::Setting<int> CURRENT_ROSTER_TAB;
- static const SettingsProvider::Setting<bool> SHOW_NICK_IN_ROSTER_HEADER;
- static const SettingsProvider::Setting<int> CHATWINDOW_FONT_SIZE;
- static const SettingsProvider::Setting<int> HISTORYWINDOW_FONT_SIZE;
- static const SettingsProvider::Setting<bool> SHOW_EMOTICONS;
- static const SettingsProvider::Setting<bool> USE_PLAIN_CHATS;
- static const SettingsProvider::Setting<bool> USE_SCREENREADER;
- };
+ class QtUISettingConstants {
+ public:
+ static const SettingsProvider::Setting<bool> COMPACT_ROSTER;
+ static const SettingsProvider::Setting<std::string> CLICKTHROUGH_BANNER;
+ static const SettingsProvider::Setting<int> CURRENT_ROSTER_TAB;
+ static const SettingsProvider::Setting<bool> SHOW_NICK_IN_ROSTER_HEADER;
+ static const SettingsProvider::Setting<int> CHATWINDOW_FONT_SIZE;
+ static const SettingsProvider::Setting<int> HISTORYWINDOW_FONT_SIZE;
+ static const SettingsProvider::Setting<bool> SHOW_EMOTICONS;
+ static const SettingsProvider::Setting<bool> USE_PLAIN_CHATS;
+ static const SettingsProvider::Setting<bool> USE_SCREENREADER;
+ };
}
diff --git a/Swift/QtUI/QtURIHandler.cpp b/Swift/QtUI/QtURIHandler.cpp
index e3b9a53..24bd328 100644
--- a/Swift/QtUI/QtURIHandler.cpp
+++ b/Swift/QtUI/QtURIHandler.cpp
@@ -15,16 +15,16 @@
using namespace Swift;
QtURIHandler::QtURIHandler() {
- qApp->installEventFilter(this);
+ qApp->installEventFilter(this);
}
bool QtURIHandler::eventFilter(QObject*, QEvent* event) {
- if (event->type() == QEvent::FileOpen) {
- QFileOpenEvent* fileOpenEvent = static_cast<QFileOpenEvent*>(event);
- if (fileOpenEvent->url().scheme() == "xmpp") {
- onURI(Q2PSTRING(fileOpenEvent->url().toString()));
- return true;
- }
- }
- return false;
+ if (event->type() == QEvent::FileOpen) {
+ QFileOpenEvent* fileOpenEvent = static_cast<QFileOpenEvent*>(event);
+ if (fileOpenEvent->url().scheme() == "xmpp") {
+ onURI(Q2PSTRING(fileOpenEvent->url().toString()));
+ return true;
+ }
+ }
+ return false;
}
diff --git a/Swift/QtUI/QtURIHandler.h b/Swift/QtUI/QtURIHandler.h
index 1abcac6..309e55b 100644
--- a/Swift/QtUI/QtURIHandler.h
+++ b/Swift/QtUI/QtURIHandler.h
@@ -13,11 +13,11 @@
class QUrl;
namespace Swift {
- class QtURIHandler : public QObject, public URIHandler {
- public:
- QtURIHandler();
+ class QtURIHandler : public QObject, public URIHandler {
+ public:
+ QtURIHandler();
- private:
- bool eventFilter(QObject* obj, QEvent* event);
- };
+ private:
+ bool eventFilter(QObject* obj, QEvent* event);
+ };
}
diff --git a/Swift/QtUI/QtURLValidator.cpp b/Swift/QtUI/QtURLValidator.cpp
index 45bf528..8017710 100644
--- a/Swift/QtUI/QtURLValidator.cpp
+++ b/Swift/QtUI/QtURLValidator.cpp
@@ -16,10 +16,10 @@ QtURLValidator::QtURLValidator(QObject* parent) : QValidator(parent) {
}
QValidator::State QtURLValidator::validate(QString& input, int&) const {
- URL url = URL::fromString(Q2PSTRING(input));
- bool valid = !url.isEmpty();
- valid &= (url.getScheme() == "http" || url.getScheme() == "https");
- return valid ? Acceptable : Intermediate;
+ URL url = URL::fromString(Q2PSTRING(input));
+ bool valid = !url.isEmpty();
+ valid &= (url.getScheme() == "http" || url.getScheme() == "https");
+ return valid ? Acceptable : Intermediate;
}
}
diff --git a/Swift/QtUI/QtURLValidator.h b/Swift/QtUI/QtURLValidator.h
index b374ef4..887828a 100644
--- a/Swift/QtUI/QtURLValidator.h
+++ b/Swift/QtUI/QtURLValidator.h
@@ -7,11 +7,11 @@
#include <QValidator>
namespace Swift {
- class QtURLValidator : public QValidator {
- Q_OBJECT
- public:
- QtURLValidator(QObject* parent);
- virtual QValidator::State validate(QString& input, int& pos) const;
- };
+ class QtURLValidator : public QValidator {
+ Q_OBJECT
+ public:
+ QtURLValidator(QObject* parent);
+ virtual QValidator::State validate(QString& input, int& pos) const;
+ };
}
diff --git a/Swift/QtUI/QtUtilities.cpp b/Swift/QtUI/QtUtilities.cpp
index b4b1b09..401af17 100644
--- a/Swift/QtUI/QtUtilities.cpp
+++ b/Swift/QtUI/QtUtilities.cpp
@@ -22,23 +22,23 @@ namespace QtUtilities {
void setX11Resource(QWidget* widget, const QString& c) {
#if defined (Q_OS_UNIX) && !defined(Q_OS_MAC) && QT_VERSION < 0x050000
- char res_class[] = SWIFT_APPLICATION_NAME;
- XClassHint hint;
- QByteArray resName = (QString(SWIFT_APPLICATION_NAME) + "-" + c).toUtf8();
- hint.res_name = resName.data();
- hint.res_class = res_class;
- XSetClassHint(widget->x11Info().display(), widget->winId(), &hint);
+ char res_class[] = SWIFT_APPLICATION_NAME;
+ XClassHint hint;
+ QByteArray resName = (QString(SWIFT_APPLICATION_NAME) + "-" + c).toUtf8();
+ hint.res_name = resName.data();
+ hint.res_class = res_class;
+ XSetClassHint(widget->x11Info().display(), widget->winId(), &hint);
#else
- (void) widget;
- (void) c;
+ (void) widget;
+ (void) c;
#endif
}
QString htmlEscape(const QString& s) {
#if QT_VERSION >= 0x050000
- return s.toHtmlEscaped();
+ return s.toHtmlEscaped();
#else
- return Qt::escape(s);
+ return Qt::escape(s);
#endif
}
diff --git a/Swift/QtUI/QtUtilities.h b/Swift/QtUI/QtUtilities.h
index 4d71d7c..ad58499 100644
--- a/Swift/QtUI/QtUtilities.h
+++ b/Swift/QtUI/QtUtilities.h
@@ -12,11 +12,11 @@ class QString;
#include <QKeyEvent>
namespace QtUtilities {
- void setX11Resource(QWidget* widget, const QString& c);
- QString htmlEscape(const QString& s);
- #ifdef SWIFTEN_PLATFORM_MACOSX
- const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::MetaModifier;
- #else
- const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::ControlModifier;
- #endif
+ void setX11Resource(QWidget* widget, const QString& c);
+ QString htmlEscape(const QString& s);
+ #ifdef SWIFTEN_PLATFORM_MACOSX
+ const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::MetaModifier;
+ #else
+ const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::ControlModifier;
+ #endif
}
diff --git a/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp b/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
index 9d79859..ec7941c 100644
--- a/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
@@ -24,28 +24,28 @@ QtCloseButton::QtCloseButton(QWidget *parent) : QAbstractButton(parent) {
}
QSize QtCloseButton::sizeHint() const {
- return QSize(style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0), style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0));
+ return QSize(style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0), style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0));
}
bool QtCloseButton::event(QEvent *e) {
- if (e->type() == QEvent::Enter || e->type() == QEvent::Leave) {
- update();
- }
- return QAbstractButton::event(e);
+ if (e->type() == QEvent::Enter || e->type() == QEvent::Leave) {
+ update();
+ }
+ return QAbstractButton::event(e);
}
void QtCloseButton::paintEvent(QPaintEvent *) {
- QPainter painter(this);
- painter.setRenderHint(QPainter::HighQualityAntialiasing);
- QStyleOption opt;
- opt.init(this);
- opt.state |= QStyle::State_AutoRaise;
- if (underMouse() && !isDown()) {
- opt.state |= QStyle::State_Raised;
- } else if (isDown()) {
- opt.state |= QStyle::State_Sunken;
- }
- style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &painter, this);
+ QPainter painter(this);
+ painter.setRenderHint(QPainter::HighQualityAntialiasing);
+ QStyleOption opt;
+ opt.init(this);
+ opt.state |= QStyle::State_AutoRaise;
+ if (underMouse() && !isDown()) {
+ opt.state |= QStyle::State_Raised;
+ } else if (isDown()) {
+ opt.state |= QStyle::State_Sunken;
+ }
+ style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &painter, this);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtCloseButton.h b/Swift/QtUI/QtVCardWidget/QtCloseButton.h
index cb92e12..1ba31a0 100644
--- a/Swift/QtUI/QtVCardWidget/QtCloseButton.h
+++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.h
@@ -10,15 +10,15 @@
namespace Swift {
- class QtCloseButton : public QAbstractButton {
- Q_OBJECT
- public:
- explicit QtCloseButton(QWidget *parent = 0);
- virtual QSize sizeHint() const;
+ class QtCloseButton : public QAbstractButton {
+ Q_OBJECT
+ public:
+ explicit QtCloseButton(QWidget *parent = 0);
+ virtual QSize sizeHint() const;
- protected:
- virtual bool event(QEvent *e);
- virtual void paintEvent(QPaintEvent* );
- };
+ protected:
+ virtual bool event(QEvent *e);
+ virtual void paintEvent(QPaintEvent* );
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
index 73575f6..67c79a9 100644
--- a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
@@ -24,42 +24,42 @@ QtRemovableItemDelegate::QtRemovableItemDelegate(const QStyle* style) : style(st
}
void QtRemovableItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- QStyleOption opt;
- opt.state = option.state;
- opt.state |= QStyle::State_AutoRaise;
- if (option.state.testFlag(QStyle::State_MouseOver)) {
- opt.state |= QStyle::State_Raised;
- }
- opt.rect = option.rect;
- painter->save();
- painter->fillRect(option.rect, option.state & QStyle::State_Selected ? option.palette.highlight() : option.palette.base());
- if (index.data().toString().isEmpty()) {
+ QStyleOption opt;
+ opt.state = option.state;
+ opt.state |= QStyle::State_AutoRaise;
+ if (option.state.testFlag(QStyle::State_MouseOver)) {
+ opt.state |= QStyle::State_Raised;
+ }
+ opt.rect = option.rect;
+ painter->save();
+ painter->fillRect(option.rect, option.state & QStyle::State_Selected ? option.palette.highlight() : option.palette.base());
+ if (index.data().toString().isEmpty()) {
#ifdef SWIFTEN_PLATFORM_MACOSX
- // workaround for Qt not painting relative to the cell we're in, on OS X
- int height = style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0);
- painter->translate(option.rect.x(), option.rect.y() + (option.rect.height() - height)/2);
+ // workaround for Qt not painting relative to the cell we're in, on OS X
+ int height = style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0);
+ painter->translate(option.rect.x(), option.rect.y() + (option.rect.height() - height)/2);
#endif
- style->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, painter);
- }
- painter->restore();
+ style->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, painter);
+ }
+ painter->restore();
}
QWidget* QtRemovableItemDelegate::createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const {
- return NULL;
+ return NULL;
}
bool QtRemovableItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) {
- if (index.data().toString().isEmpty() && event->type() == QEvent::MouseButtonRelease) {
- model->removeRow(index.row());
- return true;
- } else {
- return QItemDelegate::editorEvent(event, model, option, index);
- }
+ if (index.data().toString().isEmpty() && event->type() == QEvent::MouseButtonRelease) {
+ model->removeRow(index.row());
+ return true;
+ } else {
+ return QItemDelegate::editorEvent(event, model, option, index);
+ }
}
QSize QtRemovableItemDelegate::sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const {
- QSize size(style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0) + 2, style->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0) + 2);
- return size;
+ QSize size(style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0) + 2, style->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0) + 2);
+ return size;
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h
index 75137e1..ea9e0b2 100644
--- a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h
+++ b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h
@@ -11,18 +11,18 @@
namespace Swift {
class QtRemovableItemDelegate : public QItemDelegate {
- public:
- QtRemovableItemDelegate(const QStyle* style);
+ public:
+ QtRemovableItemDelegate(const QStyle* style);
- virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex&) const;
- virtual QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const;
- virtual QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const;
+ virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex&) const;
+ virtual QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const;
+ virtual QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const;
- protected:
- virtual bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index);
+ protected:
+ virtual bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index);
- private:
- const QStyle* style;
+ private:
+ const QStyle* style;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
index 3492cb9..9eef970 100644
--- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
@@ -16,43 +16,43 @@
namespace Swift {
QtResizableLineEdit::QtResizableLineEdit(QWidget* parent) :
- QLineEdit(parent), editable(false) {
- connect(this, SIGNAL(textChanged(QString)), SLOT(textChanged(QString)));
- setMinimumWidth(30);
+ QLineEdit(parent), editable(false) {
+ connect(this, SIGNAL(textChanged(QString)), SLOT(textChanged(QString)));
+ setMinimumWidth(30);
}
QtResizableLineEdit::~QtResizableLineEdit() {
}
bool QtResizableLineEdit::isEditable() const {
- return editable;
+ return editable;
}
void QtResizableLineEdit::setEditable(const bool editable) {
- this->editable = editable;
- if (editable) {
- setReadOnly(false);
- } else {
- setReadOnly(true);
- }
+ this->editable = editable;
+ if (editable) {
+ setReadOnly(false);
+ } else {
+ setReadOnly(true);
+ }
}
QSize QtResizableLineEdit::sizeHint() const {
- int horizontalMargin = 10;
- int verticalMargin = 6;
- QSize textDimensions;
+ int horizontalMargin = 10;
+ int verticalMargin = 6;
+ QSize textDimensions;
#if QT_VERSION >= 0x040700
- textDimensions = fontMetrics().boundingRect(text().isEmpty() ? placeholderText() : text()).size();
+ textDimensions = fontMetrics().boundingRect(text().isEmpty() ? placeholderText() : text()).size();
#else
- textDimensions = fontMetrics().boundingRect(text().isEmpty() ? QString(" ") : text()).size();
+ textDimensions = fontMetrics().boundingRect(text().isEmpty() ? QString(" ") : text()).size();
#endif
- textDimensions.setWidth(textDimensions.width() + horizontalMargin);
- textDimensions.setHeight(textDimensions.height() + verticalMargin);
- return textDimensions;
+ textDimensions.setWidth(textDimensions.width() + horizontalMargin);
+ textDimensions.setHeight(textDimensions.height() + verticalMargin);
+ return textDimensions;
}
void QtResizableLineEdit::textChanged(QString) {
- updateGeometry();
+ updateGeometry();
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
index 9022d38..47c6f3e 100644
--- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
+++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
@@ -10,24 +10,24 @@
namespace Swift {
- class QtResizableLineEdit : public QLineEdit {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ class QtResizableLineEdit : public QLineEdit {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- explicit QtResizableLineEdit(QWidget* parent = 0);
- ~QtResizableLineEdit();
+ public:
+ explicit QtResizableLineEdit(QWidget* parent = 0);
+ ~QtResizableLineEdit();
- bool isEditable() const;
- void setEditable(const bool);
+ bool isEditable() const;
+ void setEditable(const bool);
- virtual QSize sizeHint() const;
+ virtual QSize sizeHint() const;
- private slots:
- void textChanged(QString);
+ private slots:
+ void textChanged(QString);
- private:
- bool editable;
- };
+ private:
+ bool editable;
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
index 7036f84..ed36580 100644
--- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
@@ -18,14 +18,14 @@
namespace Swift {
QtTagComboBox::QtTagComboBox(QWidget* parent) : QComboBox(parent) {
- setEditable(false);
- displayModel = new QStandardItemModel(this);
- displayItem = new QStandardItem();
- displayItem->setText("");
- displayModel->insertRow(0, displayItem);
- editMenu = new QMenu(this);
- this->setModel(displayModel);
- editable = true;
+ setEditable(false);
+ displayModel = new QStandardItemModel(this);
+ displayItem = new QStandardItem();
+ displayItem->setText("");
+ displayModel->insertRow(0, displayItem);
+ editMenu = new QMenu(this);
+ this->setModel(displayModel);
+ editable = true;
}
QtTagComboBox::~QtTagComboBox() {
@@ -33,40 +33,40 @@ QtTagComboBox::~QtTagComboBox() {
}
bool QtTagComboBox::isEditable() const {
- return editable;
+ return editable;
}
void QtTagComboBox::setEditable(const bool editable) {
- this->editable = editable;
+ this->editable = editable;
}
void QtTagComboBox::addTag(const QString &id, const QString &label) {
- QAction* tagAction = new QAction(editMenu);
- tagAction->setText(label);
- tagAction->setCheckable(true);
- tagAction->setData(QString(id));
- editMenu->addAction(tagAction);
+ QAction* tagAction = new QAction(editMenu);
+ tagAction->setText(label);
+ tagAction->setCheckable(true);
+ tagAction->setData(QString(id));
+ editMenu->addAction(tagAction);
}
void QtTagComboBox::setTag(const QString &id, bool value) {
- QList<QAction*> tagActions = editMenu->actions();
- foreach(QAction* action, tagActions) {
- if (action->data() == id) {
- action->setChecked(value);
- updateDisplayItem();
- return;
- }
- }
+ QList<QAction*> tagActions = editMenu->actions();
+ foreach(QAction* action, tagActions) {
+ if (action->data() == id) {
+ action->setChecked(value);
+ updateDisplayItem();
+ return;
+ }
+ }
}
bool QtTagComboBox::isTagSet(const QString &id) const {
- QList<QAction*> tagActions = editMenu->actions();
- foreach(QAction* action, tagActions) {
- if (action->data() == id) {
- return action->isChecked();
- }
- }
- return false;
+ QList<QAction*> tagActions = editMenu->actions();
+ foreach(QAction* action, tagActions) {
+ if (action->data() == id) {
+ return action->isChecked();
+ }
+ }
+ return false;
}
void QtTagComboBox::showPopup() {
@@ -78,31 +78,31 @@ void QtTagComboBox::hidePopup() {
}
bool QtTagComboBox::event(QEvent* event) {
- if (event->type() == QEvent::MouseButtonPress ||
- event->type() == QEvent::KeyRelease) {
- if (!editable) return true;
-
- QPoint p = mapToGlobal(QPoint(0,0));
- p += QPoint(0, height());
- editMenu->exec(p);
- updateDisplayItem();
- return true;
- }
- return QComboBox::event(event);
+ if (event->type() == QEvent::MouseButtonPress ||
+ event->type() == QEvent::KeyRelease) {
+ if (!editable) return true;
+
+ QPoint p = mapToGlobal(QPoint(0,0));
+ p += QPoint(0, height());
+ editMenu->exec(p);
+ updateDisplayItem();
+ return true;
+ }
+ return QComboBox::event(event);
}
void QtTagComboBox::updateDisplayItem() {
- QList<QAction*> tagActions = editMenu->actions();
- QString text = "";
- foreach(QAction* action, tagActions) {
- if (action->isChecked()) {
- if (text != "") {
- text += ", ";
- }
- text += action->text();
- }
- }
- setItemText(0, text);
+ QList<QAction*> tagActions = editMenu->actions();
+ QString text = "";
+ foreach(QAction* action, tagActions) {
+ if (action->isChecked()) {
+ if (text != "") {
+ text += ", ";
+ }
+ text += action->text();
+ }
+ }
+ setItemText(0, text);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtTagComboBox.h b/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
index 37a60af..f08f136 100644
--- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
+++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
@@ -14,33 +14,33 @@
namespace Swift {
class QtTagComboBox : public QComboBox {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- explicit QtTagComboBox(QWidget* parent = 0);
- ~QtTagComboBox();
+ public:
+ explicit QtTagComboBox(QWidget* parent = 0);
+ ~QtTagComboBox();
- bool isEditable() const;
- void setEditable(const bool);
+ bool isEditable() const;
+ void setEditable(const bool);
- void addTag(const QString& id, const QString& label);
- void setTag(const QString& id, bool value);
- bool isTagSet(const QString& id) const;
+ void addTag(const QString& id, const QString& label);
+ void setTag(const QString& id, bool value);
+ bool isTagSet(const QString& id) const;
- virtual void showPopup();
- virtual void hidePopup();
+ virtual void showPopup();
+ virtual void hidePopup();
- virtual bool event(QEvent* event);
+ virtual bool event(QEvent* event);
- private:
- void updateDisplayItem();
+ private:
+ void updateDisplayItem();
- private:
- bool editable;
- QStandardItemModel* displayModel;
- QStandardItem* displayItem;
- QMenu* editMenu;
+ private:
+ bool editable;
+ QStandardItemModel* displayModel;
+ QStandardItem* displayItem;
+ QMenu* editMenu;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
index 5f9fddf..57bb2cd 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
@@ -20,163 +20,163 @@
namespace Swift {
QtVCardAddressField::QtVCardAddressField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address")), streetLineEdit(NULL), poboxLineEdit(NULL), addressextLineEdit(NULL), cityLineEdit(NULL), pocodeLineEdit(NULL), regionLineEdit(NULL), countryLineEdit(NULL), textFieldGridLayout(NULL), textFieldGridLayoutItem(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address")), streetLineEdit(NULL), poboxLineEdit(NULL), addressextLineEdit(NULL), cityLineEdit(NULL), pocodeLineEdit(NULL), regionLineEdit(NULL), countryLineEdit(NULL), textFieldGridLayout(NULL), textFieldGridLayoutItem(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardAddressField::~QtVCardAddressField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardAddressField::setupContentWidgets() {
- textFieldGridLayout = new QGridLayout();
+ textFieldGridLayout = new QGridLayout();
- streetLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(streetLineEdit, 0, 0, Qt::AlignVCenter);
+ streetLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(streetLineEdit, 0, 0, Qt::AlignVCenter);
- poboxLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(poboxLineEdit, 0, 1, Qt::AlignVCenter);
+ poboxLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(poboxLineEdit, 0, 1, Qt::AlignVCenter);
- addressextLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(addressextLineEdit, 1, 0, Qt::AlignVCenter);
+ addressextLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(addressextLineEdit, 1, 0, Qt::AlignVCenter);
- cityLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(cityLineEdit, 2, 0, Qt::AlignVCenter);
+ cityLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(cityLineEdit, 2, 0, Qt::AlignVCenter);
- pocodeLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(pocodeLineEdit, 2, 1, Qt::AlignVCenter);
+ pocodeLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(pocodeLineEdit, 2, 1, Qt::AlignVCenter);
- regionLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(regionLineEdit, 3, 0, Qt::AlignVCenter);
+ regionLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(regionLineEdit, 3, 0, Qt::AlignVCenter);
- countryLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(countryLineEdit, 4, 0, Qt::AlignVCenter);
- textFieldGridLayout->setVerticalSpacing(2);
- getGridLayout()->addLayout(textFieldGridLayout, getGridLayout()->rowCount()-1, 2, 5, 2, Qt::AlignVCenter);
- textFieldGridLayoutItem = getGridLayout()->itemAtPosition(getGridLayout()->rowCount()-1, 2);
+ countryLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(countryLineEdit, 4, 0, Qt::AlignVCenter);
+ textFieldGridLayout->setVerticalSpacing(2);
+ getGridLayout()->addLayout(textFieldGridLayout, getGridLayout()->rowCount()-1, 2, 5, 2, Qt::AlignVCenter);
+ textFieldGridLayoutItem = getGridLayout()->itemAtPosition(getGridLayout()->rowCount()-1, 2);
#if QT_VERSION >= 0x040700
- streetLineEdit->setPlaceholderText(tr("Street"));
- poboxLineEdit->setPlaceholderText(tr("PO Box"));
- addressextLineEdit->setPlaceholderText(tr("Address Extension"));
- cityLineEdit->setPlaceholderText(tr("City"));
- pocodeLineEdit->setPlaceholderText(tr("Postal Code"));
- regionLineEdit->setPlaceholderText(tr("Region"));
- countryLineEdit->setPlaceholderText(tr("Country"));
+ streetLineEdit->setPlaceholderText(tr("Street"));
+ poboxLineEdit->setPlaceholderText(tr("PO Box"));
+ addressextLineEdit->setPlaceholderText(tr("Address Extension"));
+ cityLineEdit->setPlaceholderText(tr("City"));
+ pocodeLineEdit->setPlaceholderText(tr("Postal Code"));
+ regionLineEdit->setPlaceholderText(tr("Region"));
+ countryLineEdit->setPlaceholderText(tr("Country"));
#endif
- deliveryTypeLabel = new QtElidingLabel(this);
- deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-3, 4, Qt::AlignVCenter);
+ deliveryTypeLabel = new QtElidingLabel(this);
+ deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-3, 4, Qt::AlignVCenter);
- domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this);
- getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
+ domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this);
+ getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
- internationalRadioButton = new QRadioButton(tr("International Delivery"), this);
- getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter);
+ internationalRadioButton = new QRadioButton(tr("International Delivery"), this);
+ getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter);
- buttonGroup = new QButtonGroup(this);
- buttonGroup->addButton(domesticRadioButton);
- buttonGroup->addButton(internationalRadioButton);
+ buttonGroup = new QButtonGroup(this);
+ buttonGroup->addButton(domesticRadioButton);
+ buttonGroup->addButton(internationalRadioButton);
- setTabOrder(internationalRadioButton, getTagComboBox());
- getTagComboBox()->addTag("postal", tr("Postal"));
- getTagComboBox()->addTag("parcel", tr("Parcel"));
+ setTabOrder(internationalRadioButton, getTagComboBox());
+ getTagComboBox()->addTag("postal", tr("Postal"));
+ getTagComboBox()->addTag("parcel", tr("Parcel"));
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
- textFields << streetLineEdit << poboxLineEdit << addressextLineEdit << cityLineEdit << pocodeLineEdit << regionLineEdit << countryLineEdit;
- childWidgets << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
+ textFields << streetLineEdit << poboxLineEdit << addressextLineEdit << cityLineEdit << pocodeLineEdit << regionLineEdit << countryLineEdit;
+ childWidgets << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
}
void QtVCardAddressField::customCleanup() {
- foreach(QWidget* widget, textFields) {
- widget->hide();
- textFieldGridLayout->removeWidget(widget);
- }
- getGridLayout()->removeItem(textFieldGridLayoutItem);
+ foreach(QWidget* widget, textFields) {
+ widget->hide();
+ textFieldGridLayout->removeWidget(widget);
+ }
+ getGridLayout()->removeItem(textFieldGridLayoutItem);
}
bool QtVCardAddressField::isEmpty() const {
- return streetLineEdit->text().isEmpty() &&
- poboxLineEdit->text().isEmpty() &&
- addressextLineEdit->text().isEmpty() &&
- cityLineEdit->text().isEmpty() &&
- pocodeLineEdit->text().isEmpty() &&
- regionLineEdit->text().isEmpty() &&
- countryLineEdit->text().isEmpty();
+ return streetLineEdit->text().isEmpty() &&
+ poboxLineEdit->text().isEmpty() &&
+ addressextLineEdit->text().isEmpty() &&
+ cityLineEdit->text().isEmpty() &&
+ pocodeLineEdit->text().isEmpty() &&
+ regionLineEdit->text().isEmpty() &&
+ countryLineEdit->text().isEmpty();
}
void QtVCardAddressField::setAddress(const VCard::Address& address) {
- setPreferred(address.isPreferred);
- setHome(address.isHome);
- setWork(address.isWork);
- getTagComboBox()->setTag("postal", address.isPostal);
- getTagComboBox()->setTag("parcel", address.isParcel);
- domesticRadioButton->setChecked(address.deliveryType == VCard::DomesticDelivery);
- internationalRadioButton->setChecked(address.deliveryType == VCard::InternationalDelivery);
- streetLineEdit->setText(P2QSTRING(address.street));
- poboxLineEdit->setText(P2QSTRING(address.poBox));
- addressextLineEdit->setText(P2QSTRING(address.addressExtension));
- cityLineEdit->setText(P2QSTRING(address.locality));
- pocodeLineEdit->setText(P2QSTRING(address.postalCode));
- regionLineEdit->setText(P2QSTRING(address.region));
- countryLineEdit->setText(P2QSTRING(address.country));
+ setPreferred(address.isPreferred);
+ setHome(address.isHome);
+ setWork(address.isWork);
+ getTagComboBox()->setTag("postal", address.isPostal);
+ getTagComboBox()->setTag("parcel", address.isParcel);
+ domesticRadioButton->setChecked(address.deliveryType == VCard::DomesticDelivery);
+ internationalRadioButton->setChecked(address.deliveryType == VCard::InternationalDelivery);
+ streetLineEdit->setText(P2QSTRING(address.street));
+ poboxLineEdit->setText(P2QSTRING(address.poBox));
+ addressextLineEdit->setText(P2QSTRING(address.addressExtension));
+ cityLineEdit->setText(P2QSTRING(address.locality));
+ pocodeLineEdit->setText(P2QSTRING(address.postalCode));
+ regionLineEdit->setText(P2QSTRING(address.region));
+ countryLineEdit->setText(P2QSTRING(address.country));
}
VCard::Address QtVCardAddressField::getAddress() const {
- VCard::Address address;
- address.isPreferred = getPreferred();
- address.isHome = getHome();
- address.isWork = getWork();
- address.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
- address.isPostal = getTagComboBox()->isTagSet("postal");
- address.isParcel = getTagComboBox()->isTagSet("parcel");
- address.street = Q2PSTRING(streetLineEdit->text());
- address.poBox = Q2PSTRING(poboxLineEdit->text());
- address.addressExtension = Q2PSTRING(addressextLineEdit->text());
- address.locality = Q2PSTRING(cityLineEdit->text());
- address.postalCode = Q2PSTRING(pocodeLineEdit->text());
- address.region = Q2PSTRING(regionLineEdit->text());
- address.country = Q2PSTRING(countryLineEdit->text());
- return address;
+ VCard::Address address;
+ address.isPreferred = getPreferred();
+ address.isHome = getHome();
+ address.isWork = getWork();
+ address.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
+ address.isPostal = getTagComboBox()->isTagSet("postal");
+ address.isParcel = getTagComboBox()->isTagSet("parcel");
+ address.street = Q2PSTRING(streetLineEdit->text());
+ address.poBox = Q2PSTRING(poboxLineEdit->text());
+ address.addressExtension = Q2PSTRING(addressextLineEdit->text());
+ address.locality = Q2PSTRING(cityLineEdit->text());
+ address.postalCode = Q2PSTRING(pocodeLineEdit->text());
+ address.region = Q2PSTRING(regionLineEdit->text());
+ address.country = Q2PSTRING(countryLineEdit->text());
+ return address;
}
void QtVCardAddressField::handleEditibleChanged(bool isEditable) {
- assert(streetLineEdit);
- assert(poboxLineEdit);
- assert(addressextLineEdit);
- assert(cityLineEdit);
- assert(pocodeLineEdit);
- assert(regionLineEdit);
- assert(countryLineEdit);
- assert(deliveryTypeLabel);
- assert(domesticRadioButton);
- assert(internationalRadioButton);
-
- streetLineEdit->setEditable(isEditable);
- poboxLineEdit->setEditable(isEditable);
- addressextLineEdit->setEditable(isEditable);
- cityLineEdit->setEditable(isEditable);
- pocodeLineEdit->setEditable(isEditable);
- regionLineEdit->setEditable(isEditable);
- countryLineEdit->setEditable(isEditable);
-
- deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text());
- deliveryTypeLabel->setVisible(!isEditable);
-
- domesticRadioButton->setVisible(isEditable);
- internationalRadioButton->setVisible(isEditable);
-
- foreach (QWidget* widget, textFields) {
- QtResizableLineEdit* lineEdit;
- if ((lineEdit = dynamic_cast<QtResizableLineEdit*>(widget))) {
- lineEdit->setVisible(isEditable ? true : !lineEdit->text().isEmpty());
- lineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
- }
- }
+ assert(streetLineEdit);
+ assert(poboxLineEdit);
+ assert(addressextLineEdit);
+ assert(cityLineEdit);
+ assert(pocodeLineEdit);
+ assert(regionLineEdit);
+ assert(countryLineEdit);
+ assert(deliveryTypeLabel);
+ assert(domesticRadioButton);
+ assert(internationalRadioButton);
+
+ streetLineEdit->setEditable(isEditable);
+ poboxLineEdit->setEditable(isEditable);
+ addressextLineEdit->setEditable(isEditable);
+ cityLineEdit->setEditable(isEditable);
+ pocodeLineEdit->setEditable(isEditable);
+ regionLineEdit->setEditable(isEditable);
+ countryLineEdit->setEditable(isEditable);
+
+ deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text());
+ deliveryTypeLabel->setVisible(!isEditable);
+
+ domesticRadioButton->setVisible(isEditable);
+ internationalRadioButton->setVisible(isEditable);
+
+ foreach (QWidget* widget, textFields) {
+ QtResizableLineEdit* lineEdit;
+ if ((lineEdit = dynamic_cast<QtResizableLineEdit*>(widget))) {
+ lineEdit->setVisible(isEditable ? true : !lineEdit->text().isEmpty());
+ lineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
index 51bc323..c90628a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
@@ -27,42 +27,42 @@ namespace Swift {
class QtElidingLabel;
class QtVCardAddressField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
-
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Address"), UNLIMITED_INSTANCES, QtVCardAddressField)
-
- QtVCardAddressField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardAddressField();
-
- virtual bool isEmpty() const;
-
- void setAddress(const VCard::Address& address);
- VCard::Address getAddress() const;
-
- protected:
- virtual void setupContentWidgets();
- virtual void customCleanup();
-
- public slots:
- void handleEditibleChanged(bool isEditable);
-
- private:
- QList<QWidget*> textFields;
- QtResizableLineEdit* streetLineEdit;
- QtResizableLineEdit* poboxLineEdit;
- QtResizableLineEdit* addressextLineEdit;
- QtResizableLineEdit* cityLineEdit;
- QtResizableLineEdit* pocodeLineEdit;
- QtResizableLineEdit* regionLineEdit;
- QtResizableLineEdit* countryLineEdit;
- QGridLayout* textFieldGridLayout;
- QLayoutItem* textFieldGridLayoutItem;
-
- QtElidingLabel* deliveryTypeLabel;
- QRadioButton* domesticRadioButton;
- QRadioButton* internationalRadioButton;
- QButtonGroup* buttonGroup;
+ Q_OBJECT
+
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Address"), UNLIMITED_INSTANCES, QtVCardAddressField)
+
+ QtVCardAddressField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardAddressField();
+
+ virtual bool isEmpty() const;
+
+ void setAddress(const VCard::Address& address);
+ VCard::Address getAddress() const;
+
+ protected:
+ virtual void setupContentWidgets();
+ virtual void customCleanup();
+
+ public slots:
+ void handleEditibleChanged(bool isEditable);
+
+ private:
+ QList<QWidget*> textFields;
+ QtResizableLineEdit* streetLineEdit;
+ QtResizableLineEdit* poboxLineEdit;
+ QtResizableLineEdit* addressextLineEdit;
+ QtResizableLineEdit* cityLineEdit;
+ QtResizableLineEdit* pocodeLineEdit;
+ QtResizableLineEdit* regionLineEdit;
+ QtResizableLineEdit* countryLineEdit;
+ QGridLayout* textFieldGridLayout;
+ QLayoutItem* textFieldGridLayoutItem;
+
+ QtElidingLabel* deliveryTypeLabel;
+ QRadioButton* domesticRadioButton;
+ QRadioButton* internationalRadioButton;
+ QButtonGroup* buttonGroup;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
index 64d2533..7f270c5 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
@@ -22,86 +22,86 @@
namespace Swift {
QtVCardAddressLabelField::QtVCardAddressLabelField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address Label")), addressLabelPlainTextEdit(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address Label")), addressLabelPlainTextEdit(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardAddressLabelField::~QtVCardAddressLabelField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardAddressLabelField::setupContentWidgets() {
- addressLabelPlainTextEdit = new QPlainTextEdit(this);
- addressLabelPlainTextEdit->setTabChangesFocus(true);
- getGridLayout()->addWidget(addressLabelPlainTextEdit, getGridLayout()->rowCount()-1, 2, 3, 2, Qt::AlignVCenter);
+ addressLabelPlainTextEdit = new QPlainTextEdit(this);
+ addressLabelPlainTextEdit->setTabChangesFocus(true);
+ getGridLayout()->addWidget(addressLabelPlainTextEdit, getGridLayout()->rowCount()-1, 2, 3, 2, Qt::AlignVCenter);
- deliveryTypeLabel = new QtElidingLabel(this);
- deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
+ deliveryTypeLabel = new QtElidingLabel(this);
+ deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
- domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this);
- getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
+ domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this);
+ getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
- internationalRadioButton = new QRadioButton(tr("International Delivery"), this);
- getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter);
+ internationalRadioButton = new QRadioButton(tr("International Delivery"), this);
+ getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter);
- buttonGroup = new QButtonGroup(this);
- buttonGroup->addButton(domesticRadioButton);
- buttonGroup->addButton(internationalRadioButton);
+ buttonGroup = new QButtonGroup(this);
+ buttonGroup->addButton(domesticRadioButton);
+ buttonGroup->addButton(internationalRadioButton);
- setTabOrder(internationalRadioButton, getTagComboBox());
- getTagComboBox()->addTag("postal", tr("Postal"));
- getTagComboBox()->addTag("parcel", tr("Parcel"));
+ setTabOrder(internationalRadioButton, getTagComboBox());
+ getTagComboBox()->addTag("postal", tr("Postal"));
+ getTagComboBox()->addTag("parcel", tr("Parcel"));
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
- deliveryTypeLabel->hide();
- childWidgets << addressLabelPlainTextEdit << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
+ deliveryTypeLabel->hide();
+ childWidgets << addressLabelPlainTextEdit << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
}
bool QtVCardAddressLabelField::isEmpty() const {
- return addressLabelPlainTextEdit->toPlainText().isEmpty();
+ return addressLabelPlainTextEdit->toPlainText().isEmpty();
}
void QtVCardAddressLabelField::setAddressLabel(const VCard::AddressLabel& addressLabel) {
- setPreferred(addressLabel.isPreferred);
- setHome(addressLabel.isHome);
- setWork(addressLabel.isWork);
- getTagComboBox()->setTag("postal", addressLabel.isPostal);
- getTagComboBox()->setTag("parcel", addressLabel.isParcel);
- domesticRadioButton->setChecked(addressLabel.deliveryType == VCard::DomesticDelivery);
- internationalRadioButton->setChecked(addressLabel.deliveryType == VCard::InternationalDelivery);
- std::string joinedLines = boost::algorithm::join(addressLabel.lines, "\n");
- addressLabelPlainTextEdit->setPlainText(P2QSTRING(joinedLines));
+ setPreferred(addressLabel.isPreferred);
+ setHome(addressLabel.isHome);
+ setWork(addressLabel.isWork);
+ getTagComboBox()->setTag("postal", addressLabel.isPostal);
+ getTagComboBox()->setTag("parcel", addressLabel.isParcel);
+ domesticRadioButton->setChecked(addressLabel.deliveryType == VCard::DomesticDelivery);
+ internationalRadioButton->setChecked(addressLabel.deliveryType == VCard::InternationalDelivery);
+ std::string joinedLines = boost::algorithm::join(addressLabel.lines, "\n");
+ addressLabelPlainTextEdit->setPlainText(P2QSTRING(joinedLines));
}
VCard::AddressLabel QtVCardAddressLabelField::getAddressLabel() const {
- VCard::AddressLabel addressLabel;
- addressLabel.isPreferred = getPreferred();
- addressLabel.isHome = getHome();
- addressLabel.isWork = getWork();
- addressLabel.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
- addressLabel.isPostal = getTagComboBox()->isTagSet("postal");
- addressLabel.isParcel = getTagComboBox()->isTagSet("parcel");
-
- std::string lines = Q2PSTRING(addressLabelPlainTextEdit->toPlainText());
- boost::split(addressLabel.lines, lines, boost::is_any_of("\n"));
- return addressLabel;
+ VCard::AddressLabel addressLabel;
+ addressLabel.isPreferred = getPreferred();
+ addressLabel.isHome = getHome();
+ addressLabel.isWork = getWork();
+ addressLabel.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
+ addressLabel.isPostal = getTagComboBox()->isTagSet("postal");
+ addressLabel.isParcel = getTagComboBox()->isTagSet("parcel");
+
+ std::string lines = Q2PSTRING(addressLabelPlainTextEdit->toPlainText());
+ boost::split(addressLabel.lines, lines, boost::is_any_of("\n"));
+ return addressLabel;
}
void QtVCardAddressLabelField::handleEditibleChanged(bool isEditable) {
- assert(addressLabelPlainTextEdit);
- assert(deliveryTypeLabel);
- assert(domesticRadioButton);
- assert(internationalRadioButton);
+ assert(addressLabelPlainTextEdit);
+ assert(deliveryTypeLabel);
+ assert(domesticRadioButton);
+ assert(internationalRadioButton);
- addressLabelPlainTextEdit->setReadOnly(!isEditable);
- addressLabelPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
+ addressLabelPlainTextEdit->setReadOnly(!isEditable);
+ addressLabelPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
- deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text());
- deliveryTypeLabel->setVisible(!isEditable);
+ deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text());
+ deliveryTypeLabel->setVisible(!isEditable);
- domesticRadioButton->setVisible(isEditable);
- internationalRadioButton->setVisible(isEditable);
+ domesticRadioButton->setVisible(isEditable);
+ internationalRadioButton->setVisible(isEditable);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
index f59e482..16910b3 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
@@ -27,32 +27,32 @@ namespace Swift {
class QtElidingLabel;
class QtVCardAddressLabelField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Address Label"), UNLIMITED_INSTANCES, QtVCardAddressLabelField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Address Label"), UNLIMITED_INSTANCES, QtVCardAddressLabelField)
- QtVCardAddressLabelField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardAddressLabelField();
+ QtVCardAddressLabelField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardAddressLabelField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setAddressLabel(const VCard::AddressLabel& addressLabel);
- VCard::AddressLabel getAddressLabel() const;
+ void setAddressLabel(const VCard::AddressLabel& addressLabel);
+ VCard::AddressLabel getAddressLabel() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QPlainTextEdit* addressLabelPlainTextEdit;
+ private:
+ QPlainTextEdit* addressLabelPlainTextEdit;
- QtElidingLabel* deliveryTypeLabel;
- QRadioButton* domesticRadioButton;
- QRadioButton* internationalRadioButton;
- QButtonGroup* buttonGroup;
+ QtElidingLabel* deliveryTypeLabel;
+ QRadioButton* domesticRadioButton;
+ QRadioButton* internationalRadioButton;
+ QButtonGroup* buttonGroup;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
index 603b8be..53dfc7f 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
@@ -22,47 +22,47 @@
namespace Swift {
QtVCardBirthdayField::QtVCardBirthdayField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Birthday"), false, false), birthdayLabel(NULL), birthdayDateEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Birthday"), false, false), birthdayLabel(NULL), birthdayDateEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardBirthdayField::~QtVCardBirthdayField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardBirthdayField::setupContentWidgets() {
- birthdayLabel = new QLabel(this);
- birthdayLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- birthdayDateEdit = new QDateEdit(this);
- birthdayDateEdit->setCalendarPopup(true);
+ birthdayLabel = new QLabel(this);
+ birthdayLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ birthdayDateEdit = new QDateEdit(this);
+ birthdayDateEdit->setCalendarPopup(true);
- QHBoxLayout* birthdayLayout = new QHBoxLayout();
- birthdayLayout->addWidget(birthdayLabel);
- birthdayLayout->addWidget(birthdayDateEdit);
+ QHBoxLayout* birthdayLayout = new QHBoxLayout();
+ birthdayLayout->addWidget(birthdayLabel);
+ birthdayLayout->addWidget(birthdayDateEdit);
- getGridLayout()->addLayout(birthdayLayout, getGridLayout()->rowCount()-1, 2, Qt::AlignVCenter);
+ getGridLayout()->addLayout(birthdayLayout, getGridLayout()->rowCount()-1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- birthdayLabel->hide();
- childWidgets << birthdayLabel << birthdayDateEdit;
+ getTagComboBox()->hide();
+ birthdayLabel->hide();
+ childWidgets << birthdayLabel << birthdayDateEdit;
}
bool QtVCardBirthdayField::isEmpty() const {
- return false;
+ return false;
}
void QtVCardBirthdayField::setBirthday(const boost::posix_time::ptime& birthday) {
- birthdayDateEdit->setDate(B2QDATE(birthday).date());
+ birthdayDateEdit->setDate(B2QDATE(birthday).date());
}
boost::posix_time::ptime QtVCardBirthdayField::getBirthday() const {
- return boost::posix_time::from_time_t(QDateTime(birthdayDateEdit->date()).toTime_t());
+ return boost::posix_time::from_time_t(QDateTime(birthdayDateEdit->date()).toTime_t());
}
void QtVCardBirthdayField::handleEditibleChanged(bool isEditable) {
- birthdayLabel->setText(birthdayDateEdit->date().toString(Qt::DefaultLocaleLongDate));
- birthdayDateEdit->setVisible(isEditable);
- birthdayLabel->setVisible(!isEditable);
+ birthdayLabel->setText(birthdayDateEdit->date().toString(Qt::DefaultLocaleLongDate));
+ birthdayDateEdit->setVisible(isEditable);
+ birthdayLabel->setVisible(!isEditable);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
index bf15a75..431751e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
@@ -23,28 +23,28 @@
namespace Swift {
class QtVCardBirthdayField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Birthday"), 1, QtVCardBirthdayField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Birthday"), 1, QtVCardBirthdayField)
- QtVCardBirthdayField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardBirthdayField();
+ QtVCardBirthdayField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardBirthdayField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setBirthday(const boost::posix_time::ptime& addressLabel);
- boost::posix_time::ptime getBirthday() const;
+ void setBirthday(const boost::posix_time::ptime& addressLabel);
+ boost::posix_time::ptime getBirthday() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QLabel* birthdayLabel;
- QDateEdit* birthdayDateEdit;
+ private:
+ QLabel* birthdayLabel;
+ QDateEdit* birthdayDateEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
index f3c4dbf..9926262 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
@@ -22,50 +22,50 @@
namespace Swift {
QtVCardDescriptionField::QtVCardDescriptionField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Description"), false, false), descriptionPlainTextEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Description"), false, false), descriptionPlainTextEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardDescriptionField::~QtVCardDescriptionField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardDescriptionField::setupContentWidgets() {
- descriptionPlainTextEdit = new QPlainTextEdit(this);
- descriptionPlainTextEdit->setMinimumHeight(70);
- getGridLayout()->addWidget(descriptionPlainTextEdit, getGridLayout()->rowCount()-1, 2, 2, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- childWidgets << descriptionPlainTextEdit;
+ descriptionPlainTextEdit = new QPlainTextEdit(this);
+ descriptionPlainTextEdit->setMinimumHeight(70);
+ getGridLayout()->addWidget(descriptionPlainTextEdit, getGridLayout()->rowCount()-1, 2, 2, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ childWidgets << descriptionPlainTextEdit;
}
bool QtVCardDescriptionField::isEmpty() const {
- return descriptionPlainTextEdit->toPlainText().isEmpty();
+ return descriptionPlainTextEdit->toPlainText().isEmpty();
}
void QtVCardDescriptionField::setDescription(const std::string& description) {
- descriptionPlainTextEdit->setPlainText(P2QSTRING(description));
+ descriptionPlainTextEdit->setPlainText(P2QSTRING(description));
}
std::string QtVCardDescriptionField::getDescription() const {
- return Q2PSTRING(descriptionPlainTextEdit->toPlainText());
+ return Q2PSTRING(descriptionPlainTextEdit->toPlainText());
}
void QtVCardDescriptionField::handleEditibleChanged(bool isEditable) {
- assert(descriptionPlainTextEdit);
+ assert(descriptionPlainTextEdit);
- if (isEditable) {
- descriptionPlainTextEdit->setMinimumHeight(70);
- } else {
- QFontMetrics inputMetrics(descriptionPlainTextEdit->document()->defaultFont());
- QRect horizontalBounds = contentsRect().adjusted(0,0,0,9999);
- QRect boundingRect = inputMetrics.boundingRect(horizontalBounds, Qt::TextWordWrap, descriptionPlainTextEdit->toPlainText() + "A");
- int left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- int height = boundingRect.height() + top + bottom + inputMetrics.height();
- descriptionPlainTextEdit->setMinimumHeight(height > 70 ? 70 : height);
- }
- descriptionPlainTextEdit->setReadOnly(!isEditable);
- descriptionPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
+ if (isEditable) {
+ descriptionPlainTextEdit->setMinimumHeight(70);
+ } else {
+ QFontMetrics inputMetrics(descriptionPlainTextEdit->document()->defaultFont());
+ QRect horizontalBounds = contentsRect().adjusted(0,0,0,9999);
+ QRect boundingRect = inputMetrics.boundingRect(horizontalBounds, Qt::TextWordWrap, descriptionPlainTextEdit->toPlainText() + "A");
+ int left, top, right, bottom;
+ getContentsMargins(&left, &top, &right, &bottom);
+ int height = boundingRect.height() + top + bottom + inputMetrics.height();
+ descriptionPlainTextEdit->setMinimumHeight(height > 70 ? 70 : height);
+ }
+ descriptionPlainTextEdit->setReadOnly(!isEditable);
+ descriptionPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
index 8fb6344..489797a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
@@ -22,27 +22,27 @@
namespace Swift {
class QtVCardDescriptionField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Description"), 1, QtVCardDescriptionField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Description"), 1, QtVCardDescriptionField)
- QtVCardDescriptionField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardDescriptionField();
+ QtVCardDescriptionField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardDescriptionField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setDescription(const std::string& description);
- std::string getDescription() const;
+ void setDescription(const std::string& description);
+ std::string getDescription() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QPlainTextEdit* descriptionPlainTextEdit;
+ private:
+ QPlainTextEdit* descriptionPlainTextEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h b/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
index 12f990a..093357a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
@@ -18,41 +18,41 @@
#include <QObject>
#include <QString>
#define GENERIC_QT_VCARD_FIELD_INFO(MENU_NAME, ALLOWED_INSTANCES, FIELD_CLASS) \
- class FieldInfo : public QtVCardFieldInfo { \
- public: \
- virtual ~FieldInfo() { \
- } \
- \
- virtual QString getMenuName() const { \
- return MENU_NAME; \
- } \
- \
- virtual int getAllowedInstances() const { \
- return ALLOWED_INSTANCES; \
- } \
- \
- virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const { \
- return new FIELD_CLASS(parent, layout, editable); \
- } \
- \
- virtual bool testInstance(QWidget* widget) const { \
- return dynamic_cast<FIELD_CLASS*>(widget) != 0; \
- } \
- };
+ class FieldInfo : public QtVCardFieldInfo { \
+ public: \
+ virtual ~FieldInfo() { \
+ } \
+ \
+ virtual QString getMenuName() const { \
+ return MENU_NAME; \
+ } \
+ \
+ virtual int getAllowedInstances() const { \
+ return ALLOWED_INSTANCES; \
+ } \
+ \
+ virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const { \
+ return new FIELD_CLASS(parent, layout, editable); \
+ } \
+ \
+ virtual bool testInstance(QWidget* widget) const { \
+ return dynamic_cast<FIELD_CLASS*>(widget) != 0; \
+ } \
+ };
class QWidget;
namespace Swift {
- class QtVCardFieldInfo {
- public:
- static const int UNLIMITED_INSTANCES = -1;
-
- virtual ~QtVCardFieldInfo() {
- }
- virtual QString getMenuName() const = 0;
- virtual int getAllowedInstances() const = 0;
- virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const = 0;
- virtual bool testInstance(QWidget*) const = 0;
- };
+ class QtVCardFieldInfo {
+ public:
+ static const int UNLIMITED_INSTANCES = -1;
+
+ virtual ~QtVCardFieldInfo() {
+ }
+ virtual QString getMenuName() const = 0;
+ virtual int getAllowedInstances() const = 0;
+ virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const = 0;
+ virtual bool testInstance(QWidget*) const = 0;
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
index ed30ae1..44d94d7 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
@@ -22,8 +22,8 @@
namespace Swift {
QtVCardGeneralField::QtVCardGeneralField(QWidget* parent, QGridLayout* layout, bool editable, int row, QString label, bool preferrable, bool taggable) :
- QWidget(parent), editable(editable), preferrable(preferrable), starVisible(false), taggable(taggable), layout(layout), row(row), preferredCheckBox(0), label(0), labelText(label),
- tagComboBox(0), tagLabel(NULL), closeButton(0) {
+ QWidget(parent), editable(editable), preferrable(preferrable), starVisible(false), taggable(taggable), layout(layout), row(row), preferredCheckBox(0), label(0), labelText(label),
+ tagComboBox(0), tagLabel(NULL), closeButton(0) {
}
QtVCardGeneralField::~QtVCardGeneralField() {
@@ -31,126 +31,126 @@ QtVCardGeneralField::~QtVCardGeneralField() {
}
void QtVCardGeneralField::initialize() {
- if (preferrable) {
- preferredCheckBox = new QCheckBox(this);
- preferredCheckBox->setToolTip(tr("Stars can be used to mark preferred contact details."));
- preferredCheckBox->setStyleSheet(
- "QCheckBox::indicator { width: 18px; height: 18px; }"
- "QCheckBox::indicator:checked { image: url(:/icons/star-checked.png); }"
- "QCheckBox::indicator:unchecked { image: url(:/icons/star-unchecked.png); }"
- );
- layout->addWidget(preferredCheckBox, row, 0, Qt::AlignVCenter);
- childWidgets << preferredCheckBox;
- connect(preferredCheckBox, SIGNAL(stateChanged(int)), SLOT(handlePreferredStarStateChanged(int)));
- }
- label = new QLabel(this);
- label->setText(labelText);
- layout->addWidget(label, row, 1, Qt::AlignVCenter | Qt::AlignRight);
-
- tagLabel = new QtElidingLabel(this);
- tagLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
-
- tagComboBox = new QtTagComboBox(this);
- closeButton = new QtCloseButton(this);
- connect(closeButton, SIGNAL(clicked()), SLOT(handleCloseButtonClicked()));
-
- QHBoxLayout* tagLayout = new QHBoxLayout();
- tagLayout->addWidget(tagLabel);
- tagLayout->addWidget(tagComboBox);
-
- setupContentWidgets();
- layout->addLayout(tagLayout, row, 4, Qt::AlignTop);
- layout->addWidget(closeButton, row, 5, Qt::AlignCenter);
- closeButton->resize(12, 12);
- tagLabel->hide();
-
- childWidgets << label << tagComboBox << tagLabel << closeButton;
- setEditable(editable);
+ if (preferrable) {
+ preferredCheckBox = new QCheckBox(this);
+ preferredCheckBox->setToolTip(tr("Stars can be used to mark preferred contact details."));
+ preferredCheckBox->setStyleSheet(
+ "QCheckBox::indicator { width: 18px; height: 18px; }"
+ "QCheckBox::indicator:checked { image: url(:/icons/star-checked.png); }"
+ "QCheckBox::indicator:unchecked { image: url(:/icons/star-unchecked.png); }"
+ );
+ layout->addWidget(preferredCheckBox, row, 0, Qt::AlignVCenter);
+ childWidgets << preferredCheckBox;
+ connect(preferredCheckBox, SIGNAL(stateChanged(int)), SLOT(handlePreferredStarStateChanged(int)));
+ }
+ label = new QLabel(this);
+ label->setText(labelText);
+ layout->addWidget(label, row, 1, Qt::AlignVCenter | Qt::AlignRight);
+
+ tagLabel = new QtElidingLabel(this);
+ tagLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+
+ tagComboBox = new QtTagComboBox(this);
+ closeButton = new QtCloseButton(this);
+ connect(closeButton, SIGNAL(clicked()), SLOT(handleCloseButtonClicked()));
+
+ QHBoxLayout* tagLayout = new QHBoxLayout();
+ tagLayout->addWidget(tagLabel);
+ tagLayout->addWidget(tagComboBox);
+
+ setupContentWidgets();
+ layout->addLayout(tagLayout, row, 4, Qt::AlignTop);
+ layout->addWidget(closeButton, row, 5, Qt::AlignCenter);
+ closeButton->resize(12, 12);
+ tagLabel->hide();
+
+ childWidgets << label << tagComboBox << tagLabel << closeButton;
+ setEditable(editable);
}
bool QtVCardGeneralField::isEditable() const {
- return editable;
+ return editable;
}
void QtVCardGeneralField::setEditable(bool editable) {
- assert(tagComboBox);
- assert(closeButton);
-
- this->editable = editable;
- if (taggable) {
- tagLabel->setText(tagComboBox->itemText(0));
- tagComboBox->setVisible(editable);
- tagLabel->setVisible(!editable);
- } else {
- tagLabel->hide();
- tagComboBox->hide();
- }
- closeButton->setVisible(editable);
- updatePreferredStarVisibility();
- editableChanged(this->editable);
+ assert(tagComboBox);
+ assert(closeButton);
+
+ this->editable = editable;
+ if (taggable) {
+ tagLabel->setText(tagComboBox->itemText(0));
+ tagComboBox->setVisible(editable);
+ tagLabel->setVisible(!editable);
+ } else {
+ tagLabel->hide();
+ tagComboBox->hide();
+ }
+ closeButton->setVisible(editable);
+ updatePreferredStarVisibility();
+ editableChanged(this->editable);
}
void QtVCardGeneralField::setStarVisible(const bool isVisible) {
- starVisible = isVisible;
- updatePreferredStarVisibility();
+ starVisible = isVisible;
+ updatePreferredStarVisibility();
}
bool QtVCardGeneralField::getStarVisible() const {
- return starVisible;
+ return starVisible;
}
void QtVCardGeneralField::setPreferred(const bool preferred) {
- if (preferredCheckBox) preferredCheckBox->setChecked(preferred);
- updatePreferredStarVisibility();
+ if (preferredCheckBox) preferredCheckBox->setChecked(preferred);
+ updatePreferredStarVisibility();
}
bool QtVCardGeneralField::getPreferred() const {
- return preferredCheckBox ? preferredCheckBox->isChecked() : false;
+ return preferredCheckBox ? preferredCheckBox->isChecked() : false;
}
void QtVCardGeneralField::customCleanup() {
}
QtTagComboBox* QtVCardGeneralField::getTagComboBox() const {
- return tagComboBox;
+ return tagComboBox;
}
QGridLayout* QtVCardGeneralField::getGridLayout() const {
- return layout;
+ return layout;
}
void QtVCardGeneralField::handleCloseButtonClicked() {
- customCleanup();
- foreach(QWidget* widget, childWidgets) {
- widget->hide();
- layout->removeWidget(widget);
- }
- deleteField(this);
+ customCleanup();
+ foreach(QWidget* widget, childWidgets) {
+ widget->hide();
+ layout->removeWidget(widget);
+ }
+ deleteField(this);
}
void QtVCardGeneralField::handlePreferredStarStateChanged(int state) {
- if (state == Qt::Checked) {
- QToolTip::showText(QCursor::pos(), tr("Marked as your preferred %1. Click again to undo.").arg(labelText));
- }
+ if (state == Qt::Checked) {
+ QToolTip::showText(QCursor::pos(), tr("Marked as your preferred %1. Click again to undo.").arg(labelText));
+ }
}
void QtVCardGeneralField::updatePreferredStarVisibility() {
- if (preferredCheckBox) {
- bool showStar = false;
- if (editable) {
- if (starVisible) {
- showStar = true;
- }
- else {
- showStar = preferredCheckBox->isChecked();
- }
- }
- else {
- showStar = preferredCheckBox->isChecked();
- }
- preferredCheckBox->setVisible(showStar);
- preferredCheckBox->setEnabled(editable);
- }
+ if (preferredCheckBox) {
+ bool showStar = false;
+ if (editable) {
+ if (starVisible) {
+ showStar = true;
+ }
+ else {
+ showStar = preferredCheckBox->isChecked();
+ }
+ }
+ else {
+ showStar = preferredCheckBox->isChecked();
+ }
+ preferredCheckBox->setVisible(showStar);
+ preferredCheckBox->setEnabled(editable);
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
index 6583d12..d907196 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
@@ -25,69 +25,69 @@ namespace Swift {
class QtElidingLabel;
/*
- * covers features like:
- * - preffered (star ceckbox)
- * - combo check box
- * - label
- * - remove button
+ * covers features like:
+ * - preffered (star ceckbox)
+ * - combo check box
+ * - label
+ * - remove button
*/
class QtVCardGeneralField : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable NOTIFY editableChanged)
- Q_PROPERTY(bool empty READ isEmpty)
-
- public:
- explicit QtVCardGeneralField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false, int row = 0, QString label = QString(),
- bool preferrable = true, bool taggable = true);
- virtual ~QtVCardGeneralField();
-
- void initialize();
-
- virtual bool isEditable() const;
- virtual void setEditable(bool);
-
- virtual bool isEmpty() const = 0;
-
- void setStarVisible(const bool isVisible);
- bool getStarVisible() const;
-
- void setPreferred(const bool preferred);
- bool getPreferred() const;
-
- protected:
- virtual void setupContentWidgets() = 0;
- virtual void customCleanup();
-
- QtTagComboBox* getTagComboBox() const;
- QGridLayout* getGridLayout() const;
-
- signals:
- void editableChanged(bool);
- void deleteField(QtVCardGeneralField*);
-
- public slots:
- void handleCloseButtonClicked();
- void handlePreferredStarStateChanged(int statte);
-
- protected:
- QList<QWidget*> childWidgets;
-
- private:
- void updatePreferredStarVisibility();
-
- private:
- bool editable;
- bool preferrable;
- bool starVisible;
- bool taggable;
- QGridLayout* layout;
- int row;
- QCheckBox* preferredCheckBox;
- QLabel* label;
- QString labelText;
- QtTagComboBox* tagComboBox;
- QtElidingLabel* tagLabel;
- QtCloseButton* closeButton;
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable NOTIFY editableChanged)
+ Q_PROPERTY(bool empty READ isEmpty)
+
+ public:
+ explicit QtVCardGeneralField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false, int row = 0, QString label = QString(),
+ bool preferrable = true, bool taggable = true);
+ virtual ~QtVCardGeneralField();
+
+ void initialize();
+
+ virtual bool isEditable() const;
+ virtual void setEditable(bool);
+
+ virtual bool isEmpty() const = 0;
+
+ void setStarVisible(const bool isVisible);
+ bool getStarVisible() const;
+
+ void setPreferred(const bool preferred);
+ bool getPreferred() const;
+
+ protected:
+ virtual void setupContentWidgets() = 0;
+ virtual void customCleanup();
+
+ QtTagComboBox* getTagComboBox() const;
+ QGridLayout* getGridLayout() const;
+
+ signals:
+ void editableChanged(bool);
+ void deleteField(QtVCardGeneralField*);
+
+ public slots:
+ void handleCloseButtonClicked();
+ void handlePreferredStarStateChanged(int statte);
+
+ protected:
+ QList<QWidget*> childWidgets;
+
+ private:
+ void updatePreferredStarVisibility();
+
+ private:
+ bool editable;
+ bool preferrable;
+ bool starVisible;
+ bool taggable;
+ QGridLayout* layout;
+ int row;
+ QCheckBox* preferredCheckBox;
+ QLabel* label;
+ QString labelText;
+ QtTagComboBox* tagComboBox;
+ QtElidingLabel* tagLabel;
+ QtCloseButton* closeButton;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
index 3be6901..c147c68 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
@@ -21,25 +21,25 @@ QtVCardHomeWork::~QtVCardHomeWork() {
}
void QtVCardHomeWork::setTagComboBox(QtTagComboBox* tagBox) {
- tagComboBox = tagBox;
- tagComboBox->addTag("home", QObject::tr("Home"));
- tagComboBox->addTag("work", QObject::tr("Work"));
+ tagComboBox = tagBox;
+ tagComboBox->addTag("home", QObject::tr("Home"));
+ tagComboBox->addTag("work", QObject::tr("Work"));
}
void QtVCardHomeWork::setHome(const bool home) {
- tagComboBox->setTag("home", home);
+ tagComboBox->setTag("home", home);
}
bool QtVCardHomeWork::getHome() const {
- return tagComboBox->isTagSet("home");
+ return tagComboBox->isTagSet("home");
}
void QtVCardHomeWork::setWork(const bool work) {
- tagComboBox->setTag("work", work);
+ tagComboBox->setTag("work", work);
}
bool QtVCardHomeWork::getWork() const {
- return tagComboBox->isTagSet("work");
+ return tagComboBox->isTagSet("work");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
index aea2ff2..dd1452a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
@@ -19,19 +19,19 @@
namespace Swift {
class QtVCardHomeWork {
- public:
- QtVCardHomeWork();
- virtual ~QtVCardHomeWork();
+ public:
+ QtVCardHomeWork();
+ virtual ~QtVCardHomeWork();
- void setTagComboBox(QtTagComboBox* tagBox);
+ void setTagComboBox(QtTagComboBox* tagBox);
- void setHome(const bool home);
- bool getHome() const;
- void setWork(const bool work);
- bool getWork() const;
+ void setHome(const bool home);
+ bool getHome() const;
+ void setWork(const bool work);
+ bool getWork() const;
- private:
- QtTagComboBox* tagComboBox;
+ private:
+ QtTagComboBox* tagComboBox;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
index 9be9737..e563ca2 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
@@ -24,66 +24,66 @@
namespace Swift {
QtVCardInternetEMailField::QtVCardInternetEMailField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("E-Mail")), emailLineEdit(NULL), emailLabel(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("E-Mail")), emailLineEdit(NULL), emailLabel(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardInternetEMailField::~QtVCardInternetEMailField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardInternetEMailField::setupContentWidgets() {
- emailLabel = new QLabel(this);
- emailLabel->setOpenExternalLinks(true);
- emailLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
- emailLineEdit = new QtResizableLineEdit(this);
+ emailLabel = new QLabel(this);
+ emailLabel->setOpenExternalLinks(true);
+ emailLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
+ emailLineEdit = new QtResizableLineEdit(this);
#if QT_VERSION >= 0x040700
- emailLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
+ emailLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
#endif
- QHBoxLayout* emailLayout = new QHBoxLayout();
- emailLayout->addWidget(emailLabel);
- emailLayout->addWidget(emailLineEdit);
- getGridLayout()->addLayout(emailLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- setTabOrder(emailLineEdit, getTagComboBox());
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
- emailLabel->hide();
- childWidgets << emailLabel << emailLineEdit;
+ QHBoxLayout* emailLayout = new QHBoxLayout();
+ emailLayout->addWidget(emailLabel);
+ emailLayout->addWidget(emailLineEdit);
+ getGridLayout()->addLayout(emailLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ setTabOrder(emailLineEdit, getTagComboBox());
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
+ emailLabel->hide();
+ childWidgets << emailLabel << emailLineEdit;
}
bool QtVCardInternetEMailField::isEmpty() const {
- return emailLineEdit->text().isEmpty();
+ return emailLineEdit->text().isEmpty();
}
void QtVCardInternetEMailField::setInternetEMailAddress(const VCard::EMailAddress& address) {
- assert(address.isInternet);
- setPreferred(address.isPreferred);
- setHome(address.isHome);
- setWork(address.isWork);
- emailLineEdit->setText(P2QSTRING(address.address));
+ assert(address.isInternet);
+ setPreferred(address.isPreferred);
+ setHome(address.isHome);
+ setWork(address.isWork);
+ emailLineEdit->setText(P2QSTRING(address.address));
}
VCard::EMailAddress QtVCardInternetEMailField::getInternetEMailAddress() const {
- VCard::EMailAddress address;
- address.isInternet = true;
- address.isPreferred = getPreferred();
- address.isHome = getHome();
- address.isWork = getWork();
- address.address = Q2PSTRING(emailLineEdit->text());
- return address;
+ VCard::EMailAddress address;
+ address.isInternet = true;
+ address.isPreferred = getPreferred();
+ address.isHome = getHome();
+ address.isWork = getWork();
+ address.address = Q2PSTRING(emailLineEdit->text());
+ return address;
}
void QtVCardInternetEMailField::handleEditibleChanged(bool isEditable) {
- assert(emailLineEdit);
- assert(emailLabel);
+ assert(emailLineEdit);
+ assert(emailLabel);
- if (isEditable) {
- emailLineEdit->show();
- emailLabel->hide();
- } else {
- emailLineEdit->hide();
- emailLabel->setText(QString("<a href=\"mailto:%1\">%1</a>").arg(QtUtilities::htmlEscape(emailLineEdit->text())));
- emailLabel->show();
- }
+ if (isEditable) {
+ emailLineEdit->show();
+ emailLabel->hide();
+ } else {
+ emailLineEdit->hide();
+ emailLabel->setText(QString("<a href=\"mailto:%1\">%1</a>").arg(QtUtilities::htmlEscape(emailLineEdit->text())));
+ emailLabel->show();
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
index e3a5d79..63a83e2 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
@@ -22,28 +22,28 @@
namespace Swift {
class QtVCardInternetEMailField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("E-Mail"), UNLIMITED_INSTANCES, QtVCardInternetEMailField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("E-Mail"), UNLIMITED_INSTANCES, QtVCardInternetEMailField)
- QtVCardInternetEMailField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardInternetEMailField();
+ QtVCardInternetEMailField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardInternetEMailField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setInternetEMailAddress(const VCard::EMailAddress& address);
- VCard::EMailAddress getInternetEMailAddress() const;
+ void setInternetEMailAddress(const VCard::EMailAddress& address);
+ VCard::EMailAddress getInternetEMailAddress() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* emailLineEdit;
- QLabel* emailLabel;
+ private:
+ QtResizableLineEdit* emailLineEdit;
+ QLabel* emailLabel;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
index 4c23036..705ad6b 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
@@ -23,58 +23,58 @@
namespace Swift {
QtVCardJIDField::QtVCardJIDField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("JID"), false, false), jidLabel(NULL), jidLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("JID"), false, false), jidLabel(NULL), jidLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardJIDField::~QtVCardJIDField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardJIDField::setupContentWidgets() {
- jidLabel = new QLabel(this);
- jidLabel->setOpenExternalLinks(true);
- jidLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
- jidLineEdit = new QtResizableLineEdit(this);
+ jidLabel = new QLabel(this);
+ jidLabel->setOpenExternalLinks(true);
+ jidLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
+ jidLineEdit = new QtResizableLineEdit(this);
#if QT_VERSION >= 0x040700
- jidLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
+ jidLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
#endif
- QHBoxLayout* jidLayout = new QHBoxLayout();
- jidLayout->addWidget(jidLabel);
- jidLayout->addWidget(jidLineEdit);
- getGridLayout()->addLayout(jidLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ QHBoxLayout* jidLayout = new QHBoxLayout();
+ jidLayout->addWidget(jidLabel);
+ jidLayout->addWidget(jidLineEdit);
+ getGridLayout()->addLayout(jidLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- jidLabel->hide();
- getTagComboBox()->hide();
+ jidLabel->hide();
+ getTagComboBox()->hide();
- childWidgets << jidLabel << jidLineEdit;
+ childWidgets << jidLabel << jidLineEdit;
}
bool QtVCardJIDField::isEmpty() const {
- return jidLineEdit->text().isEmpty();
+ return jidLineEdit->text().isEmpty();
}
void QtVCardJIDField::setJID(const JID& jid) {
- std::string jidStr = jid.toBare().toString();
- jidLineEdit->setText(P2QSTRING(jidStr));
+ std::string jidStr = jid.toBare().toString();
+ jidLineEdit->setText(P2QSTRING(jidStr));
}
JID QtVCardJIDField::getJID() const {
- return JID(Q2PSTRING(jidLineEdit->text()));
+ return JID(Q2PSTRING(jidLineEdit->text()));
}
void QtVCardJIDField::handleEditibleChanged(bool isEditable) {
- assert(jidLineEdit);
- assert(jidLabel);
-
- if (isEditable) {
- jidLineEdit->show();
- jidLabel->hide();
- } else {
- jidLineEdit->hide();
- jidLabel->setText(QString("<a href=\"xmpp:%1\">%1</a>").arg(QtUtilities::htmlEscape(jidLineEdit->text())));
- jidLabel->show();
- }
+ assert(jidLineEdit);
+ assert(jidLabel);
+
+ if (isEditable) {
+ jidLineEdit->show();
+ jidLabel->hide();
+ } else {
+ jidLineEdit->hide();
+ jidLabel->setText(QString("<a href=\"xmpp:%1\">%1</a>").arg(QtUtilities::htmlEscape(jidLineEdit->text())));
+ jidLabel->show();
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
index 4e75885..2e9b4ef 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
@@ -21,28 +21,28 @@
namespace Swift {
class QtVCardJIDField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("JID"), UNLIMITED_INSTANCES, QtVCardJIDField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("JID"), UNLIMITED_INSTANCES, QtVCardJIDField)
- QtVCardJIDField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardJIDField();
+ QtVCardJIDField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardJIDField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setJID(const JID& jid);
- JID getJID() const;
+ void setJID(const JID& jid);
+ JID getJID() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QLabel* jidLabel;
- QtResizableLineEdit* jidLineEdit;
+ private:
+ QLabel* jidLabel;
+ QtResizableLineEdit* jidLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
index ba51078..8b94c42 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
@@ -17,129 +17,129 @@
namespace Swift {
QtVCardOrganizationField::QtVCardOrganizationField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Organization"), false, false), organizationLabel(NULL), organizationLineEdit(NULL), unitsTreeWidget(NULL), itemDelegate(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Organization"), false, false), organizationLabel(NULL), organizationLineEdit(NULL), unitsTreeWidget(NULL), itemDelegate(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardOrganizationField::~QtVCardOrganizationField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardOrganizationField::setupContentWidgets() {
- organizationLabel = new QLabel(this);
- organizationLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- organizationLineEdit = new QtResizableLineEdit(this);
- QHBoxLayout* organizationLayout = new QHBoxLayout();
- organizationLayout->addWidget(organizationLabel);
- organizationLayout->addWidget(organizationLineEdit);
+ organizationLabel = new QLabel(this);
+ organizationLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ organizationLineEdit = new QtResizableLineEdit(this);
+ QHBoxLayout* organizationLayout = new QHBoxLayout();
+ organizationLayout->addWidget(organizationLabel);
+ organizationLayout->addWidget(organizationLineEdit);
- getGridLayout()->addLayout(organizationLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getGridLayout()->addLayout(organizationLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- itemDelegate = new QtRemovableItemDelegate(style());
+ itemDelegate = new QtRemovableItemDelegate(style());
- unitsTreeWidget = new QTreeWidget(this);
- connect(unitsTreeWidget->model(), SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(handleRowsRemoved(QModelIndex,int,int)));
- unitsTreeWidget->setColumnCount(2);
- unitsTreeWidget->header()->setStretchLastSection(false);
- unitsTreeWidget->header()->resizeSection(1, itemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
+ unitsTreeWidget = new QTreeWidget(this);
+ connect(unitsTreeWidget->model(), SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(handleRowsRemoved(QModelIndex,int,int)));
+ unitsTreeWidget->setColumnCount(2);
+ unitsTreeWidget->header()->setStretchLastSection(false);
+ unitsTreeWidget->header()->resizeSection(1, itemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
#if QT_VERSION >= 0x050000
- unitsTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
+ unitsTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
- unitsTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
+ unitsTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
#endif
- unitsTreeWidget->setHeaderHidden(true);
- unitsTreeWidget->setRootIsDecorated(false);
- unitsTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
- unitsTreeWidget->setItemDelegateForColumn(1, itemDelegate);
- connect(unitsTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int)));
- getGridLayout()->addWidget(unitsTreeWidget, getGridLayout()->rowCount()-1, 4, 2, 1);
+ unitsTreeWidget->setHeaderHidden(true);
+ unitsTreeWidget->setRootIsDecorated(false);
+ unitsTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
+ unitsTreeWidget->setItemDelegateForColumn(1, itemDelegate);
+ connect(unitsTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int)));
+ getGridLayout()->addWidget(unitsTreeWidget, getGridLayout()->rowCount()-1, 4, 2, 1);
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- unitsTreeWidget->addTopLevelItem(item);
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
- getTagComboBox()->hide();
- organizationLabel->hide();
- childWidgets << organizationLabel << organizationLineEdit << unitsTreeWidget;
+ getTagComboBox()->hide();
+ organizationLabel->hide();
+ childWidgets << organizationLabel << organizationLineEdit << unitsTreeWidget;
}
bool QtVCardOrganizationField::isEmpty() const {
- return organizationLineEdit->text().isEmpty() && unitsTreeWidget->model()->rowCount() != 0;
+ return organizationLineEdit->text().isEmpty() && unitsTreeWidget->model()->rowCount() != 0;
}
void QtVCardOrganizationField::setOrganization(const VCard::Organization& organization) {
- organizationLineEdit->setText(P2QSTRING(organization.name));
- unitsTreeWidget->clear();
- foreach(std::string unit, organization.units) {
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(unit)) << "");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- unitsTreeWidget->addTopLevelItem(item);
- }
-
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- unitsTreeWidget->addTopLevelItem(item);
+ organizationLineEdit->setText(P2QSTRING(organization.name));
+ unitsTreeWidget->clear();
+ foreach(std::string unit, organization.units) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(unit)) << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
+ }
+
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
}
VCard::Organization QtVCardOrganizationField::getOrganization() const {
- VCard::Organization organization;
- organization.name = Q2PSTRING(organizationLineEdit->text());
- for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) {
- QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i);
- if (!row->text(0).isEmpty()) {
- organization.units.push_back(Q2PSTRING(row->text(0)));
- }
- }
-
- return organization;
+ VCard::Organization organization;
+ organization.name = Q2PSTRING(organizationLineEdit->text());
+ for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) {
+ QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i);
+ if (!row->text(0).isEmpty()) {
+ organization.units.push_back(Q2PSTRING(row->text(0)));
+ }
+ }
+
+ return organization;
}
void QtVCardOrganizationField::handleEditibleChanged(bool isEditable) {
- assert(organizationLineEdit);
- assert(unitsTreeWidget);
-
- organizationLineEdit->setVisible(isEditable);
- organizationLabel->setVisible(!isEditable);
-
- if (!isEditable) {
- QString label;
- for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) {
- QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i);
- if (!row->text(0).isEmpty()) {
- label += row->text(0) + ", ";
- }
- }
- label += organizationLineEdit->text();
- organizationLabel->setText(label);
- }
- unitsTreeWidget->setVisible(isEditable);
+ assert(organizationLineEdit);
+ assert(unitsTreeWidget);
+
+ organizationLineEdit->setVisible(isEditable);
+ organizationLabel->setVisible(!isEditable);
+
+ if (!isEditable) {
+ QString label;
+ for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) {
+ QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i);
+ if (!row->text(0).isEmpty()) {
+ label += row->text(0) + ", ";
+ }
+ }
+ label += organizationLineEdit->text();
+ organizationLabel->setText(label);
+ }
+ unitsTreeWidget->setVisible(isEditable);
}
void QtVCardOrganizationField::handleItemChanged(QTreeWidgetItem *, int) {
- guaranteeEmptyRow();
+ guaranteeEmptyRow();
}
void QtVCardOrganizationField::handleRowsRemoved(const QModelIndex&, int, int) {
- guaranteeEmptyRow();
+ guaranteeEmptyRow();
}
void QtVCardOrganizationField::guaranteeEmptyRow() {
- bool hasEmptyRow = false;
- QList<QTreeWidgetItem*> rows = unitsTreeWidget->findItems("", Qt::MatchFixedString);
- foreach(QTreeWidgetItem* row, rows) {
- if (row->text(0).isEmpty()) {
- hasEmptyRow = true;
- }
- }
-
- if (!hasEmptyRow) {
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- unitsTreeWidget->addTopLevelItem(item);
- unitsTreeWidget->setCurrentItem(item);
- }
+ bool hasEmptyRow = false;
+ QList<QTreeWidgetItem*> rows = unitsTreeWidget->findItems("", Qt::MatchFixedString);
+ foreach(QTreeWidgetItem* row, rows) {
+ if (row->text(0).isEmpty()) {
+ hasEmptyRow = true;
+ }
+ }
+
+ if (!hasEmptyRow) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
+ unitsTreeWidget->setCurrentItem(item);
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
index f567e92..6de3167 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
@@ -24,37 +24,37 @@
namespace Swift {
class QtVCardOrganizationField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Organization"), UNLIMITED_INSTANCES, QtVCardOrganizationField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Organization"), UNLIMITED_INSTANCES, QtVCardOrganizationField)
- QtVCardOrganizationField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardOrganizationField();
+ QtVCardOrganizationField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardOrganizationField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setOrganization(const VCard::Organization& organization);
- VCard::Organization getOrganization() const;
+ void setOrganization(const VCard::Organization& organization);
+ VCard::Organization getOrganization() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private slots:
- void handleItemChanged(QTreeWidgetItem*, int);
- void handleRowsRemoved(const QModelIndex&, int, int);
+ private slots:
+ void handleItemChanged(QTreeWidgetItem*, int);
+ void handleRowsRemoved(const QModelIndex&, int, int);
- private:
- void guaranteeEmptyRow();
+ private:
+ void guaranteeEmptyRow();
- private:
- QLabel* organizationLabel;
- QtResizableLineEdit* organizationLineEdit;
- QTreeWidget* unitsTreeWidget;
- QtRemovableItemDelegate* itemDelegate;
+ private:
+ QLabel* organizationLabel;
+ QtResizableLineEdit* organizationLineEdit;
+ QTreeWidget* unitsTreeWidget;
+ QtRemovableItemDelegate* itemDelegate;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
index 680fdb5..90d6e5e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
@@ -19,134 +19,134 @@
namespace Swift {
QtVCardPhotoAndNameFields::QtVCardPhotoAndNameFields(QWidget* parent) :
- QWidget(parent),
- ui(new Ui::QtVCardPhotoAndNameFields) {
- ui->setupUi(this);
- ui->lineEditPREFIX->hide();
- ui->lineEditMIDDLE->hide();
- ui->lineEditSUFFIX->hide();
- ui->lineEditFN->hide();
- ui->lineEditNICKNAME->hide();
- ui->labelFN->hide();
- ui->labelNICKNAME->hide();
- ui->labelFULLNAME->hide();
+ QWidget(parent),
+ ui(new Ui::QtVCardPhotoAndNameFields) {
+ ui->setupUi(this);
+ ui->lineEditPREFIX->hide();
+ ui->lineEditMIDDLE->hide();
+ ui->lineEditSUFFIX->hide();
+ ui->lineEditFN->hide();
+ ui->lineEditNICKNAME->hide();
+ ui->labelFN->hide();
+ ui->labelNICKNAME->hide();
+ ui->labelFULLNAME->hide();
#if QT_VERSION >= 0x040700
- ui->lineEditFN->setPlaceholderText(tr("Formatted Name"));
- ui->lineEditNICKNAME->setPlaceholderText(tr("Nickname"));
- ui->lineEditPREFIX->setPlaceholderText(tr("Prefix"));
- ui->lineEditGIVEN->setPlaceholderText(tr("Given Name"));
- ui->lineEditMIDDLE->setPlaceholderText(tr("Middle Name"));
- ui->lineEditFAMILY->setPlaceholderText(tr("Last Name"));
- ui->lineEditSUFFIX->setPlaceholderText(tr("Suffix"));
+ ui->lineEditFN->setPlaceholderText(tr("Formatted Name"));
+ ui->lineEditNICKNAME->setPlaceholderText(tr("Nickname"));
+ ui->lineEditPREFIX->setPlaceholderText(tr("Prefix"));
+ ui->lineEditGIVEN->setPlaceholderText(tr("Given Name"));
+ ui->lineEditMIDDLE->setPlaceholderText(tr("Middle Name"));
+ ui->lineEditFAMILY->setPlaceholderText(tr("Last Name"));
+ ui->lineEditSUFFIX->setPlaceholderText(tr("Suffix"));
#endif
- setEditable(false);
+ setEditable(false);
}
QtVCardPhotoAndNameFields::~QtVCardPhotoAndNameFields() {
- delete ui;
+ delete ui;
}
bool QtVCardPhotoAndNameFields::isEditable() const {
- return editable;
+ return editable;
}
void QtVCardPhotoAndNameFields::setEditable(bool editable) {
- this->editable = editable;
+ this->editable = editable;
- ui->avatarWidget->setEditable(editable);
- ui->lineEditFN->setVisible(editable);
- ui->labelFN->setVisible(!editable);
+ ui->avatarWidget->setEditable(editable);
+ ui->lineEditFN->setVisible(editable);
+ ui->labelFN->setVisible(!editable);
- ui->lineEditNICKNAME->setVisible(editable);
- ui->labelNICKNAME->setVisible(!editable);
+ ui->lineEditNICKNAME->setVisible(editable);
+ ui->labelNICKNAME->setVisible(!editable);
- // prefix given middle last suffix
- ui->lineEditPREFIX->setVisible(editable);
- ui->lineEditGIVEN->setVisible(editable);
- ui->lineEditMIDDLE->setVisible(editable);
- ui->lineEditFAMILY->setVisible(editable);
- ui->lineEditSUFFIX->setVisible(editable);
- ui->labelFULLNAME->setVisible(!editable);
+ // prefix given middle last suffix
+ ui->lineEditPREFIX->setVisible(editable);
+ ui->lineEditGIVEN->setVisible(editable);
+ ui->lineEditMIDDLE->setVisible(editable);
+ ui->lineEditFAMILY->setVisible(editable);
+ ui->lineEditSUFFIX->setVisible(editable);
+ ui->labelFULLNAME->setVisible(!editable);
- QStringList fullname;
- fullname << ui->lineEditPREFIX->text() << ui->lineEditGIVEN->text() << ui->lineEditMIDDLE->text();
- fullname << ui->lineEditFAMILY->text() << ui->lineEditSUFFIX->text();
- for (QStringList::iterator i = fullname.begin(); i != fullname.end(); i++) {
- *i = i->trimmed();
- }
- ui->labelFULLNAME->setText((fullname.filter(QRegExp(".+"))).join(" "));
+ QStringList fullname;
+ fullname << ui->lineEditPREFIX->text() << ui->lineEditGIVEN->text() << ui->lineEditMIDDLE->text();
+ fullname << ui->lineEditFAMILY->text() << ui->lineEditSUFFIX->text();
+ for (QStringList::iterator i = fullname.begin(); i != fullname.end(); i++) {
+ *i = i->trimmed();
+ }
+ ui->labelFULLNAME->setText((fullname.filter(QRegExp(".+"))).join(" "));
}
void QtVCardPhotoAndNameFields::setAvatar(const ByteArray &data, const std::string &type) {
- ui->avatarWidget->setAvatar(data, type);
+ ui->avatarWidget->setAvatar(data, type);
}
ByteArray QtVCardPhotoAndNameFields::getAvatarData() const {
- return ui->avatarWidget->getAvatarData();
+ return ui->avatarWidget->getAvatarData();
}
std::string QtVCardPhotoAndNameFields::getAvatarType() const {
- return ui->avatarWidget->getAvatarType();
+ return ui->avatarWidget->getAvatarType();
}
void QtVCardPhotoAndNameFields::setFormattedName(const QString& formattedName) {
- ui->lineEditFN->setText(formattedName);
- ui->labelFN->setText(formattedName);
+ ui->lineEditFN->setText(formattedName);
+ ui->labelFN->setText(formattedName);
}
QString QtVCardPhotoAndNameFields::getFormattedName() const {
- return ui->lineEditFN->text();
+ return ui->lineEditFN->text();
}
void QtVCardPhotoAndNameFields::setNickname(const QString& nickname) {
- ui->lineEditNICKNAME->setText(nickname);
- ui->labelNICKNAME->setText(nickname);
+ ui->lineEditNICKNAME->setText(nickname);
+ ui->labelNICKNAME->setText(nickname);
}
QString QtVCardPhotoAndNameFields::getNickname() const {
- return ui->lineEditNICKNAME->text();
+ return ui->lineEditNICKNAME->text();
}
void QtVCardPhotoAndNameFields::setPrefix(const QString& prefix) {
- ui->lineEditPREFIX->setText(prefix);
+ ui->lineEditPREFIX->setText(prefix);
}
QString QtVCardPhotoAndNameFields::getPrefix() const {
- return ui->lineEditPREFIX->text();
+ return ui->lineEditPREFIX->text();
}
void QtVCardPhotoAndNameFields::setGivenName(const QString& givenName) {
- ui->lineEditGIVEN->setText(givenName);
+ ui->lineEditGIVEN->setText(givenName);
}
QString QtVCardPhotoAndNameFields::getGivenName() const {
- return ui->lineEditGIVEN->text();
+ return ui->lineEditGIVEN->text();
}
void QtVCardPhotoAndNameFields::setMiddleName(const QString& middleName) {
- ui->lineEditMIDDLE->setText(middleName);
+ ui->lineEditMIDDLE->setText(middleName);
}
QString QtVCardPhotoAndNameFields::getMiddleName() const {
- return ui->lineEditMIDDLE->text();
+ return ui->lineEditMIDDLE->text();
}
void QtVCardPhotoAndNameFields::setFamilyName(const QString& familyName) {
- ui->lineEditFAMILY->setText(familyName);
+ ui->lineEditFAMILY->setText(familyName);
}
QString QtVCardPhotoAndNameFields::getFamilyName() const {
- return ui->lineEditFAMILY->text();
+ return ui->lineEditFAMILY->text();
}
void QtVCardPhotoAndNameFields::setSuffix(const QString& suffix) {
- ui->lineEditSUFFIX->setText(suffix);
+ ui->lineEditSUFFIX->setText(suffix);
}
QString QtVCardPhotoAndNameFields::getSuffix() const {
- return ui->lineEditSUFFIX->text();
+ return ui->lineEditSUFFIX->text();
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
index ac35109..a0bbb24 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
@@ -12,51 +12,51 @@
#include <Swiften/Base/ByteArray.h>
namespace Ui {
- class QtVCardPhotoAndNameFields;
+ class QtVCardPhotoAndNameFields;
}
namespace Swift {
- class QtVCardPhotoAndNameFields : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ class QtVCardPhotoAndNameFields : public QWidget {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- explicit QtVCardPhotoAndNameFields(QWidget* parent = 0);
- ~QtVCardPhotoAndNameFields();
+ public:
+ explicit QtVCardPhotoAndNameFields(QWidget* parent = 0);
+ ~QtVCardPhotoAndNameFields();
- bool isEditable() const;
- void setEditable(bool);
+ bool isEditable() const;
+ void setEditable(bool);
- void setAvatar(const ByteArray& data, const std::string& type);
- ByteArray getAvatarData() const;
- std::string getAvatarType() const;
+ void setAvatar(const ByteArray& data, const std::string& type);
+ ByteArray getAvatarData() const;
+ std::string getAvatarType() const;
- void setFormattedName(const QString& formattedName);
- QString getFormattedName() const;
+ void setFormattedName(const QString& formattedName);
+ QString getFormattedName() const;
- void setNickname(const QString& nickname);
- QString getNickname() const;
+ void setNickname(const QString& nickname);
+ QString getNickname() const;
- void setPrefix(const QString& prefix);
- QString getPrefix() const;
+ void setPrefix(const QString& prefix);
+ QString getPrefix() const;
- void setGivenName(const QString& givenName);
- QString getGivenName() const;
+ void setGivenName(const QString& givenName);
+ QString getGivenName() const;
- void setMiddleName(const QString& middleName);
- QString getMiddleName() const;
+ void setMiddleName(const QString& middleName);
+ QString getMiddleName() const;
- void setFamilyName(const QString& familyName);
- QString getFamilyName() const;
+ void setFamilyName(const QString& familyName);
+ QString getFamilyName() const;
- void setSuffix(const QString& suffix);
- QString getSuffix() const;
+ void setSuffix(const QString& suffix);
+ QString getSuffix() const;
- private:
- Ui::QtVCardPhotoAndNameFields* ui;
- bool editable;
- };
+ private:
+ Ui::QtVCardPhotoAndNameFields* ui;
+ bool editable;
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
index ce3cc2f..2881932 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
@@ -21,37 +21,37 @@
namespace Swift {
QtVCardRoleField::QtVCardRoleField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Role"), false, false), roleLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Role"), false, false), roleLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardRoleField::~QtVCardRoleField() {
}
void QtVCardRoleField::setupContentWidgets() {
- roleLineEdit = new QtResizableLineEdit(this);
- getGridLayout()->addWidget(roleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- childWidgets << roleLineEdit;
+ roleLineEdit = new QtResizableLineEdit(this);
+ getGridLayout()->addWidget(roleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ childWidgets << roleLineEdit;
}
bool QtVCardRoleField::isEmpty() const {
- return roleLineEdit->text().isEmpty();
+ return roleLineEdit->text().isEmpty();
}
void QtVCardRoleField::setRole(const std::string& role) {
- roleLineEdit->setText(P2QSTRING(role));
+ roleLineEdit->setText(P2QSTRING(role));
}
std::string QtVCardRoleField::getRole() const {
- return Q2PSTRING(roleLineEdit->text());
+ return Q2PSTRING(roleLineEdit->text());
}
void QtVCardRoleField::handleEditibleChanged(bool isEditable) {
- assert(roleLineEdit);
+ assert(roleLineEdit);
- roleLineEdit->setEditable(isEditable);
- roleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ roleLineEdit->setEditable(isEditable);
+ roleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
index f2d5e75..40b5d0b 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
@@ -21,27 +21,27 @@
namespace Swift {
class QtVCardRoleField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Role"), UNLIMITED_INSTANCES, QtVCardRoleField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Role"), UNLIMITED_INSTANCES, QtVCardRoleField)
- QtVCardRoleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardRoleField();
+ QtVCardRoleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardRoleField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setRole(const std::string& role);
- std::string getRole() const;
+ void setRole(const std::string& role);
+ std::string getRole() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* roleLineEdit;
+ private:
+ QtResizableLineEdit* roleLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
index 57e2b27..4af2fa3 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
@@ -19,88 +19,88 @@
namespace Swift {
QtVCardTelephoneField::QtVCardTelephoneField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Telephone")), telephoneLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Telephone")), telephoneLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardTelephoneField::~QtVCardTelephoneField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardTelephoneField::setupContentWidgets() {
- telephoneLineEdit = new QtResizableLineEdit(this);
+ telephoneLineEdit = new QtResizableLineEdit(this);
#if QT_VERSION >= 0x040700
- telephoneLineEdit->setPlaceholderText(tr("0118 999 881 999 119 7253"));
+ telephoneLineEdit->setPlaceholderText(tr("0118 999 881 999 119 7253"));
#endif
- getGridLayout()->addWidget(telephoneLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- setTabOrder(telephoneLineEdit, getTagComboBox());
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
-
- getTagComboBox()->addTag("voice", QObject::tr("Voice"));
- getTagComboBox()->addTag("fax", QObject::tr("Fax"));
- getTagComboBox()->addTag("pager", QObject::tr("Pager"));
- getTagComboBox()->addTag("msg", QObject::tr("Voice Messaging"));
- getTagComboBox()->addTag("cell", QObject::tr("Cell"));
- getTagComboBox()->addTag("video", QObject::tr("Video"));
- getTagComboBox()->addTag("bbs", QObject::tr("Bulletin Board System"));
- getTagComboBox()->addTag("modem", QObject::tr("Modem"));
- getTagComboBox()->addTag("isdn", QObject::tr("ISDN"));
- getTagComboBox()->addTag("pcs", QObject::tr("Personal Communication Services"));
-
- childWidgets << telephoneLineEdit;
+ getGridLayout()->addWidget(telephoneLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ setTabOrder(telephoneLineEdit, getTagComboBox());
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
+
+ getTagComboBox()->addTag("voice", QObject::tr("Voice"));
+ getTagComboBox()->addTag("fax", QObject::tr("Fax"));
+ getTagComboBox()->addTag("pager", QObject::tr("Pager"));
+ getTagComboBox()->addTag("msg", QObject::tr("Voice Messaging"));
+ getTagComboBox()->addTag("cell", QObject::tr("Cell"));
+ getTagComboBox()->addTag("video", QObject::tr("Video"));
+ getTagComboBox()->addTag("bbs", QObject::tr("Bulletin Board System"));
+ getTagComboBox()->addTag("modem", QObject::tr("Modem"));
+ getTagComboBox()->addTag("isdn", QObject::tr("ISDN"));
+ getTagComboBox()->addTag("pcs", QObject::tr("Personal Communication Services"));
+
+ childWidgets << telephoneLineEdit;
}
bool QtVCardTelephoneField::isEmpty() const {
- return telephoneLineEdit->text().isEmpty();
+ return telephoneLineEdit->text().isEmpty();
}
void QtVCardTelephoneField::setTelephone(const VCard::Telephone& telephone) {
- setPreferred(telephone.isPreferred);
- setHome(telephone.isHome);
- setWork(telephone.isWork);
-
- telephoneLineEdit->setText(P2QSTRING(telephone.number));
-
- getTagComboBox()->setTag("voice", telephone.isVoice);
- getTagComboBox()->setTag("fax", telephone.isFax);
- getTagComboBox()->setTag("pager", telephone.isPager);
- getTagComboBox()->setTag("msg", telephone.isMSG);
- getTagComboBox()->setTag("cell", telephone.isCell);
- getTagComboBox()->setTag("video", telephone.isVideo);
- getTagComboBox()->setTag("bbs", telephone.isBBS);
- getTagComboBox()->setTag("modem", telephone.isModem);
- getTagComboBox()->setTag("isdn", telephone.isISDN);
- getTagComboBox()->setTag("pcs", telephone.isPCS);
+ setPreferred(telephone.isPreferred);
+ setHome(telephone.isHome);
+ setWork(telephone.isWork);
+
+ telephoneLineEdit->setText(P2QSTRING(telephone.number));
+
+ getTagComboBox()->setTag("voice", telephone.isVoice);
+ getTagComboBox()->setTag("fax", telephone.isFax);
+ getTagComboBox()->setTag("pager", telephone.isPager);
+ getTagComboBox()->setTag("msg", telephone.isMSG);
+ getTagComboBox()->setTag("cell", telephone.isCell);
+ getTagComboBox()->setTag("video", telephone.isVideo);
+ getTagComboBox()->setTag("bbs", telephone.isBBS);
+ getTagComboBox()->setTag("modem", telephone.isModem);
+ getTagComboBox()->setTag("isdn", telephone.isISDN);
+ getTagComboBox()->setTag("pcs", telephone.isPCS);
}
VCard::Telephone QtVCardTelephoneField::getTelephone() const {
- VCard::Telephone telephone;
-
- telephone.number = Q2PSTRING(telephoneLineEdit->text());
-
- telephone.isPreferred = getPreferred();
- telephone.isHome = getHome();
- telephone.isWork = getWork();
-
- telephone.isVoice = getTagComboBox()->isTagSet("voice");
- telephone.isFax = getTagComboBox()->isTagSet("fax");
- telephone.isPager = getTagComboBox()->isTagSet("pager");
- telephone.isMSG = getTagComboBox()->isTagSet("msg");
- telephone.isCell = getTagComboBox()->isTagSet("cell");
- telephone.isVideo = getTagComboBox()->isTagSet("video");
- telephone.isBBS = getTagComboBox()->isTagSet("bbs");
- telephone.isModem = getTagComboBox()->isTagSet("modem");
- telephone.isISDN = getTagComboBox()->isTagSet("isdn");
- telephone.isPCS = getTagComboBox()->isTagSet("pcs");
-
- return telephone;
+ VCard::Telephone telephone;
+
+ telephone.number = Q2PSTRING(telephoneLineEdit->text());
+
+ telephone.isPreferred = getPreferred();
+ telephone.isHome = getHome();
+ telephone.isWork = getWork();
+
+ telephone.isVoice = getTagComboBox()->isTagSet("voice");
+ telephone.isFax = getTagComboBox()->isTagSet("fax");
+ telephone.isPager = getTagComboBox()->isTagSet("pager");
+ telephone.isMSG = getTagComboBox()->isTagSet("msg");
+ telephone.isCell = getTagComboBox()->isTagSet("cell");
+ telephone.isVideo = getTagComboBox()->isTagSet("video");
+ telephone.isBBS = getTagComboBox()->isTagSet("bbs");
+ telephone.isModem = getTagComboBox()->isTagSet("modem");
+ telephone.isISDN = getTagComboBox()->isTagSet("isdn");
+ telephone.isPCS = getTagComboBox()->isTagSet("pcs");
+
+ return telephone;
}
void QtVCardTelephoneField::handleEditibleChanged(bool isEditable) {
- assert(telephoneLineEdit);
+ assert(telephoneLineEdit);
- telephoneLineEdit->setEditable(isEditable);
- telephoneLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ telephoneLineEdit->setEditable(isEditable);
+ telephoneLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
index a06eb32..1a08a5a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
@@ -22,27 +22,27 @@
namespace Swift {
class QtVCardTelephoneField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Telephone"), UNLIMITED_INSTANCES, QtVCardTelephoneField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Telephone"), UNLIMITED_INSTANCES, QtVCardTelephoneField)
- QtVCardTelephoneField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardTelephoneField();
+ QtVCardTelephoneField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardTelephoneField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setTelephone(const VCard::Telephone& telephone);
- VCard::Telephone getTelephone() const;
+ void setTelephone(const VCard::Telephone& telephone);
+ VCard::Telephone getTelephone() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* telephoneLineEdit;
+ private:
+ QtResizableLineEdit* telephoneLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
index aab7fac..5da5763 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
@@ -21,38 +21,38 @@
namespace Swift {
QtVCardTitleField::QtVCardTitleField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Title"), false, false), titleLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Title"), false, false), titleLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardTitleField::~QtVCardTitleField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardTitleField::setupContentWidgets() {
- titleLineEdit = new QtResizableLineEdit(this);
- getGridLayout()->addWidget(titleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- childWidgets << titleLineEdit;
+ titleLineEdit = new QtResizableLineEdit(this);
+ getGridLayout()->addWidget(titleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ childWidgets << titleLineEdit;
}
bool QtVCardTitleField::isEmpty() const {
- return titleLineEdit->text().isEmpty();
+ return titleLineEdit->text().isEmpty();
}
void QtVCardTitleField::setTitle(const std::string& title) {
- titleLineEdit->setText(P2QSTRING(title));
+ titleLineEdit->setText(P2QSTRING(title));
}
std::string QtVCardTitleField::getTitle() const {
- return Q2PSTRING(titleLineEdit->text());
+ return Q2PSTRING(titleLineEdit->text());
}
void QtVCardTitleField::handleEditibleChanged(bool isEditable) {
- assert(titleLineEdit);
+ assert(titleLineEdit);
- titleLineEdit->setEditable(isEditable);
- titleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ titleLineEdit->setEditable(isEditable);
+ titleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
index a7feb81..ff2a04e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
@@ -21,27 +21,27 @@
namespace Swift {
class QtVCardTitleField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Title"), UNLIMITED_INSTANCES, QtVCardTitleField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Title"), UNLIMITED_INSTANCES, QtVCardTitleField)
- QtVCardTitleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardTitleField();
+ QtVCardTitleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardTitleField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setTitle(const std::string& title);
- std::string getTitle() const;
+ void setTitle(const std::string& title);
+ std::string getTitle() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* titleLineEdit;
+ private:
+ QtResizableLineEdit* titleLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
index 262a0e2..8abc46e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
@@ -24,54 +24,54 @@
namespace Swift {
QtVCardURLField::QtVCardURLField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("URL"), false, false), urlLabel(NULL), urlLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("URL"), false, false), urlLabel(NULL), urlLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardURLField::~QtVCardURLField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardURLField::setupContentWidgets() {
- urlLabel = new QLabel(this);
- urlLabel->setOpenExternalLinks(true);
- urlLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
- urlLineEdit = new QtResizableLineEdit(this);
-
- QHBoxLayout* urlLayout = new QHBoxLayout();
- urlLayout->addWidget(urlLabel);
- urlLayout->addWidget(urlLineEdit);
-
- getGridLayout()->addLayout(urlLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- urlLabel->hide();
- childWidgets << urlLabel << urlLineEdit;
+ urlLabel = new QLabel(this);
+ urlLabel->setOpenExternalLinks(true);
+ urlLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
+ urlLineEdit = new QtResizableLineEdit(this);
+
+ QHBoxLayout* urlLayout = new QHBoxLayout();
+ urlLayout->addWidget(urlLabel);
+ urlLayout->addWidget(urlLineEdit);
+
+ getGridLayout()->addLayout(urlLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ urlLabel->hide();
+ childWidgets << urlLabel << urlLineEdit;
}
bool QtVCardURLField::isEmpty() const {
- return urlLineEdit->text().isEmpty();
+ return urlLineEdit->text().isEmpty();
}
void QtVCardURLField::setURL(const std::string& url) {
- urlLineEdit->setText(P2QSTRING(url));
+ urlLineEdit->setText(P2QSTRING(url));
}
std::string QtVCardURLField::getURL() const {
- return Q2PSTRING(urlLineEdit->text());
+ return Q2PSTRING(urlLineEdit->text());
}
void QtVCardURLField::handleEditibleChanged(bool isEditable) {
- assert(urlLineEdit);
- assert(urlLabel);
-
- if (isEditable) {
- urlLineEdit->show();
- urlLabel->hide();
- } else {
- urlLineEdit->hide();
- urlLabel->setText(QString("<a href=\"%1\">%1</a>").arg(QtUtilities::htmlEscape(urlLineEdit->text())));
- urlLabel->show();
- }
+ assert(urlLineEdit);
+ assert(urlLabel);
+
+ if (isEditable) {
+ urlLineEdit->show();
+ urlLabel->hide();
+ } else {
+ urlLineEdit->hide();
+ urlLabel->setText(QString("<a href=\"%1\">%1</a>").arg(QtUtilities::htmlEscape(urlLineEdit->text())));
+ urlLabel->show();
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardURLField.h b/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
index 824879a..a1ffacd 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
@@ -21,28 +21,28 @@
namespace Swift {
class QtVCardURLField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("URL"), UNLIMITED_INSTANCES, QtVCardURLField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("URL"), UNLIMITED_INSTANCES, QtVCardURLField)
- QtVCardURLField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardURLField();
+ QtVCardURLField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardURLField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setURL(const std::string& url);
- std::string getURL() const;
+ void setURL(const std::string& url);
+ std::string getURL() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QLabel* urlLabel;
- QtResizableLineEdit* urlLineEdit;
+ private:
+ QLabel* urlLabel;
+ QtResizableLineEdit* urlLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp b/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
index f390d30..712cedf 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
@@ -33,394 +33,394 @@
namespace Swift {
QtVCardWidget::QtVCardWidget(QWidget* parent) :
- QWidget(parent),
- ui(new ::Ui::QtVCardWidget) {
- ui->setupUi(this);
-
- ui->cardFields->setColumnStretch(0,0);
- ui->cardFields->setColumnStretch(1,0);
- ui->cardFields->setColumnStretch(2,2);
- ui->cardFields->setColumnStretch(3,1);
- ui->cardFields->setColumnStretch(4,2);
- menu = new QMenu(this);
-
- toolButton = new QToolButton(this);
- toolButton->setText(tr("Add Field"));
- toolButton->setArrowType(Qt::NoArrow);
- toolButton->setAutoRaise(false);
- toolButton->setPopupMode(QToolButton::InstantPopup);
- toolButton->hide();
- toolButton->setMenu(menu);
-
- addFieldType(menu, boost::make_shared<QtVCardInternetEMailField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardTelephoneField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardAddressField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardAddressLabelField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardBirthdayField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardJIDField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardDescriptionField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardRoleField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardTitleField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardOrganizationField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardURLField::FieldInfo>());
-
- setEditable(false);
- setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
+ QWidget(parent),
+ ui(new ::Ui::QtVCardWidget) {
+ ui->setupUi(this);
+
+ ui->cardFields->setColumnStretch(0,0);
+ ui->cardFields->setColumnStretch(1,0);
+ ui->cardFields->setColumnStretch(2,2);
+ ui->cardFields->setColumnStretch(3,1);
+ ui->cardFields->setColumnStretch(4,2);
+ menu = new QMenu(this);
+
+ toolButton = new QToolButton(this);
+ toolButton->setText(tr("Add Field"));
+ toolButton->setArrowType(Qt::NoArrow);
+ toolButton->setAutoRaise(false);
+ toolButton->setPopupMode(QToolButton::InstantPopup);
+ toolButton->hide();
+ toolButton->setMenu(menu);
+
+ addFieldType(menu, boost::make_shared<QtVCardInternetEMailField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardTelephoneField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardAddressField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardAddressLabelField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardBirthdayField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardJIDField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardDescriptionField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardRoleField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardTitleField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardOrganizationField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardURLField::FieldInfo>());
+
+ setEditable(false);
+ setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}
QtVCardWidget::~QtVCardWidget() {
- delete ui;
+ delete ui;
}
QSize QtVCardWidget::sizeHint() const {
- QSize newSizeHint = ui->photoAndName->sizeHint();
+ QSize newSizeHint = ui->photoAndName->sizeHint();
- // use mininmal size that does not require scrolling
- QSize fieldsWidgetSize = ui->scrollArea->widget()->minimumSize();
- fieldsWidgetSize.setWidth(ui->scrollArea->widget()->sizeHint().width());
+ // use mininmal size that does not require scrolling
+ QSize fieldsWidgetSize = ui->scrollArea->widget()->minimumSize();
+ fieldsWidgetSize.setWidth(ui->scrollArea->widget()->sizeHint().width());
- newSizeHint += QSize(0, ui->line->height());
+ newSizeHint += QSize(0, ui->line->height());
- newSizeHint = QSize(std::max(newSizeHint.width(), fieldsWidgetSize.width()), newSizeHint.height() + fieldsWidgetSize.height());
+ newSizeHint = QSize(std::max(newSizeHint.width(), fieldsWidgetSize.width()), newSizeHint.height() + fieldsWidgetSize.height());
- // add layout margin
- newSizeHint += QSize(layout()->contentsMargins().left() + layout()->contentsMargins().right(), layout()->contentsMargins().top() + layout()->contentsMargins().bottom());
+ // add layout margin
+ newSizeHint += QSize(layout()->contentsMargins().left() + layout()->contentsMargins().right(), layout()->contentsMargins().top() + layout()->contentsMargins().bottom());
- // the spaceing before and after the line between the profile header and its fields
- newSizeHint += QSize(0, layout()->spacing() * 2);
+ // the spaceing before and after the line between the profile header and its fields
+ newSizeHint += QSize(0, layout()->spacing() * 2);
- return newSizeHint;
+ return newSizeHint;
}
bool QtVCardWidget::isEditable() const {
- return editable;
+ return editable;
}
void QtVCardWidget::setEditable(bool editable) {
- this->editable = editable;
+ this->editable = editable;
- ui->photoAndName->setProperty("editable", QVariant(editable));
+ ui->photoAndName->setProperty("editable", QVariant(editable));
- foreach(QtVCardGeneralField* field, fields) {
- field->setEditable(editable);
- }
- toolButton->setVisible(editable);
+ foreach(QtVCardGeneralField* field, fields) {
+ field->setEditable(editable);
+ }
+ toolButton->setVisible(editable);
- editableChanged(editable);
+ editableChanged(editable);
}
void QtVCardWidget::setVCard(VCard::ref vcard) {
- clearFields();
- this->vcard = boost::make_shared<VCard>(*vcard);
- ui->photoAndName->setFormattedName(P2QSTRING(vcard->getFullName()));
- ui->photoAndName->setNickname(P2QSTRING(vcard->getNickname()));
- ui->photoAndName->setPrefix(P2QSTRING(vcard->getPrefix()));
- ui->photoAndName->setGivenName(P2QSTRING(vcard->getGivenName()));
- ui->photoAndName->setMiddleName(P2QSTRING(vcard->getMiddleName()));
- ui->photoAndName->setFamilyName(P2QSTRING(vcard->getFamilyName()));
- ui->photoAndName->setSuffix(P2QSTRING(vcard->getSuffix()));
- ui->photoAndName->setAvatar(vcard->getPhoto(), vcard->getPhotoType());
-
- foreach (const VCard::EMailAddress& address, vcard->getEMailAddresses()) {
- if (address.isInternet) {
- QtVCardInternetEMailField* internetEmailField = new QtVCardInternetEMailField(this, ui->cardFields);
- internetEmailField->initialize();
- internetEmailField->setInternetEMailAddress(address);
- appendField(internetEmailField);
- }
- }
-
- foreach (const VCard::Telephone& telephone, vcard->getTelephones()) {
- QtVCardTelephoneField* telField = new QtVCardTelephoneField(this, ui->cardFields);
- telField->initialize();
- telField->setTelephone(telephone);
- appendField(telField);
- }
-
- foreach (const VCard::Address& address, vcard->getAddresses()) {
- QtVCardAddressField* addressField = new QtVCardAddressField(this, ui->cardFields);
- addressField->initialize();
- addressField->setAddress(address);
- appendField(addressField);
- }
-
- foreach (const VCard::AddressLabel& label, vcard->getAddressLabels()) {
- QtVCardAddressLabelField* addressLabelField = new QtVCardAddressLabelField(this, ui->cardFields);
- addressLabelField->initialize();
- addressLabelField->setAddressLabel(label);
- appendField(addressLabelField);
- }
-
- if (!vcard->getBirthday().is_not_a_date_time()) {
- QtVCardBirthdayField* bdayField = new QtVCardBirthdayField(this, ui->cardFields);
- bdayField->initialize();
- bdayField->setBirthday(vcard->getBirthday());
- appendField(bdayField);
- }
-
- foreach (const JID& jid, vcard->getJIDs()) {
- QtVCardJIDField* jidField = new QtVCardJIDField(this, ui->cardFields);
- jidField->initialize();
- jidField->setJID(jid);
- appendField(jidField);
- }
-
- if (!vcard->getDescription().empty()) {
- QtVCardDescriptionField* descField = new QtVCardDescriptionField(this, ui->cardFields);
- descField->initialize();
- descField->setDescription(vcard->getDescription());
- appendField(descField);
- }
-
- foreach (const VCard::Organization& org, vcard->getOrganizations()) {
- QtVCardOrganizationField* orgField = new QtVCardOrganizationField(this, ui->cardFields);
- orgField->initialize();
- orgField->setOrganization(org);
- appendField(orgField);
- }
-
- foreach (const std::string& role, vcard->getRoles()) {
- QtVCardRoleField* roleField = new QtVCardRoleField(this, ui->cardFields);
- roleField->initialize();
- roleField->setRole(role);
- appendField(roleField);
- }
-
- foreach (const std::string& title, vcard->getTitles()) {
- QtVCardTitleField* titleField = new QtVCardTitleField(this, ui->cardFields);
- titleField->initialize();
- titleField->setTitle(title);
- appendField(titleField);
- }
-
- foreach (const std::string& url, vcard->getURLs()) {
- QtVCardURLField* urlField = new QtVCardURLField(this, ui->cardFields);
- urlField->initialize();
- urlField->setURL(url);
- appendField(urlField);
- }
-
- relayoutToolButton();
- setEditable(editable);
+ clearFields();
+ this->vcard = boost::make_shared<VCard>(*vcard);
+ ui->photoAndName->setFormattedName(P2QSTRING(vcard->getFullName()));
+ ui->photoAndName->setNickname(P2QSTRING(vcard->getNickname()));
+ ui->photoAndName->setPrefix(P2QSTRING(vcard->getPrefix()));
+ ui->photoAndName->setGivenName(P2QSTRING(vcard->getGivenName()));
+ ui->photoAndName->setMiddleName(P2QSTRING(vcard->getMiddleName()));
+ ui->photoAndName->setFamilyName(P2QSTRING(vcard->getFamilyName()));
+ ui->photoAndName->setSuffix(P2QSTRING(vcard->getSuffix()));
+ ui->photoAndName->setAvatar(vcard->getPhoto(), vcard->getPhotoType());
+
+ foreach (const VCard::EMailAddress& address, vcard->getEMailAddresses()) {
+ if (address.isInternet) {
+ QtVCardInternetEMailField* internetEmailField = new QtVCardInternetEMailField(this, ui->cardFields);
+ internetEmailField->initialize();
+ internetEmailField->setInternetEMailAddress(address);
+ appendField(internetEmailField);
+ }
+ }
+
+ foreach (const VCard::Telephone& telephone, vcard->getTelephones()) {
+ QtVCardTelephoneField* telField = new QtVCardTelephoneField(this, ui->cardFields);
+ telField->initialize();
+ telField->setTelephone(telephone);
+ appendField(telField);
+ }
+
+ foreach (const VCard::Address& address, vcard->getAddresses()) {
+ QtVCardAddressField* addressField = new QtVCardAddressField(this, ui->cardFields);
+ addressField->initialize();
+ addressField->setAddress(address);
+ appendField(addressField);
+ }
+
+ foreach (const VCard::AddressLabel& label, vcard->getAddressLabels()) {
+ QtVCardAddressLabelField* addressLabelField = new QtVCardAddressLabelField(this, ui->cardFields);
+ addressLabelField->initialize();
+ addressLabelField->setAddressLabel(label);
+ appendField(addressLabelField);
+ }
+
+ if (!vcard->getBirthday().is_not_a_date_time()) {
+ QtVCardBirthdayField* bdayField = new QtVCardBirthdayField(this, ui->cardFields);
+ bdayField->initialize();
+ bdayField->setBirthday(vcard->getBirthday());
+ appendField(bdayField);
+ }
+
+ foreach (const JID& jid, vcard->getJIDs()) {
+ QtVCardJIDField* jidField = new QtVCardJIDField(this, ui->cardFields);
+ jidField->initialize();
+ jidField->setJID(jid);
+ appendField(jidField);
+ }
+
+ if (!vcard->getDescription().empty()) {
+ QtVCardDescriptionField* descField = new QtVCardDescriptionField(this, ui->cardFields);
+ descField->initialize();
+ descField->setDescription(vcard->getDescription());
+ appendField(descField);
+ }
+
+ foreach (const VCard::Organization& org, vcard->getOrganizations()) {
+ QtVCardOrganizationField* orgField = new QtVCardOrganizationField(this, ui->cardFields);
+ orgField->initialize();
+ orgField->setOrganization(org);
+ appendField(orgField);
+ }
+
+ foreach (const std::string& role, vcard->getRoles()) {
+ QtVCardRoleField* roleField = new QtVCardRoleField(this, ui->cardFields);
+ roleField->initialize();
+ roleField->setRole(role);
+ appendField(roleField);
+ }
+
+ foreach (const std::string& title, vcard->getTitles()) {
+ QtVCardTitleField* titleField = new QtVCardTitleField(this, ui->cardFields);
+ titleField->initialize();
+ titleField->setTitle(title);
+ appendField(titleField);
+ }
+
+ foreach (const std::string& url, vcard->getURLs()) {
+ QtVCardURLField* urlField = new QtVCardURLField(this, ui->cardFields);
+ urlField->initialize();
+ urlField->setURL(url);
+ appendField(urlField);
+ }
+
+ relayoutToolButton();
+ setEditable(editable);
}
VCard::ref QtVCardWidget::getVCard() {
- clearEmptyFields();
- vcard->setFullName(Q2PSTRING(ui->photoAndName->getFormattedName()));
- vcard->setNickname(Q2PSTRING(ui->photoAndName->getNickname()));
- vcard->setPrefix(Q2PSTRING(ui->photoAndName->getPrefix()));
- vcard->setGivenName(Q2PSTRING(ui->photoAndName->getGivenName()));
- vcard->setMiddleName(Q2PSTRING(ui->photoAndName->getMiddleName()));
- vcard->setFamilyName(Q2PSTRING(ui->photoAndName->getFamilyName()));
- vcard->setSuffix(Q2PSTRING(ui->photoAndName->getSuffix()));
- vcard->setPhoto(ui->photoAndName->getAvatarData());
- vcard->setPhotoType(ui->photoAndName->getAvatarType());
-
- vcard->clearEMailAddresses();
- vcard->clearJIDs();
- vcard->clearURLs();
- vcard->clearTelephones();
- vcard->clearRoles();
- vcard->clearTitles();
- vcard->clearOrganizations();
- vcard->clearAddresses();
- vcard->clearAddressLabels();
-
-
- QtVCardBirthdayField* bdayField = NULL;
- QtVCardDescriptionField* descriptionField = NULL;
-
- foreach(QtVCardGeneralField* field, fields) {
- QtVCardInternetEMailField* emailField;
- if ((emailField = dynamic_cast<QtVCardInternetEMailField*>(field))) {
- vcard->addEMailAddress(emailField->getInternetEMailAddress());
- continue;
- }
-
- QtVCardTelephoneField* telephoneField;
- if ((telephoneField = dynamic_cast<QtVCardTelephoneField*>(field))) {
- vcard->addTelephone(telephoneField->getTelephone());
- continue;
- }
-
- QtVCardAddressField* addressField;
- if ((addressField = dynamic_cast<QtVCardAddressField*>(field))) {
- vcard->addAddress(addressField->getAddress());
- continue;
- }
-
- QtVCardAddressLabelField* addressLabelField;
- if ((addressLabelField = dynamic_cast<QtVCardAddressLabelField*>(field))) {
- vcard->addAddressLabel(addressLabelField->getAddressLabel());
- continue;
- }
-
- if ((bdayField = dynamic_cast<QtVCardBirthdayField*>(field))) {
- continue;
- }
-
- QtVCardJIDField* jidField;
- if ((jidField = dynamic_cast<QtVCardJIDField*>(field))) {
- vcard->addJID(jidField->getJID());
- continue;
- }
-
- if ((descriptionField = dynamic_cast<QtVCardDescriptionField*>(field))) {
- continue;
- }
-
- QtVCardOrganizationField* orgField;
- if ((orgField = dynamic_cast<QtVCardOrganizationField*>(field))) {
- vcard->addOrganization(orgField->getOrganization());
- continue;
- }
-
- QtVCardRoleField* roleField;
- if ((roleField = dynamic_cast<QtVCardRoleField*>(field))) {
- vcard->addRole(roleField->getRole());
- continue;
- }
-
- QtVCardTitleField* titleField;
- if ((titleField = dynamic_cast<QtVCardTitleField*>(field))) {
- vcard->addTitle(titleField->getTitle());
- continue;
- }
-
- QtVCardURLField* urlField;
- if ((urlField = dynamic_cast<QtVCardURLField*>(field))) {
- vcard->addURL(urlField->getURL());
- continue;
- }
- }
-
- if (bdayField) {
- vcard->setBirthday(bdayField->getBirthday());
- } else {
- vcard->setBirthday(boost::posix_time::ptime());
- }
-
- if (descriptionField) {
- vcard->setDescription(descriptionField->getDescription());
- } else {
- vcard->setDescription("");
- }
-
- return vcard;
+ clearEmptyFields();
+ vcard->setFullName(Q2PSTRING(ui->photoAndName->getFormattedName()));
+ vcard->setNickname(Q2PSTRING(ui->photoAndName->getNickname()));
+ vcard->setPrefix(Q2PSTRING(ui->photoAndName->getPrefix()));
+ vcard->setGivenName(Q2PSTRING(ui->photoAndName->getGivenName()));
+ vcard->setMiddleName(Q2PSTRING(ui->photoAndName->getMiddleName()));
+ vcard->setFamilyName(Q2PSTRING(ui->photoAndName->getFamilyName()));
+ vcard->setSuffix(Q2PSTRING(ui->photoAndName->getSuffix()));
+ vcard->setPhoto(ui->photoAndName->getAvatarData());
+ vcard->setPhotoType(ui->photoAndName->getAvatarType());
+
+ vcard->clearEMailAddresses();
+ vcard->clearJIDs();
+ vcard->clearURLs();
+ vcard->clearTelephones();
+ vcard->clearRoles();
+ vcard->clearTitles();
+ vcard->clearOrganizations();
+ vcard->clearAddresses();
+ vcard->clearAddressLabels();
+
+
+ QtVCardBirthdayField* bdayField = NULL;
+ QtVCardDescriptionField* descriptionField = NULL;
+
+ foreach(QtVCardGeneralField* field, fields) {
+ QtVCardInternetEMailField* emailField;
+ if ((emailField = dynamic_cast<QtVCardInternetEMailField*>(field))) {
+ vcard->addEMailAddress(emailField->getInternetEMailAddress());
+ continue;
+ }
+
+ QtVCardTelephoneField* telephoneField;
+ if ((telephoneField = dynamic_cast<QtVCardTelephoneField*>(field))) {
+ vcard->addTelephone(telephoneField->getTelephone());
+ continue;
+ }
+
+ QtVCardAddressField* addressField;
+ if ((addressField = dynamic_cast<QtVCardAddressField*>(field))) {
+ vcard->addAddress(addressField->getAddress());
+ continue;
+ }
+
+ QtVCardAddressLabelField* addressLabelField;
+ if ((addressLabelField = dynamic_cast<QtVCardAddressLabelField*>(field))) {
+ vcard->addAddressLabel(addressLabelField->getAddressLabel());
+ continue;
+ }
+
+ if ((bdayField = dynamic_cast<QtVCardBirthdayField*>(field))) {
+ continue;
+ }
+
+ QtVCardJIDField* jidField;
+ if ((jidField = dynamic_cast<QtVCardJIDField*>(field))) {
+ vcard->addJID(jidField->getJID());
+ continue;
+ }
+
+ if ((descriptionField = dynamic_cast<QtVCardDescriptionField*>(field))) {
+ continue;
+ }
+
+ QtVCardOrganizationField* orgField;
+ if ((orgField = dynamic_cast<QtVCardOrganizationField*>(field))) {
+ vcard->addOrganization(orgField->getOrganization());
+ continue;
+ }
+
+ QtVCardRoleField* roleField;
+ if ((roleField = dynamic_cast<QtVCardRoleField*>(field))) {
+ vcard->addRole(roleField->getRole());
+ continue;
+ }
+
+ QtVCardTitleField* titleField;
+ if ((titleField = dynamic_cast<QtVCardTitleField*>(field))) {
+ vcard->addTitle(titleField->getTitle());
+ continue;
+ }
+
+ QtVCardURLField* urlField;
+ if ((urlField = dynamic_cast<QtVCardURLField*>(field))) {
+ vcard->addURL(urlField->getURL());
+ continue;
+ }
+ }
+
+ if (bdayField) {
+ vcard->setBirthday(bdayField->getBirthday());
+ } else {
+ vcard->setBirthday(boost::posix_time::ptime());
+ }
+
+ if (descriptionField) {
+ vcard->setDescription(descriptionField->getDescription());
+ } else {
+ vcard->setDescription("");
+ }
+
+ return vcard;
}
void QtVCardWidget::addField() {
- QAction* action = NULL;
- if ((action = dynamic_cast<QAction*>(sender()))) {
- boost::shared_ptr<QtVCardFieldInfo> fieldInfo = actionFieldInfo[action];
- QWidget* newField = fieldInfo->createFieldInstance(this, ui->cardFields, true);
- QtVCardGeneralField* newGeneralField = dynamic_cast<QtVCardGeneralField*>(newField);
- if (newGeneralField) {
- newGeneralField->initialize();
- }
- appendField(newGeneralField);
- relayoutToolButton();
- }
+ QAction* action = NULL;
+ if ((action = dynamic_cast<QAction*>(sender()))) {
+ boost::shared_ptr<QtVCardFieldInfo> fieldInfo = actionFieldInfo[action];
+ QWidget* newField = fieldInfo->createFieldInstance(this, ui->cardFields, true);
+ QtVCardGeneralField* newGeneralField = dynamic_cast<QtVCardGeneralField*>(newField);
+ if (newGeneralField) {
+ newGeneralField->initialize();
+ }
+ appendField(newGeneralField);
+ relayoutToolButton();
+ }
}
void QtVCardWidget::removeField(QtVCardGeneralField *field) {
- int sameFields = 0;
- QtVCardGeneralField* fieldToChange = NULL;
- foreach (QtVCardGeneralField* vcardField, fields) {
- if ((vcardField != field) && (typeid(*vcardField) == typeid(*field))) {
- sameFields++;
- fieldToChange = vcardField;
- }
- }
-
- if ((sameFields == 1) && fieldToChange) {
- fieldToChange->setStarVisible(false);
- }
-
- fields.remove(field);
- delete field;
+ int sameFields = 0;
+ QtVCardGeneralField* fieldToChange = NULL;
+ foreach (QtVCardGeneralField* vcardField, fields) {
+ if ((vcardField != field) && (typeid(*vcardField) == typeid(*field))) {
+ sameFields++;
+ fieldToChange = vcardField;
+ }
+ }
+
+ if ((sameFields == 1) && fieldToChange) {
+ fieldToChange->setStarVisible(false);
+ }
+
+ fields.remove(field);
+ delete field;
}
void QtVCardWidget::addFieldType(QMenu* menu, boost::shared_ptr<QtVCardFieldInfo> fieldType) {
- if (!fieldType->getMenuName().isEmpty()) {
- QAction* action = new QAction(tr("Add %1").arg(fieldType->getMenuName()), this);
- actionFieldInfo[action] = fieldType;
- connect(action, SIGNAL(triggered()), this, SLOT(addField()));
- menu->addAction(action);
- }
+ if (!fieldType->getMenuName().isEmpty()) {
+ QAction* action = new QAction(tr("Add %1").arg(fieldType->getMenuName()), this);
+ actionFieldInfo[action] = fieldType;
+ connect(action, SIGNAL(triggered()), this, SLOT(addField()));
+ menu->addAction(action);
+ }
}
int QtVCardWidget::fieldTypeInstances(boost::shared_ptr<QtVCardFieldInfo> fieldType) {
- int instances = 0;
- for (int n = 0; n < ui->cardFields->count(); n++) {
- if (fieldType->testInstance(ui->cardFields->itemAt(n)->widget())) instances++;
- }
- return instances;
+ int instances = 0;
+ for (int n = 0; n < ui->cardFields->count(); n++) {
+ if (fieldType->testInstance(ui->cardFields->itemAt(n)->widget())) instances++;
+ }
+ return instances;
}
void layoutDeleteChildren(QLayout *layout) {
- while(layout->count() > 0) {
- QLayoutItem* child;
- if ((child = layout->takeAt(0)) != 0) {
- if (child->layout()) {
- layoutDeleteChildren(child->layout());
- }
- if (dynamic_cast<QToolButton*>(child->widget())) {
- delete child;
- break;
- }
- delete child->widget();
- delete child;
- }
- }
+ while(layout->count() > 0) {
+ QLayoutItem* child;
+ if ((child = layout->takeAt(0)) != 0) {
+ if (child->layout()) {
+ layoutDeleteChildren(child->layout());
+ }
+ if (dynamic_cast<QToolButton*>(child->widget())) {
+ delete child;
+ break;
+ }
+ delete child->widget();
+ delete child;
+ }
+ }
}
void QtVCardWidget::clearFields() {
- foreach(QtVCardGeneralField* field, fields) {
- delete field;
- }
- fields.clear();
+ foreach(QtVCardGeneralField* field, fields) {
+ delete field;
+ }
+ fields.clear();
- assert(ui->cardFields->count() >= 0);
- layoutDeleteChildren(ui->cardFields);
+ assert(ui->cardFields->count() >= 0);
+ layoutDeleteChildren(ui->cardFields);
}
void QtVCardWidget::clearEmptyFields() {
- std::vector<QtVCardGeneralField*> items_to_remove;
- foreach (QtVCardGeneralField* field, fields) {
- if (field->property("empty").isValid() && field->property("empty").toBool()) {
- ui->cardFields->removeWidget(field);
- items_to_remove.push_back(field);
- delete field;
- }
- }
-
- foreach(QtVCardGeneralField* field, items_to_remove) {
- fields.remove(field);
- }
+ std::vector<QtVCardGeneralField*> items_to_remove;
+ foreach (QtVCardGeneralField* field, fields) {
+ if (field->property("empty").isValid() && field->property("empty").toBool()) {
+ ui->cardFields->removeWidget(field);
+ items_to_remove.push_back(field);
+ delete field;
+ }
+ }
+
+ foreach(QtVCardGeneralField* field, items_to_remove) {
+ fields.remove(field);
+ }
}
void QtVCardWidget::appendField(QtVCardGeneralField *field) {
- connect(field, SIGNAL(deleteField(QtVCardGeneralField*)), SLOT(removeField(QtVCardGeneralField*)));
-
- QtVCardGeneralField* fieldToChange = NULL;
- foreach (QtVCardGeneralField* vcardField, fields) {
- if (typeid(*vcardField) == typeid(*field)) {
- fieldToChange = vcardField;
- break;
- }
- }
-
- if (fieldToChange) {
- fieldToChange->setStarVisible(true);
- field->setStarVisible(true);
- }
-
- fields.push_back(field);
+ connect(field, SIGNAL(deleteField(QtVCardGeneralField*)), SLOT(removeField(QtVCardGeneralField*)));
+
+ QtVCardGeneralField* fieldToChange = NULL;
+ foreach (QtVCardGeneralField* vcardField, fields) {
+ if (typeid(*vcardField) == typeid(*field)) {
+ fieldToChange = vcardField;
+ break;
+ }
+ }
+
+ if (fieldToChange) {
+ fieldToChange->setStarVisible(true);
+ field->setStarVisible(true);
+ }
+
+ fields.push_back(field);
}
void QtVCardWidget::relayoutToolButton() {
- ui->cardFields->addWidget(toolButton, ui->cardFields->rowCount(), ui->cardFields->columnCount()-2, 1, 1, Qt::AlignRight);
+ ui->cardFields->addWidget(toolButton, ui->cardFields->rowCount(), ui->cardFields->columnCount()-2, 1, 1, Qt::AlignRight);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardWidget.h b/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
index 8c0ff31..95283c5 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
@@ -24,50 +24,50 @@
#include <Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h>
namespace Ui {
- class QtVCardWidget;
+ class QtVCardWidget;
}
namespace Swift {
- class QtVCardWidget : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
-
- public :
- explicit QtVCardWidget(QWidget* parent = 0);
- ~QtVCardWidget();
-
- bool isEditable() const;
- void setEditable(bool);
-
- void setVCard(VCard::ref vcard);
- VCard::ref getVCard();
-
- virtual QSize sizeHint() const;
-
- signals:
- void editableChanged(bool editable);
-
- private slots:
- void addField();
- void removeField(QtVCardGeneralField* field);
-
- private:
- void addFieldType(QMenu*, boost::shared_ptr<QtVCardFieldInfo>);
- int fieldTypeInstances(boost::shared_ptr<QtVCardFieldInfo>);
- void clearFields();
- void clearEmptyFields();
- void appendField(QtVCardGeneralField* field);
- void relayoutToolButton();
-
- private:
- VCard::ref vcard;
- Ui::QtVCardWidget* ui;
- QToolButton* toolButton;
- bool editable;
- QMenu* menu;
- std::list<QtVCardGeneralField*> fields;
- std::map<QAction*, boost::shared_ptr<QtVCardFieldInfo> > actionFieldInfo;
- };
+ class QtVCardWidget : public QWidget {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+
+ public :
+ explicit QtVCardWidget(QWidget* parent = 0);
+ ~QtVCardWidget();
+
+ bool isEditable() const;
+ void setEditable(bool);
+
+ void setVCard(VCard::ref vcard);
+ VCard::ref getVCard();
+
+ virtual QSize sizeHint() const;
+
+ signals:
+ void editableChanged(bool editable);
+
+ private slots:
+ void addField();
+ void removeField(QtVCardGeneralField* field);
+
+ private:
+ void addFieldType(QMenu*, boost::shared_ptr<QtVCardFieldInfo>);
+ int fieldTypeInstances(boost::shared_ptr<QtVCardFieldInfo>);
+ void clearFields();
+ void clearEmptyFields();
+ void appendField(QtVCardGeneralField* field);
+ void relayoutToolButton();
+
+ private:
+ VCard::ref vcard;
+ Ui::QtVCardWidget* ui;
+ QToolButton* toolButton;
+ bool editable;
+ QMenu* menu;
+ std::list<QtVCardGeneralField*> fields;
+ std::map<QAction*, boost::shared_ptr<QtVCardFieldInfo> > actionFieldInfo;
+ };
}
diff --git a/Swift/QtUI/QtWebKitChatView.cpp b/Swift/QtUI/QtWebKitChatView.cpp
index a0c65ef..4193921 100644
--- a/Swift/QtUI/QtWebKitChatView.cpp
+++ b/Swift/QtUI/QtWebKitChatView.cpp
@@ -50,926 +50,926 @@ const QString QtWebKitChatView::ButtonFileTransferOpenFile = QString("filetransf
const QString QtWebKitChatView::ButtonMUCInvite = QString("mucinvite");
QtWebKitChatView::QtWebKitChatView(QtChatWindow* window, UIEventStream* eventStream, QtChatTheme* theme, QWidget* parent, bool disableAutoScroll) : QtChatView(parent), window_(window), eventStream_(eventStream), fontSizeSteps_(0), disableAutoScroll_(disableAutoScroll), previousMessageKind_(PreviosuMessageWasNone), previousMessageWasSelf_(false), showEmoticons_(false), insertingLastLine_(false), idCounter_(0) {
- theme_ = theme;
-
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
- webView_ = new QtWebView(this);
- connect(webView_, SIGNAL(linkClicked(const QUrl&)), SLOT(handleLinkClicked(const QUrl&)));
- connect(webView_, SIGNAL(loadFinished(bool)), SLOT(handleViewLoadFinished(bool)));
- connect(webView_, SIGNAL(gotFocus()), SIGNAL(gotFocus()));
- connect(webView_, SIGNAL(clearRequested()), SLOT(handleClearRequested()));
- connect(webView_, SIGNAL(fontGrowRequested()), SLOT(increaseFontSize()));
- connect(webView_, SIGNAL(fontShrinkRequested()), SLOT(decreaseFontSize()));
+ theme_ = theme;
+
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
+ webView_ = new QtWebView(this);
+ connect(webView_, SIGNAL(linkClicked(const QUrl&)), SLOT(handleLinkClicked(const QUrl&)));
+ connect(webView_, SIGNAL(loadFinished(bool)), SLOT(handleViewLoadFinished(bool)));
+ connect(webView_, SIGNAL(gotFocus()), SIGNAL(gotFocus()));
+ connect(webView_, SIGNAL(clearRequested()), SLOT(handleClearRequested()));
+ connect(webView_, SIGNAL(fontGrowRequested()), SLOT(increaseFontSize()));
+ connect(webView_, SIGNAL(fontShrinkRequested()), SLOT(decreaseFontSize()));
#if defined (Q_OS_UNIX) && !defined(Q_OS_MAC)
- /* To give a border on Linux, where it looks bad without */
- QStackedWidget* stack = new QStackedWidget(this);
- stack->addWidget(webView_);
- stack->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
- stack->setLineWidth(2);
- mainLayout->addWidget(stack);
+ /* To give a border on Linux, where it looks bad without */
+ QStackedWidget* stack = new QStackedWidget(this);
+ stack->addWidget(webView_);
+ stack->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
+ stack->setLineWidth(2);
+ mainLayout->addWidget(stack);
#else
- mainLayout->addWidget(webView_);
+ mainLayout->addWidget(webView_);
#endif
#ifdef SWIFT_EXPERIMENTAL_FT
- setAcceptDrops(true);
+ setAcceptDrops(true);
#endif
- webPage_ = new QWebPage(this);
- webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
- if (Log::getLogLevel() == Log::debug) {
- webPage_->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
- }
- webView_->setPage(webPage_);
- connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
- connect(webPage_, SIGNAL(scrollRequested(int, int, const QRect&)), SLOT(handleScrollRequested(int, int, const QRect&)));
+ webPage_ = new QWebPage(this);
+ webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
+ if (Log::getLogLevel() == Log::debug) {
+ webPage_->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
+ }
+ webView_->setPage(webPage_);
+ connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
+ connect(webPage_, SIGNAL(scrollRequested(int, int, const QRect&)), SLOT(handleScrollRequested(int, int, const QRect&)));
- viewReady_ = false;
- isAtBottom_ = true;
- resetView();
+ viewReady_ = false;
+ isAtBottom_ = true;
+ resetView();
- jsBridge = new QtChatWindowJSBridge();
- addToJSEnvironment("chatwindow", jsBridge);
- connect(jsBridge, SIGNAL(buttonClicked(QString,QString,QString,QString,QString,QString)), this, SLOT(handleHTMLButtonClicked(QString,QString,QString,QString,QString,QString)));
+ jsBridge = new QtChatWindowJSBridge();
+ addToJSEnvironment("chatwindow", jsBridge);
+ connect(jsBridge, SIGNAL(buttonClicked(QString,QString,QString,QString,QString,QString)), this, SLOT(handleHTMLButtonClicked(QString,QString,QString,QString,QString,QString)));
}
QtWebKitChatView::~QtWebKitChatView() {
- delete jsBridge;
+ delete jsBridge;
}
void QtWebKitChatView::handleClearRequested() {
- QMessageBox messageBox(this);
- messageBox.setWindowTitle(tr("Clear log"));
- messageBox.setText(tr("You are about to clear the contents of your chat log."));
- messageBox.setInformativeText(tr("Are you sure?"));
- messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- messageBox.setDefaultButton(QMessageBox::Yes);
- int button = messageBox.exec();
- if (button == QMessageBox::Yes) {
- logCleared();
- resetView();
- }
+ QMessageBox messageBox(this);
+ messageBox.setWindowTitle(tr("Clear log"));
+ messageBox.setText(tr("You are about to clear the contents of your chat log."));
+ messageBox.setInformativeText(tr("Are you sure?"));
+ messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ messageBox.setDefaultButton(QMessageBox::Yes);
+ int button = messageBox.exec();
+ if (button == QMessageBox::Yes) {
+ logCleared();
+ resetView();
+ }
}
void QtWebKitChatView::handleKeyPressEvent(QKeyEvent* event) {
- webView_->keyPressEvent(event);
+ webView_->keyPressEvent(event);
}
void QtWebKitChatView::addMessageBottom(boost::shared_ptr<ChatSnippet> snippet) {
- if (viewReady_) {
- addToDOM(snippet);
- } else {
- /* If this asserts, the previous queuing code was necessary and should be reinstated */
- assert(false);
- }
+ if (viewReady_) {
+ addToDOM(snippet);
+ } else {
+ /* If this asserts, the previous queuing code was necessary and should be reinstated */
+ assert(false);
+ }
}
void QtWebKitChatView::addMessageTop(boost::shared_ptr<ChatSnippet> /* snippet */) {
- // TODO: Implement this in a sensible manner later.
- assert(false);
+ // TODO: Implement this in a sensible manner later.
+ assert(false);
}
void QtWebKitChatView::addToDOM(boost::shared_ptr<ChatSnippet> snippet) {
- //qDebug() << snippet->getContent();
- rememberScrolledToBottom();
+ //qDebug() << snippet->getContent();
+ rememberScrolledToBottom();
- QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
- assert(!insertElement.isNull());
- insertElement.prependOutside(snippet->getContent());
+ QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
+ assert(!insertElement.isNull());
+ insertElement.prependOutside(snippet->getContent());
- //qDebug() << "-----------------";
- //qDebug() << webPage_->mainFrame()->toHtml();
+ //qDebug() << "-----------------";
+ //qDebug() << webPage_->mainFrame()->toHtml();
}
void QtWebKitChatView::addLastSeenLine() {
- // Remove a potentially existing unread bar.
- QWebElement existingUnreadBar = webPage_->mainFrame()->findFirstElement("div.unread");
- if (!existingUnreadBar.isNull()) {
- existingUnreadBar.removeFromDocument();
- }
+ // Remove a potentially existing unread bar.
+ QWebElement existingUnreadBar = webPage_->mainFrame()->findFirstElement("div.unread");
+ if (!existingUnreadBar.isNull()) {
+ existingUnreadBar.removeFromDocument();
+ }
- QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
- insertElement.prependOutside(theme_->getUnread());
+ QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
+ insertElement.prependOutside(theme_->getUnread());
}
void QtWebKitChatView::replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- rememberScrolledToBottom();
- QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
- assert(!insertElement.isNull());
+ rememberScrolledToBottom();
+ QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
+ assert(!insertElement.isNull());
- QWebElement lastMessageElement = insertElement.previousSibling();
- QWebElement messageChild = lastMessageElement.findFirst("span.swift_message");
- assert(!messageChild.isNull());
- messageChild.setInnerXml(ChatSnippet::escape(newMessage));
- if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
- QWebElement timeChild = lastMessageElement.findFirst("span.swift_time");
- assert(!timeChild.isNull());
- timeChild.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
- }
+ QWebElement lastMessageElement = insertElement.previousSibling();
+ QWebElement messageChild = lastMessageElement.findFirst("span.swift_message");
+ assert(!messageChild.isNull());
+ messageChild.setInnerXml(ChatSnippet::escape(newMessage));
+ if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
+ QWebElement timeChild = lastMessageElement.findFirst("span.swift_time");
+ assert(!timeChild.isNull());
+ timeChild.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
+ }
}
void QtWebKitChatView::replaceLastMessage(const QString& newMessage, const QString& note) {
- rememberScrolledToBottom();
- replaceLastMessage(newMessage, ChatWindow::KeepTimestamp);
- QWebElement replace = lastElement_.findFirst("span.swift_time");
- assert(!replace.isNull());
- replace.setInnerXml(ChatSnippet::escape(note));
+ rememberScrolledToBottom();
+ replaceLastMessage(newMessage, ChatWindow::KeepTimestamp);
+ QWebElement replace = lastElement_.findFirst("span.swift_time");
+ assert(!replace.isNull());
+ replace.setInnerXml(ChatSnippet::escape(note));
}
QString QtWebKitChatView::getLastSentMessage() {
- return lastElement_.toPlainText();
+ return lastElement_.toPlainText();
}
void QtWebKitChatView::addToJSEnvironment(const QString& name, QObject* obj) {
- webView_->page()->currentFrame()->addToJavaScriptWindowObject(name, obj);
+ webView_->page()->currentFrame()->addToJavaScriptWindowObject(name, obj);
}
void QtWebKitChatView::replaceMessage(const QString& newMessage, const QString& id, const QDateTime& editTime) {
- rememberScrolledToBottom();
- QWebElement message = document_.findFirst("#" + id);
- if (!message.isNull()) {
- QWebElement replaceContent = message.findFirst("span.swift_inner_message");
- assert(!replaceContent.isNull());
- QString old = replaceContent.toOuterXml();
- replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
- QWebElement replaceTime = message.findFirst("span.swift_time");
- assert(!replaceTime.isNull());
- old = replaceTime.toOuterXml();
- replaceTime.setInnerXml(ChatSnippet::escape(tr("%1 edited").arg(ChatSnippet::timeToEscapedString(editTime))));
- }
- else {
- qWarning() << "Trying to replace element with id " << id << " but it's not there.";
- }
+ rememberScrolledToBottom();
+ QWebElement message = document_.findFirst("#" + id);
+ if (!message.isNull()) {
+ QWebElement replaceContent = message.findFirst("span.swift_inner_message");
+ assert(!replaceContent.isNull());
+ QString old = replaceContent.toOuterXml();
+ replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
+ QWebElement replaceTime = message.findFirst("span.swift_time");
+ assert(!replaceTime.isNull());
+ old = replaceTime.toOuterXml();
+ replaceTime.setInnerXml(ChatSnippet::escape(tr("%1 edited").arg(ChatSnippet::timeToEscapedString(editTime))));
+ }
+ else {
+ qWarning() << "Trying to replace element with id " << id << " but it's not there.";
+ }
}
void QtWebKitChatView::showEmoticons(bool show) {
- showEmoticons_ = show;
- {
- const QWebElementCollection spans = document_.findAll("span.swift_emoticon_image");
- Q_FOREACH (QWebElement span, spans) {
- span.setStyleProperty("display", show ? "inline" : "none");
- }
- }
- {
- const QWebElementCollection spans = document_.findAll("span.swift_emoticon_text");
- Q_FOREACH (QWebElement span, spans) {
- span.setStyleProperty("display", show ? "none" : "inline");
- }
- }
+ showEmoticons_ = show;
+ {
+ const QWebElementCollection spans = document_.findAll("span.swift_emoticon_image");
+ Q_FOREACH (QWebElement span, spans) {
+ span.setStyleProperty("display", show ? "inline" : "none");
+ }
+ }
+ {
+ const QWebElementCollection spans = document_.findAll("span.swift_emoticon_text");
+ Q_FOREACH (QWebElement span, spans) {
+ span.setStyleProperty("display", show ? "none" : "inline");
+ }
+ }
}
void QtWebKitChatView::copySelectionToClipboard() {
- if (!webPage_->selectedText().isEmpty()) {
- webPage_->triggerAction(QWebPage::Copy);
- }
+ if (!webPage_->selectedText().isEmpty()) {
+ webPage_->triggerAction(QWebPage::Copy);
+ }
}
void QtWebKitChatView::setAckXML(const QString& id, const QString& xml) {
- QWebElement message = document_.findFirst("#" + id);
- /* Deliberately not asserting here, so that when we start expiring old messages it won't hit us */
- if (message.isNull()) return;
- QWebElement ackElement = message.findFirst("span.swift_ack");
- assert(!ackElement.isNull());
- ackElement.setInnerXml(xml);
+ QWebElement message = document_.findFirst("#" + id);
+ /* Deliberately not asserting here, so that when we start expiring old messages it won't hit us */
+ if (message.isNull()) return;
+ QWebElement ackElement = message.findFirst("span.swift_ack");
+ assert(!ackElement.isNull());
+ ackElement.setInnerXml(xml);
}
void QtWebKitChatView::setReceiptXML(const QString& id, const QString& xml) {
- QWebElement message = document_.findFirst("#" + id);
- if (message.isNull()) return;
- QWebElement receiptElement = message.findFirst("span.swift_receipt");
- assert(!receiptElement.isNull());
- receiptElement.setInnerXml(xml);
+ QWebElement message = document_.findFirst("#" + id);
+ if (message.isNull()) return;
+ QWebElement receiptElement = message.findFirst("span.swift_receipt");
+ assert(!receiptElement.isNull());
+ receiptElement.setInnerXml(xml);
}
void QtWebKitChatView::displayReceiptInfo(const QString& id, bool showIt) {
- QWebElement message = document_.findFirst("#" + id);
- if (message.isNull()) return;
- QWebElement receiptElement = message.findFirst("span.swift_receipt");
- assert(!receiptElement.isNull());
- receiptElement.setStyleProperty("display", showIt ? "inline" : "none");
+ QWebElement message = document_.findFirst("#" + id);
+ if (message.isNull()) return;
+ QWebElement receiptElement = message.findFirst("span.swift_receipt");
+ assert(!receiptElement.isNull());
+ receiptElement.setStyleProperty("display", showIt ? "inline" : "none");
}
void QtWebKitChatView::rememberScrolledToBottom() {
- isAtBottom_ = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) >= (webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical) - 1);
+ isAtBottom_ = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) >= (webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical) - 1);
}
void QtWebKitChatView::scrollToBottom() {
- isAtBottom_ = true;
- webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
- webView_->update(); /* Work around redraw bug in some versions of Qt. */
+ isAtBottom_ = true;
+ webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
+ webView_->update(); /* Work around redraw bug in some versions of Qt. */
}
void QtWebKitChatView::handleFrameSizeChanged() {
- if (topMessageAdded_) {
- // adjust new scrollbar position
- int newMaximum = webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical);
- webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, newMaximum - scrollBarMaximum_);
- topMessageAdded_ = false;
- }
+ if (topMessageAdded_) {
+ // adjust new scrollbar position
+ int newMaximum = webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical);
+ webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, newMaximum - scrollBarMaximum_);
+ topMessageAdded_ = false;
+ }
- if (isAtBottom_ && !disableAutoScroll_) {
- scrollToBottom();
- }
+ if (isAtBottom_ && !disableAutoScroll_) {
+ scrollToBottom();
+ }
}
void QtWebKitChatView::handleLinkClicked(const QUrl& url) {
- QDesktopServices::openUrl(url);
+ QDesktopServices::openUrl(url);
}
void QtWebKitChatView::handleViewLoadFinished(bool ok) {
- Q_ASSERT(ok);
- viewReady_ = true;
+ Q_ASSERT(ok);
+ viewReady_ = true;
}
void QtWebKitChatView::increaseFontSize(int numSteps) {
- //qDebug() << "Increasing";
- fontSizeSteps_ += numSteps;
- emit fontResized(fontSizeSteps_);
+ //qDebug() << "Increasing";
+ fontSizeSteps_ += numSteps;
+ emit fontResized(fontSizeSteps_);
}
void QtWebKitChatView::decreaseFontSize() {
- fontSizeSteps_--;
- if (fontSizeSteps_ < 0) {
- fontSizeSteps_ = 0;
- }
- emit fontResized(fontSizeSteps_);
+ fontSizeSteps_--;
+ if (fontSizeSteps_ < 0) {
+ fontSizeSteps_ = 0;
+ }
+ emit fontResized(fontSizeSteps_);
}
void QtWebKitChatView::resizeFont(int fontSizeSteps) {
- fontSizeSteps_ = fontSizeSteps;
- double size = 1.0 + 0.2 * fontSizeSteps_;
- QString sizeString(QString().setNum(size, 'g', 3) + "em");
+ fontSizeSteps_ = fontSizeSteps;
+ double size = 1.0 + 0.2 * fontSizeSteps_;
+ QString sizeString(QString().setNum(size, 'g', 3) + "em");
- // Set the font size in the <style id="text-resize-style"> element in the theme <head> element.
- QWebElement resizableTextStyle = document_.findFirst("style#text-resize-style");
- assert(!resizableTextStyle.isNull());
- resizableTextStyle.setInnerXml(QString("span.swift_resizable { font-size: %1;}").arg(sizeString));
- webView_->setFontSizeIsMinimal(size == 1.0);
+ // Set the font size in the <style id="text-resize-style"> element in the theme <head> element.
+ QWebElement resizableTextStyle = document_.findFirst("style#text-resize-style");
+ assert(!resizableTextStyle.isNull());
+ resizableTextStyle.setInnerXml(QString("span.swift_resizable { font-size: %1;}").arg(sizeString));
+ webView_->setFontSizeIsMinimal(size == 1.0);
}
void QtWebKitChatView::resetView() {
- lastElement_ = QWebElement();
- firstElement_ = lastElement_;
- topMessageAdded_ = false;
- scrollBarMaximum_ = 0;
- QString pageHTML = theme_->getTemplate();
- pageHTML.replace("==bodyBackground==", "background-color:#e3e3e3");
- pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getBase());
- if (pageHTML.count("%@") > 3) {
- pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getMainCSS());
- }
- pageHTML.replace(pageHTML.indexOf("%@"), 2, "Variants/Blue on Green.css");
- pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*headerSnippet.getContent()*/);
- pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*footerSnippet.getContent()*/);
- QEventLoop syncLoop;
- connect(webView_, SIGNAL(loadFinished(bool)), &syncLoop, SLOT(quit()));
- webPage_->mainFrame()->setHtml(pageHTML);
- while (!viewReady_) {
- QTimer t;
- t.setSingleShot(true);
- connect(&t, SIGNAL(timeout()), &syncLoop, SLOT(quit()));
- t.start(50);
- syncLoop.exec();
- }
- document_ = webPage_->mainFrame()->documentElement();
-
- scrollToBottom();
-
- connect(webPage_->mainFrame(), SIGNAL(contentsSizeChanged(const QSize&)), this, SLOT(handleFrameSizeChanged()), Qt::UniqueConnection);
+ lastElement_ = QWebElement();
+ firstElement_ = lastElement_;
+ topMessageAdded_ = false;
+ scrollBarMaximum_ = 0;
+ QString pageHTML = theme_->getTemplate();
+ pageHTML.replace("==bodyBackground==", "background-color:#e3e3e3");
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getBase());
+ if (pageHTML.count("%@") > 3) {
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getMainCSS());
+ }
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, "Variants/Blue on Green.css");
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*headerSnippet.getContent()*/);
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*footerSnippet.getContent()*/);
+ QEventLoop syncLoop;
+ connect(webView_, SIGNAL(loadFinished(bool)), &syncLoop, SLOT(quit()));
+ webPage_->mainFrame()->setHtml(pageHTML);
+ while (!viewReady_) {
+ QTimer t;
+ t.setSingleShot(true);
+ connect(&t, SIGNAL(timeout()), &syncLoop, SLOT(quit()));
+ t.start(50);
+ syncLoop.exec();
+ }
+ document_ = webPage_->mainFrame()->documentElement();
+
+ scrollToBottom();
+
+ connect(webPage_->mainFrame(), SIGNAL(contentsSizeChanged(const QSize&)), this, SLOT(handleFrameSizeChanged()), Qt::UniqueConnection);
}
static QWebElement findElementWithID(QWebElement document, QString elementName, QString id) {
- QWebElementCollection elements = document.findAll(elementName);
- Q_FOREACH(QWebElement element, elements) {
- if (element.attribute("id") == id) {
- return element;
- }
- }
- return QWebElement();
+ QWebElementCollection elements = document.findAll(elementName);
+ Q_FOREACH(QWebElement element, elements) {
+ if (element.attribute("id") == id) {
+ return element;
+ }
+ }
+ return QWebElement();
}
void QtWebKitChatView::setFileTransferProgress(QString id, const int percentageDone) {
- rememberScrolledToBottom();
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id!" << std::endl;
- return;
- }
- QWebElement progressBar = ftElement.findFirst("div.progressbar");
- progressBar.setStyleProperty("width", QString::number(percentageDone) + "%");
+ rememberScrolledToBottom();
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id!" << std::endl;
+ return;
+ }
+ QWebElement progressBar = ftElement.findFirst("div.progressbar");
+ progressBar.setStyleProperty("width", QString::number(percentageDone) + "%");
- QWebElement progressBarValue = ftElement.findFirst("div.progressbar-value");
- progressBarValue.setInnerXml(QString::number(percentageDone) + " %");
+ QWebElement progressBarValue = ftElement.findFirst("div.progressbar-value");
+ progressBarValue.setInnerXml(QString::number(percentageDone) + " %");
}
void QtWebKitChatView::setFileTransferStatus(QString id, const ChatWindow::FileTransferState state, const QString& /* msg */) {
- rememberScrolledToBottom();
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
- return;
- }
-
- QString newInnerHTML = "";
- if (state == ChatWindow::Initialisation) {
- QWebElement filenameSizeDescriptionElement = ftElement.parent().firstChild();
- QString description = QtUtilities::htmlEscape(descriptions_[id]);
- if (!description.isEmpty()) {
- filenameSizeDescriptionElement.prependOutside(QString(" \"%1\"").arg(description));
- }
- newInnerHTML = tr("Preparing to transfer.") + "<br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::WaitingForAccept) {
- newInnerHTML = tr("Waiting for other side to accept the transfer.") + "<br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::Negotiating) {
- // replace with text "Negotiaging" + Cancel button
- newInnerHTML = tr("Negotiating...") + "<br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::Transferring) {
- // progress bar + Cancel Button
- newInnerHTML = "<div style=\"position: relative; width: 90%; height: 20px; border: 2px solid grey; -webkit-border-radius: 10px;\">"
- "<div class=\"progressbar\" style=\"width: 0%; height: 100%; background: #AAA; -webkit-border-radius: 6px;\">"
- "<div class=\"progressbar-value\" style=\"position: absolute; top: 0px; left: 0px; width: 100%; text-align: center; padding-top: 2px;\">"
- "0%"
- "</div>"
- "</div>"
- "</div>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::Canceled) {
- newInnerHTML = tr("Transfer has been canceled!");
- }
- else if (state == ChatWindow::Finished) {
- // text "Successful transfer"
- newInnerHTML = tr("Transfer completed successfully." ) + " " + buildChatWindowButton(tr("Open file"), ButtonFileTransferOpenFile, id, filePaths_[id]);
- filePaths_.erase(id);
- }
- else if (state == ChatWindow::FTFailed) {
- newInnerHTML = tr("Transfer failed.");
- }
-
- ftElement.setInnerXml(newInnerHTML);
+ rememberScrolledToBottom();
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ return;
+ }
+
+ QString newInnerHTML = "";
+ if (state == ChatWindow::Initialisation) {
+ QWebElement filenameSizeDescriptionElement = ftElement.parent().firstChild();
+ QString description = QtUtilities::htmlEscape(descriptions_[id]);
+ if (!description.isEmpty()) {
+ filenameSizeDescriptionElement.prependOutside(QString(" \"%1\"").arg(description));
+ }
+ newInnerHTML = tr("Preparing to transfer.") + "<br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::WaitingForAccept) {
+ newInnerHTML = tr("Waiting for other side to accept the transfer.") + "<br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::Negotiating) {
+ // replace with text "Negotiaging" + Cancel button
+ newInnerHTML = tr("Negotiating...") + "<br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::Transferring) {
+ // progress bar + Cancel Button
+ newInnerHTML = "<div style=\"position: relative; width: 90%; height: 20px; border: 2px solid grey; -webkit-border-radius: 10px;\">"
+ "<div class=\"progressbar\" style=\"width: 0%; height: 100%; background: #AAA; -webkit-border-radius: 6px;\">"
+ "<div class=\"progressbar-value\" style=\"position: absolute; top: 0px; left: 0px; width: 100%; text-align: center; padding-top: 2px;\">"
+ "0%"
+ "</div>"
+ "</div>"
+ "</div>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::Canceled) {
+ newInnerHTML = tr("Transfer has been canceled!");
+ }
+ else if (state == ChatWindow::Finished) {
+ // text "Successful transfer"
+ newInnerHTML = tr("Transfer completed successfully." ) + " " + buildChatWindowButton(tr("Open file"), ButtonFileTransferOpenFile, id, filePaths_[id]);
+ filePaths_.erase(id);
+ }
+ else if (state == ChatWindow::FTFailed) {
+ newInnerHTML = tr("Transfer failed.");
+ }
+
+ ftElement.setInnerXml(newInnerHTML);
}
void QtWebKitChatView::setWhiteboardSessionStatus(QString id, const ChatWindow::WhiteboardSessionState state) {
- QWebElement divElement = findElementWithID(document_, "div", id);
- QString newInnerHTML;
- if (state == ChatWindow::WhiteboardAccepted) {
- newInnerHTML = tr("Started whiteboard chat") + "<br/>" + buildChatWindowButton(tr("Show whiteboard"), ButtonWhiteboardShowWindow, id);
- } else if (state == ChatWindow::WhiteboardTerminated) {
- newInnerHTML = tr("Whiteboard chat has been canceled");
- } else if (state == ChatWindow::WhiteboardRejected) {
- newInnerHTML = tr("Whiteboard chat request has been rejected");
- }
- divElement.setInnerXml(newInnerHTML);
+ QWebElement divElement = findElementWithID(document_, "div", id);
+ QString newInnerHTML;
+ if (state == ChatWindow::WhiteboardAccepted) {
+ newInnerHTML = tr("Started whiteboard chat") + "<br/>" + buildChatWindowButton(tr("Show whiteboard"), ButtonWhiteboardShowWindow, id);
+ } else if (state == ChatWindow::WhiteboardTerminated) {
+ newInnerHTML = tr("Whiteboard chat has been canceled");
+ } else if (state == ChatWindow::WhiteboardRejected) {
+ newInnerHTML = tr("Whiteboard chat request has been rejected");
+ }
+ divElement.setInnerXml(newInnerHTML);
}
void QtWebKitChatView::setMUCInvitationJoined(QString id) {
- QWebElement divElement = findElementWithID(document_, "div", id);
- QWebElement buttonElement = findElementWithID(divElement, "input", "mucinvite");
- if (!buttonElement.isNull()) {
- buttonElement.setAttribute("value", tr("Return to room"));
- }
+ QWebElement divElement = findElementWithID(document_, "div", id);
+ QWebElement buttonElement = findElementWithID(divElement, "input", "mucinvite");
+ if (!buttonElement.isNull()) {
+ buttonElement.setAttribute("value", tr("Return to room"));
+ }
}
void QtWebKitChatView::askDesktopToOpenFile(const QString& filename) {
- QFileInfo fileInfo(filename);
- if (fileInfo.exists() && fileInfo.isFile()) {
- QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
- }
+ QFileInfo fileInfo(filename);
+ if (fileInfo.exists() && fileInfo.isFile()) {
+ QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
+ }
}
void QtWebKitChatView::handleScrollRequested(int, int dy, const QRect&) {
- rememberScrolledToBottom();
+ rememberScrolledToBottom();
- int pos = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) - dy;
- emit scrollRequested(pos);
+ int pos = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) - dy;
+ emit scrollRequested(pos);
- if (pos == 0) {
- emit scrollReachedTop();
- }
- else if (pos == webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)) {
- emit scrollReachedBottom();
- }
+ if (pos == 0) {
+ emit scrollReachedTop();
+ }
+ else if (pos == webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)) {
+ emit scrollReachedBottom();
+ }
}
int QtWebKitChatView::getSnippetPositionByDate(const QDate& date) {
- QWebElement message = webPage_->mainFrame()->documentElement().findFirst(".date" + date.toString(Qt::ISODate));
+ QWebElement message = webPage_->mainFrame()->documentElement().findFirst(".date" + date.toString(Qt::ISODate));
- return message.geometry().top();
+ return message.geometry().top();
}
void QtWebKitChatView::resetTopInsertPoint() {
- // TODO: Implement or refactor later.
- assert(false);
+ // TODO: Implement or refactor later.
+ assert(false);
}
std::string QtWebKitChatView::addMessage(
- const ChatWindow::ChatMessage& message,
- const std::string& senderName,
- bool senderIsSelf,
- boost::shared_ptr<SecurityLabel> label,
- const std::string& avatarPath,
- const boost::posix_time::ptime& time) {
- return addMessage(chatMessageToHTML(message), senderName, senderIsSelf, label, avatarPath, "", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
+ const ChatWindow::ChatMessage& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ boost::shared_ptr<SecurityLabel> label,
+ const std::string& avatarPath,
+ const boost::posix_time::ptime& time) {
+ return addMessage(chatMessageToHTML(message), senderName, senderIsSelf, label, avatarPath, "", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
}
QString QtWebKitChatView::getHighlightSpanStart(const std::string& text, const std::string& background) {
- QString ecsapeColor = QtUtilities::htmlEscape(P2QSTRING(text));
- QString escapeBackground = QtUtilities::htmlEscape(P2QSTRING(background));
- if (ecsapeColor.isEmpty()) {
- ecsapeColor = "black";
- }
- if (escapeBackground.isEmpty()) {
- escapeBackground = "yellow";
- }
- return QString("<span style=\"color: %1; background: %2\">").arg(ecsapeColor).arg(escapeBackground);
+ QString ecsapeColor = QtUtilities::htmlEscape(P2QSTRING(text));
+ QString escapeBackground = QtUtilities::htmlEscape(P2QSTRING(background));
+ if (ecsapeColor.isEmpty()) {
+ ecsapeColor = "black";
+ }
+ if (escapeBackground.isEmpty()) {
+ escapeBackground = "yellow";
+ }
+ return QString("<span style=\"color: %1; background: %2\">").arg(ecsapeColor).arg(escapeBackground);
}
QString QtWebKitChatView::getHighlightSpanStart(const HighlightAction& highlight) {
- return getHighlightSpanStart(highlight.getTextColor(), highlight.getTextBackground());
+ return getHighlightSpanStart(highlight.getTextColor(), highlight.getTextBackground());
}
QString QtWebKitChatView::chatMessageToHTML(const ChatWindow::ChatMessage& message) {
- QString result;
- foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
- boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
-
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
- text.replace("\n","<br/>");
- result += text;
- continue;
- }
- if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
- QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
- result += "<a href='" + uri + "' >" + uri + "</a>";
- continue;
- }
- if ((emoticonPart = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
- QString textStyle = showEmoticons_ ? "style='display:none'" : "";
- QString imageStyle = showEmoticons_ ? "" : "style='display:none'";
- result += "<span class='swift_emoticon_image' " + imageStyle + "><img src='" + P2QSTRING(emoticonPart->imagePath) + "'/></span><span class='swift_emoticon_text' " + textStyle + ">" + QtUtilities::htmlEscape(P2QSTRING(emoticonPart->alternativeText)) + "</span>";
- continue;
- }
- if ((highlightPart = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
- QString spanStart = getHighlightSpanStart(highlightPart->action.getTextColor(), highlightPart->action.getTextBackground());
- result += spanStart + QtUtilities::htmlEscape(P2QSTRING(highlightPart->text)) + "</span>";
- continue;
- }
-
- }
- return result;
+ QString result;
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
+ boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
+ boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
+
+ if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
+ text.replace("\n","<br/>");
+ result += text;
+ continue;
+ }
+ if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
+ QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
+ result += "<a href='" + uri + "' >" + uri + "</a>";
+ continue;
+ }
+ if ((emoticonPart = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
+ QString textStyle = showEmoticons_ ? "style='display:none'" : "";
+ QString imageStyle = showEmoticons_ ? "" : "style='display:none'";
+ result += "<span class='swift_emoticon_image' " + imageStyle + "><img src='" + P2QSTRING(emoticonPart->imagePath) + "'/></span><span class='swift_emoticon_text' " + textStyle + ">" + QtUtilities::htmlEscape(P2QSTRING(emoticonPart->alternativeText)) + "</span>";
+ continue;
+ }
+ if ((highlightPart = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
+ QString spanStart = getHighlightSpanStart(highlightPart->action.getTextColor(), highlightPart->action.getTextBackground());
+ result += spanStart + QtUtilities::htmlEscape(P2QSTRING(highlightPart->text)) + "</span>";
+ continue;
+ }
+
+ }
+ return result;
}
std::string QtWebKitChatView::addMessage(
- const QString& message,
- const std::string& senderName,
- bool senderIsSelf,
- boost::shared_ptr<SecurityLabel> label,
- const std::string& avatarPath,
- const QString& style,
- const boost::posix_time::ptime& time,
- const HighlightAction& highlight,
- ChatSnippet::Direction direction) {
+ const QString& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ boost::shared_ptr<SecurityLabel> label,
+ const std::string& avatarPath,
+ const QString& style,
+ const boost::posix_time::ptime& time,
+ const HighlightAction& highlight,
+ ChatSnippet::Direction direction) {
- QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
+ QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
- QString htmlString;
- if (label) {
- htmlString = QString("<span style=\"border: thin dashed grey; padding-left: .5em; padding-right: .5em; color: %1; background-color: %2; font-size: 90%; margin-right: .5em; \" class='swift_label'>").arg(QtUtilities::htmlEscape(P2QSTRING(label->getForegroundColor()))).arg(QtUtilities::htmlEscape(P2QSTRING(label->getBackgroundColor())));
- htmlString += QString("%1</span> ").arg(QtUtilities::htmlEscape(P2QSTRING(label->getDisplayMarking())));
- }
+ QString htmlString;
+ if (label) {
+ htmlString = QString("<span style=\"border: thin dashed grey; padding-left: .5em; padding-right: .5em; color: %1; background-color: %2; font-size: 90%; margin-right: .5em; \" class='swift_label'>").arg(QtUtilities::htmlEscape(P2QSTRING(label->getForegroundColor()))).arg(QtUtilities::htmlEscape(P2QSTRING(label->getBackgroundColor())));
+ htmlString += QString("%1</span> ").arg(QtUtilities::htmlEscape(P2QSTRING(label->getDisplayMarking())));
+ }
- QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
- QString styleSpanEnd = style == "" ? "" : "</span>";
+ QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
+ QString styleSpanEnd = style == "" ? "" : "</span>";
- bool highlightWholeMessage = highlight.highlightWholeMessage() && highlight.getTextBackground() != "" && highlight.getTextColor() != "";
- QString highlightSpanStart = highlightWholeMessage ? getHighlightSpanStart(highlight) : "";
- QString highlightSpanEnd = highlightWholeMessage ? "</span>" : "";
- htmlString += "<span class='swift_inner_message'>" + styleSpanStart + highlightSpanStart + message + highlightSpanEnd + styleSpanEnd + "</span>" ;
+ bool highlightWholeMessage = highlight.highlightWholeMessage() && highlight.getTextBackground() != "" && highlight.getTextColor() != "";
+ QString highlightSpanStart = highlightWholeMessage ? getHighlightSpanStart(highlight) : "";
+ QString highlightSpanEnd = highlightWholeMessage ? "</span>" : "";
+ htmlString += "<span class='swift_inner_message'>" + styleSpanStart + highlightSpanStart + message + highlightSpanEnd + styleSpanEnd + "</span>" ;
- bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMessage, senderName, senderIsSelf);
+ bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMessage, senderName, senderIsSelf);
- QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(time), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), direction));
+ QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(time), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), direction));
- previousMessageWasSelf_ = senderIsSelf;
- previousSenderName_ = P2QSTRING(senderName);
- previousMessageKind_ = PreviousMessageWasMessage;
- return id;
+ previousMessageWasSelf_ = senderIsSelf;
+ previousSenderName_ = P2QSTRING(senderName);
+ previousMessageKind_ = PreviousMessageWasMessage;
+ return id;
}
std::string QtWebKitChatView::addAction(const ChatWindow::ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
- return addMessage(" *" + chatMessageToHTML(message) + "*", senderName, senderIsSelf, label, avatarPath, "font-style:italic ", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
+ return addMessage(" *" + chatMessageToHTML(message) + "*", senderName, senderIsSelf, label, avatarPath, "font-style:italic ", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
}
static QString encodeButtonArgument(const QString& str) {
- return QtUtilities::htmlEscape(P2QSTRING(Base64::encode(createByteArray(Q2PSTRING(str)))));
+ return QtUtilities::htmlEscape(P2QSTRING(Base64::encode(createByteArray(Q2PSTRING(str)))));
}
static QString decodeButtonArgument(const QString& str) {
- return P2QSTRING(byteArrayToString(Base64::decode(Q2PSTRING(str))));
+ return P2QSTRING(byteArrayToString(Base64::decode(Q2PSTRING(str))));
}
QString QtWebKitChatView::buildChatWindowButton(const QString& name, const QString& id, const QString& arg1, const QString& arg2, const QString& arg3, const QString& arg4, const QString& arg5) {
- QRegExp regex("[A-Za-z][A-Za-z0-9\\-\\_]+");
- Q_ASSERT(regex.exactMatch(id));
- QString html = QString("<input id='%2' type='submit' value='%1' onclick='chatwindow.buttonClicked(\"%2\", \"%3\", \"%4\", \"%5\", \"%6\", \"%7\");' />").arg(name).arg(id).arg(encodeButtonArgument(arg1)).arg(encodeButtonArgument(arg2)).arg(encodeButtonArgument(arg3)).arg(encodeButtonArgument(arg4)).arg(encodeButtonArgument(arg5));
- return html;
+ QRegExp regex("[A-Za-z][A-Za-z0-9\\-\\_]+");
+ Q_ASSERT(regex.exactMatch(id));
+ QString html = QString("<input id='%2' type='submit' value='%1' onclick='chatwindow.buttonClicked(\"%2\", \"%3\", \"%4\", \"%5\", \"%6\", \"%7\");' />").arg(name).arg(id).arg(encodeButtonArgument(arg1)).arg(encodeButtonArgument(arg2)).arg(encodeButtonArgument(arg3)).arg(encodeButtonArgument(arg4)).arg(encodeButtonArgument(arg5));
+ return html;
}
std::string QtWebKitChatView::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) {
- SWIFT_LOG(debug) << "addFileTransfer" << std::endl;
- QString ft_id = QString("ft%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
-
- QString actionText;
- QString htmlString;
- QString formattedFileSize = P2QSTRING(formatSize(sizeInBytes));
- QString sanitizedFileName = QtUtilities::htmlEscape(P2QSTRING(filename));
- QString sanitizedDescription = QtUtilities::htmlEscape(P2QSTRING(description));
- if (senderIsSelf) {
- // outgoing
- filePaths_[ft_id] = sanitizedFileName;
- actionText = tr("Send file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
- htmlString = actionText + " <br/>" +
- "<div id='" + ft_id + "'>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
- buildChatWindowButton(tr("Set Description"), ButtonFileTransferSetDescription, ft_id) +
- buildChatWindowButton(tr("Send"), ButtonFileTransferSendRequest, ft_id) +
- "</div>";
- } else {
- // incoming
- actionText = tr("Receiving file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
- if (!sanitizedDescription.isEmpty()) {
- actionText += QString(" \"%1\"").arg(sanitizedDescription);
- }
- htmlString = actionText + " <br/>" +
- "<div id='" + ft_id + "'>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
- buildChatWindowButton(tr("Accept"), ButtonFileTransferAcceptRequest, ft_id, P2QSTRING(filename)) +
- "</div>";
- }
-
- //addMessage(message, senderName, senderIsSelf, boost::shared_ptr<SecurityLabel>(), "", boost::posix_time::second_clock::local_time());
-
- bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasFileTransfer, senderName, senderIsSelf);
-
- QString qAvatarPath = "qrc:/icons/avatar.png";
- std::string id = "ftmessage" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
-
- previousMessageWasSelf_ = senderIsSelf;
- previousSenderName_ = P2QSTRING(senderName);
- previousMessageKind_ = PreviousMessageWasFileTransfer;
- return Q2PSTRING(ft_id);
+ SWIFT_LOG(debug) << "addFileTransfer" << std::endl;
+ QString ft_id = QString("ft%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
+
+ QString actionText;
+ QString htmlString;
+ QString formattedFileSize = P2QSTRING(formatSize(sizeInBytes));
+ QString sanitizedFileName = QtUtilities::htmlEscape(P2QSTRING(filename));
+ QString sanitizedDescription = QtUtilities::htmlEscape(P2QSTRING(description));
+ if (senderIsSelf) {
+ // outgoing
+ filePaths_[ft_id] = sanitizedFileName;
+ actionText = tr("Send file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
+ htmlString = actionText + " <br/>" +
+ "<div id='" + ft_id + "'>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
+ buildChatWindowButton(tr("Set Description"), ButtonFileTransferSetDescription, ft_id) +
+ buildChatWindowButton(tr("Send"), ButtonFileTransferSendRequest, ft_id) +
+ "</div>";
+ } else {
+ // incoming
+ actionText = tr("Receiving file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
+ if (!sanitizedDescription.isEmpty()) {
+ actionText += QString(" \"%1\"").arg(sanitizedDescription);
+ }
+ htmlString = actionText + " <br/>" +
+ "<div id='" + ft_id + "'>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
+ buildChatWindowButton(tr("Accept"), ButtonFileTransferAcceptRequest, ft_id, P2QSTRING(filename)) +
+ "</div>";
+ }
+
+ //addMessage(message, senderName, senderIsSelf, boost::shared_ptr<SecurityLabel>(), "", boost::posix_time::second_clock::local_time());
+
+ bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasFileTransfer, senderName, senderIsSelf);
+
+ QString qAvatarPath = "qrc:/icons/avatar.png";
+ std::string id = "ftmessage" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
+
+ previousMessageWasSelf_ = senderIsSelf;
+ previousSenderName_ = P2QSTRING(senderName);
+ previousMessageKind_ = PreviousMessageWasFileTransfer;
+ return Q2PSTRING(ft_id);
}
void QtWebKitChatView::setFileTransferProgress(std::string id, const int percentageDone) {
- setFileTransferProgress(P2QSTRING(id), percentageDone);
+ setFileTransferProgress(P2QSTRING(id), percentageDone);
}
void QtWebKitChatView::setFileTransferStatus(std::string id, const ChatWindow::FileTransferState state, const std::string& msg) {
- setFileTransferStatus(P2QSTRING(id), state, P2QSTRING(msg));
+ setFileTransferStatus(P2QSTRING(id), state, P2QSTRING(msg));
}
std::string QtWebKitChatView::addWhiteboardRequest(const QString& contact, bool senderIsSelf) {
- QString wb_id = QString("wb%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
- QString htmlString;
- QString actionText;
- if (senderIsSelf) {
- actionText = tr("Starting whiteboard chat");
- htmlString = "<div id='" + wb_id + "'>" + actionText + "<br />"+
- buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
- "</div>";
- } else {
- actionText = tr("%1 would like to start a whiteboard chat");
- htmlString = "<div id='" + wb_id + "'>" + actionText.arg(QtUtilities::htmlEscape(contact)) + ": <br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
- buildChatWindowButton(tr("Accept"), ButtonWhiteboardSessionAcceptRequest, wb_id) +
- "</div>";
- }
- QString qAvatarPath = "qrc:/icons/avatar.png";
- std::string id = "wbmessage" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(contact), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, false, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
- previousMessageWasSelf_ = false;
- previousSenderName_ = contact;
- return Q2PSTRING(wb_id);
+ QString wb_id = QString("wb%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
+ QString htmlString;
+ QString actionText;
+ if (senderIsSelf) {
+ actionText = tr("Starting whiteboard chat");
+ htmlString = "<div id='" + wb_id + "'>" + actionText + "<br />"+
+ buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
+ "</div>";
+ } else {
+ actionText = tr("%1 would like to start a whiteboard chat");
+ htmlString = "<div id='" + wb_id + "'>" + actionText.arg(QtUtilities::htmlEscape(contact)) + ": <br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
+ buildChatWindowButton(tr("Accept"), ButtonWhiteboardSessionAcceptRequest, wb_id) +
+ "</div>";
+ }
+ QString qAvatarPath = "qrc:/icons/avatar.png";
+ std::string id = "wbmessage" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(contact), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, false, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
+ previousMessageWasSelf_ = false;
+ previousSenderName_ = contact;
+ return Q2PSTRING(wb_id);
}
void QtWebKitChatView::setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) {
- setWhiteboardSessionStatus(P2QSTRING(id), state);
+ setWhiteboardSessionStatus(P2QSTRING(id), state);
}
static bool isFilePathWritable(const QString& path) {
- QFileInfo fileInfo = QFileInfo(path);
- if (fileInfo.exists()) {
- return fileInfo.isWritable();
- }
- else {
- bool writable = false;
- QFile writeTestFile(path);
- if (writeTestFile.open(QIODevice::ReadWrite)) {
- writeTestFile.write("test");
- if (writeTestFile.error() == QFileDevice::NoError) {
- writable = true;
- }
- }
- writeTestFile.close();
- writeTestFile.remove();
- return writable;
- }
+ QFileInfo fileInfo = QFileInfo(path);
+ if (fileInfo.exists()) {
+ return fileInfo.isWritable();
+ }
+ else {
+ bool writable = false;
+ QFile writeTestFile(path);
+ if (writeTestFile.open(QIODevice::ReadWrite)) {
+ writeTestFile.write("test");
+ if (writeTestFile.error() == QFileDevice::NoError) {
+ writable = true;
+ }
+ }
+ writeTestFile.close();
+ writeTestFile.remove();
+ return writable;
+ }
}
void QtWebKitChatView::setFileTransferWarning(QString id, QString warningText) {
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
- return;
- }
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ return;
+ }
- removeFileTransferWarning(id);
- ftElement.appendInside(QString("<div class='ft_warning' style='color: red;'><br/>%1</div>").arg(QtUtilities::htmlEscape(warningText)));
+ removeFileTransferWarning(id);
+ ftElement.appendInside(QString("<div class='ft_warning' style='color: red;'><br/>%1</div>").arg(QtUtilities::htmlEscape(warningText)));
}
void QtWebKitChatView::removeFileTransferWarning(QString id) {
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
- return;
- }
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ return;
+ }
- QWebElement warningElement = ftElement.findFirst(".ft_warning");
- if (!warningElement.isNull()) {
- warningElement.removeFromDocument();
- }
+ QWebElement warningElement = ftElement.findFirst(".ft_warning");
+ if (!warningElement.isNull()) {
+ warningElement.removeFromDocument();
+ }
}
void QtWebKitChatView::handleHTMLButtonClicked(QString id, QString encodedArgument1, QString encodedArgument2, QString encodedArgument3, QString encodedArgument4, QString encodedArgument5) {
- QString arg1 = decodeButtonArgument(encodedArgument1);
- QString arg2 = decodeButtonArgument(encodedArgument2);
- QString arg3 = decodeButtonArgument(encodedArgument3);
- QString arg4 = decodeButtonArgument(encodedArgument4);
- QString arg5 = decodeButtonArgument(encodedArgument5);
-
- if (id.startsWith(ButtonFileTransferCancel)) {
- QString ft_id = arg1;
- window_->onFileTransferCancel(Q2PSTRING(ft_id));
- }
- else if (id.startsWith(ButtonFileTransferSetDescription)) {
- QString ft_id = arg1;
- bool ok = false;
- QString text = QInputDialog::getText(this, tr("File transfer description"),
- tr("Description:"), QLineEdit::Normal, "", &ok);
- if (ok) {
- descriptions_[ft_id] = text;
- }
- }
- else if (id.startsWith(ButtonFileTransferSendRequest)) {
- QString ft_id = arg1;
- QString text = descriptions_.find(ft_id) == descriptions_.end() ? QString() : descriptions_[ft_id];
- window_->onFileTransferStart(Q2PSTRING(ft_id), Q2PSTRING(text));
- }
- else if (id.startsWith(ButtonFileTransferAcceptRequest)) {
- QString ft_id = arg1;
- QString filename = arg2;
-
- QString path = QFileDialog::getSaveFileName(this, tr("Save File"), filename);
- if (!path.isEmpty() && isFilePathWritable(path)) {
- filePaths_[ft_id] = path;
- window_->onFileTransferAccept(Q2PSTRING(ft_id), Q2PSTRING(path));
- removeFileTransferWarning(ft_id);
- }
- else {
- setFileTransferWarning(ft_id, tr("The chosen save location is not writable! Click the 'Accept' button to select a different save location."));
- }
- }
- else if (id.startsWith(ButtonFileTransferOpenFile)) {
- QString ft_id = arg1;
- QString filename = arg2;
- askDesktopToOpenFile(filename);
- }
- else if (id.startsWith(ButtonWhiteboardSessionAcceptRequest)) {
- QString id = arg1;
- setWhiteboardSessionStatus(id, ChatWindow::WhiteboardAccepted);
- window_->onWhiteboardSessionAccept();
- }
- else if (id.startsWith(ButtonWhiteboardSessionCancel)) {
- QString id = arg1;
- setWhiteboardSessionStatus(id, ChatWindow::WhiteboardTerminated);
- window_->onWhiteboardSessionCancel();
- }
- else if (id.startsWith(ButtonWhiteboardShowWindow)) {
- QString id = arg1;
- window_->onWhiteboardWindowShow();
- }
- else if (id.startsWith(ButtonMUCInvite)) {
- QString roomJID = arg1;
- QString password = arg2;
- QString elementID = arg3;
- QString isImpromptu = arg4;
- QString isContinuation = arg5;
- eventStream_->send(boost::make_shared<JoinMUCUIEvent>(Q2PSTRING(roomJID), Q2PSTRING(password), boost::optional<std::string>(), false, false, isImpromptu.contains("true"), isContinuation.contains("true")));
- setMUCInvitationJoined(elementID);
- }
- else {
- SWIFT_LOG(debug) << "Unknown HTML button! ( " << Q2PSTRING(id) << " )" << std::endl;
- }
+ QString arg1 = decodeButtonArgument(encodedArgument1);
+ QString arg2 = decodeButtonArgument(encodedArgument2);
+ QString arg3 = decodeButtonArgument(encodedArgument3);
+ QString arg4 = decodeButtonArgument(encodedArgument4);
+ QString arg5 = decodeButtonArgument(encodedArgument5);
+
+ if (id.startsWith(ButtonFileTransferCancel)) {
+ QString ft_id = arg1;
+ window_->onFileTransferCancel(Q2PSTRING(ft_id));
+ }
+ else if (id.startsWith(ButtonFileTransferSetDescription)) {
+ QString ft_id = arg1;
+ bool ok = false;
+ QString text = QInputDialog::getText(this, tr("File transfer description"),
+ tr("Description:"), QLineEdit::Normal, "", &ok);
+ if (ok) {
+ descriptions_[ft_id] = text;
+ }
+ }
+ else if (id.startsWith(ButtonFileTransferSendRequest)) {
+ QString ft_id = arg1;
+ QString text = descriptions_.find(ft_id) == descriptions_.end() ? QString() : descriptions_[ft_id];
+ window_->onFileTransferStart(Q2PSTRING(ft_id), Q2PSTRING(text));
+ }
+ else if (id.startsWith(ButtonFileTransferAcceptRequest)) {
+ QString ft_id = arg1;
+ QString filename = arg2;
+
+ QString path = QFileDialog::getSaveFileName(this, tr("Save File"), filename);
+ if (!path.isEmpty() && isFilePathWritable(path)) {
+ filePaths_[ft_id] = path;
+ window_->onFileTransferAccept(Q2PSTRING(ft_id), Q2PSTRING(path));
+ removeFileTransferWarning(ft_id);
+ }
+ else {
+ setFileTransferWarning(ft_id, tr("The chosen save location is not writable! Click the 'Accept' button to select a different save location."));
+ }
+ }
+ else if (id.startsWith(ButtonFileTransferOpenFile)) {
+ QString ft_id = arg1;
+ QString filename = arg2;
+ askDesktopToOpenFile(filename);
+ }
+ else if (id.startsWith(ButtonWhiteboardSessionAcceptRequest)) {
+ QString id = arg1;
+ setWhiteboardSessionStatus(id, ChatWindow::WhiteboardAccepted);
+ window_->onWhiteboardSessionAccept();
+ }
+ else if (id.startsWith(ButtonWhiteboardSessionCancel)) {
+ QString id = arg1;
+ setWhiteboardSessionStatus(id, ChatWindow::WhiteboardTerminated);
+ window_->onWhiteboardSessionCancel();
+ }
+ else if (id.startsWith(ButtonWhiteboardShowWindow)) {
+ QString id = arg1;
+ window_->onWhiteboardWindowShow();
+ }
+ else if (id.startsWith(ButtonMUCInvite)) {
+ QString roomJID = arg1;
+ QString password = arg2;
+ QString elementID = arg3;
+ QString isImpromptu = arg4;
+ QString isContinuation = arg5;
+ eventStream_->send(boost::make_shared<JoinMUCUIEvent>(Q2PSTRING(roomJID), Q2PSTRING(password), boost::optional<std::string>(), false, false, isImpromptu.contains("true"), isContinuation.contains("true")));
+ setMUCInvitationJoined(elementID);
+ }
+ else {
+ SWIFT_LOG(debug) << "Unknown HTML button! ( " << Q2PSTRING(id) << " )" << std::endl;
+ }
}
void QtWebKitChatView::addErrorMessage(const ChatWindow::ChatMessage& errorMessage) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString errorMessageHTML(chatMessageToHTML(errorMessage));
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<SystemMessageSnippet>("<span class=\"error\">" + errorMessageHTML + "</span>", QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), ChatSnippet::getDirection(errorMessage)));
+ QString errorMessageHTML(chatMessageToHTML(errorMessage));
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<SystemMessageSnippet>("<span class=\"error\">" + errorMessageHTML + "</span>", QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), ChatSnippet::getDirection(errorMessage)));
- previousMessageWasSelf_ = false;
- previousMessageKind_ = PreviousMessageWasSystem;
+ previousMessageWasSelf_ = false;
+ previousMessageKind_ = PreviousMessageWasSystem;
}
std::string QtWebKitChatView::addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString messageHTML = chatMessageToHTML(message);
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
+ QString messageHTML = chatMessageToHTML(message);
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
- previousMessageKind_ = PreviousMessageWasSystem;
- return id;
+ previousMessageKind_ = PreviousMessageWasSystem;
+ return id;
}
void QtWebKitChatView::replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- replaceMessage(" *" + chatMessageToHTML(message) + "*", id, time, "font-style:italic ", message.getFullMessageHighlightAction());
+ replaceMessage(" *" + chatMessageToHTML(message) + "*", id, time, "font-style:italic ", message.getFullMessageHighlightAction());
}
void QtWebKitChatView::replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- replaceMessage(chatMessageToHTML(message), id, time, "", message.getFullMessageHighlightAction());
+ replaceMessage(chatMessageToHTML(message), id, time, "", message.getFullMessageHighlightAction());
}
void QtWebKitChatView::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, ChatWindow::TimestampBehaviour timestampBehavior) {
- replaceSystemMessage(chatMessageToHTML(message), P2QSTRING(id), timestampBehavior);
+ replaceSystemMessage(chatMessageToHTML(message), P2QSTRING(id), timestampBehavior);
}
void QtWebKitChatView::replaceSystemMessage(const QString& newMessage, const QString& id, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- rememberScrolledToBottom();
- QWebElement message = document_.findFirst("#" + id);
- if (!message.isNull()) {
- QWebElement replaceContent = message.findFirst("span.swift_message");
- assert(!replaceContent.isNull());
- QString old = replaceContent.toOuterXml();
- replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
-
- if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
- QWebElement replace = message.findFirst("span.swift_time");
- assert(!replace.isNull());
- replace.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
- }
- }
- else {
- qWarning() << "Trying to replace element with id " << id << " but it's not there.";
- }
+ rememberScrolledToBottom();
+ QWebElement message = document_.findFirst("#" + id);
+ if (!message.isNull()) {
+ QWebElement replaceContent = message.findFirst("span.swift_message");
+ assert(!replaceContent.isNull());
+ QString old = replaceContent.toOuterXml();
+ replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
+
+ if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
+ QWebElement replace = message.findFirst("span.swift_time");
+ assert(!replace.isNull());
+ replace.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
+ }
+ }
+ else {
+ qWarning() << "Trying to replace element with id " << id << " but it's not there.";
+ }
}
void QtWebKitChatView::replaceMessage(const QString& message, const std::string& id, const boost::posix_time::ptime& time, const QString& style, const HighlightAction& highlight) {
- if (!id.empty()) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (!id.empty()) {
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString messageHTML(message);
+ QString messageHTML(message);
- QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
- QString styleSpanEnd = style == "" ? "" : "</span>";
- QString highlightSpanStart = highlight.highlightWholeMessage() ? getHighlightSpanStart(highlight) : "";
- QString highlightSpanEnd = highlight.highlightWholeMessage() ? "</span>" : "";
- messageHTML = styleSpanStart + highlightSpanStart + messageHTML + highlightSpanEnd + styleSpanEnd;
+ QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
+ QString styleSpanEnd = style == "" ? "" : "</span>";
+ QString highlightSpanStart = highlight.highlightWholeMessage() ? getHighlightSpanStart(highlight) : "";
+ QString highlightSpanEnd = highlight.highlightWholeMessage() ? "</span>" : "";
+ messageHTML = styleSpanStart + highlightSpanStart + messageHTML + highlightSpanEnd + styleSpanEnd;
- replaceMessage(messageHTML, P2QSTRING(id), B2QDATE(time));
- }
- else {
- std::cerr << "Trying to replace a message with no id";
- }
+ replaceMessage(messageHTML, P2QSTRING(id), B2QDATE(time));
+ }
+ else {
+ std::cerr << "Trying to replace a message with no id";
+ }
}
void QtWebKitChatView::addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString messageHTML = chatMessageToHTML(message);
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
+ QString messageHTML = chatMessageToHTML(message);
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
- previousMessageKind_ = PreviousMessageWasPresence;
+ previousMessageKind_ = PreviousMessageWasPresence;
}
void QtWebKitChatView::replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- replaceLastMessage(chatMessageToHTML(message), timestampBehaviour);
+ replaceLastMessage(chatMessageToHTML(message), timestampBehaviour);
}
void QtWebKitChatView::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString message;
- if (isImpromptu) {
- message = QObject::tr("You've been invited to join a chat.") + "\n";
- } else {
- message = QObject::tr("You've been invited to enter the %1 room.").arg(P2QSTRING(jid.toString())) + "\n";
- }
- QString htmlString = message;
- if (!reason.empty()) {
- htmlString += QObject::tr("Reason: %1").arg(P2QSTRING(reason)) + "\n";
- }
- if (!direct) {
- htmlString += QObject::tr("This person may not have really sent this invitation!") + "\n";
- }
- htmlString = chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING(htmlString)));
+ QString message;
+ if (isImpromptu) {
+ message = QObject::tr("You've been invited to join a chat.") + "\n";
+ } else {
+ message = QObject::tr("You've been invited to enter the %1 room.").arg(P2QSTRING(jid.toString())) + "\n";
+ }
+ QString htmlString = message;
+ if (!reason.empty()) {
+ htmlString += QObject::tr("Reason: %1").arg(P2QSTRING(reason)) + "\n";
+ }
+ if (!direct) {
+ htmlString += QObject::tr("This person may not have really sent this invitation!") + "\n";
+ }
+ htmlString = chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING(htmlString)));
- QString id = QString(ButtonMUCInvite + "%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
- htmlString += "<div id='" + id + "'>" +
- buildChatWindowButton(chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING((tr("Accept Invite"))))), ButtonMUCInvite, QtUtilities::htmlEscape(P2QSTRING(jid.toString())), QtUtilities::htmlEscape(P2QSTRING(password)), id, QtUtilities::htmlEscape(isImpromptu ? "true" : "false"), QtUtilities::htmlEscape(isContinuation ? "true" : "false")) +
- "</div>";
+ QString id = QString(ButtonMUCInvite + "%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
+ htmlString += "<div id='" + id + "'>" +
+ buildChatWindowButton(chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING((tr("Accept Invite"))))), ButtonMUCInvite, QtUtilities::htmlEscape(P2QSTRING(jid.toString())), QtUtilities::htmlEscape(P2QSTRING(password)), id, QtUtilities::htmlEscape(isImpromptu ? "true" : "false"), QtUtilities::htmlEscape(isContinuation ? "true" : "false")) +
+ "</div>";
- bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMUCInvite, senderName, false);
+ bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMUCInvite, senderName, false);
- QString qAvatarPath = "qrc:/icons/avatar.png";
+ QString qAvatarPath = "qrc:/icons/avatar.png";
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, appendToPrevious, theme_, id, ChatSnippet::getDirection(message)));
- previousMessageWasSelf_ = false;
- previousSenderName_ = P2QSTRING(senderName);
- previousMessageKind_ = PreviousMessageWasMUCInvite;
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, appendToPrevious, theme_, id, ChatSnippet::getDirection(message)));
+ previousMessageWasSelf_ = false;
+ previousSenderName_ = P2QSTRING(senderName);
+ previousMessageKind_ = PreviousMessageWasMUCInvite;
}
void QtWebKitChatView::setAckState(std::string const& id, ChatWindow::AckState state) {
- QString xml;
- switch (state) {
- case ChatWindow::Pending:
- xml = "<img src='qrc:/icons/throbber.gif' title='" + tr("This message has not been received by your server yet.") + "'/>";
- displayReceiptInfo(P2QSTRING(id), false);
- break;
- case ChatWindow::Received:
- xml = "";
- displayReceiptInfo(P2QSTRING(id), true);
- break;
- case ChatWindow::Failed: xml = "<img src='qrc:/icons/error.png' title='" + tr("This message may not have been transmitted.") + "'/>"; break;
- }
- setAckXML(P2QSTRING(id), xml);
+ QString xml;
+ switch (state) {
+ case ChatWindow::Pending:
+ xml = "<img src='qrc:/icons/throbber.gif' title='" + tr("This message has not been received by your server yet.") + "'/>";
+ displayReceiptInfo(P2QSTRING(id), false);
+ break;
+ case ChatWindow::Received:
+ xml = "";
+ displayReceiptInfo(P2QSTRING(id), true);
+ break;
+ case ChatWindow::Failed: xml = "<img src='qrc:/icons/error.png' title='" + tr("This message may not have been transmitted.") + "'/>"; break;
+ }
+ setAckXML(P2QSTRING(id), xml);
}
void QtWebKitChatView::setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) {
- QString xml;
- switch (state) {
- case ChatWindow::ReceiptReceived:
- xml = "<img src='qrc:/icons/delivery-successful.png' title='" + tr("The receipt for this message has been received.") + "'/>";
- break;
- case ChatWindow::ReceiptRequested:
- xml = "<img src='qrc:/icons/warn.png' title='" + tr("The receipt for this message has not yet been received. The recipient(s) might not have received this message.") + "'/>";
- break;
- case ChatWindow::ReceiptFailed:
- xml = "<img src='qrc:/icons/delivery-failure.png' title='" + tr("Failed to transmit message to the receipient(s).") + "'/>";
- }
- setReceiptXML(P2QSTRING(id), xml);
+ QString xml;
+ switch (state) {
+ case ChatWindow::ReceiptReceived:
+ xml = "<img src='qrc:/icons/delivery-successful.png' title='" + tr("The receipt for this message has been received.") + "'/>";
+ break;
+ case ChatWindow::ReceiptRequested:
+ xml = "<img src='qrc:/icons/warn.png' title='" + tr("The receipt for this message has not yet been received. The recipient(s) might not have received this message.") + "'/>";
+ break;
+ case ChatWindow::ReceiptFailed:
+ xml = "<img src='qrc:/icons/delivery-failure.png' title='" + tr("Failed to transmit message to the receipient(s).") + "'/>";
+ }
+ setReceiptXML(P2QSTRING(id), xml);
}
bool QtWebKitChatView::appendToPreviousCheck(PreviousMessageKind messageKind, const std::string& senderName, bool senderIsSelf) {
- bool result = previousMessageKind_ == messageKind && ((senderIsSelf && previousMessageWasSelf_) || (!senderIsSelf && !previousMessageWasSelf_&& previousSenderName_ == P2QSTRING(senderName)));
- if (insertingLastLine_) {
- insertingLastLine_ = false;
- return false;
- }
- return result;
+ bool result = previousMessageKind_ == messageKind && ((senderIsSelf && previousMessageWasSelf_) || (!senderIsSelf && !previousMessageWasSelf_&& previousSenderName_ == P2QSTRING(senderName)));
+ if (insertingLastLine_) {
+ insertingLastLine_ = false;
+ return false;
+ }
+ return result;
}
ChatSnippet::Direction QtWebKitChatView::getActualDirection(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) {
- if (direction == ChatWindow::DefaultDirection) {
- return QCoreApplication::translate("QApplication", "QT_LAYOUT_DIRECTION") == "RTL" ? ChatSnippet::RTL : ChatSnippet::LTR;
- }
- else {
- return ChatSnippet::getDirection(message);
- }
+ if (direction == ChatWindow::DefaultDirection) {
+ return QCoreApplication::translate("QApplication", "QT_LAYOUT_DIRECTION") == "RTL" ? ChatSnippet::RTL : ChatSnippet::LTR;
+ }
+ else {
+ return ChatSnippet::getDirection(message);
+ }
}
// void QtWebKitChatView::setShowEmoticons(bool value) {
-// showEmoticons_ = value;
+// showEmoticons_ = value;
// }
diff --git a/Swift/QtUI/QtWebKitChatView.h b/Swift/QtUI/QtWebKitChatView.h
index aeed53b..e3fb967 100644
--- a/Swift/QtUI/QtWebKitChatView.h
+++ b/Swift/QtUI/QtWebKitChatView.h
@@ -25,168 +25,168 @@ class QUrl;
class QDate;
namespace Swift {
- class QtWebView;
- class QtChatTheme;
- class QtChatWindowJSBridge;
- class UIEventStream;
- class QtChatWindow;
- class QtWebKitChatView : public QtChatView {
- Q_OBJECT
-
- public:
- static const QString ButtonWhiteboardSessionCancel;
- static const QString ButtonWhiteboardSessionAcceptRequest;
- static const QString ButtonWhiteboardShowWindow;
- static const QString ButtonFileTransferCancel;
- static const QString ButtonFileTransferSetDescription;
- static const QString ButtonFileTransferSendRequest;
- static const QString ButtonFileTransferAcceptRequest;
- static const QString ButtonFileTransferOpenFile;
- static const QString ButtonMUCInvite;
- public:
- QtWebKitChatView(QtChatWindow* window, UIEventStream* eventStream, QtChatTheme* theme, QWidget* parent, bool disableAutoScroll = false);
- ~QtWebKitChatView();
-
- /** Add message to window.
- * @return id of added message (for acks).
- */
- virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
- /** Adds action to window.
- * @return id of added message (for acks);
- */
- virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
-
- virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
- virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
-
- virtual void addErrorMessage(const ChatWindow::ChatMessage& message) SWIFTEN_OVERRIDE;
- virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
- virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
- virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
- virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
- virtual void setAckState(const std::string& id, ChatWindow::AckState state) SWIFTEN_OVERRIDE;
-
- virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) SWIFTEN_OVERRIDE;
- virtual void setFileTransferProgress(std::string, const int percentageDone) SWIFTEN_OVERRIDE;
- virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") SWIFTEN_OVERRIDE;
- virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) SWIFTEN_OVERRIDE;
- virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) SWIFTEN_OVERRIDE;
- virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) SWIFTEN_OVERRIDE;
- virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) SWIFTEN_OVERRIDE;
-
- virtual void showEmoticons(bool show) SWIFTEN_OVERRIDE;
- void addMessageTop(boost::shared_ptr<ChatSnippet> snippet);
- void addMessageBottom(boost::shared_ptr<ChatSnippet> snippet);
-
- int getSnippetPositionByDate(const QDate& date); // FIXME : This probably shouldn't have been public
- virtual void addLastSeenLine() SWIFTEN_OVERRIDE;
-
- private: // previously public, now private
- void replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour);
- void replaceLastMessage(const QString& newMessage, const QString& note);
- void replaceMessage(const QString& newMessage, const QString& id, const QDateTime& time);
- void replaceSystemMessage(const QString& newMessage, const QString&id, const ChatWindow::TimestampBehaviour timestampBehaviour);
- void rememberScrolledToBottom();
- void setAckXML(const QString& id, const QString& xml);
- void setReceiptXML(const QString& id, const QString& xml);
- void displayReceiptInfo(const QString& id, bool showIt);
-
- QString getLastSentMessage();
- void addToJSEnvironment(const QString&, QObject*);
- void setFileTransferProgress(QString id, const int percentageDone);
- void setFileTransferStatus(QString id, const ChatWindow::FileTransferState state, const QString& msg);
- void setFileTransferWarning(QString id, QString warningText);
- void removeFileTransferWarning(QString id);
- void setWhiteboardSessionStatus(QString id, const ChatWindow::WhiteboardSessionState state);
- void setMUCInvitationJoined(QString id);
- void askDesktopToOpenFile(const QString& filename);
-
- signals:
- void gotFocus();
- void fontResized(int);
- void logCleared();
- void scrollRequested(int pos);
- void scrollReachedTop();
- void scrollReachedBottom();
-
- public slots:
- void copySelectionToClipboard();
- void handleLinkClicked(const QUrl&);
- void resetView();
- void resetTopInsertPoint();
- void increaseFontSize(int numSteps = 1);
- void decreaseFontSize();
- virtual void resizeFont(int fontSizeSteps) SWIFTEN_OVERRIDE;
- virtual void scrollToBottom() SWIFTEN_OVERRIDE;
- virtual void handleKeyPressEvent(QKeyEvent* event) SWIFTEN_OVERRIDE;
-
- private slots:
- void handleViewLoadFinished(bool);
- void handleFrameSizeChanged();
- void handleClearRequested();
- void handleScrollRequested(int dx, int dy, const QRect& rectToScroll);
- void handleHTMLButtonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
-
- private:
- enum PreviousMessageKind {
- PreviosuMessageWasNone,
- PreviousMessageWasMessage,
- PreviousMessageWasSystem,
- PreviousMessageWasPresence,
- PreviousMessageWasFileTransfer,
- PreviousMessageWasMUCInvite
- };
- std::string addMessage(
- const QString& message,
- const std::string& senderName,
- bool senderIsSelf,
- boost::shared_ptr<SecurityLabel> label,
- const std::string& avatarPath,
- const QString& style,
- const boost::posix_time::ptime& time,
- const HighlightAction& highlight,
- ChatSnippet::Direction direction);
- void replaceMessage(
- const QString& message,
- const std::string& id,
- const boost::posix_time::ptime& time,
- const QString& style,
- const HighlightAction& highlight);
- bool appendToPreviousCheck(PreviousMessageKind messageKind, const std::string& senderName, bool senderIsSelf);
- static ChatSnippet::Direction getActualDirection(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction);
- QString getHighlightSpanStart(const std::string& text, const std::string& background);
- QString getHighlightSpanStart(const HighlightAction& highlight);
- QString chatMessageToHTML(const ChatWindow::ChatMessage& message);
- static QString buildChatWindowButton(const QString& name, const QString& id, const QString& arg1 = QString(), const QString& arg2 = QString(), const QString& arg3 = QString(), const QString& arg4 = QString(), const QString& arg5 = QString());
-
- private:
- void headerEncode();
- void messageEncode();
- void addToDOM(boost::shared_ptr<ChatSnippet> snippet);
-
- QtChatWindow* window_;
- UIEventStream* eventStream_;
- bool viewReady_;
- bool isAtBottom_;
- bool topMessageAdded_;
- int scrollBarMaximum_;
- QtWebView* webView_;
- QWebPage* webPage_;
- int fontSizeSteps_;
- QtChatTheme* theme_;
- QWebElement lineSeparator_;
- QWebElement lastElement_;
- QWebElement firstElement_;
- QWebElement document_;
- bool disableAutoScroll_;
- QtChatWindowJSBridge* jsBridge;
- PreviousMessageKind previousMessageKind_;
- bool previousMessageWasSelf_;
- bool showEmoticons_;
- bool insertingLastLine_;
- int idCounter_;
- QString previousSenderName_;
- std::map<QString, QString> descriptions_;
- std::map<QString, QString> filePaths_;
- };
+ class QtWebView;
+ class QtChatTheme;
+ class QtChatWindowJSBridge;
+ class UIEventStream;
+ class QtChatWindow;
+ class QtWebKitChatView : public QtChatView {
+ Q_OBJECT
+
+ public:
+ static const QString ButtonWhiteboardSessionCancel;
+ static const QString ButtonWhiteboardSessionAcceptRequest;
+ static const QString ButtonWhiteboardShowWindow;
+ static const QString ButtonFileTransferCancel;
+ static const QString ButtonFileTransferSetDescription;
+ static const QString ButtonFileTransferSendRequest;
+ static const QString ButtonFileTransferAcceptRequest;
+ static const QString ButtonFileTransferOpenFile;
+ static const QString ButtonMUCInvite;
+ public:
+ QtWebKitChatView(QtChatWindow* window, UIEventStream* eventStream, QtChatTheme* theme, QWidget* parent, bool disableAutoScroll = false);
+ ~QtWebKitChatView();
+
+ /** Add message to window.
+ * @return id of added message (for acks).
+ */
+ virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ /** Adds action to window.
+ * @return id of added message (for acks);
+ */
+ virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+
+ virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
+ virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
+
+ virtual void addErrorMessage(const ChatWindow::ChatMessage& message) SWIFTEN_OVERRIDE;
+ virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
+ virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
+ virtual void setAckState(const std::string& id, ChatWindow::AckState state) SWIFTEN_OVERRIDE;
+
+ virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) SWIFTEN_OVERRIDE;
+ virtual void setFileTransferProgress(std::string, const int percentageDone) SWIFTEN_OVERRIDE;
+ virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") SWIFTEN_OVERRIDE;
+ virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) SWIFTEN_OVERRIDE;
+ virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) SWIFTEN_OVERRIDE;
+ virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) SWIFTEN_OVERRIDE;
+ virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) SWIFTEN_OVERRIDE;
+
+ virtual void showEmoticons(bool show) SWIFTEN_OVERRIDE;
+ void addMessageTop(boost::shared_ptr<ChatSnippet> snippet);
+ void addMessageBottom(boost::shared_ptr<ChatSnippet> snippet);
+
+ int getSnippetPositionByDate(const QDate& date); // FIXME : This probably shouldn't have been public
+ virtual void addLastSeenLine() SWIFTEN_OVERRIDE;
+
+ private: // previously public, now private
+ void replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour);
+ void replaceLastMessage(const QString& newMessage, const QString& note);
+ void replaceMessage(const QString& newMessage, const QString& id, const QDateTime& time);
+ void replaceSystemMessage(const QString& newMessage, const QString&id, const ChatWindow::TimestampBehaviour timestampBehaviour);
+ void rememberScrolledToBottom();
+ void setAckXML(const QString& id, const QString& xml);
+ void setReceiptXML(const QString& id, const QString& xml);
+ void displayReceiptInfo(const QString& id, bool showIt);
+
+ QString getLastSentMessage();
+ void addToJSEnvironment(const QString&, QObject*);
+ void setFileTransferProgress(QString id, const int percentageDone);
+ void setFileTransferStatus(QString id, const ChatWindow::FileTransferState state, const QString& msg);
+ void setFileTransferWarning(QString id, QString warningText);
+ void removeFileTransferWarning(QString id);
+ void setWhiteboardSessionStatus(QString id, const ChatWindow::WhiteboardSessionState state);
+ void setMUCInvitationJoined(QString id);
+ void askDesktopToOpenFile(const QString& filename);
+
+ signals:
+ void gotFocus();
+ void fontResized(int);
+ void logCleared();
+ void scrollRequested(int pos);
+ void scrollReachedTop();
+ void scrollReachedBottom();
+
+ public slots:
+ void copySelectionToClipboard();
+ void handleLinkClicked(const QUrl&);
+ void resetView();
+ void resetTopInsertPoint();
+ void increaseFontSize(int numSteps = 1);
+ void decreaseFontSize();
+ virtual void resizeFont(int fontSizeSteps) SWIFTEN_OVERRIDE;
+ virtual void scrollToBottom() SWIFTEN_OVERRIDE;
+ virtual void handleKeyPressEvent(QKeyEvent* event) SWIFTEN_OVERRIDE;
+
+ private slots:
+ void handleViewLoadFinished(bool);
+ void handleFrameSizeChanged();
+ void handleClearRequested();
+ void handleScrollRequested(int dx, int dy, const QRect& rectToScroll);
+ void handleHTMLButtonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
+
+ private:
+ enum PreviousMessageKind {
+ PreviosuMessageWasNone,
+ PreviousMessageWasMessage,
+ PreviousMessageWasSystem,
+ PreviousMessageWasPresence,
+ PreviousMessageWasFileTransfer,
+ PreviousMessageWasMUCInvite
+ };
+ std::string addMessage(
+ const QString& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ boost::shared_ptr<SecurityLabel> label,
+ const std::string& avatarPath,
+ const QString& style,
+ const boost::posix_time::ptime& time,
+ const HighlightAction& highlight,
+ ChatSnippet::Direction direction);
+ void replaceMessage(
+ const QString& message,
+ const std::string& id,
+ const boost::posix_time::ptime& time,
+ const QString& style,
+ const HighlightAction& highlight);
+ bool appendToPreviousCheck(PreviousMessageKind messageKind, const std::string& senderName, bool senderIsSelf);
+ static ChatSnippet::Direction getActualDirection(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction);
+ QString getHighlightSpanStart(const std::string& text, const std::string& background);
+ QString getHighlightSpanStart(const HighlightAction& highlight);
+ QString chatMessageToHTML(const ChatWindow::ChatMessage& message);
+ static QString buildChatWindowButton(const QString& name, const QString& id, const QString& arg1 = QString(), const QString& arg2 = QString(), const QString& arg3 = QString(), const QString& arg4 = QString(), const QString& arg5 = QString());
+
+ private:
+ void headerEncode();
+ void messageEncode();
+ void addToDOM(boost::shared_ptr<ChatSnippet> snippet);
+
+ QtChatWindow* window_;
+ UIEventStream* eventStream_;
+ bool viewReady_;
+ bool isAtBottom_;
+ bool topMessageAdded_;
+ int scrollBarMaximum_;
+ QtWebView* webView_;
+ QWebPage* webPage_;
+ int fontSizeSteps_;
+ QtChatTheme* theme_;
+ QWebElement lineSeparator_;
+ QWebElement lastElement_;
+ QWebElement firstElement_;
+ QWebElement document_;
+ bool disableAutoScroll_;
+ QtChatWindowJSBridge* jsBridge;
+ PreviousMessageKind previousMessageKind_;
+ bool previousMessageWasSelf_;
+ bool showEmoticons_;
+ bool insertingLastLine_;
+ int idCounter_;
+ QString previousSenderName_;
+ std::map<QString, QString> descriptions_;
+ std::map<QString, QString> filePaths_;
+ };
}
diff --git a/Swift/QtUI/QtWebView.cpp b/Swift/QtUI/QtWebView.cpp
index 4950d27..717310b 100644
--- a/Swift/QtUI/QtWebView.cpp
+++ b/Swift/QtUI/QtWebView.cpp
@@ -17,29 +17,29 @@
namespace Swift {
QtWebView::QtWebView(QWidget* parent) : QWebView(parent), fontSizeIsMinimal(false) {
- setRenderHint(QPainter::SmoothPixmapTransform);
- filteredActions.push_back(QWebPage::CopyLinkToClipboard);
- filteredActions.push_back(QWebPage::CopyImageToClipboard);
- filteredActions.push_back(QWebPage::Copy);
- if (Log::getLogLevel() == Log::debug) {
- filteredActions.push_back(QWebPage::InspectElement);
- }
+ setRenderHint(QPainter::SmoothPixmapTransform);
+ filteredActions.push_back(QWebPage::CopyLinkToClipboard);
+ filteredActions.push_back(QWebPage::CopyImageToClipboard);
+ filteredActions.push_back(QWebPage::Copy);
+ if (Log::getLogLevel() == Log::debug) {
+ filteredActions.push_back(QWebPage::InspectElement);
+ }
}
void QtWebView::keyPressEvent(QKeyEvent* event) {
- Qt::KeyboardModifiers modifiers = event->modifiers();
- int key = event->key();
- if (modifiers == Qt::ShiftModifier && (key == Qt::Key_PageUp || key == Qt::Key_PageDown)) {
- modifiers = Qt::NoModifier;
- }
- QKeyEvent* translatedEvent = new QKeyEvent(QEvent::KeyPress,
- key,
- modifiers,
- event->text(),
- event->isAutoRepeat(),
- boost::numeric_cast<unsigned short>(event->count()));
- QWebView::keyPressEvent(translatedEvent);
- delete translatedEvent;
+ Qt::KeyboardModifiers modifiers = event->modifiers();
+ int key = event->key();
+ if (modifiers == Qt::ShiftModifier && (key == Qt::Key_PageUp || key == Qt::Key_PageDown)) {
+ modifiers = Qt::NoModifier;
+ }
+ QKeyEvent* translatedEvent = new QKeyEvent(QEvent::KeyPress,
+ key,
+ modifiers,
+ event->text(),
+ event->isAutoRepeat(),
+ boost::numeric_cast<unsigned short>(event->count()));
+ QWebView::keyPressEvent(translatedEvent);
+ delete translatedEvent;
}
void QtWebView::dragEnterEvent(QDragEnterEvent*) {
@@ -47,43 +47,43 @@ void QtWebView::dragEnterEvent(QDragEnterEvent*) {
}
void QtWebView::setFontSizeIsMinimal(bool minimum) {
- fontSizeIsMinimal = minimum;
+ fontSizeIsMinimal = minimum;
}
void QtWebView::contextMenuEvent(QContextMenuEvent* ev) {
- // Filter out the relevant actions from the standard actions
-
- QMenu* menu = page()->createStandardContextMenu();
- QList<QAction*> actions(menu->actions());
- for (int i = 0; i < actions.size(); ++i) {
- QAction* action = actions.at(i);
- bool removeAction = true;
- for(size_t j = 0; j < filteredActions.size(); ++j) {
- if (action == pageAction(filteredActions[j])) {
- removeAction = false;
- break;
- }
- }
- if (removeAction) {
- menu->removeAction(action);
- }
- }
-
- // Add our own custom actions
- menu->addAction(tr("Clear"), this, SIGNAL(clearRequested()));
- menu->addAction(tr("Increase font size"), this, SIGNAL(fontGrowRequested()));
- QAction* shrink = new QAction(tr("Decrease font size"), this);
- shrink->setEnabled(!fontSizeIsMinimal);
- connect(shrink, SIGNAL(triggered()), this, SIGNAL(fontShrinkRequested()));
- menu->addAction(shrink);
-
- menu->exec(ev->globalPos());
- delete menu;
+ // Filter out the relevant actions from the standard actions
+
+ QMenu* menu = page()->createStandardContextMenu();
+ QList<QAction*> actions(menu->actions());
+ for (int i = 0; i < actions.size(); ++i) {
+ QAction* action = actions.at(i);
+ bool removeAction = true;
+ for(size_t j = 0; j < filteredActions.size(); ++j) {
+ if (action == pageAction(filteredActions[j])) {
+ removeAction = false;
+ break;
+ }
+ }
+ if (removeAction) {
+ menu->removeAction(action);
+ }
+ }
+
+ // Add our own custom actions
+ menu->addAction(tr("Clear"), this, SIGNAL(clearRequested()));
+ menu->addAction(tr("Increase font size"), this, SIGNAL(fontGrowRequested()));
+ QAction* shrink = new QAction(tr("Decrease font size"), this);
+ shrink->setEnabled(!fontSizeIsMinimal);
+ connect(shrink, SIGNAL(triggered()), this, SIGNAL(fontShrinkRequested()));
+ menu->addAction(shrink);
+
+ menu->exec(ev->globalPos());
+ delete menu;
}
void QtWebView::focusInEvent(QFocusEvent* event) {
- QWebView::focusInEvent(event);
- emit gotFocus();
+ QWebView::focusInEvent(event);
+ emit gotFocus();
}
}
diff --git a/Swift/QtUI/QtWebView.h b/Swift/QtUI/QtWebView.h
index 134f578..985a0db 100644
--- a/Swift/QtUI/QtWebView.h
+++ b/Swift/QtUI/QtWebView.h
@@ -12,26 +12,26 @@
#include <QWebView>
namespace Swift {
- class QtWebView : public QWebView {
- Q_OBJECT
- public:
- QtWebView(QWidget* parent);
- void keyPressEvent(QKeyEvent* event);
- void dragEnterEvent(QDragEnterEvent *event);
- void contextMenuEvent(QContextMenuEvent* ev);
- void setFontSizeIsMinimal(bool minimum);
-
- signals:
- void gotFocus();
- void clearRequested();
- void fontGrowRequested();
- void fontShrinkRequested();
-
- protected:
- void focusInEvent(QFocusEvent* event);
-
- private:
- std::vector<QWebPage::WebAction> filteredActions;
- bool fontSizeIsMinimal;
- };
+ class QtWebView : public QWebView {
+ Q_OBJECT
+ public:
+ QtWebView(QWidget* parent);
+ void keyPressEvent(QKeyEvent* event);
+ void dragEnterEvent(QDragEnterEvent *event);
+ void contextMenuEvent(QContextMenuEvent* ev);
+ void setFontSizeIsMinimal(bool minimum);
+
+ signals:
+ void gotFocus();
+ void clearRequested();
+ void fontGrowRequested();
+ void fontShrinkRequested();
+
+ protected:
+ void focusInEvent(QFocusEvent* event);
+
+ private:
+ std::vector<QWebPage::WebAction> filteredActions;
+ bool fontSizeIsMinimal;
+ };
}
diff --git a/Swift/QtUI/QtWin32NotifierWindow.h b/Swift/QtUI/QtWin32NotifierWindow.h
index 54369cf..bf55706 100644
--- a/Swift/QtUI/QtWin32NotifierWindow.h
+++ b/Swift/QtUI/QtWin32NotifierWindow.h
@@ -11,19 +11,19 @@
#include <SwifTools/Notifier/Win32NotifierWindow.h>
namespace Swift {
- class QtWin32NotifierWindow : public QWidget, public Win32NotifierWindow {
- public:
- QtWin32NotifierWindow(QWidget* parent = NULL) {
- setVisible(false);
- }
+ class QtWin32NotifierWindow : public QWidget, public Win32NotifierWindow {
+ public:
+ QtWin32NotifierWindow(QWidget* parent = NULL) {
+ setVisible(false);
+ }
- bool winEvent (MSG* message, long* result ) {
- onMessageReceived(message);
- return false;
- }
+ bool winEvent (MSG* message, long* result ) {
+ onMessageReceived(message);
+ return false;
+ }
- virtual HWND getID() const {
- return (HWND) winId();
- }
- };
+ virtual HWND getID() const {
+ return (HWND) winId();
+ }
+ };
}
diff --git a/Swift/QtUI/QtXMLConsoleWidget.cpp b/Swift/QtUI/QtXMLConsoleWidget.cpp
index 1fbad8f..a7f9702 100644
--- a/Swift/QtUI/QtXMLConsoleWidget.cpp
+++ b/Swift/QtUI/QtXMLConsoleWidget.cpp
@@ -22,99 +22,99 @@
namespace Swift {
QtXMLConsoleWidget::QtXMLConsoleWidget() {
- setWindowTitle(tr("Console"));
+ setWindowTitle(tr("Console"));
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->setSpacing(0);
- layout->setContentsMargins(0,0,0,0);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->setSpacing(0);
+ layout->setContentsMargins(0,0,0,0);
- textEdit = new QTextEdit(this);
- textEdit->setReadOnly(true);
- layout->addWidget(textEdit);
+ textEdit = new QTextEdit(this);
+ textEdit->setReadOnly(true);
+ layout->addWidget(textEdit);
- QWidget* bottom = new QWidget(this);
- layout->addWidget(bottom);
- bottom->setAutoFillBackground(true);
+ QWidget* bottom = new QWidget(this);
+ layout->addWidget(bottom);
+ bottom->setAutoFillBackground(true);
- QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
- buttonLayout->setContentsMargins(10,0,20,0);
- buttonLayout->setSpacing(0);
+ QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
+ buttonLayout->setContentsMargins(10,0,20,0);
+ buttonLayout->setSpacing(0);
- enabled = new QCheckBox(tr("Trace input/output"), bottom);
- enabled->setChecked(true);
- buttonLayout->addWidget(enabled);
+ enabled = new QCheckBox(tr("Trace input/output"), bottom);
+ enabled->setChecked(true);
+ buttonLayout->addWidget(enabled);
- buttonLayout->addStretch();
+ buttonLayout->addStretch();
- QPushButton* clearButton = new QPushButton(tr("Clear"), bottom);
- connect(clearButton, SIGNAL(clicked()), textEdit, SLOT(clear()));
- buttonLayout->addWidget(clearButton);
+ QPushButton* clearButton = new QPushButton(tr("Clear"), bottom);
+ connect(clearButton, SIGNAL(clicked()), textEdit, SLOT(clear()));
+ buttonLayout->addWidget(clearButton);
- setWindowTitle(tr("Debug Console"));
- emit titleUpdated();
+ setWindowTitle(tr("Debug Console"));
+ emit titleUpdated();
}
QtXMLConsoleWidget::~QtXMLConsoleWidget() {
}
void QtXMLConsoleWidget::showEvent(QShowEvent* event) {
- emit windowOpening();
- emit titleUpdated(); /* This just needs to be somewhere after construction */
- QWidget::showEvent(event);
+ emit windowOpening();
+ emit titleUpdated(); /* This just needs to be somewhere after construction */
+ QWidget::showEvent(event);
}
void QtXMLConsoleWidget::show() {
- QWidget::show();
- emit windowOpening();
+ QWidget::show();
+ emit windowOpening();
}
void QtXMLConsoleWidget::activate() {
- emit wantsToActivate();
+ emit wantsToActivate();
}
void QtXMLConsoleWidget::closeEvent(QCloseEvent* event) {
- emit windowClosing();
- event->accept();
+ emit windowClosing();
+ event->accept();
}
void QtXMLConsoleWidget::handleDataRead(const SafeByteArray& data) {
- boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
- std::string tag = Q2PSTRING(tr("<!-- IN %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
- appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(33,98,33));
+ boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
+ std::string tag = Q2PSTRING(tr("<!-- IN %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
+ appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(33,98,33));
}
void QtXMLConsoleWidget::handleDataWritten(const SafeByteArray& data) {
- boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
- std::string tag = Q2PSTRING(tr("<!-- OUT %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
- appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(155,1,0));
+ boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
+ std::string tag = Q2PSTRING(tr("<!-- OUT %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
+ appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(155,1,0));
}
std::string QtXMLConsoleWidget::getID() const {
- return "QtXMLConsoleWidget";
+ return "QtXMLConsoleWidget";
}
void QtXMLConsoleWidget::appendTextIfEnabled(const std::string& data, const QColor& color) {
- if (enabled->isChecked()) {
- QScrollBar* scrollBar = textEdit->verticalScrollBar();
- bool scrollToBottom = (!scrollBar || scrollBar->value() == scrollBar->maximum());
-
- QTextCursor cursor(textEdit->document());
- cursor.beginEditBlock();
- cursor.movePosition(QTextCursor::End);
- QTextCharFormat format;
- format.setForeground(QBrush(color));
- cursor.mergeCharFormat(format);
- cursor.insertText(P2QSTRING(data));
- cursor.endEditBlock();
-
- // Checking for the scrollbar again, because it could have appeared after inserting text.
- // In practice, I suspect that the scrollbar is always there, but hidden, but since we were
- // explicitly testing for this already above, I'm leaving the code in.
- scrollBar = textEdit->verticalScrollBar();
- if (scrollToBottom && scrollBar) {
- scrollBar->setValue(scrollBar->maximum());
- }
- }
+ if (enabled->isChecked()) {
+ QScrollBar* scrollBar = textEdit->verticalScrollBar();
+ bool scrollToBottom = (!scrollBar || scrollBar->value() == scrollBar->maximum());
+
+ QTextCursor cursor(textEdit->document());
+ cursor.beginEditBlock();
+ cursor.movePosition(QTextCursor::End);
+ QTextCharFormat format;
+ format.setForeground(QBrush(color));
+ cursor.mergeCharFormat(format);
+ cursor.insertText(P2QSTRING(data));
+ cursor.endEditBlock();
+
+ // Checking for the scrollbar again, because it could have appeared after inserting text.
+ // In practice, I suspect that the scrollbar is always there, but hidden, but since we were
+ // explicitly testing for this already above, I'm leaving the code in.
+ scrollBar = textEdit->verticalScrollBar();
+ if (scrollToBottom && scrollBar) {
+ scrollBar->setValue(scrollBar->maximum());
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtXMLConsoleWidget.h b/Swift/QtUI/QtXMLConsoleWidget.h
index ddcfe20..ef10e63 100644
--- a/Swift/QtUI/QtXMLConsoleWidget.h
+++ b/Swift/QtUI/QtXMLConsoleWidget.h
@@ -15,29 +15,29 @@ class QCheckBox;
class QColor;
namespace Swift {
- class QtXMLConsoleWidget : public QtTabbable, public XMLConsoleWidget {
- Q_OBJECT
+ class QtXMLConsoleWidget : public QtTabbable, public XMLConsoleWidget {
+ Q_OBJECT
- public:
- QtXMLConsoleWidget();
- ~QtXMLConsoleWidget();
+ public:
+ QtXMLConsoleWidget();
+ ~QtXMLConsoleWidget();
- void show();
- void activate();
+ void show();
+ void activate();
- virtual void handleDataRead(const SafeByteArray& data);
- virtual void handleDataWritten(const SafeByteArray& data);
+ virtual void handleDataRead(const SafeByteArray& data);
+ virtual void handleDataWritten(const SafeByteArray& data);
- virtual std::string getID() const;
+ virtual std::string getID() const;
- private:
- virtual void closeEvent(QCloseEvent* event);
- virtual void showEvent(QShowEvent* event);
+ private:
+ virtual void closeEvent(QCloseEvent* event);
+ virtual void showEvent(QShowEvent* event);
- void appendTextIfEnabled(const std::string& data, const QColor& color);
+ void appendTextIfEnabled(const std::string& data, const QColor& color);
- private:
- QTextEdit* textEdit;
- QCheckBox* enabled;
- };
+ private:
+ QTextEdit* textEdit;
+ QCheckBox* enabled;
+ };
}
diff --git a/Swift/QtUI/Roster/DelegateCommons.cpp b/Swift/QtUI/Roster/DelegateCommons.cpp
index f9d732c..517683b 100644
--- a/Swift/QtUI/Roster/DelegateCommons.cpp
+++ b/Swift/QtUI/Roster/DelegateCommons.cpp
@@ -14,96 +14,96 @@ namespace Swift {
void DelegateCommons::drawElidedText(QPainter* painter, const QRect& region, const QString& text, int flags) {
- QString adjustedText(painter->fontMetrics().elidedText(text, Qt::ElideRight, region.width(), Qt::TextShowMnemonic));
- painter->setClipRect(region);
- painter->drawText(region, flags, adjustedText.simplified());
- painter->setClipping(false);
+ QString adjustedText(painter->fontMetrics().elidedText(text, Qt::ElideRight, region.width(), Qt::TextShowMnemonic));
+ painter->setClipRect(region);
+ painter->drawText(region, flags, adjustedText.simplified());
+ painter->setClipping(false);
}
void DelegateCommons::paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QColor& nameColor, const QString& avatarPath, const QIcon& presenceIcon, const QString& name, const QString& statusText, bool isIdle, int unreadCount, bool compact) const {
- painter->save();
- QRect fullRegion(option.rect);
- if ( option.state & QStyle::State_Selected ) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- } else {
- painter->setPen(QPen(nameColor));
- }
-
- QRect presenceIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth, fullRegion.height() - verticalMargin));
-
- QRect idleIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth*2, fullRegion.height() - verticalMargin));
- int calculatedAvatarSize = presenceIconRegion.height();
- //This overlaps the presenceIcon, so must be painted first
- QRect avatarRegion(QPoint(presenceIconRegion.right() - presenceIconWidth / 2, presenceIconRegion.top()), QSize(calculatedAvatarSize, calculatedAvatarSize));
-
- QPixmap avatarPixmap;
- if (!compact && !avatarPath.isEmpty()) {
- QString scaledAvatarPath = QtScaledAvatarCache(avatarRegion.height()).getScaledAvatarPath(avatarPath);
- if (QFileInfo(scaledAvatarPath).exists()) {
- avatarPixmap.load(scaledAvatarPath);
- }
- }
- if (!compact && avatarPixmap.isNull()) {
- avatarPixmap = QPixmap(":/icons/avatar.png").scaled(avatarRegion.height(), avatarRegion.width(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
-
- if (!compact) {
- painter->drawPixmap(avatarRegion.topLeft() + QPoint(((avatarRegion.width() - avatarPixmap.width()) / 2), (avatarRegion.height() - avatarPixmap.height()) / 2), avatarPixmap);
- }
-
- //Paint the presence icon over the top of the avatar
- presenceIcon.paint(painter, presenceIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
-
- if (isIdle) {
- idleIcon.paint(painter, idleIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
- }
-
- QFontMetrics nameMetrics(nameFont);
- painter->setFont(nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = (compact ? presenceIconRegion : avatarRegion).right() + horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0/*-leftOffset*/, 0));
-
- int nameHeight = nameMetrics.height() + verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, verticalMargin, 0, 0));
-
- DelegateCommons::drawElidedText(painter, nameRegion, name);
-
- if (!compact) {
- painter->setFont(detailFont);
- painter->setPen(QPen(QColor(160,160,160)));
-
- QRect statusTextRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- DelegateCommons::drawElidedText(painter, statusTextRegion, statusText);
- }
-
- if (unreadCount > 0) {
- QRect unreadRect(fullRegion.right() - unreadCountSize - horizontalMargin, fullRegion.top() + (fullRegion.height() - unreadCountSize) / 2, unreadCountSize, unreadCountSize);
- QPen pen(QColor("black"));
- pen.setWidth(1);
- painter->setRenderHint(QPainter::Antialiasing, true);
- painter->setPen(pen);
- painter->setBrush(QBrush(QColor("red"), Qt::SolidPattern));
- //painter->setBackgroundMode(Qt::OpaqueMode);
- painter->drawEllipse(unreadRect);
- painter->setBackgroundMode(Qt::TransparentMode);
- painter->setPen(QColor("white"));
- drawElidedText(painter, unreadRect, QString("%1").arg(unreadCount), Qt::AlignCenter);
- }
-
- painter->restore();
+ painter->save();
+ QRect fullRegion(option.rect);
+ if ( option.state & QStyle::State_Selected ) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ } else {
+ painter->setPen(QPen(nameColor));
+ }
+
+ QRect presenceIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth, fullRegion.height() - verticalMargin));
+
+ QRect idleIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth*2, fullRegion.height() - verticalMargin));
+ int calculatedAvatarSize = presenceIconRegion.height();
+ //This overlaps the presenceIcon, so must be painted first
+ QRect avatarRegion(QPoint(presenceIconRegion.right() - presenceIconWidth / 2, presenceIconRegion.top()), QSize(calculatedAvatarSize, calculatedAvatarSize));
+
+ QPixmap avatarPixmap;
+ if (!compact && !avatarPath.isEmpty()) {
+ QString scaledAvatarPath = QtScaledAvatarCache(avatarRegion.height()).getScaledAvatarPath(avatarPath);
+ if (QFileInfo(scaledAvatarPath).exists()) {
+ avatarPixmap.load(scaledAvatarPath);
+ }
+ }
+ if (!compact && avatarPixmap.isNull()) {
+ avatarPixmap = QPixmap(":/icons/avatar.png").scaled(avatarRegion.height(), avatarRegion.width(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+
+ if (!compact) {
+ painter->drawPixmap(avatarRegion.topLeft() + QPoint(((avatarRegion.width() - avatarPixmap.width()) / 2), (avatarRegion.height() - avatarPixmap.height()) / 2), avatarPixmap);
+ }
+
+ //Paint the presence icon over the top of the avatar
+ presenceIcon.paint(painter, presenceIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
+
+ if (isIdle) {
+ idleIcon.paint(painter, idleIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
+ }
+
+ QFontMetrics nameMetrics(nameFont);
+ painter->setFont(nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = (compact ? presenceIconRegion : avatarRegion).right() + horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0/*-leftOffset*/, 0));
+
+ int nameHeight = nameMetrics.height() + verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, verticalMargin, 0, 0));
+
+ DelegateCommons::drawElidedText(painter, nameRegion, name);
+
+ if (!compact) {
+ painter->setFont(detailFont);
+ painter->setPen(QPen(QColor(160,160,160)));
+
+ QRect statusTextRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ DelegateCommons::drawElidedText(painter, statusTextRegion, statusText);
+ }
+
+ if (unreadCount > 0) {
+ QRect unreadRect(fullRegion.right() - unreadCountSize - horizontalMargin, fullRegion.top() + (fullRegion.height() - unreadCountSize) / 2, unreadCountSize, unreadCountSize);
+ QPen pen(QColor("black"));
+ pen.setWidth(1);
+ painter->setRenderHint(QPainter::Antialiasing, true);
+ painter->setPen(pen);
+ painter->setBrush(QBrush(QColor("red"), Qt::SolidPattern));
+ //painter->setBackgroundMode(Qt::OpaqueMode);
+ painter->drawEllipse(unreadRect);
+ painter->setBackgroundMode(Qt::TransparentMode);
+ painter->setPen(QColor("white"));
+ drawElidedText(painter, unreadRect, QString("%1").arg(unreadCount), Qt::AlignCenter);
+ }
+
+ painter->restore();
}
QSize DelegateCommons::contactSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/, bool compact ) const {
- int heightByAvatar = (compact ? presenceIconHeight : avatarSize) + verticalMargin * 2;
- QFontMetrics nameMetrics(nameFont);
- QFontMetrics statusMetrics(detailFont);
- int sizeByText = 2 * verticalMargin + nameMetrics.height() + (compact ? 0 : statusMetrics.height());
- //Doesn't work, yay! FIXME: why?
- //QSize size = (option.state & QStyle::State_Selected) ? QSize(150, 80) : QSize(150, avatarSize_ + margin_ * 2);
- //qDebug() << "Returning size" << size;
- return QSize(150, sizeByText > heightByAvatar ? sizeByText : heightByAvatar);
+ int heightByAvatar = (compact ? presenceIconHeight : avatarSize) + verticalMargin * 2;
+ QFontMetrics nameMetrics(nameFont);
+ QFontMetrics statusMetrics(detailFont);
+ int sizeByText = 2 * verticalMargin + nameMetrics.height() + (compact ? 0 : statusMetrics.height());
+ //Doesn't work, yay! FIXME: why?
+ //QSize size = (option.state & QStyle::State_Selected) ? QSize(150, 80) : QSize(150, avatarSize_ + margin_ * 2);
+ //qDebug() << "Returning size" << size;
+ return QSize(150, sizeByText > heightByAvatar ? sizeByText : heightByAvatar);
}
const int DelegateCommons::horizontalMargin = 2;
diff --git a/Swift/QtUI/Roster/DelegateCommons.h b/Swift/QtUI/Roster/DelegateCommons.h
index 5e28ac1..74b08f2 100644
--- a/Swift/QtUI/Roster/DelegateCommons.h
+++ b/Swift/QtUI/Roster/DelegateCommons.h
@@ -15,29 +15,29 @@
#include <QStyleOptionViewItem>
namespace Swift {
- class DelegateCommons {
- public:
- DelegateCommons() : nameFont(QApplication::font()), detailFont(QApplication::font()), idleIcon(QIcon(":/icons/zzz.png")) {
- detailFontSizeDrop = nameFont.pointSize() >= 10 ? 2 : 0;
- detailFont.setStyle(QFont::StyleItalic);
- detailFont.setPointSize(nameFont.pointSize() - detailFontSizeDrop);
- }
+ class DelegateCommons {
+ public:
+ DelegateCommons() : nameFont(QApplication::font()), detailFont(QApplication::font()), idleIcon(QIcon(":/icons/zzz.png")) {
+ detailFontSizeDrop = nameFont.pointSize() >= 10 ? 2 : 0;
+ detailFont.setStyle(QFont::StyleItalic);
+ detailFont.setPointSize(nameFont.pointSize() - detailFontSizeDrop);
+ }
- static void drawElidedText(QPainter* painter, const QRect& region, const QString& text, int flags = Qt::AlignTop);
+ static void drawElidedText(QPainter* painter, const QRect& region, const QString& text, int flags = Qt::AlignTop);
- QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index, bool compact) const;
- void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QColor& nameColor, const QString& avatarPath, const QIcon& presenceIcon, const QString& name, const QString& statusText, bool isIdle, int unreadCount, bool compact) const;
+ QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index, bool compact) const;
+ void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QColor& nameColor, const QString& avatarPath, const QIcon& presenceIcon, const QString& name, const QString& statusText, bool isIdle, int unreadCount, bool compact) const;
- int detailFontSizeDrop;
- QFont nameFont;
- QFont detailFont;
- static const int horizontalMargin;
- static const int verticalMargin;
- static const int farLeftMargin;
- static const int avatarSize;
- static const int presenceIconHeight;
- static const int presenceIconWidth;
- static const int unreadCountSize;
- QIcon idleIcon;
- };
+ int detailFontSizeDrop;
+ QFont nameFont;
+ QFont detailFont;
+ static const int horizontalMargin;
+ static const int verticalMargin;
+ static const int farLeftMargin;
+ static const int avatarSize;
+ static const int presenceIconHeight;
+ static const int presenceIconWidth;
+ static const int unreadCountSize;
+ QIcon idleIcon;
+ };
}
diff --git a/Swift/QtUI/Roster/GroupItemDelegate.cpp b/Swift/QtUI/Roster/GroupItemDelegate.cpp
index d91d4ba..0356aa0 100644
--- a/Swift/QtUI/Roster/GroupItemDelegate.cpp
+++ b/Swift/QtUI/Roster/GroupItemDelegate.cpp
@@ -13,100 +13,100 @@
namespace Swift {
GroupItemDelegate::GroupItemDelegate() : groupFont_(QApplication::font()) {
- groupFont_.setPointSize(common_.nameFont.pointSize() - common_.detailFontSizeDrop);
- groupFont_.setWeight(QFont::Bold);
+ groupFont_.setPointSize(common_.nameFont.pointSize() - common_.detailFontSizeDrop);
+ groupFont_.setWeight(QFont::Bold);
}
QSize GroupItemDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/) const {
- QFontMetrics groupMetrics(groupFont_);
- return QSize(150, groupMetrics.height() + common_.verticalMargin + 2);
+ QFontMetrics groupMetrics(groupFont_);
+ return QSize(150, groupMetrics.height() + common_.verticalMargin + 2);
}
void GroupItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QString& name, int rowCount, bool expanded) const {
- painter->save();
- painter->setPen(QPen(QColor(189, 189, 189)));
- //FIXME: It looks like Qt is passing us a rectangle that's too small
- //This deliberately draws outside the lines, and we need to find a better solution.
- int correctionAmount = groupCornerRadius_ > 0 ? 0 : 1;
- QRect region(QPoint(option.rect.left() - correctionAmount, option.rect.top()), QSize(option.rect.width() + correctionAmount, option.rect.height() - common_.verticalMargin));
- QLinearGradient fillGradient(region.topLeft(), region.bottomLeft());
- fillGradient.setColorAt(0, QColor(244, 244, 244));
- fillGradient.setColorAt(0.1, QColor(231, 231, 231));
- fillGradient.setColorAt(1, QColor(209, 209, 209));
-
- QBrush backgroundBrush = QBrush(fillGradient);
- QPainterPath fillPath;
- fillPath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
- QPainterPath linePath;
- linePath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
- painter->fillPath(fillPath, backgroundBrush);
- painter->drawPath(linePath);
-
- int triangleHorizontalOffset = 1;
- int triangleWidth = 9;
- int triangleHeight = 5;
- paintExpansionTriangle(painter, region.adjusted(common_.horizontalMargin + triangleHorizontalOffset + 1, 0, 0, 0), triangleWidth, triangleHeight, expanded);
-
- int textLeftOffset = 3 * common_.horizontalMargin + 1 + triangleWidth + triangleHorizontalOffset;
- QFontMetrics fontMetrics(groupFont_);
- int textTopOffset = (region.height() - fontMetrics.height()) / 2;
- painter->setFont(groupFont_);
- int contactCountWidth = 0;
- QRect textRect = region.adjusted(textLeftOffset, textTopOffset, -1 * textLeftOffset, -1 * textTopOffset);
-
- if (!expanded) {
- QFontMetrics groupMetrics(groupFont_);
- int contactCount = rowCount;
- QString countString = QString("%1").arg(contactCount);
- contactCountWidth = groupMetrics.width(countString) + 2 * common_.horizontalMargin;
- int offsetAmount = textRect.width() - contactCountWidth + common_.horizontalMargin;
- QRect countRect = textRect.adjusted(offsetAmount, 0, 0/*-1 * offsetAmount*/, 0);
- paintShadowText(painter, countRect, countString);
- }
- QRect nameTextRect = expanded ? textRect : textRect.adjusted(0, 0, -contactCountWidth, 0);
- QString elidedName = fontMetrics.elidedText(name, Qt::ElideRight, nameTextRect.width(), Qt::TextShowMnemonic);
- paintShadowText(painter, nameTextRect, elidedName);
- painter->restore();
+ painter->save();
+ painter->setPen(QPen(QColor(189, 189, 189)));
+ //FIXME: It looks like Qt is passing us a rectangle that's too small
+ //This deliberately draws outside the lines, and we need to find a better solution.
+ int correctionAmount = groupCornerRadius_ > 0 ? 0 : 1;
+ QRect region(QPoint(option.rect.left() - correctionAmount, option.rect.top()), QSize(option.rect.width() + correctionAmount, option.rect.height() - common_.verticalMargin));
+ QLinearGradient fillGradient(region.topLeft(), region.bottomLeft());
+ fillGradient.setColorAt(0, QColor(244, 244, 244));
+ fillGradient.setColorAt(0.1, QColor(231, 231, 231));
+ fillGradient.setColorAt(1, QColor(209, 209, 209));
+
+ QBrush backgroundBrush = QBrush(fillGradient);
+ QPainterPath fillPath;
+ fillPath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
+ QPainterPath linePath;
+ linePath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
+ painter->fillPath(fillPath, backgroundBrush);
+ painter->drawPath(linePath);
+
+ int triangleHorizontalOffset = 1;
+ int triangleWidth = 9;
+ int triangleHeight = 5;
+ paintExpansionTriangle(painter, region.adjusted(common_.horizontalMargin + triangleHorizontalOffset + 1, 0, 0, 0), triangleWidth, triangleHeight, expanded);
+
+ int textLeftOffset = 3 * common_.horizontalMargin + 1 + triangleWidth + triangleHorizontalOffset;
+ QFontMetrics fontMetrics(groupFont_);
+ int textTopOffset = (region.height() - fontMetrics.height()) / 2;
+ painter->setFont(groupFont_);
+ int contactCountWidth = 0;
+ QRect textRect = region.adjusted(textLeftOffset, textTopOffset, -1 * textLeftOffset, -1 * textTopOffset);
+
+ if (!expanded) {
+ QFontMetrics groupMetrics(groupFont_);
+ int contactCount = rowCount;
+ QString countString = QString("%1").arg(contactCount);
+ contactCountWidth = groupMetrics.width(countString) + 2 * common_.horizontalMargin;
+ int offsetAmount = textRect.width() - contactCountWidth + common_.horizontalMargin;
+ QRect countRect = textRect.adjusted(offsetAmount, 0, 0/*-1 * offsetAmount*/, 0);
+ paintShadowText(painter, countRect, countString);
+ }
+ QRect nameTextRect = expanded ? textRect : textRect.adjusted(0, 0, -contactCountWidth, 0);
+ QString elidedName = fontMetrics.elidedText(name, Qt::ElideRight, nameTextRect.width(), Qt::TextShowMnemonic);
+ paintShadowText(painter, nameTextRect, elidedName);
+ painter->restore();
}
void GroupItemDelegate::paintExpansionTriangle(QPainter* painter, const QRect& region, int width, int height, bool expanded) const {
- // height is the height of the downward pointing triangle
- QPolygonF triangle;
- if (expanded) {
- QPointF triangleTopLeft(region.left(), region.top() + region.height() / 2 - height / 2);
- triangle << triangleTopLeft;
- triangle << triangleTopLeft + QPointF(width, 0);
- triangle << triangleTopLeft + QPointF(width / 2, height);
- // The expanded triangle should be a little lower, because its pointy shape makes it feel
- // as if it's too high.
- triangle.translate(QPointF(0,1));
- }
- else {
- QPointF triangleTopLeft(region.left() + ((width - height) / 2), region.top() + region.height() / 2 - width / 2);
- triangle << triangleTopLeft;
- triangle << triangleTopLeft + QPointF(height, width / 2);
- triangle << triangleTopLeft + QPointF(0, width);
- }
- //qDebug() << "Painting triangle: " << triangle;
-
- QPolygonF triangleShadow(triangle);
- triangleShadow.translate(QPointF(0, -1));
-
- QPainterPath trianglePath;
- QPainterPath triangleShadowPath;
- QBrush triangleBrush(QColor(110, 110, 110));
- QBrush triangleShadowBrush(QColor(47, 47, 47));
- trianglePath.addPolygon(triangle);
- triangleShadowPath.addPolygon(triangleShadow);
- painter->fillPath(triangleShadowPath, triangleShadowBrush);
- painter->fillPath(trianglePath, triangleBrush);
+ // height is the height of the downward pointing triangle
+ QPolygonF triangle;
+ if (expanded) {
+ QPointF triangleTopLeft(region.left(), region.top() + region.height() / 2 - height / 2);
+ triangle << triangleTopLeft;
+ triangle << triangleTopLeft + QPointF(width, 0);
+ triangle << triangleTopLeft + QPointF(width / 2, height);
+ // The expanded triangle should be a little lower, because its pointy shape makes it feel
+ // as if it's too high.
+ triangle.translate(QPointF(0,1));
+ }
+ else {
+ QPointF triangleTopLeft(region.left() + ((width - height) / 2), region.top() + region.height() / 2 - width / 2);
+ triangle << triangleTopLeft;
+ triangle << triangleTopLeft + QPointF(height, width / 2);
+ triangle << triangleTopLeft + QPointF(0, width);
+ }
+ //qDebug() << "Painting triangle: " << triangle;
+
+ QPolygonF triangleShadow(triangle);
+ triangleShadow.translate(QPointF(0, -1));
+
+ QPainterPath trianglePath;
+ QPainterPath triangleShadowPath;
+ QBrush triangleBrush(QColor(110, 110, 110));
+ QBrush triangleShadowBrush(QColor(47, 47, 47));
+ trianglePath.addPolygon(triangle);
+ triangleShadowPath.addPolygon(triangleShadow);
+ painter->fillPath(triangleShadowPath, triangleShadowBrush);
+ painter->fillPath(trianglePath, triangleBrush);
}
void GroupItemDelegate::paintShadowText(QPainter* painter, const QRect& region, const QString& text) const {
- painter->setPen(QPen(QColor(254, 254, 254)));
- painter->drawText(region.adjusted(0, 1, 0, 0), Qt::AlignTop, text);
- painter->setPen(QPen(QColor(115, 115, 115)));
- painter->drawText(region, Qt::AlignTop, text);
+ painter->setPen(QPen(QColor(254, 254, 254)));
+ painter->drawText(region.adjusted(0, 1, 0, 0), Qt::AlignTop, text);
+ painter->setPen(QPen(QColor(115, 115, 115)));
+ painter->drawText(region, Qt::AlignTop, text);
}
const int GroupItemDelegate::groupCornerRadius_ = 0;
diff --git a/Swift/QtUI/Roster/GroupItemDelegate.h b/Swift/QtUI/Roster/GroupItemDelegate.h
index c279c79..f989ed0 100644
--- a/Swift/QtUI/Roster/GroupItemDelegate.h
+++ b/Swift/QtUI/Roster/GroupItemDelegate.h
@@ -13,17 +13,17 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class QtTreeWidgetItem;
- class GroupItemDelegate {
- public:
- GroupItemDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QString& name, int rowCount, bool expanded) const;
- private:
- void paintShadowText(QPainter* painter, const QRect& region, const QString& text) const;
- void paintExpansionTriangle(QPainter* painter, const QRect& region, int width, int height, bool expanded) const;
- QFont groupFont_;
- static const int groupCornerRadius_;
- DelegateCommons common_;
- };
+ class QtTreeWidgetItem;
+ class GroupItemDelegate {
+ public:
+ GroupItemDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QString& name, int rowCount, bool expanded) const;
+ private:
+ void paintShadowText(QPainter* painter, const QRect& region, const QString& text) const;
+ void paintExpansionTriangle(QPainter* painter, const QRect& region, int width, int height, bool expanded) const;
+ QFont groupFont_;
+ static const int groupCornerRadius_;
+ DelegateCommons common_;
+ };
}
diff --git a/Swift/QtUI/Roster/QtFilterWidget.cpp b/Swift/QtUI/Roster/QtFilterWidget.cpp
index 24be214..60b87df 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.cpp
+++ b/Swift/QtUI/Roster/QtFilterWidget.cpp
@@ -27,24 +27,24 @@
namespace Swift {
QtFilterWidget::QtFilterWidget(QWidget* parent, QtTreeWidget* treeView, UIEventStream* eventStream, QBoxLayout* layout) : QWidget(parent), treeView_(treeView), eventStream_(eventStream), fuzzyRosterFilter_(0), isModifierSinglePressed_(false) {
- int targetIndex = layout->indexOf(treeView);
+ int targetIndex = layout->indexOf(treeView);
- QVBoxLayout* vboxLayout = new QVBoxLayout(this);
- vboxLayout->setSpacing(0);
- vboxLayout->setContentsMargins(0,0,0,0);
+ QVBoxLayout* vboxLayout = new QVBoxLayout(this);
+ vboxLayout->setSpacing(0);
+ vboxLayout->setContentsMargins(0,0,0,0);
- filterLineEdit_ = new QtClosableLineEdit(this);
- filterLineEdit_->hide();
- vboxLayout->addWidget(filterLineEdit_);
+ filterLineEdit_ = new QtClosableLineEdit(this);
+ filterLineEdit_->hide();
+ vboxLayout->addWidget(filterLineEdit_);
- vboxLayout->addWidget(treeView);
- setLayout(vboxLayout);
- layout->insertWidget(targetIndex, this);
+ vboxLayout->addWidget(treeView);
+ setLayout(vboxLayout);
+ layout->insertWidget(targetIndex, this);
- filterLineEdit_->installEventFilter(this);
- treeView->installEventFilter(this);
+ filterLineEdit_->installEventFilter(this);
+ treeView->installEventFilter(this);
- sourceModel_ = treeView_->model();
+ sourceModel_ = treeView_->model();
}
QtFilterWidget::~QtFilterWidget() {
@@ -52,118 +52,118 @@ QtFilterWidget::~QtFilterWidget() {
}
bool QtFilterWidget::eventFilter(QObject*, QEvent* event) {
- if (event->type() == QEvent::KeyPress ||
- event->type() == QEvent::KeyRelease ||
- // InputMethodQuery got introduced in Qt 5.
+ if (event->type() == QEvent::KeyPress ||
+ event->type() == QEvent::KeyRelease ||
+ // InputMethodQuery got introduced in Qt 5.
#if QT_VERSION >= 0x050000
- event->type() == QEvent::InputMethodQuery ||
+ event->type() == QEvent::InputMethodQuery ||
#endif
- event->type() == QEvent::InputMethod) {
- event->ignore();
- QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
- if (keyEvent) {
- if (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down) {
- return false;
- } else if ((keyEvent->key() == Qt::Key_Left || keyEvent->key() == Qt::Key_Right) && filterLineEdit_->text().isEmpty()) {
- return false;
- } else if (keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyPress) {
- isModifierSinglePressed_ = true;
- } else if ((keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyRelease && isModifierSinglePressed_)
- || (keyEvent->key() == Qt::Key_Menu)) {
- QPoint itemOffset(2,2);
- QPoint contextMenuPosition = treeView_->visualRect(treeView_->currentIndex()).topLeft() + itemOffset;;
- QApplication::postEvent(treeView_, new QContextMenuEvent(QContextMenuEvent::Keyboard, contextMenuPosition, treeView_->mapToGlobal(contextMenuPosition)));
- return true;
- } else if (keyEvent->key() == Qt::Key_Return) {
- JID target = treeView_->selectedJID();
- if (target.isValid()) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(target)));
- }
- filterLineEdit_->setText("");
- updateRosterFilters();
- } else if (keyEvent->key() == Qt::Key_Escape) {
- filterLineEdit_->setText("");
- } else {
- isModifierSinglePressed_ = false;
- }
- }
-
- filterLineEdit_->event(event);
-
- if (event->type() == QEvent::KeyRelease) {
- updateRosterFilters();
- }
- return true;
- }
- return false;
+ event->type() == QEvent::InputMethod) {
+ event->ignore();
+ QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
+ if (keyEvent) {
+ if (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down) {
+ return false;
+ } else if ((keyEvent->key() == Qt::Key_Left || keyEvent->key() == Qt::Key_Right) && filterLineEdit_->text().isEmpty()) {
+ return false;
+ } else if (keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyPress) {
+ isModifierSinglePressed_ = true;
+ } else if ((keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyRelease && isModifierSinglePressed_)
+ || (keyEvent->key() == Qt::Key_Menu)) {
+ QPoint itemOffset(2,2);
+ QPoint contextMenuPosition = treeView_->visualRect(treeView_->currentIndex()).topLeft() + itemOffset;;
+ QApplication::postEvent(treeView_, new QContextMenuEvent(QContextMenuEvent::Keyboard, contextMenuPosition, treeView_->mapToGlobal(contextMenuPosition)));
+ return true;
+ } else if (keyEvent->key() == Qt::Key_Return) {
+ JID target = treeView_->selectedJID();
+ if (target.isValid()) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(target)));
+ }
+ filterLineEdit_->setText("");
+ updateRosterFilters();
+ } else if (keyEvent->key() == Qt::Key_Escape) {
+ filterLineEdit_->setText("");
+ } else {
+ isModifierSinglePressed_ = false;
+ }
+ }
+
+ filterLineEdit_->event(event);
+
+ if (event->type() == QEvent::KeyRelease) {
+ updateRosterFilters();
+ }
+ return true;
+ }
+ return false;
}
void QtFilterWidget::popAllFilters() {
- std::vector<RosterFilter*> filters = treeView_->getRoster()->getFilters();
- foreach(RosterFilter* filter, filters) {
- filters_.push_back(filter);
- treeView_->getRoster()->removeFilter(filter);
- }
- treeView_->getRoster()->onFilterAdded.connect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
- treeView_->getRoster()->onFilterRemoved.connect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
+ std::vector<RosterFilter*> filters = treeView_->getRoster()->getFilters();
+ foreach(RosterFilter* filter, filters) {
+ filters_.push_back(filter);
+ treeView_->getRoster()->removeFilter(filter);
+ }
+ treeView_->getRoster()->onFilterAdded.connect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
+ treeView_->getRoster()->onFilterRemoved.connect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
}
void QtFilterWidget::pushAllFilters() {
- treeView_->getRoster()->onFilterAdded.disconnect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
- treeView_->getRoster()->onFilterRemoved.disconnect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
- foreach(RosterFilter* filter, filters_) {
- treeView_->getRoster()->addFilter(filter);
- }
- filters_.clear();
+ treeView_->getRoster()->onFilterAdded.disconnect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
+ treeView_->getRoster()->onFilterRemoved.disconnect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
+ foreach(RosterFilter* filter, filters_) {
+ treeView_->getRoster()->addFilter(filter);
+ }
+ filters_.clear();
}
void QtFilterWidget::updateRosterFilters() {
- if (fuzzyRosterFilter_) {
- if (filterLineEdit_->text().isEmpty()) {
- // remove currently installed search filter and put old filters back
- treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
- delete fuzzyRosterFilter_;
- fuzzyRosterFilter_ = NULL;
- pushAllFilters();
- } else {
- // remove currently intsalled search filter and put new search filter in place
- updateSearchFilter();
- }
- } else {
- if (!filterLineEdit_->text().isEmpty()) {
- // remove currently installed filters and put a search filter in place
- popAllFilters();
- updateSearchFilter();
- }
- }
- filterLineEdit_->setVisible(!filterLineEdit_->text().isEmpty());
+ if (fuzzyRosterFilter_) {
+ if (filterLineEdit_->text().isEmpty()) {
+ // remove currently installed search filter and put old filters back
+ treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
+ delete fuzzyRosterFilter_;
+ fuzzyRosterFilter_ = NULL;
+ pushAllFilters();
+ } else {
+ // remove currently intsalled search filter and put new search filter in place
+ updateSearchFilter();
+ }
+ } else {
+ if (!filterLineEdit_->text().isEmpty()) {
+ // remove currently installed filters and put a search filter in place
+ popAllFilters();
+ updateSearchFilter();
+ }
+ }
+ filterLineEdit_->setVisible(!filterLineEdit_->text().isEmpty());
}
void QtFilterWidget::updateSearchFilter() {
- if (fuzzyRosterFilter_) {
- treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
- delete fuzzyRosterFilter_;
- fuzzyRosterFilter_ = NULL;
- }
- fuzzyRosterFilter_ = new FuzzyRosterFilter(Q2PSTRING(filterLineEdit_->text()));
- treeView_->getRoster()->addFilter(fuzzyRosterFilter_);
- treeView_->setCurrentIndex(sourceModel_->index(0, 0, sourceModel_->index(0,0)));
+ if (fuzzyRosterFilter_) {
+ treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
+ delete fuzzyRosterFilter_;
+ fuzzyRosterFilter_ = NULL;
+ }
+ fuzzyRosterFilter_ = new FuzzyRosterFilter(Q2PSTRING(filterLineEdit_->text()));
+ treeView_->getRoster()->addFilter(fuzzyRosterFilter_);
+ treeView_->setCurrentIndex(sourceModel_->index(0, 0, sourceModel_->index(0,0)));
}
void QtFilterWidget::handleFilterAdded(RosterFilter* filter) {
- if (filter != fuzzyRosterFilter_) {
- filterLineEdit_->setText("");
- updateRosterFilters();
- }
+ if (filter != fuzzyRosterFilter_) {
+ filterLineEdit_->setText("");
+ updateRosterFilters();
+ }
}
void QtFilterWidget::handleFilterRemoved(RosterFilter* filter) {
- /* make sure we don't end up adding this one back in later */
- filters_.erase(std::remove(filters_.begin(), filters_.end(), filter), filters_.end());
- if (filter != fuzzyRosterFilter_) {
- filterLineEdit_->setText("");
- updateRosterFilters();
- }
+ /* make sure we don't end up adding this one back in later */
+ filters_.erase(std::remove(filters_.begin(), filters_.end(), filter), filters_.end());
+ if (filter != fuzzyRosterFilter_) {
+ filterLineEdit_->setText("");
+ updateRosterFilters();
+ }
}
}
diff --git a/Swift/QtUI/Roster/QtFilterWidget.h b/Swift/QtUI/Roster/QtFilterWidget.h
index 314aec2..5edcc5b 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.h
+++ b/Swift/QtUI/Roster/QtFilterWidget.h
@@ -26,32 +26,32 @@ namespace Swift {
class UIEventStream;
class QtClosableLineEdit;
class QtFilterWidget : public QWidget {
- Q_OBJECT
- public:
- QtFilterWidget(QWidget* parent, QtTreeWidget* treeView, UIEventStream* eventStream, QBoxLayout* layout = 0);
- virtual ~QtFilterWidget();
-
- protected:
- bool eventFilter(QObject*, QEvent* event);
-
- private:
- void popAllFilters();
- void pushAllFilters();
-
- void updateRosterFilters();
- void updateSearchFilter();
-
- void handleFilterAdded(RosterFilter* filter);
- void handleFilterRemoved(RosterFilter* filter);
-
- private:
- QtClosableLineEdit* filterLineEdit_;
- QtTreeWidget* treeView_;
- UIEventStream* eventStream_;
- std::vector<RosterFilter*> filters_;
- QAbstractItemModel* sourceModel_;
- FuzzyRosterFilter* fuzzyRosterFilter_;
- bool isModifierSinglePressed_;
+ Q_OBJECT
+ public:
+ QtFilterWidget(QWidget* parent, QtTreeWidget* treeView, UIEventStream* eventStream, QBoxLayout* layout = 0);
+ virtual ~QtFilterWidget();
+
+ protected:
+ bool eventFilter(QObject*, QEvent* event);
+
+ private:
+ void popAllFilters();
+ void pushAllFilters();
+
+ void updateRosterFilters();
+ void updateSearchFilter();
+
+ void handleFilterAdded(RosterFilter* filter);
+ void handleFilterRemoved(RosterFilter* filter);
+
+ private:
+ QtClosableLineEdit* filterLineEdit_;
+ QtTreeWidget* treeView_;
+ UIEventStream* eventStream_;
+ std::vector<RosterFilter*> filters_;
+ QAbstractItemModel* sourceModel_;
+ FuzzyRosterFilter* fuzzyRosterFilter_;
+ bool isModifierSinglePressed_;
};
}
diff --git a/Swift/QtUI/Roster/QtOccupantListWidget.cpp b/Swift/QtUI/Roster/QtOccupantListWidget.cpp
index 1eefd56..03c14fd 100644
--- a/Swift/QtUI/Roster/QtOccupantListWidget.cpp
+++ b/Swift/QtUI/Roster/QtOccupantListWidget.cpp
@@ -29,47 +29,47 @@ QtOccupantListWidget::~QtOccupantListWidget() {
}
void QtOccupantListWidget::setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions) {
- availableOccupantActions_ = actions;
+ availableOccupantActions_ = actions;
}
void QtOccupantListWidget::contextMenuEvent(QContextMenuEvent* event) {
- QModelIndex index = indexAt(event->pos());
- if (!index.isValid()) {
- return;
- }
+ QModelIndex index = indexAt(event->pos());
+ if (!index.isValid()) {
+ return;
+ }
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact) {
- onSomethingSelectedChanged(contact);
- QMenu contextMenu;
- if (availableOccupantActions_.empty()) {
- QAction* noAction = contextMenu.addAction(tr("No actions for this user"));
- noAction->setEnabled(false);
- contextMenu.exec(event->globalPos());
- }
- else {
- std::map<QAction*, ChatWindow::OccupantAction> actions;
- foreach (ChatWindow::OccupantAction availableAction, availableOccupantActions_) {
- QString text = "Error: missing string";
- switch (availableAction) {
- case ChatWindow::Kick: text = tr("Kick user"); break;
- case ChatWindow::Ban: text = tr("Kick and ban user"); break;
- case ChatWindow::MakeModerator: text = tr("Make moderator"); break;
- case ChatWindow::MakeParticipant: text = tr("Make participant"); break;
- case ChatWindow::MakeVisitor: text = tr("Remove voice"); break;
- case ChatWindow::AddContact: text = tr("Add to contacts"); break;
- case ChatWindow::ShowProfile: text = tr("Show profile"); break;
- }
- QAction* action = contextMenu.addAction(text);
- actions[action] = availableAction;
- }
- QAction* result = contextMenu.exec(event->globalPos());
- if (result) {
- onOccupantActionSelected(actions[result], contact);
- }
- }
- }
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact) {
+ onSomethingSelectedChanged(contact);
+ QMenu contextMenu;
+ if (availableOccupantActions_.empty()) {
+ QAction* noAction = contextMenu.addAction(tr("No actions for this user"));
+ noAction->setEnabled(false);
+ contextMenu.exec(event->globalPos());
+ }
+ else {
+ std::map<QAction*, ChatWindow::OccupantAction> actions;
+ foreach (ChatWindow::OccupantAction availableAction, availableOccupantActions_) {
+ QString text = "Error: missing string";
+ switch (availableAction) {
+ case ChatWindow::Kick: text = tr("Kick user"); break;
+ case ChatWindow::Ban: text = tr("Kick and ban user"); break;
+ case ChatWindow::MakeModerator: text = tr("Make moderator"); break;
+ case ChatWindow::MakeParticipant: text = tr("Make participant"); break;
+ case ChatWindow::MakeVisitor: text = tr("Remove voice"); break;
+ case ChatWindow::AddContact: text = tr("Add to contacts"); break;
+ case ChatWindow::ShowProfile: text = tr("Show profile"); break;
+ }
+ QAction* action = contextMenu.addAction(text);
+ actions[action] = availableAction;
+ }
+ QAction* result = contextMenu.exec(event->globalPos());
+ if (result) {
+ onOccupantActionSelected(actions[result], contact);
+ }
+ }
+ }
}
}
diff --git a/Swift/QtUI/Roster/QtOccupantListWidget.h b/Swift/QtUI/Roster/QtOccupantListWidget.h
index d433d07..4cff50f 100644
--- a/Swift/QtUI/Roster/QtOccupantListWidget.h
+++ b/Swift/QtUI/Roster/QtOccupantListWidget.h
@@ -16,16 +16,16 @@ namespace Swift {
class SettingsProvider;
class QtOccupantListWidget : public QtTreeWidget {
- Q_OBJECT
- public:
- QtOccupantListWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget privateMessageTarget, QWidget* parent = NULL);
- virtual ~QtOccupantListWidget();
- void setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions);
- boost::signal<void (ChatWindow::OccupantAction, ContactRosterItem*)> onOccupantActionSelected;
- protected:
- void contextMenuEvent(QContextMenuEvent* event);
- private:
- std::vector<ChatWindow::OccupantAction> availableOccupantActions_;
+ Q_OBJECT
+ public:
+ QtOccupantListWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget privateMessageTarget, QWidget* parent = NULL);
+ virtual ~QtOccupantListWidget();
+ void setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions);
+ boost::signal<void (ChatWindow::OccupantAction, ContactRosterItem*)> onOccupantActionSelected;
+ protected:
+ void contextMenuEvent(QContextMenuEvent* event);
+ private:
+ std::vector<ChatWindow::OccupantAction> availableOccupantActions_;
};
}
diff --git a/Swift/QtUI/Roster/QtRosterWidget.cpp b/Swift/QtUI/Roster/QtRosterWidget.cpp
index 469fa83..027ff00 100644
--- a/Swift/QtUI/Roster/QtRosterWidget.cpp
+++ b/Swift/QtUI/Roster/QtRosterWidget.cpp
@@ -38,125 +38,125 @@ QtRosterWidget::~QtRosterWidget() {
}
void QtRosterWidget::handleEditUserActionTriggered(bool /*checked*/) {
- QModelIndexList selectedIndexList = getSelectedIndexes();
- if (selectedIndexList.empty()) {
- return;
- }
- QModelIndex index = selectedIndexList[0];
- if (!index.isValid()) {
- return;
- }
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
- }
+ QModelIndexList selectedIndexList = getSelectedIndexes();
+ if (selectedIndexList.empty()) {
+ return;
+ }
+ QModelIndex index = selectedIndexList[0];
+ if (!index.isValid()) {
+ return;
+ }
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
+ }
}
void QtRosterWidget::contextMenuEvent(QContextMenuEvent* event) {
- QModelIndex index = indexAt(event->pos());
- if (!index.isValid()) {
- return;
- }
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- QMenu contextMenu;
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- QAction* editContact = contextMenu.addAction(tr("Edit…"));
- editContact->setEnabled(isOnline());
- QAction* removeContact = contextMenu.addAction(tr("Remove"));
- removeContact->setEnabled(isOnline());
- QAction* showProfileForContact = contextMenu.addAction(tr("Show Profile"));
-
- QAction* unblockContact = NULL;
- if (contact->blockState() == ContactRosterItem::IsBlocked ||
- contact->blockState() == ContactRosterItem::IsDomainBlocked) {
- unblockContact = contextMenu.addAction(tr("Unblock"));
- unblockContact->setEnabled(isOnline());
- }
-
- QAction* blockContact = NULL;
- if (contact->blockState() == ContactRosterItem::IsUnblocked) {
- blockContact = contextMenu.addAction(tr("Block"));
- blockContact->setEnabled(isOnline());
- }
+ QModelIndex index = indexAt(event->pos());
+ if (!index.isValid()) {
+ return;
+ }
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ QMenu contextMenu;
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ QAction* editContact = contextMenu.addAction(tr("Edit…"));
+ editContact->setEnabled(isOnline());
+ QAction* removeContact = contextMenu.addAction(tr("Remove"));
+ removeContact->setEnabled(isOnline());
+ QAction* showProfileForContact = contextMenu.addAction(tr("Show Profile"));
+
+ QAction* unblockContact = NULL;
+ if (contact->blockState() == ContactRosterItem::IsBlocked ||
+ contact->blockState() == ContactRosterItem::IsDomainBlocked) {
+ unblockContact = contextMenu.addAction(tr("Unblock"));
+ unblockContact->setEnabled(isOnline());
+ }
+
+ QAction* blockContact = NULL;
+ if (contact->blockState() == ContactRosterItem::IsUnblocked) {
+ blockContact = contextMenu.addAction(tr("Block"));
+ blockContact->setEnabled(isOnline());
+ }
#ifdef SWIFT_EXPERIMENTAL_FT
- QAction* sendFile = NULL;
- if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
- sendFile = contextMenu.addAction(tr("Send File"));
- sendFile->setEnabled(isOnline());
- }
+ QAction* sendFile = NULL;
+ if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
+ sendFile = contextMenu.addAction(tr("Send File"));
+ sendFile->setEnabled(isOnline());
+ }
#endif
#ifdef SWIFT_EXPERIMENTAL_WB
- QAction* startWhiteboardChat = NULL;
- if (contact->supportsFeature(ContactRosterItem::WhiteboardFeature)) {
- startWhiteboardChat = contextMenu.addAction(tr("Start Whiteboard Chat"));
- startWhiteboardChat->setEnabled(isOnline());
- }
+ QAction* startWhiteboardChat = NULL;
+ if (contact->supportsFeature(ContactRosterItem::WhiteboardFeature)) {
+ startWhiteboardChat = contextMenu.addAction(tr("Start Whiteboard Chat"));
+ startWhiteboardChat->setEnabled(isOnline());
+ }
#endif
- QAction* result = contextMenu.exec(event->globalPos());
- if (result == editContact) {
- eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
- }
- else if (result == removeContact) {
- if (QtContactEditWindow::confirmContactDeletion(contact->getJID())) {
- eventStream_->send(boost::make_shared<RemoveRosterItemUIEvent>(contact->getJID()));
- }
- }
- else if (result == showProfileForContact) {
- eventStream_->send(boost::make_shared<ShowProfileForRosterItemUIEvent>(contact->getJID()));
- }
- else if (unblockContact && result == unblockContact) {
- if (contact->blockState() == ContactRosterItem::IsDomainBlocked) {
- QMessageBox messageBox(QMessageBox::Question, tr("Swift"), tr("%2 is currently blocked because of a block on all users of the %1 service.\n %2 cannot be unblocked individually; do you want to unblock all %1 users?").arg(P2QSTRING(contact->getJID().getDomain()), P2QSTRING(contact->getJID().toString())), QMessageBox::NoButton, this);
- QPushButton* unblockDomainButton = messageBox.addButton(tr("Unblock %1 domain").arg(P2QSTRING(contact->getJID().getDomain())), QMessageBox::AcceptRole);
- messageBox.addButton(QMessageBox::Abort);
-
- messageBox.exec();
- if (messageBox.clickedButton() == unblockDomainButton) {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID().getDomain()));
- }
- } else {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID()));
- }
- }
- else if (blockContact && result == blockContact) {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, contact->getJID()));
- }
+ QAction* result = contextMenu.exec(event->globalPos());
+ if (result == editContact) {
+ eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
+ }
+ else if (result == removeContact) {
+ if (QtContactEditWindow::confirmContactDeletion(contact->getJID())) {
+ eventStream_->send(boost::make_shared<RemoveRosterItemUIEvent>(contact->getJID()));
+ }
+ }
+ else if (result == showProfileForContact) {
+ eventStream_->send(boost::make_shared<ShowProfileForRosterItemUIEvent>(contact->getJID()));
+ }
+ else if (unblockContact && result == unblockContact) {
+ if (contact->blockState() == ContactRosterItem::IsDomainBlocked) {
+ QMessageBox messageBox(QMessageBox::Question, tr("Swift"), tr("%2 is currently blocked because of a block on all users of the %1 service.\n %2 cannot be unblocked individually; do you want to unblock all %1 users?").arg(P2QSTRING(contact->getJID().getDomain()), P2QSTRING(contact->getJID().toString())), QMessageBox::NoButton, this);
+ QPushButton* unblockDomainButton = messageBox.addButton(tr("Unblock %1 domain").arg(P2QSTRING(contact->getJID().getDomain())), QMessageBox::AcceptRole);
+ messageBox.addButton(QMessageBox::Abort);
+
+ messageBox.exec();
+ if (messageBox.clickedButton() == unblockDomainButton) {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID().getDomain()));
+ }
+ } else {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID()));
+ }
+ }
+ else if (blockContact && result == blockContact) {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, contact->getJID()));
+ }
#ifdef SWIFT_EXPERIMENTAL_FT
- else if (sendFile && result == sendFile) {
- QString fileName = QFileDialog::getOpenFileName(this, tr("Send File"), "", tr("All Files (*);;"));
- if (!fileName.isEmpty()) {
- eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(fileName)));
- }
- }
+ else if (sendFile && result == sendFile) {
+ QString fileName = QFileDialog::getOpenFileName(this, tr("Send File"), "", tr("All Files (*);;"));
+ if (!fileName.isEmpty()) {
+ eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(fileName)));
+ }
+ }
#endif
#ifdef SWIFT_EXPERIMENTAL_WB
- else if (startWhiteboardChat && result == startWhiteboardChat) {
- eventStream_->send(boost::make_shared<RequestWhiteboardUIEvent>(contact->getJID()));
- }
+ else if (startWhiteboardChat && result == startWhiteboardChat) {
+ eventStream_->send(boost::make_shared<RequestWhiteboardUIEvent>(contact->getJID()));
+ }
#endif
- }
- else if (GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item)) {
- QAction* renameGroupAction = contextMenu.addAction(tr("Rename"));
- if (P2QSTRING(group->getDisplayName()) == tr("Contacts")) {
- renameGroupAction->setEnabled(false);
- }
- else {
- renameGroupAction->setEnabled(isOnline());
- }
- QAction* result = contextMenu.exec(event->globalPos());
- if (result == renameGroupAction) {
- renameGroup(group);
- }
- }
+ }
+ else if (GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item)) {
+ QAction* renameGroupAction = contextMenu.addAction(tr("Rename"));
+ if (P2QSTRING(group->getDisplayName()) == tr("Contacts")) {
+ renameGroupAction->setEnabled(false);
+ }
+ else {
+ renameGroupAction->setEnabled(isOnline());
+ }
+ QAction* result = contextMenu.exec(event->globalPos());
+ if (result == renameGroupAction) {
+ renameGroup(group);
+ }
+ }
}
void QtRosterWidget::renameGroup(GroupRosterItem* group) {
- bool ok;
- QString newName = QInputDialog::getText(NULL, tr("Rename group"), tr("Enter a new name for group '%1':").arg(P2QSTRING(group->getDisplayName())), QLineEdit::Normal, P2QSTRING(group->getDisplayName()), &ok);
- if (ok) {
- eventStream_->send(boost::make_shared<RenameGroupUIEvent>(group->getDisplayName(), Q2PSTRING(newName)));
- }
+ bool ok;
+ QString newName = QInputDialog::getText(NULL, tr("Rename group"), tr("Enter a new name for group '%1':").arg(P2QSTRING(group->getDisplayName())), QLineEdit::Normal, P2QSTRING(group->getDisplayName()), &ok);
+ if (ok) {
+ eventStream_->send(boost::make_shared<RenameGroupUIEvent>(group->getDisplayName(), Q2PSTRING(newName)));
+ }
}
}
diff --git a/Swift/QtUI/Roster/QtRosterWidget.h b/Swift/QtUI/Roster/QtRosterWidget.h
index de5ee9b..25f7f9d 100644
--- a/Swift/QtUI/Roster/QtRosterWidget.h
+++ b/Swift/QtUI/Roster/QtRosterWidget.h
@@ -12,16 +12,16 @@ namespace Swift {
class QtUIPreferences;
class QtRosterWidget : public QtTreeWidget {
- Q_OBJECT
- public:
- QtRosterWidget(UIEventStream* eventStream, SettingsProvider* settings, QWidget* parent = 0);
- virtual ~QtRosterWidget();
- public slots:
- void handleEditUserActionTriggered(bool checked);
- protected:
- void contextMenuEvent(QContextMenuEvent* event);
- private:
- void renameGroup(GroupRosterItem* group);
+ Q_OBJECT
+ public:
+ QtRosterWidget(UIEventStream* eventStream, SettingsProvider* settings, QWidget* parent = 0);
+ virtual ~QtRosterWidget();
+ public slots:
+ void handleEditUserActionTriggered(bool checked);
+ protected:
+ void contextMenuEvent(QContextMenuEvent* event);
+ private:
+ void renameGroup(GroupRosterItem* group);
};
}
diff --git a/Swift/QtUI/Roster/QtTreeWidget.cpp b/Swift/QtUI/Roster/QtTreeWidget.cpp
index 277effb..a0b6e92 100644
--- a/Swift/QtUI/Roster/QtTreeWidget.cpp
+++ b/Swift/QtUI/Roster/QtTreeWidget.cpp
@@ -32,232 +32,232 @@
namespace Swift {
QtTreeWidget::QtTreeWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget messageTarget, QWidget* parent) : QTreeView(parent), tooltipShown_(false), messageTarget_(messageTarget) {
- eventStream_ = eventStream;
- settings_ = settings;
- model_ = new RosterModel(this, settings_->getSetting(QtUISettingConstants::USE_SCREENREADER));
- setModel(model_);
- delegate_ = new RosterDelegate(this, settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- setItemDelegate(delegate_);
- setHeaderHidden(true);
+ eventStream_ = eventStream;
+ settings_ = settings;
+ model_ = new RosterModel(this, settings_->getSetting(QtUISettingConstants::USE_SCREENREADER));
+ setModel(model_);
+ delegate_ = new RosterDelegate(this, settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ setItemDelegate(delegate_);
+ setHeaderHidden(true);
#ifdef SWIFT_PLATFORM_MACOSX
- setAlternatingRowColors(true);
+ setAlternatingRowColors(true);
#endif
- setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
- expandAll();
- setAnimated(true);
- setIndentation(0);
+ setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
+ expandAll();
+ setAnimated(true);
+ setIndentation(0);
#ifdef SWIFT_EXPERIMENTAL_FT
- setAcceptDrops(true);
+ setAcceptDrops(true);
#endif
- setDragEnabled(true);
- setRootIsDecorated(true);
- connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
- connect(model_, SIGNAL(itemExpanded(const QModelIndex&, bool)), this, SLOT(handleModelItemExpanded(const QModelIndex&, bool)));
- connect(this, SIGNAL(expanded(const QModelIndex&)), this, SLOT(handleExpanded(const QModelIndex&)));
- connect(this, SIGNAL(collapsed(const QModelIndex&)), this, SLOT(handleCollapsed(const QModelIndex&)));
- connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
-
- settings_->onSettingChanged.connect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
+ setDragEnabled(true);
+ setRootIsDecorated(true);
+ connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
+ connect(model_, SIGNAL(itemExpanded(const QModelIndex&, bool)), this, SLOT(handleModelItemExpanded(const QModelIndex&, bool)));
+ connect(this, SIGNAL(expanded(const QModelIndex&)), this, SLOT(handleExpanded(const QModelIndex&)));
+ connect(this, SIGNAL(collapsed(const QModelIndex&)), this, SLOT(handleCollapsed(const QModelIndex&)));
+ connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
+
+ settings_->onSettingChanged.connect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
}
QtTreeWidget::~QtTreeWidget() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
- delete model_;
- delete delegate_;
+ settings_->onSettingChanged.disconnect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
+ delete model_;
+ delete delegate_;
}
void QtTreeWidget::handleSettingChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- repaint();
- }
+ if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ repaint();
+ }
}
void QtTreeWidget::handleRefreshTooltip() {
- if (tooltipShown_) {
- QPoint position = QCursor::pos();
- QModelIndex index = indexAt(mapFromGlobal(position));
- QToolTip::showText(position, model_->data(index, Qt::ToolTipRole).toString());
- }
+ if (tooltipShown_) {
+ QPoint position = QCursor::pos();
+ QModelIndex index = indexAt(mapFromGlobal(position));
+ QToolTip::showText(position, model_->data(index, Qt::ToolTipRole).toString());
+ }
}
void QtTreeWidget::setRosterModel(Roster* roster) {
- roster_ = roster;
- model_->setRoster(roster);
- expandAll();
+ roster_ = roster;
+ model_->setRoster(roster);
+ expandAll();
}
void QtTreeWidget::refreshTooltip() {
- // Qt needs some time to emit the events we need to detect tooltip's visibility correctly; 20 ms should be enough
- QTimer::singleShot(20, this, SLOT(handleRefreshTooltip()));
+ // Qt needs some time to emit the events we need to detect tooltip's visibility correctly; 20 ms should be enough
+ QTimer::singleShot(20, this, SLOT(handleRefreshTooltip()));
}
QtTreeWidgetItem* QtTreeWidget::getRoot() {
- return treeRoot_;
+ return treeRoot_;
}
void QtTreeWidget::handleClicked(const QModelIndex& index) {
- GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
- if (item) {
- setExpanded(index, !isExpanded(index));
- }
- currentChanged(index, QModelIndex());
+ GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
+ if (item) {
+ setExpanded(index, !isExpanded(index));
+ }
+ currentChanged(index, QModelIndex());
}
QModelIndexList QtTreeWidget::getSelectedIndexes() const {
- // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
- // QModelIndexList destructor.
- // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
- // was resolved by linking against the debug libs, ours isn't, and we're not alone)
- QItemSelection ranges = selectionModel()->selection();
- QModelIndexList selectedIndexList;
- for (int i = 0; i < ranges.count(); ++i) {
- QModelIndex parent = ranges.at(i).parent();
- int right = ranges.at(i).model()->columnCount(parent) - 1;
- if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
- for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
- selectedIndexList.append(ranges.at(i).model()->index(r, 0, parent));
- }
- }
- }
- return selectedIndexList;
+ // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
+ // QModelIndexList destructor.
+ // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
+ // was resolved by linking against the debug libs, ours isn't, and we're not alone)
+ QItemSelection ranges = selectionModel()->selection();
+ QModelIndexList selectedIndexList;
+ for (int i = 0; i < ranges.count(); ++i) {
+ QModelIndex parent = ranges.at(i).parent();
+ int right = ranges.at(i).model()->columnCount(parent) - 1;
+ if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
+ for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
+ selectedIndexList.append(ranges.at(i).model()->index(r, 0, parent));
+ }
+ }
+ }
+ return selectedIndexList;
}
void QtTreeWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous) {
- RosterItem* item = NULL;
- QModelIndexList selectedIndexList = getSelectedIndexes();
- if (selectedIndexList.empty() || !selectedIndexList[0].isValid()) {
- /* I didn't quite understand why using current didn't seem to work here.*/
- }
- else if (current.isValid()) {
- item = static_cast<RosterItem*>(current.internalPointer());
- item = dynamic_cast<ContactRosterItem*>(item);
- }
- onSomethingSelectedChanged(item);
- QTreeView::currentChanged(current, previous);
+ RosterItem* item = NULL;
+ QModelIndexList selectedIndexList = getSelectedIndexes();
+ if (selectedIndexList.empty() || !selectedIndexList[0].isValid()) {
+ /* I didn't quite understand why using current didn't seem to work here.*/
+ }
+ else if (current.isValid()) {
+ item = static_cast<RosterItem*>(current.internalPointer());
+ item = dynamic_cast<ContactRosterItem*>(item);
+ }
+ onSomethingSelectedChanged(item);
+ QTreeView::currentChanged(current, previous);
}
void QtTreeWidget::handleItemActivated(const QModelIndex& index) {
- JID target = jidFromIndex(index);
- if (target.isValid()) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(target)));
- }
+ JID target = jidFromIndex(index);
+ if (target.isValid()) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(target)));
+ }
}
void QtTreeWidget::dragEnterEvent(QDragEnterEvent *event) {
- if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
- event->acceptProposedAction();
- }
+ if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
+ event->acceptProposedAction();
+ }
}
void QtTreeWidget::dropEvent(QDropEvent *event) {
- QModelIndex index = indexAt(event->pos());
- if (index.isValid()) {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
- QString filename = event->mimeData()->urls().at(0).toLocalFile();
- if (!filename.isEmpty()) {
- eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(filename)));
- }
- }
- }
- }
+ QModelIndex index = indexAt(event->pos());
+ if (index.isValid()) {
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
+ QString filename = event->mimeData()->urls().at(0).toLocalFile();
+ if (!filename.isEmpty()) {
+ eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(filename)));
+ }
+ }
+ }
+ }
}
void QtTreeWidget::dragMoveEvent(QDragMoveEvent* event) {
- QModelIndex index = indexAt(event->pos());
- if (index.isValid()) {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
- event->accept();
- return;
- }
- }
- }
- QTreeView::dragMoveEvent(event);
+ QModelIndex index = indexAt(event->pos());
+ if (index.isValid()) {
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
+ event->accept();
+ return;
+ }
+ }
+ }
+ QTreeView::dragMoveEvent(event);
}
bool QtTreeWidget::event(QEvent* event) {
- QChildEvent* childEvent = NULL;
- if ((childEvent = dynamic_cast<QChildEvent*>(event))) {
- if (childEvent->polished()) {
- if (dynamic_cast<QLabel*>(childEvent->child())) {
- tooltipShown_ = true;
- }
- }
- else if (childEvent->removed()) {
- if (childEvent->child()->objectName() == "qtooltip_label") {
- tooltipShown_ = false;
- }
- }
- }
- return QAbstractItemView::event(event);
+ QChildEvent* childEvent = NULL;
+ if ((childEvent = dynamic_cast<QChildEvent*>(event))) {
+ if (childEvent->polished()) {
+ if (dynamic_cast<QLabel*>(childEvent->child())) {
+ tooltipShown_ = true;
+ }
+ }
+ else if (childEvent->removed()) {
+ if (childEvent->child()->objectName() == "qtooltip_label") {
+ tooltipShown_ = false;
+ }
+ }
+ }
+ return QAbstractItemView::event(event);
}
void QtTreeWidget::handleExpanded(const QModelIndex& index) {
- GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
- if (item) {
- item->setExpanded(true);
- }
+ GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
+ if (item) {
+ item->setExpanded(true);
+ }
}
void QtTreeWidget::handleCollapsed(const QModelIndex& index) {
- GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
- if (item) {
- item->setExpanded(false);
- }
+ GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
+ if (item) {
+ item->setExpanded(false);
+ }
}
void QtTreeWidget::handleModelItemExpanded(const QModelIndex& index, bool shouldExpand) {
- if (!index.isValid()) {
- return;
- }
- bool alreadyRight = this->isExpanded(index) == shouldExpand;
- if (alreadyRight) {
- return;
- }
- setExpanded(index, shouldExpand);
+ if (!index.isValid()) {
+ return;
+ }
+ bool alreadyRight = this->isExpanded(index) == shouldExpand;
+ if (alreadyRight) {
+ return;
+ }
+ setExpanded(index, shouldExpand);
}
void QtTreeWidget::drawBranches(QPainter*, const QRect&, const QModelIndex&) const {
}
void QtTreeWidget::show() {
- QWidget::show();
+ QWidget::show();
}
void QtTreeWidget::setMessageTarget(MessageTarget messageTarget) {
- messageTarget_ = messageTarget;
+ messageTarget_ = messageTarget;
}
JID QtTreeWidget::jidFromIndex(const QModelIndex& index) const {
- JID target;
- if (messageTarget_ == MessageDisplayJID) {
- target = JID(Q2PSTRING(index.data(DisplayJIDRole).toString()));
- target = target.toBare();
- }
- if (!target.isValid()) {
- target = JID(Q2PSTRING(index.data(JIDRole).toString()));
- }
- return target;
+ JID target;
+ if (messageTarget_ == MessageDisplayJID) {
+ target = JID(Q2PSTRING(index.data(DisplayJIDRole).toString()));
+ target = target.toBare();
+ }
+ if (!target.isValid()) {
+ target = JID(Q2PSTRING(index.data(JIDRole).toString()));
+ }
+ return target;
}
JID QtTreeWidget::selectedJID() const {
- QModelIndexList list = selectedIndexes();
- if (list.size() != 1) {
- return JID();
- }
- return jidFromIndex(list[0]);
+ QModelIndexList list = selectedIndexes();
+ if (list.size() != 1) {
+ return JID();
+ }
+ return jidFromIndex(list[0]);
}
void QtTreeWidget::setOnline(bool isOnline) {
- isOnline_ = isOnline;
+ isOnline_ = isOnline;
}
bool QtTreeWidget::isOnline() const {
- return isOnline_;
+ return isOnline_;
}
}
diff --git a/Swift/QtUI/Roster/QtTreeWidget.h b/Swift/QtUI/Roster/QtTreeWidget.h
index 205bc70..9a94e8f 100644
--- a/Swift/QtUI/Roster/QtTreeWidget.h
+++ b/Swift/QtUI/Roster/QtTreeWidget.h
@@ -22,59 +22,59 @@ class UIEventStream;
class SettingsProvider;
class QtTreeWidget : public QTreeView {
- Q_OBJECT
- public:
- enum MessageTarget {MessageDefaultJID, MessageDisplayJID};
+ Q_OBJECT
+ public:
+ enum MessageTarget {MessageDefaultJID, MessageDisplayJID};
- QtTreeWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget messageTarget, QWidget* parent = 0);
- ~QtTreeWidget();
- void show();
- QtTreeWidgetItem* getRoot();
- void setRosterModel(Roster* roster);
- Roster* getRoster() {return roster_;}
- void refreshTooltip();
- void setMessageTarget(MessageTarget messageTarget);
- JID jidFromIndex(const QModelIndex& index) const;
- JID selectedJID() const;
- void setOnline(bool isOnline);
+ QtTreeWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget messageTarget, QWidget* parent = 0);
+ ~QtTreeWidget();
+ void show();
+ QtTreeWidgetItem* getRoot();
+ void setRosterModel(Roster* roster);
+ Roster* getRoster() {return roster_;}
+ void refreshTooltip();
+ void setMessageTarget(MessageTarget messageTarget);
+ JID jidFromIndex(const QModelIndex& index) const;
+ JID selectedJID() const;
+ void setOnline(bool isOnline);
- public:
- boost::signal<void (RosterItem*)> onSomethingSelectedChanged;
+ public:
+ boost::signal<void (RosterItem*)> onSomethingSelectedChanged;
- private slots:
- void handleItemActivated(const QModelIndex&);
- void handleModelItemExpanded(const QModelIndex&, bool expanded);
- void handleExpanded(const QModelIndex&);
- void handleCollapsed(const QModelIndex&);
- void handleClicked(const QModelIndex&);
- void handleSettingChanged(const std::string& setting);
- void handleRefreshTooltip();
+ private slots:
+ void handleItemActivated(const QModelIndex&);
+ void handleModelItemExpanded(const QModelIndex&, bool expanded);
+ void handleExpanded(const QModelIndex&);
+ void handleCollapsed(const QModelIndex&);
+ void handleClicked(const QModelIndex&);
+ void handleSettingChanged(const std::string& setting);
+ void handleRefreshTooltip();
- protected:
- void dragEnterEvent(QDragEnterEvent* event);
- void dropEvent(QDropEvent* event);
- void dragMoveEvent(QDragMoveEvent* event);
- bool event(QEvent* event);
- QModelIndexList getSelectedIndexes() const;
- bool isOnline() const;
+ protected:
+ void dragEnterEvent(QDragEnterEvent* event);
+ void dropEvent(QDropEvent* event);
+ void dragMoveEvent(QDragMoveEvent* event);
+ bool event(QEvent* event);
+ QModelIndexList getSelectedIndexes() const;
+ bool isOnline() const;
- private:
- void drawBranches(QPainter*, const QRect&, const QModelIndex&) const;
+ private:
+ void drawBranches(QPainter*, const QRect&, const QModelIndex&) const;
- protected slots:
- virtual void currentChanged(const QModelIndex& current, const QModelIndex& previous);
- protected:
- UIEventStream* eventStream_;
+ protected slots:
+ virtual void currentChanged(const QModelIndex& current, const QModelIndex& previous);
+ protected:
+ UIEventStream* eventStream_;
- private:
- RosterModel* model_;
- Roster* roster_;
- RosterDelegate* delegate_;
- QtTreeWidgetItem* treeRoot_;
- SettingsProvider* settings_;
- bool tooltipShown_;
- MessageTarget messageTarget_;
- bool isOnline_;
+ private:
+ RosterModel* model_;
+ Roster* roster_;
+ RosterDelegate* delegate_;
+ QtTreeWidgetItem* treeRoot_;
+ SettingsProvider* settings_;
+ bool tooltipShown_;
+ MessageTarget messageTarget_;
+ bool isOnline_;
};
}
diff --git a/Swift/QtUI/Roster/RosterDelegate.cpp b/Swift/QtUI/Roster/RosterDelegate.cpp
index ff950e5..061982e 100644
--- a/Swift/QtUI/Roster/RosterDelegate.cpp
+++ b/Swift/QtUI/Roster/RosterDelegate.cpp
@@ -25,59 +25,59 @@
namespace Swift {
RosterDelegate::RosterDelegate(QtTreeWidget* tree, bool compact) : compact_(compact) {
- tree_ = tree;
- groupDelegate_ = new GroupItemDelegate();
+ tree_ = tree;
+ groupDelegate_ = new GroupItemDelegate();
}
RosterDelegate::~RosterDelegate() {
- delete groupDelegate_;
+ delete groupDelegate_;
}
void RosterDelegate::setCompact(bool compact) {
- compact_ = compact;
- emit sizeHintChanged(QModelIndex());
+ compact_ = compact;
+ emit sizeHintChanged(QModelIndex());
}
-
+
QSize RosterDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (dynamic_cast<GroupRosterItem*>(item)) {
- return groupDelegate_->sizeHint(option, index);
- }
- return contactSizeHint(option, index);
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (dynamic_cast<GroupRosterItem*>(item)) {
+ return groupDelegate_->sizeHint(option, index);
+ }
+ return contactSizeHint(option, index);
}
QSize RosterDelegate::contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- return common_.contactSizeHint(option, index, compact_);
+ return common_.contactSizeHint(option, index, compact_);
}
void RosterDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (dynamic_cast<GroupRosterItem*>(item)) {
- paintGroup(painter, option, index);
- } else {
- paintContact(painter, option, index);
- }
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (dynamic_cast<GroupRosterItem*>(item)) {
+ paintGroup(painter, option, index);
+ } else {
+ paintContact(painter, option, index);
+ }
}
void RosterDelegate::paintGroup(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- if (index.isValid()) {
- groupDelegate_->paint(painter, option, index.data(Qt::DisplayRole).toString(), index.data(ChildCountRole).toInt(), tree_->isExpanded(index));
- }
+ if (index.isValid()) {
+ groupDelegate_->paint(painter, option, index.data(Qt::DisplayRole).toString(), index.data(ChildCountRole).toInt(), tree_->isExpanded(index));
+ }
}
void RosterDelegate::paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
- QString avatarPath;
- if (index.data(AvatarRole).isValid() && !index.data(AvatarRole).value<QString>().isNull()) {
- avatarPath = index.data(AvatarRole).value<QString>();
- }
- QIcon presenceIcon = index.data(PresenceIconRole).isValid() && !index.data(PresenceIconRole).value<QIcon>().isNull()
- ? index.data(PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");
- bool isIdle = index.data(IdleRole).isValid() ? index.data(IdleRole).toBool() : false;
- QString name = index.data(Qt::DisplayRole).toString();
- QString statusText = index.data(StatusTextRole).toString();
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, isIdle, 0, compact_);
+ QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath;
+ if (index.data(AvatarRole).isValid() && !index.data(AvatarRole).value<QString>().isNull()) {
+ avatarPath = index.data(AvatarRole).value<QString>();
+ }
+ QIcon presenceIcon = index.data(PresenceIconRole).isValid() && !index.data(PresenceIconRole).value<QIcon>().isNull()
+ ? index.data(PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");
+ bool isIdle = index.data(IdleRole).isValid() ? index.data(IdleRole).toBool() : false;
+ QString name = index.data(Qt::DisplayRole).toString();
+ QString statusText = index.data(StatusTextRole).toString();
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, isIdle, 0, compact_);
}
}
diff --git a/Swift/QtUI/Roster/RosterDelegate.h b/Swift/QtUI/Roster/RosterDelegate.h
index f17f9b8..34c1569 100644
--- a/Swift/QtUI/Roster/RosterDelegate.h
+++ b/Swift/QtUI/Roster/RosterDelegate.h
@@ -14,22 +14,22 @@
#include <Swift/QtUI/Roster/GroupItemDelegate.h>
namespace Swift {
- class QtTreeWidget;
- class RosterDelegate : public QStyledItemDelegate {
- public:
- RosterDelegate(QtTreeWidget* tree, bool compact);
- ~RosterDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- public slots:
- void setCompact(bool compact);
- private:
- QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paintGroup(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- bool compact_;
- DelegateCommons common_;
- GroupItemDelegate* groupDelegate_;
- QtTreeWidget* tree_;
- };
+ class QtTreeWidget;
+ class RosterDelegate : public QStyledItemDelegate {
+ public:
+ RosterDelegate(QtTreeWidget* tree, bool compact);
+ ~RosterDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ public slots:
+ void setCompact(bool compact);
+ private:
+ QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paintGroup(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ bool compact_;
+ DelegateCommons common_;
+ GroupItemDelegate* groupDelegate_;
+ QtTreeWidget* tree_;
+ };
}
diff --git a/Swift/QtUI/Roster/RosterModel.cpp b/Swift/QtUI/Roster/RosterModel.cpp
index 60e4aca..2b3759d 100644
--- a/Swift/QtUI/Roster/RosterModel.cpp
+++ b/Swift/QtUI/Roster/RosterModel.cpp
@@ -29,251 +29,251 @@
namespace Swift {
RosterModel::RosterModel(QtTreeWidget* view, bool screenReaderMode) : roster_(NULL), view_(view), screenReader_(screenReaderMode) {
- const int tooltipAvatarSize = 96; // maximal suggested size according to XEP-0153
- cachedImageScaler_ = new QtScaledAvatarCache(tooltipAvatarSize);
+ const int tooltipAvatarSize = 96; // maximal suggested size according to XEP-0153
+ cachedImageScaler_ = new QtScaledAvatarCache(tooltipAvatarSize);
}
RosterModel::~RosterModel() {
- delete cachedImageScaler_;
+ delete cachedImageScaler_;
}
void RosterModel::setRoster(Roster* roster) {
- roster_ = roster;
- if (roster_) {
- roster->onChildrenChanged.connect(boost::bind(&RosterModel::handleChildrenChanged, this, _1));
- roster->onDataChanged.connect(boost::bind(&RosterModel::handleDataChanged, this, _1));
- }
- reLayout();
+ roster_ = roster;
+ if (roster_) {
+ roster->onChildrenChanged.connect(boost::bind(&RosterModel::handleChildrenChanged, this, _1));
+ roster->onDataChanged.connect(boost::bind(&RosterModel::handleDataChanged, this, _1));
+ }
+ reLayout();
}
void RosterModel::reLayout() {
- //emit layoutChanged();
- beginResetModel();
- endResetModel(); // TODO: Not sure if this isn't too early?
- if (!roster_) {
- return;
- }
- foreach (RosterItem* item, roster_->getRoot()->getDisplayedChildren()) {
- GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(item);
- if (!child) continue;
- emit itemExpanded(index(child), child->isExpanded());
- }
+ //emit layoutChanged();
+ beginResetModel();
+ endResetModel(); // TODO: Not sure if this isn't too early?
+ if (!roster_) {
+ return;
+ }
+ foreach (RosterItem* item, roster_->getRoot()->getDisplayedChildren()) {
+ GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(item);
+ if (!child) continue;
+ emit itemExpanded(index(child), child->isExpanded());
+ }
}
void RosterModel::handleChildrenChanged(GroupRosterItem* /*group*/) {
- reLayout();
+ reLayout();
}
void RosterModel::handleDataChanged(RosterItem* item) {
- Q_ASSERT(item);
- QModelIndex modelIndex = index(item);
- if (modelIndex.isValid()) {
- emit dataChanged(modelIndex, modelIndex);
- view_->refreshTooltip();
- }
+ Q_ASSERT(item);
+ QModelIndex modelIndex = index(item);
+ if (modelIndex.isValid()) {
+ emit dataChanged(modelIndex, modelIndex);
+ view_->refreshTooltip();
+ }
}
Qt::ItemFlags RosterModel::flags(const QModelIndex& index) const {
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (dynamic_cast<GroupRosterItem*>(getItem(index)) == NULL) {
- flags |= Qt::ItemIsDragEnabled;
- }
- return flags;
+ Qt::ItemFlags flags = QAbstractItemModel::flags(index);
+ if (dynamic_cast<GroupRosterItem*>(getItem(index)) == NULL) {
+ flags |= Qt::ItemIsDragEnabled;
+ }
+ return flags;
}
int RosterModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ return 1;
}
RosterItem* RosterModel::getItem(const QModelIndex& index) const {
- return index.isValid() ? static_cast<RosterItem*>(index.internalPointer()) : NULL;
+ return index.isValid() ? static_cast<RosterItem*>(index.internalPointer()) : NULL;
}
QVariant RosterModel::data(const QModelIndex& index, int role) const {
- RosterItem* item = getItem(index);
- if (!item) return QVariant();
-
- switch (role) {
- case Qt::DisplayRole: return getScreenReaderTextOr(item, P2QSTRING(item->getDisplayName()));
- case Qt::TextColorRole: return getTextColor(item);
- case Qt::BackgroundColorRole: return getBackgroundColor(item);
- case Qt::ToolTipRole: return getToolTip(item);
- case StatusTextRole: return getStatusText(item);
- case AvatarRole: return getAvatar(item);
- case PresenceIconRole: return getPresenceIcon(item);
- case ChildCountRole: return getChildCount(item);
- case IdleRole: return getIsIdle(item);
- case JIDRole: return getJID(item);
- case DisplayJIDRole: return getDisplayJID(item);
- default: return QVariant();
- }
+ RosterItem* item = getItem(index);
+ if (!item) return QVariant();
+
+ switch (role) {
+ case Qt::DisplayRole: return getScreenReaderTextOr(item, P2QSTRING(item->getDisplayName()));
+ case Qt::TextColorRole: return getTextColor(item);
+ case Qt::BackgroundColorRole: return getBackgroundColor(item);
+ case Qt::ToolTipRole: return getToolTip(item);
+ case StatusTextRole: return getStatusText(item);
+ case AvatarRole: return getAvatar(item);
+ case PresenceIconRole: return getPresenceIcon(item);
+ case ChildCountRole: return getChildCount(item);
+ case IdleRole: return getIsIdle(item);
+ case JIDRole: return getJID(item);
+ case DisplayJIDRole: return getDisplayJID(item);
+ default: return QVariant();
+ }
}
QString RosterModel::getScreenReaderTextOr(RosterItem* item, const QString& alternative) const {
- QString name = P2QSTRING(item->getDisplayName());
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && screenReader_) {
- name += ": " + P2QSTRING(statusShowTypeToFriendlyName(contact->getStatusShow()));
- if (!contact->getStatusText().empty()) {
- name += " (" + P2QSTRING(contact->getStatusText()) + ")";
- }
- return name;
- }
- else {
- return alternative;
- }
+ QString name = P2QSTRING(item->getDisplayName());
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && screenReader_) {
+ name += ": " + P2QSTRING(statusShowTypeToFriendlyName(contact->getStatusShow()));
+ if (!contact->getStatusText().empty()) {
+ name += " (" + P2QSTRING(contact->getStatusText()) + ")";
+ }
+ return name;
+ }
+ else {
+ return alternative;
+ }
}
int RosterModel::getChildCount(RosterItem* item) const {
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- return group ? group->getDisplayedChildren().size() : 0;
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ return group ? group->getDisplayedChildren().size() : 0;
}
bool RosterModel::getIsIdle(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- return contact ? !contact->getIdleText().empty() : false;
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ return contact ? !contact->getIdleText().empty() : false;
}
QColor RosterModel::intToColor(int color) const {
- return QColor(
- ((color & 0xFF0000)>>16),
- ((color & 0xFF00)>>8),
- (color & 0xFF));
+ return QColor(
+ ((color & 0xFF0000)>>16),
+ ((color & 0xFF00)>>8),
+ (color & 0xFF));
}
QColor RosterModel::getTextColor(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- int color = 0;
- if (contact) {
- switch (contact->getStatusShow()) {
- case StatusShow::Online: color = 0x000000; break;
- case StatusShow::Away: color = 0x336699; break;
- case StatusShow::XA: color = 0x336699; break;
- case StatusShow::FFC: color = 0x000000; break;
- case StatusShow::DND: color = 0x990000; break;
- case StatusShow::None: color = 0x7F7F7F;break;
- }
- }
- return intToColor(color);
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ int color = 0;
+ if (contact) {
+ switch (contact->getStatusShow()) {
+ case StatusShow::Online: color = 0x000000; break;
+ case StatusShow::Away: color = 0x336699; break;
+ case StatusShow::XA: color = 0x336699; break;
+ case StatusShow::FFC: color = 0x000000; break;
+ case StatusShow::DND: color = 0x990000; break;
+ case StatusShow::None: color = 0x7F7F7F;break;
+ }
+ }
+ return intToColor(color);
}
QColor RosterModel::getBackgroundColor(RosterItem* item) const {
- return dynamic_cast<ContactRosterItem*>(item) ? intToColor(0xFFFFFF) : intToColor(0x969696);
+ return dynamic_cast<ContactRosterItem*>(item) ? intToColor(0xFFFFFF) : intToColor(0x969696);
}
QString RosterModel::getToolTip(RosterItem* item) const {
- QString tip(P2QSTRING(item->getDisplayName()));
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact) {
- return RosterTooltip::buildDetailedTooltip(contact, cachedImageScaler_);
- }
- return tip;
+ QString tip(P2QSTRING(item->getDisplayName()));
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact) {
+ return RosterTooltip::buildDetailedTooltip(contact, cachedImageScaler_);
+ }
+ return tip;
}
QString RosterModel::getAvatar(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (!contact) {
- return "";
- }
- return P2QSTRING(pathToString(contact->getAvatarPath()));
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (!contact) {
+ return "";
+ }
+ return P2QSTRING(pathToString(contact->getAvatarPath()));
}
QString RosterModel::getStatusText(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (!contact) return "";
- return P2QSTRING(contact->getStatusText());
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (!contact) return "";
+ return P2QSTRING(contact->getStatusText());
}
QString RosterModel::getJID(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- return contact ? P2QSTRING(contact->getJID().toString()) : QString();
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ return contact ? P2QSTRING(contact->getJID().toString()) : QString();
}
QString RosterModel::getDisplayJID(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- QString result = contact ? P2QSTRING(contact->getDisplayJID().toString()) : QString();
- if (result.isEmpty()) {
- result = getJID(item);
- }
- return result;
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ QString result = contact ? P2QSTRING(contact->getDisplayJID().toString()) : QString();
+ if (result.isEmpty()) {
+ result = getJID(item);
+ }
+ return result;
}
QIcon RosterModel::getPresenceIcon(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (!contact) return QIcon();
- if (contact->blockState() == ContactRosterItem::IsBlocked ||
- contact->blockState() == ContactRosterItem::IsDomainBlocked) {
- return QIcon(":/icons/stop.png");
- }
-
- return QIcon(statusShowTypeToIconPath(contact->getStatusShow()));
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (!contact) return QIcon();
+ if (contact->blockState() == ContactRosterItem::IsBlocked ||
+ contact->blockState() == ContactRosterItem::IsDomainBlocked) {
+ return QIcon(":/icons/stop.png");
+ }
+
+ return QIcon(statusShowTypeToIconPath(contact->getStatusShow()));
}
QModelIndex RosterModel::index(int row, int column, const QModelIndex& parent) const {
- if (!roster_) {
- return QModelIndex();
- }
- GroupRosterItem* parentItem;
- if (!parent.isValid()) {
- //top level
- parentItem = roster_->getRoot();
- } else {
- parentItem = dynamic_cast<GroupRosterItem*>(getItem(parent));
- if (!parentItem) return QModelIndex();
- }
- return static_cast<size_t>(row) < parentItem->getDisplayedChildren().size() ? createIndex(row, column, parentItem->getDisplayedChildren()[row]) : QModelIndex();
+ if (!roster_) {
+ return QModelIndex();
+ }
+ GroupRosterItem* parentItem;
+ if (!parent.isValid()) {
+ //top level
+ parentItem = roster_->getRoot();
+ } else {
+ parentItem = dynamic_cast<GroupRosterItem*>(getItem(parent));
+ if (!parentItem) return QModelIndex();
+ }
+ return static_cast<size_t>(row) < parentItem->getDisplayedChildren().size() ? createIndex(row, column, parentItem->getDisplayedChildren()[row]) : QModelIndex();
}
QModelIndex RosterModel::index(RosterItem* item) const {
- GroupRosterItem* parent = item->getParent();
- /* Recursive check that it's ok to create such an item
- Assuming there are more contacts in a group than groups in a
- group, this could save a decent chunk of search time at startup.*/
- if (parent == NULL || roster_ == NULL || (parent != roster_->getRoot() && !index(parent).isValid())) {
- return QModelIndex();
- }
- for (size_t i = 0; i < parent->getDisplayedChildren().size(); i++) {
- if (parent->getDisplayedChildren()[i] == item) {
- return createIndex(i, 0, item);
- }
- }
- return QModelIndex();
+ GroupRosterItem* parent = item->getParent();
+ /* Recursive check that it's ok to create such an item
+ Assuming there are more contacts in a group than groups in a
+ group, this could save a decent chunk of search time at startup.*/
+ if (parent == NULL || roster_ == NULL || (parent != roster_->getRoot() && !index(parent).isValid())) {
+ return QModelIndex();
+ }
+ for (size_t i = 0; i < parent->getDisplayedChildren().size(); i++) {
+ if (parent->getDisplayedChildren()[i] == item) {
+ return createIndex(i, 0, item);
+ }
+ }
+ return QModelIndex();
}
QModelIndex RosterModel::parent(const QModelIndex& child) const {
- if (!roster_ || !child.isValid()) {
- return QModelIndex();
- }
-
- GroupRosterItem* parent = getItem(child)->getParent();
- return (parent != roster_->getRoot()) ? index(parent) : QModelIndex();
+ if (!roster_ || !child.isValid()) {
+ return QModelIndex();
+ }
+
+ GroupRosterItem* parent = getItem(child)->getParent();
+ return (parent != roster_->getRoot()) ? index(parent) : QModelIndex();
}
int RosterModel::rowCount(const QModelIndex& parent) const {
- if (!roster_) return 0;
- RosterItem* item = parent.isValid() ? static_cast<RosterItem*>(parent.internalPointer()) : roster_->getRoot();
- Q_ASSERT(item);
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- int count = group ? group->getDisplayedChildren().size() : 0;
-// qDebug() << "rowCount = " << count << " where parent.isValid() == " << parent.isValid() << ", group == " << (group ? P2QSTRING(group->getDisplayName()) : "*contact*");
- return count;
+ if (!roster_) return 0;
+ RosterItem* item = parent.isValid() ? static_cast<RosterItem*>(parent.internalPointer()) : roster_->getRoot();
+ Q_ASSERT(item);
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ int count = group ? group->getDisplayedChildren().size() : 0;
+// qDebug() << "rowCount = " << count << " where parent.isValid() == " << parent.isValid() << ", group == " << (group ? P2QSTRING(group->getDisplayName()) : "*contact*");
+ return count;
}
QMimeData* RosterModel::mimeData(const QModelIndexList& indexes) const {
- QMimeData* data = QAbstractItemModel::mimeData(indexes);
-
- ContactRosterItem *item = dynamic_cast<ContactRosterItem*>(getItem(indexes.first()));
- if (item == NULL) {
- return data;
- }
-
- /* only a single JID in this list */
- QByteArray itemData;
- QDataStream dataStream(&itemData, QIODevice::WriteOnly);
- dataStream << P2QSTRING(item->getJID().toString());
- data->setData("application/vnd.swift.contact-jid-list", itemData);
- return data;
+ QMimeData* data = QAbstractItemModel::mimeData(indexes);
+
+ ContactRosterItem *item = dynamic_cast<ContactRosterItem*>(getItem(indexes.first()));
+ if (item == NULL) {
+ return data;
+ }
+
+ /* only a single JID in this list */
+ QByteArray itemData;
+ QDataStream dataStream(&itemData, QIODevice::WriteOnly);
+ dataStream << P2QSTRING(item->getJID().toString());
+ data->setData("application/vnd.swift.contact-jid-list", itemData);
+ return data;
}
}
diff --git a/Swift/QtUI/Roster/RosterModel.h b/Swift/QtUI/Roster/RosterModel.h
index 47ed614..af0d43a 100644
--- a/Swift/QtUI/Roster/RosterModel.h
+++ b/Swift/QtUI/Roster/RosterModel.h
@@ -14,58 +14,58 @@
#include <Swift/QtUI/QtScaledAvatarCache.h>
namespace Swift {
- enum RosterRoles {
- StatusTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2,
- StatusShowTypeRole = Qt::UserRole + 3,
- ChildCountRole = Qt::UserRole + 4,
- IdleRole = Qt::UserRole + 5,
- JIDRole = Qt::UserRole + 6,
- DisplayJIDRole = Qt::UserRole + 7
- };
+ enum RosterRoles {
+ StatusTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2,
+ StatusShowTypeRole = Qt::UserRole + 3,
+ ChildCountRole = Qt::UserRole + 4,
+ IdleRole = Qt::UserRole + 5,
+ JIDRole = Qt::UserRole + 6,
+ DisplayJIDRole = Qt::UserRole + 7
+ };
- class QtTreeWidget;
+ class QtTreeWidget;
- class RosterModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- RosterModel(QtTreeWidget* view, bool screenReaderMode);
- ~RosterModel();
- void setRoster(Roster* swiftRoster);
- Qt::ItemFlags flags(const QModelIndex& index) const;
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex index(RosterItem* item) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- QMimeData* mimeData(const QModelIndexList& indexes) const;
+ class RosterModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ RosterModel(QtTreeWidget* view, bool screenReaderMode);
+ ~RosterModel();
+ void setRoster(Roster* swiftRoster);
+ Qt::ItemFlags flags(const QModelIndex& index) const;
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex index(RosterItem* item) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ QMimeData* mimeData(const QModelIndexList& indexes) const;
- signals:
- void itemExpanded(const QModelIndex& item, bool expanded);
- private:
- void handleDataChanged(RosterItem* item);
- void handleChildrenChanged(GroupRosterItem* item);
- RosterItem* getItem(const QModelIndex& index) const;
- QColor intToColor(int color) const;
- QColor getTextColor(RosterItem* item) const;
- QColor getBackgroundColor(RosterItem* item) const;
- QString getToolTip(RosterItem* item) const;
- QString getAvatar(RosterItem* item) const;
- QString getStatusText(RosterItem* item) const;
- QString getJID(RosterItem* item) const;
- QString getDisplayJID(RosterItem* item) const;
- QIcon getPresenceIcon(RosterItem* item) const;
- int getChildCount(RosterItem* item) const;
- bool getIsIdle(RosterItem* item) const;
- void reLayout();
- /** calculates screenreader-friendly text if in screenreader mode, otherwise uses alternative text */
- QString getScreenReaderTextOr(RosterItem* item, const QString& alternative) const;
- private:
- Roster* roster_;
- QtTreeWidget* view_;
- QtScaledAvatarCache* cachedImageScaler_;
- bool screenReader_;
- };
+ signals:
+ void itemExpanded(const QModelIndex& item, bool expanded);
+ private:
+ void handleDataChanged(RosterItem* item);
+ void handleChildrenChanged(GroupRosterItem* item);
+ RosterItem* getItem(const QModelIndex& index) const;
+ QColor intToColor(int color) const;
+ QColor getTextColor(RosterItem* item) const;
+ QColor getBackgroundColor(RosterItem* item) const;
+ QString getToolTip(RosterItem* item) const;
+ QString getAvatar(RosterItem* item) const;
+ QString getStatusText(RosterItem* item) const;
+ QString getJID(RosterItem* item) const;
+ QString getDisplayJID(RosterItem* item) const;
+ QIcon getPresenceIcon(RosterItem* item) const;
+ int getChildCount(RosterItem* item) const;
+ bool getIsIdle(RosterItem* item) const;
+ void reLayout();
+ /** calculates screenreader-friendly text if in screenreader mode, otherwise uses alternative text */
+ QString getScreenReaderTextOr(RosterItem* item, const QString& alternative) const;
+ private:
+ Roster* roster_;
+ QtTreeWidget* view_;
+ QtScaledAvatarCache* cachedImageScaler_;
+ bool screenReader_;
+ };
}
diff --git a/Swift/QtUI/Roster/RosterTooltip.cpp b/Swift/QtUI/Roster/RosterTooltip.cpp
index e4a5626..d151628 100644
--- a/Swift/QtUI/Roster/RosterTooltip.cpp
+++ b/Swift/QtUI/Roster/RosterTooltip.cpp
@@ -31,142 +31,142 @@ using namespace QtUtilities;
namespace Swift {
QString RosterTooltip::buildDetailedTooltip(ContactRosterItem* contact, QtScaledAvatarCache* cachedImageScaler) {
- QString tooltipTemplate;
- if (QApplication::layoutDirection() == Qt::RightToLeft) {
- tooltipTemplate = QString(
- "<table style='white-space:pre'>"
- "<tr>"
- "<td>"
- "<img src=\"%1\" />"
- "</td>"
- "<td>"
- "<p style='font-size: 14px'>%3 %2</p>"
- "<table><tr><td valign='middle'>%5</td><td valign='middle'>%4</td></tr></table>"
- "%6"
- "%7"
- "%8"
- "%9"
- "</td>"
- "</tr>"
- "</table>");
- } else {
- tooltipTemplate = QString(
- "<table style='white-space:pre'>"
- "<tr>"
- "<td>"
- "<img src=\"%1\" />"
- "</td>"
- "<td>"
- "<p style='font-size: 14px'>%2 %3</p>"
- "<table><tr><td valign='middle'>%4</td><td valign='middle'>%5</td></tr></table>"
- "%6"
- "%7"
- "%8"
- "%9"
- "</td>"
- "</tr>"
- "</table>");
- }
- // prepare tooltip
- QString fullName = P2QSTRING(contact->getDisplayName());
-
- QString vCardSummary;
- VCard::ref vCard = contact->getVCard();
- if (vCard) {
- fullName = P2QSTRING(vCard->getFullName()).trimmed();
- if (fullName.isEmpty()) {
- fullName = (P2QSTRING(vCard->getGivenName()) + " " + P2QSTRING(vCard->getFamilyName())).trimmed();
- }
- if (fullName.isEmpty()) {
- fullName = P2QSTRING(contact->getDisplayName());
- }
- vCardSummary = buildVCardSummary(vCard);
- } else {
- contact->onVCardRequested();
- }
-
- QString scaledAvatarPath = cachedImageScaler->getScaledAvatarPath(P2QSTRING(contact->getAvatarPath().empty() ? ":/icons/avatar.png" : pathToString(contact->getAvatarPath())));
-
- QString bareJID = contact->getDisplayJID().toString().empty() ? "" : "( " + P2QSTRING(contact->getDisplayJID().toString()) + " )";
-
- QString presenceIconTag = QString("<img src='%1' />").arg(statusShowTypeToIconPath(contact->getStatusShow()));
-
- QString statusMessage = contact->getStatusText().empty() ? QObject::tr("(No message)") : P2QSTRING(contact->getStatusText());
-
- QString idleString = P2QSTRING(contact->getIdleText());
- if (!idleString.isEmpty()) {
- idleString = QObject::tr("Idle since %1").arg(idleString);
- idleString = htmlEscape(idleString) + "<br/>";
- }
-
- QString lastSeen = P2QSTRING(contact->getOfflineSinceText());
- if (!lastSeen.isEmpty()) {
- lastSeen = QObject::tr("Last seen %1").arg(lastSeen);
- lastSeen = htmlEscape(lastSeen) + "<br/>";
- }
-
- QString mucOccupant= P2QSTRING(contact->getMUCAffiliationText());
- if (!mucOccupant.isEmpty()) {
- mucOccupant = htmlEscape(mucOccupant) + "<br/>";
- }
-
- return tooltipTemplate.arg(scaledAvatarPath, htmlEscape(fullName), htmlEscape(bareJID), presenceIconTag, htmlEscape(statusMessage), mucOccupant, idleString, lastSeen, vCardSummary);
+ QString tooltipTemplate;
+ if (QApplication::layoutDirection() == Qt::RightToLeft) {
+ tooltipTemplate = QString(
+ "<table style='white-space:pre'>"
+ "<tr>"
+ "<td>"
+ "<img src=\"%1\" />"
+ "</td>"
+ "<td>"
+ "<p style='font-size: 14px'>%3 %2</p>"
+ "<table><tr><td valign='middle'>%5</td><td valign='middle'>%4</td></tr></table>"
+ "%6"
+ "%7"
+ "%8"
+ "%9"
+ "</td>"
+ "</tr>"
+ "</table>");
+ } else {
+ tooltipTemplate = QString(
+ "<table style='white-space:pre'>"
+ "<tr>"
+ "<td>"
+ "<img src=\"%1\" />"
+ "</td>"
+ "<td>"
+ "<p style='font-size: 14px'>%2 %3</p>"
+ "<table><tr><td valign='middle'>%4</td><td valign='middle'>%5</td></tr></table>"
+ "%6"
+ "%7"
+ "%8"
+ "%9"
+ "</td>"
+ "</tr>"
+ "</table>");
+ }
+ // prepare tooltip
+ QString fullName = P2QSTRING(contact->getDisplayName());
+
+ QString vCardSummary;
+ VCard::ref vCard = contact->getVCard();
+ if (vCard) {
+ fullName = P2QSTRING(vCard->getFullName()).trimmed();
+ if (fullName.isEmpty()) {
+ fullName = (P2QSTRING(vCard->getGivenName()) + " " + P2QSTRING(vCard->getFamilyName())).trimmed();
+ }
+ if (fullName.isEmpty()) {
+ fullName = P2QSTRING(contact->getDisplayName());
+ }
+ vCardSummary = buildVCardSummary(vCard);
+ } else {
+ contact->onVCardRequested();
+ }
+
+ QString scaledAvatarPath = cachedImageScaler->getScaledAvatarPath(P2QSTRING(contact->getAvatarPath().empty() ? ":/icons/avatar.png" : pathToString(contact->getAvatarPath())));
+
+ QString bareJID = contact->getDisplayJID().toString().empty() ? "" : "( " + P2QSTRING(contact->getDisplayJID().toString()) + " )";
+
+ QString presenceIconTag = QString("<img src='%1' />").arg(statusShowTypeToIconPath(contact->getStatusShow()));
+
+ QString statusMessage = contact->getStatusText().empty() ? QObject::tr("(No message)") : P2QSTRING(contact->getStatusText());
+
+ QString idleString = P2QSTRING(contact->getIdleText());
+ if (!idleString.isEmpty()) {
+ idleString = QObject::tr("Idle since %1").arg(idleString);
+ idleString = htmlEscape(idleString) + "<br/>";
+ }
+
+ QString lastSeen = P2QSTRING(contact->getOfflineSinceText());
+ if (!lastSeen.isEmpty()) {
+ lastSeen = QObject::tr("Last seen %1").arg(lastSeen);
+ lastSeen = htmlEscape(lastSeen) + "<br/>";
+ }
+
+ QString mucOccupant= P2QSTRING(contact->getMUCAffiliationText());
+ if (!mucOccupant.isEmpty()) {
+ mucOccupant = htmlEscape(mucOccupant) + "<br/>";
+ }
+
+ return tooltipTemplate.arg(scaledAvatarPath, htmlEscape(fullName), htmlEscape(bareJID), presenceIconTag, htmlEscape(statusMessage), mucOccupant, idleString, lastSeen, vCardSummary);
}
QString RosterTooltip::buildVCardSummary(VCard::ref vcard) {
- QString summary;
- summary = "<table>";
-
- // star | name | content
- QString currentBlock;
- foreach (const VCard::Telephone& tel, vcard->getTelephones()) {
- QString type = tel.isFax ? QObject::tr("Fax") : QObject::tr("Telephone");
- QString field = buildVCardField(tel.isPreferred, type, htmlEscape(P2QSTRING(tel.number)));
- if (tel.isPreferred) {
- currentBlock = field;
- break;
- }
- currentBlock += field;
- }
- summary += currentBlock;
-
- currentBlock = "";
- foreach (const VCard::EMailAddress& mail, vcard->getEMailAddresses()) {
- QString field = buildVCardField(mail.isPreferred, QObject::tr("E-Mail"), htmlEscape(P2QSTRING(mail.address)));
- if (mail.isPreferred) {
- currentBlock = field;
- break;
- }
- currentBlock += field;
- }
- summary += currentBlock;
-
- currentBlock = "";
- foreach (const VCard::Organization& org, vcard->getOrganizations()) {
- QString field = buildVCardField(false, QObject::tr("Organization"), htmlEscape(P2QSTRING(org.name)));
- currentBlock += field;
- }
- summary += currentBlock;
-
- currentBlock = "";
- foreach(const std::string& title, vcard->getTitles()) {
- QString field = buildVCardField(false, QObject::tr("Title"), htmlEscape(P2QSTRING(title)));
- currentBlock += field;
- }
- summary += currentBlock;
-
- summary += "</table>";
- return summary;
+ QString summary;
+ summary = "<table>";
+
+ // star | name | content
+ QString currentBlock;
+ foreach (const VCard::Telephone& tel, vcard->getTelephones()) {
+ QString type = tel.isFax ? QObject::tr("Fax") : QObject::tr("Telephone");
+ QString field = buildVCardField(tel.isPreferred, type, htmlEscape(P2QSTRING(tel.number)));
+ if (tel.isPreferred) {
+ currentBlock = field;
+ break;
+ }
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ currentBlock = "";
+ foreach (const VCard::EMailAddress& mail, vcard->getEMailAddresses()) {
+ QString field = buildVCardField(mail.isPreferred, QObject::tr("E-Mail"), htmlEscape(P2QSTRING(mail.address)));
+ if (mail.isPreferred) {
+ currentBlock = field;
+ break;
+ }
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ currentBlock = "";
+ foreach (const VCard::Organization& org, vcard->getOrganizations()) {
+ QString field = buildVCardField(false, QObject::tr("Organization"), htmlEscape(P2QSTRING(org.name)));
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ currentBlock = "";
+ foreach(const std::string& title, vcard->getTitles()) {
+ QString field = buildVCardField(false, QObject::tr("Title"), htmlEscape(P2QSTRING(title)));
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ summary += "</table>";
+ return summary;
}
QString RosterTooltip::buildVCardField(bool preferred, const QString& name, const QString& content) {
- QString rowTemplate;
- if (QApplication::layoutDirection() == Qt::RightToLeft) {
- rowTemplate = QString("<tr><td>%3</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%1</td></tr>");
- } else {
- rowTemplate = QString("<tr><td>%1</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%3</td></tr>");
- }
- return rowTemplate.arg(preferred ? "<img src=':/icons/star-checked.png' />" : "", name, content);
+ QString rowTemplate;
+ if (QApplication::layoutDirection() == Qt::RightToLeft) {
+ rowTemplate = QString("<tr><td>%3</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%1</td></tr>");
+ } else {
+ rowTemplate = QString("<tr><td>%1</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%3</td></tr>");
+ }
+ return rowTemplate.arg(preferred ? "<img src=':/icons/star-checked.png' />" : "", name, content);
}
}
diff --git a/Swift/QtUI/Roster/RosterTooltip.h b/Swift/QtUI/Roster/RosterTooltip.h
index 37f5da2..642809f 100644
--- a/Swift/QtUI/Roster/RosterTooltip.h
+++ b/Swift/QtUI/Roster/RosterTooltip.h
@@ -16,12 +16,12 @@ class ContactRosterItem;
class QtScaledAvatarCache;
class RosterTooltip {
- public:
- static QString buildDetailedTooltip(ContactRosterItem* contact, QtScaledAvatarCache* cachedImageScaler);
+ public:
+ static QString buildDetailedTooltip(ContactRosterItem* contact, QtScaledAvatarCache* cachedImageScaler);
- private:
- static QString buildVCardSummary(VCard::ref vcard);
- static QString buildVCardField(bool preferred, const QString& name, const QString& content);
+ private:
+ static QString buildVCardSummary(VCard::ref vcard);
+ static QString buildVCardField(bool preferred, const QString& name, const QString& content);
};
}
diff --git a/Swift/QtUI/Roster/main.cpp b/Swift/QtUI/Roster/main.cpp
index 078fcaf..c0402e8 100644
--- a/Swift/QtUI/Roster/main.cpp
+++ b/Swift/QtUI/Roster/main.cpp
@@ -13,55 +13,55 @@
int main(int argc, char *argv[])
{
- QApplication app(argc, argv);
+ QApplication app(argc, argv);
- //Swift::RosterModel model;
+ //Swift::RosterModel model;
- //QTreeView view;
- //view.setModel(&model);
- //view.setWindowTitle("A roster");
- //view.show();
+ //QTreeView view;
+ //view.setModel(&model);
+ //view.setWindowTitle("A roster");
+ //view.show();
- Swift::QtTreeWidgetFactory treeWidgetFactory;
- Swift::QtTreeWidget* tree = dynamic_cast<Swift::QtTreeWidget*>(treeWidgetFactory.createTreeWidget());
- tree->show();
- QList<Swift::QtTreeWidgetItem*> item3s;
- for (int i = 0; i < 500; i++) {
- Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
- group->setText("People");
- group->setBackgroundColor(0xBBBBBB);
- Swift::QtTreeWidgetItem* item1 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- Swift::QtTreeWidgetItem* item2 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- Swift::QtTreeWidgetItem* item3 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- Swift::QtTreeWidgetItem* item4 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- item1->setText("Remko");
- item2->setText("Kevin");
- item3->setText("Cath");
- item4->setText("KimTypo");
- item4->setText("Kim");
- item3s.push_back(item3);
- }
-
- Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
- group->setText("Many People");
-
- Swift::QtTreeWidgetItem* person350;
- Swift::QtTreeWidgetItem* person1200;
+ Swift::QtTreeWidgetFactory treeWidgetFactory;
+ Swift::QtTreeWidget* tree = dynamic_cast<Swift::QtTreeWidget*>(treeWidgetFactory.createTreeWidget());
+ tree->show();
+ QList<Swift::QtTreeWidgetItem*> item3s;
+ for (int i = 0; i < 500; i++) {
+ Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
+ group->setText("People");
+ group->setBackgroundColor(0xBBBBBB);
+ Swift::QtTreeWidgetItem* item1 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ Swift::QtTreeWidgetItem* item2 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ Swift::QtTreeWidgetItem* item3 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ Swift::QtTreeWidgetItem* item4 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ item1->setText("Remko");
+ item2->setText("Kevin");
+ item3->setText("Cath");
+ item4->setText("KimTypo");
+ item4->setText("Kim");
+ item3s.push_back(item3);
+ }
- for (int i = 0; i < 1500; i++) {
- Swift::QtTreeWidgetItem* item = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- item->setText(Q2PSTRING(QString("Some person %1").arg(i)));
- item->setStatusShow(Swift::StatusShow::Away);
- if (i == 350) person350 = item;
- if (i == 1200) person1200 = item;
- }
+ Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
+ group->setText("Many People");
- for (int i = 0; i < item3s.size(); i++) {
- item3s[i]->setStatusShow(Swift::StatusShow::XA);
- }
+ Swift::QtTreeWidgetItem* person350;
+ Swift::QtTreeWidgetItem* person1200;
- person350->setStatusShow(Swift::StatusShow::DND);
- person1200->setStatusShow(Swift::StatusShow::Online);
+ for (int i = 0; i < 1500; i++) {
+ Swift::QtTreeWidgetItem* item = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ item->setText(Q2PSTRING(QString("Some person %1").arg(i)));
+ item->setStatusShow(Swift::StatusShow::Away);
+ if (i == 350) person350 = item;
+ if (i == 1200) person1200 = item;
+ }
- return app.exec();
+ for (int i = 0; i < item3s.size(); i++) {
+ item3s[i]->setStatusShow(Swift::StatusShow::XA);
+ }
+
+ person350->setStatusShow(Swift::StatusShow::DND);
+ person1200->setStatusShow(Swift::StatusShow::Online);
+
+ return app.exec();
}
diff --git a/Swift/QtUI/SystemMessageSnippet.cpp b/Swift/QtUI/SystemMessageSnippet.cpp
index 87c17b1..fbf8810 100644
--- a/Swift/QtUI/SystemMessageSnippet.cpp
+++ b/Swift/QtUI/SystemMessageSnippet.cpp
@@ -11,16 +11,16 @@
namespace Swift {
SystemMessageSnippet::SystemMessageSnippet(const QString& message, const QDateTime& time, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction) : ChatSnippet(appendToPrevious) {
- if (appendToPrevious) {
- setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new SystemMessageSnippet(message, time, false, theme, id, direction)));
- }
- content_ = theme->getStatus();
-
- content_.replace("%direction%", directionToCSS(direction));
- content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
- content_.replace("%shortTime%", wrapResizable(escape(time.toString("h:mm"))));
- content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
- content_.replace("%id%", id);
+ if (appendToPrevious) {
+ setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new SystemMessageSnippet(message, time, false, theme, id, direction)));
+ }
+ content_ = theme->getStatus();
+
+ content_.replace("%direction%", directionToCSS(direction));
+ content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
+ content_.replace("%shortTime%", wrapResizable(escape(time.toString("h:mm"))));
+ content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
+ content_.replace("%id%", id);
}
SystemMessageSnippet::~SystemMessageSnippet() {
diff --git a/Swift/QtUI/SystemMessageSnippet.h b/Swift/QtUI/SystemMessageSnippet.h
index a1f2682..c0d4d2f 100644
--- a/Swift/QtUI/SystemMessageSnippet.h
+++ b/Swift/QtUI/SystemMessageSnippet.h
@@ -13,18 +13,18 @@
class QDateTime;
namespace Swift {
- class SystemMessageSnippet : public ChatSnippet {
- public:
- SystemMessageSnippet(const QString& message, const QDateTime& time, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
- virtual ~SystemMessageSnippet();
+ class SystemMessageSnippet : public ChatSnippet {
+ public:
+ SystemMessageSnippet(const QString& message, const QDateTime& time, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
+ virtual ~SystemMessageSnippet();
- const QString& getContent() const {return content_;}
+ const QString& getContent() const {return content_;}
- /*QString getContinuationElementID() const {
- return "insert";
- };*/
+ /*QString getContinuationElementID() const {
+ return "insert";
+ };*/
- private:
- QString content_;
- };
+ private:
+ QString content_;
+ };
}
diff --git a/Swift/QtUI/Trellis/QtDNDTabBar.cpp b/Swift/QtUI/Trellis/QtDNDTabBar.cpp
index dbe397b..fac2233 100644
--- a/Swift/QtUI/Trellis/QtDNDTabBar.cpp
+++ b/Swift/QtUI/Trellis/QtDNDTabBar.cpp
@@ -18,12 +18,12 @@
namespace Swift {
QtDNDTabBar::QtDNDTabBar(QWidget* parent) : QTabBar(parent) {
- setAcceptDrops(true);
+ setAcceptDrops(true);
- // detect the default tab bar height;
- insertTab(0, "");
- defaultTabHeight = QTabBar::sizeHint().height();
- removeTab(0);
+ // detect the default tab bar height;
+ insertTab(0, "");
+ defaultTabHeight = QTabBar::sizeHint().height();
+ removeTab(0);
}
QtDNDTabBar::~QtDNDTabBar() {
@@ -31,136 +31,136 @@ QtDNDTabBar::~QtDNDTabBar() {
}
int QtDNDTabBar::getDragIndex() const {
- return dragIndex;
+ return dragIndex;
}
QString QtDNDTabBar::getDragText() const {
- return dragText;
+ return dragText;
}
QWidget* QtDNDTabBar::getDragWidget() const {
- return dragWidget;
+ return dragWidget;
}
QSize QtDNDTabBar::sizeHint() const {
- QSize hint = QTabBar::sizeHint();
- if (hint.isEmpty()) {
- hint = QSize(parentWidget()->width(), defaultTabHeight);
- }
- return hint;
+ QSize hint = QTabBar::sizeHint();
+ if (hint.isEmpty()) {
+ hint = QSize(parentWidget()->width(), defaultTabHeight);
+ }
+ return hint;
}
QSize QtDNDTabBar::tabSizeHint(int index) const {
- QSize tabSize = QTabBar::tabSizeHint(index);
+ QSize tabSize = QTabBar::tabSizeHint(index);
#if defined(Q_OS_MAC)
- // With multiple tabs having the same label in a QTabBar, the size hint computed by
- // Qt on OS X is too small and it is elided even though there is enough horizontal
- // space available. We work around this issue by adding the width of a letter to the
- // size hint.
- tabSize += QSize(QFontMetrics(font()).width("I"), 0);
+ // With multiple tabs having the same label in a QTabBar, the size hint computed by
+ // Qt on OS X is too small and it is elided even though there is enough horizontal
+ // space available. We work around this issue by adding the width of a letter to the
+ // size hint.
+ tabSize += QSize(QFontMetrics(font()).width("I"), 0);
#endif
- return tabSize;
+ return tabSize;
}
void QtDNDTabBar::dragEnterEvent(QDragEnterEvent* dragEnterEvent) {
- QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dragEnterEvent->source());
- if (sourceTabBar) {
- dragEnterEvent->acceptProposedAction();
- }
+ QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dragEnterEvent->source());
+ if (sourceTabBar) {
+ dragEnterEvent->acceptProposedAction();
+ }
}
void QtDNDTabBar::dropEvent(QDropEvent* dropEvent) {
- QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
- if (sourceTabBar && dropEvent->mimeData() && dropEvent->mimeData()->data("action") == QByteArray("application/tab-detach")) {
- QtDNDTabBar* source = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
-
- int targetTabIndex = tabAt(dropEvent->pos());
- QRect rect = tabRect(targetTabIndex);
- if (targetTabIndex >= 0 && (dropEvent->pos().x() - rect.left() - rect.width()/2 > 0)) {
- targetTabIndex++;
- }
-
- QWidget* tab = source->getDragWidget();
- assert(tab);
- QTabWidget* targetTabWidget = dynamic_cast<QTabWidget*>(parentWidget());
-
- QString tabText = source->getDragText();
-
- /*
- * When you add a widget to an empty QTabWidget, it's automatically made the current widget.
- * Making the widget the current widget, widget->show() is called for the widget. Directly reacting
- * to that event, and adding the widget again to the QTabWidget results in undefined behavior. For
- * example the tab label is shown but the widget is neither has the old nor in the new QTabWidget as
- * parent. Blocking signals on the QWidget to be added to a QTabWidget prevents this behavior.
- */
- targetTabWidget->setUpdatesEnabled(false);
- tab->blockSignals(true);
- targetTabWidget->insertTab(targetTabIndex, tab, tabText);
- dropEvent->acceptProposedAction();
- tab->blockSignals(false);
- targetTabWidget->setUpdatesEnabled(true);
- onDropSucceeded();
- }
+ QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
+ if (sourceTabBar && dropEvent->mimeData() && dropEvent->mimeData()->data("action") == QByteArray("application/tab-detach")) {
+ QtDNDTabBar* source = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
+
+ int targetTabIndex = tabAt(dropEvent->pos());
+ QRect rect = tabRect(targetTabIndex);
+ if (targetTabIndex >= 0 && (dropEvent->pos().x() - rect.left() - rect.width()/2 > 0)) {
+ targetTabIndex++;
+ }
+
+ QWidget* tab = source->getDragWidget();
+ assert(tab);
+ QTabWidget* targetTabWidget = dynamic_cast<QTabWidget*>(parentWidget());
+
+ QString tabText = source->getDragText();
+
+ /*
+ * When you add a widget to an empty QTabWidget, it's automatically made the current widget.
+ * Making the widget the current widget, widget->show() is called for the widget. Directly reacting
+ * to that event, and adding the widget again to the QTabWidget results in undefined behavior. For
+ * example the tab label is shown but the widget is neither has the old nor in the new QTabWidget as
+ * parent. Blocking signals on the QWidget to be added to a QTabWidget prevents this behavior.
+ */
+ targetTabWidget->setUpdatesEnabled(false);
+ tab->blockSignals(true);
+ targetTabWidget->insertTab(targetTabIndex, tab, tabText);
+ dropEvent->acceptProposedAction();
+ tab->blockSignals(false);
+ targetTabWidget->setUpdatesEnabled(true);
+ onDropSucceeded();
+ }
}
bool QtDNDTabBar::event(QEvent* event) {
- QMouseEvent* mouseEvent = dynamic_cast<QMouseEvent*>(event);
- if (mouseEvent) {
- QWidget* childAtPoint = window()->childAt(mapTo(window(), mouseEvent->pos()));
- QtDNDTabBar* underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint);
- if (!underMouse && childAtPoint) {
- underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint->parent());
- }
- if (!underMouse && currentIndex() >= 0) {
- // detach and drag
-
- // stop move event
- QMouseEvent* finishMoveEvent = new QMouseEvent (QEvent::MouseMove, mouseEvent->pos (), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
- QTabBar::event(finishMoveEvent);
- delete finishMoveEvent;
- finishMoveEvent = NULL;
-
- // start drag
- QDrag* drag = new QDrag(this);
- QMimeData* mimeData = new QMimeData;
-
- // distinguish tab-reordering drops from other ones
- mimeData->setData("action", "application/tab-detach") ;
- drag->setMimeData(mimeData);
-
- // set drag image
- QRect rect = tabRect( currentIndex() );
+ QMouseEvent* mouseEvent = dynamic_cast<QMouseEvent*>(event);
+ if (mouseEvent) {
+ QWidget* childAtPoint = window()->childAt(mapTo(window(), mouseEvent->pos()));
+ QtDNDTabBar* underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint);
+ if (!underMouse && childAtPoint) {
+ underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint->parent());
+ }
+ if (!underMouse && currentIndex() >= 0) {
+ // detach and drag
+
+ // stop move event
+ QMouseEvent* finishMoveEvent = new QMouseEvent (QEvent::MouseMove, mouseEvent->pos (), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
+ QTabBar::event(finishMoveEvent);
+ delete finishMoveEvent;
+ finishMoveEvent = NULL;
+
+ // start drag
+ QDrag* drag = new QDrag(this);
+ QMimeData* mimeData = new QMimeData;
+
+ // distinguish tab-reordering drops from other ones
+ mimeData->setData("action", "application/tab-detach") ;
+ drag->setMimeData(mimeData);
+
+ // set drag image
+ QRect rect = tabRect( currentIndex() );
#if QT_VERSION >= 0x050000
- QPixmap pixmap = grab(rect);
+ QPixmap pixmap = grab(rect);
#else
- QPixmap pixmap = QPixmap::grabWidget(this, rect);
+ QPixmap pixmap = QPixmap::grabWidget(this, rect);
#endif
- QPixmap targetPixmap (pixmap.size ());
- QPainter painter (&targetPixmap);
- painter.setOpacity(0.9);
- painter.drawPixmap(0,0, pixmap);
- painter.end ();
- drag->setPixmap (targetPixmap);
-
- drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height()));
-
- dragIndex = currentIndex();
- dragText = tabText(dragIndex);
- dragWidget = dynamic_cast<QTabWidget*>(parent())->widget(dragIndex);
- assert(dragWidget);
- dynamic_cast<QTabWidget*>(parent())->removeTab(currentIndex());
- Qt::DropAction dropAction = drag->exec();
- if (dropAction == Qt::IgnoreAction) {
- // aborted drag, put tab back in place
- // disable event handling during the insert for the tab to prevent infinite recursion (stack overflow)
- dragWidget->blockSignals(true);
- dynamic_cast<QTabWidget*>(parent())->insertTab(dragIndex, dragWidget, dragText);
- dragWidget->blockSignals(false);
- }
- return true;
- }
- }
- return QTabBar::event(event);
+ QPixmap targetPixmap (pixmap.size ());
+ QPainter painter (&targetPixmap);
+ painter.setOpacity(0.9);
+ painter.drawPixmap(0,0, pixmap);
+ painter.end ();
+ drag->setPixmap (targetPixmap);
+
+ drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height()));
+
+ dragIndex = currentIndex();
+ dragText = tabText(dragIndex);
+ dragWidget = dynamic_cast<QTabWidget*>(parent())->widget(dragIndex);
+ assert(dragWidget);
+ dynamic_cast<QTabWidget*>(parent())->removeTab(currentIndex());
+ Qt::DropAction dropAction = drag->exec();
+ if (dropAction == Qt::IgnoreAction) {
+ // aborted drag, put tab back in place
+ // disable event handling during the insert for the tab to prevent infinite recursion (stack overflow)
+ dragWidget->blockSignals(true);
+ dynamic_cast<QTabWidget*>(parent())->insertTab(dragIndex, dragWidget, dragText);
+ dragWidget->blockSignals(false);
+ }
+ return true;
+ }
+ }
+ return QTabBar::event(event);
}
}
diff --git a/Swift/QtUI/Trellis/QtDNDTabBar.h b/Swift/QtUI/Trellis/QtDNDTabBar.h
index 71ca94b..3677b73 100644
--- a/Swift/QtUI/Trellis/QtDNDTabBar.h
+++ b/Swift/QtUI/Trellis/QtDNDTabBar.h
@@ -11,31 +11,31 @@
namespace Swift {
class QtDNDTabBar : public QTabBar {
- Q_OBJECT
- public:
- explicit QtDNDTabBar(QWidget* parent = 0);
- virtual ~QtDNDTabBar();
-
- int getDragIndex() const;
- QString getDragText() const;
- QWidget* getDragWidget() const;
-
- virtual QSize sizeHint() const;
-
- signals:
- void onDropSucceeded();
-
- protected:
- virtual void dragEnterEvent(QDragEnterEvent* dragEnterEvent);
- virtual void dropEvent(QDropEvent* dropEvent);
- virtual bool event(QEvent* event);
- virtual QSize tabSizeHint(int index) const;
-
- private:
- int defaultTabHeight;
- int dragIndex;
- QString dragText;
- QWidget* dragWidget;
+ Q_OBJECT
+ public:
+ explicit QtDNDTabBar(QWidget* parent = 0);
+ virtual ~QtDNDTabBar();
+
+ int getDragIndex() const;
+ QString getDragText() const;
+ QWidget* getDragWidget() const;
+
+ virtual QSize sizeHint() const;
+
+ signals:
+ void onDropSucceeded();
+
+ protected:
+ virtual void dragEnterEvent(QDragEnterEvent* dragEnterEvent);
+ virtual void dropEvent(QDropEvent* dropEvent);
+ virtual bool event(QEvent* event);
+ virtual QSize tabSizeHint(int index) const;
+
+ private:
+ int defaultTabHeight;
+ int dragIndex;
+ QString dragText;
+ QWidget* dragWidget;
};
}
diff --git a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
index 3b8adf8..7de2791 100644
--- a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
+++ b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
@@ -24,127 +24,127 @@
namespace Swift {
QtDynamicGridLayout::QtDynamicGridLayout(QWidget* parent, bool enableDND) : QWidget(parent), dndEnabled_(enableDND), movingTab_(NULL) {
- gridLayout_ = new QGridLayout(this);
- setContentsMargins(0,0,0,0);
- setDimensions(QSize(1,1));
- connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*,QWidget*)));
+ gridLayout_ = new QGridLayout(this);
+ setContentsMargins(0,0,0,0);
+ setDimensions(QSize(1,1));
+ connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*,QWidget*)));
}
QtDynamicGridLayout::~QtDynamicGridLayout() {
}
int QtDynamicGridLayout::addTab(QtTabbable* tab, const QString& title) {
- assert(gridLayout_->rowCount() > 0 && gridLayout_->columnCount() > 0);
+ assert(gridLayout_->rowCount() > 0 && gridLayout_->columnCount() > 0);
- QPoint lastPos(0,0);
- if (tabPositions_.contains(P2QSTRING(tab->getID()))) {
- lastPos = tabPositions_[P2QSTRING(tab->getID())];
- }
+ QPoint lastPos(0,0);
+ if (tabPositions_.contains(P2QSTRING(tab->getID()))) {
+ lastPos = tabPositions_[P2QSTRING(tab->getID())];
+ }
- lastPos = QPoint(qMin(lastPos.x(), gridLayout_->columnCount() - 1), qMin(lastPos.y(), gridLayout_->rowCount() - 1));
+ lastPos = QPoint(qMin(lastPos.x(), gridLayout_->columnCount() - 1), qMin(lastPos.y(), gridLayout_->rowCount() - 1));
- QLayoutItem* item = gridLayout_->itemAtPosition(lastPos.y(), lastPos.x());
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(item ? item->widget() : 0);
- if (tabWidget) {
- tabWidget->addTab(tab, title);
- }
- return tabWidget ? indexOf(tab) : -1;
+ QLayoutItem* item = gridLayout_->itemAtPosition(lastPos.y(), lastPos.x());
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(item ? item->widget() : 0);
+ if (tabWidget) {
+ tabWidget->addTab(tab, title);
+ }
+ return tabWidget ? indexOf(tab) : -1;
}
int QtDynamicGridLayout::count() const {
- int count = 0;
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- count += tabWidget->count();
- }
- }
- }
- return count;
+ int count = 0;
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ count += tabWidget->count();
+ }
+ }
+ }
+ return count;
}
QWidget* QtDynamicGridLayout::widget(int index) const {
- QWidget* widgetAtIndex = NULL;
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- if (index < tabWidget->count()) {
- widgetAtIndex = tabWidget->widget(index);
- return widgetAtIndex;
- }
- else {
- index -= tabWidget->count();
- }
- }
- }
- }
- return widgetAtIndex;
+ QWidget* widgetAtIndex = NULL;
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ if (index < tabWidget->count()) {
+ widgetAtIndex = tabWidget->widget(index);
+ return widgetAtIndex;
+ }
+ else {
+ index -= tabWidget->count();
+ }
+ }
+ }
+ }
+ return widgetAtIndex;
}
int QtDynamicGridLayout::indexOf(const QWidget* widget) const {
- int index = 0;
- if (widget) {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- for (int n = 0; n < tabWidget->count(); n++) {
- QWidget* nthWidget = tabWidget->widget(n);
- if (nthWidget == widget) {
- return index;
- }
- index++;
- }
- }
- }
- }
- }
- return -1;
+ int index = 0;
+ if (widget) {
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ for (int n = 0; n < tabWidget->count(); n++) {
+ QWidget* nthWidget = tabWidget->widget(n);
+ if (nthWidget == widget) {
+ return index;
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ return -1;
}
void QtDynamicGridLayout::handleApplicationFocusChanged(QWidget*, QWidget* newFocus) {
- if (movingTab_) {
- return;
- }
-
- if (newFocus) {
- if (isAncestorOf(newFocus)) {
- QtTabbable *newTab = dynamic_cast<QtTabbable*>(newFocus->parentWidget());
- if (newTab) {
- onCurrentIndexChanged(currentIndex());
- }
- }
- }
+ if (movingTab_) {
+ return;
+ }
+
+ if (newFocus) {
+ if (isAncestorOf(newFocus)) {
+ QtTabbable *newTab = dynamic_cast<QtTabbable*>(newFocus->parentWidget());
+ if (newTab) {
+ onCurrentIndexChanged(currentIndex());
+ }
+ }
+ }
}
int QtDynamicGridLayout::currentIndex() const {
- return indexOf(currentWidget());
+ return indexOf(currentWidget());
}
void QtDynamicGridLayout::setCurrentIndex(int index) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- if (tabIndex >= 0) {
- tabWidget->setCurrentIndex(tabIndex);
- if (!tabWidget->hasFocus()) {
- tabWidget->widget(tabIndex)->setFocus(Qt::TabFocusReason);
- }
- } else {
- assert(false);
- }
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ if (tabIndex >= 0) {
+ tabWidget->setCurrentIndex(tabIndex);
+ if (!tabWidget->hasFocus()) {
+ tabWidget->widget(tabIndex)->setFocus(Qt::TabFocusReason);
+ }
+ } else {
+ assert(false);
+ }
}
void QtDynamicGridLayout::removeTab(int index) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- if (tabWidget) {
- tabWidget->removeTab(tabIndex);
- }
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ if (tabWidget) {
+ tabWidget->removeTab(tabIndex);
+ }
}
/**
@@ -158,348 +158,348 @@ void QtDynamicGridLayout::removeTab(int index) {
* being out of sync in an inconsistent state.
*/
bool QtDynamicGridLayout::eventFilter(QObject* object, QEvent* event) {
- QtTabbable* tab = qobject_cast<QtTabbable*>(object);
- if (!tab) {
- return false;
- }
- if (tab && (tab != movingTab_)) {
- if (event->type() == QEvent::Show) {
- return true;
- }
- }
- return false;
+ QtTabbable* tab = qobject_cast<QtTabbable*>(object);
+ if (!tab) {
+ return false;
+ }
+ if (tab && (tab != movingTab_)) {
+ if (event->type() == QEvent::Show) {
+ return true;
+ }
+ }
+ return false;
}
QWidget* QtDynamicGridLayout::currentWidget() const {
- QWidget* current = NULL;
- current = focusWidget();
- while (current && !dynamic_cast<QtTabbable*>(current)) {
- if (current->parentWidget()) {
- current = current->parentWidget();
- } else {
- current = NULL;
- break;
- }
- }
- if (!current) {
- current = widget(0);
- }
- return current;
+ QWidget* current = NULL;
+ current = focusWidget();
+ while (current && !dynamic_cast<QtTabbable*>(current)) {
+ if (current->parentWidget()) {
+ current = current->parentWidget();
+ } else {
+ current = NULL;
+ break;
+ }
+ }
+ if (!current) {
+ current = widget(0);
+ }
+ return current;
}
void QtDynamicGridLayout::setCurrentWidget(QWidget* widget) {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- for (int n = 0; n < tabWidget->count(); n++) {
- if (tabWidget->widget(n) == widget) {
- tabWidget->setCurrentWidget(widget);
- }
- }
- }
- }
- }
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ for (int n = 0; n < tabWidget->count(); n++) {
+ if (tabWidget->widget(n) == widget) {
+ tabWidget->setCurrentWidget(widget);
+ }
+ }
+ }
+ }
+ }
}
QtTabWidget* QtDynamicGridLayout::indexToTabWidget(int index, int& tabIndex) {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- if (index < tabWidget->count()) {
- tabIndex = index;
- return tabWidget;
- }
- else {
- index -= tabWidget->count();
- if (index < 0) {
- qWarning() << "Called QtDynamicGridLayout::setCurrentIndex with index out of bounds: index = " << index;
- tabIndex = -1;
- return NULL;
- }
- }
- }
- }
- }
- tabIndex = -1;
- return NULL;
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ if (index < tabWidget->count()) {
+ tabIndex = index;
+ return tabWidget;
+ }
+ else {
+ index -= tabWidget->count();
+ if (index < 0) {
+ qWarning() << "Called QtDynamicGridLayout::setCurrentIndex with index out of bounds: index = " << index;
+ tabIndex = -1;
+ return NULL;
+ }
+ }
+ }
+ }
+ }
+ tabIndex = -1;
+ return NULL;
}
bool QtDynamicGridLayout::isDNDEnabled() const {
- return dndEnabled_;
+ return dndEnabled_;
}
QHash<QString, QPoint> QtDynamicGridLayout::getTabPositions() const {
- return tabPositions_;
+ return tabPositions_;
}
void QtDynamicGridLayout::setTabPositions(const QHash<QString, QPoint> positions) {
- tabPositions_ = positions;
+ tabPositions_ = positions;
}
QSize QtDynamicGridLayout::getDimension() const {
- return QSize(gridLayout_->columnCount(), gridLayout_->rowCount());
+ return QSize(gridLayout_->columnCount(), gridLayout_->rowCount());
}
void QtDynamicGridLayout::setDimensions(const QSize& dim) {
- assert(dim.width() > 0 && dim.height() > 0);
- setUpdatesEnabled(false);
-
- QGridLayout* oldLayout = dynamic_cast<QGridLayout*>(layout());
- QGridLayout* newLayout = new QGridLayout;
- newLayout->setSpacing(4);
- newLayout->setContentsMargins(0,0,0,0);
-
- int oldWidth = oldLayout->columnCount();
- int oldHeight = oldLayout->rowCount();
- int maxCol = qMax(oldWidth, dim.width());
- int minCol = qMin(oldWidth, dim.width());
- int maxRow = qMax(oldHeight, dim.height());
- int minRow = qMin(oldHeight, dim.height());
-
- for (int row = 0; row < maxRow; row++) {
- for (int col = 0; col < maxCol; col++) {
- QLayoutItem* oldItem = oldLayout->itemAtPosition(row, col);
- QLayoutItem* newItem = newLayout->itemAtPosition(row, col);
- bool removeRow = !(row < dim.height());
- bool removeCol = !(col < dim.width());
-
- if (removeCol || removeRow) {
- if (oldItem) {
- int squeezeRow = removeRow ? (minRow - 1) : row;
- int squeezeCol = removeCol ? (minCol - 1) : col;
- newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
- if (!newItem) {
- newLayout->addWidget(createDNDTabWidget(this), squeezeRow, squeezeCol);
- newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
- }
- QtTabWidget* oldTabWidget = dynamic_cast<QtTabWidget*>(oldItem->widget());
- QtTabWidget* newTabWidget = dynamic_cast<QtTabWidget*>(newItem->widget());
- assert(oldTabWidget && newTabWidget);
-
- oldTabWidget->hide();
- while(oldTabWidget->count()) {
- QIcon icon = oldTabWidget->tabIcon(0);
- QString text = oldTabWidget->tabText(0);
- newTabWidget->addTab(oldTabWidget->widget(0), icon, text);
- }
- delete oldTabWidget;
- }
- } else {
- if (oldItem) {
- newLayout->addWidget(oldItem->widget(), row, col);
- newItem = newLayout->itemAtPosition(row, col);
- } else {
- newLayout->addWidget(createDNDTabWidget(this), row, col);
- }
- }
- }
- }
-
- for (int col = 0; col < dim.width(); col++) {
- newLayout->setColumnStretch(col, 1);
- }
- for (int row = 0; row < dim.height(); row++) {
- newLayout->setRowStretch(row, 1);
- }
-
- setUpdatesEnabled(true);
- delete layout();
- setLayout(newLayout);
- gridLayout_ = newLayout;
+ assert(dim.width() > 0 && dim.height() > 0);
+ setUpdatesEnabled(false);
+
+ QGridLayout* oldLayout = dynamic_cast<QGridLayout*>(layout());
+ QGridLayout* newLayout = new QGridLayout;
+ newLayout->setSpacing(4);
+ newLayout->setContentsMargins(0,0,0,0);
+
+ int oldWidth = oldLayout->columnCount();
+ int oldHeight = oldLayout->rowCount();
+ int maxCol = qMax(oldWidth, dim.width());
+ int minCol = qMin(oldWidth, dim.width());
+ int maxRow = qMax(oldHeight, dim.height());
+ int minRow = qMin(oldHeight, dim.height());
+
+ for (int row = 0; row < maxRow; row++) {
+ for (int col = 0; col < maxCol; col++) {
+ QLayoutItem* oldItem = oldLayout->itemAtPosition(row, col);
+ QLayoutItem* newItem = newLayout->itemAtPosition(row, col);
+ bool removeRow = !(row < dim.height());
+ bool removeCol = !(col < dim.width());
+
+ if (removeCol || removeRow) {
+ if (oldItem) {
+ int squeezeRow = removeRow ? (minRow - 1) : row;
+ int squeezeCol = removeCol ? (minCol - 1) : col;
+ newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
+ if (!newItem) {
+ newLayout->addWidget(createDNDTabWidget(this), squeezeRow, squeezeCol);
+ newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
+ }
+ QtTabWidget* oldTabWidget = dynamic_cast<QtTabWidget*>(oldItem->widget());
+ QtTabWidget* newTabWidget = dynamic_cast<QtTabWidget*>(newItem->widget());
+ assert(oldTabWidget && newTabWidget);
+
+ oldTabWidget->hide();
+ while(oldTabWidget->count()) {
+ QIcon icon = oldTabWidget->tabIcon(0);
+ QString text = oldTabWidget->tabText(0);
+ newTabWidget->addTab(oldTabWidget->widget(0), icon, text);
+ }
+ delete oldTabWidget;
+ }
+ } else {
+ if (oldItem) {
+ newLayout->addWidget(oldItem->widget(), row, col);
+ newItem = newLayout->itemAtPosition(row, col);
+ } else {
+ newLayout->addWidget(createDNDTabWidget(this), row, col);
+ }
+ }
+ }
+ }
+
+ for (int col = 0; col < dim.width(); col++) {
+ newLayout->setColumnStretch(col, 1);
+ }
+ for (int row = 0; row < dim.height(); row++) {
+ newLayout->setRowStretch(row, 1);
+ }
+
+ setUpdatesEnabled(true);
+ delete layout();
+ setLayout(newLayout);
+ gridLayout_ = newLayout;
}
void QtDynamicGridLayout::moveCurrentTabRight() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- assert(tabWidget);
- int newTabIndex = (tabIndex + 1) % tabWidget->count();
- moveTab(tabWidget, tabIndex, newTabIndex);
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ assert(tabWidget);
+ int newTabIndex = (tabIndex + 1) % tabWidget->count();
+ moveTab(tabWidget, tabIndex, newTabIndex);
+ }
}
void QtDynamicGridLayout::moveCurrentTabLeft() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- assert(tabWidget);
- int newTabIndex = (tabWidget->count() + tabIndex - 1) % tabWidget->count();
- moveTab(tabWidget, tabIndex, newTabIndex);
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ assert(tabWidget);
+ int newTabIndex = (tabWidget->count() + tabIndex - 1) % tabWidget->count();
+ moveTab(tabWidget, tabIndex, newTabIndex);
+ }
}
void QtDynamicGridLayout::moveCurrentTabToNextGroup() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
-
- int row = -1;
- int col = -1;
- int tmp;
- gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
-
- // calculate next cell
- col++;
- if (!(col < gridLayout_->columnCount())) {
- col = 0;
- row++;
- if (!(row < gridLayout_->rowCount())) {
- row = 0;
- }
- }
-
- QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
- assert(tabWidget);
- assert(targetTabWidget);
-
- // fetch tab information
- QWidget* tab = tabWidget->widget(tabIndex);
- QString tabText = tabWidget->tabText(tabIndex);
-
- // move tab
- tab->blockSignals(true);
- targetTabWidget->addTab(tab, tabText);
- tab->blockSignals(false);
- tab->setFocus(Qt::TabFocusReason);
-
- updateTabPositions();
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+
+ int row = -1;
+ int col = -1;
+ int tmp;
+ gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
+
+ // calculate next cell
+ col++;
+ if (!(col < gridLayout_->columnCount())) {
+ col = 0;
+ row++;
+ if (!(row < gridLayout_->rowCount())) {
+ row = 0;
+ }
+ }
+
+ QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
+ assert(tabWidget);
+ assert(targetTabWidget);
+
+ // fetch tab information
+ QWidget* tab = tabWidget->widget(tabIndex);
+ QString tabText = tabWidget->tabText(tabIndex);
+
+ // move tab
+ tab->blockSignals(true);
+ targetTabWidget->addTab(tab, tabText);
+ tab->blockSignals(false);
+ tab->setFocus(Qt::TabFocusReason);
+
+ updateTabPositions();
+ }
}
void QtDynamicGridLayout::moveCurrentTabToPreviousGroup() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
-
- int row = -1;
- int col = -1;
- int tmp;
- gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
-
- // calculate next cell
- col--;
- if (col < 0) {
- col = gridLayout_->columnCount() - 1;
- row--;
- if (row < 0) {
- row = gridLayout_->rowCount() - 1;
- }
- }
-
- QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
- assert(tabWidget);
- assert(targetTabWidget);
-
- // fetch tab information
- QWidget* tab = tabWidget->widget(tabIndex);
- QString tabText = tabWidget->tabText(tabIndex);
-
- // move tab
- tab->blockSignals(true);
- targetTabWidget->addTab(tab, tabText);
- tab->blockSignals(false);
- tab->setFocus(Qt::TabFocusReason);
-
- updateTabPositions();
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+
+ int row = -1;
+ int col = -1;
+ int tmp;
+ gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
+
+ // calculate next cell
+ col--;
+ if (col < 0) {
+ col = gridLayout_->columnCount() - 1;
+ row--;
+ if (row < 0) {
+ row = gridLayout_->rowCount() - 1;
+ }
+ }
+
+ QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
+ assert(tabWidget);
+ assert(targetTabWidget);
+
+ // fetch tab information
+ QWidget* tab = tabWidget->widget(tabIndex);
+ QString tabText = tabWidget->tabText(tabIndex);
+
+ // move tab
+ tab->blockSignals(true);
+ targetTabWidget->addTab(tab, tabText);
+ tab->blockSignals(false);
+ tab->setFocus(Qt::TabFocusReason);
+
+ updateTabPositions();
+ }
}
void QtDynamicGridLayout::handleTabCloseRequested(int index) {
- updateTabPositions();
- QtTabWidget* tabWidgetSender = dynamic_cast<QtTabWidget*>(sender());
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget == tabWidgetSender) {
- tabCloseRequested(index);
- }
- else {
- index += tabWidget->count();
- }
- }
- }
+ updateTabPositions();
+ QtTabWidget* tabWidgetSender = dynamic_cast<QtTabWidget*>(sender());
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget == tabWidgetSender) {
+ tabCloseRequested(index);
+ }
+ else {
+ index += tabWidget->count();
+ }
+ }
+ }
}
void QtDynamicGridLayout::handleTabCurrentChanged(int index) {
- if (movingTab_) {
- return;
- }
-
- if (index >= 0) {
- QTabWidget* sendingTabWidget = dynamic_cast<QTabWidget*>(sender());
- assert(sendingTabWidget);
- sendingTabWidget->widget(index)->setFocus();
- }
+ if (movingTab_) {
+ return;
+ }
+
+ if (index >= 0) {
+ QTabWidget* sendingTabWidget = dynamic_cast<QTabWidget*>(sender());
+ assert(sendingTabWidget);
+ sendingTabWidget->widget(index)->setFocus();
+ }
}
void QtDynamicGridLayout::updateTabPositions() {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- assert(tabWidget);
- for (int index = 0; index < tabWidget->count(); index++) {
- QtTabbable* tab = dynamic_cast<QtTabbable*>(tabWidget->widget(index));
- assert(tab);
- tabPositions_.insert(P2QSTRING(tab->getID()), QPoint(x, y));
- }
- }
- }
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ assert(tabWidget);
+ for (int index = 0; index < tabWidget->count(); index++) {
+ QtTabbable* tab = dynamic_cast<QtTabbable*>(tabWidget->widget(index));
+ assert(tab);
+ tabPositions_.insert(P2QSTRING(tab->getID()), QPoint(x, y));
+ }
+ }
+ }
}
void QtDynamicGridLayout::moveTab(QtTabWidget* tabWidget, int oldIndex, int newIndex) {
#if QT_VERSION >= 0x040500
- SWIFT_LOG_ASSERT(movingTab_ == NULL, error) << std::endl;
- movingTab_ = qobject_cast<QtTabbable*>(tabWidget->widget(oldIndex));
- SWIFT_LOG_ASSERT(movingTab_ != NULL, error) << std::endl;
-
- if (movingTab_) {
- // Install event filter that filters out events issued during the internal movement of the
- // tab but not targeted at the moving tab.
- qApp->installEventFilter(this);
-
- tabWidget->tabBar()->moveTab(oldIndex, newIndex);
-
- qApp->removeEventFilter(this);
- SWIFT_LOG_ASSERT(movingTab_ == tabWidget->widget(newIndex), error) << std::endl;
- }
- movingTab_ = NULL;
- tabWidget->widget(newIndex)->setFocus();
+ SWIFT_LOG_ASSERT(movingTab_ == NULL, error) << std::endl;
+ movingTab_ = qobject_cast<QtTabbable*>(tabWidget->widget(oldIndex));
+ SWIFT_LOG_ASSERT(movingTab_ != NULL, error) << std::endl;
+
+ if (movingTab_) {
+ // Install event filter that filters out events issued during the internal movement of the
+ // tab but not targeted at the moving tab.
+ qApp->installEventFilter(this);
+
+ tabWidget->tabBar()->moveTab(oldIndex, newIndex);
+
+ qApp->removeEventFilter(this);
+ SWIFT_LOG_ASSERT(movingTab_ == tabWidget->widget(newIndex), error) << std::endl;
+ }
+ movingTab_ = NULL;
+ tabWidget->widget(newIndex)->setFocus();
#else
#warning Qt 4.5 or later is needed. Trying anyway, some things will be disabled.
#endif
}
QtTabWidget* QtDynamicGridLayout::createDNDTabWidget(QWidget* parent) {
- QtTabWidget* tab = new QtTabWidget(parent);
- if (dndEnabled_) {
- QtDNDTabBar* tabBar = new QtDNDTabBar(tab);
- connect(tabBar, SIGNAL(onDropSucceeded()), this, SLOT(updateTabPositions()));
- tab->setTabBar(tabBar);
- }
- tab->setUsesScrollButtons(true);
- tab->setElideMode(Qt::ElideRight);
+ QtTabWidget* tab = new QtTabWidget(parent);
+ if (dndEnabled_) {
+ QtDNDTabBar* tabBar = new QtDNDTabBar(tab);
+ connect(tabBar, SIGNAL(onDropSucceeded()), this, SLOT(updateTabPositions()));
+ tab->setTabBar(tabBar);
+ }
+ tab->setUsesScrollButtons(true);
+ tab->setElideMode(Qt::ElideRight);
#if QT_VERSION >= 0x040500
- /*For Macs, change the tab rendering.*/
- tab->setDocumentMode(true);
- /*Closable tabs are only in Qt4.5 and later*/
- tab->setTabsClosable(true);
- tab->setMovable(true);
- connect(tab, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
- connect(tab, SIGNAL(currentChanged(int)), this, SLOT(handleTabCurrentChanged(int)));
+ /*For Macs, change the tab rendering.*/
+ tab->setDocumentMode(true);
+ /*Closable tabs are only in Qt4.5 and later*/
+ tab->setTabsClosable(true);
+ tab->setMovable(true);
+ connect(tab, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
+ connect(tab, SIGNAL(currentChanged(int)), this, SLOT(handleTabCurrentChanged(int)));
#else
#warning Qt 4.5 or later is needed. Trying anyway, some things will be disabled.
#endif
- return tab;
+ return tab;
}
}
diff --git a/Swift/QtUI/Trellis/QtDynamicGridLayout.h b/Swift/QtUI/Trellis/QtDynamicGridLayout.h
index ed8a9fc..2a6029c 100644
--- a/Swift/QtUI/Trellis/QtDynamicGridLayout.h
+++ b/Swift/QtUI/Trellis/QtDynamicGridLayout.h
@@ -14,67 +14,67 @@
#include <QWidget>
namespace Swift {
- class QtTabbable;
- class QtTabWidget;
+ class QtTabbable;
+ class QtTabWidget;
- class QtDynamicGridLayout : public QWidget {
- Q_OBJECT
- public:
- explicit QtDynamicGridLayout(QWidget* parent = 0, bool enableDND = false);
- virtual ~QtDynamicGridLayout();
+ class QtDynamicGridLayout : public QWidget {
+ Q_OBJECT
+ public:
+ explicit QtDynamicGridLayout(QWidget* parent = 0, bool enableDND = false);
+ virtual ~QtDynamicGridLayout();
- QSize getDimension() const;
+ QSize getDimension() const;
- // emulate QtTabWidget API
- int addTab(QtTabbable* tab, const QString& title);
- void removeTab(int index);
- int count() const;
+ // emulate QtTabWidget API
+ int addTab(QtTabbable* tab, const QString& title);
+ void removeTab(int index);
+ int count() const;
- QWidget* widget(int index) const;
- QWidget* currentWidget() const;
- void setCurrentWidget(QWidget* widget);
+ QWidget* widget(int index) const;
+ QWidget* currentWidget() const;
+ void setCurrentWidget(QWidget* widget);
- QtTabWidget* indexToTabWidget(int index, int& tabIndex);
+ QtTabWidget* indexToTabWidget(int index, int& tabIndex);
- int indexOf(const QWidget* widget) const;
- int currentIndex() const;
- void setCurrentIndex(int index);
+ int indexOf(const QWidget* widget) const;
+ int currentIndex() const;
+ void setCurrentIndex(int index);
- bool isDNDEnabled() const;
+ bool isDNDEnabled() const;
- QHash<QString, QPoint> getTabPositions() const;
- void setTabPositions(const QHash<QString, QPoint> positions);
+ QHash<QString, QPoint> getTabPositions() const;
+ void setTabPositions(const QHash<QString, QPoint> positions);
- bool eventFilter(QObject* object, QEvent* event);
+ bool eventFilter(QObject* object, QEvent* event);
- signals:
- void tabCloseRequested(int index);
- void onCurrentIndexChanged(int newIndex);
+ signals:
+ void tabCloseRequested(int index);
+ void onCurrentIndexChanged(int newIndex);
- public slots:
- void setDimensions(const QSize& dim);
+ public slots:
+ void setDimensions(const QSize& dim);
- // Tab Management
- void moveCurrentTabRight();
- void moveCurrentTabLeft();
- void moveCurrentTabToNextGroup();
- void moveCurrentTabToPreviousGroup();
+ // Tab Management
+ void moveCurrentTabRight();
+ void moveCurrentTabLeft();
+ void moveCurrentTabToNextGroup();
+ void moveCurrentTabToPreviousGroup();
- void updateTabPositions();
+ void updateTabPositions();
- private slots:
- void handleTabCloseRequested(int index);
- void handleTabCurrentChanged(int index);
- void handleApplicationFocusChanged(QWidget* oldFocus, QWidget* newFocus);
+ private slots:
+ void handleTabCloseRequested(int index);
+ void handleTabCurrentChanged(int index);
+ void handleApplicationFocusChanged(QWidget* oldFocus, QWidget* newFocus);
- private:
- void moveTab(QtTabWidget* tabWidget, int oldIndex, int newIndex);
- QtTabWidget* createDNDTabWidget(QWidget* parent);
+ private:
+ void moveTab(QtTabWidget* tabWidget, int oldIndex, int newIndex);
+ QtTabWidget* createDNDTabWidget(QWidget* parent);
- private:
- QGridLayout *gridLayout_;
- bool dndEnabled_;
- QHash<QString, QPoint> tabPositions_;
- QtTabbable* movingTab_;
- };
+ private:
+ QGridLayout *gridLayout_;
+ bool dndEnabled_;
+ QHash<QString, QPoint> tabPositions_;
+ QtTabbable* movingTab_;
+ };
}
diff --git a/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp b/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
index a3a1bf8..c7b7edb 100644
--- a/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
+++ b/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
@@ -16,142 +16,142 @@
namespace Swift {
QtGridSelectionDialog::QtGridSelectionDialog(QWidget* parent) : QWidget(parent) {
- frameSize = QSize(23,23) * 2;
- maxGridSize = QSize(7,7);
- minGridSize = QSize(1,1);
- currentGridSize = QSize(1,1);
- padding = 4;
- setWindowFlags(Qt::FramelessWindowHint);
- setCursor(Qt::SizeAllCursor);
- horizontalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
- verticalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
+ frameSize = QSize(23,23) * 2;
+ maxGridSize = QSize(7,7);
+ minGridSize = QSize(1,1);
+ currentGridSize = QSize(1,1);
+ padding = 4;
+ setWindowFlags(Qt::FramelessWindowHint);
+ setCursor(Qt::SizeAllCursor);
+ horizontalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
+ verticalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
}
QSize QtGridSelectionDialog::sizeHint() const {
- // PM_MenuVMargin | frameSize | ( padding | frameSize ) * | PM_MenuVMargin
- int width = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) + horizontalMargin;
- int height = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) + verticalMargin;
- return QSize(width, height);
+ // PM_MenuVMargin | frameSize | ( padding | frameSize ) * | PM_MenuVMargin
+ int width = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) + horizontalMargin;
+ int height = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) + verticalMargin;
+ return QSize(width, height);
}
void QtGridSelectionDialog::setCurrentGridSize(const QSize& size) {
- currentGridSize = size;
- emit currentGridSizeChanged(size);
+ currentGridSize = size;
+ emit currentGridSizeChanged(size);
}
QSize QtGridSelectionDialog::getCurrentGridSize() const {
- return currentGridSize;
+ return currentGridSize;
}
void QtGridSelectionDialog::setMinGridSize(const QSize& size) {
- minGridSize = size;
- emit minGridSizeChanged(size);
+ minGridSize = size;
+ emit minGridSizeChanged(size);
}
QSize QtGridSelectionDialog::getMinGridSize() const {
- return minGridSize;
+ return minGridSize;
}
void QtGridSelectionDialog::setMaxGridSize(const QSize& size) {
- maxGridSize = size;
- emit maxGridSizeChanged(size);
+ maxGridSize = size;
+ emit maxGridSizeChanged(size);
}
QSize QtGridSelectionDialog::getMaxGridSize() const {
- return maxGridSize;
+ return maxGridSize;
}
void QtGridSelectionDialog::keyReleaseEvent(QKeyEvent* event) {
- if (event) {
- QSize newGridSize = currentGridSize;
- if (event->key() == Qt::Key_Up) {
- newGridSize += QSize(0, -1);
- }
- else if (event->key() == Qt::Key_Down) {
- newGridSize += QSize(0, 1);
- }
- else if (event->key() == Qt::Key_Left) {
- newGridSize += QSize(-1, 0);
- }
- else if (event->key() == Qt::Key_Right) {
- newGridSize += QSize(1, 0);
- }
- else if (event->key() == Qt::Key_Return) {
- hide();
- setCurrentGridSize(currentGridSize);
- }
- if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
- currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
- resize(sizeHint());
- }
- }
+ if (event) {
+ QSize newGridSize = currentGridSize;
+ if (event->key() == Qt::Key_Up) {
+ newGridSize += QSize(0, -1);
+ }
+ else if (event->key() == Qt::Key_Down) {
+ newGridSize += QSize(0, 1);
+ }
+ else if (event->key() == Qt::Key_Left) {
+ newGridSize += QSize(-1, 0);
+ }
+ else if (event->key() == Qt::Key_Right) {
+ newGridSize += QSize(1, 0);
+ }
+ else if (event->key() == Qt::Key_Return) {
+ hide();
+ setCurrentGridSize(currentGridSize);
+ }
+ if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
+ currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
+ resize(sizeHint());
+ }
+ }
}
void QtGridSelectionDialog::mousePressEvent(QMouseEvent*) {
- hide();
- setCurrentGridSize(currentGridSize);
+ hide();
+ setCurrentGridSize(currentGridSize);
}
void QtGridSelectionDialog::paintEvent(QPaintEvent*) {
- QPainter painter(this);
- QStyleOptionMenuItem option;
- option.state = QStyle::State_Enabled | QStyle::State_Selected;
- option.menuRect = QRect(QPoint(0,0), frameSize);
- for (int x = 0; x < currentGridSize.width(); x++) {
- for (int y = 0; y < currentGridSize.height(); y++) {
- int xPos = horizontalMargin + (x * (frameSize.width() + padding));
- int yPos = verticalMargin + (y * (frameSize.height() + padding));
- option.menuRect.moveTo(QPoint(xPos, yPos));
- option.rect = option.menuRect;
- style()->drawControl(QStyle::CE_MenuItem, &option, &painter, 0);
- }
- }
-
- QStyleOptionSizeGrip sizeGripOption;
- sizeGripOption.init(this);
- sizeGripOption.corner = Qt::BottomRightCorner;
- style()->drawControl(QStyle::CE_SizeGrip, &sizeGripOption, &painter, this);
+ QPainter painter(this);
+ QStyleOptionMenuItem option;
+ option.state = QStyle::State_Enabled | QStyle::State_Selected;
+ option.menuRect = QRect(QPoint(0,0), frameSize);
+ for (int x = 0; x < currentGridSize.width(); x++) {
+ for (int y = 0; y < currentGridSize.height(); y++) {
+ int xPos = horizontalMargin + (x * (frameSize.width() + padding));
+ int yPos = verticalMargin + (y * (frameSize.height() + padding));
+ option.menuRect.moveTo(QPoint(xPos, yPos));
+ option.rect = option.menuRect;
+ style()->drawControl(QStyle::CE_MenuItem, &option, &painter, 0);
+ }
+ }
+
+ QStyleOptionSizeGrip sizeGripOption;
+ sizeGripOption.init(this);
+ sizeGripOption.corner = Qt::BottomRightCorner;
+ style()->drawControl(QStyle::CE_SizeGrip, &sizeGripOption, &painter, this);
}
void QtGridSelectionDialog::showEvent(QShowEvent*) {
- int xPos = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) - frameSize.width()/2;
- int yPos = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) - frameSize.height()/2;
- QCursor::setPos(mapToGlobal(QPoint(xPos, yPos)));
- setMouseTracking(true);
+ int xPos = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) - frameSize.width()/2;
+ int yPos = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) - frameSize.height()/2;
+ QCursor::setPos(mapToGlobal(QPoint(xPos, yPos)));
+ setMouseTracking(true);
}
void QtGridSelectionDialog::hideEvent(QHideEvent*) {
- setMouseTracking(false);
+ setMouseTracking(false);
}
void QtGridSelectionDialog::mouseMoveEvent(QMouseEvent*) {
- QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
- QSize newDimensions = currentGridSize;
- if (diff.x() > frameSize.width() * 1.5) {
- newDimensions -= QSize(diff.x() / (frameSize.width() * 1.5), 0);
- }
- if (diff.y() > frameSize.height() * 1.5) {
- newDimensions -= QSize(0, diff.y() / (frameSize.height() * 1.5));
- }
- if (minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize) != currentGridSize) {
- currentGridSize = minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize);
- resize(sizeHint());
- }
+ QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
+ QSize newDimensions = currentGridSize;
+ if (diff.x() > frameSize.width() * 1.5) {
+ newDimensions -= QSize(diff.x() / (frameSize.width() * 1.5), 0);
+ }
+ if (diff.y() > frameSize.height() * 1.5) {
+ newDimensions -= QSize(0, diff.y() / (frameSize.height() * 1.5));
+ }
+ if (minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize) != currentGridSize) {
+ currentGridSize = minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize);
+ resize(sizeHint());
+ }
}
void QtGridSelectionDialog::leaveEvent(QEvent *) {
- QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
- QSize newGridSize = currentGridSize;
- if (diff.x() < 0) {
- newGridSize += QSize(1,0);
- }
- if (diff.y() < 0) {
- newGridSize += QSize(0,1);
- }
- if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
- currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
- resize(sizeHint());
- }
+ QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
+ QSize newGridSize = currentGridSize;
+ if (diff.x() < 0) {
+ newGridSize += QSize(1,0);
+ }
+ if (diff.y() < 0) {
+ newGridSize += QSize(0,1);
+ }
+ if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
+ currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
+ resize(sizeHint());
+ }
}
}
diff --git a/Swift/QtUI/Trellis/QtGridSelectionDialog.h b/Swift/QtUI/Trellis/QtGridSelectionDialog.h
index abcc8b1..c763e68 100644
--- a/Swift/QtUI/Trellis/QtGridSelectionDialog.h
+++ b/Swift/QtUI/Trellis/QtGridSelectionDialog.h
@@ -11,47 +11,47 @@
namespace Swift {
- class QtGridSelectionDialog : public QWidget {
- Q_OBJECT
-
- Q_PROPERTY(QSize currentGridSize READ getCurrentGridSize WRITE setCurrentGridSize NOTIFY currentGridSizeChanged)
- Q_PROPERTY(QSize minGridSize READ getMinGridSize WRITE setMinGridSize NOTIFY minGridSizeChanged)
- Q_PROPERTY(QSize maxGridSize READ getMaxGridSize WRITE setMaxGridSize NOTIFY maxGridSizeChanged)
- public:
- explicit QtGridSelectionDialog(QWidget* parent = 0);
-
- virtual QSize sizeHint() const;
-
- void setCurrentGridSize(const QSize& size);
- QSize getCurrentGridSize() const;
- void setMinGridSize(const QSize& size);
- QSize getMinGridSize() const;
- void setMaxGridSize(const QSize& size);
- QSize getMaxGridSize() const;
-
- signals:
- void currentGridSizeChanged(QSize);
- void minGridSizeChanged(QSize);
- void maxGridSizeChanged(QSize);
-
- protected:
- void keyReleaseEvent(QKeyEvent* event);
- void mousePressEvent(QMouseEvent* event);
- void mouseMoveEvent(QMouseEvent* event);
- void paintEvent(QPaintEvent* event);
- void showEvent(QShowEvent* event);
- void hideEvent(QHideEvent* event);
- void leaveEvent(QEvent *event);
-
- private:
- int padding;
- int horizontalMargin;
- int verticalMargin;
-
- QSize frameSize;
-
- QSize currentGridSize;
- QSize minGridSize;
- QSize maxGridSize;
- };
+ class QtGridSelectionDialog : public QWidget {
+ Q_OBJECT
+
+ Q_PROPERTY(QSize currentGridSize READ getCurrentGridSize WRITE setCurrentGridSize NOTIFY currentGridSizeChanged)
+ Q_PROPERTY(QSize minGridSize READ getMinGridSize WRITE setMinGridSize NOTIFY minGridSizeChanged)
+ Q_PROPERTY(QSize maxGridSize READ getMaxGridSize WRITE setMaxGridSize NOTIFY maxGridSizeChanged)
+ public:
+ explicit QtGridSelectionDialog(QWidget* parent = 0);
+
+ virtual QSize sizeHint() const;
+
+ void setCurrentGridSize(const QSize& size);
+ QSize getCurrentGridSize() const;
+ void setMinGridSize(const QSize& size);
+ QSize getMinGridSize() const;
+ void setMaxGridSize(const QSize& size);
+ QSize getMaxGridSize() const;
+
+ signals:
+ void currentGridSizeChanged(QSize);
+ void minGridSizeChanged(QSize);
+ void maxGridSizeChanged(QSize);
+
+ protected:
+ void keyReleaseEvent(QKeyEvent* event);
+ void mousePressEvent(QMouseEvent* event);
+ void mouseMoveEvent(QMouseEvent* event);
+ void paintEvent(QPaintEvent* event);
+ void showEvent(QShowEvent* event);
+ void hideEvent(QHideEvent* event);
+ void leaveEvent(QEvent *event);
+
+ private:
+ int padding;
+ int horizontalMargin;
+ int verticalMargin;
+
+ QSize frameSize;
+
+ QSize currentGridSize;
+ QSize minGridSize;
+ QSize maxGridSize;
+ };
}
diff --git a/Swift/QtUI/UserSearch/ContactListDelegate.cpp b/Swift/QtUI/UserSearch/ContactListDelegate.cpp
index 989743e..75e25a1 100644
--- a/Swift/QtUI/UserSearch/ContactListDelegate.cpp
+++ b/Swift/QtUI/UserSearch/ContactListDelegate.cpp
@@ -26,29 +26,29 @@ ContactListDelegate::~ContactListDelegate() {
}
void ContactListDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- if (!index.isValid()) {
- return;
- }
- const Contact::ref contact = static_cast<Contact*>(index.internalPointer())->shared_from_this();
- QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
- QString avatarPath = index.data(ContactListModel::AvatarRole).value<QString>();
- QIcon presenceIcon =index.data(ChatListRecentItem::PresenceIconRole).isValid() && !index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
- ? index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");
- QString name = P2QSTRING(contact->name);
- QString statusText = P2QSTRING(contact->jid.toString());
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, 0, compact_);
+ if (!index.isValid()) {
+ return;
+ }
+ const Contact::ref contact = static_cast<Contact*>(index.internalPointer())->shared_from_this();
+ QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath = index.data(ContactListModel::AvatarRole).value<QString>();
+ QIcon presenceIcon =index.data(ChatListRecentItem::PresenceIconRole).isValid() && !index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
+ ? index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");
+ QString name = P2QSTRING(contact->name);
+ QString statusText = P2QSTRING(contact->jid.toString());
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, 0, compact_);
}
QSize ContactListDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
void ContactListDelegate::setCompact(bool compact) {
- compact_ = compact;
+ compact_ = compact;
}
}
diff --git a/Swift/QtUI/UserSearch/ContactListDelegate.h b/Swift/QtUI/UserSearch/ContactListDelegate.h
index 7680aba..208246a 100644
--- a/Swift/QtUI/UserSearch/ContactListDelegate.h
+++ b/Swift/QtUI/UserSearch/ContactListDelegate.h
@@ -13,18 +13,18 @@
namespace Swift {
class ContactListDelegate : public QStyledItemDelegate {
- public:
- ContactListDelegate(bool compact);
- virtual ~ContactListDelegate();
+ public:
+ ContactListDelegate(bool compact);
+ virtual ~ContactListDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- public slots:
- void setCompact(bool compact);
+ public slots:
+ void setCompact(bool compact);
- private:
- bool compact_;
- DelegateCommons common_;
+ private:
+ bool compact_;
+ DelegateCommons common_;
};
}
diff --git a/Swift/QtUI/UserSearch/ContactListModel.cpp b/Swift/QtUI/UserSearch/ContactListModel.cpp
index 3400924..376d3b1 100644
--- a/Swift/QtUI/UserSearch/ContactListModel.cpp
+++ b/Swift/QtUI/UserSearch/ContactListModel.cpp
@@ -24,116 +24,116 @@
namespace Swift {
QDataStream& operator >>(QDataStream& in, StatusShow::Type& e){
- quint32 buffer;
- in >> buffer;
- switch(buffer) {
- case StatusShow::Online:
- e = StatusShow::Online;
- break;
- case StatusShow::Away:
- e = StatusShow::Away;
- break;
- case StatusShow::FFC:
- e = StatusShow::FFC;
- break;
- case StatusShow::XA:
- e = StatusShow::XA;
- break;
- case StatusShow::DND:
- e = StatusShow::DND;
- break;
- default:
- e = StatusShow::None;
- break;
- }
- return in;
+ quint32 buffer;
+ in >> buffer;
+ switch(buffer) {
+ case StatusShow::Online:
+ e = StatusShow::Online;
+ break;
+ case StatusShow::Away:
+ e = StatusShow::Away;
+ break;
+ case StatusShow::FFC:
+ e = StatusShow::FFC;
+ break;
+ case StatusShow::XA:
+ e = StatusShow::XA;
+ break;
+ case StatusShow::DND:
+ e = StatusShow::DND;
+ break;
+ default:
+ e = StatusShow::None;
+ break;
+ }
+ return in;
}
ContactListModel::ContactListModel(bool editable) : QAbstractItemModel(), editable_(editable) {
}
void ContactListModel::setList(const std::vector<Contact::ref>& list) {
- emit layoutAboutToBeChanged();
- contacts_ = list;
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ contacts_ = list;
+ emit layoutChanged();
}
const std::vector<Contact::ref>& ContactListModel::getList() const {
- return contacts_;
+ return contacts_;
}
Contact::ref ContactListModel::getContact(const size_t i) const {
- return contacts_[i];
+ return contacts_[i];
}
Qt::ItemFlags ContactListModel::flags(const QModelIndex& index) const {
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (index.isValid()) {
- flags = flags & ~Qt::ItemIsDropEnabled;
- } else {
- flags = Qt::ItemIsDropEnabled | flags;
- }
- return flags;
+ Qt::ItemFlags flags = QAbstractItemModel::flags(index);
+ if (index.isValid()) {
+ flags = flags & ~Qt::ItemIsDropEnabled;
+ } else {
+ flags = Qt::ItemIsDropEnabled | flags;
+ }
+ return flags;
}
int ContactListModel::columnCount(const QModelIndex&) const {
- return editable_ ? 2 : 1;
+ return editable_ ? 2 : 1;
}
QVariant ContactListModel::data(const QModelIndex& index, int role) const {
- if ((boost::numeric_cast<size_t>(index.row()) < contacts_.size()) && (index.column() == 0)) {
- const Contact::ref& contact = contacts_[index.row()];
- if (role == Qt::EditRole) {
- return P2QSTRING(contact->jid.toString());
- }
- return dataForContact(contact, role);
- } else {
- return QVariant();
- }
+ if ((boost::numeric_cast<size_t>(index.row()) < contacts_.size()) && (index.column() == 0)) {
+ const Contact::ref& contact = contacts_[index.row()];
+ if (role == Qt::EditRole) {
+ return P2QSTRING(contact->jid.toString());
+ }
+ return dataForContact(contact, role);
+ } else {
+ return QVariant();
+ }
}
QModelIndex ContactListModel::index(int row, int column, const QModelIndex& parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
- return boost::numeric_cast<size_t>(row) < contacts_.size() ? createIndex(row, column, contacts_[row].get()) : QModelIndex();
+ return boost::numeric_cast<size_t>(row) < contacts_.size() ? createIndex(row, column, contacts_[row].get()) : QModelIndex();
}
QModelIndex ContactListModel::parent(const QModelIndex& index) const {
- if (!index.isValid()) {
- return QModelIndex();
- }
- return QModelIndex();
+ if (!index.isValid()) {
+ return QModelIndex();
+ }
+ return QModelIndex();
}
int ContactListModel::rowCount(const QModelIndex& /*parent*/) const {
- return contacts_.size();
+ return contacts_.size();
}
bool ContactListModel::removeRows(int row, int /*count*/, const QModelIndex& /*parent*/) {
- if (boost::numeric_cast<size_t>(row) < contacts_.size()) {
- emit layoutAboutToBeChanged();
- contacts_.erase(contacts_.begin() + row);
- emit layoutChanged();
- onListChanged(getList());
- return true;
- }
- return false;
+ if (boost::numeric_cast<size_t>(row) < contacts_.size()) {
+ emit layoutAboutToBeChanged();
+ contacts_.erase(contacts_.begin() + row);
+ emit layoutChanged();
+ onListChanged(getList());
+ return true;
+ }
+ return false;
}
QVariant ContactListModel::dataForContact(const Contact::ref& contact, int role) const {
- switch (role) {
- case Qt::DisplayRole: return P2QSTRING(contact->name);
- case DetailTextRole: return P2QSTRING(contact->jid.toString());
- case AvatarRole: return QVariant(P2QSTRING(pathToString(contact->avatarPath)));
- case PresenceIconRole: return getPresenceIconForContact(contact);
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return P2QSTRING(contact->name);
+ case DetailTextRole: return P2QSTRING(contact->jid.toString());
+ case AvatarRole: return QVariant(P2QSTRING(pathToString(contact->avatarPath)));
+ case PresenceIconRole: return getPresenceIconForContact(contact);
+ default: return QVariant();
+ }
}
QIcon ContactListModel::getPresenceIconForContact(const Contact::ref& contact) const {
- return QIcon(statusShowTypeToIconPath(contact->statusType));
+ return QIcon(statusShowTypeToIconPath(contact->statusType));
}
}
diff --git a/Swift/QtUI/UserSearch/ContactListModel.h b/Swift/QtUI/UserSearch/ContactListModel.h
index e980120..9b61484 100644
--- a/Swift/QtUI/UserSearch/ContactListModel.h
+++ b/Swift/QtUI/UserSearch/ContactListModel.h
@@ -27,41 +27,41 @@
#include <Swift/QtUI/ChatList/ChatListRecentItem.h>
namespace Swift {
- class ContactListModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- enum ContactRoles {
- DetailTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2
- };
-
- public:
- ContactListModel(bool editable);
-
- void setList(const std::vector<Contact::ref>& list);
- const std::vector<Contact::ref>& getList() const;
- Contact::ref getContact(const size_t i) const;
-
- Qt::ItemFlags flags(const QModelIndex& index) const;
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
-
- private:
- QVariant dataForContact(const Contact::ref& contact, int role) const;
- QIcon getPresenceIconForContact(const Contact::ref& contact) const;
-
- signals:
- void onListChanged(std::vector<Contact::ref> list);
- void onJIDsDropped(const std::vector<JID>& contact);
-
- private:
- bool editable_;
- std::vector<Contact::ref> contacts_;
- };
+ class ContactListModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ enum ContactRoles {
+ DetailTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2
+ };
+
+ public:
+ ContactListModel(bool editable);
+
+ void setList(const std::vector<Contact::ref>& list);
+ const std::vector<Contact::ref>& getList() const;
+ Contact::ref getContact(const size_t i) const;
+
+ Qt::ItemFlags flags(const QModelIndex& index) const;
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
+
+ private:
+ QVariant dataForContact(const Contact::ref& contact, int role) const;
+ QIcon getPresenceIconForContact(const Contact::ref& contact) const;
+
+ signals:
+ void onListChanged(std::vector<Contact::ref> list);
+ void onJIDsDropped(const std::vector<JID>& contact);
+
+ private:
+ bool editable_;
+ std::vector<Contact::ref> contacts_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtContactListWidget.cpp b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
index 0d55880..99bd791 100644
--- a/Swift/QtUI/UserSearch/QtContactListWidget.cpp
+++ b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
@@ -24,80 +24,80 @@
namespace Swift {
QtContactListWidget::QtContactListWidget(QWidget* parent, SettingsProvider* settings) : QTreeView(parent), settings_(settings), limited_(false) {
- contactListModel_ = new ContactListModel(true);
- setModel(contactListModel_);
+ contactListModel_ = new ContactListModel(true);
+ setModel(contactListModel_);
- connect(contactListModel_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SIGNAL(onListChanged(std::vector<Contact::ref>)));
- connect(contactListModel_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SIGNAL(onJIDsAdded(std::vector<JID>)));
+ connect(contactListModel_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SIGNAL(onListChanged(std::vector<Contact::ref>)));
+ connect(contactListModel_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SIGNAL(onJIDsAdded(std::vector<JID>)));
- setSelectionMode(QAbstractItemView::SingleSelection);
- setSelectionBehavior(QAbstractItemView::SelectRows);
- setUniformRowHeights(true);
+ setSelectionMode(QAbstractItemView::SingleSelection);
+ setSelectionBehavior(QAbstractItemView::SelectRows);
+ setUniformRowHeights(true);
- setAlternatingRowColors(true);
- setIndentation(0);
- setHeaderHidden(true);
- setExpandsOnDoubleClick(false);
- setItemsExpandable(false);
- setEditTriggers(QAbstractItemView::DoubleClicked);
+ setAlternatingRowColors(true);
+ setIndentation(0);
+ setHeaderHidden(true);
+ setExpandsOnDoubleClick(false);
+ setItemsExpandable(false);
+ setEditTriggers(QAbstractItemView::DoubleClicked);
- contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- removableItemDelegate_ = new QtRemovableItemDelegate(style());
+ contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ removableItemDelegate_ = new QtRemovableItemDelegate(style());
- setItemDelegateForColumn(0, contactListDelegate_);
- setItemDelegateForColumn(1, removableItemDelegate_);
+ setItemDelegateForColumn(0, contactListDelegate_);
+ setItemDelegateForColumn(1, removableItemDelegate_);
- header()->resizeSection(1, removableItemDelegate_->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
+ header()->resizeSection(1, removableItemDelegate_->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
- header()->setStretchLastSection(false);
+ header()->setStretchLastSection(false);
#if QT_VERSION >= 0x050000
- header()->setSectionResizeMode(0, QHeaderView::Stretch);
+ header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
- header()->setResizeMode(0, QHeaderView::Stretch);
+ header()->setResizeMode(0, QHeaderView::Stretch);
#endif
}
QtContactListWidget::~QtContactListWidget() {
- delete contactListDelegate_;
- delete removableItemDelegate_;
- delete contactListModel_;
+ delete contactListDelegate_;
+ delete removableItemDelegate_;
+ delete contactListModel_;
}
void QtContactListWidget::setList(const std::vector<Contact::ref>& list) {
- contactListModel_->setList(list);
+ contactListModel_->setList(list);
}
std::vector<Contact::ref> QtContactListWidget::getList() const {
- return contactListModel_->getList();
+ return contactListModel_->getList();
}
Contact::ref QtContactListWidget::getContact(const size_t i) {
- return contactListModel_->getContact(i);
+ return contactListModel_->getContact(i);
}
void QtContactListWidget::setMaximumNoOfContactsToOne(bool limited) {
- limited_ = limited;
+ limited_ = limited;
}
bool QtContactListWidget::isFull() const {
- return limited_ && (getList().size() == 1);
+ return limited_ && (getList().size() == 1);
}
void QtContactListWidget::updateContacts(const std::vector<Contact::ref>& contactUpdates) {
- std::vector<Contact::ref> contacts = contactListModel_->getList();
- foreach(const Contact::ref& contactUpdate, contactUpdates) {
- for(size_t n = 0; n < contacts.size(); n++) {
- if (contactUpdate->jid == contacts[n]->jid) {
- contacts[n] = contactUpdate;
- break;
- }
- }
- }
- contactListModel_->setList(contacts);
+ std::vector<Contact::ref> contacts = contactListModel_->getList();
+ foreach(const Contact::ref& contactUpdate, contactUpdates) {
+ for(size_t n = 0; n < contacts.size(); n++) {
+ if (contactUpdate->jid == contacts[n]->jid) {
+ contacts[n] = contactUpdate;
+ break;
+ }
+ }
+ }
+ contactListModel_->setList(contacts);
}
void QtContactListWidget::handleSettingsChanged(const std::string&) {
- contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
}
diff --git a/Swift/QtUI/UserSearch/QtContactListWidget.h b/Swift/QtUI/UserSearch/QtContactListWidget.h
index 59bd8f3..f2483c3 100644
--- a/Swift/QtUI/UserSearch/QtContactListWidget.h
+++ b/Swift/QtUI/UserSearch/QtContactListWidget.h
@@ -31,33 +31,33 @@ class SettingsProvider;
class QtRemovableItemDelegate;
class QtContactListWidget : public QTreeView {
- Q_OBJECT
+ Q_OBJECT
public:
- QtContactListWidget(QWidget* parent, SettingsProvider* settings);
- virtual ~QtContactListWidget();
+ QtContactListWidget(QWidget* parent, SettingsProvider* settings);
+ virtual ~QtContactListWidget();
- void setList(const std::vector<Contact::ref>& list);
- std::vector<Contact::ref> getList() const;
- Contact::ref getContact(const size_t i);
- void setMaximumNoOfContactsToOne(bool limited);
- bool isFull() const;
+ void setList(const std::vector<Contact::ref>& list);
+ std::vector<Contact::ref> getList() const;
+ Contact::ref getContact(const size_t i);
+ void setMaximumNoOfContactsToOne(bool limited);
+ bool isFull() const;
public slots:
- void updateContacts(const std::vector<Contact::ref>& contactUpdates);
+ void updateContacts(const std::vector<Contact::ref>& contactUpdates);
signals:
- void onListChanged(std::vector<Contact::ref> list);
- void onJIDsAdded(const std::vector<JID>& jids);
+ void onListChanged(std::vector<Contact::ref> list);
+ void onJIDsAdded(const std::vector<JID>& jids);
private:
- void handleSettingsChanged(const std::string&);
+ void handleSettingsChanged(const std::string&);
private:
- SettingsProvider* settings_;
- ContactListModel* contactListModel_;
- ContactListDelegate* contactListDelegate_;
- QtRemovableItemDelegate* removableItemDelegate_;
- bool limited_;
+ SettingsProvider* settings_;
+ ContactListModel* contactListModel_;
+ ContactListDelegate* contactListDelegate_;
+ QtRemovableItemDelegate* removableItemDelegate_;
+ bool limited_;
};
}
diff --git a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
index 26d0f05..4e8f4e1 100644
--- a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
+++ b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
@@ -31,180 +31,180 @@
namespace Swift {
QtSuggestingJIDInput::QtSuggestingJIDInput(QWidget* parent, SettingsProvider* settings) : QLineEdit(parent), settings_(settings) {
- treeViewPopup_ = new QTreeView();
- treeViewPopup_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
- //treeViewPopup_->setAttribute(Qt::WA_ShowWithoutActivating);
- treeViewPopup_->setAlternatingRowColors(true);
- treeViewPopup_->setIndentation(0);
- treeViewPopup_->setHeaderHidden(true);
- treeViewPopup_->setExpandsOnDoubleClick(false);
- treeViewPopup_->setItemsExpandable(false);
- treeViewPopup_->setSelectionMode(QAbstractItemView::SingleSelection);
- treeViewPopup_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
- treeViewPopup_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- QSizePolicy policy(treeViewPopup_->sizePolicy());
- policy.setVerticalPolicy(QSizePolicy::Expanding);
- treeViewPopup_->setSizePolicy(policy);
- treeViewPopup_->hide();
- treeViewPopup_->setFocusProxy(this);
- connect(treeViewPopup_, SIGNAL(clicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
- connect(treeViewPopup_, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
-
- contactListModel_ = new ContactListModel(false);
- treeViewPopup_->setModel(contactListModel_);
-
- contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- treeViewPopup_->setItemDelegate(contactListDelegate_);
-
- settings_->onSettingChanged.connect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
+ treeViewPopup_ = new QTreeView();
+ treeViewPopup_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
+ //treeViewPopup_->setAttribute(Qt::WA_ShowWithoutActivating);
+ treeViewPopup_->setAlternatingRowColors(true);
+ treeViewPopup_->setIndentation(0);
+ treeViewPopup_->setHeaderHidden(true);
+ treeViewPopup_->setExpandsOnDoubleClick(false);
+ treeViewPopup_->setItemsExpandable(false);
+ treeViewPopup_->setSelectionMode(QAbstractItemView::SingleSelection);
+ treeViewPopup_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
+ treeViewPopup_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ QSizePolicy policy(treeViewPopup_->sizePolicy());
+ policy.setVerticalPolicy(QSizePolicy::Expanding);
+ treeViewPopup_->setSizePolicy(policy);
+ treeViewPopup_->hide();
+ treeViewPopup_->setFocusProxy(this);
+ connect(treeViewPopup_, SIGNAL(clicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
+ connect(treeViewPopup_, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
+
+ contactListModel_ = new ContactListModel(false);
+ treeViewPopup_->setModel(contactListModel_);
+
+ contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ treeViewPopup_->setItemDelegate(contactListDelegate_);
+
+ settings_->onSettingChanged.connect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
}
QtSuggestingJIDInput::~QtSuggestingJIDInput() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
- delete treeViewPopup_;
- delete contactListDelegate_;
- delete contactListModel_;
+ settings_->onSettingChanged.disconnect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
+ delete treeViewPopup_;
+ delete contactListDelegate_;
+ delete contactListModel_;
}
Contact::ref QtSuggestingJIDInput::getContact() {
- if (!!currentContact_) {
- return currentContact_;
- }
-
- if (!text().isEmpty()) {
- JID jid(Q2PSTRING(text()));
- if (jid.isValid()) {
- Contact::ref manualContact = boost::make_shared<Contact>();
- manualContact->name = jid.toString();
- manualContact->jid = jid;
- return manualContact;
- }
- }
- return boost::shared_ptr<Contact>();
+ if (!!currentContact_) {
+ return currentContact_;
+ }
+
+ if (!text().isEmpty()) {
+ JID jid(Q2PSTRING(text()));
+ if (jid.isValid()) {
+ Contact::ref manualContact = boost::make_shared<Contact>();
+ manualContact->name = jid.toString();
+ manualContact->jid = jid;
+ return manualContact;
+ }
+ }
+ return boost::shared_ptr<Contact>();
}
void QtSuggestingJIDInput::setSuggestions(const std::vector<Contact::ref>& suggestions) {
- contactListModel_->setList(suggestions);
- positionPopup();
- if (!suggestions.empty()) {
- treeViewPopup_->setCurrentIndex(contactListModel_->index(0, 0));
- showPopup();
- } else {
- currentContact_.reset();
- hidePopup();
- }
+ contactListModel_->setList(suggestions);
+ positionPopup();
+ if (!suggestions.empty()) {
+ treeViewPopup_->setCurrentIndex(contactListModel_->index(0, 0));
+ showPopup();
+ } else {
+ currentContact_.reset();
+ hidePopup();
+ }
}
void QtSuggestingJIDInput::clear() {
- setText("");
- currentContact_.reset();
+ setText("");
+ currentContact_.reset();
}
void QtSuggestingJIDInput::keyPressEvent(QKeyEvent* event) {
- if (event->key() == Qt::Key_Up) {
- if (contactListModel_->rowCount() > 0) {
- int row = treeViewPopup_->currentIndex().row();
- row = (row + contactListModel_->rowCount() - 1) % contactListModel_->rowCount();
- treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
- }
- } else if (event->key() == Qt::Key_Down) {
- if (contactListModel_->rowCount() > 0) {
- int row = treeViewPopup_->currentIndex().row();
- row = (row + contactListModel_->rowCount() + 1) % contactListModel_->rowCount();
- treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
- }
- } else if (event->key() == Qt::Key_Return && treeViewPopup_->isVisible()) {
- QModelIndex index = treeViewPopup_->currentIndex();
- if (!contactListModel_->getList().empty() && index.isValid()) {
- currentContact_ = contactListModel_->getContact(index.row());
- if (currentContact_->jid.isValid()) {
- setText(P2QSTRING(currentContact_->jid.toString()));
- } else {
- setText(P2QSTRING(currentContact_->name));
- }
- hidePopup();
- clearFocus();
- } else {
- currentContact_.reset();
- }
- editingDone();
- } else {
- QLineEdit::keyPressEvent(event);
- }
+ if (event->key() == Qt::Key_Up) {
+ if (contactListModel_->rowCount() > 0) {
+ int row = treeViewPopup_->currentIndex().row();
+ row = (row + contactListModel_->rowCount() - 1) % contactListModel_->rowCount();
+ treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
+ }
+ } else if (event->key() == Qt::Key_Down) {
+ if (contactListModel_->rowCount() > 0) {
+ int row = treeViewPopup_->currentIndex().row();
+ row = (row + contactListModel_->rowCount() + 1) % contactListModel_->rowCount();
+ treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
+ }
+ } else if (event->key() == Qt::Key_Return && treeViewPopup_->isVisible()) {
+ QModelIndex index = treeViewPopup_->currentIndex();
+ if (!contactListModel_->getList().empty() && index.isValid()) {
+ currentContact_ = contactListModel_->getContact(index.row());
+ if (currentContact_->jid.isValid()) {
+ setText(P2QSTRING(currentContact_->jid.toString()));
+ } else {
+ setText(P2QSTRING(currentContact_->name));
+ }
+ hidePopup();
+ clearFocus();
+ } else {
+ currentContact_.reset();
+ }
+ editingDone();
+ } else {
+ QLineEdit::keyPressEvent(event);
+ }
}
void QtSuggestingJIDInput::hideEvent(QHideEvent* /* event */) {
- // Hide our popup when we are hidden (can happen when a dialog is closed by the user).
- treeViewPopup_->hide();
+ // Hide our popup when we are hidden (can happen when a dialog is closed by the user).
+ treeViewPopup_->hide();
}
void QtSuggestingJIDInput::handleApplicationFocusChanged(QWidget* /*old*/, QWidget* /*now*/) {
- /* Using the now argument gives use the wrong widget. This is part of the code needed
- to prevent stealing of focus when opening a the suggestion window. */
- QWidget* now = qApp->focusWidget();
- if (!now || (now != treeViewPopup_ && now != this && !now->isAncestorOf(this) && !now->isAncestorOf(treeViewPopup_) && !this->isAncestorOf(now) && !treeViewPopup_->isAncestorOf(now))) {
- hidePopup();
- }
+ /* Using the now argument gives use the wrong widget. This is part of the code needed
+ to prevent stealing of focus when opening a the suggestion window. */
+ QWidget* now = qApp->focusWidget();
+ if (!now || (now != treeViewPopup_ && now != this && !now->isAncestorOf(this) && !now->isAncestorOf(treeViewPopup_) && !this->isAncestorOf(now) && !treeViewPopup_->isAncestorOf(now))) {
+ hidePopup();
+ }
}
void QtSuggestingJIDInput::handleSettingsChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- }
+ if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ }
}
void QtSuggestingJIDInput::handleClicked(const QModelIndex& index) {
- if (index.isValid()) {
- currentContact_ = contactListModel_->getContact(index.row());
- onUserSelected(currentContact_);
- hidePopup();
- }
+ if (index.isValid()) {
+ currentContact_ = contactListModel_->getContact(index.row());
+ onUserSelected(currentContact_);
+ hidePopup();
+ }
}
void QtSuggestingJIDInput::positionPopup() {
- QDesktopWidget* desktop = QApplication::desktop();
- int screen = desktop->screenNumber(this);
- QPoint point = mapToGlobal(QPoint(0, height()));
- QRect geometry = desktop->availableGeometry(screen);
- int x = point.x();
- int y = point.y();
- int width = this->width();
- int height = 80;
-
- int screenWidth = geometry.x() + geometry.width();
- if (x + width > screenWidth) {
- x = screenWidth - width;
- }
-
- height = treeViewPopup_->sizeHintForRow(0) * contactListModel_->rowCount();
- height = height > 200 ? 200 : height;
-
- int marginLeft;
- int marginTop;
- int marginRight;
- int marginBottom;
- treeViewPopup_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
- height += marginTop + marginBottom;
- width += marginLeft + marginRight;
-
- treeViewPopup_->setGeometry(x, y, width, height);
- treeViewPopup_->move(x, y);
- treeViewPopup_->setMaximumWidth(width);
+ QDesktopWidget* desktop = QApplication::desktop();
+ int screen = desktop->screenNumber(this);
+ QPoint point = mapToGlobal(QPoint(0, height()));
+ QRect geometry = desktop->availableGeometry(screen);
+ int x = point.x();
+ int y = point.y();
+ int width = this->width();
+ int height = 80;
+
+ int screenWidth = geometry.x() + geometry.width();
+ if (x + width > screenWidth) {
+ x = screenWidth - width;
+ }
+
+ height = treeViewPopup_->sizeHintForRow(0) * contactListModel_->rowCount();
+ height = height > 200 ? 200 : height;
+
+ int marginLeft;
+ int marginTop;
+ int marginRight;
+ int marginBottom;
+ treeViewPopup_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
+ height += marginTop + marginBottom;
+ width += marginLeft + marginRight;
+
+ treeViewPopup_->setGeometry(x, y, width, height);
+ treeViewPopup_->move(x, y);
+ treeViewPopup_->setMaximumWidth(width);
}
void QtSuggestingJIDInput::showPopup() {
- treeViewPopup_->show();
- activateWindow();
- connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
- setFocus();
+ treeViewPopup_->show();
+ activateWindow();
+ connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
+ setFocus();
}
void QtSuggestingJIDInput::hidePopup() {
- disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
- treeViewPopup_->hide();
+ disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
+ treeViewPopup_->hide();
- // Give focus back to input widget because the hide() call passes the focus to the wrong widget.
- setFocus();
+ // Give focus back to input widget because the hide() call passes the focus to the wrong widget.
+ setFocus();
}
}
diff --git a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
index 73840b4..2077d55 100644
--- a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
+++ b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
@@ -26,44 +26,44 @@ class SettingsProvider;
class ContactListModel;
class QtSuggestingJIDInput : public QLineEdit {
- Q_OBJECT
- public:
- QtSuggestingJIDInput(QWidget* parent, SettingsProvider* settings);
- virtual ~QtSuggestingJIDInput();
+ Q_OBJECT
+ public:
+ QtSuggestingJIDInput(QWidget* parent, SettingsProvider* settings);
+ virtual ~QtSuggestingJIDInput();
- Contact::ref getContact();
+ Contact::ref getContact();
- void setSuggestions(const std::vector<Contact::ref>& suggestions);
+ void setSuggestions(const std::vector<Contact::ref>& suggestions);
- void clear();
+ void clear();
- boost::signal<void (const Contact::ref&)> onUserSelected;
+ boost::signal<void (const Contact::ref&)> onUserSelected;
- signals:
- void editingDone();
+ signals:
+ void editingDone();
- protected:
- virtual void keyPressEvent(QKeyEvent* event);
- virtual void hideEvent(QHideEvent* event);
+ protected:
+ virtual void keyPressEvent(QKeyEvent* event);
+ virtual void hideEvent(QHideEvent* event);
- private:
- void handleSettingsChanged(const std::string& setting);
+ private:
+ void handleSettingsChanged(const std::string& setting);
- private slots:
- void handleClicked(const QModelIndex& index);
- void handleApplicationFocusChanged(QWidget* old, QWidget* now);
+ private slots:
+ void handleClicked(const QModelIndex& index);
+ void handleApplicationFocusChanged(QWidget* old, QWidget* now);
- private:
- void positionPopup();
- void showPopup();
- void hidePopup();
+ private:
+ void positionPopup();
+ void showPopup();
+ void hidePopup();
- private:
- SettingsProvider* settings_;
- ContactListModel* contactListModel_;
- QTreeView* treeViewPopup_;
- ContactListDelegate* contactListDelegate_;
- Contact::ref currentContact_;
+ private:
+ SettingsProvider* settings_;
+ ContactListModel* contactListModel_;
+ QTreeView* treeViewPopup_;
+ ContactListDelegate* contactListDelegate_;
+ Contact::ref currentContact_;
};
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
index 4e8354f..601d6ac 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
@@ -19,10 +19,10 @@
namespace Swift {
QtUserSearchDetailsPage::QtUserSearchDetailsPage(const std::set<std::string>& groups) {
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->addWidget(new QLabel(tr("Please choose a name for the contact, and select the groups you want to add the contact to.")));
- editWidget = new QtContactEditWidget(groups, this);
- layout->addWidget(editWidget);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->addWidget(new QLabel(tr("Please choose a name for the contact, and select the groups you want to add the contact to.")));
+ editWidget = new QtContactEditWidget(groups, this);
+ layout->addWidget(editWidget);
}
QtUserSearchDetailsPage::~QtUserSearchDetailsPage() {
@@ -30,27 +30,27 @@ QtUserSearchDetailsPage::~QtUserSearchDetailsPage() {
}
void QtUserSearchDetailsPage::setJID(const JID& jid) {
- contactJID = jid;
+ contactJID = jid;
}
void QtUserSearchDetailsPage::setNameSuggestions(const std::vector<std::string>& nameSuggestions) {
- editWidget->setNameSuggestions(nameSuggestions);
+ editWidget->setNameSuggestions(nameSuggestions);
}
void QtUserSearchDetailsPage::setName(const std::string& name) {
- editWidget->setName(name);
+ editWidget->setName(name);
}
std::set<std::string> QtUserSearchDetailsPage::getSelectedGroups() {
- return editWidget->getSelectedGroups();
+ return editWidget->getSelectedGroups();
}
std::string QtUserSearchDetailsPage::getName() {
- return editWidget->getName();
+ return editWidget->getName();
}
void QtUserSearchDetailsPage::clear() {
- editWidget->clear();
+ editWidget->clear();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
index 568dfe3..7185bce 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
@@ -18,28 +18,28 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFieldsPage.h>
namespace Swift {
- class QtContactEditWidget;
+ class QtContactEditWidget;
- class QtUserSearchDetailsPage : public QWizardPage {
- Q_OBJECT
- public:
- QtUserSearchDetailsPage(const std::set<std::string>& availableGroups);
- virtual ~QtUserSearchDetailsPage();
+ class QtUserSearchDetailsPage : public QWizardPage {
+ Q_OBJECT
+ public:
+ QtUserSearchDetailsPage(const std::set<std::string>& availableGroups);
+ virtual ~QtUserSearchDetailsPage();
- void setJID(const JID& jid);
- void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
- void setName(const std::string& name);
+ void setJID(const JID& jid);
+ void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
+ void setName(const std::string& name);
- std::set<std::string> getSelectedGroups();
- std::string getName();
+ std::set<std::string> getSelectedGroups();
+ std::string getName();
- void clear();
+ void clear();
- signals:
- void onUserTriggersFinish();
+ signals:
+ void onUserTriggersFinish();
- private:
- QtContactEditWidget* editWidget;
- JID contactJID;
- };
+ private:
+ QtContactEditWidget* editWidget;
+ JID contactJID;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
index 9b02273..3a82a62 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
@@ -9,34 +9,34 @@
namespace Swift {
QtUserSearchFieldsPage::QtUserSearchFieldsPage() : formWidget_(0) {
- setupUi(this);
+ setupUi(this);
}
bool QtUserSearchFieldsPage::isComplete() const {
- if (formWidget_) {
- return formWidget_->isEnabled();
- } else {
- return nickInput_->isEnabled() || firstInput_->isEnabled() || lastInput_->isEnabled() || emailInput_->isEnabled();
- }
+ if (formWidget_) {
+ return formWidget_->isEnabled();
+ } else {
+ return nickInput_->isEnabled() || firstInput_->isEnabled() || lastInput_->isEnabled() || emailInput_->isEnabled();
+ }
}
QtFormWidget* QtUserSearchFieldsPage::getFormWidget() {
- return formWidget_;
+ return formWidget_;
}
void QtUserSearchFieldsPage::setFormWidget(QtFormWidget *widget) {
- if (formWidget_) {
- delete formWidget_;
- formWidget_ = NULL;
- }
- if (widget) {
- formContainer_->layout()->addWidget(widget);
- }
- formWidget_ = widget;
+ if (formWidget_) {
+ delete formWidget_;
+ formWidget_ = NULL;
+ }
+ if (widget) {
+ formContainer_->layout()->addWidget(widget);
+ }
+ formWidget_ = widget;
}
void QtUserSearchFieldsPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
index 29ff675..4089d05 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
@@ -12,19 +12,19 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFieldsPage.h>
namespace Swift {
- class QtUserSearchFieldsPage : public QWizardPage, public Ui::QtUserSearchFieldsPage {
- Q_OBJECT
- public:
- QtUserSearchFieldsPage();
- virtual bool isComplete() const;
+ class QtUserSearchFieldsPage : public QWizardPage, public Ui::QtUserSearchFieldsPage {
+ Q_OBJECT
+ public:
+ QtUserSearchFieldsPage();
+ virtual bool isComplete() const;
- QtFormWidget* getFormWidget();
- void setFormWidget(QtFormWidget *widget);
+ QtFormWidget* getFormWidget();
+ void setFormWidget(QtFormWidget *widget);
- public slots:
- void emitCompletenessCheck();
+ public slots:
+ void emitCompletenessCheck();
- private:
- QtFormWidget *formWidget_;
- };
+ private:
+ QtFormWidget *formWidget_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
index 40ea1c0..1327a8f 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
@@ -25,78 +25,78 @@
namespace Swift {
QtUserSearchFirstMultiJIDPage::QtUserSearchFirstMultiJIDPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings) {
- setupUi(this);
- setTitle(title);
- QString introText = "";
- switch (type) {
- case UserSearchWindow::AddContact:
- introText = tr("Add another user to your contact list");
- break;
- case UserSearchWindow::ChatToContact:
- introText = tr("Chat to another user");
- break;
- case UserSearchWindow::InviteToChat:
- introText = tr("Invite contact to chat");
- break;
- }
-
- setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(introText));
-
- contactList_ = new QtContactListWidget(this, settings);
- horizontalLayout_5->addWidget(contactList_);
-
- jid_ = new QtSuggestingJIDInput(this, settings);
- horizontalLayout_6->insertWidget(0, jid_);
-
- connect(contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(emitCompletenessCheck()));
- connect(jid_, SIGNAL(editingDone()), this, SLOT(handleEditingDone()));
-
- setAcceptDrops(true);
+ setupUi(this);
+ setTitle(title);
+ QString introText = "";
+ switch (type) {
+ case UserSearchWindow::AddContact:
+ introText = tr("Add another user to your contact list");
+ break;
+ case UserSearchWindow::ChatToContact:
+ introText = tr("Chat to another user");
+ break;
+ case UserSearchWindow::InviteToChat:
+ introText = tr("Invite contact to chat");
+ break;
+ }
+
+ setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(introText));
+
+ contactList_ = new QtContactListWidget(this, settings);
+ horizontalLayout_5->addWidget(contactList_);
+
+ jid_ = new QtSuggestingJIDInput(this, settings);
+ horizontalLayout_6->insertWidget(0, jid_);
+
+ connect(contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(emitCompletenessCheck()));
+ connect(jid_, SIGNAL(editingDone()), this, SLOT(handleEditingDone()));
+
+ setAcceptDrops(true);
}
bool QtUserSearchFirstMultiJIDPage::isComplete() const {
- return !contactList_->getList().empty();
+ return !contactList_->getList().empty();
}
void QtUserSearchFirstMultiJIDPage::reset() {
- jid_->clear();
- reason_->clear();
+ jid_->clear();
+ reason_->clear();
}
void QtUserSearchFirstMultiJIDPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
void QtUserSearchFirstMultiJIDPage::handleEditingDone() {
- addContactButton_->setFocus();
+ addContactButton_->setFocus();
}
void QtUserSearchFirstMultiJIDPage::dragEnterEvent(QDragEnterEvent *event) {
- if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")
- || event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
- if (!contactList_->isFull()) {
- event->acceptProposedAction();
- }
- }
+ if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")
+ || event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
+ if (!contactList_->isFull()) {
+ event->acceptProposedAction();
+ }
+ }
}
void QtUserSearchFirstMultiJIDPage::dropEvent(QDropEvent *event) {
- if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
- QByteArray dataBytes = event->mimeData()->data("application/vnd.swift.contact-jid-list");
- QDataStream dataStream(&dataBytes, QIODevice::ReadOnly);
- std::vector<JID> jids;
- while (!dataStream.atEnd()) {
- QString jidString;
- dataStream >> jidString;
- jids.push_back(Q2PSTRING(jidString));
- }
- onJIDsDropped(jids);
- } else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
- QMessageBox* messageBox = new QMessageBox(this);
- messageBox->setText(tr("You can't invite a room to chat."));
- messageBox->setWindowTitle(tr("Error inviting room to chat"));
- messageBox->show();
- }
+ if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
+ QByteArray dataBytes = event->mimeData()->data("application/vnd.swift.contact-jid-list");
+ QDataStream dataStream(&dataBytes, QIODevice::ReadOnly);
+ std::vector<JID> jids;
+ while (!dataStream.atEnd()) {
+ QString jidString;
+ dataStream >> jidString;
+ jids.push_back(Q2PSTRING(jidString));
+ }
+ onJIDsDropped(jids);
+ } else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
+ QMessageBox* messageBox = new QMessageBox(this);
+ messageBox->setText(tr("You can't invite a room to chat."));
+ messageBox->setWindowTitle(tr("Error inviting room to chat"));
+ messageBox->show();
+ }
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
index 82b8f93..d9147db 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
@@ -19,35 +19,35 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFirstMultiJIDPage.h>
namespace Swift {
- class UserSearchModel;
- class UserSearchDelegate;
- class UserSearchResult;
- class UIEventStream;
- class QtContactListWidget;
- class ContactSuggester;
- class AvatarManager;
- class VCardManager;
- class SettingsProvider;
- class QtSuggestingJIDInput;
-
- class QtUserSearchFirstMultiJIDPage : public QWizardPage, public Ui::QtUserSearchFirstMultiJIDPage {
- Q_OBJECT
- public:
- QtUserSearchFirstMultiJIDPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
- virtual bool isComplete() const;
- void reset();
-
- signals:
- void onJIDsDropped(std::vector<JID> jid);
-
- public slots:
- void emitCompletenessCheck();
- void handleEditingDone();
- virtual void dragEnterEvent(QDragEnterEvent *event);
- virtual void dropEvent(QDropEvent *event);
-
- public:
- QtContactListWidget* contactList_;
- QtSuggestingJIDInput* jid_;
- };
+ class UserSearchModel;
+ class UserSearchDelegate;
+ class UserSearchResult;
+ class UIEventStream;
+ class QtContactListWidget;
+ class ContactSuggester;
+ class AvatarManager;
+ class VCardManager;
+ class SettingsProvider;
+ class QtSuggestingJIDInput;
+
+ class QtUserSearchFirstMultiJIDPage : public QWizardPage, public Ui::QtUserSearchFirstMultiJIDPage {
+ Q_OBJECT
+ public:
+ QtUserSearchFirstMultiJIDPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
+ virtual bool isComplete() const;
+ void reset();
+
+ signals:
+ void onJIDsDropped(std::vector<JID> jid);
+
+ public slots:
+ void emitCompletenessCheck();
+ void handleEditingDone();
+ virtual void dragEnterEvent(QDragEnterEvent *event);
+ virtual void dropEvent(QDropEvent *event);
+
+ public:
+ QtContactListWidget* contactList_;
+ QtSuggestingJIDInput* jid_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
index 93157c7..5d0c9fa 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
@@ -13,37 +13,37 @@
namespace Swift {
QtUserSearchFirstPage::QtUserSearchFirstPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings) {
- setupUi(this);
- setTitle(title);
- setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(type == UserSearchWindow::AddContact ? tr("Add another user to your contact list") : tr("Chat to another user")));
- jid_ = new QtSuggestingJIDInput(this, settings);
- horizontalLayout_2->addWidget(jid_);
- jidWarning_ = new QLabel(this);
- jidWarning_->setPixmap(QPixmap(":icons/warn.png"));
- jidWarning_->hide();
- horizontalLayout_2->addWidget(jidWarning_);
- setTabOrder(byJID_, jid_);
- setTabOrder(jid_, byLocalSearch_);
- setTabOrder(byLocalSearch_, byRemoteSearch_);
- connect(jid_, SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
- connect(jid_, SIGNAL(editingDone()), this, SLOT(emitCompletenessCheck()));
- connect(service_->lineEdit(), SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
+ setupUi(this);
+ setTitle(title);
+ setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(type == UserSearchWindow::AddContact ? tr("Add another user to your contact list") : tr("Chat to another user")));
+ jid_ = new QtSuggestingJIDInput(this, settings);
+ horizontalLayout_2->addWidget(jid_);
+ jidWarning_ = new QLabel(this);
+ jidWarning_->setPixmap(QPixmap(":icons/warn.png"));
+ jidWarning_->hide();
+ horizontalLayout_2->addWidget(jidWarning_);
+ setTabOrder(byJID_, jid_);
+ setTabOrder(jid_, byLocalSearch_);
+ setTabOrder(byLocalSearch_, byRemoteSearch_);
+ connect(jid_, SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
+ connect(jid_, SIGNAL(editingDone()), this, SLOT(emitCompletenessCheck()));
+ connect(service_->lineEdit(), SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
}
bool QtUserSearchFirstPage::isComplete() const {
- bool complete = false;
- if (byJID_->isChecked()) {
- complete = JID(Q2PSTRING(jid_->text().trimmed())).isValid() && jidWarning_->toolTip().isEmpty();
- } else if (byLocalSearch_->isChecked()) {
- complete = true;
- } else if (byRemoteSearch_->isChecked()) {
- complete = JID(Q2PSTRING(service_->currentText().trimmed())).isValid();
- }
- return complete;
+ bool complete = false;
+ if (byJID_->isChecked()) {
+ complete = JID(Q2PSTRING(jid_->text().trimmed())).isValid() && jidWarning_->toolTip().isEmpty();
+ } else if (byLocalSearch_->isChecked()) {
+ complete = true;
+ } else if (byRemoteSearch_->isChecked()) {
+ complete = JID(Q2PSTRING(service_->currentText().trimmed())).isValid();
+ }
+ return complete;
}
void QtUserSearchFirstPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
index 9e765a0..2e73e9e 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
@@ -14,20 +14,20 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFirstPage.h>
namespace Swift {
- class UserSearchModel;
- class UserSearchDelegate;
- class UserSearchResult;
- class UIEventStream;
+ class UserSearchModel;
+ class UserSearchDelegate;
+ class UserSearchResult;
+ class UIEventStream;
- class QtUserSearchFirstPage : public QWizardPage, public Ui::QtUserSearchFirstPage {
- Q_OBJECT
- public:
- QtUserSearchFirstPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
- virtual bool isComplete() const;
- public slots:
- void emitCompletenessCheck();
- public:
- QtSuggestingJIDInput* jid_;
- QLabel* jidWarning_;
- };
+ class QtUserSearchFirstPage : public QWizardPage, public Ui::QtUserSearchFirstPage {
+ Q_OBJECT
+ public:
+ QtUserSearchFirstPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
+ virtual bool isComplete() const;
+ public slots:
+ void emitCompletenessCheck();
+ public:
+ QtSuggestingJIDInput* jid_;
+ QLabel* jidWarning_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
index 6ec4a34..c8a9ad8 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
@@ -9,31 +9,31 @@
namespace Swift {
QtUserSearchResultsPage::QtUserSearchResultsPage() {
- setupUi(this);
- connect(results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
- connect(results_, SIGNAL(activated(const QModelIndex&)), this, SIGNAL(onUserTriggersContinue()));
- connect(results_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
- connect(results_, SIGNAL(entered(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
- results_->setExpandsOnDoubleClick(false);
- setNoResults(false);
+ setupUi(this);
+ connect(results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
+ connect(results_, SIGNAL(activated(const QModelIndex&)), this, SIGNAL(onUserTriggersContinue()));
+ connect(results_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
+ connect(results_, SIGNAL(entered(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
+ results_->setExpandsOnDoubleClick(false);
+ setNoResults(false);
}
bool QtUserSearchResultsPage::isComplete() const {
- return results_->currentIndex().isValid();
+ return results_->currentIndex().isValid();
}
void QtUserSearchResultsPage::setNoResults(bool noResults) {
- if (noResults) {
- results_->setEnabled(false);
- noResults_->show();
- } else {
- results_->setEnabled(true);
- noResults_->hide();
- }
+ if (noResults) {
+ results_->setEnabled(false);
+ noResults_->show();
+ } else {
+ results_->setEnabled(true);
+ noResults_->hide();
+ }
}
void QtUserSearchResultsPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
index d2ee566..33227e6 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
@@ -11,15 +11,15 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchResultsPage.h>
namespace Swift {
- class QtUserSearchResultsPage : public QWizardPage, public Ui::QtUserSearchResultsPage {
- Q_OBJECT
- public:
- QtUserSearchResultsPage();
- virtual bool isComplete() const;
- void setNoResults(bool noResults);
- signals:
- void onUserTriggersContinue();
- public slots:
- void emitCompletenessCheck();
- };
+ class QtUserSearchResultsPage : public QWizardPage, public Ui::QtUserSearchResultsPage {
+ Q_OBJECT
+ public:
+ QtUserSearchResultsPage();
+ virtual bool isComplete() const;
+ void setNoResults(bool noResults);
+ signals:
+ void onUserTriggersContinue();
+ public slots:
+ void emitCompletenessCheck();
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp b/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
index 52b17b0..1140b6e 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
@@ -37,592 +37,592 @@
namespace Swift {
QtUserSearchWindow::QtUserSearchWindow(UIEventStream* eventStream, UserSearchWindow::Type type, const std::set<std::string>& groups, SettingsProvider* settingsProvider) : eventStream_(eventStream), type_(type), model_(NULL), firstMultiJIDPage_(NULL), settings_(settingsProvider), searchNext_(false), supportsImpromptu_(false) {
- setupUi(this);
+ setupUi(this);
#ifndef Q_OS_MAC
#ifdef Q_OS_WIN32
- setWindowIcon(QIcon(":/logo-icon-16-win.png"));
+ setWindowIcon(QIcon(":/logo-icon-16-win.png"));
#else
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
#endif
- QString title;
- switch(type) {
- case AddContact:
- title = tr("Add Contact");
- break;
- case ChatToContact:
- title = tr("Chat to Users");
- break;
- case InviteToChat:
- title = tr("Add Users to Chat");
- break;
- }
- setWindowTitle(title);
-
- delegate_ = new UserSearchDelegate(this);
-
- setFirstPage(title);
- setSecondPage();
- setThirdPage();
-
- detailsPage_ = new QtUserSearchDetailsPage(groups);
- setPage(4, detailsPage_);
-
- connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(handleCurrentChanged(int)));
- connect(this, SIGNAL(accepted()), this, SLOT(handleAccepted()));
- clear();
+ QString title;
+ switch(type) {
+ case AddContact:
+ title = tr("Add Contact");
+ break;
+ case ChatToContact:
+ title = tr("Chat to Users");
+ break;
+ case InviteToChat:
+ title = tr("Add Users to Chat");
+ break;
+ }
+ setWindowTitle(title);
+
+ delegate_ = new UserSearchDelegate(this);
+
+ setFirstPage(title);
+ setSecondPage();
+ setThirdPage();
+
+ detailsPage_ = new QtUserSearchDetailsPage(groups);
+ setPage(4, detailsPage_);
+
+ connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(handleCurrentChanged(int)));
+ connect(this, SIGNAL(accepted()), this, SLOT(handleAccepted()));
+ clear();
}
QtUserSearchWindow::~QtUserSearchWindow() {
- delete model_;
+ delete model_;
}
void QtUserSearchWindow::handleCurrentChanged(int page) {
- searchNext_ = false;
- if (firstMultiJIDPage_) {
- firstMultiJIDPage_->reset();
- }
- resultsPage_->emitCompletenessCheck();
- if (page == 1 && lastPage_ == 3) {
- addSearchedJIDToList(getContact());
- setSecondPage();
- }
- else if (page == 2 && lastPage_ == 1) {
- setError("");
- /* next won't be called if JID is selected */
- JID server = getServerToSearch();
- clearForm();
- onFormRequested(server);
- setThirdPage();
- }
- else if (page == 3 && lastPage_ == 2) {
- JID server = getServerToSearch();
- handleSearch();
-
- if (type_ == AddContact) {
- bool remote = firstPage_->byRemoteSearch_->isChecked();
- firstPage_->byRemoteSearch_->setChecked(remote);
- firstPage_->service_->setEditText(P2QSTRING(server.toString()));
- } else {
- bool remote = firstMultiJIDPage_->byRemoteSearch_->isChecked();
- setFirstPage();
- firstMultiJIDPage_->byRemoteSearch_->setChecked(remote);
- firstMultiJIDPage_->service_->setEditText(P2QSTRING(server.toString()));
- }
- }
- else if (page == 4) {
- detailsPage_->clear();
- detailsPage_->setJID(getContactJID());
- onNameSuggestionRequested(getContactJID());
- }
- lastPage_ = page;
+ searchNext_ = false;
+ if (firstMultiJIDPage_) {
+ firstMultiJIDPage_->reset();
+ }
+ resultsPage_->emitCompletenessCheck();
+ if (page == 1 && lastPage_ == 3) {
+ addSearchedJIDToList(getContact());
+ setSecondPage();
+ }
+ else if (page == 2 && lastPage_ == 1) {
+ setError("");
+ /* next won't be called if JID is selected */
+ JID server = getServerToSearch();
+ clearForm();
+ onFormRequested(server);
+ setThirdPage();
+ }
+ else if (page == 3 && lastPage_ == 2) {
+ JID server = getServerToSearch();
+ handleSearch();
+
+ if (type_ == AddContact) {
+ bool remote = firstPage_->byRemoteSearch_->isChecked();
+ firstPage_->byRemoteSearch_->setChecked(remote);
+ firstPage_->service_->setEditText(P2QSTRING(server.toString()));
+ } else {
+ bool remote = firstMultiJIDPage_->byRemoteSearch_->isChecked();
+ setFirstPage();
+ firstMultiJIDPage_->byRemoteSearch_->setChecked(remote);
+ firstMultiJIDPage_->service_->setEditText(P2QSTRING(server.toString()));
+ }
+ }
+ else if (page == 4) {
+ detailsPage_->clear();
+ detailsPage_->setJID(getContactJID());
+ onNameSuggestionRequested(getContactJID());
+ }
+ lastPage_ = page;
}
JID QtUserSearchWindow::getServerToSearch() {
- if (type_ == AddContact) {
- return firstPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstPage_->service_->currentText().trimmed())) : myServer_;
- } else {
- return firstMultiJIDPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstMultiJIDPage_->service_->currentText().trimmed())) : myServer_;
- }
+ if (type_ == AddContact) {
+ return firstPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstPage_->service_->currentText().trimmed())) : myServer_;
+ } else {
+ return firstMultiJIDPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstMultiJIDPage_->service_->currentText().trimmed())) : myServer_;
+ }
}
void QtUserSearchWindow::handleAccepted() {
- JID jid;
- std::vector<JID> jids;
- switch(type_) {
- case AddContact:
- jid = getContactJID();
- eventStream_->send(boost::make_shared<AddContactUIEvent>(jid, detailsPage_->getName(), detailsPage_->getSelectedGroups()));
- break;
- case ChatToContact:
- if (contactVector_.size() == 1) {
- boost::shared_ptr<UIEvent> event(new RequestChatUIEvent(contactVector_[0]->jid));
- eventStream_->send(event);
- break;
- }
-
- foreach(Contact::ref contact, contactVector_) {
- jids.push_back(contact->jid);
- }
-
- eventStream_->send(boost::make_shared<CreateImpromptuMUCUIEvent>(jids, JID(), Q2PSTRING(firstMultiJIDPage_->reason_->text())));
- break;
- case InviteToChat:
- foreach(Contact::ref contact, contactVector_) {
- jids.push_back(contact->jid);
- }
- eventStream_->send(boost::make_shared<InviteToMUCUIEvent>(roomJID_, jids, Q2PSTRING(firstMultiJIDPage_->reason_->text())));
- break;
- }
+ JID jid;
+ std::vector<JID> jids;
+ switch(type_) {
+ case AddContact:
+ jid = getContactJID();
+ eventStream_->send(boost::make_shared<AddContactUIEvent>(jid, detailsPage_->getName(), detailsPage_->getSelectedGroups()));
+ break;
+ case ChatToContact:
+ if (contactVector_.size() == 1) {
+ boost::shared_ptr<UIEvent> event(new RequestChatUIEvent(contactVector_[0]->jid));
+ eventStream_->send(event);
+ break;
+ }
+
+ foreach(Contact::ref contact, contactVector_) {
+ jids.push_back(contact->jid);
+ }
+
+ eventStream_->send(boost::make_shared<CreateImpromptuMUCUIEvent>(jids, JID(), Q2PSTRING(firstMultiJIDPage_->reason_->text())));
+ break;
+ case InviteToChat:
+ foreach(Contact::ref contact, contactVector_) {
+ jids.push_back(contact->jid);
+ }
+ eventStream_->send(boost::make_shared<InviteToMUCUIEvent>(roomJID_, jids, Q2PSTRING(firstMultiJIDPage_->reason_->text())));
+ break;
+ }
}
void QtUserSearchWindow::handleContactSuggestionRequested(const QString& text) {
- std::string stdText = Q2PSTRING(text);
- onContactSuggestionsRequested(stdText);
+ std::string stdText = Q2PSTRING(text);
+ onContactSuggestionsRequested(stdText);
}
void QtUserSearchWindow::addContact() {
- if (!!firstMultiJIDPage_->jid_->getContact()) {
- contactVector_.push_back(firstMultiJIDPage_->jid_->getContact());
- firstMultiJIDPage_->jid_->clear();
- }
- firstMultiJIDPage_->contactList_->setList(contactVector_);
- firstMultiJIDPage_->emitCompletenessCheck();
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
- }
+ if (!!firstMultiJIDPage_->jid_->getContact()) {
+ contactVector_.push_back(firstMultiJIDPage_->jid_->getContact());
+ firstMultiJIDPage_->jid_->clear();
+ }
+ firstMultiJIDPage_->contactList_->setList(contactVector_);
+ firstMultiJIDPage_->emitCompletenessCheck();
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
+ }
}
void QtUserSearchWindow::setWarning(const boost::optional<std::string>& message) {
- if (message) {
- firstPage_->jidWarning_->setToolTip(P2QSTRING((*message)));
- firstPage_->jidWarning_->setAccessibleDescription(P2QSTRING((*message)));
- firstPage_->jidWarning_->show();
- }
- else {
- firstPage_->jidWarning_->setToolTip("");
- firstPage_->jidWarning_->setAccessibleDescription("");
- firstPage_->jidWarning_->hide();
- }
- firstPage_->emitCompletenessCheck();
+ if (message) {
+ firstPage_->jidWarning_->setToolTip(P2QSTRING((*message)));
+ firstPage_->jidWarning_->setAccessibleDescription(P2QSTRING((*message)));
+ firstPage_->jidWarning_->show();
+ }
+ else {
+ firstPage_->jidWarning_->setToolTip("");
+ firstPage_->jidWarning_->setAccessibleDescription("");
+ firstPage_->jidWarning_->hide();
+ }
+ firstPage_->emitCompletenessCheck();
}
int QtUserSearchWindow::nextId() const {
- if (type_ == AddContact) {
- switch (currentId()) {
- case 1: return firstPage_->byJID_->isChecked() ? (type_ == AddContact ? 4 : -1) : 2;
- case 2: return 3;
- case 3: return type_ == AddContact ? 4 : -1;
- case 4: return -1;
- default: return -1;
- }
- } else {
- switch (currentId()) {
- case 1: return searchNext_ ? 2 : -1;
- case 2: return 3;
- case 3: return 1;
- case 4: return -1;
- default: return -1;
- }
- }
+ if (type_ == AddContact) {
+ switch (currentId()) {
+ case 1: return firstPage_->byJID_->isChecked() ? (type_ == AddContact ? 4 : -1) : 2;
+ case 2: return 3;
+ case 3: return type_ == AddContact ? 4 : -1;
+ case 4: return -1;
+ default: return -1;
+ }
+ } else {
+ switch (currentId()) {
+ case 1: return searchNext_ ? 2 : -1;
+ case 2: return 3;
+ case 3: return 1;
+ case 4: return -1;
+ default: return -1;
+ }
+ }
}
void QtUserSearchWindow::handleFirstPageRadioChange() {
- if (firstPage_->byJID_->isChecked()) {
- firstPage_->jid_->setText("");
- firstPage_->jid_->setEnabled(true);
- firstPage_->service_->setEnabled(false);
- restart();
- }
- else if (firstPage_->byRemoteSearch_->isChecked()) {
- firstPage_->service_->setEditText("");
- firstPage_->jid_->setEnabled(false);
- firstPage_->service_->setEnabled(true);
- //firstPage_->jid_->setText("");
- restart();
- }
- else {
- firstPage_->jid_->setEnabled(false);
- firstPage_->service_->setEnabled(false);
- restart();
- }
+ if (firstPage_->byJID_->isChecked()) {
+ firstPage_->jid_->setText("");
+ firstPage_->jid_->setEnabled(true);
+ firstPage_->service_->setEnabled(false);
+ restart();
+ }
+ else if (firstPage_->byRemoteSearch_->isChecked()) {
+ firstPage_->service_->setEditText("");
+ firstPage_->jid_->setEnabled(false);
+ firstPage_->service_->setEnabled(true);
+ //firstPage_->jid_->setText("");
+ restart();
+ }
+ else {
+ firstPage_->jid_->setEnabled(false);
+ firstPage_->service_->setEnabled(false);
+ restart();
+ }
}
void QtUserSearchWindow::handleSearch() {
- boost::shared_ptr<SearchPayload> search(new SearchPayload());
- if (fieldsPage_->getFormWidget()) {
- search->setForm(fieldsPage_->getFormWidget()->getCompletedForm());
- search->getForm()->clearEmptyTextFields();
- } else {
- if (fieldsPage_->nickInput_->isEnabled() && !fieldsPage_->nickInput_->text().isEmpty()) {
- search->setNick(Q2PSTRING(fieldsPage_->nickInput_->text()));
- }
- if (fieldsPage_->firstInput_->isEnabled() && !fieldsPage_->firstInput_->text().isEmpty()) {
- search->setFirst(Q2PSTRING(fieldsPage_->firstInput_->text()));
- }
- if (fieldsPage_->lastInput_->isEnabled() && !fieldsPage_->lastInput_->text().isEmpty()) {
- search->setLast(Q2PSTRING(fieldsPage_->lastInput_->text()));
- }
- if (fieldsPage_->emailInput_->isEnabled() && !fieldsPage_->emailInput_->text().isEmpty()) {
- search->setEMail(Q2PSTRING(fieldsPage_->emailInput_->text()));
- }
- }
- onSearchRequested(search, getServerToSearch());
+ boost::shared_ptr<SearchPayload> search(new SearchPayload());
+ if (fieldsPage_->getFormWidget()) {
+ search->setForm(fieldsPage_->getFormWidget()->getCompletedForm());
+ search->getForm()->clearEmptyTextFields();
+ } else {
+ if (fieldsPage_->nickInput_->isEnabled() && !fieldsPage_->nickInput_->text().isEmpty()) {
+ search->setNick(Q2PSTRING(fieldsPage_->nickInput_->text()));
+ }
+ if (fieldsPage_->firstInput_->isEnabled() && !fieldsPage_->firstInput_->text().isEmpty()) {
+ search->setFirst(Q2PSTRING(fieldsPage_->firstInput_->text()));
+ }
+ if (fieldsPage_->lastInput_->isEnabled() && !fieldsPage_->lastInput_->text().isEmpty()) {
+ search->setLast(Q2PSTRING(fieldsPage_->lastInput_->text()));
+ }
+ if (fieldsPage_->emailInput_->isEnabled() && !fieldsPage_->emailInput_->text().isEmpty()) {
+ search->setEMail(Q2PSTRING(fieldsPage_->emailInput_->text()));
+ }
+ }
+ onSearchRequested(search, getServerToSearch());
}
JID QtUserSearchWindow::getContactJID() const {
- JID jid;
-
- bool useSearchResult;
- if (type_ == AddContact) {
- useSearchResult = !firstPage_->byJID_->isChecked();
- } else {
- useSearchResult = true;
- }
-
- if (useSearchResult) {
- if (dynamic_cast<UserSearchModel*>(model_)) {
- UserSearchResult* userItem = static_cast<UserSearchResult*>(resultsPage_->results_->currentIndex().internalPointer());
- if (userItem) { /* Remember to leave this if we change to dynamic cast */
- jid = userItem->getJID();
- }
- } else if (dynamic_cast<QtFormResultItemModel*>(model_)) {
- int row = resultsPage_->results_->currentIndex().row();
-
- Form::FormItem item = dynamic_cast<QtFormResultItemModel*>(model_)->getForm()->getItems().at(row);
- JID fallbackJid;
- foreach(FormField::ref field, item) {
- if (field->getType() == FormField::JIDSingleType) {
- jid = JID(field->getJIDSingleValue());
- break;
- }
- if (field->getName() == "jid") {
- fallbackJid = field->getValues()[0];
- }
- }
- if (!jid.isValid()) {
- jid = fallbackJid;
- }
- }
- }
- else {
- jid = JID(Q2PSTRING(firstPage_->jid_->text().trimmed()));
- }
- return jid;
+ JID jid;
+
+ bool useSearchResult;
+ if (type_ == AddContact) {
+ useSearchResult = !firstPage_->byJID_->isChecked();
+ } else {
+ useSearchResult = true;
+ }
+
+ if (useSearchResult) {
+ if (dynamic_cast<UserSearchModel*>(model_)) {
+ UserSearchResult* userItem = static_cast<UserSearchResult*>(resultsPage_->results_->currentIndex().internalPointer());
+ if (userItem) { /* Remember to leave this if we change to dynamic cast */
+ jid = userItem->getJID();
+ }
+ } else if (dynamic_cast<QtFormResultItemModel*>(model_)) {
+ int row = resultsPage_->results_->currentIndex().row();
+
+ Form::FormItem item = dynamic_cast<QtFormResultItemModel*>(model_)->getForm()->getItems().at(row);
+ JID fallbackJid;
+ foreach(FormField::ref field, item) {
+ if (field->getType() == FormField::JIDSingleType) {
+ jid = JID(field->getJIDSingleValue());
+ break;
+ }
+ if (field->getName() == "jid") {
+ fallbackJid = field->getValues()[0];
+ }
+ }
+ if (!jid.isValid()) {
+ jid = fallbackJid;
+ }
+ }
+ }
+ else {
+ jid = JID(Q2PSTRING(firstPage_->jid_->text().trimmed()));
+ }
+ return jid;
}
Contact::ref QtUserSearchWindow::getContact() const {
- return boost::make_shared<Contact>("", getContactJID(), StatusShow::None, "");
+ return boost::make_shared<Contact>("", getContactJID(), StatusShow::None, "");
}
void QtUserSearchWindow::addSearchedJIDToList(const Contact::ref& contact) {
- std::vector<JID> jids;
- jids.push_back(contact->jid);
- handleJIDsAdded(jids);
- firstMultiJIDPage_->jid_->clear();
+ std::vector<JID> jids;
+ jids.push_back(contact->jid);
+ handleJIDsAdded(jids);
+ firstMultiJIDPage_->jid_->clear();
}
void QtUserSearchWindow::handleOnSearchedJIDSelected(const Contact::ref& contact) {
- firstPage_->jid_->setText(P2QSTRING(contact->jid.toString()));
+ firstPage_->jid_->setText(P2QSTRING(contact->jid.toString()));
}
void QtUserSearchWindow::show() {
- clear();
- if (type_ == AddContact) {
- setWarning(boost::optional<std::string>());
- }
- QWidget::show();
+ clear();
+ if (type_ == AddContact) {
+ setWarning(boost::optional<std::string>());
+ }
+ QWidget::show();
}
void QtUserSearchWindow::addSavedServices(const std::vector<JID>& services) {
- if (type_ == AddContact) {
- firstPage_->service_->clear();
- foreach (JID jid, services) {
- firstPage_->service_->addItem(P2QSTRING(jid.toString()));
- }
- firstPage_->service_->clearEditText();
- } else {
- firstMultiJIDPage_->service_->clear();
- foreach (JID jid, services) {
- firstMultiJIDPage_->service_->addItem(P2QSTRING(jid.toString()));
- }
- firstMultiJIDPage_->service_->clearEditText();
- }
+ if (type_ == AddContact) {
+ firstPage_->service_->clear();
+ foreach (JID jid, services) {
+ firstPage_->service_->addItem(P2QSTRING(jid.toString()));
+ }
+ firstPage_->service_->clearEditText();
+ } else {
+ firstMultiJIDPage_->service_->clear();
+ foreach (JID jid, services) {
+ firstMultiJIDPage_->service_->addItem(P2QSTRING(jid.toString()));
+ }
+ firstMultiJIDPage_->service_->clearEditText();
+ }
}
void QtUserSearchWindow::setSearchFields(boost::shared_ptr<SearchPayload> fields) {
- fieldsPage_->fetchingThrobber_->hide();
- fieldsPage_->fetchingThrobber_->movie()->stop();
- fieldsPage_->fetchingLabel_->hide();
-
- fieldsPage_->instructionsLabel_->setText(fields->getInstructions() ? P2QSTRING(fields->getInstructions().get()) : "Enter search terms");
- if (fields->getForm()) {
- fieldsPage_->setFormWidget(new QtFormWidget(fields->getForm(), fieldsPage_));
- } else {
- fieldsPage_->setFormWidget(NULL);
- bool enabled[8] = {!!fields->getNick(), !!fields->getNick(), !!fields->getFirst(), !!fields->getFirst(), !!fields->getLast(), !!fields->getLast(), !!fields->getEMail(), !!fields->getEMail()};
- QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
- for (int i = 0; i < 8; i++) {
- legacySearchWidgets[i]->setVisible(enabled[i]);
- legacySearchWidgets[i]->setEnabled(enabled[i]);
- }
- }
- fieldsPage_->emitCompletenessCheck();
+ fieldsPage_->fetchingThrobber_->hide();
+ fieldsPage_->fetchingThrobber_->movie()->stop();
+ fieldsPage_->fetchingLabel_->hide();
+
+ fieldsPage_->instructionsLabel_->setText(fields->getInstructions() ? P2QSTRING(fields->getInstructions().get()) : "Enter search terms");
+ if (fields->getForm()) {
+ fieldsPage_->setFormWidget(new QtFormWidget(fields->getForm(), fieldsPage_));
+ } else {
+ fieldsPage_->setFormWidget(NULL);
+ bool enabled[8] = {!!fields->getNick(), !!fields->getNick(), !!fields->getFirst(), !!fields->getFirst(), !!fields->getLast(), !!fields->getLast(), !!fields->getEMail(), !!fields->getEMail()};
+ QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
+ for (int i = 0; i < 8; i++) {
+ legacySearchWidgets[i]->setVisible(enabled[i]);
+ legacySearchWidgets[i]->setEnabled(enabled[i]);
+ }
+ }
+ fieldsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::setNameSuggestions(const std::vector<std::string>& suggestions) {
- if (detailsPage_) {
- detailsPage_->setNameSuggestions(suggestions);
- }
+ if (detailsPage_) {
+ detailsPage_->setNameSuggestions(suggestions);
+ }
}
void QtUserSearchWindow::prepopulateJIDAndName(const JID& jid, const std::string& name) {
- firstPage_->jid_->setText(P2QSTRING(jid.toBare().toString()));
- detailsPage_->setJID(jid);
- lastPage_ = 1;
- restart();
- next();
- detailsPage_->setName(name);
+ firstPage_->jid_->setText(P2QSTRING(jid.toBare().toString()));
+ detailsPage_->setJID(jid);
+ lastPage_ = 1;
+ restart();
+ next();
+ detailsPage_->setName(name);
}
void QtUserSearchWindow::setContactSuggestions(const std::vector<Contact::ref>& suggestions) {
- if (type_ == AddContact) {
- firstPage_->jid_->setSuggestions(suggestions);
- } else {
- firstMultiJIDPage_->jid_->setSuggestions(suggestions);
- }
+ if (type_ == AddContact) {
+ firstPage_->jid_->setSuggestions(suggestions);
+ } else {
+ firstMultiJIDPage_->jid_->setSuggestions(suggestions);
+ }
}
void QtUserSearchWindow::setJIDs(const std::vector<JID> &jids) {
- foreach(JID jid, jids) {
- addSearchedJIDToList(boost::make_shared<Contact>("", jid, StatusShow::None, ""));
- }
- onJIDUpdateRequested(jids);
+ foreach(JID jid, jids) {
+ addSearchedJIDToList(boost::make_shared<Contact>("", jid, StatusShow::None, ""));
+ }
+ onJIDUpdateRequested(jids);
}
void QtUserSearchWindow::setRoomJID(const JID& roomJID) {
- roomJID_ = roomJID;
+ roomJID_ = roomJID;
}
std::string QtUserSearchWindow::getReason() const {
- return Q2PSTRING(firstMultiJIDPage_->reason_->text());
+ return Q2PSTRING(firstMultiJIDPage_->reason_->text());
}
std::vector<JID> QtUserSearchWindow::getJIDs() const {
- std::vector<JID> jids;
- foreach (Contact::ref contact, contactVector_) {
- jids.push_back(contact->jid);
- }
- return jids;
+ std::vector<JID> jids;
+ foreach (Contact::ref contact, contactVector_) {
+ jids.push_back(contact->jid);
+ }
+ return jids;
}
void QtUserSearchWindow::setCanStartImpromptuChats(bool supportsImpromptu) {
- supportsImpromptu_ = supportsImpromptu;
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->contactList_->setMaximumNoOfContactsToOne(!supportsImpromptu_);
- }
+ supportsImpromptu_ = supportsImpromptu;
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->contactList_->setMaximumNoOfContactsToOne(!supportsImpromptu_);
+ }
}
void QtUserSearchWindow::updateContacts(const std::vector<Contact::ref>& contacts) {
- if (type_ != AddContact) {
- firstMultiJIDPage_->contactList_->updateContacts(contacts);
- }
+ if (type_ != AddContact) {
+ firstMultiJIDPage_->contactList_->updateContacts(contacts);
+ }
}
void QtUserSearchWindow::addContacts(const std::vector<Contact::ref>& contacts) {
- if (type_ != AddContact) {
- /* prevent duplicate JIDs from appearing in the contact list */
- foreach (Contact::ref newContact, contacts) {
- bool found = false;
- foreach (Contact::ref oldContact, contactVector_) {
- if (newContact->jid == oldContact->jid) {
- found = true;
- break;
- }
- }
- if (!found) {
- contactVector_.push_back(newContact);
- }
- }
- if (!supportsImpromptu_ && contactVector_.size() > 1) {
- contactVector_.resize(1); /* can't chat with more than one user */
- }
- firstMultiJIDPage_->contactList_->setList(contactVector_);
- firstMultiJIDPage_->emitCompletenessCheck();
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? true : (contactVector_.size() < 1));
- }
- }
+ if (type_ != AddContact) {
+ /* prevent duplicate JIDs from appearing in the contact list */
+ foreach (Contact::ref newContact, contacts) {
+ bool found = false;
+ foreach (Contact::ref oldContact, contactVector_) {
+ if (newContact->jid == oldContact->jid) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ contactVector_.push_back(newContact);
+ }
+ }
+ if (!supportsImpromptu_ && contactVector_.size() > 1) {
+ contactVector_.resize(1); /* can't chat with more than one user */
+ }
+ firstMultiJIDPage_->contactList_->setList(contactVector_);
+ firstMultiJIDPage_->emitCompletenessCheck();
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? true : (contactVector_.size() < 1));
+ }
+ }
}
void QtUserSearchWindow::setCanSupplyDescription(bool allowed) {
- firstMultiJIDPage_->label->setVisible(allowed);
- firstMultiJIDPage_->reason_->setVisible(allowed);
+ firstMultiJIDPage_->label->setVisible(allowed);
+ firstMultiJIDPage_->reason_->setVisible(allowed);
}
void QtUserSearchWindow::handleAddViaSearch() {
- searchNext_ = true;
- next();
+ searchNext_ = true;
+ next();
}
void QtUserSearchWindow::handleListChanged(std::vector<Contact::ref> list) {
- contactVector_ = list;
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
- }
+ contactVector_ = list;
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
+ }
}
void QtUserSearchWindow::handleJIDsAdded(std::vector<JID> jids) {
- onJIDAddRequested(jids);
+ onJIDAddRequested(jids);
}
void QtUserSearchWindow::setResults(const std::vector<UserSearchResult>& results) {
- UserSearchModel *newModel = new UserSearchModel();
- newModel->setResults(results);
- resultsPage_->results_->setModel(newModel);
- resultsPage_->results_->setItemDelegate(delegate_);
- resultsPage_->results_->setHeaderHidden(true);
- delete model_;
- model_ = newModel;
- resultsPage_->setNoResults(model_->rowCount() == 0);
- resultsPage_->emitCompletenessCheck();
+ UserSearchModel *newModel = new UserSearchModel();
+ newModel->setResults(results);
+ resultsPage_->results_->setModel(newModel);
+ resultsPage_->results_->setItemDelegate(delegate_);
+ resultsPage_->results_->setHeaderHidden(true);
+ delete model_;
+ model_ = newModel;
+ resultsPage_->setNoResults(model_->rowCount() == 0);
+ resultsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::setResultsForm(Form::ref results) {
- QtFormResultItemModel *newModel = new QtFormResultItemModel(this);
- newModel->setForm(results);
- resultsPage_->results_->setModel(newModel);
- resultsPage_->results_->setItemDelegate(new QItemDelegate());
- resultsPage_->results_->setHeaderHidden(false);
+ QtFormResultItemModel *newModel = new QtFormResultItemModel(this);
+ newModel->setForm(results);
+ resultsPage_->results_->setModel(newModel);
+ resultsPage_->results_->setItemDelegate(new QItemDelegate());
+ resultsPage_->results_->setHeaderHidden(false);
#if QT_VERSION >= 0x050000
- resultsPage_->results_->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
+ resultsPage_->results_->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
- resultsPage_->results_->header()->setResizeMode(QHeaderView::ResizeToContents);
+ resultsPage_->results_->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
- delete model_;
- model_ = newModel;
- resultsPage_->setNoResults(model_->rowCount() == 0);
- resultsPage_->emitCompletenessCheck();
+ delete model_;
+ model_ = newModel;
+ resultsPage_->setNoResults(model_->rowCount() == 0);
+ resultsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::setSelectedService(const JID& jid) {
- myServer_ = jid;
+ myServer_ = jid;
}
void QtUserSearchWindow::handleJIDEditingDone() {
- onJIDEditFieldChanged(JID(Q2PSTRING(firstPage_->jid_->text())));
+ onJIDEditFieldChanged(JID(Q2PSTRING(firstPage_->jid_->text())));
}
void QtUserSearchWindow::setFirstPage(QString title) {
- if (page(1) != 0) {
- removePage(1);
- }
- if (type_ == AddContact) {
- firstPage_ = new QtUserSearchFirstPage(type_, title.isEmpty() ? firstPage_->title() : title, settings_);
- connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
- connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleJIDEditingDone()), Qt::UniqueConnection);
- firstPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::handleOnSearchedJIDSelected, this, _1));
- connect(firstPage_->byJID_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
- connect(firstPage_->byLocalSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
- connect(firstPage_->byRemoteSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
+ if (page(1) != 0) {
+ removePage(1);
+ }
+ if (type_ == AddContact) {
+ firstPage_ = new QtUserSearchFirstPage(type_, title.isEmpty() ? firstPage_->title() : title, settings_);
+ connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
+ connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleJIDEditingDone()), Qt::UniqueConnection);
+ firstPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::handleOnSearchedJIDSelected, this, _1));
+ connect(firstPage_->byJID_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
+ connect(firstPage_->byLocalSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
+ connect(firstPage_->byRemoteSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
#if QT_VERSION >= 0x040700
- firstPage_->jid_->setPlaceholderText(tr("alice@wonderland.lit"));
+ firstPage_->jid_->setPlaceholderText(tr("alice@wonderland.lit"));
#endif
- firstPage_->service_->setEnabled(false);
- setPage(1, firstPage_);
- } else {
- firstMultiJIDPage_ = new QtUserSearchFirstMultiJIDPage(type_, title.isEmpty() ? firstMultiJIDPage_->title() : title, settings_);
- connect(firstMultiJIDPage_->addContactButton_, SIGNAL(clicked()), this, SLOT(addContact()));
- connect(firstMultiJIDPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
- firstMultiJIDPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::addSearchedJIDToList, this, _1));
- connect(firstMultiJIDPage_->addViaSearchButton_, SIGNAL(clicked()), this, SLOT(handleAddViaSearch()));
- connect(firstMultiJIDPage_->contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(handleListChanged(std::vector<Contact::ref>)));
- connect(firstMultiJIDPage_->contactList_, SIGNAL(onJIDsAdded(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
- connect(firstMultiJIDPage_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
- setPage(1, firstMultiJIDPage_);
- }
+ firstPage_->service_->setEnabled(false);
+ setPage(1, firstPage_);
+ } else {
+ firstMultiJIDPage_ = new QtUserSearchFirstMultiJIDPage(type_, title.isEmpty() ? firstMultiJIDPage_->title() : title, settings_);
+ connect(firstMultiJIDPage_->addContactButton_, SIGNAL(clicked()), this, SLOT(addContact()));
+ connect(firstMultiJIDPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
+ firstMultiJIDPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::addSearchedJIDToList, this, _1));
+ connect(firstMultiJIDPage_->addViaSearchButton_, SIGNAL(clicked()), this, SLOT(handleAddViaSearch()));
+ connect(firstMultiJIDPage_->contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(handleListChanged(std::vector<Contact::ref>)));
+ connect(firstMultiJIDPage_->contactList_, SIGNAL(onJIDsAdded(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
+ connect(firstMultiJIDPage_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
+ setPage(1, firstMultiJIDPage_);
+ }
}
void QtUserSearchWindow::setSecondPage() {
- if (page(2) != 0) {
- removePage(2);
- }
- fieldsPage_ = new QtUserSearchFieldsPage();
- fieldsPage_->fetchingThrobber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
- fieldsPage_->fetchingThrobber_->movie()->stop();
- setPage(2, fieldsPage_);
+ if (page(2) != 0) {
+ removePage(2);
+ }
+ fieldsPage_ = new QtUserSearchFieldsPage();
+ fieldsPage_->fetchingThrobber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
+ fieldsPage_->fetchingThrobber_->movie()->stop();
+ setPage(2, fieldsPage_);
}
void QtUserSearchWindow::setThirdPage() {
- if (page(3) != 0) {
- removePage(3);
- }
- resultsPage_ = new QtUserSearchResultsPage();
+ if (page(3) != 0) {
+ removePage(3);
+ }
+ resultsPage_ = new QtUserSearchResultsPage();
#ifdef SWIFT_PLATFORM_MACOSX
- resultsPage_->results_->setAlternatingRowColors(true);
+ resultsPage_->results_->setAlternatingRowColors(true);
#endif
- if (type_ == AddContact) {
- connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
- }
- else {
- connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
- }
- setPage(3, resultsPage_);
+ if (type_ == AddContact) {
+ connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
+ }
+ else {
+ connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
+ }
+ setPage(3, resultsPage_);
}
void QtUserSearchWindow::clearForm() {
- fieldsPage_->fetchingThrobber_->show();
- fieldsPage_->fetchingThrobber_->movie()->start();
- fieldsPage_->fetchingLabel_->show();
- QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
- for (int i = 0; i < 8; i++) {
- legacySearchWidgets[i]->hide();
- if (QLineEdit* edit = qobject_cast<QLineEdit*>(legacySearchWidgets[i])) {
- edit->clear();
- }
- }
- fieldsPage_->emitCompletenessCheck();
+ fieldsPage_->fetchingThrobber_->show();
+ fieldsPage_->fetchingThrobber_->movie()->start();
+ fieldsPage_->fetchingLabel_->show();
+ QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
+ for (int i = 0; i < 8; i++) {
+ legacySearchWidgets[i]->hide();
+ if (QLineEdit* edit = qobject_cast<QLineEdit*>(legacySearchWidgets[i])) {
+ edit->clear();
+ }
+ }
+ fieldsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::clear() {
- QString howText;
- if (type_ == AddContact) {
- firstPage_->errorLabel_->setVisible(false);
- howText = QString(tr("How would you like to find the user to add?"));
- firstPage_->howLabel_->setText(howText);
- firstPage_->byJID_->setChecked(true);
- handleFirstPageRadioChange();
- } else {
- contactVector_.clear();
- firstMultiJIDPage_->contactList_->setList(contactVector_);
- firstMultiJIDPage_->errorLabel_->setVisible(false);
- if (type_ == ChatToContact) {
- howText = QString(tr("List of participants:"));
- } else if (type_ == InviteToChat) {
- howText = QString(tr("Who do you want to invite to the chat?"));
- }
- firstMultiJIDPage_->howLabel_->setText(howText);
- }
- clearForm();
- resultsPage_->results_->setModel(NULL);
- delete model_;
- model_ = NULL;
- restart();
- lastPage_ = 1;
+ QString howText;
+ if (type_ == AddContact) {
+ firstPage_->errorLabel_->setVisible(false);
+ howText = QString(tr("How would you like to find the user to add?"));
+ firstPage_->howLabel_->setText(howText);
+ firstPage_->byJID_->setChecked(true);
+ handleFirstPageRadioChange();
+ } else {
+ contactVector_.clear();
+ firstMultiJIDPage_->contactList_->setList(contactVector_);
+ firstMultiJIDPage_->errorLabel_->setVisible(false);
+ if (type_ == ChatToContact) {
+ howText = QString(tr("List of participants:"));
+ } else if (type_ == InviteToChat) {
+ howText = QString(tr("Who do you want to invite to the chat?"));
+ }
+ firstMultiJIDPage_->howLabel_->setText(howText);
+ }
+ clearForm();
+ resultsPage_->results_->setModel(NULL);
+ delete model_;
+ model_ = NULL;
+ restart();
+ lastPage_ = 1;
}
void QtUserSearchWindow::setError(const QString& error) {
- if (error.isEmpty()) {
- if (type_ == AddContact) {
- firstPage_->errorLabel_->hide();
- } else {
- firstMultiJIDPage_->errorLabel_->hide();
- }
- }
- else {
- if (type_ == AddContact) {
- firstPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
- firstPage_->errorLabel_->show();
- } else {
- firstMultiJIDPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
- firstMultiJIDPage_->errorLabel_->show();
- }
- restart();
- lastPage_ = 1;
- }
+ if (error.isEmpty()) {
+ if (type_ == AddContact) {
+ firstPage_->errorLabel_->hide();
+ } else {
+ firstMultiJIDPage_->errorLabel_->hide();
+ }
+ }
+ else {
+ if (type_ == AddContact) {
+ firstPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
+ firstPage_->errorLabel_->show();
+ } else {
+ firstMultiJIDPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
+ firstMultiJIDPage_->errorLabel_->show();
+ }
+ restart();
+ lastPage_ = 1;
+ }
}
void QtUserSearchWindow::setSearchError(bool error) {
- if (error) {
- setError(tr("Error while searching"));
- }
+ if (error) {
+ setError(tr("Error while searching"));
+ }
}
void QtUserSearchWindow::setServerSupportsSearch(bool support) {
- if (!support) {
- setError(tr("This server doesn't support searching for users."));
- }
+ if (!support) {
+ setError(tr("This server doesn't support searching for users."));
+ }
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchWindow.h b/Swift/QtUI/UserSearch/QtUserSearchWindow.h
index 81d6e85..bcef0b9 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchWindow.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchWindow.h
@@ -15,92 +15,92 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchWizard.h>
namespace Swift {
- class UserSearchModel;
- class UserSearchDelegate;
- class UserSearchResult;
- class UIEventStream;
- class QtUserSearchFirstPage;
- class QtUserSearchFirstMultiJIDPage;
- class QtUserSearchFieldsPage;
- class QtUserSearchResultsPage;
- class QtUserSearchDetailsPage;
- class QtFormResultItemModel;
- class SettingsProvider;
+ class UserSearchModel;
+ class UserSearchDelegate;
+ class UserSearchResult;
+ class UIEventStream;
+ class QtUserSearchFirstPage;
+ class QtUserSearchFirstMultiJIDPage;
+ class QtUserSearchFieldsPage;
+ class QtUserSearchResultsPage;
+ class QtUserSearchDetailsPage;
+ class QtFormResultItemModel;
+ class SettingsProvider;
- class QtUserSearchWindow : public QWizard, public UserSearchWindow, private Ui::QtUserSearchWizard {
- Q_OBJECT
- public:
- QtUserSearchWindow(UIEventStream* eventStream, UserSearchWindow::Type type, const std::set<std::string>& groups, SettingsProvider* settingsProvider);
- virtual ~QtUserSearchWindow();
+ class QtUserSearchWindow : public QWizard, public UserSearchWindow, private Ui::QtUserSearchWizard {
+ Q_OBJECT
+ public:
+ QtUserSearchWindow(UIEventStream* eventStream, UserSearchWindow::Type type, const std::set<std::string>& groups, SettingsProvider* settingsProvider);
+ virtual ~QtUserSearchWindow();
- virtual void addSavedServices(const std::vector<JID>& services);
+ virtual void addSavedServices(const std::vector<JID>& services);
- virtual void clear();
- virtual void show();
- virtual void setResults(const std::vector<UserSearchResult>& results);
- virtual void setResultsForm(Form::ref results);
- virtual void setSelectedService(const JID& jid);
- virtual void setServerSupportsSearch(bool error);
- virtual void setSearchError(bool error);
- virtual void setSearchFields(boost::shared_ptr<SearchPayload> fields);
- virtual void setNameSuggestions(const std::vector<std::string>& suggestions);
- virtual void prepopulateJIDAndName(const JID& jid, const std::string& name);
- virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
- virtual void setJIDs(const std::vector<JID> &jids);
- virtual void setRoomJID(const JID &roomJID);
- virtual std::string getReason() const;
- virtual std::vector<JID> getJIDs() const;
- virtual void setCanStartImpromptuChats(bool supportsImpromptu);
- virtual void updateContacts(const std::vector<Contact::ref> &contacts);
- virtual void addContacts(const std::vector<Contact::ref>& contacts);
- virtual void setCanSupplyDescription(bool allowed);
- virtual void setWarning(const boost::optional<std::string>& message);
+ virtual void clear();
+ virtual void show();
+ virtual void setResults(const std::vector<UserSearchResult>& results);
+ virtual void setResultsForm(Form::ref results);
+ virtual void setSelectedService(const JID& jid);
+ virtual void setServerSupportsSearch(bool error);
+ virtual void setSearchError(bool error);
+ virtual void setSearchFields(boost::shared_ptr<SearchPayload> fields);
+ virtual void setNameSuggestions(const std::vector<std::string>& suggestions);
+ virtual void prepopulateJIDAndName(const JID& jid, const std::string& name);
+ virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
+ virtual void setJIDs(const std::vector<JID> &jids);
+ virtual void setRoomJID(const JID &roomJID);
+ virtual std::string getReason() const;
+ virtual std::vector<JID> getJIDs() const;
+ virtual void setCanStartImpromptuChats(bool supportsImpromptu);
+ virtual void updateContacts(const std::vector<Contact::ref> &contacts);
+ virtual void addContacts(const std::vector<Contact::ref>& contacts);
+ virtual void setCanSupplyDescription(bool allowed);
+ virtual void setWarning(const boost::optional<std::string>& message);
- protected:
- virtual int nextId() const;
+ protected:
+ virtual int nextId() const;
- private slots:
- void handleFirstPageRadioChange();
- virtual void handleCurrentChanged(int);
- virtual void handleAccepted();
- void handleContactSuggestionRequested(const QString& text);
- void addContact();
- void handleAddViaSearch();
- void handleListChanged(std::vector<Contact::ref> list);
- void handleJIDsAdded(std::vector<JID> jids);
- void handleJIDEditingDone();
+ private slots:
+ void handleFirstPageRadioChange();
+ virtual void handleCurrentChanged(int);
+ virtual void handleAccepted();
+ void handleContactSuggestionRequested(const QString& text);
+ void addContact();
+ void handleAddViaSearch();
+ void handleListChanged(std::vector<Contact::ref> list);
+ void handleJIDsAdded(std::vector<JID> jids);
+ void handleJIDEditingDone();
- private:
- void setFirstPage(QString title = "");
- void setSecondPage();
- void setThirdPage();
+ private:
+ void setFirstPage(QString title = "");
+ void setSecondPage();
+ void setThirdPage();
- private:
- void clearForm();
- void setError(const QString& error);
- JID getServerToSearch();
- void handleSearch();
- JID getContactJID() const;
- Contact::ref getContact() const;
- void addSearchedJIDToList(const Contact::ref& contact);
- void handleOnSearchedJIDSelected(const Contact::ref& contact);
+ private:
+ void clearForm();
+ void setError(const QString& error);
+ JID getServerToSearch();
+ void handleSearch();
+ JID getContactJID() const;
+ Contact::ref getContact() const;
+ void addSearchedJIDToList(const Contact::ref& contact);
+ void handleOnSearchedJIDSelected(const Contact::ref& contact);
- private:
- UIEventStream* eventStream_;
- UserSearchWindow::Type type_;
- QAbstractItemModel* model_;
- UserSearchDelegate* delegate_;
- QtUserSearchFirstPage* firstPage_;
- QtUserSearchFirstMultiJIDPage* firstMultiJIDPage_;
- QtUserSearchFieldsPage* fieldsPage_;
- QtUserSearchResultsPage* resultsPage_;
- QtUserSearchDetailsPage* detailsPage_;
- JID myServer_;
- JID roomJID_;
- int lastPage_;
- std::vector<Contact::ref> contactVector_;
- SettingsProvider* settings_;
- bool searchNext_;
- bool supportsImpromptu_;
- };
+ private:
+ UIEventStream* eventStream_;
+ UserSearchWindow::Type type_;
+ QAbstractItemModel* model_;
+ UserSearchDelegate* delegate_;
+ QtUserSearchFirstPage* firstPage_;
+ QtUserSearchFirstMultiJIDPage* firstMultiJIDPage_;
+ QtUserSearchFieldsPage* fieldsPage_;
+ QtUserSearchResultsPage* resultsPage_;
+ QtUserSearchDetailsPage* detailsPage_;
+ JID myServer_;
+ JID roomJID_;
+ int lastPage_;
+ std::vector<Contact::ref> contactVector_;
+ SettingsProvider* settings_;
+ bool searchNext_;
+ bool supportsImpromptu_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/UserSearchDelegate.cpp b/Swift/QtUI/UserSearch/UserSearchDelegate.cpp
index 1ac9eb3..8c7ca9a 100644
--- a/Swift/QtUI/UserSearch/UserSearchDelegate.cpp
+++ b/Swift/QtUI/UserSearch/UserSearchDelegate.cpp
@@ -27,44 +27,44 @@ UserSearchDelegate::~UserSearchDelegate() {
}
QSize UserSearchDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
- //UserSearchItem* item = static_cast<UserSearchItem*>(index.internalPointer());
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ //UserSearchItem* item = static_cast<UserSearchItem*>(index.internalPointer());
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
-void UserSearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- UserSearchResult* item = static_cast<UserSearchResult*>(index.internalPointer());
- painter->save();
- QRect fullRegion(option.rect);
- if (option.state & QStyle::State_Selected) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- }
- else {
- QColor nameColor = UserSearchModel::data(item, Qt::TextColorRole).value<QColor> ();
- painter->setPen(QPen(nameColor));
- }
-
- QFontMetrics nameMetrics(common_.nameFont);
- painter->setFont(common_.nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
- int nameHeight = nameMetrics.height() + common_.verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
- painter->drawText(nameRegion, Qt::AlignTop, UserSearchModel::data(item, Qt::DisplayRole).toString());
-
- painter->setFont(common_.detailFont);
- painter->setPen(QPen(QColor(160, 160, 160)));
-
- QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- painter->drawText(detailRegion, Qt::AlignTop, UserSearchModel::data(item, UserSearchModel::DetailTextRole).toString());
-
- painter->restore();
+void UserSearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
+ UserSearchResult* item = static_cast<UserSearchResult*>(index.internalPointer());
+ painter->save();
+ QRect fullRegion(option.rect);
+ if (option.state & QStyle::State_Selected) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ }
+ else {
+ QColor nameColor = UserSearchModel::data(item, Qt::TextColorRole).value<QColor> ();
+ painter->setPen(QPen(nameColor));
+ }
+
+ QFontMetrics nameMetrics(common_.nameFont);
+ painter->setFont(common_.nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+ int nameHeight = nameMetrics.height() + common_.verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+ painter->drawText(nameRegion, Qt::AlignTop, UserSearchModel::data(item, Qt::DisplayRole).toString());
+
+ painter->setFont(common_.detailFont);
+ painter->setPen(QPen(QColor(160, 160, 160)));
+
+ QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ painter->drawText(detailRegion, Qt::AlignTop, UserSearchModel::data(item, UserSearchModel::DetailTextRole).toString());
+
+ painter->restore();
}
}
diff --git a/Swift/QtUI/UserSearch/UserSearchDelegate.h b/Swift/QtUI/UserSearch/UserSearchDelegate.h
index 92fa0e8..8234689 100644
--- a/Swift/QtUI/UserSearch/UserSearchDelegate.h
+++ b/Swift/QtUI/UserSearch/UserSearchDelegate.h
@@ -13,18 +13,18 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class UserSearchDelegate : public QStyledItemDelegate {
- Q_OBJECT
-
- public:
- UserSearchDelegate(QObject* parent = 0);
- virtual ~UserSearchDelegate();
-
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const;
- private:
- DelegateCommons common_;
- };
+ class UserSearchDelegate : public QStyledItemDelegate {
+ Q_OBJECT
+
+ public:
+ UserSearchDelegate(QObject* parent = 0);
+ virtual ~UserSearchDelegate();
+
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const;
+ private:
+ DelegateCommons common_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/UserSearchModel.cpp b/Swift/QtUI/UserSearch/UserSearchModel.cpp
index ba6ede3..b6ac3cf 100644
--- a/Swift/QtUI/UserSearch/UserSearchModel.cpp
+++ b/Swift/QtUI/UserSearch/UserSearchModel.cpp
@@ -14,76 +14,76 @@ UserSearchModel::UserSearchModel() {
}
void UserSearchModel::clear() {
- emit layoutAboutToBeChanged();
- results_.clear();
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ results_.clear();
+ emit layoutChanged();
}
void UserSearchModel::setResults(const std::vector<UserSearchResult>& results) {
- clear();
- emit layoutAboutToBeChanged();
- results_ = results;
- emit layoutChanged();
+ clear();
+ emit layoutAboutToBeChanged();
+ results_ = results;
+ emit layoutChanged();
}
int UserSearchModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ return 1;
}
QVariant UserSearchModel::data(const QModelIndex& index, int role) const {
- if (!index.isValid()) return QVariant();
- UserSearchResult* result = static_cast<UserSearchResult*>(index.internalPointer());
- return data(result, role);
+ if (!index.isValid()) return QVariant();
+ UserSearchResult* result = static_cast<UserSearchResult*>(index.internalPointer());
+ return data(result, role);
}
QVariant UserSearchModel::data(UserSearchResult* item, int role) {
- switch (role) {
- case Qt::DisplayRole: return QVariant(nameLine(item));
- case DetailTextRole: return QVariant(detailLine(item));
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return QVariant(nameLine(item));
+ case DetailTextRole: return QVariant(detailLine(item));
+ default: return QVariant();
+ }
}
QString UserSearchModel::nameLine(UserSearchResult* item) {
- QString result;
- const std::map<std::string, std::string> fields = item->getFields();
- std::map<std::string, std::string>::const_iterator first = fields.find("first");
- if (first != fields.end()) {
- result += P2QSTRING((*first).second);
- }
- std::map<std::string, std::string>::const_iterator last = fields.find("last");
- if (last != fields.end()) {
- if (!result.isEmpty()) {
- result += " ";
- }
- result += P2QSTRING((*last).second);
- }
- if (result.isEmpty()) {
- result = P2QSTRING(item->getJID().toString());
- }
- return result;
+ QString result;
+ const std::map<std::string, std::string> fields = item->getFields();
+ std::map<std::string, std::string>::const_iterator first = fields.find("first");
+ if (first != fields.end()) {
+ result += P2QSTRING((*first).second);
+ }
+ std::map<std::string, std::string>::const_iterator last = fields.find("last");
+ if (last != fields.end()) {
+ if (!result.isEmpty()) {
+ result += " ";
+ }
+ result += P2QSTRING((*last).second);
+ }
+ if (result.isEmpty()) {
+ result = P2QSTRING(item->getJID().toString());
+ }
+ return result;
}
QString UserSearchModel::detailLine(UserSearchResult* item) {
- return P2QSTRING(item->getJID().toString());
+ return P2QSTRING(item->getJID().toString());
}
QModelIndex UserSearchModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
- return row < static_cast<int>(results_.size()) ? createIndex(row, column, reinterpret_cast<void*>(const_cast<UserSearchResult*>(&(results_[row])))) : QModelIndex();
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
+ return row < static_cast<int>(results_.size()) ? createIndex(row, column, reinterpret_cast<void*>(const_cast<UserSearchResult*>(&(results_[row])))) : QModelIndex();
}
QModelIndex UserSearchModel::parent(const QModelIndex& /*index*/) const {
- return QModelIndex();
+ return QModelIndex();
}
int UserSearchModel::rowCount(const QModelIndex& parentIndex) const {
- if (!parentIndex.isValid()) {
- return results_.size();
- }
- return 0;
+ if (!parentIndex.isValid()) {
+ return results_.size();
+ }
+ return 0;
}
}
diff --git a/Swift/QtUI/UserSearch/UserSearchModel.h b/Swift/QtUI/UserSearch/UserSearchModel.h
index db3ef3a..0a57b28 100644
--- a/Swift/QtUI/UserSearch/UserSearchModel.h
+++ b/Swift/QtUI/UserSearch/UserSearchModel.h
@@ -14,28 +14,28 @@
#include <Swift/Controllers/Chat/UserSearchController.h>
namespace Swift {
- class UserSearchModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- enum UserItemRoles {
- DetailTextRole = Qt::UserRole/*,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2,
- StatusShowTypeRole = Qt::UserRole + 3*/
- };
- UserSearchModel();
- void clear();
- void setResults(const std::vector<UserSearchResult>& results);
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- static QVariant data(UserSearchResult* item, int role);
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- private:
- static QString nameLine(UserSearchResult* item);
- static QString detailLine(UserSearchResult* item);
- std::vector<UserSearchResult> results_;
- };
+ class UserSearchModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ enum UserItemRoles {
+ DetailTextRole = Qt::UserRole/*,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2,
+ StatusShowTypeRole = Qt::UserRole + 3*/
+ };
+ UserSearchModel();
+ void clear();
+ void setResults(const std::vector<UserSearchResult>& results);
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ static QVariant data(UserSearchResult* item, int role);
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ private:
+ static QString nameLine(UserSearchResult* item);
+ static QString detailLine(UserSearchResult* item);
+ std::vector<UserSearchResult> results_;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/ColorWidget.cpp b/Swift/QtUI/Whiteboard/ColorWidget.cpp
index e12ade1..7669ecc 100644
--- a/Swift/QtUI/Whiteboard/ColorWidget.cpp
+++ b/Swift/QtUI/Whiteboard/ColorWidget.cpp
@@ -17,28 +17,28 @@
#include <QPainter>
namespace Swift {
- ColorWidget::ColorWidget(QWidget* parent) : QWidget(parent) {
- setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
- }
-
- QSize ColorWidget::sizeHint() const {
- return QSize(20, 20);
- }
-
- void ColorWidget::setColor(QColor color) {
- this->color = color;
- update();
- }
-
- void ColorWidget::paintEvent(QPaintEvent* /*event*/) {
- QPainter painter(this);
- painter.fillRect(0, 0, 20, 20, color);
- }
-
- void ColorWidget::mouseReleaseEvent(QMouseEvent* event) {
- if (event->button() == Qt::LeftButton) {
- emit clicked();
- }
- }
+ ColorWidget::ColorWidget(QWidget* parent) : QWidget(parent) {
+ setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
+ }
+
+ QSize ColorWidget::sizeHint() const {
+ return QSize(20, 20);
+ }
+
+ void ColorWidget::setColor(QColor color) {
+ this->color = color;
+ update();
+ }
+
+ void ColorWidget::paintEvent(QPaintEvent* /*event*/) {
+ QPainter painter(this);
+ painter.fillRect(0, 0, 20, 20, color);
+ }
+
+ void ColorWidget::mouseReleaseEvent(QMouseEvent* event) {
+ if (event->button() == Qt::LeftButton) {
+ emit clicked();
+ }
+ }
}
diff --git a/Swift/QtUI/Whiteboard/ColorWidget.h b/Swift/QtUI/Whiteboard/ColorWidget.h
index ae1af0f..18dc73f 100644
--- a/Swift/QtUI/Whiteboard/ColorWidget.h
+++ b/Swift/QtUI/Whiteboard/ColorWidget.h
@@ -9,25 +9,25 @@
#include <QWidget>
namespace Swift {
- class ColorWidget : public QWidget {
- Q_OBJECT
- public:
- ColorWidget(QWidget* parent = 0);
- QSize sizeHint() const;
+ class ColorWidget : public QWidget {
+ Q_OBJECT
+ public:
+ ColorWidget(QWidget* parent = 0);
+ QSize sizeHint() const;
- public slots:
- void setColor(QColor color);
+ public slots:
+ void setColor(QColor color);
- private:
- QColor color;
+ private:
+ QColor color;
- protected:
- void paintEvent(QPaintEvent* /*event*/);
- void mouseReleaseEvent(QMouseEvent* event);
+ protected:
+ void paintEvent(QPaintEvent* /*event*/);
+ void mouseReleaseEvent(QMouseEvent* event);
- signals:
- void clicked();
+ signals:
+ void clicked();
- };
+ };
}
diff --git a/Swift/QtUI/Whiteboard/FreehandLineItem.cpp b/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
index f4808d6..4ac93b8 100644
--- a/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
+++ b/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
@@ -13,90 +13,90 @@
#include <Swift/QtUI/Whiteboard/FreehandLineItem.h>
namespace Swift {
- FreehandLineItem::FreehandLineItem(QGraphicsItem* parent) : QGraphicsItem(parent) {
- }
+ FreehandLineItem::FreehandLineItem(QGraphicsItem* parent) : QGraphicsItem(parent) {
+ }
- QRectF FreehandLineItem::boundingRect() const
- {
- return boundRect;
- }
+ QRectF FreehandLineItem::boundingRect() const
+ {
+ return boundRect;
+ }
- void FreehandLineItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
- {
- painter->setPen(pen_);
- if (points_.size() > 0) {
- QVector<QPointF>::const_iterator it = points_.begin();
- QPointF previous = *it;
- ++it;
- for (; it != points_.end(); ++it) {
- painter->drawLine(previous, *it);
- previous = *it;
- }
- }
- }
+ void FreehandLineItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
+ {
+ painter->setPen(pen_);
+ if (points_.size() > 0) {
+ QVector<QPointF>::const_iterator it = points_.begin();
+ QPointF previous = *it;
+ ++it;
+ for (; it != points_.end(); ++it) {
+ painter->drawLine(previous, *it);
+ previous = *it;
+ }
+ }
+ }
- void FreehandLineItem::setStartPoint(QPointF point)
- {
- points_.clear();
- points_.append(point);
- QRectF rect(point, point);
- prepareGeometryChange();
- boundRect = rect;
- }
+ void FreehandLineItem::setStartPoint(QPointF point)
+ {
+ points_.clear();
+ points_.append(point);
+ QRectF rect(point, point);
+ prepareGeometryChange();
+ boundRect = rect;
+ }
- void FreehandLineItem::lineTo(QPointF point)
- {
- qreal x1, x2, y1, y2;
- x1 = points_.last().x();
- x2 = point.x();
- y1 = points_.last().y();
- y2 = point.y();
- if (x1 > x2) {
- qreal temp = x1;
- x1 = x2;
- x2 = temp;
- }
- if (y1 > y2) {
- qreal temp = y1;
- y1 = y2;
- y2 = temp;
- }
- QRectF rect(x1-1, y1-1, x2+1-x1, y2+1-y1);
+ void FreehandLineItem::lineTo(QPointF point)
+ {
+ qreal x1, x2, y1, y2;
+ x1 = points_.last().x();
+ x2 = point.x();
+ y1 = points_.last().y();
+ y2 = point.y();
+ if (x1 > x2) {
+ qreal temp = x1;
+ x1 = x2;
+ x2 = temp;
+ }
+ if (y1 > y2) {
+ qreal temp = y1;
+ y1 = y2;
+ y2 = temp;
+ }
+ QRectF rect(x1-1, y1-1, x2+1-x1, y2+1-y1);
- points_.append(point);
+ points_.append(point);
- prepareGeometryChange();
- boundRect |= rect;
- }
+ prepareGeometryChange();
+ boundRect |= rect;
+ }
- bool FreehandLineItem::collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/) const
- {
- QVector<QPointF>::const_iterator it;
- QSizeF size(1,1);
- for (it = points_.begin(); it != points_.end(); ++it) {
- if (path.intersects(QRectF(*it, size))) {
- return true;
- }
- }
- return false;
- }
+ bool FreehandLineItem::collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/) const
+ {
+ QVector<QPointF>::const_iterator it;
+ QSizeF size(1,1);
+ for (it = points_.begin(); it != points_.end(); ++it) {
+ if (path.intersects(QRectF(*it, size))) {
+ return true;
+ }
+ }
+ return false;
+ }
- void FreehandLineItem::setPen(const QPen& pen)
- {
- pen_ = pen;
- update(boundRect);
- }
+ void FreehandLineItem::setPen(const QPen& pen)
+ {
+ pen_ = pen;
+ update(boundRect);
+ }
- QPen FreehandLineItem::pen() const
- {
- return pen_;
- }
+ QPen FreehandLineItem::pen() const
+ {
+ return pen_;
+ }
- const QVector<QPointF>& FreehandLineItem::points() const {
- return points_;
- }
+ const QVector<QPointF>& FreehandLineItem::points() const {
+ return points_;
+ }
- int FreehandLineItem::type() const {
- return Type;
- }
+ int FreehandLineItem::type() const {
+ return Type;
+ }
}
diff --git a/Swift/QtUI/Whiteboard/FreehandLineItem.h b/Swift/QtUI/Whiteboard/FreehandLineItem.h
index db37460..a2dab34 100644
--- a/Swift/QtUI/Whiteboard/FreehandLineItem.h
+++ b/Swift/QtUI/Whiteboard/FreehandLineItem.h
@@ -18,23 +18,23 @@
#include <QPainter>
namespace Swift {
- class FreehandLineItem : public QGraphicsItem {
- public:
- enum {Type = UserType + 1};
- FreehandLineItem(QGraphicsItem* parent = 0);
- QRectF boundingRect() const;
- void paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/ = 0);
- void setStartPoint(QPointF point);
- void lineTo(QPointF point);
- bool collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/ = Qt::IntersectsItemShape) const;
- void setPen(const QPen& pen);
- QPen pen() const;
- const QVector<QPointF>& points() const;
- int type() const;
+ class FreehandLineItem : public QGraphicsItem {
+ public:
+ enum {Type = UserType + 1};
+ FreehandLineItem(QGraphicsItem* parent = 0);
+ QRectF boundingRect() const;
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/ = 0);
+ void setStartPoint(QPointF point);
+ void lineTo(QPointF point);
+ bool collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/ = Qt::IntersectsItemShape) const;
+ void setPen(const QPen& pen);
+ QPen pen() const;
+ const QVector<QPointF>& points() const;
+ int type() const;
- private:
- QPen pen_;
- QVector<QPointF> points_;
- QRectF boundRect;
- };
+ private:
+ QPen pen_;
+ QVector<QPointF> points_;
+ QRectF boundRect;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/GView.cpp b/Swift/QtUI/Whiteboard/GView.cpp
index 9134d58..4deaaf6 100644
--- a/Swift/QtUI/Whiteboard/GView.cpp
+++ b/Swift/QtUI/Whiteboard/GView.cpp
@@ -15,489 +15,489 @@
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
- GView::GView(QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent), zValue(0), mousePressed(false), brush(QColor(Qt::white)), defaultBrush(QColor(Qt::white)), mode(GView::Select), lastItem(NULL), selectionRect(NULL), textDialog(NULL) {
- }
-
- void GView::setLineWidth(int i) {
- pen.setWidth(i);
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- } else {
- defaultPen.setWidth(i);
- }
- }
-
- void GView::setLineColor(QColor color) {
- pen.setColor(color);
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- } else {
- defaultPen.setColor(color);
- }
- lineColorChanged(color);
- }
-
- QColor GView::getLineColor() {
- return pen.color();
- }
-
- void GView::setBrushColor(QColor color) {
- brush.setColor(color);
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- } else {
- defaultBrush.setColor(color);
- }
- brushColorChanged(color);
- }
-
- QColor GView::getBrushColor() {
- return brush.color();
- }
-
- void GView::setMode(Mode mode) {
- this->mode = mode;
- lastItem = 0;
- deselect();
- }
-
- void GView::addItem(QGraphicsItem* item, QString id, int pos) {
- itemsMap_.insert(id, item);
- if (pos > items_.size()) {
- item->setZValue(zValue++);
- scene()->addItem(item);
- items_.append(item);
- } else {
- QGraphicsItem* temp = items_.at(pos-1);
- item->setZValue(temp->zValue());
- scene()->addItem(item);
- item->stackBefore(temp);
- items_.insert(pos-1, item);
- }
- }
-
- void GView::clear() {
- scene()->clear();
- items_.clear();
- itemsMap_.clear();
- lastItem = 0;
- selectionRect = 0;
- brush = QBrush(QColor(Qt::white));
- defaultBrush = QBrush(QColor(Qt::white));
- pen = QPen();
- pen.setWidth(1);
- defaultPen = pen;
- lineWidthChanged(1);
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
-
- QGraphicsItem* GView::getItem(QString id) {
- return itemsMap_.value(id);
- }
-
- void GView::deleteItem(QString id) {
- deselect(id);
- QGraphicsItem* item = itemsMap_.value(id);
- items_.removeOne(item);
- itemsMap_.remove(id);
- scene()->removeItem(item);
- delete item;
- }
-
- QString GView::getNewID() {
- return P2QSTRING(idGenerator.generateID());
- }
-
- void GView::mouseMoveEvent(QMouseEvent* event)
- {
- if (!mousePressed) {
- return;
- }
-
- if (mode == Line) {
- QGraphicsLineItem* item = qgraphicsitem_cast<QGraphicsLineItem*>(lastItem);
- if(item != 0) {
- QLineF line = item->line();
- line.setP1(this->mapToScene(event->pos()));
- item->setLine(line);
-
- }
- }
- else if (mode == Rect) {
- QGraphicsRectItem* item = qgraphicsitem_cast<QGraphicsRectItem*>(lastItem);
- if (item != 0) {
- QPointF beginPoint = item->data(0).toPointF();
- QPointF newPoint = this->mapToScene(event->pos());
- QRectF rect = item->rect();
- if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopLeft(beginPoint);
- rect.setBottomRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopRight(beginPoint);
- rect.setBottomLeft(newPoint);
- }
- else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomLeft(beginPoint);
- rect.setTopRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomRight(beginPoint);
- rect.setTopLeft(newPoint);
- }
- item->setRect(rect);
- }
- }
- else if (mode == Circle) {
- QGraphicsEllipseItem* item = qgraphicsitem_cast<QGraphicsEllipseItem*>(lastItem);
- QPainterPath path;
- QPointF beginPoint = item->data(0).toPointF();
- QPointF newPoint = this->mapToScene(event->pos());
- QRectF rect = item->rect();
- if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopLeft(beginPoint);
- rect.setBottomRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopRight(beginPoint);
- rect.setBottomLeft(newPoint);
- }
- else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomLeft(beginPoint);
- rect.setTopRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomRight(beginPoint);
- rect.setTopLeft(newPoint);
- }
-
- item->setRect(rect);
- }
- else if (mode == HandLine) {
- FreehandLineItem* item = qgraphicsitem_cast<FreehandLineItem*>(lastItem);
- if (item != 0) {
- QPointF newPoint = this->mapToScene(event->pos());
- item->lineTo(newPoint);
- }
- }
- else if (mode == Polygon) {
- QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(lastItem);
- QPointF newPoint = this->mapToScene(event->pos());
- QPolygonF polygon = item->polygon();
- polygon.erase(polygon.end()-1);
- polygon.append(newPoint);
- item->setPolygon(polygon);
- }
- else if (mode == Select) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- if (item != 0) {
- QPainterPath path;
- QPointF beginPoint = selectionRect->data(0).toPointF();
- QPointF newPoint = this->mapToScene(event->pos());
- item->setPos(beginPoint + newPoint);
- selectionRect->setPos(beginPoint + newPoint);
- }
- }
- }
-
- void GView::mousePressEvent(QMouseEvent *event)
- {
- mousePressed = true;
- deselect();
- if (mode == Line) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsItem* item = scene()->addLine(point.x(), point.y(), point.x(), point.y(), pen);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else if (mode == Rect) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsRectItem* item = scene()->addRect(point.x(), point.y(), 0, 0, pen, brush);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(0, point);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else if (mode == Rubber) {
- QPointF point = this->mapToScene(event->pos());
- int w = pen.width();
- QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
- QList<QGraphicsItem*> list = scene()->items(rect);
- if (!list.isEmpty())
- {
- QGraphicsItem* item = scene()->items(rect).first();
- QString id = item->data(100).toString();
- int pos = items_.indexOf(item)+1;
- itemDeleted(id, pos);
- deleteItem(id);
- }
- }
- else if (mode == Circle) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsEllipseItem* item = scene()->addEllipse(point.x(), point.y(), 0, 0, pen, brush);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(0, point);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else if (mode == HandLine) {
- QPointF point = this->mapToScene(event->pos());
- FreehandLineItem* item = new FreehandLineItem;
- QString id = getNewID();
- item->setPen(pen);
- item->setStartPoint(point);
- item->setZValue(10000000);
- item->setData(100, id);
- item->setData(101, items_.size());
- scene()->addItem(item);
- lastItem = item;
- }
- else if (mode == Text) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsTextItem* item = scene()->addText("");
- QString id = getNewID();
- item->setData(100, id);
- item->setData(101, items_.size());
- item->setDefaultTextColor(pen.color());
- textDialog = new TextDialog(item, this);
- connect(textDialog, SIGNAL(accepted(QGraphicsTextItem*)), this, SLOT(handleTextItemModified(QGraphicsTextItem*)));
- textDialog->setAttribute(Qt::WA_DeleteOnClose);
- textDialog->show();
- item->setPos(point);
- lastItem = item;
- }
- else if (mode == Polygon) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsPolygonItem* item = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
- if (item == 0) {
- QPolygonF polygon;
- polygon.append(point);
- polygon.append(point);
- item = scene()->addPolygon(polygon, pen, brush);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else {
- QPolygonF polygon;
- polygon = item->polygon();
- polygon.append(point);
- item->setPolygon(polygon);
- }
- }
- else if (mode == Select) {
- QPointF point = this->mapToScene(event->pos());
- int w = pen.width();
- if (w == 0) {
- w = 1;
- }
- QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
- QList<QGraphicsItem*> list = scene()->items(rect);
- if (!list.isEmpty()) {
- QPen pen;
- pen.setColor(QColor(Qt::gray));
- pen.setStyle(Qt::DashLine);
- QGraphicsItem *item = scene()->items(rect).first();
- selectionRect = scene()->addRect(item->boundingRect(), pen);
- selectionRect->setZValue(1000000);
- selectionRect->setData(0, item->pos()-point);
- selectionRect->setPos(item->pos());
- QVariant var(QVariant::UserType);
- var.setValue(item);
- selectionRect->setData(1, var);
- setActualPenAndBrushFromItem(item);
- }
- }
- }
-
- void GView::mouseReleaseEvent(QMouseEvent* /*event*/)
- {
- mousePressed = false;
- QGraphicsPolygonItem* polygon = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
- if (polygon && polygon->polygon().size() >= 3) {
- lastItemChanged(polygon, items_.indexOf(polygon)+1, Update);
- } else if (lastItem) {
- zValue++;
- lastItem->setZValue(zValue++);
- items_.append(lastItem);
- itemsMap_.insert(lastItem->data(100).toString(), lastItem);
-
- lastItemChanged(lastItem, items_.size(), New);
- } else if (selectionRect){
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- }
- }
-
-
- void GView::handleTextItemModified(QGraphicsTextItem* item) {
- lastItemChanged(item, item->data(101).toInt(), Update);
- }
-
- void GView::moveUpSelectedItem()
- {
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- int pos = items_.indexOf(item);
- if (pos < items_.size()-1) {
- lastItemChanged(item, pos+1, MoveUp);
- move(item, pos+2);
- }
- }
- }
-
- void GView::moveDownSelectedItem()
- {
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- int pos = items_.indexOf(item);
- if (pos > 0) {
- lastItemChanged(item, pos+1, MoveDown);
- move(item, pos);
- }
- }
- }
-
- void GView::move(QGraphicsItem* item, int npos) {
- int pos = items_.indexOf(item);
- QGraphicsItem* itemAfter = NULL;
- if (npos-1 > pos) {
- if (npos == items_.size()) {
- item->setZValue(zValue++);
- } else {
- itemAfter = items_.at(npos);
- }
-
- items_.insert(npos, item);
- items_.removeAt(pos);
- } else if (npos-1 < pos) {
- itemAfter = items_.at(npos-1);
- items_.insert(npos-1, item);
- items_.removeAt(pos+1);
- }
- if (itemAfter) {
- item->setZValue(itemAfter->zValue());
- item->stackBefore(itemAfter);
- }
- }
-
- void GView::changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush) {
- QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
- if (lineItem) {
- lineItem->setPen(pen);
- }
-
- FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
- if (handLineItem) {
- handLineItem->setPen(pen);
- }
-
- QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
- if (rectItem) {
- rectItem->setPen(pen);
- rectItem->setBrush(brush);
- }
-
- QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
- if (textItem) {
- textItem->setDefaultTextColor(pen.color());
- }
-
- QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
- if (polygonItem) {
- polygonItem->setPen(pen);
- polygonItem->setBrush(brush);
- }
-
- QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
- if (ellipseItem) {
- ellipseItem->setPen(pen);
- ellipseItem->setBrush(brush);
- }
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
-
- void GView::setActualPenAndBrushFromItem(QGraphicsItem* item) {
- QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
- if (lineItem) {
- pen = lineItem->pen();
- }
-
- FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
- if (handLineItem) {
- pen = handLineItem->pen();
- }
-
- QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
- if (rectItem) {
- pen = rectItem->pen();
- brush = rectItem->brush();
- }
-
- QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
- if (textItem) {
- pen.setColor(textItem->defaultTextColor());
- }
-
- QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
- if (polygonItem) {
- pen = polygonItem->pen();
- brush = polygonItem->brush();
- }
-
- QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
- if (ellipseItem) {
- pen = ellipseItem->pen();
- brush = ellipseItem->brush();
- }
- lineWidthChanged(pen.width());
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
-
- void GView::deselect() {
- if (selectionRect != 0) {
- pen = defaultPen;
- brush = defaultBrush;
- scene()->removeItem(selectionRect);
- delete selectionRect;
- selectionRect = 0;
- lineWidthChanged(pen.width());
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
- }
-
- void GView::deselect(QString id) {
- if (selectionRect != 0) {
- QGraphicsItem* item = getItem(id);
- if (item && selectionRect->data(1).value<QGraphicsItem*>() == item) {
- pen = defaultPen;
- brush = defaultBrush;
- scene()->removeItem(selectionRect);
- delete selectionRect;
- selectionRect = 0;
- lineWidthChanged(pen.width());
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
- }
- }
+ GView::GView(QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent), zValue(0), mousePressed(false), brush(QColor(Qt::white)), defaultBrush(QColor(Qt::white)), mode(GView::Select), lastItem(NULL), selectionRect(NULL), textDialog(NULL) {
+ }
+
+ void GView::setLineWidth(int i) {
+ pen.setWidth(i);
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ } else {
+ defaultPen.setWidth(i);
+ }
+ }
+
+ void GView::setLineColor(QColor color) {
+ pen.setColor(color);
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ } else {
+ defaultPen.setColor(color);
+ }
+ lineColorChanged(color);
+ }
+
+ QColor GView::getLineColor() {
+ return pen.color();
+ }
+
+ void GView::setBrushColor(QColor color) {
+ brush.setColor(color);
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ } else {
+ defaultBrush.setColor(color);
+ }
+ brushColorChanged(color);
+ }
+
+ QColor GView::getBrushColor() {
+ return brush.color();
+ }
+
+ void GView::setMode(Mode mode) {
+ this->mode = mode;
+ lastItem = 0;
+ deselect();
+ }
+
+ void GView::addItem(QGraphicsItem* item, QString id, int pos) {
+ itemsMap_.insert(id, item);
+ if (pos > items_.size()) {
+ item->setZValue(zValue++);
+ scene()->addItem(item);
+ items_.append(item);
+ } else {
+ QGraphicsItem* temp = items_.at(pos-1);
+ item->setZValue(temp->zValue());
+ scene()->addItem(item);
+ item->stackBefore(temp);
+ items_.insert(pos-1, item);
+ }
+ }
+
+ void GView::clear() {
+ scene()->clear();
+ items_.clear();
+ itemsMap_.clear();
+ lastItem = 0;
+ selectionRect = 0;
+ brush = QBrush(QColor(Qt::white));
+ defaultBrush = QBrush(QColor(Qt::white));
+ pen = QPen();
+ pen.setWidth(1);
+ defaultPen = pen;
+ lineWidthChanged(1);
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+
+ QGraphicsItem* GView::getItem(QString id) {
+ return itemsMap_.value(id);
+ }
+
+ void GView::deleteItem(QString id) {
+ deselect(id);
+ QGraphicsItem* item = itemsMap_.value(id);
+ items_.removeOne(item);
+ itemsMap_.remove(id);
+ scene()->removeItem(item);
+ delete item;
+ }
+
+ QString GView::getNewID() {
+ return P2QSTRING(idGenerator.generateID());
+ }
+
+ void GView::mouseMoveEvent(QMouseEvent* event)
+ {
+ if (!mousePressed) {
+ return;
+ }
+
+ if (mode == Line) {
+ QGraphicsLineItem* item = qgraphicsitem_cast<QGraphicsLineItem*>(lastItem);
+ if(item != 0) {
+ QLineF line = item->line();
+ line.setP1(this->mapToScene(event->pos()));
+ item->setLine(line);
+
+ }
+ }
+ else if (mode == Rect) {
+ QGraphicsRectItem* item = qgraphicsitem_cast<QGraphicsRectItem*>(lastItem);
+ if (item != 0) {
+ QPointF beginPoint = item->data(0).toPointF();
+ QPointF newPoint = this->mapToScene(event->pos());
+ QRectF rect = item->rect();
+ if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopLeft(beginPoint);
+ rect.setBottomRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopRight(beginPoint);
+ rect.setBottomLeft(newPoint);
+ }
+ else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomLeft(beginPoint);
+ rect.setTopRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomRight(beginPoint);
+ rect.setTopLeft(newPoint);
+ }
+ item->setRect(rect);
+ }
+ }
+ else if (mode == Circle) {
+ QGraphicsEllipseItem* item = qgraphicsitem_cast<QGraphicsEllipseItem*>(lastItem);
+ QPainterPath path;
+ QPointF beginPoint = item->data(0).toPointF();
+ QPointF newPoint = this->mapToScene(event->pos());
+ QRectF rect = item->rect();
+ if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopLeft(beginPoint);
+ rect.setBottomRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopRight(beginPoint);
+ rect.setBottomLeft(newPoint);
+ }
+ else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomLeft(beginPoint);
+ rect.setTopRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomRight(beginPoint);
+ rect.setTopLeft(newPoint);
+ }
+
+ item->setRect(rect);
+ }
+ else if (mode == HandLine) {
+ FreehandLineItem* item = qgraphicsitem_cast<FreehandLineItem*>(lastItem);
+ if (item != 0) {
+ QPointF newPoint = this->mapToScene(event->pos());
+ item->lineTo(newPoint);
+ }
+ }
+ else if (mode == Polygon) {
+ QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(lastItem);
+ QPointF newPoint = this->mapToScene(event->pos());
+ QPolygonF polygon = item->polygon();
+ polygon.erase(polygon.end()-1);
+ polygon.append(newPoint);
+ item->setPolygon(polygon);
+ }
+ else if (mode == Select) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ if (item != 0) {
+ QPainterPath path;
+ QPointF beginPoint = selectionRect->data(0).toPointF();
+ QPointF newPoint = this->mapToScene(event->pos());
+ item->setPos(beginPoint + newPoint);
+ selectionRect->setPos(beginPoint + newPoint);
+ }
+ }
+ }
+
+ void GView::mousePressEvent(QMouseEvent *event)
+ {
+ mousePressed = true;
+ deselect();
+ if (mode == Line) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsItem* item = scene()->addLine(point.x(), point.y(), point.x(), point.y(), pen);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else if (mode == Rect) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsRectItem* item = scene()->addRect(point.x(), point.y(), 0, 0, pen, brush);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(0, point);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else if (mode == Rubber) {
+ QPointF point = this->mapToScene(event->pos());
+ int w = pen.width();
+ QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
+ QList<QGraphicsItem*> list = scene()->items(rect);
+ if (!list.isEmpty())
+ {
+ QGraphicsItem* item = scene()->items(rect).first();
+ QString id = item->data(100).toString();
+ int pos = items_.indexOf(item)+1;
+ itemDeleted(id, pos);
+ deleteItem(id);
+ }
+ }
+ else if (mode == Circle) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsEllipseItem* item = scene()->addEllipse(point.x(), point.y(), 0, 0, pen, brush);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(0, point);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else if (mode == HandLine) {
+ QPointF point = this->mapToScene(event->pos());
+ FreehandLineItem* item = new FreehandLineItem;
+ QString id = getNewID();
+ item->setPen(pen);
+ item->setStartPoint(point);
+ item->setZValue(10000000);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ scene()->addItem(item);
+ lastItem = item;
+ }
+ else if (mode == Text) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsTextItem* item = scene()->addText("");
+ QString id = getNewID();
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ item->setDefaultTextColor(pen.color());
+ textDialog = new TextDialog(item, this);
+ connect(textDialog, SIGNAL(accepted(QGraphicsTextItem*)), this, SLOT(handleTextItemModified(QGraphicsTextItem*)));
+ textDialog->setAttribute(Qt::WA_DeleteOnClose);
+ textDialog->show();
+ item->setPos(point);
+ lastItem = item;
+ }
+ else if (mode == Polygon) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsPolygonItem* item = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
+ if (item == 0) {
+ QPolygonF polygon;
+ polygon.append(point);
+ polygon.append(point);
+ item = scene()->addPolygon(polygon, pen, brush);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else {
+ QPolygonF polygon;
+ polygon = item->polygon();
+ polygon.append(point);
+ item->setPolygon(polygon);
+ }
+ }
+ else if (mode == Select) {
+ QPointF point = this->mapToScene(event->pos());
+ int w = pen.width();
+ if (w == 0) {
+ w = 1;
+ }
+ QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
+ QList<QGraphicsItem*> list = scene()->items(rect);
+ if (!list.isEmpty()) {
+ QPen pen;
+ pen.setColor(QColor(Qt::gray));
+ pen.setStyle(Qt::DashLine);
+ QGraphicsItem *item = scene()->items(rect).first();
+ selectionRect = scene()->addRect(item->boundingRect(), pen);
+ selectionRect->setZValue(1000000);
+ selectionRect->setData(0, item->pos()-point);
+ selectionRect->setPos(item->pos());
+ QVariant var(QVariant::UserType);
+ var.setValue(item);
+ selectionRect->setData(1, var);
+ setActualPenAndBrushFromItem(item);
+ }
+ }
+ }
+
+ void GView::mouseReleaseEvent(QMouseEvent* /*event*/)
+ {
+ mousePressed = false;
+ QGraphicsPolygonItem* polygon = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
+ if (polygon && polygon->polygon().size() >= 3) {
+ lastItemChanged(polygon, items_.indexOf(polygon)+1, Update);
+ } else if (lastItem) {
+ zValue++;
+ lastItem->setZValue(zValue++);
+ items_.append(lastItem);
+ itemsMap_.insert(lastItem->data(100).toString(), lastItem);
+
+ lastItemChanged(lastItem, items_.size(), New);
+ } else if (selectionRect){
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ }
+ }
+
+
+ void GView::handleTextItemModified(QGraphicsTextItem* item) {
+ lastItemChanged(item, item->data(101).toInt(), Update);
+ }
+
+ void GView::moveUpSelectedItem()
+ {
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ int pos = items_.indexOf(item);
+ if (pos < items_.size()-1) {
+ lastItemChanged(item, pos+1, MoveUp);
+ move(item, pos+2);
+ }
+ }
+ }
+
+ void GView::moveDownSelectedItem()
+ {
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ int pos = items_.indexOf(item);
+ if (pos > 0) {
+ lastItemChanged(item, pos+1, MoveDown);
+ move(item, pos);
+ }
+ }
+ }
+
+ void GView::move(QGraphicsItem* item, int npos) {
+ int pos = items_.indexOf(item);
+ QGraphicsItem* itemAfter = NULL;
+ if (npos-1 > pos) {
+ if (npos == items_.size()) {
+ item->setZValue(zValue++);
+ } else {
+ itemAfter = items_.at(npos);
+ }
+
+ items_.insert(npos, item);
+ items_.removeAt(pos);
+ } else if (npos-1 < pos) {
+ itemAfter = items_.at(npos-1);
+ items_.insert(npos-1, item);
+ items_.removeAt(pos+1);
+ }
+ if (itemAfter) {
+ item->setZValue(itemAfter->zValue());
+ item->stackBefore(itemAfter);
+ }
+ }
+
+ void GView::changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush) {
+ QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
+ if (lineItem) {
+ lineItem->setPen(pen);
+ }
+
+ FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
+ if (handLineItem) {
+ handLineItem->setPen(pen);
+ }
+
+ QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
+ if (rectItem) {
+ rectItem->setPen(pen);
+ rectItem->setBrush(brush);
+ }
+
+ QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
+ if (textItem) {
+ textItem->setDefaultTextColor(pen.color());
+ }
+
+ QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
+ if (polygonItem) {
+ polygonItem->setPen(pen);
+ polygonItem->setBrush(brush);
+ }
+
+ QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
+ if (ellipseItem) {
+ ellipseItem->setPen(pen);
+ ellipseItem->setBrush(brush);
+ }
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+
+ void GView::setActualPenAndBrushFromItem(QGraphicsItem* item) {
+ QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
+ if (lineItem) {
+ pen = lineItem->pen();
+ }
+
+ FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
+ if (handLineItem) {
+ pen = handLineItem->pen();
+ }
+
+ QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
+ if (rectItem) {
+ pen = rectItem->pen();
+ brush = rectItem->brush();
+ }
+
+ QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
+ if (textItem) {
+ pen.setColor(textItem->defaultTextColor());
+ }
+
+ QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
+ if (polygonItem) {
+ pen = polygonItem->pen();
+ brush = polygonItem->brush();
+ }
+
+ QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
+ if (ellipseItem) {
+ pen = ellipseItem->pen();
+ brush = ellipseItem->brush();
+ }
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+
+ void GView::deselect() {
+ if (selectionRect != 0) {
+ pen = defaultPen;
+ brush = defaultBrush;
+ scene()->removeItem(selectionRect);
+ delete selectionRect;
+ selectionRect = 0;
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+ }
+
+ void GView::deselect(QString id) {
+ if (selectionRect != 0) {
+ QGraphicsItem* item = getItem(id);
+ if (item && selectionRect->data(1).value<QGraphicsItem*>() == item) {
+ pen = defaultPen;
+ brush = defaultBrush;
+ scene()->removeItem(selectionRect);
+ delete selectionRect;
+ selectionRect = 0;
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+ }
+ }
}
diff --git a/Swift/QtUI/Whiteboard/GView.h b/Swift/QtUI/Whiteboard/GView.h
index 1cf5275..396e381 100644
--- a/Swift/QtUI/Whiteboard/GView.h
+++ b/Swift/QtUI/Whiteboard/GView.h
@@ -25,60 +25,60 @@
#include <Swift/QtUI/Whiteboard/TextDialog.h>
namespace Swift {
- class GView : public QGraphicsView {
- Q_OBJECT
- public:
- enum Mode { Rubber, Line, Rect, Circle, HandLine, Text, Polygon, Select };
- enum Type { New, Update, MoveUp, MoveDown };
- GView(QGraphicsScene* scene, QWidget* parent = 0);
- void setLineWidth(int i);
- void setLineColor(QColor color);
- QColor getLineColor();
- void setBrushColor(QColor color);
- QColor getBrushColor();
- void setMode(Mode mode);
- void mouseMoveEvent(QMouseEvent* event);
- void mousePressEvent(QMouseEvent* event);
- void mouseReleaseEvent(QMouseEvent* /*event*/);
- void addItem(QGraphicsItem* item, QString id, int pos);
- void clear();
- QGraphicsItem* getItem(QString id);
- void deleteItem(QString id);
- QString getNewID();
- void move(QGraphicsItem* item, int npos);
- void deselect(QString id);
+ class GView : public QGraphicsView {
+ Q_OBJECT
+ public:
+ enum Mode { Rubber, Line, Rect, Circle, HandLine, Text, Polygon, Select };
+ enum Type { New, Update, MoveUp, MoveDown };
+ GView(QGraphicsScene* scene, QWidget* parent = 0);
+ void setLineWidth(int i);
+ void setLineColor(QColor color);
+ QColor getLineColor();
+ void setBrushColor(QColor color);
+ QColor getBrushColor();
+ void setMode(Mode mode);
+ void mouseMoveEvent(QMouseEvent* event);
+ void mousePressEvent(QMouseEvent* event);
+ void mouseReleaseEvent(QMouseEvent* /*event*/);
+ void addItem(QGraphicsItem* item, QString id, int pos);
+ void clear();
+ QGraphicsItem* getItem(QString id);
+ void deleteItem(QString id);
+ QString getNewID();
+ void move(QGraphicsItem* item, int npos);
+ void deselect(QString id);
- signals:
- void lastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
- void itemDeleted(QString id, int pos);
- void lineWidthChanged(int i);
- void lineColorChanged(QColor color);
- void brushColorChanged(QColor color);
+ signals:
+ void lastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
+ void itemDeleted(QString id, int pos);
+ void lineWidthChanged(int i);
+ void lineColorChanged(QColor color);
+ void brushColorChanged(QColor color);
- public slots:
- void moveUpSelectedItem();
- void moveDownSelectedItem();
+ public slots:
+ void moveUpSelectedItem();
+ void moveDownSelectedItem();
- private slots:
- void handleTextItemModified(QGraphicsTextItem*);
+ private slots:
+ void handleTextItemModified(QGraphicsTextItem*);
- private:
- void changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush);
- void setActualPenAndBrushFromItem(QGraphicsItem* item);
- void deselect();
+ private:
+ void changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush);
+ void setActualPenAndBrushFromItem(QGraphicsItem* item);
+ void deselect();
- int zValue;
- bool mousePressed;
- QPen pen;
- QBrush brush;
- QPen defaultPen;
- QBrush defaultBrush;
- Mode mode;
- QGraphicsItem* lastItem;
- QGraphicsRectItem* selectionRect;
- TextDialog* textDialog;
- QMap<QString, QGraphicsItem*> itemsMap_;
- QList<QGraphicsItem*> items_;
- IDGenerator idGenerator;
- };
+ int zValue;
+ bool mousePressed;
+ QPen pen;
+ QBrush brush;
+ QPen defaultPen;
+ QBrush defaultBrush;
+ Mode mode;
+ QGraphicsItem* lastItem;
+ QGraphicsRectItem* selectionRect;
+ TextDialog* textDialog;
+ QMap<QString, QGraphicsItem*> itemsMap_;
+ QList<QGraphicsItem*> items_;
+ IDGenerator idGenerator;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
index ca887d1..26887e0 100644
--- a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
+++ b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
@@ -32,374 +32,374 @@
#include <Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h>
namespace Swift {
- QtWhiteboardWindow::QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession) : QWidget() {
+ QtWhiteboardWindow::QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession) : QWidget() {
#ifndef Q_OS_MAC
#ifdef Q_OS_WIN32
- setWindowIcon(QIcon(":/logo-icon-16-win.png"));
+ setWindowIcon(QIcon(":/logo-icon-16-win.png"));
#else
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
#endif
- layout = new QVBoxLayout(this);
- hLayout = new QHBoxLayout;
- sidebarLayout = new QVBoxLayout;
- toolboxLayout = new QGridLayout;
-
- scene = new QGraphicsScene(this);
- scene->setSceneRect(0, 0, 400, 400);
-
- graphicsView = new GView(scene, this);
- graphicsView->setMode(GView::Line);
- connect(graphicsView, SIGNAL(lastItemChanged(QGraphicsItem*, int, GView::Type)), this, SLOT(handleLastItemChanged(QGraphicsItem*, int, GView::Type)));
- connect(graphicsView, SIGNAL(itemDeleted(QString, int)), this, SLOT(handleItemDeleted(QString, int)));
-
- widthBox = new QSpinBox(this);
- connect(widthBox, SIGNAL(valueChanged(int)), this, SLOT(changeLineWidth(int)));
- connect(graphicsView, SIGNAL(lineWidthChanged(int)), widthBox, SLOT(setValue(int)));
- widthBox->setValue(1);
-
- moveUpButton = new QPushButton("Move Up", this);
- connect(moveUpButton, SIGNAL(clicked()), graphicsView, SLOT(moveUpSelectedItem()));
-
- moveDownButton = new QPushButton("Move Down", this);
- connect(moveDownButton, SIGNAL(clicked()), graphicsView, SLOT(moveDownSelectedItem()));
-
- strokeLayout = new QHBoxLayout;
- strokeColor = new ColorWidget;
- strokeLayout->addWidget(new QLabel("Stroke:"));
- strokeLayout->addWidget(strokeColor);
- connect(strokeColor, SIGNAL(clicked()), this, SLOT(showColorDialog()));
- connect(graphicsView, SIGNAL(lineColorChanged(QColor)), strokeColor, SLOT(setColor(QColor)));
-
- fillLayout = new QHBoxLayout;
- fillColor = new ColorWidget;
- fillLayout->addWidget(new QLabel("Fill:"));
- fillLayout->addWidget(fillColor);
- connect(fillColor, SIGNAL(clicked()), this, SLOT(showBrushColorDialog()));
- connect(graphicsView, SIGNAL(brushColorChanged(QColor)), fillColor, SLOT(setColor(QColor)));
-
- rubberButton = new QToolButton(this);
- rubberButton->setIcon(QIcon(":/icons/eraser.png"));
- rubberButton->setCheckable(true);
- rubberButton->setAutoExclusive(true);
- connect(rubberButton, SIGNAL(clicked()), this, SLOT(setRubberMode()));
-
- lineButton = new QToolButton(this);
- lineButton->setIcon(QIcon(":/icons/line.png"));
- lineButton->setCheckable(true);
- lineButton->setAutoExclusive(true);
- lineButton->setChecked(true);
- connect(lineButton, SIGNAL(clicked()), this, SLOT(setLineMode()));
-
- rectButton = new QToolButton(this);
- rectButton->setIcon(QIcon(":/icons/rect.png"));
- rectButton->setCheckable(true);
- rectButton->setAutoExclusive(true);
- connect(rectButton, SIGNAL(clicked()), this, SLOT(setRectMode()));
-
- circleButton = new QToolButton(this);
- circleButton->setIcon(QIcon(":/icons/circle.png"));
- circleButton->setCheckable(true);
- circleButton->setAutoExclusive(true);
- connect(circleButton, SIGNAL(clicked()), this, SLOT(setCircleMode()));
-
- handLineButton = new QToolButton(this);
- handLineButton->setIcon(QIcon(":/icons/handline.png"));
- handLineButton->setCheckable(true);
- handLineButton->setAutoExclusive(true);
- connect(handLineButton, SIGNAL(clicked()), this, SLOT(setHandLineMode()));
-
- textButton = new QToolButton(this);
- textButton->setIcon(QIcon(":/icons/text.png"));
- textButton->setCheckable(true);
- textButton->setAutoExclusive(true);
- connect(textButton, SIGNAL(clicked()), this, SLOT(setTextMode()));
-
- polygonButton = new QToolButton(this);
- polygonButton->setIcon(QIcon(":/icons/polygon.png"));
- polygonButton->setCheckable(true);
- polygonButton->setAutoExclusive(true);
- connect(polygonButton, SIGNAL(clicked()), this, SLOT(setPolygonMode()));
-
- selectButton = new QToolButton(this);
- selectButton->setIcon(QIcon(":/icons/cursor.png"));
- selectButton->setCheckable(true);
- selectButton->setAutoExclusive(true);
- connect(selectButton, SIGNAL(clicked()), this, SLOT(setSelectMode()));
-
- toolboxLayout->addWidget(rubberButton, 0, 0);
- toolboxLayout->addWidget(selectButton, 0, 1);
- toolboxLayout->addWidget(lineButton, 0, 2);
- toolboxLayout->addWidget(circleButton, 1, 0);
- toolboxLayout->addWidget(handLineButton, 1, 1);
- toolboxLayout->addWidget(rectButton, 1, 2);
- toolboxLayout->addWidget(textButton, 2, 0);
- toolboxLayout->addWidget(polygonButton, 2, 1);
-
- sidebarLayout->addLayout(toolboxLayout);
- sidebarLayout->addSpacing(30);
- sidebarLayout->addWidget(moveUpButton);
- sidebarLayout->addWidget(moveDownButton);
- sidebarLayout->addSpacing(40);
- sidebarLayout->addWidget(widthBox);
- sidebarLayout->addLayout(strokeLayout);
- sidebarLayout->addLayout(fillLayout);
- sidebarLayout->addStretch();
- hLayout->addWidget(graphicsView);
- hLayout->addLayout(sidebarLayout);
- layout->addLayout(hLayout);
- this->setLayout(layout);
-
- setSession(whiteboardSession);
- }
-
- void QtWhiteboardWindow::handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation) {
- WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
- if (insertOp) {
- WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::New);
- insertOp->getElement()->accept(visitor);
- }
-
- WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
- if (updateOp) {
- WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::Update);
- updateOp->getElement()->accept(visitor);
- if (updateOp->getPos() != updateOp->getNewPos()) {
- graphicsView->move(graphicsView->getItem(P2QSTRING(updateOp->getElement()->getID())), updateOp->getNewPos());
- }
- }
-
- WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
- if (deleteOp) {
- graphicsView->deleteItem(P2QSTRING(deleteOp->getElementID()));
- }
- }
-
- void QtWhiteboardWindow::changeLineWidth(int i)
- {
- graphicsView->setLineWidth(i);
- }
-
- void QtWhiteboardWindow::showColorDialog()
- {
- QColor color = QColorDialog::getColor(graphicsView->getLineColor(), 0, "Select pen color", QColorDialog::ShowAlphaChannel);
- if(color.isValid())
- graphicsView->setLineColor(color);
- }
-
- void QtWhiteboardWindow::showBrushColorDialog()
- {
- QColor color = QColorDialog::getColor(graphicsView->getBrushColor(), 0, "Select brush color", QColorDialog::ShowAlphaChannel);
- if(color.isValid())
- graphicsView->setBrushColor(color);
- }
-
- void QtWhiteboardWindow::setRubberMode()
- {
- graphicsView->setMode(GView::Rubber);
- }
-
- void QtWhiteboardWindow::setLineMode()
- {
- graphicsView->setMode(GView::Line);
- }
-
- void QtWhiteboardWindow::setRectMode()
- {
- graphicsView->setMode(GView::Rect);
- }
-
- void QtWhiteboardWindow::setCircleMode()
- {
- graphicsView->setMode(GView::Circle);
- }
-
- void QtWhiteboardWindow::setHandLineMode()
- {
- graphicsView->setMode(GView::HandLine);
- }
-
- void QtWhiteboardWindow::setTextMode()
- {
- graphicsView->setMode(GView::Text);
- }
-
- void QtWhiteboardWindow::setPolygonMode()
- {
- graphicsView->setMode(GView::Polygon);
- }
-
- void QtWhiteboardWindow::setSelectMode()
- {
- graphicsView->setMode(GView::Select);
- }
-
- void QtWhiteboardWindow::show()
- {
- QWidget::show();
- }
-
- void QtWhiteboardWindow::setSession(WhiteboardSession::ref session) {
- graphicsView->clear();
- whiteboardSession_ = session;
- whiteboardSession_->onOperationReceived.connect(boost::bind(&QtWhiteboardWindow::handleWhiteboardOperationReceive, this, _1));
- whiteboardSession_->onRequestAccepted.connect(boost::bind(&QWidget::show, this));
- whiteboardSession_->onSessionTerminated.connect(boost::bind(&QtWhiteboardWindow::handleSessionTerminate, this));
- }
-
- void QtWhiteboardWindow::activateWindow() {
- QWidget::activateWindow();
- }
-
- void QtWhiteboardWindow::setName(const std::string& name) {
- setWindowTitle(P2QSTRING(name));
- }
-
- void QtWhiteboardWindow::handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type) {
- WhiteboardElement::ref el;
- QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
- if (lineItem != 0) {
- QLine line = lineItem->line().toLine();
- QColor color = lineItem->pen().color();
- WhiteboardLineElement::ref element = boost::make_shared<WhiteboardLineElement>(line.x1()+lineItem->pos().x(), line.y1()+lineItem->pos().y(), line.x2()+lineItem->pos().x(), line.y2()+lineItem->pos().y());
- element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
- element->setPenWidth(lineItem->pen().width());
-
- element->setID(lineItem->data(100).toString().toStdString());
- el = element;
- }
-
- FreehandLineItem* freehandLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
- if (freehandLineItem != 0) {
- WhiteboardFreehandPathElement::ref element = boost::make_shared<WhiteboardFreehandPathElement>();
- QColor color = freehandLineItem->pen().color();
- std::vector<std::pair<int, int> > points;
- QVector<QPointF>::const_iterator it = freehandLineItem->points().constBegin();
- for ( ; it != freehandLineItem->points().constEnd(); ++it) {
- points.push_back(std::pair<int, int>(
- boost::numeric_cast<int>(it->x()+item->pos().x()),
- boost::numeric_cast<int>(it->y()+item->pos().y())));
- }
-
- element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
- element->setPenWidth(freehandLineItem->pen().width());
- element->setPoints(points);
-
- element->setID(freehandLineItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
- if (rectItem != 0) {
- QRectF rect = rectItem->rect();
- WhiteboardRectElement::ref element = boost::make_shared<WhiteboardRectElement>(rect.x()+item->pos().x(), rect.y()+item->pos().y(), rect.width(), rect.height());
- QColor penColor = rectItem->pen().color();
- QColor brushColor = rectItem->brush().color();
-
- element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
- element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
- element->setPenWidth(rectItem->pen().width());
-
- element->setID(rectItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
- if (textItem != 0) {
- QPointF point = textItem->pos();
- WhiteboardTextElement::ref element = boost::make_shared<WhiteboardTextElement>(point.x(), point.y());
- element->setText(textItem->toPlainText().toStdString());
- element->setSize(textItem->font().pointSize());
- QColor color = textItem->defaultTextColor();
- element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
-
- element->setID(textItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
- if (polygonItem) {
- WhiteboardPolygonElement::ref element = boost::make_shared<WhiteboardPolygonElement>();
- QPolygonF polygon = polygonItem->polygon();
- std::vector<std::pair<int, int> > points;
- QVector<QPointF>::const_iterator it = polygon.begin();
- for (; it != polygon.end(); ++it) {
- points.push_back(std::pair<int, int>(
- boost::numeric_cast<int>(it->x()+item->pos().x()),
- boost::numeric_cast<int>(it->y()+item->pos().y())));
- }
-
- element->setPoints(points);
-
- QColor penColor = polygonItem->pen().color();
- QColor brushColor = polygonItem->brush().color();
- element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
- element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
- element->setPenWidth(polygonItem->pen().width());
-
- element->setID(polygonItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
- if (ellipseItem) {
- QRectF rect = ellipseItem->rect();
- int cx = boost::numeric_cast<int>(rect.x()+rect.width()/2 + item->pos().x());
- int cy = boost::numeric_cast<int>(rect.y()+rect.height()/2 + item->pos().y());
- int rx = boost::numeric_cast<int>(rect.width()/2);
- int ry = boost::numeric_cast<int>(rect.height()/2);
- WhiteboardEllipseElement::ref element = boost::make_shared<WhiteboardEllipseElement>(cx, cy, rx, ry);
-
- QColor penColor = ellipseItem->pen().color();
- QColor brushColor = ellipseItem->brush().color();
- element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
- element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
- element->setPenWidth(ellipseItem->pen().width());
-
- element->setID(ellipseItem->data(100).toString().toStdString());
- el = element;
- }
-
- if (type == GView::New) {
- WhiteboardInsertOperation::ref insertOp = boost::make_shared<WhiteboardInsertOperation>();
- insertOp->setPos(pos);
- insertOp->setElement(el);
- whiteboardSession_->sendOperation(insertOp);
- } else {
- WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>();
- updateOp->setPos(pos);
- if (type == GView::Update) {
- updateOp->setNewPos(pos);
- } else if (type == GView::MoveUp) {
- updateOp->setNewPos(pos+1);
- } else if (type == GView::MoveDown) {
- updateOp->setNewPos(pos-1);
- }
- updateOp->setElement(el);
- whiteboardSession_->sendOperation(updateOp);
- }
- }
-
- void QtWhiteboardWindow::handleItemDeleted(QString id, int pos) {
- WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
- deleteOp->setElementID(Q2PSTRING(id));
- deleteOp->setPos(pos);
- whiteboardSession_->sendOperation(deleteOp);
- }
-
- void QtWhiteboardWindow::handleSessionTerminate() {
- hide();
- }
-
- void QtWhiteboardWindow::closeEvent(QCloseEvent* event) {
- QMessageBox box(this);
- box.setText(tr("Closing window is equivalent closing the session. Are you sure you want to do this?"));
- box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- box.setIcon(QMessageBox::Question);
- if (box.exec() == QMessageBox::Yes) {
- whiteboardSession_->cancel();
- } else {
- event->ignore();
- }
- }
+ layout = new QVBoxLayout(this);
+ hLayout = new QHBoxLayout;
+ sidebarLayout = new QVBoxLayout;
+ toolboxLayout = new QGridLayout;
+
+ scene = new QGraphicsScene(this);
+ scene->setSceneRect(0, 0, 400, 400);
+
+ graphicsView = new GView(scene, this);
+ graphicsView->setMode(GView::Line);
+ connect(graphicsView, SIGNAL(lastItemChanged(QGraphicsItem*, int, GView::Type)), this, SLOT(handleLastItemChanged(QGraphicsItem*, int, GView::Type)));
+ connect(graphicsView, SIGNAL(itemDeleted(QString, int)), this, SLOT(handleItemDeleted(QString, int)));
+
+ widthBox = new QSpinBox(this);
+ connect(widthBox, SIGNAL(valueChanged(int)), this, SLOT(changeLineWidth(int)));
+ connect(graphicsView, SIGNAL(lineWidthChanged(int)), widthBox, SLOT(setValue(int)));
+ widthBox->setValue(1);
+
+ moveUpButton = new QPushButton("Move Up", this);
+ connect(moveUpButton, SIGNAL(clicked()), graphicsView, SLOT(moveUpSelectedItem()));
+
+ moveDownButton = new QPushButton("Move Down", this);
+ connect(moveDownButton, SIGNAL(clicked()), graphicsView, SLOT(moveDownSelectedItem()));
+
+ strokeLayout = new QHBoxLayout;
+ strokeColor = new ColorWidget;
+ strokeLayout->addWidget(new QLabel("Stroke:"));
+ strokeLayout->addWidget(strokeColor);
+ connect(strokeColor, SIGNAL(clicked()), this, SLOT(showColorDialog()));
+ connect(graphicsView, SIGNAL(lineColorChanged(QColor)), strokeColor, SLOT(setColor(QColor)));
+
+ fillLayout = new QHBoxLayout;
+ fillColor = new ColorWidget;
+ fillLayout->addWidget(new QLabel("Fill:"));
+ fillLayout->addWidget(fillColor);
+ connect(fillColor, SIGNAL(clicked()), this, SLOT(showBrushColorDialog()));
+ connect(graphicsView, SIGNAL(brushColorChanged(QColor)), fillColor, SLOT(setColor(QColor)));
+
+ rubberButton = new QToolButton(this);
+ rubberButton->setIcon(QIcon(":/icons/eraser.png"));
+ rubberButton->setCheckable(true);
+ rubberButton->setAutoExclusive(true);
+ connect(rubberButton, SIGNAL(clicked()), this, SLOT(setRubberMode()));
+
+ lineButton = new QToolButton(this);
+ lineButton->setIcon(QIcon(":/icons/line.png"));
+ lineButton->setCheckable(true);
+ lineButton->setAutoExclusive(true);
+ lineButton->setChecked(true);
+ connect(lineButton, SIGNAL(clicked()), this, SLOT(setLineMode()));
+
+ rectButton = new QToolButton(this);
+ rectButton->setIcon(QIcon(":/icons/rect.png"));
+ rectButton->setCheckable(true);
+ rectButton->setAutoExclusive(true);
+ connect(rectButton, SIGNAL(clicked()), this, SLOT(setRectMode()));
+
+ circleButton = new QToolButton(this);
+ circleButton->setIcon(QIcon(":/icons/circle.png"));
+ circleButton->setCheckable(true);
+ circleButton->setAutoExclusive(true);
+ connect(circleButton, SIGNAL(clicked()), this, SLOT(setCircleMode()));
+
+ handLineButton = new QToolButton(this);
+ handLineButton->setIcon(QIcon(":/icons/handline.png"));
+ handLineButton->setCheckable(true);
+ handLineButton->setAutoExclusive(true);
+ connect(handLineButton, SIGNAL(clicked()), this, SLOT(setHandLineMode()));
+
+ textButton = new QToolButton(this);
+ textButton->setIcon(QIcon(":/icons/text.png"));
+ textButton->setCheckable(true);
+ textButton->setAutoExclusive(true);
+ connect(textButton, SIGNAL(clicked()), this, SLOT(setTextMode()));
+
+ polygonButton = new QToolButton(this);
+ polygonButton->setIcon(QIcon(":/icons/polygon.png"));
+ polygonButton->setCheckable(true);
+ polygonButton->setAutoExclusive(true);
+ connect(polygonButton, SIGNAL(clicked()), this, SLOT(setPolygonMode()));
+
+ selectButton = new QToolButton(this);
+ selectButton->setIcon(QIcon(":/icons/cursor.png"));
+ selectButton->setCheckable(true);
+ selectButton->setAutoExclusive(true);
+ connect(selectButton, SIGNAL(clicked()), this, SLOT(setSelectMode()));
+
+ toolboxLayout->addWidget(rubberButton, 0, 0);
+ toolboxLayout->addWidget(selectButton, 0, 1);
+ toolboxLayout->addWidget(lineButton, 0, 2);
+ toolboxLayout->addWidget(circleButton, 1, 0);
+ toolboxLayout->addWidget(handLineButton, 1, 1);
+ toolboxLayout->addWidget(rectButton, 1, 2);
+ toolboxLayout->addWidget(textButton, 2, 0);
+ toolboxLayout->addWidget(polygonButton, 2, 1);
+
+ sidebarLayout->addLayout(toolboxLayout);
+ sidebarLayout->addSpacing(30);
+ sidebarLayout->addWidget(moveUpButton);
+ sidebarLayout->addWidget(moveDownButton);
+ sidebarLayout->addSpacing(40);
+ sidebarLayout->addWidget(widthBox);
+ sidebarLayout->addLayout(strokeLayout);
+ sidebarLayout->addLayout(fillLayout);
+ sidebarLayout->addStretch();
+ hLayout->addWidget(graphicsView);
+ hLayout->addLayout(sidebarLayout);
+ layout->addLayout(hLayout);
+ this->setLayout(layout);
+
+ setSession(whiteboardSession);
+ }
+
+ void QtWhiteboardWindow::handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation) {
+ WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::New);
+ insertOp->getElement()->accept(visitor);
+ }
+
+ WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::Update);
+ updateOp->getElement()->accept(visitor);
+ if (updateOp->getPos() != updateOp->getNewPos()) {
+ graphicsView->move(graphicsView->getItem(P2QSTRING(updateOp->getElement()->getID())), updateOp->getNewPos());
+ }
+ }
+
+ WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
+ if (deleteOp) {
+ graphicsView->deleteItem(P2QSTRING(deleteOp->getElementID()));
+ }
+ }
+
+ void QtWhiteboardWindow::changeLineWidth(int i)
+ {
+ graphicsView->setLineWidth(i);
+ }
+
+ void QtWhiteboardWindow::showColorDialog()
+ {
+ QColor color = QColorDialog::getColor(graphicsView->getLineColor(), 0, "Select pen color", QColorDialog::ShowAlphaChannel);
+ if(color.isValid())
+ graphicsView->setLineColor(color);
+ }
+
+ void QtWhiteboardWindow::showBrushColorDialog()
+ {
+ QColor color = QColorDialog::getColor(graphicsView->getBrushColor(), 0, "Select brush color", QColorDialog::ShowAlphaChannel);
+ if(color.isValid())
+ graphicsView->setBrushColor(color);
+ }
+
+ void QtWhiteboardWindow::setRubberMode()
+ {
+ graphicsView->setMode(GView::Rubber);
+ }
+
+ void QtWhiteboardWindow::setLineMode()
+ {
+ graphicsView->setMode(GView::Line);
+ }
+
+ void QtWhiteboardWindow::setRectMode()
+ {
+ graphicsView->setMode(GView::Rect);
+ }
+
+ void QtWhiteboardWindow::setCircleMode()
+ {
+ graphicsView->setMode(GView::Circle);
+ }
+
+ void QtWhiteboardWindow::setHandLineMode()
+ {
+ graphicsView->setMode(GView::HandLine);
+ }
+
+ void QtWhiteboardWindow::setTextMode()
+ {
+ graphicsView->setMode(GView::Text);
+ }
+
+ void QtWhiteboardWindow::setPolygonMode()
+ {
+ graphicsView->setMode(GView::Polygon);
+ }
+
+ void QtWhiteboardWindow::setSelectMode()
+ {
+ graphicsView->setMode(GView::Select);
+ }
+
+ void QtWhiteboardWindow::show()
+ {
+ QWidget::show();
+ }
+
+ void QtWhiteboardWindow::setSession(WhiteboardSession::ref session) {
+ graphicsView->clear();
+ whiteboardSession_ = session;
+ whiteboardSession_->onOperationReceived.connect(boost::bind(&QtWhiteboardWindow::handleWhiteboardOperationReceive, this, _1));
+ whiteboardSession_->onRequestAccepted.connect(boost::bind(&QWidget::show, this));
+ whiteboardSession_->onSessionTerminated.connect(boost::bind(&QtWhiteboardWindow::handleSessionTerminate, this));
+ }
+
+ void QtWhiteboardWindow::activateWindow() {
+ QWidget::activateWindow();
+ }
+
+ void QtWhiteboardWindow::setName(const std::string& name) {
+ setWindowTitle(P2QSTRING(name));
+ }
+
+ void QtWhiteboardWindow::handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type) {
+ WhiteboardElement::ref el;
+ QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
+ if (lineItem != 0) {
+ QLine line = lineItem->line().toLine();
+ QColor color = lineItem->pen().color();
+ WhiteboardLineElement::ref element = boost::make_shared<WhiteboardLineElement>(line.x1()+lineItem->pos().x(), line.y1()+lineItem->pos().y(), line.x2()+lineItem->pos().x(), line.y2()+lineItem->pos().y());
+ element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
+ element->setPenWidth(lineItem->pen().width());
+
+ element->setID(lineItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ FreehandLineItem* freehandLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
+ if (freehandLineItem != 0) {
+ WhiteboardFreehandPathElement::ref element = boost::make_shared<WhiteboardFreehandPathElement>();
+ QColor color = freehandLineItem->pen().color();
+ std::vector<std::pair<int, int> > points;
+ QVector<QPointF>::const_iterator it = freehandLineItem->points().constBegin();
+ for ( ; it != freehandLineItem->points().constEnd(); ++it) {
+ points.push_back(std::pair<int, int>(
+ boost::numeric_cast<int>(it->x()+item->pos().x()),
+ boost::numeric_cast<int>(it->y()+item->pos().y())));
+ }
+
+ element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
+ element->setPenWidth(freehandLineItem->pen().width());
+ element->setPoints(points);
+
+ element->setID(freehandLineItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
+ if (rectItem != 0) {
+ QRectF rect = rectItem->rect();
+ WhiteboardRectElement::ref element = boost::make_shared<WhiteboardRectElement>(rect.x()+item->pos().x(), rect.y()+item->pos().y(), rect.width(), rect.height());
+ QColor penColor = rectItem->pen().color();
+ QColor brushColor = rectItem->brush().color();
+
+ element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
+ element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
+ element->setPenWidth(rectItem->pen().width());
+
+ element->setID(rectItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
+ if (textItem != 0) {
+ QPointF point = textItem->pos();
+ WhiteboardTextElement::ref element = boost::make_shared<WhiteboardTextElement>(point.x(), point.y());
+ element->setText(textItem->toPlainText().toStdString());
+ element->setSize(textItem->font().pointSize());
+ QColor color = textItem->defaultTextColor();
+ element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
+
+ element->setID(textItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
+ if (polygonItem) {
+ WhiteboardPolygonElement::ref element = boost::make_shared<WhiteboardPolygonElement>();
+ QPolygonF polygon = polygonItem->polygon();
+ std::vector<std::pair<int, int> > points;
+ QVector<QPointF>::const_iterator it = polygon.begin();
+ for (; it != polygon.end(); ++it) {
+ points.push_back(std::pair<int, int>(
+ boost::numeric_cast<int>(it->x()+item->pos().x()),
+ boost::numeric_cast<int>(it->y()+item->pos().y())));
+ }
+
+ element->setPoints(points);
+
+ QColor penColor = polygonItem->pen().color();
+ QColor brushColor = polygonItem->brush().color();
+ element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
+ element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
+ element->setPenWidth(polygonItem->pen().width());
+
+ element->setID(polygonItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
+ if (ellipseItem) {
+ QRectF rect = ellipseItem->rect();
+ int cx = boost::numeric_cast<int>(rect.x()+rect.width()/2 + item->pos().x());
+ int cy = boost::numeric_cast<int>(rect.y()+rect.height()/2 + item->pos().y());
+ int rx = boost::numeric_cast<int>(rect.width()/2);
+ int ry = boost::numeric_cast<int>(rect.height()/2);
+ WhiteboardEllipseElement::ref element = boost::make_shared<WhiteboardEllipseElement>(cx, cy, rx, ry);
+
+ QColor penColor = ellipseItem->pen().color();
+ QColor brushColor = ellipseItem->brush().color();
+ element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
+ element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
+ element->setPenWidth(ellipseItem->pen().width());
+
+ element->setID(ellipseItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ if (type == GView::New) {
+ WhiteboardInsertOperation::ref insertOp = boost::make_shared<WhiteboardInsertOperation>();
+ insertOp->setPos(pos);
+ insertOp->setElement(el);
+ whiteboardSession_->sendOperation(insertOp);
+ } else {
+ WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>();
+ updateOp->setPos(pos);
+ if (type == GView::Update) {
+ updateOp->setNewPos(pos);
+ } else if (type == GView::MoveUp) {
+ updateOp->setNewPos(pos+1);
+ } else if (type == GView::MoveDown) {
+ updateOp->setNewPos(pos-1);
+ }
+ updateOp->setElement(el);
+ whiteboardSession_->sendOperation(updateOp);
+ }
+ }
+
+ void QtWhiteboardWindow::handleItemDeleted(QString id, int pos) {
+ WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
+ deleteOp->setElementID(Q2PSTRING(id));
+ deleteOp->setPos(pos);
+ whiteboardSession_->sendOperation(deleteOp);
+ }
+
+ void QtWhiteboardWindow::handleSessionTerminate() {
+ hide();
+ }
+
+ void QtWhiteboardWindow::closeEvent(QCloseEvent* event) {
+ QMessageBox box(this);
+ box.setText(tr("Closing window is equivalent closing the session. Are you sure you want to do this?"));
+ box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ box.setIcon(QMessageBox::Question);
+ if (box.exec() == QMessageBox::Yes) {
+ whiteboardSession_->cancel();
+ } else {
+ event->ignore();
+ }
+ }
}
diff --git a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
index 862ae66..3b3f74e 100644
--- a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
+++ b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
@@ -35,61 +35,61 @@
#include <Swift/QtUI/Whiteboard/GView.h>
namespace Swift {
- class QtWhiteboardWindow : public QWidget, public WhiteboardWindow
- {
- Q_OBJECT
- public:
- QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession);
- void show();
- void setSession(WhiteboardSession::ref session);
- void activateWindow();
- void setName(const std::string& name);
+ class QtWhiteboardWindow : public QWidget, public WhiteboardWindow
+ {
+ Q_OBJECT
+ public:
+ QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession);
+ void show();
+ void setSession(WhiteboardSession::ref session);
+ void activateWindow();
+ void setName(const std::string& name);
- private slots:
- void changeLineWidth(int i);
- void showColorDialog();
- void showBrushColorDialog();
- void setRubberMode();
- void setLineMode();
- void setRectMode();
- void setCircleMode();
- void setHandLineMode();
- void setTextMode();
- void setPolygonMode();
- void setSelectMode();
- void handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
- void handleItemDeleted(QString id, int pos);
+ private slots:
+ void changeLineWidth(int i);
+ void showColorDialog();
+ void showBrushColorDialog();
+ void setRubberMode();
+ void setLineMode();
+ void setRectMode();
+ void setCircleMode();
+ void setHandLineMode();
+ void setTextMode();
+ void setPolygonMode();
+ void setSelectMode();
+ void handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
+ void handleItemDeleted(QString id, int pos);
- private:
- void handleSessionTerminate();
- void handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation);
- void closeEvent(QCloseEvent* event);
+ private:
+ void handleSessionTerminate();
+ void handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation);
+ void closeEvent(QCloseEvent* event);
- private:
- QGraphicsScene* scene;
- GView* graphicsView;
- QVBoxLayout* layout;
- QVBoxLayout* sidebarLayout;
- QHBoxLayout* hLayout;
- QGridLayout* toolboxLayout;
- QHBoxLayout* strokeLayout;
- QHBoxLayout* fillLayout;
- ColorWidget* strokeColor;
- ColorWidget* fillColor;
- QWidget* widget;
- QPushButton* moveUpButton;
- QPushButton* moveDownButton;
- QSpinBox* widthBox;
- QToolButton* rubberButton;
- QToolButton* lineButton;
- QToolButton* rectButton;
- QToolButton* circleButton;
- QToolButton* handLineButton;
- QToolButton* textButton;
- QToolButton* polygonButton;
- QToolButton* selectButton;
+ private:
+ QGraphicsScene* scene;
+ GView* graphicsView;
+ QVBoxLayout* layout;
+ QVBoxLayout* sidebarLayout;
+ QHBoxLayout* hLayout;
+ QGridLayout* toolboxLayout;
+ QHBoxLayout* strokeLayout;
+ QHBoxLayout* fillLayout;
+ ColorWidget* strokeColor;
+ ColorWidget* fillColor;
+ QWidget* widget;
+ QPushButton* moveUpButton;
+ QPushButton* moveDownButton;
+ QSpinBox* widthBox;
+ QToolButton* rubberButton;
+ QToolButton* lineButton;
+ QToolButton* rectButton;
+ QToolButton* circleButton;
+ QToolButton* handLineButton;
+ QToolButton* textButton;
+ QToolButton* polygonButton;
+ QToolButton* selectButton;
- std::string lastOpID;
- WhiteboardSession::ref whiteboardSession_;
- };
+ std::string lastOpID;
+ WhiteboardSession::ref whiteboardSession_;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/TextDialog.cpp b/Swift/QtUI/Whiteboard/TextDialog.cpp
index 13d83d5..c15e7b4 100644
--- a/Swift/QtUI/Whiteboard/TextDialog.cpp
+++ b/Swift/QtUI/Whiteboard/TextDialog.cpp
@@ -13,46 +13,46 @@
#include <Swift/QtUI/Whiteboard/TextDialog.h>
namespace Swift {
- TextDialog::TextDialog(QGraphicsTextItem* item, QWidget* parent) : QDialog(parent)
- {
- this->item = item;
-
- layout = new QVBoxLayout(this);
- hLayout = new QHBoxLayout;
-
- editor = new QLineEdit(this);
- connect(editor, SIGNAL(textChanged(const QString&)), this, SLOT(changeItemText(const QString&)));
-
- fontSizeBox = new QSpinBox(this);
- fontSizeBox->setMinimum(1);
- connect(fontSizeBox, SIGNAL(valueChanged(int)), this, SLOT(changeItemFontSize(int)));
- fontSizeBox->setValue(13);
-
-
- buttonBox = new QDialogButtonBox(this);
- buttonBox->setStandardButtons(QDialogButtonBox::Ok);
- connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
-
- hLayout->addWidget(editor);
- hLayout->addWidget(fontSizeBox);
- layout->addLayout(hLayout);
- layout->addWidget(buttonBox);
- }
-
- void TextDialog::changeItemText(const QString &text)
- {
- item->setPlainText(text);
- }
-
- void TextDialog::changeItemFontSize(int i)
- {
- QFont font = item->font();
- font.setPointSize(i);
- item->setFont(font);
- }
-
- void TextDialog::accept() {
- emit accepted(item);
- done(QDialog::Accepted);
- }
+ TextDialog::TextDialog(QGraphicsTextItem* item, QWidget* parent) : QDialog(parent)
+ {
+ this->item = item;
+
+ layout = new QVBoxLayout(this);
+ hLayout = new QHBoxLayout;
+
+ editor = new QLineEdit(this);
+ connect(editor, SIGNAL(textChanged(const QString&)), this, SLOT(changeItemText(const QString&)));
+
+ fontSizeBox = new QSpinBox(this);
+ fontSizeBox->setMinimum(1);
+ connect(fontSizeBox, SIGNAL(valueChanged(int)), this, SLOT(changeItemFontSize(int)));
+ fontSizeBox->setValue(13);
+
+
+ buttonBox = new QDialogButtonBox(this);
+ buttonBox->setStandardButtons(QDialogButtonBox::Ok);
+ connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
+
+ hLayout->addWidget(editor);
+ hLayout->addWidget(fontSizeBox);
+ layout->addLayout(hLayout);
+ layout->addWidget(buttonBox);
+ }
+
+ void TextDialog::changeItemText(const QString &text)
+ {
+ item->setPlainText(text);
+ }
+
+ void TextDialog::changeItemFontSize(int i)
+ {
+ QFont font = item->font();
+ font.setPointSize(i);
+ item->setFont(font);
+ }
+
+ void TextDialog::accept() {
+ emit accepted(item);
+ done(QDialog::Accepted);
+ }
}
diff --git a/Swift/QtUI/Whiteboard/TextDialog.h b/Swift/QtUI/Whiteboard/TextDialog.h
index 911bd37..31bd096 100644
--- a/Swift/QtUI/Whiteboard/TextDialog.h
+++ b/Swift/QtUI/Whiteboard/TextDialog.h
@@ -23,27 +23,27 @@
#include <QVBoxLayout>
namespace Swift {
- class TextDialog : public QDialog
- {
- Q_OBJECT
- public:
- TextDialog(QGraphicsTextItem* item, QWidget* parent = 0);
-
- private:
- QGraphicsTextItem* item;
- QLineEdit* editor;
- QDialogButtonBox* buttonBox;
- QVBoxLayout* layout;
- QHBoxLayout* hLayout;
- QSpinBox* fontSizeBox;
-
- signals:
- void accepted(QGraphicsTextItem* item);
-
- private slots:
- void accept();
- void changeItemText(const QString &text);
- void changeItemFontSize(int i);
- };
+ class TextDialog : public QDialog
+ {
+ Q_OBJECT
+ public:
+ TextDialog(QGraphicsTextItem* item, QWidget* parent = 0);
+
+ private:
+ QGraphicsTextItem* item;
+ QLineEdit* editor;
+ QDialogButtonBox* buttonBox;
+ QVBoxLayout* layout;
+ QHBoxLayout* hLayout;
+ QSpinBox* fontSizeBox;
+
+ signals:
+ void accepted(QGraphicsTextItem* item);
+
+ private slots:
+ void accept();
+ void changeItemText(const QString &text);
+ void changeItemFontSize(int i);
+ };
}
diff --git a/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h b/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
index 4d37704..719725c 100644
--- a/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
+++ b/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
@@ -23,172 +23,172 @@
#include <Swift/QtUI/Whiteboard/GView.h>
namespace Swift {
- class WhiteboardElementDrawingVisitor : public WhiteboardElementVisitor {
- public:
- WhiteboardElementDrawingVisitor(GView* graphicsView, int pos, GView::Type type) : graphicsView_(graphicsView), pos_(pos), type_(type) {}
-
- void visit(WhiteboardLineElement& element) {
- QGraphicsLineItem *item;
- if (type_ == GView::New) {
- item = new QGraphicsLineItem(element.x1(), element.y1(), element.x2(), element.y2());
- graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- QLineF line(element.x1(), element.y1(), element.x2(), element.y2());
- item->setLine(line);
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
- if (item) {
- QPen pen;
- WhiteboardColor color = element.getColor();
- pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
- pen.setWidth(element.getPenWidth());
- item->setPen(pen);
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- }
- }
-
- void visit(WhiteboardFreehandPathElement& element) {
- FreehandLineItem *item;
- if (type_ == GView::New) {
- item = new FreehandLineItem;
- } else {
- item = qgraphicsitem_cast<FreehandLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
-
- if (item) {
- QPen pen;
- WhiteboardColor color = element.getColor();
- pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
- pen.setWidth(element.getPenWidth());
- item->setPen(pen);
-
- std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
- item->setStartPoint(QPointF(it->first, it->second));
- for (++it; it != element.getPoints().end(); ++it) {
- item->lineTo(QPointF(it->first, it->second));
- }
-
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- }
- if (type_ == GView::New) {
- graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
- }
- }
-
- void visit(WhiteboardRectElement& element) {
- QGraphicsRectItem* item;
- if (type_ == GView::New) {
- item = new QGraphicsRectItem(element.getX(), element.getY(), element.getWidth(), element.getHeight());
- graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsRectItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- QRectF rect(element.getX(), element.getY(), element.getWidth(), element.getHeight());
- item->setRect(rect);
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
-
- if (item) {
- QPen pen;
- QBrush brush(Qt::SolidPattern);
- WhiteboardColor penColor = element.getPenColor();
- WhiteboardColor brushColor = element.getBrushColor();
- pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
- pen.setWidth(element.getPenWidth());
- brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
- item->setPen(pen);
- item->setBrush(brush);
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- }
- }
-
- void visit(WhiteboardPolygonElement& element) {
- QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- if (item == 0 && type_ == GView::New) {
- item = new QGraphicsPolygonItem();
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- graphicsView_->addItem(item, id, pos_);
- }
- graphicsView_->deselect(P2QSTRING(element.getID()));
- QPen pen;
- QBrush brush(Qt::SolidPattern);
- WhiteboardColor penColor = element.getPenColor();
- WhiteboardColor brushColor = element.getBrushColor();
- pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
- pen.setWidth(element.getPenWidth());
- brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
- item->setPen(pen);
- item->setBrush(brush);
-
- item->setPos(0,0);
- QPolygonF polygon;
- std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
- for (; it != element.getPoints().end(); ++it) {
- polygon.append(QPointF(it->first, it->second));
- }
- item->setPolygon(polygon);
- }
-
- void visit(WhiteboardTextElement& element) {
- QGraphicsTextItem* item;
- QString id = P2QSTRING(element.getID());
- if (type_ == GView::New) {
- item = new QGraphicsTextItem;
- graphicsView_->addItem(item, id, pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsTextItem*>(graphicsView_->getItem(id));
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
- if (item) {
- item->setPlainText(P2QSTRING(element.getText()));
- item->setPos(QPointF(element.getX(), element.getY()));
- QFont font = item->font();
- font.setPointSize(element.getSize());
- item->setFont(font);
- WhiteboardColor color = element.getColor();
- item->setDefaultTextColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
- item->setData(100, id);
- }
- }
-
- void visit(WhiteboardEllipseElement& element) {
- QRectF rect;
- QGraphicsEllipseItem* item;
- QString id = P2QSTRING(element.getID());
- rect.setTopLeft(QPointF(element.getCX()-element.getRX(), element.getCY()-element.getRY()));
- rect.setBottomRight(QPointF(element.getCX()+element.getRX(), element.getCY()+element.getRY()));
- if (type_ == GView::New) {
- item = new QGraphicsEllipseItem(rect);
- graphicsView_->addItem(item, id, pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsEllipseItem*>(graphicsView_->getItem(id));
- item->setRect(rect);
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
- QPen pen;
- QBrush brush(Qt::SolidPattern);
- WhiteboardColor penColor = element.getPenColor();
- WhiteboardColor brushColor = element.getBrushColor();
- pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
- pen.setWidth(element.getPenWidth());
- brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
- item->setPen(pen);
- item->setBrush(brush);
- item->setData(100, id);
- }
-
- private:
- GView* graphicsView_;
- int pos_;
- GView::Type type_;
- };
+ class WhiteboardElementDrawingVisitor : public WhiteboardElementVisitor {
+ public:
+ WhiteboardElementDrawingVisitor(GView* graphicsView, int pos, GView::Type type) : graphicsView_(graphicsView), pos_(pos), type_(type) {}
+
+ void visit(WhiteboardLineElement& element) {
+ QGraphicsLineItem *item;
+ if (type_ == GView::New) {
+ item = new QGraphicsLineItem(element.x1(), element.y1(), element.x2(), element.y2());
+ graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ QLineF line(element.x1(), element.y1(), element.x2(), element.y2());
+ item->setLine(line);
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+ if (item) {
+ QPen pen;
+ WhiteboardColor color = element.getColor();
+ pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ item->setPen(pen);
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ }
+ }
+
+ void visit(WhiteboardFreehandPathElement& element) {
+ FreehandLineItem *item;
+ if (type_ == GView::New) {
+ item = new FreehandLineItem;
+ } else {
+ item = qgraphicsitem_cast<FreehandLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+
+ if (item) {
+ QPen pen;
+ WhiteboardColor color = element.getColor();
+ pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ item->setPen(pen);
+
+ std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
+ item->setStartPoint(QPointF(it->first, it->second));
+ for (++it; it != element.getPoints().end(); ++it) {
+ item->lineTo(QPointF(it->first, it->second));
+ }
+
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ }
+ if (type_ == GView::New) {
+ graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
+ }
+ }
+
+ void visit(WhiteboardRectElement& element) {
+ QGraphicsRectItem* item;
+ if (type_ == GView::New) {
+ item = new QGraphicsRectItem(element.getX(), element.getY(), element.getWidth(), element.getHeight());
+ graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsRectItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ QRectF rect(element.getX(), element.getY(), element.getWidth(), element.getHeight());
+ item->setRect(rect);
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+
+ if (item) {
+ QPen pen;
+ QBrush brush(Qt::SolidPattern);
+ WhiteboardColor penColor = element.getPenColor();
+ WhiteboardColor brushColor = element.getBrushColor();
+ pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
+ item->setPen(pen);
+ item->setBrush(brush);
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ }
+ }
+
+ void visit(WhiteboardPolygonElement& element) {
+ QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ if (item == 0 && type_ == GView::New) {
+ item = new QGraphicsPolygonItem();
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ graphicsView_->addItem(item, id, pos_);
+ }
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ QPen pen;
+ QBrush brush(Qt::SolidPattern);
+ WhiteboardColor penColor = element.getPenColor();
+ WhiteboardColor brushColor = element.getBrushColor();
+ pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
+ item->setPen(pen);
+ item->setBrush(brush);
+
+ item->setPos(0,0);
+ QPolygonF polygon;
+ std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
+ for (; it != element.getPoints().end(); ++it) {
+ polygon.append(QPointF(it->first, it->second));
+ }
+ item->setPolygon(polygon);
+ }
+
+ void visit(WhiteboardTextElement& element) {
+ QGraphicsTextItem* item;
+ QString id = P2QSTRING(element.getID());
+ if (type_ == GView::New) {
+ item = new QGraphicsTextItem;
+ graphicsView_->addItem(item, id, pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsTextItem*>(graphicsView_->getItem(id));
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+ if (item) {
+ item->setPlainText(P2QSTRING(element.getText()));
+ item->setPos(QPointF(element.getX(), element.getY()));
+ QFont font = item->font();
+ font.setPointSize(element.getSize());
+ item->setFont(font);
+ WhiteboardColor color = element.getColor();
+ item->setDefaultTextColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
+ item->setData(100, id);
+ }
+ }
+
+ void visit(WhiteboardEllipseElement& element) {
+ QRectF rect;
+ QGraphicsEllipseItem* item;
+ QString id = P2QSTRING(element.getID());
+ rect.setTopLeft(QPointF(element.getCX()-element.getRX(), element.getCY()-element.getRY()));
+ rect.setBottomRight(QPointF(element.getCX()+element.getRX(), element.getCY()+element.getRY()));
+ if (type_ == GView::New) {
+ item = new QGraphicsEllipseItem(rect);
+ graphicsView_->addItem(item, id, pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsEllipseItem*>(graphicsView_->getItem(id));
+ item->setRect(rect);
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+ QPen pen;
+ QBrush brush(Qt::SolidPattern);
+ WhiteboardColor penColor = element.getPenColor();
+ WhiteboardColor brushColor = element.getBrushColor();
+ pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
+ item->setPen(pen);
+ item->setBrush(brush);
+ item->setData(100, id);
+ }
+
+ private:
+ GView* graphicsView_;
+ int pos_;
+ GView::Type type_;
+ };
}
diff --git a/Swift/QtUI/WinUIHelpers.cpp b/Swift/QtUI/WinUIHelpers.cpp
index c307937..30f18a6 100644
--- a/Swift/QtUI/WinUIHelpers.cpp
+++ b/Swift/QtUI/WinUIHelpers.cpp
@@ -24,44 +24,44 @@
namespace Swift {
void WinUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
- if (chain.empty()) {
- return;
- }
+ if (chain.empty()) {
+ return;
+ }
- // create certificate store to store the certificate chain in
- HCERTSTORE chainStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL);
- if (!chainStore) {
- return;
- }
+ // create certificate store to store the certificate chain in
+ HCERTSTORE chainStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL);
+ if (!chainStore) {
+ return;
+ }
- ByteArray certAsDER = chain[0]->toDER();
- boost::shared_ptr<const CERT_CONTEXT> certificate_chain;
- {
- PCCERT_CONTEXT certChain;
- BOOL ok = CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, &certChain);
- // maybe free the cert contex we created
- if (!ok || !certChain) {
- return;
- }
- certificate_chain.reset(certChain, CertFreeCertificateContext);
- }
+ ByteArray certAsDER = chain[0]->toDER();
+ boost::shared_ptr<const CERT_CONTEXT> certificate_chain;
+ {
+ PCCERT_CONTEXT certChain;
+ BOOL ok = CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, &certChain);
+ // maybe free the cert contex we created
+ if (!ok || !certChain) {
+ return;
+ }
+ certificate_chain.reset(certChain, CertFreeCertificateContext);
+ }
- for (size_t i = 1; i < chain.size(); ++i) {
- ByteArray certAsDER = chain[i]->toDER();
- CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, NULL);
- }
+ for (size_t i = 1; i < chain.size(); ++i) {
+ ByteArray certAsDER = chain[i]->toDER();
+ CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, NULL);
+ }
- CRYPTUI_VIEWCERTIFICATE_STRUCT viewDialogProperties = { 0 };
- viewDialogProperties.dwSize = sizeof(viewDialogProperties);
- viewDialogProperties.hwndParent = (HWND) parent->winId();
- viewDialogProperties.dwFlags = CRYPTUI_DISABLE_EDITPROPERTIES | CRYPTUI_DISABLE_ADDTOSTORE | CRYPTUI_ENABLE_REVOCATION_CHECKING;
- viewDialogProperties.pCertContext = certificate_chain.get();
- viewDialogProperties.cStores = 1;
- viewDialogProperties.rghStores = &chainStore;
- BOOL properties_changed;
+ CRYPTUI_VIEWCERTIFICATE_STRUCT viewDialogProperties = { 0 };
+ viewDialogProperties.dwSize = sizeof(viewDialogProperties);
+ viewDialogProperties.hwndParent = (HWND) parent->winId();
+ viewDialogProperties.dwFlags = CRYPTUI_DISABLE_EDITPROPERTIES | CRYPTUI_DISABLE_ADDTOSTORE | CRYPTUI_ENABLE_REVOCATION_CHECKING;
+ viewDialogProperties.pCertContext = certificate_chain.get();
+ viewDialogProperties.cStores = 1;
+ viewDialogProperties.rghStores = &chainStore;
+ BOOL properties_changed;
- // blocking call that shows modal certificate dialog
- BOOL rv = ::CryptUIDlgViewCertificate(&viewDialogProperties, &properties_changed);
+ // blocking call that shows modal certificate dialog
+ BOOL rv = ::CryptUIDlgViewCertificate(&viewDialogProperties, &properties_changed);
}
}
diff --git a/Swift/QtUI/WinUIHelpers.h b/Swift/QtUI/WinUIHelpers.h
index 2146cfd..36f5c9e 100644
--- a/Swift/QtUI/WinUIHelpers.h
+++ b/Swift/QtUI/WinUIHelpers.h
@@ -20,7 +20,7 @@ namespace Swift {
class WinUIHelpers {
public:
- static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
+ static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
};
}
diff --git a/Swift/QtUI/WindowsNotifier.cpp b/Swift/QtUI/WindowsNotifier.cpp
index 1241d8f..c954fab 100644
--- a/Swift/QtUI/WindowsNotifier.cpp
+++ b/Swift/QtUI/WindowsNotifier.cpp
@@ -19,38 +19,38 @@
namespace Swift {
WindowsNotifier::WindowsNotifier(const std::string& name, const boost::filesystem::path& icon, QSystemTrayIcon* tray) : tray(tray) {
- notifierWindow = new QtWin32NotifierWindow();
- snarlNotifier = new SnarlNotifier(name, notifierWindow, icon);
- connect(tray, SIGNAL(messageClicked()), SLOT(handleMessageClicked()));
+ notifierWindow = new QtWin32NotifierWindow();
+ snarlNotifier = new SnarlNotifier(name, notifierWindow, icon);
+ connect(tray, SIGNAL(messageClicked()), SLOT(handleMessageClicked()));
}
WindowsNotifier::~WindowsNotifier() {
- delete snarlNotifier;
- delete notifierWindow;
+ delete snarlNotifier;
+ delete notifierWindow;
}
void WindowsNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) {
- if (snarlNotifier->isAvailable()) {
- snarlNotifier->showMessage(type, subject, description, picture, callback);
- return;
- }
- std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
- if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
- return;
- }
- lastCallback = callback;
- int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
- tray->showMessage(P2QSTRING(subject), P2QSTRING(description), type == SystemMessage ? QSystemTrayIcon::Information : QSystemTrayIcon::NoIcon, timeout * 1000);
+ if (snarlNotifier->isAvailable()) {
+ snarlNotifier->showMessage(type, subject, description, picture, callback);
+ return;
+ }
+ std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
+ if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
+ return;
+ }
+ lastCallback = callback;
+ int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
+ tray->showMessage(P2QSTRING(subject), P2QSTRING(description), type == SystemMessage ? QSystemTrayIcon::Information : QSystemTrayIcon::NoIcon, timeout * 1000);
}
void WindowsNotifier::handleMessageClicked() {
- if (lastCallback) {
- lastCallback();
- }
+ if (lastCallback) {
+ lastCallback();
+ }
}
void WindowsNotifier::purgeCallbacks() {
- lastCallback = boost::function<void()>();
+ lastCallback = boost::function<void()>();
}
}
diff --git a/Swift/QtUI/WindowsNotifier.h b/Swift/QtUI/WindowsNotifier.h
index 8412b6e..fae0795 100644
--- a/Swift/QtUI/WindowsNotifier.h
+++ b/Swift/QtUI/WindowsNotifier.h
@@ -16,23 +16,23 @@
class QSystemTrayIcon;
namespace Swift {
- class WindowsNotifier : public QObject, public Notifier {
- Q_OBJECT
+ class WindowsNotifier : public QObject, public Notifier {
+ Q_OBJECT
- public:
- WindowsNotifier(const std::string& name, const boost::filesystem::path& icon, QSystemTrayIcon* tray);
- ~WindowsNotifier();
+ public:
+ WindowsNotifier(const std::string& name, const boost::filesystem::path& icon, QSystemTrayIcon* tray);
+ ~WindowsNotifier();
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
- virtual void purgeCallbacks();
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
+ virtual void purgeCallbacks();
- private slots:
- void handleMessageClicked();
+ private slots:
+ void handleMessageClicked();
- private:
- QSystemTrayIcon* tray;
- Win32NotifierWindow* notifierWindow;
- SnarlNotifier* snarlNotifier;
- boost::function<void()> lastCallback;
- };
+ private:
+ QSystemTrayIcon* tray;
+ Win32NotifierWindow* notifierWindow;
+ SnarlNotifier* snarlNotifier;
+ boost::function<void()> lastCallback;
+ };
}
diff --git a/Swift/QtUI/main.cpp b/Swift/QtUI/main.cpp
index 46b3853..86ba931 100644
--- a/Swift/QtUI/main.cpp
+++ b/Swift/QtUI/main.cpp
@@ -33,72 +33,72 @@
#include <Swift/QtUI/QtTranslator.h>
int main(int argc, char* argv[]) {
- Swift::PlatformApplicationPathProvider applicationPathProvider(SWIFT_APPLICATION_NAME);
+ Swift::PlatformApplicationPathProvider applicationPathProvider(SWIFT_APPLICATION_NAME);
- Swift::CrashReporter crashReporter(applicationPathProvider.getDataDir() / "crashes");
+ Swift::CrashReporter crashReporter(applicationPathProvider.getDataDir() / "crashes");
#if QT_VERSION < 0x050000
- QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
+ QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif
- // Parse program options
- boost::program_options::options_description desc = Swift::QtSwift::getOptionsDescription();
- boost::program_options::variables_map vm;
- try {
- boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
- } catch (const boost::program_options::unknown_option& option) {
+ // Parse program options
+ boost::program_options::options_description desc = Swift::QtSwift::getOptionsDescription();
+ boost::program_options::variables_map vm;
+ try {
+ boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
+ } catch (const boost::program_options::unknown_option& option) {
#if BOOST_VERSION >= 104200
- std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl;
+ std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl;
#else
- std::cout << "Error: " << option.what() << " (continuing)" << std::endl;
+ std::cout << "Error: " << option.what() << " (continuing)" << std::endl;
#endif
- }
- boost::program_options::notify(vm);
- if (vm.count("help") > 0) {
- std::cout << SWIFT_APPLICATION_NAME << " is an instant messaging client for the XMPP network." << std::endl;
- std::cout << std::endl;
- std::cout << "Usage: " << argv[0] << " [OPTIONS]..." << std::endl;
- std::cout << std::endl;
- std::cout << desc << std::endl;
- return 1;
- }
- if (vm.count("version") > 0) {
- std::cout << SWIFT_APPLICATION_NAME << " " << buildVersion << std::endl;
- return 0;
- }
-
- // Translation
+ }
+ boost::program_options::notify(vm);
+ if (vm.count("help") > 0) {
+ std::cout << SWIFT_APPLICATION_NAME << " is an instant messaging client for the XMPP network." << std::endl;
+ std::cout << std::endl;
+ std::cout << "Usage: " << argv[0] << " [OPTIONS]..." << std::endl;
+ std::cout << std::endl;
+ std::cout << desc << std::endl;
+ return 1;
+ }
+ if (vm.count("version") > 0) {
+ std::cout << SWIFT_APPLICATION_NAME << " " << buildVersion << std::endl;
+ return 0;
+ }
+
+ // Translation
#if QT_VERSION < 0x050000
- QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
+ QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
#endif
- boost::filesystem::path someTranslationPath = applicationPathProvider.getResourcePath("/translations/swift_en.qm");
+ boost::filesystem::path someTranslationPath = applicationPathProvider.getResourcePath("/translations/swift_en.qm");
- QTranslator qtTranslator;
- if (!someTranslationPath.empty()) {
+ QTranslator qtTranslator;
+ if (!someTranslationPath.empty()) {
#if QT_VERSION >= 0x040800
- if (vm.count("language") > 0) {
- qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + P2QSTRING(vm["language"].as<std::string>()), P2QSTRING(Swift::pathToString(someTranslationPath.parent_path())));
- }
- else {
- qtTranslator.load(QLocale::system(), QString(SWIFT_APPLICATION_NAME).toLower(), "_", P2QSTRING(Swift::pathToString(someTranslationPath)));
- }
+ if (vm.count("language") > 0) {
+ qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + P2QSTRING(vm["language"].as<std::string>()), P2QSTRING(Swift::pathToString(someTranslationPath.parent_path())));
+ }
+ else {
+ qtTranslator.load(QLocale::system(), QString(SWIFT_APPLICATION_NAME).toLower(), "_", P2QSTRING(Swift::pathToString(someTranslationPath)));
+ }
#else
- //std::cout << "Loading " << std::string(QLocale::system().name().toUtf8()) << std::endl;
- qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + QLocale::system().name(), P2QSTRING(Swift::pathToString(someTranslationPath)));
+ //std::cout << "Loading " << std::string(QLocale::system().name().toUtf8()) << std::endl;
+ qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + QLocale::system().name(), P2QSTRING(Swift::pathToString(someTranslationPath)));
#endif
- }
+ }
- QApplication app(argc, argv);
+ QApplication app(argc, argv);
- app.installTranslator(&qtTranslator);
- QtTranslator swiftTranslator;
- Swift::Translator::setInstance(&swiftTranslator);
+ app.installTranslator(&qtTranslator);
+ QtTranslator swiftTranslator;
+ Swift::Translator::setInstance(&swiftTranslator);
- Swift::QtSwift swift(vm);
- int result = app.exec();
+ Swift::QtSwift swift(vm);
+ int result = app.exec();
- Swift::Translator::setInstance(NULL);
+ Swift::Translator::setInstance(NULL);
- return result;
+ return result;
}
diff --git a/Swift/QtUI/swift-open-uri.cpp b/Swift/QtUI/swift-open-uri.cpp
index 735cf5e..23a8851 100644
--- a/Swift/QtUI/swift-open-uri.cpp
+++ b/Swift/QtUI/swift-open-uri.cpp
@@ -11,21 +11,21 @@
#include <QDBusMessage>
int main(int argc, char* argv[]) {
- QCoreApplication app(argc, argv);
+ QCoreApplication app(argc, argv);
- QDBusConnection bus = QDBusConnection::sessionBus();
- if (!bus.isConnected()) {
- return -1;
- }
- if (argc != 2) {
- std::cerr << "Usage: " << argv[0] << " uri" << std::endl;
- return -1;
- }
+ QDBusConnection bus = QDBusConnection::sessionBus();
+ if (!bus.isConnected()) {
+ return -1;
+ }
+ if (argc != 2) {
+ std::cerr << "Usage: " << argv[0] << " uri" << std::endl;
+ return -1;
+ }
- QDBusMessage msg = QDBusMessage::createMethodCall("im.swift.Swift.URIHandler", "/", "im.swift.Swift.URIHandler", "openURI");
- msg << argv[1];
+ QDBusMessage msg = QDBusMessage::createMethodCall("im.swift.Swift.URIHandler", "/", "im.swift.Swift.URIHandler", "openURI");
+ msg << argv[1];
- bus.call(msg);
+ bus.call(msg);
- return 0;
+ return 0;
}