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

* Lint script with CLang format

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

* Apply LLVM CLang formatting

* Fixed comment

* Update ChangeLog

* Fixed bad return code logic

* Improve output for linters

* Fixed re-used var in clang lint

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

* Use full Clang format dump

* Dump Ubuntu Clang format

* Dump Clang format from Debian

* Dumped from: clang-format version 18.1.8

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

This reverts commit b9bbda2995bb0b4b65baf14afebb0361ec64e644.

* Remove BasedOnStyle

* Restore base Clang format file

* Use clang-format from pip

* Apply Clang format 18 style

* Add clang_format deps

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

11
.clang-format Normal file
View file

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

View file

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

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

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

View file

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

View file

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

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

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

57
scripts/lint_clang.py Executable file
View file

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

59
scripts/lint_cmake.py Executable file
View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -16,15 +16,14 @@
*/ */
#pragma once #pragma once
#include <QObject>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QObject>
class QNetworkReply; class QNetworkReply;
class MainWindow; class MainWindow;
class AppConfig; class AppConfig;
class CreditsLoader : public QObject class CreditsLoader : public QObject {
{
Q_OBJECT Q_OBJECT
public: public:
explicit CreditsLoader(MainWindow &mainWindow, const AppConfig &config); explicit CreditsLoader(MainWindow &mainWindow, const AppConfig &config);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -23,13 +23,10 @@
// this table originally comes from Qt sources (gui/kernel/qkeysequence.cpp) // this table originally comes from Qt sources (gui/kernel/qkeysequence.cpp)
// and is heavily modified for QSynergy // and is heavily modified for QSynergy
static const struct static const struct {
{
int key; int key;
const char *name; const char *name;
} keyname[] = } keyname[] = {{Qt::Key_Space, "Space"},
{
{ Qt::Key_Space, "Space" },
{Qt::Key_Escape, "Escape"}, {Qt::Key_Escape, "Escape"},
{Qt::Key_Tab, "Tab"}, {Qt::Key_Tab, "Tab"},
{Qt::Key_Backtab, "LeftTab"}, {Qt::Key_Backtab, "LeftTab"},
@ -77,27 +74,18 @@ static const struct
{Qt::Key_Launch1, "AppUser2"}, {Qt::Key_Launch1, "AppUser2"},
{Qt::Key_Select, "Select"}, {Qt::Key_Select, "Select"},
{ 0, 0 } {0, 0}};
};
KeySequence::KeySequence() : KeySequence::KeySequence() : m_Sequence(), m_Modifiers(0), m_IsValid(false) {}
m_Sequence(),
m_Modifiers(0),
m_IsValid(false)
{
}
bool KeySequence::isMouseButton() const bool KeySequence::isMouseButton() const {
{
return !m_Sequence.isEmpty() && m_Sequence.last() < Qt::Key_Space; return !m_Sequence.isEmpty() && m_Sequence.last() < Qt::Key_Space;
} }
QString KeySequence::toString() const QString KeySequence::toString() const {
{
QString result; QString result;
for (int i = 0; i < m_Sequence.size(); i++) for (int i = 0; i < m_Sequence.size(); i++) {
{
result += keyToString(m_Sequence[i]); result += keyToString(m_Sequence[i]);
if (i != m_Sequence.size() - 1) if (i != m_Sequence.size() - 1)
@ -107,18 +95,13 @@ QString KeySequence::toString() const
return result; return result;
} }
bool KeySequence::appendMouseButton(int button) bool KeySequence::appendMouseButton(int button) { return appendKey(button, 0); }
{
return appendKey(button, 0);
}
bool KeySequence::appendKey(int key, int modifiers) bool KeySequence::appendKey(int key, int modifiers) {
{
if (m_Sequence.size() == 4) if (m_Sequence.size() == 4)
return true; return true;
switch(key) switch (key) {
{
case Qt::Key_AltGr: case Qt::Key_AltGr:
return false; return false;
@ -126,16 +109,13 @@ bool KeySequence::appendKey(int key, int modifiers)
case Qt::Key_Alt: case Qt::Key_Alt:
case Qt::Key_Shift: case Qt::Key_Shift:
case Qt::Key_Meta: case Qt::Key_Meta:
case Qt::Key_Menu: case Qt::Key_Menu: {
{
int mod = modifiers & (~m_Modifiers); int mod = modifiers & (~m_Modifiers);
if (mod) if (mod) {
{
m_Sequence.append(mod); m_Sequence.append(mod);
m_Modifiers |= mod; m_Modifiers |= mod;
} }
} } break;
break;
default: default:
// see if we can handle this key, if not, don't accept it // see if we can handle this key, if not, don't accept it
@ -150,12 +130,10 @@ bool KeySequence::appendKey(int key, int modifiers)
return false; return false;
} }
void KeySequence::loadSettings(QSettings& settings) void KeySequence::loadSettings(QSettings &settings) {
{
sequence().clear(); sequence().clear();
int num = settings.beginReadArray("keys"); int num = settings.beginReadArray("keys");
for (int i = 0; i < num; i++) for (int i = 0; i < num; i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
sequence().append(settings.value("key", 0).toInt()); sequence().append(settings.value("key", 0).toInt());
} }
@ -165,34 +143,33 @@ void KeySequence::loadSettings(QSettings& settings)
setValid(true); setValid(true);
} }
void KeySequence::saveSettings(QSettings& settings) const void KeySequence::saveSettings(QSettings &settings) const {
{
settings.beginWriteArray("keys"); settings.beginWriteArray("keys");
for (int i = 0; i < sequence().size(); i++) for (int i = 0; i < sequence().size(); i++) {
{
settings.setArrayIndex(i); settings.setArrayIndex(i);
settings.setValue("key", sequence()[i]); settings.setValue("key", sequence()[i]);
} }
settings.endArray(); settings.endArray();
} }
QString KeySequence::keyToString(int key) QString KeySequence::keyToString(int key) {
{
// nothing there? // nothing there?
if (key == 0) if (key == 0)
return ""; return "";
// a hack to handle mouse buttons as if they were keys // a hack to handle mouse buttons as if they were keys
if (key < Qt::Key_Space) if (key < Qt::Key_Space) {
{ switch (key) {
switch(key) case Qt::LeftButton:
{ return "1";
case Qt::LeftButton: return "1"; case Qt::RightButton:
case Qt::RightButton: return "2"; return "2";
case Qt::MidButton: return "3"; case Qt::MidButton:
return "3";
} }
return "4"; // qt only knows three mouse buttons, so assume it's an unknown fourth one return "4"; // qt only knows three mouse buttons, so assume it's an unknown
// fourth one
} }
// modifiers? // modifiers?
@ -208,7 +185,8 @@ QString KeySequence::keyToString(int key)
if (key & Qt::MetaModifier) if (key & Qt::MetaModifier)
return "Meta"; return "Meta";
// treat key pad like normal keys (FIXME: we should have another lookup table for keypad keys instead) // treat key pad like normal keys (FIXME: we should have another lookup table
// for keypad keys instead)
key &= ~Qt::KeypadModifier; key &= ~Qt::KeypadModifier;
// a printable 7 bit character? // a printable 7 bit character?
@ -221,8 +199,7 @@ QString KeySequence::keyToString(int key)
// a special key? // a special key?
int i = 0; int i = 0;
while (keyname[i].name) while (keyname[i].name) {
{
if (key == keyname[i].key) if (key == keyname[i].key)
return QString::fromUtf8(keyname[i].name); return QString::fromUtf8(keyname[i].name);
i++; i++;
@ -230,15 +207,14 @@ QString KeySequence::keyToString(int key)
// representable in ucs2? // representable in ucs2?
if (key < 0x10000) if (key < 0x10000)
return QString("\\u%1").arg(QChar(key).toLower().unicode(), 4, 16, QChar('0')); return QString("\\u%1").arg(QChar(key).toLower().unicode(), 4, 16,
QChar('0'));
// give up, synergy probably won't handle this // give up, synergy probably won't handle this
return ""; return "";
} }
bool KeySequence::operator==(const KeySequence& ks) const bool KeySequence::operator==(const KeySequence &ks) const {
{ return m_Sequence == ks.m_Sequence && m_Modifiers == ks.m_Modifiers &&
return m_Sequence == ks.m_Sequence &&
m_Modifiers == ks.m_Modifiers &&
m_IsValid == ks.m_IsValid; m_IsValid == ks.m_IsValid;
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -20,9 +20,9 @@
#define SCREEN__H #define SCREEN__H
#include <QList>
#include <QPixmap> #include <QPixmap>
#include <QString> #include <QString>
#include <QList>
#include <QStringList> #include <QStringList>
#include "BaseConfig.h" #include "BaseConfig.h"
@ -32,8 +32,7 @@ class QTextStream;
class ScreenSettingsDialog; class ScreenSettingsDialog;
class Screen : public BaseConfig class Screen : public BaseConfig {
{
friend QDataStream &operator<<(QDataStream &outStream, const Screen &screen); friend QDataStream &operator<<(QDataStream &outStream, const Screen &screen);
friend QDataStream &operator>>(QDataStream &inStream, Screen &screen); friend QDataStream &operator>>(QDataStream &inStream, Screen &screen);
friend class ScreenSettingsDialog; friend class ScreenSettingsDialog;
@ -50,7 +49,9 @@ class Screen : public BaseConfig
const QStringList &aliases() const { return m_Aliases; } const QStringList &aliases() const { return m_Aliases; }
bool isNull() const { return m_Name.isEmpty(); } bool isNull() const { return m_Name.isEmpty(); }
int modifier(int m) const { return m_Modifiers[m] == DefaultMod ? m : m_Modifiers[m]; } int modifier(int m) const {
return m_Modifiers[m] == DefaultMod ? m : m_Modifiers[m];
}
const QList<int> &modifiers() const { return m_Modifiers; } const QList<int> &modifiers() const { return m_Modifiers; }
bool switchCorner(int c) const { return m_SwitchCorners[c]; } bool switchCorner(int c) const { return m_SwitchCorners[c]; }
const QList<bool> &switchCorners() const { return m_SwitchCorners; } const QList<bool> &switchCorners() const { return m_SwitchCorners; }
@ -103,4 +104,3 @@ QDataStream& operator<<(QDataStream& outStream, const Screen& screen);
QDataStream &operator>>(QDataStream &inStream, Screen &screen); QDataStream &operator>>(QDataStream &inStream, Screen &screen);
#endif #endif

View file

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

View file

@ -20,24 +20,21 @@
#include "Screen.h" #include "Screen.h"
class ScreenList : public QList<Screen> class ScreenList : public QList<Screen> {
{
int m_width = 5; int m_width = 5;
public: public:
explicit ScreenList(int width = 5); explicit ScreenList(int width = 5);
/** /**
* @brief addScreenByPriority adds a new screen according to the following priority: * @brief addScreenByPriority adds a new screen according to the following
* 1.left side of the server * priority: 1.left side of the server 2.right side of the server 3.top 4.down
* 2.right side of the server
* 3.top
* 4.down
* 5.top left-hand diagonally * 5.top left-hand diagonally
* 6.top right-hand diagonally * 6.top right-hand diagonally
* 7.bottom right-hand diagonally * 7.bottom right-hand diagonally
* 8.bottom left-hand diagonally * 8.bottom left-hand diagonally
* 9.In case all places from the list have already booked, place in any spare place * 9.In case all places from the list have already booked, place in any spare
* place
* @param newScreen * @param newScreen
*/ */
void addScreenByPriority(const Screen &newScreen); void addScreenByPriority(const Screen &newScreen);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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