Merge branch 'master' into feature/websocketnavigation

This merge changes the default websocket port from 8001 to 4862.
This commit is contained in:
Matthew Territo
2019-02-13 12:18:28 -07:00
60 changed files with 863 additions and 206 deletions

8
Jenkinsfile vendored
View File

@@ -36,7 +36,7 @@ stage('Build') {
cd build
cmake .. ''' +
flags + ''' ..
make -j4 OpenSpace
make -j4 OpenSpace GhoulTest OpenSpaceTest
'''
}
}
@@ -45,7 +45,7 @@ stage('Build') {
node('windows') {
timeout(time: 90, unit: 'MINUTES') {
// We specify the workspace directory manually to reduce the path length and thus try to avoid MSB3491 on Visual Studio
ws("C:/J/O/${env.BRANCH_NAME}/${env.BUILD_ID}") {
ws("${env.JENKINS_BASE}/O/${env.BRANCH_NAME}/${env.BUILD_ID}") {
deleteDir()
checkout scm
bat '''
@@ -54,7 +54,7 @@ stage('Build') {
cd build
cmake -G "Visual Studio 15 2017 Win64" .. ''' +
flags + ''' ..
msbuild.exe OpenSpace.sln /nologo /verbosity:minimal /p:Configuration=Debug /target:OpenSpace
msbuild.exe OpenSpace.sln /nologo /verbosity:minimal /p:Configuration=Debug /target:OpenSpace /target:"Unit Tests"\\GhoulTest /target:"Unit Tests"\\OpenSpaceTest
'''
}
}
@@ -79,7 +79,7 @@ stage('Build') {
cd ${srcDir}/build
/Applications/CMake.app/Contents/bin/cmake -G Xcode ${srcDir} .. ''' +
flags + '''
xcodebuild -quiet -parallelizeTargets -jobs 4
xcodebuild -parallelizeTargets -jobs 4 -target OpenSpace -target GhoulTest -target OpenSpaceTest
'''
}
}

View File

