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)
- #7361 Re-implement packaging for GitHub workflows (Linux)
- #7363 Schedule CI daily at 5am to detect code rot early
- #7364 Format all source with Clang and introduce lint workflow
# 1.14.6

View file

@ -13,6 +13,11 @@ def main():
parser.add_argument(
"--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()
env.ensure_dependencies()
@ -20,6 +25,7 @@ def main():
env.install_requirements()
error = False
if not args.only_python:
try:
deps = Dependencies(args.only)
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
clang-format
python-dotenv
pyyaml
dmgbuild; sys_platform == 'darwin'

View file

@ -15,33 +15,35 @@
* You should have received a copy of the GNU General Public License
* 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/ServerApp.h"
#include "arch/Arch.h"
#include "base/Log.h"
#include "base/EventQueue.h"
#include <iostream>
void showHelp()
{
std::cout<<"Usage: synergy-core <server | client> [...options]"<<std::endl;
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
void showHelp() {
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;
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"));
}
bool isClient(int argc, char** argv)
{
bool isClient(int argc, char **argv) {
return (argc > 1 && argv[1] == std::string("client"));
}
int main(int argc, char** argv)
{
int main(int argc, char **argv) {
#if SYSAPI_WIN32
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif
@ -55,12 +57,10 @@ int main(int argc, char** argv)
if (isServer(argc, argv)) {
ServerApp app(&events, nullptr);
return app.run(argc, argv);
}
else if (isClient(argc, argv)) {
} else if (isClient(argc, argv)) {
ClientApp app(&events, nullptr);
return app.run(argc, argv);
}
else {
} else {
showHelp();
}

View file

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

View file

@ -29,7 +29,8 @@ class IEventQueue;
//! Implementation of ClientTaskBarReceiver for Microsoft Windows
class MSWindowsClientTaskBarReceiver : public ClientTaskBarReceiver {
public:
MSWindowsClientTaskBarReceiver(HINSTANCE, const BufferedLogOutputter*, IEventQueue* events);
MSWindowsClientTaskBarReceiver(HINSTANCE, const BufferedLogOutputter *,
IEventQueue *events);
virtual ~MSWindowsClientTaskBarReceiver();
// IArchTaskBarReceiver overrides
@ -51,11 +52,9 @@ private:
void createWindow();
void destroyWindow();
BOOL dlgProc(HWND hwnd,
UINT msg, WPARAM wParam, LPARAM lParam);
static BOOL CALLBACK
staticDlgProc(HWND hwnd,
UINT msg, WPARAM wParam, LPARAM lParam);
BOOL dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
static BOOL CALLBACK staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam,
LPARAM lParam);
private:
HINSTANCE m_appInstance;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -29,7 +29,8 @@ class IEventQueue;
//! Implementation of ServerTaskBarReceiver for Microsoft Windows
class MSWindowsServerTaskBarReceiver : public ServerTaskBarReceiver {
public:
MSWindowsServerTaskBarReceiver(HINSTANCE, const BufferedLogOutputter*, IEventQueue* events);
MSWindowsServerTaskBarReceiver(HINSTANCE, const BufferedLogOutputter *,
IEventQueue *events);
virtual ~MSWindowsServerTaskBarReceiver();
// IArchTaskBarReceiver overrides
@ -51,11 +52,9 @@ private:
void createWindow();
void destroyWindow();
BOOL dlgProc(HWND hwnd,
UINT msg, WPARAM wParam, LPARAM lParam);
static BOOL CALLBACK
staticDlgProc(HWND hwnd,
UINT msg, WPARAM wParam, LPARAM lParam);
BOOL dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
static BOOL CALLBACK staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam,
LPARAM lParam);
private:
HINSTANCE m_appInstance;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -16,13 +16,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "OSXHelpers.h"
#include "AboutDialog.h"
#include "OSXHelpers.h"
AboutDialog::AboutDialog(MainWindow* parent, const AppConfig& config) :
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::AboutDialogBase()
{
AboutDialog::AboutDialog(MainWindow *parent, const AppConfig &config)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::AboutDialogBase() {
setupUi(this);
m_versionChecker.setApp(parent->appPath(config.synergycName()));
@ -38,8 +37,7 @@ AboutDialog::AboutDialog(MainWindow* parent, const AppConfig& config) :
labelCreditsLink->hide();
}
int AboutDialog::exec()
{
int AboutDialog::exec() {
// Sets the current build year into the copyright text
label_3->setText(getCopyrights() + getKeyContributors());
resizeWindow();
@ -48,16 +46,14 @@ int AboutDialog::exec()
return QDialog::exec();
}
void AboutDialog::resizeWindow()
{
void AboutDialog::resizeWindow() {
QSize size(600, 310);
setMaximumSize(size);
setMinimumSize(size);
resize(size);
}
void AboutDialog::updateLogo() const
{
void AboutDialog::updateLogo() const {
#if defined(Q_OS_MAC)
if (isOSXInterfaceStyleDark()) {
QPixmap logo(":/res/image/about-dark.png");
@ -68,8 +64,7 @@ void AboutDialog::updateLogo() const
#endif
}
QString AboutDialog::getKeyContributors() const
{
QString AboutDialog::getKeyContributors() const {
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,
Ryan Breen, Guido Poschta, Bertrand Landry Hetu, Tom Chadwick, Brent Priddy, Kyle Bloom,
@ -77,11 +72,12 @@ QString AboutDialog::getKeyContributors() const
</p>)");
}
QString AboutDialog::getCopyrights() const
{
QString AboutDialog::getCopyrights() const {
QString buildDateString = QString::fromLocal8Bit(__DATE__).simplified();
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>)");
return copyrights.replace(QString("%%YEAR%%"), QString::number(buildDate.year()));
QString copyrights(
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
#include <QDialog>
#include "VersionChecker.h"
#include "MainWindow.h"
#include "VersionChecker.h"
#include <QDialog>
#include "ui_AboutDialogBase.h"
@ -34,6 +34,7 @@ class AboutDialog : public QDialog, public Ui::AboutDialogBase {
public:
AboutDialog(MainWindow *parent, const AppConfig &config);
int exec() override;
private:
VersionChecker m_versionChecker;
void updateLogo() const;
@ -44,4 +45,3 @@ private:
};
#endif

View file

@ -14,13 +14,12 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CreditsLoader.h"
#include "AboutDialogEliteBackers.h"
#include "CreditsLoader.h"
AboutDialogEliteBackers::AboutDialogEliteBackers(MainWindow* parent, const AppConfig& config) :
AboutDialog(parent, config),
credits(*parent, config)
{
AboutDialogEliteBackers::AboutDialogEliteBackers(MainWindow *parent,
const AppConfig &config)
: AboutDialog(parent, config), credits(*parent, config) {
setupCreditsLoader();
textEliteBackers->show();
@ -29,35 +28,35 @@ AboutDialogEliteBackers::AboutDialogEliteBackers(MainWindow* parent, const AppCo
labelCreditsLink->show();
}
void AboutDialogEliteBackers::setupCreditsLoader()
{
void AboutDialogEliteBackers::setupCreditsLoader() {
this->textEliteBackers->setText("Loading...");
this->textEliteBackers->viewport()->setAutoFillBackground(false);
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();
}
void AboutDialogEliteBackers::updateEliteBackers(const QString& eliteBackers) const
{
void AboutDialogEliteBackers::updateEliteBackers(
const QString &eliteBackers) const {
this->textEliteBackers->setText(eliteBackers);
}
QString AboutDialogEliteBackers::getCopyrights() const
{
QString AboutDialogEliteBackers::getCopyrights() const {
QString buildDateString = QString::fromLocal8Bit(__DATE__).simplified();
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 />
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
#if defined(Q_OS_MAC)
QSize size(600, 490);

View file

@ -16,8 +16,8 @@
*/
#pragma once
#include "CreditsLoader.h"
#include "AboutDialog.h"
#include "CreditsLoader.h"
class AboutDialogEliteBackers : public AboutDialog {
Q_OBJECT

View file

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

View file

@ -22,16 +22,15 @@
#include "KeySequence.h"
#include <QList>
#include <QString>
#include <QStringList>
#include <QList>
class ActionDialog;
class QSettings;
class QTextStream;
class Action
{
class Action {
friend class ActionDialog;
friend QTextStream &operator<<(QTextStream &outStream, const Action &action);
@ -48,17 +47,8 @@ class Action
mouseUp,
mousebutton,
};
enum SwitchDirection {
switchLeft,
switchRight,
switchUp,
switchDown
};
enum LockCursorMode {
lockCursorToggle,
lockCursonOn,
lockCursorOff
};
enum SwitchDirection { switchLeft, switchRight, switchUp, switchDown };
enum LockCursorMode { lockCursorToggle, lockCursonOn, lockCursorOff };
public:
Action();

View file

@ -18,30 +18,34 @@
#include "ActionDialog.h"
#include "Hotkey.h"
#include "Action.h"
#include "ServerConfig.h"
#include "Hotkey.h"
#include "KeySequence.h"
#include "ServerConfig.h"
#include <QButtonGroup>
#include <QtCore>
#include <QtGui>
#include <QButtonGroup>
ActionDialog::ActionDialog(QWidget* parent, ServerConfig& config, Hotkey& hotkey, Action& action) :
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::ActionDialogBase(),
m_ServerConfig(config),
m_Hotkey(hotkey),
m_Action(action),
m_pButtonGroupType(new QButtonGroup(this))
{
ActionDialog::ActionDialog(QWidget *parent, ServerConfig &config,
Hotkey &hotkey, Action &action)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::ActionDialogBase(), m_ServerConfig(config), m_Hotkey(hotkey),
m_Action(action), m_pButtonGroupType(new QButtonGroup(this)) {
setupUi(this);
// work around Qt Designer's lack of a QButtonGroup; we need it to get
// 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_pKeySequenceWidgetHotkey->setText(m_Action.keySequence().toString());
@ -59,8 +63,7 @@ ActionDialog::ActionDialog(QWidget* parent, ServerConfig& config, Hotkey& hotkey
int idx = 0;
foreach (const Screen &screen, serverConfig().screens())
if (!screen.isNull())
{
if (!screen.isNull()) {
QListWidgetItem *pListItem = new QListWidgetItem(screen.name());
m_pListScreens->addItem(pListItem);
if (m_Action.typeScreenNames().indexOf(screen.name()) != -1)
@ -74,9 +77,9 @@ ActionDialog::ActionDialog(QWidget* parent, ServerConfig& config, Hotkey& hotkey
}
}
void ActionDialog::accept()
{
if (!sequenceWidget()->valid() && m_pButtonGroupType->checkedId() >= 0 && m_pButtonGroupType->checkedId() < 3)
void ActionDialog::accept() {
if (!sequenceWidget()->valid() && m_pButtonGroupType->checkedId() >= 0 &&
m_pButtonGroupType->checkedId() < 3)
return;
m_Action.setKeySequence(sequenceWidget()->keySequence());
@ -96,15 +99,11 @@ void ActionDialog::accept()
QDialog::accept();
}
void ActionDialog::on_m_pKeySequenceWidgetHotkey_keySequenceChanged()
{
if (sequenceWidget()->keySequence().isMouseButton())
{
void ActionDialog::on_m_pKeySequenceWidgetHotkey_keySequenceChanged() {
if (sequenceWidget()->keySequence().isMouseButton()) {
m_pGroupBoxScreens->setEnabled(false);
m_pListScreens->setEnabled(false);
}
else
{
} else {
m_pGroupBoxScreens->setEnabled(true);
m_pListScreens->setEnabled(true);
}

View file

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

View file

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

View file

@ -1,8 +1,8 @@
#ifndef ACTIVATIONDIALOG_H
#define ACTIVATIONDIALOG_H
#include <QDialog>
#include <LicenseManager.h>
#include <QDialog>
namespace Ui {
class ActivationDialog;
@ -10,8 +10,7 @@ class ActivationDialog;
class AppConfig;
class ActivationDialog : public QDialog
{
class ActivationDialog : public QDialog {
Q_OBJECT
public:

View file

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

View file

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

View file

@ -18,19 +18,18 @@
#include "AddClientDialog.h"
#include "ui_AddClientDialogBase.h"
#include <QPushButton>
#include <QLabel>
#include <QPushButton>
AddClientDialog::AddClientDialog(const QString& clientName, QWidget* parent) :
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::AddClientDialog(),
m_AddResult(kAddClientIgnore),
m_IgnoreAutoConfigClient(false)
{
AddClientDialog::AddClientDialog(const QString &clientName, QWidget *parent)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::AddClientDialog(), m_AddResult(kAddClientIgnore),
m_IgnoreAutoConfigClient(false) {
setupUi(this);
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");
QSize IconSize(32, 32);
@ -67,13 +66,12 @@ AddClientDialog::AddClientDialog(const QString& clientName, QWidget* parent) :
m_pDialogButtonBox->setLayoutDirection(Qt::RightToLeft);
#endif
QPushButton* advanced = m_pDialogButtonBox->addButton("Advanced",
QDialogButtonBox::HelpRole);
QPushButton *advanced =
m_pDialogButtonBox->addButton("Advanced", QDialogButtonBox::HelpRole);
connect(advanced, SIGNAL(clicked()), this, SLOT(handleButtonAdvanced()));
}
AddClientDialog::~AddClientDialog()
{
AddClientDialog::~AddClientDialog() {
delete m_pButtonUp;
delete m_pButtonDown;
delete m_pButtonLeft;
@ -81,8 +79,7 @@ AddClientDialog::~AddClientDialog()
delete m_pLabelCenter;
}
void AddClientDialog::changeEvent(QEvent *e)
{
void AddClientDialog::changeEvent(QEvent *e) {
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
@ -93,37 +90,31 @@ void AddClientDialog::changeEvent(QEvent *e)
}
}
void AddClientDialog::handleButtonLeft()
{
void AddClientDialog::handleButtonLeft() {
m_AddResult = kAddClientLeft;
close();
}
void AddClientDialog::handleButtonUp()
{
void AddClientDialog::handleButtonUp() {
m_AddResult = kAddClientUp;
close();
}
void AddClientDialog::handleButtonRight()
{
void AddClientDialog::handleButtonRight() {
m_AddResult = kAddClientRight;
close();
}
void AddClientDialog::handleButtonDown()
{
void AddClientDialog::handleButtonDown() {
m_AddResult = kAddClientDown;
close();
}
void AddClientDialog::handleButtonAdvanced()
{
void AddClientDialog::handleButtonAdvanced() {
m_AddResult = kAddClientOther;
close();
}
void AddClientDialog::on_m_pCheckBoxIgnoreClient_toggled(bool checked)
{
void AddClientDialog::on_m_pCheckBoxIgnoreClient_toggled(bool checked) {
m_IgnoreAutoConfigClient = checked;
}

View file

@ -34,8 +34,7 @@ enum {
kAddClientIgnore
};
class AddClientDialog : public QDialog, public Ui::AddClientDialog
{
class AddClientDialog : public QDialog, public Ui::AddClientDialog {
Q_OBJECT
public:
AddClientDialog(const QString &clientName, QWidget *parent = 0);

View file

@ -16,14 +16,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "QSynergyApplication.h"
#include "AppConfig.h"
#include "QSynergyApplication.h"
#include "QUtility.h"
#include <QPushButton>
#include <QtCore>
#include <QtNetwork>
#include <QtWidgets/QMessageBox>
#include <QPushButton>
#include "ConfigWriter.h"
#include "SslCertificate.h"
@ -86,41 +86,19 @@ const char* AppConfig::m_SynergySettingsName[] = {
"licenseNextCheck",
"initiateConnectionFromServer",
"clientHostMode",
"serverClientMode"
};
"serverClientMode"};
static const char* logLevelNames[] =
{
"INFO",
"DEBUG",
"DEBUG1",
"DEBUG2"
};
static const char *logLevelNames[] = {"INFO", "DEBUG", "DEBUG1", "DEBUG2"};
AppConfig::AppConfig() :
m_ScreenName(),
m_Port(24800),
m_Interface(),
m_LogLevel(0),
m_LogToFile(),
m_WizardLastRun(0),
m_ProcessMode(DEFAULT_PROCESS_MODE),
m_StartedBefore(),
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()
{
AppConfig::AppConfig()
: m_ScreenName(), m_Port(24800), m_Interface(), m_LogLevel(0),
m_LogToFile(), m_WizardLastRun(0), m_ProcessMode(DEFAULT_PROCESS_MODE),
m_StartedBefore(), 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();
@ -129,11 +107,13 @@ AppConfig::AppConfig() :
writer->globalLoad();
// 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);
}
// 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);
}
}
@ -150,31 +130,26 @@ bool AppConfig::logToFile() const { return m_LogToFile; }
const QString &AppConfig::logFilename() const { return m_LogFilename; }
QString AppConfig::synergyLogDir() const
{
QString AppConfig::synergyLogDir() const {
// by default log to home dir
return QDir::home().absolutePath() + "/";
}
QString AppConfig::synergyProgramDir() const
{
QString AppConfig::synergyProgramDir() const {
// synergy binaries should be in the same dir.
return QCoreApplication::applicationDirPath() + "/";
}
void AppConfig::persistLogDir()
{
void AppConfig::persistLogDir() {
QDir dir = synergyLogDir();
// persist the log directory
if (!dir.exists())
{
if (!dir.exists()) {
dir.mkpath(dir.path());
}
}
const QString AppConfig::logFilenameCmd() const
{
const QString AppConfig::logFilenameCmd() const {
QString filename = m_LogFilename;
#if defined(Q_OS_WIN)
// wrap in quotes in case username contains spaces.
@ -183,14 +158,13 @@ const QString AppConfig::logFilenameCmd() const
return filename;
}
QString AppConfig::logLevelText() const
{
return logLevelNames[logLevel()];
}
QString AppConfig::logLevelText() const { return logLevelNames[logLevel()]; }
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; }
@ -207,9 +181,9 @@ bool AppConfig::autoConfig() const {
QString AppConfig::autoConfigServer() const { return m_AutoConfigServer; }
void AppConfig::loadSettings()
{
m_ScreenName = loadSetting(kScreenName, QHostInfo::localHostName()).toString();
void AppConfig::loadSettings() {
m_ScreenName =
loadSetting(kScreenName, QHostInfo::localHostName()).toString();
if (m_ScreenName.isEmpty()) {
m_ScreenName = QHostInfo::localHostName();
}
@ -218,7 +192,8 @@ void AppConfig::loadSettings()
m_Interface = loadSetting(kInterfaceSetting).toString();
m_LogLevel = loadSetting(kLogLevel, 0).toInt();
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_Language = loadSetting(kLanguage, QLocale::system().name()).toString();
m_StartedBefore = loadSetting(kStartedBefore, false).toBool();
@ -242,51 +217,62 @@ void AppConfig::loadSettings()
m_LastExpiringWarningTime = loadSetting(kLastExpireWarningTime, 0).toInt();
m_ActivationHasRun = loadSetting(kActivationHasRun, 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_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_ClientGroupChecked = loadSetting(kGroupClientCheck, false).toBool();
m_ServerHostname = loadSetting(kServerHostname).toString();
m_PreventSleep = loadSetting(kPreventSleep, false).toBool();
m_LanguageSync = loadSetting(kLanguageSync, 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_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_ClientHostMode = loadSetting(kClientHostMode, 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
bool updateSerial = ConfigWriter::make()
->hasSetting(settingName(kLoadSystemSettings),ConfigWriter::kCurrent);
bool updateSerial = ConfigWriter::make()->hasSetting(
settingName(kLoadSystemSettings), ConfigWriter::kCurrent);
// if the setting exists and is not empty
updateSerial = updateSerial && !loadSetting(kSerialKey, "").toString().trimmed().isEmpty();
updateSerial = updateSerial &&
!loadSetting(kSerialKey, "").toString().trimmed().isEmpty();
if (updateSerial) {
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
QString certificateFilename = QString("%1/%2/%3").arg(m_CoreInterface.getProfileDir(),
"SSL",
"Synergy.pem");
QString certificateFilename =
QString("%1/%2/%3")
.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();
if (getCryptoEnabled()) {
generateCertificate();
}
}
void AppConfig::saveSettings()
{
void AppConfig::saveSettings() {
setCommonSetting(kWizardLastRun, m_WizardLastRun);
setCommonSetting(kLoadSystemSettings, m_LoadFromSystemScope);
setCommonSetting(kGroupClientCheck, m_ClientGroupChecked);
@ -334,22 +320,15 @@ void AppConfig::saveSettings()
}
#ifndef SYNERGY_ENTERPRISE
bool AppConfig::activationHasRun() const
{
return m_ActivationHasRun;
}
bool AppConfig::activationHasRun() const { return m_ActivationHasRun; }
AppConfig& AppConfig::activationHasRun(bool value)
{
AppConfig &AppConfig::activationHasRun(bool value) {
m_ActivationHasRun = value;
return *this;
}
#endif
QString AppConfig::lastVersion() const
{
return m_lastVersion;
}
QString AppConfig::lastVersion() const { return m_lastVersion; }
void AppConfig::setLastVersion(const QString &version) {
setSettingModified(m_lastVersion, version);
@ -360,21 +339,15 @@ void AppConfig::setScreenName(const QString &s) {
emit screenNameChanged();
}
void AppConfig::setPort(int i) {
setSettingModified(m_Port, i);
}
void AppConfig::setPort(int i) { setSettingModified(m_Port, i); }
void AppConfig::setNetworkInterface(const QString &s) {
setSettingModified(m_Interface, s);
}
void AppConfig::setLogLevel(int i) {
setSettingModified(m_LogLevel, i);
}
void AppConfig::setLogLevel(int i) { setSettingModified(m_LogLevel, i); }
void AppConfig::setLogToFile(bool b) {
setSettingModified(m_LogToFile, b);
}
void AppConfig::setLogToFile(bool b) { setSettingModified(m_LogToFile, b); }
void AppConfig::setLogFilename(const QString &s) {
setSettingModified(m_LogFilename, s);
@ -396,14 +369,12 @@ void AppConfig::setElevateMode(ElevateMode em) {
setSettingModified(m_ElevateMode, em);
}
void AppConfig::setAutoConfig(bool autoConfig)
{
void AppConfig::setAutoConfig(bool autoConfig) {
setSettingModified(m_AutoConfig, autoConfig);
emit zeroConfToggled();
}
void AppConfig::setAutoConfigServer(const QString& autoConfigServer)
{
void AppConfig::setAutoConfigServer(const QString &autoConfigServer) {
setSettingModified(m_AutoConfigServer, autoConfigServer);
}
@ -420,14 +391,13 @@ void AppConfig::setSerialKey(const QString& serial) {
setCommonSetting(kSerialKey, m_Serialkey);
}
void AppConfig::clearSerialKey()
{
m_Serialkey.clear();
}
void AppConfig::clearSerialKey() { m_Serialkey.clear(); }
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) {
setSettingModified(m_LastExpiringWarningTime, newValue);
@ -438,16 +408,12 @@ QString AppConfig::synergysName() const { return m_SynergysName; }
QString AppConfig::synergycName() const { return m_SynergycName; }
ElevateMode AppConfig::elevateMode()
{
return m_ElevateMode;
}
ElevateMode AppConfig::elevateMode() { return m_ElevateMode; }
void AppConfig::setCryptoEnabled(bool newValue) {
if (m_CryptoEnabled != newValue && newValue) {
generateCertificate();
}
else {
} else {
emit sslToggled();
}
setSettingModified(m_CryptoEnabled, newValue);
@ -457,10 +423,8 @@ bool AppConfig::isCryptoAvailable() const {
bool result{true};
#if !defined(SYNERGY_ENTERPRISE) && !defined(SYNERGY_BUSINESS)
result = (edition() == kPro ||
edition() == kPro_China ||
edition() == kBusiness ||
edition() == kUltimate);
result = (edition() == kPro || edition() == kPro_China ||
edition() == kBusiness || edition() == kUltimate);
#endif
return result;
@ -470,9 +434,7 @@ bool AppConfig::getCryptoEnabled() const {
return isCryptoAvailable() && m_CryptoEnabled;
}
void AppConfig::setAutoHide(bool b) {
setSettingModified(m_AutoHide, b);
}
void AppConfig::setAutoHide(bool b) { setSettingModified(m_AutoHide, b); }
bool AppConfig::getAutoHide() { return m_AutoHide; }
@ -504,9 +466,7 @@ unsigned long long AppConfig::getLicenseNextCheck() const {
return m_licenseNextCheck;
}
const QString& AppConfig::getGuid() const {
return m_guid;
}
const QString &AppConfig::getGuid() const { return m_guid; }
bool AppConfig::getLanguageSync() const { return m_LanguageSync; }
@ -549,28 +509,30 @@ void AppConfig::setSetting(AppConfig::Setting name, T value) {
template <typename T>
void AppConfig::setCommonSetting(AppConfig::Setting name, T value) {
ConfigWriter::make()->setSetting(settingName(name), value, ConfigWriter::kUser);
ConfigWriter::make()->setSetting(settingName(name), value, ConfigWriter::kSystem);
ConfigWriter::make()->setSetting(settingName(name), value,
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);
}
QVariant AppConfig::loadCommonSetting(AppConfig::Setting name, const QVariant& defaultValue) const {
QVariant AppConfig::loadCommonSetting(AppConfig::Setting name,
const QVariant &defaultValue) const {
QVariant result(defaultValue);
QString setting(settingName(name));
auto &writer = *ConfigWriter::make();
if (writer.hasSetting(setting)) {
result = writer.loadSetting(setting, defaultValue);
}
else if (writer.getScope() == ConfigWriter::kSystem ) {
} else if (writer.getScope() == ConfigWriter::kSystem) {
if (writer.hasSetting(setting, 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);
}
@ -590,17 +552,13 @@ void AppConfig::loadScope(ConfigWriter::Scope scope) {
}
}
void AppConfig::setDefaultValues()
{
m_InitiateConnectionFromServer = false;
}
void AppConfig::setDefaultValues() { m_InitiateConnectionFromServer = false; }
void AppConfig::setLoadFromSystemScope(bool value) {
if (value) {
loadScope(ConfigWriter::kSystem);
}
else {
} else {
loadScope(ConfigWriter::kUser);
}
@ -619,29 +577,17 @@ bool AppConfig::isSystemScoped() const {
return ConfigWriter::make()->getScope() == ConfigWriter::kSystem;
}
bool AppConfig::getServerGroupChecked() const {
return m_ServerGroupChecked;
}
bool AppConfig::getServerGroupChecked() const { return m_ServerGroupChecked; }
bool AppConfig::getUseExternalConfig() const {
return m_UseExternalConfig;
}
bool AppConfig::getUseExternalConfig() const { return m_UseExternalConfig; }
const QString& AppConfig::getConfigFile() const {
return m_ConfigFile;
}
const QString &AppConfig::getConfigFile() const { return m_ConfigFile; }
bool AppConfig::getUseInternalConfig() const {
return m_UseInternalConfig;
}
bool AppConfig::getUseInternalConfig() const { return m_UseInternalConfig; }
bool AppConfig::getClientGroupChecked() const {
return m_ClientGroupChecked;
}
bool AppConfig::getClientGroupChecked() const { return m_ClientGroupChecked; }
QString AppConfig::getServerHostname() const {
return m_ServerHostname;
}
QString AppConfig::getServerHostname() const { return m_ServerHostname; }
void AppConfig::setServerGroupChecked(bool newValue) {
setSettingModified(m_ServerGroupChecked, newValue);
@ -677,8 +623,7 @@ void AppConfig::setServerClientMode(bool newValue) {
template <typename T>
void AppConfig::setSettingModified(T &variable, const T &newValue) {
if (variable != newValue)
{
if (variable != newValue) {
variable = newValue;
m_unsavedChanges = true;
}
@ -688,13 +633,9 @@ void AppConfig::setTLSCertPath(const QString& path) {
m_TLSCertificatePath = path;
}
QString AppConfig::getTLSCertPath() const {
return m_TLSCertificatePath;
}
QString AppConfig::getTLSCertPath() const { return m_TLSCertificatePath; }
QString AppConfig::getTLSKeyLength() const {
return m_TLSKeyLength;
}
QString AppConfig::getTLSKeyLength() const { return m_TLSKeyLength; }
void AppConfig::setTLSKeyLength(const QString &length) {
if (m_TLSKeyLength != length) {
@ -705,8 +646,7 @@ void AppConfig::setTLSKeyLength(const QString& length) {
void AppConfig::generateCertificate(bool forceGeneration) const {
SslCertificate sslCertificate;
sslCertificate.generateCertificate(getTLSCertPath(), getTLSKeyLength(), forceGeneration);
sslCertificate.generateCertificate(getTLSCertPath(), getTLSKeyLength(),
forceGeneration);
emit sslToggled();
}

View file

@ -20,15 +20,15 @@
#define APPCONFIG_H
#include <QObject>
#include <QString>
#include <QVariant>
#include "ElevateMode.h"
#include <shared/EditionType.h>
#include <mutex>
#include "ConfigBase.h"
#include "ConfigWriter.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
// saved to settings when the user finishes running the wizard. if
@ -52,13 +52,9 @@ class SettingsDialog;
class ServerConfig;
class LicenseRegister;
enum ProcessMode {
Service,
Desktop
};
enum ProcessMode { Service, Desktop };
class AppConfig: public QObject, public GUI::Config::ConfigBase
{
class AppConfig : public QObject, public GUI::Config::ConfigBase {
Q_OBJECT
friend class SettingsDialog;
@ -134,11 +130,11 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
#endif
/// @brief Sets the user preference to load from SystemScope.
/// @param [in] value
/// True - This will set the variable and load the global scope settings.
/// False - This will set the variable and load the user scope settings.
/// True - This will set the variable and load the global scope
/// settings. False - This will set the variable and load the user
/// scope settings.
void setLoadFromSystemScope(bool value);
bool getServerGroupChecked() const;
bool getUseExternalConfig() const;
const QString &getConfigFile() const;
@ -171,7 +167,6 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
/// @param [in] QString length The key length eg: 1024, 2048, 4096
void setTLSKeyLength(const QString &length);
QString lastVersion() const;
void setMinimizeToTray(bool b);
@ -185,7 +180,8 @@ class AppConfig: public QObject, public GUI::Config::ConfigBase
void generateCertificate(bool forceGeneration = false) const;
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 {
kScreenName,
kPort,
@ -242,12 +238,12 @@ protected:
void setElevateMode(ElevateMode em);
/// @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;
static QString settingName(AppConfig::Setting name);
private:
QString m_ScreenName;
int m_Port;
QString m_Interface;
@ -291,9 +287,11 @@ protected:
QString m_TLSCertificatePath; /// @brief The path to the TLS certificate file
QString m_TLSKeyLength; /// @brief The key length of the TLS cert to make
bool m_LoadFromSystemScope; /// @brief should the setting be loaded from SystemScope
/// If the user has settings but this is true then
/// system settings will be loaded instead of the users
bool m_LoadFromSystemScope; /// @brief should the setting be loaded from
/// SystemScope
/// If the user has settings but this is
/// true then system settings will be
/// loaded instead of the users
CoreInterface m_CoreInterface;
@ -310,37 +308,38 @@ protected:
/// @brief Sets the value of a setting
/// @param [in] name The Setting to be saved
/// @param [in] value The Value to be saved
template <typename T>
void setSetting(AppConfig::Setting name, T value);
template <typename T> void setSetting(AppConfig::Setting name, T value);
/// @brief Sets the value of a common setting
/// which should have the same value for all scopes
/// @param [in] name The Setting to be saved
/// @param [in] value The Value to be saved
template <typename T>
void setCommonSetting(AppConfig::Setting name, T value);
template <typename T> void setCommonSetting(AppConfig::Setting name, T value);
/// @brief Loads a setting
/// @param [in] name The setting to be loaded
/// @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
/// @param [in] name The setting to be loaded
/// @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
/// it cant be modified by more that one object at a time if the setting is being switched
/// from system to user.
/// @brief As the settings will be accessible by multiple objects this lock
/// will ensure that
/// 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;
/// @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
/// @param [in] variable the setting that will be changed
/// @param [in] newValue The new value of the setting
template <typename T>
void setSettingModified(T& variable,const T& newValue);
template <typename T> void setSettingModified(T &variable, const T &newValue);
/// @brief This method loads config from specified scope
/// @param [in] scope which should be loaded.

View file

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

View file

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

View file

@ -24,11 +24,25 @@
#include <QString>
#include <QVariant>
class BaseConfig
{
class BaseConfig {
public:
enum Modifier { DefaultMod = -1, Shift, Ctrl, Alt, Meta, Super, None, NumModifiers };
enum SwitchCorner { TopLeft, TopRight, BottomLeft, BottomRight, NumSwitchCorners };
enum Modifier {
DefaultMod = -1,
Shift,
Ctrl,
Alt,
Meta,
Super,
None,
NumModifiers
};
enum SwitchCorner {
TopLeft,
TopRight,
BottomLeft,
BottomRight,
NumSwitchCorners
};
enum Fix { CapsLock, NumLock, ScrollLock, XTest, NumFixes };
protected:
@ -37,12 +51,11 @@ class BaseConfig
protected:
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");
array.clear();
for (int i = 0; i < entries; i++)
{
for (int i = 0; i < entries; i++) {
settings.setArrayIndex(i);
QVariant v = settings.value(arrayName, deflt);
array.append(v.value<T2>());
@ -51,12 +64,11 @@ class BaseConfig
}
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);
settings.beginReadArray(arrayName + "Array");
for (int i = 0; i < entries; i++)
{
for (int i = 0; i < entries; i++) {
settings.setArrayIndex(i);
QVariant v = settings.value(arrayName, deflt);
array[i] = v.value<T2>();
@ -65,22 +77,22 @@ class BaseConfig
}
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");
for (int i = 0; i < array.size(); i++)
{
for (int i = 0; i < array.size(); i++) {
settings.setArrayIndex(i);
settings.setValue(arrayName, array[i]);
}
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]; }
static const char *switchCornerName(int idx) {
return m_SwitchCornerNames[idx];
}
private:
static const char *m_ModifierNames[];

View file

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

View file

@ -34,12 +34,12 @@ class CommandProcess;
class DataDownloader;
class AppConfig;
class BonjourWindows : public QObject
{
class BonjourWindows : public QObject {
Q_OBJECT
public:
BonjourWindows(SettingsDialog* settingsDialog, MainWindow* mainWindow, AppConfig& appConfig);
BonjourWindows(SettingsDialog *settingsDialog, MainWindow *mainWindow,
AppConfig &appConfig);
virtual ~BonjourWindows();
public:

View file

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

View file

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

View file

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

View file

@ -23,8 +23,7 @@
class MainWindow;
class ClientConnection
{
class ClientConnection {
MainWindow &m_parent;
bool m_checkConnection = false;

View file

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

View file

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

View file

@ -21,7 +21,8 @@
namespace GUI {
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
/// ConfigWriter
/// to allow global saving and loading
class ConfigBase {
public:
@ -29,20 +30,22 @@ namespace GUI {
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;
/// @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;
/// @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; }
protected:
/// @brief Does the class have unsaved changes in it.
bool m_unsavedChanges = false;
};
}
}
} // namespace Config
} // namespace GUI
#endif // SYNERGY_CORE_CONFIGBASE_H

View file

@ -20,13 +20,12 @@
#include <QCoreApplication>
#include <QFile>
#include "ConfigWriter.h"
#include "ConfigBase.h"
#include "ConfigWriter.h"
namespace {
QString getSystemSettingPath()
{
QString getSystemSettingPath() {
const QString settingFilename("SystemConfig.ini");
QString path;
#if defined(Q_OS_WIN)
@ -47,12 +46,11 @@ QString getSystemSettingPath()
}
#if defined(Q_OS_WIN)
void loadOldSystemSettings(QSettings& settings)
{
void loadOldSystemSettings(QSettings &settings) {
if (!QFile(settings.fileName()).exists()) {
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, "SystemConfig.ini");
QSettings oldSystemSettings (QSettings::IniFormat,
QSettings::SystemScope,
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope,
"SystemConfig.ini");
QSettings oldSystemSettings(QSettings::IniFormat, QSettings::SystemScope,
QCoreApplication::organizationName(),
QCoreApplication::applicationName());
@ -63,19 +61,19 @@ void loadOldSystemSettings(QSettings& settings)
}
// Restore system settings path
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, getSystemSettingPath());
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope,
getSystemSettingPath());
}
}
#endif
}
} // namespace
namespace GUI {
namespace Config {
// Assignment of static variable
ConfigWriter *ConfigWriter::s_pConfiguration = nullptr;
ConfigWriter *ConfigWriter::make() {
// Only one ConfigWriter can exist at any one time (Singleton)
if (!s_pConfiguration) {
@ -86,13 +84,12 @@ namespace GUI {
ConfigWriter::ConfigWriter() {
QSettings::setPath(QSettings::Format::IniFormat,
QSettings::Scope::SystemScope,
getSystemSettingPath());
QSettings::Scope::SystemScope, getSystemSettingPath());
// Config will default to User settings if they exist,
// otherwise it will load System setting and save them to User settings
m_pSettingsSystem = new QSettings(QSettings::Format::IniFormat,
QSettings::Scope::SystemScope,
m_pSettingsSystem =
new QSettings(QSettings::Format::IniFormat, QSettings::Scope::SystemScope,
QCoreApplication::organizationName(),
QCoreApplication::applicationName());
@ -101,19 +98,17 @@ namespace GUI {
loadOldSystemSettings(*m_pSettingsSystem);
#endif
//defaults to user scope, if we set the scope specifically then we also have to set
// the application name and the organisation name which breaks backwards compatibility
// See #6730
// defaults to user scope, if we set the scope specifically then we also have
// to set
// the application name and the organisation name which breaks backwards
// compatibility See #6730
m_pSettingsUser = new QSettings();
// Set scope to user for initially
m_pSettingsCurrent = m_pSettingsUser;
}
void ConfigWriter::destroy() {
destroy(s_pConfiguration);
}
void ConfigWriter::destroy() { destroy(s_pConfiguration); }
ConfigWriter::~ConfigWriter() {
while (!m_pCallerList.empty()) {
@ -124,7 +119,6 @@ namespace GUI {
destroy(m_pSettingsUser);
}
bool ConfigWriter::hasSetting(const QString &name, Scope scope) const {
switch (scope) {
case kUser:
@ -140,7 +134,8 @@ namespace GUI {
return m_pSettingsCurrent->isWritable();
}
QVariant ConfigWriter::loadSetting(const QString& name, const QVariant &defaultValue, Scope scope) {
QVariant ConfigWriter::loadSetting(const QString &name,
const QVariant &defaultValue, Scope scope) {
switch (scope) {
case kUser:
return m_pSettingsUser->value(name, defaultValue);
@ -151,7 +146,6 @@ namespace GUI {
}
}
void ConfigWriter::setScope(ConfigWriter::Scope scope) {
if (m_CurrentScope != scope) {
m_CurrentScope = scope;
@ -169,9 +163,7 @@ namespace GUI {
}
}
ConfigWriter::Scope ConfigWriter::getScope() const {
return m_CurrentScope;
}
ConfigWriter::Scope ConfigWriter::getScope() const { return m_CurrentScope; }
void ConfigWriter::globalLoad() {
for (auto &i : m_pCallerList) {
@ -194,16 +186,12 @@ namespace GUI {
}
}
QSettings &ConfigWriter::settings() {
return *m_pSettingsCurrent;
}
QSettings &ConfigWriter::settings() { return *m_pSettingsCurrent; }
void ConfigWriter::registerClass(ConfigBase *receiver) {
m_pCallerList.push_back(receiver);
}
bool ConfigWriter::unsavedChanges() const {
if (m_unsavedChanges) {
return true;
@ -219,8 +207,6 @@ namespace GUI {
return false;
}
void ConfigWriter::markUnsaved() {
m_unsavedChanges = true;
}
}
}
void ConfigWriter::markUnsaved() { m_unsavedChanges = true; }
} // namespace Config
} // namespace GUI

View file

@ -17,8 +17,8 @@
#ifndef SYNERGY_CORE_CONFIGWRITER_H
#define SYNERGY_CORE_CONFIGWRITER_H
#include <QVariant>
#include <QSettings>
#include <QVariant>
/// @brief Contains GUI code
namespace GUI {
@ -31,10 +31,9 @@ namespace GUI {
class ConfigWriter : private QObject {
public:
/// @brief the public way to construct the configuration calls
/// The pointer returned is owned by this class and should not be stored
/// by other classes.
/// The pointer returned is owned by this class and should not be
/// stored by other classes.
static ConfigWriter *make();
/// @brief the public way to destroy the configuration class
@ -58,17 +57,22 @@ namespace GUI {
/// @brief Sets the value of a setting
/// @param [in] name The Setting to be saved
/// @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>
void setSetting(const QString &name, T value, Scope scope = kCurrent);
/// @brief Loads a setting
/// @param [in] name The setting to be loaded
/// @param [in] defaultValue The default value of the setting
/// @param [in] scope The scope to get the value from, default is current scope
QVariant loadSetting(const QString& name, const QVariant& defaultValue = QVariant(), Scope scope = kCurrent);
/// @param [in] scope The scope to get the value from, default is current
/// 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
void setScope(Scope scope = kUser);
@ -83,12 +87,13 @@ namespace GUI {
void globalSave();
/// @brief Returns the current scopes settings object
/// If more specialize control into the settings is needed this can provide
/// direct access to the settings file handler
/// If more specialize control into the settings is needed this can
/// provide direct access to the settings file handler
/// @return QSettings The Settings object as a reference
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();
/// @brief Register a class to receives globalLoad and globalSave events
@ -100,15 +105,14 @@ namespace GUI {
bool unsavedChanges() const;
protected:
Scope m_CurrentScope = kUser; /// @brief The current scope of the settings
QSettings* m_pSettingsCurrent = nullptr; /// @brief The currently active settings
QSettings *m_pSettingsCurrent =
nullptr; /// @brief The currently active settings
QSettings *m_pSettingsUser = nullptr; /// @brief The user specific settings
QSettings *m_pSettingsSystem = nullptr; /// @brief The system wide settings
private:
/// @brief Contains a list all all classes that hook into the writer.
/// This allows all classes that save settings to be called an updated
/// on a save and reload by any other class
@ -117,18 +121,22 @@ namespace GUI {
/// @brief if this class modified settings then set the flag
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();
/// @brief the pointer of the ConfigWriter for singolton use
static ConfigWriter *s_pConfiguration;
/// @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
// Moved so its not bulking out the class definition
// Implementation of a template function needs to be visible to all calls thus
// is must be in the header Moved so its not bulking out the class definition
template <typename T>
void ConfigWriter::setSetting(const QString &name, T value, Scope scope) {
switch (scope) {
@ -144,6 +152,6 @@ namespace GUI {
}
m_unsavedChanges = true;
}
}
}
} // namespace Config
} // namespace GUI
#endif // SYNERGY_CORE_CONFIGWRITER_H

View file

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

View file

@ -19,8 +19,7 @@
#include <QString>
class CoreInterface
{
class CoreInterface {
public:
CoreInterface();

View file

@ -16,13 +16,13 @@
*/
#include "CreditsLoader.h"
#include "MainWindow.h"
#include "AppConfig.h"
#include "MainWindow.h"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QNetworkReply>
#include <QNetworkRequest>
namespace {
@ -34,26 +34,18 @@ public:
if (isSuccess()) {
m_data = data["data"].toString();
}
else if (isFailed()) {
} else if (isFailed()) {
m_data = data["message"].toString();
}
else {
} else {
m_data = "Unknown response from the server";
}
}
bool isSuccess() const {
return (m_status == "success");
}
bool isSuccess() const { return (m_status == "success"); }
bool isFailed() const {
return (m_status == "failed");
}
bool isFailed() const { return (m_status == "failed"); }
const QString& getData() const {
return m_data;
}
const QString &getData() const { return m_data; }
private:
QMap<QString, QVariant> parseJson(const QByteArray &json) const {
@ -69,40 +61,38 @@ private:
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) :
m_mainWindow(mainWindow),
m_config(config)
{
connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
void CreditsLoader::loadEliteBackers()
{
void CreditsLoader::loadEliteBackers() {
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 request = QNetworkRequest(url);
m_manager.get(request);
}
void CreditsLoader::replyFinished(QNetworkReply* reply) const
{
void CreditsLoader::replyFinished(QNetworkReply *reply) const {
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);
if (creditsResponse.isSuccess()) {
emit loaded(creditsResponse.getData());
}
else {
} else {
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);
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,15 +16,14 @@
*/
#pragma once
#include <QObject>
#include <QNetworkAccessManager>
#include <QObject>
class QNetworkReply;
class MainWindow;
class AppConfig;
class CreditsLoader : public QObject
{
class CreditsLoader : public QObject {
Q_OBJECT
public:
explicit CreditsLoader(MainWindow &mainWindow, const AppConfig &config);

View file

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

View file

@ -18,14 +18,13 @@
#ifndef DATADOWNLOADER_H
#define DATADOWNLOADER_H
#include <QObject>
#include <QByteArray>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QObject>
class DataDownloader : public QObject
{
class DataDownloader : public QObject {
Q_OBJECT
public:

View file

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

View file

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

View file

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

View file

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

View file

@ -19,8 +19,7 @@
#include <QString>
class Fingerprint
{
class Fingerprint {
private:
Fingerprint(const QString &filename);

View file

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

View file

@ -20,8 +20,8 @@
#define HOTKEY_H
#include <QString>
#include <QList>
#include <QString>
#include <QTextStream>
#include "Action.h"
@ -31,8 +31,7 @@ class HotkeyDialog;
class ServerConfigDialog;
class QSettings;
class Hotkey
{
class Hotkey {
friend class HotkeyDialog;
friend class ServerConfigDialog;
friend QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey);
@ -55,7 +54,6 @@ class Hotkey
void setKeySequence(const KeySequence &seq) { m_KeySequence = seq; }
ActionList &actions() { return m_Actions; }
private:
KeySequence m_KeySequence;
ActionList m_Actions;

View file

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

View file

@ -20,13 +20,12 @@
#define HOTKEYDIALOG_H
#include "ui_HotkeyDialogBase.h"
#include "Hotkey.h"
#include "ui_HotkeyDialogBase.h"
#include <QDialog>
class HotkeyDialog : public QDialog, public Ui::HotkeyDialogBase
{
class HotkeyDialog : public QDialog, public Ui::HotkeyDialogBase {
Q_OBJECT
public:
@ -39,7 +38,9 @@ class HotkeyDialog : public QDialog, public Ui::HotkeyDialogBase
void accept();
protected:
const KeySequenceWidget* sequenceWidget() const { return m_pKeySequenceWidgetHotkey; }
const KeySequenceWidget *sequenceWidget() const {
return m_pKeySequenceWidgetHotkey;
}
Hotkey &hotkey() { return m_Hotkey; }
private:

View file

@ -17,38 +17,33 @@
*/
#include "IpcClient.h"
#include <QTcpSocket>
#include <QHostAddress>
#include <iostream>
#include <QTimer>
#include "IpcReader.h"
#include "Ipc.h"
#include "IpcReader.h"
#include <QDataStream>
#include <QHostAddress>
#include <QTcpSocket>
#include <QTimer>
#include <iostream>
IpcClient::IpcClient() :
m_ReaderStarted(false),
m_Enabled(false)
{
IpcClient::IpcClient() : m_ReaderStarted(false), m_Enabled(false) {
m_Socket = new QTcpSocket(this);
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);
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();
infoMessage("connection established");
}
void IpcClient::connectToHost()
{
void IpcClient::connectToHost() {
m_Enabled = true;
infoMessage("connecting to service...");
@ -60,20 +55,24 @@ void IpcClient::connectToHost()
}
}
void IpcClient::disconnectFromHost()
{
void IpcClient::disconnectFromHost() {
infoMessage("service disconnect");
m_Reader->stop();
m_Socket->close();
}
void IpcClient::error(QAbstractSocket::SocketError error)
{
void IpcClient::error(QAbstractSocket::SocketError error) {
QString text;
switch (error) {
case 0: text = "connection refused"; break;
case 1: text = "remote host closed"; break;
default: text = QString("code=%1").arg(error); break;
case 0:
text = "connection refused";
break;
case 1:
text = "remote host closed";
break;
default:
text = QString("code=%1").arg(error);
break;
}
errorMessage(QString("ipc connection error, %1").arg(text));
@ -81,15 +80,13 @@ void IpcClient::error(QAbstractSocket::SocketError error)
QTimer::singleShot(1000, this, SLOT(retryConnect()));
}
void IpcClient::retryConnect()
{
void IpcClient::retryConnect() {
if (m_Enabled) {
connectToHost();
}
}
void IpcClient::sendHello()
{
void IpcClient::sendHello() {
QDataStream stream(m_Socket);
stream.writeRawData(kIpcMsgHello, 4);
@ -98,15 +95,16 @@ void IpcClient::sendHello()
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);
stream.writeRawData(kIpcMsgCommand, 4);
std::string stdStringCommand = command.toStdString();
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];
intToBytes(length, lenBuf, 4);
@ -114,33 +112,27 @@ void IpcClient::sendCommand(const QString& command, ElevateMode const elevate)
stream.writeRawData(charCommand, length);
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;
stream.writeRawData(elevateBuf, 1);
}
void IpcClient::handleReadLogLine(const QString& text)
{
readLogLine(text);
}
void IpcClient::handleReadLogLine(const QString &text) { readLogLine(text); }
// 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) {
buffer[0] = value & 0xff;
}
else if (size == 2) {
} else if (size == 2) {
buffer[0] = (value >> 8) & 0xff;
buffer[1] = value & 0xff;
}
else if (size == 4) {
} else if (size == 4) {
buffer[0] = (value >> 24) & 0xff;
buffer[1] = (value >> 16) & 0xff;
buffer[2] = (value >> 8) & 0xff;
buffer[3] = value & 0xff;
}
else {
} else {
// TODO: other sizes, if needed.
}
}

View file

@ -18,16 +18,15 @@
#pragma once
#include <QObject>
#include <QAbstractSocket>
#include <QObject>
#include "ElevateMode.h"
class QTcpSocket;
class IpcReader;
class IpcClient : public QObject
{
class IpcClient : public QObject {
Q_OBJECT
public:

View file

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

View file

@ -18,13 +18,12 @@
#pragma once
#include <QObject>
#include <QMutex>
#include <QObject>
class QTcpSocket;
class IpcReader : public QObject
{
class IpcReader : public QObject {
Q_OBJECT;
public:

View file

@ -23,13 +23,10 @@
// this table originally comes from Qt sources (gui/kernel/qkeysequence.cpp)
// and is heavily modified for QSynergy
static const struct
{
static const struct {
int key;
const char *name;
} keyname[] =
{
{ Qt::Key_Space, "Space" },
} keyname[] = {{Qt::Key_Space, "Space"},
{Qt::Key_Escape, "Escape"},
{Qt::Key_Tab, "Tab"},
{Qt::Key_Backtab, "LeftTab"},
@ -77,27 +74,18 @@ static const struct
{Qt::Key_Launch1, "AppUser2"},
{Qt::Key_Select, "Select"},
{ 0, 0 }
};
{0, 0}};
KeySequence::KeySequence() :
m_Sequence(),
m_Modifiers(0),
m_IsValid(false)
{
}
KeySequence::KeySequence() : 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;
}
QString KeySequence::toString() const
{
QString KeySequence::toString() const {
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]);
if (i != m_Sequence.size() - 1)
@ -107,18 +95,13 @@ QString KeySequence::toString() const
return result;
}
bool KeySequence::appendMouseButton(int button)
{
return appendKey(button, 0);
}
bool KeySequence::appendMouseButton(int button) { return appendKey(button, 0); }
bool KeySequence::appendKey(int key, int modifiers)
{
bool KeySequence::appendKey(int key, int modifiers) {
if (m_Sequence.size() == 4)
return true;
switch(key)
{
switch (key) {
case Qt::Key_AltGr:
return false;
@ -126,16 +109,13 @@ bool KeySequence::appendKey(int key, int modifiers)
case Qt::Key_Alt:
case Qt::Key_Shift:
case Qt::Key_Meta:
case Qt::Key_Menu:
{
case Qt::Key_Menu: {
int mod = modifiers & (~m_Modifiers);
if (mod)
{
if (mod) {
m_Sequence.append(mod);
m_Modifiers |= mod;
}
}
break;
} break;
default:
// 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;
}
void KeySequence::loadSettings(QSettings& settings)
{
void KeySequence::loadSettings(QSettings &settings) {
sequence().clear();
int num = settings.beginReadArray("keys");
for (int i = 0; i < num; i++)
{
for (int i = 0; i < num; i++) {
settings.setArrayIndex(i);
sequence().append(settings.value("key", 0).toInt());
}
@ -165,34 +143,33 @@ void KeySequence::loadSettings(QSettings& settings)
setValid(true);
}
void KeySequence::saveSettings(QSettings& settings) const
{
void KeySequence::saveSettings(QSettings &settings) const {
settings.beginWriteArray("keys");
for (int i = 0; i < sequence().size(); i++)
{
for (int i = 0; i < sequence().size(); i++) {
settings.setArrayIndex(i);
settings.setValue("key", sequence()[i]);
}
settings.endArray();
}
QString KeySequence::keyToString(int key)
{
QString KeySequence::keyToString(int key) {
// nothing there?
if (key == 0)
return "";
// a hack to handle mouse buttons as if they were keys
if (key < Qt::Key_Space)
{
switch(key)
{
case Qt::LeftButton: return "1";
case Qt::RightButton: return "2";
case Qt::MidButton: return "3";
if (key < Qt::Key_Space) {
switch (key) {
case Qt::LeftButton:
return "1";
case Qt::RightButton:
return "2";
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?
@ -208,7 +185,8 @@ QString KeySequence::keyToString(int key)
if (key & Qt::MetaModifier)
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;
// a printable 7 bit character?
@ -221,8 +199,7 @@ QString KeySequence::keyToString(int key)
// a special key?
int i = 0;
while (keyname[i].name)
{
while (keyname[i].name) {
if (key == keyname[i].key)
return QString::fromUtf8(keyname[i].name);
i++;
@ -230,15 +207,14 @@ QString KeySequence::keyToString(int key)
// representable in ucs2?
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
return "";
}
bool KeySequence::operator==(const KeySequence& ks) const
{
return m_Sequence == ks.m_Sequence &&
m_Modifiers == ks.m_Modifiers &&
bool KeySequence::operator==(const KeySequence &ks) const {
return m_Sequence == ks.m_Sequence && m_Modifiers == ks.m_Modifiers &&
m_IsValid == ks.m_IsValid;
}

View file

@ -25,8 +25,7 @@
class QSettings;
class KeySequence
{
class KeySequence {
public:
KeySequence();
@ -57,4 +56,3 @@ class KeySequence
};
#endif

View file

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

View file

@ -24,8 +24,7 @@
#include "KeySequence.h"
class KeySequenceWidget : public QPushButton
{
class KeySequenceWidget : public QPushButton {
Q_OBJECT
public:
@ -78,4 +77,3 @@ class KeySequenceWidget : public QPushButton
};
#endif

View file

@ -17,31 +17,30 @@
#include "LicenseManager.h"
#include "AppConfig.h"
#include <QDateTime>
#include <QLocale>
#include <QThread>
#include <QTimer>
#include <ctime>
#include <stdexcept>
#include <utility>
#include <QThread>
#include <QTimer>
#include <QDateTime>
#include <QLocale>
namespace {
std::string
getMaintenanceMessage(const SerialKey& serialKey)
{
std::string getMaintenanceMessage(const SerialKey &serialKey) {
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."
"<p>To use this version, you’ll need to renew your Synergy maintenance license. "
QString message =
"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\""
"style=\"text-decoration: none; color: #4285F4;\">Renew today</a>.</p>";
auto formatedDate = QLocale("en_US").toString(expiration, "MMM dd yyyy");
return message.arg(formatedDate).toStdString();
}
void
checkSerialKey(const SerialKey& serialKey, bool acceptExpired)
{
void checkSerialKey(const SerialKey &serialKey, bool acceptExpired) {
if (serialKey.isMaintenance()) {
auto buildDate = QDateTime::fromString(__TIMESTAMP__).toTime_t();
@ -56,30 +55,25 @@ checkSerialKey(const SerialKey& serialKey, bool acceptExpired)
#ifdef SYNERGY_BUSINESS
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
}
}
} // namespace
LicenseManager::LicenseManager(AppConfig *appConfig)
: m_AppConfig(appConfig), m_serialKey(appConfig->edition()),
m_registry(*appConfig) {}
LicenseManager::LicenseManager(AppConfig* appConfig) :
m_AppConfig(appConfig),
m_serialKey(appConfig->edition()),
m_registry(*appConfig) {
}
void
LicenseManager::setSerialKey(SerialKey serialKey, bool acceptExpired)
{
void LicenseManager::setSerialKey(SerialKey serialKey, bool acceptExpired) {
checkSerialKey(serialKey, acceptExpired);
if (serialKey != m_serialKey) {
using std::swap;
swap(serialKey, m_serialKey);
m_AppConfig->setSerialKey(QString::fromStdString
(m_serialKey.toString()));
m_AppConfig->setSerialKey(QString::fromStdString(m_serialKey.toString()));
emit showLicenseNotice(getLicenseNotice());
validateSerialKey();
@ -92,10 +86,9 @@ LicenseManager::setSerialKey(SerialKey serialKey, bool acceptExpired)
}
}
void
LicenseManager::notifyUpdate(QString fromVersion, QString toVersion) const {
if ((fromVersion == "Unknown")
&& (m_serialKey == SerialKey(kUnregistered))) {
void LicenseManager::notifyUpdate(QString fromVersion,
QString toVersion) const {
if ((fromVersion == "Unknown") && (m_serialKey == SerialKey(kUnregistered))) {
return;
}
@ -111,31 +104,18 @@ LicenseManager::notifyUpdate(QString fromVersion, QString toVersion) const {
notifier->moveToThread(thread);
thread->start();
QMetaObject::invokeMethod(notifier, "notifyUpdate",
Qt::QueuedConnection);
QMetaObject::invokeMethod(notifier, "notifyUpdate", Qt::QueuedConnection);
}
Edition
LicenseManager::activeEdition() const
{
return m_serialKey.edition();
}
Edition LicenseManager::activeEdition() const { return m_serialKey.edition(); }
QString
LicenseManager::activeEditionName() const
{
QString LicenseManager::activeEditionName() const {
return getEditionName(activeEdition(), m_serialKey.isTrial());
}
const SerialKey&
LicenseManager::serialKey() const
{
return m_serialKey;
}
const SerialKey &LicenseManager::serialKey() const { return m_serialKey; }
void
LicenseManager::refresh()
{
void LicenseManager::refresh() {
if (!m_AppConfig->serialKey().isEmpty()) {
try {
SerialKey serialKey(m_AppConfig->serialKey().toStdString());
@ -150,15 +130,11 @@ LicenseManager::refresh()
}
}
void
LicenseManager::skipActivation() const
{
void LicenseManager::skipActivation() const {
notifyActivation("skip:unknown");
}
QString
LicenseManager::getEditionName(Edition const edition, bool trial)
{
QString LicenseManager::getEditionName(Edition const edition, bool trial) {
SerialKeyEdition KeyEdition(edition);
std::string name = KeyEdition.getDisplayName();
@ -169,9 +145,7 @@ LicenseManager::getEditionName(Edition const edition, bool trial)
return QString::fromUtf8(name.c_str(), static_cast<int>(name.size()));
}
void
LicenseManager::notifyActivation(QString identity) const
{
void LicenseManager::notifyActivation(QString identity) const {
ActivationNotifier *notifier = new ActivationNotifier();
notifier->setIdentity(identity);
@ -186,16 +160,13 @@ LicenseManager::notifyActivation(QString identity) const
QMetaObject::invokeMethod(notifier, "notify", Qt::QueuedConnection);
}
QString
LicenseManager::getLicenseNotice() const
{
QString LicenseManager::getLicenseNotice() const {
QString Notice;
if (m_serialKey.isTemporary()) {
if (m_serialKey.isTrial()) {
Notice = getTrialNotice();
}
else{
} else {
Notice = getTemporaryNotice();
}
}
@ -203,27 +174,22 @@ LicenseManager::getLicenseNotice() const
return Notice;
}
void
LicenseManager::registerLicense()
{
m_registry.registerLicense();
}
void LicenseManager::registerLicense() { m_registry.registerLicense(); }
QString
LicenseManager::getTrialNotice() const
{
QString LicenseManager::getTrialNotice() const {
QString Notice;
if (m_serialKey.isExpired(::time(0))) {
Notice = "<html><head/><body><p>"
"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>";
}
else{
} else {
Notice = "<html><head/><body><p>"
"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>";
time_t daysLeft = m_serialKey.daysLeft(::time(0));
@ -233,21 +199,20 @@ LicenseManager::getTrialNotice() const
return Notice;
}
QString
LicenseManager::getTemporaryNotice() const
{
QString LicenseManager::getTemporaryNotice() const {
QString Notice;
if (m_serialKey.isExpired(::time(0))) {
Notice = "<html><head/><body><p>"
"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>";
}
else if (m_serialKey.isExpiring(::time(0))) {
} else if (m_serialKey.isExpiring(::time(0))) {
Notice = "<html><head/><body><p>"
"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>";
time_t daysLeft = m_serialKey.daysLeft(::time(0));
@ -257,15 +222,13 @@ LicenseManager::getTemporaryNotice() const
return Notice;
}
void
LicenseManager::validateSerialKey() const
{
void LicenseManager::validateSerialKey() const {
if (m_serialKey.isValid()) {
if (m_serialKey.isTemporary()) {
QTimer::singleShot(m_serialKey.getSpanLeft(), this, SLOT(validateSerialKey()));
QTimer::singleShot(m_serialKey.getSpanLeft(), this,
SLOT(validateSerialKey()));
}
}
else{
} else {
emit InvalidLicense();
}
}

View file

@ -17,18 +17,17 @@
#pragma once
#include <ActivationNotifier.h>
#include <QObject>
#include <shared/EditionType.h>
#include <shared/SerialKey.h>
#include <ActivationNotifier.h>
#include <utility>
#include "LicenseRegistry.h"
class AppConfig;
class LicenseManager: public QObject
{
class LicenseManager : public QObject {
Q_OBJECT
public:

View file

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

View file

@ -16,15 +16,14 @@
*/
#pragma once
#include <QNetworkAccessManager>
#include <QObject>
#include <QTimer>
#include <QNetworkAccessManager>
class QNetworkReply;
class AppConfig;
class LicenseRegistry : public QObject
{
class LicenseRegistry : public QObject {
Q_OBJECT
public:

File diff suppressed because it is too large Load diff

View file

@ -19,23 +19,23 @@
#pragma once
#include <QMainWindow>
#include <QSystemTrayIcon>
#include <QSettings>
#include <QProcess>
#include <QThread>
#include <QMutex>
#include <QProcess>
#include <QSettings>
#include <QSystemTrayIcon>
#include <QThread>
#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 "ServerConnection.h"
#include "ClientConnection.h"
#include "AppConfig.h"
#include "VersionChecker.h"
#include "IpcClient.h"
#include "Ipc.h"
#include "ActivationDialog.h"
#include "ConfigWriter.h"
#include "TrayIcon.h"
@ -61,8 +61,7 @@ class SslCertificate;
class LicenseManager;
class Zeroconf;
class MainWindow : public QMainWindow, public Ui::MainWindowBase
{
class MainWindow : public QMainWindow, public Ui::MainWindowBase {
Q_OBJECT
friend class QSynergyApplication;
@ -73,8 +72,7 @@ class MainWindow : public QMainWindow, public Ui::MainWindowBase
friend class ClientConnection;
public:
enum qSynergyState
{
enum qSynergyState {
synergyDisconnected,
synergyConnecting,
synergyConnected,
@ -82,34 +80,25 @@ class MainWindow : public QMainWindow, public Ui::MainWindowBase
synergyPendingRetry
};
enum qSynergyType
{
synergyClient,
synergyServer
};
enum qSynergyType { synergyClient, synergyServer };
enum qLevel {
Error,
Info
};
enum qLevel { Error, Info };
enum qRuningState {
kStarted,
kStopped
};
enum qRuningState { kStarted, kStopped };
public:
#ifdef SYNERGY_ENTERPRISE
MainWindow(AppConfig &appConfig);
#else
MainWindow(AppConfig& appConfig,
LicenseManager& licenseManager);
MainWindow(AppConfig &appConfig, LicenseManager &licenseManager);
#endif
~MainWindow();
public:
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; }
QString hostname() const { return m_pLineEditHostname->text(); }
QString configFilename();
@ -170,7 +159,9 @@ public slots:
protected:
// TODO This should be properly using the ConfigWriter system.
QSettings& settings() { return GUI::Config::ConfigWriter::make()->settings(); }
QSettings &settings() {
return GUI::Config::ConfigWriter::make()->settings();
}
AppConfig &appConfig() { return *m_AppConfig; }
AppConfig const &appConfig() const { return *m_AppConfig; }
QProcess *synergyProcess() { return m_pSynergy; }
@ -186,7 +177,8 @@ public slots:
bool clientArgs(QStringList &args, QString &app);
bool serverArgs(QStringList &args, QString &app);
void setStatus(const QString &status);
void sendIpcMessage(qIpcMessageType type, const char* buffer, bool showErrors);
void sendIpcMessage(qIpcMessageType type, const char *buffer,
bool showErrors);
void updateFromLogLine(const QString &line);
QString getIPAddresses();
void stopService();
@ -222,7 +214,6 @@ public slots:
void windowStateChanged();
private:
#ifndef SYNERGY_ENTERPRISE
LicenseManager *m_LicenseManager;
@ -246,8 +237,10 @@ public slots:
TrayIcon m_trayIcon;
qRuningState m_ExpectedRunningState;
QMutex m_StopDesktopMutex;
bool m_SecureSocket; // brief Is the program running a secure socket protocol (SSL/TLS)
QString m_SecureSocketVersion; // brief Contains the version of the Secure Socket currently active
bool m_SecureSocket; // brief Is the program running a secure socket protocol
// (SSL/TLS)
QString m_SecureSocketVersion; // brief Contains the version of the Secure
// Socket currently active
ServerConnection m_serverConnection;
ClientConnection m_clientConnection;

View file

@ -21,11 +21,7 @@
#include <QString>
enum class IconsTheme {
ICONS_DARK,
ICONS_LIGHT,
ICONS_TEMPLATE
};
enum class IconsTheme { ICONS_DARK, ICONS_LIGHT, ICONS_TEMPLATE };
void requestOSXNotificationPermission();
bool isOSXDevelopmentBuild();

View file

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

View file

@ -24,8 +24,7 @@
class QSessionManager;
class QSynergyApplication : public QApplication
{
class QSynergyApplication : public QApplication {
public:
QSynergyApplication(int &argc, char **argv);
~QSynergyApplication();
@ -44,4 +43,3 @@ class QSynergyApplication : public QApplication
};
#endif

View file

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

View file

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

View file

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

View file

@ -28,8 +28,7 @@ namespace {
* @param size of the grid
* @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 LEFT = 0;
const int RIGHT = 1;
@ -42,16 +41,26 @@ std::array<int, 8> getNeighborsIndexes(int serverIndex, int width, int size)
std::array<int, 8> indexes = {UNSET};
if (serverIndex >= 0 && serverIndex < size)
{
indexes[LEFT] = (serverIndex - 1) % width != width - 1 ? (serverIndex - 1) : UNSET;
if (serverIndex >= 0 && serverIndex < size) {
indexes[LEFT] =
(serverIndex - 1) % width != width - 1 ? (serverIndex - 1) : UNSET;
indexes[RIGHT] = (serverIndex + 1) % width != 0 ? (serverIndex + 1) : UNSET;
indexes[TOP] = (serverIndex - width) >= 0 ? (serverIndex - width) : UNSET;
indexes[BOTTOM] = (serverIndex + width) < size ? (serverIndex + width) : UNSET;
indexes[TOP_LEFT] = (indexes[TOP] != UNSET && indexes[LEFT] != UNSET) ? indexes[TOP] - 1 : 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;
indexes[BOTTOM] =
(serverIndex + width) < size ? (serverIndex + width) : UNSET;
indexes[TOP_LEFT] = (indexes[TOP] != UNSET && indexes[LEFT] != UNSET)
? indexes[TOP] - 1
: 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;
@ -62,12 +71,10 @@ std::array<int, 8> getNeighborsIndexes(int serverIndex, int width, int size)
* @param screens list to find server
* @return server index
*/
int getServerIndex(const ScreenList& screens)
{
int getServerIndex(const ScreenList &screens) {
int serverIndex = -1;
for (int i = 0; i < screens.size(); ++i)
{
for (int i = 0; i < screens.size(); ++i) {
if (screens[i].isServer()) {
serverIndex = i;
break;
@ -79,26 +86,17 @@ int getServerIndex(const ScreenList& screens)
} // namespace
ScreenList::ScreenList(int width) :
QList<Screen>(),
m_width(width)
{
ScreenList::ScreenList(int width) : QList<Screen>(), m_width(width) {}
}
void ScreenList::addScreenByPriority(const Screen& newScreen)
{
void ScreenList::addScreenByPriority(const Screen &newScreen) {
int serverIndex = getServerIndex(*this);
auto indexes = getNeighborsIndexes(serverIndex, m_width, size());
bool isAdded = false;
for (const auto& index : indexes)
{
if (index >= 0 && index < size())
{
for (const auto &index : indexes) {
if (index >= 0 && index < size()) {
auto &screen = operator[](index);
if (screen.isNull())
{
if (screen.isNull()) {
screen = newScreen;
isAdded = true;
break;
@ -106,27 +104,21 @@ void ScreenList::addScreenByPriority(const Screen& newScreen)
}
}
if (!isAdded)
{
if (!isAdded) {
addScreenToFirstEmpty(newScreen);
}
}
void ScreenList::addScreenToFirstEmpty(const Screen& newScreen)
{
for (int i = 0; i < size(); ++i)
{
void ScreenList::addScreenToFirstEmpty(const Screen &newScreen) {
for (int i = 0; i < size(); ++i) {
auto &screen = operator[](i);
if (screen.isNull())
{
if (screen.isNull()) {
screen = newScreen;
break;
}
}
}
bool ScreenList::operator==(const ScreenList& sc) const
{
bool ScreenList::operator==(const ScreenList &sc) const {
return m_width == sc.m_width && QList::operator==(sc);
}

View file

@ -20,24 +20,21 @@
#include "Screen.h"
class ScreenList : public QList<Screen>
{
class ScreenList : public QList<Screen> {
int m_width = 5;
public:
explicit ScreenList(int width = 5);
/**
* @brief addScreenByPriority adds a new screen according to the following priority:
* 1.left side of the server
* 2.right side of the server
* 3.top
* 4.down
* @brief addScreenByPriority adds a new screen according to the following
* priority: 1.left side of the server 2.right side of the server 3.top 4.down
* 5.top left-hand diagonally
* 6.top right-hand diagonally
* 7.bottom right-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
*/
void addScreenByPriority(const Screen &newScreen);

View file

@ -16,27 +16,28 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "validators/ScreenNameValidator.h"
#include "validators/AliasValidator.h"
#include "ScreenSettingsDialog.h"
#include "Screen.h"
#include "validators/AliasValidator.h"
#include "validators/ScreenNameValidator.h"
#include <QMessageBox>
#include <QtCore>
#include <QtGui>
#include <QMessageBox>
ScreenSettingsDialog::ScreenSettingsDialog(QWidget* parent, Screen* pScreen,const ScreenList* pScreens) :
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::ScreenSettingsDialogBase(),
m_pScreen(pScreen)
{
ScreenSettingsDialog::ScreenSettingsDialog(QWidget *parent, Screen *pScreen,
const ScreenList *pScreens)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
Ui::ScreenSettingsDialogBase(), m_pScreen(pScreen) {
setupUi(this);
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_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++)
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_pComboBoxSuper->setCurrentIndex(m_pScreen->modifier(Screen::Super));
m_pCheckBoxCornerTopLeft->setChecked(m_pScreen->switchCorner(Screen::TopLeft));
m_pCheckBoxCornerTopRight->setChecked(m_pScreen->switchCorner(Screen::TopRight));
m_pCheckBoxCornerBottomLeft->setChecked(m_pScreen->switchCorner(Screen::BottomLeft));
m_pCheckBoxCornerBottomRight->setChecked(m_pScreen->switchCorner(Screen::BottomRight));
m_pCheckBoxCornerTopLeft->setChecked(
m_pScreen->switchCorner(Screen::TopLeft));
m_pCheckBoxCornerTopRight->setChecked(
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_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));
}
void ScreenSettingsDialog::accept()
{
if (m_pLineEditName->text().isEmpty())
{
void ScreenSettingsDialog::accept() {
if (m_pLineEditName->text().isEmpty()) {
QMessageBox::warning(
this, tr("Screen name is empty"),
tr("The screen name cannot be empty. "
"Please either fill in a name or cancel the dialog."));
return;
}
else if (!m_pLabelNameError->text().isEmpty()) {
} else if (!m_pLabelNameError->text().isEmpty()) {
return;
}
@ -77,11 +79,9 @@ void ScreenSettingsDialog::accept()
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());
if (alias == m_pLineEditName->text())
{
if (alias == m_pLineEditName->text()) {
QMessageBox::warning(
this, tr("Screen name matches 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::Super, m_pComboBoxSuper->currentIndex());
m_pScreen->setSwitchCorner(Screen::TopLeft, m_pCheckBoxCornerTopLeft->isChecked());
m_pScreen->setSwitchCorner(Screen::TopRight, m_pCheckBoxCornerTopRight->isChecked());
m_pScreen->setSwitchCorner(Screen::BottomLeft, m_pCheckBoxCornerBottomLeft->isChecked());
m_pScreen->setSwitchCorner(Screen::BottomRight, m_pCheckBoxCornerBottomRight->isChecked());
m_pScreen->setSwitchCorner(Screen::TopLeft,
m_pCheckBoxCornerTopLeft->isChecked());
m_pScreen->setSwitchCorner(Screen::TopRight,
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->setFix(Screen::CapsLock, m_pCheckBoxCapsLock->isChecked());
@ -111,30 +115,28 @@ void ScreenSettingsDialog::accept()
QDialog::accept();
}
void ScreenSettingsDialog::on_m_pButtonAddAlias_clicked()
{
if (!m_pLineEditAlias->text().isEmpty() && m_pListAliases->findItems(m_pLineEditAlias->text(), Qt::MatchFixedString).isEmpty())
{
void ScreenSettingsDialog::on_m_pButtonAddAlias_clicked() {
if (!m_pLineEditAlias->text().isEmpty() &&
m_pListAliases->findItems(m_pLineEditAlias->text(), Qt::MatchFixedString)
.isEmpty()) {
new QListWidgetItem(m_pLineEditAlias->text(), m_pListAliases);
m_pLineEditAlias->clear();
}
}
void ScreenSettingsDialog::on_m_pLineEditAlias_textChanged(const QString& text)
{
m_pButtonAddAlias->setEnabled(!text.isEmpty() && m_pLabelAliasError->text().isEmpty());
void ScreenSettingsDialog::on_m_pLineEditAlias_textChanged(
const QString &text) {
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();
for (int i = 0; i < items.count(); i++)
delete items[i];
}
void ScreenSettingsDialog::on_m_pListAliases_itemSelectionChanged()
{
void ScreenSettingsDialog::on_m_pListAliases_itemSelectionChanged() {
m_pButtonRemoveAlias->setEnabled(!m_pListAliases->selectedItems().isEmpty());
}

View file

@ -31,12 +31,13 @@ class QString;
class Screen;
class ScreenList;
class ScreenSettingsDialog : public QDialog, public Ui::ScreenSettingsDialogBase
{
class ScreenSettingsDialog : public QDialog,
public Ui::ScreenSettingsDialogBase {
Q_OBJECT
public:
ScreenSettingsDialog(QWidget* parent, Screen* pScreen = nullptr, const ScreenList* pScreens = nullptr);
ScreenSettingsDialog(QWidget *parent, Screen *pScreen = nullptr,
const ScreenList *pScreens = nullptr);
public slots:
void accept();
@ -49,8 +50,6 @@ class ScreenSettingsDialog : public QDialog, public Ui::ScreenSettingsDialogBase
private:
Screen *m_pScreen;
};
#endif

View file

@ -24,22 +24,20 @@
const QString ScreenSetupModel::m_MimeType = "application/x-qsynergy-screen";
ScreenSetupModel::ScreenSetupModel(ScreenList& screens, int numColumns, int numRows) :
QAbstractTableModel(NULL),
m_Screens(screens),
m_NumColumns(numColumns),
m_NumRows(numRows)
{
ScreenSetupModel::ScreenSetupModel(ScreenList &screens, int numColumns,
int numRows)
: QAbstractTableModel(NULL), m_Screens(screens), m_NumColumns(numColumns),
m_NumRows(numRows) {
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
{
if (index.isValid() && index.row() < m_NumRows && index.column() < m_NumColumns)
{
switch(role)
{
QVariant ScreenSetupModel::data(const QModelIndex &index, int role) const {
if (index.isValid() && index.row() < m_NumRows &&
index.column() < m_NumColumns) {
switch (role) {
case Qt::DecorationRole:
if (screen(index).isNull())
break;
@ -48,10 +46,10 @@ QVariant ScreenSetupModel::data(const QModelIndex& index, int role) const
case Qt::ToolTipRole:
if (screen(index).isNull())
break;
return QString(tr(
"<center>Screen: <b>%1</b></center>"
return QString(tr("<center>Screen: <b>%1</b></center>"
"<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:
if (screen(index).isNull())
@ -63,29 +61,27 @@ QVariant ScreenSetupModel::data(const QModelIndex& index, int role) const
return QVariant();
}
Qt::ItemFlags ScreenSetupModel::flags(const QModelIndex& index) const
{
if (!index.isValid() || index.row() >= m_NumRows || index.column() >= m_NumColumns)
Qt::ItemFlags ScreenSetupModel::flags(const QModelIndex &index) const {
if (!index.isValid() || index.row() >= m_NumRows ||
index.column() >= m_NumColumns)
return 0;
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;
}
Qt::DropActions ScreenSetupModel::supportedDropActions() const
{
Qt::DropActions ScreenSetupModel::supportedDropActions() const {
return Qt::MoveAction | Qt::CopyAction;
}
QStringList ScreenSetupModel::mimeTypes() const
{
QStringList ScreenSetupModel::mimeTypes() const {
return QStringList() << m_MimeType;
}
QMimeData* ScreenSetupModel::mimeData(const QModelIndexList& indexes) const
{
QMimeData *ScreenSetupModel::mimeData(const QModelIndexList &indexes) const {
QMimeData *pMimeData = new QMimeData();
QByteArray encodedData;
@ -100,8 +96,9 @@ QMimeData* ScreenSetupModel::mimeData(const QModelIndexList& indexes) const
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)
return true;
@ -128,8 +125,7 @@ bool ScreenSetupModel::dropMimeData(const QMimeData* data, Qt::DropAction action
stream >> droppedScreen;
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
// see ScreenSetupView::startDrag()
oldScreen.setSwapped(true);
@ -143,17 +139,15 @@ bool ScreenSetupModel::dropMimeData(const QMimeData* data, Qt::DropAction action
return true;
}
void ScreenSetupModel::addScreen(const Screen& newScreen)
{
void ScreenSetupModel::addScreen(const Screen &newScreen) {
m_Screens.addScreenByPriority(newScreen);
emit screensChanged();
}
bool ScreenSetupModel::isFull() const
{
auto emptyScreen = std::find_if(m_Screens.cbegin(), m_Screens.cend(),
bool ScreenSetupModel::isFull() const {
auto emptyScreen =
std::find_if(m_Screens.cbegin(), m_Screens.cend(),
[](const Screen &item) { return item.isNull(); });
return (emptyScreen == m_Screens.cend());
}

View file

@ -30,8 +30,7 @@
class ScreenSetupView;
class ServerConfigDialog;
class ScreenSetupModel : public QAbstractTableModel
{
class ScreenSetupModel : public QAbstractTableModel {
Q_OBJECT
friend class ScreenSetupView;
@ -56,13 +55,21 @@ class ScreenSetupModel : public QAbstractTableModel
signals:
void screensChanged();
protected:
bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent);
const Screen& screen(const QModelIndex& index) const { return screen(index.column(), index.row()); }
Screen& screen(const QModelIndex& index) { return screen(index.column(), index.row()); }
const Screen& screen(int column, int row) const { return m_Screens[row * m_NumColumns + column]; }
Screen& screen(int column, int row) { return m_Screens[row * m_NumColumns + column]; }
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row,
int column, const QModelIndex &parent);
const Screen &screen(const QModelIndex &index) const {
return screen(index.column(), index.row());
}
Screen &screen(const QModelIndex &index) {
return screen(index.column(), index.row());
}
const Screen &screen(int column, int row) const {
return m_Screens[row * m_NumColumns + column];
}
Screen &screen(int column, int row) {
return m_Screens[row * m_NumColumns + column];
}
void addScreen(const Screen &newScreen);
private:
@ -74,4 +81,3 @@ class ScreenSetupModel : public QAbstractTableModel
};
#endif

View file

@ -17,16 +17,14 @@
*/
#include "ScreenSetupView.h"
#include "ScreenSetupModel.h"
#include "ScreenSettingsDialog.h"
#include "ScreenSetupModel.h"
#include <QHeaderView>
#include <QtCore>
#include <QtGui>
#include <QHeaderView>
ScreenSetupView::ScreenSetupView(QWidget* parent) :
QTableView(parent)
{
ScreenSetupView::ScreenSetupView(QWidget *parent) : QTableView(parent) {
setDropIndicatorShown(true);
setDragDropMode(DragDrop);
setSelectionMode(SingleSelection);
@ -39,19 +37,16 @@ ScreenSetupView::ScreenSetupView(QWidget* parent) :
verticalHeader()->hide();
}
void ScreenSetupView::setModel(QAbstractItemModel* model)
{
void ScreenSetupView::setModel(QAbstractItemModel *model) {
QTableView::setModel(model);
setTableSize();
}
ScreenSetupModel* ScreenSetupView::model() const
{
ScreenSetupModel *ScreenSetupView::model() const {
return qobject_cast<ScreenSetupModel *>(QTableView::model());
}
void ScreenSetupView::setTableSize()
{
void ScreenSetupView::setTableSize() {
for (int i = 0; i < model()->columnCount(); i++)
setColumnWidth(i, width() / model()->columnCount());
@ -59,32 +54,27 @@ void ScreenSetupView::setTableSize()
setRowHeight(i, height() / model()->rowCount());
}
void ScreenSetupView::resizeEvent(QResizeEvent* event)
{
void ScreenSetupView::resizeEvent(QResizeEvent *event) {
setTableSize();
event->ignore();
}
void ScreenSetupView::mouseDoubleClickEvent(QMouseEvent* event)
{
if (event->buttons() & Qt::LeftButton)
{
void ScreenSetupView::mouseDoubleClickEvent(QMouseEvent *event) {
if (event->buttons() & Qt::LeftButton) {
int col = columnAt(event->pos().x());
int row = rowAt(event->pos().y());
if (!model()->screen(col, row).isNull())
{
ScreenSettingsDialog dlg(this, &model()->screen(col, row), &model()->m_Screens);
if (!model()->screen(col, row).isNull()) {
ScreenSettingsDialog dlg(this, &model()->screen(col, row),
&model()->m_Screens);
dlg.exec();
emit model() -> screensChanged();
}
}
else
} else
event->ignore();
}
void ScreenSetupView::dragEnterEvent(QDragEnterEvent* event)
{
void ScreenSetupView::dragEnterEvent(QDragEnterEvent *event) {
// we accept anything that enters us by a drag as long as the
// mime type is okay. anything else is dealt with in dragMoveEvent()
if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType()))
@ -93,19 +83,14 @@ void ScreenSetupView::dragEnterEvent(QDragEnterEvent* event)
event->ignore();
}
void ScreenSetupView::dragMoveEvent(QDragMoveEvent* event)
{
if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType()))
{
void ScreenSetupView::dragMoveEvent(QDragMoveEvent *event) {
if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) {
// where does the event come from? myself or someone else?
if (event->source() == this)
{
if (event->source() == this) {
// myself is ok, but then it must be a move action, never a copy
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
{
} else {
int col = columnAt(event->pos().x());
int row = rowAt(event->pos().y());
@ -115,14 +100,12 @@ void ScreenSetupView::dragMoveEvent(QDragMoveEvent* event)
else
event->acceptProposedAction();
}
}
else
} else
event->ignore();
}
// this is reimplemented from QAbstractItemView::startDrag()
void ScreenSetupView::startDrag(Qt::DropActions)
{
void ScreenSetupView::startDrag(Qt::DropActions) {
QModelIndexList indexes = selectedIndexes();
if (indexes.count() != 1)
@ -138,8 +121,7 @@ void ScreenSetupView::startDrag(Qt::DropActions)
pDrag->setMimeData(pData);
pDrag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));
if (pDrag->exec(Qt::MoveAction, Qt::MoveAction) == Qt::MoveAction)
{
if (pDrag->exec(Qt::MoveAction, Qt::MoveAction) == Qt::MoveAction) {
selectionModel()->clear();
// make sure to only delete the drag source if screens weren't swapped
@ -153,8 +135,7 @@ void ScreenSetupView::startDrag(Qt::DropActions)
}
}
QStyleOptionViewItem ScreenSetupView::viewOptions() const
{
QStyleOptionViewItem ScreenSetupView::viewOptions() const {
QStyleOptionViewItem option = QTableView::viewOptions();
option.showDecorationSelected = true;
option.decorationPosition = QStyleOptionViewItem::Top;
@ -162,4 +143,3 @@ QStyleOptionViewItem ScreenSetupView::viewOptions() const
option.textElideMode = Qt::ElideMiddle;
return option;
}

View file

@ -20,8 +20,8 @@
#define SCREENSETUPVIEW__H
#include <QTableView>
#include <QFlags>
#include <QTableView>
#include "Screen.h"
@ -31,8 +31,7 @@ class QResizeEvent;
class QDragEnterEvent;
class ScreenSetupModel;
class ScreenSetupView : public QTableView
{
class ScreenSetupView : public QTableView {
Q_OBJECT
public:
@ -54,4 +53,3 @@ class ScreenSetupView : public QTableView
};
#endif

View file

@ -17,22 +17,20 @@
*/
#include "ServerConfig.h"
#include "AddClientDialog.h"
#include "Hotkey.h"
#include "MainWindow.h"
#include "AddClientDialog.h"
#include <QtCore>
#include <QMessageBox>
#include <QAbstractButton>
#include <QMessageBox>
#include <QPushButton>
#include <QtCore>
static const struct
{
static const struct {
int x;
int y;
const char *name;
} neighbourDirs[] =
{
} neighbourDirs[] = {
{1, 0, "right"},
{-1, 0, "left"},
{0, -1, "up"},
@ -42,25 +40,21 @@ static const struct
const int serverDefaultIndex = 7;
ServerConfig::ServerConfig(int numColumns, int numRows, AppConfig* appConfig, MainWindow* mainWindow) :
ServerConfig::ServerConfig(int numColumns, int numRows, AppConfig *appConfig,
MainWindow *mainWindow)
:
m_Screens(numColumns),
m_NumColumns(numColumns),
m_NumRows(numRows),
m_pAppConfig(appConfig),
m_IgnoreAutoConfigClient(false),
m_EnableDragAndDrop(false),
m_DisableLockToScreen(false),
m_Screens(numColumns), m_NumColumns(numColumns), m_NumRows(numRows),
m_pAppConfig(appConfig), m_IgnoreAutoConfigClient(false),
m_EnableDragAndDrop(false), m_DisableLockToScreen(false),
m_ClipboardSharing(true),
m_ClipboardSharingSize(defaultClipboardSharingSize()),
m_pMainWindow(mainWindow)
{
m_pMainWindow(mainWindow) {
GUI::Config::ConfigWriter::make()->registerClass(this);
ServerConfig::loadSettings();
}
ServerConfig::~ServerConfig()
{
ServerConfig::~ServerConfig() {
try {
ServerConfig::saveSettings();
} catch (const std::exception &e) {
@ -68,8 +62,7 @@ ServerConfig::~ServerConfig()
}
}
bool ServerConfig::save(const QString& fileName) const
{
bool ServerConfig::save(const QString &fileName) const {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
@ -80,12 +73,9 @@ bool ServerConfig::save(const QString& fileName) const
return true;
}
bool ServerConfig::operator==(const ServerConfig& sc) const
{
return m_Screens == sc.m_Screens &&
m_NumColumns == sc.m_NumColumns &&
m_NumRows == sc.m_NumRows &&
m_HasHeartbeat == sc.m_HasHeartbeat &&
bool ServerConfig::operator==(const ServerConfig &sc) const {
return m_Screens == sc.m_Screens && m_NumColumns == sc.m_NumColumns &&
m_NumRows == sc.m_NumRows && m_HasHeartbeat == sc.m_HasHeartbeat &&
m_Heartbeat == sc.m_Heartbeat &&
m_RelativeMouseMoves == sc.m_RelativeMouseMoves &&
m_Win32KeepForeground == sc.m_Win32KeepForeground &&
@ -94,8 +84,7 @@ bool ServerConfig::operator==(const ServerConfig& sc) const
m_HasSwitchDoubleTap == sc.m_HasSwitchDoubleTap &&
m_SwitchDoubleTap == sc.m_SwitchDoubleTap &&
m_SwitchCornerSize == sc.m_SwitchCornerSize &&
m_SwitchCorners == sc.m_SwitchCorners &&
m_Hotkeys == sc.m_Hotkeys &&
m_SwitchCorners == sc.m_SwitchCorners && m_Hotkeys == sc.m_Hotkeys &&
m_pAppConfig == sc.m_pAppConfig &&
m_IgnoreAutoConfigClient == sc.m_IgnoreAutoConfigClient &&
m_EnableDragAndDrop == sc.m_EnableDragAndDrop &&
@ -105,14 +94,12 @@ bool ServerConfig::operator==(const ServerConfig& sc) const
m_pMainWindow == sc.m_pMainWindow;
}
void ServerConfig::save(QFile& file) const
{
void ServerConfig::save(QFile &file) const {
QTextStream outStream(&file);
outStream << *this;
}
void ServerConfig::init()
{
void ServerConfig::init() {
switchCorners().clear();
screens().clear();
hotkeys().clear();
@ -121,14 +108,13 @@ void ServerConfig::init()
for (int i = 0; i < NumSwitchCorners; i++)
switchCorners() << false;
// There must always be screen objects for each cell in the screens QList. Unused screens
// are identified by having an empty name.
// There must always be screen objects for each cell in the screens QList.
// Unused screens are identified by having an empty name.
for (int i = 0; i < numColumns() * numRows(); i++)
addScreen(Screen());
}
void ServerConfig::saveSettings()
{
void ServerConfig::saveSettings() {
settings().beginGroup("internalConfig");
settings().remove("");
@ -148,7 +134,8 @@ void ServerConfig::saveSettings()
settings().setValue("disableLockToScreen", disableLockToScreen());
settings().setValue("enableDragAndDrop", enableDragAndDrop());
settings().setValue("clipboardSharing", clipboardSharing());
settings().setValue("clipboardSharingSize", QVariant::fromValue(clipboardSharingSize()));
settings().setValue("clipboardSharingSize",
QVariant::fromValue(clipboardSharingSize()));
if (!getClientAddress().isEmpty()) {
settings().setValue("clientAddress", getClientAddress());
@ -157,8 +144,7 @@ void ServerConfig::saveSettings()
writeSettings(settings(), switchCorners(), "switchCorner");
settings().beginWriteArray("screens");
for (int i = 0; i < screens().size(); i++)
{
for (int i = 0; i < screens().size(); i++) {
settings().setArrayIndex(i);
auto &screen = screens()[i];
screen.saveSettings(settings());
@ -169,8 +155,7 @@ void ServerConfig::saveSettings()
settings().endArray();
settings().beginWriteArray("hotkeys");
for (int i = 0; i < hotkeys().size(); i++)
{
for (int i = 0; i < hotkeys().size(); i++) {
settings().setArrayIndex(i);
hotkeys()[i].saveSettings(settings());
}
@ -183,39 +168,45 @@ void ServerConfig::saveSettings()
GUI::Config::ConfigWriter::make()->markUnsaved();
}
void ServerConfig::loadSettings()
{
void ServerConfig::loadSettings() {
settings().beginGroup("internalConfig");
setNumColumns(settings().value("numColumns", 5).toInt());
setNumRows(settings().value("numRows", 3).toInt());
// we need to know the number of columns and rows before we can set up ourselves
// we need to know the number of columns and rows before we can set up
// ourselves
init();
haveHeartbeat(settings().value("hasHeartbeat", false).toBool());
setHeartbeat(settings().value("heartbeat", 5000).toInt());
setRelativeMouseMoves(settings().value("relativeMouseMoves", false).toBool());
setWin32KeepForeground(settings().value("win32KeepForeground", false).toBool());
setWin32KeepForeground(
settings().value("win32KeepForeground", false).toBool());
haveSwitchDelay(settings().value("hasSwitchDelay", false).toBool());
setSwitchDelay(settings().value("switchDelay", 250).toInt());
haveSwitchDoubleTap(settings().value("hasSwitchDoubleTap", false).toBool());
setSwitchDoubleTap(settings().value("switchDoubleTap", 250).toInt());
setSwitchCornerSize(settings().value("switchCornerSize").toInt());
setIgnoreAutoConfigClient(settings().value("ignoreAutoConfigClient").toBool());
setDisableLockToScreen(settings().value("disableLockToScreen", false).toBool());
setIgnoreAutoConfigClient(
settings().value("ignoreAutoConfigClient").toBool());
setDisableLockToScreen(
settings().value("disableLockToScreen", false).toBool());
setEnableDragAndDrop(settings().value("enableDragAndDrop", false).toBool());
setClipboardSharingSize(settings().value("clipboardSharingSize",
(int) ServerConfig::defaultClipboardSharingSize()).toULongLong());
setClipboardSharingSize(
settings()
.value("clipboardSharingSize",
(int)ServerConfig::defaultClipboardSharingSize())
.toULongLong());
setClipboardSharing(settings().value("clipboardSharing", true).toBool());
setClientAddress(settings().value("clientAddress", "").toString());
readSettings(settings(), switchCorners(), "switchCorner", false, NumSwitchCorners);
readSettings(settings(), switchCorners(), "switchCorner", false,
NumSwitchCorners);
int numScreens = settings().beginReadArray("screens");
Q_ASSERT(numScreens <= screens().size());
for (int i = 0; i < numScreens; i++)
{
for (int i = 0; i < numScreens; i++) {
settings().setArrayIndex(i);
screens()[i].loadSettings(settings());
if (getServerName() == screens()[i].name()) {
@ -225,8 +216,7 @@ void ServerConfig::loadSettings()
settings().endArray();
int numHotkeys = settings().beginReadArray("hotkeys");
for (int i = 0; i < numHotkeys; i++)
{
for (int i = 0; i < numHotkeys; i++) {
settings().setArrayIndex(i);
Hotkey h;
h.loadSettings(settings());
@ -237,14 +227,15 @@ void ServerConfig::loadSettings()
settings().endGroup();
}
int ServerConfig::adjacentScreenIndex(int idx, int deltaColumn, int deltaRow) const
{
int ServerConfig::adjacentScreenIndex(int idx, int deltaColumn,
int deltaRow) const {
if (screens()[idx].isNull())
return -1;
// if we're at the left or right end of the table, don't find results going further left or right
if ((deltaColumn > 0 && (idx+1) % numColumns() == 0)
|| (deltaColumn < 0 && idx % numColumns() == 0))
// if we're at the left or right end of the table, don't find results going
// further left or right
if ((deltaColumn > 0 && (idx + 1) % numColumns() == 0) ||
(deltaColumn < 0 && idx % numColumns() == 0))
return -1;
int arrayPos = idx + deltaColumn + deltaRow * numColumns();
@ -255,8 +246,7 @@ int ServerConfig::adjacentScreenIndex(int idx, int deltaColumn, int deltaRow) co
return arrayPos;
}
QTextStream& operator<<(QTextStream& outStream, const ServerConfig& config)
{
QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config) {
outStream << "section: screens" << endl;
foreach (const Screen &s, config.screens())
@ -276,15 +266,16 @@ QTextStream& operator<<(QTextStream& outStream, const ServerConfig& config)
outStream << "section: links" << endl;
for (int i = 0; i < config.screens().size(); i++)
if (!config.screens()[i].isNull())
{
if (!config.screens()[i].isNull()) {
outStream << "\t" << config.screens()[i].name() << ":" << endl;
for (unsigned int j = 0; j < sizeof(neighbourDirs) / sizeof(neighbourDirs[0]); j++)
{
int idx = config.adjacentScreenIndex(i, neighbourDirs[j].x, neighbourDirs[j].y);
for (unsigned int j = 0;
j < sizeof(neighbourDirs) / sizeof(neighbourDirs[0]); j++) {
int idx = config.adjacentScreenIndex(i, neighbourDirs[j].x,
neighbourDirs[j].y);
if (idx != -1 && !config.screens()[idx].isNull())
outStream << "\t\t" << neighbourDirs[j].name << " = " << config.screens()[idx].name() << endl;
outStream << "\t\t" << neighbourDirs[j].name << " = "
<< config.screens()[idx].name() << endl;
}
}
@ -293,31 +284,47 @@ QTextStream& operator<<(QTextStream& outStream, const ServerConfig& config)
outStream << "section: options" << endl;
if (config.hasHeartbeat())
outStream << "\t" << "heartbeat = " << config.heartbeat() << endl;
outStream << "\t"
<< "heartbeat = " << config.heartbeat() << endl;
outStream << "\t" << "relativeMouseMoves = " << (config.relativeMouseMoves() ? "true" : "false") << endl;
outStream << "\t" << "win32KeepForeground = " << (config.win32KeepForeground() ? "true" : "false") << endl;
outStream << "\t" << "disableLockToScreen = " << (config.disableLockToScreen() ? "true" : "false") << endl;
outStream << "\t" << "clipboardSharing = " << (config.clipboardSharing() ? "true" : "false") << endl;
outStream << "\t" << "clipboardSharingSize = " << config.clipboardSharingSize() << endl;
outStream << "\t"
<< "relativeMouseMoves = "
<< (config.relativeMouseMoves() ? "true" : "false") << endl;
outStream << "\t"
<< "win32KeepForeground = "
<< (config.win32KeepForeground() ? "true" : "false") << endl;
outStream << "\t"
<< "disableLockToScreen = "
<< (config.disableLockToScreen() ? "true" : "false") << endl;
outStream << "\t"
<< "clipboardSharing = "
<< (config.clipboardSharing() ? "true" : "false") << endl;
outStream << "\t"
<< "clipboardSharingSize = " << config.clipboardSharingSize()
<< endl;
if (!config.getClientAddress().isEmpty()) {
outStream << "\t" << "clientAddress = " << config.getClientAddress() << endl;
outStream << "\t"
<< "clientAddress = " << config.getClientAddress() << endl;
}
if (config.hasSwitchDelay())
outStream << "\t" << "switchDelay = " << config.switchDelay() << endl;
outStream << "\t"
<< "switchDelay = " << config.switchDelay() << endl;
if (config.hasSwitchDoubleTap())
outStream << "\t" << "switchDoubleTap = " << config.switchDoubleTap() << endl;
outStream << "\t"
<< "switchDoubleTap = " << config.switchDoubleTap() << endl;
outStream << "\t" << "switchCorners = none ";
outStream << "\t"
<< "switchCorners = none ";
for (int i = 0; i < config.switchCorners().size(); i++)
if (config.switchCorners()[i])
outStream << "+" << config.switchCornerName(i) << " ";
outStream << endl;
outStream << "\t" << "switchCornerSize = " << config.switchCornerSize() << endl;
outStream << "\t"
<< "switchCornerSize = " << config.switchCornerSize() << endl;
foreach (const Hotkey &hotkey, config.hotkeys())
outStream << hotkey;
@ -327,8 +334,7 @@ QTextStream& operator<<(QTextStream& outStream, const ServerConfig& config)
return outStream;
}
int ServerConfig::numScreens() const
{
int ServerConfig::numScreens() const {
int rval = 0;
foreach (const Screen &s, screens())
@ -338,18 +344,17 @@ int ServerConfig::numScreens() const
return rval;
}
int ServerConfig::autoAddScreen(const QString name)
{
int ServerConfig::autoAddScreen(const QString name) {
int serverIndex = -1;
int targetIndex = -1;
if (!findScreenName(m_pAppConfig->screenName(), serverIndex) &&
!fixNoServer(m_pAppConfig->screenName(), serverIndex))
{
!fixNoServer(m_pAppConfig->screenName(), serverIndex)) {
return kAutoAddScreenManualServer;
}
if (findScreenName(name, targetIndex)) {
m_pMainWindow->appendLogDebug(QString("ignoring screen already in config: %1").arg(name));
m_pMainWindow->appendLogDebug(
QString("ignoring screen already in config: %1").arg(name));
return kAutoAddScreenIgnore;
}
@ -372,17 +377,14 @@ int ServerConfig::autoAddScreen(const QString name)
if (result == kAddClientLeft) {
offset = -1;
dirIndex = 1;
}
else if (result == kAddClientUp) {
} else if (result == kAddClientUp) {
offset = -5;
dirIndex = 2;
}
else if (result == kAddClientDown) {
} else if (result == kAddClientDown) {
offset = 5;
dirIndex = 3;
}
int idx = adjacentScreenIndex(startIndex, neighbourDirs[dirIndex].x,
neighbourDirs[dirIndex].y);
while (idx != -1) {
@ -406,13 +408,11 @@ int ServerConfig::autoAddScreen(const QString name)
return kAutoAddScreenOk;
}
const QString& ServerConfig::getServerName() const
{
const QString &ServerConfig::getServerName() const {
return m_pAppConfig->screenName();
}
void ServerConfig::updateServerName()
{
void ServerConfig::updateServerName() {
for (auto &screen : screens()) {
if (screen.isServer()) {
screen.setName(m_pAppConfig->screenName());
@ -422,24 +422,19 @@ void ServerConfig::updateServerName()
}
}
const QString& ServerConfig::getConfigFile() const
{
const QString &ServerConfig::getConfigFile() const {
return m_pAppConfig->getConfigFile();
}
bool ServerConfig::getUseExternalConfig() const
{
bool ServerConfig::getUseExternalConfig() const {
return m_pAppConfig->getUseExternalConfig();
}
bool ServerConfig::isFull() const
{
bool ServerConfig::isFull() const {
bool isFull = true;
for (const auto& screen : screens())
{
if (screen.isNull())
{
for (const auto &screen : screens()) {
if (screen.isNull()) {
isFull = false;
break;
}
@ -448,15 +443,11 @@ bool ServerConfig::isFull() const
return isFull;
}
bool ServerConfig::isScreenExists(const QString& screenName) const
{
bool ServerConfig::isScreenExists(const QString &screenName) const {
bool isExists = false;
for (const auto& screen : screens())
{
if (!screen.isNull() &&
screen.name() == screenName)
{
for (const auto &screen : screens()) {
if (!screen.isNull() && screen.name() == screenName) {
isExists = true;
break;
}
@ -465,38 +456,30 @@ bool ServerConfig::isScreenExists(const QString& screenName) const
return isExists;
}
void ServerConfig::addClient(const QString& clientName)
{
void ServerConfig::addClient(const QString &clientName) {
int serverIndex = -1;
if (findScreenName(m_pAppConfig->screenName(), serverIndex))
{
if (findScreenName(m_pAppConfig->screenName(), serverIndex)) {
m_Screens[serverIndex].markAsServer();
}
else
{
} else {
fixNoServer(m_pAppConfig->screenName(), serverIndex);
}
m_Screens.addScreenByPriority(clientName);
}
void ServerConfig::setConfigFile(const QString& configFile)
{
void ServerConfig::setConfigFile(const QString &configFile) {
m_pAppConfig->setConfigFile(configFile);
}
void ServerConfig::setUseExternalConfig(bool useExternalConfig)
{
void ServerConfig::setUseExternalConfig(bool useExternalConfig) {
m_pAppConfig->setUseExternalConfig(useExternalConfig);
}
bool ServerConfig::findScreenName(const QString& name, int& index)
{
bool ServerConfig::findScreenName(const QString &name, int &index) {
bool found = false;
for (int i = 0; i < screens().size(); i++) {
if (!screens()[i].isNull() &&
screens()[i].name().compare(name) == 0) {
if (!screens()[i].isNull() && screens()[i].name().compare(name) == 0) {
index = i;
found = true;
break;
@ -505,8 +488,7 @@ bool ServerConfig::findScreenName(const QString& name, int& index)
return found;
}
bool ServerConfig::fixNoServer(const QString& name, int& index)
{
bool ServerConfig::fixNoServer(const QString &name, int &index) {
bool fixed = false;
if (screens()[serverDefaultIndex].isNull()) {
m_Screens[serverDefaultIndex].setName(name);
@ -518,8 +500,7 @@ bool ServerConfig::fixNoServer(const QString& name, int& index)
return fixed;
}
int ServerConfig::showAddClientDialog(const QString& clientName)
{
int ServerConfig::showAddClientDialog(const QString &clientName) {
int result = kAddClientIgnore;
if (!m_pMainWindow->isActiveWindow()) {
@ -535,8 +516,7 @@ int ServerConfig::showAddClientDialog(const QString& clientName)
return result;
}
void::ServerConfig::addToFirstEmptyGrid(const QString &clientName)
{
void ::ServerConfig::addToFirstEmptyGrid(const QString &clientName) {
for (int i = 0; i < screens().size(); i++) {
if (screens()[i].isNull()) {
m_Screens[i].setName(clientName);

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