From d162494ec8d6c26fd48099ca3558acd931705b88 Mon Sep 17 00:00:00 2001 From: blue Date: Wed, 17 Aug 2022 19:25:35 +0300 Subject: [PATCH] Better way to store expanded elements in roster, several clean ups, translations --- CHANGELOG.md | 3 + main/application.cpp | 96 ++++++--- main/application.h | 7 +- translations/squawk.en.ts | 259 ++++++++---------------- translations/squawk.pt_BR.ts | 299 +++++++++++++++++++++++++++- translations/squawk.ru.ts | 299 +++++++++++++++++++++++++++- ui/models/element.cpp | 5 + ui/models/element.h | 1 + ui/models/item.cpp | 5 + ui/models/item.h | 1 + ui/models/reference.cpp | 5 + ui/models/reference.h | 2 + ui/models/room.h | 1 - ui/models/roster.cpp | 82 +++++++- ui/models/roster.h | 11 +- ui/squawk.cpp | 45 +---- ui/squawk.h | 3 +- ui/widgets/settings/pagegeneral.cpp | 2 +- 18 files changed, 874 insertions(+), 252 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40a85c8..7107e26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,9 +3,12 @@ ## Squawk 0.2.3 (UNRELEASED) ### Bug fixes - "Add contact" and "Join conference" menu are enabled once again (pavavno)! +- availability is now read from the same section of config file it was stored ### Improvements - deactivated accounts now don't appear in combobox of "Add contact" and "Join conference" dialogues +- all of the expandable roster items now get saved between launches +- settings file on the disk is not rewritten every roster element expansion or collapse ### New features - Now you can enable tray icon from settings! diff --git a/main/application.cpp b/main/application.cpp index a319ee5..3942e53 100644 --- a/main/application.cpp +++ b/main/application.cpp @@ -30,16 +30,18 @@ Application::Application(Core::Squawk* p_core): storage(), trayIcon(nullptr), actionQuit(Shared::icon("application-exit"), tr("Quit")), - actionToggle(tr("Minimize to tray")) + actionToggle(QApplication::windowIcon(), tr("Minimize to tray")), + expandedPaths() { connect(&actionQuit, &QAction::triggered, this, &Application::quit); connect(&actionToggle, &QAction::triggered, this, &Application::toggleSquawk); connect(&roster, &Models::Roster::unnoticedMessage, this, &Application::notify); connect(&roster, &Models::Roster::unreadMessagesCountChanged, this, &Application::unreadMessagesCountChanged); + connect(&roster, &Models::Roster::addedElement, this, &Application::onAddedElement); - //connecting myself to the backed + //connecting myself to the backend connect(this, &Application::changeState, core, &Core::Squawk::changeState); connect(this, &Application::setRoomJoined, core, &Core::Squawk::setRoomJoined); connect(this, &Application::setRoomAutoJoin, core, &Core::Squawk::setRoomAutoJoin); @@ -70,7 +72,7 @@ Application::Application(Core::Squawk* p_core): connect(core, &Core::Squawk::changeAccount, this, &Application::changeAccount); connect(core, &Core::Squawk::removeAccount, this, &Application::removeAccount); - connect(core, &Core::Squawk::addContact, this, &Application::addContact); + connect(core, &Core::Squawk::addContact, &roster, &Models::Roster::addContact); connect(core, &Core::Squawk::addGroup, this, &Application::addGroup); connect(core, &Core::Squawk::removeGroup, &roster, &Models::Roster::removeGroup); connect(core, qOverload(&Core::Squawk::removeContact), @@ -168,6 +170,8 @@ void Application::createMainWindow() connect(squawk, &Squawk::openConversation, this, &Application::openConversation); connect(squawk, &Squawk::changeState, this, &Application::setState); connect(squawk, &Squawk::changeTray, this, &Application::onChangeTray); + connect(squawk, &Squawk::itemExpanded, this, &Application::onItemExpanded); + connect(squawk, &Squawk::itemCollapsed, this, &Application::onItemCollapsed); connect(squawk, &Squawk::quit, this, &Application::quit); connect(squawk, &Squawk::closing, this, &Application::onSquawkClosing); @@ -192,7 +196,19 @@ void Application::createMainWindow() dialogueQueue.setParentWidnow(squawk); squawk->stateChanged(availability); + squawk->raise(); squawk->show(); + squawk->activateWindow(); + + for (const std::list& entry : expandedPaths) { + QModelIndex ind = roster.getIndexByPath(entry); + if (ind.isValid()) { + squawk->expand(ind); + } + } + + connect(squawk, &Squawk::itemExpanded, this, &Application::onItemExpanded); + connect(squawk, &Squawk::itemCollapsed, this, &Application::onItemCollapsed); } } @@ -292,6 +308,32 @@ void Application::toggleSquawk() } } +void Application::onItemCollapsed(const QModelIndex& index) +{ + std::list address = roster.getItemPath(index); + if (address.size() > 0) { + expandedPaths.erase(address); + } +} + +void Application::onItemExpanded(const QModelIndex& index) +{ + std::list address = roster.getItemPath(index); + if (address.size() > 0) { + expandedPaths.insert(address); + } +} + +void Application::onAddedElement(const std::list& path) +{ + if (squawk != nullptr && expandedPaths.count(path) > 0) { + QModelIndex index = roster.getIndexByPath(path); + if (index.isValid()) { + squawk->expand(index); + } + } +} + void Application::notify(const QString& account, const Shared::Message& msg) { QString jid = msg.getPenPalJid(); @@ -427,6 +469,18 @@ void Application::readSettings() } else { avail = static_cast(Shared::Availability::online); } + + settings.beginGroup("roster"); + QStringList entries = settings.allKeys(); + for (const QString& entry : entries) { + QStringList p = entry.split("/"); + if (p.last() == "expanded" && settings.value(entry, false).toBool()) { + p.pop_back(); + expandedPaths.emplace(p.begin(), p.end()); + } + } + + settings.endGroup(); settings.endGroup(); setState(Shared::Global::fromInt(avail)); @@ -440,7 +494,22 @@ void Application::readSettings() void Application::writeSettings() { QSettings settings; - settings.setValue("availability", static_cast(availability)); + settings.beginGroup("ui"); + settings.setValue("availability", static_cast(availability)); + + settings.remove("roster"); + settings.beginGroup("roster"); + for (const std::list& address : expandedPaths) { + QString path = ""; + for (const QString& hop : address) { + path += hop + "/"; + } + path += "expanded"; + settings.setValue(path, true); + } + + settings.endGroup(); + settings.endGroup(); } void Application::requestPassword(const QString& account, bool authenticationError) { @@ -611,25 +680,6 @@ void Application::changeAccount(const QString& account, const QMap& data) -{ - roster.addContact(account, jid, group, data); - - if (squawk != nullptr) { - QSettings settings; - settings.beginGroup("ui"); - settings.beginGroup("roster"); - settings.beginGroup(account); - if (settings.value("expanded", false).toBool()) { - QModelIndex ind = roster.getAccountIndex(account); - squawk->expand(ind); - } - settings.endGroup(); - settings.endGroup(); - settings.endGroup(); - } -} - void Application::addGroup(const QString& account, const QString& name) { roster.addGroup(account, name); diff --git a/main/application.h b/main/application.h index db60009..54c2dbc 100644 --- a/main/application.h +++ b/main/application.h @@ -18,6 +18,8 @@ #define APPLICATION_H #include +#include +#include #include #include @@ -76,7 +78,6 @@ protected slots: void openConversation(const Models::Roster::ElId& id, const QString& resource = ""); void addGroup(const QString& account, const QString& name); - void addContact(const QString& account, const QString& jid, const QString& group, const QMap& data); void requestPassword(const QString& account, bool authenticationError); @@ -97,6 +98,9 @@ private slots: void onChangeTray(bool enabled, bool hide); void trayClicked(QSystemTrayIcon::ActivationReason reason); void toggleSquawk(); + void onItemExpanded(const QModelIndex& index); + void onItemCollapsed(const QModelIndex& index); + void onAddedElement(const std::list& path); private: void createMainWindow(); @@ -122,6 +126,7 @@ private: QSystemTrayIcon* trayIcon; QAction actionQuit; QAction actionToggle; + std::set> expandedPaths; }; #endif // APPLICATION_H diff --git a/translations/squawk.en.ts b/translations/squawk.en.ts index 0aef979..db178ac 100644 --- a/translations/squawk.en.ts +++ b/translations/squawk.en.ts @@ -5,51 +5,43 @@ About - About Squawk About window header About Squawk - Squawk Squawk - About Tab title About - XMPP (jabber) messenger XMPP (jabber) messenger - (c) 2019 - 2022, Yury Gubich (c) 2019 - 2022, Yury Gubich - <a href="https://git.macaw.me/blue/squawk">Project site</a> <a href="https://git.macaw.me/blue/squawk">Project site</a> - <a href="https://git.macaw.me/blue/squawk/src/branch/master/LICENSE.md">License: GNU General Public License version 3</a> <a href="https://git.macaw.me/blue/squawk/src/branch/master/LICENSE.md">License: GNU General Public License version 3</a> - Components Tab header Components @@ -58,9 +50,6 @@ - - - Version Version @@ -68,21 +57,16 @@ - - - 0.0.0 0.0.0 - Report Bugs Report Bugs - Please report any bug you find! To report bugs you can use: Please report any bug you find! @@ -90,61 +74,51 @@ To report bugs you can use: - <a href="https://git.macaw.me/blue/squawk/issues">Project bug tracker</> <a href="https://git.macaw.me/blue/squawk/issues">Project bug tracker</> - XMPP (<a href="xmpp:blue@macaw.me">blue@macaw.me</a>) XMPP (<a href="xmpp:blue@macaw.me">blue@macaw.me</a>) - E-Mail (<a href="mailto:blue@macaw.me">blue@macaw.me</a>) E-Mail (<a href="mailto:blue@macaw.me">blue@macaw.me</a>) - Thanks To Thanks to - Vae Vae - Major refactoring, bug fixes, constructive criticism Major refactoring, bug fixes, constructive criticism - Shunf4 Shunf4 - Major refactoring, bug fixes, build adaptations for Windows and MacOS Major refactoring, bug fixes, build adaptations for Windows and MacOS - Bruno F. Fontes Bruno F. Fontes - Brazilian Portuguese translation Brazilian Portuguese translation @@ -164,118 +138,100 @@ To report bugs you can use: Account - Account Window title Account - Your account login Tooltip Your account login - john_smith1987 Login placeholder john_smith1987 - Server Server - A server address of your account. Like 404.city or macaw.me Tooltip A server address of your account. Like 404.city or macaw.me - macaw.me Placeholder macaw.me - Login Login - Password Password - Password of your account Tooltip Password of your account - Name Name - Just a name how would you call this account, doesn't affect anything Just a name how would you call this account, doesn't affect anything (cant be changed) - John Placeholder John - Resource Resource - A resource name like "Home" or "Work" Tooltip A resource name like "Home" or "Work" - QXmpp Default resource QXmpp - Password storage Password storage - Active Active - enable enable @@ -284,37 +240,31 @@ To report bugs you can use: Accounts - Accounts Accounts - Delete Delete - Add Add - Edit Edit - Change password Change password - Connect Connect @@ -333,22 +283,38 @@ To report bugs you can use: Application - + + Quit + Quit + + + + + Minimize to tray + Minimize to tray + + + + Show Squawk + Show Squawk + + + from from - + Attached file Attached file - + Mark as Read Mark as Read - + Open conversation Open conversation @@ -357,7 +323,6 @@ To report bugs you can use: Conversation - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -371,7 +336,6 @@ p, li { white-space: pre-wrap; } - Type your message here... Placeholder Type your message here... @@ -431,14 +395,12 @@ p, li { white-space: pre-wrap; } CredentialsPrompt - Authentication error: %1 Window title Authentication error: %1 - Couldn't authenticate account %1: login or password is icorrect. Would you like to check them and try again? Couldn't authenticate account %1: login or password is incorrect. @@ -446,26 +408,22 @@ Would you like to check them and try again? - Login Login - Your account login (without @server.domain) Tooltip Your account login (without @server.domain) - Password Password - Your password Password @@ -724,61 +682,51 @@ Would you like to check them and try again? JoinConference - Join new conference Join new conference - JID JID - Room JID Room JID - identifier@conference.server.org identifier@conference.server.org - Account Account - Join on login Join on login - If checked Squawk will try to join this conference on login If checked Squawk will try to join this conference on login - Nick name Nick name - Your nick name for that conference. If you leave this field empty your account name will be used as a nick name Your nick name for that conference. If you leave this field empty your account name will be used as a nick name - John John @@ -818,66 +766,66 @@ Would you like to check them and try again? Models::Roster - + New messages New messages - - - + + + New messages: New messages: - - + + Jabber ID: Jabber ID: - - - + + + Availability: Availability: - - - + + + Status: Status: - - + + Subscription: Subscription: - + Affiliation: Affiliation: - + Role: Role: - + Online contacts: Online contacts: - + Total contacts: Total contacts: - + Members: Members: @@ -886,57 +834,48 @@ Would you like to check them and try again? NewContact - Add new contact Window title Add new contact - Account Account - An account that is going to have new contact An account that is going to have new contact - JID JID - Jabber id of your new contact Jabber id of your new contact - name@server.dmn Placeholder name@server.dmn - Name Name - The way this new contact will be labeled in your roster (optional) The way this new contact will be labeled in your roster (optional) - John Smith John Smith @@ -945,13 +884,11 @@ Would you like to check them and try again? PageAppearance - Theme Style - Color scheme Color scheme @@ -968,23 +905,45 @@ Would you like to check them and try again? PageGeneral - Downloads path Downloads path + Tray icon + Tray icon + + + + Mimimize Squawk to tray when closing main window + Mimimize Squawk to tray when closing main window + + + + Hide tray icon + Hide tray icon + + + + Hide tray icon when Squawk main window is visible + Hide tray icon when Squawk main window is visible + + Close to tray icon - Close to tray icon + Close to tray icon - Browse Browse + Tray is not available for your system + Tray is not available for your system + + + Select where downloads folder is going to be Select where downloads folder is going to be @@ -993,7 +952,6 @@ Would you like to check them and try again? Settings - Preferences Window title Preferences @@ -1001,32 +959,26 @@ Would you like to check them and try again? - - General General - Appearance Appearance - Apply Apply - Cancel Cancel - Ok Ok @@ -1035,118 +987,107 @@ Would you like to check them and try again? Squawk - squawk Squawk - Please select a contact to start chatting Please select a contact to start chatting - Settings Settings - Squawk Menu bar entry Squawk - Help Help - Accounts Accounts - Quit Quit - Add contact Add contact - Add conference Join conference - Preferences Preferences - About Squawk About Squawk - + Deactivate Deactivate - + Activate Activate - - + + VCard VCard - - - + + + Remove Remove - + Open dialog Open dialog - - + + Unsubscribe Unsubscribe - - + + Subscribe Subscribe - + Rename Rename - + Input new name for %1 or leave it empty for the contact to be displayed as %1 @@ -1155,47 +1096,47 @@ or leave it empty for the contact to be displayed as %1 - + Renaming %1 Renaming %1 - + Groups Groups - + New group New group - + New group name New group name - + Add %1 to a new group Add %1 to a new group - + Open conversation Open conversation - + %1 account card %1 account card - + %1 contact card %1 contact card - + Downloading vCard Downloading vCard @@ -1204,145 +1145,119 @@ to be displayed as %1 VCard - Received 12.07.2007 at 17.35 Never updated - - General General - Organization Organization - Middle name Middle name - First name First name - Last name Last name - Nick name Nick name - Birthday Birthday - Organization name Organization name - Unit / Department Unit / Department - Role / Profession Role / Profession - Job title Job title - Full name Full name - Personal information Personal information - - Contact Contact - Addresses Addresses - E-Mail addresses E-Mail addresses - Jabber ID Jabber ID - Web site Web site - Phone numbers Phone numbers - - Description Description - Set avatar Set avatar - Clear avatar Clear avatar diff --git a/translations/squawk.pt_BR.ts b/translations/squawk.pt_BR.ts index f818e63..5d76ade 100644 --- a/translations/squawk.pt_BR.ts +++ b/translations/squawk.pt_BR.ts @@ -4,101 +4,130 @@ About + About Squawk Sorbe Squawk + Squawk Squawk + About Tab title Sobre + XMPP (jabber) messenger XMPP (jabber) mensageiro + (c) 2019 - 2022, Yury Gubich (c) 2019 - 2022, Yury Gubich + <a href="https://git.macaw.me/blue/squawk">Project site</a> <a href="https://git.macaw.me/blue/squawk">Site do projeto</a> + <a href="https://git.macaw.me/blue/squawk/src/branch/master/LICENSE.md">License: GNU General Public License version 3</a> <a href="https://git.macaw.me/blue/squawk/src/branch/master/LICENSE.md">Licença: GNU General Public License versão 3</a> + Components Componentes + + + Version Versão + + + 0.0.0 0.0.0 + Report Bugs Relatório de erros + Please report any bug you find! To report bugs you can use: Por favor reportar qualquer erro que você encontrar! Para relatar bugs você pode usar: + <a href="https://git.macaw.me/blue/squawk/issues">Project bug tracker</> <a href="https://git.macaw.me/blue/squawk/issues">Rastreador de bugs do projeto</> + XMPP (<a href="xmpp:blue@macaw.me">blue@macaw.me</a>) XMPP (<a href="xmpp:blue@macaw.me">blue@macaw.me</a>) + E-Mail (<a href="mailto:blue@macaw.me">blue@macaw.me</a>) E-Mail (<a href="mailto:blue@macaw.me">blue@macaw.me</a>) + Thanks To Graças ao + Vae Vae + Major refactoring, bug fixes, constructive criticism Refatoração importante, correção de erros, críticas construtivas + Shunf4 Shunf4 + Major refactoring, bug fixes, build adaptations for Windows and MacOS Refatoração importante, correção de erros, adaptações de construção para Windows e MacOS + Bruno F. Fontes Bruno F. Fontes + Brazilian Portuguese translation Tradução para o português do Brasil + + (built against %1) (Versão durante a compilação %1) + License Licença @@ -106,83 +135,101 @@ Para relatar bugs você pode usar: Account + Account Window header Conta + Your account login Tooltip Suas informações de login + john_smith1987 Login placeholder josé_silva1987 + Server Servidor + A server address of your account. Like 404.city or macaw.me Tooltip O endereço do servidor da sua conta, como o 404.city ou o macaw.me + macaw.me Placeholder macaw.me + Login Usuário + Password Senha + Password of your account Tooltip Senha da sua conta + Name Nome + Just a name how would you call this account, doesn't affect anything Apenas um nome para identificar esta conta. Não influencia em nada (não pode ser mudado) + John Placeholder José + Resource Recurso + A resource name like "Home" or "Work" Tooltip Um nome de recurso como "Casa" ou "Trabalho" + QXmpp Default resource QXmpp + Password storage Armazenamento de senha + Active Ativo + enable habilitar @@ -190,26 +237,32 @@ Para relatar bugs você pode usar: Accounts + Accounts Contas + Delete Apagar + Add Adicionar + Edit Editar + Change password Alterar senha + Connect Conectar @@ -218,10 +271,13 @@ Para relatar bugs você pode usar: Desconectar + Deactivate Desativar + + Activate Ativar @@ -229,18 +285,38 @@ Para relatar bugs você pode usar: Application + + Quit + Sair + + + + + Minimize to tray + Minimizar para bandeja + + + + Show Squawk + Aparecer Squawk + + + from de + Attached file Arquivo anexado + Mark as Read Marcar como lido + Open conversation Abrir conversa @@ -248,19 +324,23 @@ Para relatar bugs você pode usar: Conversation + Type your message here... Placeholder Digite sua mensagem aqui... + Chose a file to send Escolha um arquivo para enviar + Drop files here to attach them to your message Arraste seus arquivos aqui para anexá-los a sua mensagem + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -273,34 +353,42 @@ p, li { white-space: pre-wrap; } <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + Paste Image Colar imagem + Try sending again Tente enviar de novo + Copy selected Copiar selecionado + Copy message Copiar mensagem + Open Abrir + Show in folder Show in explorer + Edit Editar + Editing message... Messae está sendo editado... @@ -308,29 +396,35 @@ p, li { white-space: pre-wrap; } CredentialsPrompt + Authentication error: %1 Window title Erro de autenticação: %1 + Couldn't authenticate account %1: login or password is icorrect. Would you like to check them and try again? Não foi possível autenticar a conta %1: login ou senha incorretos. Deseja verificá-los e tentar novamente? + Login Usuário + Your account login (without @server.domain) Suas informações de login (sem @server.domain) + Password Senha + Your password Senha da sua conta @@ -338,10 +432,12 @@ Deseja verificá-los e tentar novamente? DialogQueue + Input the password for account %1 Digite a senha para a conta %1 + Password for account %1 Senha para a conta %1 @@ -349,196 +445,235 @@ Deseja verificá-los e tentar novamente? Global + Online Availability Conectado + Away Availability Distante + Absent Availability Ausente + Busy Availability Ocupado + Chatty Availability Tagarela + Invisible Availability Invisível + Offline Availability Desconectado + Disconnected ConnectionState Desconectado + Connecting ConnectionState Connectando + Connected ConnectionState Conectado + Error ConnectionState Erro + None SubscriptionState Nenhum + From SubscriptionState De + To SubscriptionState Para + Both SubscriptionState Ambos + Unknown SubscriptionState Desconhecido + Unspecified Affiliation Não especificado + Outcast Affiliation Rejeitado + Nobody Affiliation Ninguém + Member Affiliation Membro + Admin Affiliation Administrador + Owner Affiliation Dono + Unspecified Role Não especificado + Nobody Role Ninguém + Visitor Role Visitante + Participant Role Participante + Moderator Role Moderador + Pending MessageState Aguardando + Sent MessageState Enviada + Delivered MessageState Entregue + Error MessageState Erro + Plain AccountPassword Texto simples + Jammed AccountPassword Embaralhado + Always Ask AccountPassword Sempre perguntar + KWallet AccountPassword KWallet + Your password is going to be stored in config file but jammed with constant encryption key you can find in program source code. It might look like encryption but it's not AccountPasswordDescription Sua senha será armazenada em um arquivo de configurações, porém embaralhada com uma chave criptográfica constante que você pode encontrar no código fonte do programa. Parece criptografado, mas não é + Squawk is going to query you for the password on every start of the program AccountPasswordDescription O Squark vai requisitar sua senha a cada vez que você abrir o programa + Your password is going to be stored in config file in plain text AccountPasswordDescription Sua senha será armazenada em um arquivo de configurações em texto simples + Your password is going to be stored in KDE wallet storage (KWallet). You're going to be queried for permissions AccountPasswordDescription Sua senha será armazenada no KDE wallet (KWallet). Sua autorização será requerida @@ -547,43 +682,53 @@ Deseja verificá-los e tentar novamente? JoinConference + Join new conference Заголовок окна Entrar em uma nova conferência + JID JID + Room JID Sala JID + identifier@conference.server.org identifier@conference.server.org + Account Conta + Join on login Entrar ao se conectar + If checked Squawk will try to join this conference on login Se marcado, o Squawk tentará entrar nesta conferência automaticamente durante o login + Nick name Apelido + Your nick name for that conference. If you leave this field empty your account name will be used as a nick name Seu apelido para essa conferência. Se você deixar este campo em branco, seu nome de usuário será usado como apelido + John José @@ -602,6 +747,8 @@ Deseja verificá-los e tentar novamente? Baixando... + + Download Baixar @@ -635,18 +782,22 @@ Você pode tentar novamente Models::Room + Subscribed Inscrito + Temporarily unsubscribed Inscrição temporariamente cancelada + Temporarily subscribed Temporariamente inscrito + Unsubscribed Não inscrito @@ -654,47 +805,67 @@ Você pode tentar novamente Models::Roster + New messages Novas mensagens + + + New messages: Novas mensagens: + + Jabber ID: ID Jabber: + + + Availability: Disponibilidade: + + + Status: Status: + + + Subscription: Inscrição: + Affiliation: Я правда не знаю, как это объяснить, не то что перевести Afiliação: + Role: Papel: + Online contacts: Contatos online: + Total contacts: Contatos totais: + Members: Membros: @@ -702,40 +873,49 @@ Você pode tentar novamente NewContact + Add new contact Window title Adicionar novo contato + Account Conta + An account that is going to have new contact A conta que terá um novo contato + JID JID + Jabber id of your new contact ID Jabber do seu novo contato + name@server.dmn Placeholder nome@servidor.com.br + Name Nome + The way this new contact will be labeled in your roster (optional) A forma com que o novo contato será classificado em sua lista (opcional) + John Smith José Silva @@ -743,14 +923,20 @@ Você pode tentar novamente PageAppearance + Theme Estilo + Color scheme Esquema de cores + + + + System Do sistema @@ -758,21 +944,48 @@ Você pode tentar novamente PageGeneral + Downloads path Pasta de downloads - Close to tray icon - Fechar ao ícone da bandeja + Tray icon + Ícone da bandeja + + Mimimize Squawk to tray when closing main window + Minimizar Squawk para bandeja ao fechar a janela principal + + + + Hide tray icon + Esconder o ícone da bandeja + + + + Hide tray icon when Squawk main window is visible + Esconder o ícone da bandeja quando a janela principal não está fechada + + + Close to tray icon + Fechar ao ícone da bandeja + + + Browse 6 / 5,000 Translation results Navegar + + Tray is not available for your system + A bandeja não está disponível para seu sistema + + + Select where downloads folder is going to be Selecione onde a pasta de downloads ficará @@ -780,27 +993,34 @@ Navegar Settings + Preferences Window title Preferências + + General Geral + Appearance Aparência + Apply Aplicar + Cancel Cancelar + Ok Feito @@ -808,31 +1028,38 @@ Navegar Squawk + squawk Squawk + Settings Configurações + Squawk Menu bar entry Squawk + Accounts Contas + Quit Sair + Add contact Adicionar contato + Add conference Adicionar conferência @@ -845,30 +1072,42 @@ Navegar Conectar + + VCard VCard + + + Remove Remover + Open dialog Abrir caixa de diálogo + + Unsubscribe Cancelar inscrição + + Subscribe Inscrever-se + Rename Renomear + Input new name for %1 or leave it empty for the contact to be displayed as %1 @@ -878,38 +1117,47 @@ ser exibido com %1 + Renaming %1 Renomeando %1 + Groups Grupos + New group Novo grupo + New group name Novo nome do grupo + Add %1 to a new group Adicionar %1 a um novo grupo + Open conversation Abrir conversa + %1 account card cartão da conta %1 + %1 contact card cartão de contato %1 + Downloading vCard Baixando vCard @@ -926,26 +1174,32 @@ ser exibido com Senha para a conta %1 + Please select a contact to start chatting Por favor selecione um contato para começar a conversar + Help Ajuda + Preferences Preferências + About Squawk Sorbe Squawk + Deactivate Desativar + Activate Ativar @@ -953,154 +1207,195 @@ ser exibido com VCard + Received 12.07.2007 at 17.35 Nunca atualizado + + General Geral + Organization Empresa + Middle name Nome do meio + First name Primeiro nome + Last name Sobrenome + Nick name Apelido + Birthday Data de aniversário + Organization name Nome da empresa + Unit / Department Unidade / Departamento + Role / Profession Profissão + Job title Cargo + Full name Nome completo + Personal information Informações pessoais + Addresses Endereços + E-Mail addresses Endereços de e-mail + Phone numbers Números de telefone + + Contact Contato + Jabber ID ID Jabber + Web site Site web + + Description Descrição + Set avatar Definir avatar + Clear avatar Apagar avatar + Account %1 card Cartão da conta %1 + Contact %1 card Cartão do contato %1 + Received %1 at %2 Recebido %1 em %2 + Chose your new avatar Escolha um novo avatar + Images (*.png *.jpg *.jpeg) Imagens (*.png *.jpg *.jpeg) + Add email address Adicionar endereço de e-mail + Unset this email as preferred Desmarcar este e-mail como preferido + Set this email as preferred Marcar este e-mail como preferido + Remove selected email addresses Remover endereço de e-mail selecionado + Copy selected emails to clipboard Copiar endereços de e-mails selecionados para a área de transferência + Add phone number Adicionar número de telefone + Unset this phone as preferred Desmarcar este número de telefone como preferido + Set this phone as preferred Marcar este número de telefone como preferido + Remove selected phone numbers Remover os números de telefones selecionados + Copy selected phones to clipboard Copiar os números de telefone selecionados para a área de transferência diff --git a/translations/squawk.ru.ts b/translations/squawk.ru.ts index 1774bb9..421a2d2 100644 --- a/translations/squawk.ru.ts +++ b/translations/squawk.ru.ts @@ -4,101 +4,130 @@ About + About Squawk О Программе Squawk + Squawk Squawk + About Tab title Общее + XMPP (jabber) messenger XMPP (jabber) мессенджер + (c) 2019 - 2022, Yury Gubich (c) 2019 - 2022, Юрий Губич + <a href="https://git.macaw.me/blue/squawk">Project site</a> <a href="https://git.macaw.me/blue/squawk">Сайт проекта</a> + <a href="https://git.macaw.me/blue/squawk/src/branch/master/LICENSE.md">License: GNU General Public License version 3</a> <a href="https://git.macaw.me/blue/squawk/src/branch/master/LICENSE.md">Лицензия: GNU General Public License версия 3</a> + Components Компоненты + + + Version Версия + + + 0.0.0 0.0.0 + Report Bugs Сообщать об ошибках + Please report any bug you find! To report bugs you can use: Пожалуйста, сообщайте о любых ошибках! Способы сообщить об ошибках: + <a href="https://git.macaw.me/blue/squawk/issues">Project bug tracker</> <a href="https://git.macaw.me/blue/squawk/issues">Баг-трекер проекта</> + XMPP (<a href="xmpp:blue@macaw.me">blue@macaw.me</a>) XMPP (<a href="xmpp:blue@macaw.me">blue@macaw.me</a>) + E-Mail (<a href="mailto:blue@macaw.me">blue@macaw.me</a>) E-Mail (<a href="mailto:blue@macaw.me">blue@macaw.me</a>) + Thanks To Благодарности + Vae Vae + Major refactoring, bug fixes, constructive criticism Крупный рефакторинг, исправление ошибок, конструктивная критика + Shunf4 Shunf4 + Major refactoring, bug fixes, build adaptations for Windows and MacOS Крупный рефакторинг, исправление ошибок, адаптация сборки под Windows and MacOS + Bruno F. Fontes Bruno F. Fontes + Brazilian Portuguese translation Перевод на Португальский (Бразилия) + + (built against %1) (версия при сборке %1) + License Лицензия @@ -106,83 +135,101 @@ To report bugs you can use: Account + Account Заголовок окна Учетная запись + Your account login Tooltip Имя пользователя Вашей учетной записи + john_smith1987 Login placeholder ivan_ivanov1987 + Server Сервер + A server address of your account. Like 404.city or macaw.me Tooltip Адресс сервера вашей учетной записи (выглядит как 404.city или macaw.me) + macaw.me Placeholder macaw.me + Login Имя учетной записи + Password Пароль + Password of your account Tooltip Пароль вашей учетной записи + Name Имя + Just a name how would you call this account, doesn't affect anything Просто имя, то как Вы называете свою учетную запись, может быть любым (нельзя поменять) + John Placeholder Иван + Resource Ресурс + A resource name like "Home" or "Work" Tooltip Имя этой программы для ваших контактов, может быть "Home" или "Phone" + QXmpp Ресурс по умолчанию QXmpp + Password storage Хранение пароля + Active Активен + enable включен @@ -190,26 +237,32 @@ To report bugs you can use: Accounts + Accounts Учетные записи + Delete Удалить + Add Добавить + Edit Редактировать + Change password Изменить пароль + Connect Подключить @@ -218,10 +271,13 @@ To report bugs you can use: Отключить + Deactivate Деактивировать + + Activate Активировать @@ -229,18 +285,38 @@ To report bugs you can use: Application + + Quit + Выйти + + + + + Minimize to tray + Свернуть в трей + + + + Show Squawk + Показать Squawk + + + from от + Attached file Прикрепленный файл + Mark as Read Пометить прочитанным + Open conversation Открыть окно беседы @@ -248,19 +324,23 @@ To report bugs you can use: Conversation + Type your message here... Placeholder Введите сообщение... + Chose a file to send Выберите файл для отправки + Drop files here to attach them to your message Бросьте файлы сюда для того что бы прикрепить их к сообщению + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } @@ -273,34 +353,42 @@ p, li { white-space: pre-wrap; } <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + Paste Image Вставить изображение + Try sending again Отправить снова + Copy selected Скопировать выделенное + Copy message Скопировать сообщение + Open Открыть + Show in folder Показать в проводнике + Edit Редактировать + Editing message... Сообщение редактируется... @@ -308,11 +396,13 @@ p, li { white-space: pre-wrap; } CredentialsPrompt + Authentication error: %1 Window title Ошибка аутентификации: %1 + Couldn't authenticate account %1: login or password is icorrect. Would you like to check them and try again? Не получилось аутентифицировать @@ -322,19 +412,23 @@ Would you like to check them and try again? попробовать аутентифицироваться еще раз? + Login Имя учетной записи + Your account login (without @server.domain) Tooltip Имя вашей учтетной записи (без @server.domain) + Password Пароль + Your password Ваш пароль @@ -342,10 +436,12 @@ Would you like to check them and try again? DialogQueue + Input the password for account %1 Введите пароль для учетной записи %1 + Password for account %1 Пароль для учетной записи %1 @@ -353,196 +449,235 @@ Would you like to check them and try again? Global + Online Availability В сети + Away Availability Отошел + Absent Availability Недоступен + Busy Availability Занят + Chatty Availability Готов поболтать + Invisible Availability Невидимый + Offline Availability Отключен + Disconnected ConnectionState Отключен + Connecting ConnectionState Подключается + Connected ConnectionState Подключен + Error ConnectionState Ошибка + None SubscriptionState Нет + From SubscriptionState Входящая + To SubscriptionState Исходящая + Both SubscriptionState Взаимная + Unknown SubscriptionState Неизвестно + Unspecified Affiliation Не назначено + Outcast Affiliation Изгой + Nobody Affiliation Никто + Member Affiliation Участник + Admin Affiliation Администратор + Owner Affiliation Владелец + Unspecified Role Не назначено + Nobody Role Никто + Visitor Role Гость + Participant Role Участник + Moderator Role Модератор + Pending MessageState В процессе отправки + Sent MessageState Отправлено + Delivered MessageState Доставлено + Error MessageState Ошибка + Plain AccountPassword Открытый текст + Jammed AccountPassword Обфусцированный + Always Ask AccountPassword Всегда спрашивать + KWallet AccountPassword KWallet + Your password is going to be stored in config file but jammed with constant encryption key you can find in program source code. It might look like encryption but it's not AccountPasswordDescription Ваш пароль будет храниться в обфусцированном виде в конфигурационном файле. Обфускация производится с помощью постоянного числа, которое можно найти в исходном коде программы. Это может и выглядит как шифрование но им не является + Squawk is going to query you for the password on every start of the program AccountPasswordDescription Squawk будет спрашивать пароль от этой учетной записи каждый раз при запуске + Your password is going to be stored in config file in plain text AccountPasswordDescription Ваш пароль будет храниться в конфигурационном файле открытым текстром + Your password is going to be stored in KDE wallet storage (KWallet). You're going to be queried for permissions AccountPasswordDescription Ваш пароль будет храниться в бумажнике KDE (KWallet). В первый раз программа попросит разрешения для доступа к бумажнику @@ -551,43 +686,53 @@ Would you like to check them and try again? JoinConference + Join new conference Заголовок окна Присоединиться к новой беседе + JID JID + Room JID Jabber-идентификатор беседы + identifier@conference.server.org identifier@conference.server.org + Account Учетная запись + Join on login Автовход + If checked Squawk will try to join this conference on login Если стоит галочка Squawk автоматически присоединится к этой беседе при подключении + Nick name Псевдоним + Your nick name for that conference. If you leave this field empty your account name will be used as a nick name Ваш псевдоним в этой беседе, если оставите это поле пустым - будет использовано имя Вашей учетной записи + John Ivan @@ -606,6 +751,8 @@ Would you like to check them and try again? Скачивается... + + Download Скачать @@ -639,18 +786,22 @@ You can try again Models::Room + Subscribed Вы состоите в беседе + Temporarily unsubscribed Вы временно не состоите в беседе + Temporarily subscribed Вы временно состоите в беседе + Unsubscribed Вы не состоите в беседе @@ -658,47 +809,67 @@ You can try again Models::Roster + New messages Есть непрочитанные сообщения + + + New messages: Новых сообщений: + + Jabber ID: Идентификатор: + + + Availability: Доступность: + + + Status: Статус: + + + Subscription: Подписка: + Affiliation: Я правда не знаю, как это объяснить, не то что перевести Причастность: + Role: Роль: + Online contacts: Контакстов в сети: + Total contacts: Всего контактов: + Members: Участников: @@ -706,40 +877,49 @@ You can try again NewContact + Add new contact Window title Добавление нового контакта + Account Учетная запись + An account that is going to have new contact Учетная запись для которой будет добавлен контакт + JID JID + Jabber id of your new contact Jabber-идентификатор нового контакта + name@server.dmn Placeholder name@server.dmn + Name Имя + The way this new contact will be labeled in your roster (optional) То, как будет подписан контакт в вашем списке контактов (не обязательно) + John Smith Иван Иванов @@ -747,14 +927,20 @@ You can try again PageAppearance + Theme Оформление + Color scheme Цветовая схема + + + + System Системная @@ -762,19 +948,46 @@ You can try again PageGeneral + Downloads path Папка для сохраненных файлов - Close to tray icon - Закрывать в трей + Tray icon + Иконка трея + + Mimimize Squawk to tray when closing main window + Сворачивать Squawk в трей когда закрывается основное окно + + + + Hide tray icon + Скрывать иконку трея + + + + Hide tray icon when Squawk main window is visible + Прятать иконку трея если основное окно не закрыто + + + Close to tray icon + Закрывать в трей + + + Browse Выбрать + + Tray is not available for your system + На вашей системе недоступен трей + + + Select where downloads folder is going to be Выберете папку, в которую будут сохраняться файлы @@ -782,27 +995,34 @@ You can try again Settings + Preferences Window title Настройки + + General Общее + Appearance Внешний вид + Apply Применить + Cancel Отменить + Ok Готово @@ -810,31 +1030,38 @@ You can try again Squawk + squawk Squawk + Settings Настройки + Squawk Menu bar entry Squawk + Accounts Учетные записи + Quit Выйти + Add contact Добавить контакт + Add conference Присоединиться к беседе @@ -847,30 +1074,42 @@ You can try again Подключить + + VCard Карточка + + + Remove Удалить + Open dialog Открыть диалог + + Unsubscribe Отписаться + + Subscribe Подписаться + Rename Переименовать + Input new name for %1 or leave it empty for the contact to be displayed as %1 @@ -880,38 +1119,47 @@ to be displayed as %1 %1 + Renaming %1 Назначение имени контакту %1 + Groups Группы + New group Создать новую группу + New group name Имя группы + Add %1 to a new group Добавление %1 в новую группу + Open conversation Открыть окно беседы + %1 account card Карточка учетной записи %1 + %1 contact card Карточка контакта %1 + Downloading vCard Получение карточки @@ -928,26 +1176,32 @@ to be displayed as %1 Пароль для учетной записи %1 + Please select a contact to start chatting Выберите контакт или группу что бы начать переписку + Help Помощь + Preferences Настройки + About Squawk О Программе Squawk + Deactivate Деактивировать + Activate Активировать @@ -955,154 +1209,195 @@ to be displayed as %1 VCard + Received 12.07.2007 at 17.35 Не обновлялось + + General Общее + Organization Место работы + Middle name Среднее имя + First name Имя + Last name Фамилия + Nick name Псевдоним + Birthday Дата рождения + Organization name Название организации + Unit / Department Отдел + Role / Profession Профессия + Job title Наименование должности + Full name Полное имя + Personal information Личная информация + Addresses Адреса + E-Mail addresses Адреса электронной почты + Phone numbers Номера телефонов + + Contact Контактная информация + Jabber ID Jabber ID + Web site Веб сайт + + Description Описание + Set avatar Установить иконку + Clear avatar Убрать иконку + Account %1 card Карточка учетной записи %1 + Contact %1 card Карточка контакта %1 + Received %1 at %2 Получено %1 в %2 + Chose your new avatar Выберите новую иконку + Images (*.png *.jpg *.jpeg) Изображения (*.png *.jpg *.jpeg) + Add email address Добавить адрес электронной почты + Unset this email as preferred Убрать отметку "предпочтительный" с этого адреса + Set this email as preferred Отметить этот адрес как "предпочтительный" + Remove selected email addresses Удалить выбранные адреса + Copy selected emails to clipboard Скопировать выбранные адреса в буфер обмена + Add phone number Добавить номер телефона + Unset this phone as preferred Убрать отметку "предпочтительный" с этого номера + Set this phone as preferred Отметить этот номер как "предпочтительный" + Remove selected phone numbers Удалить выбранные телефонные номера + Copy selected phones to clipboard Скопировать выбранные телефонные номера в буфер обмена diff --git a/ui/models/element.cpp b/ui/models/element.cpp index acea46f..e89c5aa 100644 --- a/ui/models/element.cpp +++ b/ui/models/element.cpp @@ -75,6 +75,11 @@ void Models::Element::update(const QString& field, const QVariant& value) } } +QString Models::Element::getId() const +{ + return jid; +} + QString Models::Element::getAvatarPath() const { return avatarPath; diff --git a/ui/models/element.h b/ui/models/element.h index c6d3d6e..2ce5a21 100644 --- a/ui/models/element.h +++ b/ui/models/element.h @@ -38,6 +38,7 @@ public: QString getAvatarPath() const; virtual void update(const QString& field, const QVariant& value); + virtual QString getId() const override; void addMessage(const Shared::Message& data); void changeMessage(const QString& id, const QMap& data); diff --git a/ui/models/item.cpp b/ui/models/item.cpp index 4a88dd2..dda28d6 100644 --- a/ui/models/item.cpp +++ b/ui/models/item.cpp @@ -181,6 +181,11 @@ QString Models::Item::getName() const return name; } +QString Models::Item::getId() const +{ + return name; +} + QVariant Models::Item::data(int column) const { if (column != 0) { diff --git a/ui/models/item.h b/ui/models/item.h index 4661479..d3fbb02 100644 --- a/ui/models/item.h +++ b/ui/models/item.h @@ -65,6 +65,7 @@ class Item : public QObject{ virtual void appendChild(Item *child); virtual void removeChild(int index); virtual QString getDisplayedName() const; + virtual QString getId() const; QString getName() const; void setName(const QString& name); diff --git a/ui/models/reference.cpp b/ui/models/reference.cpp index 1aaea15..fe3bf41 100644 --- a/ui/models/reference.cpp +++ b/ui/models/reference.cpp @@ -75,6 +75,11 @@ QString Models::Reference::getDisplayedName() const return original->getDisplayedName(); } +QString Models::Reference::getId() const +{ + return original->getId(); +} + Models::Item * Models::Reference::dereference() { return original; diff --git a/ui/models/reference.h b/ui/models/reference.h index 8ec5352..bc717bb 100644 --- a/ui/models/reference.h +++ b/ui/models/reference.h @@ -38,6 +38,8 @@ public: QString getDisplayedName() const override; void appendChild(Models::Item * child) override; void removeChild(int index) override; + QString getId() const override; + Item* dereference(); const Item* dereferenceConst() const; diff --git a/ui/models/room.h b/ui/models/room.h index 707b35b..b3e889c 100644 --- a/ui/models/room.h +++ b/ui/models/room.h @@ -76,7 +76,6 @@ private: private: bool autoJoin; bool joined; - QString jid; QString nick; QString subject; std::map participants; diff --git a/ui/models/roster.cpp b/ui/models/roster.cpp index fbb7e52..8ce3464 100644 --- a/ui/models/roster.cpp +++ b/ui/models/roster.cpp @@ -52,6 +52,8 @@ void Models::Roster::addAccount(const QMap& data) root->appendChild(acc); accounts.insert(std::make_pair(acc->getName(), acc)); accountsModel->addAccount(acc); + + emit addedElement({acc->getId()}); } QVariant Models::Roster::data (const QModelIndex& index, int role) const @@ -433,6 +435,9 @@ void Models::Roster::addGroup(const QString& account, const QString& name) Group* group = new Group({{"name", name}}); groups.insert(std::make_pair(id, group)); acc->appendChild(group); + + + emit addedElement({acc->getId(), group->getId()}); } else { qDebug() << "An attempt to add group " << name << " to non existing account " << account << ", skipping"; } @@ -470,6 +475,7 @@ void Models::Roster::addContact(const QString& account, const QString& jid, cons } } + std::list path = {acc->getId()}; if (group == "") { if (acc->getContact(jid) != -1) { qDebug() << "An attempt to add a contact" << jid << "to the ungrouped contact set of account" << account << "for the second time, skipping"; @@ -486,6 +492,7 @@ void Models::Roster::addContact(const QString& account, const QString& jid, cons } parent = itr->second; + path.push_back(parent->getId()); if (parent->getContact(jid) != -1) { qDebug() << "An attempt to add a contact" << jid << "to the group" << group << "for the second time, skipping"; @@ -502,11 +509,14 @@ void Models::Roster::addContact(const QString& account, const QString& jid, cons } } + path.push_back(contact->getId()); if (ref == 0) { ref = new Reference(contact); } parent->appendChild(ref); + + emit addedElement(path); } void Models::Roster::removeGroup(const QString& account, const QString& name) @@ -694,6 +704,7 @@ void Models::Roster::addPresence(const QString& account, const QString& jid, con if (itr != contacts.end()) { itr->second->addPresence(name, data); } + } void Models::Roster::removePresence(const QString& account, const QString& jid, const QString& name) @@ -809,6 +820,8 @@ void Models::Roster::addRoom(const QString& account, const QString jid, const QM connect(room, &Room::unreadMessagesCountChanged, this, &Roster::recalculateUnreadMessages); rooms.insert(std::make_pair(id, room)); acc->appendChild(room); + + emit addedElement({acc->getId(), room->getId()}); } void Models::Roster::changeRoom(const QString& account, const QString jid, const QMap& data) @@ -961,7 +974,7 @@ bool Models::Roster::markMessageAsRead(const Models::Roster::ElId& elementId, co } } -QModelIndex Models::Roster::getAccountIndex(const QString& name) +QModelIndex Models::Roster::getAccountIndex(const QString& name) const { std::map::const_iterator itr = accounts.find(name); if (itr == accounts.end()) { @@ -971,7 +984,7 @@ QModelIndex Models::Roster::getAccountIndex(const QString& name) } } -QModelIndex Models::Roster::getGroupIndex(const QString& account, const QString& name) +QModelIndex Models::Roster::getGroupIndex(const QString& account, const QString& name) const { std::map::const_iterator itr = accounts.find(account); if (itr == accounts.end()) { @@ -987,7 +1000,7 @@ QModelIndex Models::Roster::getGroupIndex(const QString& account, const QString& } } -QModelIndex Models::Roster::getContactIndex(const QString& account, const QString& jid, const QString& resource) +QModelIndex Models::Roster::getContactIndex(const QString& account, const QString& jid, const QString& resource) const { std::map::const_iterator itr = accounts.find(account); if (itr == accounts.end()) { @@ -1113,3 +1126,66 @@ void Models::Roster::recalculateUnreadMessages() } emit unreadMessagesCountChanged(count); } + +std::list Models::Roster::getItemPath(const QModelIndex& index) const +{ + std::list result; + if (index.isValid() && index.model() == this) { + Item* item = static_cast(index.internalPointer()); + while (item->type != Item::root) { + result.push_front(item->getId()); + item = item->parentItem(); + } + } + + return result; +} + +QModelIndex Models::Roster::getIndexByPath(const std::list& path) const +{ + if (path.empty()) + return QModelIndex(); + + QModelIndex current; + for (const QString& hop : path) { + int rows = rowCount(current); + bool found = false; + for (int i = 0; i < rows; ++i) { + QModelIndex el = index(i, 0, current); + Item* item = static_cast(el.internalPointer()); + if (item->getId() == hop) { + found = true; + current = el; + break; + } + } + if (!found) + break; + + } + return current; //this way I will return the last matching model index, may be it's logically incorrect + + +// std::list::const_iterator pathItr = path.begin(); +// QString accName = *pathItr; +// QModelIndex accIndex = getAccountIndex(accName); +// if (path.size() == 1) +// return accIndex; +// +// if (!accIndex.isValid()) +// return QModelIndex(); +// +// ++pathItr; +// ElId id{accName, *pathItr}; +// QModelIndex contactIndex = getContactIndex(id.account, id.name); +// if (!contactIndex.isValid()) +// contactIndex = getGroupIndex(id.account, id.name); +// +// if (path.size() == 2) +// return contactIndex; +// +// if (!contactIndex.isValid()) +// return QModelIndex(); +// +// ++pathItr; +} diff --git a/ui/models/roster.h b/ui/models/roster.h index efc50f2..59fef44 100644 --- a/ui/models/roster.h +++ b/ui/models/roster.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include "shared/message.h" @@ -86,9 +87,12 @@ public: QString getContactIconPath(const QString& account, const QString& jid, const QString& resource) const; Account* getAccount(const QString& name); const Account* getAccountConst(const QString& name) const; - QModelIndex getAccountIndex(const QString& name); - QModelIndex getGroupIndex(const QString& account, const QString& name); - QModelIndex getContactIndex(const QString& account, const QString& jid, const QString& resource = ""); + QModelIndex getAccountIndex(const QString& name) const; + QModelIndex getGroupIndex(const QString& account, const QString& name) const; + QModelIndex getContactIndex(const QString& account, const QString& jid, const QString& resource = "") const; + QModelIndex getIndexByPath(const std::list& path) const; + std::list getItemPath(const QModelIndex& index) const; + bool markMessageAsRead(const ElId& elementId, const QString& messageId); void responseArchive(const QString& account, const QString& jid, const std::list& list, bool last); @@ -104,6 +108,7 @@ signals: void unreadMessagesCountChanged(int count); void unnoticedMessage(const QString& account, const Shared::Message& msg); void localPathInvalid(const QString& path); + void addedElement(const std::list& path); //emits only on addition of Account, Contact, Room or Group. Presence and Participant are ignored private slots: void onAccountDataChanged(const QModelIndex& tl, const QModelIndex& br, const QVector& roles); diff --git a/ui/squawk.cpp b/ui/squawk.cpp index 39a7202..c086e10 100644 --- a/ui/squawk.cpp +++ b/ui/squawk.cpp @@ -60,7 +60,8 @@ Squawk::Squawk(Models::Roster& p_rosterModel, QWidget *parent) : connect(m_ui->comboBox, qOverload(&QComboBox::activated), this, &Squawk::onComboboxActivated); //connect(m_ui->roster, &QTreeView::doubleClicked, this, &Squawk::onRosterItemDoubleClicked); connect(m_ui->roster, &QTreeView::customContextMenuRequested, this, &Squawk::onRosterContextMenu); - connect(m_ui->roster, &QTreeView::collapsed, this, &Squawk::onItemCollepsed); + connect(m_ui->roster, &QTreeView::collapsed, this, &Squawk::itemCollapsed); + connect(m_ui->roster, &QTreeView::expanded, this, &Squawk::itemExpanded); connect(m_ui->roster->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &Squawk::onRosterSelectionChanged); connect(rosterModel.accountsModel, &Models::Accounts::changed, this, &Squawk::onAccountsChanged); @@ -491,49 +492,7 @@ void Squawk::writeSettings() settings.endGroup(); settings.setValue("splitter", m_ui->splitter->saveState()); - settings.remove("roster"); - settings.beginGroup("roster"); - int size = rosterModel.accountsModel->rowCount(QModelIndex()); - for (int i = 0; i < size; ++i) { - QModelIndex acc = rosterModel.index(i, 0, QModelIndex()); - Models::Account* account = rosterModel.accountsModel->getAccount(i); - QString accName = account->getName(); - settings.beginGroup(accName); - - settings.setValue("expanded", m_ui->roster->isExpanded(acc)); - std::deque groups = rosterModel.groupList(accName); - for (const QString& groupName : groups) { - settings.beginGroup(groupName); - QModelIndex gIndex = rosterModel.getGroupIndex(accName, groupName); - settings.setValue("expanded", m_ui->roster->isExpanded(gIndex)); - settings.endGroup(); - } - - settings.endGroup(); - } - settings.endGroup(); settings.endGroup(); - - settings.sync(); -} - -void Squawk::onItemCollepsed(const QModelIndex& index) -{ - QSettings settings; - Models::Item* item = static_cast(index.internalPointer()); - switch (item->type) { - case Models::Item::account: - settings.setValue("ui/roster/" + item->getName() + "/expanded", false); - break; - case Models::Item::group: { - QModelIndex accInd = rosterModel.parent(index); - Models::Account* account = rosterModel.accountsModel->getAccount(accInd.row()); - settings.setValue("ui/roster/" + account->getName() + "/" + item->getName() + "/expanded", false); - } - break; - default: - break; - } } void Squawk::onRosterSelectionChanged(const QModelIndex& current, const QModelIndex& previous) diff --git a/ui/squawk.h b/ui/squawk.h index 19fc058..84e94a8 100644 --- a/ui/squawk.h +++ b/ui/squawk.h @@ -83,6 +83,8 @@ signals: void openConversation(const Models::Roster::ElId& id, const QString& resource = ""); void modifyAccountRequest(const QString&, const QMap&); + void itemExpanded (const QModelIndex& index); + void itemCollapsed (const QModelIndex& index); public: Models::Roster::ElId currentConversationId() const; @@ -127,7 +129,6 @@ private slots: void onComboboxActivated(int index); void onRosterItemDoubleClicked(const QModelIndex& item); void onRosterContextMenu(const QPoint& point); - void onItemCollepsed(const QModelIndex& index); void onRosterSelectionChanged(const QModelIndex& current, const QModelIndex& previous); void onContextAboutToHide(); void onAboutSquawkCalled(); diff --git a/ui/widgets/settings/pagegeneral.cpp b/ui/widgets/settings/pagegeneral.cpp index 39e155a..9e73574 100644 --- a/ui/widgets/settings/pagegeneral.cpp +++ b/ui/widgets/settings/pagegeneral.cpp @@ -100,7 +100,7 @@ void PageGeneral::onTrayChecked(int state) emit variableModified("tray", enabled); m_ui->hideTrayInput->setEnabled(enabled); if (!enabled) { - m_ui->hideTrayInput->setEnabled(false); + m_ui->hideTrayInput->setChecked(false); } }