From d879db827ffb6cd594591a0e1398e4e669c60a47 Mon Sep 17 00:00:00 2001 From: "Marcus D. Hanwell" Date: Mon, 17 Apr 2023 11:10:09 -0400 Subject: [PATCH] Remove the ProtoCall code from the repository Signed-off-by: Marcus D. Hanwell --- CMakeLists.txt | 1 - avogadro/CMakeLists.txt | 4 - avogadro/protocall/CMakeLists.txt | 24 - avogadro/protocall/matrixserialization.cpp | 196 ----- avogadro/protocall/matrixserialization.h | 190 ----- avogadro/protocall/moleculedeserializer.cpp | 165 ---- avogadro/protocall/moleculedeserializer.h | 85 -- avogadro/protocall/moleculeserializer.cpp | 191 ----- avogadro/protocall/moleculeserializer.h | 100 --- avogadro/protocall/utils.h | 60 -- avogadro/qtplugins/CMakeLists.txt | 4 - .../qtplugins/clientserver/CMakeLists.txt | 75 -- .../qtplugins/clientserver/avogadroserver.cpp | 161 ---- .../qtplugins/clientserver/avogadroserver.h | 41 - .../avoremotefilesystemservice.cpp | 206 ----- .../clientserver/avoremotefilesystemservice.h | 37 - .../clientserver/avoremotemoleculeservice.cpp | 65 -- .../clientserver/avoremotemoleculeservice.h | 28 - .../qtplugins/clientserver/clientserver.cpp | 301 ------- .../qtplugins/clientserver/clientserver.h | 88 --- .../clientserver/connectionsettingsdialog.cpp | 90 --- .../clientserver/connectionsettingsdialog.h | 48 -- .../clientserver/connectionsettingsdialog.ui | 137 ---- .../clientserver/external_avogadrocore.proto | 5 - .../qtplugins/clientserver/filedialog.cpp | 746 ------------------ avogadro/qtplugins/clientserver/filedialog.h | 112 --- avogadro/qtplugins/clientserver/filedialog.ui | 239 ------ .../clientserver/filedialogfilter.cpp | 112 --- .../qtplugins/clientserver/filedialogfilter.h | 39 - .../clientserver/filedialogmodel.cpp | 684 ---------------- .../qtplugins/clientserver/filedialogmodel.h | 168 ---- avogadro/qtplugins/clientserver/remote.proto | 53 -- tests/CMakeLists.txt | 3 - tests/protocall/CMakeLists.txt | 49 -- tests/protocall/matrixserialization.cpp | 105 --- tests/protocall/moleculeserialization.cpp | 120 --- tests/protocall/protocalltests.h.in | 6 - 37 files changed, 4738 deletions(-) delete mode 100644 avogadro/protocall/CMakeLists.txt delete mode 100644 avogadro/protocall/matrixserialization.cpp delete mode 100644 avogadro/protocall/matrixserialization.h delete mode 100644 avogadro/protocall/moleculedeserializer.cpp delete mode 100644 avogadro/protocall/moleculedeserializer.h delete mode 100644 avogadro/protocall/moleculeserializer.cpp delete mode 100644 avogadro/protocall/moleculeserializer.h delete mode 100644 avogadro/protocall/utils.h delete mode 100644 avogadro/qtplugins/clientserver/CMakeLists.txt delete mode 100644 avogadro/qtplugins/clientserver/avogadroserver.cpp delete mode 100644 avogadro/qtplugins/clientserver/avogadroserver.h delete mode 100644 avogadro/qtplugins/clientserver/avoremotefilesystemservice.cpp delete mode 100644 avogadro/qtplugins/clientserver/avoremotefilesystemservice.h delete mode 100644 avogadro/qtplugins/clientserver/avoremotemoleculeservice.cpp delete mode 100644 avogadro/qtplugins/clientserver/avoremotemoleculeservice.h delete mode 100644 avogadro/qtplugins/clientserver/clientserver.cpp delete mode 100644 avogadro/qtplugins/clientserver/clientserver.h delete mode 100644 avogadro/qtplugins/clientserver/connectionsettingsdialog.cpp delete mode 100644 avogadro/qtplugins/clientserver/connectionsettingsdialog.h delete mode 100644 avogadro/qtplugins/clientserver/connectionsettingsdialog.ui delete mode 100644 avogadro/qtplugins/clientserver/external_avogadrocore.proto delete mode 100644 avogadro/qtplugins/clientserver/filedialog.cpp delete mode 100644 avogadro/qtplugins/clientserver/filedialog.h delete mode 100644 avogadro/qtplugins/clientserver/filedialog.ui delete mode 100644 avogadro/qtplugins/clientserver/filedialogfilter.cpp delete mode 100644 avogadro/qtplugins/clientserver/filedialogfilter.h delete mode 100644 avogadro/qtplugins/clientserver/filedialogmodel.cpp delete mode 100644 avogadro/qtplugins/clientserver/filedialogmodel.h delete mode 100644 avogadro/qtplugins/clientserver/remote.proto delete mode 100644 tests/protocall/CMakeLists.txt delete mode 100644 tests/protocall/matrixserialization.cpp delete mode 100644 tests/protocall/moleculeserialization.cpp delete mode 100644 tests/protocall/protocalltests.h.in diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f9fc68a1f..56037422bf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,7 +56,6 @@ option(USE_LIBARCHIVE "Enable optional Libarchive features" ON) option(USE_LIBMSYM "Enable optional features using libmsym" ON) option(USE_SPGLIB "Enable optional features using spglib" ON) option(USE_MMTF "Enable optional features using mmtf" ON) -option(USE_PROTOCALL "Enable libraries that use ProtoCall" OFF) option(USE_PYTHON "Use Python to wrap some of our API" OFF) set(QT_VERSION "5" CACHE STRING "What major version of Qt") set(QT_VERSIONS_SUPPORTED 5 6) diff --git a/avogadro/CMakeLists.txt b/avogadro/CMakeLists.txt index bd35281896..130aa8a83f 100644 --- a/avogadro/CMakeLists.txt +++ b/avogadro/CMakeLists.txt @@ -69,7 +69,3 @@ if(USE_QT) endif() add_subdirectory(qtplugins) endif() - -if(USE_PROTOCALL) - add_subdirectory(protocall) -endif() diff --git a/avogadro/protocall/CMakeLists.txt b/avogadro/protocall/CMakeLists.txt deleted file mode 100644 index 96888d8de6..0000000000 --- a/avogadro/protocall/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -find_package(Eigen3 REQUIRED) -include_directories(SYSTEM ${EIGEN3_INCLUDE_DIR}) - -find_package(protobuf REQUIRED NO_MODULE) -include_directories(SYSTEM ${protobuf_INCLUDE_DIRS}) - -find_package(ProtoCall REQUIRED NO_MODULE) -include_directories(SYSTEM ${ProtoCall_INCLUDE_DIRS}) - -set(HEADERS - moleculeserializer.h - moleculedeserializer.h - matrixserialization.h - ) - -set(SOURCES - moleculeserializer.cpp - moleculedeserializer.cpp - matrixserialization.cpp - ) - -avogadro_add_library(AvogadroProtoCall ${HEADERS} ${SOURCES}) - -target_link_libraries(AvogadroProtoCall AvogadroIO protobuf) diff --git a/avogadro/protocall/matrixserialization.cpp b/avogadro/protocall/matrixserialization.cpp deleted file mode 100644 index 0dd911d8dc..0000000000 --- a/avogadro/protocall/matrixserialization.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "matrixserialization.h" - -#include -#include -#include - -#include "utils.h" - -namespace Avogadro { -namespace ProtoCall { -namespace MatrixSerialization { - -using google::protobuf::uint32; -using google::protobuf::uint64; -using google::protobuf::io::CodedInputStream; -using google::protobuf::io::CodedOutputStream; -using google::protobuf::io::ArrayInputStream; -using google::protobuf::io::ArrayOutputStream; - -size_t sizeOf(const Avogadro::Vector2& vec2) -{ - AVO_UNUSED(vec2); - - return 2 * sizeof(uint64); -} - -size_t sizeOf(const Avogadro::Vector3& vec3) -{ - AVO_UNUSED(vec3); - - return 3 * sizeof(uint64); -} - -size_t sizeOf(const Avogadro::MatrixX& matrix) -{ - // TODO varint encode the size ? ... - return (2 * sizeof(uint32)) + - (matrix.rows() * matrix.cols() * sizeof(uint64)); -} - -bool serializeInternal(const Avogadro::MatrixX& matrix, - google::protobuf::io::CodedOutputStream* stream) -{ - for (int row = 0; row < matrix.rows(); row++) { - for (int col = 0; col < matrix.cols(); col++) { - uint64 value = Utils::encodeDouble(matrix(row, col)); - - stream->WriteLittleEndian64(value); - if (stream->HadError()) - return false; - } - } - - return true; -} - -bool serialize(const Avogadro::Vector2& vec2, void* data, size_t size) -{ - ArrayOutputStream aos(data, size); - CodedOutputStream cos(&aos); - - return serialize(vec2, &cos); -} - -bool serialize(const Avogadro::Vector3& vec3, void* data, size_t size) -{ - ArrayOutputStream aos(data, size); - CodedOutputStream cos(&aos); - - return serialize(vec3, &cos); -} - -bool serialize(const Avogadro::MatrixX& matrix, void* data, size_t size) -{ - ArrayOutputStream aos(data, size); - CodedOutputStream cos(&aos); - - return serialize(matrix, &cos); -} - -bool serialize(const Avogadro::Vector2& vec2, - google::protobuf::io::CodedOutputStream* stream) -{ - return serializeInternal(vec2, stream); -} - -bool serialize(const Avogadro::Vector3& vec3, - google::protobuf::io::CodedOutputStream* stream) -{ - return serializeInternal(vec3, stream); -} - -bool serialize(const Avogadro::MatrixX& matrix, - google::protobuf::io::CodedOutputStream* stream) -{ - stream->WriteLittleEndian32(matrix.rows()); - if (stream->HadError()) - return false; - - stream->WriteLittleEndian32(matrix.cols()); - if (stream->HadError()) - return false; - - return serializeInternal(matrix, stream); -} - -bool deserialize(Avogadro::Vector2& vec2, const void* data) -{ - size_t size = sizeOf(vec2); - ArrayInputStream ais(data, size); - CodedInputStream cis(&ais); - - return deserialize(vec2, &cis); -} - -bool deserialize(Avogadro::Vector3& vec3, const void* data) -{ - size_t size = sizeOf(vec3); - ArrayInputStream ais(data, size); - CodedInputStream cis(&ais); - - return deserialize(vec3, &cis); -} - -bool deserialize(Avogadro::MatrixX& matrix, const void* data, size_t size) -{ - ArrayInputStream ais(data, size); - CodedInputStream cis(&ais); - - return deserialize(matrix, &cis); -} - -bool deserialize(Avogadro::Vector2& vec2, - google::protobuf::io::CodedInputStream* stream) -{ - for (int row = 0; row < 2; row++) { - uint64 tmp; - if (!stream->ReadLittleEndian64(&tmp)) - return false; - - vec2[row] = Utils::decodeDouble(tmp); - } - - return true; -} - -bool deserialize(Avogadro::Vector3& vec3, - google::protobuf::io::CodedInputStream* stream) -{ - for (int row = 0; row < 3; row++) { - uint64 tmp; - if (!stream->ReadLittleEndian64(&tmp)) - return false; - - vec3[row] = Utils::decodeDouble(tmp); - } - - return true; -} - -bool deserialize(Avogadro::MatrixX& matrix, - google::protobuf::io::CodedInputStream* stream) -{ - uint32 rows; - uint32 cols; - - if (!stream->ReadLittleEndian32(&rows)) { - return false; - } - - if (!stream->ReadLittleEndian32(&cols)) - return false; - - matrix.resize(rows, cols); - - for (uint32 row = 0; row < rows; row++) { - for (uint32 col = 0; col < cols; col++) { - uint64 tmp; - if (!stream->ReadLittleEndian64(&tmp)) - return false; - - matrix(row, col) = Utils::decodeDouble(tmp); - } - } - - return true; -} - -} // namespace MatrixSerialization -} // namespace ProtoCall -} // namespace Avogadro diff --git a/avogadro/protocall/matrixserialization.h b/avogadro/protocall/matrixserialization.h deleted file mode 100644 index 1b55e6758f..0000000000 --- a/avogadro/protocall/matrixserialization.h +++ /dev/null @@ -1,190 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "avogadroprotocallexport.h" - -#include -#include -#include - -#ifndef AVOGADRO_PROTOCALL_MATRIXSERIALIZATION_H -#define AVOGADRO_PROTOCALL_MATRIXSERIALIZATION_H - -namespace google { -namespace protobuf { -namespace io { -class CodedOutputStream; -class CodedInputStream; -} -} -} - -/** - * Namespace contain utility methods to serialize and deserialize vectors and - * matrixes - */ -namespace Avogadro { -namespace ProtoCall { -namespace MatrixSerialization { - -/** - * @return the size of Avogadro::Vector2 within byte stream. - */ -AVOGADROPROTOCALL_EXPORT size_t sizeOf(const Avogadro::Vector2& vec2); - -/** - * @return the size of Avogadro::Vector3 within byte stream. - */ -AVOGADROPROTOCALL_EXPORT size_t sizeOf(const Avogadro::Vector3& vec3); - -/** - * @return the size of Avogadro::MatrixX within byte stream. - */ -AVOGADROPROTOCALL_EXPORT size_t sizeOf(const Avogadro::MatrixX& matrix); - -/** - * Serialize Avogadro::Vector2 instance to buffer. - * - * @param vec2 The vector to serialize. - * @param data The buffer to serialize into. - * @param size The buffer size. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool serialize(const Avogadro::Vector2& vec2, - void* data, size_t size); - -/** - * Serialize Avogadro::Vector3 instance to buffer. - * - * @param vec3 The vector to serialize. - * @param data The buffer to serialize into. - * @param size The buffer size. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool serialize(const Avogadro::Vector3& vec3, - void* data, size_t size); - -/** - * Serialize Avogadro::MatrixX instance to buffer. - * - * @param matrix The matrix to serialize. - * @param data The buffer to serialize into. - * @param size The buffer size. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool serialize(const Avogadro::MatrixX& matrix, - void* data, size_t size); - -/** - * Serialize Avogadro::Vector2 instance to stream. - * - * @param vec2 The vector to serialize. - * @param stream The stream to serialize into. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool serialize( - const Avogadro::Vector2& vec2, - google::protobuf::io::CodedOutputStream* stream); - -/** - * Serialize Avogadro::Vector3 instance to stream. - * - * @param vec3 The vector to serialize. - * @param stream The stream to serialize into. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool serialize( - const Avogadro::Vector3& vec3, - google::protobuf::io::CodedOutputStream* stream); - -/** - * Serialize Avogadro::MatrixX instance to stream. - * - * @param matrix The matrix to serialize. - * @param stream The stream to serialize into. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool serialize( - const Avogadro::MatrixX& matrix, - google::protobuf::io::CodedOutputStream* stream); - -/** - * Deserialize Avogadro::Vector2 instance from buffer. - * - * @param vec2 The vector to deserialize into. - * @param data The buffer to read the instance from. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool deserialize(Avogadro::Vector2& vec2, - const void* data); - -/** - * Deserialize Avogadro::Vector3 instance from buffer. - * - * @param vec3 The vector to deserialize into. - * @param data The buffer to read the instance from. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool deserialize(Avogadro::Vector3& vec3, - const void* data); - -/** - * Deserialize Avogadro::MatrixX instance from buffer. - * - * @param matrix The matrix to deserialize into. - * @param data The buffer to read the instance from. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool deserialize(Avogadro::MatrixX& matrix, - const void* data, size_t size); - -/** - * Deserialize Avogadro::Vector2 instance from stream. - * - * @param vec2 The vector to deserialize into. - * @param stream The stream to read the instance from. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool deserialize( - Avogadro::Vector2& vec2, google::protobuf::io::CodedInputStream* stream); - -/** - * Deserialize Avogadro::Vector3 instance from stream. - * - * @param vec3 The vector to deserialize into. - * @param stream The stream to read the instance from. - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool deserialize( - Avogadro::Vector3& vec3, google::protobuf::io::CodedInputStream* stream); - -/** - * Deserialize Avogadro::MatrixX instance from stream. - * - * @param matrix The matrix to deserialize into. - * @param stream The stream to read the instance from. - * - * - * @return true if successful, false otherwise. - */ -AVOGADROPROTOCALL_EXPORT bool deserialize( - Avogadro::MatrixX& matrix, google::protobuf::io::CodedInputStream* stream); - -} // namespace MatrixSerialization -} // namespace ProtoCall -} // namespace Avogadro - -#endif /* MATRIXSERIALIZATION_H_ */ diff --git a/avogadro/protocall/moleculedeserializer.cpp b/avogadro/protocall/moleculedeserializer.cpp deleted file mode 100644 index f6cec53137..0000000000 --- a/avogadro/protocall/moleculedeserializer.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "moleculedeserializer.h" - -#include "matrixserialization.h" -#include -#include -#include - -#include - -using Avogadro::Core::Molecule; -using Avogadro::Io::FileFormat; -using Avogadro::Io::FileFormatManager; - -using google::protobuf::io::ArrayOutputStream; -using google::protobuf::io::CodedOutputStream; -using google::protobuf::io::ArrayInputStream; -using google::protobuf::io::CodedInputStream; -using google::protobuf::uint32; -using google::protobuf::uint8; - -namespace Avogadro { -namespace Core { - -MoleculeDeserializer::MoleculeDeserializer(Molecule* molecule) - : m_molecule(molecule) -{ -} - -bool MoleculeDeserializer::deserialize(const void* data, size_t size) -{ - ArrayInputStream ais(data, size); - CodedInputStream cis(&ais); - - // Read the atoms - if (!this->deserializeAtomicNumbers(&cis)) - return false; - - // Read the positions2d - if (!this->deserializePositions2d(&cis)) - return false; - - // Read the positions3d - if (!this->deserializePostions3d(&cis)) - return false; - - // Read bond pairs - if (!this->deserializeBondPairs(&cis)) - return false; - - // Read bond orders - if (!this->deserializeBondOrders(&cis)) - return false; - - return true; -} - -bool MoleculeDeserializer::deserializeAtomicNumbers( - google::protobuf::io::CodedInputStream* stream) -{ - // Read the atoms - m_molecule->clearAtoms(); - uint32 numberOfAtoms; - if (!stream->ReadLittleEndian32(&numberOfAtoms)) - return false; - for (uint32 i = 0; i < numberOfAtoms; i++) { - unsigned char atom; - if (!stream->ReadRaw(&atom, sizeof(unsigned char))) - return false; - m_molecule->addAtom(atom); - } - - return true; -} - -bool MoleculeDeserializer::deserializePositions2d( - google::protobuf::io::CodedInputStream* stream) -{ - // Get the count - uint32 posCount; - if (!stream->ReadLittleEndian32(&posCount)) - return false; - // Clear an current positions - m_molecule->atomPositions2d().clear(); - for (uint32 i = 0; i < posCount; i++) { - Avogadro::Vector2 vec2; - if (!ProtoCall::MatrixSerialization::deserialize(vec2, stream)) - return false; - m_molecule->atomPositions2d().push_back(vec2); - } - - return true; -} - -bool MoleculeDeserializer::deserializePostions3d( - google::protobuf::io::CodedInputStream* stream) -{ - // Get the count - uint32 posCount; - if (!stream->ReadLittleEndian32(&posCount)) - return false; - // Clear an current positions - m_molecule->atomPositions3d().clear(); - for (uint32 i = 0; i < posCount; i++) { - Avogadro::Vector3 vec3; - if (!ProtoCall::MatrixSerialization::deserialize(vec3, stream)) - return false; - m_molecule->atomPositions3d().push_back(vec3); - } - - return true; -} - -bool MoleculeDeserializer::deserializeBondPairs( - google::protobuf::io::CodedInputStream* stream) -{ - uint32 bondCount; - if (!stream->ReadLittleEndian32(&bondCount)) - return false; - - // Clear and bond pairs - m_molecule->bondPairs().clear(); - - for (uint32 i = 0; i < bondCount; i++) { - uint32 from, to; - if (!stream->ReadLittleEndian32(&from)) - return false; - if (!stream->ReadLittleEndian32(&to)) - return false; - std::pair bond; - bond.first = from; - bond.second = to; - m_molecule->bondPairs().push_back(bond); - } - - return true; -} - -bool MoleculeDeserializer::deserializeBondOrders( - google::protobuf::io::CodedInputStream* stream) -{ - uint32 bondOrderCount; - if (!stream->ReadLittleEndian32(&bondOrderCount)) - return false; - - // Clear bond order - m_molecule->bondOrders().clear(); - - for (uint32 i = 0; i < bondOrderCount; i++) { - unsigned char bond; - if (!stream->ReadRaw(&bond, sizeof(unsigned char))) - return false; - - m_molecule->bondOrders().push_back(bond); - } - - return true; -} - -} // namespace Core -} // namespace Avogadro diff --git a/avogadro/protocall/moleculedeserializer.h b/avogadro/protocall/moleculedeserializer.h deleted file mode 100644 index 3096c3f427..0000000000 --- a/avogadro/protocall/moleculedeserializer.h +++ /dev/null @@ -1,85 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#ifndef AVOGADRO_PROTOCALL_MOLECULEDESERIALIZER_H -#define AVOGADRO_PROTOCALL_MOLECULEDESERIALIZER_H - -#include "avogadro/core/molecule.h" -#include "avogadroprotocallexport.h" -#include -#include - -namespace Avogadro { -namespace Core { - -/** - * @class MoleculeDeserializer moleculedeserializer.h - * - * @brief Implementation of ProtoCall::Serialization::Deserializer - * - */ -class AVOGADROPROTOCALL_EXPORT MoleculeDeserializer - : public ProtoCall::Serialization::Deserializer -{ -public: - /** - * @param molecule The molecule to deserialize into. - */ - MoleculeDeserializer(Molecule* molecule); - - /** - * Deserialize buffer into molecules. - * - * @param data The buffer containing the molecule byte stream. - * @param size The size of the buffer. - * - * @return true if successful, false otherwise. - */ - bool deserialize(const void* data, size_t size); - -private: - /** - * Deserialize bond pairs from stream. - * - * @return true if successful, false otherwise. - */ - bool deserializeBondPairs(google::protobuf::io::CodedInputStream* stream); - - /** - * - * Deserialize bond order from stream. - * - * @return true if successful, false otherwise. - */ - bool deserializeBondOrders(google::protobuf::io::CodedInputStream* stream); - - /** - * Deserialize atomic numbers from stream. - * - * @return true if successful, false otherwise. - */ - bool deserializeAtomicNumbers(google::protobuf::io::CodedInputStream* stream); - - /** - * Deserialize 2d positions from stream. - * - * @return true if successful, false otherwise. - */ - bool deserializePositions2d(google::protobuf::io::CodedInputStream* stream); - - /** - * Deserialize 3d positions from stream. - * - * @return true if successful, false otherwise. - */ - bool deserializePostions3d(google::protobuf::io::CodedInputStream* stream); - - Molecule* m_molecule; -}; - -} // namespace Core -} // namespace Avogadro - -#endif diff --git a/avogadro/protocall/moleculeserializer.cpp b/avogadro/protocall/moleculeserializer.cpp deleted file mode 100644 index ea8e876dc4..0000000000 --- a/avogadro/protocall/moleculeserializer.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "moleculeserializer.h" - -#include "matrixserialization.h" -#include -#include -#include - -#include - -namespace Avogadro { -namespace Core { - -using Avogadro::Io::FileFormat; -using Avogadro::Io::FileFormatManager; - -using google::protobuf::io::ArrayOutputStream; -using google::protobuf::io::CodedOutputStream; -using google::protobuf::io::ArrayInputStream; -using google::protobuf::io::CodedInputStream; -using google::protobuf::uint32; -using google::protobuf::uint8; - -MoleculeSerializer::MoleculeSerializer(const Avogadro::Core::Molecule* molecule) - : m_molecule(molecule) -{ -} - -bool MoleculeSerializer::serialize(void* data, size_t size_) -{ - ArrayOutputStream aos(data, size_); - CodedOutputStream cos(&aos); - - // Write atomic numbers - if (!this->serializeAtomicNumbers(&cos)) - return false; - - // Write position2d - if (!this->serializePositons2d(&cos)) - return false; - - // Write position3d - if (!this->serializePostions3d(&cos)) - return false; - - // Write bondPairs - if (!this->serializeBondPairs(&cos)) - return false; - - // Write bondOrders - if (!this->serializeBondOrders(&cos)) - return false; - - return true; -} - -size_t MoleculeSerializer::size() -{ - // atomicNumbers - size_t moleSize = - sizeof(uint32) + m_molecule->atomicNumbers().size() * sizeof(unsigned char); - - // positions2d - moleSize += sizeof(uint32); - std::vector pos2d = m_molecule->atomPositions2d(); - for (std::vector::iterator it = pos2d.begin(); - it != pos2d.end(); ++it) { - moleSize += ProtoCall::MatrixSerialization::sizeOf(*it); - } - - // positions3d - moleSize += sizeof(uint32); - std::vector pos3d = m_molecule->atomPositions3d(); - for (std::vector::iterator it = pos3d.begin(); - it != pos3d.end(); ++it) { - moleSize += ProtoCall::MatrixSerialization::sizeOf(*it); - } - - // bondPairs - moleSize += this->sizeOfBondPairs(); - // bondOrder - moleSize += this->sizeOfBondOrders(); - - return moleSize; -} - -bool MoleculeSerializer::serializeAtomicNumbers( - google::protobuf::io::CodedOutputStream* stream) -{ - // Write atomic numbers - uint32 numberOfAtoms = m_molecule->atomicNumbers().size(); - stream->WriteLittleEndian32(numberOfAtoms); - if (stream->HadError()) - return false; - std::vector atomicNumbers = m_molecule->atomicNumbers(); - stream->WriteRaw(&atomicNumbers[0], numberOfAtoms * sizeof(unsigned char)); - if (stream->HadError()) - return false; - - return true; -} - -bool MoleculeSerializer::serializePositons2d( - google::protobuf::io::CodedOutputStream* stream) -{ - std::vector pos2d = m_molecule->atomPositions2d(); - stream->WriteLittleEndian32(pos2d.size()); - if (stream->HadError()) - return false; - for (std::vector::iterator it = pos2d.begin(); - it != pos2d.end(); ++it) { - if (!ProtoCall::MatrixSerialization::serialize(*it, stream)) - return false; - } - - return true; -} - -bool MoleculeSerializer::serializePostions3d( - google::protobuf::io::CodedOutputStream* stream) -{ - // position3d - std::vector pos3d = m_molecule->atomPositions3d(); - stream->WriteLittleEndian32(pos3d.size()); - if (stream->HadError()) - return false; - for (std::vector::iterator it = pos3d.begin(); - it != pos3d.end(); ++it) { - if (!ProtoCall::MatrixSerialization::serialize(*it, stream)) - return false; - } - - return true; -} - -size_t MoleculeSerializer::sizeOfBondPairs() -{ - return sizeof(uint32) + m_molecule->bondPairs().size() * (2 * sizeof(uint32)); -} - -bool MoleculeSerializer::serializeBondPairs( - google::protobuf::io::CodedOutputStream* stream) -{ - // Write the number of pairs - stream->WriteLittleEndian32(m_molecule->bondPairs().size()); - - if (stream->HadError()) - return false; - - for (std::vector>::const_iterator it = - m_molecule->bondPairs().begin(); - it != m_molecule->bondPairs().end(); ++it) { - std::pair bond = *it; - stream->WriteLittleEndian32(bond.first); - if (stream->HadError()) - return false; - stream->WriteLittleEndian32(bond.second); - if (stream->HadError()) - return false; - } - - return true; -} - -size_t MoleculeSerializer::sizeOfBondOrders() -{ - return sizeof(uint32) + - m_molecule->bondOrders().size() * sizeof(unsigned char); -} - -bool MoleculeSerializer::serializeBondOrders( - google::protobuf::io::CodedOutputStream* stream) -{ - stream->WriteLittleEndian32(m_molecule->bondOrders().size()); - if (stream->HadError()) - return false; - - stream->WriteRaw(&m_molecule->bondOrders()[0], - m_molecule->bondOrders().size()); - if (stream->HadError()) - return false; - - return true; -} - -} // namespace Core -} // namespace Avogadro diff --git a/avogadro/protocall/moleculeserializer.h b/avogadro/protocall/moleculeserializer.h deleted file mode 100644 index 950d925275..0000000000 --- a/avogadro/protocall/moleculeserializer.h +++ /dev/null @@ -1,100 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#ifndef AVOGADRO_PROTOCALL_MOLECULESERIALIZER_H -#define AVOGADRO_PROTOCALL_MOLECULESERIALIZER_H - -#include "avogadro/core/molecule.h" -#include "avogadroprotocallexport.h" - -#include -#include - -namespace Avogadro { -namespace Core { - -/** - * @class MoleculeSerializer moleculeserializer.h - * - * @brief Implementation of ProtoCall::Serialization::Serializer - * - */ -class AVOGADROPROTOCALL_EXPORT MoleculeSerializer - : public ProtoCall::Serialization::Serializer -{ -public: - /** - * @param molecule The molecule being serialized - */ - MoleculeSerializer(const Avogadro::Core::Molecule* molecule); - - /** - * Serialize the molecule to that buffer provided. - * - * @param data The buffer to serialize the molecule into. - * @param size The size of the buffer. - * - * @return true if successful, false otherwise. - */ - bool serialize(void* data, size_t size); - - /** - * @return The size of the serialized molecule when written to byte stream. - */ - size_t size(); - -private: - /** - * @return The size of the bond pairs will take in the byte stream. - */ - size_t sizeOfBondPairs(); - - /** - * Serialize the bond pairs to the stream. - * - * @return true if successful, false otherwise. - */ - bool serializeBondPairs(google::protobuf::io::CodedOutputStream* stream); - - /** - * @return The size of the bond orders will take in the byte stream. - */ - size_t sizeOfBondOrders(); - - /** - * Serialize the bond pairs to the stream. - * - * @return true if successful, false otherwise. - */ - bool serializeBondOrders(google::protobuf::io::CodedOutputStream* stream); - - /** - * Serialize the atomic numbers to the stream. - * - * @return true if successful, false otherwise. - */ - bool serializeAtomicNumbers(google::protobuf::io::CodedOutputStream* stream); - - /** - * Serialize the 2d positions to the stream. - * - * @return true if successful, false otherwise. - */ - bool serializePositons2d(google::protobuf::io::CodedOutputStream* stream); - - /** - * Serialize the 3d positions to the stream. - * - * @return true if successful, false otherwise. - */ - bool serializePostions3d(google::protobuf::io::CodedOutputStream* stream); - - const Avogadro::Core::Molecule* m_molecule; -}; - -} // namespace Core -} // namespace Avogadro - -#endif diff --git a/avogadro/protocall/utils.h b/avogadro/protocall/utils.h deleted file mode 100644 index bfea389555..0000000000 --- a/avogadro/protocall/utils.h +++ /dev/null @@ -1,60 +0,0 @@ -#include - -/** - * namespace containing utility functions for encoding and decoding - * floats and doubles. - */ -namespace Avogadro { -namespace ProtoCall { -namespace Utils { - -using google::protobuf::uint32; -using google::protobuf::uint64; - -inline uint32 encodeFloat(float value) -{ - union - { - float f; - uint32 i; - }; - f = value; - return i; -} - -inline float decodeFloat(uint32 value) -{ - union - { - float f; - uint32 i; - }; - i = value; - return f; -} - -inline uint64 encodeDouble(double value) -{ - union - { - double f; - uint64 i; - }; - f = value; - return i; -} - -inline double decodeDouble(uint64 value) -{ - union - { - double f; - uint64 i; - }; - i = value; - return f; -} - -} // Utils namespace -} // ProtoCall namespace -} // Avogadro namespace diff --git a/avogadro/qtplugins/CMakeLists.txt b/avogadro/qtplugins/CMakeLists.txt index 88a42dfba5..4e43b0839b 100644 --- a/avogadro/qtplugins/CMakeLists.txt +++ b/avogadro/qtplugins/CMakeLists.txt @@ -192,10 +192,6 @@ if (USE_OPENGL) endif() # other optional plugins -if (USE_PROTOCALL) - add_subdirectory(clientserver) -endif() - if(BUILD_GPL_PLUGINS) # qtaimcurvature.h/cpp contains GPL licensed code: add_subdirectory(qtaim) diff --git a/avogadro/qtplugins/clientserver/CMakeLists.txt b/avogadro/qtplugins/clientserver/CMakeLists.txt deleted file mode 100644 index d434f719a4..0000000000 --- a/avogadro/qtplugins/clientserver/CMakeLists.txt +++ /dev/null @@ -1,75 +0,0 @@ -find_package(protobuf REQUIRED NO_MODULE) -include_directories(SYSTEM ${protobuf_INCLUDE_DIRS}) - -find_package(ProtoCall REQUIRED NO_MODULE) -include_directories(SYSTEM ${ProtoCall_INCLUDE_DIRS}) - -find_package(VTK COMPONENTS vtkParallelCore) -set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS ${VTK_DEFINITIONS}) -include_directories(${VTK_INCLUDE_DIRS}) - -find_package(Qt4 COMPONENTS QtCore QtGui QtOpenGL REQUIRED) -include_directories(SYSTEM ${QT_INCLUDES}) -add_definitions(${QT_DEFINITIONS}) - - -protocallc(_protocall_common_source - _protocall_service_source - _protocall_proxy_source - _protocall_include_dir - "remote.proto") - -include_directories(${_protocall_include_dir} - ${CMAKE_SOURCE_DIR}/avogadro/protocall - ${CMAKE_BINARY_DIR}/avogadro/protocall - ${CMAKE_CURRENT_SOURCE_DIR}) - -# Build server -set(_server_source - avogadroserver.cpp - avoremotemoleculeservice.cpp - avoremotefilesystemservice.cpp - ) - -add_executable(avogadroserver - ${_protocall_common_source} - ${_protocall_service_source} - ${_server_source} - ) - -target_link_libraries(avogadroserver - PRIVATE vtkParallelCore AvogadroProtoCall) - -install(TARGETS avogadroserver - RUNTIME DESTINATION ${INSTALL_RUNTIME_DIR} - BUNDLE DESTINATION . - ) - -# Build plugin -foreach(_file ${_protocall_common_source} ${_protocall_proxy_source}) - set_source_files_properties(${_file} PROPERTIES SKIP_AUTOMOC TRUE) -endforeach() - -set(_plugin_src "clientserver.cpp;connectionsettingsdialog.cpp") -list(APPEND _plugin_src ${_protocall_common_source}) -list(APPEND _plugin_src ${_protocall_proxy_source}) -list(APPEND _plugin_src - filedialogmodel.cpp - filedialogfilter.cpp - filedialog.cpp -) - -set(_ui_src "connectionsettingsdialog.ui") -list(APPEND _ui_src "filedialog.ui") - -avogadro_plugin(ClientServer - "Client server operations." - ExtensionPlugin - "clientserver.h" - ClientServer - "${_plugin_src}" - "${_ui_src}" - ) - -target_link_libraries(ClientServer - PRIVATE AvogadroIO vtkParallelCore AvogadroProtoCall) diff --git a/avogadro/qtplugins/clientserver/avogadroserver.cpp b/avogadro/qtplugins/clientserver/avogadroserver.cpp deleted file mode 100644 index a4e7ffd548..0000000000 --- a/avogadro/qtplugins/clientserver/avogadroserver.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "avogadroserver.h" -#include "RemoteFileSystemService_Dispatcher.pb.h" -#include "RemoteMoleculeService_Dispatcher.pb.h" -#include "avoremotefilesystemservice.h" -#include "avoremotemoleculeservice.h" - -#include -#include -#include -#include - -#include -#include - -#include - -using std::vector; -using std::list; - -using ProtoCall::Runtime::vtkCommunicatorChannel; -using ProtoCall::Runtime::RpcChannel; - -AvogadroServer::AvogadroServer() -{ - // It's essential to initialize the socket controller to initialize sockets on - // Windows. - vtkSocketController* controller = vtkSocketController::New(); - controller->Initialize(); - controller->Delete(); -} - -AvogadroServer::~AvogadroServer() -{ -} - -void AvogadroServer::listen(int port) -{ - m_socket = vtkServerSocket::New(); - if (m_socket->CreateServer(port) != 0) { - std::cerr << "Failed to set up server socket.\n"; - m_socket->Delete(); - return; - } - - std::cout << "Listening on " << port << std::endl; - - while (true) - processConnectionEvents(); -} - -void AvogadroServer::accept() -{ - vtkCommunicatorChannel* channel = nullptr; - - while (!channel) { - vtkClientSocket* clientSocket = nullptr; - clientSocket = m_socket->WaitForConnection(100); - - if (!clientSocket) - return; - - vtkSocketController* controller = vtkSocketController::New(); - vtkSocketCommunicator* comm = - vtkSocketCommunicator::SafeDownCast(controller->GetCommunicator()); - comm->SetReportErrors(0); - comm->SetSocket(clientSocket); - clientSocket->FastDelete(); - channel = new vtkCommunicatorChannel(comm); - - comm->ServerSideHandshake(); - } - - m_clientChannels.push_back(channel); -} - -void AvogadroServer::processConnectionEvents() -{ - int timeout = 200; - vector socketsToSelect; - vector channels; - - for (list::iterator it = m_clientChannels.begin(); - it != m_clientChannels.end(); ++it) { - - vtkCommunicatorChannel* channel = *it; - - vtkSocketCommunicator* comm = channel->communicator(); - vtkSocket* socket = comm->GetSocket(); - if (socket && socket->GetConnected()) { - socketsToSelect.push_back(socket->GetSocketDescriptor()); - channels.push_back(channel); - } - } - - // Add server socket first, we are looking for incoming connections - socketsToSelect.push_back(m_socket->GetSocketDescriptor()); - - int selectedIndex = -1; - int result = vtkSocket::SelectSockets( - &socketsToSelect[0], socketsToSelect.size(), timeout, &selectedIndex); - if (result < 0) { - std::cerr << "Socket select failed with error code: " << result - << std::endl; - return; - } - - if (selectedIndex == -1) - return; - - // Are we dealing with an incoming connection? - if (selectedIndex == socketsToSelect.size() - 1) { - accept(); - } - // We have a message waiting from a client - else { - RpcChannel* channel = channels[selectedIndex]; - if (!channel->receive(true)) { - // Connection lost remove channel from list - list::iterator it = - std::find(m_clientChannels.begin(), m_clientChannels.end(), channel); - m_clientChannels.erase(it); - } - } -} - -void usage() -{ - std::cerr << "Usage: avogadroserver port" << std::endl; -} - -int main(int argc, char* argv[]) -{ - if (argc > 2) { - usage(); - return 1; - } - - int port = 6060; - - if (argc == 2) - port = atoi(argv[1]); - - // Register the RPC service - ProtoCall::Runtime::ServiceManager* mgr = - ProtoCall::Runtime::ServiceManager::instance(); - AvoRemoteMoleculeService service; - AvoRemoteMoleculeService::Dispatcher dispatcher(&service); - mgr->registerService(&dispatcher); - AvoRemoteFileSystemService remoteFileSystemService; - AvoRemoteFileSystemService::Dispatcher remoteFileSystemDispatcher( - &remoteFileSystemService); - mgr->registerService(&remoteFileSystemDispatcher); - - AvogadroServer server; - server.listen(port); -} diff --git a/avogadro/qtplugins/clientserver/avogadroserver.h b/avogadro/qtplugins/clientserver/avogadroserver.h deleted file mode 100644 index e26303699e..0000000000 --- a/avogadro/qtplugins/clientserver/avogadroserver.h +++ /dev/null @@ -1,41 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#ifndef AVOGADROSERVER_H -#define AVOGADROSERVER_H - -#include -#include - -namespace ProtoCall { -namespace Runtime { -class vtkCommunicatorChannel; -} -} - -class vtkServerSocket; - -/** - * @class AvogadroServer avogadroserver.h - * - * @brief Simple server implementation based on vtkServerSocket, accepting - * connections and processing ProtoCall requests. - */ -class AvogadroServer -{ -public: - AvogadroServer(); - virtual ~AvogadroServer(); - void listen(int port); - -private: - vtkServerSocket* m_socket; - std::list m_clientChannels; - - void processConnectionEvents(); - void accept(); -}; - -#endif /* AVOGADROSERVER_H */ diff --git a/avogadro/qtplugins/clientserver/avoremotefilesystemservice.cpp b/avogadro/qtplugins/clientserver/avoremotefilesystemservice.cpp deleted file mode 100644 index 7f2cd90489..0000000000 --- a/avogadro/qtplugins/clientserver/avoremotefilesystemservice.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "avoremotefilesystemservice.h" -#include "filedialogmodel.h" -#include -#include - -#if defined(_WIN32) -#define _WIN32_IE 0x0400 // special folder support -#define _WIN32_WINNT 0x0400 // shared folder support -#include // _getcwd -#include // SHGetFolderPath -#include // for strcasecmp -#include // stat -#include // FindFirstFile, FindNextFile, FindClose, ... -#define vtkPVServerFileListingGetCWD _getcwd -#else -#include // opendir, readdir, closedir -#include // errno -#include // getenv -#include // strerror -#include // stat -#include // DIR, struct dirent, struct stat -#include // access, getcwd -#define vtkPVServerFileListingGetCWD getcwd -#endif -#if defined(__APPLE__) -#include -#include -#endif - -#include -#include -#include -#include - -#include - -using std::string; -using std::ostringstream; - -AvoRemoteFileSystemService::~AvoRemoteFileSystemService() -{ -} - -void ls(const std::string path, Listing* output) -{ - vtkNew dir; - if (!dir->Open(path.c_str())) { - ostringstream msg; - msg << "Unable to open directory: " << path; - output->setErrorString(msg.str()); - return; - } - - for (vtkIdType i = 0; i < dir->GetNumberOfFiles(); i++) { - const char* filepath = dir->GetFile(i); - - Path* path = output->add_paths(); - path->set_path(filepath); - } -} - -void AvoRemoteFileSystemService::ls(const Path* input, Listing* output, - ::google::protobuf::Closure* done) -{ - string dirPath; - - if (input->has_path()) { - dirPath = input->path(); - } - // List the current working directory - else { - dirPath = vtksys::SystemTools::GetCurrentWorkingDirectory().c_str(); - } - - ls(dirPath, output); - done->Run(); -} - -inline void vtkPVFileInformationAddTerminatingSlash(std::string& name) -{ - if (name.size() > 0) { - char last = *(name.end() - 1); - if (last != '/' && last != '\\') { -#if defined(_WIN32) - name += "\\"; -#else - name += "/"; -#endif - } - } -} - -bool isHidden(const string& name, const string& path) -{ - bool hidden; -#if defined(_WIN32) - LPCSTR fp = path; - DWORD flags = GetFileAttributes(fp); - hidden = (flags & FILE_ATTRIBUTE_HIDDEN) ? true : false; -#else - hidden = (name[0] == '.') ? true : false; -#endif - return hidden; -} - -void AvoRemoteFileSystemService::ls(string path, Listing* output) -{ - output->mutable_path()->set_path(path); - -#if defined(_WIN32) - - vtkErrorMacro("GetDirectoryListing() cannot be called on Windows systems."); - return; - -#else - - std::string prefix = path; - vtkPVFileInformationAddTerminatingSlash(prefix); - - if (vtksys::SystemTools::FileExists(path.c_str())) { - output->mutable_path()->set_type( - (vtksys::SystemTools::FileIsDirectory(path.c_str())) - ? FileDialogModel::DIRECTORY - : FileDialogModel::SINGLE_FILE); - } - - // Open the directory and make sure it exists. - DIR* dir = opendir(path.c_str()); - if (!dir) { - // Could add check of errno here. - return; - } - - // Loop through the directory listing. - while (const dirent* d = readdir(dir)) { - // Skip the special directory entries. - if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) { - continue; - } - Path* entry = output->add_paths(); - - string fullPath = prefix + d->d_name; - - entry->set_name(string(d->d_name)); - entry->set_path(fullPath); - entry->set_hidden(isHidden(entry->name(), entry->path())); - - FileDialogModel::FileType type = FileDialogModel::INVALID; - - if (vtksys::SystemTools::FileExists(fullPath.c_str())) { - type = (vtksys::SystemTools::FileIsDirectory(fullPath.c_str())) - ? FileDialogModel::DIRECTORY - : FileDialogModel::SINGLE_FILE; - } - - entry->set_type(type); - } - - closedir(dir); -#endif -} - -void AvoRemoteFileSystemService::cwd(Path* output, - ::google::protobuf::Closure* done) -{ - std::string path = vtksys::SystemTools::GetCurrentWorkingDirectory().c_str(); - - output->set_path(path); - - done->Run(); -} - -void AvoRemoteFileSystemService::separator(Separator* output, - ::google::protobuf::Closure* done) -{ -#if defined(_WIN32) && !defined(__CYGWIN__) - output->set_separator("\\"); -#else - output->set_separator("/"); -#endif - - done->Run(); -} - -void AvoRemoteFileSystemService::absolutePath(const Path* input, Path* output, - ::google::protobuf::Closure* done) -{ - std::string ret = input->name(); -#if defined(WIN32) - if (!IsUncPath(input->name()) && !IsNetworkPath(input->name())) -#endif - { - ret = vtksys::SystemTools::CollapseFullPath(input->name().c_str(), - input->path().c_str()); - } - - output->set_path(ret); - output->set_name(input->name()); - - done->Run(); -} diff --git a/avogadro/qtplugins/clientserver/avoremotefilesystemservice.h b/avogadro/qtplugins/clientserver/avoremotefilesystemservice.h deleted file mode 100644 index 6df1a8fe03..0000000000 --- a/avogadro/qtplugins/clientserver/avoremotefilesystemservice.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#ifndef AVOREMOTEFILESYSTEMSERVICE_H -#define AVOREMOTEFILESYSTEMSERVICE_H - -#include "RemoteFileSystemService.pb.h" - -/** - * @class AvoRemoteFileSystemService avoremotefilesystemservice.h - * - * @brief Server side implementation of RemoteFileSystemService. Provides - * methods for browsing a remote filesystem. - */ -class AvoRemoteFileSystemService : public RemoteFileSystemService -{ -public: - virtual ~AvoRemoteFileSystemService(); - - void ls(const Path* input, Listing* output, - ::google::protobuf::Closure* done); - - void cwd(Path* output, ::google::protobuf::Closure* done); - - void separator(Separator* output, ::google::protobuf::Closure* done); - - void specialDirectories(Paths* output, ::google::protobuf::Closure* done){}; - void absolutePath(const Path* input, Path* output, - ::google::protobuf::Closure* done); - -private: - void ls(const std::string path, Listing* output); -}; - -#endif /* AVOREMOTEFILESYSTEMSERVICE_H */ diff --git a/avogadro/qtplugins/clientserver/avoremotemoleculeservice.cpp b/avogadro/qtplugins/clientserver/avoremotemoleculeservice.cpp deleted file mode 100644 index 96c911cc17..0000000000 --- a/avogadro/qtplugins/clientserver/avoremotemoleculeservice.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "avoremotemoleculeservice.h" - -#include -#include -#include -#include -#include - -using Avogadro::Core::Molecule; -using std::string; - -AvoRemoteMoleculeService::~AvoRemoteMoleculeService() -{ -} - -void AvoRemoteMoleculeService::open(const OpenRequest* input, - OpenResponse* output, - ::google::protobuf::Closure* done) -{ - - string path = input->path(); - - Avogadro::Io::FileFormatManager& mgr = - Avogadro::Io::FileFormatManager::instance(); - Molecule molecule; - - // Try and read the file - if (!mgr.readFile(molecule, path)) { - output->setErrorString(mgr.error()); - done->Run(); - return; - } - - // If we where successful send the result back - output->mutable_molecule()->set(&molecule); - done->Run(); -} - -void AvoRemoteMoleculeService::fileFormats(FileFormats* formats, - ::google::protobuf::Closure* done) -{ - Avogadro::Io::FileFormatManager& mgr = - Avogadro::Io::FileFormatManager::instance(); - - std::vector fileFormats = mgr.fileFormats(); - for (std::vector::iterator iter = - fileFormats.begin(); - iter != fileFormats.end(); ++iter) { - FileFormat* format = formats->add_formats(); - format->set_name((*iter)->name()); - - std::vector extensions = (*iter)->fileExtensions(); - for (std::vector::iterator extIter = extensions.begin(); - extIter != extensions.end(); ++extIter) { - format->add_extension(*extIter); - } - } - - done->Run(); -} diff --git a/avogadro/qtplugins/clientserver/avoremotemoleculeservice.h b/avogadro/qtplugins/clientserver/avoremotemoleculeservice.h deleted file mode 100644 index 3426f80906..0000000000 --- a/avogadro/qtplugins/clientserver/avoremotemoleculeservice.h +++ /dev/null @@ -1,28 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#ifndef AVOREMOTEMOLECULESERVICE_H -#define AVOREMOTEMOLECULESERVICE_H - -#include "RemoteMoleculeService.pb.h" - -/** - * @class AvoRemoteMoleculeService avoremotemoleculeservice.h - * - * @brief The server side implementation of the RemoteMoleculeService, provides - * functionality to open a molecule on a remote system. - */ -class AvoRemoteMoleculeService : public RemoteMoleculeService -{ -public: - virtual ~AvoRemoteMoleculeService(); - - void open(const OpenRequest* input, OpenResponse* output, - ::google::protobuf::Closure* done); - - void fileFormats(FileFormats* formats, ::google::protobuf::Closure* done); -}; - -#endif /* AVOREMOTEMOLECULESERVICE_H */ diff --git a/avogadro/qtplugins/clientserver/clientserver.cpp b/avogadro/qtplugins/clientserver/clientserver.cpp deleted file mode 100644 index af337c5617..0000000000 --- a/avogadro/qtplugins/clientserver/clientserver.cpp +++ /dev/null @@ -1,301 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#include "clientserver.h" -#include "RemoteMoleculeService.pb.h" -#include "connectionsettingsdialog.h" -#include "filedialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -#include -#include - -using namespace google::protobuf; -using namespace ProtoCall::Runtime; - -namespace Avogadro { -namespace QtPlugins { - -ClientServer::ClientServer(QObject* parent_) - : Avogadro::QtGui::ExtensionPlugin(parent_), m_dialog(nullptr), - m_openAction(new QAction(this)), m_settingsAction(new QAction(this)), - m_molecule(nullptr), m_controller(nullptr), m_communicator(nullptr), - m_channel(nullptr) -{ - m_openAction->setEnabled(true); - m_openAction->setText("Open Molecule"); - m_actions.append(m_openAction); - - m_settingsAction->setEnabled(true); - m_settingsAction->setText("Settings"); - m_actions.append(m_settingsAction); - - connect(m_openAction, SIGNAL(triggered()), SLOT(openFile())); - connect(m_settingsAction, SIGNAL(triggered()), SLOT(openSettings())); - connect(this, SIGNAL(connectionError()), SLOT(onConnectionError())); -} - -ClientServer::~ClientServer() -{ - disconnect(); -} - -QString ClientServer::description() const -{ - return tr("Client server operations."); -} - -QList ClientServer::actions() const -{ - return m_actions; -} - -QStringList ClientServer::menuPath(QAction*) const -{ - return QStringList() << tr("&Extensions") << tr("S&erver"); -} - -void ClientServer::disconnect() -{ - - if (m_communicator) - m_communicator->CloseConnection(); - - delete m_channel; - m_channel = nullptr; - if (m_communicator) - m_communicator->Delete(); - if (m_controller) - m_controller->Delete(); -} - -void ClientServer::select() -{ - if (m_channel) { - if (m_channel->select()) { - if (!m_channel->receive()) { - emit connectionError(); - return; - } - } - QTimer::singleShot(100, this, SLOT(select())); - } -} - -bool ClientServer::isConnected() -{ - return m_channel != nullptr; -} - -bool ClientServer::connectToServer(const QString& host, int port) -{ - - if (m_channel) - disconnect(); - - m_controller = vtkSocketController::New(); - m_communicator = vtkSocketCommunicator::New(); - m_controller->SetCommunicator(m_communicator); - m_controller->Initialize(); - - if (!m_communicator->ConnectTo(host.toLocal8Bit().data(), port)) { - m_controller->Delete(); - m_communicator->Delete(); - - return false; - } - - m_channel = new vtkCommunicatorChannel(m_communicator); - - // Start the event loop - select(); - - return true; -} - -void ClientServer::openFile() -{ - QSettings settings; - if (!isConnected()) { - QString host = settings - .value("clientServer/connectionSettings/hostName", - ConnectionSettingsDialog::defaultHost) - .toString(); - int port = settings - .value("clientServer/connectionSettings/port", - ConnectionSettingsDialog::defaultPort) - .toInt(); - - if (!connectToServer(host.toLocal8Bit().data(), port)) { - QMessageBox::critical(qobject_cast(parent()), - tr("Connection failed"), - tr("The connection to %2:%3 failed: connection" - " refused.") - .arg(host) - .arg(port)); - return; - } - } - - RemoteMoleculeService::Proxy proxy(m_channel); - FileFormats* response = new FileFormats(); - Closure* callback = - NewCallback(this, &ClientServer::handleFileFormatsResponse, response); - - proxy.fileFormats(response, callback); -} - -void ClientServer::openFile(const QString& filePath) -{ - QSettings settings; - QFileInfo fileInfo(filePath); - settings.setValue(lastOpenDirSettingPath(), fileInfo.dir().path()); - - RemoteMoleculeService::Proxy proxy(m_channel); - - OpenRequest request; - request.set_path(filePath.toStdString()); - - OpenResponse* response = new OpenResponse(); - Closure* callback = - NewCallback(this, &ClientServer::handleOpenResponse, response); - - proxy.open(&request, response, callback); -} - -void ClientServer::setMolecule(QtGui::Molecule* mol) -{ - // Do nothing -} - -bool ClientServer::readMolecule(QtGui::Molecule& mol) -{ - if (m_molecule) { - mol = *m_molecule; - - return true; - } - - return false; -} - -void ClientServer::handleOpenResponse(OpenResponse* response) -{ - if (!response->hasError()) { - m_molecule = response->mutable_molecule()->get(); - - emit ExtensionPlugin::moleculeReady(1); - } else { - QMessageBox::warning(qobject_cast(parent()), - tr("Remote service error"), - response->errorString().c_str()); - return; - } - - delete response; -} - -void ClientServer::onConnectionError() -{ - QMessageBox::critical( - qobject_cast(parent()), tr("Remote service error"), - tr("Connection failed with: %1").arg(m_channel->errorString().c_str())); - disconnect(); -} - -void ClientServer::openSettings() -{ - if (!m_dialog) { - m_dialog = new ConnectionSettingsDialog(qobject_cast(parent())); - connect(m_dialog, SIGNAL(settingsChanged()), this, SLOT(disconnect())); - } - m_dialog->show(); -} - -QString ClientServer::lastOpenDirSettingPath() -{ - QSettings settings; - QString host = - settings.value("clientServer/connectionSettings/hostName").toString(); - QString port = - settings.value("clientServer/connectionSettings/port").toString(); - - QString settingsPath = - tr("clientServer/%1:%2/lastOpenDir").arg(host).arg(port); - - return settingsPath; -} - -void ClientServer::handleFileFormatsResponse(FileFormats* response) -{ - QSettings settings; - - QStringList filters; - for (int i = 0; i < response->formats_size(); i++) { - FileFormat format = response->formats(i); - QString filter = tr("%1 (").arg(QString::fromStdString(format.name())); - for (int j = 0; j < format.extension_size(); j++) { - filter += tr("*.%1").arg(QString::fromStdString(format.extension(j))); - - if (j != format.extension_size() - 1) - filter += " "; - } - - filter += ")"; - filters << filter; - } - - qDebug() << filters.join(";;"); - - QString dir = settings.value(lastOpenDirSettingPath()).toString(); - FileDialog* remoteFileDialog = new FileDialog( - m_channel, nullptr, QString("Remote File Dialog"), dir, filters.join(";;")); - - connect(remoteFileDialog, SIGNAL(accepted()), this, SLOT(onAccepted())); - connect(remoteFileDialog, SIGNAL(finished(int)), this, SLOT(onFinished(int))); - - remoteFileDialog->show(); - - delete response; -} - -void ClientServer::onAccepted() -{ - FileDialog* dialog = qobject_cast(sender()); - - if (!dialog) - return; - - QString file = dialog->getSelectedFile(); - - if (!file.isEmpty()) - openFile(file); -} - -void ClientServer::onFinished(int result) -{ - FileDialog* dialog = qobject_cast(sender()); - - if (dialog) - dialog->deleteLater(); -} - -} // namespace QtPlugins -} diff --git a/avogadro/qtplugins/clientserver/clientserver.h b/avogadro/qtplugins/clientserver/clientserver.h deleted file mode 100644 index d1cfbda9ff..0000000000 --- a/avogadro/qtplugins/clientserver/clientserver.h +++ /dev/null @@ -1,88 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#ifndef AVOGADRO_QTPLUGINS_CLIENTSERVER_H -#define AVOGADRO_QTPLUGINS_CLIENTSERVER_H - -#include - -class OpenResponse; -class FileFormats; - -namespace ProtoCall { -namespace Runtime { -class vtkCommunicatorChannel; -} -} - -class vtkSocketController; -class vtkSocketCommunicator; - -namespace Avogadro { -namespace Core { -class Molecule; -} - -namespace QtPlugins { - -class ConnectionSettingsDialog; - -/** - * @class ClientServer clientserver.h - * - * @brief Plugin used to connect to and perform remote operations on an - * Avodadro server. - */ -class ClientServer : public Avogadro::QtGui::ExtensionPlugin -{ - Q_OBJECT -public: - explicit ClientServer(QObject* parent_ = nullptr); - ~ClientServer(); - - QString name() const { return tr("Client server"); } - QString description() const; - QList actions() const; - QStringList menuPath(QAction*) const; - -public slots: - void setMolecule(QtGui::Molecule* mol); - bool readMolecule(QtGui::Molecule& mol); - -signals: - void connectionError(); - -private slots: - void openFile(); - void openFile(const QString& filePath); - void openSettings(); - void onConnectionError(); - void select(); - void onAccepted(); - void onFinished(int result); - void disconnect(); - -private: - ConnectionSettingsDialog* m_dialog; - QAction* m_openAction; - QAction* m_settingsAction; - Core::Molecule* m_molecule; - vtkSocketController* m_controller; - vtkSocketCommunicator* m_communicator; - ProtoCall::Runtime::vtkCommunicatorChannel* m_channel; - QList m_actions; - - void handleOpenResponse(OpenResponse* response); - void handleFileFormatsResponse(FileFormats* response); - bool connectToServer(const QString& host, int port); - - bool isConnected(); - QString lastOpenDirSettingPath(); -}; - -} // namespace QtPlugins -} // namespace Avogadro - -#endif // AVOGADRO_QTPLUGINS_CLIENTSERVER_H diff --git a/avogadro/qtplugins/clientserver/connectionsettingsdialog.cpp b/avogadro/qtplugins/clientserver/connectionsettingsdialog.cpp deleted file mode 100644 index af79da9f44..0000000000 --- a/avogadro/qtplugins/clientserver/connectionsettingsdialog.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#include "connectionsettingsdialog.h" -#include "ui_connectionsettingsdialog.h" - -#include -#include -#include - -#include -#include -#include - -namespace Avogadro { -namespace QtPlugins { - -const QString ConnectionSettingsDialog::defaultHost = "localhost"; - -ConnectionSettingsDialog::ConnectionSettingsDialog(QWidget* parent_) - : QDialog(parent_), m_ui(new Ui::ConnectionSettingsDialog) -{ - m_ui->setupUi(this); - - connect(m_ui->pushTestConnection, SIGNAL(clicked()), SLOT(testConnection())); - connect(m_ui->buttonBox, SIGNAL(accepted()), SLOT(updateSettings())); - - QSettings settings; - QString host = - settings.value("clientServer/connectionSettings/hostName", defaultHost) - .toString(); - int port = - settings.value("clientServer/connectionSettings/port", defaultPort).toInt(); - - m_ui->editHostName->setText(host); - m_ui->spinPort->setValue(port); -} - -ConnectionSettingsDialog::~ConnectionSettingsDialog() -{ -} - -void ConnectionSettingsDialog::testConnection() -{ - QString host = m_ui->editHostName->text(); - int port = m_ui->spinPort->value(); - - vtkNew controller; - vtkNew communicator; - controller->SetCommunicator(communicator.GetPointer()); - controller->Initialize(); - - if (!communicator->ConnectTo(host.toLocal8Bit().data(), port)) { - QMessageBox::critical(this, tr("Connection refused"), - tr("The connection to %2:%3 failed: connection" - " refused.") - .arg(host) - .arg(port)); - - } else { - QMessageBox::information( - this, tr("Success"), - tr("Connection to %2:%3 succeeded!").arg(host).arg(port)); - - communicator->CloseConnection(); - } -} - -void ConnectionSettingsDialog::updateSettings() -{ - QSettings settings; - QVariant host(m_ui->editHostName->text()); - QVariant port(m_ui->spinPort->value()); - - bool changed = false; - if (host != settings.value("clientServer/connectionSettings/hostName") || - port != settings.value("clientServer/connectionSettings/port")) - changed = true; - - settings.setValue("clientServer/connectionSettings/hostName", host); - settings.setValue("clientServer/connectionSettings/port", port); - - if (changed) - emit settingsChanged(); -} - -} /* namespace QtPlugins */ -} /* namespace Avogadro */ diff --git a/avogadro/qtplugins/clientserver/connectionsettingsdialog.h b/avogadro/qtplugins/clientserver/connectionsettingsdialog.h deleted file mode 100644 index 701da13f22..0000000000 --- a/avogadro/qtplugins/clientserver/connectionsettingsdialog.h +++ /dev/null @@ -1,48 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). - ******************************************************************************/ - -#ifndef AVOGADRO_QTPLUGINS_CONNECTIONSETTINGSDIALOG_H -#define AVOGADRO_QTPLUGINS_CONNECTIONSETTINGSDIALOG_H - -#include - -namespace Avogadro { -namespace QtPlugins { - -namespace Ui { -class ConnectionSettingsDialog; -} - -/** - * @class ConnectionSettingsDialog connectionsettingsdialog.h - * - * @brief Dialog to set the connection settings for connecting to a remote - * server. - */ -class ConnectionSettingsDialog : public QDialog -{ - Q_OBJECT -public: - explicit ConnectionSettingsDialog(QWidget* parent_ = nullptr); - virtual ~ConnectionSettingsDialog(); - - static const QString defaultHost; - static const int defaultPort = 6060; - -signals: - void settingsChanged(); - -private slots: - void testConnection(); - void updateSettings(); - -private: - Ui::ConnectionSettingsDialog* m_ui; -}; - -} /* namespace QtPlugins */ -} /* namespace Avogadro */ - -#endif /* AVOGADRO_QTPLUGINS_CONNECTIONSETTINGSDIALOG_H */ diff --git a/avogadro/qtplugins/clientserver/connectionsettingsdialog.ui b/avogadro/qtplugins/clientserver/connectionsettingsdialog.ui deleted file mode 100644 index d9962c80ef..0000000000 --- a/avogadro/qtplugins/clientserver/connectionsettingsdialog.ui +++ /dev/null @@ -1,137 +0,0 @@ - - - Avogadro::QtPlugins::ConnectionSettingsDialog - - - - 0 - 0 - 331 - 150 - - - - Server settings - - - - - 50 - 110 - 271 - 32 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - 10 - 10 - 311 - 111 - - - - - QFormLayout::AllNonFixedFieldsGrow - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - &Hostname: - - - editHostName - - - - - - - - - - Port - - - - - - - - - Qt::Horizontal - - - - 70 - 20 - - - - - - - - Test C&onnection... - - - - - - - - - 65535 - - - - - - - - - - buttonBox - rejected() - Avogadro::QtPlugins::ConnectionSettingsDialog - reject() - - - 200 - 195 - - - 203 - 119 - - - - - buttonBox - accepted() - Avogadro::QtPlugins::ConnectionSettingsDialog - accept() - - - 200 - 195 - - - 203 - 119 - - - - - diff --git a/avogadro/qtplugins/clientserver/external_avogadrocore.proto b/avogadro/qtplugins/clientserver/external_avogadrocore.proto deleted file mode 100644 index 94c03c35a9..0000000000 --- a/avogadro/qtplugins/clientserver/external_avogadrocore.proto +++ /dev/null @@ -1,5 +0,0 @@ -package external.Avogadro.Core; - -message Molecule { - -} \ No newline at end of file diff --git a/avogadro/qtplugins/clientserver/filedialog.cpp b/avogadro/qtplugins/clientserver/filedialog.cpp deleted file mode 100644 index 466afd6ab0..0000000000 --- a/avogadro/qtplugins/clientserver/filedialog.cpp +++ /dev/null @@ -1,746 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#include "filedialog.h" -#include "filedialogfilter.h" -#include "filedialogmodel.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -using ProtoCall::Runtime::vtkCommunicatorChannel; - -class FileComboBox : public QComboBox -{ -public: - FileComboBox(QWidget* p) : QComboBox(p) {} - void showPopup() - { - QWidget* container = view()->parentWidget(); - container->setMaximumWidth(width()); - QComboBox::showPopup(); - } -}; - -#include "ui_filedialog.h" - -namespace { - -QStringList makeFilterList(const QString& filter) -{ - QString f(filter); - - if (f.isEmpty()) - return QStringList(); - - QString sep(";;"); - int i = f.indexOf(sep, 0); - if (i == -1) { - if (f.indexOf("\n", 0) != -1) { - sep = "\n"; - i = f.indexOf(sep, 0); - } - } - return f.split(sep, QString::SkipEmptyParts); -} - -QStringList getWildCardsFromFilter(const QString& filter) -{ - QString f = filter; - int start, end; - start = filter.indexOf('('); - end = filter.lastIndexOf(')'); - if (start != -1 && end != -1) { - f = f.mid(start + 1, end - start - 1); - } else if (start != -1 || end != -1) { - f = QString(); // hmm... I'm confused - } - - // separated by spaces or semi-colons - QStringList fs = f.split(QRegExp("[\\s+;]"), QString::SkipEmptyParts); - - // add a *.ext.* for every *.ext we get to support file groups - QStringList ret = fs; - foreach (QString ext, fs) { - ret.append(ext + ".*"); - } - return ret; -} -} - -class FileDialog::Private : public QObject -{ -public: - FileDialogModel* const m_model; - FileDialogFilter m_fileFilter; - QString m_fileName; - QCompleter* m_completer; - Ui::FileDialog m_ui; - QString m_selectedFile; - QStringList m_filters; - - // remember the last locations we browsed - static QMap m_serverFilePaths; - - Private(FileDialog* p, vtkCommunicatorChannel* server) - : QObject(p), m_model(new FileDialogModel(server, nullptr)), - m_fileFilter(m_model), m_completer(new QCompleter(&m_fileFilter, nullptr)) - { - } - - ~Private() - { - delete m_model; - delete m_completer; - } - - bool eventFilter(QObject* obj, QEvent* anEvent) - { - if (obj == m_ui.Files) { - if (anEvent->type() == QEvent::KeyPress) { - QKeyEvent* keyEvent = static_cast(anEvent); - if (keyEvent->key() == Qt::Key_Backspace || - keyEvent->key() == Qt::Key_Delete) { - m_ui.FileName->setFocus(Qt::OtherFocusReason); - // send out a backspace event to the file name now - QKeyEvent replicateDelete(keyEvent->type(), keyEvent->key(), - keyEvent->modifiers()); - QApplication::sendEvent(m_ui.FileName, &replicateDelete); - return true; - } - } - return false; - } - return QObject::eventFilter(obj, anEvent); - } - - QString getStartPath() - { - QMap::iterator iter; - iter = m_serverFilePaths.find(m_model->server()); - if (iter != m_serverFilePaths.end()) { - return *iter; - } - - return m_model->getCurrentPath(); - } - - void setCurrentPath(const QString& p) - { - m_model->setCurrentPath(p); - vtkCommunicatorChannel* s = m_model->server(); - m_serverFilePaths[s] = p; - m_ui.Files->setFocus(Qt::OtherFocusReason); - } - - void addHistory(const QString& p) - { - m_backHistory.append(p); - m_forwardHistory.clear(); - - if (m_backHistory.size() > 1) - m_ui.NavigateBack->setEnabled(true); - else - m_ui.NavigateBack->setEnabled(false); - - m_ui.NavigateForward->setEnabled(false); - } - - QString backHistory() - { - QString path = m_backHistory.takeLast(); - m_forwardHistory.append(m_model->getCurrentPath()); - m_ui.NavigateForward->setEnabled(true); - if (m_backHistory.size() == 1) - m_ui.NavigateBack->setEnabled(false); - - return path; - } - - QString forwardHistory() - { - QString path = m_forwardHistory.takeLast(); - m_backHistory.append(m_model->getCurrentPath()); - m_ui.NavigateBack->setEnabled(true); - if (m_forwardHistory.size() == 0) { - m_ui.NavigateForward->setEnabled(false); - } - - return path; - } - -protected: - QStringList m_backHistory; - QStringList m_forwardHistory; -}; - -QMap FileDialog::Private::m_serverFilePaths; - -///////////////////////////////////////////////////////////////////////////// -// FileDialog - -FileDialog::FileDialog(vtkCommunicatorChannel* server, QWidget* p, - const QString& title, const QString& startDirectory, - const QString& nameFilter) - : QDialog(p), m_implementation(new Private(this, server)) -{ - m_implementation->m_ui.setupUi(this); - // ensures that the favorites and the browser component are sized - // proportionately. - m_implementation->m_ui.mainSplitter->setStretchFactor(0, 1); - m_implementation->m_ui.mainSplitter->setStretchFactor(1, 4); - setWindowTitle(title); - - m_implementation->m_ui.Files->setEditTriggers( - QAbstractItemView::EditKeyPressed); - - // install the event filter - m_implementation->m_ui.Files->installEventFilter(m_implementation); - - // install the autocompleter - m_implementation->m_ui.FileName->setCompleter(m_implementation->m_completer); - - QPixmap back = style()->standardPixmap(QStyle::SP_FileDialogBack); - m_implementation->m_ui.NavigateBack->setIcon(back); - m_implementation->m_ui.NavigateBack->setEnabled(false); - QObject::connect(m_implementation->m_ui.NavigateBack, SIGNAL(clicked(bool)), - this, SLOT(onNavigateBack())); - // just flip the back image to make a forward image - QPixmap forward = QPixmap::fromImage(back.toImage().mirrored(true, false)); - m_implementation->m_ui.NavigateForward->setIcon(forward); - m_implementation->m_ui.NavigateForward->setDisabled(true); - QObject::connect(m_implementation->m_ui.NavigateForward, - SIGNAL(clicked(bool)), this, SLOT(onNavigateForward())); - m_implementation->m_ui.NavigateUp->setIcon( - style()->standardPixmap(QStyle::SP_FileDialogToParent)); - - m_implementation->m_ui.Files->setModel(&m_implementation->m_fileFilter); - m_implementation->m_ui.Files->setSelectionBehavior( - QAbstractItemView::SelectRows); - - m_implementation->m_ui.Files->setContextMenuPolicy(Qt::CustomContextMenu); - QObject::connect(m_implementation->m_ui.Files, - SIGNAL(customContextMenuRequested(const QPoint&)), this, - SLOT(onContextMenuRequested(const QPoint&))); - - QObject::connect(m_implementation->m_model, SIGNAL(modelReset()), this, - SLOT(onModelReset())); - - QObject::connect(m_implementation->m_ui.NavigateUp, SIGNAL(clicked()), this, - SLOT(onNavigateUp())); - - QObject::connect(m_implementation->m_ui.Parents, - SIGNAL(activated(const QString&)), this, - SLOT(onNavigate(const QString&))); - - QObject::connect(m_implementation->m_ui.FileType, - SIGNAL(currentIndexChanged(const QString&)), this, - SLOT(onFilterChange(const QString&))); - - QObject::connect( - m_implementation->m_ui.Files->selectionModel(), - SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), - this, SLOT(fileSelectionChanged())); - - QObject::connect(m_implementation->m_ui.Files, - SIGNAL(doubleClicked(const QModelIndex&)), this, - SLOT(onDoubleClickFile(const QModelIndex&))); - - QObject::connect(m_implementation->m_ui.FileName, - SIGNAL(textChanged(const QString&)), this, - SLOT(onTextEdited(const QString&))); - - QStringList filterList = makeFilterList(nameFilter); - if (filterList.empty()) { - m_implementation->m_ui.FileType->addItem("All Files (*)"); - m_implementation->m_filters << "All Files (*)"; - } else { - m_implementation->m_ui.FileType->addItems(filterList); - m_implementation->m_filters = filterList; - } - onFilterChange(m_implementation->m_ui.FileType->currentText()); - - QString startPath = startDirectory; - - if (startPath.isEmpty()) { - startPath = m_implementation->getStartPath(); - } - m_implementation->addHistory(startPath); - m_implementation->setCurrentPath(startPath); -} - -//----------------------------------------------------------------------------- -FileDialog::~FileDialog() -{ -} - -//----------------------------------------------------------------------------- -void FileDialog::onContextMenuRequested(const QPoint& menuPos) -{ - QMenu menu; - menu.setObjectName("FileDialogContextMenu"); - - QAction* actionHiddenFiles = new QAction("Show Hidden Files", this); - actionHiddenFiles->setCheckable(true); - actionHiddenFiles->setChecked(m_implementation->m_fileFilter.getShowHidden()); - QObject::connect(actionHiddenFiles, SIGNAL(triggered(bool)), this, - SLOT(onShowHiddenFiles(bool))); - menu.addAction(actionHiddenFiles); - - menu.exec(m_implementation->m_ui.Files->mapToGlobal(menuPos)); -} - -//----------------------------------------------------------------------------- -void FileDialog::setRecentlyUsedExtension(const QString& fileExtension) -{ - if (fileExtension.isEmpty()) { - // upon the initial use of any kind (e.g., data or screenshot) of dialog - // 'fileExtension' is equal /set to an empty string. - // In this case, no any user preferences are considered - m_implementation->m_ui.FileType->setCurrentIndex(0); - } else { - int index = m_implementation->m_ui.FileType->findText(fileExtension, - Qt::MatchContains); - // just in case the provided extension is not in the combobox list - index = (index == -1) ? 0 : index; - m_implementation->m_ui.FileType->setCurrentIndex(index); - } -} - -//----------------------------------------------------------------------------- -void FileDialog::setSelectedFile(const QString& file) -{ - // Ensure that we are hidden before broadcasting the selection, - // so we don't get caught by screen-captures - setVisible(false); - m_implementation->m_selectedFile = file; -} - -//----------------------------------------------------------------------------- -void FileDialog::emitFilesSelectionDone() -{ - emit fileSelected(m_implementation->m_selectedFile); - done(QDialog::Accepted); -} - -//----------------------------------------------------------------------------- -QString FileDialog::getSelectedFile() -{ - return m_implementation->m_selectedFile; -} - -//----------------------------------------------------------------------------- -void FileDialog::accept() -{ - acceptExistingFiles(); -} - -class AcceptRequest : public QObject -{ - Q_OBJECT -public: - AcceptRequest(FileDialog* dialog, const QString& selectedFile, - bool doubleClicked) - : m_dialog(dialog), m_selectedFile(selectedFile), - m_doubleClicked(doubleClicked) - { - } - -public slots: - void accept() - { - if (m_selectedFile.isEmpty()) { - emit finished(false); - return; - } - - accept(m_selectedFile); - } - - void accept(const QString& file) - { - // Connect up cleanup slot - connect(this, SIGNAL(finished(bool)), this, SLOT(cleanup())); - - if (file.isEmpty()) { - emit finished(false); - return; - } - // User chose an existing directory - m_dialog->m_implementation->m_model->dirExists( - file, this, SLOT(onDirExists(const QString, bool))); - } - - void onDirExists(const QString& path, bool exists) - { - - if (exists) { - acceptExistingDirectory(path); - } else { - acceptFile(path); - } - } - - void acceptExistingDirectory(const QString& file) - { - m_dialog->onNavigate(file); - emit finished(false); - } - - void acceptFile(const QString& file) - { - m_dialog->m_implementation->m_model->fileExists( - file, this, SLOT(onFileExistsComplete(const QString, bool))); - } - - void acceptOnDirExists(const QString& dir, bool exists) - { - if (exists) { - m_dialog->onNavigate(dir); - m_dialog->m_implementation->m_ui.FileName->clear(); - emit finished(false); - } else { - m_dialog->m_implementation->m_model->fileExists( - m_selectedFile, this, SLOT(onFileExistsComplete)); - } - } - - void onFileExistsComplete(const QString& file, bool exists) - { - if (exists) { - m_dialog->setSelectedFile(file); - emit finished(true); - return; - } else { - m_dialog->m_implementation->m_ui.FileName->selectAll(); - emit finished(false); - return; - } - - emit finished(false); - } - - void cleanup() - { - AcceptRequest* request = qobject_cast(sender()); - - if (request) - delete request; - } - -signals: - void finished(bool accept); - -private: - FileDialog* m_dialog; - QString m_selectedFile; - bool m_doubleClicked; -}; - -//----------------------------------------------------------------------------- -void FileDialog::acceptExistingFiles() -{ - QString filename; - if (m_implementation->m_fileName.isEmpty()) { - // when we have nothing selected in the current selection model, we will - // attempt to use the default way - acceptDefault(); - } - - AcceptRequest* request = - new AcceptRequest(this, m_implementation->m_fileName, false); - - connect(request, SIGNAL(finished(bool)), this, - SLOT(acceptRequestFinished(bool))); - - m_implementation->m_model->absoluteFilePath( - m_implementation->m_fileName, request, SLOT(accept(const QString&))); -} - -void FileDialog::acceptRequestFinished(bool accept) -{ - if (accept) - emit emitFilesSelectionDone(); -} - -//----------------------------------------------------------------------------- -void FileDialog::acceptDefault() -{ - QString filename = m_implementation->m_ui.FileName->text(); - filename = filename.trimmed(); - - m_implementation->m_model->absoluteFilePath( - filename, this, SLOT(acceptDefaultContinued(const QString&))); -} - -//----------------------------------------------------------------------------- -void FileDialog::onModelReset() -{ - m_implementation->m_ui.Parents->clear(); - - QString currentPath = m_implementation->m_model->getCurrentPath(); - // clean the path to always look like a unix path - currentPath = QDir::cleanPath(currentPath); - - // the separator is always the unix separator - QChar separator = '/'; - - QStringList parents = currentPath.split(separator, QString::SkipEmptyParts); - - // put our root back in - if (parents.count()) { - int idx = currentPath.indexOf(parents[0]); - if (idx != 0 && idx != -1) - parents.prepend(currentPath.left(idx)); - - } else { - parents.prepend(separator); - } - - for (int i = 0; i != parents.size(); ++i) { - QString str; - for (int j = 0; j <= i; j++) { - str += parents[j]; - if (!str.endsWith(separator)) { - str += separator; - } - } - m_implementation->m_ui.Parents->addItem(str); - } - m_implementation->m_ui.Parents->setCurrentIndex(parents.size() - 1); -} - -//----------------------------------------------------------------------------- -void FileDialog::onNavigate(const QString& Path) -{ - m_implementation->addHistory(m_implementation->m_model->getCurrentPath()); - m_implementation->setCurrentPath(Path); -} - -//----------------------------------------------------------------------------- -void FileDialog::onNavigateUp() -{ - m_implementation->addHistory(m_implementation->m_model->getCurrentPath()); - QFileInfo info(m_implementation->m_model->getCurrentPath()); - m_implementation->setCurrentPath(info.path()); -} - -//----------------------------------------------------------------------------- -void FileDialog::onNavigateDown(const QModelIndex& idx) -{ - if (!m_implementation->m_model->isDir(idx)) - return; - - const QStringList paths = m_implementation->m_model->getFilePaths(idx); - - if (1 != paths.size()) - return; - - m_implementation->addHistory(m_implementation->m_model->getCurrentPath()); - m_implementation->setCurrentPath(paths[0]); -} - -//----------------------------------------------------------------------------- -void FileDialog::onNavigateBack() -{ - QString path = m_implementation->backHistory(); - m_implementation->setCurrentPath(path); -} - -//----------------------------------------------------------------------------- -void FileDialog::onNavigateForward() -{ - QString path = m_implementation->forwardHistory(); - m_implementation->setCurrentPath(path); -} - -//----------------------------------------------------------------------------- -void FileDialog::onFilterChange(const QString& filter) -{ - // set filter on proxy - m_implementation->m_fileFilter.setFilter(filter); - - // update view - m_implementation->m_fileFilter.clear(); -} - -//----------------------------------------------------------------------------- -void FileDialog::onDoubleClickFile(const QModelIndex& index) -{ - accept(); -} - -//----------------------------------------------------------------------------- -void FileDialog::onShowHiddenFiles(const bool& hidden) -{ - m_implementation->m_fileFilter.setShowHidden(hidden); -} - -//----------------------------------------------------------------------------- -void FileDialog::setShowHidden(const bool& hidden) -{ - onShowHiddenFiles(hidden); -} - -//----------------------------------------------------------------------------- -bool FileDialog::getShowHidden() -{ - return m_implementation->m_fileFilter.getShowHidden(); -} - -//----------------------------------------------------------------------------- -void FileDialog::onTextEdited(const QString& str) -{ - // really important to block signals so that the clearSelection - // doesn't cause a signal to be fired that calls fileSelectionChanged - m_implementation->m_ui.Files->blockSignals(true); - m_implementation->m_ui.Files->clearSelection(); - if (str.size() > 0) - m_implementation->m_fileName = str; - else - m_implementation->m_fileName.clear(); - - m_implementation->m_ui.Files->blockSignals(false); -} - -//----------------------------------------------------------------------------- -QString FileDialog::fixFileExtension(const QString& filename, - const QString& filter) -{ - // Add missing extension if necessary - QFileInfo fileInfo(filename); - QString ext = fileInfo.completeSuffix(); - QString extensionWildcard = getWildCardsFromFilter(filter).first(); - QString wantedExtension = - extensionWildcard.mid(extensionWildcard.indexOf('.') + 1); - - if (!ext.isEmpty()) { - // Ensure that the extension the user added is indeed of one the supported - // types. (BUG #7634). - QStringList wildCards; - foreach (QString curfilter, m_implementation->m_filters) { - wildCards += ::getWildCardsFromFilter(curfilter); - } - bool pass = false; - foreach (QString wildcard, wildCards) { - if (wildcard.indexOf('.') != -1) { - // we only need to validate the extension, not the filename. - wildcard = QString("*.%1").arg(wildcard.mid(wildcard.indexOf('.') + 1)); - QRegExp regEx = - QRegExp(wildcard, Qt::CaseInsensitive, QRegExp::Wildcard); - if (regEx.exactMatch(fileInfo.fileName())) { - pass = true; - break; - } - } else { - // we have a filter which does not specify any rule for the extension. - // In that case, just assume the extension matched. - pass = true; - break; - } - } - if (!pass) { - // force adding of the wantedExtension. - ext = QString(); - } - } - - QString fixedFilename = filename; - if (ext.isEmpty() && !wantedExtension.isEmpty() && wantedExtension != "*") { - if (fixedFilename.at(fixedFilename.size() - 1) != '.') - fixedFilename += "."; - - fixedFilename += wantedExtension; - } - return fixedFilename; -} - -//----------------------------------------------------------------------------- -void FileDialog::fileSelectionChanged() -{ - // Selection changed, update the FileName entry box - // to reflect the current selection. - QString fileString; - const QModelIndexList indices = - m_implementation->m_ui.Files->selectionModel()->selectedIndexes(); - if (indices.isEmpty()) { - // do not change the FileName text if no selections - return; - } - QString fileName; - - QModelIndex index = indices[0]; - if (index.column() != 0) - return; - - if (index.model() == &m_implementation->m_fileFilter) - fileName = m_implementation->m_fileFilter.data(index).toString(); - - // user is currently editing a name, don't change the text - m_implementation->m_ui.FileName->blockSignals(true); - m_implementation->m_ui.FileName->setText(fileString); - m_implementation->m_ui.FileName->blockSignals(false); - m_implementation->m_fileName = fileName; -} - -//----------------------------------------------------------------------------- -bool FileDialog::selectFile(const QString& f) -{ - // We don't use QFileInfo here since it messes the paths up if the client and - // the server are heterogeneous systems. - std::string unix_path = f.toAscii().data(); - vtksys::SystemTools::ConvertToUnixSlashes(unix_path); - - std::string filename, dirname; - std::string::size_type slashPos = unix_path.rfind("/"); - if (slashPos != std::string::npos) { - filename = unix_path.substr(slashPos + 1); - dirname = unix_path.substr(0, slashPos); - } else { - filename = unix_path; - dirname = ""; - } - - QPointer diag = this; - m_implementation->m_model->setCurrentPath(dirname.c_str()); - m_implementation->m_ui.FileName->setText(filename.c_str()); - accept(); - if (diag && diag->result() != QDialog::Accepted) - return false; - - return true; -} - -//----------------------------------------------------------------------------- -void FileDialog::showEvent(QShowEvent* _showEvent) -{ - QDialog::showEvent(_showEvent); - // Qt sets the default keyboard focus to the last item in the tab order - // which is determined by the creation order. This means that we have - // to explicitly state that the line edit has the focus on showing no - // matter the tab order - m_implementation->m_ui.FileName->setFocus(Qt::OtherFocusReason); -} - -#include "filedialog.moc" diff --git a/avogadro/qtplugins/clientserver/filedialog.h b/avogadro/qtplugins/clientserver/filedialog.h deleted file mode 100644 index f4196ba9f5..0000000000 --- a/avogadro/qtplugins/clientserver/filedialog.h +++ /dev/null @@ -1,112 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#ifndef AVOGADRO_QTPLUGINS_FILEDIALOG_H -#define AVOGADRO_QTPLUGINS_FILEDIALOG_H - -#include -#include - -class QModelIndex; -class QPoint; -class QShowEvent; - -namespace ProtoCall { -namespace Runtime { -class vtkCommunicatorChannel; -} -} - -/** - * @class FileDialog filedialog.h - * @brief Remote file dialog - */ -class FileDialog : public QDialog -{ - Q_OBJECT -public: - FileDialog(ProtoCall::Runtime::vtkCommunicatorChannel*, QWidget* Parent, - const QString& Title = QString(), - const QString& Directory = QString(), - const QString& Filter = QString()); - ~FileDialog(); - - /// set the most recently used file extension - void setRecentlyUsedExtension(const QString& fileExtension); - - /// Returns all the file groups - QString getSelectedFile(); - - /// accept this dialog - void accept(); - - /// set a file current to support test playback - bool selectFile(const QString&); - - /// set if we show hidden files and holders - void setShowHidden(const bool& hidden); - - /// returns the state of the show hidden flag - bool getShowHidden(); - -signals: - /// Signal emitted when the user has chosen a file - void fileSelected(const QString&); - - void fileAcceptedInternal(const QString&); - - friend class AcceptRequest; - -protected: - void acceptExistingFiles(); - void acceptDefault(); - - QStringList buildFileGroup(const QString& filename); - - virtual void showEvent(QShowEvent* showEvent); - -private slots: - void onModelReset(); - void onNavigate(const QString&); - void onNavigateUp(); - void onNavigateBack(); - void onNavigateForward(); - void onNavigateDown(const QModelIndex&); - void onFilterChange(const QString&); - - void onDoubleClickFile(const QModelIndex&); - - void onTextEdited(const QString&); - - void onShowHiddenFiles(const bool& hide); - - // Called when the user changes the file selection. - void fileSelectionChanged(); - - // Called when the user right-clicks in the file qtreeview - void onContextMenuRequested(const QPoint& pos); - - // Set the selected file - void setSelectedFile(const QString&); - - // Emits the filesSelected() signal and closes the dialog, - void emitFilesSelectionDone(); - - void acceptRequestFinished(bool accept); - -private: - FileDialog(const FileDialog&); - FileDialog& operator=(const FileDialog&); - - class Private; - Private* const m_implementation; - - // returns if true if files are loaded - void acceptInternal(const QStringList& selected_files, - const bool& doubleclicked); - QString fixFileExtension(const QString& filename, const QString& filter); -}; - -#endif diff --git a/avogadro/qtplugins/clientserver/filedialog.ui b/avogadro/qtplugins/clientserver/filedialog.ui deleted file mode 100644 index ea2e1be120..0000000000 --- a/avogadro/qtplugins/clientserver/filedialog.ui +++ /dev/null @@ -1,239 +0,0 @@ - - - FileDialog - - - - 0 - 0 - 683 - 402 - - - - Dialog - - - - - - 6 - - - 0 - - - - - - 0 - 0 - - - - - 100 - 0 - - - - - 100 - 16777215 - - - - Look in: - - - Qt::AlignCenter - - - - - - - - 0 - 0 - - - - - - - - Navigate Back - - - - - - true - - - - - - - Navigate Forward - - - - - - true - - - - - - - Navigate Up - - - - - - true - - - - - - - - - Qt::Horizontal - - - - - 0 - 0 - - - - Qt::Vertical - - - - - - - - - 2 - 0 - - - - - - - - 0 - - - 6 - - - - - File name: - - - - - - - - - - OK - - - - - - - Files of type: - - - - - - - QComboBox::AdjustToMinimumContentsLength - - - - - - - Cancel - - - - - - - - - - - - - - FileComboBox - QComboBox -
filedialog.h
-
-
- - FileName - FileType - OK - Cancel - Parents - NavigateBack - NavigateForward - NavigateUp - Files - - - - - OK - clicked() - FileDialog - accept() - - - 487 - 371 - - - 60 - 368 - - - - - Cancel - clicked() - FileDialog - reject() - - - 487 - 404 - - - 84 - 388 - - - - -
diff --git a/avogadro/qtplugins/clientserver/filedialogfilter.cpp b/avogadro/qtplugins/clientserver/filedialogfilter.cpp deleted file mode 100644 index f4ce1a9140..0000000000 --- a/avogadro/qtplugins/clientserver/filedialogfilter.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#include "filedialogfilter.h" - -#include -#include -#include - -#include "filedialogmodel.h" - -FileDialogFilter::FileDialogFilter(FileDialogModel* model, QObject* Parent) - : QSortFilterProxyModel(Parent), m_model(model), m_showHidden(false) -{ - setSourceModel(model); - m_wildcards.setPatternSyntax(QRegExp::RegExp2); - m_wildcards.setCaseSensitivity(Qt::CaseSensitive); -} - -FileDialogFilter::~FileDialogFilter() -{ -} - -#include - -void FileDialogFilter::setFilter(const QString& filter) -{ - QString f(filter); - // if we have (...) in our filter, strip everything out but the contents of () - int start, end; - end = filter.lastIndexOf(')'); - start = filter.lastIndexOf('(', end); - if (start != -1 && end != -1) - f = f.mid(start + 1, end - start - 1); - - QString pattern = ".*"; - if (f != "*") { - f = f.trimmed(); - - // convert all spaces into | - f.replace(QRegExp("[\\s+;]+"), "|"); - - QStringList strings = f.split("|"); - QStringList extensions_list, filepatterns_list; - foreach (QString string, strings) { - if (string.startsWith("*.")) - extensions_list.push_back(string.remove(0, 2)); - else - filepatterns_list.push_back(string); - } - - QString extensions = extensions_list.join("|"); - QString filepatterns = filepatterns_list.join("|"); - - extensions.replace(".", "\\."); - extensions.replace("*", ".*"); - - filepatterns.replace(".", "\\."); - filepatterns.replace("*", ".*"); - - // use non capturing(?:) for speed - // name.ext or ext.001 or name.ext001 (for bug #10101) - QString postExtFileSeries("(\\.?\\d+)?$"); // match the .0001 component - QString extGroup = ".*\\.(?:" % extensions % ")" % postExtFileSeries; - QString fileGroup = "(?:" % filepatterns % ")" % postExtFileSeries; - if (extensions_list.size() > 0 && filepatterns_list.size() > 0) - pattern = "(?:" % fileGroup % "|" % extGroup % ")"; - else if (extensions_list.size() > 0) - pattern = extGroup; - else - pattern = fileGroup; - } - - m_wildcards.setPattern(pattern); - invalidateFilter(); -} - -void FileDialogFilter::setShowHidden(const bool& hidden) -{ - if (m_showHidden != hidden) { - m_showHidden = hidden; - invalidateFilter(); - } -} - -bool FileDialogFilter::filterAcceptsRow(int row_source, - const QModelIndex& source_parent) const -{ - QModelIndex idx = m_model->index(row_source, 0, source_parent); - - // hidden flag supersedes anything else - if (m_model->isHidden(idx) && !m_showHidden) - return false; - - if (m_model->isDir(idx)) { - QString str = sourceModel()->data(idx).toString(); - return true; - } - - if (source_parent.isValid()) { - // if source_parent is valid, then the item is an element in a file-group. - // For file-groups, we use pass any file in a group, if the group's label - // passes the test (BUG #13179). - QString str = sourceModel()->data(source_parent).toString(); - return m_wildcards.exactMatch(str); - } else { - QString str = sourceModel()->data(idx).toString(); - return m_wildcards.exactMatch(str); - } -} diff --git a/avogadro/qtplugins/clientserver/filedialogfilter.h b/avogadro/qtplugins/clientserver/filedialogfilter.h deleted file mode 100644 index 7cec791fee..0000000000 --- a/avogadro/qtplugins/clientserver/filedialogfilter.h +++ /dev/null @@ -1,39 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#ifndef AVOGADRO_QTPLUGINS_FILEDIALOGFILTER_H -#define AVOGADRO_QTPLUGINS_FILEDIALOGFILTER_H - -#include -#include -class FileDialogModel; - -/** - * @class FileDialogFilter filedialogfilter.h - * - * @brief Filter used to filter data in file dialog model - */ -class FileDialogFilter : public QSortFilterProxyModel -{ - Q_OBJECT - -public: - FileDialogFilter(FileDialogModel* sourceModel, QObject* Parent = nullptr); - ~FileDialogFilter(); - -public slots: - void setFilter(const QString& filter); - void setShowHidden(const bool& hidden); - bool getShowHidden() { return m_showHidden; }; - -protected: - bool filterAcceptsRow(int row_source, const QModelIndex& source_parent) const; - - FileDialogModel* m_model; - QRegExp m_wildcards; - bool m_showHidden; -}; - -#endif diff --git a/avogadro/qtplugins/clientserver/filedialogmodel.cpp b/avogadro/qtplugins/clientserver/filedialogmodel.cpp deleted file mode 100644 index caaf0e19e2..0000000000 --- a/avogadro/qtplugins/clientserver/filedialogmodel.cpp +++ /dev/null @@ -1,684 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#include "filedialogmodel.h" - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "RemoteFileSystemService.pb.h" -#include -#include - -using namespace ProtoCall::Runtime; -using namespace google::protobuf; - -// FileDialogModelFileInfo - -class FileDialogModelFileInfo -{ -public: - FileDialogModelFileInfo() : m_type(FileDialogModel::INVALID), m_hidden(false) - { - } - - FileDialogModelFileInfo( - const QString& l, const QString& filepath, FileDialogModel::FileType t, - const bool& h, - const QList& g = QList()) - : m_label(l), m_filePath(filepath), m_type(t), m_hidden(h), m_group(g) - { - } - - const QString& label() const { return m_label; } - - const QString& filePath() const { return m_filePath; } - - FileDialogModel::FileType type() const { return m_type; } - - bool isGroup() const { return !m_group.empty(); } - - bool isHidden() const { return m_hidden; } - - const QList& group() const { return m_group; } - -private: - QString m_label; - QString m_filePath; - FileDialogModel::FileType m_type; - bool m_hidden; - QList m_group; -}; - -///////////////////////////////////////////////////////////////////// -// Icons - -FileDialogModelIconProvider::FileDialogModelIconProvider() -{ - QStyle* style = QApplication::style(); - m_folderLinkIcon = style->standardIcon(QStyle::SP_DirLinkIcon); - m_fileLinkIcon = style->standardIcon(QStyle::SP_FileLinkIcon); -} - -QIcon FileDialogModelIconProvider::icon(IconType t) const -{ - switch (t) { - case Computer: - return QFileIconProvider::icon(QFileIconProvider::Computer); - case Drive: - return QFileIconProvider::icon(QFileIconProvider::Drive); - case Folder: - return QFileIconProvider::icon(QFileIconProvider::Folder); - case File: - return QFileIconProvider::icon(QFileIconProvider::File); - case FolderLink: - return m_folderLinkIcon; - case FileLink: - return m_fileLinkIcon; - case NetworkFolder: - return QFileIconProvider::icon(QFileIconProvider::Network); - } - return QIcon(); -} - -QIcon FileDialogModelIconProvider::icon(FileDialogModel::FileType f) const -{ - if (f == FileDialogModel::DIRECTORY_LINK) { - return icon(FileDialogModelIconProvider::FolderLink); - } else if (f == FileDialogModel::SINGLE_FILE_LINK) { - return icon(FileDialogModelIconProvider::FileLink); - } else if (f == FileDialogModel::NETWORK_SHARE) { - return icon(FileDialogModelIconProvider::NetworkFolder); - } else if (f == FileDialogModel::NETWORK_SERVER) { - return icon(FileDialogModelIconProvider::Computer); - } else if (f == FileDialogModel::DIRECTORY) { - return icon(FileDialogModelIconProvider::Folder); - } - - return icon(FileDialogModelIconProvider::File); -} -QIcon FileDialogModelIconProvider::icon(const QFileInfo& info) const -{ - return QFileIconProvider::icon(info); -} -QIcon FileDialogModelIconProvider::icon(QFileIconProvider::IconType ico) const -{ - return QFileIconProvider::icon(ico); -} - -Q_GLOBAL_STATIC(FileDialogModelIconProvider, Icons) - -namespace { - -/////////////////////////////////////////////////////////////////////// -// caseInsensitiveSort - -bool caseInsensitiveSort(const FileDialogModelFileInfo& A, - const FileDialogModelFileInfo& B) -{ - // Sort alphabetically (but case-insensitively) - return A.label().toLower() < B.label().toLower(); -} - -} // namespace - -class FileDialogModel::Private -{ -public: - Private(FileDialogModel* model, - ProtoCall::Runtime::vtkCommunicatorChannel* server) - : m_separator(0), m_server(server), m_model(model) - { - RemoteFileSystemService::Proxy proxy(m_server); - - // Get the separator - Separator* separator = new Separator(); - Closure* callback = NewCallback( - this, &FileDialogModel::Private::handleSeparatorResponse, separator); - - proxy.separator(separator, callback); - } - - ~Private() {} - - void listCurrentWorkingDir() - { - Path dir; - listDirectory(dir); - } - - void listDirectory(const QString& path) - { - // Get the listing of the current working directory - Path dir; - dir.set_path(path.toStdString()); - - listDirectory(dir); - } - - void listDirectory(Path& dir) - { - - RemoteFileSystemService::Proxy proxy(m_server); - - // Get the listing of the current working directory - Listing* listing = new Listing(); - - Closure* callback = NewCallback( - this, &FileDialogModel::Private::handleListingResponse, listing); - - proxy.ls(&dir, listing, callback); - } - - void handleSeparatorResponse(Separator* response) - { - m_separator = response->separator()[0]; - delete response; - } - - void handleListingResponse(Listing* response) - { - m_currentPath = response->path().path().c_str(); - m_fileList.clear(); - - QList dirs; - QList files; - - for (int i = 0; i < response->paths_size(); i++) { - const Path& path = response->paths(i); - - const QString label = QString::fromStdString(path.name()); - - FileDialogModelFileInfo info( - label, label, static_cast(path.type()), - false); - - if (path.type() == FileDialogModel::DIRECTORY) { - dirs.push_back(info); - } else { - files.push_back(info); - } - } - - qSort(dirs.begin(), dirs.end(), caseInsensitiveSort); - qSort(files.begin(), files.end(), caseInsensitiveSort); - - for (int i = 0; i != dirs.size(); ++i) { - m_fileList.push_back(dirs[i]); - } - for (int i = 0; i != files.size(); ++i) { - m_fileList.push_back(files[i]); - } - - m_model->reset(); - - delete response; - } - - /// Removes multiple-slashes, ".", and ".." from the given path string, - /// and points slashes in the correct direction for the server - const QString cleanPath(const QString& Path) - { - QString result = QDir::cleanPath(QDir::fromNativeSeparators(Path)); - return result.trimmed(); - } - - QStringList getFilePaths(const QModelIndex& Index) - { - QStringList results; - - QModelIndex p = Index.parent(); - if (p.isValid()) { - if (p.row() < m_fileList.size()) { - FileDialogModelFileInfo& file = m_fileList[p.row()]; - const QList& grp = file.group(); - if (Index.row() < grp.size()) - results.push_back(grp[Index.row()].filePath()); - } - } else if (Index.row() < m_fileList.size()) { - FileDialogModelFileInfo& file = m_fileList[Index.row()]; - if (file.isGroup() && file.group().count() > 0) { - for (int i = 0; i < file.group().count(); i++) - results.push_back(file.group().at(i).filePath()); - - } else - results.push_back(file.filePath()); - } - - return results; - } - - bool isHidden(const QModelIndex& idx) - { - const FileDialogModelFileInfo* info = infoForIndex(idx); - return info ? info->isHidden() : false; - } - - bool isDir(const QModelIndex& idx) - { - const FileDialogModelFileInfo* info = infoForIndex(idx); - return info ? isDirectory(info->type()) : false; - } - - bool isRemote() { return m_server; } - - ProtoCall::Runtime::vtkCommunicatorChannel* getServer() { return m_server; } - - /// Path separator for the connected server's filesystem. - char m_separator; - - /// Current path being displayed (server's filesystem). - QString m_currentPath; - /// Caches information about the set of files within the current path. - QVector m_fileList; - - const FileDialogModelFileInfo* infoForIndex(const QModelIndex& idx) const - { - if (idx.isValid() && nullptr == idx.internalPointer() && idx.row() >= 0 && - idx.row() < m_fileList.size()) { - return &m_fileList[idx.row()]; - } else if (idx.isValid() && idx.internalPointer()) { - FileDialogModelFileInfo* ptr = - reinterpret_cast(idx.internalPointer()); - const QList& grp = ptr->group(); - if (idx.row() >= 0 && idx.row() < grp.size()) { - return &grp[idx.row()]; - ; - } - } - - return nullptr; - } - -private: - ProtoCall::Runtime::vtkCommunicatorChannel* m_server; - FileDialogModel* m_model; -}; - -////////////////////////////////////////////////////////////////////////// -// FileDialogModel -FileDialogModel::FileDialogModel( - ProtoCall::Runtime::vtkCommunicatorChannel* _server, QObject* Parent) - : base(Parent), m_implementation(new Private(this, _server)) -{ -} - -FileDialogModel::~FileDialogModel() -{ - delete m_implementation; -} - -ProtoCall::Runtime::vtkCommunicatorChannel* FileDialogModel::server() const -{ - return m_implementation->getServer(); -} - -void FileDialogModel::setCurrentPath(const QString& path) -{ - if (path.isEmpty()) - m_implementation->listCurrentWorkingDir(); - else - m_implementation->listDirectory(path); -} - -QString FileDialogModel::getCurrentPath() -{ - return m_implementation->m_currentPath; -} - -class AbsoluteFilePathRequest : public QObject -{ - Q_OBJECT -public: - AbsoluteFilePathRequest(vtkCommunicatorChannel* server, - const QString& currentDir, const QString& path) - : m_currentDir(currentDir), m_path(path), m_server(server) - { - } - - void handleAbsolutePathResponse(Path* response) - { - emit complete(QString::fromStdString(response->path())); - delete response; - } - - void execute() - { - - if (m_path.isEmpty()) { - emit complete(QString()); - } - - RemoteFileSystemService::Proxy proxy(m_server); - Path absolutePathRequest; - absolutePathRequest.set_name(m_path.toStdString()); - absolutePathRequest.set_path(m_currentDir.toStdString()); - Path* response = new Path(); - - Closure* callback = NewCallback( - this, &AbsoluteFilePathRequest::handleAbsolutePathResponse, response); - - proxy.absolutePath(&absolutePathRequest, response, callback); - } - -signals: - void complete(const QString& path); - -private: - QString m_currentDir; - QString m_path; - vtkCommunicatorChannel* m_server; -}; - -void FileDialogModel::absoluteFilePath(const QString& path, - const QObject* requester, - const char* resultSlot) -{ - - AbsoluteFilePathRequest* request = new AbsoluteFilePathRequest( - server(), m_implementation->m_currentPath, path); - - connect(request, SIGNAL(complete(const QString&)), requester, resultSlot); - connect(request, SIGNAL(complete(const QString&)), this, SLOT(cleanup())); - - request->execute(); -} - -QStringList FileDialogModel::getFilePaths(const QModelIndex& Index) -{ - if (Index.model() == this) - return m_implementation->getFilePaths(Index); - - return QStringList(); -} - -bool FileDialogModel::isHidden(const QModelIndex& Index) -{ - if (Index.model() == this) - return m_implementation->isHidden(Index); - - return false; -} - -bool FileDialogModel::isDir(const QModelIndex& Index) -{ - if (Index.model() == this) - return m_implementation->isDir(Index); - - return false; -} - -void FileDialogModel::cleanup() -{ - sender()->deleteLater(); -} - -class FileExistsRequest : public QObject -{ - Q_OBJECT -public: - FileExistsRequest(vtkCommunicatorChannel* server, const QString& path) - : m_path(path), m_server(server) - { - } - - void handleFileExists(Listing* listing) - { - if (listing->path().type() == FileDialogModel::SINGLE_FILE) - emit complete(QString::fromStdString(listing->path().path()), true); - else if (!QString::fromStdString(listing->path().path()).endsWith(".lnk")) - execute(QString::fromStdString(listing->path().path() + ".lnk")); - else - emit complete(QString::fromStdString(listing->path().path()), false); - - delete listing; - } - - void execute() { execute(m_path); } - -signals: - void complete(const QString& path, bool exists); - -private: - QString m_path; - vtkCommunicatorChannel* m_server; - - void execute(const QString& filePath) - { - if (filePath.isEmpty()) - emit complete(QString(), false); - - RemoteFileSystemService::Proxy proxy(m_server); - Path path; - path.set_path(filePath.toStdString()); - - Listing* listing = new Listing(); - Closure* callback = - NewCallback(this, &FileExistsRequest::handleFileExists, listing); - - proxy.ls(&path, listing, callback); - } -}; - -void FileDialogModel::fileExists(const QString& file, const QObject* requester, - const char* resultSlot) -{ - QString filePath = m_implementation->cleanPath(file); - - FileExistsRequest* request = new FileExistsRequest(server(), file); - - connect(request, SIGNAL(complete(const QString&, bool)), requester, - resultSlot); - connect(request, SIGNAL(complete(const QString&, bool)), this, - SLOT(cleanup())); - - request->execute(); -} - -class DirExistsRequest : public QObject -{ - Q_OBJECT -public: - DirExistsRequest(vtkCommunicatorChannel* server, const QString& path) - : m_path(path), m_server(server) - { - } - - void handleDirExists(Listing* listing) - { - if (FileDialogModel::isDirectory( - static_cast(listing->path().type()))) - emit complete(QString::fromStdString(listing->path().path()), true); - else if (!FileDialogModel::isFile(static_cast( - listing->path().type())) && - !QString::fromStdString(listing->path().path()).endsWith(".lnk")) - execute(QString::fromStdString(listing->path().path() + ".lnk")); - else - emit complete(QString::fromStdString(listing->path().path()), false); - - delete listing; - } - - void execute() { execute(m_path); } - -signals: - void complete(const QString& path, bool exists); - -private: - QString m_path; - vtkCommunicatorChannel* m_server; - - void execute(const QString& dirPath) - { - if (dirPath.isEmpty()) - emit complete(QString(), false); - - RemoteFileSystemService::Proxy proxy(m_server); - Path path; - path.set_path(dirPath.toStdString()); - - Listing* listing = new Listing(); - Closure* callback = - NewCallback(this, &DirExistsRequest::handleDirExists, listing); - - proxy.ls(&path, listing, callback); - } -}; - -void FileDialogModel::dirExists(const QString& path, const QObject* requester, - const char* resultSlot) -{ - QString dirPath = m_implementation->cleanPath(path); - - DirExistsRequest* request = new DirExistsRequest(server(), dirPath); - - connect(request, SIGNAL(complete(const QString&, bool)), requester, - resultSlot); - connect(request, SIGNAL(complete(const QString&, bool)), this, - SLOT(cleanup())); - - request->execute(); -} - -QChar FileDialogModel::separator() const -{ - return m_implementation->m_separator; -} - -int FileDialogModel::columnCount(const QModelIndex& idx) const -{ - const FileDialogModelFileInfo* file = m_implementation->infoForIndex(idx); - - if (!file) - // should never get here anyway - return 1; - - return file->group().size() + 1; -} - -QVariant FileDialogModel::data(const QModelIndex& idx, int role) const -{ - - const FileDialogModelFileInfo* file; - - if (idx.column() == 0) - file = m_implementation->infoForIndex(idx); - else - file = m_implementation->infoForIndex(idx.parent()); - - if (!file) - // should never get here anyway - return QVariant(); - - if (role == Qt::DisplayRole || role == Qt::EditRole) { - if (idx.column() == 0) - return file->label(); - else if (idx.column() <= file->group().size()) - return file->group().at(idx.column() - 1).label(); - } else if (role == Qt::UserRole) { - if (idx.column() == 0) - return file->filePath(); - else if (idx.column() <= file->group().size()) - return file->group().at(idx.column() - 1).filePath(); - } else if (role == Qt::DecorationRole && idx.column() == 0) - return Icons()->icon(file->type()); - - return QVariant(); -} - -QModelIndex FileDialogModel::index(int row, int column, - const QModelIndex& p) const -{ - if (!p.isValid()) - return createIndex(row, column); - - if (p.row() >= 0 && p.row() < m_implementation->m_fileList.size() && - nullptr == p.internalPointer()) { - FileDialogModelFileInfo* fi = &m_implementation->m_fileList[p.row()]; - return createIndex(row, column, fi); - } - - return QModelIndex(); -} - -QModelIndex FileDialogModel::parent(const QModelIndex& idx) const -{ - if (!idx.isValid() || !idx.internalPointer()) - return QModelIndex(); - - const FileDialogModelFileInfo* ptr = - reinterpret_cast(idx.internalPointer()); - int row = ptr - &m_implementation->m_fileList.first(); - return createIndex(row, idx.column()); -} - -int FileDialogModel::rowCount(const QModelIndex& idx) const -{ - if (!idx.isValid()) - return m_implementation->m_fileList.size(); - - if (nullptr == idx.internalPointer() && idx.row() >= 0 && - idx.row() < m_implementation->m_fileList.size()) - return m_implementation->m_fileList[idx.row()].group().size(); - - return 0; -} - -bool FileDialogModel::hasChildren(const QModelIndex& idx) const -{ - if (!idx.isValid()) - return true; - - if (nullptr == idx.internalPointer() && idx.row() >= 0 && - idx.row() < m_implementation->m_fileList.size()) - return m_implementation->m_fileList[idx.row()].isGroup(); - - return false; -} - -QVariant FileDialogModel::headerData(int section, Qt::Orientation, - int role) const -{ - switch (role) { - case Qt::DisplayRole: - switch (section) { - case 0: - return tr("Filename"); - } - } - - return QVariant(); -} - -Qt::ItemFlags FileDialogModel::flags(const QModelIndex& idx) const -{ - Qt::ItemFlags ret = Qt::ItemIsSelectable | Qt::ItemIsEnabled; - const FileDialogModelFileInfo* file = m_implementation->infoForIndex(idx); - if (file && !file->isGroup()) - ret |= Qt::ItemIsEditable; - - return ret; -} - -bool FileDialogModel::isDirectory(FileDialogModel::FileType t) -{ - return t == DIRECTORY || t == DIRECTORY_LINK || t == DRIVE || - t == NETWORK_ROOT || t == NETWORK_DOMAIN || t == NETWORK_SERVER || - t == NETWORK_SHARE; -} - -bool FileDialogModel::isFile(FileType t) -{ - return t == SINGLE_FILE || t == SINGLE_FILE_LINK; -} - -#include "filedialogmodel.moc" diff --git a/avogadro/qtplugins/clientserver/filedialogmodel.h b/avogadro/qtplugins/clientserver/filedialogmodel.h deleted file mode 100644 index 0971d26db2..0000000000 --- a/avogadro/qtplugins/clientserver/filedialogmodel.h +++ /dev/null @@ -1,168 +0,0 @@ -/****************************************************************************** - This source file is part of the Avogadro project. - This source code is released under the 3-Clause BSD License, (see "LICENSE"). -******************************************************************************/ - -#ifndef AVOGADRO_QTPLUGINS_FILEDIALOGMODEL_H -#define AVOGADRO_QTPLUGINS_FILEDIALOGMODEL_H - -#include -#include -#include - -class vtkProcessModule; -class QModelIndex; - -namespace ProtoCall { -namespace Runtime { -class RpcChannel; -class vtkCommunicatorChannel; -} -} - -class Listing; -class Path; - -/** - * @class FileDialogModel filedialogmodel.h - * - * @brief Remote file dialog model - */ -class FileDialogModel : public QAbstractItemModel -{ - typedef QAbstractItemModel base; - - Q_OBJECT - -public: - enum FileType - { - INVALID = 0, - SINGLE_FILE, - SINGLE_FILE_LINK, - DIRECTORY, - DIRECTORY_LINK, - FILE_GROUP, - DRIVE, - NETWORK_ROOT, - NETWORK_DOMAIN, - NETWORK_SERVER, - NETWORK_SHARE - }; - - FileDialogModel(ProtoCall::Runtime::vtkCommunicatorChannel* server, - QObject* Parent = nullptr); - ~FileDialogModel(); - - /// Sets the path that the file dialog will display - void setCurrentPath(const QString&); - - /// Returns the path to the file dialog will display - QString getCurrentPath(); - - /// Return true if the file at the index is hidden - bool isHidden(const QModelIndex&); - - /// Return true if the given row is a directory - bool isDir(const QModelIndex&); - - // Creates a directory. "dirName" can be relative or absolute path - bool mkdir(const QString& dirname); - - // Removes a directory. "dirName" can be relative or absolute path - bool rmdir(const QString& dirname); - - // Renames a directory or file. - bool rename(const QString& oldname, const QString& newname); - - /// Returns whether the file exists - /// also returns the full path, which could be a resolved shortcut - void fileExists(const QString& file, const QObject* requestor, - const char* resultSlot); - - /// Returns whether a directory exists - /// also returns the full path, which could be a resolved shortcut - void dirExists(const QString& dir, const QObject* requestor, - const char* resultSlot); - - /// returns the path delimiter, could be \ or / depending on the platform - /// this model is browsing - QChar separator() const; - - /// return the absolute path for this file - void absoluteFilePath(const QString& path, const QObject* requester, - const char* resultSlot); - - /// Returns the set of file paths associated with the given row - /// (a row may represent one-to-many paths if grouping is implemented) - /// this also resolved symlinks if necessary - QStringList getFilePaths(const QModelIndex&); - - /// Returns the server that this model is browsing - ProtoCall::Runtime::vtkCommunicatorChannel* server() const; - - // overloads for QAbstractItemModel - - /// return the number of columns in the model - int columnCount(const QModelIndex&) const; - /// return the data for an item - QVariant data(const QModelIndex& idx, int role) const; - /// return an index from another index - QModelIndex index(int row, int column, const QModelIndex&) const; - /// return the parent index of an index - QModelIndex parent(const QModelIndex&) const; - /// return the number of rows under a given index - int rowCount(const QModelIndex&) const; - /// return whether a given index has children - bool hasChildren(const QModelIndex& p) const; - /// returns header data - QVariant headerData(int section, Qt::Orientation, int role) const; - /// returns flags for item - Qt::ItemFlags flags(const QModelIndex& idx) const; - - static bool isDirectory(FileDialogModel::FileType type); - static bool isFile(FileDialogModel::FileType type); - -signals: - void fileExistsComplete(const QString& path, bool exists); - void dirExistsComplete(const QString& path, bool exits); - void absoluteFilePathComplete(const QString& path); - -private: - class Private; - Private* const m_implementation; - - void handleFileExists(Listing* listing); - void handleDirExists(Listing* listing); - void handleAbsolutePathResponse(Path* response); - -private slots: - void cleanup(); -}; - -class FileDialogModelIconProvider : protected QFileIconProvider -{ -public: - enum IconType - { - Computer, - Drive, - Folder, - File, - FolderLink, - FileLink, - NetworkFolder - }; - FileDialogModelIconProvider(); - QIcon icon(IconType t) const; - QIcon icon(FileDialogModel::FileType f) const; - -protected: - QIcon icon(const QFileInfo& info) const; - QIcon icon(QFileIconProvider::IconType ico) const; - - QIcon m_folderLinkIcon; - QIcon m_fileLinkIcon; -}; - -#endif diff --git a/avogadro/qtplugins/clientserver/remote.proto b/avogadro/qtplugins/clientserver/remote.proto deleted file mode 100644 index 97ef255823..0000000000 --- a/avogadro/qtplugins/clientserver/remote.proto +++ /dev/null @@ -1,53 +0,0 @@ -import "protocall.proto"; -import "external_avogadrocore.proto"; - - -message OpenRequest { - optional string path = 1; -} - -message OpenResponse { - optional external.Avogadro.Core.Molecule molecule = 1; -} - -service RemoteMoleculeService { - rpc open(OpenRequest) returns(OpenResponse); - rpc fileFormats(Void) returns(FileFormats); -} - -message Path { - optional string name = 1; - optional string path = 2; - optional uint32 type = 3; - optional bool hidden = 4; -} - -message Listing { - optional Path path = 1; - repeated Path paths = 2; -} - -message Separator { - optional string separator = 1; -} - -message Paths { - repeated Paths dirs = 1; -} - -message FileFormat { - optional string name = 1; - repeated string extension = 2; -} - -message FileFormats { - repeated FileFormat formats = 1; -} - -service RemoteFileSystemService { - rpc ls(Path) returns(Listing); - rpc cwd(Void) returns(Path); - rpc separator(Void) returns(Separator); - rpc specialDirectories(Void) returns(Paths); - rpc absolutePath(Path) returns(Path); -} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9c3ff4695d..73278356f8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -45,6 +45,3 @@ if(USE_OPENGL) endif() endif() -if(USE_PROTOCALL) - add_subdirectory(protocall) -endif() diff --git a/tests/protocall/CMakeLists.txt b/tests/protocall/CMakeLists.txt deleted file mode 100644 index 62c5db5d49..0000000000 --- a/tests/protocall/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -find_package(GTest REQUIRED) - -include_directories("${CMAKE_CURRENT_BINARY_DIR}" - "${AvogadroLibs_BINARY_DIR}/avogadro/io" - "${AvogadroLibs_BINARY_DIR}/avogadro/protocall" - "${AvogadroLibs_SOURCE_DIR}/avogadro/protocall" -) - -find_package(protobuf REQUIRED NO_MODULE) -include_directories(SYSTEM ${protobuf_INCLUDE_DIRS}) - -find_package(ProtoCall REQUIRED NO_MODULE) -include_directories(SYSTEM ${ProtoCall_INCLUDE_DIRS}) - -if(AVOGADRO_DATA_ROOT) - set(AVOGADRO_DATA ${AVOGADRO_DATA_ROOT}) -else() - message("No data root found, please set to run the tests.") - return() -endif() - -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/protocalltests.h.in" - "${CMAKE_CURRENT_BINARY_DIR}/protocalltests.h" @ONLY) - -set(tests - MoleculeSerialization - MatrixSerialization - ) - -# Build up the source file names. -set(_test_srcs "") -foreach(_test ${tests}) - message(STATUS "Adding ${_test} test.") - string(TOLOWER ${_test} testname) - list(APPEND test_srcs ${testname}.cpp) -endforeach() -message(STATUS "Test source files: ${_test_srcs}") - -# Add a single executable for all of our tests. -add_executable(AvogadroProtoCallTests ${test_srcs}) -target_link_libraries(AvogadroProtoCallTests AvogadroProtoCall - ${GTEST_BOTH_LIBRARIES} ${EXTRA_LINK_LIB}) - -# Now add all of the tests, using the gtest_filter argument so that only those -# cases are run in each test invocation. -foreach(_test ${tests}) - add_test(NAME "${_test}" - COMMAND AvogadroProtoCallTests "--gtest_filter=${_test}Test.*") -endforeach() diff --git a/tests/protocall/matrixserialization.cpp b/tests/protocall/matrixserialization.cpp deleted file mode 100644 index 1c1dec1ca2..0000000000 --- a/tests/protocall/matrixserialization.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/****************************************************************************** - - This source file is part of the Avogadro project. - - Copyright 2013 Kitware, Inc. - - This source code is released under the New BSD License, (the "License"). - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ******************************************************************************/ - -#include "matrixserialization.h" - -#include -#include - -TEST(MatrixSerializationTest, vector2) -{ - Avogadro::Vector2 vec2; - vec2[0] = 1; - vec2[1] = 2; - - size_t size = Avogadro::ProtoCall::MatrixSerialization::sizeOf(vec2); - unsigned char* data = new unsigned char[size]; - - bool success = - Avogadro::ProtoCall::MatrixSerialization::serialize(vec2, data, size); - EXPECT_TRUE(success); - - Avogadro::Vector2 afterRoundTrip; - success = - Avogadro::ProtoCall::MatrixSerialization::deserialize(afterRoundTrip, data); - - EXPECT_TRUE(success); - - delete[] data; - - for (int row = 0; row < 2; row++) - EXPECT_EQ(vec2[row], afterRoundTrip[row]); -} - -TEST(MatrixSerializationTest, vector3) -{ - Avogadro::Vector3 vec3; - vec3[0] = 1; - vec3[1] = 2; - vec3[2] = 3; - - size_t size = Avogadro::ProtoCall::MatrixSerialization::sizeOf(vec3); - unsigned char* data = new unsigned char[size]; - - bool success = - Avogadro::ProtoCall::MatrixSerialization::serialize(vec3, data, size); - - EXPECT_TRUE(success); - - Avogadro::Vector3 afterRoundTrip; - success = - Avogadro::ProtoCall::MatrixSerialization::deserialize(afterRoundTrip, data); - - EXPECT_TRUE(success); - - delete[] data; - - for (int row = 0; row < 3; row++) - EXPECT_EQ(vec3[row], afterRoundTrip[row]); -} - -TEST(MatrixSerializationTest, matrixX) -{ - Avogadro::MatrixX matrix(100, 100); - - for (int row = 0; row < 100; row++) { - for (int col = 0; col < 100; col++) { - matrix(row, col) = row * col; - } - } - - size_t size = Avogadro::ProtoCall::MatrixSerialization::sizeOf(matrix); - - unsigned char* data = new unsigned char[size]; - - bool success = - Avogadro::ProtoCall::MatrixSerialization::serialize(matrix, data, size); - - EXPECT_TRUE(success); - - Avogadro::MatrixX afterRoundTrip(100, 100); - success = Avogadro::ProtoCall::MatrixSerialization::deserialize( - afterRoundTrip, data, size); - - EXPECT_TRUE(success); - - delete[] data; - - for (int row = 0; row < 100; row++) { - for (int col = 0; col < 100; col++) - EXPECT_EQ(matrix(row, col), afterRoundTrip(row, col)); - } -} diff --git a/tests/protocall/moleculeserialization.cpp b/tests/protocall/moleculeserialization.cpp deleted file mode 100644 index 681c48b06a..0000000000 --- a/tests/protocall/moleculeserialization.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/****************************************************************************** - - This source file is part of the Avogadro project. - - Copyright 2013 Kitware, Inc. - - This source code is released under the New BSD License, (the "License"). - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ******************************************************************************/ - -#include -#include -#include -#include - -#include "moleculedeserializer.h" -#include "moleculeserializer.h" -#include "protocalltests.h" - -using Avogadro::Core::Molecule; -using Avogadro::Io::FileFormat; -using Avogadro::Io::FileFormatManager; -using Avogadro::Core::MoleculeDeserializer; -using Avogadro::Core::MoleculeSerializer; - -using google::protobuf::io::ArrayOutputStream; -using google::protobuf::io::CodedOutputStream; -using google::protobuf::io::ArrayInputStream; -using google::protobuf::io::CodedInputStream; -using google::protobuf::uint32; -using google::protobuf::uint8; - -class MoleculeSerializationTest : public testing::Test -{ -protected: - virtual void SetUp() - { - FileFormatManager::instance().readFile( - ethane, AVOGADRO_DATA "/data/ethane.cml", "cml"); - } - - bool equal(const Avogadro::MatrixX& mat1, const Avogadro::MatrixX& mat2) - { - if (mat1.rows() != mat2.rows() || mat1.cols() != mat2.cols()) - return false; - for (int row = 0; row < mat1.rows(); row++) { - for (int col = 0; col < mat1.cols(); col++) { - if (mat1(row, col) != mat2(row, col)) - return false; - } - } - - return true; - } - - Molecule ethane; -}; - -TEST_F(MoleculeSerializationTest, roundTrip) -{ - MoleculeSerializer serializer(&this->ethane); - - size_t size = serializer.size(); - - uint8* data = new uint8[size]; - - bool success = serializer.serialize(data, size); - EXPECT_TRUE(success); - - Molecule after; - - MoleculeDeserializer deserializer(&after); - success = deserializer.deserialize(data, size); - EXPECT_TRUE(success); - - delete[] data; - - EXPECT_EQ(this->ethane.atomicNumbers(), after.atomicNumbers()); - - std::vector expected2d = this->ethane.atomPositions2d(); - std::vector actual2d = after.atomPositions2d(); - - EXPECT_EQ(expected2d.size(), actual2d.size()); - - for (size_t i = 0; i < expected2d.size(); i++) - EXPECT_TRUE(this->equal(expected2d[i], actual2d[i])); - - std::vector expected3d = this->ethane.atomPositions3d(); - std::vector actual3d = after.atomPositions3d(); - - EXPECT_EQ(expected3d.size(), actual3d.size()); - - for (size_t i = 0; i < expected3d.size(); i++) - EXPECT_TRUE(this->equal(expected3d[i], actual3d[i])); - - const std::vector> expectedBondPairs = - this->ethane.bondPairs(); - const std::vector> actualBondPairs = - after.bondPairs(); - - EXPECT_EQ(expectedBondPairs.size(), actualBondPairs.size()); - - for (size_t i = 0; i < expectedBondPairs.size(); i++) { - EXPECT_EQ(expectedBondPairs[i].first, actualBondPairs[i].first); - EXPECT_EQ(expectedBondPairs[i].second, actualBondPairs[i].second); - } - - const std::vector expectedBondOrder = - this->ethane.bondOrders(); - const std::vector actualBondOrder = after.bondOrders(); - - for (size_t i = 0; i < expectedBondOrder.size(); i++) - EXPECT_EQ(expectedBondOrder[i], actualBondOrder[i]); -} diff --git a/tests/protocall/protocalltests.h.in b/tests/protocall/protocalltests.h.in deleted file mode 100644 index 938bcc00e0..0000000000 --- a/tests/protocall/protocalltests.h.in +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef AVOGADRO_PROTOCALLTESTS_H -#define AVOGADRO_PROTOCALLTESTS_H - -#define AVOGADRO_DATA "@AVOGADRO_DATA@" - -#endif // AVOGADRO_PROTOCALLTESTS_H