@@ -548,11 +548,12 @@ void mainKeyboardCallback(int key, int, int action, int mods) {
void mainMouseButtonCallback(int key, int action) {
void mainMouseButtonCallback(int key, int action, int modifiers) {
LTRACE("main::mainMouseButtonCallback(begin)");
openspace::global::openSpaceEngine.mouseButtonCallback(
openspace::MouseButton(key),
openspace::MouseAction(action)
openspace::MouseAction(action),
openspace::KeyModifier(modifiers)
);
LTRACE("main::mainMouseButtonCallback(end)");
}

View File

@@ -28,6 +28,7 @@
<Window fullScreen="false" msaa="1" name="GUI" tags="GUI">
<Stereo type="none" />
<Size x="1280" y="720" />
<Res x="2048" y="2048" />
<Pos x="50" y="50" />
<Viewport>
<Pos x="0.0" y="0.0" />

View File

@@ -1,8 +1,8 @@
local guiCustomization = asset.require('customization/gui')
-- Select which commit hashes to use for the frontend and backend
local frontendHash = "f6db6a5dd79df1e310a75d50f8b1f97aea8a9596"
local backendHash = "3e862a67ff2869d83187ad8bda05746b583d13d4"
local frontendHash = "abf5fe23ef29af408d6c071057f1cc706c9b09a3"
local backendHash = "6e773425b3e90ba93f0090e44427e474fe5c633f"
local dataProvider = "data.openspaceproject.com/files/webgui"
@@ -10,7 +10,7 @@ local backend = asset.syncedResource({
Identifier = "WebGuiBackend",
Name = "Web Gui Backend",
Type = "UrlSynchronization",
Url = dataProvider .. "/backend/" .. backendHash .. "/backend.js"
Url = dataProvider .. "/backend/" .. backendHash .. "/backend.zip"
})
local frontend = asset.syncedResource({
@@ -26,14 +26,21 @@ asset.onInitialize(function ()
if not openspace.directoryExists(dest) then
openspace.unzipFile(frontend .. "/frontend.zip", dest, true)
end
-- Unzip the frontend bundle
dest = backend .. "/backend"
if not openspace.directoryExists(dest) then
openspace.unzipFile(backend .. "/backend.zip", dest, true)
end
-- Do not serve the files if we are in webgui development mode.
-- In that case, you have to serve the webgui manually, using `npm start`.
if not guiCustomization.webguiDevelopmentMode then
openspace.setPropertyValueSingle(
"Modules.WebGui.ServerProcessEntryPoint", backend .. "/backend.js"
"Modules.WebGui.ServerProcessEntryPoint", backend .. "/backend/backend.js"
)
openspace.setPropertyValueSingle(
"Modules.WebGui.ServerProcessWorkingDirectory", frontend .. "/frontend"
"Modules.WebGui.WebDirectory", frontend .. "/frontend"
)
openspace.setPropertyValueSingle("Modules.WebGui.ServerProcessEnabled", true)
end

View File

@@ -105,10 +105,6 @@ struct Configuration {
};
OpenGLDebugContext openGLDebugContext;
std::string serverPasskey = "17308";
bool doesRequireSocketAuthentication = true;
std::vector<std::string> clientAddressWhitelist = {};
struct HTTPProxy {
bool usingHttpProxy = false;
std::string address;

View File

@@ -49,7 +49,7 @@ std::vector<std::function<void()>>& gPostDraw();
std::vector<std::function<bool(Key, KeyModifier, KeyAction)>>& gKeyboard();
std::vector<std::function<bool(unsigned int, KeyModifier)>>& gCharacter();
std::vector<std::function<bool(MouseButton, MouseAction)>>& gMouseButton();
std::vector<std::function<bool(MouseButton, MouseAction, KeyModifier)>>& gMouseButton();
std::vector<std::function<void(double, double)>>& gMousePosition();
std::vector<std::function<bool(double, double)>>& gMouseScrollWheel();
@@ -70,8 +70,8 @@ static std::vector<std::function<bool(Key, KeyModifier, KeyAction)>>& keyboard =
detail::gKeyboard();
static std::vector<std::function<bool(unsigned int, KeyModifier)>>& character =
detail::gCharacter();
static std::vector<std::function<bool(MouseButton, MouseAction)>>& mouseButton =
detail::gMouseButton();
static std::vector<std::function<bool(MouseButton, MouseAction, KeyModifier)>>&
mouseButton = detail::gMouseButton();
static std::vector<std::function<void(double, double)>>& mousePosition =
detail::gMousePosition();
static std::vector<std::function<bool(double, double)>>& mouseScrollWheel =

View File

@@ -76,7 +76,7 @@ public:
void postDraw();
void keyboardCallback(Key key, KeyModifier mod, KeyAction action);
void charCallback(unsigned int codepoint, KeyModifier modifier);
void mouseButtonCallback(MouseButton button, MouseAction action);
void mouseButtonCallback(MouseButton button, MouseAction action, KeyModifier mods);
void mousePositionCallback(double x, double y);
void mouseScrollWheelCallback(double posX, double posY);
void externalControlCallback(const char* receivedChars, int size, int clientId);

View File

@@ -308,8 +308,9 @@ bool NumericalProperty<T>::setLuaValue(lua_State* state) {
T value = PropertyDelegate<NumericalProperty<T>>::template fromLuaValue<T>(
state, success
);
if (success)
if (success) {
TemplateProperty<T>::setValue(std::move(value));
}
return success;
}
@@ -340,8 +341,9 @@ bool NumericalProperty<T>::setStringValue(std::string value) {
T thisValue = PropertyDelegate<NumericalProperty<T>>::template fromString<T>(
value, success
);
if (success)
if (success) {
TemplateProperty<T>::set(ghoul::any(std::move(thisValue)));
}
return success;
}
@@ -402,7 +404,7 @@ std::string NumericalProperty<T>::generateAdditionalJsonDescription() const {
template <typename T>
std::string NumericalProperty<T>::luaToJson(std::string luaValue) const {
if(luaValue[0] == '{') {
if (luaValue[0] == '{') {
luaValue.replace(0, 1, "[");
}
if (luaValue[luaValue.size() - 1] == '}') {

View File

@@ -218,6 +218,7 @@ protected:
size_t handleData(HttpRequest::Data d) override;
static std::mutex _directoryCreationMutex;
std::atomic_bool _hasHandle = false;
private:
std::string _destination;

View File

@@ -22,9 +22,10 @@
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/webbrowser/webbrowsermodule.h>
#include <modules/cefwebgui/cefwebguimodule.h>
#include <modules/webbrowser/webbrowsermodule.h>
#include <modules/webgui/webguimodule.h>
#include <modules/cefwebgui/include/guirenderhandler.h>
#include <modules/cefwebgui/include/guikeyboardhandler.h>
#include <modules/webbrowser/include/browserinstance.h>
@@ -56,6 +57,12 @@ namespace {
"GUI URL",
"The URL of the webpage that is used to load the WebGUI from."
};
constexpr openspace::properties::Property::PropertyInfo GuiScaleInfo = {
"GuiScale",
"Gui Scale",
"GUI scale multiplier."
};
} // namespace
namespace openspace {
@@ -65,10 +72,12 @@ CefWebGuiModule::CefWebGuiModule()
, _enabled(EnabledInfo, true)
, _visible(VisibleInfo, true)
, _url(GuiUrlInfo, "")
, _guiScale(GuiScaleInfo, 1.0, 0.1, 3.0)
{
addProperty(_enabled);
addProperty(_visible);
addProperty(_url);
addProperty(_guiScale);
}
void CefWebGuiModule::startOrStopGui() {
@@ -94,6 +103,9 @@ void CefWebGuiModule::startOrStopGui() {
if (_visible) {
webBrowserModule->attachEventHandler(_instance.get());
}
_instance->setZoom(_guiScale);
webBrowserModule->addBrowser(_instance.get());
} else if (_instance) {
_instance->close(true);
@@ -123,6 +135,12 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration)
}
});
_guiScale.onChange([this]() {
if (_instance) {
_instance->setZoom(_guiScale);
}
});
_visible.onChange([this, webBrowserModule]() {
if (_visible && _instance) {
webBrowserModule->attachEventHandler(_instance.get());
@@ -131,7 +149,17 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration)
}
});
_url = configuration.value<std::string>(GuiUrlInfo.identifier);
if (configuration.hasValue<std::string>(GuiUrlInfo.identifier)) {
_url = configuration.value<std::string>(GuiUrlInfo.identifier);
} else {
WebGuiModule* webGuiModule = global::moduleEngine.module<WebGuiModule>();
_url = "http://localhost:" +
std::to_string(webGuiModule->port()) + "/#/onscreen";
}
if (configuration.hasValue<float>(GuiScaleInfo.identifier)) {
_guiScale = configuration.value<float>(GuiScaleInfo.identifier);
}
_enabled = configuration.hasValue<bool>(EnabledInfo.identifier) &&
configuration.value<bool>(EnabledInfo.identifier);

View File

@@ -28,6 +28,7 @@
#include <openspace/util/openspacemodule.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/properties/scalar/floatproperty.h>
#include <openspace/properties/stringproperty.h>
namespace openspace {
@@ -48,6 +49,7 @@ private:
properties::BoolProperty _enabled;
properties::BoolProperty _visible;
properties::StringProperty _url;
properties::FloatProperty _guiScale;
std::unique_ptr<BrowserInstance> _instance;
};

View File

@@ -27,10 +27,6 @@
#include <ghoul/glm.h>
#include <ghoul/logging/logmanager.h>
namespace {
constexpr const char* _loggerCat = "OctreeCuller";
} // namespace
namespace openspace {
namespace {

View File

@@ -620,6 +620,9 @@ RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary)
#endif // __APPLE__
if (dictionary.hasKey(ShaderOptionInfo.identifier)) {
// Default shader option:
_shaderOption = gaia::ShaderOption::Billboard_VBO;
const std::string shaderOption = dictionary.value<std::string>(
ShaderOptionInfo.identifier
);
@@ -639,7 +642,7 @@ RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary)
if (shaderOption == "Point_VBO") {
_shaderOption = gaia::ShaderOption::Point_VBO;
}
else {
else if (shaderOption == "Billboard_VBO") {
_shaderOption = gaia::ShaderOption::Billboard_VBO;
}
}

View File

@@ -205,7 +205,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) {
);
global::callback::mouseButton.emplace_back(
[&](MouseButton button, MouseAction action) -> bool {
[&](MouseButton button, MouseAction action, KeyModifier) -> bool {
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())

View File

@@ -95,14 +95,6 @@ namespace {
"Tooltip Delay (in s)",
"This value determines the delay in seconds after which the tooltip is shown."
};
constexpr openspace::properties::Property::PropertyInfo HiddenInfo = {
"IsHidden",
"Is Hidden",
"If this value is true, all GUI items will not be rendered, regardless of their "
"status"
};
} // namespace
namespace openspace::gui {

View File

@@ -30,6 +30,7 @@ set(HEADER_FILES
include/connection.h
include/connectionpool.h
include/jsonconverters.h
include/serverinterface.h
include/topics/authorizationtopic.h
include/topics/bouncetopic.h
include/topics/getpropertytopic.h
@@ -50,6 +51,7 @@ set(SOURCE_FILES
src/connection.cpp
src/connectionpool.cpp
src/jsonconverters.cpp
src/serverinterface.cpp
src/topics/authorizationtopic.cpp
src/topics/bouncetopic.cpp
src/topics/getpropertytopic.cpp

View File

@@ -41,7 +41,12 @@ class Topic;
class Connection {
public:
Connection(std::unique_ptr<ghoul::io::Socket> s, std::string address);
Connection(
std::unique_ptr<ghoul::io::Socket> s,
std::string address,
bool authorized = false,
const std::string& password = ""
);
void handleMessage(const std::string& message);
void sendMessage(const std::string& message);
@@ -62,12 +67,9 @@ private:
std::thread _thread;
std::string _address;
bool _requireAuthorization;
bool _isAuthorized = false;
std::map<TopicId, std::string> _messageQueue;
std::map<TopicId, std::chrono::system_clock::time_point> _sentMessages;
bool isWhitelisted() const;
};
} // namespace openspace

View File

@@ -0,0 +1,84 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __OPENSPACE_MODULE_SERVER___SERVERINTERFACE___H__
#define __OPENSPACE_MODULE_SERVER___SERVERINTERFACE___H__
#include <openspace/properties/propertyowner.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/stringlistproperty.h>
#include <openspace/properties/optionproperty.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <openspace/properties/scalar/intproperty.h>
namespace ghoul::io { class SocketServer; }
namespace openspace {
class ServerInterface : public properties::PropertyOwner {
public:
static std::unique_ptr<ServerInterface> createFromDictionary(
const ghoul::Dictionary& dictionary);
ServerInterface(const ghoul::Dictionary& dictionary);
~ServerInterface();
void initialize();
void deinitialize();
bool isEnabled() const;
bool isActive() const;
int port() const;
std::string password() const;
bool clientHasAccessWithoutPassword(const std::string& address) const;
bool clientIsBlocked(const std::string& address) const;
ghoul::io::SocketServer* server();
private:
enum class InterfaceType : int {
TcpSocket = 0,
WebSocket
};
enum class Access : int {
Deny = 0,
RequirePassword,
Allow
};
properties::OptionProperty _type;
properties::IntProperty _port;
properties::BoolProperty _enabled;
properties::StringListProperty _allowAddresses;
properties::StringListProperty _requirePasswordAddresses;
properties::StringListProperty _denyAddresses;
properties::OptionProperty _defaultAccess;
properties::StringProperty _password;
std::unique_ptr<ghoul::io::SocketServer> _socketServer;
};
} // namespace openspace
#endif // __OPENSPACE_MODULE_SERVER___SERVERINTERFACE___H__

View File

@@ -31,7 +31,7 @@ namespace openspace {
class AuthorizationTopic : public Topic {
public:
AuthorizationTopic() = default;
AuthorizationTopic(std::string password);
void handleJson(const nlohmann::json& json) override;
bool isDone() const override;
@@ -39,6 +39,7 @@ public:
private:
bool authorize(const std::string& key);
std::string _password;
bool _isAuthenticated = false;
};

View File

@@ -24,6 +24,7 @@
#include <modules/server/servermodule.h>
#include <modules/server/include/serverinterface.h>
#include <modules/server/include/connection.h>
#include <modules/server/include/topics/topic.h>
#include <openspace/engine/globalscallbacks.h>
@@ -36,54 +37,102 @@
#include <ghoul/misc/templatefactory.h>
namespace {
constexpr const char* _loggerCat = "ServerModule";
constexpr const char* KeyInterfaces = "Interfaces";
} // namespace
namespace openspace {
ServerModule::ServerModule() : OpenSpaceModule(ServerModule::Name) {}
ServerModule::ServerModule()
: OpenSpaceModule(ServerModule::Name)
, _interfaceOwner({"Interfaces", "Interfaces", "Server Interfaces"})
{
addPropertySubOwner(_interfaceOwner);
}
ServerModule::~ServerModule() {
disconnectAll();
cleanUpFinishedThreads();
}
void ServerModule::internalInitialize(const ghoul::Dictionary&) {
ServerInterface* ServerModule::serverInterfaceByIdentifier(const std::string& identifier)
{
const auto si = std::find_if(
_interfaces.begin(),
_interfaces.end(),
[identifier](std::unique_ptr<ServerInterface>& i) {
return i->identifier() == identifier;
}
);
if (si == _interfaces.end()) {
return nullptr;
}
return si->get();
}
void ServerModule::internalInitialize(const ghoul::Dictionary& configuration) {
using namespace ghoul::io;
std::unique_ptr<TcpSocketServer> tcpServer = std::make_unique<TcpSocketServer>();
std::unique_ptr<WebSocketServer> wsServer = std::make_unique<WebSocketServer>();
if (configuration.hasValue<ghoul::Dictionary>(KeyInterfaces)) {
ghoul::Dictionary interfaces =
configuration.value<ghoul::Dictionary>(KeyInterfaces);
// Temporary hard coded addresses and ports.
tcpServer->listen("localhost", 8000);
wsServer->listen("localhost", 8001);
LDEBUG(fmt::format(
"TCP Server listening on {}:{}",tcpServer->address(), tcpServer->port()
));
for (std::string& key : interfaces.keys()) {
if (!interfaces.hasValue<ghoul::Dictionary>(key)) {
continue;
}
ghoul::Dictionary interfaceDictionary =
interfaces.value<ghoul::Dictionary>(key);
LDEBUG(fmt::format(
"WS Server listening on {}:{}", wsServer->address(), wsServer->port()
));
std::unique_ptr<ServerInterface> serverInterface =
ServerInterface::createFromDictionary(interfaceDictionary);
_servers.push_back(std::move(tcpServer));
_servers.push_back(std::move(wsServer));
serverInterface->initialize();
_interfaceOwner.addPropertySubOwner(serverInterface.get());
if (serverInterface) {
_interfaces.push_back(std::move(serverInterface));
}
}
}
global::callback::preSync.emplace_back([this]() { preSync(); });
}
void ServerModule::preSync() {
// Set up new connections.
for (std::unique_ptr<ghoul::io::SocketServer>& server : _servers) {
for (std::unique_ptr<ServerInterface>& serverInterface : _interfaces) {
if (!serverInterface->isEnabled()) {
continue;
}
ghoul::io::SocketServer* socketServer = serverInterface->server();
if (!socketServer) {
continue;
}
std::unique_ptr<ghoul::io::Socket> socket;
while ((socket = server->nextPendingSocket())) {
while ((socket = socketServer->nextPendingSocket())) {
std::string address = socket->address();
if (serverInterface->clientIsBlocked(address)) {
// Drop connection if the address is blocked.
continue;
}
socket->startStreams();
std::shared_ptr<Connection> connection = std::make_shared<Connection>(
std::move(socket),
server->address()
address,
false,
serverInterface->password()
);
connection->setThread(std::thread(
[this, connection] () { handleConnection(connection); }
));
if (serverInterface->clientHasAccessWithoutPassword(address)) {
connection->setAuthorized(true);
}
_connections.push_back({ std::move(connection), false });
}
}
@@ -115,6 +164,10 @@ void ServerModule::cleanUpFinishedThreads() {
}
void ServerModule::disconnectAll() {
for (std::unique_ptr<ServerInterface>& serverInterface : _interfaces) {
serverInterface->deinitialize();
}
for (ConnectionData& connectionData : _connections) {
Connection& connection = *connectionData.connection;
if (connection.socket() && connection.socket()->isConnected()) {

View File

@@ -27,12 +27,12 @@
#include <openspace/util/openspacemodule.h>
#include <modules/server/include/serverinterface.h>
#include <deque>
#include <memory>
#include <mutex>
namespace ghoul::io { class SocketServer; }
namespace openspace {
constexpr int SOCKET_API_VERSION_MAJOR = 0;
@@ -53,6 +53,8 @@ public:
ServerModule();
virtual ~ServerModule();
ServerInterface* serverInterfaceByIdentifier(const std::string& identifier);
protected:
void internalInitialize(const ghoul::Dictionary& configuration) override;
@@ -72,7 +74,8 @@ private:
std::deque<Message> _messageQueue;
std::vector<ConnectionData> _connections;
std::vector<std::unique_ptr<ghoul::io::SocketServer>> _servers;
std::vector<std::unique_ptr<ServerInterface>> _interfaces;
properties::PropertyOwner _interfaceOwner;
};
} // namespace openspace

View File

@@ -66,13 +66,23 @@ namespace {
namespace openspace {
Connection::Connection(std::unique_ptr<ghoul::io::Socket> s, std::string address)
Connection::Connection(std::unique_ptr<ghoul::io::Socket> s,
std::string address,
bool authorized,
const std::string& password)
: _socket(std::move(s))
, _address(std::move(address))
, _isAuthorized(authorized)
{
ghoul_assert(_socket, "Socket must not be nullptr");
_topicFactory.registerClass<AuthorizationTopic>(AuthenticationTopicKey);
_topicFactory.registerClass(
AuthenticationTopicKey,
[password](bool, const ghoul::Dictionary&) {
return new AuthorizationTopic(password);
}
);
_topicFactory.registerClass<GetPropertyTopic>(GetPropertyTopicKey);
_topicFactory.registerClass<LuaScriptTopic>(LuaScriptTopicKey);
_topicFactory.registerClass<SetPropertyTopic>(SetPropertyTopicKey);
@@ -83,9 +93,6 @@ Connection::Connection(std::unique_ptr<ghoul::io::Socket> s, std::string address
_topicFactory.registerClass<BounceTopic>(BounceTopicKey);
_topicFactory.registerClass<FlightControllerTopic>(FlightControllerTopicKey);
_topicFactory.registerClass<VersionTopic>(VersionTopicKey);
// see if the default config for requiring auth (on) is overwritten
_requireAuthorization = global::configuration.doesRequireSocketAuthentication;
}
void Connection::handleMessage(const std::string& message) {
@@ -102,7 +109,7 @@ void Connection::handleMessage(const std::string& message) {
catch (const std::exception& e) {
LERROR(e.what());
} catch (...) {
if (!isAuthorized()) {
if (! isAuthorized()) {
_socket->disconnect();
LERROR(fmt::format(
"Could not parse JSON: '{}'. Connection is unauthorized. Disconnecting.",
@@ -189,8 +196,7 @@ void Connection::sendJson(const nlohmann::json& json) {
}
bool Connection::isAuthorized() const {
// require either auth to be disabled or client to be authenticated
return !_requireAuthorization || isWhitelisted() || _isAuthorized;
return _isAuthorized;
}
void Connection::setThread(std::thread&& thread) {
@@ -209,9 +215,4 @@ void Connection::setAuthorized(bool status) {
_isAuthorized = status;
}
bool Connection::isWhitelisted() const {
const std::vector<std::string>& wl = global::configuration.clientAddressWhitelist;
return std::find(wl.begin(), wl.end(), _address) != wl.end();
}
} // namespace openspace

View File

@@ -0,0 +1,263 @@
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/server/include/serverinterface.h>
#include <ghoul/io/socket/socketserver.h>
#include <ghoul/io/socket/tcpsocketserver.h>
#include <ghoul/io/socket/websocketserver.h>
#include <functional>
namespace {
constexpr const char* KeyIdentifier = "Identifier";
constexpr const char* TcpSocketType = "TcpSocket";
constexpr const char* WebSocketType = "WebSocket";
constexpr const char* DenyAccess = "Deny";
constexpr const char* RequirePassword = "RequirePassword";
constexpr const char* AllowAccess = "Allow";
constexpr openspace::properties::Property::PropertyInfo EnabledInfo = {
"Enabled",
"Is Enabled",
"This setting determines whether this server interface is enabled or not."
};
constexpr openspace::properties::Property::PropertyInfo TypeInfo = {
"Type",
"Type",
"Whether the interface is using a Socket or a WebSocket"
};
constexpr openspace::properties::Property::PropertyInfo PortInfo = {
"Port",
"Port",
"The network port to use for this sevrer interface"
};
constexpr openspace::properties::Property::PropertyInfo DefaultAccessInfo = {
"DefaultAccess",
"Default Access",
"Sets the default access policy: Allow, RequirePassword or Deny"
};
constexpr openspace::properties::Property::PropertyInfo AllowAddressesInfo = {
"AllowAddresses",
"Allow Addresses",
"Ip addresses or domains that should always be allowed access to this interface"
};
constexpr openspace::properties::Property::PropertyInfo RequirePasswordAddressesInfo = {
"RequirePasswordAddresses",
"Require Password Addresses",
"Ip addresses or domains that should be allowed access if they provide a password"
};
constexpr openspace::properties::Property::PropertyInfo DenyAddressesInfo = {
"DenyAddresses",
"Deny Addresses",
"Ip addresses or domains that should never be allowed access to this interface"
};
constexpr openspace::properties::Property::PropertyInfo PasswordInfo = {
"Password",
"Password",
"Password for connecting to this interface"
};
}
namespace openspace {
std::unique_ptr<ServerInterface> ServerInterface::createFromDictionary(
const ghoul::Dictionary& config)
{
// TODO: Use documentation to verify dictionary
std::unique_ptr<ServerInterface> si = std::make_unique<ServerInterface>(config);
return si;
}
ServerInterface::ServerInterface(const ghoul::Dictionary& config)
: properties::PropertyOwner({ "", "", "" })
, _type(TypeInfo)
, _port(PortInfo, 0)
, _enabled(EnabledInfo)
, _allowAddresses(AllowAddressesInfo)
, _requirePasswordAddresses(RequirePasswordAddressesInfo)
, _denyAddresses(DenyAddressesInfo)
, _defaultAccess(DefaultAccessInfo)
, _password(PasswordInfo)
{
_type.addOption(static_cast<int>(InterfaceType::TcpSocket), TcpSocketType);
_type.addOption(static_cast<int>(InterfaceType::WebSocket), WebSocketType);
_defaultAccess.addOption(static_cast<int>(Access::Deny), DenyAccess);
_defaultAccess.addOption(static_cast<int>(Access::RequirePassword), RequirePassword);
_defaultAccess.addOption(static_cast<int>(Access::Allow), AllowAccess);
const std::string identifier = config.value<std::string>(KeyIdentifier);
auto readList =
[config](const std::string& key, properties::StringListProperty& list) {
if (config.hasValue<ghoul::Dictionary>(key)) {
const ghoul::Dictionary& dict = config.value<ghoul::Dictionary>(key);
std::vector<std::string> v;
for (const std::string& k : dict.keys()) {
v.push_back(dict.value<std::string>(k));
}
list.set(v);
}
};
readList(AllowAddressesInfo.identifier, _allowAddresses);
readList(DenyAddressesInfo.identifier, _denyAddresses);
readList(RequirePasswordAddressesInfo.identifier, _requirePasswordAddresses);
this->setIdentifier(identifier);
this->setGuiName(identifier);
this->setDescription("Settings for server interface " + identifier);
const std::string type = config.value<std::string>(TypeInfo.identifier);
if (type == TcpSocketType) {
_type = static_cast<int>(InterfaceType::TcpSocket);
} else if (type == WebSocketType) {
_type = static_cast<int>(InterfaceType::WebSocket);
}
if (config.hasValue<std::string>(PasswordInfo.identifier)) {
_password = config.value<std::string>(PasswordInfo.identifier);
}
_port = static_cast<int>(config.value<double>(PortInfo.identifier));
_enabled = config.value<bool>(EnabledInfo.identifier);
std::function<void()> reinitialize = [this]() {
deinitialize();
initialize();
};
_type.onChange(reinitialize);
_port.onChange(reinitialize);
_enabled.onChange(reinitialize);
_defaultAccess.onChange(reinitialize);
_allowAddresses.onChange(reinitialize);
_requirePasswordAddresses.onChange(reinitialize);
_denyAddresses.onChange(reinitialize);
addProperty(_type);
addProperty(_port);
addProperty(_enabled);
addProperty(_defaultAccess);
addProperty(_allowAddresses);
addProperty(_requirePasswordAddresses);
addProperty(_denyAddresses);
addProperty(_password);
}
ServerInterface::~ServerInterface() {}
void ServerInterface::initialize() {
if (!_enabled) {
return;
}
switch (static_cast<InterfaceType>(_type.value())) {
case InterfaceType::TcpSocket:
_socketServer = std::make_unique<ghoul::io::TcpSocketServer>();
break;
case InterfaceType::WebSocket:
_socketServer = std::make_unique<ghoul::io::WebSocketServer>();
break;
}
_socketServer->listen(_port);
}
void ServerInterface::deinitialize() {
_socketServer->close();
}
bool ServerInterface::isEnabled() const {
return _enabled.value();
}
bool ServerInterface::isActive() const {
return _socketServer->isListening();
}
int ServerInterface::port() const {
return _port;
}
std::string ServerInterface::password() const {
return _password;
}
bool ServerInterface::clientHasAccessWithoutPassword(
const std::string& clientAddress) const
{
for (const std::string& address : _allowAddresses.value()) {
if (clientAddress == address) {
return true;
}
}
Access access = static_cast<Access>(_defaultAccess.value());
if (access == Access::Allow) {
for (const std::string& address : _denyAddresses.value()) {
if (clientAddress == address) {
return false;
}
}
return true;
}
return false;
}
bool ServerInterface::clientIsBlocked(const std::string& clientAddress) const {
for (const std::string& address : _denyAddresses.value()) {
if (clientAddress == address) {
return true;
}
}
Access access = static_cast<Access>(_defaultAccess.value());
if (access == Access::Deny) {
for (const std::string& address : _allowAddresses.value()) {
if (clientAddress == address) {
return false;
}
}
for (const std::string& address : _requirePasswordAddresses.value()) {
if (clientAddress == address) {
return false;
}
}
return true;
}
return false;
}
ghoul::io::SocketServer* ServerInterface::server() {
return _socketServer.get();
}
}

View File

@@ -32,59 +32,45 @@
namespace {
constexpr const char* _loggerCat = "AuthorizationTopic";
/* https://httpstatuses.com/ */
enum class StatusCode : int {
OK = 200,
Accepted = 202,
BadRequest = 400,
Unauthorized = 401,
NotAcceptable = 406,
NotImplemented = 501
};
nlohmann::json message(const std::string& message, StatusCode statusCode) {
return { { "message", message }, { "code", static_cast<int>(statusCode) } };
}
constexpr const char* KeyStatus = "status";
constexpr const char* Authorized = "authorized";
constexpr const char* IncorrectKey = "incorrectKey";
constexpr const char* BadRequest = "badRequest";
} // namespace
namespace openspace {
AuthorizationTopic::AuthorizationTopic(std::string password)
: _password(std::move(password))
{}
bool AuthorizationTopic::isDone() const {
return _isAuthenticated;
}
void AuthorizationTopic::handleJson(const nlohmann::json& json) {
if (isDone()) {
_connection->sendJson(message("Already authorized.", StatusCode::OK));
_connection->sendJson(wrappedPayload({ KeyStatus, Authorized }));
} else {
try {
auto providedKey = json.at("key").get<std::string>();
if (authorize(providedKey)) {
_connection->sendJson(message("Authorization OK.", StatusCode::Accepted));
_connection->setAuthorized(true);
_connection->sendJson(wrappedPayload({ KeyStatus, Authorized }));
LINFO("Client successfully authorized.");
} else {
_connection->sendJson(message("Invalid key", StatusCode::NotAcceptable));
_connection->sendJson(wrappedPayload({ KeyStatus, IncorrectKey }));
}
} catch (const std::out_of_range&) {
_connection->sendJson(
message("Invalid request, key must be provided.", StatusCode::BadRequest)
);
_connection->sendJson(wrappedPayload({ KeyStatus, BadRequest }));
} catch (const std::domain_error&) {
_connection->sendJson(
message("Invalid request, invalid key format.", StatusCode::BadRequest)
);
_connection->sendJson(wrappedPayload({ KeyStatus, BadRequest }));
}
}
}
bool AuthorizationTopic::authorize(const std::string& key) {
_isAuthenticated = (key == global::configuration.serverPasskey);
_isAuthenticated = (key == _password);
return _isAuthenticated;
}

View File

@@ -41,6 +41,8 @@
#include <cstdint>
#include <fstream>
#include <type_traits>
namespace {
constexpr const char* _loggerCat = "RenderableStars";
@@ -56,27 +58,39 @@ namespace {
constexpr int8_t CurrentCacheVersion = 2;
struct CommonDataLayout {
struct ColorVBOLayout {
std::array<float, 4> position; // (x,y,z,e)
float value;
float luminance;
float absoluteMagnitude;
};
struct VelocityVBOLayout {
std::array<float, 4> position; // (x,y,z,e)
float value;
float luminance;
float absoluteMagnitude;
};
struct ColorVBOLayout : public CommonDataLayout {};
struct VelocityVBOLayout : public CommonDataLayout {
float vx; // v_x
float vy; // v_y
float vz; // v_z
};
struct SpeedVBOLayout : public CommonDataLayout {
struct SpeedVBOLayout {
std::array<float, 4> position; // (x,y,z,e)
float value;
float luminance;
float absoluteMagnitude;
float speed;
};
struct OtherDataLayout : public CommonDataLayout {};
struct OtherDataLayout {
std::array<float, 4> position; // (x,y,z,e)
float value;
float luminance;
float absoluteMagnitude;
};
constexpr openspace::properties::Property::PropertyInfo SpeckFileInfo = {
"SpeckFile",
@@ -407,7 +421,7 @@ void RenderableStars::initializeGL() {
LERROR(fmt::format("Could not find other data column {}", _queuedOtherData));
}
else {
_otherDataOption = std::distance(_dataNames.begin(), it);
_otherDataOption = static_cast<int>(std::distance(_dataNames.begin(), it));
_queuedOtherData.clear();
}
}

View File

@@ -30,8 +30,17 @@
#pragma warning (disable : 4100)
#endif // _MSC_VER
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif // __clang__
#include <include/cef_client.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
#ifdef _MSC_VER
#pragma warning (pop)
#endif // _MSC_VER
@@ -90,6 +99,13 @@ public:
* \return if this scroll should be blocked or not
*/
bool sendMouseWheelEvent(const CefMouseEvent& event, const glm::ivec2& delta);
/**
* Set the browser zoom level.
* 1.0 = default, 2.0 = double, etc.
*/
void setZoom(float ratio);
void reloadBrowser();
const CefRefPtr<CefBrowser>& getBrowser() const;
@@ -102,6 +118,7 @@ private:
CefRefPtr<BrowserClient> _client;
CefRefPtr<CefBrowser> _browser;
bool _isInitialized = false;
double _zoomLevel = 1.0;
};
} // namespace openspace

View File

@@ -35,8 +35,17 @@
#pragma warning (disable : 4100)
#endif // _MSC_VER
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif // __clang__
#include <include/cef_browser.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
#ifdef _MSC_VER
#pragma warning (pop)
#endif // _MSC_VER
@@ -53,7 +62,7 @@ public:
void detachBrowser();
private:
bool mouseButtonCallback(MouseButton button, MouseAction action);
bool mouseButtonCallback(MouseButton button, MouseAction action, KeyModifier mods);
bool mousePositionCallback(double x, double y);
bool mouseWheelCallback(glm::ivec2 delta);
bool charCallback(unsigned int charCode, KeyModifier modifier);
@@ -73,7 +82,7 @@ private:
*
* \return
*/
CefMouseEvent mouseEvent();
CefMouseEvent mouseEvent(KeyModifier mods = KeyModifier::NoModifier);
/**
* Find the CEF key event to use for a given action.

View File

@@ -36,8 +36,17 @@
#pragma warning (disable : 4100)
#endif // _MSC_VER
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif // __clang__
#include <include/cef_client.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
#ifdef _MSC_VER
#pragma warning (pop)
#endif // _MSC_VER

View File

@@ -30,8 +30,18 @@
#pragma warning (disable : 4100)
#endif // _MSC_VER
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif // __clang__
#include <include/cef_keyboard_handler.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
#ifdef _MSC_VER
#pragma warning (pop)
#endif // _MSC_VER

View File

@@ -97,6 +97,9 @@ void BrowserInstance::reshape(const glm::ivec2& windowSize) {
}
void BrowserInstance::draw() {
if (_zoomLevel != _browser->GetHost()->GetZoomLevel()) {
_browser->GetHost()->SetZoomLevel(_zoomLevel);
}
_renderHandler->draw();
}
@@ -142,6 +145,13 @@ bool BrowserInstance::sendMouseWheelEvent(const CefMouseEvent& event,
return hasContent(event.x, event.y);
}
void BrowserInstance::setZoom(float ratio) {
//Zooming in CEF is non-linear according to this:
//https://www.magpcss.org/ceforum/viewtopic.php?f=6&t=11491
_zoomLevel = glm::log(static_cast<double>(ratio))/glm::log(1.2);
_browser->GetHost()->SetZoomLevel(_zoomLevel);
}
void BrowserInstance::reloadBrowser() {
_browser->Reload();
}

View File

@@ -125,9 +125,9 @@ void EventHandler::initialize() {
}
);
global::callback::mouseButton.emplace_back(
[this](MouseButton button, MouseAction action) -> bool {
[this](MouseButton button, MouseAction action, KeyModifier mods) -> bool {
if (_browserInstance) {
return mouseButtonCallback(button, action);
return mouseButtonCallback(button, action, mods);
}
return false;
}
@@ -143,7 +143,10 @@ void EventHandler::initialize() {
);
}
bool EventHandler::mouseButtonCallback(MouseButton button, MouseAction action) {
bool EventHandler::mouseButtonCallback(MouseButton button,
MouseAction action,
KeyModifier mods)
{
if (button != MouseButton::Left && button != MouseButton::Right) {
return false;
}
@@ -167,7 +170,7 @@ bool EventHandler::mouseButtonCallback(MouseButton button, MouseAction action) {
}
return _browserInstance->sendMouseClickEvent(
mouseEvent(),
mouseEvent(mods),
(button == MouseButton::Left) ? MBT_LEFT : MBT_RIGHT,
!state.down,
clickCount
@@ -250,7 +253,7 @@ cef_key_event_type_t EventHandler::keyEventType(KeyAction action) {
}
}
CefMouseEvent EventHandler::mouseEvent() {
CefMouseEvent EventHandler::mouseEvent(KeyModifier mods) {
CefMouseEvent event;
event.x = static_cast<int>(_mousePosition.x);
event.y = static_cast<int>(_mousePosition.y);
@@ -263,6 +266,7 @@ CefMouseEvent EventHandler::mouseEvent() {
event.modifiers = EVENTFLAG_RIGHT_MOUSE_BUTTON;
}
event.modifiers |= static_cast<uint32_t>(mapToCefModifiers(mods));
return event;
}

View File

@@ -24,6 +24,9 @@
#include <modules/webgui/webguimodule.h>
#include <modules/server/servermodule.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/moduleengine.h>
#include <ghoul/fmt.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
@@ -38,20 +41,41 @@ namespace {
"Enable the node js based process used to serve the Web GUI."
};
constexpr openspace::properties::Property::PropertyInfo AddressInfo = {
"Address",
"Address",
"The network address to use when connecting to OpenSpace from the Web GUI."
};
constexpr openspace::properties::Property::PropertyInfo PortInfo = {
"Port",
"Port",
"The network port to use when serving the Web GUI over HTTP."
};
constexpr openspace::properties::Property::PropertyInfo WebSocketInterfaceInfo = {
"WebSocketInterface",
"WebSocket Interface",
"The identifier of the websocket interface to use when communicating."
};
constexpr openspace::properties::Property::PropertyInfo ServerProcessEntryPointInfo =
{
"ServerProcessEntryPoint",
"Server Process Entry Point",
"The node js command to invoke"
"The node js command to invoke."
};
constexpr openspace::properties::Property::PropertyInfo
ServerProcessWorkingDirectoryInfo =
WebDirectoryInfo =
{
"ServerProcessWorkingDirectory",
"Server Process Working Directory",
"The working directory of the process"
"WebDirectory",
"Web Directory",
"Directory from which to to serve static content",
};
constexpr const char* DefaultAddress = "localhost";
constexpr const int DefaultPort = 4680;
}
namespace openspace {
@@ -60,14 +84,40 @@ WebGuiModule::WebGuiModule()
: OpenSpaceModule(WebGuiModule::Name)
, _enabled(ServerProcessEnabledInfo, false)
, _entryPoint(ServerProcessEntryPointInfo)
, _workingDirectory(ServerProcessWorkingDirectoryInfo)
, _webDirectory(WebDirectoryInfo)
, _port(PortInfo, DefaultPort)
, _address(AddressInfo, DefaultAddress)
, _webSocketInterface(WebSocketInterfaceInfo, "")
{
addProperty(_enabled);
addProperty(_entryPoint);
addProperty(_workingDirectory);
addProperty(_webDirectory);
addProperty(_address);
addProperty(_port);
}
void WebGuiModule::internalInitialize(const ghoul::Dictionary&) {
int WebGuiModule::port() const {
return _port;
}
std::string WebGuiModule::address() const {
return _address;
}
void WebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) {
if (configuration.hasValue<int>(PortInfo.identifier)) {
_port = configuration.value<int>(PortInfo.identifier);
}
if (configuration.hasValue<std::string>(AddressInfo.identifier)) {
_address = configuration.value<std::string>(AddressInfo.identifier);
}
if (configuration.hasValue<std::string>(WebSocketInterfaceInfo.identifier)) {
_webSocketInterface =
configuration.value<std::string>(WebSocketInterfaceInfo.identifier);
}
auto startOrStop = [this]() {
if (_enabled) {
startProcess();
@@ -85,20 +135,39 @@ void WebGuiModule::internalInitialize(const ghoul::Dictionary&) {
_enabled.onChange(startOrStop);
_entryPoint.onChange(restartIfEnabled);
_workingDirectory.onChange(restartIfEnabled);
_webDirectory.onChange(restartIfEnabled);
_port.onChange(restartIfEnabled);
startOrStop();
}
void WebGuiModule::startProcess() {
ServerModule* serverModule = global::moduleEngine.module<ServerModule>();
const ServerInterface* serverInterface =
serverModule->serverInterfaceByIdentifier(_webSocketInterface);
if (!serverInterface) {
LERROR("Missing server interface. Server process could not start.");
return;
}
const int webSocketPort = serverInterface->port();
#ifdef _MSC_VER
const std::string nodePath = absPath("${MODULE_WEBGUI}/ext/nodejs/node.exe");
#else
const std::string nodePath = absPath("${MODULE_WEBGUI}/ext/nodejs/node");
#endif
const std::string command = "\"" + nodePath + "\" "
+ "\"" + absPath(_entryPoint.value()) + "\"" +
" --directory \"" + absPath(_webDirectory.value()) + "\"" +
" --http-port \"" + std::to_string(_port.value()) + "\" " +
" --ws-address \"" + _address.value() + "\"" +
" --ws-port \"" + std::to_string(webSocketPort) + "\"" +
" --auto-close --local";
_process = std::make_unique<ghoul::Process>(
"\"" + nodePath + "\" \"" + _entryPoint.value() + "\"",
_workingDirectory.value(),
command,
_webDirectory.value(),
[](const char* data, size_t n) {
const std::string str(data, n);
LDEBUG(fmt::format("Web GUI server output: {}", str));

View File

@@ -28,6 +28,7 @@
#include <openspace/util/openspacemodule.h>
#include <openspace/properties/stringproperty.h>
#include <openspace/properties/scalar/intproperty.h>
#include <openspace/properties/scalar/boolproperty.h>
#include <ghoul/misc/process.h>
#include <memory>
@@ -38,6 +39,8 @@ class WebGuiModule : public OpenSpaceModule {
public:
static constexpr const char* Name = "WebGui";
WebGuiModule();
int port() const;
std::string address() const;
protected:
void internalInitialize(const ghoul::Dictionary&) override;
@@ -49,7 +52,11 @@ private:
std::unique_ptr<ghoul::Process> _process;
properties::BoolProperty _enabled;
properties::StringProperty _entryPoint;
properties::StringProperty _workingDirectory;
properties::StringProperty _webDirectory;
properties::IntProperty _port;
properties::StringProperty _address;
properties::StringProperty _webSocketInterface;
};
} // namespace openspace

View File

@@ -86,12 +86,42 @@ ModuleConfigurations = {
"data.openspaceproject.com/request"
}
},
Server = {
Interfaces = {
{
Type = "TcpSocket",
Identifier = "DefaultTcpSocketInterface",
Port = 4681,
Enabled = true,
DefaultAccess = "Deny",
AllowAddresses = {"127.0.0.1", "localhost"},
RequirePasswordAddresses = {},
Password = ""
},
{
Type = "WebSocket",
Identifier = "DefaultWebSocketInterface",
Port = 4682,
Enabled = true,
DefaultAccess = "Deny",
AllowAddresses = {"127.0.0.1", "localhost"},
RequirePasswordAddresses = {},
Password = ""
}
}
},
WebBrowser = {
Enabled = true,
WebHelperLocation = "${BIN}/openspace_web_helper"
},
WebGui = {
Address = "localhost",
HttpPort = 4680,
WebSocketInterface = "DefaultWebSocketInterface"
},
CefWebGui = {
GuiUrl = "http://localhost:8080/#/onscreen/",
-- GuiUrl = "http://localhost:4680/#/onscreen/",
-- GuiScale = 2.0,
Enabled = true,
Visible = true
}
@@ -154,9 +184,3 @@ OpenGLDebugContext = {
-- FilterSeverity = { }
}
--RenderingMethod = "ABuffer" -- alternative: "Framebuffer"
ServerPasskey = "secret!"
ClientAddressWhitelist = {
"127.0.0.1",
"localhost"
}

View File

@@ -57,9 +57,6 @@ namespace {
constexpr const char* KeyKeyboardShortcuts = "KeyboardShortcuts";
constexpr const char* KeyDocumentation = "Documentation";
constexpr const char* KeyFactoryDocumentation = "FactoryDocumentation";
constexpr const char* KeyRequireSocketAuthentication = "RequireSocketAuthentication";
constexpr const char* KeyServerPasskey = "ServerPasskey";
constexpr const char* KeyClientAddressWhitelist = "ClientAddressWhitelist";
constexpr const char* KeyLicenseDocumentation = "LicenseDocumentation";
constexpr const char* KeyShutdownCountdown = "ShutdownCountdown";
constexpr const char* KeyPerSceneCache = "PerSceneCache";
@@ -294,9 +291,6 @@ void parseLuaState(Configuration& configuration) {
getValue(s, KeyDisableSceneOnMaster, c.isSceneTranslationOnMasterDisabled);
getValue(s, KeyDisableInGameConsole, c.isConsoleDisabled);
getValue(s, KeyRenderingMethod, c.renderingMethod);
getValue(s, KeyServerPasskey, c.serverPasskey);
getValue(s, KeyRequireSocketAuthentication, c.doesRequireSocketAuthentication);
getValue(s, KeyClientAddressWhitelist, c.clientAddressWhitelist);
getValue(s, KeyLogging, c.logging);
getValue(s, KeyDocumentation, c.documentation);

View File

@@ -209,26 +209,6 @@ documentation::Documentation Configuration::Documentation = {
Optional::Yes,
"All documentations that are generated at application startup."
},
{
KeyRequireSocketAuthentication,
new BoolVerifier,
Optional::Yes,
"If socket connections should be authenticated or not before they are "
"allowed to get or set information. Defaults to 'true'."
},
{
KeyServerPasskey,
new StringVerifier,
Optional::Yes,
"Passkey to limit server access. Used to authorize incoming connections."
},
{
KeyClientAddressWhitelist,
new StringListVerifier,
Optional::Yes,
"String containing white listed client IP addresses that won't need to be"
"authorized with the server. Space separated"
},
{
KeyShutdownCountdown,
new DoubleGreaterEqualVerifier(0.0),

View File

@@ -81,8 +81,8 @@ std::vector<std::function<bool(unsigned int, KeyModifier)>>& gCharacter() {
return g;
}
std::vector<std::function<bool(MouseButton, MouseAction)>>& gMouseButton() {
static std::vector<std::function<bool(MouseButton, MouseAction)>> g;
std::vector<std::function<bool(MouseButton, MouseAction, KeyModifier)>>& gMouseButton() {
static std::vector<std::function<bool(MouseButton, MouseAction, KeyModifier)>> g;
return g;
}

View File

@@ -1180,10 +1180,13 @@ void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier)
global::luaConsole.charCallback(codepoint, modifier);
}
void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action) {
using F = std::function<bool (MouseButton, MouseAction)>;
void OpenSpaceEngine::mouseButtonCallback(MouseButton button,
MouseAction action,
KeyModifier mods)
{
using F = std::function<bool (MouseButton, MouseAction, KeyModifier)>;
for (const F& func : global::callback::mouseButton) {
bool isConsumed = func(button, action);
bool isConsumed = func(button, action, mods);
if (isConsumed) {
// If the mouse was released, we still want to forward it to the navigation
// handler in order to reliably terminate a rotation or zoom. Accidentally

View File

@@ -41,7 +41,7 @@ namespace openspace {
void ParallelServer::start(int port, const std::string& password,
const std::string& changeHostPassword)
{
_socketServer.listen("localhost", port);
_socketServer.listen(port);
_passwordHash = std::hash<std::string>{}(password);
_changeHostPasswordHash = std::hash<std::string>{}(changeHostPassword);

View File

@@ -50,6 +50,9 @@ glm::bvec2 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,6 +50,9 @@ glm::bvec3 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,6 +50,9 @@ glm::bvec4 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::dvec2 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::dvec3 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::dvec4 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::ivec2 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::ivec3 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::ivec4 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::uvec2 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::uvec3 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::uvec4 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::vec2 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,8 @@ glm::vec3 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -50,8 +50,9 @@ glm::vec4 fromLuaConversion(lua_State* state, bool& success) {
lua_pop(state, 1);
}
}
// The last accessor argument and the table are still on the stack
lua_pop(state, 2);
// The last accessor argument is still on the stack
lua_pop(state, 1);
success = true;
return result;
}

View File

@@ -605,6 +605,14 @@ scripting::LuaLibrary Scene::luaLibrary() {
"Returns the value the property, identified by "
"the provided URI."
},
{
"getProperty",
&luascriptfunctions::property_getProperty,
{},
"string",
"Returns a list of property identifiers that match the passed regular "
"expression"
},
{
"loadScene",
&luascriptfunctions::loadScene,

View File

@@ -401,6 +401,51 @@ int property_getValue(lua_State* L) {
return 1;
}
/**
* \ingroup LuaScripts
* getProperty
* Returns a list of property identifiers that match the passed regular expression
*/
int property_getProperty(lua_State* L) {
ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::property_getProperty");
std::string regex = ghoul::lua::value<std::string>(L, 1);
lua_pop(L, 1);
// Replace all wildcards * with the correct regex (.*)
size_t startPos = regex.find("*");
while (startPos != std::string::npos) {
regex.replace(startPos, 1, "(.*)");
startPos += 4; // (.*)
startPos = regex.find("*", startPos);
}
std::regex r(regex);
std::vector<properties::Property*> props = allProperties();
std::vector<std::string> res;
for (properties::Property* prop : props) {
// Check the regular expression for all properties
const std::string& id = prop->fullyQualifiedIdentifier();
if (std::regex_match(id, r)) {
res.push_back(id);
}
}
lua_newtable(L);
int number = 1;
for (const std::string& s : res) {
lua_pushstring(L, s.c_str());
lua_rawseti(L, -2, number);
++number;
}
return 1;
}
/**
* \ingroup LuaScripts
* getPropertyValue(string):

View File

@@ -197,6 +197,7 @@ void SyncHttpDownload::download(HttpRequest::RequestOptions opt) {
if (!initDownload()) {
LERROR(fmt::format("Failed sync download '{}'", _httpRequest.url()));
deinitDownload();
markAsFailed();
return;
}
@@ -211,14 +212,15 @@ void SyncHttpDownload::download(HttpRequest::RequestOptions opt) {
_httpRequest.onReadyStateChange([this](HttpRequest::ReadyState rs) {
if (rs == HttpRequest::ReadyState::Success) {
LTRACE(fmt::format("Finished sync download '{}'", _httpRequest.url()));
deinitDownload();
markAsSuccessful();
} else if (rs == HttpRequest::ReadyState::Fail) {
LERROR(fmt::format("Failed sync download '{}'", _httpRequest.url()));
deinitDownload();
markAsFailed();
}
});
_httpRequest.perform(opt);
deinitDownload();
LTRACE(fmt::format("End sync download '{}'", _httpRequest.url()));
}
@@ -286,21 +288,25 @@ void AsyncHttpDownload::download(HttpRequest::RequestOptions opt) {
_httpRequest.onReadyStateChange([this](HttpRequest::ReadyState rs) {
if (rs == HttpRequest::ReadyState::Success) {
LTRACE(fmt::format("Finished async download '{}'", _httpRequest.url()));
deinitDownload();
markAsSuccessful();
}
else if (rs == HttpRequest::ReadyState::Fail) {
LTRACE(fmt::format("Failed async download '{}'", _httpRequest.url()));
deinitDownload();
markAsFailed();
}
});
_httpRequest.perform(opt);
if (!hasSucceeded()) {
deinitDownload();
markAsFailed();
}
_downloadFinishCondition.notify_all();
deinitDownload();
LTRACE(fmt::format("End async download '{}'", _httpRequest.url()));
_downloadFinishCondition.notify_all();
}
const std::string& AsyncHttpDownload::url() const {
@@ -351,6 +357,7 @@ bool HttpFileDownload::initDownload() {
}
++nCurrentFilehandles;
_hasHandle = true;
_file = std::ofstream(_destination, std::ofstream::binary);
if (_file.fail()) {
@@ -414,8 +421,11 @@ const std::string& HttpFileDownload::destination() const {
}
bool HttpFileDownload::deinitDownload() {
_file.close();
--nCurrentFilehandles;
if (_hasHandle) {
_hasHandle = false;
_file.close();
--nCurrentFilehandles;
}
return _file.good();
}