Format all source with Clang and introduce lint workflow (#7364)

* Lint script with CLang format

* Use `-i` for `clang-format` and add more logging for lint scripts

* Apply LLVM CLang formatting

* Fixed comment

* Update ChangeLog

* Fixed bad return code logic

* Improve output for linters

* Fixed re-used var in clang lint

* Fixed include order for tests and use `#if 0` instead of commenting out code

* Use full Clang format dump

* Dump Ubuntu Clang format

* Dump Clang format from Debian

* Dumped from: clang-format version 18.1.8

* Revert "Dumped from: clang-format version 18.1.8"

This reverts commit b9bbda2995bb0b4b65baf14afebb0361ec64e644.

* Remove BasedOnStyle

* Restore base Clang format file

* Use clang-format from pip

* Apply Clang format 18 style

* Add clang_format deps

* Fixed include order issues and *some* accidental includes
This commit is contained in:
Nick Bolton 2024-07-02 20:07:06 +01:00 committed by GitHub
parent f2cc964b3d
commit 37bb0f989e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
664 changed files with 62656 additions and 70427 deletions

11
.clang-format Normal file
View file

@ -0,0 +1,11 @@
# Important: Use the same version of clang-format as our linter, which is:
#
# $ ./scripts/install_deps.py --only-python
# $ ./build/python/bin/clang-format --version
#
# Warning: If you use a different version, the formatting will be different.
#
# To install a specific version of clang-format, use pip:
# $ pip install clang-format==<version>
BasedOnStyle: LLVM

View file

@ -1,23 +0,0 @@
# Runs
name: "Lint CMake files"
on:
pull_request:
jobs:
lint-cmake-files:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: |
python3 -m venv build/python
source build/python/bin/activate
pip install cmake_format pyyaml
- name: Lint CMake files
run: ./scripts/lint_cmake_files.py

26
.github/workflows/lint-source.yml vendored Normal file
View file

@ -0,0 +1,26 @@
# Lints CMake config and C++ source code.
name: "Lint source code"
on:
pull_request:
jobs:
lint-cmake-files:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: |
python3 -m venv build/python
source build/python/bin/activate
pip install pyyaml cmake_format clang_format
- name: Linting with CMake formatter
run: ./scripts/lint_cmake.py
- name: Linting with Clang format
run: ./scripts/lint_clang.py

View file

@ -38,6 +38,7 @@ Enhancements:
- #7360 Re-implement packaging for GitHub workflows (Windows) - #7360 Re-implement packaging for GitHub workflows (Windows)
- #7361 Re-implement packaging for GitHub workflows (Linux) - #7361 Re-implement packaging for GitHub workflows (Linux)
- #7363 Schedule CI daily at 5am to detect code rot early - #7363 Schedule CI daily at 5am to detect code rot early
- #7364 Format all source with Clang and introduce lint workflow
# 1.14.6 # 1.14.6

View file

@ -13,6 +13,11 @@ def main():
parser.add_argument( parser.add_argument(
"--only", type=str, help="Only install the specified dependency" "--only", type=str, help="Only install the specified dependency"
) )
parser.add_argument(
"--only-python",
action="store_true",
help="Only install Python dependencies",
)
args = parser.parse_args() args = parser.parse_args()
env.ensure_dependencies() env.ensure_dependencies()
@ -20,6 +25,7 @@ def main():
env.install_requirements() env.install_requirements()
error = False error = False
if not args.only_python:
try: try:
deps = Dependencies(args.only) deps = Dependencies(args.only)
deps.install() deps.install()

14
scripts/lib/fs.py Normal file
View file

@ -0,0 +1,14 @@
import os, fnmatch
def find_files(search_dirs, include_files, exclude_dirs=[]):
"""Recursively find files, excluding specified directories"""
matches = []
for dir in search_dirs:
for root, dirnames, filenames in os.walk(dir):
dirnames[:] = [d for d in dirnames if d not in exclude_dirs]
for pattern in include_files:
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches

57
scripts/lint_clang.py Executable file
View file

@ -0,0 +1,57 @@
#!/usr/bin/env python3
import argparse, sys
import lib.fs as fs
import lib.env as env
include_files = [
"*.h",
"*.c",
"*.hpp",
"*.cpp",
]
dirs = ["src"]
def main():
"""
Cross-platform equivalent of using find and xargs with clang-format.
Lints by performing a dry run (--dry-run) which fails when formatting is needed.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--format",
action="store_true",
help="In-place format all files",
)
args = parser.parse_args()
env.ensure_in_venv(__file__)
from clang_format import clang_format # type: ignore
cmd_args = ["-i"] if args.format else ["--dry-run", "--Werror"]
files_recursive = fs.find_files(dirs, include_files)
if args.format:
print("Formatting files with Clang formatter:")
else:
print("Checking files with Clang formatter:")
for file in files_recursive:
print(file)
if files_recursive:
sys.argv = [""] + cmd_args + files_recursive
result = clang_format()
if result == 0:
print("Clang lint passed")
sys.exit(result)
else:
print("No files for Clang to process", file=sys.stderr)
sys.exit(0)
if __name__ == "__main__":
main()

59
scripts/lint_cmake.py Executable file
View file

@ -0,0 +1,59 @@
#!/usr/bin/env python3
import sys, argparse
import lib.env as env
import lib.fs as fs
include_files = [
"*.cmake",
"CMakeLists.txt",
]
exclude_dirs = [
"ext",
"build",
]
def main():
"""
Cross-platform equivalent of using find and xargs with cmake-format.
Lints by performing a dry run (--check) which fails when formatting is needed.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--format",
action="store_true",
help="In-place format all files",
)
args = parser.parse_args()
env.ensure_in_venv(__file__)
from cmakelang.format.__main__ import main as cmake_format_main
cmd_args = ["--in-place"] if args.format else ["--check"]
files_recursive = fs.find_files(".", include_files, exclude_dirs)
if args.format:
print("Formatting files with CMake formatter:")
else:
print("Checking files with CMake formatter:")
for file in files_recursive:
print(file)
if files_recursive:
sys.argv = [""] + cmd_args + files_recursive
result = cmake_format_main()
if result == 0:
print("CMake lint passed")
sys.exit(result)
else:
print("No CMake files found to process.", file=sys.stderr)
sys.exit(0)
if __name__ == "__main__":
main()

View file

@ -1,51 +0,0 @@
#!/usr/bin/env python3
import sys, os, argparse, fnmatch
import lib.env as env
include_files = [
"*.cmake",
"CMakeLists.txt",
]
exclude_dirs = [
"ext",
"build",
]
def find_files(base_dir, include_files, exclude_dirs):
"""Recursively find files, excluding specified directories"""
matches = []
for root, dirnames, filenames in os.walk(base_dir):
dirnames[:] = [d for d in dirnames if d not in exclude_dirs]
for pattern in include_files:
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--format", action="store_true", help="Formats all CMake files")
args = parser.parse_args()
# important: load venv before loading modules that install deps.
env.ensure_in_venv(__file__)
from cmakelang.format.__main__ import main as cmake_format_main
new_args = ["--in-place"] if args.format else ["--check"]
files_recursive = find_files(".", include_files, exclude_dirs)
if files_recursive:
sys.argv = [""] + new_args + files_recursive
sys.exit(cmake_format_main())
else:
print("No CMake files found to process.")
sys.exit(0)
if __name__ == "__main__":
main()

View file

@ -1,4 +1,5 @@
cmake_format cmake_format
clang-format
python-dotenv python-dotenv
pyyaml pyyaml
dmgbuild; sys_platform == 'darwin' dmgbuild; sys_platform == 'darwin'

View file

@ -15,33 +15,35 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <iostream> #include "arch/Arch.h"
#include "base/EventQueue.h"
#include "base/Log.h"
#include "synergy/ClientApp.h" #include "synergy/ClientApp.h"
#include "synergy/ServerApp.h" #include "synergy/ServerApp.h"
#include "arch/Arch.h" #include <iostream>
#include "base/Log.h"
#include "base/EventQueue.h"
void showHelp() #if SYSAPI_WIN32
{ #include "arch/win32/ArchMiscWindows.h"
std::cout<<"Usage: synergy-core <server | client> [...options]"<<std::endl; #endif
std::cout<<"server - start as a server (synergys)"<<std::endl;
std::cout<<"client - start as a client (synergyc)"<<std::endl; void showHelp() {
std::cout<<"use synergy-core <server|client> --help for more information."<<std::endl; std::cout << "Usage: synergy-core <server | client> [...options]"
<< std::endl;
std::cout << "server - start as a server (synergys)" << std::endl;
std::cout << "client - start as a client (synergyc)" << std::endl;
std::cout << "use synergy-core <server|client> --help for more information."
<< std::endl;
} }
bool isServer(int argc, char** argv) bool isServer(int argc, char **argv) {
{
return (argc > 1 && argv[1] == std::string("server")); return (argc > 1 && argv[1] == std::string("server"));
} }
bool isClient(int argc, char** argv) bool isClient(int argc, char **argv) {
{
return (argc > 1 && argv[1] == std::string("client")); return (argc > 1 && argv[1] == std::string("client"));
} }
int main(int argc, char** argv) int main(int argc, char **argv) {
{
#if SYSAPI_WIN32 #if SYSAPI_WIN32
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif #endif
@ -55,12 +57,10 @@ int main(int argc, char** argv)
if (isServer(argc, argv)) { if (isServer(argc, argv)) {
ServerApp app(&events, nullptr); ServerApp app(&events, nullptr);
return app.run(argc, argv); return app.run(argc, argv);
} } else if (isClient(argc, argv)) {
else if (isClient(argc, argv)) {
ClientApp app(&events, nullptr); ClientApp app(&events, nullptr);
return app.run(argc, argv); return app.run(argc, argv);
} } else {
else {
showHelp(); showHelp();
} }

View file

@ -18,37 +18,30 @@
#include "MSWindowsClientTaskBarReceiver.h" #include "MSWindowsClientTaskBarReceiver.h"
#include "resource.h" #include "arch/Arch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/win32/ArchTaskBarWindows.h"
#include "base/EventQueue.h"
#include "base/EventTypes.h"
#include "base/log_outputters.h"
#include "client/Client.h" #include "client/Client.h"
#include "platform/MSWindowsClipboard.h" #include "platform/MSWindowsClipboard.h"
#include "platform/MSWindowsScreen.h" #include "platform/MSWindowsScreen.h"
#include "arch/win32/ArchTaskBarWindows.h" #include "resource.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/Arch.h"
#include "base/EventQueue.h"
#include "base/log_outputters.h"
#include "base/EventTypes.h"
// //
// MSWindowsClientTaskBarReceiver // MSWindowsClientTaskBarReceiver
// //
const UINT MSWindowsClientTaskBarReceiver::s_stateToIconID[kMaxState] = const UINT MSWindowsClientTaskBarReceiver::s_stateToIconID[kMaxState] = {
{ IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED,
IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_CONNECTED, IDI_TASKBAR_CONNECTED};
IDI_TASKBAR_NOT_WORKING,
IDI_TASKBAR_NOT_CONNECTED,
IDI_TASKBAR_NOT_CONNECTED,
IDI_TASKBAR_CONNECTED
};
MSWindowsClientTaskBarReceiver::MSWindowsClientTaskBarReceiver( MSWindowsClientTaskBarReceiver::MSWindowsClientTaskBarReceiver(
HINSTANCE appInstance, const BufferedLogOutputter* logBuffer, IEventQueue* events) : HINSTANCE appInstance, const BufferedLogOutputter *logBuffer,
ClientTaskBarReceiver(events), IEventQueue *events)
m_appInstance(appInstance), : ClientTaskBarReceiver(events), m_appInstance(appInstance), m_window(NULL),
m_window(NULL), m_logBuffer(logBuffer) {
m_logBuffer(logBuffer)
{
for (UInt32 i = 0; i < kMaxState; ++i) { for (UInt32 i = 0; i < kMaxState; ++i) {
m_icon[i] = loadIcon(s_stateToIconID[i]); m_icon[i] = loadIcon(s_stateToIconID[i]);
} }
@ -63,14 +56,9 @@ MSWindowsClientTaskBarReceiver::MSWindowsClientTaskBarReceiver(
ARCH->addReceiver(this); ARCH->addReceiver(this);
} }
MSWindowsClientTaskBarReceiver::~MSWindowsClientTaskBarReceiver() MSWindowsClientTaskBarReceiver::~MSWindowsClientTaskBarReceiver() { cleanup(); }
{
cleanup();
}
void void MSWindowsClientTaskBarReceiver::cleanup() {
MSWindowsClientTaskBarReceiver::cleanup()
{
ARCH->removeReceiver(this); ARCH->removeReceiver(this);
for (UInt32 i = 0; i < kMaxState; ++i) { for (UInt32 i = 0; i < kMaxState; ++i) {
deleteIcon(m_icon[i]); deleteIcon(m_icon[i]);
@ -79,9 +67,7 @@ MSWindowsClientTaskBarReceiver::cleanup()
destroyWindow(); destroyWindow();
} }
void void MSWindowsClientTaskBarReceiver::showStatus() {
MSWindowsClientTaskBarReceiver::showStatus()
{
// create the window // create the window
createWindow(); createWindow();
@ -120,8 +106,7 @@ MSWindowsClientTaskBarReceiver::showStatus()
} }
if (x + ww - fw > sw) { if (x + ww - fw > sw) {
x -= ww - fw; x -= ww - fw;
} } else {
else {
x -= fw; x -= fw;
} }
if (x < 0) { if (x < 0) {
@ -129,21 +114,17 @@ MSWindowsClientTaskBarReceiver::showStatus()
} }
if (y + wh - fh > sh) { if (y + wh - fh > sh) {
y -= wh - fh; y -= wh - fh;
} } else {
else {
y -= fh; y -= fh;
} }
if (y < 0) { if (y < 0) {
y = 0; y = 0;
} }
SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh, SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh, SWP_SHOWWINDOW);
SWP_SHOWWINDOW);
} }
} }
void void MSWindowsClientTaskBarReceiver::runMenu(int x, int y) {
MSWindowsClientTaskBarReceiver::runMenu(int x, int y)
{
// do popup menu. we need a window to pass to TrackPopupMenu(). // do popup menu. we need a window to pass to TrackPopupMenu().
// the SetForegroundWindow() and SendMessage() calls around // the SetForegroundWindow() and SendMessage() calls around
// TrackPopupMenu() are to get the menu to be dismissed when // TrackPopupMenu() are to get the menu to be dismissed when
@ -154,14 +135,11 @@ MSWindowsClientTaskBarReceiver::runMenu(int x, int y)
HMENU menu = GetSubMenu(m_menu, 0); HMENU menu = GetSubMenu(m_menu, 0);
SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE); SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
HMENU logLevelMenu = GetSubMenu(menu, 3); HMENU logLevelMenu = GetSubMenu(menu, 3);
CheckMenuRadioItem(logLevelMenu, 0, 6, CheckMenuRadioItem(logLevelMenu, 0, 6, CLOG->getFilter() - kERROR,
CLOG->getFilter() - kERROR, MF_BYPOSITION); MF_BYPOSITION);
int n = TrackPopupMenu(menu, int n = TrackPopupMenu(
TPM_NONOTIFY | menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x,
TPM_RETURNCMD | y, 0, m_window, NULL);
TPM_LEFTBUTTON |
TPM_RIGHTBUTTON,
x, y, 0, m_window, NULL);
SendMessage(m_window, WM_NULL, 0, 0); SendMessage(m_window, WM_NULL, 0, 0);
// perform the requested operation // perform the requested operation
@ -212,21 +190,14 @@ MSWindowsClientTaskBarReceiver::runMenu(int x, int y)
} }
} }
void void MSWindowsClientTaskBarReceiver::primaryAction() { showStatus(); }
MSWindowsClientTaskBarReceiver::primaryAction()
{
showStatus();
}
const IArchTaskBarReceiver::Icon const IArchTaskBarReceiver::Icon
MSWindowsClientTaskBarReceiver::getIcon() const MSWindowsClientTaskBarReceiver::getIcon() const {
{
return static_cast<Icon>(m_icon[getStatus()]); return static_cast<Icon>(m_icon[getStatus()]);
} }
void void MSWindowsClientTaskBarReceiver::copyLog() const {
MSWindowsClientTaskBarReceiver::copyLog() const
{
if (m_logBuffer != NULL) { if (m_logBuffer != NULL) {
// collect log buffer // collect log buffer
String data; String data;
@ -247,48 +218,36 @@ MSWindowsClientTaskBarReceiver::copyLog() const
} }
} }
void void MSWindowsClientTaskBarReceiver::onStatusChanged() {
MSWindowsClientTaskBarReceiver::onStatusChanged()
{
if (IsWindowVisible(m_window)) { if (IsWindowVisible(m_window)) {
showStatus(); showStatus();
} }
} }
HICON HICON
MSWindowsClientTaskBarReceiver::loadIcon(UINT id) MSWindowsClientTaskBarReceiver::loadIcon(UINT id) {
{ HANDLE icon = LoadImage(m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0,
HANDLE icon = LoadImage(m_appInstance,
MAKEINTRESOURCE(id),
IMAGE_ICON,
0, 0,
LR_DEFAULTCOLOR); LR_DEFAULTCOLOR);
return static_cast<HICON>(icon); return static_cast<HICON>(icon);
} }
void void MSWindowsClientTaskBarReceiver::deleteIcon(HICON icon) {
MSWindowsClientTaskBarReceiver::deleteIcon(HICON icon)
{
if (icon != NULL) { if (icon != NULL) {
DestroyIcon(icon); DestroyIcon(icon);
} }
} }
void void MSWindowsClientTaskBarReceiver::createWindow() {
MSWindowsClientTaskBarReceiver::createWindow()
{
// ignore if already created // ignore if already created
if (m_window != NULL) { if (m_window != NULL) {
return; return;
} }
// get the status dialog // get the status dialog
m_window = CreateDialogParam(m_appInstance, m_window = CreateDialogParam(
MAKEINTRESOURCE(IDD_TASKBAR_STATUS), m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL,
NULL,
(DLGPROC)&MSWindowsClientTaskBarReceiver::staticDlgProc, (DLGPROC)&MSWindowsClientTaskBarReceiver::staticDlgProc,
reinterpret_cast<LPARAM>( reinterpret_cast<LPARAM>(static_cast<void *>(this)));
static_cast<void*>(this)));
// window should appear on top of everything, including (especially) // window should appear on top of everything, including (especially)
// the task bar. // the task bar.
@ -300,9 +259,7 @@ MSWindowsClientTaskBarReceiver::createWindow()
ArchTaskBarWindows::addDialog(m_window); ArchTaskBarWindows::addDialog(m_window);
} }
void void MSWindowsClientTaskBarReceiver::destroyWindow() {
MSWindowsClientTaskBarReceiver::destroyWindow()
{
if (m_window != NULL) { if (m_window != NULL) {
ArchTaskBarWindows::removeDialog(m_window); ArchTaskBarWindows::removeDialog(m_window);
DestroyWindow(m_window); DestroyWindow(m_window);
@ -310,10 +267,8 @@ MSWindowsClientTaskBarReceiver::destroyWindow()
} }
} }
BOOL BOOL MSWindowsClientTaskBarReceiver::dlgProc(HWND hwnd, UINT msg, WPARAM wParam,
MSWindowsClientTaskBarReceiver::dlgProc(HWND hwnd, LPARAM) {
UINT msg, WPARAM wParam, LPARAM)
{
switch (msg) { switch (msg) {
case WM_INITDIALOG: case WM_INITDIALOG:
// use default focus // use default focus
@ -329,47 +284,41 @@ MSWindowsClientTaskBarReceiver::dlgProc(HWND hwnd,
return FALSE; return FALSE;
} }
BOOL CALLBACK BOOL CALLBACK MSWindowsClientTaskBarReceiver::staticDlgProc(HWND hwnd, UINT msg,
MSWindowsClientTaskBarReceiver::staticDlgProc(HWND hwnd, WPARAM wParam,
UINT msg, WPARAM wParam, LPARAM lParam) LPARAM lParam) {
{
// if msg is WM_INITDIALOG, extract the MSWindowsClientTaskBarReceiver* // if msg is WM_INITDIALOG, extract the MSWindowsClientTaskBarReceiver*
// and put it in the extra window data then forward the call. // and put it in the extra window data then forward the call.
MSWindowsClientTaskBarReceiver* self = NULL; MSWindowsClientTaskBarReceiver *self = NULL;
if (msg == WM_INITDIALOG) { if (msg == WM_INITDIALOG) {
self = static_cast<MSWindowsClientTaskBarReceiver*>( self = static_cast<MSWindowsClientTaskBarReceiver *>(
reinterpret_cast<void*>(lParam)); reinterpret_cast<void *>(lParam));
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) lParam); SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)lParam);
} } else {
else {
// get the extra window data and forward the call // get the extra window data and forward the call
LONG_PTR data = GetWindowLongPtr(hwnd, GWLP_USERDATA); LONG_PTR data = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (data != 0) { if (data != 0) {
self = (MSWindowsClientTaskBarReceiver*) data; self = (MSWindowsClientTaskBarReceiver *)data;
} }
} }
// forward the message // forward the message
if (self != NULL) { if (self != NULL) {
return self->dlgProc(hwnd, msg, wParam, lParam); return self->dlgProc(hwnd, msg, wParam, lParam);
} } else {
else {
return (msg == WM_INITDIALOG) ? TRUE : FALSE; return (msg == WM_INITDIALOG) ? TRUE : FALSE;
} }
} }
IArchTaskBarReceiver* IArchTaskBarReceiver *
createTaskBarReceiver(const BufferedLogOutputter* logBuffer, IEventQueue* events) createTaskBarReceiver(const BufferedLogOutputter *logBuffer,
{ IEventQueue *events) {
ArchMiscWindows::setIcons( ArchMiscWindows::setIcons((HICON)LoadImage(ArchMiscWindows::instanceWin32(),
MAKEINTRESOURCE(IDI_SYNERGY),
IMAGE_ICON, 32, 32, LR_SHARED),
(HICON)LoadImage(ArchMiscWindows::instanceWin32(), (HICON)LoadImage(ArchMiscWindows::instanceWin32(),
MAKEINTRESOURCE(IDI_SYNERGY), MAKEINTRESOURCE(IDI_SYNERGY),
IMAGE_ICON, IMAGE_ICON, 16, 16, LR_SHARED));
32, 32, LR_SHARED),
(HICON)LoadImage(ArchMiscWindows::instanceWin32(),
MAKEINTRESOURCE(IDI_SYNERGY),
IMAGE_ICON,
16, 16, LR_SHARED));
return new MSWindowsClientTaskBarReceiver( return new MSWindowsClientTaskBarReceiver(
MSWindowsScreen::getWindowInstance(), logBuffer, events); MSWindowsScreen::getWindowInstance(), logBuffer, events);

View file

@ -29,7 +29,8 @@ class IEventQueue;
//! Implementation of ClientTaskBarReceiver for Microsoft Windows //! Implementation of ClientTaskBarReceiver for Microsoft Windows
class MSWindowsClientTaskBarReceiver : public ClientTaskBarReceiver { class MSWindowsClientTaskBarReceiver : public ClientTaskBarReceiver {
public: public:
MSWindowsClientTaskBarReceiver(HINSTANCE, const BufferedLogOutputter*, IEventQueue* events); MSWindowsClientTaskBarReceiver(HINSTANCE, const BufferedLogOutputter *,
IEventQueue *events);
virtual ~MSWindowsClientTaskBarReceiver(); virtual ~MSWindowsClientTaskBarReceiver();
// IArchTaskBarReceiver overrides // IArchTaskBarReceiver overrides
@ -51,18 +52,16 @@ private:
void createWindow(); void createWindow();
void destroyWindow(); void destroyWindow();
BOOL dlgProc(HWND hwnd, BOOL dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
UINT msg, WPARAM wParam, LPARAM lParam); static BOOL CALLBACK staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam,
static BOOL CALLBACK LPARAM lParam);
staticDlgProc(HWND hwnd,
UINT msg, WPARAM wParam, LPARAM lParam);
private: private:
HINSTANCE m_appInstance; HINSTANCE m_appInstance;
HWND m_window; HWND m_window;
HMENU m_menu; HMENU m_menu;
HICON m_icon[kMaxState]; HICON m_icon[kMaxState];
const BufferedLogOutputter* m_logBuffer; const BufferedLogOutputter *m_logBuffer;
static const UINT s_stateToIconID[]; static const UINT s_stateToIconID[];
}; };

View file

@ -23,47 +23,35 @@
// OSXClientTaskBarReceiver // OSXClientTaskBarReceiver
// //
OSXClientTaskBarReceiver::OSXClientTaskBarReceiver( OSXClientTaskBarReceiver::OSXClientTaskBarReceiver(const BufferedLogOutputter *,
const BufferedLogOutputter*, IEventQueue *events)
IEventQueue* events) : : ClientTaskBarReceiver(events) {
ClientTaskBarReceiver(events)
{
// add ourself to the task bar // add ourself to the task bar
ARCH->addReceiver(this); ARCH->addReceiver(this);
} }
OSXClientTaskBarReceiver::~OSXClientTaskBarReceiver() OSXClientTaskBarReceiver::~OSXClientTaskBarReceiver() {
{
ARCH->removeReceiver(this); ARCH->removeReceiver(this);
} }
void void OSXClientTaskBarReceiver::showStatus() {
OSXClientTaskBarReceiver::showStatus()
{
// do nothing // do nothing
} }
void void OSXClientTaskBarReceiver::runMenu(int, int) {
OSXClientTaskBarReceiver::runMenu(int, int)
{
// do nothing // do nothing
} }
void void OSXClientTaskBarReceiver::primaryAction() {
OSXClientTaskBarReceiver::primaryAction()
{
// do nothing // do nothing
} }
const IArchTaskBarReceiver::Icon const IArchTaskBarReceiver::Icon OSXClientTaskBarReceiver::getIcon() const {
OSXClientTaskBarReceiver::getIcon() const
{
return NULL; return NULL;
} }
IArchTaskBarReceiver* IArchTaskBarReceiver *
createTaskBarReceiver(const BufferedLogOutputter* logBuffer, IEventQueue* events) createTaskBarReceiver(const BufferedLogOutputter *logBuffer,
{ IEventQueue *events) {
return new OSXClientTaskBarReceiver(logBuffer, events); return new OSXClientTaskBarReceiver(logBuffer, events);
} }

View file

@ -26,7 +26,7 @@ class IEventQueue;
//! Implementation of ClientTaskBarReceiver for OS X //! Implementation of ClientTaskBarReceiver for OS X
class OSXClientTaskBarReceiver : public ClientTaskBarReceiver { class OSXClientTaskBarReceiver : public ClientTaskBarReceiver {
public: public:
OSXClientTaskBarReceiver(const BufferedLogOutputter*, IEventQueue* events); OSXClientTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events);
virtual ~OSXClientTaskBarReceiver(); virtual ~OSXClientTaskBarReceiver();
// IArchTaskBarReceiver overrides // IArchTaskBarReceiver overrides

View file

@ -24,45 +24,35 @@
// //
CXWindowsClientTaskBarReceiver::CXWindowsClientTaskBarReceiver( CXWindowsClientTaskBarReceiver::CXWindowsClientTaskBarReceiver(
const BufferedLogOutputter*, const BufferedLogOutputter *, IEventQueue *events)
IEventQueue* events) : : ClientTaskBarReceiver(events) {
ClientTaskBarReceiver(events)
{
// add ourself to the task bar // add ourself to the task bar
ARCH->addReceiver(this); ARCH->addReceiver(this);
} }
CXWindowsClientTaskBarReceiver::~CXWindowsClientTaskBarReceiver() CXWindowsClientTaskBarReceiver::~CXWindowsClientTaskBarReceiver() {
{
ARCH->removeReceiver(this); ARCH->removeReceiver(this);
} }
void void CXWindowsClientTaskBarReceiver::showStatus() {
CXWindowsClientTaskBarReceiver::showStatus()
{
// do nothing // do nothing
} }
void void CXWindowsClientTaskBarReceiver::runMenu(int, int) {
CXWindowsClientTaskBarReceiver::runMenu(int, int)
{
// do nothing // do nothing
} }
void void CXWindowsClientTaskBarReceiver::primaryAction() {
CXWindowsClientTaskBarReceiver::primaryAction()
{
// do nothing // do nothing
} }
const IArchTaskBarReceiver::Icon const IArchTaskBarReceiver::Icon
CXWindowsClientTaskBarReceiver::getIcon() const CXWindowsClientTaskBarReceiver::getIcon() const {
{
return NULL; return NULL;
} }
IArchTaskBarReceiver* IArchTaskBarReceiver *
createTaskBarReceiver(const BufferedLogOutputter* logBuffer, IEventQueue* events) createTaskBarReceiver(const BufferedLogOutputter *logBuffer,
{ IEventQueue *events) {
return new CXWindowsClientTaskBarReceiver(logBuffer, events); return new CXWindowsClientTaskBarReceiver(logBuffer, events);
} }

View file

@ -26,14 +26,17 @@ class IEventQueue;
//! Implementation of ClientTaskBarReceiver for X Windows //! Implementation of ClientTaskBarReceiver for X Windows
class CXWindowsClientTaskBarReceiver : public ClientTaskBarReceiver { class CXWindowsClientTaskBarReceiver : public ClientTaskBarReceiver {
public: public:
CXWindowsClientTaskBarReceiver( CXWindowsClientTaskBarReceiver(const BufferedLogOutputter *,
const BufferedLogOutputter*, IEventQueue* events); IEventQueue *events);
CXWindowsClientTaskBarReceiver(const CXWindowsClientTaskBarReceiver &) =delete; CXWindowsClientTaskBarReceiver(const CXWindowsClientTaskBarReceiver &) =
CXWindowsClientTaskBarReceiver(CXWindowsClientTaskBarReceiver &&) =delete; delete;
CXWindowsClientTaskBarReceiver(CXWindowsClientTaskBarReceiver &&) = delete;
virtual ~CXWindowsClientTaskBarReceiver(); virtual ~CXWindowsClientTaskBarReceiver();
CXWindowsClientTaskBarReceiver& operator=(const CXWindowsClientTaskBarReceiver &) =delete; CXWindowsClientTaskBarReceiver &
CXWindowsClientTaskBarReceiver& operator=(CXWindowsClientTaskBarReceiver &&) =delete; operator=(const CXWindowsClientTaskBarReceiver &) = delete;
CXWindowsClientTaskBarReceiver &
operator=(CXWindowsClientTaskBarReceiver &&) = delete;
// IArchTaskBarReceiver overrides // IArchTaskBarReceiver overrides
virtual void showStatus(); virtual void showStatus();

View file

@ -16,10 +16,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "synergy/ClientApp.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/Log.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/Log.h"
#include "synergy/ClientApp.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
#if WINAPI_MSWINDOWS #if WINAPI_MSWINDOWS
#include "MSWindowsClientTaskBarReceiver.h" #include "MSWindowsClientTaskBarReceiver.h"
@ -31,9 +35,7 @@
#error Platform not supported. #error Platform not supported.
#endif #endif
int int main(int argc, char **argv) {
main(int argc, char** argv)
{
#if SYSAPI_WIN32 #if SYSAPI_WIN32
// record window instance for tray icon, etc // record window instance for tray icon, etc
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));

View file

@ -22,9 +22,7 @@
#ifdef SYSAPI_UNIX #ifdef SYSAPI_UNIX
int int main(int argc, char **argv) {
main(int argc, char** argv)
{
DaemonApp app; DaemonApp app;
return app.run(argc, argv); return app.run(argc, argv);
} }
@ -34,9 +32,7 @@ main(int argc, char** argv)
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <Windows.h> #include <Windows.h>
int WINAPI int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
DaemonApp app; DaemonApp app;
return app.run(__argc, __argv); return app.run(__argc, __argv);
} }

View file

@ -18,38 +18,31 @@
#include "MSWindowsServerTaskBarReceiver.h" #include "MSWindowsServerTaskBarReceiver.h"
#include "resource.h"
#include "server/Server.h"
#include "platform/MSWindowsClipboard.h"
#include "platform/MSWindowsScreen.h"
#include "arch/win32/ArchTaskBarWindows.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/win32/ArchTaskBarWindows.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/EventTypes.h"
#include "base/IEventQueue.h" #include "base/IEventQueue.h"
#include "base/log_outputters.h" #include "base/log_outputters.h"
#include "base/EventTypes.h" #include "platform/MSWindowsClipboard.h"
#include "platform/MSWindowsScreen.h"
#include "resource.h"
#include "server/Server.h"
// //
// MSWindowsServerTaskBarReceiver // MSWindowsServerTaskBarReceiver
// //
const UINT MSWindowsServerTaskBarReceiver::s_stateToIconID[kMaxState] = const UINT MSWindowsServerTaskBarReceiver::s_stateToIconID[kMaxState] = {
{ IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED,
IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_CONNECTED};
IDI_TASKBAR_NOT_WORKING,
IDI_TASKBAR_NOT_CONNECTED,
IDI_TASKBAR_CONNECTED
};
MSWindowsServerTaskBarReceiver::MSWindowsServerTaskBarReceiver( MSWindowsServerTaskBarReceiver::MSWindowsServerTaskBarReceiver(
HINSTANCE appInstance, const BufferedLogOutputter* logBuffer, IEventQueue* events) : HINSTANCE appInstance, const BufferedLogOutputter *logBuffer,
ServerTaskBarReceiver(events), IEventQueue *events)
m_events(events), : ServerTaskBarReceiver(events), m_events(events),
m_appInstance(appInstance), m_appInstance(appInstance), m_window(NULL), m_logBuffer(logBuffer) {
m_window(NULL),
m_logBuffer(logBuffer)
{
for (UInt32 i = 0; i < kMaxState; ++i) { for (UInt32 i = 0; i < kMaxState; ++i) {
m_icon[i] = loadIcon(s_stateToIconID[i]); m_icon[i] = loadIcon(s_stateToIconID[i]);
} }
@ -64,9 +57,7 @@ MSWindowsServerTaskBarReceiver::MSWindowsServerTaskBarReceiver(
ARCH->addReceiver(this); ARCH->addReceiver(this);
} }
void void MSWindowsServerTaskBarReceiver::cleanup() {
MSWindowsServerTaskBarReceiver::cleanup()
{
ARCH->removeReceiver(this); ARCH->removeReceiver(this);
for (UInt32 i = 0; i < kMaxState; ++i) { for (UInt32 i = 0; i < kMaxState; ++i) {
deleteIcon(m_icon[i]); deleteIcon(m_icon[i]);
@ -75,14 +66,9 @@ MSWindowsServerTaskBarReceiver::cleanup()
destroyWindow(); destroyWindow();
} }
MSWindowsServerTaskBarReceiver::~MSWindowsServerTaskBarReceiver() MSWindowsServerTaskBarReceiver::~MSWindowsServerTaskBarReceiver() { cleanup(); }
{
cleanup();
}
void void MSWindowsServerTaskBarReceiver::showStatus() {
MSWindowsServerTaskBarReceiver::showStatus()
{
// create the window // create the window
createWindow(); createWindow();
@ -93,7 +79,7 @@ MSWindowsServerTaskBarReceiver::showStatus()
std::string status = getToolTip(); std::string status = getToolTip();
// get the connect clients, if any // get the connect clients, if any
const Clients& clients = getClients(); const Clients &clients = getClients();
// done getting status // done getting status
unlock(); unlock();
@ -104,12 +90,11 @@ MSWindowsServerTaskBarReceiver::showStatus()
child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_CLIENTS); child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_CLIENTS);
SendMessage(child, LB_RESETCONTENT, 0, 0); SendMessage(child, LB_RESETCONTENT, 0, 0);
for (Clients::const_iterator index = clients.begin(); for (Clients::const_iterator index = clients.begin();
index != clients.end(); ) { index != clients.end();) {
const char* client = index->c_str(); const char *client = index->c_str();
if (++index == clients.end()) { if (++index == clients.end()) {
SendMessage(child, LB_ADDSTRING, 0, (LPARAM)client); SendMessage(child, LB_ADDSTRING, 0, (LPARAM)client);
} } else {
else {
SendMessage(child, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)client); SendMessage(child, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)client);
} }
} }
@ -136,8 +121,7 @@ MSWindowsServerTaskBarReceiver::showStatus()
} }
if (x + ww - fw > sw) { if (x + ww - fw > sw) {
x -= ww - fw; x -= ww - fw;
} } else {
else {
x -= fw; x -= fw;
} }
if (x < 0) { if (x < 0) {
@ -145,21 +129,17 @@ MSWindowsServerTaskBarReceiver::showStatus()
} }
if (y + wh - fh > sh) { if (y + wh - fh > sh) {
y -= wh - fh; y -= wh - fh;
} } else {
else {
y -= fh; y -= fh;
} }
if (y < 0) { if (y < 0) {
y = 0; y = 0;
} }
SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh, SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh, SWP_SHOWWINDOW);
SWP_SHOWWINDOW);
} }
} }
void void MSWindowsServerTaskBarReceiver::runMenu(int x, int y) {
MSWindowsServerTaskBarReceiver::runMenu(int x, int y)
{
// do popup menu. we need a window to pass to TrackPopupMenu(). // do popup menu. we need a window to pass to TrackPopupMenu().
// the SetForegroundWindow() and SendMessage() calls around // the SetForegroundWindow() and SendMessage() calls around
// TrackPopupMenu() are to get the menu to be dismissed when // TrackPopupMenu() are to get the menu to be dismissed when
@ -170,14 +150,11 @@ MSWindowsServerTaskBarReceiver::runMenu(int x, int y)
HMENU menu = GetSubMenu(m_menu, 0); HMENU menu = GetSubMenu(m_menu, 0);
SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE); SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
HMENU logLevelMenu = GetSubMenu(menu, 3); HMENU logLevelMenu = GetSubMenu(menu, 3);
CheckMenuRadioItem(logLevelMenu, 0, 6, CheckMenuRadioItem(logLevelMenu, 0, 6, CLOG->getFilter() - kERROR,
CLOG->getFilter() - kERROR, MF_BYPOSITION); MF_BYPOSITION);
int n = TrackPopupMenu(menu, int n = TrackPopupMenu(
TPM_NONOTIFY | menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x,
TPM_RETURNCMD | y, 0, m_window, NULL);
TPM_LEFTBUTTON |
TPM_RIGHTBUTTON,
x, y, 0, m_window, NULL);
SendMessage(m_window, WM_NULL, 0, 0); SendMessage(m_window, WM_NULL, 0, 0);
// perform the requested operation // perform the requested operation
@ -243,21 +220,14 @@ MSWindowsServerTaskBarReceiver::runMenu(int x, int y)
} }
} }
void void MSWindowsServerTaskBarReceiver::primaryAction() { showStatus(); }
MSWindowsServerTaskBarReceiver::primaryAction()
{
showStatus();
}
const IArchTaskBarReceiver::Icon const IArchTaskBarReceiver::Icon
MSWindowsServerTaskBarReceiver::getIcon() const MSWindowsServerTaskBarReceiver::getIcon() const {
{
return static_cast<Icon>(m_icon[getStatus()]); return static_cast<Icon>(m_icon[getStatus()]);
} }
void void MSWindowsServerTaskBarReceiver::copyLog() const {
MSWindowsServerTaskBarReceiver::copyLog() const
{
if (m_logBuffer != NULL) { if (m_logBuffer != NULL) {
// collect log buffer // collect log buffer
String data; String data;
@ -278,48 +248,36 @@ MSWindowsServerTaskBarReceiver::copyLog() const
} }
} }
void void MSWindowsServerTaskBarReceiver::onStatusChanged() {
MSWindowsServerTaskBarReceiver::onStatusChanged()
{
if (IsWindowVisible(m_window)) { if (IsWindowVisible(m_window)) {
showStatus(); showStatus();
} }
} }
HICON HICON
MSWindowsServerTaskBarReceiver::loadIcon(UINT id) MSWindowsServerTaskBarReceiver::loadIcon(UINT id) {
{ HANDLE icon = LoadImage(m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0,
HANDLE icon = LoadImage(m_appInstance,
MAKEINTRESOURCE(id),
IMAGE_ICON,
0, 0,
LR_DEFAULTCOLOR); LR_DEFAULTCOLOR);
return static_cast<HICON>(icon); return static_cast<HICON>(icon);
} }
void void MSWindowsServerTaskBarReceiver::deleteIcon(HICON icon) {
MSWindowsServerTaskBarReceiver::deleteIcon(HICON icon)
{
if (icon != NULL) { if (icon != NULL) {
DestroyIcon(icon); DestroyIcon(icon);
} }
} }
void void MSWindowsServerTaskBarReceiver::createWindow() {
MSWindowsServerTaskBarReceiver::createWindow()
{
// ignore if already created // ignore if already created
if (m_window != NULL) { if (m_window != NULL) {
return; return;
} }
// get the status dialog // get the status dialog
m_window = CreateDialogParam(m_appInstance, m_window = CreateDialogParam(
MAKEINTRESOURCE(IDD_TASKBAR_STATUS), m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL,
NULL,
(DLGPROC)&MSWindowsServerTaskBarReceiver::staticDlgProc, (DLGPROC)&MSWindowsServerTaskBarReceiver::staticDlgProc,
reinterpret_cast<LPARAM>( reinterpret_cast<LPARAM>(static_cast<void *>(this)));
static_cast<void*>(this)));
// window should appear on top of everything, including (especially) // window should appear on top of everything, including (especially)
// the task bar. // the task bar.
@ -331,9 +289,7 @@ MSWindowsServerTaskBarReceiver::createWindow()
ArchTaskBarWindows::addDialog(m_window); ArchTaskBarWindows::addDialog(m_window);
} }
void void MSWindowsServerTaskBarReceiver::destroyWindow() {
MSWindowsServerTaskBarReceiver::destroyWindow()
{
if (m_window != NULL) { if (m_window != NULL) {
ArchTaskBarWindows::removeDialog(m_window); ArchTaskBarWindows::removeDialog(m_window);
DestroyWindow(m_window); DestroyWindow(m_window);
@ -341,10 +297,8 @@ MSWindowsServerTaskBarReceiver::destroyWindow()
} }
} }
BOOL BOOL MSWindowsServerTaskBarReceiver::dlgProc(HWND hwnd, UINT msg, WPARAM wParam,
MSWindowsServerTaskBarReceiver::dlgProc(HWND hwnd, LPARAM) {
UINT msg, WPARAM wParam, LPARAM)
{
switch (msg) { switch (msg) {
case WM_INITDIALOG: case WM_INITDIALOG:
// use default focus // use default focus
@ -360,48 +314,42 @@ MSWindowsServerTaskBarReceiver::dlgProc(HWND hwnd,
return FALSE; return FALSE;
} }
BOOL CALLBACK BOOL CALLBACK MSWindowsServerTaskBarReceiver::staticDlgProc(HWND hwnd, UINT msg,
MSWindowsServerTaskBarReceiver::staticDlgProc(HWND hwnd, WPARAM wParam,
UINT msg, WPARAM wParam, LPARAM lParam) LPARAM lParam) {
{
// if msg is WM_INITDIALOG, extract the MSWindowsServerTaskBarReceiver* // if msg is WM_INITDIALOG, extract the MSWindowsServerTaskBarReceiver*
// and put it in the extra window data then forward the call. // and put it in the extra window data then forward the call.
MSWindowsServerTaskBarReceiver* self = NULL; MSWindowsServerTaskBarReceiver *self = NULL;
if (msg == WM_INITDIALOG) { if (msg == WM_INITDIALOG) {
self = static_cast<MSWindowsServerTaskBarReceiver*>( self = static_cast<MSWindowsServerTaskBarReceiver *>(
reinterpret_cast<void*>(lParam)); reinterpret_cast<void *>(lParam));
SetWindowLongPtr(hwnd, GWLP_USERDATA, lParam); SetWindowLongPtr(hwnd, GWLP_USERDATA, lParam);
} } else {
else {
// get the extra window data and forward the call // get the extra window data and forward the call
LONG_PTR data = GetWindowLongPtr(hwnd, GWLP_USERDATA); LONG_PTR data = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (data != 0) { if (data != 0) {
self = static_cast<MSWindowsServerTaskBarReceiver*>( self = static_cast<MSWindowsServerTaskBarReceiver *>(
reinterpret_cast<void*>(data)); reinterpret_cast<void *>(data));
} }
} }
// forward the message // forward the message
if (self != NULL) { if (self != NULL) {
return self->dlgProc(hwnd, msg, wParam, lParam); return self->dlgProc(hwnd, msg, wParam, lParam);
} } else {
else {
return (msg == WM_INITDIALOG) ? TRUE : FALSE; return (msg == WM_INITDIALOG) ? TRUE : FALSE;
} }
} }
IArchTaskBarReceiver* IArchTaskBarReceiver *
createTaskBarReceiver(const BufferedLogOutputter* logBuffer, IEventQueue* events) createTaskBarReceiver(const BufferedLogOutputter *logBuffer,
{ IEventQueue *events) {
ArchMiscWindows::setIcons( ArchMiscWindows::setIcons((HICON)LoadImage(ArchMiscWindows::instanceWin32(),
MAKEINTRESOURCE(IDI_SYNERGY),
IMAGE_ICON, 32, 32, LR_SHARED),
(HICON)LoadImage(ArchMiscWindows::instanceWin32(), (HICON)LoadImage(ArchMiscWindows::instanceWin32(),
MAKEINTRESOURCE(IDI_SYNERGY), MAKEINTRESOURCE(IDI_SYNERGY),
IMAGE_ICON, IMAGE_ICON, 16, 16, LR_SHARED));
32, 32, LR_SHARED),
(HICON)LoadImage(ArchMiscWindows::instanceWin32(),
MAKEINTRESOURCE(IDI_SYNERGY),
IMAGE_ICON,
16, 16, LR_SHARED));
return new MSWindowsServerTaskBarReceiver( return new MSWindowsServerTaskBarReceiver(
MSWindowsScreen::getWindowInstance(), logBuffer, events); MSWindowsScreen::getWindowInstance(), logBuffer, events);

View file

@ -29,7 +29,8 @@ class IEventQueue;
//! Implementation of ServerTaskBarReceiver for Microsoft Windows //! Implementation of ServerTaskBarReceiver for Microsoft Windows
class MSWindowsServerTaskBarReceiver : public ServerTaskBarReceiver { class MSWindowsServerTaskBarReceiver : public ServerTaskBarReceiver {
public: public:
MSWindowsServerTaskBarReceiver(HINSTANCE, const BufferedLogOutputter*, IEventQueue* events); MSWindowsServerTaskBarReceiver(HINSTANCE, const BufferedLogOutputter *,
IEventQueue *events);
virtual ~MSWindowsServerTaskBarReceiver(); virtual ~MSWindowsServerTaskBarReceiver();
// IArchTaskBarReceiver overrides // IArchTaskBarReceiver overrides
@ -51,19 +52,17 @@ private:
void createWindow(); void createWindow();
void destroyWindow(); void destroyWindow();
BOOL dlgProc(HWND hwnd, BOOL dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
UINT msg, WPARAM wParam, LPARAM lParam); static BOOL CALLBACK staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam,
static BOOL CALLBACK LPARAM lParam);
staticDlgProc(HWND hwnd,
UINT msg, WPARAM wParam, LPARAM lParam);
private: private:
HINSTANCE m_appInstance; HINSTANCE m_appInstance;
HWND m_window; HWND m_window;
HMENU m_menu; HMENU m_menu;
HICON m_icon[kMaxState]; HICON m_icon[kMaxState];
const BufferedLogOutputter* m_logBuffer; const BufferedLogOutputter *m_logBuffer;
IEventQueue* m_events; IEventQueue *m_events;
static const UINT s_stateToIconID[]; static const UINT s_stateToIconID[];
}; };

View file

@ -23,45 +23,35 @@
// OSXServerTaskBarReceiver // OSXServerTaskBarReceiver
// //
OSXServerTaskBarReceiver::OSXServerTaskBarReceiver( OSXServerTaskBarReceiver::OSXServerTaskBarReceiver(const BufferedLogOutputter *,
const BufferedLogOutputter*, IEventQueue* events) : IEventQueue *events)
ServerTaskBarReceiver(events) : ServerTaskBarReceiver(events) {
{
// add ourself to the task bar // add ourself to the task bar
ARCH->addReceiver(this); ARCH->addReceiver(this);
} }
OSXServerTaskBarReceiver::~OSXServerTaskBarReceiver() OSXServerTaskBarReceiver::~OSXServerTaskBarReceiver() {
{
ARCH->removeReceiver(this); ARCH->removeReceiver(this);
} }
void void OSXServerTaskBarReceiver::showStatus() {
OSXServerTaskBarReceiver::showStatus()
{
// do nothing // do nothing
} }
void void OSXServerTaskBarReceiver::runMenu(int, int) {
OSXServerTaskBarReceiver::runMenu(int, int)
{
// do nothing // do nothing
} }
void void OSXServerTaskBarReceiver::primaryAction() {
OSXServerTaskBarReceiver::primaryAction()
{
// do nothing // do nothing
} }
const IArchTaskBarReceiver::Icon const IArchTaskBarReceiver::Icon OSXServerTaskBarReceiver::getIcon() const {
OSXServerTaskBarReceiver::getIcon() const
{
return NULL; return NULL;
} }
IArchTaskBarReceiver* IArchTaskBarReceiver *
createTaskBarReceiver(const BufferedLogOutputter* logBuffer, IEventQueue* events) createTaskBarReceiver(const BufferedLogOutputter *logBuffer,
{ IEventQueue *events) {
return new OSXServerTaskBarReceiver(logBuffer, events); return new OSXServerTaskBarReceiver(logBuffer, events);
} }

View file

@ -25,7 +25,7 @@ class BufferedLogOutputter;
//! Implementation of ServerTaskBarReceiver for OS X //! Implementation of ServerTaskBarReceiver for OS X
class OSXServerTaskBarReceiver : public ServerTaskBarReceiver { class OSXServerTaskBarReceiver : public ServerTaskBarReceiver {
public: public:
OSXServerTaskBarReceiver(const BufferedLogOutputter*, IEventQueue* events); OSXServerTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events);
virtual ~OSXServerTaskBarReceiver(); virtual ~OSXServerTaskBarReceiver();
// IArchTaskBarReceiver overrides // IArchTaskBarReceiver overrides

View file

@ -24,44 +24,35 @@
// //
CXWindowsServerTaskBarReceiver::CXWindowsServerTaskBarReceiver( CXWindowsServerTaskBarReceiver::CXWindowsServerTaskBarReceiver(
const BufferedLogOutputter*, IEventQueue* events) : const BufferedLogOutputter *, IEventQueue *events)
ServerTaskBarReceiver(events) : ServerTaskBarReceiver(events) {
{
// add ourself to the task bar // add ourself to the task bar
ARCH->addReceiver(this); ARCH->addReceiver(this);
} }
CXWindowsServerTaskBarReceiver::~CXWindowsServerTaskBarReceiver() CXWindowsServerTaskBarReceiver::~CXWindowsServerTaskBarReceiver() {
{
ARCH->removeReceiver(this); ARCH->removeReceiver(this);
} }
void void CXWindowsServerTaskBarReceiver::showStatus() {
CXWindowsServerTaskBarReceiver::showStatus()
{
// do nothing // do nothing
} }
void void CXWindowsServerTaskBarReceiver::runMenu(int, int) {
CXWindowsServerTaskBarReceiver::runMenu(int, int)
{
// do nothing // do nothing
} }
void void CXWindowsServerTaskBarReceiver::primaryAction() {
CXWindowsServerTaskBarReceiver::primaryAction()
{
// do nothing // do nothing
} }
const IArchTaskBarReceiver::Icon const IArchTaskBarReceiver::Icon
CXWindowsServerTaskBarReceiver::getIcon() const CXWindowsServerTaskBarReceiver::getIcon() const {
{
return NULL; return NULL;
} }
IArchTaskBarReceiver* IArchTaskBarReceiver *
createTaskBarReceiver(const BufferedLogOutputter* logBuffer, IEventQueue* events) createTaskBarReceiver(const BufferedLogOutputter *logBuffer,
{ IEventQueue *events) {
return new CXWindowsServerTaskBarReceiver(logBuffer, events); return new CXWindowsServerTaskBarReceiver(logBuffer, events);
} }

View file

@ -26,14 +26,17 @@ class IEventQueue;
//! Implementation of ServerTaskBarReceiver for X Windows //! Implementation of ServerTaskBarReceiver for X Windows
class CXWindowsServerTaskBarReceiver : public ServerTaskBarReceiver { class CXWindowsServerTaskBarReceiver : public ServerTaskBarReceiver {
public: public:
CXWindowsServerTaskBarReceiver( CXWindowsServerTaskBarReceiver(const BufferedLogOutputter *,
const BufferedLogOutputter*, IEventQueue* events); IEventQueue *events);
CXWindowsServerTaskBarReceiver(const CXWindowsServerTaskBarReceiver&) =delete; CXWindowsServerTaskBarReceiver(const CXWindowsServerTaskBarReceiver &) =
CXWindowsServerTaskBarReceiver(CXWindowsServerTaskBarReceiver&&) =delete; delete;
CXWindowsServerTaskBarReceiver(CXWindowsServerTaskBarReceiver &&) = delete;
virtual ~CXWindowsServerTaskBarReceiver(); virtual ~CXWindowsServerTaskBarReceiver();
CXWindowsServerTaskBarReceiver& operator=(const CXWindowsServerTaskBarReceiver&) =delete; CXWindowsServerTaskBarReceiver &
CXWindowsServerTaskBarReceiver& operator=(const CXWindowsServerTaskBarReceiver&&) =delete; operator=(const CXWindowsServerTaskBarReceiver &) = delete;
CXWindowsServerTaskBarReceiver &
operator=(const CXWindowsServerTaskBarReceiver &&) = delete;
// IArchTaskBarReceiver overrides // IArchTaskBarReceiver overrides
virtual void showStatus(); virtual void showStatus();

View file

@ -16,10 +16,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "synergy/ServerApp.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/Log.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/Log.h"
#include "synergy/ServerApp.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
#if WINAPI_MSWINDOWS #if WINAPI_MSWINDOWS
#include "MSWindowsServerTaskBarReceiver.h" #include "MSWindowsServerTaskBarReceiver.h"
@ -31,9 +35,7 @@
#error Platform not supported. #error Platform not supported.
#endif #endif
int int main(int argc, char **argv) {
main(int argc, char** argv)
{
#if SYSAPI_WIN32 #if SYSAPI_WIN32
// record window instance for tray icon, etc // record window instance for tray icon, etc
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));

View file

@ -15,12 +15,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "synergy/ToolApp.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "synergy/ToolApp.h"
int #if SYSAPI_WIN32
main(int argc, char** argv) #include "arch/win32/ArchMiscWindows.h"
{ #endif
int main(int argc, char **argv) {
#if SYSAPI_WIN32 #if SYSAPI_WIN32
// record window instance for tray icon, etc // record window instance for tray icon, etc
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));

View file

@ -16,13 +16,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "OSXHelpers.h"
#include "AboutDialog.h" #include "AboutDialog.h"
#include "OSXHelpers.h"
AboutDialog::AboutDialog(MainWindow* parent, const AppConfig& config) : AboutDialog::AboutDialog(MainWindow *parent, const AppConfig &config)
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::AboutDialogBase() Ui::AboutDialogBase() {
{
setupUi(this); setupUi(this);
m_versionChecker.setApp(parent->appPath(config.synergycName())); m_versionChecker.setApp(parent->appPath(config.synergycName()));
@ -38,9 +37,8 @@ AboutDialog::AboutDialog(MainWindow* parent, const AppConfig& config) :
labelCreditsLink->hide(); labelCreditsLink->hide();
} }
int AboutDialog::exec() int AboutDialog::exec() {
{ // Sets the current build year into the copyright text
//Sets the current build year into the copyright text
label_3->setText(getCopyrights() + getKeyContributors()); label_3->setText(getCopyrights() + getKeyContributors());
resizeWindow(); resizeWindow();
updateLogo(); updateLogo();
@ -48,16 +46,14 @@ int AboutDialog::exec()
return QDialog::exec(); return QDialog::exec();
} }
void AboutDialog::resizeWindow() void AboutDialog::resizeWindow() {
{
QSize size(600, 310); QSize size(600, 310);
setMaximumSize(size); setMaximumSize(size);
setMinimumSize(size); setMinimumSize(size);
resize(size); resize(size);
} }
void AboutDialog::updateLogo() const void AboutDialog::updateLogo() const {
{
#if defined(Q_OS_MAC) #if defined(Q_OS_MAC)
if (isOSXInterfaceStyleDark()) { if (isOSXInterfaceStyleDark()) {
QPixmap logo(":/res/image/about-dark.png"); QPixmap logo(":/res/image/about-dark.png");
@ -68,8 +64,7 @@ void AboutDialog::updateLogo() const
#endif #endif
} }
QString AboutDialog::getKeyContributors() const QString AboutDialog::getKeyContributors() const {
{
return QString(R"(<p style="font-size: 14px">Key contributors<br> return QString(R"(<p style="font-size: 14px">Key contributors<br>
<span style="font-size: 11px">Chris Schoeneman, Nick Bolton, Richard Lee, Adam Feder, Volker Lanz, <span style="font-size: 11px">Chris Schoeneman, Nick Bolton, Richard Lee, Adam Feder, Volker Lanz,
Ryan Breen, Guido Poschta, Bertrand Landry Hetu, Tom Chadwick, Brent Priddy, Kyle Bloom, Ryan Breen, Guido Poschta, Bertrand Landry Hetu, Tom Chadwick, Brent Priddy, Kyle Bloom,
@ -77,11 +72,12 @@ QString AboutDialog::getKeyContributors() const
</p>)"); </p>)");
} }
QString AboutDialog::getCopyrights() const QString AboutDialog::getCopyrights() const {
{
QString buildDateString = QString::fromLocal8Bit(__DATE__).simplified(); QString buildDateString = QString::fromLocal8Bit(__DATE__).simplified();
QDate buildDate = QLocale("en_US").toDate(buildDateString, "MMM d yyyy"); QDate buildDate = QLocale("en_US").toDate(buildDateString, "MMM d yyyy");
QString copyrights(R"(<p>Keyboard and mouse sharing application.<br /><br />Copyright © %%YEAR%% Symless Ltd.</p>)"); QString copyrights(
return copyrights.replace(QString("%%YEAR%%"), QString::number(buildDate.year())); R"(<p>Keyboard and mouse sharing application.<br /><br />Copyright © %%YEAR%% Symless Ltd.</p>)");
return copyrights.replace(QString("%%YEAR%%"),
QString::number(buildDate.year()));
} }

View file

@ -20,9 +20,9 @@
#define ABOUTDIALOG__H #define ABOUTDIALOG__H
#include <QDialog>
#include "VersionChecker.h"
#include "MainWindow.h" #include "MainWindow.h"
#include "VersionChecker.h"
#include <QDialog>
#include "ui_AboutDialogBase.h" #include "ui_AboutDialogBase.h"
@ -32,8 +32,9 @@ class QString;
class AboutDialog : public QDialog, public Ui::AboutDialogBase { class AboutDialog : public QDialog, public Ui::AboutDialogBase {
Q_OBJECT Q_OBJECT
public: public:
AboutDialog(MainWindow* parent, const AppConfig& config); AboutDialog(MainWindow *parent, const AppConfig &config);
int exec() override; int exec() override;
private: private:
VersionChecker m_versionChecker; VersionChecker m_versionChecker;
void updateLogo() const; void updateLogo() const;
@ -44,4 +45,3 @@ private:
}; };
#endif #endif

View file

@ -14,13 +14,12 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "CreditsLoader.h"
#include "AboutDialogEliteBackers.h" #include "AboutDialogEliteBackers.h"
#include "CreditsLoader.h"
AboutDialogEliteBackers::AboutDialogEliteBackers(MainWindow* parent, const AppConfig& config) : AboutDialogEliteBackers::AboutDialogEliteBackers(MainWindow *parent,
AboutDialog(parent, config), const AppConfig &config)
credits(*parent, config) : AboutDialog(parent, config), credits(*parent, config) {
{
setupCreditsLoader(); setupCreditsLoader();
textEliteBackers->show(); textEliteBackers->show();
@ -29,35 +28,35 @@ AboutDialogEliteBackers::AboutDialogEliteBackers(MainWindow* parent, const AppCo
labelCreditsLink->show(); labelCreditsLink->show();
} }
void AboutDialogEliteBackers::setupCreditsLoader() void AboutDialogEliteBackers::setupCreditsLoader() {
{
this->textEliteBackers->setText("Loading..."); this->textEliteBackers->setText("Loading...");
this->textEliteBackers->viewport()->setAutoFillBackground(false); this->textEliteBackers->viewport()->setAutoFillBackground(false);
this->textEliteBackers->document()->setDocumentMargin(0); this->textEliteBackers->document()->setDocumentMargin(0);
connect(&credits, SIGNAL(loaded(const QString&)), this, SLOT(updateEliteBackers(const QString&))); connect(&credits, SIGNAL(loaded(const QString &)), this,
SLOT(updateEliteBackers(const QString &)));
credits.loadEliteBackers(); credits.loadEliteBackers();
} }
void AboutDialogEliteBackers::updateEliteBackers(const QString& eliteBackers) const void AboutDialogEliteBackers::updateEliteBackers(
{ const QString &eliteBackers) const {
this->textEliteBackers->setText(eliteBackers); this->textEliteBackers->setText(eliteBackers);
} }
QString AboutDialogEliteBackers::getCopyrights() const QString AboutDialogEliteBackers::getCopyrights() const {
{
QString buildDateString = QString::fromLocal8Bit(__DATE__).simplified(); QString buildDateString = QString::fromLocal8Bit(__DATE__).simplified();
QDate buildDate = QLocale("en_US").toDate(buildDateString, "MMM d yyyy"); QDate buildDate = QLocale("en_US").toDate(buildDateString, "MMM d yyyy");
QString aboutText(R"(<p>Keyboard and mouse sharing application. Cross platform and open source since 2001.<br /><br /> QString aboutText(
R"(<p>Keyboard and mouse sharing application. Cross platform and open source since 2001.<br /><br />
Copyright © %%YEAR%% Symless Ltd.<br /><br /> Copyright © %%YEAR%% Symless Ltd.<br /><br />
Synergy is released under the GNU General Public License (GPLv2).</p>)"); Synergy is released under the GNU General Public License (GPLv2).</p>)");
return aboutText.replace(QString("%%YEAR%%"), QString::number(buildDate.year())); return aboutText.replace(QString("%%YEAR%%"),
QString::number(buildDate.year()));
} }
void AboutDialogEliteBackers::resizeWindow() void AboutDialogEliteBackers::resizeWindow() {
{
// change default size based on os // change default size based on os
#if defined(Q_OS_MAC) #if defined(Q_OS_MAC)
QSize size(600, 490); QSize size(600, 490);

View file

@ -16,16 +16,16 @@
*/ */
#pragma once #pragma once
#include "CreditsLoader.h"
#include "AboutDialog.h" #include "AboutDialog.h"
#include "CreditsLoader.h"
class AboutDialogEliteBackers : public AboutDialog { class AboutDialogEliteBackers : public AboutDialog {
Q_OBJECT Q_OBJECT
public: public:
AboutDialogEliteBackers(MainWindow* parent, const AppConfig& config); AboutDialogEliteBackers(MainWindow *parent, const AppConfig &config);
public slots: public slots:
void updateEliteBackers(const QString& eliteBackers) const; void updateEliteBackers(const QString &eliteBackers) const;
private: private:
CreditsLoader credits; CreditsLoader credits;

View file

@ -21,59 +21,48 @@
#include <QSettings> #include <QSettings>
#include <QTextStream> #include <QTextStream>
const char* Action::m_ActionTypeNames[] = const char *Action::m_ActionTypeNames[] = {
{ "keyDown", "keyUp",
"keyDown", "keyUp", "keystroke", "keystroke", "switchToScreen",
"switchToScreen", "switchInDirection", "lockCursorToScreen", "restartServer", "switchInDirection", "lockCursorToScreen",
"mouseDown", "mouseUp", "mousebutton" "restartServer", "mouseDown",
}; "mouseUp", "mousebutton"};
const char* Action::m_SwitchDirectionNames[] = { "left", "right", "up", "down" }; const char *Action::m_SwitchDirectionNames[] = {"left", "right", "up", "down"};
const char* Action::m_LockCursorModeNames[] = { "toggle", "on", "off" }; const char *Action::m_LockCursorModeNames[] = {"toggle", "on", "off"};
Action::Action() : Action::Action()
m_KeySequence(), : m_KeySequence(), m_Type(keystroke), m_TypeScreenNames(),
m_Type(keystroke), m_SwitchScreenName(), m_SwitchDirection(switchLeft),
m_TypeScreenNames(), m_LockCursorMode(lockCursorToggle), m_ActiveOnRelease(false),
m_SwitchScreenName(), m_HasScreens(false) {}
m_SwitchDirection(switchLeft),
m_LockCursorMode(lockCursorToggle),
m_ActiveOnRelease(false),
m_HasScreens(false)
{
}
QString Action::text() const QString Action::text() const {
{ QString text =
QString text = QString(m_ActionTypeNames[keySequence().isMouseButton() ? type() + 6 : type() ]) + "("; QString(m_ActionTypeNames[keySequence().isMouseButton() ? type() + 6
: type()]) +
"(";
switch (type()) switch (type()) {
{
case keyDown: case keyDown:
case keyUp: case keyUp:
case keystroke: case keystroke: {
{
text += keySequence().toString(); text += keySequence().toString();
if (!keySequence().isMouseButton()) if (!keySequence().isMouseButton()) {
{ const QStringList &screens = typeScreenNames();
const QStringList& screens = typeScreenNames(); if (haveScreens() && !screens.isEmpty()) {
if (haveScreens() && !screens.isEmpty())
{
text += ","; text += ",";
for (int i = 0; i < screens.size(); i++) for (int i = 0; i < screens.size(); i++) {
{
text += screens[i]; text += screens[i];
if (i != screens.size() - 1) if (i != screens.size() - 1)
text += ":"; text += ":";
} }
} } else
else
text += ",*"; text += ",*";
} }
} } break;
break;
case switchToScreen: case switchToScreen:
text += switchScreenName(); text += switchScreenName();
@ -100,15 +89,13 @@ QString Action::text() const
return text; return text;
} }
void Action::loadSettings(QSettings& settings) void Action::loadSettings(QSettings &settings) {
{
keySequence().loadSettings(settings); keySequence().loadSettings(settings);
setType(settings.value("type", keyDown).toInt()); setType(settings.value("type", keyDown).toInt());
typeScreenNames().clear(); typeScreenNames().clear();
int numTypeScreens = settings.beginReadArray("typeScreenNames"); int numTypeScreens = settings.beginReadArray("typeScreenNames");
for (int i = 0; i < numTypeScreens; i++) for (int i = 0; i < numTypeScreens; i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
typeScreenNames().append(settings.value("typeScreenName").toString()); typeScreenNames().append(settings.value("typeScreenName").toString());
} }
@ -116,20 +103,19 @@ void Action::loadSettings(QSettings& settings)
setSwitchScreenName(settings.value("switchScreenName").toString()); setSwitchScreenName(settings.value("switchScreenName").toString());
setSwitchDirection(settings.value("switchInDirection", switchLeft).toInt()); setSwitchDirection(settings.value("switchInDirection", switchLeft).toInt());
setLockCursorMode(settings.value("lockCursorToScreen", lockCursorToggle).toInt()); setLockCursorMode(
settings.value("lockCursorToScreen", lockCursorToggle).toInt());
setActiveOnRelease(settings.value("activeOnRelease", false).toBool()); setActiveOnRelease(settings.value("activeOnRelease", false).toBool());
setHaveScreens(settings.value("hasScreens", false).toBool()); setHaveScreens(settings.value("hasScreens", false).toBool());
setRestartServer(settings.value("restartServer", false).toBool()); setRestartServer(settings.value("restartServer", false).toBool());
} }
void Action::saveSettings(QSettings& settings) const void Action::saveSettings(QSettings &settings) const {
{
keySequence().saveSettings(settings); keySequence().saveSettings(settings);
settings.setValue("type", type()); settings.setValue("type", type());
settings.beginWriteArray("typeScreenNames"); settings.beginWriteArray("typeScreenNames");
for (int i = 0; i < typeScreenNames().size(); i++) for (int i = 0; i < typeScreenNames().size(); i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
settings.setValue("typeScreenName", typeScreenNames()[i]); settings.setValue("typeScreenName", typeScreenNames()[i]);
} }
@ -143,21 +129,17 @@ void Action::saveSettings(QSettings& settings) const
settings.setValue("restartServer", restartServer()); settings.setValue("restartServer", restartServer());
} }
bool Action::operator==(const Action& a) const bool Action::operator==(const Action &a) const {
{ return m_KeySequence == a.m_KeySequence && m_Type == a.m_Type &&
return m_KeySequence == a.m_KeySequence &&
m_Type == a.m_Type &&
m_TypeScreenNames == a.m_TypeScreenNames && m_TypeScreenNames == a.m_TypeScreenNames &&
m_SwitchScreenName == a.m_SwitchScreenName && m_SwitchScreenName == a.m_SwitchScreenName &&
m_SwitchDirection == a.m_SwitchDirection && m_SwitchDirection == a.m_SwitchDirection &&
m_LockCursorMode == a.m_LockCursorMode && m_LockCursorMode == a.m_LockCursorMode &&
m_ActiveOnRelease == a.m_ActiveOnRelease && m_ActiveOnRelease == a.m_ActiveOnRelease &&
m_HasScreens == a.m_HasScreens && m_HasScreens == a.m_HasScreens && m_restartServer == a.m_restartServer;
m_restartServer == a.m_restartServer;
} }
QTextStream& operator<<(QTextStream& outStream, const Action& action) QTextStream &operator<<(QTextStream &outStream, const Action &action) {
{
if (action.activeOnRelease()) if (action.activeOnRelease())
outStream << ";"; outStream << ";";
@ -165,4 +147,3 @@ QTextStream& operator<<(QTextStream& outStream, const Action& action)
return outStream; return outStream;
} }

View file

@ -22,20 +22,19 @@
#include "KeySequence.h" #include "KeySequence.h"
#include <QList>
#include <QString> #include <QString>
#include <QStringList> #include <QStringList>
#include <QList>
class ActionDialog; class ActionDialog;
class QSettings; class QSettings;
class QTextStream; class QTextStream;
class Action class Action {
{
friend class ActionDialog; friend class ActionDialog;
friend QTextStream& operator<<(QTextStream& outStream, const Action& action); friend QTextStream &operator<<(QTextStream &outStream, const Action &action);
public: public:
enum ActionType { enum ActionType {
keyDown, keyDown,
keyUp, keyUp,
@ -48,50 +47,41 @@ class Action
mouseUp, mouseUp,
mousebutton, mousebutton,
}; };
enum SwitchDirection { enum SwitchDirection { switchLeft, switchRight, switchUp, switchDown };
switchLeft, enum LockCursorMode { lockCursorToggle, lockCursonOn, lockCursorOff };
switchRight,
switchUp,
switchDown
};
enum LockCursorMode {
lockCursorToggle,
lockCursonOn,
lockCursorOff
};
public: public:
Action(); Action();
public: public:
QString text() const; QString text() const;
const KeySequence& keySequence() const { return m_KeySequence; } const KeySequence &keySequence() const { return m_KeySequence; }
void loadSettings(QSettings& settings); void loadSettings(QSettings &settings);
void saveSettings(QSettings& settings) const; void saveSettings(QSettings &settings) const;
int type() const { return m_Type; } int type() const { return m_Type; }
const QStringList& typeScreenNames() const { return m_TypeScreenNames; } const QStringList &typeScreenNames() const { return m_TypeScreenNames; }
const QString& switchScreenName() const { return m_SwitchScreenName; } const QString &switchScreenName() const { return m_SwitchScreenName; }
int switchDirection() const { return m_SwitchDirection; } int switchDirection() const { return m_SwitchDirection; }
int lockCursorMode() const { return m_LockCursorMode; } int lockCursorMode() const { return m_LockCursorMode; }
bool activeOnRelease() const { return m_ActiveOnRelease; } bool activeOnRelease() const { return m_ActiveOnRelease; }
bool haveScreens() const { return m_HasScreens; } bool haveScreens() const { return m_HasScreens; }
bool restartServer() const { return m_restartServer; } bool restartServer() const { return m_restartServer; }
bool operator==(const Action& a) const; bool operator==(const Action &a) const;
protected: protected:
KeySequence& keySequence() { return m_KeySequence; } KeySequence &keySequence() { return m_KeySequence; }
void setKeySequence(const KeySequence& seq) { m_KeySequence = seq; } void setKeySequence(const KeySequence &seq) { m_KeySequence = seq; }
void setType(int t) { m_Type = t; } void setType(int t) { m_Type = t; }
QStringList& typeScreenNames() { return m_TypeScreenNames; } QStringList &typeScreenNames() { return m_TypeScreenNames; }
void setSwitchScreenName(const QString& n) { m_SwitchScreenName = n; } void setSwitchScreenName(const QString &n) { m_SwitchScreenName = n; }
void setSwitchDirection(int d) { m_SwitchDirection = d; } void setSwitchDirection(int d) { m_SwitchDirection = d; }
void setLockCursorMode(int m) { m_LockCursorMode = m; } void setLockCursorMode(int m) { m_LockCursorMode = m; }
void setActiveOnRelease(bool b) { m_ActiveOnRelease = b; } void setActiveOnRelease(bool b) { m_ActiveOnRelease = b; }
void setHaveScreens(bool b) { m_HasScreens = b; } void setHaveScreens(bool b) { m_HasScreens = b; }
void setRestartServer( bool b) { m_restartServer = b; } void setRestartServer(bool b) { m_restartServer = b; }
private: private:
KeySequence m_KeySequence; KeySequence m_KeySequence;
int m_Type; int m_Type;
QStringList m_TypeScreenNames; QStringList m_TypeScreenNames;
@ -102,13 +92,13 @@ class Action
bool m_HasScreens; bool m_HasScreens;
bool m_restartServer; bool m_restartServer;
static const char* m_ActionTypeNames[]; static const char *m_ActionTypeNames[];
static const char* m_SwitchDirectionNames[]; static const char *m_SwitchDirectionNames[];
static const char* m_LockCursorModeNames[]; static const char *m_LockCursorModeNames[];
}; };
typedef QList<Action> ActionList; typedef QList<Action> ActionList;
QTextStream& operator<<(QTextStream& outStream, const Action& action); QTextStream &operator<<(QTextStream &outStream, const Action &action);
#endif #endif

View file

@ -18,30 +18,34 @@
#include "ActionDialog.h" #include "ActionDialog.h"
#include "Hotkey.h"
#include "Action.h" #include "Action.h"
#include "ServerConfig.h" #include "Hotkey.h"
#include "KeySequence.h" #include "KeySequence.h"
#include "ServerConfig.h"
#include <QButtonGroup>
#include <QtCore> #include <QtCore>
#include <QtGui> #include <QtGui>
#include <QButtonGroup>
ActionDialog::ActionDialog(QWidget* parent, ServerConfig& config, Hotkey& hotkey, Action& action) : ActionDialog::ActionDialog(QWidget *parent, ServerConfig &config,
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Hotkey &hotkey, Action &action)
Ui::ActionDialogBase(), : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
m_ServerConfig(config), Ui::ActionDialogBase(), m_ServerConfig(config), m_Hotkey(hotkey),
m_Hotkey(hotkey), m_Action(action), m_pButtonGroupType(new QButtonGroup(this)) {
m_Action(action),
m_pButtonGroupType(new QButtonGroup(this))
{
setupUi(this); setupUi(this);
// work around Qt Designer's lack of a QButtonGroup; we need it to get // work around Qt Designer's lack of a QButtonGroup; we need it to get
// at the button id of the checked radio button // at the button id of the checked radio button
QRadioButton* const typeButtons[] = { m_pRadioPress, m_pRadioRelease, m_pRadioPressAndRelease, m_pRadioSwitchToScreen, m_pRadioSwitchInDirection, m_pRadioLockCursorToScreen , m_pRadioRestartAllConnections}; QRadioButton *const typeButtons[] = {m_pRadioPress,
m_pRadioRelease,
m_pRadioPressAndRelease,
m_pRadioSwitchToScreen,
m_pRadioSwitchInDirection,
m_pRadioLockCursorToScreen,
m_pRadioRestartAllConnections};
for (unsigned int i = 0; i < sizeof(typeButtons) / sizeof(typeButtons[0]); i++) for (unsigned int i = 0; i < sizeof(typeButtons) / sizeof(typeButtons[0]);
i++)
m_pButtonGroupType->addButton(typeButtons[i], i); m_pButtonGroupType->addButton(typeButtons[i], i);
m_pKeySequenceWidgetHotkey->setText(m_Action.keySequence().toString()); m_pKeySequenceWidgetHotkey->setText(m_Action.keySequence().toString());
@ -58,9 +62,8 @@ ActionDialog::ActionDialog(QWidget* parent, ServerConfig& config, Hotkey& hotkey
m_pGroupBoxScreens->setChecked(m_Action.haveScreens()); m_pGroupBoxScreens->setChecked(m_Action.haveScreens());
int idx = 0; int idx = 0;
foreach(const Screen& screen, serverConfig().screens()) foreach (const Screen &screen, serverConfig().screens())
if (!screen.isNull()) if (!screen.isNull()) {
{
QListWidgetItem *pListItem = new QListWidgetItem(screen.name()); QListWidgetItem *pListItem = new QListWidgetItem(screen.name());
m_pListScreens->addItem(pListItem); m_pListScreens->addItem(pListItem);
if (m_Action.typeScreenNames().indexOf(screen.name()) != -1) if (m_Action.typeScreenNames().indexOf(screen.name()) != -1)
@ -74,9 +77,9 @@ ActionDialog::ActionDialog(QWidget* parent, ServerConfig& config, Hotkey& hotkey
} }
} }
void ActionDialog::accept() void ActionDialog::accept() {
{ if (!sequenceWidget()->valid() && m_pButtonGroupType->checkedId() >= 0 &&
if (!sequenceWidget()->valid() && m_pButtonGroupType->checkedId() >= 0 && m_pButtonGroupType->checkedId() < 3) m_pButtonGroupType->checkedId() < 3)
return; return;
m_Action.setKeySequence(sequenceWidget()->keySequence()); m_Action.setKeySequence(sequenceWidget()->keySequence());
@ -84,7 +87,7 @@ void ActionDialog::accept()
m_Action.setHaveScreens(m_pGroupBoxScreens->isChecked()); m_Action.setHaveScreens(m_pGroupBoxScreens->isChecked());
m_Action.typeScreenNames().clear(); m_Action.typeScreenNames().clear();
foreach(const QListWidgetItem* pItem, m_pListScreens->selectedItems()) foreach (const QListWidgetItem *pItem, m_pListScreens->selectedItems())
m_Action.typeScreenNames().append(pItem->text()); m_Action.typeScreenNames().append(pItem->text());
m_Action.setSwitchScreenName(m_pComboSwitchToScreen->currentText()); m_Action.setSwitchScreenName(m_pComboSwitchToScreen->currentText());
@ -96,15 +99,11 @@ void ActionDialog::accept()
QDialog::accept(); QDialog::accept();
} }
void ActionDialog::on_m_pKeySequenceWidgetHotkey_keySequenceChanged() void ActionDialog::on_m_pKeySequenceWidgetHotkey_keySequenceChanged() {
{ if (sequenceWidget()->keySequence().isMouseButton()) {
if (sequenceWidget()->keySequence().isMouseButton())
{
m_pGroupBoxScreens->setEnabled(false); m_pGroupBoxScreens->setEnabled(false);
m_pListScreens->setEnabled(false); m_pListScreens->setEnabled(false);
} } else {
else
{
m_pGroupBoxScreens->setEnabled(true); m_pGroupBoxScreens->setEnabled(true);
m_pListScreens->setEnabled(true); m_pListScreens->setEnabled(true);
} }

View file

@ -30,27 +30,29 @@ class QRadioButton;
class QButtonGroup; class QButtonGroup;
class ServerConfig; class ServerConfig;
class ActionDialog : public QDialog, public Ui::ActionDialogBase class ActionDialog : public QDialog, public Ui::ActionDialogBase {
{
Q_OBJECT Q_OBJECT
public: public:
ActionDialog(QWidget* parent, ServerConfig& config, Hotkey& hotkey, Action& action); ActionDialog(QWidget *parent, ServerConfig &config, Hotkey &hotkey,
Action &action);
protected slots: protected slots:
void accept(); void accept();
void on_m_pKeySequenceWidgetHotkey_keySequenceChanged(); void on_m_pKeySequenceWidgetHotkey_keySequenceChanged();
protected: protected:
const KeySequenceWidget* sequenceWidget() const { return m_pKeySequenceWidgetHotkey; } const KeySequenceWidget *sequenceWidget() const {
const ServerConfig& serverConfig() const { return m_ServerConfig; } return m_pKeySequenceWidgetHotkey;
}
const ServerConfig &serverConfig() const { return m_ServerConfig; }
private: private:
const ServerConfig& m_ServerConfig; const ServerConfig &m_ServerConfig;
Hotkey& m_Hotkey; Hotkey &m_Hotkey;
Action& m_Action; Action &m_Action;
QButtonGroup* m_pButtonGroupType; QButtonGroup *m_pButtonGroupType;
}; };
#endif #endif

View file

@ -1,25 +1,22 @@
#include "ActivationDialog.h" #include "ActivationDialog.h"
#include "ui_ActivationDialog.h"
#include "CancelActivationDialog.h"
#include "AppConfig.h"
#include <shared/EditionType.h>
#include "ActivationNotifier.h" #include "ActivationNotifier.h"
#include "AppConfig.h"
#include "CancelActivationDialog.h"
#include "FailedLoginDialog.h"
#include "LicenseManager.h"
#include "MainWindow.h" #include "MainWindow.h"
#include "QUtility.h" #include "QUtility.h"
#include "LicenseManager.h" #include "ui_ActivationDialog.h"
#include "FailedLoginDialog.h" #include <shared/EditionType.h>
#include <QMessageBox> #include <QMessageBox>
#include <QThread> #include <QThread>
#include <iostream> #include <iostream>
ActivationDialog::ActivationDialog(QWidget* parent, AppConfig& appConfig, ActivationDialog::ActivationDialog(QWidget *parent, AppConfig &appConfig,
LicenseManager& licenseManager) : LicenseManager &licenseManager)
QDialog(parent), : QDialog(parent), ui(new Ui::ActivationDialog), m_appConfig(&appConfig),
ui(new Ui::ActivationDialog), m_LicenseManager(&licenseManager) {
m_appConfig(&appConfig),
m_LicenseManager (&licenseManager)
{
ui->setupUi(this); ui->setupUi(this);
refreshSerialKey(); refreshSerialKey();
time_t currentTime = ::time(0); time_t currentTime = ::time(0);
@ -28,21 +25,17 @@ ActivationDialog::ActivationDialog(QWidget* parent, AppConfig& appConfig,
} }
} }
void ActivationDialog::refreshSerialKey() void ActivationDialog::refreshSerialKey() {
{
ui->m_pTextEditSerialKey->setText(m_appConfig->serialKey()); ui->m_pTextEditSerialKey->setText(m_appConfig->serialKey());
ui->m_pTextEditSerialKey->setFocus(); ui->m_pTextEditSerialKey->setFocus();
ui->m_pTextEditSerialKey->moveCursor(QTextCursor::End); ui->m_pTextEditSerialKey->moveCursor(QTextCursor::End);
ui->m_trialLabel->setText(tr(m_LicenseManager->getLicenseNotice().toStdString().c_str())); ui->m_trialLabel->setText(
tr(m_LicenseManager->getLicenseNotice().toStdString().c_str()));
} }
ActivationDialog::~ActivationDialog() ActivationDialog::~ActivationDialog() { delete ui; }
{
delete ui;
}
void ActivationDialog::reject() void ActivationDialog::reject() {
{
if (m_LicenseManager->activeEdition() == kUnregistered) { if (m_LicenseManager->activeEdition() == kUnregistered) {
CancelActivationDialog cancelActivationDialog(this); CancelActivationDialog cancelActivationDialog(this);
if (QDialog::Accepted == cancelActivationDialog.exec()) { if (QDialog::Accepted == cancelActivationDialog.exec()) {
@ -54,22 +47,24 @@ void ActivationDialog::reject()
QDialog::reject(); QDialog::reject();
} }
void ActivationDialog::accept() void ActivationDialog::accept() {
{
QMessageBox message; QMessageBox message;
m_appConfig->activationHasRun(true); m_appConfig->activationHasRun(true);
try { try {
SerialKey serialKey (ui->m_pTextEditSerialKey->toPlainText(). SerialKey serialKey(
trimmed().toStdString()); ui->m_pTextEditSerialKey->toPlainText().trimmed().toStdString());
m_LicenseManager->setSerialKey(serialKey); m_LicenseManager->setSerialKey(serialKey);
} } catch (std::exception &e) {
catch (std::exception& e) { message.critical(
message.critical(this, "Activation failed", this, "Activation failed",
tr("An error occurred while trying to activate Synergy. " tr("An error occurred while trying to activate Synergy. "
"<a href=\"https://symless.com/synergy/contact-support?source=gui\" style=\"text-decoration: none; color: #4285F4;\">" "<a href=\"https://symless.com/synergy/contact-support?source=gui\" "
"Please contact the helpdesk</a>, and provide the following information:" "style=\"text-decoration: none; color: #4285F4;\">"
"<br><br>%1").arg(e.what())); "Please contact the helpdesk</a>, and provide the following "
"information:"
"<br><br>%1")
.arg(e.what()));
refreshSerialKey(); refreshSerialKey();
return; return;
} }
@ -79,15 +74,16 @@ void ActivationDialog::accept()
time_t daysLeft = m_LicenseManager->serialKey().daysLeft(::time(0)); time_t daysLeft = m_LicenseManager->serialKey().daysLeft(::time(0));
if (edition != kUnregistered) { if (edition != kUnregistered) {
QString thanksMessage = tr("Thanks for trying %1! %5\n\n%2 day%3 of " QString thanksMessage = tr("Thanks for trying %1! %5\n\n%2 day%3 of "
"your trial remain%4"). "your trial remain%4")
arg (m_LicenseManager->getEditionName(edition)). .arg(m_LicenseManager->getEditionName(edition))
arg (daysLeft). .arg(daysLeft)
arg ((daysLeft == 1) ? "" : "s"). .arg((daysLeft == 1) ? "" : "s")
arg ((daysLeft == 1) ? "s" : ""); .arg((daysLeft == 1) ? "s" : "");
if (m_appConfig->isCryptoAvailable()) { if (m_appConfig->isCryptoAvailable()) {
m_appConfig->generateCertificate(); m_appConfig->generateCertificate();
thanksMessage = thanksMessage.arg("If you're using SSL, " thanksMessage =
thanksMessage.arg("If you're using SSL, "
"remember to activate all of your devices."); "remember to activate all of your devices.");
} else { } else {
thanksMessage = thanksMessage.arg(""); thanksMessage = thanksMessage.arg("");
@ -95,11 +91,10 @@ void ActivationDialog::accept()
if (m_LicenseManager->serialKey().isTrial()) { if (m_LicenseManager->serialKey().isTrial()) {
message.information(this, "Thanks!", thanksMessage); message.information(this, "Thanks!", thanksMessage);
} } else {
else {
message.information(this, "Activated!", message.information(this, "Activated!",
tr("Thanks for activating %1!").arg tr("Thanks for activating %1!")
(m_LicenseManager->getEditionName(edition))); .arg(m_LicenseManager->getEditionName(edition)));
} }
} }

View file

@ -1,8 +1,8 @@
#ifndef ACTIVATIONDIALOG_H #ifndef ACTIVATIONDIALOG_H
#define ACTIVATIONDIALOG_H #define ACTIVATIONDIALOG_H
#include <QDialog>
#include <LicenseManager.h> #include <LicenseManager.h>
#include <QDialog>
namespace Ui { namespace Ui {
class ActivationDialog; class ActivationDialog;
@ -10,13 +10,12 @@ class ActivationDialog;
class AppConfig; class AppConfig;
class ActivationDialog : public QDialog class ActivationDialog : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:
ActivationDialog(QWidget *parent, AppConfig& appConfig, ActivationDialog(QWidget *parent, AppConfig &appConfig,
LicenseManager& licenseManager); LicenseManager &licenseManager);
~ActivationDialog(); ~ActivationDialog();
public slots: public slots:
@ -28,8 +27,8 @@ protected:
private: private:
Ui::ActivationDialog *ui; Ui::ActivationDialog *ui;
AppConfig* m_appConfig; AppConfig *m_appConfig;
LicenseManager* m_LicenseManager; LicenseManager *m_LicenseManager;
}; };
#endif // ACTIVATIONDIALOG_H #endif // ACTIVATIONDIALOG_H

View file

@ -19,31 +19,24 @@
#include "CoreInterface.h" #include "CoreInterface.h"
ActivationNotifier::ActivationNotifier(QObject *parent) : ActivationNotifier::ActivationNotifier(QObject *parent) : QObject(parent) {}
QObject(parent)
{
}
void ActivationNotifier::setIdentity(QString identity) void ActivationNotifier::setIdentity(QString identity) {
{
m_Identity = identity; m_Identity = identity;
} }
void ActivationNotifier::setUpdateInfo(QString const& fromVersion, void ActivationNotifier::setUpdateInfo(QString const &fromVersion,
QString const& toVersion, QString const &toVersion,
QString const& serialKey) QString const &serialKey) {
{
m_fromVersion = fromVersion; m_fromVersion = fromVersion;
m_toVersion = toVersion; m_toVersion = toVersion;
m_serialKey = serialKey; m_serialKey = serialKey;
} }
void ActivationNotifier::notify() void ActivationNotifier::notify() {
{
// TODO: use something other than CURL // TODO: use something other than CURL
} }
void ActivationNotifier::notifyUpdate() void ActivationNotifier::notifyUpdate() {
{
// TODO: use something other than CURL // TODO: use something other than CURL
} }

View file

@ -20,15 +20,14 @@
#include <QObject> #include <QObject>
class ActivationNotifier : public QObject class ActivationNotifier : public QObject {
{ Q_OBJECT
Q_OBJECT
public: public:
explicit ActivationNotifier(QObject *parent = 0); explicit ActivationNotifier(QObject *parent = 0);
void setIdentity(QString identity); void setIdentity(QString identity);
void setUpdateInfo(QString const& fromVersion, void setUpdateInfo(QString const &fromVersion, QString const &toVersion,
QString const& toVersion, QString const& serialKey); QString const &serialKey);
public slots: public slots:
void notify(); void notify();

View file

@ -18,22 +18,21 @@
#include "AddClientDialog.h" #include "AddClientDialog.h"
#include "ui_AddClientDialogBase.h" #include "ui_AddClientDialogBase.h"
#include <QPushButton>
#include <QLabel> #include <QLabel>
#include <QPushButton>
AddClientDialog::AddClientDialog(const QString& clientName, QWidget* parent) : AddClientDialog::AddClientDialog(const QString &clientName, QWidget *parent)
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::AddClientDialog(), Ui::AddClientDialog(), m_AddResult(kAddClientIgnore),
m_AddResult(kAddClientIgnore), m_IgnoreAutoConfigClient(false) {
m_IgnoreAutoConfigClient(false)
{
setupUi(this); setupUi(this);
m_pLabelHead->setText("A client wants to connect. " m_pLabelHead->setText("A client wants to connect. "
"Please choose a location for " + clientName + "."); "Please choose a location for " +
clientName + ".");
QIcon icon(":res/icons/64x64/video-display.png"); QIcon icon(":res/icons/64x64/video-display.png");
QSize IconSize(32,32); QSize IconSize(32, 32);
m_pButtonLeft = new QPushButton(this); m_pButtonLeft = new QPushButton(this);
m_pButtonLeft->setIcon(icon); m_pButtonLeft->setIcon(icon);
@ -67,13 +66,12 @@ AddClientDialog::AddClientDialog(const QString& clientName, QWidget* parent) :
m_pDialogButtonBox->setLayoutDirection(Qt::RightToLeft); m_pDialogButtonBox->setLayoutDirection(Qt::RightToLeft);
#endif #endif
QPushButton* advanced = m_pDialogButtonBox->addButton("Advanced", QPushButton *advanced =
QDialogButtonBox::HelpRole); m_pDialogButtonBox->addButton("Advanced", QDialogButtonBox::HelpRole);
connect(advanced, SIGNAL(clicked()), this, SLOT(handleButtonAdvanced())); connect(advanced, SIGNAL(clicked()), this, SLOT(handleButtonAdvanced()));
} }
AddClientDialog::~AddClientDialog() AddClientDialog::~AddClientDialog() {
{
delete m_pButtonUp; delete m_pButtonUp;
delete m_pButtonDown; delete m_pButtonDown;
delete m_pButtonLeft; delete m_pButtonLeft;
@ -81,8 +79,7 @@ AddClientDialog::~AddClientDialog()
delete m_pLabelCenter; delete m_pLabelCenter;
} }
void AddClientDialog::changeEvent(QEvent *e) void AddClientDialog::changeEvent(QEvent *e) {
{
QDialog::changeEvent(e); QDialog::changeEvent(e);
switch (e->type()) { switch (e->type()) {
case QEvent::LanguageChange: case QEvent::LanguageChange:
@ -93,37 +90,31 @@ void AddClientDialog::changeEvent(QEvent *e)
} }
} }
void AddClientDialog::handleButtonLeft() void AddClientDialog::handleButtonLeft() {
{
m_AddResult = kAddClientLeft; m_AddResult = kAddClientLeft;
close(); close();
} }
void AddClientDialog::handleButtonUp() void AddClientDialog::handleButtonUp() {
{
m_AddResult = kAddClientUp; m_AddResult = kAddClientUp;
close(); close();
} }
void AddClientDialog::handleButtonRight() void AddClientDialog::handleButtonRight() {
{
m_AddResult = kAddClientRight; m_AddResult = kAddClientRight;
close(); close();
} }
void AddClientDialog::handleButtonDown() void AddClientDialog::handleButtonDown() {
{
m_AddResult = kAddClientDown; m_AddResult = kAddClientDown;
close(); close();
} }
void AddClientDialog::handleButtonAdvanced() void AddClientDialog::handleButtonAdvanced() {
{
m_AddResult = kAddClientOther; m_AddResult = kAddClientOther;
close(); close();
} }
void AddClientDialog::on_m_pCheckBoxIgnoreClient_toggled(bool checked) void AddClientDialog::on_m_pCheckBoxIgnoreClient_toggled(bool checked) {
{
m_IgnoreAutoConfigClient = checked; m_IgnoreAutoConfigClient = checked;
} }

View file

@ -34,11 +34,10 @@ enum {
kAddClientIgnore kAddClientIgnore
}; };
class AddClientDialog : public QDialog, public Ui::AddClientDialog class AddClientDialog : public QDialog, public Ui::AddClientDialog {
{
Q_OBJECT Q_OBJECT
public: public:
AddClientDialog(const QString& clientName, QWidget* parent = 0); AddClientDialog(const QString &clientName, QWidget *parent = 0);
~AddClientDialog(); ~AddClientDialog();
int addResult() { return m_AddResult; } int addResult() { return m_AddResult; }
@ -56,11 +55,11 @@ private slots:
void handleButtonAdvanced(); void handleButtonAdvanced();
private: private:
QPushButton* m_pButtonLeft; QPushButton *m_pButtonLeft;
QPushButton* m_pButtonUp; QPushButton *m_pButtonUp;
QPushButton* m_pButtonRight; QPushButton *m_pButtonRight;
QPushButton* m_pButtonDown; QPushButton *m_pButtonDown;
QLabel* m_pLabelCenter; QLabel *m_pLabelCenter;
int m_AddResult; int m_AddResult;
bool m_IgnoreAutoConfigClient; bool m_IgnoreAutoConfigClient;
}; };

View file

@ -16,14 +16,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "QSynergyApplication.h"
#include "AppConfig.h" #include "AppConfig.h"
#include "QSynergyApplication.h"
#include "QUtility.h" #include "QUtility.h"
#include <QPushButton>
#include <QtCore> #include <QtCore>
#include <QtNetwork> #include <QtNetwork>
#include <QtWidgets/QMessageBox> #include <QtWidgets/QMessageBox>
#include <QPushButton>
#include "ConfigWriter.h" #include "ConfigWriter.h"
#include "SslCertificate.h" #include "SslCertificate.h"
@ -45,7 +45,7 @@ const char AppConfig::synergyConfigName[] = "synergy.conf";
const ElevateMode defaultElevateMode = ElevateAsNeeded; const ElevateMode defaultElevateMode = ElevateAsNeeded;
const char* AppConfig::m_SynergySettingsName[] = { const char *AppConfig::m_SynergySettingsName[] = {
"screenName", "screenName",
"port", "port",
"interface", "interface",
@ -86,54 +86,34 @@ const char* AppConfig::m_SynergySettingsName[] = {
"licenseNextCheck", "licenseNextCheck",
"initiateConnectionFromServer", "initiateConnectionFromServer",
"clientHostMode", "clientHostMode",
"serverClientMode" "serverClientMode"};
};
static const char* logLevelNames[] = static const char *logLevelNames[] = {"INFO", "DEBUG", "DEBUG1", "DEBUG2"};
{
"INFO",
"DEBUG",
"DEBUG1",
"DEBUG2"
};
AppConfig::AppConfig() : AppConfig::AppConfig()
m_ScreenName(), : m_ScreenName(), m_Port(24800), m_Interface(), m_LogLevel(0),
m_Port(24800), m_LogToFile(), m_WizardLastRun(0), m_ProcessMode(DEFAULT_PROCESS_MODE),
m_Interface(), m_StartedBefore(), m_AutoConfig(true), m_AutoConfigServer(),
m_LogLevel(0), m_ElevateMode(defaultElevateMode), m_Edition(kUnregistered),
m_LogToFile(), m_CryptoEnabled(false), m_AutoHide(false), m_LastExpiringWarningTime(0),
m_WizardLastRun(0), m_ActivationHasRun(), m_MinimizeToTray(false), m_ServerGroupChecked(),
m_ProcessMode(DEFAULT_PROCESS_MODE), m_UseExternalConfig(), m_UseInternalConfig(), m_ClientGroupChecked(),
m_StartedBefore(), m_LoadFromSystemScope() {
m_AutoConfig(true),
m_AutoConfigServer(),
m_ElevateMode(defaultElevateMode),
m_Edition(kUnregistered),
m_CryptoEnabled(false),
m_AutoHide(false),
m_LastExpiringWarningTime(0),
m_ActivationHasRun(),
m_MinimizeToTray(false),
m_ServerGroupChecked(),
m_UseExternalConfig(),
m_UseInternalConfig(),
m_ClientGroupChecked(),
m_LoadFromSystemScope()
{
auto writer = ConfigWriter::make(); auto writer = ConfigWriter::make();
//Register this class to receive global load and saves // Register this class to receive global load and saves
writer->registerClass(this); writer->registerClass(this);
writer->globalLoad(); writer->globalLoad();
//User settings exist and the load from system scope variable is true // User settings exist and the load from system scope variable is true
if (writer->hasSetting(settingName(kLoadSystemSettings), ConfigWriter::kUser)) { if (writer->hasSetting(settingName(kLoadSystemSettings),
ConfigWriter::kUser)) {
setLoadFromSystemScope(m_LoadFromSystemScope); setLoadFromSystemScope(m_LoadFromSystemScope);
} }
//If user setting don't exist but system ones do, load the system settings // If user setting don't exist but system ones do, load the system settings
else if (writer->hasSetting(settingName(kScreenName), ConfigWriter::kSystem)) { else if (writer->hasSetting(settingName(kScreenName),
ConfigWriter::kSystem)) {
setLoadFromSystemScope(true); setLoadFromSystemScope(true);
} }
} }
@ -150,31 +130,26 @@ bool AppConfig::logToFile() const { return m_LogToFile; }
const QString &AppConfig::logFilename() const { return m_LogFilename; } const QString &AppConfig::logFilename() const { return m_LogFilename; }
QString AppConfig::synergyLogDir() const QString AppConfig::synergyLogDir() const {
{
// by default log to home dir // by default log to home dir
return QDir::home().absolutePath() + "/"; return QDir::home().absolutePath() + "/";
} }
QString AppConfig::synergyProgramDir() const QString AppConfig::synergyProgramDir() const {
{
// synergy binaries should be in the same dir. // synergy binaries should be in the same dir.
return QCoreApplication::applicationDirPath() + "/"; return QCoreApplication::applicationDirPath() + "/";
} }
void AppConfig::persistLogDir() void AppConfig::persistLogDir() {
{
QDir dir = synergyLogDir(); QDir dir = synergyLogDir();
// persist the log directory // persist the log directory
if (!dir.exists()) if (!dir.exists()) {
{
dir.mkpath(dir.path()); dir.mkpath(dir.path());
} }
} }
const QString AppConfig::logFilenameCmd() const const QString AppConfig::logFilenameCmd() const {
{
QString filename = m_LogFilename; QString filename = m_LogFilename;
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
// wrap in quotes in case username contains spaces. // wrap in quotes in case username contains spaces.
@ -183,14 +158,13 @@ const QString AppConfig::logFilenameCmd() const
return filename; return filename;
} }
QString AppConfig::logLevelText() const QString AppConfig::logLevelText() const { return logLevelNames[logLevel()]; }
{
return logLevelNames[logLevel()];
}
ProcessMode AppConfig::processMode() const { return m_ProcessMode; } ProcessMode AppConfig::processMode() const { return m_ProcessMode; }
bool AppConfig::wizardShouldRun() const { return m_WizardLastRun < kWizardVersion; } bool AppConfig::wizardShouldRun() const {
return m_WizardLastRun < kWizardVersion;
}
const QString &AppConfig::language() const { return m_Language; } const QString &AppConfig::language() const { return m_Language; }
@ -207,9 +181,9 @@ bool AppConfig::autoConfig() const {
QString AppConfig::autoConfigServer() const { return m_AutoConfigServer; } QString AppConfig::autoConfigServer() const { return m_AutoConfigServer; }
void AppConfig::loadSettings() void AppConfig::loadSettings() {
{ m_ScreenName =
m_ScreenName = loadSetting(kScreenName, QHostInfo::localHostName()).toString(); loadSetting(kScreenName, QHostInfo::localHostName()).toString();
if (m_ScreenName.isEmpty()) { if (m_ScreenName.isEmpty()) {
m_ScreenName = QHostInfo::localHostName(); m_ScreenName = QHostInfo::localHostName();
} }
@ -218,14 +192,15 @@ void AppConfig::loadSettings()
m_Interface = loadSetting(kInterfaceSetting).toString(); m_Interface = loadSetting(kInterfaceSetting).toString();
m_LogLevel = loadSetting(kLogLevel, 0).toInt(); m_LogLevel = loadSetting(kLogLevel, 0).toInt();
m_LogToFile = loadSetting(kLogToFile, false).toBool(); m_LogToFile = loadSetting(kLogToFile, false).toBool();
m_LogFilename = loadSetting(kLogFilename, synergyLogDir() + "synergy.log").toString(); m_LogFilename =
loadSetting(kLogFilename, synergyLogDir() + "synergy.log").toString();
m_WizardLastRun = loadCommonSetting(kWizardLastRun, 0).toInt(); m_WizardLastRun = loadCommonSetting(kWizardLastRun, 0).toInt();
m_Language = loadSetting(kLanguage, QLocale::system().name()).toString(); m_Language = loadSetting(kLanguage, QLocale::system().name()).toString();
m_StartedBefore = loadSetting(kStartedBefore, false).toBool(); m_StartedBefore = loadSetting(kStartedBefore, false).toBool();
m_AutoConfig = loadSetting(kAutoConfig, false).toBool(); m_AutoConfig = loadSetting(kAutoConfig, false).toBool();
m_AutoConfigServer = loadSetting(kAutoConfigServer, "").toString(); m_AutoConfigServer = loadSetting(kAutoConfigServer, "").toString();
{ //Scope related code together { // Scope related code together
// TODO Investigate why kElevateModeEnum isn't loaded fully // TODO Investigate why kElevateModeEnum isn't loaded fully
QVariant elevateMode = loadSetting(kElevateModeEnum); QVariant elevateMode = loadSetting(kElevateModeEnum);
if (!elevateMode.isValid()) { if (!elevateMode.isValid()) {
@ -242,51 +217,62 @@ void AppConfig::loadSettings()
m_LastExpiringWarningTime = loadSetting(kLastExpireWarningTime, 0).toInt(); m_LastExpiringWarningTime = loadSetting(kLastExpireWarningTime, 0).toInt();
m_ActivationHasRun = loadSetting(kActivationHasRun, false).toBool(); m_ActivationHasRun = loadSetting(kActivationHasRun, false).toBool();
m_MinimizeToTray = loadSetting(kMinimizeToTray, false).toBool(); m_MinimizeToTray = loadSetting(kMinimizeToTray, false).toBool();
m_LoadFromSystemScope = loadCommonSetting(kLoadSystemSettings, false).toBool(); m_LoadFromSystemScope =
loadCommonSetting(kLoadSystemSettings, false).toBool();
m_ServerGroupChecked = loadSetting(kGroupServerCheck, false).toBool(); m_ServerGroupChecked = loadSetting(kGroupServerCheck, false).toBool();
m_UseExternalConfig = loadSetting(kUseExternalConfig, false).toBool(); m_UseExternalConfig = loadSetting(kUseExternalConfig, false).toBool();
m_ConfigFile = loadSetting(kConfigFile, QDir::homePath() + "/" + synergyConfigName).toString(); m_ConfigFile =
loadSetting(kConfigFile, QDir::homePath() + "/" + synergyConfigName)
.toString();
m_UseInternalConfig = loadSetting(kUseInternalConfig, false).toBool(); m_UseInternalConfig = loadSetting(kUseInternalConfig, false).toBool();
m_ClientGroupChecked = loadSetting(kGroupClientCheck, false).toBool(); m_ClientGroupChecked = loadSetting(kGroupClientCheck, false).toBool();
m_ServerHostname = loadSetting(kServerHostname).toString(); m_ServerHostname = loadSetting(kServerHostname).toString();
m_PreventSleep = loadSetting(kPreventSleep, false).toBool(); m_PreventSleep = loadSetting(kPreventSleep, false).toBool();
m_LanguageSync = loadSetting(kLanguageSync, false).toBool(); m_LanguageSync = loadSetting(kLanguageSync, false).toBool();
m_InvertScrollDirection = loadSetting(kInvertScrollDirection, false).toBool(); m_InvertScrollDirection = loadSetting(kInvertScrollDirection, false).toBool();
m_eliteBackersUrl = loadCommonSetting(kEliteBackersUrl, "https://api2.prod.symless.com/credits/elite-backers").toString(); m_eliteBackersUrl =
loadCommonSetting(kEliteBackersUrl,
"https://api2.prod.symless.com/credits/elite-backers")
.toString();
m_guid = loadCommonSetting(kGuid, QUuid::createUuid()).toString(); m_guid = loadCommonSetting(kGuid, QUuid::createUuid()).toString();
m_licenseRegistryUrl = loadCommonSetting(kLicenseRegistryUrl, "https://api2.prod.symless.com/license/register").toString(); m_licenseRegistryUrl =
loadCommonSetting(kLicenseRegistryUrl,
"https://api2.prod.symless.com/license/register")
.toString();
m_licenseNextCheck = loadCommonSetting(kLicenseNextCheck, 0).toULongLong(); m_licenseNextCheck = loadCommonSetting(kLicenseNextCheck, 0).toULongLong();
m_ClientHostMode = loadSetting(kClientHostMode, true).toBool(); m_ClientHostMode = loadSetting(kClientHostMode, true).toBool();
m_ServerClientMode = loadSetting(kServerClientMode, true).toBool(); m_ServerClientMode = loadSetting(kServerClientMode, true).toBool();
m_InitiateConnectionFromServer = loadSetting(kInitiateConnectionFromServer, false).toBool(); m_InitiateConnectionFromServer =
loadSetting(kInitiateConnectionFromServer, false).toBool();
//only change the serial key if the settings being loaded contains a key // only change the serial key if the settings being loaded contains a key
bool updateSerial = ConfigWriter::make() bool updateSerial = ConfigWriter::make()->hasSetting(
->hasSetting(settingName(kLoadSystemSettings),ConfigWriter::kCurrent); settingName(kLoadSystemSettings), ConfigWriter::kCurrent);
//if the setting exists and is not empty // if the setting exists and is not empty
updateSerial = updateSerial && !loadSetting(kSerialKey, "").toString().trimmed().isEmpty(); updateSerial = updateSerial &&
!loadSetting(kSerialKey, "").toString().trimmed().isEmpty();
if (updateSerial) { if (updateSerial) {
m_Serialkey = loadSetting(kSerialKey, "").toString().trimmed(); m_Serialkey = loadSetting(kSerialKey, "").toString().trimmed();
m_Edition = static_cast<Edition>(loadSetting(kEditionSetting, kUnregistered).toInt()); m_Edition = static_cast<Edition>(
loadSetting(kEditionSetting, kUnregistered).toInt());
} }
//Set the default path of the TLS certificate file in the users DIR // Set the default path of the TLS certificate file in the users DIR
QString certificateFilename = QString("%1/%2/%3").arg(m_CoreInterface.getProfileDir(), QString certificateFilename =
"SSL", QString("%1/%2/%3")
"Synergy.pem"); .arg(m_CoreInterface.getProfileDir(), "SSL", "Synergy.pem");
m_TLSCertificatePath = loadSetting(kTLSCertPath, certificateFilename).toString(); m_TLSCertificatePath =
loadSetting(kTLSCertPath, certificateFilename).toString();
m_TLSKeyLength = loadSetting(kTLSKeyLength, "2048").toString(); m_TLSKeyLength = loadSetting(kTLSKeyLength, "2048").toString();
if (getCryptoEnabled()) { if (getCryptoEnabled()) {
generateCertificate(); generateCertificate();
} }
} }
void AppConfig::saveSettings() void AppConfig::saveSettings() {
{
setCommonSetting(kWizardLastRun, m_WizardLastRun); setCommonSetting(kWizardLastRun, m_WizardLastRun);
setCommonSetting(kLoadSystemSettings, m_LoadFromSystemScope); setCommonSetting(kLoadSystemSettings, m_LoadFromSystemScope);
setCommonSetting(kGroupClientCheck, m_ClientGroupChecked); setCommonSetting(kGroupClientCheck, m_ClientGroupChecked);
@ -334,24 +320,17 @@ void AppConfig::saveSettings()
} }
#ifndef SYNERGY_ENTERPRISE #ifndef SYNERGY_ENTERPRISE
bool AppConfig::activationHasRun() const bool AppConfig::activationHasRun() const { return m_ActivationHasRun; }
{
return m_ActivationHasRun;
}
AppConfig& AppConfig::activationHasRun(bool value) AppConfig &AppConfig::activationHasRun(bool value) {
{
m_ActivationHasRun = value; m_ActivationHasRun = value;
return *this; return *this;
} }
#endif #endif
QString AppConfig::lastVersion() const QString AppConfig::lastVersion() const { return m_lastVersion; }
{
return m_lastVersion;
}
void AppConfig::setLastVersion(const QString& version) { void AppConfig::setLastVersion(const QString &version) {
setSettingModified(m_lastVersion, version); setSettingModified(m_lastVersion, version);
} }
@ -360,21 +339,15 @@ void AppConfig::setScreenName(const QString &s) {
emit screenNameChanged(); emit screenNameChanged();
} }
void AppConfig::setPort(int i) { void AppConfig::setPort(int i) { setSettingModified(m_Port, i); }
setSettingModified(m_Port, i);
}
void AppConfig::setNetworkInterface(const QString &s) { void AppConfig::setNetworkInterface(const QString &s) {
setSettingModified(m_Interface, s); setSettingModified(m_Interface, s);
} }
void AppConfig::setLogLevel(int i) { void AppConfig::setLogLevel(int i) { setSettingModified(m_LogLevel, i); }
setSettingModified(m_LogLevel, i);
}
void AppConfig::setLogToFile(bool b) { void AppConfig::setLogToFile(bool b) { setSettingModified(m_LogToFile, b); }
setSettingModified(m_LogToFile, b);
}
void AppConfig::setLogFilename(const QString &s) { void AppConfig::setLogFilename(const QString &s) {
setSettingModified(m_LogFilename, s); setSettingModified(m_LogFilename, s);
@ -384,7 +357,7 @@ void AppConfig::setWizardHasRun() {
setSettingModified(m_WizardLastRun, kWizardVersion); setSettingModified(m_WizardLastRun, kWizardVersion);
} }
void AppConfig::setLanguage(const QString& language) { void AppConfig::setLanguage(const QString &language) {
setSettingModified(m_Language, language); setSettingModified(m_Language, language);
} }
@ -396,14 +369,12 @@ void AppConfig::setElevateMode(ElevateMode em) {
setSettingModified(m_ElevateMode, em); setSettingModified(m_ElevateMode, em);
} }
void AppConfig::setAutoConfig(bool autoConfig) void AppConfig::setAutoConfig(bool autoConfig) {
{
setSettingModified(m_AutoConfig, autoConfig); setSettingModified(m_AutoConfig, autoConfig);
emit zeroConfToggled(); emit zeroConfToggled();
} }
void AppConfig::setAutoConfigServer(const QString& autoConfigServer) void AppConfig::setAutoConfigServer(const QString &autoConfigServer) {
{
setSettingModified(m_AutoConfigServer, autoConfigServer); setSettingModified(m_AutoConfigServer, autoConfigServer);
} }
@ -415,19 +386,18 @@ void AppConfig::setEdition(Edition e) {
Edition AppConfig::edition() const { return m_Edition; } Edition AppConfig::edition() const { return m_Edition; }
void AppConfig::setSerialKey(const QString& serial) { void AppConfig::setSerialKey(const QString &serial) {
setSettingModified(m_Serialkey, serial); setSettingModified(m_Serialkey, serial);
setCommonSetting(kSerialKey, m_Serialkey); setCommonSetting(kSerialKey, m_Serialkey);
} }
void AppConfig::clearSerialKey() void AppConfig::clearSerialKey() { m_Serialkey.clear(); }
{
m_Serialkey.clear();
}
QString AppConfig::serialKey() const { return m_Serialkey; } QString AppConfig::serialKey() const { return m_Serialkey; }
int AppConfig::lastExpiringWarningTime() const { return m_LastExpiringWarningTime; } int AppConfig::lastExpiringWarningTime() const {
return m_LastExpiringWarningTime;
}
void AppConfig::setLastExpiringWarningTime(int newValue) { void AppConfig::setLastExpiringWarningTime(int newValue) {
setSettingModified(m_LastExpiringWarningTime, newValue); setSettingModified(m_LastExpiringWarningTime, newValue);
@ -438,29 +408,23 @@ QString AppConfig::synergysName() const { return m_SynergysName; }
QString AppConfig::synergycName() const { return m_SynergycName; } QString AppConfig::synergycName() const { return m_SynergycName; }
ElevateMode AppConfig::elevateMode() ElevateMode AppConfig::elevateMode() { return m_ElevateMode; }
{
return m_ElevateMode;
}
void AppConfig::setCryptoEnabled(bool newValue) { void AppConfig::setCryptoEnabled(bool newValue) {
if (m_CryptoEnabled != newValue && newValue){ if (m_CryptoEnabled != newValue && newValue) {
generateCertificate(); generateCertificate();
} } else {
else {
emit sslToggled(); emit sslToggled();
} }
setSettingModified(m_CryptoEnabled, newValue); setSettingModified(m_CryptoEnabled, newValue);
} }
bool AppConfig::isCryptoAvailable() const { bool AppConfig::isCryptoAvailable() const {
bool result {true}; bool result{true};
#if !defined(SYNERGY_ENTERPRISE) && !defined(SYNERGY_BUSINESS) #if !defined(SYNERGY_ENTERPRISE) && !defined(SYNERGY_BUSINESS)
result = (edition() == kPro || result = (edition() == kPro || edition() == kPro_China ||
edition() == kPro_China || edition() == kBusiness || edition() == kUltimate);
edition() == kBusiness ||
edition() == kUltimate);
#endif #endif
return result; return result;
@ -470,9 +434,7 @@ bool AppConfig::getCryptoEnabled() const {
return isCryptoAvailable() && m_CryptoEnabled; return isCryptoAvailable() && m_CryptoEnabled;
} }
void AppConfig::setAutoHide(bool b) { void AppConfig::setAutoHide(bool b) { setSettingModified(m_AutoHide, b); }
setSettingModified(m_AutoHide, b);
}
bool AppConfig::getAutoHide() { return m_AutoHide; } bool AppConfig::getAutoHide() { return m_AutoHide; }
@ -484,7 +446,7 @@ bool AppConfig::getInvertScrollDirection() const {
return m_InvertScrollDirection; return m_InvertScrollDirection;
} }
void AppConfig::setEliteBackersUrl(const QString& newValue) { void AppConfig::setEliteBackersUrl(const QString &newValue) {
setSettingModified(m_eliteBackersUrl, newValue); setSettingModified(m_eliteBackersUrl, newValue);
} }
@ -492,11 +454,11 @@ void AppConfig::setLicenseNextCheck(unsigned long long time) {
setSettingModified(m_licenseNextCheck, time); setSettingModified(m_licenseNextCheck, time);
} }
const QString& AppConfig::getEliteBackersUrl() const { const QString &AppConfig::getEliteBackersUrl() const {
return m_eliteBackersUrl; return m_eliteBackersUrl;
} }
const QString& AppConfig::getLicenseRegistryUrl() const { const QString &AppConfig::getLicenseRegistryUrl() const {
return m_licenseRegistryUrl; return m_licenseRegistryUrl;
} }
@ -504,9 +466,7 @@ unsigned long long AppConfig::getLicenseNextCheck() const {
return m_licenseNextCheck; return m_licenseNextCheck;
} }
const QString& AppConfig::getGuid() const { const QString &AppConfig::getGuid() const { return m_guid; }
return m_guid;
}
bool AppConfig::getLanguageSync() const { return m_LanguageSync; } bool AppConfig::getLanguageSync() const { return m_LanguageSync; }
@ -542,35 +502,37 @@ QString AppConfig::settingName(AppConfig::Setting name) {
return m_SynergySettingsName[name]; return m_SynergySettingsName[name];
} }
template<typename T> template <typename T>
void AppConfig::setSetting(AppConfig::Setting name, T value) { void AppConfig::setSetting(AppConfig::Setting name, T value) {
ConfigWriter::make()->setSetting(settingName(name), value); ConfigWriter::make()->setSetting(settingName(name), value);
} }
template<typename T> template <typename T>
void AppConfig::setCommonSetting(AppConfig::Setting name, T value) { void AppConfig::setCommonSetting(AppConfig::Setting name, T value) {
ConfigWriter::make()->setSetting(settingName(name), value, ConfigWriter::kUser); ConfigWriter::make()->setSetting(settingName(name), value,
ConfigWriter::make()->setSetting(settingName(name), value, ConfigWriter::kSystem); ConfigWriter::kUser);
ConfigWriter::make()->setSetting(settingName(name), value,
ConfigWriter::kSystem);
} }
QVariant AppConfig::loadSetting(AppConfig::Setting name, const QVariant& defaultValue) { QVariant AppConfig::loadSetting(AppConfig::Setting name,
const QVariant &defaultValue) {
return ConfigWriter::make()->loadSetting(settingName(name), defaultValue); return ConfigWriter::make()->loadSetting(settingName(name), defaultValue);
} }
QVariant AppConfig::loadCommonSetting(AppConfig::Setting name, const QVariant& defaultValue) const { QVariant AppConfig::loadCommonSetting(AppConfig::Setting name,
const QVariant &defaultValue) const {
QVariant result(defaultValue); QVariant result(defaultValue);
QString setting(settingName(name)); QString setting(settingName(name));
auto& writer = *ConfigWriter::make(); auto &writer = *ConfigWriter::make();
if (writer.hasSetting(setting)) { if (writer.hasSetting(setting)) {
result = writer.loadSetting(setting, defaultValue); result = writer.loadSetting(setting, defaultValue);
} } else if (writer.getScope() == ConfigWriter::kSystem) {
else if (writer.getScope() == ConfigWriter::kSystem ) {
if (writer.hasSetting(setting, ConfigWriter::kUser)) { if (writer.hasSetting(setting, ConfigWriter::kUser)) {
result = writer.loadSetting(setting, defaultValue, ConfigWriter::kUser); result = writer.loadSetting(setting, defaultValue, ConfigWriter::kUser);
} }
} } else if (writer.hasSetting(setting, ConfigWriter::kSystem)) {
else if (writer.hasSetting(setting, ConfigWriter::kSystem)){
result = writer.loadSetting(setting, defaultValue, ConfigWriter::kSystem); result = writer.loadSetting(setting, defaultValue, ConfigWriter::kSystem);
} }
@ -584,23 +546,19 @@ void AppConfig::loadScope(ConfigWriter::Scope scope) {
setDefaultValues(); setDefaultValues();
writer->setScope(scope); writer->setScope(scope);
if (writer->hasSetting(settingName(kScreenName), writer->getScope())) { if (writer->hasSetting(settingName(kScreenName), writer->getScope())) {
//If the user already has settings, then load them up now. // If the user already has settings, then load them up now.
writer->globalLoad(); writer->globalLoad();
} }
} }
} }
void AppConfig::setDefaultValues() void AppConfig::setDefaultValues() { m_InitiateConnectionFromServer = false; }
{
m_InitiateConnectionFromServer = false;
}
void AppConfig::setLoadFromSystemScope(bool value) { void AppConfig::setLoadFromSystemScope(bool value) {
if (value) { if (value) {
loadScope(ConfigWriter::kSystem); loadScope(ConfigWriter::kSystem);
} } else {
else {
loadScope(ConfigWriter::kUser); loadScope(ConfigWriter::kUser);
} }
@ -619,29 +577,17 @@ bool AppConfig::isSystemScoped() const {
return ConfigWriter::make()->getScope() == ConfigWriter::kSystem; return ConfigWriter::make()->getScope() == ConfigWriter::kSystem;
} }
bool AppConfig::getServerGroupChecked() const { bool AppConfig::getServerGroupChecked() const { return m_ServerGroupChecked; }
return m_ServerGroupChecked;
}
bool AppConfig::getUseExternalConfig() const { bool AppConfig::getUseExternalConfig() const { return m_UseExternalConfig; }
return m_UseExternalConfig;
}
const QString& AppConfig::getConfigFile() const { const QString &AppConfig::getConfigFile() const { return m_ConfigFile; }
return m_ConfigFile;
}
bool AppConfig::getUseInternalConfig() const { bool AppConfig::getUseInternalConfig() const { return m_UseInternalConfig; }
return m_UseInternalConfig;
}
bool AppConfig::getClientGroupChecked() const { bool AppConfig::getClientGroupChecked() const { return m_ClientGroupChecked; }
return m_ClientGroupChecked;
}
QString AppConfig::getServerHostname() const { QString AppConfig::getServerHostname() const { return m_ServerHostname; }
return m_ServerHostname;
}
void AppConfig::setServerGroupChecked(bool newValue) { void AppConfig::setServerGroupChecked(bool newValue) {
setSettingModified(m_ServerGroupChecked, newValue); setSettingModified(m_ServerGroupChecked, newValue);
@ -651,7 +597,7 @@ void AppConfig::setUseExternalConfig(bool newValue) {
setSettingModified(m_UseExternalConfig, newValue); setSettingModified(m_UseExternalConfig, newValue);
} }
void AppConfig::setConfigFile(const QString& newValue) { void AppConfig::setConfigFile(const QString &newValue) {
setSettingModified(m_ConfigFile, newValue); setSettingModified(m_ConfigFile, newValue);
} }
@ -663,7 +609,7 @@ void AppConfig::setClientGroupChecked(bool newValue) {
setSettingModified(m_ClientGroupChecked, newValue); setSettingModified(m_ClientGroupChecked, newValue);
} }
void AppConfig::setServerHostname(const QString& newValue) { void AppConfig::setServerHostname(const QString &newValue) {
setSettingModified(m_ServerHostname, newValue); setSettingModified(m_ServerHostname, newValue);
} }
@ -675,28 +621,23 @@ void AppConfig::setServerClientMode(bool newValue) {
setSettingModified(m_ServerClientMode, newValue); setSettingModified(m_ServerClientMode, newValue);
} }
template<typename T> template <typename T>
void AppConfig::setSettingModified(T &variable, const T& newValue) { void AppConfig::setSettingModified(T &variable, const T &newValue) {
if (variable != newValue) if (variable != newValue) {
{
variable = newValue; variable = newValue;
m_unsavedChanges = true; m_unsavedChanges = true;
} }
} }
void AppConfig::setTLSCertPath(const QString& path) { void AppConfig::setTLSCertPath(const QString &path) {
m_TLSCertificatePath = path; m_TLSCertificatePath = path;
} }
QString AppConfig::getTLSCertPath() const { QString AppConfig::getTLSCertPath() const { return m_TLSCertificatePath; }
return m_TLSCertificatePath;
}
QString AppConfig::getTLSKeyLength() const { QString AppConfig::getTLSKeyLength() const { return m_TLSKeyLength; }
return m_TLSKeyLength;
}
void AppConfig::setTLSKeyLength(const QString& length) { void AppConfig::setTLSKeyLength(const QString &length) {
if (m_TLSKeyLength != length) { if (m_TLSKeyLength != length) {
m_TLSKeyLength = length; m_TLSKeyLength = length;
generateCertificate(true); generateCertificate(true);
@ -705,8 +646,7 @@ void AppConfig::setTLSKeyLength(const QString& length) {
void AppConfig::generateCertificate(bool forceGeneration) const { void AppConfig::generateCertificate(bool forceGeneration) const {
SslCertificate sslCertificate; SslCertificate sslCertificate;
sslCertificate.generateCertificate(getTLSCertPath(), getTLSKeyLength(), forceGeneration); sslCertificate.generateCertificate(getTLSCertPath(), getTLSKeyLength(),
forceGeneration);
emit sslToggled(); emit sslToggled();
} }

View file

@ -20,15 +20,15 @@
#define APPCONFIG_H #define APPCONFIG_H
#include <QObject>
#include <QString>
#include <QVariant>
#include "ElevateMode.h"
#include <shared/EditionType.h>
#include <mutex>
#include "ConfigBase.h" #include "ConfigBase.h"
#include "ConfigWriter.h" #include "ConfigWriter.h"
#include "CoreInterface.h" #include "CoreInterface.h"
#include "ElevateMode.h"
#include <QObject>
#include <QString>
#include <QVariant>
#include <mutex>
#include <shared/EditionType.h>
// this should be incremented each time a new page is added. this is // this should be incremented each time a new page is added. this is
// saved to settings when the user finishes running the wizard. if // saved to settings when the user finishes running the wizard. if
@ -52,13 +52,9 @@ class SettingsDialog;
class ServerConfig; class ServerConfig;
class LicenseRegister; class LicenseRegister;
enum ProcessMode { enum ProcessMode { Service, Desktop };
Service,
Desktop
};
class AppConfig: public QObject, public GUI::Config::ConfigBase class AppConfig : public QObject, public GUI::Config::ConfigBase {
{
Q_OBJECT Q_OBJECT
friend class SettingsDialog; friend class SettingsDialog;
@ -66,33 +62,33 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
friend class SetupWizard; friend class SetupWizard;
friend class ServerConfig; friend class ServerConfig;
public: public:
AppConfig(); AppConfig();
public: public:
bool isWritable() const; bool isWritable() const;
bool isSystemScoped() const; bool isSystemScoped() const;
const QString& screenName() const; const QString &screenName() const;
int port() const; int port() const;
const QString& networkInterface() const; const QString &networkInterface() const;
int logLevel() const; int logLevel() const;
bool logToFile() const; bool logToFile() const;
const QString& logFilename() const; const QString &logFilename() const;
const QString logFilenameCmd() const; const QString logFilenameCmd() const;
QString logLevelText() const; QString logLevelText() const;
ProcessMode processMode() const; ProcessMode processMode() const;
bool wizardShouldRun() const; bool wizardShouldRun() const;
const QString& language() const; const QString &language() const;
bool startedBefore() const; bool startedBefore() const;
bool autoConfig() const; bool autoConfig() const;
void setAutoConfig(bool autoConfig); void setAutoConfig(bool autoConfig);
QString autoConfigServer() const; QString autoConfigServer() const;
void setAutoConfigServer(const QString& autoConfigServer); void setAutoConfigServer(const QString &autoConfigServer);
#ifndef SYNERGY_ENTERPRISE #ifndef SYNERGY_ENTERPRISE
void setEdition(Edition); void setEdition(Edition);
Edition edition() const; Edition edition() const;
void setSerialKey(const QString& serial); void setSerialKey(const QString &serial);
void clearSerialKey(); void clearSerialKey();
QString serialKey() const; QString serialKey() const;
int lastExpiringWarningTime() const; int lastExpiringWarningTime() const;
@ -115,12 +111,12 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
bool getAutoHide(); bool getAutoHide();
void setInvertScrollDirection(bool b); void setInvertScrollDirection(bool b);
bool getInvertScrollDirection() const; bool getInvertScrollDirection() const;
void setEliteBackersUrl(const QString&); void setEliteBackersUrl(const QString &);
void setLicenseNextCheck(unsigned long long); void setLicenseNextCheck(unsigned long long);
const QString& getEliteBackersUrl() const; const QString &getEliteBackersUrl() const;
const QString& getLicenseRegistryUrl() const; const QString &getLicenseRegistryUrl() const;
unsigned long long getLicenseNextCheck() const; unsigned long long getLicenseNextCheck() const;
const QString& getGuid() const; const QString &getGuid() const;
void setLanguageSync(bool b); void setLanguageSync(bool b);
bool getLanguageSync() const; bool getLanguageSync() const;
void setPreventSleep(bool b); void setPreventSleep(bool b);
@ -130,18 +126,18 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
bool getInitiateConnectionFromServer() const; bool getInitiateConnectionFromServer() const;
#ifndef SYNERGY_ENTERPRISE #ifndef SYNERGY_ENTERPRISE
bool activationHasRun() const; bool activationHasRun() const;
AppConfig& activationHasRun(bool value); AppConfig &activationHasRun(bool value);
#endif #endif
/// @brief Sets the user preference to load from SystemScope. /// @brief Sets the user preference to load from SystemScope.
/// @param [in] value /// @param [in] value
/// True - This will set the variable and load the global scope settings. /// True - This will set the variable and load the global scope
/// False - This will set the variable and load the user scope settings. /// settings. False - This will set the variable and load the user
/// scope settings.
void setLoadFromSystemScope(bool value); void setLoadFromSystemScope(bool value);
bool getServerGroupChecked() const; bool getServerGroupChecked() const;
bool getUseExternalConfig() const; bool getUseExternalConfig() const;
const QString& getConfigFile() const; const QString &getConfigFile() const;
bool getUseInternalConfig() const; bool getUseInternalConfig() const;
bool getClientGroupChecked() const; bool getClientGroupChecked() const;
QString getServerHostname() const; QString getServerHostname() const;
@ -155,22 +151,21 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
QString getTLSKeyLength() const; QString getTLSKeyLength() const;
void setServerGroupChecked(bool); void setServerGroupChecked(bool);
void setUseExternalConfig(bool) ; void setUseExternalConfig(bool);
void setConfigFile(const QString&); void setConfigFile(const QString &);
void setUseInternalConfig(bool) ; void setUseInternalConfig(bool);
void setClientGroupChecked(bool) ; void setClientGroupChecked(bool);
void setServerHostname(const QString&); void setServerHostname(const QString &);
void setClientHostMode(bool newValue); void setClientHostMode(bool newValue);
void setServerClientMode(bool newValue); void setServerClientMode(bool newValue);
/// @brief Set the path to the TLS/SSL certificate file that will be used /// @brief Set the path to the TLS/SSL certificate file that will be used
/// @param [in] path The path to the Certificate /// @param [in] path The path to the Certificate
void setTLSCertPath(const QString& path); void setTLSCertPath(const QString &path);
/// @brief Sets the key length of the private key to use in a TLS connection /// @brief Sets the key length of the private key to use in a TLS connection
/// @param [in] QString length The key length eg: 1024, 2048, 4096 /// @param [in] QString length The key length eg: 1024, 2048, 4096
void setTLSKeyLength(const QString& length); void setTLSKeyLength(const QString &length);
QString lastVersion() const; QString lastVersion() const;
@ -178,14 +173,15 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
bool getMinimizeToTray(); bool getMinimizeToTray();
void saveSettings() override; void saveSettings() override;
void setLastVersion(const QString& version); void setLastVersion(const QString &version);
/// @brief Generates TLS certificate /// @brief Generates TLS certificate
/// @param [in] bool forceGeneration Generate certificate even if it's exists. /// @param [in] bool forceGeneration Generate certificate even if it's exists.
void generateCertificate(bool forceGeneration=false) const; void generateCertificate(bool forceGeneration = false) const;
protected: protected:
/// @brief The enumeration to easily access the names of the setting inside m_SynergySettingsName /// @brief The enumeration to easily access the names of the setting inside
/// m_SynergySettingsName
enum Setting { enum Setting {
kScreenName, kScreenName,
kPort, kPort,
@ -230,24 +226,24 @@ protected:
kServerClientMode kServerClientMode
}; };
void setScreenName(const QString& s); void setScreenName(const QString &s);
void setPort(int i); void setPort(int i);
void setNetworkInterface(const QString& s); void setNetworkInterface(const QString &s);
void setLogLevel(int i); void setLogLevel(int i);
void setLogToFile(bool b); void setLogToFile(bool b);
void setLogFilename(const QString& s); void setLogFilename(const QString &s);
void setWizardHasRun(); void setWizardHasRun();
void setLanguage(const QString& language); void setLanguage(const QString &language);
void setStartedBefore(bool b); void setStartedBefore(bool b);
void setElevateMode(ElevateMode em); void setElevateMode(ElevateMode em);
/// @brief loads the setting from the current scope /// @brief loads the setting from the current scope
/// @param ignoreSystem should the load feature ignore the globalScope setting that was saved /// @param ignoreSystem should the load feature ignore the globalScope setting
/// that was saved
void loadSettings() override; void loadSettings() override;
static QString settingName(AppConfig::Setting name); static QString settingName(AppConfig::Setting name);
private: private:
QString m_ScreenName; QString m_ScreenName;
int m_Port; int m_Port;
QString m_Interface; QString m_Interface;
@ -291,9 +287,11 @@ protected:
QString m_TLSCertificatePath; /// @brief The path to the TLS certificate file QString m_TLSCertificatePath; /// @brief The path to the TLS certificate file
QString m_TLSKeyLength; /// @brief The key length of the TLS cert to make QString m_TLSKeyLength; /// @brief The key length of the TLS cert to make
bool m_LoadFromSystemScope; /// @brief should the setting be loaded from SystemScope bool m_LoadFromSystemScope; /// @brief should the setting be loaded from
/// If the user has settings but this is true then /// SystemScope
/// system settings will be loaded instead of the users /// If the user has settings but this is
/// true then system settings will be
/// loaded instead of the users
CoreInterface m_CoreInterface; CoreInterface m_CoreInterface;
@ -302,7 +300,7 @@ protected:
static const char m_SynergyLogDir[]; static const char m_SynergyLogDir[];
/// @brief Contains the string values of the settings names that will be saved /// @brief Contains the string values of the settings names that will be saved
static const char* m_SynergySettingsName[]; static const char *m_SynergySettingsName[];
/// @brief Contains the name of the default configuration filename /// @brief Contains the name of the default configuration filename
static const char synergyConfigName[]; static const char synergyConfigName[];
@ -310,37 +308,38 @@ protected:
/// @brief Sets the value of a setting /// @brief Sets the value of a setting
/// @param [in] name The Setting to be saved /// @param [in] name The Setting to be saved
/// @param [in] value The Value to be saved /// @param [in] value The Value to be saved
template <typename T> template <typename T> void setSetting(AppConfig::Setting name, T value);
void setSetting(AppConfig::Setting name, T value);
/// @brief Sets the value of a common setting /// @brief Sets the value of a common setting
/// which should have the same value for all scopes /// which should have the same value for all scopes
/// @param [in] name The Setting to be saved /// @param [in] name The Setting to be saved
/// @param [in] value The Value to be saved /// @param [in] value The Value to be saved
template <typename T> template <typename T> void setCommonSetting(AppConfig::Setting name, T value);
void setCommonSetting(AppConfig::Setting name, T value);
/// @brief Loads a setting /// @brief Loads a setting
/// @param [in] name The setting to be loaded /// @param [in] name The setting to be loaded
/// @param [in] defaultValue The default value of the setting /// @param [in] defaultValue The default value of the setting
QVariant loadSetting(AppConfig::Setting name, const QVariant& defaultValue = QVariant()); QVariant loadSetting(AppConfig::Setting name,
const QVariant &defaultValue = QVariant());
/// @brief Loads a common setting /// @brief Loads a common setting
/// @param [in] name The setting to be loaded /// @param [in] name The setting to be loaded
/// @param [in] defaultValue The default value of the setting /// @param [in] defaultValue The default value of the setting
QVariant loadCommonSetting(AppConfig::Setting name, const QVariant& defaultValue = QVariant()) const; QVariant loadCommonSetting(AppConfig::Setting name,
const QVariant &defaultValue = QVariant()) const;
/// @brief As the settings will be accessible by multiple objects this lock will ensure that /// @brief As the settings will be accessible by multiple objects this lock
/// it cant be modified by more that one object at a time if the setting is being switched /// will ensure that
/// from system to user. /// it cant be modified by more that one object at a time if the
/// setting is being switched from system to user.
std::mutex m_settings_lock; std::mutex m_settings_lock;
/// @brief Sets the setting in the config checking if it has changed and flagging that settings /// @brief Sets the setting in the config checking if it has changed and
/// flagging that settings
/// needs to be saved if the setting was different /// needs to be saved if the setting was different
/// @param [in] variable the setting that will be changed /// @param [in] variable the setting that will be changed
/// @param [in] newValue The new value of the setting /// @param [in] newValue The new value of the setting
template <typename T> template <typename T> void setSettingModified(T &variable, const T &newValue);
void setSettingModified(T& variable,const T& newValue);
/// @brief This method loads config from specified scope /// @brief This method loads config from specified scope
/// @param [in] scope which should be loaded. /// @param [in] scope which should be loaded.
@ -350,7 +349,7 @@ protected:
/// for settings that shouldn't be copied from between scopes. /// for settings that shouldn't be copied from between scopes.
void setDefaultValues(); void setDefaultValues();
signals: signals:
void sslToggled() const; void sslToggled() const;
void zeroConfToggled(); void zeroConfToggled();
void screenNameChanged() const; void screenNameChanged() const;

View file

@ -7,9 +7,12 @@ extern "C" {
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#if OSX_DEPLOYMENT_TARGET >= 1014 #if OSX_DEPLOYMENT_TARGET >= 1014
#import <UserNotifications/UNUserNotificationCenter.h> #import <UserNotifications/UNUserNotificationCenter.h>
@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate, UNUserNotificationCenterDelegate> @interface AppDelegate
: NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate,
UNUserNotificationCenterDelegate>
#else #else
@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate> @interface AppDelegate
: NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate>
#endif #endif
@end @end

View file

@ -18,29 +18,12 @@
#include "BaseConfig.h" #include "BaseConfig.h"
const char* BaseConfig::m_ModifierNames[] = const char *BaseConfig::m_ModifierNames[] = {"shift", "ctrl", "alt",
{ "meta", "super", "none"};
"shift",
"ctrl",
"alt",
"meta",
"super",
"none"
};
const char* BaseConfig::m_FixNames[] = const char *BaseConfig::m_FixNames[] = {
{ "halfDuplexCapsLock", "halfDuplexNumLock", "halfDuplexScrollLock",
"halfDuplexCapsLock", "xtestIsXineramaUnaware"};
"halfDuplexNumLock",
"halfDuplexScrollLock",
"xtestIsXineramaUnaware"
};
const char* BaseConfig::m_SwitchCornerNames[] =
{
"top-left",
"top-right",
"bottom-left",
"bottom-right"
};
const char *BaseConfig::m_SwitchCornerNames[] = {"top-left", "top-right",
"bottom-left", "bottom-right"};

View file

@ -24,25 +24,38 @@
#include <QString> #include <QString>
#include <QVariant> #include <QVariant>
class BaseConfig class BaseConfig {
{ public:
public: enum Modifier {
enum Modifier { DefaultMod = -1, Shift, Ctrl, Alt, Meta, Super, None, NumModifiers }; DefaultMod = -1,
enum SwitchCorner { TopLeft, TopRight, BottomLeft, BottomRight, NumSwitchCorners }; Shift,
Ctrl,
Alt,
Meta,
Super,
None,
NumModifiers
};
enum SwitchCorner {
TopLeft,
TopRight,
BottomLeft,
BottomRight,
NumSwitchCorners
};
enum Fix { CapsLock, NumLock, ScrollLock, XTest, NumFixes }; enum Fix { CapsLock, NumLock, ScrollLock, XTest, NumFixes };
protected: protected:
BaseConfig() {} BaseConfig() {}
virtual ~BaseConfig() {} virtual ~BaseConfig() {}
protected: protected:
template<typename T1, typename T2> template <typename T1, typename T2>
void readSettings(QSettings& settings, T1& array, const QString& arrayName, const T2& deflt) void readSettings(QSettings &settings, T1 &array, const QString &arrayName,
{ const T2 &deflt) {
int entries = settings.beginReadArray(arrayName + "Array"); int entries = settings.beginReadArray(arrayName + "Array");
array.clear(); array.clear();
for (int i = 0; i < entries; i++) for (int i = 0; i < entries; i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
QVariant v = settings.value(arrayName, deflt); QVariant v = settings.value(arrayName, deflt);
array.append(v.value<T2>()); array.append(v.value<T2>());
@ -50,13 +63,12 @@ class BaseConfig
settings.endArray(); settings.endArray();
} }
template<typename T1, typename T2> template <typename T1, typename T2>
void readSettings(QSettings& settings, T1& array, const QString& arrayName, const T2& deflt, int entries) void readSettings(QSettings &settings, T1 &array, const QString &arrayName,
{ const T2 &deflt, int entries) {
Q_ASSERT(array.size() >= entries); Q_ASSERT(array.size() >= entries);
settings.beginReadArray(arrayName + "Array"); settings.beginReadArray(arrayName + "Array");
for (int i = 0; i < entries; i++) for (int i = 0; i < entries; i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
QVariant v = settings.value(arrayName, deflt); QVariant v = settings.value(arrayName, deflt);
array[i] = v.value<T2>(); array[i] = v.value<T2>();
@ -64,28 +76,28 @@ class BaseConfig
settings.endArray(); settings.endArray();
} }
template<typename T> template <typename T>
void writeSettings(QSettings& settings, const T& array, const QString& arrayName) const void writeSettings(QSettings &settings, const T &array,
{ const QString &arrayName) const {
settings.beginWriteArray(arrayName + "Array"); settings.beginWriteArray(arrayName + "Array");
for (int i = 0; i < array.size(); i++) for (int i = 0; i < array.size(); i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
settings.setValue(arrayName, array[i]); settings.setValue(arrayName, array[i]);
} }
settings.endArray(); settings.endArray();
} }
public:
static const char *modifierName(int idx) { return m_ModifierNames[idx]; }
static const char *fixName(int idx) { return m_FixNames[idx]; }
static const char *switchCornerName(int idx) {
return m_SwitchCornerNames[idx];
}
public: private:
static const char* modifierName(int idx) { return m_ModifierNames[idx]; } static const char *m_ModifierNames[];
static const char* fixName(int idx) { return m_FixNames[idx]; } static const char *m_FixNames[];
static const char* switchCornerName(int idx) { return m_SwitchCornerNames[idx]; } static const char *m_SwitchCornerNames[];
private:
static const char* m_ModifierNames[];
static const char* m_FixNames[];
static const char* m_SwitchCornerNames[];
}; };
#endif #endif

View file

@ -19,36 +19,28 @@
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
#include "MainWindow.h"
#include "SettingsDialog.h"
#include "DataDownloader.h"
#include "QUtility.h"
#include "CommandProcess.h" #include "CommandProcess.h"
#include "DataDownloader.h"
#include "MainWindow.h"
#include "QUtility.h"
#include "SettingsDialog.h"
#include <QUrl>
#include <QThread>
#include <QDir> #include <QDir>
#include <QStandardPaths>
#include <QMessageBox> #include <QMessageBox>
#include <QStandardPaths>
#include <QThread>
#include <QUrl>
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <Windows.h> #include <Windows.h>
BonjourWindows::BonjourWindows( BonjourWindows::BonjourWindows(SettingsDialog *settingsDialog,
SettingsDialog* settingsDialog, MainWindow *mainWindow, AppConfig &appConfig)
MainWindow* mainWindow, : m_pSettingsDialog(settingsDialog), m_pMainWindow(mainWindow),
AppConfig& appConfig) : m_pBonjourInstall(nullptr), m_pDownloadMessageBox(nullptr),
m_pSettingsDialog(settingsDialog), m_pDataDownloader(nullptr), m_appConfig(appConfig) {}
m_pMainWindow(mainWindow),
m_pBonjourInstall(nullptr),
m_pDownloadMessageBox(nullptr),
m_pDataDownloader(nullptr),
m_appConfig(appConfig)
{
}
BonjourWindows::~BonjourWindows() BonjourWindows::~BonjourWindows() {
{
if (m_pBonjourInstall != nullptr) { if (m_pBonjourInstall != nullptr) {
delete m_pBonjourInstall; delete m_pBonjourInstall;
} }
@ -62,21 +54,17 @@ BonjourWindows::~BonjourWindows()
} }
} }
void BonjourWindows::downloadAndInstall() void BonjourWindows::downloadAndInstall() {
{
QUrl url; QUrl url;
int arch = getProcessorArch(); int arch = getProcessorArch();
if (arch == kProcessorArchWin32) { if (arch == kProcessorArchWin32) {
url.setUrl(bonjourBaseUrl + bonjourFilename32); url.setUrl(bonjourBaseUrl + bonjourFilename32);
m_pMainWindow->appendLogInfo("downloading bonjour (32-bit)"); m_pMainWindow->appendLogInfo("downloading bonjour (32-bit)");
} } else if (arch == kProcessorArchWin64) {
else if (arch == kProcessorArchWin64) {
url.setUrl(bonjourBaseUrl + bonjourFilename64); url.setUrl(bonjourBaseUrl + bonjourFilename64);
m_pMainWindow->appendLogInfo("downloading bonjour (64-bit)"); m_pMainWindow->appendLogInfo("downloading bonjour (64-bit)");
} } else {
else { QMessageBox::critical(m_pSettingsDialog, tr("Synergy Auto Config"),
QMessageBox::critical(
m_pSettingsDialog, tr("Synergy Auto Config"),
tr("Failed to detect system architecture.")); tr("Failed to detect system architecture."));
return; return;
} }
@ -97,8 +85,8 @@ void BonjourWindows::downloadAndInstall()
m_pDownloadMessageBox->setWindowTitle("Synergy Auto Config"); m_pDownloadMessageBox->setWindowTitle("Synergy Auto Config");
m_pDownloadMessageBox->setIcon(QMessageBox::Information); m_pDownloadMessageBox->setIcon(QMessageBox::Information);
m_pDownloadMessageBox->setText("Installing Bonjour, please wait..."); m_pDownloadMessageBox->setText("Installing Bonjour, please wait...");
QAbstractButton* cancel = m_pDownloadMessageBox->addButton( QAbstractButton *cancel =
tr("Cancel"), QMessageBox::RejectRole); m_pDownloadMessageBox->addButton(tr("Cancel"), QMessageBox::RejectRole);
m_pDownloadMessageBox->exec(); m_pDownloadMessageBox->exec();
@ -107,17 +95,16 @@ void BonjourWindows::downloadAndInstall()
} }
} }
void BonjourWindows::downloadFinished() void BonjourWindows::downloadFinished() {
{
m_pMainWindow->appendLogInfo("bonjour downloaded"); m_pMainWindow->appendLogInfo("bonjour downloaded");
install(); install();
} }
void BonjourWindows::install() void BonjourWindows::install() {
{
m_pMainWindow->appendLogInfo("installing bonjour"); m_pMainWindow->appendLogInfo("installing bonjour");
QString tempLocation = QStandardPaths::writableLocation(QStandardPaths::TempLocation); QString tempLocation =
QStandardPaths::writableLocation(QStandardPaths::TempLocation);
QString filename = tempLocation; QString filename = tempLocation;
filename.append("\\").append(bonjourTargetFilename); filename.append("\\").append(bonjourTargetFilename);
@ -148,7 +135,7 @@ void BonjourWindows::install()
m_pBonjourInstall = new CommandProcess("msiexec", arguments); m_pBonjourInstall = new CommandProcess("msiexec", arguments);
QThread* thread = new QThread; QThread *thread = new QThread;
connect(m_pBonjourInstall, SIGNAL(finished()), this, SLOT(installFinished())); connect(m_pBonjourInstall, SIGNAL(finished()), this, SLOT(installFinished()));
connect(m_pBonjourInstall, SIGNAL(finished()), thread, SLOT(quit())); connect(m_pBonjourInstall, SIGNAL(finished()), thread, SLOT(quit()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
@ -161,8 +148,7 @@ void BonjourWindows::install()
m_pDownloadMessageBox->hide(); m_pDownloadMessageBox->hide();
} }
bool BonjourWindows::isRunning() const bool BonjourWindows::isRunning() const {
{
QString name = "Bonjour Service"; QString name = "Bonjour Service";
SC_HANDLE hSCManager; SC_HANDLE hSCManager;
@ -170,12 +156,14 @@ bool BonjourWindows::isRunning() const
if (hSCManager == nullptr) { if (hSCManager == nullptr) {
m_pMainWindow->appendLogError( m_pMainWindow->appendLogError(
QString("failed to open a service controller manager, error: %1").arg(GetLastError())); QString("failed to open a service controller manager, error: %1")
.arg(GetLastError()));
return false; return false;
} }
auto array = name.toLocal8Bit(); auto array = name.toLocal8Bit();
SC_HANDLE hService = OpenService(hSCManager, array.data(), SERVICE_QUERY_STATUS); SC_HANDLE hService =
OpenService(hSCManager, array.data(), SERVICE_QUERY_STATUS);
if (hService == nullptr) { if (hService == nullptr) {
m_pMainWindow->appendLogDebug( m_pMainWindow->appendLogDebug(
@ -193,8 +181,7 @@ bool BonjourWindows::isRunning() const
return false; return false;
} }
void BonjourWindows::installFinished() void BonjourWindows::installFinished() {
{
m_pMainWindow->appendLogInfo("bonjour installed"); m_pMainWindow->appendLogInfo("bonjour installed");
m_appConfig.setAutoConfig(true); m_appConfig.setAutoConfig(true);
m_pSettingsDialog->allowAutoConfig(); m_pSettingsDialog->allowAutoConfig();

View file

@ -34,12 +34,12 @@ class CommandProcess;
class DataDownloader; class DataDownloader;
class AppConfig; class AppConfig;
class BonjourWindows : public QObject class BonjourWindows : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
BonjourWindows(SettingsDialog* settingsDialog, MainWindow* mainWindow, AppConfig& appConfig); BonjourWindows(SettingsDialog *settingsDialog, MainWindow *mainWindow,
AppConfig &appConfig);
virtual ~BonjourWindows(); virtual ~BonjourWindows();
public: public:
@ -54,12 +54,12 @@ private:
void install(); void install();
private: private:
SettingsDialog* m_pSettingsDialog; SettingsDialog *m_pSettingsDialog;
MainWindow* m_pMainWindow; MainWindow *m_pMainWindow;
CommandProcess* m_pBonjourInstall; CommandProcess *m_pBonjourInstall;
QMessageBox* m_pDownloadMessageBox; QMessageBox *m_pDownloadMessageBox;
DataDownloader* m_pDataDownloader; DataDownloader *m_pDataDownloader;
AppConfig& m_appConfig; AppConfig &m_appConfig;
}; };
#endif // Q_OS_WIN #endif // Q_OS_WIN

View file

@ -1,14 +1,9 @@
#include "CancelActivationDialog.h" #include "CancelActivationDialog.h"
#include "ui_CancelActivationDialog.h" #include "ui_CancelActivationDialog.h"
CancelActivationDialog::CancelActivationDialog(QWidget *parent) : CancelActivationDialog::CancelActivationDialog(QWidget *parent)
QDialog(parent), : QDialog(parent), ui(new Ui::CancelActivationDialog) {
ui(new Ui::CancelActivationDialog)
{
ui->setupUi(this); ui->setupUi(this);
} }
CancelActivationDialog::~CancelActivationDialog() CancelActivationDialog::~CancelActivationDialog() { delete ui; }
{
delete ui;
}

View file

@ -7,8 +7,7 @@ namespace Ui {
class CancelActivationDialog; class CancelActivationDialog;
} }
class CancelActivationDialog : public QDialog class CancelActivationDialog : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:

View file

@ -20,40 +20,29 @@
#include "MainWindow.h" #include "MainWindow.h"
#include <QMessageBox>
#include <QHostAddress> #include <QHostAddress>
#include <QMessageBox>
ClientConnection::ClientConnection(MainWindow& parent) : ClientConnection::ClientConnection(MainWindow &parent) : m_parent(parent) {}
m_parent(parent)
{
}
void ClientConnection::update(const QString& line) void ClientConnection::update(const QString &line) {
{ if (m_checkConnection && checkMainWindow()) {
if (m_checkConnection && checkMainWindow()) if (line.contains("failed to connect to server")) {
{
if (line.contains("failed to connect to server"))
{
m_checkConnection = false; m_checkConnection = false;
if (!line.contains("server refused client with our name") && if (!line.contains("server refused client with our name") &&
!line.contains("Trying next address")) !line.contains("Trying next address")) {
{
showMessage(getMessage(line)); showMessage(getMessage(line));
} }
} } else if (line.contains("connected to server")) {
else if (line.contains("connected to server"))
{
m_checkConnection = false; m_checkConnection = false;
} }
} }
} }
bool ClientConnection::checkMainWindow() bool ClientConnection::checkMainWindow() {
{
bool result = m_parent.isActiveWindow(); bool result = m_parent.isActiveWindow();
if (m_parent.isMinimized() || m_parent.isHidden()) if (m_parent.isMinimized() || m_parent.isHidden()) {
{
m_parent.showNormal(); m_parent.showNormal();
m_parent.activateWindow(); m_parent.activateWindow();
result = true; result = true;
@ -62,20 +51,20 @@ bool ClientConnection::checkMainWindow()
return result; return result;
} }
QString ClientConnection::getMessage(const QString& line) const QString ClientConnection::getMessage(const QString &line) const {
{ QString message(QObject::tr("Connection failed.\nCheck the IP address on the "
QString message(QObject::tr("Connection failed.\nCheck the IP address on the server, your TLS and firewall settings.")); "server, your TLS and firewall settings."));
if (line.contains("server already has a connected client with our name")) if (line.contains("server already has a connected client with our name")) {
{ message =
message = QObject::tr("Connection failed.\nYou can’t name 2 computers the same."); QObject::tr("Connection failed.\nYou can’t name 2 computers the same.");
} } else {
else
{
QHostAddress address(m_parent.appConfig().getServerHostname()); QHostAddress address(m_parent.appConfig().getServerHostname());
if (address.isNull()) if (address.isNull()) {
{ message =
message = QObject::tr("We can’t connect to the server \"%1\" try to connect using the server IP address and check your firewall settings.") QObject::tr(
"We can’t connect to the server \"%1\" try to connect using the "
"server IP address and check your firewall settings.")
.arg(m_parent.appConfig().getServerHostname()); .arg(m_parent.appConfig().getServerHostname());
} }
} }
@ -83,15 +72,13 @@ QString ClientConnection::getMessage(const QString& line) const
return message; return message;
} }
void ClientConnection::showMessage(const QString& message) const void ClientConnection::showMessage(const QString &message) const {
{
QMessageBox dialog(&m_parent); QMessageBox dialog(&m_parent);
dialog.addButton(QObject::tr("Close"), QMessageBox::RejectRole); dialog.addButton(QObject::tr("Close"), QMessageBox::RejectRole);
dialog.setText(message); dialog.setText(message);
dialog.exec(); dialog.exec();
} }
void ClientConnection::setCheckConnection(bool checkConnection) void ClientConnection::setCheckConnection(bool checkConnection) {
{
m_checkConnection = checkConnection; m_checkConnection = checkConnection;
} }

View file

@ -23,20 +23,19 @@
class MainWindow; class MainWindow;
class ClientConnection class ClientConnection {
{ MainWindow &m_parent;
MainWindow& m_parent;
bool m_checkConnection = false; bool m_checkConnection = false;
public: public:
explicit ClientConnection(MainWindow& parent); explicit ClientConnection(MainWindow &parent);
void update(const QString& line); void update(const QString &line);
void setCheckConnection(bool checkConnection); void setCheckConnection(bool checkConnection);
private: private:
QString getMessage(const QString& line) const; QString getMessage(const QString &line) const;
bool checkMainWindow(); bool checkMainWindow();
void showMessage(const QString& message) const; void showMessage(const QString &message) const;
}; };
#endif // CLIENTCONNECTION_H #endif // CLIENTCONNECTION_H

View file

@ -20,38 +20,32 @@
#include <QProcess> #include <QProcess>
#include <stdexcept> #include <stdexcept>
CommandProcess::CommandProcess(QString cmd, QStringList arguments, QString input) : CommandProcess::CommandProcess(QString cmd, QStringList arguments,
m_Command(cmd), QString input)
m_Arguments(arguments), : m_Command(cmd), m_Arguments(arguments), m_Input(input) {}
m_Input(input)
{
}
QString CommandProcess::run() QString CommandProcess::run() {
{
QProcess process; QProcess process;
process.setReadChannel(QProcess::StandardOutput); process.setReadChannel(QProcess::StandardOutput);
process.start(m_Command, m_Arguments); process.start(m_Command, m_Arguments);
bool success = process.waitForStarted(); bool success = process.waitForStarted();
QString output, error; QString output, error;
if (success) if (success) {
{
if (!m_Input.isEmpty()) { if (!m_Input.isEmpty()) {
process.write(m_Input.toStdString().c_str()); process.write(m_Input.toStdString().c_str());
} }
if (process.waitForFinished()) { if (process.waitForFinished()) {
output = QString::fromLocal8Bit(process.readAllStandardOutput().trimmed()); output =
QString::fromLocal8Bit(process.readAllStandardOutput().trimmed());
error = process.readAllStandardError().trimmed(); error = process.readAllStandardError().trimmed();
} }
} }
int code = process.exitCode(); int code = process.exitCode();
if (!error.isEmpty() || !success || code != 0) if (!error.isEmpty() || !success || code != 0) {
{ throw std::runtime_error(QString("Code: %1\nError: %2")
throw std::runtime_error(
QString("Code: %1\nError: %2")
.arg(process.exitCode()) .arg(process.exitCode())
.arg(error.isEmpty() ? "Unknown" : error) .arg(error.isEmpty() ? "Unknown" : error)
.toStdString()); .toStdString());

View file

@ -21,8 +21,7 @@
#include <QObject> #include <QObject>
#include <QStringList> #include <QStringList>
class CommandProcess : public QObject class CommandProcess : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:

View file

@ -19,30 +19,33 @@
#define SYNERGY_CORE_CONFIGBASE_H #define SYNERGY_CORE_CONFIGBASE_H
namespace GUI { namespace GUI {
namespace Config { namespace Config {
///@brief This abstract class will be used by all classes that use the ConfigWriter ///@brief This abstract class will be used by all classes that use the
/// to allow global saving and loading /// ConfigWriter
class ConfigBase { /// to allow global saving and loading
public : class ConfigBase {
public:
ConfigBase() = default; ConfigBase() = default;
virtual ~ConfigBase() = default; virtual ~ConfigBase() = default;
/// @brief The function that is called when the settings need to be loaded from file /// @brief The function that is called when the settings need to be loaded
/// from file
virtual void loadSettings() = 0; virtual void loadSettings() = 0;
/// @brief The function that is called when the settings need to be saved to file /// @brief The function that is called when the settings need to be saved to
/// file
virtual void saveSettings() = 0; virtual void saveSettings() = 0;
/// @brief Returns true if the class has marked itself with having unsaved changes /// @brief Returns true if the class has marked itself with having unsaved
/// changes
bool modified() const { return m_unsavedChanges; } bool modified() const { return m_unsavedChanges; }
protected: protected:
/// @brief Does the class have unsaved changes in it. /// @brief Does the class have unsaved changes in it.
bool m_unsavedChanges = false; bool m_unsavedChanges = false;
};
}; } // namespace Config
} } // namespace GUI
} #endif // SYNERGY_CORE_CONFIGBASE_H
#endif //SYNERGY_CORE_CONFIGBASE_H

View file

@ -20,20 +20,19 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QFile> #include <QFile>
#include "ConfigWriter.h"
#include "ConfigBase.h" #include "ConfigBase.h"
#include "ConfigWriter.h"
namespace { namespace {
QString getSystemSettingPath() QString getSystemSettingPath() {
{
const QString settingFilename("SystemConfig.ini"); const QString settingFilename("SystemConfig.ini");
QString path; QString path;
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
// Program file // Program file
path = QCoreApplication::applicationDirPath() + "\\"; path = QCoreApplication::applicationDirPath() + "\\";
#elif defined(Q_OS_DARWIN) #elif defined(Q_OS_DARWIN)
//Global preferances dir // Global preferances dir
// Would be nice to use /library, but QT has no elevate system in place // Would be nice to use /library, but QT has no elevate system in place
path = "/usr/local/etc/symless/"; path = "/usr/local/etc/symless/";
#elif defined(Q_OS_LINUX) #elif defined(Q_OS_LINUX)
@ -47,86 +46,81 @@ QString getSystemSettingPath()
} }
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
void loadOldSystemSettings(QSettings& settings) void loadOldSystemSettings(QSettings &settings) {
{
if (!QFile(settings.fileName()).exists()) { if (!QFile(settings.fileName()).exists()) {
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, "SystemConfig.ini"); QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope,
QSettings oldSystemSettings (QSettings::IniFormat, "SystemConfig.ini");
QSettings::SystemScope, QSettings oldSystemSettings(QSettings::IniFormat, QSettings::SystemScope,
QCoreApplication::organizationName(), QCoreApplication::organizationName(),
QCoreApplication::applicationName()); QCoreApplication::applicationName());
if (QFile(oldSystemSettings.fileName()).exists()) { if (QFile(oldSystemSettings.fileName()).exists()) {
for (const auto& key : oldSystemSettings.allKeys()) { for (const auto &key : oldSystemSettings.allKeys()) {
settings.setValue(key, oldSystemSettings.value(key)); settings.setValue(key, oldSystemSettings.value(key));
} }
} }
//Restore system settings path // Restore system settings path
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, getSystemSettingPath()); QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope,
getSystemSettingPath());
} }
} }
#endif #endif
} } // namespace
namespace GUI { namespace GUI {
namespace Config { namespace Config {
//Assignment of static variable // Assignment of static variable
ConfigWriter *ConfigWriter::s_pConfiguration = nullptr; ConfigWriter *ConfigWriter::s_pConfiguration = nullptr;
ConfigWriter *ConfigWriter::make() {
ConfigWriter *ConfigWriter::make() {
// Only one ConfigWriter can exist at any one time (Singleton) // Only one ConfigWriter can exist at any one time (Singleton)
if (!s_pConfiguration) { if (!s_pConfiguration) {
s_pConfiguration = new ConfigWriter(); s_pConfiguration = new ConfigWriter();
} }
return s_pConfiguration; return s_pConfiguration;
} }
ConfigWriter::ConfigWriter() { ConfigWriter::ConfigWriter() {
QSettings::setPath(QSettings::Format::IniFormat, QSettings::setPath(QSettings::Format::IniFormat,
QSettings::Scope::SystemScope, QSettings::Scope::SystemScope, getSystemSettingPath());
getSystemSettingPath());
//Config will default to User settings if they exist, // Config will default to User settings if they exist,
// otherwise it will load System setting and save them to User settings // otherwise it will load System setting and save them to User settings
m_pSettingsSystem = new QSettings(QSettings::Format::IniFormat, m_pSettingsSystem =
QSettings::Scope::SystemScope, new QSettings(QSettings::Format::IniFormat, QSettings::Scope::SystemScope,
QCoreApplication::organizationName(), QCoreApplication::organizationName(),
QCoreApplication::applicationName()); QCoreApplication::applicationName());
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
//This call is needed for backwardcapability with old settings. // This call is needed for backwardcapability with old settings.
loadOldSystemSettings(*m_pSettingsSystem); loadOldSystemSettings(*m_pSettingsSystem);
#endif #endif
//defaults to user scope, if we set the scope specifically then we also have to set // defaults to user scope, if we set the scope specifically then we also have
// the application name and the organisation name which breaks backwards compatibility // to set
// See #6730 // the application name and the organisation name which breaks backwards
// compatibility See #6730
m_pSettingsUser = new QSettings(); m_pSettingsUser = new QSettings();
//Set scope to user for initially // Set scope to user for initially
m_pSettingsCurrent = m_pSettingsUser; m_pSettingsCurrent = m_pSettingsUser;
} }
void ConfigWriter::destroy() { destroy(s_pConfiguration); }
void ConfigWriter::destroy() { ConfigWriter::~ConfigWriter() {
destroy(s_pConfiguration); while (!m_pCallerList.empty()) {
}
ConfigWriter::~ConfigWriter() {
while(!m_pCallerList.empty()) {
m_pCallerList.pop_back(); m_pCallerList.pop_back();
} }
m_pSettingsCurrent = nullptr; //this only references other pointers m_pSettingsCurrent = nullptr; // this only references other pointers
destroy(m_pSettingsSystem); destroy(m_pSettingsSystem);
destroy(m_pSettingsUser); destroy(m_pSettingsUser);
} }
bool ConfigWriter::hasSetting(const QString &name, Scope scope) const {
bool ConfigWriter::hasSetting(const QString &name, Scope scope) const { switch (scope) {
switch (scope){
case kUser: case kUser:
return m_pSettingsUser->contains(name); return m_pSettingsUser->contains(name);
case kSystem: case kSystem:
@ -134,14 +128,15 @@ namespace GUI {
default: default:
return m_pSettingsCurrent->contains(name); return m_pSettingsCurrent->contains(name);
} }
} }
bool ConfigWriter::isWritable() const { bool ConfigWriter::isWritable() const {
return m_pSettingsCurrent->isWritable(); return m_pSettingsCurrent->isWritable();
} }
QVariant ConfigWriter::loadSetting(const QString& name, const QVariant &defaultValue, Scope scope) { QVariant ConfigWriter::loadSetting(const QString &name,
switch (scope){ const QVariant &defaultValue, Scope scope) {
switch (scope) {
case kUser: case kUser:
return m_pSettingsUser->value(name, defaultValue); return m_pSettingsUser->value(name, defaultValue);
case kSystem: case kSystem:
@ -149,10 +144,9 @@ namespace GUI {
default: default:
return m_pSettingsCurrent->value(name, defaultValue); return m_pSettingsCurrent->value(name, defaultValue);
} }
} }
void ConfigWriter::setScope(ConfigWriter::Scope scope) {
void ConfigWriter::setScope(ConfigWriter::Scope scope) {
if (m_CurrentScope != scope) { if (m_CurrentScope != scope) {
m_CurrentScope = scope; m_CurrentScope = scope;
switch (scope) { switch (scope) {
@ -163,25 +157,23 @@ namespace GUI {
m_pSettingsCurrent = m_pSettingsSystem; m_pSettingsCurrent = m_pSettingsSystem;
break; break;
default: default:
//setScope should never be kCurrent // setScope should never be kCurrent
assert(scope); assert(scope);
} }
} }
} }
ConfigWriter::Scope ConfigWriter::getScope() const { ConfigWriter::Scope ConfigWriter::getScope() const { return m_CurrentScope; }
return m_CurrentScope;
}
void ConfigWriter::globalLoad() { void ConfigWriter::globalLoad() {
for (auto &i : m_pCallerList) { for (auto &i : m_pCallerList) {
i->loadSettings(); i->loadSettings();
} }
} }
void ConfigWriter::globalSave() { void ConfigWriter::globalSave() {
//Save if there are any unsaved changes otherwise skip // Save if there are any unsaved changes otherwise skip
if (unsavedChanges()) { if (unsavedChanges()) {
for (auto &i : m_pCallerList) { for (auto &i : m_pCallerList) {
i->saveSettings(); i->saveSettings();
@ -192,35 +184,29 @@ namespace GUI {
m_unsavedChanges = false; m_unsavedChanges = false;
} }
} }
QSettings &ConfigWriter::settings() { QSettings &ConfigWriter::settings() { return *m_pSettingsCurrent; }
return *m_pSettingsCurrent;
}
void ConfigWriter::registerClass(ConfigBase * receiver) { void ConfigWriter::registerClass(ConfigBase *receiver) {
m_pCallerList.push_back(receiver); m_pCallerList.push_back(receiver);
} }
bool ConfigWriter::unsavedChanges() const {
bool ConfigWriter::unsavedChanges() const {
if (m_unsavedChanges) { if (m_unsavedChanges) {
return true; return true;
} }
for (const auto &i : m_pCallerList) { for (const auto &i : m_pCallerList) {
if (i->modified()){ if (i->modified()) {
//If any class returns true there is no point checking more // If any class returns true there is no point checking more
return true; return true;
} }
} }
// If this line is reached no class has unsaved changes // If this line is reached no class has unsaved changes
return false; return false;
}
void ConfigWriter::markUnsaved() {
m_unsavedChanges = true;
}
}
} }
void ConfigWriter::markUnsaved() { m_unsavedChanges = true; }
} // namespace Config
} // namespace GUI

View file

@ -17,25 +17,24 @@
#ifndef SYNERGY_CORE_CONFIGWRITER_H #ifndef SYNERGY_CORE_CONFIGWRITER_H
#define SYNERGY_CORE_CONFIGWRITER_H #define SYNERGY_CORE_CONFIGWRITER_H
#include <QVariant>
#include <QSettings> #include <QSettings>
#include <QVariant>
/// @brief Contains GUI code /// @brief Contains GUI code
namespace GUI { namespace GUI {
/// @brief Contains Configuration code /// @brief Contains Configuration code
namespace Config { namespace Config {
//Forward declare the class referenced by pointer // Forward declare the class referenced by pointer
class ConfigBase; class ConfigBase;
class ConfigWriter: private QObject { class ConfigWriter : private QObject {
public:
public:
/// @brief the public way to construct the configuration calls /// @brief the public way to construct the configuration calls
/// The pointer returned is owned by this class and should not be stored /// The pointer returned is owned by this class and should not be
/// by other classes. /// stored by other classes.
static ConfigWriter* make(); static ConfigWriter *make();
/// @brief the public way to destroy the configuration class /// @brief the public way to destroy the configuration class
static void destroy(); static void destroy();
@ -43,13 +42,13 @@ namespace GUI {
~ConfigWriter() override; ~ConfigWriter() override;
///@brief An Enumeration of all the scopes available ///@brief An Enumeration of all the scopes available
enum Scope { kCurrent, kSystem, kUser}; enum Scope { kCurrent, kSystem, kUser };
/// @brief Checks if the setting exists /// @brief Checks if the setting exists
/// @param [in] name The name of the setting to check /// @param [in] name The name of the setting to check
/// @param [in] scope The scope to search in /// @param [in] scope The scope to search in
/// @return bool True if the current scope has the named setting /// @return bool True if the current scope has the named setting
bool hasSetting(const QString& name, Scope scope = kCurrent) const; bool hasSetting(const QString &name, Scope scope = kCurrent) const;
/// @brief Checks if the current scope settings writable /// @brief Checks if the current scope settings writable
/// @return bool True if the current scope writable /// @return bool True if the current scope writable
@ -58,17 +57,22 @@ namespace GUI {
/// @brief Sets the value of a setting /// @brief Sets the value of a setting
/// @param [in] name The Setting to be saved /// @param [in] name The Setting to be saved
/// @param [in] value The Value to be saved (Templated) /// @param [in] value The Value to be saved (Templated)
/// @param [in] scope The scope to get the value from, default is current scope /// @param [in] scope The scope to get the value from, default is current
/// scope
template <typename T> template <typename T>
void setSetting(const QString& name, T value, Scope scope = kCurrent); void setSetting(const QString &name, T value, Scope scope = kCurrent);
/// @brief Loads a setting /// @brief Loads a setting
/// @param [in] name The setting to be loaded /// @param [in] name The setting to be loaded
/// @param [in] defaultValue The default value of the setting /// @param [in] defaultValue The default value of the setting
/// @param [in] scope The scope to get the value from, default is current scope /// @param [in] scope The scope to get the value from, default is current
QVariant loadSetting(const QString& name, const QVariant& defaultValue = QVariant(), Scope scope = kCurrent); /// scope
QVariant loadSetting(const QString &name,
const QVariant &defaultValue = QVariant(),
Scope scope = kCurrent);
/// @brief Changes the setting save and load location between System and User scope /// @brief Changes the setting save and load location between System and User
/// scope
/// @param [in] scope The scope to set /// @param [in] scope The scope to set
void setScope(Scope scope = kUser); void setScope(Scope scope = kUser);
@ -83,55 +87,59 @@ namespace GUI {
void globalSave(); void globalSave();
/// @brief Returns the current scopes settings object /// @brief Returns the current scopes settings object
/// If more specialize control into the settings is needed this can provide /// If more specialize control into the settings is needed this can
/// direct access to the settings file handler /// provide direct access to the settings file handler
/// @return QSettings The Settings object as a reference /// @return QSettings The Settings object as a reference
QSettings& settings(); QSettings &settings();
/// @brief This marks the settings as unsaved if the settings() was used to directly affect the config file /// @brief This marks the settings as unsaved if the settings() was used to
/// directly affect the config file
void markUnsaved(); void markUnsaved();
/// @brief Register a class to receives globalLoad and globalSave events /// @brief Register a class to receives globalLoad and globalSave events
/// @param [in] ConfigBase The class that will receive the events /// @param [in] ConfigBase The class that will receive the events
void registerClass(ConfigBase* receiver); void registerClass(ConfigBase *receiver);
/// @brief Checks if any registered class has any unsaved changes /// @brief Checks if any registered class has any unsaved changes
/// @return bool True if any registered class has unsaved changes /// @return bool True if any registered class has unsaved changes
bool unsavedChanges() const; bool unsavedChanges() const;
protected: protected:
Scope m_CurrentScope = kUser; /// @brief The current scope of the settings Scope m_CurrentScope = kUser; /// @brief The current scope of the settings
QSettings* m_pSettingsCurrent = nullptr; /// @brief The currently active settings QSettings *m_pSettingsCurrent =
QSettings* m_pSettingsUser = nullptr; /// @brief The user specific settings nullptr; /// @brief The currently active settings
QSettings* m_pSettingsSystem = nullptr; /// @brief The system wide settings QSettings *m_pSettingsUser = nullptr; /// @brief The user specific settings
QSettings *m_pSettingsSystem = nullptr; /// @brief The system wide settings
private:
private:
/// @brief Contains a list all all classes that hook into the writer. /// @brief Contains a list all all classes that hook into the writer.
/// This allows all classes that save settings to be called an updated /// This allows all classes that save settings to be called an updated
/// on a save and reload by any other class /// on a save and reload by any other class
std::list<ConfigBase*> m_pCallerList; std::list<ConfigBase *> m_pCallerList;
/// @brief if this class modified settings then set the flag /// @brief if this class modified settings then set the flag
bool m_unsavedChanges = false; bool m_unsavedChanges = false;
/// @brief The constructor, as this is a singolton we want to control who can call the constructor /// @brief The constructor, as this is a singolton we want to control who can
/// call the constructor
ConfigWriter(); ConfigWriter();
/// @brief the pointer of the ConfigWriter for singolton use /// @brief the pointer of the ConfigWriter for singolton use
static ConfigWriter* s_pConfiguration; static ConfigWriter *s_pConfiguration;
/// @brief deletes pointers and sets the value to null /// @brief deletes pointers and sets the value to null
template<class T> static inline void destroy(T*& p) { delete p; p = 0; } template <class T> static inline void destroy(T *&p) {
}; delete p;
p = 0;
}
};
// Implementation of a template function needs to be visible to all calls thus is must be in the header // Implementation of a template function needs to be visible to all calls thus
// Moved so its not bulking out the class definition // is must be in the header Moved so its not bulking out the class definition
template<typename T> template <typename T>
void ConfigWriter::setSetting(const QString& name, T value, Scope scope) { void ConfigWriter::setSetting(const QString &name, T value, Scope scope) {
switch (scope){ switch (scope) {
case kUser: case kUser:
m_pSettingsUser->setValue(name, value); m_pSettingsUser->setValue(name, value);
break; break;
@ -143,7 +151,7 @@ namespace GUI {
break; break;
} }
m_unsavedChanges = true; m_unsavedChanges = true;
}
}
} }
#endif //SYNERGY_CORE_CONFIGWRITER_H } // namespace Config
} // namespace GUI
#endif // SYNERGY_CORE_CONFIGWRITER_H

View file

@ -21,9 +21,9 @@
#include "QUtility.h" #include "QUtility.h"
#include <QCoreApplication> #include <QCoreApplication>
#include <QDir>
#include <QProcess> #include <QProcess>
#include <QtGlobal> #include <QtGlobal>
#include <QDir>
#include <stdexcept> #include <stdexcept>
static const char kCoreBinary[] = "syntool"; static const char kCoreBinary[] = "syntool";
@ -34,39 +34,30 @@ static const char kSerialKeyFilename[] = "Synergy.subkey";
static const char kSerialKeyFilename[] = ".synergy.subkey"; static const char kSerialKeyFilename[] = ".synergy.subkey";
#endif #endif
CoreInterface::CoreInterface() CoreInterface::CoreInterface() {}
{
}
QString CoreInterface::getProfileDir() QString CoreInterface::getProfileDir() {
{
QStringList args("--get-profile-dir"); QStringList args("--get-profile-dir");
return run(args); return run(args);
} }
QString CoreInterface::getInstalledDir() QString CoreInterface::getInstalledDir() {
{
QStringList args("--get-installed-dir"); QStringList args("--get-installed-dir");
return run(args); return run(args);
} }
QString CoreInterface::getArch() QString CoreInterface::getArch() {
{
QStringList args("--get-arch"); QStringList args("--get-arch");
return run(args); return run(args);
} }
QString CoreInterface::getSerialKeyFilePath() QString CoreInterface::getSerialKeyFilePath() {
{
QString filename = getProfileDir() + QDir::separator() + kSerialKeyFilename; QString filename = getProfileDir() + QDir::separator() + kSerialKeyFilename;
return filename; return filename;
} }
QString CoreInterface::run(const QStringList& args, const QString& input) QString CoreInterface::run(const QStringList &args, const QString &input) {
{ QString program(QCoreApplication::applicationDirPath() + "/" + kCoreBinary);
QString program(
QCoreApplication::applicationDirPath()
+ "/" + kCoreBinary);
CommandProcess commandProcess(program, args, input); CommandProcess commandProcess(program, args, input);
return commandProcess.run(); return commandProcess.run();

View file

@ -19,8 +19,7 @@
#include <QString> #include <QString>
class CoreInterface class CoreInterface {
{
public: public:
CoreInterface(); CoreInterface();
@ -28,5 +27,5 @@ public:
QString getInstalledDir(); QString getInstalledDir();
QString getArch(); QString getArch();
QString getSerialKeyFilePath(); QString getSerialKeyFilePath();
QString run(const QStringList& args, const QString& input = ""); QString run(const QStringList &args, const QString &input = "");
}; };

View file

@ -16,47 +16,39 @@
*/ */
#include "CreditsLoader.h" #include "CreditsLoader.h"
#include "MainWindow.h"
#include "AppConfig.h" #include "AppConfig.h"
#include "MainWindow.h"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonParseError> #include <QJsonParseError>
#include <QNetworkReply>
#include <QNetworkRequest>
namespace { namespace {
class CreditsResponse { class CreditsResponse {
public: public:
explicit CreditsResponse(const QByteArray& response) { explicit CreditsResponse(const QByteArray &response) {
auto data = parseJson(response); auto data = parseJson(response);
m_status = data["status"].toString(); m_status = data["status"].toString();
if (isSuccess()) { if (isSuccess()) {
m_data = data["data"].toString(); m_data = data["data"].toString();
} } else if (isFailed()) {
else if (isFailed()) {
m_data = data["message"].toString(); m_data = data["message"].toString();
} } else {
else {
m_data = "Unknown response from the server"; m_data = "Unknown response from the server";
} }
} }
bool isSuccess() const { bool isSuccess() const { return (m_status == "success"); }
return (m_status == "success");
}
bool isFailed() const { bool isFailed() const { return (m_status == "failed"); }
return (m_status == "failed");
}
const QString& getData() const { const QString &getData() const { return m_data; }
return m_data;
}
private: private:
QMap<QString, QVariant> parseJson(const QByteArray& json) const { QMap<QString, QVariant> parseJson(const QByteArray &json) const {
QJsonParseError jsonError; QJsonParseError jsonError;
auto data = QJsonDocument::fromJson(json, &jsonError); auto data = QJsonDocument::fromJson(json, &jsonError);
if (jsonError.error == QJsonParseError::NoError) { if (jsonError.error == QJsonParseError::NoError) {
@ -69,40 +61,38 @@ private:
QString m_status; QString m_status;
}; };
} // namespace
CreditsLoader::CreditsLoader(MainWindow &mainWindow, const AppConfig &config)
: m_mainWindow(mainWindow), m_config(config) {
connect(&m_manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(replyFinished(QNetworkReply *)));
} }
CreditsLoader::CreditsLoader(MainWindow& mainWindow, const AppConfig& config) : void CreditsLoader::loadEliteBackers() {
m_mainWindow(mainWindow),
m_config(config)
{
connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
void CreditsLoader::loadEliteBackers()
{
const auto ELITE_BACKERS_URL = m_config.getEliteBackersUrl(); const auto ELITE_BACKERS_URL = m_config.getEliteBackersUrl();
m_mainWindow.appendLogDebug(QString("Send request: %1").arg(ELITE_BACKERS_URL)); m_mainWindow.appendLogDebug(
QString("Send request: %1").arg(ELITE_BACKERS_URL));
const auto url = QUrl(ELITE_BACKERS_URL); const auto url = QUrl(ELITE_BACKERS_URL);
const auto request = QNetworkRequest(url); const auto request = QNetworkRequest(url);
m_manager.get(request); m_manager.get(request);
} }
void CreditsLoader::replyFinished(QNetworkReply* reply) const void CreditsLoader::replyFinished(QNetworkReply *reply) const {
{
auto response = reply->readAll(); auto response = reply->readAll();
m_mainWindow.appendLogDebug(QString("Received response: %1").arg(response.toStdString().c_str())); m_mainWindow.appendLogDebug(
QString("Received response: %1").arg(response.toStdString().c_str()));
CreditsResponse creditsResponse(response); CreditsResponse creditsResponse(response);
if (creditsResponse.isSuccess()) { if (creditsResponse.isSuccess()) {
emit loaded(creditsResponse.getData()); emit loaded(creditsResponse.getData());
} } else {
else {
error(QString("Server error: %1").arg(creditsResponse.getData())); error(QString("Server error: %1").arg(creditsResponse.getData()));
} }
} }
void CreditsLoader::error(const QString& error) const void CreditsLoader::error(const QString &error) const {
{
m_mainWindow.appendLogError(error); m_mainWindow.appendLogError(error);
emit loaded("Something went wrong when retrieving the list of Elite Backers. Check the logs for more info."); emit loaded("Something went wrong when retrieving the list of Elite Backers. "
"Check the logs for more info.");
} }

View file

@ -16,30 +16,29 @@
*/ */
#pragma once #pragma once
#include <QObject>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QObject>
class QNetworkReply; class QNetworkReply;
class MainWindow; class MainWindow;
class AppConfig; class AppConfig;
class CreditsLoader : public QObject class CreditsLoader : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
explicit CreditsLoader(MainWindow& mainWindow, const AppConfig& config); explicit CreditsLoader(MainWindow &mainWindow, const AppConfig &config);
void loadEliteBackers(); void loadEliteBackers();
signals: signals:
void loaded(const QString& eliteBakers) const; void loaded(const QString &eliteBakers) const;
public slots: public slots:
void replyFinished(QNetworkReply* reply) const; void replyFinished(QNetworkReply *reply) const;
private: private:
MainWindow& m_mainWindow; MainWindow &m_mainWindow;
const AppConfig& m_config; const AppConfig &m_config;
QNetworkAccessManager m_manager; QNetworkAccessManager m_manager;
void error(const QString& error) const; void error(const QString &error) const;
}; };

View file

@ -17,21 +17,15 @@
#include "DataDownloader.h" #include "DataDownloader.h"
DataDownloader::DataDownloader(QObject* parent) : DataDownloader::DataDownloader(QObject *parent)
QObject(parent), : QObject(parent), m_pReply(nullptr), m_IsFinished(false) {
m_pReply(nullptr), connect(&m_NetworkManager, SIGNAL(finished(QNetworkReply *)),
m_IsFinished(false) SLOT(complete(QNetworkReply *)));
{
connect(&m_NetworkManager, SIGNAL(finished(QNetworkReply*)),
SLOT(complete(QNetworkReply*)));
} }
DataDownloader::~DataDownloader() DataDownloader::~DataDownloader() {}
{
}
void DataDownloader::complete(QNetworkReply* reply) void DataDownloader::complete(QNetworkReply *reply) {
{
m_Data = reply->readAll(); m_Data = reply->readAll();
reply->deleteLater(); reply->deleteLater();
m_pReply = nullptr; m_pReply = nullptr;
@ -42,20 +36,15 @@ void DataDownloader::complete(QNetworkReply* reply)
} }
} }
QByteArray DataDownloader::data() const QByteArray DataDownloader::data() const { return m_Data; }
{
return m_Data;
}
void DataDownloader::cancel() void DataDownloader::cancel() {
{
if (m_pReply != nullptr) { if (m_pReply != nullptr) {
m_pReply->abort(); m_pReply->abort();
} }
} }
void DataDownloader::download(QUrl url) void DataDownloader::download(QUrl url) {
{
QNetworkRequest request(url); QNetworkRequest request(url);
m_pReply = m_NetworkManager.get(request); m_pReply = m_NetworkManager.get(request);
} }

View file

@ -18,18 +18,17 @@
#ifndef DATADOWNLOADER_H #ifndef DATADOWNLOADER_H
#define DATADOWNLOADER_H #define DATADOWNLOADER_H
#include <QObject>
#include <QByteArray> #include <QByteArray>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply> #include <QNetworkReply>
#include <QNetworkRequest>
#include <QObject>
class DataDownloader : public QObject class DataDownloader : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
explicit DataDownloader(QObject* parent = 0); explicit DataDownloader(QObject *parent = 0);
virtual ~DataDownloader(); virtual ~DataDownloader();
QByteArray data() const; QByteArray data() const;
@ -41,12 +40,12 @@ signals:
void isComplete(); void isComplete();
private slots: private slots:
void complete(QNetworkReply* reply); void complete(QNetworkReply *reply);
private: private:
QNetworkAccessManager m_NetworkManager; QNetworkAccessManager m_NetworkManager;
QByteArray m_Data; QByteArray m_Data;
QNetworkReply* m_pReply; QNetworkReply *m_pReply;
bool m_IsFinished; bool m_IsFinished;
}; };

View file

@ -32,10 +32,6 @@
// ElevateAlways | false | true // ElevateAlways | false | true
// ElevateNever | false | false // ElevateNever | false | false
// //
enum ElevateMode { enum ElevateMode { ElevateAsNeeded = 0, ElevateAlways = 1, ElevateNever = 2 };
ElevateAsNeeded = 0,
ElevateAlways = 1,
ElevateNever = 2
};
extern const ElevateMode defaultElevateMode; extern const ElevateMode defaultElevateMode;

View file

@ -1,15 +1,10 @@
#include "FailedLoginDialog.h" #include "FailedLoginDialog.h"
#include "ui_FailedLoginDialog.h" #include "ui_FailedLoginDialog.h"
FailedLoginDialog::FailedLoginDialog(QWidget *parent, QString message): FailedLoginDialog::FailedLoginDialog(QWidget *parent, QString message)
QDialog(parent), : QDialog(parent), ui(new Ui::FailedLoginDialog) {
ui(new Ui::FailedLoginDialog)
{
ui->setupUi(this); ui->setupUi(this);
ui->messageLabel->setText(ui->messageLabel->text().arg(message)); ui->messageLabel->setText(ui->messageLabel->text().arg(message));
} }
FailedLoginDialog::~FailedLoginDialog() FailedLoginDialog::~FailedLoginDialog() { delete ui; }
{
delete ui;
}

View file

@ -8,8 +8,7 @@ namespace Ui {
class FailedLoginDialog; class FailedLoginDialog;
} }
class FailedLoginDialog : public QDialog class FailedLoginDialog : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:

View file

@ -27,34 +27,27 @@ static const char kLocalFilename[] = "Local.txt";
static const char kTrustedServersFilename[] = "TrustedServers.txt"; static const char kTrustedServersFilename[] = "TrustedServers.txt";
static const char kTrustedClientsFilename[] = "TrustedClients.txt"; static const char kTrustedClientsFilename[] = "TrustedClients.txt";
Fingerprint::Fingerprint(const QString& filename) Fingerprint::Fingerprint(const QString &filename) { m_Filename = filename; }
{
m_Filename = filename;
}
void Fingerprint::trust(const QString& fingerprintText, bool append) void Fingerprint::trust(const QString &fingerprintText, bool append) {
{
Fingerprint::persistDirectory(); Fingerprint::persistDirectory();
QIODevice::OpenMode openMode; QIODevice::OpenMode openMode;
if (append) { if (append) {
openMode = QIODevice::Append; openMode = QIODevice::Append;
} } else {
else {
openMode = QIODevice::WriteOnly; openMode = QIODevice::WriteOnly;
} }
QFile file(filePath()); QFile file(filePath());
if (file.open(openMode)) if (file.open(openMode)) {
{
QTextStream out(&file); QTextStream out(&file);
out << fingerprintText << "\n"; out << fingerprintText << "\n";
file.close(); file.close();
} }
} }
bool Fingerprint::fileExists() const bool Fingerprint::fileExists() const {
{
QString dirName = Fingerprint::directoryPath(); QString dirName = Fingerprint::directoryPath();
if (!QDir(dirName).exists()) { if (!QDir(dirName).exists()) {
return false; return false;
@ -64,11 +57,9 @@ bool Fingerprint::fileExists() const
return file.exists(); return file.exists();
} }
bool Fingerprint::isTrusted(const QString& fingerprintText) bool Fingerprint::isTrusted(const QString &fingerprintText) {
{
QStringList list = readList(); QStringList list = readList();
foreach (QString trusted, list) foreach (QString trusted, list) {
{
if (trusted == fingerprintText) { if (trusted == fingerprintText) {
return true; return true;
} }
@ -76,8 +67,7 @@ bool Fingerprint::isTrusted(const QString& fingerprintText)
return false; return false;
} }
QStringList Fingerprint::readList(const int readTo) QStringList Fingerprint::readList(const int readTo) {
{
QStringList list; QStringList list;
QString dirName = Fingerprint::directoryPath(); QString dirName = Fingerprint::directoryPath();
@ -87,11 +77,9 @@ QStringList Fingerprint::readList(const int readTo)
QFile file(filePath()); QFile file(filePath());
if (file.open(QIODevice::ReadOnly)) if (file.open(QIODevice::ReadOnly)) {
{
QTextStream in(&file); QTextStream in(&file);
while (!in.atEnd()) while (!in.atEnd()) {
{
list.append(in.readLine()); list.append(in.readLine());
if (list.size() == readTo) { if (list.size() == readTo) {
break; break;
@ -103,47 +91,36 @@ QStringList Fingerprint::readList(const int readTo)
return list; return list;
} }
QString Fingerprint::readFirst() QString Fingerprint::readFirst() {
{
QStringList list = readList(1); QStringList list = readList(1);
return list.at(0); return list.at(0);
} }
QString Fingerprint::filePath() const QString Fingerprint::filePath() const {
{
QString dir = Fingerprint::directoryPath(); QString dir = Fingerprint::directoryPath();
return QString("%1/%2").arg(dir).arg(m_Filename); return QString("%1/%2").arg(dir).arg(m_Filename);
} }
void Fingerprint::persistDirectory() void Fingerprint::persistDirectory() {
{
QDir dir(Fingerprint::directoryPath()); QDir dir(Fingerprint::directoryPath());
if (!dir.exists()) { if (!dir.exists()) {
dir.mkpath("."); dir.mkpath(".");
} }
} }
QString Fingerprint::directoryPath() QString Fingerprint::directoryPath() {
{
CoreInterface coreInterface; CoreInterface coreInterface;
QString profileDir = coreInterface.getProfileDir(); QString profileDir = coreInterface.getProfileDir();
return QString("%1/%2") return QString("%1/%2").arg(profileDir).arg(kDirName);
.arg(profileDir)
.arg(kDirName);
} }
Fingerprint Fingerprint::local() Fingerprint Fingerprint::local() { return Fingerprint(kLocalFilename); }
{
return Fingerprint(kLocalFilename);
}
Fingerprint Fingerprint::trustedServers() Fingerprint Fingerprint::trustedServers() {
{
return Fingerprint(kTrustedServersFilename); return Fingerprint(kTrustedServersFilename);
} }
Fingerprint Fingerprint::trustedClients() Fingerprint Fingerprint::trustedClients() {
{
return Fingerprint(kTrustedClientsFilename); return Fingerprint(kTrustedClientsFilename);
} }

View file

@ -19,14 +19,13 @@
#include <QString> #include <QString>
class Fingerprint class Fingerprint {
{
private: private:
Fingerprint(const QString& filename); Fingerprint(const QString &filename);
public: public:
void trust(const QString& fingerprintText, bool append = true); void trust(const QString &fingerprintText, bool append = true);
bool isTrusted(const QString& fingerprintText); bool isTrusted(const QString &fingerprintText);
QStringList readList(const int readTo = -1); QStringList readList(const int readTo = -1);
QString readFirst(); QString readFirst();
QString filePath() const; QString filePath() const;

View file

@ -20,14 +20,9 @@
#include <QSettings> #include <QSettings>
Hotkey::Hotkey() : Hotkey::Hotkey() : m_KeySequence(), m_Actions() {}
m_KeySequence(),
m_Actions()
{
}
QString Hotkey::text() const QString Hotkey::text() const {
{
QString text = keySequence().toString(); QString text = keySequence().toString();
if (keySequence().isMouseButton()) if (keySequence().isMouseButton())
@ -36,14 +31,12 @@ QString Hotkey::text() const
return "keystroke(" + text + ")"; return "keystroke(" + text + ")";
} }
void Hotkey::loadSettings(QSettings& settings) void Hotkey::loadSettings(QSettings &settings) {
{
keySequence().loadSettings(settings); keySequence().loadSettings(settings);
actions().clear(); actions().clear();
int num = settings.beginReadArray("actions"); int num = settings.beginReadArray("actions");
for (int i = 0; i < num; i++) for (int i = 0; i < num; i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
Action a; Action a;
a.loadSettings(settings); a.loadSettings(settings);
@ -53,26 +46,22 @@ void Hotkey::loadSettings(QSettings& settings)
settings.endArray(); settings.endArray();
} }
void Hotkey::saveSettings(QSettings& settings) const void Hotkey::saveSettings(QSettings &settings) const {
{
keySequence().saveSettings(settings); keySequence().saveSettings(settings);
settings.beginWriteArray("actions"); settings.beginWriteArray("actions");
for (int i = 0; i < actions().size(); i++) for (int i = 0; i < actions().size(); i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
actions()[i].saveSettings(settings); actions()[i].saveSettings(settings);
} }
settings.endArray(); settings.endArray();
} }
bool Hotkey::operator==(const Hotkey& hk) const bool Hotkey::operator==(const Hotkey &hk) const {
{
return m_KeySequence == hk.m_KeySequence && m_Actions == hk.m_Actions; return m_KeySequence == hk.m_KeySequence && m_Actions == hk.m_Actions;
} }
QTextStream& operator<<(QTextStream& outStream, const Hotkey& hotkey) QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey) {
{
for (int i = 0; i < hotkey.actions().size(); i++) for (int i = 0; i < hotkey.actions().size(); i++)
outStream << "\t" << hotkey.text() << " = " << hotkey.actions()[i] << endl; outStream << "\t" << hotkey.text() << " = " << hotkey.actions()[i] << endl;

View file

@ -20,8 +20,8 @@
#define HOTKEY_H #define HOTKEY_H
#include <QString>
#include <QList> #include <QList>
#include <QString>
#include <QTextStream> #include <QTextStream>
#include "Action.h" #include "Action.h"
@ -31,38 +31,36 @@ class HotkeyDialog;
class ServerConfigDialog; class ServerConfigDialog;
class QSettings; class QSettings;
class Hotkey class Hotkey {
{
friend class HotkeyDialog; friend class HotkeyDialog;
friend class ServerConfigDialog; friend class ServerConfigDialog;
friend QTextStream& operator<<(QTextStream& outStream, const Hotkey& hotkey); friend QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey);
public: public:
Hotkey(); Hotkey();
public: public:
QString text() const; QString text() const;
const KeySequence& keySequence() const { return m_KeySequence; } const KeySequence &keySequence() const { return m_KeySequence; }
const ActionList& actions() const { return m_Actions; } const ActionList &actions() const { return m_Actions; }
void loadSettings(QSettings& settings); void loadSettings(QSettings &settings);
void saveSettings(QSettings& settings) const; void saveSettings(QSettings &settings) const;
bool operator==(const Hotkey& hk) const; bool operator==(const Hotkey &hk) const;
protected: protected:
KeySequence& keySequence() { return m_KeySequence; } KeySequence &keySequence() { return m_KeySequence; }
void setKeySequence(const KeySequence& seq) { m_KeySequence = seq; } void setKeySequence(const KeySequence &seq) { m_KeySequence = seq; }
ActionList& actions() { return m_Actions; } ActionList &actions() { return m_Actions; }
private:
private:
KeySequence m_KeySequence; KeySequence m_KeySequence;
ActionList m_Actions; ActionList m_Actions;
}; };
typedef QList<Hotkey> HotkeyList; typedef QList<Hotkey> HotkeyList;
QTextStream& operator<<(QTextStream& outStream, const Hotkey& hotkey); QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey);
#endif #endif

View file

@ -21,18 +21,15 @@
#include <QtCore> #include <QtCore>
#include <QtGui> #include <QtGui>
HotkeyDialog::HotkeyDialog (QWidget* parent, Hotkey& hotkey) : HotkeyDialog::HotkeyDialog(QWidget *parent, Hotkey &hotkey)
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::HotkeyDialogBase(), Ui::HotkeyDialogBase(), m_Hotkey(hotkey) {
m_Hotkey(hotkey)
{
setupUi(this); setupUi(this);
m_pKeySequenceWidgetHotkey->setText(m_Hotkey.text()); m_pKeySequenceWidgetHotkey->setText(m_Hotkey.text());
} }
void HotkeyDialog::accept() void HotkeyDialog::accept() {
{
if (!sequenceWidget()->valid()) if (!sequenceWidget()->valid())
return; return;

View file

@ -20,30 +20,31 @@
#define HOTKEYDIALOG_H #define HOTKEYDIALOG_H
#include "ui_HotkeyDialogBase.h"
#include "Hotkey.h" #include "Hotkey.h"
#include "ui_HotkeyDialogBase.h"
#include <QDialog> #include <QDialog>
class HotkeyDialog : public QDialog, public Ui::HotkeyDialogBase class HotkeyDialog : public QDialog, public Ui::HotkeyDialogBase {
{
Q_OBJECT Q_OBJECT
public: public:
HotkeyDialog(QWidget* parent, Hotkey& hotkey); HotkeyDialog(QWidget *parent, Hotkey &hotkey);
public: public:
const Hotkey& hotkey() const { return m_Hotkey; } const Hotkey &hotkey() const { return m_Hotkey; }
protected slots: protected slots:
void accept(); void accept();
protected: protected:
const KeySequenceWidget* sequenceWidget() const { return m_pKeySequenceWidgetHotkey; } const KeySequenceWidget *sequenceWidget() const {
Hotkey& hotkey() { return m_Hotkey; } return m_pKeySequenceWidgetHotkey;
}
Hotkey &hotkey() { return m_Hotkey; }
private: private:
Hotkey& m_Hotkey; Hotkey &m_Hotkey;
}; };
#endif #endif

View file

@ -20,7 +20,7 @@
#include "Ipc.h" #include "Ipc.h"
const char* kIpcMsgHello = "IHEL%1i"; const char *kIpcMsgHello = "IHEL%1i";
const char* kIpcMsgLogLine = "ILOG%s"; const char *kIpcMsgLogLine = "ILOG%s";
const char* kIpcMsgCommand = "ICMD%s%1i"; const char *kIpcMsgCommand = "ICMD%s%1i";
const char* kIpcMsgShutdown = "ISDN"; const char *kIpcMsgShutdown = "ISDN";

View file

@ -36,7 +36,7 @@ enum qIpcClientType {
kIpcClientNode, kIpcClientNode,
}; };
extern const char* kIpcMsgHello; extern const char *kIpcMsgHello;
extern const char* kIpcMsgLogLine; extern const char *kIpcMsgLogLine;
extern const char* kIpcMsgCommand; extern const char *kIpcMsgCommand;
extern const char* kIpcMsgShutdown; extern const char *kIpcMsgShutdown;

View file

@ -17,38 +17,33 @@
*/ */
#include "IpcClient.h" #include "IpcClient.h"
#include <QTcpSocket>
#include <QHostAddress>
#include <iostream>
#include <QTimer>
#include "IpcReader.h"
#include "Ipc.h" #include "Ipc.h"
#include "IpcReader.h"
#include <QDataStream> #include <QDataStream>
#include <QHostAddress>
#include <QTcpSocket>
#include <QTimer>
#include <iostream>
IpcClient::IpcClient() : IpcClient::IpcClient() : m_ReaderStarted(false), m_Enabled(false) {
m_ReaderStarted(false),
m_Enabled(false)
{
m_Socket = new QTcpSocket(this); m_Socket = new QTcpSocket(this);
connect(m_Socket, SIGNAL(connected()), this, SLOT(connected())); connect(m_Socket, SIGNAL(connected()), this, SLOT(connected()));
connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(error(QAbstractSocket::SocketError)));
m_Reader = new IpcReader(m_Socket); m_Reader = new IpcReader(m_Socket);
connect(m_Reader, SIGNAL(readLogLine(const QString&)), this, SLOT(handleReadLogLine(const QString&))); connect(m_Reader, SIGNAL(readLogLine(const QString &)), this,
SLOT(handleReadLogLine(const QString &)));
} }
IpcClient::~IpcClient() IpcClient::~IpcClient() {}
{
}
void IpcClient::connected() void IpcClient::connected() {
{
sendHello(); sendHello();
infoMessage("connection established"); infoMessage("connection established");
} }
void IpcClient::connectToHost() void IpcClient::connectToHost() {
{
m_Enabled = true; m_Enabled = true;
infoMessage("connecting to service..."); infoMessage("connecting to service...");
@ -60,20 +55,24 @@ void IpcClient::connectToHost()
} }
} }
void IpcClient::disconnectFromHost() void IpcClient::disconnectFromHost() {
{
infoMessage("service disconnect"); infoMessage("service disconnect");
m_Reader->stop(); m_Reader->stop();
m_Socket->close(); m_Socket->close();
} }
void IpcClient::error(QAbstractSocket::SocketError error) void IpcClient::error(QAbstractSocket::SocketError error) {
{
QString text; QString text;
switch (error) { switch (error) {
case 0: text = "connection refused"; break; case 0:
case 1: text = "remote host closed"; break; text = "connection refused";
default: text = QString("code=%1").arg(error); break; break;
case 1:
text = "remote host closed";
break;
default:
text = QString("code=%1").arg(error);
break;
} }
errorMessage(QString("ipc connection error, %1").arg(text)); errorMessage(QString("ipc connection error, %1").arg(text));
@ -81,15 +80,13 @@ void IpcClient::error(QAbstractSocket::SocketError error)
QTimer::singleShot(1000, this, SLOT(retryConnect())); QTimer::singleShot(1000, this, SLOT(retryConnect()));
} }
void IpcClient::retryConnect() void IpcClient::retryConnect() {
{
if (m_Enabled) { if (m_Enabled) {
connectToHost(); connectToHost();
} }
} }
void IpcClient::sendHello() void IpcClient::sendHello() {
{
QDataStream stream(m_Socket); QDataStream stream(m_Socket);
stream.writeRawData(kIpcMsgHello, 4); stream.writeRawData(kIpcMsgHello, 4);
@ -98,15 +95,16 @@ void IpcClient::sendHello()
stream.writeRawData(typeBuf, 1); stream.writeRawData(typeBuf, 1);
} }
void IpcClient::sendCommand(const QString& command, ElevateMode const elevate) void IpcClient::sendCommand(const QString &command, ElevateMode const elevate) {
{
QDataStream stream(m_Socket); QDataStream stream(m_Socket);
stream.writeRawData(kIpcMsgCommand, 4); stream.writeRawData(kIpcMsgCommand, 4);
std::string stdStringCommand = command.toStdString(); std::string stdStringCommand = command.toStdString();
const char* charCommand = stdStringCommand.c_str(); const char *charCommand = stdStringCommand.c_str();
int length = static_cast<int>(strlen(charCommand)); // Compliant: we made sure that charCommand variable ended with null(String type is safe) int length = static_cast<int>(
strlen(charCommand)); // Compliant: we made sure that charCommand variable
// ended with null(String type is safe)
char lenBuf[4]; char lenBuf[4];
intToBytes(length, lenBuf, 4); intToBytes(length, lenBuf, 4);
@ -114,33 +112,27 @@ void IpcClient::sendCommand(const QString& command, ElevateMode const elevate)
stream.writeRawData(charCommand, length); stream.writeRawData(charCommand, length);
char elevateBuf[1]; char elevateBuf[1];
// Refer to enum ElevateMode documentation for why this flag is mapped this way // Refer to enum ElevateMode documentation for why this flag is mapped this
// way
elevateBuf[0] = (elevate == ElevateAlways) ? 1 : 0; elevateBuf[0] = (elevate == ElevateAlways) ? 1 : 0;
stream.writeRawData(elevateBuf, 1); stream.writeRawData(elevateBuf, 1);
} }
void IpcClient::handleReadLogLine(const QString& text) void IpcClient::handleReadLogLine(const QString &text) { readLogLine(text); }
{
readLogLine(text);
}
// TODO: qt must have a built in way of converting int to bytes. // TODO: qt must have a built in way of converting int to bytes.
void IpcClient::intToBytes(int value, char *buffer, int size) void IpcClient::intToBytes(int value, char *buffer, int size) {
{
if (size == 1) { if (size == 1) {
buffer[0] = value & 0xff; buffer[0] = value & 0xff;
} } else if (size == 2) {
else if (size == 2) {
buffer[0] = (value >> 8) & 0xff; buffer[0] = (value >> 8) & 0xff;
buffer[1] = value & 0xff; buffer[1] = value & 0xff;
} } else if (size == 4) {
else if (size == 4) {
buffer[0] = (value >> 24) & 0xff; buffer[0] = (value >> 24) & 0xff;
buffer[1] = (value >> 16) & 0xff; buffer[1] = (value >> 16) & 0xff;
buffer[2] = (value >> 8) & 0xff; buffer[2] = (value >> 8) & 0xff;
buffer[3] = value & 0xff; buffer[3] = value & 0xff;
} } else {
else {
// TODO: other sizes, if needed. // TODO: other sizes, if needed.
} }
} }

View file

@ -18,16 +18,15 @@
#pragma once #pragma once
#include <QObject>
#include <QAbstractSocket> #include <QAbstractSocket>
#include <QObject>
#include "ElevateMode.h" #include "ElevateMode.h"
class QTcpSocket; class QTcpSocket;
class IpcReader; class IpcReader;
class IpcClient : public QObject class IpcClient : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
@ -35,7 +34,7 @@ public:
virtual ~IpcClient(); virtual ~IpcClient();
void sendHello(); void sendHello();
void sendCommand(const QString& command, ElevateMode elevate); void sendCommand(const QString &command, ElevateMode elevate);
void connectToHost(); void connectToHost();
void disconnectFromHost(); void disconnectFromHost();
@ -43,21 +42,21 @@ public slots:
void retryConnect(); void retryConnect();
private: private:
void intToBytes(int value, char* buffer, int size); void intToBytes(int value, char *buffer, int size);
private slots: private slots:
void connected(); void connected();
void error(QAbstractSocket::SocketError error); void error(QAbstractSocket::SocketError error);
void handleReadLogLine(const QString& text); void handleReadLogLine(const QString &text);
signals: signals:
void readLogLine(const QString& text); void readLogLine(const QString &text);
void infoMessage(const QString& text); void infoMessage(const QString &text);
void errorMessage(const QString& text); void errorMessage(const QString &text);
private: private:
QTcpSocket* m_Socket; QTcpSocket *m_Socket;
IpcReader* m_Reader; IpcReader *m_Reader;
bool m_ReaderStarted; bool m_ReaderStarted;
bool m_Enabled; bool m_Enabled;
}; };

View file

@ -17,33 +17,25 @@
*/ */
#include "IpcReader.h" #include "IpcReader.h"
#include <QTcpSocket>
#include "Ipc.h" #include "Ipc.h"
#include <iostream>
#include <QMutex>
#include <QByteArray> #include <QByteArray>
#include <QMutex>
#include <QTcpSocket>
#include <iostream>
IpcReader::IpcReader(QTcpSocket* socket) : IpcReader::IpcReader(QTcpSocket *socket) : m_Socket(socket) {}
m_Socket(socket)
{
}
IpcReader::~IpcReader() IpcReader::~IpcReader() {}
{
}
void IpcReader::start() void IpcReader::start() {
{
connect(m_Socket, SIGNAL(readyRead()), this, SLOT(read())); connect(m_Socket, SIGNAL(readyRead()), this, SLOT(read()));
} }
void IpcReader::stop() void IpcReader::stop() {
{
disconnect(m_Socket, SIGNAL(readyRead()), this, SLOT(read())); disconnect(m_Socket, SIGNAL(readyRead()), this, SLOT(read()));
} }
void IpcReader::read() void IpcReader::read() {
{
QMutexLocker locker(&m_Mutex); QMutexLocker locker(&m_Mutex);
std::cout << "ready read" << std::endl; std::cout << "ready read" << std::endl;
@ -62,14 +54,13 @@ void IpcReader::read()
readStream(lenBuf, 4); readStream(lenBuf, 4);
int len = bytesToInt(lenBuf, 4); int len = bytesToInt(lenBuf, 4);
char* data = new char[len]; char *data = new char[len];
readStream(data, len); readStream(data, len);
QString line = QString::fromUtf8(data, len); QString line = QString::fromUtf8(data, len);
delete[] data; delete[] data;
readLogLine(line); readLogLine(line);
} } else {
else {
std::cerr << "aborting, message invalid" << std::endl; std::cerr << "aborting, message invalid" << std::endl;
return; return;
} }
@ -78,8 +69,7 @@ void IpcReader::read()
std::cout << "read done" << std::endl; std::cout << "read done" << std::endl;
} }
bool IpcReader::readStream(char* buffer, int length) bool IpcReader::readStream(char *buffer, int length) {
{
std::cout << "reading stream" << std::endl; std::cout << "reading stream" << std::endl;
int read = 0; int read = 0;
@ -93,14 +83,13 @@ bool IpcReader::readStream(char* buffer, int length)
int got = m_Socket->read(buffer, ask); int got = m_Socket->read(buffer, ask);
read += got; read += got;
std::cout << "> ask=" << ask << " got=" << got std::cout << "> ask=" << ask << " got=" << got << " read=" << read
<< " read=" << read << std::endl; << std::endl;
if (got == -1) { if (got == -1) {
std::cout << "socket ended, aborting" << std::endl; std::cout << "socket ended, aborting" << std::endl;
return false; return false;
} } else if (length - read > 0) {
else if (length - read > 0) {
std::cout << "more remains, seek to " << got << std::endl; std::cout << "more remains, seek to " << got << std::endl;
buffer += got; buffer += got;
} }
@ -108,24 +97,16 @@ bool IpcReader::readStream(char* buffer, int length)
return true; return true;
} }
int IpcReader::bytesToInt(const char *buffer, int size) int IpcReader::bytesToInt(const char *buffer, int size) {
{
if (size == 1) { if (size == 1) {
return (unsigned char)buffer[0]; return (unsigned char)buffer[0];
} } else if (size == 2) {
else if (size == 2) { return (((unsigned char)buffer[0]) << 8) + (unsigned char)buffer[1];
return } else if (size == 4) {
(((unsigned char)buffer[0]) << 8) + return (((unsigned char)buffer[0]) << 24) +
(unsigned char)buffer[1];
}
else if (size == 4) {
return
(((unsigned char)buffer[0]) << 24) +
(((unsigned char)buffer[1]) << 16) + (((unsigned char)buffer[1]) << 16) +
(((unsigned char)buffer[2]) << 8) + (((unsigned char)buffer[2]) << 8) + (unsigned char)buffer[3];
(unsigned char)buffer[3]; } else {
}
else {
return 0; return 0;
} }
} }

View file

@ -18,32 +18,31 @@
#pragma once #pragma once
#include <QObject>
#include <QMutex> #include <QMutex>
#include <QObject>
class QTcpSocket; class QTcpSocket;
class IpcReader : public QObject class IpcReader : public QObject {
{
Q_OBJECT; Q_OBJECT;
public: public:
IpcReader(QTcpSocket* socket); IpcReader(QTcpSocket *socket);
virtual ~IpcReader(); virtual ~IpcReader();
void start(); void start();
void stop(); void stop();
signals: signals:
void readLogLine(const QString& text); void readLogLine(const QString &text);
private: private:
bool readStream(char* buffer, int length); bool readStream(char *buffer, int length);
int bytesToInt(const char* buffer, int size); int bytesToInt(const char *buffer, int size);
private slots: private slots:
void read(); void read();
private: private:
QTcpSocket* m_Socket; QTcpSocket *m_Socket;
QMutex m_Mutex; QMutex m_Mutex;
}; };

View file

@ -23,81 +23,69 @@
// this table originally comes from Qt sources (gui/kernel/qkeysequence.cpp) // this table originally comes from Qt sources (gui/kernel/qkeysequence.cpp)
// and is heavily modified for QSynergy // and is heavily modified for QSynergy
static const struct static const struct {
{
int key; int key;
const char* name; const char *name;
} keyname[] = } keyname[] = {{Qt::Key_Space, "Space"},
{ {Qt::Key_Escape, "Escape"},
{ Qt::Key_Space, "Space" }, {Qt::Key_Tab, "Tab"},
{ Qt::Key_Escape, "Escape" }, {Qt::Key_Backtab, "LeftTab"},
{ Qt::Key_Tab, "Tab" }, {Qt::Key_Backspace, "BackSpace"},
{ Qt::Key_Backtab, "LeftTab" }, {Qt::Key_Return, "Return"},
{ Qt::Key_Backspace, "BackSpace" }, {Qt::Key_Insert, "Insert"},
{ Qt::Key_Return, "Return" }, {Qt::Key_Delete, "Delete"},
{ Qt::Key_Insert, "Insert" }, {Qt::Key_Pause, "Pause"},
{ Qt::Key_Delete, "Delete" }, {Qt::Key_Print, "Print"},
{ Qt::Key_Pause, "Pause" }, {Qt::Key_SysReq, "SysReq"},
{ Qt::Key_Print, "Print" }, {Qt::Key_Home, "Home"},
{ Qt::Key_SysReq, "SysReq" }, {Qt::Key_End, "End"},
{ Qt::Key_Home, "Home" }, {Qt::Key_Left, "Left"},
{ Qt::Key_End, "End" }, {Qt::Key_Up, "Up"},
{ Qt::Key_Left, "Left" }, {Qt::Key_Right, "Right"},
{ Qt::Key_Up, "Up" }, {Qt::Key_Down, "Down"},
{ Qt::Key_Right, "Right" }, {Qt::Key_PageUp, "PageUp"},
{ Qt::Key_Down, "Down" }, {Qt::Key_PageDown, "PageDown"},
{ Qt::Key_PageUp, "PageUp" }, {Qt::Key_CapsLock, "CapsLock"},
{ Qt::Key_PageDown, "PageDown" }, {Qt::Key_NumLock, "NumLock"},
{ Qt::Key_CapsLock, "CapsLock" }, {Qt::Key_ScrollLock, "ScrollLock"},
{ Qt::Key_NumLock, "NumLock" }, {Qt::Key_Menu, "Menu"},
{ Qt::Key_ScrollLock, "ScrollLock" }, {Qt::Key_Help, "Help"},
{ Qt::Key_Menu, "Menu" }, {Qt::Key_Enter, "KP_Enter"},
{ Qt::Key_Help, "Help" }, {Qt::Key_Clear, "Clear"},
{ Qt::Key_Enter, "KP_Enter" },
{ Qt::Key_Clear, "Clear" },
{ Qt::Key_Back, "WWWBack" }, {Qt::Key_Back, "WWWBack"},
{ Qt::Key_Forward, "WWWForward" }, {Qt::Key_Forward, "WWWForward"},
{ Qt::Key_Stop, "WWWStop" }, {Qt::Key_Stop, "WWWStop"},
{ Qt::Key_Refresh, "WWWRefresh" }, {Qt::Key_Refresh, "WWWRefresh"},
{ Qt::Key_VolumeDown, "AudioDown" }, {Qt::Key_VolumeDown, "AudioDown"},
{ Qt::Key_VolumeMute, "AudioMute" }, {Qt::Key_VolumeMute, "AudioMute"},
{ Qt::Key_VolumeUp, "AudioUp" }, {Qt::Key_VolumeUp, "AudioUp"},
{ Qt::Key_MediaPlay, "AudioPlay" }, {Qt::Key_MediaPlay, "AudioPlay"},
{ Qt::Key_MediaStop, "AudioStop" }, {Qt::Key_MediaStop, "AudioStop"},
{ Qt::Key_MediaPrevious,"AudioPrev" }, {Qt::Key_MediaPrevious, "AudioPrev"},
{ Qt::Key_MediaNext, "AudioNext" }, {Qt::Key_MediaNext, "AudioNext"},
{ Qt::Key_HomePage, "WWWHome" }, {Qt::Key_HomePage, "WWWHome"},
{ Qt::Key_Favorites, "WWWFavorites" }, {Qt::Key_Favorites, "WWWFavorites"},
{ Qt::Key_Search, "WWWSearch" }, {Qt::Key_Search, "WWWSearch"},
{ Qt::Key_Standby, "Sleep" }, {Qt::Key_Standby, "Sleep"},
{ Qt::Key_LaunchMail, "AppMail" }, {Qt::Key_LaunchMail, "AppMail"},
{ Qt::Key_LaunchMedia, "AppMedia" }, {Qt::Key_LaunchMedia, "AppMedia"},
{ Qt::Key_Launch0, "AppUser1" }, {Qt::Key_Launch0, "AppUser1"},
{ Qt::Key_Launch1, "AppUser2" }, {Qt::Key_Launch1, "AppUser2"},
{ Qt::Key_Select, "Select" }, {Qt::Key_Select, "Select"},
{ 0, 0 } {0, 0}};
};
KeySequence::KeySequence() : KeySequence::KeySequence() : m_Sequence(), m_Modifiers(0), m_IsValid(false) {}
m_Sequence(),
m_Modifiers(0),
m_IsValid(false)
{
}
bool KeySequence::isMouseButton() const bool KeySequence::isMouseButton() const {
{
return !m_Sequence.isEmpty() && m_Sequence.last() < Qt::Key_Space; return !m_Sequence.isEmpty() && m_Sequence.last() < Qt::Key_Space;
} }
QString KeySequence::toString() const QString KeySequence::toString() const {
{
QString result; QString result;
for (int i = 0; i < m_Sequence.size(); i++) for (int i = 0; i < m_Sequence.size(); i++) {
{
result += keyToString(m_Sequence[i]); result += keyToString(m_Sequence[i]);
if (i != m_Sequence.size() - 1) if (i != m_Sequence.size() - 1)
@ -107,18 +95,13 @@ QString KeySequence::toString() const
return result; return result;
} }
bool KeySequence::appendMouseButton(int button) bool KeySequence::appendMouseButton(int button) { return appendKey(button, 0); }
{
return appendKey(button, 0);
}
bool KeySequence::appendKey(int key, int modifiers) bool KeySequence::appendKey(int key, int modifiers) {
{
if (m_Sequence.size() == 4) if (m_Sequence.size() == 4)
return true; return true;
switch(key) switch (key) {
{
case Qt::Key_AltGr: case Qt::Key_AltGr:
return false; return false;
@ -126,16 +109,13 @@ bool KeySequence::appendKey(int key, int modifiers)
case Qt::Key_Alt: case Qt::Key_Alt:
case Qt::Key_Shift: case Qt::Key_Shift:
case Qt::Key_Meta: case Qt::Key_Meta:
case Qt::Key_Menu: case Qt::Key_Menu: {
{
int mod = modifiers & (~m_Modifiers); int mod = modifiers & (~m_Modifiers);
if (mod) if (mod) {
{
m_Sequence.append(mod); m_Sequence.append(mod);
m_Modifiers |= mod; m_Modifiers |= mod;
} }
} } break;
break;
default: default:
// see if we can handle this key, if not, don't accept it // see if we can handle this key, if not, don't accept it
@ -150,12 +130,10 @@ bool KeySequence::appendKey(int key, int modifiers)
return false; return false;
} }
void KeySequence::loadSettings(QSettings& settings) void KeySequence::loadSettings(QSettings &settings) {
{
sequence().clear(); sequence().clear();
int num = settings.beginReadArray("keys"); int num = settings.beginReadArray("keys");
for (int i = 0; i < num; i++) for (int i = 0; i < num; i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
sequence().append(settings.value("key", 0).toInt()); sequence().append(settings.value("key", 0).toInt());
} }
@ -165,34 +143,33 @@ void KeySequence::loadSettings(QSettings& settings)
setValid(true); setValid(true);
} }
void KeySequence::saveSettings(QSettings& settings) const void KeySequence::saveSettings(QSettings &settings) const {
{
settings.beginWriteArray("keys"); settings.beginWriteArray("keys");
for (int i = 0; i < sequence().size(); i++) for (int i = 0; i < sequence().size(); i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
settings.setValue("key", sequence()[i]); settings.setValue("key", sequence()[i]);
} }
settings.endArray(); settings.endArray();
} }
QString KeySequence::keyToString(int key) QString KeySequence::keyToString(int key) {
{
// nothing there? // nothing there?
if (key == 0) if (key == 0)
return ""; return "";
// a hack to handle mouse buttons as if they were keys // a hack to handle mouse buttons as if they were keys
if (key < Qt::Key_Space) if (key < Qt::Key_Space) {
{ switch (key) {
switch(key) case Qt::LeftButton:
{ return "1";
case Qt::LeftButton: return "1"; case Qt::RightButton:
case Qt::RightButton: return "2"; return "2";
case Qt::MidButton: return "3"; case Qt::MidButton:
return "3";
} }
return "4"; // qt only knows three mouse buttons, so assume it's an unknown fourth one return "4"; // qt only knows three mouse buttons, so assume it's an unknown
// fourth one
} }
// modifiers? // modifiers?
@ -208,7 +185,8 @@ QString KeySequence::keyToString(int key)
if (key & Qt::MetaModifier) if (key & Qt::MetaModifier)
return "Meta"; return "Meta";
// treat key pad like normal keys (FIXME: we should have another lookup table for keypad keys instead) // treat key pad like normal keys (FIXME: we should have another lookup table
// for keypad keys instead)
key &= ~Qt::KeypadModifier; key &= ~Qt::KeypadModifier;
// a printable 7 bit character? // a printable 7 bit character?
@ -220,9 +198,8 @@ QString KeySequence::keyToString(int key)
return QString::fromUtf8("F%1").arg(key - Qt::Key_F1 + 1); return QString::fromUtf8("F%1").arg(key - Qt::Key_F1 + 1);
// a special key? // a special key?
int i=0; int i = 0;
while (keyname[i].name) while (keyname[i].name) {
{
if (key == keyname[i].key) if (key == keyname[i].key)
return QString::fromUtf8(keyname[i].name); return QString::fromUtf8(keyname[i].name);
i++; i++;
@ -230,15 +207,14 @@ QString KeySequence::keyToString(int key)
// representable in ucs2? // representable in ucs2?
if (key < 0x10000) if (key < 0x10000)
return QString("\\u%1").arg(QChar(key).toLower().unicode(), 4, 16, QChar('0')); return QString("\\u%1").arg(QChar(key).toLower().unicode(), 4, 16,
QChar('0'));
// give up, synergy probably won't handle this // give up, synergy probably won't handle this
return ""; return "";
} }
bool KeySequence::operator==(const KeySequence& ks) const bool KeySequence::operator==(const KeySequence &ks) const {
{ return m_Sequence == ks.m_Sequence && m_Modifiers == ks.m_Modifiers &&
return m_Sequence == ks.m_Sequence &&
m_Modifiers == ks.m_Modifiers &&
m_IsValid == ks.m_IsValid; m_IsValid == ks.m_IsValid;
} }

View file

@ -25,30 +25,29 @@
class QSettings; class QSettings;
class KeySequence class KeySequence {
{ public:
public:
KeySequence(); KeySequence();
public: public:
QString toString() const; QString toString() const;
bool appendKey(int modifiers, int key); bool appendKey(int modifiers, int key);
bool appendMouseButton(int button); bool appendMouseButton(int button);
bool isMouseButton() const; bool isMouseButton() const;
bool valid() const { return m_IsValid; } bool valid() const { return m_IsValid; }
int modifiers() const { return m_Modifiers; } int modifiers() const { return m_Modifiers; }
void saveSettings(QSettings& settings) const; void saveSettings(QSettings &settings) const;
void loadSettings(QSettings& settings); void loadSettings(QSettings &settings);
const QList<int>& sequence() const { return m_Sequence; } const QList<int> &sequence() const { return m_Sequence; }
bool operator==(const KeySequence& ks) const; bool operator==(const KeySequence &ks) const;
private: private:
void setValid(bool b) { m_IsValid = b; } void setValid(bool b) { m_IsValid = b; }
void setModifiers(int i) { m_Modifiers = i; } void setModifiers(int i) { m_Modifiers = i; }
QList<int>& sequence() { return m_Sequence; } QList<int> &sequence() { return m_Sequence; }
private: private:
QList<int> m_Sequence; QList<int> m_Sequence;
int m_Modifiers; int m_Modifiers;
bool m_IsValid; bool m_IsValid;
@ -57,4 +56,3 @@ class KeySequence
}; };
#endif #endif

View file

@ -18,25 +18,18 @@
#include "KeySequenceWidget.h" #include "KeySequenceWidget.h"
#include <iostream>
#include <QMouseEvent> #include <QMouseEvent>
#include <iostream>
KeySequenceWidget::KeySequenceWidget(QWidget* parent, const KeySequence& seq) : KeySequenceWidget::KeySequenceWidget(QWidget *parent, const KeySequence &seq)
QPushButton(parent), : QPushButton(parent), m_KeySequence(seq), m_BackupSequence(seq),
m_KeySequence(seq), m_Status(Stopped), m_MousePrefix("mousebutton("), m_MousePostfix(")"),
m_BackupSequence(seq), m_KeyPrefix("keystroke("), m_KeyPostfix(")") {
m_Status(Stopped),
m_MousePrefix("mousebutton("),
m_MousePostfix(")"),
m_KeyPrefix("keystroke("),
m_KeyPostfix(")")
{
setFocusPolicy(Qt::NoFocus); setFocusPolicy(Qt::NoFocus);
updateOutput(); updateOutput();
} }
void KeySequenceWidget::setKeySequence(const KeySequence& seq) void KeySequenceWidget::setKeySequence(const KeySequence &seq) {
{
keySequence() = seq; keySequence() = seq;
backupSequence() = seq; backupSequence() = seq;
@ -44,12 +37,10 @@ void KeySequenceWidget::setKeySequence(const KeySequence& seq)
updateOutput(); updateOutput();
} }
void KeySequenceWidget::mousePressEvent(QMouseEvent* event) void KeySequenceWidget::mousePressEvent(QMouseEvent *event) {
{
event->accept(); event->accept();
if (status() == Stopped) if (status() == Stopped) {
{
startRecording(); startRecording();
return; return;
} }
@ -60,8 +51,7 @@ void KeySequenceWidget::mousePressEvent(QMouseEvent* event)
updateOutput(); updateOutput();
} }
void KeySequenceWidget::startRecording() void KeySequenceWidget::startRecording() {
{
keySequence() = KeySequence(); keySequence() = KeySequence();
setDown(true); setDown(true);
setFocus(); setFocus();
@ -69,10 +59,8 @@ void KeySequenceWidget::startRecording()
setStatus(Recording); setStatus(Recording);
} }
void KeySequenceWidget::stopRecording() void KeySequenceWidget::stopRecording() {
{ if (!keySequence().valid()) {
if (!keySequence().valid())
{
keySequence() = backupSequence(); keySequence() = backupSequence();
updateOutput(); updateOutput();
} }
@ -84,14 +72,11 @@ void KeySequenceWidget::stopRecording()
emit keySequenceChanged(); emit keySequenceChanged();
} }
bool KeySequenceWidget::event(QEvent* event) bool KeySequenceWidget::event(QEvent *event) {
{ if (status() == Recording) {
if (status() == Recording) switch (event->type()) {
{
switch(event->type())
{
case QEvent::KeyPress: case QEvent::KeyPress:
keyPressEvent(static_cast<QKeyEvent*>(event)); keyPressEvent(static_cast<QKeyEvent *>(event));
return true; return true;
case QEvent::MouseButtonRelease: case QEvent::MouseButtonRelease:
@ -104,8 +89,7 @@ bool KeySequenceWidget::event(QEvent* event)
case QEvent::FocusOut: case QEvent::FocusOut:
stopRecording(); stopRecording();
if (!valid()) if (!valid()) {
{
keySequence() = backupSequence(); keySequence() = backupSequence();
updateOutput(); updateOutput();
} }
@ -119,8 +103,7 @@ bool KeySequenceWidget::event(QEvent* event)
return QPushButton::event(event); return QPushButton::event(event);
} }
void KeySequenceWidget::keyPressEvent(QKeyEvent* event) void KeySequenceWidget::keyPressEvent(QKeyEvent *event) {
{
event->accept(); event->accept();
if (status() == Stopped) if (status() == Stopped)
@ -132,8 +115,7 @@ void KeySequenceWidget::keyPressEvent(QKeyEvent* event)
updateOutput(); updateOutput();
} }
void KeySequenceWidget::updateOutput() void KeySequenceWidget::updateOutput() {
{
QString s; QString s;
if (m_KeySequence.isMouseButton()) if (m_KeySequence.isMouseButton())

View file

@ -24,50 +24,49 @@
#include "KeySequence.h" #include "KeySequence.h"
class KeySequenceWidget : public QPushButton class KeySequenceWidget : public QPushButton {
{
Q_OBJECT Q_OBJECT
public: public:
KeySequenceWidget(QWidget* parent, const KeySequence& seq = KeySequence()); KeySequenceWidget(QWidget *parent, const KeySequence &seq = KeySequence());
signals: signals:
void keySequenceChanged(); void keySequenceChanged();
public: public:
const QString& mousePrefix() const { return m_MousePrefix; } const QString &mousePrefix() const { return m_MousePrefix; }
const QString& mousePostfix() const { return m_MousePostfix; } const QString &mousePostfix() const { return m_MousePostfix; }
const QString& keyPrefix() const { return m_KeyPrefix; } const QString &keyPrefix() const { return m_KeyPrefix; }
const QString& keyPostfix() const { return m_KeyPostfix; } const QString &keyPostfix() const { return m_KeyPostfix; }
void setMousePrefix(const QString& s) { m_MousePrefix = s; } void setMousePrefix(const QString &s) { m_MousePrefix = s; }
void setMousePostfix(const QString& s) { m_MousePostfix = s; } void setMousePostfix(const QString &s) { m_MousePostfix = s; }
void setKeyPrefix(const QString& s) { m_KeyPrefix = s; } void setKeyPrefix(const QString &s) { m_KeyPrefix = s; }
void setKeyPostfix(const QString& s) { m_KeyPostfix = s; } void setKeyPostfix(const QString &s) { m_KeyPostfix = s; }
const KeySequence& keySequence() const { return m_KeySequence; } const KeySequence &keySequence() const { return m_KeySequence; }
const KeySequence& backupSequence() const { return m_BackupSequence; } const KeySequence &backupSequence() const { return m_BackupSequence; }
void setKeySequence(const KeySequence& seq); void setKeySequence(const KeySequence &seq);
bool valid() const { return keySequence().valid(); } bool valid() const { return keySequence().valid(); }
protected: protected:
void mousePressEvent(QMouseEvent*); void mousePressEvent(QMouseEvent *);
void keyPressEvent(QKeyEvent*); void keyPressEvent(QKeyEvent *);
bool event(QEvent* event); bool event(QEvent *event);
void appendToSequence(int key); void appendToSequence(int key);
void updateOutput(); void updateOutput();
void startRecording(); void startRecording();
void stopRecording(); void stopRecording();
KeySequence& keySequence() { return m_KeySequence; } KeySequence &keySequence() { return m_KeySequence; }
KeySequence& backupSequence() { return m_BackupSequence; } KeySequence &backupSequence() { return m_BackupSequence; }
private: private:
enum Status { Stopped, Recording }; enum Status { Stopped, Recording };
void setStatus(Status s) { m_Status = s; } void setStatus(Status s) { m_Status = s; }
Status status() const { return m_Status; } Status status() const { return m_Status; }
private: private:
KeySequence m_KeySequence; KeySequence m_KeySequence;
KeySequence m_BackupSequence; KeySequence m_BackupSequence;
Status m_Status; Status m_Status;
@ -78,4 +77,3 @@ class KeySequenceWidget : public QPushButton
}; };
#endif #endif

View file

@ -17,31 +17,30 @@
#include "LicenseManager.h" #include "LicenseManager.h"
#include "AppConfig.h" #include "AppConfig.h"
#include <QDateTime>
#include <QLocale>
#include <QThread>
#include <QTimer>
#include <ctime> #include <ctime>
#include <stdexcept> #include <stdexcept>
#include <utility> #include <utility>
#include <QThread>
#include <QTimer>
#include <QDateTime>
#include <QLocale>
namespace { namespace {
std::string std::string getMaintenanceMessage(const SerialKey &serialKey) {
getMaintenanceMessage(const SerialKey& serialKey)
{
auto expiration = QDateTime::fromTime_t(serialKey.getExpiration()).date(); auto expiration = QDateTime::fromTime_t(serialKey.getExpiration()).date();
QString message = "The license key you used will only work with versions of Synergy released before %1." QString message =
"<p>To use this version, you’ll need to renew your Synergy maintenance license. " "The license key you used will only work with versions of Synergy "
"released before %1."
"<p>To use this version, you’ll need to renew your Synergy maintenance "
"license. "
"<a href=\"https://symless.com/synergy/account?source=gui\"" "<a href=\"https://symless.com/synergy/account?source=gui\""
"style=\"text-decoration: none; color: #4285F4;\">Renew today</a>.</p>"; "style=\"text-decoration: none; color: #4285F4;\">Renew today</a>.</p>";
auto formatedDate = QLocale("en_US").toString(expiration, "MMM dd yyyy"); auto formatedDate = QLocale("en_US").toString(expiration, "MMM dd yyyy");
return message.arg(formatedDate).toStdString(); return message.arg(formatedDate).toStdString();
} }
void void checkSerialKey(const SerialKey &serialKey, bool acceptExpired) {
checkSerialKey(const SerialKey& serialKey, bool acceptExpired)
{
if (serialKey.isMaintenance()) { if (serialKey.isMaintenance()) {
auto buildDate = QDateTime::fromString(__TIMESTAMP__).toTime_t(); auto buildDate = QDateTime::fromString(__TIMESTAMP__).toTime_t();
@ -54,32 +53,27 @@ checkSerialKey(const SerialKey& serialKey, bool acceptExpired)
throw std::runtime_error("Serial key expired"); throw std::runtime_error("Serial key expired");
} }
#ifdef SYNERGY_BUSINESS #ifdef SYNERGY_BUSINESS
if (!serialKey.isValid()) { if (!serialKey.isValid()) {
throw std::runtime_error("The serial key is not compatible with the business version of Synergy."); throw std::runtime_error("The serial key is not compatible with the "
"business version of Synergy.");
} }
#endif #endif
} }
} } // namespace
LicenseManager::LicenseManager(AppConfig *appConfig)
: m_AppConfig(appConfig), m_serialKey(appConfig->edition()),
m_registry(*appConfig) {}
LicenseManager::LicenseManager(AppConfig* appConfig) : void LicenseManager::setSerialKey(SerialKey serialKey, bool acceptExpired) {
m_AppConfig(appConfig),
m_serialKey(appConfig->edition()),
m_registry(*appConfig) {
}
void
LicenseManager::setSerialKey(SerialKey serialKey, bool acceptExpired)
{
checkSerialKey(serialKey, acceptExpired); checkSerialKey(serialKey, acceptExpired);
if (serialKey != m_serialKey) { if (serialKey != m_serialKey) {
using std::swap; using std::swap;
swap (serialKey, m_serialKey); swap(serialKey, m_serialKey);
m_AppConfig->setSerialKey(QString::fromStdString m_AppConfig->setSerialKey(QString::fromStdString(m_serialKey.toString()));
(m_serialKey.toString()));
emit showLicenseNotice(getLicenseNotice()); emit showLicenseNotice(getLicenseNotice());
validateSerialKey(); validateSerialKey();
@ -92,18 +86,17 @@ LicenseManager::setSerialKey(SerialKey serialKey, bool acceptExpired)
} }
} }
void void LicenseManager::notifyUpdate(QString fromVersion,
LicenseManager::notifyUpdate(QString fromVersion, QString toVersion) const { QString toVersion) const {
if ((fromVersion == "Unknown") if ((fromVersion == "Unknown") && (m_serialKey == SerialKey(kUnregistered))) {
&& (m_serialKey == SerialKey(kUnregistered))) {
return; return;
} }
ActivationNotifier* notifier = new ActivationNotifier(); ActivationNotifier *notifier = new ActivationNotifier();
notifier->setUpdateInfo (fromVersion, toVersion, notifier->setUpdateInfo(fromVersion, toVersion,
QString::fromStdString(m_serialKey.toString())); QString::fromStdString(m_serialKey.toString()));
QThread* thread = new QThread(); QThread *thread = new QThread();
connect(notifier, SIGNAL(finished()), thread, SLOT(quit())); connect(notifier, SIGNAL(finished()), thread, SLOT(quit()));
connect(notifier, SIGNAL(finished()), notifier, SLOT(deleteLater())); connect(notifier, SIGNAL(finished()), notifier, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
@ -111,34 +104,21 @@ LicenseManager::notifyUpdate(QString fromVersion, QString toVersion) const {
notifier->moveToThread(thread); notifier->moveToThread(thread);
thread->start(); thread->start();
QMetaObject::invokeMethod(notifier, "notifyUpdate", QMetaObject::invokeMethod(notifier, "notifyUpdate", Qt::QueuedConnection);
Qt::QueuedConnection);
} }
Edition Edition LicenseManager::activeEdition() const { return m_serialKey.edition(); }
LicenseManager::activeEdition() const
{
return m_serialKey.edition();
}
QString QString LicenseManager::activeEditionName() const {
LicenseManager::activeEditionName() const
{
return getEditionName(activeEdition(), m_serialKey.isTrial()); return getEditionName(activeEdition(), m_serialKey.isTrial());
} }
const SerialKey& const SerialKey &LicenseManager::serialKey() const { return m_serialKey; }
LicenseManager::serialKey() const
{
return m_serialKey;
}
void void LicenseManager::refresh() {
LicenseManager::refresh()
{
if (!m_AppConfig->serialKey().isEmpty()) { if (!m_AppConfig->serialKey().isEmpty()) {
try { try {
SerialKey serialKey (m_AppConfig->serialKey().toStdString()); SerialKey serialKey(m_AppConfig->serialKey().toStdString());
setSerialKey(serialKey, true); setSerialKey(serialKey, true);
} catch (...) { } catch (...) {
m_serialKey = SerialKey(); m_serialKey = SerialKey();
@ -150,15 +130,11 @@ LicenseManager::refresh()
} }
} }
void void LicenseManager::skipActivation() const {
LicenseManager::skipActivation() const notifyActivation("skip:unknown");
{
notifyActivation ("skip:unknown");
} }
QString QString LicenseManager::getEditionName(Edition const edition, bool trial) {
LicenseManager::getEditionName(Edition const edition, bool trial)
{
SerialKeyEdition KeyEdition(edition); SerialKeyEdition KeyEdition(edition);
std::string name = KeyEdition.getDisplayName(); std::string name = KeyEdition.getDisplayName();
@ -166,16 +142,14 @@ LicenseManager::getEditionName(Edition const edition, bool trial)
name += " (Trial)"; name += " (Trial)";
} }
return QString::fromUtf8 (name.c_str(), static_cast<int>(name.size())); return QString::fromUtf8(name.c_str(), static_cast<int>(name.size()));
} }
void void LicenseManager::notifyActivation(QString identity) const {
LicenseManager::notifyActivation(QString identity) const ActivationNotifier *notifier = new ActivationNotifier();
{
ActivationNotifier* notifier = new ActivationNotifier();
notifier->setIdentity(identity); notifier->setIdentity(identity);
QThread* thread = new QThread(); QThread *thread = new QThread();
connect(notifier, SIGNAL(finished()), thread, SLOT(quit())); connect(notifier, SIGNAL(finished()), thread, SLOT(quit()));
connect(notifier, SIGNAL(finished()), notifier, SLOT(deleteLater())); connect(notifier, SIGNAL(finished()), notifier, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
@ -186,16 +160,13 @@ LicenseManager::notifyActivation(QString identity) const
QMetaObject::invokeMethod(notifier, "notify", Qt::QueuedConnection); QMetaObject::invokeMethod(notifier, "notify", Qt::QueuedConnection);
} }
QString QString LicenseManager::getLicenseNotice() const {
LicenseManager::getLicenseNotice() const
{
QString Notice; QString Notice;
if (m_serialKey.isTemporary()){ if (m_serialKey.isTemporary()) {
if (m_serialKey.isTrial()){ if (m_serialKey.isTrial()) {
Notice = getTrialNotice(); Notice = getTrialNotice();
} } else {
else{
Notice = getTemporaryNotice(); Notice = getTemporaryNotice();
} }
} }
@ -203,69 +174,61 @@ LicenseManager::getLicenseNotice() const
return Notice; return Notice;
} }
void void LicenseManager::registerLicense() { m_registry.registerLicense(); }
LicenseManager::registerLicense()
{
m_registry.registerLicense();
}
QString QString LicenseManager::getTrialNotice() const {
LicenseManager::getTrialNotice() const
{
QString Notice; QString Notice;
if (m_serialKey.isExpired(::time(0))){ if (m_serialKey.isExpired(::time(0))) {
Notice = "<html><head/><body><p>" Notice = "<html><head/><body><p>"
"Trial expired - " "Trial expired - "
"<a href=\"https://symless.com/synergy/purchase?source=gui\" style=\"color: #FFFFFF;\">Buy now</a>" "<a href=\"https://symless.com/synergy/purchase?source=gui\" "
"style=\"color: #FFFFFF;\">Buy now</a>"
"</p></body></html>"; "</p></body></html>";
} } else {
else{
Notice = "<html><head/><body><p>" Notice = "<html><head/><body><p>"
"Trial expires in %1 day%2 - " "Trial expires in %1 day%2 - "
"<a href=\"https://symless.com/synergy/purchase?source=gui\" style=\"color: #FFFFFF;\">Buy now</a>" "<a href=\"https://symless.com/synergy/purchase?source=gui\" "
"style=\"color: #FFFFFF;\">Buy now</a>"
"</p></body></html>"; "</p></body></html>";
time_t daysLeft = m_serialKey.daysLeft(::time(0)); time_t daysLeft = m_serialKey.daysLeft(::time(0));
Notice = Notice.arg (daysLeft).arg ((daysLeft == 1) ? "" : "s"); Notice = Notice.arg(daysLeft).arg((daysLeft == 1) ? "" : "s");
} }
return Notice; return Notice;
} }
QString QString LicenseManager::getTemporaryNotice() const {
LicenseManager::getTemporaryNotice() const
{
QString Notice; QString Notice;
if (m_serialKey.isExpired(::time(0))) { if (m_serialKey.isExpired(::time(0))) {
Notice = "<html><head/><body><p>" Notice = "<html><head/><body><p>"
"License expired - " "License expired - "
"<a href=\"https://symless.com/synergy/purchase?source=gui\" style=\"color: #FFFFFF;\">Renew now</a>" "<a href=\"https://symless.com/synergy/purchase?source=gui\" "
"style=\"color: #FFFFFF;\">Renew now</a>"
"</p></body></html>"; "</p></body></html>";
} } else if (m_serialKey.isExpiring(::time(0))) {
else if (m_serialKey.isExpiring(::time(0))) {
Notice = "<html><head/><body><p>" Notice = "<html><head/><body><p>"
"License expires in %1 day%2 - " "License expires in %1 day%2 - "
"<a href=\"https://symless.com/synergy/purchase?source=gui\" style=\"color: #FFFFFF;\">Renew now</a>" "<a href=\"https://symless.com/synergy/purchase?source=gui\" "
"style=\"color: #FFFFFF;\">Renew now</a>"
"</p></body></html>"; "</p></body></html>";
time_t daysLeft = m_serialKey.daysLeft(::time(0)); time_t daysLeft = m_serialKey.daysLeft(::time(0));
Notice = Notice.arg (daysLeft).arg ((daysLeft == 1) ? "" : "s"); Notice = Notice.arg(daysLeft).arg((daysLeft == 1) ? "" : "s");
} }
return Notice; return Notice;
} }
void void LicenseManager::validateSerialKey() const {
LicenseManager::validateSerialKey() const
{
if (m_serialKey.isValid()) { if (m_serialKey.isValid()) {
if (m_serialKey.isTemporary()){ if (m_serialKey.isTemporary()) {
QTimer::singleShot(m_serialKey.getSpanLeft(), this, SLOT(validateSerialKey())); QTimer::singleShot(m_serialKey.getSpanLeft(), this,
SLOT(validateSerialKey()));
} }
} } else {
else{
emit InvalidLicense(); emit InvalidLicense();
} }
} }

View file

@ -17,27 +17,26 @@
#pragma once #pragma once
#include <ActivationNotifier.h>
#include <QObject> #include <QObject>
#include <shared/EditionType.h> #include <shared/EditionType.h>
#include <shared/SerialKey.h> #include <shared/SerialKey.h>
#include <ActivationNotifier.h>
#include <utility> #include <utility>
#include "LicenseRegistry.h" #include "LicenseRegistry.h"
class AppConfig; class AppConfig;
class LicenseManager: public QObject class LicenseManager : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
LicenseManager(AppConfig* appConfig); LicenseManager(AppConfig *appConfig);
void setSerialKey(SerialKey serialKey, bool acceptExpired = false); void setSerialKey(SerialKey serialKey, bool acceptExpired = false);
void refresh(); void refresh();
Edition activeEdition() const; Edition activeEdition() const;
QString activeEditionName() const; QString activeEditionName() const;
const SerialKey& serialKey() const; const SerialKey &serialKey() const;
void skipActivation() const; void skipActivation() const;
void notifyUpdate(QString fromVersion, QString toVersion) const; void notifyUpdate(QString fromVersion, QString toVersion) const;
static QString getEditionName(Edition edition, bool trial = false); static QString getEditionName(Edition edition, bool trial = false);
@ -45,7 +44,7 @@ public:
QString getLicenseNotice() const; QString getLicenseNotice() const;
private: private:
AppConfig* m_AppConfig; AppConfig *m_AppConfig;
SerialKey m_serialKey; SerialKey m_serialKey;
LicenseRegistry m_registry; LicenseRegistry m_registry;
@ -54,9 +53,9 @@ public slots:
void registerLicense(); void registerLicense();
signals: signals:
void editionChanged (Edition) const; void editionChanged(Edition) const;
void InvalidLicense () const; void InvalidLicense() const;
void showLicenseNotice(const QString& notice) const; void showLicenseNotice(const QString &notice) const;
protected: protected:
QString getTrialNotice() const; QString getTrialNotice() const;

View file

@ -14,23 +14,20 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QNetworkReply>
#include <QJsonObject>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QTimer> #include <QTimer>
#include "LicenseRegistry.h"
#include "AppConfig.h" #include "AppConfig.h"
#include "LicenseRegistry.h"
#include <QSysInfo> #include <QSysInfo>
LicenseRegistry::LicenseRegistry(AppConfig& config) : LicenseRegistry::LicenseRegistry(AppConfig &config) : m_config(config) {
m_config(config)
{
connect(&m_timer, SIGNAL(timeout()), this, SLOT(registerLicense())); connect(&m_timer, SIGNAL(timeout()), this, SLOT(registerLicense()));
} }
void LicenseRegistry::registerLicense() void LicenseRegistry::registerLicense() {
{
m_timer.stop(); m_timer.stop();
if (m_config.edition() == Edition::kBusiness) { if (m_config.edition() == Edition::kBusiness) {
const auto REGISTER_LICENSE_URL = m_config.getLicenseRegistryUrl(); const auto REGISTER_LICENSE_URL = m_config.getLicenseRegistryUrl();
@ -40,22 +37,21 @@ void LicenseRegistry::registerLicense()
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
m_manager.post(request, getRequestData()); m_manager.post(request, getRequestData());
connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleResponse(QNetworkReply*))); connect(&m_manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(handleResponse(QNetworkReply *)));
} }
} }
void LicenseRegistry::handleResponse(QNetworkReply *reply) void LicenseRegistry::handleResponse(QNetworkReply *reply) {
{
if (reply) { if (reply) {
const auto HOUR = (60*60); //seconds per hour const auto HOUR = (60 * 60); // seconds per hour
const auto DAY = (24*HOUR);//seconds per day const auto DAY = (24 * HOUR); // seconds per day
const auto WEEK = (7*DAY); //seconds per week const auto WEEK = (7 * DAY); // seconds per week
const auto currentTimestamp = time(nullptr); const auto currentTimestamp = time(nullptr);
if(reply->error() == QNetworkReply::NoError) { if (reply->error() == QNetworkReply::NoError) {
m_config.setLicenseNextCheck(currentTimestamp + WEEK); m_config.setLicenseNextCheck(currentTimestamp + WEEK);
} } else {
else{
m_config.setLicenseNextCheck(currentTimestamp + HOUR); m_config.setLicenseNextCheck(currentTimestamp + HOUR);
} }
@ -64,8 +60,7 @@ void LicenseRegistry::handleResponse(QNetworkReply *reply)
} }
} }
QByteArray LicenseRegistry::getRequestData() const QByteArray LicenseRegistry::getRequestData() const {
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
QString guid(QSysInfo::machineUniqueId()); QString guid(QSysInfo::machineUniqueId());
#else #else
@ -76,8 +71,7 @@ QByteArray LicenseRegistry::getRequestData() const
if (!guid.isEmpty()) { if (!guid.isEmpty()) {
data["guid"] = guid; data["guid"] = guid;
data["guid_type"] = "system"; data["guid_type"] = "system";
} } else {
else {
data["guid"] = m_config.getGuid(); data["guid"] = m_config.getGuid();
data["guid_type"] = "synergy"; data["guid_type"] = "synergy";
} }
@ -88,16 +82,15 @@ QByteArray LicenseRegistry::getRequestData() const
return QJsonDocument(data).toJson(); return QJsonDocument(data).toJson();
} }
void LicenseRegistry::scheduleRegistration() void LicenseRegistry::scheduleRegistration() {
{
const auto nextCheck = m_config.getLicenseNextCheck(); const auto nextCheck = m_config.getLicenseNextCheck();
const auto currentTimestamp = static_cast<unsigned long long>(time(nullptr)); const auto currentTimestamp = static_cast<unsigned long long>(time(nullptr));
if (currentTimestamp >= nextCheck) { if (currentTimestamp >= nextCheck) {
registerLicense(); registerLicense();
} } else {
else { const auto interval =
const auto interval = (nextCheck - currentTimestamp) * 1000; //interval in milliseconds (nextCheck - currentTimestamp) * 1000; // interval in milliseconds
m_timer.setInterval(static_cast<int>(interval)); m_timer.setInterval(static_cast<int>(interval));
m_timer.setSingleShot(true); m_timer.setSingleShot(true);
m_timer.start(); m_timer.start();

View file

@ -16,19 +16,18 @@
*/ */
#pragma once #pragma once
#include <QNetworkAccessManager>
#include <QObject> #include <QObject>
#include <QTimer> #include <QTimer>
#include <QNetworkAccessManager>
class QNetworkReply; class QNetworkReply;
class AppConfig; class AppConfig;
class LicenseRegistry : public QObject class LicenseRegistry : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
explicit LicenseRegistry(AppConfig& config); explicit LicenseRegistry(AppConfig &config);
void scheduleRegistration(); void scheduleRegistration();
public slots: public slots:
@ -36,7 +35,7 @@ public slots:
void handleResponse(QNetworkReply *reply); void handleResponse(QNetworkReply *reply);
private: private:
AppConfig& m_config; AppConfig &m_config;
QNetworkAccessManager m_manager; QNetworkAccessManager m_manager;
QTimer m_timer; QTimer m_timer;

File diff suppressed because it is too large Load diff

View file

@ -19,23 +19,23 @@
#pragma once #pragma once
#include <QMainWindow> #include <QMainWindow>
#include <QSystemTrayIcon>
#include <QSettings>
#include <QProcess>
#include <QThread>
#include <QMutex> #include <QMutex>
#include <QProcess>
#include <QSettings>
#include <QSystemTrayIcon>
#include <QThread>
#include "ui_MainWindowBase.h" #include "ui_MainWindowBase.h"
#include "ActivationDialog.h"
#include "AppConfig.h"
#include "ClientConnection.h"
#include "ConfigWriter.h"
#include "Ipc.h"
#include "IpcClient.h"
#include "ServerConfig.h" #include "ServerConfig.h"
#include "ServerConnection.h" #include "ServerConnection.h"
#include "ClientConnection.h"
#include "AppConfig.h"
#include "VersionChecker.h" #include "VersionChecker.h"
#include "IpcClient.h"
#include "Ipc.h"
#include "ActivationDialog.h"
#include "ConfigWriter.h"
#include "TrayIcon.h" #include "TrayIcon.h"
@ -61,8 +61,7 @@ class SslCertificate;
class LicenseManager; class LicenseManager;
class Zeroconf; class Zeroconf;
class MainWindow : public QMainWindow, public Ui::MainWindowBase class MainWindow : public QMainWindow, public Ui::MainWindowBase {
{
Q_OBJECT Q_OBJECT
friend class QSynergyApplication; friend class QSynergyApplication;
@ -72,9 +71,8 @@ class MainWindow : public QMainWindow, public Ui::MainWindowBase
friend class ServerConnection; friend class ServerConnection;
friend class ClientConnection; friend class ClientConnection;
public: public:
enum qSynergyState enum qSynergyState {
{
synergyDisconnected, synergyDisconnected,
synergyConnecting, synergyConnecting,
synergyConnected, synergyConnected,
@ -82,50 +80,41 @@ class MainWindow : public QMainWindow, public Ui::MainWindowBase
synergyPendingRetry synergyPendingRetry
}; };
enum qSynergyType enum qSynergyType { synergyClient, synergyServer };
{
synergyClient,
synergyServer
};
enum qLevel { enum qLevel { Error, Info };
Error,
Info
};
enum qRuningState { enum qRuningState { kStarted, kStopped };
kStarted,
kStopped
};
public: public:
#ifdef SYNERGY_ENTERPRISE #ifdef SYNERGY_ENTERPRISE
MainWindow(AppConfig& appConfig); MainWindow(AppConfig &appConfig);
#else #else
MainWindow(AppConfig& appConfig, MainWindow(AppConfig &appConfig, LicenseManager &licenseManager);
LicenseManager& licenseManager);
#endif #endif
~MainWindow(); ~MainWindow();
public: public:
void setVisible(bool visible); void setVisible(bool visible);
int synergyType() const { return m_pRadioGroupClient->isChecked() ? synergyClient : synergyServer; } int synergyType() const {
return m_pRadioGroupClient->isChecked() ? synergyClient : synergyServer;
}
int synergyState() const { return m_SynergyState; } int synergyState() const { return m_SynergyState; }
QString hostname() const { return m_pLineEditHostname->text(); } QString hostname() const { return m_pLineEditHostname->text(); }
QString configFilename(); QString configFilename();
QString address() const; QString address() const;
QString appPath(const QString& name); QString appPath(const QString &name);
void open(); void open();
void clearLog(); void clearLog();
VersionChecker& versionChecker() { return m_VersionChecker; } VersionChecker &versionChecker() { return m_VersionChecker; }
ServerConfig& serverConfig() { return m_ServerConfig; } ServerConfig &serverConfig() { return m_ServerConfig; }
void showConfigureServer(const QString& message); void showConfigureServer(const QString &message);
void showConfigureServer() { showConfigureServer(""); } void showConfigureServer() { showConfigureServer(""); }
void autoAddScreen(const QString name); void autoAddScreen(const QString name);
void addZeroconfServer(const QString name); void addZeroconfServer(const QString name);
Zeroconf& zeroconf() { return *m_pZeroconf; } Zeroconf &zeroconf() { return *m_pZeroconf; }
#ifndef SYNERGY_ENTERPRISE #ifndef SYNERGY_ENTERPRISE
LicenseManager& licenseManager() const; LicenseManager &licenseManager() const;
int raiseActivationDialog(); int raiseActivationDialog();
#endif #endif
@ -135,18 +124,18 @@ public slots:
void setEdition(Edition edition); void setEdition(Edition edition);
#ifndef SYNERGY_ENTERPRISE #ifndef SYNERGY_ENTERPRISE
void InvalidLicense(); void InvalidLicense();
void showLicenseNotice(const QString& message); void showLicenseNotice(const QString &message);
#endif #endif
void appendLogRaw(const QString& text); void appendLogRaw(const QString &text);
void appendLogInfo(const QString& text); void appendLogInfo(const QString &text);
void appendLogDebug(const QString& text); void appendLogDebug(const QString &text);
void appendLogError(const QString& text); void appendLogError(const QString &text);
void startSynergy(); void startSynergy();
void retryStart(); // If the connection failed this will retry a startSynergy void retryStart(); // If the connection failed this will retry a startSynergy
void actionStart(); void actionStart();
void handleIdleService(const QString& text); void handleIdleService(const QString &text);
protected slots: protected slots:
void updateLocalFingerprint(); void updateLocalFingerprint();
void updateScreenName(); void updateScreenName();
void on_m_pRadioGroupServer_clicked(bool); void on_m_pRadioGroupServer_clicked(bool);
@ -162,19 +151,21 @@ public slots:
void stopSynergy(); void stopSynergy();
void logOutput(); void logOutput();
void logError(); void logError();
void updateFound(const QString& version); void updateFound(const QString &version);
void saveSettings(); void saveSettings();
/// @brief Receives the signal that the auto config option has changed /// @brief Receives the signal that the auto config option has changed
void zeroConfToggled(); void zeroConfToggled();
protected: protected:
// TODO This should be properly using the ConfigWriter system. // TODO This should be properly using the ConfigWriter system.
QSettings& settings() { return GUI::Config::ConfigWriter::make()->settings(); } QSettings &settings() {
AppConfig& appConfig() { return *m_AppConfig; } return GUI::Config::ConfigWriter::make()->settings();
AppConfig const& appConfig() const { return *m_AppConfig; } }
QProcess* synergyProcess() { return m_pSynergy; } AppConfig &appConfig() { return *m_AppConfig; }
void setSynergyProcess(QProcess* p) { m_pSynergy = p; } AppConfig const &appConfig() const { return *m_AppConfig; }
QProcess *synergyProcess() { return m_pSynergy; }
void setSynergyProcess(QProcess *p) { m_pSynergy = p; }
void initConnections(); void initConnections();
void createMenuBar(); void createMenuBar();
void createStatusBar(); void createStatusBar();
@ -182,20 +173,21 @@ public slots:
void loadSettings(); void loadSettings();
void setIcon(qSynergyState state) const; void setIcon(qSynergyState state) const;
void setSynergyState(qSynergyState state); void setSynergyState(qSynergyState state);
bool checkForApp(int which, QString& app); bool checkForApp(int which, QString &app);
bool clientArgs(QStringList& args, QString& app); bool clientArgs(QStringList &args, QString &app);
bool serverArgs(QStringList& args, QString& app); bool serverArgs(QStringList &args, QString &app);
void setStatus(const QString& status); void setStatus(const QString &status);
void sendIpcMessage(qIpcMessageType type, const char* buffer, bool showErrors); void sendIpcMessage(qIpcMessageType type, const char *buffer,
void updateFromLogLine(const QString& line); bool showErrors);
void updateFromLogLine(const QString &line);
QString getIPAddresses(); QString getIPAddresses();
void stopService(); void stopService();
void stopDesktop(); void stopDesktop();
void changeEvent(QEvent* event); void changeEvent(QEvent *event);
void retranslateMenuBar(); void retranslateMenuBar();
void enableServer(bool enable); void enableServer(bool enable);
void enableClient(bool enable); void enableClient(bool enable);
void closeEvent(QCloseEvent* event) override; void closeEvent(QCloseEvent *event) override;
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
bool isServiceRunning(QString name); bool isServiceRunning(QString name);
@ -204,50 +196,51 @@ public slots:
#endif #endif
QString getProfileRootForArg(); QString getProfileRootForArg();
void checkConnected(const QString& line); void checkConnected(const QString &line);
void checkFingerprint(const QString& line); void checkFingerprint(const QString &line);
void checkSecureSocket(const QString& line); void checkSecureSocket(const QString &line);
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
void checkOSXNotification(const QString& line); void checkOSXNotification(const QString &line);
#endif #endif
#ifndef SYNERGY_ENTERPRISE #ifndef SYNERGY_ENTERPRISE
void checkLicense(const QString& line); void checkLicense(const QString &line);
#endif #endif
QString getTimeStamp(); QString getTimeStamp();
void restartSynergy(); void restartSynergy();
void proofreadInfo(); void proofreadInfo();
void showEvent (QShowEvent*); void showEvent(QShowEvent *);
void secureSocket(bool secureSocket); void secureSocket(bool secureSocket);
void windowStateChanged(); void windowStateChanged();
private:
private:
#ifndef SYNERGY_ENTERPRISE #ifndef SYNERGY_ENTERPRISE
LicenseManager* m_LicenseManager; LicenseManager *m_LicenseManager;
bool m_ActivationDialogRunning; bool m_ActivationDialogRunning;
QStringList m_PendingClientNames; QStringList m_PendingClientNames;
#endif #endif
Zeroconf* m_pZeroconf; Zeroconf *m_pZeroconf;
AppConfig* m_AppConfig; AppConfig *m_AppConfig;
QProcess* m_pSynergy; QProcess *m_pSynergy;
int m_SynergyState; int m_SynergyState;
ServerConfig m_ServerConfig; ServerConfig m_ServerConfig;
bool m_AlreadyHidden; bool m_AlreadyHidden;
VersionChecker m_VersionChecker; VersionChecker m_VersionChecker;
IpcClient m_IpcClient; IpcClient m_IpcClient;
QMenuBar* m_pMenuBar; QMenuBar *m_pMenuBar;
QMenu* m_pMenuFile; QMenu *m_pMenuFile;
QMenu* m_pMenuEdit; QMenu *m_pMenuEdit;
QMenu* m_pMenuWindow; QMenu *m_pMenuWindow;
QMenu* m_pMenuHelp; QMenu *m_pMenuHelp;
QAbstractButton* m_pCancelButton; QAbstractButton *m_pCancelButton;
TrayIcon m_trayIcon; TrayIcon m_trayIcon;
qRuningState m_ExpectedRunningState; qRuningState m_ExpectedRunningState;
QMutex m_StopDesktopMutex; QMutex m_StopDesktopMutex;
bool m_SecureSocket; // brief Is the program running a secure socket protocol (SSL/TLS) bool m_SecureSocket; // brief Is the program running a secure socket protocol
QString m_SecureSocketVersion; // brief Contains the version of the Secure Socket currently active // (SSL/TLS)
QString m_SecureSocketVersion; // brief Contains the version of the Secure
// Socket currently active
ServerConnection m_serverConnection; ServerConnection m_serverConnection;
ClientConnection m_clientConnection; ClientConnection m_clientConnection;
@ -259,7 +252,7 @@ private slots:
void on_windowShown(); void on_windowShown();
void on_m_pLabelComputerName_linkActivated(const QString &link); void on_m_pLabelComputerName_linkActivated(const QString &link);
void on_m_pLabelFingerprint_linkActivated(const QString& link); void on_m_pLabelFingerprint_linkActivated(const QString &link);
void on_m_pComboServerList_currentIndexChanged(const QString &arg1); void on_m_pComboServerList_currentIndexChanged(const QString &arg1);
void on_m_pButtonConnect_clicked(); void on_m_pButtonConnect_clicked();

View file

@ -21,15 +21,11 @@
#include <QString> #include <QString>
enum class IconsTheme { enum class IconsTheme { ICONS_DARK, ICONS_LIGHT, ICONS_TEMPLATE };
ICONS_DARK,
ICONS_LIGHT,
ICONS_TEMPLATE
};
void requestOSXNotificationPermission(); void requestOSXNotificationPermission();
bool isOSXDevelopmentBuild(); bool isOSXDevelopmentBuild();
bool showOSXNotification(const QString& title, const QString& body); bool showOSXNotification(const QString &title, const QString &body);
bool isOSXInterfaceStyleDark(); bool isOSXInterfaceStyleDark();
IconsTheme getOSXIconsTheme(); IconsTheme getOSXIconsTheme();

View file

@ -22,12 +22,10 @@
#include <QtCore> #include <QtCore>
#include <QtGui> #include <QtGui>
QSynergyApplication* QSynergyApplication::s_Instance = NULL; QSynergyApplication *QSynergyApplication::s_Instance = NULL;
QSynergyApplication::QSynergyApplication(int& argc, char** argv) : QSynergyApplication::QSynergyApplication(int &argc, char **argv)
QApplication(argc, argv), : QApplication(argc, argv), m_Translator(NULL) {
m_Translator(NULL)
{
s_Instance = this; s_Instance = this;
QFontDatabase::addApplicationFont(":/res/fonts/Arial.ttf"); QFontDatabase::addApplicationFont(":/res/fonts/Arial.ttf");
@ -37,30 +35,20 @@ QSynergyApplication::QSynergyApplication(int& argc, char** argv) :
setFont(Arial); setFont(Arial);
} }
QSynergyApplication::~QSynergyApplication() QSynergyApplication::~QSynergyApplication() { delete m_Translator; }
{
delete m_Translator;
}
void QSynergyApplication::commitData(QSessionManager&) void QSynergyApplication::commitData(QSessionManager &) {
{ foreach (QWidget *widget, topLevelWidgets()) {
foreach(QWidget* widget, topLevelWidgets()) MainWindow *mainWindow = qobject_cast<MainWindow *>(widget);
{
MainWindow* mainWindow = qobject_cast<MainWindow*>(widget);
if (mainWindow) if (mainWindow)
mainWindow->saveSettings(); mainWindow->saveSettings();
} }
} }
QSynergyApplication* QSynergyApplication::getInstance() QSynergyApplication *QSynergyApplication::getInstance() { return s_Instance; }
{
return s_Instance;
}
void QSynergyApplication::switchTranslator(QString lang) void QSynergyApplication::switchTranslator(QString lang) {
{ if (m_Translator != NULL) {
if (m_Translator != NULL)
{
removeTranslator(m_Translator); removeTranslator(m_Translator);
delete m_Translator; delete m_Translator;
} }
@ -71,8 +59,7 @@ void QSynergyApplication::switchTranslator(QString lang)
installTranslator(m_Translator); installTranslator(m_Translator);
} }
void QSynergyApplication::setTranslator(QTranslator* translator) void QSynergyApplication::setTranslator(QTranslator *translator) {
{
m_Translator = translator; m_Translator = translator;
installTranslator(m_Translator); installTranslator(m_Translator);
} }

View file

@ -24,24 +24,22 @@
class QSessionManager; class QSessionManager;
class QSynergyApplication : public QApplication class QSynergyApplication : public QApplication {
{ public:
public: QSynergyApplication(int &argc, char **argv);
QSynergyApplication(int& argc, char** argv);
~QSynergyApplication(); ~QSynergyApplication();
public: public:
void commitData(QSessionManager& manager); void commitData(QSessionManager &manager);
void switchTranslator(QString lang); void switchTranslator(QString lang);
void setTranslator(QTranslator* translator); void setTranslator(QTranslator *translator);
static QSynergyApplication* getInstance(); static QSynergyApplication *getInstance();
private: private:
QTranslator* m_Translator; QTranslator *m_Translator;
static QSynergyApplication* s_Instance; static QSynergyApplication *s_Instance;
}; };
#endif #endif

View file

@ -17,12 +17,12 @@
#include "QUtility.h" #include "QUtility.h"
#include "ProcessorArch.h"
#include "CommandProcess.h" #include "CommandProcess.h"
#include "ProcessorArch.h"
#if defined(Q_OS_LINUX) #if defined(Q_OS_LINUX)
#include <QProcess>
#include <QFile> #include <QFile>
#include <QProcess>
#endif #endif
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
@ -30,27 +30,22 @@
#include <Windows.h> #include <Windows.h>
#endif #endif
void setIndexFromItemData(QComboBox* comboBox, const QVariant& itemData) void setIndexFromItemData(QComboBox *comboBox, const QVariant &itemData) {
{ for (int i = 0; i < comboBox->count(); ++i) {
for (int i = 0; i < comboBox->count(); ++i) if (comboBox->itemData(i) == itemData) {
{
if (comboBox->itemData(i) == itemData)
{
comboBox->setCurrentIndex(i); comboBox->setCurrentIndex(i);
return; return;
} }
} }
} }
QString hash(const QString& string) QString hash(const QString &string) {
{
QByteArray data = string.toUtf8(); QByteArray data = string.toUtf8();
QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5); QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5);
return hash.toHex(); return hash.toHex();
} }
qProcessorArch getProcessorArch() qProcessorArch getProcessorArch() {
{
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
SYSTEM_INFO systemInfo; SYSTEM_INFO systemInfo;
GetNativeSystemInfo(&systemInfo); GetNativeSystemInfo(&systemInfo);

View file

@ -20,10 +20,10 @@
#include "ProcessorArch.h" #include "ProcessorArch.h"
#include <QComboBox> #include <QComboBox>
#include <QVariant>
#include <QCryptographicHash> #include <QCryptographicHash>
#include <QNetworkInterface> #include <QNetworkInterface>
#include <QVariant>
void setIndexFromItemData(QComboBox* comboBox, const QVariant& itemData); void setIndexFromItemData(QComboBox *comboBox, const QVariant &itemData);
QString hash(const QString& string); QString hash(const QString &string);
qProcessorArch getProcessorArch(); qProcessorArch getProcessorArch();

View file

@ -21,23 +21,20 @@
#include <QtCore> #include <QtCore>
#include <QtGui> #include <QtGui>
Screen::Screen() : Screen::Screen()
m_Pixmap(QPixmap(":res/icons/64x64/video-display.png")), : m_Pixmap(QPixmap(":res/icons/64x64/video-display.png")),
m_Swapped(false) m_Swapped(false) {
{
init(); init();
} }
Screen::Screen(const QString& name) : Screen::Screen(const QString &name)
m_Pixmap(QPixmap(":res/icons/64x64/video-display.png")), : m_Pixmap(QPixmap(":res/icons/64x64/video-display.png")),
m_Swapped(false) m_Swapped(false) {
{
init(); init();
setName(name); setName(name);
} }
void Screen::init() void Screen::init() {
{
name().clear(); name().clear();
aliases().clear(); aliases().clear();
modifiers().clear(); modifiers().clear();
@ -45,8 +42,9 @@ void Screen::init()
fixes().clear(); fixes().clear();
setSwitchCornerSize(0); setSwitchCornerSize(0);
// m_Modifiers, m_SwitchCorners and m_Fixes are QLists we use like fixed-size arrays, // m_Modifiers, m_SwitchCorners and m_Fixes are QLists we use like fixed-size
// thus we need to make sure to fill them with the required number of elements. // arrays, thus we need to make sure to fill them with the required number of
// elements.
for (int i = 0; i < NumModifiers; i++) for (int i = 0; i < NumModifiers; i++)
modifiers() << i; modifiers() << i;
@ -57,8 +55,7 @@ void Screen::init()
fixes() << false; fixes() << false;
} }
void Screen::loadSettings(QSettings& settings) void Screen::loadSettings(QSettings &settings) {
{
setName(settings.value("name").toString()); setName(settings.value("name").toString());
if (name().isEmpty()) if (name().isEmpty())
@ -67,13 +64,14 @@ void Screen::loadSettings(QSettings& settings)
setSwitchCornerSize(settings.value("switchCornerSize").toInt()); setSwitchCornerSize(settings.value("switchCornerSize").toInt());
readSettings(settings, aliases(), "alias", QString("")); readSettings(settings, aliases(), "alias", QString(""));
readSettings(settings, modifiers(), "modifier", static_cast<int>(DefaultMod), NumModifiers); readSettings(settings, modifiers(), "modifier", static_cast<int>(DefaultMod),
readSettings(settings, switchCorners(), "switchCorner", false, NumSwitchCorners); NumModifiers);
readSettings(settings, switchCorners(), "switchCorner", false,
NumSwitchCorners);
readSettings(settings, fixes(), "fix", false, NumFixes); readSettings(settings, fixes(), "fix", false, NumFixes);
} }
void Screen::saveSettings(QSettings& settings) const void Screen::saveSettings(QSettings &settings) const {
{
settings.setValue("name", name()); settings.setValue("name", name());
if (name().isEmpty()) if (name().isEmpty())
@ -87,75 +85,60 @@ void Screen::saveSettings(QSettings& settings) const
writeSettings(settings, fixes(), "fix"); writeSettings(settings, fixes(), "fix");
} }
QTextStream& Screen::writeScreensSection(QTextStream& outStream) const QTextStream &Screen::writeScreensSection(QTextStream &outStream) const {
{
outStream << "\t" << name() << ":" << endl; outStream << "\t" << name() << ":" << endl;
for (int i = 0; i < modifiers().size(); i++) for (int i = 0; i < modifiers().size(); i++)
if (modifier(i) != i) if (modifier(i) != i)
outStream << "\t\t" << modifierName(i) << " = " << modifierName(modifier(i)) << endl; outStream << "\t\t" << modifierName(i) << " = "
<< modifierName(modifier(i)) << endl;
for (int i = 0; i < fixes().size(); i++) for (int i = 0; i < fixes().size(); i++)
outStream << "\t\t" << fixName(i) << " = " << (fixes()[i] ? "true" : "false") << endl; outStream << "\t\t" << fixName(i) << " = "
<< (fixes()[i] ? "true" : "false") << endl;
outStream << "\t\t" << "switchCorners = none "; outStream << "\t\t"
<< "switchCorners = none ";
for (int i = 0; i < switchCorners().size(); i++) for (int i = 0; i < switchCorners().size(); i++)
if (switchCorners()[i]) if (switchCorners()[i])
outStream << "+" << switchCornerName(i) << " "; outStream << "+" << switchCornerName(i) << " ";
outStream << endl; outStream << endl;
outStream << "\t\t" << "switchCornerSize = " << switchCornerSize() << endl; outStream << "\t\t"
<< "switchCornerSize = " << switchCornerSize() << endl;
return outStream; return outStream;
} }
QTextStream& Screen::writeAliasesSection(QTextStream& outStream) const QTextStream &Screen::writeAliasesSection(QTextStream &outStream) const {
{ if (!aliases().isEmpty()) {
if (!aliases().isEmpty())
{
outStream << "\t" << name() << ":" << endl; outStream << "\t" << name() << ":" << endl;
foreach (const QString& alias, aliases()) foreach (const QString &alias, aliases())
outStream << "\t\t" << alias << endl; outStream << "\t\t" << alias << endl;
} }
return outStream; return outStream;
} }
bool Screen::operator==(const Screen& screen) const bool Screen::operator==(const Screen &screen) const {
{ return m_Name == screen.m_Name && m_Aliases == screen.m_Aliases &&
return m_Name == screen.m_Name &&
m_Aliases == screen.m_Aliases &&
m_Modifiers == screen.m_Modifiers && m_Modifiers == screen.m_Modifiers &&
m_SwitchCorners == screen.m_SwitchCorners && m_SwitchCorners == screen.m_SwitchCorners &&
m_SwitchCornerSize == screen.m_SwitchCornerSize && m_SwitchCornerSize == screen.m_SwitchCornerSize &&
m_Fixes == screen.m_Fixes && m_Fixes == screen.m_Fixes && m_Swapped == screen.m_Swapped &&
m_Swapped == screen.m_Swapped &&
m_isServer == screen.m_isServer; m_isServer == screen.m_isServer;
} }
QDataStream& operator<<(QDataStream& outStream, const Screen& screen) QDataStream &operator<<(QDataStream &outStream, const Screen &screen) {
{ return outStream << screen.name() << screen.switchCornerSize()
return outStream << screen.aliases() << screen.modifiers()
<< screen.name() << screen.switchCorners() << screen.fixes()
<< screen.switchCornerSize() << screen.isServer();
<< screen.aliases()
<< screen.modifiers()
<< screen.switchCorners()
<< screen.fixes()
<< screen.isServer()
;
} }
QDataStream& operator>>(QDataStream& inStream, Screen& screen) QDataStream &operator>>(QDataStream &inStream, Screen &screen) {
{ return inStream >> screen.m_Name >> screen.m_SwitchCornerSize >>
return inStream screen.m_Aliases >> screen.m_Modifiers >> screen.m_SwitchCorners >>
>> screen.m_Name screen.m_Fixes >> screen.m_isServer;
>> screen.m_SwitchCornerSize
>> screen.m_Aliases
>> screen.m_Modifiers
>> screen.m_SwitchCorners
>> screen.m_Fixes
>> screen.m_isServer
;
} }

View file

@ -20,9 +20,9 @@
#define SCREEN__H #define SCREEN__H
#include <QList>
#include <QPixmap> #include <QPixmap>
#include <QString> #include <QString>
#include <QList>
#include <QStringList> #include <QStringList>
#include "BaseConfig.h" #include "BaseConfig.h"
@ -32,60 +32,61 @@ class QTextStream;
class ScreenSettingsDialog; class ScreenSettingsDialog;
class Screen : public BaseConfig class Screen : public BaseConfig {
{ friend QDataStream &operator<<(QDataStream &outStream, const Screen &screen);
friend QDataStream& operator<<(QDataStream& outStream, const Screen& screen); friend QDataStream &operator>>(QDataStream &inStream, Screen &screen);
friend QDataStream& operator>>(QDataStream& inStream, Screen& screen);
friend class ScreenSettingsDialog; friend class ScreenSettingsDialog;
friend class ScreenSetupModel; friend class ScreenSetupModel;
friend class ScreenSetupView; friend class ScreenSetupView;
public: public:
Screen(); Screen();
Screen(const QString& name); Screen(const QString &name);
public: public:
const QPixmap& pixmap() const { return m_Pixmap; } const QPixmap &pixmap() const { return m_Pixmap; }
const QString& name() const { return m_Name; } const QString &name() const { return m_Name; }
const QStringList& aliases() const { return m_Aliases; } const QStringList &aliases() const { return m_Aliases; }
bool isNull() const { return m_Name.isEmpty(); } bool isNull() const { return m_Name.isEmpty(); }
int modifier(int m) const { return m_Modifiers[m] == DefaultMod ? m : m_Modifiers[m]; } int modifier(int m) const {
const QList<int>& modifiers() const { return m_Modifiers; } return m_Modifiers[m] == DefaultMod ? m : m_Modifiers[m];
}
const QList<int> &modifiers() const { return m_Modifiers; }
bool switchCorner(int c) const { return m_SwitchCorners[c]; } bool switchCorner(int c) const { return m_SwitchCorners[c]; }
const QList<bool>& switchCorners() const { return m_SwitchCorners; } const QList<bool> &switchCorners() const { return m_SwitchCorners; }
int switchCornerSize() const { return m_SwitchCornerSize; } int switchCornerSize() const { return m_SwitchCornerSize; }
bool fix(Fix f) const { return m_Fixes[f]; } bool fix(Fix f) const { return m_Fixes[f]; }
const QList<bool>& fixes() const { return m_Fixes; } const QList<bool> &fixes() const { return m_Fixes; }
void loadSettings(QSettings& settings); void loadSettings(QSettings &settings);
void saveSettings(QSettings& settings) const; void saveSettings(QSettings &settings) const;
QTextStream& writeScreensSection(QTextStream& outStream) const; QTextStream &writeScreensSection(QTextStream &outStream) const;
QTextStream& writeAliasesSection(QTextStream& outStream) const; QTextStream &writeAliasesSection(QTextStream &outStream) const;
bool swapped() const { return m_Swapped; } bool swapped() const { return m_Swapped; }
QString& name() { return m_Name; } QString &name() { return m_Name; }
void setName(const QString& name) { m_Name = name; } void setName(const QString &name) { m_Name = name; }
bool isServer() const { return m_isServer;} bool isServer() const { return m_isServer; }
void markAsServer() { m_isServer = true; } void markAsServer() { m_isServer = true; }
bool operator==(const Screen& screen) const; bool operator==(const Screen &screen) const;
protected: protected:
void init(); void init();
QStringList& aliases() { return m_Aliases; } QStringList &aliases() { return m_Aliases; }
void setModifier(int m, int n) { m_Modifiers[m] = n; } void setModifier(int m, int n) { m_Modifiers[m] = n; }
QList<int>& modifiers() { return m_Modifiers; } QList<int> &modifiers() { return m_Modifiers; }
void addAlias(const QString& alias) { m_Aliases.append(alias); } void addAlias(const QString &alias) { m_Aliases.append(alias); }
void setSwitchCorner(int c, bool on) { m_SwitchCorners[c] = on; } void setSwitchCorner(int c, bool on) { m_SwitchCorners[c] = on; }
QList<bool>& switchCorners() { return m_SwitchCorners; } QList<bool> &switchCorners() { return m_SwitchCorners; }
void setSwitchCornerSize(int val) { m_SwitchCornerSize = val; } void setSwitchCornerSize(int val) { m_SwitchCornerSize = val; }
void setFix(int f, bool on) { m_Fixes[f] = on; } void setFix(int f, bool on) { m_Fixes[f] = on; }
QList<bool>& fixes() { return m_Fixes; } QList<bool> &fixes() { return m_Fixes; }
void setSwapped(bool on) { m_Swapped = on; } void setSwapped(bool on) { m_Swapped = on; }
private: private:
QPixmap m_Pixmap; QPixmap m_Pixmap;
QString m_Name; QString m_Name;
@ -99,8 +100,7 @@ class Screen : public BaseConfig
bool m_isServer = false; bool m_isServer = false;
}; };
QDataStream& operator<<(QDataStream& outStream, const Screen& screen); QDataStream &operator<<(QDataStream &outStream, const Screen &screen);
QDataStream& operator>>(QDataStream& inStream, Screen& screen); QDataStream &operator>>(QDataStream &inStream, Screen &screen);
#endif #endif

View file

@ -28,8 +28,7 @@ namespace {
* @param size of the grid * @param size of the grid
* @return indexes for server neighbors * @return indexes for server neighbors
*/ */
std::array<int, 8> getNeighborsIndexes(int serverIndex, int width, int size) std::array<int, 8> getNeighborsIndexes(int serverIndex, int width, int size) {
{
const int UNSET = -1; const int UNSET = -1;
const int LEFT = 0; const int LEFT = 0;
const int RIGHT = 1; const int RIGHT = 1;
@ -40,18 +39,28 @@ std::array<int, 8> getNeighborsIndexes(int serverIndex, int width, int size)
const int BOTTOM_RIGHT = 6; const int BOTTOM_RIGHT = 6;
const int BOTTOM_LEFT = 7; const int BOTTOM_LEFT = 7;
std::array<int, 8> indexes = { UNSET }; std::array<int, 8> indexes = {UNSET};
if (serverIndex >= 0 && serverIndex < size) if (serverIndex >= 0 && serverIndex < size) {
{ indexes[LEFT] =
indexes[LEFT] = (serverIndex - 1) % width != width - 1 ? (serverIndex - 1) : UNSET; (serverIndex - 1) % width != width - 1 ? (serverIndex - 1) : UNSET;
indexes[RIGHT] = (serverIndex + 1) % width != 0 ? (serverIndex + 1) : UNSET; indexes[RIGHT] = (serverIndex + 1) % width != 0 ? (serverIndex + 1) : UNSET;
indexes[TOP] = (serverIndex - width) >= 0 ? (serverIndex - width) : UNSET; indexes[TOP] = (serverIndex - width) >= 0 ? (serverIndex - width) : UNSET;
indexes[BOTTOM] = (serverIndex + width) < size ? (serverIndex + width) : UNSET; indexes[BOTTOM] =
indexes[TOP_LEFT] = (indexes[TOP] != UNSET && indexes[LEFT] != UNSET) ? indexes[TOP] - 1 : UNSET; (serverIndex + width) < size ? (serverIndex + width) : UNSET;
indexes[TOP_RIGHT] = (indexes[TOP] != UNSET && indexes[RIGHT] != UNSET) ? indexes[TOP] + 1 : UNSET; indexes[TOP_LEFT] = (indexes[TOP] != UNSET && indexes[LEFT] != UNSET)
indexes[BOTTOM_RIGHT] = (indexes[BOTTOM] != UNSET && indexes[RIGHT] != UNSET) ? indexes[BOTTOM] + 1 : UNSET; ? indexes[TOP] - 1
indexes[BOTTOM_LEFT] = (indexes[BOTTOM] != UNSET && indexes[LEFT] != UNSET) ? indexes[BOTTOM] - 1 : UNSET; : UNSET;
indexes[TOP_RIGHT] = (indexes[TOP] != UNSET && indexes[RIGHT] != UNSET)
? indexes[TOP] + 1
: UNSET;
indexes[BOTTOM_RIGHT] =
(indexes[BOTTOM] != UNSET && indexes[RIGHT] != UNSET)
? indexes[BOTTOM] + 1
: UNSET;
indexes[BOTTOM_LEFT] = (indexes[BOTTOM] != UNSET && indexes[LEFT] != UNSET)
? indexes[BOTTOM] - 1
: UNSET;
} }
return indexes; return indexes;
@ -62,13 +71,11 @@ std::array<int, 8> getNeighborsIndexes(int serverIndex, int width, int size)
* @param screens list to find server * @param screens list to find server
* @return server index * @return server index
*/ */
int getServerIndex(const ScreenList& screens) int getServerIndex(const ScreenList &screens) {
{
int serverIndex = -1; int serverIndex = -1;
for (int i = 0; i < screens.size(); ++i) for (int i = 0; i < screens.size(); ++i) {
{ if (screens[i].isServer()) {
if (screens[i].isServer()){
serverIndex = i; serverIndex = i;
break; break;
} }
@ -77,28 +84,19 @@ int getServerIndex(const ScreenList& screens)
return serverIndex; return serverIndex;
} }
} //namespace } // namespace
ScreenList::ScreenList(int width) : ScreenList::ScreenList(int width) : QList<Screen>(), m_width(width) {}
QList<Screen>(),
m_width(width)
{
} void ScreenList::addScreenByPriority(const Screen &newScreen) {
void ScreenList::addScreenByPriority(const Screen& newScreen)
{
int serverIndex = getServerIndex(*this); int serverIndex = getServerIndex(*this);
auto indexes = getNeighborsIndexes(serverIndex, m_width, size()); auto indexes = getNeighborsIndexes(serverIndex, m_width, size());
bool isAdded = false; bool isAdded = false;
for (const auto& index : indexes) for (const auto &index : indexes) {
{ if (index >= 0 && index < size()) {
if (index >= 0 && index < size()) auto &screen = operator[](index);
{ if (screen.isNull()) {
auto& screen = operator[](index);
if (screen.isNull())
{
screen = newScreen; screen = newScreen;
isAdded = true; isAdded = true;
break; break;
@ -106,27 +104,21 @@ void ScreenList::addScreenByPriority(const Screen& newScreen)
} }
} }
if (!isAdded) if (!isAdded) {
{
addScreenToFirstEmpty(newScreen); addScreenToFirstEmpty(newScreen);
} }
} }
void ScreenList::addScreenToFirstEmpty(const Screen& newScreen) void ScreenList::addScreenToFirstEmpty(const Screen &newScreen) {
{ for (int i = 0; i < size(); ++i) {
for (int i = 0; i < size(); ++i) auto &screen = operator[](i);
{ if (screen.isNull()) {
auto& screen = operator[](i);
if (screen.isNull())
{
screen = newScreen; screen = newScreen;
break; break;
} }
} }
} }
bool ScreenList::operator==(const ScreenList& sc) const bool ScreenList::operator==(const ScreenList &sc) const {
{
return m_width == sc.m_width && QList::operator==(sc); return m_width == sc.m_width && QList::operator==(sc);
} }

View file

@ -20,39 +20,36 @@
#include "Screen.h" #include "Screen.h"
class ScreenList : public QList<Screen> class ScreenList : public QList<Screen> {
{
int m_width = 5; int m_width = 5;
public: public:
explicit ScreenList(int width = 5); explicit ScreenList(int width = 5);
/** /**
* @brief addScreenByPriority adds a new screen according to the following priority: * @brief addScreenByPriority adds a new screen according to the following
* 1.left side of the server * priority: 1.left side of the server 2.right side of the server 3.top 4.down
* 2.right side of the server
* 3.top
* 4.down
* 5.top left-hand diagonally * 5.top left-hand diagonally
* 6.top right-hand diagonally * 6.top right-hand diagonally
* 7.bottom right-hand diagonally * 7.bottom right-hand diagonally
* 8.bottom left-hand diagonally * 8.bottom left-hand diagonally
* 9.In case all places from the list have already booked, place in any spare place * 9.In case all places from the list have already booked, place in any spare
* place
* @param newScreen * @param newScreen
*/ */
void addScreenByPriority(const Screen& newScreen); void addScreenByPriority(const Screen &newScreen);
/** /**
* @brief addScreenToFirstEmpty adds screen into the first empty place * @brief addScreenToFirstEmpty adds screen into the first empty place
* @param newScreen * @param newScreen
*/ */
void addScreenToFirstEmpty(const Screen& newScreen); void addScreenToFirstEmpty(const Screen &newScreen);
/** /**
* @brief Returns true if screens are equal * @brief Returns true if screens are equal
* @param sc * @param sc
*/ */
bool operator==(const ScreenList& sc) const; bool operator==(const ScreenList &sc) const;
}; };
#endif // SCREENLIST_H #endif // SCREENLIST_H

View file

@ -16,27 +16,28 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "validators/ScreenNameValidator.h"
#include "validators/AliasValidator.h"
#include "ScreenSettingsDialog.h" #include "ScreenSettingsDialog.h"
#include "Screen.h" #include "Screen.h"
#include "validators/AliasValidator.h"
#include "validators/ScreenNameValidator.h"
#include <QMessageBox>
#include <QtCore> #include <QtCore>
#include <QtGui> #include <QtGui>
#include <QMessageBox>
ScreenSettingsDialog::ScreenSettingsDialog(QWidget* parent, Screen* pScreen,const ScreenList* pScreens) : ScreenSettingsDialog::ScreenSettingsDialog(QWidget *parent, Screen *pScreen,
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), const ScreenList *pScreens)
Ui::ScreenSettingsDialogBase(), : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
m_pScreen(pScreen) Ui::ScreenSettingsDialogBase(), m_pScreen(pScreen) {
{
setupUi(this); setupUi(this);
m_pLineEditName->setText(m_pScreen->name()); m_pLineEditName->setText(m_pScreen->name());
m_pLineEditName->setValidator(new validators::ScreenNameValidator(m_pLineEditName, m_pLabelNameError, pScreens)); m_pLineEditName->setValidator(new validators::ScreenNameValidator(
m_pLineEditName, m_pLabelNameError, pScreens));
m_pLineEditName->selectAll(); m_pLineEditName->selectAll();
m_pLineEditAlias->setValidator(new validators::AliasValidator(m_pLineEditAlias, m_pLabelAliasError)); m_pLineEditAlias->setValidator(
new validators::AliasValidator(m_pLineEditAlias, m_pLabelAliasError));
for (int i = 0; i < m_pScreen->aliases().count(); i++) for (int i = 0; i < m_pScreen->aliases().count(); i++)
new QListWidgetItem(m_pScreen->aliases()[i], m_pListAliases); new QListWidgetItem(m_pScreen->aliases()[i], m_pListAliases);
@ -47,10 +48,14 @@ ScreenSettingsDialog::ScreenSettingsDialog(QWidget* parent, Screen* pScreen,cons
m_pComboBoxMeta->setCurrentIndex(m_pScreen->modifier(Screen::Meta)); m_pComboBoxMeta->setCurrentIndex(m_pScreen->modifier(Screen::Meta));
m_pComboBoxSuper->setCurrentIndex(m_pScreen->modifier(Screen::Super)); m_pComboBoxSuper->setCurrentIndex(m_pScreen->modifier(Screen::Super));
m_pCheckBoxCornerTopLeft->setChecked(m_pScreen->switchCorner(Screen::TopLeft)); m_pCheckBoxCornerTopLeft->setChecked(
m_pCheckBoxCornerTopRight->setChecked(m_pScreen->switchCorner(Screen::TopRight)); m_pScreen->switchCorner(Screen::TopLeft));
m_pCheckBoxCornerBottomLeft->setChecked(m_pScreen->switchCorner(Screen::BottomLeft)); m_pCheckBoxCornerTopRight->setChecked(
m_pCheckBoxCornerBottomRight->setChecked(m_pScreen->switchCorner(Screen::BottomRight)); m_pScreen->switchCorner(Screen::TopRight));
m_pCheckBoxCornerBottomLeft->setChecked(
m_pScreen->switchCorner(Screen::BottomLeft));
m_pCheckBoxCornerBottomRight->setChecked(
m_pScreen->switchCorner(Screen::BottomRight));
m_pSpinBoxSwitchCornerSize->setValue(m_pScreen->switchCornerSize()); m_pSpinBoxSwitchCornerSize->setValue(m_pScreen->switchCornerSize());
m_pCheckBoxCapsLock->setChecked(m_pScreen->fix(Screen::CapsLock)); m_pCheckBoxCapsLock->setChecked(m_pScreen->fix(Screen::CapsLock));
@ -59,17 +64,14 @@ ScreenSettingsDialog::ScreenSettingsDialog(QWidget* parent, Screen* pScreen,cons
m_pCheckBoxXTest->setChecked(m_pScreen->fix(Screen::XTest)); m_pCheckBoxXTest->setChecked(m_pScreen->fix(Screen::XTest));
} }
void ScreenSettingsDialog::accept() void ScreenSettingsDialog::accept() {
{ if (m_pLineEditName->text().isEmpty()) {
if (m_pLineEditName->text().isEmpty())
{
QMessageBox::warning( QMessageBox::warning(
this, tr("Screen name is empty"), this, tr("Screen name is empty"),
tr("The screen name cannot be empty. " tr("The screen name cannot be empty. "
"Please either fill in a name or cancel the dialog.")); "Please either fill in a name or cancel the dialog."));
return; return;
} } else if (!m_pLabelNameError->text().isEmpty()) {
else if (!m_pLabelNameError->text().isEmpty()) {
return; return;
} }
@ -77,11 +79,9 @@ void ScreenSettingsDialog::accept()
m_pScreen->setName(m_pLineEditName->text()); m_pScreen->setName(m_pLineEditName->text());
for (int i = 0; i < m_pListAliases->count(); i++) for (int i = 0; i < m_pListAliases->count(); i++) {
{
QString alias(m_pListAliases->item(i)->text()); QString alias(m_pListAliases->item(i)->text());
if (alias == m_pLineEditName->text()) if (alias == m_pLineEditName->text()) {
{
QMessageBox::warning( QMessageBox::warning(
this, tr("Screen name matches alias"), this, tr("Screen name matches alias"),
tr("The screen name cannot be the same as an alias. " tr("The screen name cannot be the same as an alias. "
@ -97,10 +97,14 @@ void ScreenSettingsDialog::accept()
m_pScreen->setModifier(Screen::Meta, m_pComboBoxMeta->currentIndex()); m_pScreen->setModifier(Screen::Meta, m_pComboBoxMeta->currentIndex());
m_pScreen->setModifier(Screen::Super, m_pComboBoxSuper->currentIndex()); m_pScreen->setModifier(Screen::Super, m_pComboBoxSuper->currentIndex());
m_pScreen->setSwitchCorner(Screen::TopLeft, m_pCheckBoxCornerTopLeft->isChecked()); m_pScreen->setSwitchCorner(Screen::TopLeft,
m_pScreen->setSwitchCorner(Screen::TopRight, m_pCheckBoxCornerTopRight->isChecked()); m_pCheckBoxCornerTopLeft->isChecked());
m_pScreen->setSwitchCorner(Screen::BottomLeft, m_pCheckBoxCornerBottomLeft->isChecked()); m_pScreen->setSwitchCorner(Screen::TopRight,
m_pScreen->setSwitchCorner(Screen::BottomRight, m_pCheckBoxCornerBottomRight->isChecked()); m_pCheckBoxCornerTopRight->isChecked());
m_pScreen->setSwitchCorner(Screen::BottomLeft,
m_pCheckBoxCornerBottomLeft->isChecked());
m_pScreen->setSwitchCorner(Screen::BottomRight,
m_pCheckBoxCornerBottomRight->isChecked());
m_pScreen->setSwitchCornerSize(m_pSpinBoxSwitchCornerSize->value()); m_pScreen->setSwitchCornerSize(m_pSpinBoxSwitchCornerSize->value());
m_pScreen->setFix(Screen::CapsLock, m_pCheckBoxCapsLock->isChecked()); m_pScreen->setFix(Screen::CapsLock, m_pCheckBoxCapsLock->isChecked());
@ -111,30 +115,28 @@ void ScreenSettingsDialog::accept()
QDialog::accept(); QDialog::accept();
} }
void ScreenSettingsDialog::on_m_pButtonAddAlias_clicked() void ScreenSettingsDialog::on_m_pButtonAddAlias_clicked() {
{ if (!m_pLineEditAlias->text().isEmpty() &&
if (!m_pLineEditAlias->text().isEmpty() && m_pListAliases->findItems(m_pLineEditAlias->text(), Qt::MatchFixedString).isEmpty()) m_pListAliases->findItems(m_pLineEditAlias->text(), Qt::MatchFixedString)
{ .isEmpty()) {
new QListWidgetItem(m_pLineEditAlias->text(), m_pListAliases); new QListWidgetItem(m_pLineEditAlias->text(), m_pListAliases);
m_pLineEditAlias->clear(); m_pLineEditAlias->clear();
} }
} }
void ScreenSettingsDialog::on_m_pLineEditAlias_textChanged(const QString& text) void ScreenSettingsDialog::on_m_pLineEditAlias_textChanged(
{ const QString &text) {
m_pButtonAddAlias->setEnabled(!text.isEmpty() && m_pLabelAliasError->text().isEmpty()); m_pButtonAddAlias->setEnabled(!text.isEmpty() &&
m_pLabelAliasError->text().isEmpty());
} }
void ScreenSettingsDialog::on_m_pButtonRemoveAlias_clicked() void ScreenSettingsDialog::on_m_pButtonRemoveAlias_clicked() {
{ QList<QListWidgetItem *> items = m_pListAliases->selectedItems();
QList<QListWidgetItem*> items = m_pListAliases->selectedItems();
for (int i = 0; i < items.count(); i++) for (int i = 0; i < items.count(); i++)
delete items[i]; delete items[i];
} }
void ScreenSettingsDialog::on_m_pListAliases_itemSelectionChanged() void ScreenSettingsDialog::on_m_pListAliases_itemSelectionChanged() {
{
m_pButtonRemoveAlias->setEnabled(!m_pListAliases->selectedItems().isEmpty()); m_pButtonRemoveAlias->setEnabled(!m_pListAliases->selectedItems().isEmpty());
} }

View file

@ -31,26 +31,25 @@ class QString;
class Screen; class Screen;
class ScreenList; class ScreenList;
class ScreenSettingsDialog : public QDialog, public Ui::ScreenSettingsDialogBase class ScreenSettingsDialog : public QDialog,
{ public Ui::ScreenSettingsDialogBase {
Q_OBJECT Q_OBJECT
public: public:
ScreenSettingsDialog(QWidget* parent, Screen* pScreen = nullptr, const ScreenList* pScreens = nullptr); ScreenSettingsDialog(QWidget *parent, Screen *pScreen = nullptr,
const ScreenList *pScreens = nullptr);
public slots: public slots:
void accept(); void accept();
private slots: private slots:
void on_m_pButtonAddAlias_clicked(); void on_m_pButtonAddAlias_clicked();
void on_m_pButtonRemoveAlias_clicked(); void on_m_pButtonRemoveAlias_clicked();
void on_m_pLineEditAlias_textChanged(const QString& text); void on_m_pLineEditAlias_textChanged(const QString &text);
void on_m_pListAliases_itemSelectionChanged(); void on_m_pListAliases_itemSelectionChanged();
private: private:
Screen* m_pScreen; Screen *m_pScreen;
}; };
#endif #endif

View file

@ -24,22 +24,20 @@
const QString ScreenSetupModel::m_MimeType = "application/x-qsynergy-screen"; const QString ScreenSetupModel::m_MimeType = "application/x-qsynergy-screen";
ScreenSetupModel::ScreenSetupModel(ScreenList& screens, int numColumns, int numRows) : ScreenSetupModel::ScreenSetupModel(ScreenList &screens, int numColumns,
QAbstractTableModel(NULL), int numRows)
m_Screens(screens), : QAbstractTableModel(NULL), m_Screens(screens), m_NumColumns(numColumns),
m_NumColumns(numColumns), m_NumRows(numRows) {
m_NumRows(numRows)
{
if (m_NumColumns * m_NumRows > screens.size()) if (m_NumColumns * m_NumRows > screens.size())
qFatal("Not enough elements (%u) in screens QList for %d columns and %d rows", screens.size(), m_NumColumns, m_NumRows); qFatal(
"Not enough elements (%u) in screens QList for %d columns and %d rows",
screens.size(), m_NumColumns, m_NumRows);
} }
QVariant ScreenSetupModel::data(const QModelIndex& index, int role) const QVariant ScreenSetupModel::data(const QModelIndex &index, int role) const {
{ if (index.isValid() && index.row() < m_NumRows &&
if (index.isValid() && index.row() < m_NumRows && index.column() < m_NumColumns) index.column() < m_NumColumns) {
{ switch (role) {
switch(role)
{
case Qt::DecorationRole: case Qt::DecorationRole:
if (screen(index).isNull()) if (screen(index).isNull())
break; break;
@ -48,10 +46,10 @@ QVariant ScreenSetupModel::data(const QModelIndex& index, int role) const
case Qt::ToolTipRole: case Qt::ToolTipRole:
if (screen(index).isNull()) if (screen(index).isNull())
break; break;
return QString(tr( return QString(tr("<center>Screen: <b>%1</b></center>"
"<center>Screen: <b>%1</b></center>"
"<br>Double click to edit settings" "<br>Double click to edit settings"
"<br>Drag screen to the trashcan to remove it")).arg(screen(index).name()); "<br>Drag screen to the trashcan to remove it"))
.arg(screen(index).name());
case Qt::DisplayRole: case Qt::DisplayRole:
if (screen(index).isNull()) if (screen(index).isNull())
@ -63,35 +61,33 @@ QVariant ScreenSetupModel::data(const QModelIndex& index, int role) const
return QVariant(); return QVariant();
} }
Qt::ItemFlags ScreenSetupModel::flags(const QModelIndex& index) const Qt::ItemFlags ScreenSetupModel::flags(const QModelIndex &index) const {
{ if (!index.isValid() || index.row() >= m_NumRows ||
if (!index.isValid() || index.row() >= m_NumRows || index.column() >= m_NumColumns) index.column() >= m_NumColumns)
return 0; return 0;
if (!screen(index).isNull()) if (!screen(index).isNull())
return Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled; return Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable |
Qt::ItemIsDropEnabled;
return Qt::ItemIsDropEnabled; return Qt::ItemIsDropEnabled;
} }
Qt::DropActions ScreenSetupModel::supportedDropActions() const Qt::DropActions ScreenSetupModel::supportedDropActions() const {
{
return Qt::MoveAction | Qt::CopyAction; return Qt::MoveAction | Qt::CopyAction;
} }
QStringList ScreenSetupModel::mimeTypes() const QStringList ScreenSetupModel::mimeTypes() const {
{
return QStringList() << m_MimeType; return QStringList() << m_MimeType;
} }
QMimeData* ScreenSetupModel::mimeData(const QModelIndexList& indexes) const QMimeData *ScreenSetupModel::mimeData(const QModelIndexList &indexes) const {
{ QMimeData *pMimeData = new QMimeData();
QMimeData* pMimeData = new QMimeData();
QByteArray encodedData; QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly); QDataStream stream(&encodedData, QIODevice::WriteOnly);
foreach (const QModelIndex& index, indexes) foreach (const QModelIndex &index, indexes)
if (index.isValid()) if (index.isValid())
stream << index.column() << index.row() << screen(index); stream << index.column() << index.row() << screen(index);
@ -100,8 +96,9 @@ QMimeData* ScreenSetupModel::mimeData(const QModelIndexList& indexes) const
return pMimeData; return pMimeData;
} }
bool ScreenSetupModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) bool ScreenSetupModel::dropMimeData(const QMimeData *data,
{ Qt::DropAction action, int row, int column,
const QModelIndex &parent) {
if (action == Qt::IgnoreAction) if (action == Qt::IgnoreAction)
return true; return true;
@ -128,8 +125,7 @@ bool ScreenSetupModel::dropMimeData(const QMimeData* data, Qt::DropAction action
stream >> droppedScreen; stream >> droppedScreen;
Screen oldScreen = screen(parent.column(), parent.row()); Screen oldScreen = screen(parent.column(), parent.row());
if (!oldScreen.isNull() && sourceColumn != -1 && sourceRow != -1) if (!oldScreen.isNull() && sourceColumn != -1 && sourceRow != -1) {
{
// mark the screen so it isn't deleted after the dragndrop succeeded // mark the screen so it isn't deleted after the dragndrop succeeded
// see ScreenSetupView::startDrag() // see ScreenSetupView::startDrag()
oldScreen.setSwapped(true); oldScreen.setSwapped(true);
@ -143,17 +139,15 @@ bool ScreenSetupModel::dropMimeData(const QMimeData* data, Qt::DropAction action
return true; return true;
} }
void ScreenSetupModel::addScreen(const Screen& newScreen) void ScreenSetupModel::addScreen(const Screen &newScreen) {
{
m_Screens.addScreenByPriority(newScreen); m_Screens.addScreenByPriority(newScreen);
emit screensChanged(); emit screensChanged();
} }
bool ScreenSetupModel::isFull() const bool ScreenSetupModel::isFull() const {
{ auto emptyScreen =
auto emptyScreen = std::find_if(m_Screens.cbegin(), m_Screens.cend(), std::find_if(m_Screens.cbegin(), m_Screens.cend(),
[](const Screen& item) { return item.isNull(); }); [](const Screen &item) { return item.isNull(); });
return (emptyScreen == m_Screens.cend()); return (emptyScreen == m_Screens.cend());
} }

Some files were not shown because too many files have changed in this diff Show more